blob: 788d3bbe5b3cac75ad6061362edb789180da1b0f [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
Mike Williams51024bb2024-05-30 07:46:30 +0200295 size_t *usedlen, // characters after src that are used
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200296 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 {
Mike Williams51024bb2024-05-30 07:46:30 +0200671 *usedlen = p + 1 - src;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200672 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(
Yee Cheng China7767072023-04-16 20:13:12 +0100941 typval_T *argvars,
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200942 typval_T *rettv,
Yee Cheng China7767072023-04-16 20:13:12 +0100943 int find_what)
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200944{
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 {
Bram Moolenaar5145c9a2023-03-11 13:55:53 +0000985 char_u *file_to_find = NULL;
986 char *search_ctx = NULL;
987
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200988 do
989 {
990 if (rettv->v_type == VAR_STRING || rettv->v_type == VAR_LIST)
991 vim_free(fresult);
992 fresult = find_file_in_path_option(first ? fname : NULL,
993 first ? (int)STRLEN(fname) : 0,
994 0, first, path,
995 find_what,
996 curbuf->b_ffname,
997 find_what == FINDFILE_DIR
Bram Moolenaar5145c9a2023-03-11 13:55:53 +0000998 ? (char_u *)"" : curbuf->b_p_sua,
999 &file_to_find, &search_ctx);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001000 first = FALSE;
1001
1002 if (fresult != NULL && rettv->v_type == VAR_LIST)
1003 list_append_string(rettv->vval.v_list, fresult, -1);
1004
1005 } while ((rettv->v_type == VAR_LIST || --count > 0) && fresult != NULL);
Bram Moolenaar5145c9a2023-03-11 13:55:53 +00001006
1007 vim_free(file_to_find);
1008 vim_findfile_cleanup(search_ctx);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001009 }
1010
1011 if (rettv->v_type == VAR_STRING)
1012 rettv->vval.v_string = fresult;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001013}
1014
1015/*
1016 * "finddir({fname}[, {path}[, {count}]])" function
1017 */
1018 void
1019f_finddir(typval_T *argvars, typval_T *rettv)
1020{
1021 findfilendir(argvars, rettv, FINDFILE_DIR);
1022}
1023
1024/*
1025 * "findfile({fname}[, {path}[, {count}]])" function
1026 */
1027 void
1028f_findfile(typval_T *argvars, typval_T *rettv)
1029{
1030 findfilendir(argvars, rettv, FINDFILE_FILE);
1031}
1032
1033/*
1034 * "fnamemodify({fname}, {mods})" function
1035 */
1036 void
1037f_fnamemodify(typval_T *argvars, typval_T *rettv)
1038{
1039 char_u *fname;
1040 char_u *mods;
Mike Williams51024bb2024-05-30 07:46:30 +02001041 size_t usedlen = 0;
Bram Moolenaarc5308522020-12-13 12:25:35 +01001042 int len = 0;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001043 char_u *fbuf = NULL;
1044 char_u buf[NUMBUFLEN];
1045
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001046 if (in_vim9script()
1047 && (check_for_string_arg(argvars, 0) == FAIL
1048 || check_for_string_arg(argvars, 1) == FAIL))
Bram Moolenaar7bb4e742020-12-09 12:41:50 +01001049 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001050
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001051 fname = tv_get_string_chk(&argvars[0]);
1052 mods = tv_get_string_buf_chk(&argvars[1], buf);
Bram Moolenaarc5308522020-12-13 12:25:35 +01001053 if (mods == NULL || fname == NULL)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001054 fname = NULL;
Bram Moolenaarc5308522020-12-13 12:25:35 +01001055 else
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001056 {
1057 len = (int)STRLEN(fname);
Bram Moolenaarc5308522020-12-13 12:25:35 +01001058 if (mods != NULL && *mods != NUL)
1059 (void)modify_fname(mods, FALSE, &usedlen, &fname, &fbuf, &len);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001060 }
1061
1062 rettv->v_type = VAR_STRING;
1063 if (fname == NULL)
1064 rettv->vval.v_string = NULL;
1065 else
1066 rettv->vval.v_string = vim_strnsave(fname, len);
1067 vim_free(fbuf);
1068}
1069
1070/*
1071 * "getcwd()" function
1072 *
1073 * Return the current working directory of a window in a tab page.
1074 * First optional argument 'winnr' is the window number or -1 and the second
1075 * optional argument 'tabnr' is the tab page number.
1076 *
1077 * If no arguments are supplied, then return the directory of the current
1078 * window.
1079 * If only 'winnr' is specified and is not -1 or 0 then return the directory of
1080 * the specified window.
1081 * If 'winnr' is 0 then return the directory of the current window.
1082 * If both 'winnr and 'tabnr' are specified and 'winnr' is -1 then return the
1083 * directory of the specified tab page. Otherwise return the directory of the
1084 * specified window in the specified tab page.
1085 * If the window or the tab page doesn't exist then return NULL.
1086 */
1087 void
1088f_getcwd(typval_T *argvars, typval_T *rettv)
1089{
1090 win_T *wp = NULL;
1091 tabpage_T *tp = NULL;
1092 char_u *cwd;
1093 int global = FALSE;
1094
1095 rettv->v_type = VAR_STRING;
1096 rettv->vval.v_string = NULL;
1097
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001098 if (in_vim9script()
1099 && (check_for_opt_number_arg(argvars, 0) == FAIL
1100 || (argvars[0].v_type != VAR_UNKNOWN
1101 && check_for_opt_number_arg(argvars, 1) == FAIL)))
1102 return;
1103
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001104 if (argvars[0].v_type == VAR_NUMBER
1105 && argvars[0].vval.v_number == -1
1106 && argvars[1].v_type == VAR_UNKNOWN)
1107 global = TRUE;
1108 else
1109 wp = find_tabwin(&argvars[0], &argvars[1], &tp);
1110
Bram Moolenaar851c7a62021-11-18 20:47:31 +00001111 if (wp != NULL && wp->w_localdir != NULL
1112 && argvars[0].v_type != VAR_UNKNOWN)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001113 rettv->vval.v_string = vim_strsave(wp->w_localdir);
Bram Moolenaar851c7a62021-11-18 20:47:31 +00001114 else if (tp != NULL && tp->tp_localdir != NULL
1115 && argvars[0].v_type != VAR_UNKNOWN)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001116 rettv->vval.v_string = vim_strsave(tp->tp_localdir);
1117 else if (wp != NULL || tp != NULL || global)
1118 {
Bram Moolenaar851c7a62021-11-18 20:47:31 +00001119 if (globaldir != NULL && argvars[0].v_type != VAR_UNKNOWN)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001120 rettv->vval.v_string = vim_strsave(globaldir);
1121 else
1122 {
1123 cwd = alloc(MAXPATHL);
1124 if (cwd != NULL)
1125 {
1126 if (mch_dirname(cwd, MAXPATHL) != FAIL)
1127 rettv->vval.v_string = vim_strsave(cwd);
1128 vim_free(cwd);
1129 }
1130 }
1131 }
1132#ifdef BACKSLASH_IN_FILENAME
1133 if (rettv->vval.v_string != NULL)
1134 slash_adjust(rettv->vval.v_string);
1135#endif
1136}
1137
1138/*
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001139 * Convert "st" to file permission string.
1140 */
1141 char_u *
1142getfpermst(stat_T *st, char_u *perm)
1143{
1144 char_u flags[] = "rwx";
1145 int i;
1146
1147 for (i = 0; i < 9; i++)
1148 {
1149 if (st->st_mode & (1 << (8 - i)))
1150 perm[i] = flags[i % 3];
1151 else
1152 perm[i] = '-';
1153 }
1154 return perm;
1155}
1156
1157/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001158 * "getfperm({fname})" function
1159 */
1160 void
1161f_getfperm(typval_T *argvars, typval_T *rettv)
1162{
1163 char_u *fname;
1164 stat_T st;
1165 char_u *perm = NULL;
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001166 char_u permbuf[] = "---------";
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001167
Bram Moolenaar32105ae2021-03-27 18:59:25 +01001168 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +01001169 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001170
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001171 fname = tv_get_string(&argvars[0]);
1172
1173 rettv->v_type = VAR_STRING;
1174 if (mch_stat((char *)fname, &st) >= 0)
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001175 perm = vim_strsave(getfpermst(&st, permbuf));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001176 rettv->vval.v_string = perm;
1177}
1178
1179/*
1180 * "getfsize({fname})" function
1181 */
1182 void
1183f_getfsize(typval_T *argvars, typval_T *rettv)
1184{
1185 char_u *fname;
1186 stat_T st;
1187
Bram Moolenaar32105ae2021-03-27 18:59:25 +01001188 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +01001189 return;
1190
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001191 fname = tv_get_string(&argvars[0]);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001192 if (mch_stat((char *)fname, &st) >= 0)
1193 {
1194 if (mch_isdir(fname))
1195 rettv->vval.v_number = 0;
1196 else
1197 {
1198 rettv->vval.v_number = (varnumber_T)st.st_size;
1199
Bram Moolenaar26262f82019-09-04 20:59:15 +02001200 // non-perfect check for overflow
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001201 if ((off_T)rettv->vval.v_number != (off_T)st.st_size)
1202 rettv->vval.v_number = -2;
1203 }
1204 }
1205 else
1206 rettv->vval.v_number = -1;
1207}
1208
1209/*
1210 * "getftime({fname})" function
1211 */
1212 void
1213f_getftime(typval_T *argvars, typval_T *rettv)
1214{
1215 char_u *fname;
1216 stat_T st;
1217
Bram Moolenaar32105ae2021-03-27 18:59:25 +01001218 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +01001219 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001220
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001221 fname = tv_get_string(&argvars[0]);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001222 if (mch_stat((char *)fname, &st) >= 0)
1223 rettv->vval.v_number = (varnumber_T)st.st_mtime;
1224 else
1225 rettv->vval.v_number = -1;
1226}
1227
1228/*
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001229 * Convert "st" to file type string.
1230 */
1231 char_u *
1232getftypest(stat_T *st)
1233{
1234 char *t;
1235
1236 if (S_ISREG(st->st_mode))
1237 t = "file";
1238 else if (S_ISDIR(st->st_mode))
1239 t = "dir";
1240 else if (S_ISLNK(st->st_mode))
1241 t = "link";
1242 else if (S_ISBLK(st->st_mode))
1243 t = "bdev";
1244 else if (S_ISCHR(st->st_mode))
1245 t = "cdev";
1246 else if (S_ISFIFO(st->st_mode))
1247 t = "fifo";
1248 else if (S_ISSOCK(st->st_mode))
1249 t = "socket";
1250 else
1251 t = "other";
1252 return (char_u*)t;
1253}
1254
1255/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001256 * "getftype({fname})" function
1257 */
1258 void
1259f_getftype(typval_T *argvars, typval_T *rettv)
1260{
1261 char_u *fname;
1262 stat_T st;
1263 char_u *type = NULL;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001264
Bram Moolenaar32105ae2021-03-27 18:59:25 +01001265 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +01001266 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001267
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001268 fname = tv_get_string(&argvars[0]);
1269
1270 rettv->v_type = VAR_STRING;
1271 if (mch_lstat((char *)fname, &st) >= 0)
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001272 type = vim_strsave(getftypest(&st));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001273 rettv->vval.v_string = type;
1274}
1275
1276/*
1277 * "glob()" function
1278 */
1279 void
1280f_glob(typval_T *argvars, typval_T *rettv)
1281{
1282 int options = WILD_SILENT|WILD_USE_NL;
1283 expand_T xpc;
1284 int error = FALSE;
1285
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02001286 if (in_vim9script()
1287 && (check_for_string_arg(argvars, 0) == FAIL
1288 || check_for_opt_bool_arg(argvars, 1) == FAIL
1289 || (argvars[1].v_type != VAR_UNKNOWN
1290 && (check_for_opt_bool_arg(argvars, 2) == FAIL
1291 || (argvars[2].v_type != VAR_UNKNOWN
1292 && check_for_opt_bool_arg(argvars, 3) == FAIL)))))
1293 return;
1294
Bram Moolenaar26262f82019-09-04 20:59:15 +02001295 // When the optional second argument is non-zero, don't remove matches
1296 // for 'wildignore' and don't put matches for 'suffixes' at the end.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001297 rettv->v_type = VAR_STRING;
1298 if (argvars[1].v_type != VAR_UNKNOWN)
1299 {
Bram Moolenaar5892ea12020-09-02 21:53:11 +02001300 if (tv_get_bool_chk(&argvars[1], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001301 options |= WILD_KEEP_ALL;
1302 if (argvars[2].v_type != VAR_UNKNOWN)
1303 {
Bram Moolenaar5892ea12020-09-02 21:53:11 +02001304 if (tv_get_bool_chk(&argvars[2], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001305 rettv_list_set(rettv, NULL);
1306 if (argvars[3].v_type != VAR_UNKNOWN
Bram Moolenaar5892ea12020-09-02 21:53:11 +02001307 && tv_get_bool_chk(&argvars[3], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001308 options |= WILD_ALLLINKS;
1309 }
1310 }
1311 if (!error)
1312 {
1313 ExpandInit(&xpc);
1314 xpc.xp_context = EXPAND_FILES;
1315 if (p_wic)
1316 options += WILD_ICASE;
1317 if (rettv->v_type == VAR_STRING)
1318 rettv->vval.v_string = ExpandOne(&xpc, tv_get_string(&argvars[0]),
1319 NULL, options, WILD_ALL);
Bram Moolenaar8088ae92022-06-20 11:38:17 +01001320 else if (rettv_list_alloc(rettv) == OK)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001321 {
1322 int i;
1323
1324 ExpandOne(&xpc, tv_get_string(&argvars[0]),
1325 NULL, options, WILD_ALL_KEEP);
1326 for (i = 0; i < xpc.xp_numfiles; i++)
1327 list_append_string(rettv->vval.v_list, xpc.xp_files[i], -1);
1328
1329 ExpandCleanup(&xpc);
1330 }
1331 }
1332 else
1333 rettv->vval.v_string = NULL;
1334}
1335
1336/*
1337 * "glob2regpat()" function
1338 */
1339 void
1340f_glob2regpat(typval_T *argvars, typval_T *rettv)
1341{
Bram Moolenaar3cfa5b12021-06-06 14:14:39 +02001342 char_u buf[NUMBUFLEN];
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001343 char_u *pat;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001344
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001345 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
1346 return;
1347
1348 pat = tv_get_string_buf_chk_strict(&argvars[0], buf, in_vim9script());
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001349 rettv->v_type = VAR_STRING;
1350 rettv->vval.v_string = (pat == NULL)
1351 ? NULL : file_pat_to_reg_pat(pat, NULL, NULL, FALSE);
1352}
1353
1354/*
1355 * "globpath()" function
1356 */
1357 void
1358f_globpath(typval_T *argvars, typval_T *rettv)
1359{
1360 int flags = WILD_IGNORE_COMPLETESLASH;
1361 char_u buf1[NUMBUFLEN];
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02001362 char_u *file;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001363 int error = FALSE;
1364 garray_T ga;
1365 int i;
1366
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02001367 if (in_vim9script()
1368 && (check_for_string_arg(argvars, 0) == FAIL
1369 || check_for_string_arg(argvars, 1) == FAIL
1370 || check_for_opt_bool_arg(argvars, 2) == FAIL
1371 || (argvars[2].v_type != VAR_UNKNOWN
1372 && (check_for_opt_bool_arg(argvars, 3) == FAIL
1373 || (argvars[3].v_type != VAR_UNKNOWN
1374 && check_for_opt_bool_arg(argvars, 4) == FAIL)))))
1375 return;
1376
1377 file = tv_get_string_buf_chk(&argvars[1], buf1);
1378
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001379 // When the optional second argument is non-zero, don't remove matches
1380 // for 'wildignore' and don't put matches for 'suffixes' at the end.
1381 rettv->v_type = VAR_STRING;
1382 if (argvars[2].v_type != VAR_UNKNOWN)
1383 {
Bram Moolenaarf966ce52020-09-02 21:57:07 +02001384 if (tv_get_bool_chk(&argvars[2], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001385 flags |= WILD_KEEP_ALL;
1386 if (argvars[3].v_type != VAR_UNKNOWN)
1387 {
Bram Moolenaarf966ce52020-09-02 21:57:07 +02001388 if (tv_get_bool_chk(&argvars[3], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001389 rettv_list_set(rettv, NULL);
1390 if (argvars[4].v_type != VAR_UNKNOWN
Bram Moolenaarf966ce52020-09-02 21:57:07 +02001391 && tv_get_bool_chk(&argvars[4], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001392 flags |= WILD_ALLLINKS;
1393 }
1394 }
1395 if (file != NULL && !error)
1396 {
Bram Moolenaar04935fb2022-01-08 16:19:22 +00001397 ga_init2(&ga, sizeof(char_u *), 10);
zeertzjq3770f4c2023-01-22 18:38:51 +00001398 globpath(tv_get_string(&argvars[0]), file, &ga, flags, FALSE);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001399 if (rettv->v_type == VAR_STRING)
1400 rettv->vval.v_string = ga_concat_strings(&ga, "\n");
Bram Moolenaar8088ae92022-06-20 11:38:17 +01001401 else if (rettv_list_alloc(rettv) == OK)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001402 for (i = 0; i < ga.ga_len; ++i)
1403 list_append_string(rettv->vval.v_list,
1404 ((char_u **)(ga.ga_data))[i], -1);
1405 ga_clear_strings(&ga);
1406 }
1407 else
1408 rettv->vval.v_string = NULL;
1409}
1410
1411/*
1412 * "isdirectory()" function
1413 */
1414 void
1415f_isdirectory(typval_T *argvars, typval_T *rettv)
1416{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001417 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
1418 return;
1419
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001420 rettv->vval.v_number = mch_isdir(tv_get_string(&argvars[0]));
1421}
1422
1423/*
LemonBoydca1d402022-04-28 15:26:33 +01001424 * "isabsolutepath()" function
1425 */
1426 void
1427f_isabsolutepath(typval_T *argvars, typval_T *rettv)
1428{
1429 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
1430 return;
1431
1432 rettv->vval.v_number = mch_isFullName(tv_get_string_strict(&argvars[0]));
1433}
1434
1435/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001436 * Create the directory in which "dir" is located, and higher levels when
1437 * needed.
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001438 * Set "created" to the full name of the first created directory. It will be
1439 * NULL until that happens.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001440 * Return OK or FAIL.
1441 */
1442 static int
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001443mkdir_recurse(char_u *dir, int prot, char_u **created)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001444{
1445 char_u *p;
1446 char_u *updir;
1447 int r = FAIL;
1448
Bram Moolenaar26262f82019-09-04 20:59:15 +02001449 // Get end of directory name in "dir".
1450 // We're done when it's "/" or "c:/".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001451 p = gettail_sep(dir);
1452 if (p <= get_past_head(dir))
1453 return OK;
1454
Bram Moolenaar26262f82019-09-04 20:59:15 +02001455 // If the directory exists we're done. Otherwise: create it.
Bram Moolenaar71ccd032020-06-12 22:59:11 +02001456 updir = vim_strnsave(dir, p - dir);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001457 if (updir == NULL)
1458 return FAIL;
1459 if (mch_isdir(updir))
1460 r = OK;
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001461 else if (mkdir_recurse(updir, prot, created) == OK)
1462 {
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001463 r = vim_mkdir_emsg(updir, prot);
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001464 if (r == OK && created != NULL && *created == NULL)
1465 *created = FullName_save(updir, FALSE);
1466 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001467 vim_free(updir);
1468 return r;
1469}
1470
1471/*
1472 * "mkdir()" function
1473 */
1474 void
1475f_mkdir(typval_T *argvars, typval_T *rettv)
1476{
1477 char_u *dir;
1478 char_u buf[NUMBUFLEN];
1479 int prot = 0755;
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001480 int defer = FALSE;
1481 int defer_recurse = FALSE;
1482 char_u *created = NULL;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001483
1484 rettv->vval.v_number = FAIL;
1485 if (check_restricted() || check_secure())
1486 return;
1487
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001488 if (in_vim9script()
1489 && (check_for_nonempty_string_arg(argvars, 0) == FAIL
1490 || check_for_opt_string_arg(argvars, 1) == FAIL
1491 || (argvars[1].v_type != VAR_UNKNOWN
1492 && check_for_opt_number_arg(argvars, 2) == FAIL)))
1493 return;
1494
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001495 dir = tv_get_string_buf(&argvars[0], buf);
1496 if (*dir == NUL)
1497 return;
1498
1499 if (*gettail(dir) == NUL)
Bram Moolenaar26262f82019-09-04 20:59:15 +02001500 // remove trailing slashes
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001501 *gettail_sep(dir) = NUL;
1502
1503 if (argvars[1].v_type != VAR_UNKNOWN)
1504 {
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001505 char_u *arg2;
1506
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001507 if (argvars[2].v_type != VAR_UNKNOWN)
1508 {
1509 prot = (int)tv_get_number_chk(&argvars[2], NULL);
1510 if (prot == -1)
1511 return;
1512 }
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001513 arg2 = tv_get_string(&argvars[1]);
1514 defer = vim_strchr(arg2, 'D') != NULL;
1515 defer_recurse = vim_strchr(arg2, 'R') != NULL;
1516 if ((defer || defer_recurse) && !can_add_defer())
1517 return;
1518
1519 if (vim_strchr(arg2, 'p') != NULL)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001520 {
1521 if (mch_isdir(dir))
1522 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001523 // With the "p" flag it's OK if the dir already exists.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001524 rettv->vval.v_number = OK;
1525 return;
1526 }
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001527 mkdir_recurse(dir, prot, defer || defer_recurse ? &created : NULL);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001528 }
1529 }
1530 rettv->vval.v_number = vim_mkdir_emsg(dir, prot);
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001531
1532 // Handle "D" and "R": deferred deletion of the created directory.
1533 if (rettv->vval.v_number == OK
1534 && created == NULL && (defer || defer_recurse))
1535 created = FullName_save(dir, FALSE);
1536 if (created != NULL)
1537 {
1538 typval_T tv[2];
1539
1540 tv[0].v_type = VAR_STRING;
1541 tv[0].v_lock = 0;
1542 tv[0].vval.v_string = created;
1543 tv[1].v_type = VAR_STRING;
1544 tv[1].v_lock = 0;
1545 tv[1].vval.v_string = vim_strsave(
1546 (char_u *)(defer_recurse ? "rf" : "d"));
1547 if (tv[0].vval.v_string == NULL || tv[1].vval.v_string == NULL
1548 || add_defer((char_u *)"delete", 2, tv) == FAIL)
1549 {
1550 vim_free(tv[0].vval.v_string);
1551 vim_free(tv[1].vval.v_string);
1552 }
1553 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001554}
1555
1556/*
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02001557 * "pathshorten()" function
1558 */
1559 void
1560f_pathshorten(typval_T *argvars, typval_T *rettv)
1561{
1562 char_u *p;
Bram Moolenaar6a33ef02020-09-25 22:42:48 +02001563 int trim_len = 1;
1564
Yegappan Lakshmanan1a71d312021-07-15 12:49:58 +02001565 if (in_vim9script()
1566 && (check_for_string_arg(argvars, 0) == FAIL
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02001567 || check_for_opt_number_arg(argvars, 1) == FAIL))
Yegappan Lakshmanan1a71d312021-07-15 12:49:58 +02001568 return;
1569
Bram Moolenaar6a33ef02020-09-25 22:42:48 +02001570 if (argvars[1].v_type != VAR_UNKNOWN)
1571 {
1572 trim_len = (int)tv_get_number(&argvars[1]);
1573 if (trim_len < 1)
1574 trim_len = 1;
1575 }
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02001576
1577 rettv->v_type = VAR_STRING;
1578 p = tv_get_string_chk(&argvars[0]);
Bram Moolenaar6a33ef02020-09-25 22:42:48 +02001579
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02001580 if (p == NULL)
1581 rettv->vval.v_string = NULL;
1582 else
1583 {
1584 p = vim_strsave(p);
1585 rettv->vval.v_string = p;
1586 if (p != NULL)
Bram Moolenaar6a33ef02020-09-25 22:42:48 +02001587 shorten_dir_len(p, trim_len);
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02001588 }
1589}
1590
1591/*
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001592 * Common code for readdir_checkitem() and readdirex_checkitem().
1593 * Either "name" or "dict" is NULL.
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001594 */
1595 static int
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001596checkitem_common(void *context, char_u *name, dict_T *dict)
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001597{
1598 typval_T *expr = (typval_T *)context;
1599 typval_T save_val;
1600 typval_T rettv;
1601 typval_T argv[2];
1602 int retval = 0;
1603 int error = FALSE;
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001604
1605 prepare_vimvar(VV_VAL, &save_val);
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001606 if (name != NULL)
1607 {
1608 set_vim_var_string(VV_VAL, name, -1);
1609 argv[0].v_type = VAR_STRING;
1610 argv[0].vval.v_string = name;
1611 }
1612 else
1613 {
1614 set_vim_var_dict(VV_VAL, dict);
1615 argv[0].v_type = VAR_DICT;
1616 argv[0].vval.v_dict = dict;
1617 }
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001618
zeertzjqad0c4422023-08-17 22:15:47 +02001619 if (eval_expr_typval(expr, FALSE, argv, 1, NULL, &rettv) == FAIL)
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001620 goto theend;
1621
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001622 // We want to use -1, but also true/false should be allowed.
1623 if (rettv.v_type == VAR_SPECIAL || rettv.v_type == VAR_BOOL)
1624 {
1625 rettv.v_type = VAR_NUMBER;
1626 rettv.vval.v_number = rettv.vval.v_number == VVAL_TRUE;
1627 }
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001628 retval = tv_get_number_chk(&rettv, &error);
1629 if (error)
1630 retval = -1;
1631 clear_tv(&rettv);
1632
1633theend:
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001634 if (name != NULL)
1635 set_vim_var_string(VV_VAL, NULL, 0);
1636 else
1637 set_vim_var_dict(VV_VAL, NULL);
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001638 restore_vimvar(VV_VAL, &save_val);
1639 return retval;
1640}
1641
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001642/*
1643 * Evaluate "expr" (= "context") for readdir().
1644 */
1645 static int
1646readdir_checkitem(void *context, void *item)
1647{
1648 char_u *name = (char_u *)item;
1649
1650 return checkitem_common(context, name, NULL);
1651}
1652
Bram Moolenaard83392a2022-09-01 12:22:46 +01001653/*
1654 * Process the keys in the Dict argument to the readdir() and readdirex()
1655 * functions. Assumes the Dict argument is the 3rd argument.
1656 */
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001657 static int
Bram Moolenaard83392a2022-09-01 12:22:46 +01001658readdirex_dict_arg(typval_T *argvars, int *cmp)
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001659{
1660 char_u *compare;
1661
Bram Moolenaard83392a2022-09-01 12:22:46 +01001662 if (check_for_nonnull_dict_arg(argvars, 2) == FAIL)
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001663 return FAIL;
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001664
Bram Moolenaard83392a2022-09-01 12:22:46 +01001665 if (dict_has_key(argvars[2].vval.v_dict, "sort"))
1666 compare = dict_get_string(argvars[2].vval.v_dict, "sort", FALSE);
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001667 else
1668 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00001669 semsg(_(e_dictionary_key_str_required), "sort");
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001670 return FAIL;
1671 }
1672
1673 if (STRCMP(compare, (char_u *) "none") == 0)
1674 *cmp = READDIR_SORT_NONE;
1675 else if (STRCMP(compare, (char_u *) "case") == 0)
1676 *cmp = READDIR_SORT_BYTE;
1677 else if (STRCMP(compare, (char_u *) "icase") == 0)
1678 *cmp = READDIR_SORT_IC;
1679 else if (STRCMP(compare, (char_u *) "collate") == 0)
1680 *cmp = READDIR_SORT_COLLATE;
1681 return OK;
1682}
1683
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001684/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001685 * "readdir()" function
1686 */
1687 void
1688f_readdir(typval_T *argvars, typval_T *rettv)
1689{
1690 typval_T *expr;
1691 int ret;
1692 char_u *path;
1693 char_u *p;
1694 garray_T ga;
1695 int i;
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01001696 int sort = READDIR_SORT_BYTE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001697
1698 if (rettv_list_alloc(rettv) == FAIL)
1699 return;
Yegappan Lakshmanan5bca9062021-07-24 21:33:26 +02001700
1701 if (in_vim9script()
1702 && (check_for_string_arg(argvars, 0) == FAIL
1703 || (argvars[1].v_type != VAR_UNKNOWN
1704 && check_for_opt_dict_arg(argvars, 2) == FAIL)))
1705 return;
1706
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001707 path = tv_get_string(&argvars[0]);
1708 expr = &argvars[1];
1709
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001710 if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN &&
Bram Moolenaard83392a2022-09-01 12:22:46 +01001711 readdirex_dict_arg(argvars, &sort) == FAIL)
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001712 return;
1713
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001714 ret = readdir_core(&ga, path, FALSE, (void *)expr,
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001715 (expr->v_type == VAR_UNKNOWN) ? NULL : readdir_checkitem, sort);
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001716 if (ret == OK)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001717 {
1718 for (i = 0; i < ga.ga_len; i++)
1719 {
1720 p = ((char_u **)ga.ga_data)[i];
1721 list_append_string(rettv->vval.v_list, p, -1);
1722 }
1723 }
1724 ga_clear_strings(&ga);
1725}
1726
1727/*
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001728 * Evaluate "expr" (= "context") for readdirex().
1729 */
1730 static int
1731readdirex_checkitem(void *context, void *item)
1732{
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001733 dict_T *dict = (dict_T*)item;
1734
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001735 return checkitem_common(context, NULL, dict);
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001736}
1737
1738/*
1739 * "readdirex()" function
1740 */
1741 void
1742f_readdirex(typval_T *argvars, typval_T *rettv)
1743{
1744 typval_T *expr;
1745 int ret;
1746 char_u *path;
1747 garray_T ga;
1748 int i;
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01001749 int sort = READDIR_SORT_BYTE;
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001750
1751 if (rettv_list_alloc(rettv) == FAIL)
1752 return;
Yegappan Lakshmanan5bca9062021-07-24 21:33:26 +02001753
1754 if (in_vim9script()
1755 && (check_for_string_arg(argvars, 0) == FAIL
1756 || (argvars[1].v_type != VAR_UNKNOWN
1757 && check_for_opt_dict_arg(argvars, 2) == FAIL)))
1758 return;
1759
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001760 path = tv_get_string(&argvars[0]);
1761 expr = &argvars[1];
1762
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001763 if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN &&
Bram Moolenaard83392a2022-09-01 12:22:46 +01001764 readdirex_dict_arg(argvars, &sort) == FAIL)
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001765 return;
1766
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001767 ret = readdir_core(&ga, path, TRUE, (void *)expr,
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001768 (expr->v_type == VAR_UNKNOWN) ? NULL : readdirex_checkitem, sort);
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001769 if (ret == OK)
1770 {
1771 for (i = 0; i < ga.ga_len; i++)
1772 {
1773 dict_T *dict = ((dict_T**)ga.ga_data)[i];
1774 list_append_dict(rettv->vval.v_list, dict);
1775 dict_unref(dict);
1776 }
1777 }
1778 ga_clear(&ga);
1779}
1780
1781/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001782 * "readfile()" function
1783 */
Bram Moolenaarc423ad72021-01-13 20:38:03 +01001784 static void
1785read_file_or_blob(typval_T *argvars, typval_T *rettv, int always_blob)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001786{
1787 int binary = FALSE;
Bram Moolenaarc423ad72021-01-13 20:38:03 +01001788 int blob = always_blob;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001789 int failed = FALSE;
1790 char_u *fname;
1791 FILE *fd;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001792 char_u buf[(IOSIZE/256)*256]; // rounded to avoid odd + 1
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001793 int io_size = sizeof(buf);
Bram Moolenaar26262f82019-09-04 20:59:15 +02001794 int readlen; // size of last fread()
1795 char_u *prev = NULL; // previously read bytes, if any
1796 long prevlen = 0; // length of data in prev
1797 long prevsize = 0; // size of prev buffer
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001798 long maxline = MAXLNUM;
1799 long cnt = 0;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001800 char_u *p; // position in buf
1801 char_u *start; // start of current line
K.Takata11df3ae2022-10-19 14:02:40 +01001802 off_T offset = 0;
1803 off_T size = -1;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001804
1805 if (argvars[1].v_type != VAR_UNKNOWN)
1806 {
K.Takata11df3ae2022-10-19 14:02:40 +01001807 if (always_blob)
1808 {
1809 offset = (off_T)tv_get_number(&argvars[1]);
1810 if (argvars[2].v_type != VAR_UNKNOWN)
1811 size = (off_T)tv_get_number(&argvars[2]);
1812 }
1813 else
1814 {
1815 if (STRCMP(tv_get_string(&argvars[1]), "b") == 0)
1816 binary = TRUE;
1817 if (STRCMP(tv_get_string(&argvars[1]), "B") == 0)
1818 blob = TRUE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001819
K.Takata11df3ae2022-10-19 14:02:40 +01001820 if (argvars[2].v_type != VAR_UNKNOWN)
1821 maxline = (long)tv_get_number(&argvars[2]);
1822 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001823 }
1824
Bram Moolenaar15352dc2020-04-06 21:12:42 +02001825 if ((blob ? rettv_blob_alloc(rettv) : rettv_list_alloc(rettv)) == FAIL)
1826 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001827
Bram Moolenaar26262f82019-09-04 20:59:15 +02001828 // Always open the file in binary mode, library functions have a mind of
1829 // their own about CR-LF conversion.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001830 fname = tv_get_string(&argvars[0]);
Bram Moolenaar15352dc2020-04-06 21:12:42 +02001831
1832 if (mch_isdir(fname))
1833 {
Bram Moolenaar4dea2d92022-03-31 11:37:57 +01001834 semsg(_(e_str_is_directory), fname);
Bram Moolenaar15352dc2020-04-06 21:12:42 +02001835 return;
1836 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001837 if (*fname == NUL || (fd = mch_fopen((char *)fname, READBIN)) == NULL)
1838 {
K.Takata11df3ae2022-10-19 14:02:40 +01001839 semsg(_(e_cant_open_file_str),
1840 *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001841 return;
1842 }
1843
1844 if (blob)
1845 {
K.Takata11df3ae2022-10-19 14:02:40 +01001846 if (read_blob(fd, rettv, offset, size) == FAIL)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00001847 semsg(_(e_cant_read_file_str), fname);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001848 fclose(fd);
1849 return;
1850 }
1851
1852 while (cnt < maxline || maxline < 0)
1853 {
1854 readlen = (int)fread(buf, 1, io_size, fd);
1855
Bram Moolenaar26262f82019-09-04 20:59:15 +02001856 // This for loop processes what was read, but is also entered at end
1857 // of file so that either:
1858 // - an incomplete line gets written
1859 // - a "binary" file gets an empty line at the end if it ends in a
1860 // newline.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001861 for (p = buf, start = buf;
1862 p < buf + readlen || (readlen <= 0 && (prevlen > 0 || binary));
1863 ++p)
1864 {
Dominique Pellef5d639a2022-01-12 15:24:40 +00001865 if (readlen <= 0 || *p == '\n')
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001866 {
1867 listitem_T *li;
1868 char_u *s = NULL;
1869 long_u len = p - start;
1870
Bram Moolenaar26262f82019-09-04 20:59:15 +02001871 // Finished a line. Remove CRs before NL.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001872 if (readlen > 0 && !binary)
1873 {
1874 while (len > 0 && start[len - 1] == '\r')
1875 --len;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001876 // removal may cross back to the "prev" string
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001877 if (len == 0)
1878 while (prevlen > 0 && prev[prevlen - 1] == '\r')
1879 --prevlen;
1880 }
1881 if (prevlen == 0)
Bram Moolenaar71ccd032020-06-12 22:59:11 +02001882 s = vim_strnsave(start, len);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001883 else
1884 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001885 // Change "prev" buffer to be the right size. This way
1886 // the bytes are only copied once, and very long lines are
1887 // allocated only once.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001888 if ((s = vim_realloc(prev, prevlen + len + 1)) != NULL)
1889 {
1890 mch_memmove(s + prevlen, start, len);
1891 s[prevlen + len] = NUL;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001892 prev = NULL; // the list will own the string
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001893 prevlen = prevsize = 0;
1894 }
1895 }
1896 if (s == NULL)
1897 {
1898 do_outofmem_msg((long_u) prevlen + len + 1);
1899 failed = TRUE;
1900 break;
1901 }
1902
1903 if ((li = listitem_alloc()) == NULL)
1904 {
1905 vim_free(s);
1906 failed = TRUE;
1907 break;
1908 }
1909 li->li_tv.v_type = VAR_STRING;
1910 li->li_tv.v_lock = 0;
1911 li->li_tv.vval.v_string = s;
1912 list_append(rettv->vval.v_list, li);
1913
Bram Moolenaar26262f82019-09-04 20:59:15 +02001914 start = p + 1; // step over newline
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001915 if ((++cnt >= maxline && maxline >= 0) || readlen <= 0)
1916 break;
1917 }
1918 else if (*p == NUL)
1919 *p = '\n';
Bram Moolenaar26262f82019-09-04 20:59:15 +02001920 // Check for utf8 "bom"; U+FEFF is encoded as EF BB BF. Do this
1921 // when finding the BF and check the previous two bytes.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001922 else if (*p == 0xbf && enc_utf8 && !binary)
1923 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001924 // Find the two bytes before the 0xbf. If p is at buf, or buf
1925 // + 1, these may be in the "prev" string.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001926 char_u back1 = p >= buf + 1 ? p[-1]
1927 : prevlen >= 1 ? prev[prevlen - 1] : NUL;
1928 char_u back2 = p >= buf + 2 ? p[-2]
1929 : p == buf + 1 && prevlen >= 1 ? prev[prevlen - 1]
1930 : prevlen >= 2 ? prev[prevlen - 2] : NUL;
1931
1932 if (back2 == 0xef && back1 == 0xbb)
1933 {
1934 char_u *dest = p - 2;
1935
Bram Moolenaar26262f82019-09-04 20:59:15 +02001936 // Usually a BOM is at the beginning of a file, and so at
1937 // the beginning of a line; then we can just step over it.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001938 if (start == dest)
1939 start = p + 1;
1940 else
1941 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001942 // have to shuffle buf to close gap
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001943 int adjust_prevlen = 0;
1944
1945 if (dest < buf)
1946 {
Bram Moolenaarc423ad72021-01-13 20:38:03 +01001947 // must be 1 or 2
1948 adjust_prevlen = (int)(buf - dest);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001949 dest = buf;
1950 }
1951 if (readlen > p - buf + 1)
1952 mch_memmove(dest, p + 1, readlen - (p - buf) - 1);
1953 readlen -= 3 - adjust_prevlen;
1954 prevlen -= adjust_prevlen;
1955 p = dest - 1;
1956 }
1957 }
1958 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02001959 } // for
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001960
1961 if (failed || (cnt >= maxline && maxline >= 0) || readlen <= 0)
1962 break;
1963 if (start < p)
1964 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001965 // There's part of a line in buf, store it in "prev".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001966 if (p - start + prevlen >= prevsize)
1967 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001968 // need bigger "prev" buffer
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001969 char_u *newprev;
1970
Bram Moolenaar26262f82019-09-04 20:59:15 +02001971 // A common use case is ordinary text files and "prev" gets a
1972 // fragment of a line, so the first allocation is made
1973 // small, to avoid repeatedly 'allocing' large and
1974 // 'reallocing' small.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001975 if (prevsize == 0)
1976 prevsize = (long)(p - start);
1977 else
1978 {
1979 long grow50pc = (prevsize * 3) / 2;
1980 long growmin = (long)((p - start) * 2 + prevlen);
1981 prevsize = grow50pc > growmin ? grow50pc : growmin;
1982 }
1983 newprev = vim_realloc(prev, prevsize);
1984 if (newprev == NULL)
1985 {
1986 do_outofmem_msg((long_u)prevsize);
1987 failed = TRUE;
1988 break;
1989 }
1990 prev = newprev;
1991 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02001992 // Add the line part to end of "prev".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001993 mch_memmove(prev + prevlen, start, p - start);
1994 prevlen += (long)(p - start);
1995 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02001996 } // while
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001997
Bram Moolenaar26262f82019-09-04 20:59:15 +02001998 // For a negative line count use only the lines at the end of the file,
1999 // free the rest.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002000 if (!failed && maxline < 0)
2001 while (cnt > -maxline)
2002 {
2003 listitem_remove(rettv->vval.v_list, rettv->vval.v_list->lv_first);
2004 --cnt;
2005 }
2006
2007 if (failed)
2008 {
2009 // an empty list is returned on error
2010 list_free(rettv->vval.v_list);
2011 rettv_list_alloc(rettv);
2012 }
2013
2014 vim_free(prev);
2015 fclose(fd);
2016}
2017
2018/*
Bram Moolenaarc423ad72021-01-13 20:38:03 +01002019 * "readblob()" function
2020 */
2021 void
2022f_readblob(typval_T *argvars, typval_T *rettv)
2023{
K.Takata11df3ae2022-10-19 14:02:40 +01002024 if (in_vim9script()
2025 && (check_for_string_arg(argvars, 0) == FAIL
2026 || check_for_opt_number_arg(argvars, 1) == FAIL
2027 || (argvars[1].v_type != VAR_UNKNOWN
2028 && check_for_opt_number_arg(argvars, 2) == FAIL)))
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02002029 return;
2030
Bram Moolenaarc423ad72021-01-13 20:38:03 +01002031 read_file_or_blob(argvars, rettv, TRUE);
2032}
2033
2034/*
2035 * "readfile()" function
2036 */
2037 void
2038f_readfile(typval_T *argvars, typval_T *rettv)
2039{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02002040 if (in_vim9script()
2041 && (check_for_nonempty_string_arg(argvars, 0) == FAIL
2042 || check_for_opt_string_arg(argvars, 1) == FAIL
2043 || (argvars[1].v_type != VAR_UNKNOWN
2044 && check_for_opt_number_arg(argvars, 2) == FAIL)))
2045 return;
2046
Bram Moolenaarc423ad72021-01-13 20:38:03 +01002047 read_file_or_blob(argvars, rettv, FALSE);
2048}
2049
2050/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002051 * "resolve()" function
2052 */
2053 void
2054f_resolve(typval_T *argvars, typval_T *rettv)
2055{
2056 char_u *p;
2057#ifdef HAVE_READLINK
2058 char_u *buf = NULL;
2059#endif
2060
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02002061 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
2062 return;
2063
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002064 p = tv_get_string(&argvars[0]);
2065#ifdef FEAT_SHORTCUT
2066 {
2067 char_u *v = NULL;
2068
2069 v = mch_resolve_path(p, TRUE);
2070 if (v != NULL)
2071 rettv->vval.v_string = v;
2072 else
2073 rettv->vval.v_string = vim_strsave(p);
2074 }
2075#else
2076# ifdef HAVE_READLINK
2077 {
2078 char_u *cpy;
2079 int len;
2080 char_u *remain = NULL;
2081 char_u *q;
2082 int is_relative_to_current = FALSE;
2083 int has_trailing_pathsep = FALSE;
2084 int limit = 100;
2085
2086 p = vim_strsave(p);
Bram Moolenaar70188f52019-12-23 18:18:52 +01002087 if (p == NULL)
2088 goto fail;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002089 if (p[0] == '.' && (vim_ispathsep(p[1])
2090 || (p[1] == '.' && (vim_ispathsep(p[2])))))
2091 is_relative_to_current = TRUE;
2092
2093 len = STRLEN(p);
Bram Moolenaar50c4e9e2020-10-05 20:38:06 +02002094 if (len > 1 && after_pathsep(p, p + len))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002095 {
2096 has_trailing_pathsep = TRUE;
Bram Moolenaar26262f82019-09-04 20:59:15 +02002097 p[len - 1] = NUL; // the trailing slash breaks readlink()
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002098 }
2099
2100 q = getnextcomp(p);
2101 if (*q != NUL)
2102 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002103 // Separate the first path component in "p", and keep the
2104 // remainder (beginning with the path separator).
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002105 remain = vim_strsave(q - 1);
2106 q[-1] = NUL;
2107 }
2108
2109 buf = alloc(MAXPATHL + 1);
2110 if (buf == NULL)
Bram Moolenaar70188f52019-12-23 18:18:52 +01002111 {
2112 vim_free(p);
Christian Brabandt29269a72024-04-16 22:44:31 +02002113 vim_free(remain);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002114 goto fail;
Bram Moolenaar70188f52019-12-23 18:18:52 +01002115 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002116
2117 for (;;)
2118 {
2119 for (;;)
2120 {
2121 len = readlink((char *)p, (char *)buf, MAXPATHL);
2122 if (len <= 0)
2123 break;
2124 buf[len] = NUL;
2125
2126 if (limit-- == 0)
2127 {
2128 vim_free(p);
2129 vim_free(remain);
Bram Moolenaara6f79292022-01-04 21:30:47 +00002130 emsg(_(e_too_many_symbolic_links_cycle));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002131 rettv->vval.v_string = NULL;
2132 goto fail;
2133 }
2134
Bram Moolenaar26262f82019-09-04 20:59:15 +02002135 // Ensure that the result will have a trailing path separator
2136 // if the argument has one.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002137 if (remain == NULL && has_trailing_pathsep)
2138 add_pathsep(buf);
2139
Bram Moolenaar26262f82019-09-04 20:59:15 +02002140 // Separate the first path component in the link value and
2141 // concatenate the remainders.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002142 q = getnextcomp(vim_ispathsep(*buf) ? buf + 1 : buf);
2143 if (*q != NUL)
2144 {
2145 if (remain == NULL)
2146 remain = vim_strsave(q - 1);
2147 else
2148 {
2149 cpy = concat_str(q - 1, remain);
2150 if (cpy != NULL)
2151 {
2152 vim_free(remain);
2153 remain = cpy;
2154 }
2155 }
2156 q[-1] = NUL;
2157 }
2158
2159 q = gettail(p);
2160 if (q > p && *q == NUL)
2161 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002162 // Ignore trailing path separator.
Ken Takata215c3262023-10-16 09:57:43 +02002163 p[q - p - 1] = NUL;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002164 q = gettail(p);
2165 }
2166 if (q > p && !mch_isFullName(buf))
2167 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002168 // symlink is relative to directory of argument
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002169 cpy = alloc(STRLEN(p) + STRLEN(buf) + 1);
2170 if (cpy != NULL)
2171 {
2172 STRCPY(cpy, p);
2173 STRCPY(gettail(cpy), buf);
2174 vim_free(p);
2175 p = cpy;
2176 }
2177 }
2178 else
2179 {
2180 vim_free(p);
2181 p = vim_strsave(buf);
2182 }
2183 }
2184
2185 if (remain == NULL)
2186 break;
2187
Bram Moolenaar26262f82019-09-04 20:59:15 +02002188 // Append the first path component of "remain" to "p".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002189 q = getnextcomp(remain + 1);
2190 len = q - remain - (*q != NUL);
2191 cpy = vim_strnsave(p, STRLEN(p) + len);
2192 if (cpy != NULL)
2193 {
2194 STRNCAT(cpy, remain, len);
2195 vim_free(p);
2196 p = cpy;
2197 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02002198 // Shorten "remain".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002199 if (*q != NUL)
2200 STRMOVE(remain, q - 1);
2201 else
2202 VIM_CLEAR(remain);
2203 }
2204
Bram Moolenaar26262f82019-09-04 20:59:15 +02002205 // If the result is a relative path name, make it explicitly relative to
2206 // the current directory if and only if the argument had this form.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002207 if (!vim_ispathsep(*p))
2208 {
2209 if (is_relative_to_current
2210 && *p != NUL
2211 && !(p[0] == '.'
2212 && (p[1] == NUL
2213 || vim_ispathsep(p[1])
2214 || (p[1] == '.'
2215 && (p[2] == NUL
2216 || vim_ispathsep(p[2]))))))
2217 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002218 // Prepend "./".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002219 cpy = concat_str((char_u *)"./", p);
2220 if (cpy != NULL)
2221 {
2222 vim_free(p);
2223 p = cpy;
2224 }
2225 }
2226 else if (!is_relative_to_current)
2227 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002228 // Strip leading "./".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002229 q = p;
2230 while (q[0] == '.' && vim_ispathsep(q[1]))
2231 q += 2;
2232 if (q > p)
2233 STRMOVE(p, p + 2);
2234 }
2235 }
2236
Bram Moolenaar26262f82019-09-04 20:59:15 +02002237 // Ensure that the result will have no trailing path separator
2238 // if the argument had none. But keep "/" or "//".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002239 if (!has_trailing_pathsep)
2240 {
2241 q = p + STRLEN(p);
2242 if (after_pathsep(p, q))
2243 *gettail_sep(p) = NUL;
2244 }
2245
2246 rettv->vval.v_string = p;
2247 }
2248# else
2249 rettv->vval.v_string = vim_strsave(p);
2250# endif
2251#endif
2252
2253 simplify_filename(rettv->vval.v_string);
2254
2255#ifdef HAVE_READLINK
2256fail:
2257 vim_free(buf);
2258#endif
2259 rettv->v_type = VAR_STRING;
2260}
2261
2262/*
2263 * "tempname()" function
2264 */
2265 void
2266f_tempname(typval_T *argvars UNUSED, typval_T *rettv)
2267{
2268 static int x = 'A';
2269
2270 rettv->v_type = VAR_STRING;
2271 rettv->vval.v_string = vim_tempname(x, FALSE);
2272
Bram Moolenaar26262f82019-09-04 20:59:15 +02002273 // Advance 'x' to use A-Z and 0-9, so that there are at least 34 different
2274 // names. Skip 'I' and 'O', they are used for shell redirection.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002275 do
2276 {
2277 if (x == 'Z')
2278 x = '0';
2279 else if (x == '9')
2280 x = 'A';
2281 else
Bram Moolenaar424bcae2022-01-31 14:59:41 +00002282 ++x;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002283 } while (x == 'I' || x == 'O');
2284}
2285
2286/*
2287 * "writefile()" function
2288 */
2289 void
2290f_writefile(typval_T *argvars, typval_T *rettv)
2291{
2292 int binary = FALSE;
2293 int append = FALSE;
Bram Moolenaar806a2732022-09-04 15:40:36 +01002294 int defer = FALSE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002295#ifdef HAVE_FSYNC
2296 int do_fsync = p_fs;
2297#endif
2298 char_u *fname;
2299 FILE *fd;
2300 int ret = 0;
2301 listitem_T *li;
2302 list_T *list = NULL;
2303 blob_T *blob = NULL;
2304
2305 rettv->vval.v_number = -1;
2306 if (check_secure())
2307 return;
2308
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02002309 if (in_vim9script()
2310 && (check_for_list_or_blob_arg(argvars, 0) == FAIL
2311 || check_for_string_arg(argvars, 1) == FAIL
2312 || check_for_opt_string_arg(argvars, 2) == FAIL))
2313 return;
2314
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002315 if (argvars[0].v_type == VAR_LIST)
2316 {
2317 list = argvars[0].vval.v_list;
2318 if (list == NULL)
2319 return;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02002320 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002321 FOR_ALL_LIST_ITEMS(list, li)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002322 if (tv_get_string_chk(&li->li_tv) == NULL)
2323 return;
2324 }
2325 else if (argvars[0].v_type == VAR_BLOB)
2326 {
2327 blob = argvars[0].vval.v_blob;
2328 if (blob == NULL)
2329 return;
2330 }
2331 else
2332 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00002333 semsg(_(e_invalid_argument_str),
Bram Moolenaar18a2b872020-03-19 13:08:45 +01002334 _("writefile() first argument must be a List or a Blob"));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002335 return;
2336 }
2337
2338 if (argvars[2].v_type != VAR_UNKNOWN)
2339 {
2340 char_u *arg2 = tv_get_string_chk(&argvars[2]);
2341
2342 if (arg2 == NULL)
2343 return;
2344 if (vim_strchr(arg2, 'b') != NULL)
2345 binary = TRUE;
2346 if (vim_strchr(arg2, 'a') != NULL)
2347 append = TRUE;
Bram Moolenaar806a2732022-09-04 15:40:36 +01002348 if (vim_strchr(arg2, 'D') != NULL)
2349 defer = TRUE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002350#ifdef HAVE_FSYNC
2351 if (vim_strchr(arg2, 's') != NULL)
2352 do_fsync = TRUE;
2353 else if (vim_strchr(arg2, 'S') != NULL)
2354 do_fsync = FALSE;
2355#endif
2356 }
2357
2358 fname = tv_get_string_chk(&argvars[1]);
2359 if (fname == NULL)
2360 return;
2361
Bram Moolenaar6f14da12022-09-07 21:30:44 +01002362 if (defer && !can_add_defer())
Bram Moolenaar806a2732022-09-04 15:40:36 +01002363 return;
Bram Moolenaar806a2732022-09-04 15:40:36 +01002364
Bram Moolenaar26262f82019-09-04 20:59:15 +02002365 // Always open the file in binary mode, library functions have a mind of
2366 // their own about CR-LF conversion.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002367 if (*fname == NUL || (fd = mch_fopen((char *)fname,
2368 append ? APPENDBIN : WRITEBIN)) == NULL)
2369 {
Bram Moolenaar806a2732022-09-04 15:40:36 +01002370 semsg(_(e_cant_create_file_str),
2371 *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002372 ret = -1;
2373 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002374 else
2375 {
Bram Moolenaar806a2732022-09-04 15:40:36 +01002376 if (defer)
2377 {
2378 typval_T tv;
2379
2380 tv.v_type = VAR_STRING;
2381 tv.v_lock = 0;
Bram Moolenaar6f14da12022-09-07 21:30:44 +01002382 tv.vval.v_string = FullName_save(fname, FALSE);
Bram Moolenaar806a2732022-09-04 15:40:36 +01002383 if (tv.vval.v_string == NULL
2384 || add_defer((char_u *)"delete", 1, &tv) == FAIL)
2385 {
2386 ret = -1;
2387 fclose(fd);
2388 (void)mch_remove(fname);
2389 }
2390 }
2391
2392 if (ret == 0)
2393 {
2394 if (blob)
2395 {
2396 if (write_blob(fd, blob) == FAIL)
2397 ret = -1;
2398 }
2399 else
2400 {
2401 if (write_list(fd, list, binary) == FAIL)
2402 ret = -1;
2403 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002404#ifdef HAVE_FSYNC
Bram Moolenaar806a2732022-09-04 15:40:36 +01002405 if (ret == 0 && do_fsync)
2406 // Ignore the error, the user wouldn't know what to do about
2407 // it. May happen for a device.
2408 vim_ignored = vim_fsync(fileno(fd));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002409#endif
Bram Moolenaar806a2732022-09-04 15:40:36 +01002410 fclose(fd);
2411 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002412 }
2413
2414 rettv->vval.v_number = ret;
2415}
2416
2417#endif // FEAT_EVAL
2418
2419#if defined(FEAT_BROWSE) || defined(PROTO)
2420/*
2421 * Generic browse function. Calls gui_mch_browse() when possible.
2422 * Later this may pop-up a non-GUI file selector (external command?).
2423 */
2424 char_u *
2425do_browse(
Bram Moolenaar26262f82019-09-04 20:59:15 +02002426 int flags, // BROWSE_SAVE and BROWSE_DIR
2427 char_u *title, // title for the window
2428 char_u *dflt, // default file name (may include directory)
2429 char_u *ext, // extension added
2430 char_u *initdir, // initial directory, NULL for current dir or
2431 // when using path from "dflt"
2432 char_u *filter, // file name filter
2433 buf_T *buf) // buffer to read/write for
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002434{
2435 char_u *fname;
Bram Moolenaar26262f82019-09-04 20:59:15 +02002436 static char_u *last_dir = NULL; // last used directory
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002437 char_u *tofree = NULL;
Bram Moolenaare1004402020-10-24 20:49:43 +02002438 int save_cmod_flags = cmdmod.cmod_flags;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002439
Bram Moolenaar26262f82019-09-04 20:59:15 +02002440 // Must turn off browse to avoid that autocommands will get the
2441 // flag too!
Bram Moolenaare1004402020-10-24 20:49:43 +02002442 cmdmod.cmod_flags &= ~CMOD_BROWSE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002443
2444 if (title == NULL || *title == NUL)
2445 {
2446 if (flags & BROWSE_DIR)
2447 title = (char_u *)_("Select Directory dialog");
2448 else if (flags & BROWSE_SAVE)
2449 title = (char_u *)_("Save File dialog");
2450 else
2451 title = (char_u *)_("Open File dialog");
2452 }
2453
Bram Moolenaar26262f82019-09-04 20:59:15 +02002454 // When no directory specified, use default file name, default dir, buffer
2455 // dir, last dir or current dir
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002456 if ((initdir == NULL || *initdir == NUL) && dflt != NULL && *dflt != NUL)
2457 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002458 if (mch_isdir(dflt)) // default file name is a directory
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002459 {
2460 initdir = dflt;
2461 dflt = NULL;
2462 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02002463 else if (gettail(dflt) != dflt) // default file name includes a path
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002464 {
2465 tofree = vim_strsave(dflt);
2466 if (tofree != NULL)
2467 {
2468 initdir = tofree;
2469 *gettail(initdir) = NUL;
2470 dflt = gettail(dflt);
2471 }
2472 }
2473 }
2474
2475 if (initdir == NULL || *initdir == NUL)
2476 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002477 // When 'browsedir' is a directory, use it
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002478 if (STRCMP(p_bsdir, "last") != 0
2479 && STRCMP(p_bsdir, "buffer") != 0
2480 && STRCMP(p_bsdir, "current") != 0
2481 && mch_isdir(p_bsdir))
2482 initdir = p_bsdir;
Bram Moolenaar26262f82019-09-04 20:59:15 +02002483 // When saving or 'browsedir' is "buffer", use buffer fname
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002484 else if (((flags & BROWSE_SAVE) || *p_bsdir == 'b')
2485 && buf != NULL && buf->b_ffname != NULL)
2486 {
2487 if (dflt == NULL || *dflt == NUL)
2488 dflt = gettail(curbuf->b_ffname);
2489 tofree = vim_strsave(curbuf->b_ffname);
2490 if (tofree != NULL)
2491 {
2492 initdir = tofree;
2493 *gettail(initdir) = NUL;
2494 }
2495 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02002496 // When 'browsedir' is "last", use dir from last browse
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002497 else if (*p_bsdir == 'l')
2498 initdir = last_dir;
Bram Moolenaar26262f82019-09-04 20:59:15 +02002499 // When 'browsedir is "current", use current directory. This is the
2500 // default already, leave initdir empty.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002501 }
2502
2503# ifdef FEAT_GUI
Bram Moolenaar26262f82019-09-04 20:59:15 +02002504 if (gui.in_use) // when this changes, also adjust f_has()!
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002505 {
2506 if (filter == NULL
2507# ifdef FEAT_EVAL
2508 && (filter = get_var_value((char_u *)"b:browsefilter")) == NULL
2509 && (filter = get_var_value((char_u *)"g:browsefilter")) == NULL
2510# endif
2511 )
2512 filter = BROWSE_FILTER_DEFAULT;
2513 if (flags & BROWSE_DIR)
2514 {
2515# if defined(FEAT_GUI_GTK) || defined(MSWIN)
Bram Moolenaar26262f82019-09-04 20:59:15 +02002516 // For systems that have a directory dialog.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002517 fname = gui_mch_browsedir(title, initdir);
2518# else
Bram Moolenaar26262f82019-09-04 20:59:15 +02002519 // Generic solution for selecting a directory: select a file and
2520 // remove the file name.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002521 fname = gui_mch_browse(0, title, dflt, ext, initdir, (char_u *)"");
2522# endif
2523# if !defined(FEAT_GUI_GTK)
Bram Moolenaar26262f82019-09-04 20:59:15 +02002524 // Win32 adds a dummy file name, others return an arbitrary file
2525 // name. GTK+ 2 returns only the directory,
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002526 if (fname != NULL && *fname != NUL && !mch_isdir(fname))
2527 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002528 // Remove the file name.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002529 char_u *tail = gettail_sep(fname);
2530
2531 if (tail == fname)
Bram Moolenaar26262f82019-09-04 20:59:15 +02002532 *tail++ = '.'; // use current dir
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002533 *tail = NUL;
2534 }
2535# endif
2536 }
2537 else
2538 fname = gui_mch_browse(flags & BROWSE_SAVE,
2539 title, dflt, ext, initdir, (char_u *)_(filter));
2540
Bram Moolenaar26262f82019-09-04 20:59:15 +02002541 // We hang around in the dialog for a while, the user might do some
2542 // things to our files. The Win32 dialog allows deleting or renaming
2543 // a file, check timestamps.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002544 need_check_timestamps = TRUE;
2545 did_check_timestamps = FALSE;
2546 }
2547 else
2548# endif
2549 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002550 // TODO: non-GUI file selector here
Bram Moolenaareaaac012022-01-02 17:00:40 +00002551 emsg(_(e_sorry_no_file_browser_in_console_mode));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002552 fname = NULL;
2553 }
2554
Bram Moolenaar26262f82019-09-04 20:59:15 +02002555 // keep the directory for next time
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002556 if (fname != NULL)
2557 {
2558 vim_free(last_dir);
2559 last_dir = vim_strsave(fname);
2560 if (last_dir != NULL && !(flags & BROWSE_DIR))
2561 {
2562 *gettail(last_dir) = NUL;
2563 if (*last_dir == NUL)
2564 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002565 // filename only returned, must be in current dir
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002566 vim_free(last_dir);
2567 last_dir = alloc(MAXPATHL);
2568 if (last_dir != NULL)
2569 mch_dirname(last_dir, MAXPATHL);
2570 }
2571 }
2572 }
2573
2574 vim_free(tofree);
Bram Moolenaare1004402020-10-24 20:49:43 +02002575 cmdmod.cmod_flags = save_cmod_flags;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002576
2577 return fname;
2578}
2579#endif
2580
2581#if defined(FEAT_EVAL) || defined(PROTO)
2582
2583/*
2584 * "browse(save, title, initdir, default)" function
2585 */
2586 void
2587f_browse(typval_T *argvars UNUSED, typval_T *rettv)
2588{
2589# ifdef FEAT_BROWSE
2590 int save;
2591 char_u *title;
2592 char_u *initdir;
2593 char_u *defname;
2594 char_u buf[NUMBUFLEN];
2595 char_u buf2[NUMBUFLEN];
2596 int error = FALSE;
2597
Bram Moolenaarf28f2ac2021-03-22 22:21:26 +01002598 if (in_vim9script()
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02002599 && (check_for_bool_arg(argvars, 0) == FAIL
2600 || check_for_string_arg(argvars, 1) == FAIL
Bram Moolenaar32105ae2021-03-27 18:59:25 +01002601 || check_for_string_arg(argvars, 2) == FAIL
2602 || check_for_string_arg(argvars, 3) == FAIL))
Bram Moolenaarf28f2ac2021-03-22 22:21:26 +01002603 return;
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02002604
Bram Moolenaar5a049842022-10-08 12:52:09 +01002605 save = (int)tv_get_bool_chk(&argvars[0], &error);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002606 title = tv_get_string_chk(&argvars[1]);
2607 initdir = tv_get_string_buf_chk(&argvars[2], buf);
2608 defname = tv_get_string_buf_chk(&argvars[3], buf2);
2609
2610 if (error || title == NULL || initdir == NULL || defname == NULL)
2611 rettv->vval.v_string = NULL;
2612 else
2613 rettv->vval.v_string =
2614 do_browse(save ? BROWSE_SAVE : 0,
2615 title, defname, NULL, initdir, NULL, curbuf);
2616# else
2617 rettv->vval.v_string = NULL;
2618# endif
2619 rettv->v_type = VAR_STRING;
2620}
2621
2622/*
2623 * "browsedir(title, initdir)" function
2624 */
2625 void
2626f_browsedir(typval_T *argvars UNUSED, typval_T *rettv)
2627{
2628# ifdef FEAT_BROWSE
2629 char_u *title;
2630 char_u *initdir;
2631 char_u buf[NUMBUFLEN];
2632
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02002633 if (in_vim9script()
2634 && (check_for_string_arg(argvars, 0) == FAIL
2635 || check_for_string_arg(argvars, 1) == FAIL))
2636 return;
2637
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002638 title = tv_get_string_chk(&argvars[0]);
2639 initdir = tv_get_string_buf_chk(&argvars[1], buf);
2640
2641 if (title == NULL || initdir == NULL)
2642 rettv->vval.v_string = NULL;
2643 else
2644 rettv->vval.v_string = do_browse(BROWSE_DIR,
2645 title, NULL, NULL, initdir, NULL, curbuf);
2646# else
2647 rettv->vval.v_string = NULL;
2648# endif
2649 rettv->v_type = VAR_STRING;
2650}
2651
Shougo Matsushita60c87432024-06-03 22:59:27 +02002652/*
2653 * "filecopy()" function
2654 */
2655 void
2656f_filecopy(typval_T *argvars, typval_T *rettv)
2657{
2658 char_u *from;
2659 stat_T st;
2660
2661 rettv->vval.v_number = FALSE;
2662
2663 if (check_restricted() || check_secure()
2664 || check_for_string_arg(argvars, 0) == FAIL
2665 || check_for_string_arg(argvars, 1) == FAIL)
2666 return;
2667
2668 from = tv_get_string(&argvars[0]);
2669
2670 if (mch_lstat((char *)from, &st) >= 0
2671 && (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)))
2672 rettv->vval.v_number = vim_copyfile(
2673 tv_get_string(&argvars[0]),
2674 tv_get_string(&argvars[1])) == OK ? TRUE : FALSE;
2675}
2676
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002677#endif // FEAT_EVAL
Bram Moolenaar26262f82019-09-04 20:59:15 +02002678
2679/*
2680 * Replace home directory by "~" in each space or comma separated file name in
2681 * 'src'.
2682 * If anything fails (except when out of space) dst equals src.
2683 */
2684 void
2685home_replace(
2686 buf_T *buf, // when not NULL, check for help files
2687 char_u *src, // input file name
2688 char_u *dst, // where to put the result
2689 int dstlen, // maximum length of the result
2690 int one) // if TRUE, only replace one file name, include
2691 // spaces and commas in the file name.
2692{
2693 size_t dirlen = 0, envlen = 0;
2694 size_t len;
2695 char_u *homedir_env, *homedir_env_orig;
2696 char_u *p;
2697
2698 if (src == NULL)
2699 {
2700 *dst = NUL;
2701 return;
2702 }
2703
2704 /*
2705 * If the file is a help file, remove the path completely.
2706 */
2707 if (buf != NULL && buf->b_help)
2708 {
2709 vim_snprintf((char *)dst, dstlen, "%s", gettail(src));
2710 return;
2711 }
2712
2713 /*
2714 * We check both the value of the $HOME environment variable and the
2715 * "real" home directory.
2716 */
2717 if (homedir != NULL)
2718 dirlen = STRLEN(homedir);
2719
2720#ifdef VMS
2721 homedir_env_orig = homedir_env = mch_getenv((char_u *)"SYS$LOGIN");
2722#else
2723 homedir_env_orig = homedir_env = mch_getenv((char_u *)"HOME");
2724#endif
2725#ifdef MSWIN
2726 if (homedir_env == NULL)
2727 homedir_env_orig = homedir_env = mch_getenv((char_u *)"USERPROFILE");
2728#endif
2729 // Empty is the same as not set.
2730 if (homedir_env != NULL && *homedir_env == NUL)
2731 homedir_env = NULL;
2732
2733 if (homedir_env != NULL && *homedir_env == '~')
2734 {
Mike Williams51024bb2024-05-30 07:46:30 +02002735 size_t usedlen = 0;
Bram Moolenaar26262f82019-09-04 20:59:15 +02002736 int flen;
2737 char_u *fbuf = NULL;
2738
2739 flen = (int)STRLEN(homedir_env);
2740 (void)modify_fname((char_u *)":p", FALSE, &usedlen,
2741 &homedir_env, &fbuf, &flen);
2742 flen = (int)STRLEN(homedir_env);
2743 if (flen > 0 && vim_ispathsep(homedir_env[flen - 1]))
2744 // Remove the trailing / that is added to a directory.
2745 homedir_env[flen - 1] = NUL;
2746 }
2747
2748 if (homedir_env != NULL)
2749 envlen = STRLEN(homedir_env);
2750
2751 if (!one)
2752 src = skipwhite(src);
2753 while (*src && dstlen > 0)
2754 {
2755 /*
2756 * Here we are at the beginning of a file name.
2757 * First, check to see if the beginning of the file name matches
2758 * $HOME or the "real" home directory. Check that there is a '/'
2759 * after the match (so that if e.g. the file is "/home/pieter/bla",
2760 * and the home directory is "/home/piet", the file does not end up
2761 * as "~er/bla" (which would seem to indicate the file "bla" in user
2762 * er's home directory)).
2763 */
2764 p = homedir;
2765 len = dirlen;
2766 for (;;)
2767 {
2768 if ( len
2769 && fnamencmp(src, p, len) == 0
2770 && (vim_ispathsep(src[len])
2771 || (!one && (src[len] == ',' || src[len] == ' '))
2772 || src[len] == NUL))
2773 {
2774 src += len;
2775 if (--dstlen > 0)
2776 *dst++ = '~';
2777
Bram Moolenaar0e390f42020-06-10 13:12:28 +02002778 // Do not add directory separator into dst, because dst is
2779 // expected to just return the directory name without the
2780 // directory separator '/'.
Bram Moolenaar26262f82019-09-04 20:59:15 +02002781 break;
2782 }
2783 if (p == homedir_env)
2784 break;
2785 p = homedir_env;
2786 len = envlen;
2787 }
2788
2789 // if (!one) skip to separator: space or comma
2790 while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0)
2791 *dst++ = *src++;
2792 // skip separator
2793 while ((*src == ' ' || *src == ',') && --dstlen > 0)
2794 *dst++ = *src++;
2795 }
2796 // if (dstlen == 0) out of space, what to do???
2797
2798 *dst = NUL;
2799
2800 if (homedir_env != homedir_env_orig)
2801 vim_free(homedir_env);
2802}
2803
2804/*
2805 * Like home_replace, store the replaced string in allocated memory.
2806 * When something fails, NULL is returned.
2807 */
2808 char_u *
2809home_replace_save(
2810 buf_T *buf, // when not NULL, check for help files
2811 char_u *src) // input file name
2812{
2813 char_u *dst;
2814 unsigned len;
2815
2816 len = 3; // space for "~/" and trailing NUL
2817 if (src != NULL) // just in case
2818 len += (unsigned)STRLEN(src);
2819 dst = alloc(len);
2820 if (dst != NULL)
2821 home_replace(buf, src, dst, len, TRUE);
2822 return dst;
2823}
2824
2825/*
2826 * Compare two file names and return:
2827 * FPC_SAME if they both exist and are the same file.
2828 * FPC_SAMEX if they both don't exist and have the same file name.
2829 * FPC_DIFF if they both exist and are different files.
2830 * FPC_NOTX if they both don't exist.
2831 * FPC_DIFFX if one of them doesn't exist.
2832 * For the first name environment variables are expanded if "expandenv" is
2833 * TRUE.
2834 */
2835 int
2836fullpathcmp(
2837 char_u *s1,
2838 char_u *s2,
2839 int checkname, // when both don't exist, check file names
2840 int expandenv)
2841{
2842#ifdef UNIX
2843 char_u exp1[MAXPATHL];
2844 char_u full1[MAXPATHL];
2845 char_u full2[MAXPATHL];
2846 stat_T st1, st2;
2847 int r1, r2;
2848
2849 if (expandenv)
2850 expand_env(s1, exp1, MAXPATHL);
2851 else
2852 vim_strncpy(exp1, s1, MAXPATHL - 1);
2853 r1 = mch_stat((char *)exp1, &st1);
2854 r2 = mch_stat((char *)s2, &st2);
2855 if (r1 != 0 && r2 != 0)
2856 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002857 // if mch_stat() doesn't work, may compare the names
Bram Moolenaar26262f82019-09-04 20:59:15 +02002858 if (checkname)
2859 {
2860 if (fnamecmp(exp1, s2) == 0)
2861 return FPC_SAMEX;
2862 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
2863 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
2864 if (r1 == OK && r2 == OK && fnamecmp(full1, full2) == 0)
2865 return FPC_SAMEX;
2866 }
2867 return FPC_NOTX;
2868 }
2869 if (r1 != 0 || r2 != 0)
2870 return FPC_DIFFX;
2871 if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
2872 return FPC_SAME;
2873 return FPC_DIFF;
2874#else
2875 char_u *exp1; // expanded s1
2876 char_u *full1; // full path of s1
2877 char_u *full2; // full path of s2
2878 int retval = FPC_DIFF;
2879 int r1, r2;
2880
2881 // allocate one buffer to store three paths (alloc()/free() is slow!)
2882 if ((exp1 = alloc(MAXPATHL * 3)) != NULL)
2883 {
2884 full1 = exp1 + MAXPATHL;
2885 full2 = full1 + MAXPATHL;
2886
2887 if (expandenv)
2888 expand_env(s1, exp1, MAXPATHL);
2889 else
2890 vim_strncpy(exp1, s1, MAXPATHL - 1);
2891 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
2892 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
2893
2894 // If vim_FullName() fails, the file probably doesn't exist.
2895 if (r1 != OK && r2 != OK)
2896 {
2897 if (checkname && fnamecmp(exp1, s2) == 0)
2898 retval = FPC_SAMEX;
2899 else
2900 retval = FPC_NOTX;
2901 }
2902 else if (r1 != OK || r2 != OK)
2903 retval = FPC_DIFFX;
2904 else if (fnamecmp(full1, full2))
2905 retval = FPC_DIFF;
2906 else
2907 retval = FPC_SAME;
2908 vim_free(exp1);
2909 }
2910 return retval;
2911#endif
2912}
2913
2914/*
2915 * Get the tail of a path: the file name.
2916 * When the path ends in a path separator the tail is the NUL after it.
2917 * Fail safe: never returns NULL.
2918 */
2919 char_u *
2920gettail(char_u *fname)
2921{
2922 char_u *p1, *p2;
2923
2924 if (fname == NULL)
2925 return (char_u *)"";
2926 for (p1 = p2 = get_past_head(fname); *p2; ) // find last part of path
2927 {
2928 if (vim_ispathsep_nocolon(*p2))
2929 p1 = p2 + 1;
2930 MB_PTR_ADV(p2);
2931 }
2932 return p1;
2933}
2934
2935/*
2936 * Get pointer to tail of "fname", including path separators. Putting a NUL
2937 * here leaves the directory name. Takes care of "c:/" and "//".
2938 * Always returns a valid pointer.
2939 */
2940 char_u *
2941gettail_sep(char_u *fname)
2942{
2943 char_u *p;
2944 char_u *t;
2945
2946 p = get_past_head(fname); // don't remove the '/' from "c:/file"
2947 t = gettail(fname);
2948 while (t > p && after_pathsep(fname, t))
2949 --t;
2950#ifdef VMS
2951 // path separator is part of the path
2952 ++t;
2953#endif
2954 return t;
2955}
2956
2957/*
2958 * get the next path component (just after the next path separator).
2959 */
2960 char_u *
2961getnextcomp(char_u *fname)
2962{
2963 while (*fname && !vim_ispathsep(*fname))
2964 MB_PTR_ADV(fname);
2965 if (*fname)
2966 ++fname;
2967 return fname;
2968}
2969
2970/*
2971 * Get a pointer to one character past the head of a path name.
2972 * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
2973 * If there is no head, path is returned.
2974 */
2975 char_u *
2976get_past_head(char_u *path)
2977{
2978 char_u *retval;
2979
2980#if defined(MSWIN)
2981 // may skip "c:"
Keith Thompson184f71c2024-01-04 21:19:04 +01002982 if (SAFE_isalpha(path[0]) && path[1] == ':')
Bram Moolenaar26262f82019-09-04 20:59:15 +02002983 retval = path + 2;
2984 else
2985 retval = path;
2986#else
2987# if defined(AMIGA)
2988 // may skip "label:"
2989 retval = vim_strchr(path, ':');
2990 if (retval == NULL)
2991 retval = path;
2992# else // Unix
2993 retval = path;
2994# endif
2995#endif
2996
2997 while (vim_ispathsep(*retval))
2998 ++retval;
2999
3000 return retval;
3001}
3002
3003/*
3004 * Return TRUE if 'c' is a path separator.
3005 * Note that for MS-Windows this includes the colon.
3006 */
3007 int
3008vim_ispathsep(int c)
3009{
3010#ifdef UNIX
3011 return (c == '/'); // UNIX has ':' inside file names
3012#else
3013# ifdef BACKSLASH_IN_FILENAME
3014 return (c == ':' || c == '/' || c == '\\');
3015# else
3016# ifdef VMS
3017 // server"user passwd"::device:[full.path.name]fname.extension;version"
3018 return (c == ':' || c == '[' || c == ']' || c == '/'
3019 || c == '<' || c == '>' || c == '"' );
3020# else
3021 return (c == ':' || c == '/');
3022# endif // VMS
3023# endif
3024#endif
3025}
3026
3027/*
3028 * Like vim_ispathsep(c), but exclude the colon for MS-Windows.
3029 */
3030 int
3031vim_ispathsep_nocolon(int c)
3032{
3033 return vim_ispathsep(c)
3034#ifdef BACKSLASH_IN_FILENAME
3035 && c != ':'
3036#endif
3037 ;
3038}
3039
3040/*
Bram Moolenaar26262f82019-09-04 20:59:15 +02003041 * Return TRUE if the directory of "fname" exists, FALSE otherwise.
3042 * Also returns TRUE if there is no directory name.
3043 * "fname" must be writable!.
3044 */
3045 int
3046dir_of_file_exists(char_u *fname)
3047{
3048 char_u *p;
3049 int c;
3050 int retval;
3051
3052 p = gettail_sep(fname);
3053 if (p == fname)
3054 return TRUE;
3055 c = *p;
3056 *p = NUL;
3057 retval = mch_isdir(fname);
3058 *p = c;
3059 return retval;
3060}
3061
3062/*
3063 * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally
3064 * and deal with 'fileignorecase'.
3065 */
3066 int
3067vim_fnamecmp(char_u *x, char_u *y)
3068{
3069#ifdef BACKSLASH_IN_FILENAME
3070 return vim_fnamencmp(x, y, MAXPATHL);
3071#else
3072 if (p_fic)
3073 return MB_STRICMP(x, y);
3074 return STRCMP(x, y);
3075#endif
3076}
3077
3078 int
3079vim_fnamencmp(char_u *x, char_u *y, size_t len)
3080{
3081#ifdef BACKSLASH_IN_FILENAME
3082 char_u *px = x;
3083 char_u *py = y;
3084 int cx = NUL;
3085 int cy = NUL;
3086
3087 while (len > 0)
3088 {
3089 cx = PTR2CHAR(px);
3090 cy = PTR2CHAR(py);
3091 if (cx == NUL || cy == NUL
3092 || ((p_fic ? MB_TOLOWER(cx) != MB_TOLOWER(cy) : cx != cy)
3093 && !(cx == '/' && cy == '\\')
3094 && !(cx == '\\' && cy == '/')))
3095 break;
Bram Moolenaar1614a142019-10-06 22:00:13 +02003096 len -= mb_ptr2len(px);
3097 px += mb_ptr2len(px);
3098 py += mb_ptr2len(py);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003099 }
3100 if (len == 0)
3101 return 0;
3102 return (cx - cy);
3103#else
3104 if (p_fic)
3105 return MB_STRNICMP(x, y, len);
3106 return STRNCMP(x, y, len);
3107#endif
3108}
3109
3110/*
3111 * Concatenate file names fname1 and fname2 into allocated memory.
3112 * Only add a '/' or '\\' when 'sep' is TRUE and it is necessary.
3113 */
3114 char_u *
3115concat_fnames(char_u *fname1, char_u *fname2, int sep)
3116{
3117 char_u *dest;
3118
3119 dest = alloc(STRLEN(fname1) + STRLEN(fname2) + 3);
Yegappan Lakshmanan1cfb14a2023-01-09 19:04:23 +00003120 if (dest == NULL)
3121 return NULL;
3122
3123 STRCPY(dest, fname1);
3124 if (sep)
3125 add_pathsep(dest);
3126 STRCAT(dest, fname2);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003127 return dest;
3128}
3129
3130/*
3131 * Add a path separator to a file name, unless it already ends in a path
3132 * separator.
3133 */
3134 void
3135add_pathsep(char_u *p)
3136{
3137 if (*p != NUL && !after_pathsep(p, p + STRLEN(p)))
3138 STRCAT(p, PATHSEPSTR);
3139}
3140
3141/*
3142 * FullName_save - Make an allocated copy of a full file name.
3143 * Returns NULL when out of memory.
3144 */
3145 char_u *
3146FullName_save(
3147 char_u *fname,
3148 int force) // force expansion, even when it already looks
3149 // like a full path name
3150{
3151 char_u *buf;
3152 char_u *new_fname = NULL;
3153
3154 if (fname == NULL)
3155 return NULL;
3156
3157 buf = alloc(MAXPATHL);
Yegappan Lakshmanan1cfb14a2023-01-09 19:04:23 +00003158 if (buf == NULL)
3159 return NULL;
3160
3161 if (vim_FullName(fname, buf, MAXPATHL, force) != FAIL)
3162 new_fname = vim_strsave(buf);
3163 else
3164 new_fname = vim_strsave(fname);
3165 vim_free(buf);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003166 return new_fname;
3167}
3168
3169/*
3170 * return TRUE if "fname" exists.
3171 */
3172 int
3173vim_fexists(char_u *fname)
3174{
3175 stat_T st;
3176
3177 if (mch_stat((char *)fname, &st))
3178 return FALSE;
3179 return TRUE;
3180}
3181
3182/*
3183 * Invoke expand_wildcards() for one pattern.
3184 * Expand items like "%:h" before the expansion.
3185 * Returns OK or FAIL.
3186 */
3187 int
3188expand_wildcards_eval(
3189 char_u **pat, // pointer to input pattern
3190 int *num_file, // resulting number of files
3191 char_u ***file, // array of resulting files
3192 int flags) // EW_DIR, etc.
3193{
3194 int ret = FAIL;
3195 char_u *eval_pat = NULL;
3196 char_u *exp_pat = *pat;
Bram Moolenaarf5724372022-09-02 19:45:15 +01003197 char *ignored_msg;
Mike Williams51024bb2024-05-30 07:46:30 +02003198 size_t usedlen;
Bram Moolenaarf5724372022-09-02 19:45:15 +01003199 int is_cur_alt_file = *exp_pat == '%' || *exp_pat == '#';
3200 int star_follows = FALSE;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003201
Bram Moolenaarf5724372022-09-02 19:45:15 +01003202 if (is_cur_alt_file || *exp_pat == '<')
Bram Moolenaar26262f82019-09-04 20:59:15 +02003203 {
3204 ++emsg_off;
3205 eval_pat = eval_vars(exp_pat, exp_pat, &usedlen,
Bram Moolenaara96edb72022-04-28 17:52:24 +01003206 NULL, &ignored_msg, NULL, TRUE);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003207 --emsg_off;
3208 if (eval_pat != NULL)
Bram Moolenaarf5724372022-09-02 19:45:15 +01003209 {
3210 star_follows = STRCMP(exp_pat + usedlen, "*") == 0;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003211 exp_pat = concat_str(eval_pat, exp_pat + usedlen);
Bram Moolenaarf5724372022-09-02 19:45:15 +01003212 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02003213 }
3214
3215 if (exp_pat != NULL)
3216 ret = expand_wildcards(1, &exp_pat, num_file, file, flags);
3217
3218 if (eval_pat != NULL)
3219 {
Bram Moolenaarf5724372022-09-02 19:45:15 +01003220 if (*num_file == 0 && is_cur_alt_file && star_follows)
3221 {
3222 // Expanding "%" or "#" and the file does not exist: Add the
3223 // pattern anyway (without the star) so that this works for remote
3224 // files and non-file buffer names.
3225 *file = ALLOC_ONE(char_u *);
3226 if (*file != NULL)
3227 {
3228 **file = eval_pat;
3229 eval_pat = NULL;
3230 *num_file = 1;
3231 ret = OK;
3232 }
3233 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02003234 vim_free(exp_pat);
3235 vim_free(eval_pat);
3236 }
3237
3238 return ret;
3239}
3240
3241/*
3242 * Expand wildcards. Calls gen_expand_wildcards() and removes files matching
3243 * 'wildignore'.
3244 * Returns OK or FAIL. When FAIL then "num_files" won't be set.
3245 */
3246 int
3247expand_wildcards(
3248 int num_pat, // number of input patterns
3249 char_u **pat, // array of input patterns
3250 int *num_files, // resulting number of files
3251 char_u ***files, // array of resulting files
3252 int flags) // EW_DIR, etc.
3253{
3254 int retval;
3255 int i, j;
3256 char_u *p;
3257 int non_suf_match; // number without matching suffix
3258
3259 retval = gen_expand_wildcards(num_pat, pat, num_files, files, flags);
3260
3261 // When keeping all matches, return here
3262 if ((flags & EW_KEEPALL) || retval == FAIL)
3263 return retval;
3264
Bram Moolenaar26262f82019-09-04 20:59:15 +02003265 /*
3266 * Remove names that match 'wildignore'.
3267 */
3268 if (*p_wig)
3269 {
3270 char_u *ffname;
3271
3272 // check all files in (*files)[]
3273 for (i = 0; i < *num_files; ++i)
3274 {
3275 ffname = FullName_save((*files)[i], FALSE);
3276 if (ffname == NULL) // out of memory
3277 break;
3278# ifdef VMS
3279 vms_remove_version(ffname);
3280# endif
3281 if (match_file_list(p_wig, (*files)[i], ffname))
3282 {
3283 // remove this matching file from the list
3284 vim_free((*files)[i]);
3285 for (j = i; j + 1 < *num_files; ++j)
3286 (*files)[j] = (*files)[j + 1];
3287 --*num_files;
3288 --i;
3289 }
3290 vim_free(ffname);
3291 }
3292
3293 // If the number of matches is now zero, we fail.
3294 if (*num_files == 0)
3295 {
3296 VIM_CLEAR(*files);
3297 return FAIL;
3298 }
3299 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02003300
3301 /*
3302 * Move the names where 'suffixes' match to the end.
Bram Moolenaar57e95172022-08-20 19:26:14 +01003303 * Skip when interrupted, the result probably won't be used.
Bram Moolenaar26262f82019-09-04 20:59:15 +02003304 */
Bram Moolenaar57e95172022-08-20 19:26:14 +01003305 if (*num_files > 1 && !got_int)
Bram Moolenaar26262f82019-09-04 20:59:15 +02003306 {
3307 non_suf_match = 0;
3308 for (i = 0; i < *num_files; ++i)
3309 {
3310 if (!match_suffix((*files)[i]))
3311 {
3312 /*
3313 * Move the name without matching suffix to the front
3314 * of the list.
3315 */
3316 p = (*files)[i];
3317 for (j = i; j > non_suf_match; --j)
3318 (*files)[j] = (*files)[j - 1];
3319 (*files)[non_suf_match++] = p;
3320 }
3321 }
3322 }
3323
3324 return retval;
3325}
3326
3327/*
3328 * Return TRUE if "fname" matches with an entry in 'suffixes'.
3329 */
3330 int
3331match_suffix(char_u *fname)
3332{
3333 int fnamelen, setsuflen;
3334 char_u *setsuf;
3335#define MAXSUFLEN 30 // maximum length of a file suffix
3336 char_u suf_buf[MAXSUFLEN];
3337
3338 fnamelen = (int)STRLEN(fname);
3339 setsuflen = 0;
3340 for (setsuf = p_su; *setsuf; )
3341 {
3342 setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
3343 if (setsuflen == 0)
3344 {
3345 char_u *tail = gettail(fname);
3346
3347 // empty entry: match name without a '.'
3348 if (vim_strchr(tail, '.') == NULL)
3349 {
3350 setsuflen = 1;
3351 break;
3352 }
3353 }
3354 else
3355 {
3356 if (fnamelen >= setsuflen
3357 && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
3358 (size_t)setsuflen) == 0)
3359 break;
3360 setsuflen = 0;
3361 }
3362 }
3363 return (setsuflen != 0);
3364}
3365
3366#ifdef VIM_BACKTICK
3367
3368/*
3369 * Return TRUE if we can expand this backtick thing here.
3370 */
3371 static int
3372vim_backtick(char_u *p)
3373{
3374 return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
3375}
3376
3377/*
3378 * Expand an item in `backticks` by executing it as a command.
3379 * Currently only works when pat[] starts and ends with a `.
3380 * Returns number of file names found, -1 if an error is encountered.
3381 */
3382 static int
3383expand_backtick(
3384 garray_T *gap,
3385 char_u *pat,
3386 int flags) // EW_* flags
3387{
3388 char_u *p;
3389 char_u *cmd;
3390 char_u *buffer;
3391 int cnt = 0;
3392 int i;
3393
3394 // Create the command: lop off the backticks.
Bram Moolenaar71ccd032020-06-12 22:59:11 +02003395 cmd = vim_strnsave(pat + 1, STRLEN(pat) - 2);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003396 if (cmd == NULL)
3397 return -1;
3398
3399#ifdef FEAT_EVAL
3400 if (*cmd == '=') // `={expr}`: Expand expression
Bram Moolenaara4e0b972022-10-01 19:43:52 +01003401 buffer = eval_to_string(cmd + 1, TRUE, FALSE);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003402 else
3403#endif
3404 buffer = get_cmd_output(cmd, NULL,
3405 (flags & EW_SILENT) ? SHELL_SILENT : 0, NULL);
3406 vim_free(cmd);
3407 if (buffer == NULL)
3408 return -1;
3409
3410 cmd = buffer;
3411 while (*cmd != NUL)
3412 {
3413 cmd = skipwhite(cmd); // skip over white space
3414 p = cmd;
3415 while (*p != NUL && *p != '\r' && *p != '\n') // skip over entry
3416 ++p;
3417 // add an entry if it is not empty
3418 if (p > cmd)
3419 {
3420 i = *p;
3421 *p = NUL;
3422 addfile(gap, cmd, flags);
3423 *p = i;
3424 ++cnt;
3425 }
3426 cmd = p;
3427 while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
3428 ++cmd;
3429 }
3430
3431 vim_free(buffer);
3432 return cnt;
3433}
3434#endif // VIM_BACKTICK
3435
3436#if defined(MSWIN)
3437/*
3438 * File name expansion code for MS-DOS, Win16 and Win32. It's here because
3439 * it's shared between these systems.
3440 */
3441
3442/*
3443 * comparison function for qsort in dos_expandpath()
3444 */
3445 static int
3446pstrcmp(const void *a, const void *b)
3447{
3448 return (pathcmp(*(char **)a, *(char **)b, -1));
3449}
3450
3451/*
3452 * Recursively expand one path component into all matching files and/or
3453 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
3454 * Return the number of matches found.
3455 * "path" has backslashes before chars that are not to be expanded, starting
3456 * at "path[wildoff]".
3457 * Return the number of matches found.
3458 * NOTE: much of this is identical to unix_expandpath(), keep in sync!
3459 */
3460 static int
3461dos_expandpath(
3462 garray_T *gap,
3463 char_u *path,
3464 int wildoff,
3465 int flags, // EW_* flags
3466 int didstar) // expanded "**" once already
3467{
3468 char_u *buf;
3469 char_u *path_end;
3470 char_u *p, *s, *e;
3471 int start_len = gap->ga_len;
3472 char_u *pat;
3473 regmatch_T regmatch;
3474 int starts_with_dot;
3475 int matches;
3476 int len;
3477 int starstar = FALSE;
3478 static int stardepth = 0; // depth for "**" expansion
3479 HANDLE hFind = INVALID_HANDLE_VALUE;
3480 WIN32_FIND_DATAW wfb;
3481 WCHAR *wn = NULL; // UCS-2 name, NULL when not used.
3482 char_u *matchname;
3483 int ok;
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003484 char_u *p_alt;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003485
3486 // Expanding "**" may take a long time, check for CTRL-C.
3487 if (stardepth > 0)
3488 {
3489 ui_breakcheck();
3490 if (got_int)
3491 return 0;
3492 }
3493
3494 // Make room for file name. When doing encoding conversion the actual
3495 // length may be quite a bit longer, thus use the maximum possible length.
3496 buf = alloc(MAXPATHL);
3497 if (buf == NULL)
3498 return 0;
3499
3500 /*
3501 * Find the first part in the path name that contains a wildcard or a ~1.
3502 * Copy it into buf, including the preceding characters.
3503 */
3504 p = buf;
3505 s = buf;
3506 e = NULL;
3507 path_end = path;
3508 while (*path_end != NUL)
3509 {
3510 // May ignore a wildcard that has a backslash before it; it will
3511 // be removed by rem_backslash() or file_pat_to_reg_pat() below.
3512 if (path_end >= path + wildoff && rem_backslash(path_end))
3513 *p++ = *path_end++;
3514 else if (*path_end == '\\' || *path_end == ':' || *path_end == '/')
3515 {
3516 if (e != NULL)
3517 break;
3518 s = p + 1;
3519 }
3520 else if (path_end >= path + wildoff
3521 && vim_strchr((char_u *)"*?[~", *path_end) != NULL)
3522 e = p;
3523 if (has_mbyte)
3524 {
3525 len = (*mb_ptr2len)(path_end);
3526 STRNCPY(p, path_end, len);
3527 p += len;
3528 path_end += len;
3529 }
3530 else
3531 *p++ = *path_end++;
3532 }
3533 e = p;
3534 *e = NUL;
3535
3536 // now we have one wildcard component between s and e
3537 // Remove backslashes between "wildoff" and the start of the wildcard
3538 // component.
3539 for (p = buf + wildoff; p < s; ++p)
3540 if (rem_backslash(p))
3541 {
3542 STRMOVE(p, p + 1);
3543 --e;
3544 --s;
3545 }
3546
3547 // Check for "**" between "s" and "e".
3548 for (p = s; p < e; ++p)
3549 if (p[0] == '*' && p[1] == '*')
3550 starstar = TRUE;
3551
3552 starts_with_dot = *s == '.';
3553 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
3554 if (pat == NULL)
3555 {
3556 vim_free(buf);
3557 return 0;
3558 }
3559
3560 // compile the regexp into a program
3561 if (flags & (EW_NOERROR | EW_NOTWILD))
3562 ++emsg_silent;
3563 regmatch.rm_ic = TRUE; // Always ignore case
3564 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
3565 if (flags & (EW_NOERROR | EW_NOTWILD))
3566 --emsg_silent;
3567 vim_free(pat);
3568
3569 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
3570 {
3571 vim_free(buf);
3572 return 0;
3573 }
3574
3575 // remember the pattern or file name being looked for
3576 matchname = vim_strsave(s);
3577
3578 // If "**" is by itself, this is the first time we encounter it and more
3579 // is following then find matches without any directory.
3580 if (!didstar && stardepth < 100 && starstar && e - s == 2
3581 && *path_end == '/')
3582 {
3583 STRCPY(s, path_end + 1);
3584 ++stardepth;
3585 (void)dos_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
3586 --stardepth;
3587 }
3588
3589 // Scan all files in the directory with "dir/ *.*"
3590 STRCPY(s, "*.*");
3591 wn = enc_to_utf16(buf, NULL);
3592 if (wn != NULL)
3593 hFind = FindFirstFileW(wn, &wfb);
3594 ok = (hFind != INVALID_HANDLE_VALUE);
3595
3596 while (ok)
3597 {
3598 p = utf16_to_enc(wfb.cFileName, NULL); // p is allocated here
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003599
Bram Moolenaar26262f82019-09-04 20:59:15 +02003600 if (p == NULL)
3601 break; // out of memory
3602
Bram Moolenaar0dc5f602021-02-07 14:01:35 +01003603 // Do not use the alternate filename when the file name ends in '~',
3604 // because it picks up backup files: short name for "foo.vim~" is
3605 // "foo~1.vim", which matches "*.vim".
3606 if (*wfb.cAlternateFileName == NUL || p[STRLEN(p) - 1] == '~')
Bram Moolenaar40655d52020-04-06 23:49:50 +02003607 p_alt = NULL;
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003608 else
3609 p_alt = utf16_to_enc(wfb.cAlternateFileName, NULL);
3610
Bram Moolenaar26262f82019-09-04 20:59:15 +02003611 // Ignore entries starting with a dot, unless when asked for. Accept
3612 // all entries found with "matchname".
3613 if ((p[0] != '.' || starts_with_dot
3614 || ((flags & EW_DODOT)
3615 && p[1] != NUL && (p[1] != '.' || p[2] != NUL)))
3616 && (matchname == NULL
3617 || (regmatch.regprog != NULL
Bram Moolenaar40655d52020-04-06 23:49:50 +02003618 && (vim_regexec(&regmatch, p, (colnr_T)0)
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003619 || (p_alt != NULL
Bram Moolenaar40655d52020-04-06 23:49:50 +02003620 && vim_regexec(&regmatch, p_alt, (colnr_T)0))))
Bram Moolenaar26262f82019-09-04 20:59:15 +02003621 || ((flags & EW_NOTWILD)
3622 && fnamencmp(path + (s - buf), p, e - s) == 0)))
3623 {
3624 STRCPY(s, p);
3625 len = (int)STRLEN(buf);
3626
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003627 if (starstar && stardepth < 100
3628 && (wfb.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
Bram Moolenaar26262f82019-09-04 20:59:15 +02003629 {
3630 // For "**" in the pattern first go deeper in the tree to
3631 // find matches.
3632 STRCPY(buf + len, "/**");
3633 STRCPY(buf + len + 3, path_end);
3634 ++stardepth;
3635 (void)dos_expandpath(gap, buf, len + 1, flags, TRUE);
3636 --stardepth;
3637 }
3638
3639 STRCPY(buf + len, path_end);
3640 if (mch_has_exp_wildcard(path_end))
3641 {
3642 // need to expand another component of the path
3643 // remove backslashes for the remaining components only
3644 (void)dos_expandpath(gap, buf, len + 1, flags, FALSE);
3645 }
3646 else
3647 {
LemonBoy23c5ebe2024-06-18 20:43:51 +02003648 stat_T sb;
3649
Bram Moolenaar26262f82019-09-04 20:59:15 +02003650 // no more wildcards, check if there is a match
3651 // remove backslashes for the remaining components only
3652 if (*path_end != 0)
3653 backslash_halve(buf + len + 1);
LemonBoy23c5ebe2024-06-18 20:43:51 +02003654 // add existing file
3655 if ((flags & EW_ALLLINKS) ? mch_lstat((char *)buf, &sb) >= 0
3656 : mch_getperm(buf) >= 0)
Bram Moolenaar26262f82019-09-04 20:59:15 +02003657 addfile(gap, buf, flags);
3658 }
3659 }
3660
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003661 vim_free(p_alt);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003662 vim_free(p);
3663 ok = FindNextFileW(hFind, &wfb);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003664 }
3665
3666 FindClose(hFind);
3667 vim_free(wn);
3668 vim_free(buf);
3669 vim_regfree(regmatch.regprog);
3670 vim_free(matchname);
3671
3672 matches = gap->ga_len - start_len;
3673 if (matches > 0)
3674 qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
3675 sizeof(char_u *), pstrcmp);
3676 return matches;
3677}
3678
3679 int
3680mch_expandpath(
3681 garray_T *gap,
3682 char_u *path,
3683 int flags) // EW_* flags
3684{
3685 return dos_expandpath(gap, path, 0, flags, FALSE);
3686}
3687#endif // MSWIN
3688
3689#if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \
3690 || defined(PROTO)
3691/*
3692 * Unix style wildcard expansion code.
3693 * It's here because it's used both for Unix and Mac.
3694 */
3695 static int
3696pstrcmp(const void *a, const void *b)
3697{
3698 return (pathcmp(*(char **)a, *(char **)b, -1));
3699}
3700
3701/*
3702 * Recursively expand one path component into all matching files and/or
3703 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
3704 * "path" has backslashes before chars that are not to be expanded, starting
3705 * at "path + wildoff".
3706 * Return the number of matches found.
3707 * NOTE: much of this is identical to dos_expandpath(), keep in sync!
3708 */
3709 int
3710unix_expandpath(
3711 garray_T *gap,
3712 char_u *path,
3713 int wildoff,
3714 int flags, // EW_* flags
3715 int didstar) // expanded "**" once already
3716{
3717 char_u *buf;
3718 char_u *path_end;
3719 char_u *p, *s, *e;
3720 int start_len = gap->ga_len;
3721 char_u *pat;
3722 regmatch_T regmatch;
3723 int starts_with_dot;
3724 int matches;
3725 int len;
3726 int starstar = FALSE;
3727 static int stardepth = 0; // depth for "**" expansion
3728
3729 DIR *dirp;
3730 struct dirent *dp;
3731
3732 // Expanding "**" may take a long time, check for CTRL-C.
3733 if (stardepth > 0)
3734 {
3735 ui_breakcheck();
3736 if (got_int)
3737 return 0;
3738 }
3739
Yee Cheng China7767072023-04-16 20:13:12 +01003740 // make room for file name (a bit too much to stay on the safe side)
3741 size_t buflen = STRLEN(path) + MAXPATHL;
Bram Moolenaar386c24c2022-05-16 12:37:36 +01003742 buf = alloc(buflen);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003743 if (buf == NULL)
3744 return 0;
3745
3746 /*
3747 * Find the first part in the path name that contains a wildcard.
3748 * When EW_ICASE is set every letter is considered to be a wildcard.
3749 * Copy it into "buf", including the preceding characters.
3750 */
3751 p = buf;
3752 s = buf;
3753 e = NULL;
3754 path_end = path;
3755 while (*path_end != NUL)
3756 {
3757 // May ignore a wildcard that has a backslash before it; it will
3758 // be removed by rem_backslash() or file_pat_to_reg_pat() below.
3759 if (path_end >= path + wildoff && rem_backslash(path_end))
3760 *p++ = *path_end++;
3761 else if (*path_end == '/')
3762 {
3763 if (e != NULL)
3764 break;
3765 s = p + 1;
3766 }
3767 else if (path_end >= path + wildoff
3768 && (vim_strchr((char_u *)"*?[{~$", *path_end) != NULL
3769 || (!p_fic && (flags & EW_ICASE)
Bram Moolenaar5921aeb2022-02-19 11:20:12 +00003770 && vim_isalpha(PTR2CHAR(path_end)))))
Bram Moolenaar26262f82019-09-04 20:59:15 +02003771 e = p;
3772 if (has_mbyte)
3773 {
3774 len = (*mb_ptr2len)(path_end);
3775 STRNCPY(p, path_end, len);
3776 p += len;
3777 path_end += len;
3778 }
3779 else
3780 *p++ = *path_end++;
3781 }
3782 e = p;
3783 *e = NUL;
3784
3785 // Now we have one wildcard component between "s" and "e".
3786 // Remove backslashes between "wildoff" and the start of the wildcard
3787 // component.
3788 for (p = buf + wildoff; p < s; ++p)
3789 if (rem_backslash(p))
3790 {
3791 STRMOVE(p, p + 1);
3792 --e;
3793 --s;
3794 }
3795
3796 // Check for "**" between "s" and "e".
3797 for (p = s; p < e; ++p)
3798 if (p[0] == '*' && p[1] == '*')
3799 starstar = TRUE;
3800
3801 // convert the file pattern to a regexp pattern
3802 starts_with_dot = *s == '.';
3803 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
3804 if (pat == NULL)
3805 {
3806 vim_free(buf);
3807 return 0;
3808 }
3809
3810 // compile the regexp into a program
3811 if (flags & EW_ICASE)
3812 regmatch.rm_ic = TRUE; // 'wildignorecase' set
3813 else
3814 regmatch.rm_ic = p_fic; // ignore case when 'fileignorecase' is set
3815 if (flags & (EW_NOERROR | EW_NOTWILD))
3816 ++emsg_silent;
3817 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
3818 if (flags & (EW_NOERROR | EW_NOTWILD))
3819 --emsg_silent;
3820 vim_free(pat);
3821
3822 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
3823 {
3824 vim_free(buf);
3825 return 0;
3826 }
3827
3828 // If "**" is by itself, this is the first time we encounter it and more
3829 // is following then find matches without any directory.
3830 if (!didstar && stardepth < 100 && starstar && e - s == 2
3831 && *path_end == '/')
3832 {
3833 STRCPY(s, path_end + 1);
3834 ++stardepth;
3835 (void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
3836 --stardepth;
3837 }
3838
3839 // open the directory for scanning
3840 *s = NUL;
3841 dirp = opendir(*buf == NUL ? "." : (char *)buf);
3842
3843 // Find all matching entries
3844 if (dirp != NULL)
3845 {
Bram Moolenaar57e95172022-08-20 19:26:14 +01003846 while (!got_int)
Bram Moolenaar26262f82019-09-04 20:59:15 +02003847 {
3848 dp = readdir(dirp);
3849 if (dp == NULL)
3850 break;
3851 if ((dp->d_name[0] != '.' || starts_with_dot
3852 || ((flags & EW_DODOT)
3853 && dp->d_name[1] != NUL
3854 && (dp->d_name[1] != '.' || dp->d_name[2] != NUL)))
3855 && ((regmatch.regprog != NULL && vim_regexec(&regmatch,
3856 (char_u *)dp->d_name, (colnr_T)0))
3857 || ((flags & EW_NOTWILD)
3858 && fnamencmp(path + (s - buf), dp->d_name, e - s) == 0)))
3859 {
Yee Cheng China7767072023-04-16 20:13:12 +01003860 vim_strncpy(s, (char_u *)dp->d_name, buflen - (s - buf) - 1);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003861 len = STRLEN(buf);
3862
3863 if (starstar && stardepth < 100)
3864 {
3865 // For "**" in the pattern first go deeper in the tree to
3866 // find matches.
Bram Moolenaar386c24c2022-05-16 12:37:36 +01003867 vim_snprintf((char *)buf + len, buflen - len,
3868 "/**%s", path_end);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003869 ++stardepth;
3870 (void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
3871 --stardepth;
3872 }
3873
Bram Moolenaar386c24c2022-05-16 12:37:36 +01003874 vim_snprintf((char *)buf + len, buflen - len, "%s", path_end);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003875 if (mch_has_exp_wildcard(path_end)) // handle more wildcards
3876 {
3877 // need to expand another component of the path
3878 // remove backslashes for the remaining components only
3879 (void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
3880 }
3881 else
3882 {
3883 stat_T sb;
3884
3885 // no more wildcards, check if there is a match
3886 // remove backslashes for the remaining components only
3887 if (*path_end != NUL)
3888 backslash_halve(buf + len + 1);
3889 // add existing file or symbolic link
3890 if ((flags & EW_ALLLINKS) ? mch_lstat((char *)buf, &sb) >= 0
3891 : mch_getperm(buf) >= 0)
3892 {
3893#ifdef MACOS_CONVERT
3894 size_t precomp_len = STRLEN(buf)+1;
3895 char_u *precomp_buf =
3896 mac_precompose_path(buf, precomp_len, &precomp_len);
3897
3898 if (precomp_buf)
3899 {
3900 mch_memmove(buf, precomp_buf, precomp_len);
3901 vim_free(precomp_buf);
3902 }
3903#endif
3904 addfile(gap, buf, flags);
3905 }
3906 }
3907 }
3908 }
3909
3910 closedir(dirp);
3911 }
3912
3913 vim_free(buf);
3914 vim_regfree(regmatch.regprog);
3915
Bram Moolenaar57e95172022-08-20 19:26:14 +01003916 // When interrupted the matches probably won't be used and sorting can be
3917 // slow, thus skip it.
Bram Moolenaar26262f82019-09-04 20:59:15 +02003918 matches = gap->ga_len - start_len;
Bram Moolenaar57e95172022-08-20 19:26:14 +01003919 if (matches > 0 && !got_int)
Bram Moolenaar26262f82019-09-04 20:59:15 +02003920 qsort(((char_u **)gap->ga_data) + start_len, matches,
3921 sizeof(char_u *), pstrcmp);
3922 return matches;
3923}
3924#endif
3925
3926/*
3927 * Return TRUE if "p" contains what looks like an environment variable.
3928 * Allowing for escaping.
3929 */
3930 static int
3931has_env_var(char_u *p)
3932{
3933 for ( ; *p; MB_PTR_ADV(p))
3934 {
3935 if (*p == '\\' && p[1] != NUL)
3936 ++p;
3937 else if (vim_strchr((char_u *)
3938#if defined(MSWIN)
3939 "$%"
3940#else
3941 "$"
3942#endif
3943 , *p) != NULL)
3944 return TRUE;
3945 }
3946 return FALSE;
3947}
3948
3949#ifdef SPECIAL_WILDCHAR
3950/*
3951 * Return TRUE if "p" contains a special wildcard character, one that Vim
3952 * cannot expand, requires using a shell.
3953 */
3954 static int
3955has_special_wildchar(char_u *p)
3956{
3957 for ( ; *p; MB_PTR_ADV(p))
3958 {
3959 // Disallow line break characters.
3960 if (*p == '\r' || *p == '\n')
3961 break;
3962 // Allow for escaping.
3963 if (*p == '\\' && p[1] != NUL && p[1] != '\r' && p[1] != '\n')
3964 ++p;
3965 else if (vim_strchr((char_u *)SPECIAL_WILDCHAR, *p) != NULL)
3966 {
3967 // A { must be followed by a matching }.
3968 if (*p == '{' && vim_strchr(p, '}') == NULL)
3969 continue;
3970 // A quote and backtick must be followed by another one.
3971 if ((*p == '`' || *p == '\'') && vim_strchr(p, *p) == NULL)
3972 continue;
3973 return TRUE;
3974 }
3975 }
3976 return FALSE;
3977}
3978#endif
3979
3980/*
3981 * Generic wildcard expansion code.
3982 *
3983 * Characters in "pat" that should not be expanded must be preceded with a
3984 * backslash. E.g., "/path\ with\ spaces/my\*star*"
3985 *
3986 * Return FAIL when no single file was found. In this case "num_file" is not
3987 * set, and "file" may contain an error message.
3988 * Return OK when some files found. "num_file" is set to the number of
3989 * matches, "file" to the array of matches. Call FreeWild() later.
3990 */
3991 int
3992gen_expand_wildcards(
3993 int num_pat, // number of input patterns
3994 char_u **pat, // array of input patterns
3995 int *num_file, // resulting number of files
3996 char_u ***file, // array of resulting files
3997 int flags) // EW_* flags
3998{
3999 int i;
4000 garray_T ga;
4001 char_u *p;
4002 static int recursive = FALSE;
4003 int add_pat;
4004 int retval = OK;
Bram Moolenaar26262f82019-09-04 20:59:15 +02004005 int did_expand_in_path = FALSE;
Bram Moolenaar26262f82019-09-04 20:59:15 +02004006
4007 /*
4008 * expand_env() is called to expand things like "~user". If this fails,
4009 * it calls ExpandOne(), which brings us back here. In this case, always
4010 * call the machine specific expansion function, if possible. Otherwise,
4011 * return FAIL.
4012 */
4013 if (recursive)
4014#ifdef SPECIAL_WILDCHAR
4015 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
4016#else
4017 return FAIL;
4018#endif
4019
4020#ifdef SPECIAL_WILDCHAR
4021 /*
4022 * If there are any special wildcard characters which we cannot handle
4023 * here, call machine specific function for all the expansion. This
4024 * avoids starting the shell for each argument separately.
4025 * For `=expr` do use the internal function.
4026 */
4027 for (i = 0; i < num_pat; i++)
4028 {
4029 if (has_special_wildchar(pat[i])
4030# ifdef VIM_BACKTICK
4031 && !(vim_backtick(pat[i]) && pat[i][1] == '=')
4032# endif
4033 )
4034 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
4035 }
4036#endif
4037
4038 recursive = TRUE;
4039
4040 /*
4041 * The matching file names are stored in a growarray. Init it empty.
4042 */
Bram Moolenaar04935fb2022-01-08 16:19:22 +00004043 ga_init2(&ga, sizeof(char_u *), 30);
Bram Moolenaar26262f82019-09-04 20:59:15 +02004044
Bram Moolenaar57e95172022-08-20 19:26:14 +01004045 for (i = 0; i < num_pat && !got_int; ++i)
Bram Moolenaar26262f82019-09-04 20:59:15 +02004046 {
4047 add_pat = -1;
4048 p = pat[i];
4049
4050#ifdef VIM_BACKTICK
4051 if (vim_backtick(p))
4052 {
4053 add_pat = expand_backtick(&ga, p, flags);
4054 if (add_pat == -1)
4055 retval = FAIL;
4056 }
4057 else
4058#endif
4059 {
4060 /*
4061 * First expand environment variables, "~/" and "~user/".
4062 */
4063 if ((has_env_var(p) && !(flags & EW_NOTENV)) || *p == '~')
4064 {
4065 p = expand_env_save_opt(p, TRUE);
4066 if (p == NULL)
4067 p = pat[i];
4068#ifdef UNIX
4069 /*
4070 * On Unix, if expand_env() can't expand an environment
4071 * variable, use the shell to do that. Discard previously
4072 * found file names and start all over again.
4073 */
4074 else if (has_env_var(p) || *p == '~')
4075 {
4076 vim_free(p);
4077 ga_clear_strings(&ga);
4078 i = mch_expand_wildcards(num_pat, pat, num_file, file,
4079 flags|EW_KEEPDOLLAR);
4080 recursive = FALSE;
4081 return i;
4082 }
4083#endif
4084 }
4085
4086 /*
LemonBoya3157a42022-04-03 11:58:31 +01004087 * If there are wildcards or case-insensitive expansion is
4088 * required: Expand file names and add each match to the list. If
4089 * there is no match, and EW_NOTFOUND is given, add the pattern.
4090 * Otherwise: Add the file name if it exists or when EW_NOTFOUND is
4091 * given.
Bram Moolenaar26262f82019-09-04 20:59:15 +02004092 */
LemonBoya3157a42022-04-03 11:58:31 +01004093 if (mch_has_exp_wildcard(p) || (flags & EW_ICASE))
Bram Moolenaar26262f82019-09-04 20:59:15 +02004094 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02004095 if ((flags & EW_PATH)
4096 && !mch_isFullName(p)
4097 && !(p[0] == '.'
4098 && (vim_ispathsep(p[1])
4099 || (p[1] == '.' && vim_ispathsep(p[2]))))
4100 )
4101 {
4102 // :find completion where 'path' is used.
4103 // Recursiveness is OK here.
4104 recursive = FALSE;
4105 add_pat = expand_in_path(&ga, p, flags);
4106 recursive = TRUE;
4107 did_expand_in_path = TRUE;
4108 }
4109 else
Bram Moolenaar26262f82019-09-04 20:59:15 +02004110 add_pat = mch_expandpath(&ga, p, flags);
4111 }
4112 }
4113
4114 if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
4115 {
4116 char_u *t = backslash_halve_save(p);
4117
4118 // When EW_NOTFOUND is used, always add files and dirs. Makes
4119 // "vim c:/" work.
4120 if (flags & EW_NOTFOUND)
4121 addfile(&ga, t, flags | EW_DIR | EW_FILE);
4122 else
4123 addfile(&ga, t, flags);
4124
4125 if (t != p)
4126 vim_free(t);
4127 }
4128
Bram Moolenaar26262f82019-09-04 20:59:15 +02004129 if (did_expand_in_path && ga.ga_len > 0 && (flags & EW_PATH))
4130 uniquefy_paths(&ga, p);
Bram Moolenaar26262f82019-09-04 20:59:15 +02004131 if (p != pat[i])
4132 vim_free(p);
4133 }
4134
Bram Moolenaar566cc8c2020-06-29 21:14:51 +02004135 // When returning FAIL the array must be freed here.
4136 if (retval == FAIL)
Yegappan Lakshmanan2b74b682022-04-03 21:30:32 +01004137 ga_clear_strings(&ga);
Bram Moolenaar566cc8c2020-06-29 21:14:51 +02004138
Bram Moolenaar26262f82019-09-04 20:59:15 +02004139 *num_file = ga.ga_len;
Bram Moolenaar566cc8c2020-06-29 21:14:51 +02004140 *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data
4141 : (char_u **)_("no matches");
Bram Moolenaar26262f82019-09-04 20:59:15 +02004142
4143 recursive = FALSE;
4144
4145 return ((flags & EW_EMPTYOK) || ga.ga_data != NULL) ? retval : FAIL;
4146}
4147
4148/*
4149 * Add a file to a file list. Accepted flags:
4150 * EW_DIR add directories
4151 * EW_FILE add files
4152 * EW_EXEC add executable files
4153 * EW_NOTFOUND add even when it doesn't exist
4154 * EW_ADDSLASH add slash after directory name
4155 * EW_ALLLINKS add symlink also when the referred file does not exist
4156 */
4157 void
4158addfile(
4159 garray_T *gap,
Bram Moolenaar217e1b82019-12-01 21:41:28 +01004160 char_u *f, // filename
Bram Moolenaar26262f82019-09-04 20:59:15 +02004161 int flags)
4162{
4163 char_u *p;
4164 int isdir;
4165 stat_T sb;
4166
4167 // if the file/dir/link doesn't exist, may not add it
4168 if (!(flags & EW_NOTFOUND) && ((flags & EW_ALLLINKS)
4169 ? mch_lstat((char *)f, &sb) < 0 : mch_getperm(f) < 0))
4170 return;
4171
4172#ifdef FNAME_ILLEGAL
4173 // if the file/dir contains illegal characters, don't add it
4174 if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
4175 return;
4176#endif
4177
4178 isdir = mch_isdir(f);
4179 if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
4180 return;
4181
4182 // If the file isn't executable, may not add it. Do accept directories.
4183 // When invoked from expand_shellcmd() do not use $PATH.
4184 if (!isdir && (flags & EW_EXEC)
4185 && !mch_can_exe(f, NULL, !(flags & EW_SHELLCMD)))
4186 return;
4187
4188 // Make room for another item in the file list.
4189 if (ga_grow(gap, 1) == FAIL)
4190 return;
4191
4192 p = alloc(STRLEN(f) + 1 + isdir);
4193 if (p == NULL)
4194 return;
4195
4196 STRCPY(p, f);
4197#ifdef BACKSLASH_IN_FILENAME
4198 slash_adjust(p);
4199#endif
4200 /*
4201 * Append a slash or backslash after directory names if none is present.
4202 */
Bram Moolenaar26262f82019-09-04 20:59:15 +02004203 if (isdir && (flags & EW_ADDSLASH))
4204 add_pathsep(p);
Bram Moolenaar26262f82019-09-04 20:59:15 +02004205 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
4206}
4207
4208/*
4209 * Free the list of files returned by expand_wildcards() or other expansion
4210 * functions.
4211 */
4212 void
4213FreeWild(int count, char_u **files)
4214{
4215 if (count <= 0 || files == NULL)
4216 return;
4217 while (count--)
4218 vim_free(files[count]);
4219 vim_free(files);
4220}
4221
4222/*
4223 * Compare path "p[]" to "q[]".
4224 * If "maxlen" >= 0 compare "p[maxlen]" to "q[maxlen]"
4225 * Return value like strcmp(p, q), but consider path separators.
4226 */
4227 int
4228pathcmp(const char *p, const char *q, int maxlen)
4229{
4230 int i, j;
4231 int c1, c2;
4232 const char *s = NULL;
4233
4234 for (i = 0, j = 0; maxlen < 0 || (i < maxlen && j < maxlen);)
4235 {
4236 c1 = PTR2CHAR((char_u *)p + i);
4237 c2 = PTR2CHAR((char_u *)q + j);
4238
4239 // End of "p": check if "q" also ends or just has a slash.
4240 if (c1 == NUL)
4241 {
4242 if (c2 == NUL) // full match
4243 return 0;
4244 s = q;
4245 i = j;
4246 break;
4247 }
4248
4249 // End of "q": check if "p" just has a slash.
4250 if (c2 == NUL)
4251 {
4252 s = p;
4253 break;
4254 }
4255
4256 if ((p_fic ? MB_TOUPPER(c1) != MB_TOUPPER(c2) : c1 != c2)
4257#ifdef BACKSLASH_IN_FILENAME
4258 // consider '/' and '\\' to be equal
4259 && !((c1 == '/' && c2 == '\\')
4260 || (c1 == '\\' && c2 == '/'))
4261#endif
4262 )
4263 {
4264 if (vim_ispathsep(c1))
4265 return -1;
4266 if (vim_ispathsep(c2))
4267 return 1;
4268 return p_fic ? MB_TOUPPER(c1) - MB_TOUPPER(c2)
4269 : c1 - c2; // no match
4270 }
4271
Bram Moolenaar1614a142019-10-06 22:00:13 +02004272 i += mb_ptr2len((char_u *)p + i);
4273 j += mb_ptr2len((char_u *)q + j);
Bram Moolenaar26262f82019-09-04 20:59:15 +02004274 }
4275 if (s == NULL) // "i" or "j" ran into "maxlen"
4276 return 0;
4277
4278 c1 = PTR2CHAR((char_u *)s + i);
Bram Moolenaar1614a142019-10-06 22:00:13 +02004279 c2 = PTR2CHAR((char_u *)s + i + mb_ptr2len((char_u *)s + i));
Bram Moolenaar26262f82019-09-04 20:59:15 +02004280 // ignore a trailing slash, but not "//" or ":/"
4281 if (c2 == NUL
4282 && i > 0
4283 && !after_pathsep((char_u *)s, (char_u *)s + i)
4284#ifdef BACKSLASH_IN_FILENAME
4285 && (c1 == '/' || c1 == '\\')
4286#else
4287 && c1 == '/'
4288#endif
4289 )
4290 return 0; // match with trailing slash
4291 if (s == q)
4292 return -1; // no match
4293 return 1;
4294}
4295
4296/*
4297 * Return TRUE if "name" is a full (absolute) path name or URL.
4298 */
4299 int
4300vim_isAbsName(char_u *name)
4301{
4302 return (path_with_url(name) != 0 || mch_isFullName(name));
4303}
4304
4305/*
4306 * Get absolute file name into buffer "buf[len]".
4307 *
4308 * return FAIL for failure, OK otherwise
4309 */
4310 int
4311vim_FullName(
4312 char_u *fname,
4313 char_u *buf,
4314 int len,
4315 int force) // force expansion even when already absolute
4316{
4317 int retval = OK;
4318 int url;
4319
4320 *buf = NUL;
4321 if (fname == NULL)
4322 return FAIL;
4323
4324 url = path_with_url(fname);
4325 if (!url)
4326 retval = mch_FullName(fname, buf, len, force);
4327 if (url || retval == FAIL)
4328 {
4329 // something failed; use the file name (truncate when too long)
4330 vim_strncpy(buf, fname, len - 1);
4331 }
4332#if defined(MSWIN)
4333 slash_adjust(buf);
4334#endif
4335 return retval;
4336}