blob: cbf2da41360bd781b4a7b7fbf074fa136c197323 [file] [log] [blame]
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001/* vi:set ts=8 sts=4 sw=4 noet:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
Bram Moolenaar9810cfb2019-12-11 21:23:00 +010011 * filepath.c: dealing with file names and paths.
Bram Moolenaarb005cd82019-09-04 15:54:55 +020012 */
13
14#include "vim.h"
15
16#ifdef MSWIN
17/*
18 * Functions for ":8" filename modifier: get 8.3 version of a filename.
19 */
20
21/*
22 * Get the short path (8.3) for the filename in "fnamep".
23 * Only works for a valid file name.
24 * When the path gets longer "fnamep" is changed and the allocated buffer
25 * is put in "bufp".
26 * *fnamelen is the length of "fnamep" and set to 0 for a nonexistent path.
27 * Returns OK on success, FAIL on failure.
28 */
29 static int
30get_short_pathname(char_u **fnamep, char_u **bufp, int *fnamelen)
31{
32 int l, len;
Bram Moolenaar3f396972019-10-30 04:10:06 +010033 WCHAR *newbuf;
34 WCHAR *wfname;
Bram Moolenaarb005cd82019-09-04 15:54:55 +020035
Bram Moolenaar3f396972019-10-30 04:10:06 +010036 len = MAXPATHL;
37 newbuf = malloc(len * sizeof(*newbuf));
38 if (newbuf == NULL)
39 return FAIL;
40
41 wfname = enc_to_utf16(*fnamep, NULL);
42 if (wfname == NULL)
43 {
44 vim_free(newbuf);
45 return FAIL;
46 }
47
48 l = GetShortPathNameW(wfname, newbuf, len);
Bram Moolenaarb005cd82019-09-04 15:54:55 +020049 if (l > len - 1)
50 {
Bram Moolenaar26262f82019-09-04 20:59:15 +020051 // If that doesn't work (not enough space), then save the string
52 // and try again with a new buffer big enough.
Bram Moolenaar3f396972019-10-30 04:10:06 +010053 WCHAR *newbuf_t = newbuf;
54 newbuf = vim_realloc(newbuf, (l + 1) * sizeof(*newbuf));
Bram Moolenaarb005cd82019-09-04 15:54:55 +020055 if (newbuf == NULL)
Bram Moolenaar3f396972019-10-30 04:10:06 +010056 {
57 vim_free(wfname);
58 vim_free(newbuf_t);
Bram Moolenaarb005cd82019-09-04 15:54:55 +020059 return FAIL;
Bram Moolenaar3f396972019-10-30 04:10:06 +010060 }
Bram Moolenaar26262f82019-09-04 20:59:15 +020061 // Really should always succeed, as the buffer is big enough.
Bram Moolenaar3f396972019-10-30 04:10:06 +010062 l = GetShortPathNameW(wfname, newbuf, l+1);
Bram Moolenaarb005cd82019-09-04 15:54:55 +020063 }
Bram Moolenaar3f396972019-10-30 04:10:06 +010064 if (l != 0)
65 {
66 char_u *p = utf16_to_enc(newbuf, NULL);
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +020067
Bram Moolenaar3f396972019-10-30 04:10:06 +010068 if (p != NULL)
69 {
70 vim_free(*bufp);
71 *fnamep = *bufp = p;
72 }
73 else
74 {
75 vim_free(wfname);
76 vim_free(newbuf);
77 return FAIL;
78 }
79 }
80 vim_free(wfname);
81 vim_free(newbuf);
Bram Moolenaarb005cd82019-09-04 15:54:55 +020082
Bram Moolenaar2ade7142019-11-04 20:36:50 +010083 *fnamelen = l == 0 ? l : (int)STRLEN(*bufp);
Bram Moolenaarb005cd82019-09-04 15:54:55 +020084 return OK;
85}
86
87/*
88 * Get the short path (8.3) for the filename in "fname". The converted
89 * path is returned in "bufp".
90 *
91 * Some of the directories specified in "fname" may not exist. This function
92 * will shorten the existing directories at the beginning of the path and then
93 * append the remaining non-existing path.
94 *
95 * fname - Pointer to the filename to shorten. On return, contains the
96 * pointer to the shortened pathname
97 * bufp - Pointer to an allocated buffer for the filename.
98 * fnamelen - Length of the filename pointed to by fname
99 *
100 * Returns OK on success (or nothing done) and FAIL on failure (out of memory).
101 */
102 static int
103shortpath_for_invalid_fname(
104 char_u **fname,
105 char_u **bufp,
106 int *fnamelen)
107{
108 char_u *short_fname, *save_fname, *pbuf_unused;
109 char_u *endp, *save_endp;
110 char_u ch;
111 int old_len, len;
112 int new_len, sfx_len;
113 int retval = OK;
114
Bram Moolenaar26262f82019-09-04 20:59:15 +0200115 // Make a copy
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200116 old_len = *fnamelen;
117 save_fname = vim_strnsave(*fname, old_len);
118 pbuf_unused = NULL;
119 short_fname = NULL;
120
Bram Moolenaar26262f82019-09-04 20:59:15 +0200121 endp = save_fname + old_len - 1; // Find the end of the copy
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200122 save_endp = endp;
123
124 /*
125 * Try shortening the supplied path till it succeeds by removing one
126 * directory at a time from the tail of the path.
127 */
128 len = 0;
129 for (;;)
130 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200131 // go back one path-separator
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200132 while (endp > save_fname && !after_pathsep(save_fname, endp + 1))
133 --endp;
134 if (endp <= save_fname)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200135 break; // processed the complete path
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200136
137 /*
138 * Replace the path separator with a NUL and try to shorten the
139 * resulting path.
140 */
141 ch = *endp;
142 *endp = 0;
143 short_fname = save_fname;
144 len = (int)STRLEN(short_fname) + 1;
145 if (get_short_pathname(&short_fname, &pbuf_unused, &len) == FAIL)
146 {
147 retval = FAIL;
148 goto theend;
149 }
Bram Moolenaar26262f82019-09-04 20:59:15 +0200150 *endp = ch; // preserve the string
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200151
152 if (len > 0)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200153 break; // successfully shortened the path
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200154
Bram Moolenaar26262f82019-09-04 20:59:15 +0200155 // failed to shorten the path. Skip the path separator
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200156 --endp;
157 }
158
159 if (len > 0)
160 {
161 /*
162 * Succeeded in shortening the path. Now concatenate the shortened
163 * path with the remaining path at the tail.
164 */
165
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100166 // Compute the length of the new path.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200167 sfx_len = (int)(save_endp - endp) + 1;
168 new_len = len + sfx_len;
169
170 *fnamelen = new_len;
171 vim_free(*bufp);
172 if (new_len > old_len)
173 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200174 // There is not enough space in the currently allocated string,
175 // copy it to a buffer big enough.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200176 *fname = *bufp = vim_strnsave(short_fname, new_len);
177 if (*fname == NULL)
178 {
179 retval = FAIL;
180 goto theend;
181 }
182 }
183 else
184 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200185 // Transfer short_fname to the main buffer (it's big enough),
186 // unless get_short_pathname() did its work in-place.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200187 *fname = *bufp = save_fname;
188 if (short_fname != save_fname)
Christian Brabandt81da16b2022-03-10 12:24:02 +0000189 STRNCPY(save_fname, short_fname, len);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200190 save_fname = NULL;
191 }
192
Bram Moolenaar26262f82019-09-04 20:59:15 +0200193 // concat the not-shortened part of the path
Yegappan Lakshmanana34b4462022-06-11 10:43:26 +0100194 if ((*fname + len) != endp)
195 vim_strncpy(*fname + len, endp, sfx_len);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200196 (*fname)[new_len] = NUL;
197 }
198
199theend:
200 vim_free(pbuf_unused);
201 vim_free(save_fname);
202
203 return retval;
204}
205
206/*
207 * Get a pathname for a partial path.
208 * Returns OK for success, FAIL for failure.
209 */
210 static int
211shortpath_for_partial(
212 char_u **fnamep,
213 char_u **bufp,
214 int *fnamelen)
215{
216 int sepcount, len, tflen;
217 char_u *p;
218 char_u *pbuf, *tfname;
219 int hasTilde;
220
Bram Moolenaar26262f82019-09-04 20:59:15 +0200221 // Count up the path separators from the RHS.. so we know which part
222 // of the path to return.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200223 sepcount = 0;
224 for (p = *fnamep; p < *fnamep + *fnamelen; MB_PTR_ADV(p))
225 if (vim_ispathsep(*p))
226 ++sepcount;
227
Bram Moolenaar26262f82019-09-04 20:59:15 +0200228 // Need full path first (use expand_env() to remove a "~/")
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200229 hasTilde = (**fnamep == '~');
230 if (hasTilde)
231 pbuf = tfname = expand_env_save(*fnamep);
232 else
233 pbuf = tfname = FullName_save(*fnamep, FALSE);
234
235 len = tflen = (int)STRLEN(tfname);
236
237 if (get_short_pathname(&tfname, &pbuf, &len) == FAIL)
238 return FAIL;
239
240 if (len == 0)
241 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200242 // Don't have a valid filename, so shorten the rest of the
243 // path if we can. This CAN give us invalid 8.3 filenames, but
244 // there's not a lot of point in guessing what it might be.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200245 len = tflen;
246 if (shortpath_for_invalid_fname(&tfname, &pbuf, &len) == FAIL)
247 return FAIL;
248 }
249
Bram Moolenaar26262f82019-09-04 20:59:15 +0200250 // Count the paths backward to find the beginning of the desired string.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200251 for (p = tfname + len - 1; p >= tfname; --p)
252 {
253 if (has_mbyte)
254 p -= mb_head_off(tfname, p);
255 if (vim_ispathsep(*p))
256 {
257 if (sepcount == 0 || (hasTilde && sepcount == 1))
258 break;
259 else
260 sepcount --;
261 }
262 }
263 if (hasTilde)
264 {
265 --p;
266 if (p >= tfname)
267 *p = '~';
268 else
269 return FAIL;
270 }
271 else
272 ++p;
273
Bram Moolenaar26262f82019-09-04 20:59:15 +0200274 // Copy in the string - p indexes into tfname - allocated at pbuf
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200275 vim_free(*bufp);
276 *fnamelen = (int)STRLEN(p);
277 *bufp = pbuf;
278 *fnamep = p;
279
280 return OK;
281}
282#endif // MSWIN
283
284/*
285 * Adjust a filename, according to a string of modifiers.
286 * *fnamep must be NUL terminated when called. When returning, the length is
287 * determined by *fnamelen.
288 * Returns VALID_ flags or -1 for failure.
289 * When there is an error, *fnamep is set to NULL.
290 */
291 int
292modify_fname(
293 char_u *src, // string with modifiers
294 int tilde_file, // "~" is a file name, not $HOME
295 int *usedlen, // characters after src that are used
296 char_u **fnamep, // file name so far
297 char_u **bufp, // buffer for allocated file name or NULL
298 int *fnamelen) // length of fnamep
299{
300 int valid = 0;
301 char_u *tail;
302 char_u *s, *p, *pbuf;
303 char_u dirname[MAXPATHL];
304 int c;
305 int has_fullname = 0;
Bram Moolenaard816cd92020-02-04 22:23:09 +0100306 int has_homerelative = 0;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200307#ifdef MSWIN
308 char_u *fname_start = *fnamep;
309 int has_shortname = 0;
310#endif
311
312repeat:
Bram Moolenaar26262f82019-09-04 20:59:15 +0200313 // ":p" - full path/file_name
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200314 if (src[*usedlen] == ':' && src[*usedlen + 1] == 'p')
315 {
316 has_fullname = 1;
317
318 valid |= VALID_PATH;
319 *usedlen += 2;
320
Bram Moolenaar26262f82019-09-04 20:59:15 +0200321 // Expand "~/path" for all systems and "~user/path" for Unix and VMS
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200322 if ((*fnamep)[0] == '~'
323#if !defined(UNIX) && !(defined(VMS) && defined(USER_HOME))
324 && ((*fnamep)[1] == '/'
325# ifdef BACKSLASH_IN_FILENAME
326 || (*fnamep)[1] == '\\'
327# endif
328 || (*fnamep)[1] == NUL)
329#endif
330 && !(tilde_file && (*fnamep)[1] == NUL)
331 )
332 {
333 *fnamep = expand_env_save(*fnamep);
Bram Moolenaar26262f82019-09-04 20:59:15 +0200334 vim_free(*bufp); // free any allocated file name
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200335 *bufp = *fnamep;
336 if (*fnamep == NULL)
337 return -1;
338 }
339
Bram Moolenaar26262f82019-09-04 20:59:15 +0200340 // When "/." or "/.." is used: force expansion to get rid of it.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200341 for (p = *fnamep; *p != NUL; MB_PTR_ADV(p))
342 {
343 if (vim_ispathsep(*p)
344 && p[1] == '.'
345 && (p[2] == NUL
346 || vim_ispathsep(p[2])
347 || (p[2] == '.'
348 && (p[3] == NUL || vim_ispathsep(p[3])))))
349 break;
350 }
351
Bram Moolenaar26262f82019-09-04 20:59:15 +0200352 // FullName_save() is slow, don't use it when not needed.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200353 if (*p != NUL || !vim_isAbsName(*fnamep))
354 {
355 *fnamep = FullName_save(*fnamep, *p != NUL);
Bram Moolenaar26262f82019-09-04 20:59:15 +0200356 vim_free(*bufp); // free any allocated file name
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200357 *bufp = *fnamep;
358 if (*fnamep == NULL)
359 return -1;
360 }
361
362#ifdef MSWIN
363# if _WIN32_WINNT >= 0x0500
364 if (vim_strchr(*fnamep, '~') != NULL)
365 {
366 // Expand 8.3 filename to full path. Needed to make sure the same
367 // file does not have two different names.
368 // Note: problem does not occur if _WIN32_WINNT < 0x0500.
369 WCHAR *wfname = enc_to_utf16(*fnamep, NULL);
370 WCHAR buf[_MAX_PATH];
371
372 if (wfname != NULL)
373 {
374 if (GetLongPathNameW(wfname, buf, _MAX_PATH))
375 {
K.Takata54119102022-02-03 13:33:03 +0000376 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200377
K.Takata54119102022-02-03 13:33:03 +0000378 if (q != NULL)
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200379 {
380 vim_free(*bufp); // free any allocated file name
K.Takata54119102022-02-03 13:33:03 +0000381 *bufp = *fnamep = q;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200382 }
383 }
384 vim_free(wfname);
385 }
386 }
387# endif
388#endif
Bram Moolenaar26262f82019-09-04 20:59:15 +0200389 // Append a path separator to a directory.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200390 if (mch_isdir(*fnamep))
391 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200392 // Make room for one or two extra characters.
Bram Moolenaar71ccd032020-06-12 22:59:11 +0200393 *fnamep = vim_strnsave(*fnamep, STRLEN(*fnamep) + 2);
Bram Moolenaar26262f82019-09-04 20:59:15 +0200394 vim_free(*bufp); // free any allocated file name
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200395 *bufp = *fnamep;
396 if (*fnamep == NULL)
397 return -1;
398 add_pathsep(*fnamep);
399 }
400 }
401
Bram Moolenaar26262f82019-09-04 20:59:15 +0200402 // ":." - path relative to the current directory
403 // ":~" - path relative to the home directory
404 // ":8" - shortname path - postponed till after
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200405 while (src[*usedlen] == ':'
406 && ((c = src[*usedlen + 1]) == '.' || c == '~' || c == '8'))
407 {
408 *usedlen += 2;
409 if (c == '8')
410 {
411#ifdef MSWIN
Bram Moolenaar26262f82019-09-04 20:59:15 +0200412 has_shortname = 1; // Postpone this.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200413#endif
414 continue;
415 }
416 pbuf = NULL;
Bram Moolenaar26262f82019-09-04 20:59:15 +0200417 // Need full path first (use expand_env() to remove a "~/")
Bram Moolenaard816cd92020-02-04 22:23:09 +0100418 if (!has_fullname && !has_homerelative)
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200419 {
=?UTF-8?q?Dundar=20G=C3=B6c?=78a84042022-02-09 15:20:39 +0000420 if (**fnamep == '~')
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200421 p = pbuf = expand_env_save(*fnamep);
422 else
423 p = pbuf = FullName_save(*fnamep, FALSE);
424 }
425 else
426 p = *fnamep;
427
428 has_fullname = 0;
429
430 if (p != NULL)
431 {
432 if (c == '.')
433 {
Bram Moolenaard816cd92020-02-04 22:23:09 +0100434 size_t namelen;
435
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200436 mch_dirname(dirname, MAXPATHL);
Bram Moolenaard816cd92020-02-04 22:23:09 +0100437 if (has_homerelative)
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200438 {
Bram Moolenaard816cd92020-02-04 22:23:09 +0100439 s = vim_strsave(dirname);
440 if (s != NULL)
441 {
442 home_replace(NULL, s, dirname, MAXPATHL, TRUE);
443 vim_free(s);
444 }
445 }
446 namelen = STRLEN(dirname);
447
448 // Do not call shorten_fname() here since it removes the prefix
449 // even though the path does not have a prefix.
450 if (fnamencmp(p, dirname, namelen) == 0)
451 {
452 p += namelen;
Bram Moolenaara78e9c62020-02-05 21:14:00 +0100453 if (vim_ispathsep(*p))
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200454 {
Bram Moolenaara78e9c62020-02-05 21:14:00 +0100455 while (*p && vim_ispathsep(*p))
456 ++p;
457 *fnamep = p;
458 if (pbuf != NULL)
459 {
460 // free any allocated file name
461 vim_free(*bufp);
462 *bufp = pbuf;
463 pbuf = NULL;
464 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200465 }
466 }
467 }
468 else
469 {
470 home_replace(NULL, p, dirname, MAXPATHL, TRUE);
Bram Moolenaar26262f82019-09-04 20:59:15 +0200471 // Only replace it when it starts with '~'
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200472 if (*dirname == '~')
473 {
474 s = vim_strsave(dirname);
475 if (s != NULL)
476 {
477 *fnamep = s;
478 vim_free(*bufp);
479 *bufp = s;
Bram Moolenaard816cd92020-02-04 22:23:09 +0100480 has_homerelative = TRUE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200481 }
482 }
483 }
484 vim_free(pbuf);
485 }
486 }
487
488 tail = gettail(*fnamep);
489 *fnamelen = (int)STRLEN(*fnamep);
490
Bram Moolenaar26262f82019-09-04 20:59:15 +0200491 // ":h" - head, remove "/file_name", can be repeated
492 // Don't remove the first "/" or "c:\"
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200493 while (src[*usedlen] == ':' && src[*usedlen + 1] == 'h')
494 {
495 valid |= VALID_HEAD;
496 *usedlen += 2;
497 s = get_past_head(*fnamep);
498 while (tail > s && after_pathsep(s, tail))
499 MB_PTR_BACK(*fnamep, tail);
500 *fnamelen = (int)(tail - *fnamep);
501#ifdef VMS
502 if (*fnamelen > 0)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200503 *fnamelen += 1; // the path separator is part of the path
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200504#endif
505 if (*fnamelen == 0)
506 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200507 // Result is empty. Turn it into "." to make ":cd %:h" work.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200508 p = vim_strsave((char_u *)".");
509 if (p == NULL)
510 return -1;
511 vim_free(*bufp);
512 *bufp = *fnamep = tail = p;
513 *fnamelen = 1;
514 }
515 else
516 {
517 while (tail > s && !after_pathsep(s, tail))
518 MB_PTR_BACK(*fnamep, tail);
519 }
520 }
521
Bram Moolenaar26262f82019-09-04 20:59:15 +0200522 // ":8" - shortname
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200523 if (src[*usedlen] == ':' && src[*usedlen + 1] == '8')
524 {
525 *usedlen += 2;
526#ifdef MSWIN
527 has_shortname = 1;
528#endif
529 }
530
531#ifdef MSWIN
532 /*
533 * Handle ":8" after we have done 'heads' and before we do 'tails'.
534 */
535 if (has_shortname)
536 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200537 // Copy the string if it is shortened by :h and when it wasn't copied
538 // yet, because we are going to change it in place. Avoids changing
539 // the buffer name for "%:8".
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200540 if (*fnamelen < (int)STRLEN(*fnamep) || *fnamep == fname_start)
541 {
542 p = vim_strnsave(*fnamep, *fnamelen);
543 if (p == NULL)
544 return -1;
545 vim_free(*bufp);
546 *bufp = *fnamep = p;
547 }
548
Bram Moolenaar26262f82019-09-04 20:59:15 +0200549 // Split into two implementations - makes it easier. First is where
550 // there isn't a full name already, second is where there is.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200551 if (!has_fullname && !vim_isAbsName(*fnamep))
552 {
553 if (shortpath_for_partial(fnamep, bufp, fnamelen) == FAIL)
554 return -1;
555 }
556 else
557 {
558 int l = *fnamelen;
559
Bram Moolenaar26262f82019-09-04 20:59:15 +0200560 // Simple case, already have the full-name.
561 // Nearly always shorter, so try first time.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200562 if (get_short_pathname(fnamep, bufp, &l) == FAIL)
563 return -1;
564
565 if (l == 0)
566 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200567 // Couldn't find the filename, search the paths.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200568 l = *fnamelen;
569 if (shortpath_for_invalid_fname(fnamep, bufp, &l) == FAIL)
570 return -1;
571 }
572 *fnamelen = l;
573 }
574 }
575#endif // MSWIN
576
Bram Moolenaar26262f82019-09-04 20:59:15 +0200577 // ":t" - tail, just the basename
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200578 if (src[*usedlen] == ':' && src[*usedlen + 1] == 't')
579 {
580 *usedlen += 2;
581 *fnamelen -= (int)(tail - *fnamep);
582 *fnamep = tail;
583 }
584
Bram Moolenaar26262f82019-09-04 20:59:15 +0200585 // ":e" - extension, can be repeated
586 // ":r" - root, without extension, can be repeated
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200587 while (src[*usedlen] == ':'
588 && (src[*usedlen + 1] == 'e' || src[*usedlen + 1] == 'r'))
589 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200590 // find a '.' in the tail:
591 // - for second :e: before the current fname
592 // - otherwise: The last '.'
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200593 if (src[*usedlen + 1] == 'e' && *fnamep > tail)
594 s = *fnamep - 2;
595 else
596 s = *fnamep + *fnamelen - 1;
597 for ( ; s > tail; --s)
598 if (s[0] == '.')
599 break;
Bram Moolenaar26262f82019-09-04 20:59:15 +0200600 if (src[*usedlen + 1] == 'e') // :e
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200601 {
602 if (s > tail)
603 {
604 *fnamelen += (int)(*fnamep - (s + 1));
605 *fnamep = s + 1;
606#ifdef VMS
Bram Moolenaar26262f82019-09-04 20:59:15 +0200607 // cut version from the extension
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200608 s = *fnamep + *fnamelen - 1;
609 for ( ; s > *fnamep; --s)
610 if (s[0] == ';')
611 break;
612 if (s > *fnamep)
613 *fnamelen = s - *fnamep;
614#endif
615 }
616 else if (*fnamep <= tail)
617 *fnamelen = 0;
618 }
Bram Moolenaar26262f82019-09-04 20:59:15 +0200619 else // :r
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200620 {
Bram Moolenaarb1892952019-10-08 23:26:50 +0200621 char_u *limit = *fnamep;
622
623 if (limit < tail)
624 limit = tail;
625 if (s > limit) // remove one extension
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200626 *fnamelen = (int)(s - *fnamep);
627 }
628 *usedlen += 2;
629 }
630
Bram Moolenaar26262f82019-09-04 20:59:15 +0200631 // ":s?pat?foo?" - substitute
632 // ":gs?pat?foo?" - global substitute
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200633 if (src[*usedlen] == ':'
634 && (src[*usedlen + 1] == 's'
635 || (src[*usedlen + 1] == 'g' && src[*usedlen + 2] == 's')))
636 {
637 char_u *str;
638 char_u *pat;
639 char_u *sub;
640 int sep;
641 char_u *flags;
642 int didit = FALSE;
643
644 flags = (char_u *)"";
645 s = src + *usedlen + 2;
646 if (src[*usedlen + 1] == 'g')
647 {
648 flags = (char_u *)"g";
649 ++s;
650 }
651
652 sep = *s++;
653 if (sep)
654 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200655 // find end of pattern
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200656 p = vim_strchr(s, sep);
657 if (p != NULL)
658 {
Bram Moolenaar71ccd032020-06-12 22:59:11 +0200659 pat = vim_strnsave(s, p - s);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200660 if (pat != NULL)
661 {
662 s = p + 1;
Bram Moolenaar26262f82019-09-04 20:59:15 +0200663 // find end of substitution
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200664 p = vim_strchr(s, sep);
665 if (p != NULL)
666 {
Bram Moolenaar71ccd032020-06-12 22:59:11 +0200667 sub = vim_strnsave(s, p - s);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200668 str = vim_strnsave(*fnamep, *fnamelen);
669 if (sub != NULL && str != NULL)
670 {
671 *usedlen = (int)(p + 1 - src);
672 s = do_string_sub(str, pat, sub, NULL, flags);
673 if (s != NULL)
674 {
675 *fnamep = s;
676 *fnamelen = (int)STRLEN(s);
677 vim_free(*bufp);
678 *bufp = s;
679 didit = TRUE;
680 }
681 }
682 vim_free(sub);
683 vim_free(str);
684 }
685 vim_free(pat);
686 }
687 }
Bram Moolenaar26262f82019-09-04 20:59:15 +0200688 // after using ":s", repeat all the modifiers
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200689 if (didit)
690 goto repeat;
691 }
692 }
693
694 if (src[*usedlen] == ':' && src[*usedlen + 1] == 'S')
695 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200696 // vim_strsave_shellescape() needs a NUL terminated string.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200697 c = (*fnamep)[*fnamelen];
698 if (c != NUL)
699 (*fnamep)[*fnamelen] = NUL;
700 p = vim_strsave_shellescape(*fnamep, FALSE, FALSE);
701 if (c != NUL)
702 (*fnamep)[*fnamelen] = c;
703 if (p == NULL)
704 return -1;
705 vim_free(*bufp);
706 *bufp = *fnamep = p;
707 *fnamelen = (int)STRLEN(p);
708 *usedlen += 2;
709 }
710
711 return valid;
712}
713
Bram Moolenaar273af492020-09-25 23:49:01 +0200714/*
715 * Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
716 * "trim_len" specifies how many characters to keep for each directory.
717 * Must be 1 or more.
718 * It's done in-place.
719 */
720 static void
721shorten_dir_len(char_u *str, int trim_len)
722{
723 char_u *tail, *s, *d;
724 int skip = FALSE;
725 int dirchunk_len = 0;
726
727 tail = gettail(str);
728 d = str;
729 for (s = str; ; ++s)
730 {
731 if (s >= tail) // copy the whole tail
732 {
733 *d++ = *s;
734 if (*s == NUL)
735 break;
736 }
737 else if (vim_ispathsep(*s)) // copy '/' and next char
738 {
739 *d++ = *s;
740 skip = FALSE;
741 dirchunk_len = 0;
742 }
743 else if (!skip)
744 {
745 *d++ = *s; // copy next char
746 if (*s != '~' && *s != '.') // and leading "~" and "."
747 {
748 ++dirchunk_len; // only count word chars for the size
749
750 // keep copying chars until we have our preferred length (or
751 // until the above if/else branches move us along)
752 if (dirchunk_len >= trim_len)
753 skip = TRUE;
754 }
755
756 if (has_mbyte)
757 {
758 int l = mb_ptr2len(s);
759
760 while (--l > 0)
761 *d++ = *++s;
762 }
763 }
764 }
765}
766
767/*
768 * Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
769 * It's done in-place.
770 */
771 void
772shorten_dir(char_u *str)
773{
774 shorten_dir_len(str, 1);
775}
776
Bram Moolenaar022f9ef2022-07-02 17:36:31 +0100777/*
778 * Return TRUE if "fname" is a readable file.
779 */
780 int
781file_is_readable(char_u *fname)
782{
783 int fd;
784
785#ifndef O_NONBLOCK
786# define O_NONBLOCK 0
787#endif
788 if (*fname && !mch_isdir(fname)
789 && (fd = mch_open((char *)fname, O_RDONLY | O_NONBLOCK, 0)) >= 0)
790 {
791 close(fd);
792 return TRUE;
793 }
794 return FALSE;
795}
796
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200797#if defined(FEAT_EVAL) || defined(PROTO)
798
799/*
800 * "chdir(dir)" function
801 */
802 void
803f_chdir(typval_T *argvars, typval_T *rettv)
804{
805 char_u *cwd;
806 cdscope_T scope = CDSCOPE_GLOBAL;
807
808 rettv->v_type = VAR_STRING;
809 rettv->vval.v_string = NULL;
810
811 if (argvars[0].v_type != VAR_STRING)
Bram Moolenaarc5809432021-03-27 21:23:30 +0100812 {
Bram Moolenaard816cd92020-02-04 22:23:09 +0100813 // Returning an empty string means it failed.
Bram Moolenaar002bc792020-06-05 22:33:42 +0200814 // No error message, for historic reasons.
Bram Moolenaarc5809432021-03-27 21:23:30 +0100815 if (in_vim9script())
816 (void) check_for_string_arg(argvars, 0);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200817 return;
Bram Moolenaarc5809432021-03-27 21:23:30 +0100818 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200819
820 // Return the current directory
821 cwd = alloc(MAXPATHL);
822 if (cwd != NULL)
823 {
824 if (mch_dirname(cwd, MAXPATHL) != FAIL)
825 {
826#ifdef BACKSLASH_IN_FILENAME
827 slash_adjust(cwd);
828#endif
829 rettv->vval.v_string = vim_strsave(cwd);
830 }
831 vim_free(cwd);
832 }
833
834 if (curwin->w_localdir != NULL)
835 scope = CDSCOPE_WINDOW;
836 else if (curtab->tp_localdir != NULL)
837 scope = CDSCOPE_TABPAGE;
838
839 if (!changedir_func(argvars[0].vval.v_string, TRUE, scope))
840 // Directory change failed
841 VIM_CLEAR(rettv->vval.v_string);
842}
843
844/*
845 * "delete()" function
846 */
847 void
848f_delete(typval_T *argvars, typval_T *rettv)
849{
850 char_u nbuf[NUMBUFLEN];
851 char_u *name;
852 char_u *flags;
853
854 rettv->vval.v_number = -1;
855 if (check_restricted() || check_secure())
856 return;
857
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +0200858 if (in_vim9script()
859 && (check_for_string_arg(argvars, 0) == FAIL
860 || check_for_opt_string_arg(argvars, 1) == FAIL))
861 return;
862
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200863 name = tv_get_string(&argvars[0]);
864 if (name == NULL || *name == NUL)
865 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +0000866 emsg(_(e_invalid_argument));
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200867 return;
868 }
869
870 if (argvars[1].v_type != VAR_UNKNOWN)
871 flags = tv_get_string_buf(&argvars[1], nbuf);
872 else
873 flags = (char_u *)"";
874
875 if (*flags == NUL)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200876 // delete a file
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200877 rettv->vval.v_number = mch_remove(name) == 0 ? 0 : -1;
878 else if (STRCMP(flags, "d") == 0)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200879 // delete an empty directory
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200880 rettv->vval.v_number = mch_rmdir(name) == 0 ? 0 : -1;
881 else if (STRCMP(flags, "rf") == 0)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200882 // delete a directory recursively
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200883 rettv->vval.v_number = delete_recursive(name);
884 else
Bram Moolenaar108010a2021-06-27 22:03:33 +0200885 semsg(_(e_invalid_expression_str), flags);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200886}
887
888/*
889 * "executable()" function
890 */
891 void
892f_executable(typval_T *argvars, typval_T *rettv)
893{
Bram Moolenaar32105ae2021-03-27 18:59:25 +0100894 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100895 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200896
Bram Moolenaar26262f82019-09-04 20:59:15 +0200897 // Check in $PATH and also check directly if there is a directory name.
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100898 rettv->vval.v_number = mch_can_exe(tv_get_string(&argvars[0]), NULL, TRUE);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200899}
900
901/*
902 * "exepath()" function
903 */
904 void
905f_exepath(typval_T *argvars, typval_T *rettv)
906{
907 char_u *p = NULL;
908
Bram Moolenaar32105ae2021-03-27 18:59:25 +0100909 if (in_vim9script() && check_for_nonempty_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100910 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200911 (void)mch_can_exe(tv_get_string(&argvars[0]), &p, TRUE);
912 rettv->v_type = VAR_STRING;
913 rettv->vval.v_string = p;
914}
915
916/*
917 * "filereadable()" function
918 */
919 void
920f_filereadable(typval_T *argvars, typval_T *rettv)
921{
Bram Moolenaar32105ae2021-03-27 18:59:25 +0100922 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100923 return;
Bram Moolenaar4dea2d92022-03-31 11:37:57 +0100924 rettv->vval.v_number = file_is_readable(tv_get_string(&argvars[0]));
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200925}
926
927/*
928 * Return 0 for not writable, 1 for writable file, 2 for a dir which we have
929 * rights to write into.
930 */
931 void
932f_filewritable(typval_T *argvars, typval_T *rettv)
933{
Bram Moolenaar32105ae2021-03-27 18:59:25 +0100934 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100935 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200936 rettv->vval.v_number = filewritable(tv_get_string(&argvars[0]));
937}
938
Bram Moolenaar840d16f2019-09-10 21:27:18 +0200939 static void
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200940findfilendir(
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;
1041 int 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);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002113 goto fail;
Bram Moolenaar70188f52019-12-23 18:18:52 +01002114 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002115
2116 for (;;)
2117 {
2118 for (;;)
2119 {
2120 len = readlink((char *)p, (char *)buf, MAXPATHL);
2121 if (len <= 0)
2122 break;
2123 buf[len] = NUL;
2124
2125 if (limit-- == 0)
2126 {
2127 vim_free(p);
2128 vim_free(remain);
Bram Moolenaara6f79292022-01-04 21:30:47 +00002129 emsg(_(e_too_many_symbolic_links_cycle));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002130 rettv->vval.v_string = NULL;
2131 goto fail;
2132 }
2133
Bram Moolenaar26262f82019-09-04 20:59:15 +02002134 // Ensure that the result will have a trailing path separator
2135 // if the argument has one.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002136 if (remain == NULL && has_trailing_pathsep)
2137 add_pathsep(buf);
2138
Bram Moolenaar26262f82019-09-04 20:59:15 +02002139 // Separate the first path component in the link value and
2140 // concatenate the remainders.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002141 q = getnextcomp(vim_ispathsep(*buf) ? buf + 1 : buf);
2142 if (*q != NUL)
2143 {
2144 if (remain == NULL)
2145 remain = vim_strsave(q - 1);
2146 else
2147 {
2148 cpy = concat_str(q - 1, remain);
2149 if (cpy != NULL)
2150 {
2151 vim_free(remain);
2152 remain = cpy;
2153 }
2154 }
2155 q[-1] = NUL;
2156 }
2157
2158 q = gettail(p);
2159 if (q > p && *q == NUL)
2160 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002161 // Ignore trailing path separator.
Ken Takata215c3262023-10-16 09:57:43 +02002162 p[q - p - 1] = NUL;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002163 q = gettail(p);
2164 }
2165 if (q > p && !mch_isFullName(buf))
2166 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002167 // symlink is relative to directory of argument
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002168 cpy = alloc(STRLEN(p) + STRLEN(buf) + 1);
2169 if (cpy != NULL)
2170 {
2171 STRCPY(cpy, p);
2172 STRCPY(gettail(cpy), buf);
2173 vim_free(p);
2174 p = cpy;
2175 }
2176 }
2177 else
2178 {
2179 vim_free(p);
2180 p = vim_strsave(buf);
2181 }
2182 }
2183
2184 if (remain == NULL)
2185 break;
2186
Bram Moolenaar26262f82019-09-04 20:59:15 +02002187 // Append the first path component of "remain" to "p".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002188 q = getnextcomp(remain + 1);
2189 len = q - remain - (*q != NUL);
2190 cpy = vim_strnsave(p, STRLEN(p) + len);
2191 if (cpy != NULL)
2192 {
2193 STRNCAT(cpy, remain, len);
2194 vim_free(p);
2195 p = cpy;
2196 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02002197 // Shorten "remain".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002198 if (*q != NUL)
2199 STRMOVE(remain, q - 1);
2200 else
2201 VIM_CLEAR(remain);
2202 }
2203
Bram Moolenaar26262f82019-09-04 20:59:15 +02002204 // If the result is a relative path name, make it explicitly relative to
2205 // the current directory if and only if the argument had this form.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002206 if (!vim_ispathsep(*p))
2207 {
2208 if (is_relative_to_current
2209 && *p != NUL
2210 && !(p[0] == '.'
2211 && (p[1] == NUL
2212 || vim_ispathsep(p[1])
2213 || (p[1] == '.'
2214 && (p[2] == NUL
2215 || vim_ispathsep(p[2]))))))
2216 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002217 // Prepend "./".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002218 cpy = concat_str((char_u *)"./", p);
2219 if (cpy != NULL)
2220 {
2221 vim_free(p);
2222 p = cpy;
2223 }
2224 }
2225 else if (!is_relative_to_current)
2226 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002227 // Strip leading "./".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002228 q = p;
2229 while (q[0] == '.' && vim_ispathsep(q[1]))
2230 q += 2;
2231 if (q > p)
2232 STRMOVE(p, p + 2);
2233 }
2234 }
2235
Bram Moolenaar26262f82019-09-04 20:59:15 +02002236 // Ensure that the result will have no trailing path separator
2237 // if the argument had none. But keep "/" or "//".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002238 if (!has_trailing_pathsep)
2239 {
2240 q = p + STRLEN(p);
2241 if (after_pathsep(p, q))
2242 *gettail_sep(p) = NUL;
2243 }
2244
2245 rettv->vval.v_string = p;
2246 }
2247# else
2248 rettv->vval.v_string = vim_strsave(p);
2249# endif
2250#endif
2251
2252 simplify_filename(rettv->vval.v_string);
2253
2254#ifdef HAVE_READLINK
2255fail:
2256 vim_free(buf);
2257#endif
2258 rettv->v_type = VAR_STRING;
2259}
2260
2261/*
2262 * "tempname()" function
2263 */
2264 void
2265f_tempname(typval_T *argvars UNUSED, typval_T *rettv)
2266{
2267 static int x = 'A';
2268
2269 rettv->v_type = VAR_STRING;
2270 rettv->vval.v_string = vim_tempname(x, FALSE);
2271
Bram Moolenaar26262f82019-09-04 20:59:15 +02002272 // Advance 'x' to use A-Z and 0-9, so that there are at least 34 different
2273 // names. Skip 'I' and 'O', they are used for shell redirection.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002274 do
2275 {
2276 if (x == 'Z')
2277 x = '0';
2278 else if (x == '9')
2279 x = 'A';
2280 else
Bram Moolenaar424bcae2022-01-31 14:59:41 +00002281 ++x;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002282 } while (x == 'I' || x == 'O');
2283}
2284
2285/*
2286 * "writefile()" function
2287 */
2288 void
2289f_writefile(typval_T *argvars, typval_T *rettv)
2290{
2291 int binary = FALSE;
2292 int append = FALSE;
Bram Moolenaar806a2732022-09-04 15:40:36 +01002293 int defer = FALSE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002294#ifdef HAVE_FSYNC
2295 int do_fsync = p_fs;
2296#endif
2297 char_u *fname;
2298 FILE *fd;
2299 int ret = 0;
2300 listitem_T *li;
2301 list_T *list = NULL;
2302 blob_T *blob = NULL;
2303
2304 rettv->vval.v_number = -1;
2305 if (check_secure())
2306 return;
2307
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02002308 if (in_vim9script()
2309 && (check_for_list_or_blob_arg(argvars, 0) == FAIL
2310 || check_for_string_arg(argvars, 1) == FAIL
2311 || check_for_opt_string_arg(argvars, 2) == FAIL))
2312 return;
2313
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002314 if (argvars[0].v_type == VAR_LIST)
2315 {
2316 list = argvars[0].vval.v_list;
2317 if (list == NULL)
2318 return;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02002319 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002320 FOR_ALL_LIST_ITEMS(list, li)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002321 if (tv_get_string_chk(&li->li_tv) == NULL)
2322 return;
2323 }
2324 else if (argvars[0].v_type == VAR_BLOB)
2325 {
2326 blob = argvars[0].vval.v_blob;
2327 if (blob == NULL)
2328 return;
2329 }
2330 else
2331 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00002332 semsg(_(e_invalid_argument_str),
Bram Moolenaar18a2b872020-03-19 13:08:45 +01002333 _("writefile() first argument must be a List or a Blob"));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002334 return;
2335 }
2336
2337 if (argvars[2].v_type != VAR_UNKNOWN)
2338 {
2339 char_u *arg2 = tv_get_string_chk(&argvars[2]);
2340
2341 if (arg2 == NULL)
2342 return;
2343 if (vim_strchr(arg2, 'b') != NULL)
2344 binary = TRUE;
2345 if (vim_strchr(arg2, 'a') != NULL)
2346 append = TRUE;
Bram Moolenaar806a2732022-09-04 15:40:36 +01002347 if (vim_strchr(arg2, 'D') != NULL)
2348 defer = TRUE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002349#ifdef HAVE_FSYNC
2350 if (vim_strchr(arg2, 's') != NULL)
2351 do_fsync = TRUE;
2352 else if (vim_strchr(arg2, 'S') != NULL)
2353 do_fsync = FALSE;
2354#endif
2355 }
2356
2357 fname = tv_get_string_chk(&argvars[1]);
2358 if (fname == NULL)
2359 return;
2360
Bram Moolenaar6f14da12022-09-07 21:30:44 +01002361 if (defer && !can_add_defer())
Bram Moolenaar806a2732022-09-04 15:40:36 +01002362 return;
Bram Moolenaar806a2732022-09-04 15:40:36 +01002363
Bram Moolenaar26262f82019-09-04 20:59:15 +02002364 // Always open the file in binary mode, library functions have a mind of
2365 // their own about CR-LF conversion.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002366 if (*fname == NUL || (fd = mch_fopen((char *)fname,
2367 append ? APPENDBIN : WRITEBIN)) == NULL)
2368 {
Bram Moolenaar806a2732022-09-04 15:40:36 +01002369 semsg(_(e_cant_create_file_str),
2370 *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002371 ret = -1;
2372 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002373 else
2374 {
Bram Moolenaar806a2732022-09-04 15:40:36 +01002375 if (defer)
2376 {
2377 typval_T tv;
2378
2379 tv.v_type = VAR_STRING;
2380 tv.v_lock = 0;
Bram Moolenaar6f14da12022-09-07 21:30:44 +01002381 tv.vval.v_string = FullName_save(fname, FALSE);
Bram Moolenaar806a2732022-09-04 15:40:36 +01002382 if (tv.vval.v_string == NULL
2383 || add_defer((char_u *)"delete", 1, &tv) == FAIL)
2384 {
2385 ret = -1;
2386 fclose(fd);
2387 (void)mch_remove(fname);
2388 }
2389 }
2390
2391 if (ret == 0)
2392 {
2393 if (blob)
2394 {
2395 if (write_blob(fd, blob) == FAIL)
2396 ret = -1;
2397 }
2398 else
2399 {
2400 if (write_list(fd, list, binary) == FAIL)
2401 ret = -1;
2402 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002403#ifdef HAVE_FSYNC
Bram Moolenaar806a2732022-09-04 15:40:36 +01002404 if (ret == 0 && do_fsync)
2405 // Ignore the error, the user wouldn't know what to do about
2406 // it. May happen for a device.
2407 vim_ignored = vim_fsync(fileno(fd));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002408#endif
Bram Moolenaar806a2732022-09-04 15:40:36 +01002409 fclose(fd);
2410 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002411 }
2412
2413 rettv->vval.v_number = ret;
2414}
2415
2416#endif // FEAT_EVAL
2417
2418#if defined(FEAT_BROWSE) || defined(PROTO)
2419/*
2420 * Generic browse function. Calls gui_mch_browse() when possible.
2421 * Later this may pop-up a non-GUI file selector (external command?).
2422 */
2423 char_u *
2424do_browse(
Bram Moolenaar26262f82019-09-04 20:59:15 +02002425 int flags, // BROWSE_SAVE and BROWSE_DIR
2426 char_u *title, // title for the window
2427 char_u *dflt, // default file name (may include directory)
2428 char_u *ext, // extension added
2429 char_u *initdir, // initial directory, NULL for current dir or
2430 // when using path from "dflt"
2431 char_u *filter, // file name filter
2432 buf_T *buf) // buffer to read/write for
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002433{
2434 char_u *fname;
Bram Moolenaar26262f82019-09-04 20:59:15 +02002435 static char_u *last_dir = NULL; // last used directory
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002436 char_u *tofree = NULL;
Bram Moolenaare1004402020-10-24 20:49:43 +02002437 int save_cmod_flags = cmdmod.cmod_flags;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002438
Bram Moolenaar26262f82019-09-04 20:59:15 +02002439 // Must turn off browse to avoid that autocommands will get the
2440 // flag too!
Bram Moolenaare1004402020-10-24 20:49:43 +02002441 cmdmod.cmod_flags &= ~CMOD_BROWSE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002442
2443 if (title == NULL || *title == NUL)
2444 {
2445 if (flags & BROWSE_DIR)
2446 title = (char_u *)_("Select Directory dialog");
2447 else if (flags & BROWSE_SAVE)
2448 title = (char_u *)_("Save File dialog");
2449 else
2450 title = (char_u *)_("Open File dialog");
2451 }
2452
Bram Moolenaar26262f82019-09-04 20:59:15 +02002453 // When no directory specified, use default file name, default dir, buffer
2454 // dir, last dir or current dir
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002455 if ((initdir == NULL || *initdir == NUL) && dflt != NULL && *dflt != NUL)
2456 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002457 if (mch_isdir(dflt)) // default file name is a directory
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002458 {
2459 initdir = dflt;
2460 dflt = NULL;
2461 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02002462 else if (gettail(dflt) != dflt) // default file name includes a path
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002463 {
2464 tofree = vim_strsave(dflt);
2465 if (tofree != NULL)
2466 {
2467 initdir = tofree;
2468 *gettail(initdir) = NUL;
2469 dflt = gettail(dflt);
2470 }
2471 }
2472 }
2473
2474 if (initdir == NULL || *initdir == NUL)
2475 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002476 // When 'browsedir' is a directory, use it
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002477 if (STRCMP(p_bsdir, "last") != 0
2478 && STRCMP(p_bsdir, "buffer") != 0
2479 && STRCMP(p_bsdir, "current") != 0
2480 && mch_isdir(p_bsdir))
2481 initdir = p_bsdir;
Bram Moolenaar26262f82019-09-04 20:59:15 +02002482 // When saving or 'browsedir' is "buffer", use buffer fname
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002483 else if (((flags & BROWSE_SAVE) || *p_bsdir == 'b')
2484 && buf != NULL && buf->b_ffname != NULL)
2485 {
2486 if (dflt == NULL || *dflt == NUL)
2487 dflt = gettail(curbuf->b_ffname);
2488 tofree = vim_strsave(curbuf->b_ffname);
2489 if (tofree != NULL)
2490 {
2491 initdir = tofree;
2492 *gettail(initdir) = NUL;
2493 }
2494 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02002495 // When 'browsedir' is "last", use dir from last browse
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002496 else if (*p_bsdir == 'l')
2497 initdir = last_dir;
Bram Moolenaar26262f82019-09-04 20:59:15 +02002498 // When 'browsedir is "current", use current directory. This is the
2499 // default already, leave initdir empty.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002500 }
2501
2502# ifdef FEAT_GUI
Bram Moolenaar26262f82019-09-04 20:59:15 +02002503 if (gui.in_use) // when this changes, also adjust f_has()!
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002504 {
2505 if (filter == NULL
2506# ifdef FEAT_EVAL
2507 && (filter = get_var_value((char_u *)"b:browsefilter")) == NULL
2508 && (filter = get_var_value((char_u *)"g:browsefilter")) == NULL
2509# endif
2510 )
2511 filter = BROWSE_FILTER_DEFAULT;
2512 if (flags & BROWSE_DIR)
2513 {
2514# if defined(FEAT_GUI_GTK) || defined(MSWIN)
Bram Moolenaar26262f82019-09-04 20:59:15 +02002515 // For systems that have a directory dialog.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002516 fname = gui_mch_browsedir(title, initdir);
2517# else
Bram Moolenaar26262f82019-09-04 20:59:15 +02002518 // Generic solution for selecting a directory: select a file and
2519 // remove the file name.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002520 fname = gui_mch_browse(0, title, dflt, ext, initdir, (char_u *)"");
2521# endif
2522# if !defined(FEAT_GUI_GTK)
Bram Moolenaar26262f82019-09-04 20:59:15 +02002523 // Win32 adds a dummy file name, others return an arbitrary file
2524 // name. GTK+ 2 returns only the directory,
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002525 if (fname != NULL && *fname != NUL && !mch_isdir(fname))
2526 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002527 // Remove the file name.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002528 char_u *tail = gettail_sep(fname);
2529
2530 if (tail == fname)
Bram Moolenaar26262f82019-09-04 20:59:15 +02002531 *tail++ = '.'; // use current dir
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002532 *tail = NUL;
2533 }
2534# endif
2535 }
2536 else
2537 fname = gui_mch_browse(flags & BROWSE_SAVE,
2538 title, dflt, ext, initdir, (char_u *)_(filter));
2539
Bram Moolenaar26262f82019-09-04 20:59:15 +02002540 // We hang around in the dialog for a while, the user might do some
2541 // things to our files. The Win32 dialog allows deleting or renaming
2542 // a file, check timestamps.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002543 need_check_timestamps = TRUE;
2544 did_check_timestamps = FALSE;
2545 }
2546 else
2547# endif
2548 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002549 // TODO: non-GUI file selector here
Bram Moolenaareaaac012022-01-02 17:00:40 +00002550 emsg(_(e_sorry_no_file_browser_in_console_mode));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002551 fname = NULL;
2552 }
2553
Bram Moolenaar26262f82019-09-04 20:59:15 +02002554 // keep the directory for next time
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002555 if (fname != NULL)
2556 {
2557 vim_free(last_dir);
2558 last_dir = vim_strsave(fname);
2559 if (last_dir != NULL && !(flags & BROWSE_DIR))
2560 {
2561 *gettail(last_dir) = NUL;
2562 if (*last_dir == NUL)
2563 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002564 // filename only returned, must be in current dir
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002565 vim_free(last_dir);
2566 last_dir = alloc(MAXPATHL);
2567 if (last_dir != NULL)
2568 mch_dirname(last_dir, MAXPATHL);
2569 }
2570 }
2571 }
2572
2573 vim_free(tofree);
Bram Moolenaare1004402020-10-24 20:49:43 +02002574 cmdmod.cmod_flags = save_cmod_flags;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002575
2576 return fname;
2577}
2578#endif
2579
2580#if defined(FEAT_EVAL) || defined(PROTO)
2581
2582/*
2583 * "browse(save, title, initdir, default)" function
2584 */
2585 void
2586f_browse(typval_T *argvars UNUSED, typval_T *rettv)
2587{
2588# ifdef FEAT_BROWSE
2589 int save;
2590 char_u *title;
2591 char_u *initdir;
2592 char_u *defname;
2593 char_u buf[NUMBUFLEN];
2594 char_u buf2[NUMBUFLEN];
2595 int error = FALSE;
2596
Bram Moolenaarf28f2ac2021-03-22 22:21:26 +01002597 if (in_vim9script()
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02002598 && (check_for_bool_arg(argvars, 0) == FAIL
2599 || check_for_string_arg(argvars, 1) == FAIL
Bram Moolenaar32105ae2021-03-27 18:59:25 +01002600 || check_for_string_arg(argvars, 2) == FAIL
2601 || check_for_string_arg(argvars, 3) == FAIL))
Bram Moolenaarf28f2ac2021-03-22 22:21:26 +01002602 return;
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02002603
Bram Moolenaar5a049842022-10-08 12:52:09 +01002604 save = (int)tv_get_bool_chk(&argvars[0], &error);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002605 title = tv_get_string_chk(&argvars[1]);
2606 initdir = tv_get_string_buf_chk(&argvars[2], buf);
2607 defname = tv_get_string_buf_chk(&argvars[3], buf2);
2608
2609 if (error || title == NULL || initdir == NULL || defname == NULL)
2610 rettv->vval.v_string = NULL;
2611 else
2612 rettv->vval.v_string =
2613 do_browse(save ? BROWSE_SAVE : 0,
2614 title, defname, NULL, initdir, NULL, curbuf);
2615# else
2616 rettv->vval.v_string = NULL;
2617# endif
2618 rettv->v_type = VAR_STRING;
2619}
2620
2621/*
2622 * "browsedir(title, initdir)" function
2623 */
2624 void
2625f_browsedir(typval_T *argvars UNUSED, typval_T *rettv)
2626{
2627# ifdef FEAT_BROWSE
2628 char_u *title;
2629 char_u *initdir;
2630 char_u buf[NUMBUFLEN];
2631
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02002632 if (in_vim9script()
2633 && (check_for_string_arg(argvars, 0) == FAIL
2634 || check_for_string_arg(argvars, 1) == FAIL))
2635 return;
2636
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002637 title = tv_get_string_chk(&argvars[0]);
2638 initdir = tv_get_string_buf_chk(&argvars[1], buf);
2639
2640 if (title == NULL || initdir == NULL)
2641 rettv->vval.v_string = NULL;
2642 else
2643 rettv->vval.v_string = do_browse(BROWSE_DIR,
2644 title, NULL, NULL, initdir, NULL, curbuf);
2645# else
2646 rettv->vval.v_string = NULL;
2647# endif
2648 rettv->v_type = VAR_STRING;
2649}
2650
2651#endif // FEAT_EVAL
Bram Moolenaar26262f82019-09-04 20:59:15 +02002652
2653/*
2654 * Replace home directory by "~" in each space or comma separated file name in
2655 * 'src'.
2656 * If anything fails (except when out of space) dst equals src.
2657 */
2658 void
2659home_replace(
2660 buf_T *buf, // when not NULL, check for help files
2661 char_u *src, // input file name
2662 char_u *dst, // where to put the result
2663 int dstlen, // maximum length of the result
2664 int one) // if TRUE, only replace one file name, include
2665 // spaces and commas in the file name.
2666{
2667 size_t dirlen = 0, envlen = 0;
2668 size_t len;
2669 char_u *homedir_env, *homedir_env_orig;
2670 char_u *p;
2671
2672 if (src == NULL)
2673 {
2674 *dst = NUL;
2675 return;
2676 }
2677
2678 /*
2679 * If the file is a help file, remove the path completely.
2680 */
2681 if (buf != NULL && buf->b_help)
2682 {
2683 vim_snprintf((char *)dst, dstlen, "%s", gettail(src));
2684 return;
2685 }
2686
2687 /*
2688 * We check both the value of the $HOME environment variable and the
2689 * "real" home directory.
2690 */
2691 if (homedir != NULL)
2692 dirlen = STRLEN(homedir);
2693
2694#ifdef VMS
2695 homedir_env_orig = homedir_env = mch_getenv((char_u *)"SYS$LOGIN");
2696#else
2697 homedir_env_orig = homedir_env = mch_getenv((char_u *)"HOME");
2698#endif
2699#ifdef MSWIN
2700 if (homedir_env == NULL)
2701 homedir_env_orig = homedir_env = mch_getenv((char_u *)"USERPROFILE");
2702#endif
2703 // Empty is the same as not set.
2704 if (homedir_env != NULL && *homedir_env == NUL)
2705 homedir_env = NULL;
2706
2707 if (homedir_env != NULL && *homedir_env == '~')
2708 {
2709 int usedlen = 0;
2710 int flen;
2711 char_u *fbuf = NULL;
2712
2713 flen = (int)STRLEN(homedir_env);
2714 (void)modify_fname((char_u *)":p", FALSE, &usedlen,
2715 &homedir_env, &fbuf, &flen);
2716 flen = (int)STRLEN(homedir_env);
2717 if (flen > 0 && vim_ispathsep(homedir_env[flen - 1]))
2718 // Remove the trailing / that is added to a directory.
2719 homedir_env[flen - 1] = NUL;
2720 }
2721
2722 if (homedir_env != NULL)
2723 envlen = STRLEN(homedir_env);
2724
2725 if (!one)
2726 src = skipwhite(src);
2727 while (*src && dstlen > 0)
2728 {
2729 /*
2730 * Here we are at the beginning of a file name.
2731 * First, check to see if the beginning of the file name matches
2732 * $HOME or the "real" home directory. Check that there is a '/'
2733 * after the match (so that if e.g. the file is "/home/pieter/bla",
2734 * and the home directory is "/home/piet", the file does not end up
2735 * as "~er/bla" (which would seem to indicate the file "bla" in user
2736 * er's home directory)).
2737 */
2738 p = homedir;
2739 len = dirlen;
2740 for (;;)
2741 {
2742 if ( len
2743 && fnamencmp(src, p, len) == 0
2744 && (vim_ispathsep(src[len])
2745 || (!one && (src[len] == ',' || src[len] == ' '))
2746 || src[len] == NUL))
2747 {
2748 src += len;
2749 if (--dstlen > 0)
2750 *dst++ = '~';
2751
Bram Moolenaar0e390f42020-06-10 13:12:28 +02002752 // Do not add directory separator into dst, because dst is
2753 // expected to just return the directory name without the
2754 // directory separator '/'.
Bram Moolenaar26262f82019-09-04 20:59:15 +02002755 break;
2756 }
2757 if (p == homedir_env)
2758 break;
2759 p = homedir_env;
2760 len = envlen;
2761 }
2762
2763 // if (!one) skip to separator: space or comma
2764 while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0)
2765 *dst++ = *src++;
2766 // skip separator
2767 while ((*src == ' ' || *src == ',') && --dstlen > 0)
2768 *dst++ = *src++;
2769 }
2770 // if (dstlen == 0) out of space, what to do???
2771
2772 *dst = NUL;
2773
2774 if (homedir_env != homedir_env_orig)
2775 vim_free(homedir_env);
2776}
2777
2778/*
2779 * Like home_replace, store the replaced string in allocated memory.
2780 * When something fails, NULL is returned.
2781 */
2782 char_u *
2783home_replace_save(
2784 buf_T *buf, // when not NULL, check for help files
2785 char_u *src) // input file name
2786{
2787 char_u *dst;
2788 unsigned len;
2789
2790 len = 3; // space for "~/" and trailing NUL
2791 if (src != NULL) // just in case
2792 len += (unsigned)STRLEN(src);
2793 dst = alloc(len);
2794 if (dst != NULL)
2795 home_replace(buf, src, dst, len, TRUE);
2796 return dst;
2797}
2798
2799/*
2800 * Compare two file names and return:
2801 * FPC_SAME if they both exist and are the same file.
2802 * FPC_SAMEX if they both don't exist and have the same file name.
2803 * FPC_DIFF if they both exist and are different files.
2804 * FPC_NOTX if they both don't exist.
2805 * FPC_DIFFX if one of them doesn't exist.
2806 * For the first name environment variables are expanded if "expandenv" is
2807 * TRUE.
2808 */
2809 int
2810fullpathcmp(
2811 char_u *s1,
2812 char_u *s2,
2813 int checkname, // when both don't exist, check file names
2814 int expandenv)
2815{
2816#ifdef UNIX
2817 char_u exp1[MAXPATHL];
2818 char_u full1[MAXPATHL];
2819 char_u full2[MAXPATHL];
2820 stat_T st1, st2;
2821 int r1, r2;
2822
2823 if (expandenv)
2824 expand_env(s1, exp1, MAXPATHL);
2825 else
2826 vim_strncpy(exp1, s1, MAXPATHL - 1);
2827 r1 = mch_stat((char *)exp1, &st1);
2828 r2 = mch_stat((char *)s2, &st2);
2829 if (r1 != 0 && r2 != 0)
2830 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002831 // if mch_stat() doesn't work, may compare the names
Bram Moolenaar26262f82019-09-04 20:59:15 +02002832 if (checkname)
2833 {
2834 if (fnamecmp(exp1, s2) == 0)
2835 return FPC_SAMEX;
2836 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
2837 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
2838 if (r1 == OK && r2 == OK && fnamecmp(full1, full2) == 0)
2839 return FPC_SAMEX;
2840 }
2841 return FPC_NOTX;
2842 }
2843 if (r1 != 0 || r2 != 0)
2844 return FPC_DIFFX;
2845 if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
2846 return FPC_SAME;
2847 return FPC_DIFF;
2848#else
2849 char_u *exp1; // expanded s1
2850 char_u *full1; // full path of s1
2851 char_u *full2; // full path of s2
2852 int retval = FPC_DIFF;
2853 int r1, r2;
2854
2855 // allocate one buffer to store three paths (alloc()/free() is slow!)
2856 if ((exp1 = alloc(MAXPATHL * 3)) != NULL)
2857 {
2858 full1 = exp1 + MAXPATHL;
2859 full2 = full1 + MAXPATHL;
2860
2861 if (expandenv)
2862 expand_env(s1, exp1, MAXPATHL);
2863 else
2864 vim_strncpy(exp1, s1, MAXPATHL - 1);
2865 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
2866 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
2867
2868 // If vim_FullName() fails, the file probably doesn't exist.
2869 if (r1 != OK && r2 != OK)
2870 {
2871 if (checkname && fnamecmp(exp1, s2) == 0)
2872 retval = FPC_SAMEX;
2873 else
2874 retval = FPC_NOTX;
2875 }
2876 else if (r1 != OK || r2 != OK)
2877 retval = FPC_DIFFX;
2878 else if (fnamecmp(full1, full2))
2879 retval = FPC_DIFF;
2880 else
2881 retval = FPC_SAME;
2882 vim_free(exp1);
2883 }
2884 return retval;
2885#endif
2886}
2887
2888/*
2889 * Get the tail of a path: the file name.
2890 * When the path ends in a path separator the tail is the NUL after it.
2891 * Fail safe: never returns NULL.
2892 */
2893 char_u *
2894gettail(char_u *fname)
2895{
2896 char_u *p1, *p2;
2897
2898 if (fname == NULL)
2899 return (char_u *)"";
2900 for (p1 = p2 = get_past_head(fname); *p2; ) // find last part of path
2901 {
2902 if (vim_ispathsep_nocolon(*p2))
2903 p1 = p2 + 1;
2904 MB_PTR_ADV(p2);
2905 }
2906 return p1;
2907}
2908
2909/*
2910 * Get pointer to tail of "fname", including path separators. Putting a NUL
2911 * here leaves the directory name. Takes care of "c:/" and "//".
2912 * Always returns a valid pointer.
2913 */
2914 char_u *
2915gettail_sep(char_u *fname)
2916{
2917 char_u *p;
2918 char_u *t;
2919
2920 p = get_past_head(fname); // don't remove the '/' from "c:/file"
2921 t = gettail(fname);
2922 while (t > p && after_pathsep(fname, t))
2923 --t;
2924#ifdef VMS
2925 // path separator is part of the path
2926 ++t;
2927#endif
2928 return t;
2929}
2930
2931/*
2932 * get the next path component (just after the next path separator).
2933 */
2934 char_u *
2935getnextcomp(char_u *fname)
2936{
2937 while (*fname && !vim_ispathsep(*fname))
2938 MB_PTR_ADV(fname);
2939 if (*fname)
2940 ++fname;
2941 return fname;
2942}
2943
2944/*
2945 * Get a pointer to one character past the head of a path name.
2946 * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
2947 * If there is no head, path is returned.
2948 */
2949 char_u *
2950get_past_head(char_u *path)
2951{
2952 char_u *retval;
2953
2954#if defined(MSWIN)
2955 // may skip "c:"
Keith Thompson184f71c2024-01-04 21:19:04 +01002956 if (SAFE_isalpha(path[0]) && path[1] == ':')
Bram Moolenaar26262f82019-09-04 20:59:15 +02002957 retval = path + 2;
2958 else
2959 retval = path;
2960#else
2961# if defined(AMIGA)
2962 // may skip "label:"
2963 retval = vim_strchr(path, ':');
2964 if (retval == NULL)
2965 retval = path;
2966# else // Unix
2967 retval = path;
2968# endif
2969#endif
2970
2971 while (vim_ispathsep(*retval))
2972 ++retval;
2973
2974 return retval;
2975}
2976
2977/*
2978 * Return TRUE if 'c' is a path separator.
2979 * Note that for MS-Windows this includes the colon.
2980 */
2981 int
2982vim_ispathsep(int c)
2983{
2984#ifdef UNIX
2985 return (c == '/'); // UNIX has ':' inside file names
2986#else
2987# ifdef BACKSLASH_IN_FILENAME
2988 return (c == ':' || c == '/' || c == '\\');
2989# else
2990# ifdef VMS
2991 // server"user passwd"::device:[full.path.name]fname.extension;version"
2992 return (c == ':' || c == '[' || c == ']' || c == '/'
2993 || c == '<' || c == '>' || c == '"' );
2994# else
2995 return (c == ':' || c == '/');
2996# endif // VMS
2997# endif
2998#endif
2999}
3000
3001/*
3002 * Like vim_ispathsep(c), but exclude the colon for MS-Windows.
3003 */
3004 int
3005vim_ispathsep_nocolon(int c)
3006{
3007 return vim_ispathsep(c)
3008#ifdef BACKSLASH_IN_FILENAME
3009 && c != ':'
3010#endif
3011 ;
3012}
3013
3014/*
Bram Moolenaar26262f82019-09-04 20:59:15 +02003015 * Return TRUE if the directory of "fname" exists, FALSE otherwise.
3016 * Also returns TRUE if there is no directory name.
3017 * "fname" must be writable!.
3018 */
3019 int
3020dir_of_file_exists(char_u *fname)
3021{
3022 char_u *p;
3023 int c;
3024 int retval;
3025
3026 p = gettail_sep(fname);
3027 if (p == fname)
3028 return TRUE;
3029 c = *p;
3030 *p = NUL;
3031 retval = mch_isdir(fname);
3032 *p = c;
3033 return retval;
3034}
3035
3036/*
3037 * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally
3038 * and deal with 'fileignorecase'.
3039 */
3040 int
3041vim_fnamecmp(char_u *x, char_u *y)
3042{
3043#ifdef BACKSLASH_IN_FILENAME
3044 return vim_fnamencmp(x, y, MAXPATHL);
3045#else
3046 if (p_fic)
3047 return MB_STRICMP(x, y);
3048 return STRCMP(x, y);
3049#endif
3050}
3051
3052 int
3053vim_fnamencmp(char_u *x, char_u *y, size_t len)
3054{
3055#ifdef BACKSLASH_IN_FILENAME
3056 char_u *px = x;
3057 char_u *py = y;
3058 int cx = NUL;
3059 int cy = NUL;
3060
3061 while (len > 0)
3062 {
3063 cx = PTR2CHAR(px);
3064 cy = PTR2CHAR(py);
3065 if (cx == NUL || cy == NUL
3066 || ((p_fic ? MB_TOLOWER(cx) != MB_TOLOWER(cy) : cx != cy)
3067 && !(cx == '/' && cy == '\\')
3068 && !(cx == '\\' && cy == '/')))
3069 break;
Bram Moolenaar1614a142019-10-06 22:00:13 +02003070 len -= mb_ptr2len(px);
3071 px += mb_ptr2len(px);
3072 py += mb_ptr2len(py);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003073 }
3074 if (len == 0)
3075 return 0;
3076 return (cx - cy);
3077#else
3078 if (p_fic)
3079 return MB_STRNICMP(x, y, len);
3080 return STRNCMP(x, y, len);
3081#endif
3082}
3083
3084/*
3085 * Concatenate file names fname1 and fname2 into allocated memory.
3086 * Only add a '/' or '\\' when 'sep' is TRUE and it is necessary.
3087 */
3088 char_u *
3089concat_fnames(char_u *fname1, char_u *fname2, int sep)
3090{
3091 char_u *dest;
3092
3093 dest = alloc(STRLEN(fname1) + STRLEN(fname2) + 3);
Yegappan Lakshmanan1cfb14a2023-01-09 19:04:23 +00003094 if (dest == NULL)
3095 return NULL;
3096
3097 STRCPY(dest, fname1);
3098 if (sep)
3099 add_pathsep(dest);
3100 STRCAT(dest, fname2);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003101 return dest;
3102}
3103
3104/*
3105 * Add a path separator to a file name, unless it already ends in a path
3106 * separator.
3107 */
3108 void
3109add_pathsep(char_u *p)
3110{
3111 if (*p != NUL && !after_pathsep(p, p + STRLEN(p)))
3112 STRCAT(p, PATHSEPSTR);
3113}
3114
3115/*
3116 * FullName_save - Make an allocated copy of a full file name.
3117 * Returns NULL when out of memory.
3118 */
3119 char_u *
3120FullName_save(
3121 char_u *fname,
3122 int force) // force expansion, even when it already looks
3123 // like a full path name
3124{
3125 char_u *buf;
3126 char_u *new_fname = NULL;
3127
3128 if (fname == NULL)
3129 return NULL;
3130
3131 buf = alloc(MAXPATHL);
Yegappan Lakshmanan1cfb14a2023-01-09 19:04:23 +00003132 if (buf == NULL)
3133 return NULL;
3134
3135 if (vim_FullName(fname, buf, MAXPATHL, force) != FAIL)
3136 new_fname = vim_strsave(buf);
3137 else
3138 new_fname = vim_strsave(fname);
3139 vim_free(buf);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003140 return new_fname;
3141}
3142
3143/*
3144 * return TRUE if "fname" exists.
3145 */
3146 int
3147vim_fexists(char_u *fname)
3148{
3149 stat_T st;
3150
3151 if (mch_stat((char *)fname, &st))
3152 return FALSE;
3153 return TRUE;
3154}
3155
3156/*
3157 * Invoke expand_wildcards() for one pattern.
3158 * Expand items like "%:h" before the expansion.
3159 * Returns OK or FAIL.
3160 */
3161 int
3162expand_wildcards_eval(
3163 char_u **pat, // pointer to input pattern
3164 int *num_file, // resulting number of files
3165 char_u ***file, // array of resulting files
3166 int flags) // EW_DIR, etc.
3167{
3168 int ret = FAIL;
3169 char_u *eval_pat = NULL;
3170 char_u *exp_pat = *pat;
Bram Moolenaarf5724372022-09-02 19:45:15 +01003171 char *ignored_msg;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003172 int usedlen;
Bram Moolenaarf5724372022-09-02 19:45:15 +01003173 int is_cur_alt_file = *exp_pat == '%' || *exp_pat == '#';
3174 int star_follows = FALSE;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003175
Bram Moolenaarf5724372022-09-02 19:45:15 +01003176 if (is_cur_alt_file || *exp_pat == '<')
Bram Moolenaar26262f82019-09-04 20:59:15 +02003177 {
3178 ++emsg_off;
3179 eval_pat = eval_vars(exp_pat, exp_pat, &usedlen,
Bram Moolenaara96edb72022-04-28 17:52:24 +01003180 NULL, &ignored_msg, NULL, TRUE);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003181 --emsg_off;
3182 if (eval_pat != NULL)
Bram Moolenaarf5724372022-09-02 19:45:15 +01003183 {
3184 star_follows = STRCMP(exp_pat + usedlen, "*") == 0;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003185 exp_pat = concat_str(eval_pat, exp_pat + usedlen);
Bram Moolenaarf5724372022-09-02 19:45:15 +01003186 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02003187 }
3188
3189 if (exp_pat != NULL)
3190 ret = expand_wildcards(1, &exp_pat, num_file, file, flags);
3191
3192 if (eval_pat != NULL)
3193 {
Bram Moolenaarf5724372022-09-02 19:45:15 +01003194 if (*num_file == 0 && is_cur_alt_file && star_follows)
3195 {
3196 // Expanding "%" or "#" and the file does not exist: Add the
3197 // pattern anyway (without the star) so that this works for remote
3198 // files and non-file buffer names.
3199 *file = ALLOC_ONE(char_u *);
3200 if (*file != NULL)
3201 {
3202 **file = eval_pat;
3203 eval_pat = NULL;
3204 *num_file = 1;
3205 ret = OK;
3206 }
3207 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02003208 vim_free(exp_pat);
3209 vim_free(eval_pat);
3210 }
3211
3212 return ret;
3213}
3214
3215/*
3216 * Expand wildcards. Calls gen_expand_wildcards() and removes files matching
3217 * 'wildignore'.
3218 * Returns OK or FAIL. When FAIL then "num_files" won't be set.
3219 */
3220 int
3221expand_wildcards(
3222 int num_pat, // number of input patterns
3223 char_u **pat, // array of input patterns
3224 int *num_files, // resulting number of files
3225 char_u ***files, // array of resulting files
3226 int flags) // EW_DIR, etc.
3227{
3228 int retval;
3229 int i, j;
3230 char_u *p;
3231 int non_suf_match; // number without matching suffix
3232
3233 retval = gen_expand_wildcards(num_pat, pat, num_files, files, flags);
3234
3235 // When keeping all matches, return here
3236 if ((flags & EW_KEEPALL) || retval == FAIL)
3237 return retval;
3238
Bram Moolenaar26262f82019-09-04 20:59:15 +02003239 /*
3240 * Remove names that match 'wildignore'.
3241 */
3242 if (*p_wig)
3243 {
3244 char_u *ffname;
3245
3246 // check all files in (*files)[]
3247 for (i = 0; i < *num_files; ++i)
3248 {
3249 ffname = FullName_save((*files)[i], FALSE);
3250 if (ffname == NULL) // out of memory
3251 break;
3252# ifdef VMS
3253 vms_remove_version(ffname);
3254# endif
3255 if (match_file_list(p_wig, (*files)[i], ffname))
3256 {
3257 // remove this matching file from the list
3258 vim_free((*files)[i]);
3259 for (j = i; j + 1 < *num_files; ++j)
3260 (*files)[j] = (*files)[j + 1];
3261 --*num_files;
3262 --i;
3263 }
3264 vim_free(ffname);
3265 }
3266
3267 // If the number of matches is now zero, we fail.
3268 if (*num_files == 0)
3269 {
3270 VIM_CLEAR(*files);
3271 return FAIL;
3272 }
3273 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02003274
3275 /*
3276 * Move the names where 'suffixes' match to the end.
Bram Moolenaar57e95172022-08-20 19:26:14 +01003277 * Skip when interrupted, the result probably won't be used.
Bram Moolenaar26262f82019-09-04 20:59:15 +02003278 */
Bram Moolenaar57e95172022-08-20 19:26:14 +01003279 if (*num_files > 1 && !got_int)
Bram Moolenaar26262f82019-09-04 20:59:15 +02003280 {
3281 non_suf_match = 0;
3282 for (i = 0; i < *num_files; ++i)
3283 {
3284 if (!match_suffix((*files)[i]))
3285 {
3286 /*
3287 * Move the name without matching suffix to the front
3288 * of the list.
3289 */
3290 p = (*files)[i];
3291 for (j = i; j > non_suf_match; --j)
3292 (*files)[j] = (*files)[j - 1];
3293 (*files)[non_suf_match++] = p;
3294 }
3295 }
3296 }
3297
3298 return retval;
3299}
3300
3301/*
3302 * Return TRUE if "fname" matches with an entry in 'suffixes'.
3303 */
3304 int
3305match_suffix(char_u *fname)
3306{
3307 int fnamelen, setsuflen;
3308 char_u *setsuf;
3309#define MAXSUFLEN 30 // maximum length of a file suffix
3310 char_u suf_buf[MAXSUFLEN];
3311
3312 fnamelen = (int)STRLEN(fname);
3313 setsuflen = 0;
3314 for (setsuf = p_su; *setsuf; )
3315 {
3316 setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
3317 if (setsuflen == 0)
3318 {
3319 char_u *tail = gettail(fname);
3320
3321 // empty entry: match name without a '.'
3322 if (vim_strchr(tail, '.') == NULL)
3323 {
3324 setsuflen = 1;
3325 break;
3326 }
3327 }
3328 else
3329 {
3330 if (fnamelen >= setsuflen
3331 && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
3332 (size_t)setsuflen) == 0)
3333 break;
3334 setsuflen = 0;
3335 }
3336 }
3337 return (setsuflen != 0);
3338}
3339
3340#ifdef VIM_BACKTICK
3341
3342/*
3343 * Return TRUE if we can expand this backtick thing here.
3344 */
3345 static int
3346vim_backtick(char_u *p)
3347{
3348 return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
3349}
3350
3351/*
3352 * Expand an item in `backticks` by executing it as a command.
3353 * Currently only works when pat[] starts and ends with a `.
3354 * Returns number of file names found, -1 if an error is encountered.
3355 */
3356 static int
3357expand_backtick(
3358 garray_T *gap,
3359 char_u *pat,
3360 int flags) // EW_* flags
3361{
3362 char_u *p;
3363 char_u *cmd;
3364 char_u *buffer;
3365 int cnt = 0;
3366 int i;
3367
3368 // Create the command: lop off the backticks.
Bram Moolenaar71ccd032020-06-12 22:59:11 +02003369 cmd = vim_strnsave(pat + 1, STRLEN(pat) - 2);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003370 if (cmd == NULL)
3371 return -1;
3372
3373#ifdef FEAT_EVAL
3374 if (*cmd == '=') // `={expr}`: Expand expression
Bram Moolenaara4e0b972022-10-01 19:43:52 +01003375 buffer = eval_to_string(cmd + 1, TRUE, FALSE);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003376 else
3377#endif
3378 buffer = get_cmd_output(cmd, NULL,
3379 (flags & EW_SILENT) ? SHELL_SILENT : 0, NULL);
3380 vim_free(cmd);
3381 if (buffer == NULL)
3382 return -1;
3383
3384 cmd = buffer;
3385 while (*cmd != NUL)
3386 {
3387 cmd = skipwhite(cmd); // skip over white space
3388 p = cmd;
3389 while (*p != NUL && *p != '\r' && *p != '\n') // skip over entry
3390 ++p;
3391 // add an entry if it is not empty
3392 if (p > cmd)
3393 {
3394 i = *p;
3395 *p = NUL;
3396 addfile(gap, cmd, flags);
3397 *p = i;
3398 ++cnt;
3399 }
3400 cmd = p;
3401 while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
3402 ++cmd;
3403 }
3404
3405 vim_free(buffer);
3406 return cnt;
3407}
3408#endif // VIM_BACKTICK
3409
3410#if defined(MSWIN)
3411/*
3412 * File name expansion code for MS-DOS, Win16 and Win32. It's here because
3413 * it's shared between these systems.
3414 */
3415
3416/*
3417 * comparison function for qsort in dos_expandpath()
3418 */
3419 static int
3420pstrcmp(const void *a, const void *b)
3421{
3422 return (pathcmp(*(char **)a, *(char **)b, -1));
3423}
3424
3425/*
3426 * Recursively expand one path component into all matching files and/or
3427 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
3428 * Return the number of matches found.
3429 * "path" has backslashes before chars that are not to be expanded, starting
3430 * at "path[wildoff]".
3431 * Return the number of matches found.
3432 * NOTE: much of this is identical to unix_expandpath(), keep in sync!
3433 */
3434 static int
3435dos_expandpath(
3436 garray_T *gap,
3437 char_u *path,
3438 int wildoff,
3439 int flags, // EW_* flags
3440 int didstar) // expanded "**" once already
3441{
3442 char_u *buf;
3443 char_u *path_end;
3444 char_u *p, *s, *e;
3445 int start_len = gap->ga_len;
3446 char_u *pat;
3447 regmatch_T regmatch;
3448 int starts_with_dot;
3449 int matches;
3450 int len;
3451 int starstar = FALSE;
3452 static int stardepth = 0; // depth for "**" expansion
3453 HANDLE hFind = INVALID_HANDLE_VALUE;
3454 WIN32_FIND_DATAW wfb;
3455 WCHAR *wn = NULL; // UCS-2 name, NULL when not used.
3456 char_u *matchname;
3457 int ok;
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003458 char_u *p_alt;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003459
3460 // Expanding "**" may take a long time, check for CTRL-C.
3461 if (stardepth > 0)
3462 {
3463 ui_breakcheck();
3464 if (got_int)
3465 return 0;
3466 }
3467
3468 // Make room for file name. When doing encoding conversion the actual
3469 // length may be quite a bit longer, thus use the maximum possible length.
3470 buf = alloc(MAXPATHL);
3471 if (buf == NULL)
3472 return 0;
3473
3474 /*
3475 * Find the first part in the path name that contains a wildcard or a ~1.
3476 * Copy it into buf, including the preceding characters.
3477 */
3478 p = buf;
3479 s = buf;
3480 e = NULL;
3481 path_end = path;
3482 while (*path_end != NUL)
3483 {
3484 // May ignore a wildcard that has a backslash before it; it will
3485 // be removed by rem_backslash() or file_pat_to_reg_pat() below.
3486 if (path_end >= path + wildoff && rem_backslash(path_end))
3487 *p++ = *path_end++;
3488 else if (*path_end == '\\' || *path_end == ':' || *path_end == '/')
3489 {
3490 if (e != NULL)
3491 break;
3492 s = p + 1;
3493 }
3494 else if (path_end >= path + wildoff
3495 && vim_strchr((char_u *)"*?[~", *path_end) != NULL)
3496 e = p;
3497 if (has_mbyte)
3498 {
3499 len = (*mb_ptr2len)(path_end);
3500 STRNCPY(p, path_end, len);
3501 p += len;
3502 path_end += len;
3503 }
3504 else
3505 *p++ = *path_end++;
3506 }
3507 e = p;
3508 *e = NUL;
3509
3510 // now we have one wildcard component between s and e
3511 // Remove backslashes between "wildoff" and the start of the wildcard
3512 // component.
3513 for (p = buf + wildoff; p < s; ++p)
3514 if (rem_backslash(p))
3515 {
3516 STRMOVE(p, p + 1);
3517 --e;
3518 --s;
3519 }
3520
3521 // Check for "**" between "s" and "e".
3522 for (p = s; p < e; ++p)
3523 if (p[0] == '*' && p[1] == '*')
3524 starstar = TRUE;
3525
3526 starts_with_dot = *s == '.';
3527 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
3528 if (pat == NULL)
3529 {
3530 vim_free(buf);
3531 return 0;
3532 }
3533
3534 // compile the regexp into a program
3535 if (flags & (EW_NOERROR | EW_NOTWILD))
3536 ++emsg_silent;
3537 regmatch.rm_ic = TRUE; // Always ignore case
3538 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
3539 if (flags & (EW_NOERROR | EW_NOTWILD))
3540 --emsg_silent;
3541 vim_free(pat);
3542
3543 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
3544 {
3545 vim_free(buf);
3546 return 0;
3547 }
3548
3549 // remember the pattern or file name being looked for
3550 matchname = vim_strsave(s);
3551
3552 // If "**" is by itself, this is the first time we encounter it and more
3553 // is following then find matches without any directory.
3554 if (!didstar && stardepth < 100 && starstar && e - s == 2
3555 && *path_end == '/')
3556 {
3557 STRCPY(s, path_end + 1);
3558 ++stardepth;
3559 (void)dos_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
3560 --stardepth;
3561 }
3562
3563 // Scan all files in the directory with "dir/ *.*"
3564 STRCPY(s, "*.*");
3565 wn = enc_to_utf16(buf, NULL);
3566 if (wn != NULL)
3567 hFind = FindFirstFileW(wn, &wfb);
3568 ok = (hFind != INVALID_HANDLE_VALUE);
3569
3570 while (ok)
3571 {
3572 p = utf16_to_enc(wfb.cFileName, NULL); // p is allocated here
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003573
Bram Moolenaar26262f82019-09-04 20:59:15 +02003574 if (p == NULL)
3575 break; // out of memory
3576
Bram Moolenaar0dc5f602021-02-07 14:01:35 +01003577 // Do not use the alternate filename when the file name ends in '~',
3578 // because it picks up backup files: short name for "foo.vim~" is
3579 // "foo~1.vim", which matches "*.vim".
3580 if (*wfb.cAlternateFileName == NUL || p[STRLEN(p) - 1] == '~')
Bram Moolenaar40655d52020-04-06 23:49:50 +02003581 p_alt = NULL;
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003582 else
3583 p_alt = utf16_to_enc(wfb.cAlternateFileName, NULL);
3584
Bram Moolenaar26262f82019-09-04 20:59:15 +02003585 // Ignore entries starting with a dot, unless when asked for. Accept
3586 // all entries found with "matchname".
3587 if ((p[0] != '.' || starts_with_dot
3588 || ((flags & EW_DODOT)
3589 && p[1] != NUL && (p[1] != '.' || p[2] != NUL)))
3590 && (matchname == NULL
3591 || (regmatch.regprog != NULL
Bram Moolenaar40655d52020-04-06 23:49:50 +02003592 && (vim_regexec(&regmatch, p, (colnr_T)0)
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003593 || (p_alt != NULL
Bram Moolenaar40655d52020-04-06 23:49:50 +02003594 && vim_regexec(&regmatch, p_alt, (colnr_T)0))))
Bram Moolenaar26262f82019-09-04 20:59:15 +02003595 || ((flags & EW_NOTWILD)
3596 && fnamencmp(path + (s - buf), p, e - s) == 0)))
3597 {
3598 STRCPY(s, p);
3599 len = (int)STRLEN(buf);
3600
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003601 if (starstar && stardepth < 100
3602 && (wfb.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
Bram Moolenaar26262f82019-09-04 20:59:15 +02003603 {
3604 // For "**" in the pattern first go deeper in the tree to
3605 // find matches.
3606 STRCPY(buf + len, "/**");
3607 STRCPY(buf + len + 3, path_end);
3608 ++stardepth;
3609 (void)dos_expandpath(gap, buf, len + 1, flags, TRUE);
3610 --stardepth;
3611 }
3612
3613 STRCPY(buf + len, path_end);
3614 if (mch_has_exp_wildcard(path_end))
3615 {
3616 // need to expand another component of the path
3617 // remove backslashes for the remaining components only
3618 (void)dos_expandpath(gap, buf, len + 1, flags, FALSE);
3619 }
3620 else
3621 {
3622 // no more wildcards, check if there is a match
3623 // remove backslashes for the remaining components only
3624 if (*path_end != 0)
3625 backslash_halve(buf + len + 1);
3626 if (mch_getperm(buf) >= 0) // add existing file
3627 addfile(gap, buf, flags);
3628 }
3629 }
3630
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003631 vim_free(p_alt);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003632 vim_free(p);
3633 ok = FindNextFileW(hFind, &wfb);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003634 }
3635
3636 FindClose(hFind);
3637 vim_free(wn);
3638 vim_free(buf);
3639 vim_regfree(regmatch.regprog);
3640 vim_free(matchname);
3641
3642 matches = gap->ga_len - start_len;
3643 if (matches > 0)
3644 qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
3645 sizeof(char_u *), pstrcmp);
3646 return matches;
3647}
3648
3649 int
3650mch_expandpath(
3651 garray_T *gap,
3652 char_u *path,
3653 int flags) // EW_* flags
3654{
3655 return dos_expandpath(gap, path, 0, flags, FALSE);
3656}
3657#endif // MSWIN
3658
3659#if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \
3660 || defined(PROTO)
3661/*
3662 * Unix style wildcard expansion code.
3663 * It's here because it's used both for Unix and Mac.
3664 */
3665 static int
3666pstrcmp(const void *a, const void *b)
3667{
3668 return (pathcmp(*(char **)a, *(char **)b, -1));
3669}
3670
3671/*
3672 * Recursively expand one path component into all matching files and/or
3673 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
3674 * "path" has backslashes before chars that are not to be expanded, starting
3675 * at "path + wildoff".
3676 * Return the number of matches found.
3677 * NOTE: much of this is identical to dos_expandpath(), keep in sync!
3678 */
3679 int
3680unix_expandpath(
3681 garray_T *gap,
3682 char_u *path,
3683 int wildoff,
3684 int flags, // EW_* flags
3685 int didstar) // expanded "**" once already
3686{
3687 char_u *buf;
3688 char_u *path_end;
3689 char_u *p, *s, *e;
3690 int start_len = gap->ga_len;
3691 char_u *pat;
3692 regmatch_T regmatch;
3693 int starts_with_dot;
3694 int matches;
3695 int len;
3696 int starstar = FALSE;
3697 static int stardepth = 0; // depth for "**" expansion
3698
3699 DIR *dirp;
3700 struct dirent *dp;
3701
3702 // Expanding "**" may take a long time, check for CTRL-C.
3703 if (stardepth > 0)
3704 {
3705 ui_breakcheck();
3706 if (got_int)
3707 return 0;
3708 }
3709
Yee Cheng China7767072023-04-16 20:13:12 +01003710 // make room for file name (a bit too much to stay on the safe side)
3711 size_t buflen = STRLEN(path) + MAXPATHL;
Bram Moolenaar386c24c2022-05-16 12:37:36 +01003712 buf = alloc(buflen);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003713 if (buf == NULL)
3714 return 0;
3715
3716 /*
3717 * Find the first part in the path name that contains a wildcard.
3718 * When EW_ICASE is set every letter is considered to be a wildcard.
3719 * Copy it into "buf", including the preceding characters.
3720 */
3721 p = buf;
3722 s = buf;
3723 e = NULL;
3724 path_end = path;
3725 while (*path_end != NUL)
3726 {
3727 // May ignore a wildcard that has a backslash before it; it will
3728 // be removed by rem_backslash() or file_pat_to_reg_pat() below.
3729 if (path_end >= path + wildoff && rem_backslash(path_end))
3730 *p++ = *path_end++;
3731 else if (*path_end == '/')
3732 {
3733 if (e != NULL)
3734 break;
3735 s = p + 1;
3736 }
3737 else if (path_end >= path + wildoff
3738 && (vim_strchr((char_u *)"*?[{~$", *path_end) != NULL
3739 || (!p_fic && (flags & EW_ICASE)
Bram Moolenaar5921aeb2022-02-19 11:20:12 +00003740 && vim_isalpha(PTR2CHAR(path_end)))))
Bram Moolenaar26262f82019-09-04 20:59:15 +02003741 e = p;
3742 if (has_mbyte)
3743 {
3744 len = (*mb_ptr2len)(path_end);
3745 STRNCPY(p, path_end, len);
3746 p += len;
3747 path_end += len;
3748 }
3749 else
3750 *p++ = *path_end++;
3751 }
3752 e = p;
3753 *e = NUL;
3754
3755 // Now we have one wildcard component between "s" and "e".
3756 // Remove backslashes between "wildoff" and the start of the wildcard
3757 // component.
3758 for (p = buf + wildoff; p < s; ++p)
3759 if (rem_backslash(p))
3760 {
3761 STRMOVE(p, p + 1);
3762 --e;
3763 --s;
3764 }
3765
3766 // Check for "**" between "s" and "e".
3767 for (p = s; p < e; ++p)
3768 if (p[0] == '*' && p[1] == '*')
3769 starstar = TRUE;
3770
3771 // convert the file pattern to a regexp pattern
3772 starts_with_dot = *s == '.';
3773 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
3774 if (pat == NULL)
3775 {
3776 vim_free(buf);
3777 return 0;
3778 }
3779
3780 // compile the regexp into a program
3781 if (flags & EW_ICASE)
3782 regmatch.rm_ic = TRUE; // 'wildignorecase' set
3783 else
3784 regmatch.rm_ic = p_fic; // ignore case when 'fileignorecase' is set
3785 if (flags & (EW_NOERROR | EW_NOTWILD))
3786 ++emsg_silent;
3787 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
3788 if (flags & (EW_NOERROR | EW_NOTWILD))
3789 --emsg_silent;
3790 vim_free(pat);
3791
3792 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
3793 {
3794 vim_free(buf);
3795 return 0;
3796 }
3797
3798 // If "**" is by itself, this is the first time we encounter it and more
3799 // is following then find matches without any directory.
3800 if (!didstar && stardepth < 100 && starstar && e - s == 2
3801 && *path_end == '/')
3802 {
3803 STRCPY(s, path_end + 1);
3804 ++stardepth;
3805 (void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
3806 --stardepth;
3807 }
3808
3809 // open the directory for scanning
3810 *s = NUL;
3811 dirp = opendir(*buf == NUL ? "." : (char *)buf);
3812
3813 // Find all matching entries
3814 if (dirp != NULL)
3815 {
Bram Moolenaar57e95172022-08-20 19:26:14 +01003816 while (!got_int)
Bram Moolenaar26262f82019-09-04 20:59:15 +02003817 {
3818 dp = readdir(dirp);
3819 if (dp == NULL)
3820 break;
3821 if ((dp->d_name[0] != '.' || starts_with_dot
3822 || ((flags & EW_DODOT)
3823 && dp->d_name[1] != NUL
3824 && (dp->d_name[1] != '.' || dp->d_name[2] != NUL)))
3825 && ((regmatch.regprog != NULL && vim_regexec(&regmatch,
3826 (char_u *)dp->d_name, (colnr_T)0))
3827 || ((flags & EW_NOTWILD)
3828 && fnamencmp(path + (s - buf), dp->d_name, e - s) == 0)))
3829 {
Yee Cheng China7767072023-04-16 20:13:12 +01003830 vim_strncpy(s, (char_u *)dp->d_name, buflen - (s - buf) - 1);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003831 len = STRLEN(buf);
3832
3833 if (starstar && stardepth < 100)
3834 {
3835 // For "**" in the pattern first go deeper in the tree to
3836 // find matches.
Bram Moolenaar386c24c2022-05-16 12:37:36 +01003837 vim_snprintf((char *)buf + len, buflen - len,
3838 "/**%s", path_end);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003839 ++stardepth;
3840 (void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
3841 --stardepth;
3842 }
3843
Bram Moolenaar386c24c2022-05-16 12:37:36 +01003844 vim_snprintf((char *)buf + len, buflen - len, "%s", path_end);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003845 if (mch_has_exp_wildcard(path_end)) // handle more wildcards
3846 {
3847 // need to expand another component of the path
3848 // remove backslashes for the remaining components only
3849 (void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
3850 }
3851 else
3852 {
3853 stat_T sb;
3854
3855 // no more wildcards, check if there is a match
3856 // remove backslashes for the remaining components only
3857 if (*path_end != NUL)
3858 backslash_halve(buf + len + 1);
3859 // add existing file or symbolic link
3860 if ((flags & EW_ALLLINKS) ? mch_lstat((char *)buf, &sb) >= 0
3861 : mch_getperm(buf) >= 0)
3862 {
3863#ifdef MACOS_CONVERT
3864 size_t precomp_len = STRLEN(buf)+1;
3865 char_u *precomp_buf =
3866 mac_precompose_path(buf, precomp_len, &precomp_len);
3867
3868 if (precomp_buf)
3869 {
3870 mch_memmove(buf, precomp_buf, precomp_len);
3871 vim_free(precomp_buf);
3872 }
3873#endif
3874 addfile(gap, buf, flags);
3875 }
3876 }
3877 }
3878 }
3879
3880 closedir(dirp);
3881 }
3882
3883 vim_free(buf);
3884 vim_regfree(regmatch.regprog);
3885
Bram Moolenaar57e95172022-08-20 19:26:14 +01003886 // When interrupted the matches probably won't be used and sorting can be
3887 // slow, thus skip it.
Bram Moolenaar26262f82019-09-04 20:59:15 +02003888 matches = gap->ga_len - start_len;
Bram Moolenaar57e95172022-08-20 19:26:14 +01003889 if (matches > 0 && !got_int)
Bram Moolenaar26262f82019-09-04 20:59:15 +02003890 qsort(((char_u **)gap->ga_data) + start_len, matches,
3891 sizeof(char_u *), pstrcmp);
3892 return matches;
3893}
3894#endif
3895
3896/*
3897 * Return TRUE if "p" contains what looks like an environment variable.
3898 * Allowing for escaping.
3899 */
3900 static int
3901has_env_var(char_u *p)
3902{
3903 for ( ; *p; MB_PTR_ADV(p))
3904 {
3905 if (*p == '\\' && p[1] != NUL)
3906 ++p;
3907 else if (vim_strchr((char_u *)
3908#if defined(MSWIN)
3909 "$%"
3910#else
3911 "$"
3912#endif
3913 , *p) != NULL)
3914 return TRUE;
3915 }
3916 return FALSE;
3917}
3918
3919#ifdef SPECIAL_WILDCHAR
3920/*
3921 * Return TRUE if "p" contains a special wildcard character, one that Vim
3922 * cannot expand, requires using a shell.
3923 */
3924 static int
3925has_special_wildchar(char_u *p)
3926{
3927 for ( ; *p; MB_PTR_ADV(p))
3928 {
3929 // Disallow line break characters.
3930 if (*p == '\r' || *p == '\n')
3931 break;
3932 // Allow for escaping.
3933 if (*p == '\\' && p[1] != NUL && p[1] != '\r' && p[1] != '\n')
3934 ++p;
3935 else if (vim_strchr((char_u *)SPECIAL_WILDCHAR, *p) != NULL)
3936 {
3937 // A { must be followed by a matching }.
3938 if (*p == '{' && vim_strchr(p, '}') == NULL)
3939 continue;
3940 // A quote and backtick must be followed by another one.
3941 if ((*p == '`' || *p == '\'') && vim_strchr(p, *p) == NULL)
3942 continue;
3943 return TRUE;
3944 }
3945 }
3946 return FALSE;
3947}
3948#endif
3949
3950/*
3951 * Generic wildcard expansion code.
3952 *
3953 * Characters in "pat" that should not be expanded must be preceded with a
3954 * backslash. E.g., "/path\ with\ spaces/my\*star*"
3955 *
3956 * Return FAIL when no single file was found. In this case "num_file" is not
3957 * set, and "file" may contain an error message.
3958 * Return OK when some files found. "num_file" is set to the number of
3959 * matches, "file" to the array of matches. Call FreeWild() later.
3960 */
3961 int
3962gen_expand_wildcards(
3963 int num_pat, // number of input patterns
3964 char_u **pat, // array of input patterns
3965 int *num_file, // resulting number of files
3966 char_u ***file, // array of resulting files
3967 int flags) // EW_* flags
3968{
3969 int i;
3970 garray_T ga;
3971 char_u *p;
3972 static int recursive = FALSE;
3973 int add_pat;
3974 int retval = OK;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003975 int did_expand_in_path = FALSE;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003976
3977 /*
3978 * expand_env() is called to expand things like "~user". If this fails,
3979 * it calls ExpandOne(), which brings us back here. In this case, always
3980 * call the machine specific expansion function, if possible. Otherwise,
3981 * return FAIL.
3982 */
3983 if (recursive)
3984#ifdef SPECIAL_WILDCHAR
3985 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
3986#else
3987 return FAIL;
3988#endif
3989
3990#ifdef SPECIAL_WILDCHAR
3991 /*
3992 * If there are any special wildcard characters which we cannot handle
3993 * here, call machine specific function for all the expansion. This
3994 * avoids starting the shell for each argument separately.
3995 * For `=expr` do use the internal function.
3996 */
3997 for (i = 0; i < num_pat; i++)
3998 {
3999 if (has_special_wildchar(pat[i])
4000# ifdef VIM_BACKTICK
4001 && !(vim_backtick(pat[i]) && pat[i][1] == '=')
4002# endif
4003 )
4004 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
4005 }
4006#endif
4007
4008 recursive = TRUE;
4009
4010 /*
4011 * The matching file names are stored in a growarray. Init it empty.
4012 */
Bram Moolenaar04935fb2022-01-08 16:19:22 +00004013 ga_init2(&ga, sizeof(char_u *), 30);
Bram Moolenaar26262f82019-09-04 20:59:15 +02004014
Bram Moolenaar57e95172022-08-20 19:26:14 +01004015 for (i = 0; i < num_pat && !got_int; ++i)
Bram Moolenaar26262f82019-09-04 20:59:15 +02004016 {
4017 add_pat = -1;
4018 p = pat[i];
4019
4020#ifdef VIM_BACKTICK
4021 if (vim_backtick(p))
4022 {
4023 add_pat = expand_backtick(&ga, p, flags);
4024 if (add_pat == -1)
4025 retval = FAIL;
4026 }
4027 else
4028#endif
4029 {
4030 /*
4031 * First expand environment variables, "~/" and "~user/".
4032 */
4033 if ((has_env_var(p) && !(flags & EW_NOTENV)) || *p == '~')
4034 {
4035 p = expand_env_save_opt(p, TRUE);
4036 if (p == NULL)
4037 p = pat[i];
4038#ifdef UNIX
4039 /*
4040 * On Unix, if expand_env() can't expand an environment
4041 * variable, use the shell to do that. Discard previously
4042 * found file names and start all over again.
4043 */
4044 else if (has_env_var(p) || *p == '~')
4045 {
4046 vim_free(p);
4047 ga_clear_strings(&ga);
4048 i = mch_expand_wildcards(num_pat, pat, num_file, file,
4049 flags|EW_KEEPDOLLAR);
4050 recursive = FALSE;
4051 return i;
4052 }
4053#endif
4054 }
4055
4056 /*
LemonBoya3157a42022-04-03 11:58:31 +01004057 * If there are wildcards or case-insensitive expansion is
4058 * required: Expand file names and add each match to the list. If
4059 * there is no match, and EW_NOTFOUND is given, add the pattern.
4060 * Otherwise: Add the file name if it exists or when EW_NOTFOUND is
4061 * given.
Bram Moolenaar26262f82019-09-04 20:59:15 +02004062 */
LemonBoya3157a42022-04-03 11:58:31 +01004063 if (mch_has_exp_wildcard(p) || (flags & EW_ICASE))
Bram Moolenaar26262f82019-09-04 20:59:15 +02004064 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02004065 if ((flags & EW_PATH)
4066 && !mch_isFullName(p)
4067 && !(p[0] == '.'
4068 && (vim_ispathsep(p[1])
4069 || (p[1] == '.' && vim_ispathsep(p[2]))))
4070 )
4071 {
4072 // :find completion where 'path' is used.
4073 // Recursiveness is OK here.
4074 recursive = FALSE;
4075 add_pat = expand_in_path(&ga, p, flags);
4076 recursive = TRUE;
4077 did_expand_in_path = TRUE;
4078 }
4079 else
Bram Moolenaar26262f82019-09-04 20:59:15 +02004080 add_pat = mch_expandpath(&ga, p, flags);
4081 }
4082 }
4083
4084 if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
4085 {
4086 char_u *t = backslash_halve_save(p);
4087
4088 // When EW_NOTFOUND is used, always add files and dirs. Makes
4089 // "vim c:/" work.
4090 if (flags & EW_NOTFOUND)
4091 addfile(&ga, t, flags | EW_DIR | EW_FILE);
4092 else
4093 addfile(&ga, t, flags);
4094
4095 if (t != p)
4096 vim_free(t);
4097 }
4098
Bram Moolenaar26262f82019-09-04 20:59:15 +02004099 if (did_expand_in_path && ga.ga_len > 0 && (flags & EW_PATH))
4100 uniquefy_paths(&ga, p);
Bram Moolenaar26262f82019-09-04 20:59:15 +02004101 if (p != pat[i])
4102 vim_free(p);
4103 }
4104
Bram Moolenaar566cc8c2020-06-29 21:14:51 +02004105 // When returning FAIL the array must be freed here.
4106 if (retval == FAIL)
Yegappan Lakshmanan2b74b682022-04-03 21:30:32 +01004107 ga_clear_strings(&ga);
Bram Moolenaar566cc8c2020-06-29 21:14:51 +02004108
Bram Moolenaar26262f82019-09-04 20:59:15 +02004109 *num_file = ga.ga_len;
Bram Moolenaar566cc8c2020-06-29 21:14:51 +02004110 *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data
4111 : (char_u **)_("no matches");
Bram Moolenaar26262f82019-09-04 20:59:15 +02004112
4113 recursive = FALSE;
4114
4115 return ((flags & EW_EMPTYOK) || ga.ga_data != NULL) ? retval : FAIL;
4116}
4117
4118/*
4119 * Add a file to a file list. Accepted flags:
4120 * EW_DIR add directories
4121 * EW_FILE add files
4122 * EW_EXEC add executable files
4123 * EW_NOTFOUND add even when it doesn't exist
4124 * EW_ADDSLASH add slash after directory name
4125 * EW_ALLLINKS add symlink also when the referred file does not exist
4126 */
4127 void
4128addfile(
4129 garray_T *gap,
Bram Moolenaar217e1b82019-12-01 21:41:28 +01004130 char_u *f, // filename
Bram Moolenaar26262f82019-09-04 20:59:15 +02004131 int flags)
4132{
4133 char_u *p;
4134 int isdir;
4135 stat_T sb;
4136
4137 // if the file/dir/link doesn't exist, may not add it
4138 if (!(flags & EW_NOTFOUND) && ((flags & EW_ALLLINKS)
4139 ? mch_lstat((char *)f, &sb) < 0 : mch_getperm(f) < 0))
4140 return;
4141
4142#ifdef FNAME_ILLEGAL
4143 // if the file/dir contains illegal characters, don't add it
4144 if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
4145 return;
4146#endif
4147
4148 isdir = mch_isdir(f);
4149 if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
4150 return;
4151
4152 // If the file isn't executable, may not add it. Do accept directories.
4153 // When invoked from expand_shellcmd() do not use $PATH.
4154 if (!isdir && (flags & EW_EXEC)
4155 && !mch_can_exe(f, NULL, !(flags & EW_SHELLCMD)))
4156 return;
4157
4158 // Make room for another item in the file list.
4159 if (ga_grow(gap, 1) == FAIL)
4160 return;
4161
4162 p = alloc(STRLEN(f) + 1 + isdir);
4163 if (p == NULL)
4164 return;
4165
4166 STRCPY(p, f);
4167#ifdef BACKSLASH_IN_FILENAME
4168 slash_adjust(p);
4169#endif
4170 /*
4171 * Append a slash or backslash after directory names if none is present.
4172 */
Bram Moolenaar26262f82019-09-04 20:59:15 +02004173 if (isdir && (flags & EW_ADDSLASH))
4174 add_pathsep(p);
Bram Moolenaar26262f82019-09-04 20:59:15 +02004175 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
4176}
4177
4178/*
4179 * Free the list of files returned by expand_wildcards() or other expansion
4180 * functions.
4181 */
4182 void
4183FreeWild(int count, char_u **files)
4184{
4185 if (count <= 0 || files == NULL)
4186 return;
4187 while (count--)
4188 vim_free(files[count]);
4189 vim_free(files);
4190}
4191
4192/*
4193 * Compare path "p[]" to "q[]".
4194 * If "maxlen" >= 0 compare "p[maxlen]" to "q[maxlen]"
4195 * Return value like strcmp(p, q), but consider path separators.
4196 */
4197 int
4198pathcmp(const char *p, const char *q, int maxlen)
4199{
4200 int i, j;
4201 int c1, c2;
4202 const char *s = NULL;
4203
4204 for (i = 0, j = 0; maxlen < 0 || (i < maxlen && j < maxlen);)
4205 {
4206 c1 = PTR2CHAR((char_u *)p + i);
4207 c2 = PTR2CHAR((char_u *)q + j);
4208
4209 // End of "p": check if "q" also ends or just has a slash.
4210 if (c1 == NUL)
4211 {
4212 if (c2 == NUL) // full match
4213 return 0;
4214 s = q;
4215 i = j;
4216 break;
4217 }
4218
4219 // End of "q": check if "p" just has a slash.
4220 if (c2 == NUL)
4221 {
4222 s = p;
4223 break;
4224 }
4225
4226 if ((p_fic ? MB_TOUPPER(c1) != MB_TOUPPER(c2) : c1 != c2)
4227#ifdef BACKSLASH_IN_FILENAME
4228 // consider '/' and '\\' to be equal
4229 && !((c1 == '/' && c2 == '\\')
4230 || (c1 == '\\' && c2 == '/'))
4231#endif
4232 )
4233 {
4234 if (vim_ispathsep(c1))
4235 return -1;
4236 if (vim_ispathsep(c2))
4237 return 1;
4238 return p_fic ? MB_TOUPPER(c1) - MB_TOUPPER(c2)
4239 : c1 - c2; // no match
4240 }
4241
Bram Moolenaar1614a142019-10-06 22:00:13 +02004242 i += mb_ptr2len((char_u *)p + i);
4243 j += mb_ptr2len((char_u *)q + j);
Bram Moolenaar26262f82019-09-04 20:59:15 +02004244 }
4245 if (s == NULL) // "i" or "j" ran into "maxlen"
4246 return 0;
4247
4248 c1 = PTR2CHAR((char_u *)s + i);
Bram Moolenaar1614a142019-10-06 22:00:13 +02004249 c2 = PTR2CHAR((char_u *)s + i + mb_ptr2len((char_u *)s + i));
Bram Moolenaar26262f82019-09-04 20:59:15 +02004250 // ignore a trailing slash, but not "//" or ":/"
4251 if (c2 == NUL
4252 && i > 0
4253 && !after_pathsep((char_u *)s, (char_u *)s + i)
4254#ifdef BACKSLASH_IN_FILENAME
4255 && (c1 == '/' || c1 == '\\')
4256#else
4257 && c1 == '/'
4258#endif
4259 )
4260 return 0; // match with trailing slash
4261 if (s == q)
4262 return -1; // no match
4263 return 1;
4264}
4265
4266/*
4267 * Return TRUE if "name" is a full (absolute) path name or URL.
4268 */
4269 int
4270vim_isAbsName(char_u *name)
4271{
4272 return (path_with_url(name) != 0 || mch_isFullName(name));
4273}
4274
4275/*
4276 * Get absolute file name into buffer "buf[len]".
4277 *
4278 * return FAIL for failure, OK otherwise
4279 */
4280 int
4281vim_FullName(
4282 char_u *fname,
4283 char_u *buf,
4284 int len,
4285 int force) // force expansion even when already absolute
4286{
4287 int retval = OK;
4288 int url;
4289
4290 *buf = NUL;
4291 if (fname == NULL)
4292 return FAIL;
4293
4294 url = path_with_url(fname);
4295 if (!url)
4296 retval = mch_FullName(fname, buf, len, force);
4297 if (url || retval == FAIL)
4298 {
4299 // something failed; use the file name (truncate when too long)
4300 vim_strncpy(buf, fname, len - 1);
4301 }
4302#if defined(MSWIN)
4303 slash_adjust(buf);
4304#endif
4305 return retval;
4306}