blob: 1ac2f868a43ffc0e7caad91cca904be27b9a2b5e [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{
Christian Brabandt6cc30272024-12-13 17:54:33 +010032 int l, len;
Bram Moolenaar3f396972019-10-30 04:10:06 +010033 WCHAR *newbuf;
34 WCHAR *wfname;
Bram Moolenaarb005cd82019-09-04 15:54:55 +020035
Christian Brabandt6cc30272024-12-13 17:54:33 +010036 len = MAXPATHL;
37 newbuf = malloc(len * sizeof(*newbuf));
Bram Moolenaar3f396972019-10-30 04:10:06 +010038 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
Christian Brabandt6cc30272024-12-13 17:54:33 +010048 l = GetShortPathNameW(wfname, newbuf, len);
49 if (l > len - 1)
Bram Moolenaarb005cd82019-09-04 15:54:55 +020050 {
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{
Christian Brabandt6cc30272024-12-13 17:54:33 +0100108 char_u *short_fname, *save_fname, *pbuf_unused;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200109 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;
Christian Brabandt6cc30272024-12-13 17:54:33 +0100142 *endp = 0;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200143 short_fname = save_fname;
Christian Brabandt6cc30272024-12-13 17:54:33 +0100144 len = (int)STRLEN(short_fname) + 1;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200145 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
Christian Brabandt6cc30272024-12-13 17:54:33 +0100228 // 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);
Christian Brabandt6cc30272024-12-13 17:54:33 +0100276 *fnamelen = (int)STRLEN(p);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200277 *bufp = pbuf;
278 *fnamep = p;
279
280 return OK;
281}
282#endif // MSWIN
283
284/*
285 * Adjust a filename, according to a string of modifiers.
286 * *fnamep must be NUL terminated when called. When returning, the length is
287 * determined by *fnamelen.
288 * Returns VALID_ flags or -1 for failure.
289 * When there is an error, *fnamep is set to NULL.
290 */
291 int
292modify_fname(
293 char_u *src, // string with modifiers
294 int tilde_file, // "~" is a file name, not $HOME
Mike Williams51024bb2024-05-30 07:46:30 +0200295 size_t *usedlen, // characters after src that are used
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200296 char_u **fnamep, // file name so far
297 char_u **bufp, // buffer for allocated file name or NULL
298 int *fnamelen) // length of fnamep
299{
300 int valid = 0;
301 char_u *tail;
302 char_u *s, *p, *pbuf;
303 char_u dirname[MAXPATHL];
304 int c;
305 int has_fullname = 0;
Bram Moolenaard816cd92020-02-04 22:23:09 +0100306 int has_homerelative = 0;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200307#ifdef MSWIN
308 char_u *fname_start = *fnamep;
309 int has_shortname = 0;
310#endif
311
312repeat:
Bram Moolenaar26262f82019-09-04 20:59:15 +0200313 // ":p" - full path/file_name
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200314 if (src[*usedlen] == ':' && src[*usedlen + 1] == 'p')
315 {
316 has_fullname = 1;
317
318 valid |= VALID_PATH;
319 *usedlen += 2;
320
Bram Moolenaar26262f82019-09-04 20:59:15 +0200321 // Expand "~/path" for all systems and "~user/path" for Unix and VMS
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200322 if ((*fnamep)[0] == '~'
323#if !defined(UNIX) && !(defined(VMS) && defined(USER_HOME))
324 && ((*fnamep)[1] == '/'
325# ifdef BACKSLASH_IN_FILENAME
326 || (*fnamep)[1] == '\\'
327# endif
328 || (*fnamep)[1] == NUL)
329#endif
330 && !(tilde_file && (*fnamep)[1] == NUL)
331 )
332 {
333 *fnamep = expand_env_save(*fnamep);
Bram Moolenaar26262f82019-09-04 20:59:15 +0200334 vim_free(*bufp); // free any allocated file name
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200335 *bufp = *fnamep;
336 if (*fnamep == NULL)
337 return -1;
338 }
339
Bram Moolenaar26262f82019-09-04 20:59:15 +0200340 // When "/." or "/.." is used: force expansion to get rid of it.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200341 for (p = *fnamep; *p != NUL; MB_PTR_ADV(p))
342 {
343 if (vim_ispathsep(*p)
344 && p[1] == '.'
345 && (p[2] == NUL
346 || vim_ispathsep(p[2])
347 || (p[2] == '.'
348 && (p[3] == NUL || vim_ispathsep(p[3])))))
349 break;
350 }
351
Bram Moolenaar26262f82019-09-04 20:59:15 +0200352 // FullName_save() is slow, don't use it when not needed.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200353 if (*p != NUL || !vim_isAbsName(*fnamep))
354 {
355 *fnamep = FullName_save(*fnamep, *p != NUL);
Bram Moolenaar26262f82019-09-04 20:59:15 +0200356 vim_free(*bufp); // free any allocated file name
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200357 *bufp = *fnamep;
358 if (*fnamep == NULL)
359 return -1;
360 }
361
362#ifdef MSWIN
363# if _WIN32_WINNT >= 0x0500
364 if (vim_strchr(*fnamep, '~') != NULL)
365 {
366 // Expand 8.3 filename to full path. Needed to make sure the same
367 // file does not have two different names.
368 // Note: problem does not occur if _WIN32_WINNT < 0x0500.
369 WCHAR *wfname = enc_to_utf16(*fnamep, NULL);
370 WCHAR buf[_MAX_PATH];
371
372 if (wfname != NULL)
373 {
374 if (GetLongPathNameW(wfname, buf, _MAX_PATH))
375 {
K.Takata54119102022-02-03 13:33:03 +0000376 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200377
K.Takata54119102022-02-03 13:33:03 +0000378 if (q != NULL)
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200379 {
380 vim_free(*bufp); // free any allocated file name
K.Takata54119102022-02-03 13:33:03 +0000381 *bufp = *fnamep = q;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200382 }
383 }
384 vim_free(wfname);
385 }
386 }
387# endif
388#endif
Bram Moolenaar26262f82019-09-04 20:59:15 +0200389 // Append a path separator to a directory.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200390 if (mch_isdir(*fnamep))
391 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200392 // Make room for one or two extra characters.
Bram Moolenaar71ccd032020-06-12 22:59:11 +0200393 *fnamep = vim_strnsave(*fnamep, STRLEN(*fnamep) + 2);
Bram Moolenaar26262f82019-09-04 20:59:15 +0200394 vim_free(*bufp); // free any allocated file name
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200395 *bufp = *fnamep;
396 if (*fnamep == NULL)
397 return -1;
398 add_pathsep(*fnamep);
399 }
400 }
401
Bram Moolenaar26262f82019-09-04 20:59:15 +0200402 // ":." - path relative to the current directory
403 // ":~" - path relative to the home directory
404 // ":8" - shortname path - postponed till after
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200405 while (src[*usedlen] == ':'
406 && ((c = src[*usedlen + 1]) == '.' || c == '~' || c == '8'))
407 {
408 *usedlen += 2;
409 if (c == '8')
410 {
411#ifdef MSWIN
Bram Moolenaar26262f82019-09-04 20:59:15 +0200412 has_shortname = 1; // Postpone this.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200413#endif
414 continue;
415 }
416 pbuf = NULL;
Christian Brabandt6cc30272024-12-13 17:54:33 +0100417 // 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.
Christian Brabandt6cc30272024-12-13 17:54:33 +0100508 p = vim_strsave((char_u *)".");
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200509 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 {
John Marriottbd4614f2024-11-18 20:25:21 +0100671 size_t slen;
672
Mike Williams51024bb2024-05-30 07:46:30 +0200673 *usedlen = p + 1 - src;
John Marriottbd4614f2024-11-18 20:25:21 +0100674 s = do_string_sub(str, *fnamelen, pat, sub, NULL, flags, &slen);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200675 if (s != NULL)
676 {
677 *fnamep = s;
Yegappan Lakshmanan084529c2024-12-24 09:50:01 +0100678 *fnamelen = (int)slen;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200679 vim_free(*bufp);
680 *bufp = s;
681 didit = TRUE;
682 }
683 }
684 vim_free(sub);
685 vim_free(str);
686 }
687 vim_free(pat);
688 }
689 }
Bram Moolenaar26262f82019-09-04 20:59:15 +0200690 // after using ":s", repeat all the modifiers
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200691 if (didit)
692 goto repeat;
693 }
694 }
695
696 if (src[*usedlen] == ':' && src[*usedlen + 1] == 'S')
697 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200698 // vim_strsave_shellescape() needs a NUL terminated string.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200699 c = (*fnamep)[*fnamelen];
700 if (c != NUL)
701 (*fnamep)[*fnamelen] = NUL;
702 p = vim_strsave_shellescape(*fnamep, FALSE, FALSE);
703 if (c != NUL)
704 (*fnamep)[*fnamelen] = c;
705 if (p == NULL)
706 return -1;
707 vim_free(*bufp);
708 *bufp = *fnamep = p;
709 *fnamelen = (int)STRLEN(p);
710 *usedlen += 2;
711 }
712
713 return valid;
714}
715
Bram Moolenaar273af492020-09-25 23:49:01 +0200716/*
717 * Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
718 * "trim_len" specifies how many characters to keep for each directory.
719 * Must be 1 or more.
720 * It's done in-place.
721 */
722 static void
723shorten_dir_len(char_u *str, int trim_len)
724{
725 char_u *tail, *s, *d;
726 int skip = FALSE;
727 int dirchunk_len = 0;
728
729 tail = gettail(str);
730 d = str;
731 for (s = str; ; ++s)
732 {
733 if (s >= tail) // copy the whole tail
734 {
735 *d++ = *s;
736 if (*s == NUL)
737 break;
738 }
739 else if (vim_ispathsep(*s)) // copy '/' and next char
740 {
741 *d++ = *s;
742 skip = FALSE;
743 dirchunk_len = 0;
744 }
745 else if (!skip)
746 {
747 *d++ = *s; // copy next char
748 if (*s != '~' && *s != '.') // and leading "~" and "."
749 {
750 ++dirchunk_len; // only count word chars for the size
751
752 // keep copying chars until we have our preferred length (or
753 // until the above if/else branches move us along)
754 if (dirchunk_len >= trim_len)
755 skip = TRUE;
756 }
757
758 if (has_mbyte)
759 {
760 int l = mb_ptr2len(s);
761
762 while (--l > 0)
763 *d++ = *++s;
764 }
765 }
766 }
767}
768
769/*
770 * Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
771 * It's done in-place.
772 */
773 void
774shorten_dir(char_u *str)
775{
776 shorten_dir_len(str, 1);
777}
778
Bram Moolenaar022f9ef2022-07-02 17:36:31 +0100779/*
780 * Return TRUE if "fname" is a readable file.
781 */
782 int
783file_is_readable(char_u *fname)
784{
785 int fd;
786
787#ifndef O_NONBLOCK
788# define O_NONBLOCK 0
789#endif
790 if (*fname && !mch_isdir(fname)
791 && (fd = mch_open((char *)fname, O_RDONLY | O_NONBLOCK, 0)) >= 0)
792 {
793 close(fd);
794 return TRUE;
795 }
796 return FALSE;
797}
798
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200799#if defined(FEAT_EVAL) || defined(PROTO)
800
801/*
802 * "chdir(dir)" function
803 */
804 void
805f_chdir(typval_T *argvars, typval_T *rettv)
806{
807 char_u *cwd;
808 cdscope_T scope = CDSCOPE_GLOBAL;
809
810 rettv->v_type = VAR_STRING;
811 rettv->vval.v_string = NULL;
812
813 if (argvars[0].v_type != VAR_STRING)
Bram Moolenaarc5809432021-03-27 21:23:30 +0100814 {
Bram Moolenaard816cd92020-02-04 22:23:09 +0100815 // Returning an empty string means it failed.
Bram Moolenaar002bc792020-06-05 22:33:42 +0200816 // No error message, for historic reasons.
Bram Moolenaarc5809432021-03-27 21:23:30 +0100817 if (in_vim9script())
818 (void) check_for_string_arg(argvars, 0);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200819 return;
Bram Moolenaarc5809432021-03-27 21:23:30 +0100820 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200821
822 // Return the current directory
823 cwd = alloc(MAXPATHL);
824 if (cwd != NULL)
825 {
826 if (mch_dirname(cwd, MAXPATHL) != FAIL)
827 {
828#ifdef BACKSLASH_IN_FILENAME
829 slash_adjust(cwd);
830#endif
831 rettv->vval.v_string = vim_strsave(cwd);
832 }
833 vim_free(cwd);
834 }
835
836 if (curwin->w_localdir != NULL)
837 scope = CDSCOPE_WINDOW;
838 else if (curtab->tp_localdir != NULL)
839 scope = CDSCOPE_TABPAGE;
840
841 if (!changedir_func(argvars[0].vval.v_string, TRUE, scope))
842 // Directory change failed
843 VIM_CLEAR(rettv->vval.v_string);
844}
845
846/*
847 * "delete()" function
848 */
849 void
850f_delete(typval_T *argvars, typval_T *rettv)
851{
852 char_u nbuf[NUMBUFLEN];
853 char_u *name;
854 char_u *flags;
855
856 rettv->vval.v_number = -1;
857 if (check_restricted() || check_secure())
858 return;
859
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +0200860 if (in_vim9script()
861 && (check_for_string_arg(argvars, 0) == FAIL
862 || check_for_opt_string_arg(argvars, 1) == FAIL))
863 return;
864
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200865 name = tv_get_string(&argvars[0]);
866 if (name == NULL || *name == NUL)
867 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +0000868 emsg(_(e_invalid_argument));
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200869 return;
870 }
871
872 if (argvars[1].v_type != VAR_UNKNOWN)
873 flags = tv_get_string_buf(&argvars[1], nbuf);
874 else
875 flags = (char_u *)"";
876
877 if (*flags == NUL)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200878 // delete a file
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200879 rettv->vval.v_number = mch_remove(name) == 0 ? 0 : -1;
880 else if (STRCMP(flags, "d") == 0)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200881 // delete an empty directory
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200882 rettv->vval.v_number = mch_rmdir(name) == 0 ? 0 : -1;
883 else if (STRCMP(flags, "rf") == 0)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200884 // delete a directory recursively
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200885 rettv->vval.v_number = delete_recursive(name);
886 else
Bram Moolenaar108010a2021-06-27 22:03:33 +0200887 semsg(_(e_invalid_expression_str), flags);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200888}
889
890/*
891 * "executable()" function
892 */
893 void
894f_executable(typval_T *argvars, typval_T *rettv)
895{
Bram Moolenaar32105ae2021-03-27 18:59:25 +0100896 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100897 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200898
Bram Moolenaar26262f82019-09-04 20:59:15 +0200899 // Check in $PATH and also check directly if there is a directory name.
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100900 rettv->vval.v_number = mch_can_exe(tv_get_string(&argvars[0]), NULL, TRUE);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200901}
902
903/*
904 * "exepath()" function
905 */
906 void
907f_exepath(typval_T *argvars, typval_T *rettv)
908{
909 char_u *p = NULL;
910
Bram Moolenaar32105ae2021-03-27 18:59:25 +0100911 if (in_vim9script() && check_for_nonempty_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100912 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200913 (void)mch_can_exe(tv_get_string(&argvars[0]), &p, TRUE);
914 rettv->v_type = VAR_STRING;
915 rettv->vval.v_string = p;
916}
917
918/*
919 * "filereadable()" function
920 */
921 void
922f_filereadable(typval_T *argvars, typval_T *rettv)
923{
Bram Moolenaar32105ae2021-03-27 18:59:25 +0100924 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100925 return;
Bram Moolenaar4dea2d92022-03-31 11:37:57 +0100926 rettv->vval.v_number = file_is_readable(tv_get_string(&argvars[0]));
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200927}
928
929/*
930 * Return 0 for not writable, 1 for writable file, 2 for a dir which we have
931 * rights to write into.
932 */
933 void
934f_filewritable(typval_T *argvars, typval_T *rettv)
935{
Bram Moolenaar32105ae2021-03-27 18:59:25 +0100936 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100937 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200938 rettv->vval.v_number = filewritable(tv_get_string(&argvars[0]));
939}
940
Bram Moolenaar840d16f2019-09-10 21:27:18 +0200941 static void
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200942findfilendir(
Yee Cheng China7767072023-04-16 20:13:12 +0100943 typval_T *argvars,
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200944 typval_T *rettv,
Yee Cheng China7767072023-04-16 20:13:12 +0100945 int find_what)
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200946{
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200947 char_u *fname;
948 char_u *fresult = NULL;
949 char_u *path = *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path;
950 char_u *p;
951 char_u pathbuf[NUMBUFLEN];
952 int count = 1;
953 int first = TRUE;
954 int error = FALSE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200955
956 rettv->vval.v_string = NULL;
957 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +0200958 if (in_vim9script()
959 && (check_for_nonempty_string_arg(argvars, 0) == FAIL
960 || check_for_opt_string_arg(argvars, 1) == FAIL
961 || (argvars[1].v_type != VAR_UNKNOWN
962 && check_for_opt_number_arg(argvars, 2) == FAIL)))
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100963 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200964
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200965 fname = tv_get_string(&argvars[0]);
966
967 if (argvars[1].v_type != VAR_UNKNOWN)
968 {
969 p = tv_get_string_buf_chk(&argvars[1], pathbuf);
970 if (p == NULL)
971 error = TRUE;
972 else
973 {
974 if (*p != NUL)
975 path = p;
976
977 if (argvars[2].v_type != VAR_UNKNOWN)
978 count = (int)tv_get_number_chk(&argvars[2], &error);
979 }
980 }
981
982 if (count < 0 && rettv_list_alloc(rettv) == FAIL)
983 error = TRUE;
984
985 if (*fname != NUL && !error)
986 {
Bram Moolenaar5145c9a2023-03-11 13:55:53 +0000987 char_u *file_to_find = NULL;
988 char *search_ctx = NULL;
989
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200990 do
991 {
992 if (rettv->v_type == VAR_STRING || rettv->v_type == VAR_LIST)
993 vim_free(fresult);
994 fresult = find_file_in_path_option(first ? fname : NULL,
995 first ? (int)STRLEN(fname) : 0,
996 0, first, path,
997 find_what,
998 curbuf->b_ffname,
999 find_what == FINDFILE_DIR
Bram Moolenaar5145c9a2023-03-11 13:55:53 +00001000 ? (char_u *)"" : curbuf->b_p_sua,
1001 &file_to_find, &search_ctx);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001002 first = FALSE;
1003
1004 if (fresult != NULL && rettv->v_type == VAR_LIST)
1005 list_append_string(rettv->vval.v_list, fresult, -1);
1006
1007 } while ((rettv->v_type == VAR_LIST || --count > 0) && fresult != NULL);
Bram Moolenaar5145c9a2023-03-11 13:55:53 +00001008
1009 vim_free(file_to_find);
1010 vim_findfile_cleanup(search_ctx);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001011 }
1012
1013 if (rettv->v_type == VAR_STRING)
1014 rettv->vval.v_string = fresult;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001015}
1016
1017/*
1018 * "finddir({fname}[, {path}[, {count}]])" function
1019 */
1020 void
1021f_finddir(typval_T *argvars, typval_T *rettv)
1022{
1023 findfilendir(argvars, rettv, FINDFILE_DIR);
1024}
1025
1026/*
1027 * "findfile({fname}[, {path}[, {count}]])" function
1028 */
1029 void
1030f_findfile(typval_T *argvars, typval_T *rettv)
1031{
1032 findfilendir(argvars, rettv, FINDFILE_FILE);
1033}
1034
1035/*
1036 * "fnamemodify({fname}, {mods})" function
1037 */
1038 void
1039f_fnamemodify(typval_T *argvars, typval_T *rettv)
1040{
1041 char_u *fname;
1042 char_u *mods;
Mike Williams51024bb2024-05-30 07:46:30 +02001043 size_t usedlen = 0;
Bram Moolenaarc5308522020-12-13 12:25:35 +01001044 int len = 0;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001045 char_u *fbuf = NULL;
1046 char_u buf[NUMBUFLEN];
1047
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001048 if (in_vim9script()
1049 && (check_for_string_arg(argvars, 0) == FAIL
1050 || check_for_string_arg(argvars, 1) == FAIL))
Bram Moolenaar7bb4e742020-12-09 12:41:50 +01001051 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001052
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001053 fname = tv_get_string_chk(&argvars[0]);
1054 mods = tv_get_string_buf_chk(&argvars[1], buf);
Bram Moolenaarc5308522020-12-13 12:25:35 +01001055 if (mods == NULL || fname == NULL)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001056 fname = NULL;
Bram Moolenaarc5308522020-12-13 12:25:35 +01001057 else
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001058 {
1059 len = (int)STRLEN(fname);
Bram Moolenaarc5308522020-12-13 12:25:35 +01001060 if (mods != NULL && *mods != NUL)
1061 (void)modify_fname(mods, FALSE, &usedlen, &fname, &fbuf, &len);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001062 }
1063
1064 rettv->v_type = VAR_STRING;
1065 if (fname == NULL)
1066 rettv->vval.v_string = NULL;
1067 else
1068 rettv->vval.v_string = vim_strnsave(fname, len);
1069 vim_free(fbuf);
1070}
1071
1072/*
1073 * "getcwd()" function
1074 *
1075 * Return the current working directory of a window in a tab page.
1076 * First optional argument 'winnr' is the window number or -1 and the second
1077 * optional argument 'tabnr' is the tab page number.
1078 *
1079 * If no arguments are supplied, then return the directory of the current
1080 * window.
1081 * If only 'winnr' is specified and is not -1 or 0 then return the directory of
1082 * the specified window.
1083 * If 'winnr' is 0 then return the directory of the current window.
1084 * If both 'winnr and 'tabnr' are specified and 'winnr' is -1 then return the
1085 * directory of the specified tab page. Otherwise return the directory of the
1086 * specified window in the specified tab page.
1087 * If the window or the tab page doesn't exist then return NULL.
1088 */
1089 void
1090f_getcwd(typval_T *argvars, typval_T *rettv)
1091{
1092 win_T *wp = NULL;
1093 tabpage_T *tp = NULL;
1094 char_u *cwd;
1095 int global = FALSE;
1096
1097 rettv->v_type = VAR_STRING;
1098 rettv->vval.v_string = NULL;
1099
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001100 if (in_vim9script()
1101 && (check_for_opt_number_arg(argvars, 0) == FAIL
1102 || (argvars[0].v_type != VAR_UNKNOWN
1103 && check_for_opt_number_arg(argvars, 1) == FAIL)))
1104 return;
1105
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001106 if (argvars[0].v_type == VAR_NUMBER
1107 && argvars[0].vval.v_number == -1
1108 && argvars[1].v_type == VAR_UNKNOWN)
1109 global = TRUE;
1110 else
1111 wp = find_tabwin(&argvars[0], &argvars[1], &tp);
1112
Bram Moolenaar851c7a62021-11-18 20:47:31 +00001113 if (wp != NULL && wp->w_localdir != NULL
1114 && argvars[0].v_type != VAR_UNKNOWN)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001115 rettv->vval.v_string = vim_strsave(wp->w_localdir);
Bram Moolenaar851c7a62021-11-18 20:47:31 +00001116 else if (tp != NULL && tp->tp_localdir != NULL
1117 && argvars[0].v_type != VAR_UNKNOWN)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001118 rettv->vval.v_string = vim_strsave(tp->tp_localdir);
1119 else if (wp != NULL || tp != NULL || global)
1120 {
Bram Moolenaar851c7a62021-11-18 20:47:31 +00001121 if (globaldir != NULL && argvars[0].v_type != VAR_UNKNOWN)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001122 rettv->vval.v_string = vim_strsave(globaldir);
1123 else
1124 {
1125 cwd = alloc(MAXPATHL);
1126 if (cwd != NULL)
1127 {
1128 if (mch_dirname(cwd, MAXPATHL) != FAIL)
1129 rettv->vval.v_string = vim_strsave(cwd);
1130 vim_free(cwd);
1131 }
1132 }
1133 }
1134#ifdef BACKSLASH_IN_FILENAME
1135 if (rettv->vval.v_string != NULL)
1136 slash_adjust(rettv->vval.v_string);
1137#endif
1138}
1139
1140/*
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001141 * Convert "st" to file permission string.
1142 */
1143 char_u *
1144getfpermst(stat_T *st, char_u *perm)
1145{
1146 char_u flags[] = "rwx";
1147 int i;
1148
1149 for (i = 0; i < 9; i++)
1150 {
1151 if (st->st_mode & (1 << (8 - i)))
1152 perm[i] = flags[i % 3];
1153 else
1154 perm[i] = '-';
1155 }
1156 return perm;
1157}
1158
1159/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001160 * "getfperm({fname})" function
1161 */
1162 void
1163f_getfperm(typval_T *argvars, typval_T *rettv)
1164{
1165 char_u *fname;
1166 stat_T st;
1167 char_u *perm = NULL;
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001168 char_u permbuf[] = "---------";
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001169
Bram Moolenaar32105ae2021-03-27 18:59:25 +01001170 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +01001171 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001172
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001173 fname = tv_get_string(&argvars[0]);
1174
1175 rettv->v_type = VAR_STRING;
1176 if (mch_stat((char *)fname, &st) >= 0)
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001177 perm = vim_strsave(getfpermst(&st, permbuf));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001178 rettv->vval.v_string = perm;
1179}
1180
1181/*
1182 * "getfsize({fname})" function
1183 */
1184 void
1185f_getfsize(typval_T *argvars, typval_T *rettv)
1186{
1187 char_u *fname;
1188 stat_T st;
1189
Bram Moolenaar32105ae2021-03-27 18:59:25 +01001190 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +01001191 return;
1192
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001193 fname = tv_get_string(&argvars[0]);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001194 if (mch_stat((char *)fname, &st) >= 0)
1195 {
1196 if (mch_isdir(fname))
1197 rettv->vval.v_number = 0;
1198 else
1199 {
1200 rettv->vval.v_number = (varnumber_T)st.st_size;
1201
Bram Moolenaar26262f82019-09-04 20:59:15 +02001202 // non-perfect check for overflow
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001203 if ((off_T)rettv->vval.v_number != (off_T)st.st_size)
1204 rettv->vval.v_number = -2;
1205 }
1206 }
1207 else
1208 rettv->vval.v_number = -1;
1209}
1210
1211/*
1212 * "getftime({fname})" function
1213 */
1214 void
1215f_getftime(typval_T *argvars, typval_T *rettv)
1216{
1217 char_u *fname;
1218 stat_T st;
1219
Bram Moolenaar32105ae2021-03-27 18:59:25 +01001220 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +01001221 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001222
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001223 fname = tv_get_string(&argvars[0]);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001224 if (mch_stat((char *)fname, &st) >= 0)
1225 rettv->vval.v_number = (varnumber_T)st.st_mtime;
1226 else
1227 rettv->vval.v_number = -1;
1228}
1229
1230/*
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001231 * Convert "st" to file type string.
1232 */
1233 char_u *
1234getftypest(stat_T *st)
1235{
1236 char *t;
1237
1238 if (S_ISREG(st->st_mode))
1239 t = "file";
1240 else if (S_ISDIR(st->st_mode))
1241 t = "dir";
1242 else if (S_ISLNK(st->st_mode))
1243 t = "link";
1244 else if (S_ISBLK(st->st_mode))
1245 t = "bdev";
1246 else if (S_ISCHR(st->st_mode))
1247 t = "cdev";
1248 else if (S_ISFIFO(st->st_mode))
1249 t = "fifo";
1250 else if (S_ISSOCK(st->st_mode))
1251 t = "socket";
1252 else
1253 t = "other";
1254 return (char_u*)t;
1255}
1256
1257/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001258 * "getftype({fname})" function
1259 */
1260 void
1261f_getftype(typval_T *argvars, typval_T *rettv)
1262{
1263 char_u *fname;
1264 stat_T st;
1265 char_u *type = NULL;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001266
Bram Moolenaar32105ae2021-03-27 18:59:25 +01001267 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +01001268 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001269
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001270 fname = tv_get_string(&argvars[0]);
1271
1272 rettv->v_type = VAR_STRING;
1273 if (mch_lstat((char *)fname, &st) >= 0)
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001274 type = vim_strsave(getftypest(&st));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001275 rettv->vval.v_string = type;
1276}
1277
1278/*
1279 * "glob()" function
1280 */
1281 void
1282f_glob(typval_T *argvars, typval_T *rettv)
1283{
1284 int options = WILD_SILENT|WILD_USE_NL;
1285 expand_T xpc;
1286 int error = FALSE;
1287
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02001288 if (in_vim9script()
1289 && (check_for_string_arg(argvars, 0) == FAIL
1290 || check_for_opt_bool_arg(argvars, 1) == FAIL
1291 || (argvars[1].v_type != VAR_UNKNOWN
1292 && (check_for_opt_bool_arg(argvars, 2) == FAIL
1293 || (argvars[2].v_type != VAR_UNKNOWN
1294 && check_for_opt_bool_arg(argvars, 3) == FAIL)))))
1295 return;
1296
Bram Moolenaar26262f82019-09-04 20:59:15 +02001297 // When the optional second argument is non-zero, don't remove matches
1298 // for 'wildignore' and don't put matches for 'suffixes' at the end.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001299 rettv->v_type = VAR_STRING;
1300 if (argvars[1].v_type != VAR_UNKNOWN)
1301 {
Bram Moolenaar5892ea12020-09-02 21:53:11 +02001302 if (tv_get_bool_chk(&argvars[1], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001303 options |= WILD_KEEP_ALL;
1304 if (argvars[2].v_type != VAR_UNKNOWN)
1305 {
Bram Moolenaar5892ea12020-09-02 21:53:11 +02001306 if (tv_get_bool_chk(&argvars[2], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001307 rettv_list_set(rettv, NULL);
1308 if (argvars[3].v_type != VAR_UNKNOWN
Bram Moolenaar5892ea12020-09-02 21:53:11 +02001309 && tv_get_bool_chk(&argvars[3], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001310 options |= WILD_ALLLINKS;
1311 }
1312 }
1313 if (!error)
1314 {
1315 ExpandInit(&xpc);
1316 xpc.xp_context = EXPAND_FILES;
1317 if (p_wic)
1318 options += WILD_ICASE;
1319 if (rettv->v_type == VAR_STRING)
1320 rettv->vval.v_string = ExpandOne(&xpc, tv_get_string(&argvars[0]),
1321 NULL, options, WILD_ALL);
Bram Moolenaar8088ae92022-06-20 11:38:17 +01001322 else if (rettv_list_alloc(rettv) == OK)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001323 {
1324 int i;
1325
1326 ExpandOne(&xpc, tv_get_string(&argvars[0]),
1327 NULL, options, WILD_ALL_KEEP);
1328 for (i = 0; i < xpc.xp_numfiles; i++)
1329 list_append_string(rettv->vval.v_list, xpc.xp_files[i], -1);
1330
1331 ExpandCleanup(&xpc);
1332 }
1333 }
1334 else
1335 rettv->vval.v_string = NULL;
1336}
1337
1338/*
1339 * "glob2regpat()" function
1340 */
1341 void
1342f_glob2regpat(typval_T *argvars, typval_T *rettv)
1343{
Bram Moolenaar3cfa5b12021-06-06 14:14:39 +02001344 char_u buf[NUMBUFLEN];
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001345 char_u *pat;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001346
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001347 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
1348 return;
1349
1350 pat = tv_get_string_buf_chk_strict(&argvars[0], buf, in_vim9script());
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001351 rettv->v_type = VAR_STRING;
1352 rettv->vval.v_string = (pat == NULL)
1353 ? NULL : file_pat_to_reg_pat(pat, NULL, NULL, FALSE);
1354}
1355
1356/*
1357 * "globpath()" function
1358 */
1359 void
1360f_globpath(typval_T *argvars, typval_T *rettv)
1361{
1362 int flags = WILD_IGNORE_COMPLETESLASH;
1363 char_u buf1[NUMBUFLEN];
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02001364 char_u *file;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001365 int error = FALSE;
1366 garray_T ga;
1367 int i;
1368
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02001369 if (in_vim9script()
1370 && (check_for_string_arg(argvars, 0) == FAIL
1371 || check_for_string_arg(argvars, 1) == FAIL
1372 || check_for_opt_bool_arg(argvars, 2) == FAIL
1373 || (argvars[2].v_type != VAR_UNKNOWN
1374 && (check_for_opt_bool_arg(argvars, 3) == FAIL
1375 || (argvars[3].v_type != VAR_UNKNOWN
1376 && check_for_opt_bool_arg(argvars, 4) == FAIL)))))
1377 return;
1378
1379 file = tv_get_string_buf_chk(&argvars[1], buf1);
1380
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001381 // When the optional second argument is non-zero, don't remove matches
1382 // for 'wildignore' and don't put matches for 'suffixes' at the end.
1383 rettv->v_type = VAR_STRING;
1384 if (argvars[2].v_type != VAR_UNKNOWN)
1385 {
Bram Moolenaarf966ce52020-09-02 21:57:07 +02001386 if (tv_get_bool_chk(&argvars[2], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001387 flags |= WILD_KEEP_ALL;
1388 if (argvars[3].v_type != VAR_UNKNOWN)
1389 {
Bram Moolenaarf966ce52020-09-02 21:57:07 +02001390 if (tv_get_bool_chk(&argvars[3], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001391 rettv_list_set(rettv, NULL);
1392 if (argvars[4].v_type != VAR_UNKNOWN
Bram Moolenaarf966ce52020-09-02 21:57:07 +02001393 && tv_get_bool_chk(&argvars[4], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001394 flags |= WILD_ALLLINKS;
1395 }
1396 }
1397 if (file != NULL && !error)
1398 {
Bram Moolenaar04935fb2022-01-08 16:19:22 +00001399 ga_init2(&ga, sizeof(char_u *), 10);
zeertzjq3770f4c2023-01-22 18:38:51 +00001400 globpath(tv_get_string(&argvars[0]), file, &ga, flags, FALSE);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001401 if (rettv->v_type == VAR_STRING)
1402 rettv->vval.v_string = ga_concat_strings(&ga, "\n");
Bram Moolenaar8088ae92022-06-20 11:38:17 +01001403 else if (rettv_list_alloc(rettv) == OK)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001404 for (i = 0; i < ga.ga_len; ++i)
1405 list_append_string(rettv->vval.v_list,
1406 ((char_u **)(ga.ga_data))[i], -1);
1407 ga_clear_strings(&ga);
1408 }
1409 else
1410 rettv->vval.v_string = NULL;
1411}
1412
1413/*
1414 * "isdirectory()" function
1415 */
1416 void
1417f_isdirectory(typval_T *argvars, typval_T *rettv)
1418{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001419 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
1420 return;
1421
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001422 rettv->vval.v_number = mch_isdir(tv_get_string(&argvars[0]));
1423}
1424
1425/*
LemonBoydca1d402022-04-28 15:26:33 +01001426 * "isabsolutepath()" function
1427 */
1428 void
1429f_isabsolutepath(typval_T *argvars, typval_T *rettv)
1430{
1431 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
1432 return;
1433
1434 rettv->vval.v_number = mch_isFullName(tv_get_string_strict(&argvars[0]));
1435}
1436
1437/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001438 * Create the directory in which "dir" is located, and higher levels when
1439 * needed.
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001440 * Set "created" to the full name of the first created directory. It will be
1441 * NULL until that happens.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001442 * Return OK or FAIL.
1443 */
1444 static int
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001445mkdir_recurse(char_u *dir, int prot, char_u **created)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001446{
1447 char_u *p;
1448 char_u *updir;
1449 int r = FAIL;
1450
Bram Moolenaar26262f82019-09-04 20:59:15 +02001451 // Get end of directory name in "dir".
1452 // We're done when it's "/" or "c:/".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001453 p = gettail_sep(dir);
1454 if (p <= get_past_head(dir))
1455 return OK;
1456
Bram Moolenaar26262f82019-09-04 20:59:15 +02001457 // If the directory exists we're done. Otherwise: create it.
Bram Moolenaar71ccd032020-06-12 22:59:11 +02001458 updir = vim_strnsave(dir, p - dir);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001459 if (updir == NULL)
1460 return FAIL;
1461 if (mch_isdir(updir))
1462 r = OK;
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001463 else if (mkdir_recurse(updir, prot, created) == OK)
1464 {
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001465 r = vim_mkdir_emsg(updir, prot);
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001466 if (r == OK && created != NULL && *created == NULL)
1467 *created = FullName_save(updir, FALSE);
1468 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001469 vim_free(updir);
1470 return r;
1471}
1472
1473/*
1474 * "mkdir()" function
1475 */
1476 void
1477f_mkdir(typval_T *argvars, typval_T *rettv)
1478{
1479 char_u *dir;
1480 char_u buf[NUMBUFLEN];
1481 int prot = 0755;
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001482 int defer = FALSE;
1483 int defer_recurse = FALSE;
1484 char_u *created = NULL;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001485
1486 rettv->vval.v_number = FAIL;
1487 if (check_restricted() || check_secure())
1488 return;
1489
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001490 if (in_vim9script()
1491 && (check_for_nonempty_string_arg(argvars, 0) == FAIL
1492 || check_for_opt_string_arg(argvars, 1) == FAIL
1493 || (argvars[1].v_type != VAR_UNKNOWN
1494 && check_for_opt_number_arg(argvars, 2) == FAIL)))
1495 return;
1496
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001497 dir = tv_get_string_buf(&argvars[0], buf);
1498 if (*dir == NUL)
1499 return;
1500
1501 if (*gettail(dir) == NUL)
Bram Moolenaar26262f82019-09-04 20:59:15 +02001502 // remove trailing slashes
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001503 *gettail_sep(dir) = NUL;
1504
1505 if (argvars[1].v_type != VAR_UNKNOWN)
1506 {
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001507 char_u *arg2;
1508
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001509 if (argvars[2].v_type != VAR_UNKNOWN)
1510 {
1511 prot = (int)tv_get_number_chk(&argvars[2], NULL);
1512 if (prot == -1)
1513 return;
1514 }
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001515 arg2 = tv_get_string(&argvars[1]);
1516 defer = vim_strchr(arg2, 'D') != NULL;
1517 defer_recurse = vim_strchr(arg2, 'R') != NULL;
1518 if ((defer || defer_recurse) && !can_add_defer())
1519 return;
1520
1521 if (vim_strchr(arg2, 'p') != NULL)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001522 {
1523 if (mch_isdir(dir))
1524 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001525 // With the "p" flag it's OK if the dir already exists.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001526 rettv->vval.v_number = OK;
1527 return;
1528 }
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001529 mkdir_recurse(dir, prot, defer || defer_recurse ? &created : NULL);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001530 }
1531 }
1532 rettv->vval.v_number = vim_mkdir_emsg(dir, prot);
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001533
1534 // Handle "D" and "R": deferred deletion of the created directory.
1535 if (rettv->vval.v_number == OK
1536 && created == NULL && (defer || defer_recurse))
1537 created = FullName_save(dir, FALSE);
1538 if (created != NULL)
1539 {
1540 typval_T tv[2];
1541
1542 tv[0].v_type = VAR_STRING;
1543 tv[0].v_lock = 0;
1544 tv[0].vval.v_string = created;
1545 tv[1].v_type = VAR_STRING;
1546 tv[1].v_lock = 0;
Christian Brabandt6cc30272024-12-13 17:54:33 +01001547 tv[1].vval.v_string = vim_strsave(
1548 (char_u *)(defer_recurse ? "rf" : "d"));
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001549 if (tv[0].vval.v_string == NULL || tv[1].vval.v_string == NULL
1550 || add_defer((char_u *)"delete", 2, tv) == FAIL)
1551 {
1552 vim_free(tv[0].vval.v_string);
1553 vim_free(tv[1].vval.v_string);
1554 }
1555 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001556}
1557
1558/*
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02001559 * "pathshorten()" function
1560 */
1561 void
1562f_pathshorten(typval_T *argvars, typval_T *rettv)
1563{
1564 char_u *p;
Bram Moolenaar6a33ef02020-09-25 22:42:48 +02001565 int trim_len = 1;
1566
Yegappan Lakshmanan1a71d312021-07-15 12:49:58 +02001567 if (in_vim9script()
1568 && (check_for_string_arg(argvars, 0) == FAIL
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02001569 || check_for_opt_number_arg(argvars, 1) == FAIL))
Yegappan Lakshmanan1a71d312021-07-15 12:49:58 +02001570 return;
1571
Bram Moolenaar6a33ef02020-09-25 22:42:48 +02001572 if (argvars[1].v_type != VAR_UNKNOWN)
1573 {
1574 trim_len = (int)tv_get_number(&argvars[1]);
1575 if (trim_len < 1)
1576 trim_len = 1;
1577 }
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02001578
1579 rettv->v_type = VAR_STRING;
1580 p = tv_get_string_chk(&argvars[0]);
Bram Moolenaar6a33ef02020-09-25 22:42:48 +02001581
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02001582 if (p == NULL)
1583 rettv->vval.v_string = NULL;
1584 else
1585 {
1586 p = vim_strsave(p);
1587 rettv->vval.v_string = p;
1588 if (p != NULL)
Bram Moolenaar6a33ef02020-09-25 22:42:48 +02001589 shorten_dir_len(p, trim_len);
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02001590 }
1591}
1592
1593/*
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001594 * Common code for readdir_checkitem() and readdirex_checkitem().
1595 * Either "name" or "dict" is NULL.
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001596 */
1597 static int
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001598checkitem_common(void *context, char_u *name, dict_T *dict)
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001599{
1600 typval_T *expr = (typval_T *)context;
1601 typval_T save_val;
1602 typval_T rettv;
1603 typval_T argv[2];
1604 int retval = 0;
1605 int error = FALSE;
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001606
1607 prepare_vimvar(VV_VAL, &save_val);
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001608 if (name != NULL)
1609 {
1610 set_vim_var_string(VV_VAL, name, -1);
1611 argv[0].v_type = VAR_STRING;
1612 argv[0].vval.v_string = name;
1613 }
1614 else
1615 {
1616 set_vim_var_dict(VV_VAL, dict);
1617 argv[0].v_type = VAR_DICT;
1618 argv[0].vval.v_dict = dict;
1619 }
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001620
zeertzjqad0c4422023-08-17 22:15:47 +02001621 if (eval_expr_typval(expr, FALSE, argv, 1, NULL, &rettv) == FAIL)
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001622 goto theend;
1623
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001624 // We want to use -1, but also true/false should be allowed.
1625 if (rettv.v_type == VAR_SPECIAL || rettv.v_type == VAR_BOOL)
1626 {
1627 rettv.v_type = VAR_NUMBER;
1628 rettv.vval.v_number = rettv.vval.v_number == VVAL_TRUE;
1629 }
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001630 retval = tv_get_number_chk(&rettv, &error);
1631 if (error)
1632 retval = -1;
1633 clear_tv(&rettv);
1634
1635theend:
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001636 if (name != NULL)
1637 set_vim_var_string(VV_VAL, NULL, 0);
1638 else
1639 set_vim_var_dict(VV_VAL, NULL);
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001640 restore_vimvar(VV_VAL, &save_val);
1641 return retval;
1642}
1643
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001644/*
1645 * Evaluate "expr" (= "context") for readdir().
1646 */
1647 static int
1648readdir_checkitem(void *context, void *item)
1649{
1650 char_u *name = (char_u *)item;
1651
1652 return checkitem_common(context, name, NULL);
1653}
1654
Bram Moolenaard83392a2022-09-01 12:22:46 +01001655/*
1656 * Process the keys in the Dict argument to the readdir() and readdirex()
1657 * functions. Assumes the Dict argument is the 3rd argument.
1658 */
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001659 static int
Bram Moolenaard83392a2022-09-01 12:22:46 +01001660readdirex_dict_arg(typval_T *argvars, int *cmp)
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001661{
1662 char_u *compare;
1663
Bram Moolenaard83392a2022-09-01 12:22:46 +01001664 if (check_for_nonnull_dict_arg(argvars, 2) == FAIL)
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001665 return FAIL;
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001666
Bram Moolenaard83392a2022-09-01 12:22:46 +01001667 if (dict_has_key(argvars[2].vval.v_dict, "sort"))
1668 compare = dict_get_string(argvars[2].vval.v_dict, "sort", FALSE);
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001669 else
1670 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00001671 semsg(_(e_dictionary_key_str_required), "sort");
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001672 return FAIL;
1673 }
1674
1675 if (STRCMP(compare, (char_u *) "none") == 0)
1676 *cmp = READDIR_SORT_NONE;
1677 else if (STRCMP(compare, (char_u *) "case") == 0)
1678 *cmp = READDIR_SORT_BYTE;
1679 else if (STRCMP(compare, (char_u *) "icase") == 0)
1680 *cmp = READDIR_SORT_IC;
1681 else if (STRCMP(compare, (char_u *) "collate") == 0)
1682 *cmp = READDIR_SORT_COLLATE;
1683 return OK;
1684}
1685
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001686/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001687 * "readdir()" function
1688 */
1689 void
1690f_readdir(typval_T *argvars, typval_T *rettv)
1691{
1692 typval_T *expr;
1693 int ret;
1694 char_u *path;
1695 char_u *p;
1696 garray_T ga;
1697 int i;
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01001698 int sort = READDIR_SORT_BYTE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001699
1700 if (rettv_list_alloc(rettv) == FAIL)
1701 return;
Yegappan Lakshmanan5bca9062021-07-24 21:33:26 +02001702
1703 if (in_vim9script()
1704 && (check_for_string_arg(argvars, 0) == FAIL
1705 || (argvars[1].v_type != VAR_UNKNOWN
1706 && check_for_opt_dict_arg(argvars, 2) == FAIL)))
1707 return;
1708
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001709 path = tv_get_string(&argvars[0]);
1710 expr = &argvars[1];
1711
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001712 if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN &&
Bram Moolenaard83392a2022-09-01 12:22:46 +01001713 readdirex_dict_arg(argvars, &sort) == FAIL)
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001714 return;
1715
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001716 ret = readdir_core(&ga, path, FALSE, (void *)expr,
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001717 (expr->v_type == VAR_UNKNOWN) ? NULL : readdir_checkitem, sort);
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001718 if (ret == OK)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001719 {
1720 for (i = 0; i < ga.ga_len; i++)
1721 {
1722 p = ((char_u **)ga.ga_data)[i];
1723 list_append_string(rettv->vval.v_list, p, -1);
1724 }
1725 }
1726 ga_clear_strings(&ga);
1727}
1728
1729/*
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001730 * Evaluate "expr" (= "context") for readdirex().
1731 */
1732 static int
1733readdirex_checkitem(void *context, void *item)
1734{
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001735 dict_T *dict = (dict_T*)item;
1736
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001737 return checkitem_common(context, NULL, dict);
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001738}
1739
1740/*
1741 * "readdirex()" function
1742 */
1743 void
1744f_readdirex(typval_T *argvars, typval_T *rettv)
1745{
1746 typval_T *expr;
1747 int ret;
1748 char_u *path;
1749 garray_T ga;
1750 int i;
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01001751 int sort = READDIR_SORT_BYTE;
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001752
1753 if (rettv_list_alloc(rettv) == FAIL)
1754 return;
Yegappan Lakshmanan5bca9062021-07-24 21:33:26 +02001755
1756 if (in_vim9script()
1757 && (check_for_string_arg(argvars, 0) == FAIL
1758 || (argvars[1].v_type != VAR_UNKNOWN
1759 && check_for_opt_dict_arg(argvars, 2) == FAIL)))
1760 return;
1761
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001762 path = tv_get_string(&argvars[0]);
1763 expr = &argvars[1];
1764
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001765 if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN &&
Bram Moolenaard83392a2022-09-01 12:22:46 +01001766 readdirex_dict_arg(argvars, &sort) == FAIL)
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001767 return;
1768
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001769 ret = readdir_core(&ga, path, TRUE, (void *)expr,
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001770 (expr->v_type == VAR_UNKNOWN) ? NULL : readdirex_checkitem, sort);
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001771 if (ret == OK)
1772 {
1773 for (i = 0; i < ga.ga_len; i++)
1774 {
1775 dict_T *dict = ((dict_T**)ga.ga_data)[i];
1776 list_append_dict(rettv->vval.v_list, dict);
1777 dict_unref(dict);
1778 }
1779 }
1780 ga_clear(&ga);
1781}
1782
1783/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001784 * "readfile()" function
1785 */
Bram Moolenaarc423ad72021-01-13 20:38:03 +01001786 static void
1787read_file_or_blob(typval_T *argvars, typval_T *rettv, int always_blob)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001788{
1789 int binary = FALSE;
Bram Moolenaarc423ad72021-01-13 20:38:03 +01001790 int blob = always_blob;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001791 int failed = FALSE;
1792 char_u *fname;
1793 FILE *fd;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001794 char_u buf[(IOSIZE/256)*256]; // rounded to avoid odd + 1
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001795 int io_size = sizeof(buf);
Bram Moolenaar26262f82019-09-04 20:59:15 +02001796 int readlen; // size of last fread()
1797 char_u *prev = NULL; // previously read bytes, if any
1798 long prevlen = 0; // length of data in prev
1799 long prevsize = 0; // size of prev buffer
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001800 long maxline = MAXLNUM;
1801 long cnt = 0;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001802 char_u *p; // position in buf
1803 char_u *start; // start of current line
K.Takata11df3ae2022-10-19 14:02:40 +01001804 off_T offset = 0;
1805 off_T size = -1;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001806
1807 if (argvars[1].v_type != VAR_UNKNOWN)
1808 {
K.Takata11df3ae2022-10-19 14:02:40 +01001809 if (always_blob)
1810 {
1811 offset = (off_T)tv_get_number(&argvars[1]);
1812 if (argvars[2].v_type != VAR_UNKNOWN)
1813 size = (off_T)tv_get_number(&argvars[2]);
1814 }
1815 else
1816 {
1817 if (STRCMP(tv_get_string(&argvars[1]), "b") == 0)
1818 binary = TRUE;
1819 if (STRCMP(tv_get_string(&argvars[1]), "B") == 0)
1820 blob = TRUE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001821
K.Takata11df3ae2022-10-19 14:02:40 +01001822 if (argvars[2].v_type != VAR_UNKNOWN)
1823 maxline = (long)tv_get_number(&argvars[2]);
1824 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001825 }
1826
Bram Moolenaar15352dc2020-04-06 21:12:42 +02001827 if ((blob ? rettv_blob_alloc(rettv) : rettv_list_alloc(rettv)) == FAIL)
1828 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001829
Bram Moolenaar26262f82019-09-04 20:59:15 +02001830 // Always open the file in binary mode, library functions have a mind of
1831 // their own about CR-LF conversion.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001832 fname = tv_get_string(&argvars[0]);
Bram Moolenaar15352dc2020-04-06 21:12:42 +02001833
1834 if (mch_isdir(fname))
1835 {
Bram Moolenaar4dea2d92022-03-31 11:37:57 +01001836 semsg(_(e_str_is_directory), fname);
Bram Moolenaar15352dc2020-04-06 21:12:42 +02001837 return;
1838 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001839 if (*fname == NUL || (fd = mch_fopen((char *)fname, READBIN)) == NULL)
1840 {
K.Takata11df3ae2022-10-19 14:02:40 +01001841 semsg(_(e_cant_open_file_str),
1842 *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001843 return;
1844 }
1845
1846 if (blob)
1847 {
K.Takata11df3ae2022-10-19 14:02:40 +01001848 if (read_blob(fd, rettv, offset, size) == FAIL)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00001849 semsg(_(e_cant_read_file_str), fname);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001850 fclose(fd);
1851 return;
1852 }
1853
1854 while (cnt < maxline || maxline < 0)
1855 {
1856 readlen = (int)fread(buf, 1, io_size, fd);
1857
Bram Moolenaar26262f82019-09-04 20:59:15 +02001858 // This for loop processes what was read, but is also entered at end
1859 // of file so that either:
1860 // - an incomplete line gets written
1861 // - a "binary" file gets an empty line at the end if it ends in a
1862 // newline.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001863 for (p = buf, start = buf;
1864 p < buf + readlen || (readlen <= 0 && (prevlen > 0 || binary));
1865 ++p)
1866 {
Dominique Pellef5d639a2022-01-12 15:24:40 +00001867 if (readlen <= 0 || *p == '\n')
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001868 {
1869 listitem_T *li;
1870 char_u *s = NULL;
1871 long_u len = p - start;
1872
Bram Moolenaar26262f82019-09-04 20:59:15 +02001873 // Finished a line. Remove CRs before NL.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001874 if (readlen > 0 && !binary)
1875 {
1876 while (len > 0 && start[len - 1] == '\r')
1877 --len;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001878 // removal may cross back to the "prev" string
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001879 if (len == 0)
1880 while (prevlen > 0 && prev[prevlen - 1] == '\r')
1881 --prevlen;
1882 }
1883 if (prevlen == 0)
Bram Moolenaar71ccd032020-06-12 22:59:11 +02001884 s = vim_strnsave(start, len);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001885 else
1886 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001887 // Change "prev" buffer to be the right size. This way
1888 // the bytes are only copied once, and very long lines are
1889 // allocated only once.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001890 if ((s = vim_realloc(prev, prevlen + len + 1)) != NULL)
1891 {
1892 mch_memmove(s + prevlen, start, len);
1893 s[prevlen + len] = NUL;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001894 prev = NULL; // the list will own the string
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001895 prevlen = prevsize = 0;
1896 }
1897 }
1898 if (s == NULL)
1899 {
1900 do_outofmem_msg((long_u) prevlen + len + 1);
1901 failed = TRUE;
1902 break;
1903 }
1904
1905 if ((li = listitem_alloc()) == NULL)
1906 {
1907 vim_free(s);
1908 failed = TRUE;
1909 break;
1910 }
1911 li->li_tv.v_type = VAR_STRING;
1912 li->li_tv.v_lock = 0;
1913 li->li_tv.vval.v_string = s;
1914 list_append(rettv->vval.v_list, li);
1915
Bram Moolenaar26262f82019-09-04 20:59:15 +02001916 start = p + 1; // step over newline
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001917 if ((++cnt >= maxline && maxline >= 0) || readlen <= 0)
1918 break;
1919 }
1920 else if (*p == NUL)
1921 *p = '\n';
Bram Moolenaar26262f82019-09-04 20:59:15 +02001922 // Check for utf8 "bom"; U+FEFF is encoded as EF BB BF. Do this
1923 // when finding the BF and check the previous two bytes.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001924 else if (*p == 0xbf && enc_utf8 && !binary)
1925 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001926 // Find the two bytes before the 0xbf. If p is at buf, or buf
1927 // + 1, these may be in the "prev" string.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001928 char_u back1 = p >= buf + 1 ? p[-1]
1929 : prevlen >= 1 ? prev[prevlen - 1] : NUL;
1930 char_u back2 = p >= buf + 2 ? p[-2]
1931 : p == buf + 1 && prevlen >= 1 ? prev[prevlen - 1]
1932 : prevlen >= 2 ? prev[prevlen - 2] : NUL;
1933
1934 if (back2 == 0xef && back1 == 0xbb)
1935 {
1936 char_u *dest = p - 2;
1937
Bram Moolenaar26262f82019-09-04 20:59:15 +02001938 // Usually a BOM is at the beginning of a file, and so at
1939 // the beginning of a line; then we can just step over it.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001940 if (start == dest)
1941 start = p + 1;
1942 else
1943 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001944 // have to shuffle buf to close gap
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001945 int adjust_prevlen = 0;
1946
1947 if (dest < buf)
1948 {
Bram Moolenaarc423ad72021-01-13 20:38:03 +01001949 // must be 1 or 2
1950 adjust_prevlen = (int)(buf - dest);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001951 dest = buf;
1952 }
1953 if (readlen > p - buf + 1)
1954 mch_memmove(dest, p + 1, readlen - (p - buf) - 1);
1955 readlen -= 3 - adjust_prevlen;
1956 prevlen -= adjust_prevlen;
1957 p = dest - 1;
1958 }
1959 }
1960 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02001961 } // for
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001962
1963 if (failed || (cnt >= maxline && maxline >= 0) || readlen <= 0)
1964 break;
1965 if (start < p)
1966 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001967 // There's part of a line in buf, store it in "prev".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001968 if (p - start + prevlen >= prevsize)
1969 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001970 // need bigger "prev" buffer
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001971 char_u *newprev;
1972
Bram Moolenaar26262f82019-09-04 20:59:15 +02001973 // A common use case is ordinary text files and "prev" gets a
1974 // fragment of a line, so the first allocation is made
1975 // small, to avoid repeatedly 'allocing' large and
1976 // 'reallocing' small.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001977 if (prevsize == 0)
1978 prevsize = (long)(p - start);
1979 else
1980 {
1981 long grow50pc = (prevsize * 3) / 2;
1982 long growmin = (long)((p - start) * 2 + prevlen);
1983 prevsize = grow50pc > growmin ? grow50pc : growmin;
1984 }
1985 newprev = vim_realloc(prev, prevsize);
1986 if (newprev == NULL)
1987 {
1988 do_outofmem_msg((long_u)prevsize);
1989 failed = TRUE;
1990 break;
1991 }
1992 prev = newprev;
1993 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02001994 // Add the line part to end of "prev".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001995 mch_memmove(prev + prevlen, start, p - start);
1996 prevlen += (long)(p - start);
1997 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02001998 } // while
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001999
Bram Moolenaar26262f82019-09-04 20:59:15 +02002000 // For a negative line count use only the lines at the end of the file,
2001 // free the rest.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002002 if (!failed && maxline < 0)
2003 while (cnt > -maxline)
2004 {
2005 listitem_remove(rettv->vval.v_list, rettv->vval.v_list->lv_first);
2006 --cnt;
2007 }
2008
2009 if (failed)
2010 {
2011 // an empty list is returned on error
2012 list_free(rettv->vval.v_list);
2013 rettv_list_alloc(rettv);
2014 }
2015
2016 vim_free(prev);
2017 fclose(fd);
2018}
2019
2020/*
Bram Moolenaarc423ad72021-01-13 20:38:03 +01002021 * "readblob()" function
2022 */
2023 void
2024f_readblob(typval_T *argvars, typval_T *rettv)
2025{
K.Takata11df3ae2022-10-19 14:02:40 +01002026 if (in_vim9script()
2027 && (check_for_string_arg(argvars, 0) == FAIL
2028 || check_for_opt_number_arg(argvars, 1) == FAIL
2029 || (argvars[1].v_type != VAR_UNKNOWN
2030 && check_for_opt_number_arg(argvars, 2) == FAIL)))
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02002031 return;
2032
Bram Moolenaarc423ad72021-01-13 20:38:03 +01002033 read_file_or_blob(argvars, rettv, TRUE);
2034}
2035
2036/*
2037 * "readfile()" function
2038 */
2039 void
2040f_readfile(typval_T *argvars, typval_T *rettv)
2041{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02002042 if (in_vim9script()
2043 && (check_for_nonempty_string_arg(argvars, 0) == FAIL
2044 || check_for_opt_string_arg(argvars, 1) == FAIL
2045 || (argvars[1].v_type != VAR_UNKNOWN
2046 && check_for_opt_number_arg(argvars, 2) == FAIL)))
2047 return;
2048
Bram Moolenaarc423ad72021-01-13 20:38:03 +01002049 read_file_or_blob(argvars, rettv, FALSE);
2050}
2051
2052/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002053 * "resolve()" function
2054 */
2055 void
2056f_resolve(typval_T *argvars, typval_T *rettv)
2057{
2058 char_u *p;
2059#ifdef HAVE_READLINK
2060 char_u *buf = NULL;
2061#endif
2062
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02002063 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
2064 return;
2065
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002066 p = tv_get_string(&argvars[0]);
2067#ifdef FEAT_SHORTCUT
2068 {
2069 char_u *v = NULL;
2070
2071 v = mch_resolve_path(p, TRUE);
2072 if (v != NULL)
2073 rettv->vval.v_string = v;
2074 else
2075 rettv->vval.v_string = vim_strsave(p);
2076 }
2077#else
2078# ifdef HAVE_READLINK
2079 {
2080 char_u *cpy;
Christian Brabandt6cc30272024-12-13 17:54:33 +01002081 int len;
2082 char_u *remain = NULL;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002083 char_u *q;
2084 int is_relative_to_current = FALSE;
2085 int has_trailing_pathsep = FALSE;
2086 int limit = 100;
2087
Christian Brabandt6cc30272024-12-13 17:54:33 +01002088 p = vim_strsave(p);
Bram Moolenaar70188f52019-12-23 18:18:52 +01002089 if (p == NULL)
2090 goto fail;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002091 if (p[0] == '.' && (vim_ispathsep(p[1])
2092 || (p[1] == '.' && (vim_ispathsep(p[2])))))
2093 is_relative_to_current = TRUE;
2094
Christian Brabandt6cc30272024-12-13 17:54:33 +01002095 len = STRLEN(p);
2096 if (len > 1 && after_pathsep(p, p + len))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002097 {
2098 has_trailing_pathsep = TRUE;
Christian Brabandt6cc30272024-12-13 17:54:33 +01002099 p[len - 1] = NUL; // the trailing slash breaks readlink()
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002100 }
2101
2102 q = getnextcomp(p);
2103 if (*q != NUL)
2104 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002105 // Separate the first path component in "p", and keep the
2106 // remainder (beginning with the path separator).
Christian Brabandt6cc30272024-12-13 17:54:33 +01002107 remain = vim_strsave(q - 1);
2108 q[-1] = NUL;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002109 }
2110
2111 buf = alloc(MAXPATHL + 1);
2112 if (buf == NULL)
Christian Brabandt6cc30272024-12-13 17:54:33 +01002113 {
2114 vim_free(p);
2115 vim_free(remain);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002116 goto fail;
Christian Brabandt6cc30272024-12-13 17:54:33 +01002117 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002118
2119 for (;;)
2120 {
2121 for (;;)
2122 {
Christian Brabandt6cc30272024-12-13 17:54:33 +01002123 len = readlink((char *)p, (char *)buf, MAXPATHL);
2124 if (len <= 0)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002125 break;
Christian Brabandt6cc30272024-12-13 17:54:33 +01002126 buf[len] = NUL;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002127
2128 if (limit-- == 0)
2129 {
Christian Brabandt6cc30272024-12-13 17:54:33 +01002130 vim_free(p);
2131 vim_free(remain);
Bram Moolenaara6f79292022-01-04 21:30:47 +00002132 emsg(_(e_too_many_symbolic_links_cycle));
Christian Brabandt6cc30272024-12-13 17:54:33 +01002133 rettv->vval.v_string = NULL;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002134 goto fail;
2135 }
2136
Bram Moolenaar26262f82019-09-04 20:59:15 +02002137 // Ensure that the result will have a trailing path separator
2138 // if the argument has one.
Christian Brabandt6cc30272024-12-13 17:54:33 +01002139 if (remain == NULL && has_trailing_pathsep)
2140 add_pathsep(buf);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002141
Bram Moolenaar26262f82019-09-04 20:59:15 +02002142 // Separate the first path component in the link value and
2143 // concatenate the remainders.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002144 q = getnextcomp(vim_ispathsep(*buf) ? buf + 1 : buf);
2145 if (*q != NUL)
2146 {
2147 if (remain == NULL)
Christian Brabandt6cc30272024-12-13 17:54:33 +01002148 remain = vim_strsave(q - 1);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002149 else
2150 {
Christian Brabandt6cc30272024-12-13 17:54:33 +01002151 cpy = concat_str(q - 1, remain);
2152 if (cpy != NULL)
2153 {
2154 vim_free(remain);
2155 remain = cpy;
2156 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002157 }
Christian Brabandt6cc30272024-12-13 17:54:33 +01002158 q[-1] = NUL;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002159 }
2160
2161 q = gettail(p);
2162 if (q > p && *q == NUL)
2163 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002164 // Ignore trailing path separator.
Christian Brabandt6cc30272024-12-13 17:54:33 +01002165 p[q - p - 1] = NUL;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002166 q = gettail(p);
2167 }
2168 if (q > p && !mch_isFullName(buf))
2169 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002170 // symlink is relative to directory of argument
Christian Brabandt6cc30272024-12-13 17:54:33 +01002171 cpy = alloc(STRLEN(p) + STRLEN(buf) + 1);
2172 if (cpy != NULL)
2173 {
2174 STRCPY(cpy, p);
2175 STRCPY(gettail(cpy), buf);
2176 vim_free(p);
2177 p = cpy;
2178 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002179 }
2180 else
2181 {
2182 vim_free(p);
Christian Brabandt6cc30272024-12-13 17:54:33 +01002183 p = vim_strsave(buf);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002184 }
2185 }
2186
2187 if (remain == NULL)
2188 break;
2189
Bram Moolenaar26262f82019-09-04 20:59:15 +02002190 // Append the first path component of "remain" to "p".
Christian Brabandt6cc30272024-12-13 17:54:33 +01002191 q = getnextcomp(remain + 1);
2192 len = q - remain - (*q != NUL);
2193 cpy = vim_strnsave(p, STRLEN(p) + len);
2194 if (cpy != NULL)
2195 {
2196 STRNCAT(cpy, remain, len);
2197 vim_free(p);
2198 p = cpy;
2199 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02002200 // Shorten "remain".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002201 if (*q != NUL)
Christian Brabandt6cc30272024-12-13 17:54:33 +01002202 STRMOVE(remain, q - 1);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002203 else
2204 VIM_CLEAR(remain);
2205 }
2206
Bram Moolenaar26262f82019-09-04 20:59:15 +02002207 // If the result is a relative path name, make it explicitly relative to
2208 // the current directory if and only if the argument had this form.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002209 if (!vim_ispathsep(*p))
2210 {
2211 if (is_relative_to_current
2212 && *p != NUL
2213 && !(p[0] == '.'
2214 && (p[1] == NUL
2215 || vim_ispathsep(p[1])
2216 || (p[1] == '.'
2217 && (p[2] == NUL
2218 || vim_ispathsep(p[2]))))))
2219 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002220 // Prepend "./".
Christian Brabandt6cc30272024-12-13 17:54:33 +01002221 cpy = concat_str((char_u *)"./", p);
2222 if (cpy != NULL)
2223 {
2224 vim_free(p);
2225 p = cpy;
2226 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002227 }
2228 else if (!is_relative_to_current)
2229 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002230 // Strip leading "./".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002231 q = p;
2232 while (q[0] == '.' && vim_ispathsep(q[1]))
2233 q += 2;
2234 if (q > p)
Christian Brabandt6cc30272024-12-13 17:54:33 +01002235 STRMOVE(p, p + 2);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002236 }
2237 }
2238
Bram Moolenaar26262f82019-09-04 20:59:15 +02002239 // Ensure that the result will have no trailing path separator
2240 // if the argument had none. But keep "/" or "//".
Christian Brabandt6cc30272024-12-13 17:54:33 +01002241 if (!has_trailing_pathsep)
2242 {
2243 q = p + STRLEN(p);
2244 if (after_pathsep(p, q))
2245 *gettail_sep(p) = NUL;
2246 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002247
2248 rettv->vval.v_string = p;
2249 }
2250# else
2251 rettv->vval.v_string = vim_strsave(p);
2252# endif
2253#endif
2254
2255 simplify_filename(rettv->vval.v_string);
2256
2257#ifdef HAVE_READLINK
2258fail:
2259 vim_free(buf);
2260#endif
2261 rettv->v_type = VAR_STRING;
2262}
2263
2264/*
2265 * "tempname()" function
2266 */
2267 void
2268f_tempname(typval_T *argvars UNUSED, typval_T *rettv)
2269{
2270 static int x = 'A';
2271
2272 rettv->v_type = VAR_STRING;
2273 rettv->vval.v_string = vim_tempname(x, FALSE);
2274
Bram Moolenaar26262f82019-09-04 20:59:15 +02002275 // Advance 'x' to use A-Z and 0-9, so that there are at least 34 different
2276 // names. Skip 'I' and 'O', they are used for shell redirection.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002277 do
2278 {
2279 if (x == 'Z')
2280 x = '0';
2281 else if (x == '9')
2282 x = 'A';
2283 else
Bram Moolenaar424bcae2022-01-31 14:59:41 +00002284 ++x;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002285 } while (x == 'I' || x == 'O');
2286}
2287
2288/*
2289 * "writefile()" function
2290 */
2291 void
2292f_writefile(typval_T *argvars, typval_T *rettv)
2293{
2294 int binary = FALSE;
2295 int append = FALSE;
Bram Moolenaar806a2732022-09-04 15:40:36 +01002296 int defer = FALSE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002297#ifdef HAVE_FSYNC
2298 int do_fsync = p_fs;
2299#endif
2300 char_u *fname;
2301 FILE *fd;
2302 int ret = 0;
2303 listitem_T *li;
2304 list_T *list = NULL;
2305 blob_T *blob = NULL;
2306
2307 rettv->vval.v_number = -1;
2308 if (check_secure())
2309 return;
2310
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02002311 if (in_vim9script()
2312 && (check_for_list_or_blob_arg(argvars, 0) == FAIL
2313 || check_for_string_arg(argvars, 1) == FAIL
2314 || check_for_opt_string_arg(argvars, 2) == FAIL))
2315 return;
2316
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002317 if (argvars[0].v_type == VAR_LIST)
2318 {
2319 list = argvars[0].vval.v_list;
2320 if (list == NULL)
2321 return;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02002322 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002323 FOR_ALL_LIST_ITEMS(list, li)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002324 if (tv_get_string_chk(&li->li_tv) == NULL)
2325 return;
2326 }
2327 else if (argvars[0].v_type == VAR_BLOB)
2328 {
2329 blob = argvars[0].vval.v_blob;
2330 if (blob == NULL)
2331 return;
2332 }
2333 else
2334 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00002335 semsg(_(e_invalid_argument_str),
Bram Moolenaar18a2b872020-03-19 13:08:45 +01002336 _("writefile() first argument must be a List or a Blob"));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002337 return;
2338 }
2339
2340 if (argvars[2].v_type != VAR_UNKNOWN)
2341 {
2342 char_u *arg2 = tv_get_string_chk(&argvars[2]);
2343
2344 if (arg2 == NULL)
2345 return;
2346 if (vim_strchr(arg2, 'b') != NULL)
2347 binary = TRUE;
2348 if (vim_strchr(arg2, 'a') != NULL)
2349 append = TRUE;
Bram Moolenaar806a2732022-09-04 15:40:36 +01002350 if (vim_strchr(arg2, 'D') != NULL)
2351 defer = TRUE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002352#ifdef HAVE_FSYNC
2353 if (vim_strchr(arg2, 's') != NULL)
2354 do_fsync = TRUE;
2355 else if (vim_strchr(arg2, 'S') != NULL)
2356 do_fsync = FALSE;
2357#endif
2358 }
2359
2360 fname = tv_get_string_chk(&argvars[1]);
2361 if (fname == NULL)
2362 return;
2363
Bram Moolenaar6f14da12022-09-07 21:30:44 +01002364 if (defer && !can_add_defer())
Bram Moolenaar806a2732022-09-04 15:40:36 +01002365 return;
Bram Moolenaar806a2732022-09-04 15:40:36 +01002366
Bram Moolenaar26262f82019-09-04 20:59:15 +02002367 // Always open the file in binary mode, library functions have a mind of
2368 // their own about CR-LF conversion.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002369 if (*fname == NUL || (fd = mch_fopen((char *)fname,
2370 append ? APPENDBIN : WRITEBIN)) == NULL)
2371 {
Bram Moolenaar806a2732022-09-04 15:40:36 +01002372 semsg(_(e_cant_create_file_str),
2373 *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002374 ret = -1;
2375 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002376 else
2377 {
Bram Moolenaar806a2732022-09-04 15:40:36 +01002378 if (defer)
2379 {
2380 typval_T tv;
2381
2382 tv.v_type = VAR_STRING;
2383 tv.v_lock = 0;
Bram Moolenaar6f14da12022-09-07 21:30:44 +01002384 tv.vval.v_string = FullName_save(fname, FALSE);
Bram Moolenaar806a2732022-09-04 15:40:36 +01002385 if (tv.vval.v_string == NULL
2386 || add_defer((char_u *)"delete", 1, &tv) == FAIL)
2387 {
2388 ret = -1;
2389 fclose(fd);
2390 (void)mch_remove(fname);
2391 }
2392 }
2393
2394 if (ret == 0)
2395 {
2396 if (blob)
2397 {
2398 if (write_blob(fd, blob) == FAIL)
2399 ret = -1;
2400 }
2401 else
2402 {
2403 if (write_list(fd, list, binary) == FAIL)
2404 ret = -1;
2405 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002406#ifdef HAVE_FSYNC
Bram Moolenaar806a2732022-09-04 15:40:36 +01002407 if (ret == 0 && do_fsync)
2408 // Ignore the error, the user wouldn't know what to do about
2409 // it. May happen for a device.
2410 vim_ignored = vim_fsync(fileno(fd));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002411#endif
Bram Moolenaar806a2732022-09-04 15:40:36 +01002412 fclose(fd);
2413 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002414 }
2415
2416 rettv->vval.v_number = ret;
2417}
2418
2419#endif // FEAT_EVAL
2420
2421#if defined(FEAT_BROWSE) || defined(PROTO)
2422/*
2423 * Generic browse function. Calls gui_mch_browse() when possible.
2424 * Later this may pop-up a non-GUI file selector (external command?).
2425 */
2426 char_u *
2427do_browse(
Bram Moolenaar26262f82019-09-04 20:59:15 +02002428 int flags, // BROWSE_SAVE and BROWSE_DIR
2429 char_u *title, // title for the window
2430 char_u *dflt, // default file name (may include directory)
2431 char_u *ext, // extension added
2432 char_u *initdir, // initial directory, NULL for current dir or
2433 // when using path from "dflt"
2434 char_u *filter, // file name filter
2435 buf_T *buf) // buffer to read/write for
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002436{
2437 char_u *fname;
Bram Moolenaar26262f82019-09-04 20:59:15 +02002438 static char_u *last_dir = NULL; // last used directory
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002439 char_u *tofree = NULL;
Bram Moolenaare1004402020-10-24 20:49:43 +02002440 int save_cmod_flags = cmdmod.cmod_flags;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002441
Bram Moolenaar26262f82019-09-04 20:59:15 +02002442 // Must turn off browse to avoid that autocommands will get the
2443 // flag too!
Bram Moolenaare1004402020-10-24 20:49:43 +02002444 cmdmod.cmod_flags &= ~CMOD_BROWSE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002445
2446 if (title == NULL || *title == NUL)
2447 {
2448 if (flags & BROWSE_DIR)
2449 title = (char_u *)_("Select Directory dialog");
2450 else if (flags & BROWSE_SAVE)
2451 title = (char_u *)_("Save File dialog");
2452 else
2453 title = (char_u *)_("Open File dialog");
2454 }
2455
Bram Moolenaar26262f82019-09-04 20:59:15 +02002456 // When no directory specified, use default file name, default dir, buffer
2457 // dir, last dir or current dir
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002458 if ((initdir == NULL || *initdir == NUL) && dflt != NULL && *dflt != NUL)
2459 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002460 if (mch_isdir(dflt)) // default file name is a directory
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002461 {
2462 initdir = dflt;
2463 dflt = NULL;
2464 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02002465 else if (gettail(dflt) != dflt) // default file name includes a path
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002466 {
2467 tofree = vim_strsave(dflt);
2468 if (tofree != NULL)
2469 {
2470 initdir = tofree;
2471 *gettail(initdir) = NUL;
2472 dflt = gettail(dflt);
2473 }
2474 }
2475 }
2476
2477 if (initdir == NULL || *initdir == NUL)
2478 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002479 // When 'browsedir' is a directory, use it
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002480 if (STRCMP(p_bsdir, "last") != 0
2481 && STRCMP(p_bsdir, "buffer") != 0
2482 && STRCMP(p_bsdir, "current") != 0
2483 && mch_isdir(p_bsdir))
2484 initdir = p_bsdir;
Bram Moolenaar26262f82019-09-04 20:59:15 +02002485 // When saving or 'browsedir' is "buffer", use buffer fname
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002486 else if (((flags & BROWSE_SAVE) || *p_bsdir == 'b')
2487 && buf != NULL && buf->b_ffname != NULL)
2488 {
2489 if (dflt == NULL || *dflt == NUL)
2490 dflt = gettail(curbuf->b_ffname);
2491 tofree = vim_strsave(curbuf->b_ffname);
2492 if (tofree != NULL)
2493 {
2494 initdir = tofree;
2495 *gettail(initdir) = NUL;
2496 }
2497 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02002498 // When 'browsedir' is "last", use dir from last browse
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002499 else if (*p_bsdir == 'l')
2500 initdir = last_dir;
Bram Moolenaar26262f82019-09-04 20:59:15 +02002501 // When 'browsedir is "current", use current directory. This is the
2502 // default already, leave initdir empty.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002503 }
2504
2505# ifdef FEAT_GUI
Bram Moolenaar26262f82019-09-04 20:59:15 +02002506 if (gui.in_use) // when this changes, also adjust f_has()!
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002507 {
2508 if (filter == NULL
2509# ifdef FEAT_EVAL
2510 && (filter = get_var_value((char_u *)"b:browsefilter")) == NULL
2511 && (filter = get_var_value((char_u *)"g:browsefilter")) == NULL
2512# endif
2513 )
2514 filter = BROWSE_FILTER_DEFAULT;
2515 if (flags & BROWSE_DIR)
2516 {
2517# if defined(FEAT_GUI_GTK) || defined(MSWIN)
Bram Moolenaar26262f82019-09-04 20:59:15 +02002518 // For systems that have a directory dialog.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002519 fname = gui_mch_browsedir(title, initdir);
2520# else
Bram Moolenaar26262f82019-09-04 20:59:15 +02002521 // Generic solution for selecting a directory: select a file and
2522 // remove the file name.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002523 fname = gui_mch_browse(0, title, dflt, ext, initdir, (char_u *)"");
2524# endif
2525# if !defined(FEAT_GUI_GTK)
Bram Moolenaar26262f82019-09-04 20:59:15 +02002526 // Win32 adds a dummy file name, others return an arbitrary file
2527 // name. GTK+ 2 returns only the directory,
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002528 if (fname != NULL && *fname != NUL && !mch_isdir(fname))
2529 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002530 // Remove the file name.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002531 char_u *tail = gettail_sep(fname);
2532
2533 if (tail == fname)
Bram Moolenaar26262f82019-09-04 20:59:15 +02002534 *tail++ = '.'; // use current dir
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002535 *tail = NUL;
2536 }
2537# endif
2538 }
2539 else
2540 fname = gui_mch_browse(flags & BROWSE_SAVE,
2541 title, dflt, ext, initdir, (char_u *)_(filter));
2542
Bram Moolenaar26262f82019-09-04 20:59:15 +02002543 // We hang around in the dialog for a while, the user might do some
2544 // things to our files. The Win32 dialog allows deleting or renaming
2545 // a file, check timestamps.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002546 need_check_timestamps = TRUE;
2547 did_check_timestamps = FALSE;
2548 }
2549 else
2550# endif
2551 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002552 // TODO: non-GUI file selector here
Bram Moolenaareaaac012022-01-02 17:00:40 +00002553 emsg(_(e_sorry_no_file_browser_in_console_mode));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002554 fname = NULL;
2555 }
2556
Bram Moolenaar26262f82019-09-04 20:59:15 +02002557 // keep the directory for next time
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002558 if (fname != NULL)
2559 {
2560 vim_free(last_dir);
2561 last_dir = vim_strsave(fname);
2562 if (last_dir != NULL && !(flags & BROWSE_DIR))
2563 {
2564 *gettail(last_dir) = NUL;
2565 if (*last_dir == NUL)
2566 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002567 // filename only returned, must be in current dir
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002568 vim_free(last_dir);
2569 last_dir = alloc(MAXPATHL);
2570 if (last_dir != NULL)
2571 mch_dirname(last_dir, MAXPATHL);
2572 }
2573 }
2574 }
2575
2576 vim_free(tofree);
Bram Moolenaare1004402020-10-24 20:49:43 +02002577 cmdmod.cmod_flags = save_cmod_flags;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002578
2579 return fname;
2580}
2581#endif
2582
2583#if defined(FEAT_EVAL) || defined(PROTO)
2584
2585/*
2586 * "browse(save, title, initdir, default)" function
2587 */
2588 void
2589f_browse(typval_T *argvars UNUSED, typval_T *rettv)
2590{
2591# ifdef FEAT_BROWSE
2592 int save;
2593 char_u *title;
2594 char_u *initdir;
2595 char_u *defname;
2596 char_u buf[NUMBUFLEN];
2597 char_u buf2[NUMBUFLEN];
2598 int error = FALSE;
2599
Bram Moolenaarf28f2ac2021-03-22 22:21:26 +01002600 if (in_vim9script()
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02002601 && (check_for_bool_arg(argvars, 0) == FAIL
2602 || check_for_string_arg(argvars, 1) == FAIL
Bram Moolenaar32105ae2021-03-27 18:59:25 +01002603 || check_for_string_arg(argvars, 2) == FAIL
2604 || check_for_string_arg(argvars, 3) == FAIL))
Bram Moolenaarf28f2ac2021-03-22 22:21:26 +01002605 return;
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02002606
Bram Moolenaar5a049842022-10-08 12:52:09 +01002607 save = (int)tv_get_bool_chk(&argvars[0], &error);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002608 title = tv_get_string_chk(&argvars[1]);
2609 initdir = tv_get_string_buf_chk(&argvars[2], buf);
2610 defname = tv_get_string_buf_chk(&argvars[3], buf2);
2611
2612 if (error || title == NULL || initdir == NULL || defname == NULL)
2613 rettv->vval.v_string = NULL;
2614 else
2615 rettv->vval.v_string =
2616 do_browse(save ? BROWSE_SAVE : 0,
2617 title, defname, NULL, initdir, NULL, curbuf);
2618# else
2619 rettv->vval.v_string = NULL;
2620# endif
2621 rettv->v_type = VAR_STRING;
2622}
2623
2624/*
2625 * "browsedir(title, initdir)" function
2626 */
2627 void
2628f_browsedir(typval_T *argvars UNUSED, typval_T *rettv)
2629{
2630# ifdef FEAT_BROWSE
2631 char_u *title;
2632 char_u *initdir;
2633 char_u buf[NUMBUFLEN];
2634
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02002635 if (in_vim9script()
2636 && (check_for_string_arg(argvars, 0) == FAIL
2637 || check_for_string_arg(argvars, 1) == FAIL))
2638 return;
2639
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002640 title = tv_get_string_chk(&argvars[0]);
2641 initdir = tv_get_string_buf_chk(&argvars[1], buf);
2642
2643 if (title == NULL || initdir == NULL)
2644 rettv->vval.v_string = NULL;
2645 else
2646 rettv->vval.v_string = do_browse(BROWSE_DIR,
2647 title, NULL, NULL, initdir, NULL, curbuf);
2648# else
2649 rettv->vval.v_string = NULL;
2650# endif
2651 rettv->v_type = VAR_STRING;
2652}
2653
Shougo Matsushita60c87432024-06-03 22:59:27 +02002654/*
2655 * "filecopy()" function
2656 */
2657 void
2658f_filecopy(typval_T *argvars, typval_T *rettv)
2659{
2660 char_u *from;
2661 stat_T st;
2662
2663 rettv->vval.v_number = FALSE;
2664
2665 if (check_restricted() || check_secure()
2666 || check_for_string_arg(argvars, 0) == FAIL
2667 || check_for_string_arg(argvars, 1) == FAIL)
2668 return;
2669
2670 from = tv_get_string(&argvars[0]);
2671
2672 if (mch_lstat((char *)from, &st) >= 0
2673 && (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)))
2674 rettv->vval.v_number = vim_copyfile(
2675 tv_get_string(&argvars[0]),
2676 tv_get_string(&argvars[1])) == OK ? TRUE : FALSE;
2677}
2678
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002679#endif // FEAT_EVAL
Bram Moolenaar26262f82019-09-04 20:59:15 +02002680
2681/*
2682 * Replace home directory by "~" in each space or comma separated file name in
2683 * 'src'.
2684 * If anything fails (except when out of space) dst equals src.
2685 */
2686 void
2687home_replace(
2688 buf_T *buf, // when not NULL, check for help files
2689 char_u *src, // input file name
2690 char_u *dst, // where to put the result
2691 int dstlen, // maximum length of the result
2692 int one) // if TRUE, only replace one file name, include
2693 // spaces and commas in the file name.
2694{
2695 size_t dirlen = 0, envlen = 0;
2696 size_t len;
2697 char_u *homedir_env, *homedir_env_orig;
2698 char_u *p;
2699
2700 if (src == NULL)
2701 {
2702 *dst = NUL;
2703 return;
2704 }
2705
2706 /*
2707 * If the file is a help file, remove the path completely.
2708 */
2709 if (buf != NULL && buf->b_help)
2710 {
2711 vim_snprintf((char *)dst, dstlen, "%s", gettail(src));
2712 return;
2713 }
2714
2715 /*
2716 * We check both the value of the $HOME environment variable and the
2717 * "real" home directory.
2718 */
2719 if (homedir != NULL)
2720 dirlen = STRLEN(homedir);
2721
2722#ifdef VMS
2723 homedir_env_orig = homedir_env = mch_getenv((char_u *)"SYS$LOGIN");
2724#else
2725 homedir_env_orig = homedir_env = mch_getenv((char_u *)"HOME");
2726#endif
2727#ifdef MSWIN
2728 if (homedir_env == NULL)
2729 homedir_env_orig = homedir_env = mch_getenv((char_u *)"USERPROFILE");
2730#endif
2731 // Empty is the same as not set.
2732 if (homedir_env != NULL && *homedir_env == NUL)
2733 homedir_env = NULL;
2734
2735 if (homedir_env != NULL && *homedir_env == '~')
2736 {
Mike Williams51024bb2024-05-30 07:46:30 +02002737 size_t usedlen = 0;
Bram Moolenaar26262f82019-09-04 20:59:15 +02002738 int flen;
2739 char_u *fbuf = NULL;
2740
2741 flen = (int)STRLEN(homedir_env);
2742 (void)modify_fname((char_u *)":p", FALSE, &usedlen,
2743 &homedir_env, &fbuf, &flen);
2744 flen = (int)STRLEN(homedir_env);
2745 if (flen > 0 && vim_ispathsep(homedir_env[flen - 1]))
2746 // Remove the trailing / that is added to a directory.
2747 homedir_env[flen - 1] = NUL;
2748 }
2749
2750 if (homedir_env != NULL)
2751 envlen = STRLEN(homedir_env);
2752
2753 if (!one)
2754 src = skipwhite(src);
2755 while (*src && dstlen > 0)
2756 {
2757 /*
2758 * Here we are at the beginning of a file name.
2759 * First, check to see if the beginning of the file name matches
2760 * $HOME or the "real" home directory. Check that there is a '/'
2761 * after the match (so that if e.g. the file is "/home/pieter/bla",
2762 * and the home directory is "/home/piet", the file does not end up
2763 * as "~er/bla" (which would seem to indicate the file "bla" in user
2764 * er's home directory)).
2765 */
2766 p = homedir;
2767 len = dirlen;
2768 for (;;)
2769 {
2770 if ( len
2771 && fnamencmp(src, p, len) == 0
2772 && (vim_ispathsep(src[len])
2773 || (!one && (src[len] == ',' || src[len] == ' '))
2774 || src[len] == NUL))
2775 {
2776 src += len;
2777 if (--dstlen > 0)
2778 *dst++ = '~';
2779
Bram Moolenaar0e390f42020-06-10 13:12:28 +02002780 // Do not add directory separator into dst, because dst is
2781 // expected to just return the directory name without the
2782 // directory separator '/'.
Bram Moolenaar26262f82019-09-04 20:59:15 +02002783 break;
2784 }
2785 if (p == homedir_env)
2786 break;
2787 p = homedir_env;
2788 len = envlen;
2789 }
2790
2791 // if (!one) skip to separator: space or comma
2792 while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0)
2793 *dst++ = *src++;
2794 // skip separator
2795 while ((*src == ' ' || *src == ',') && --dstlen > 0)
2796 *dst++ = *src++;
2797 }
2798 // if (dstlen == 0) out of space, what to do???
2799
2800 *dst = NUL;
2801
2802 if (homedir_env != homedir_env_orig)
2803 vim_free(homedir_env);
2804}
2805
2806/*
2807 * Like home_replace, store the replaced string in allocated memory.
2808 * When something fails, NULL is returned.
2809 */
2810 char_u *
2811home_replace_save(
2812 buf_T *buf, // when not NULL, check for help files
2813 char_u *src) // input file name
2814{
2815 char_u *dst;
2816 unsigned len;
2817
2818 len = 3; // space for "~/" and trailing NUL
2819 if (src != NULL) // just in case
2820 len += (unsigned)STRLEN(src);
2821 dst = alloc(len);
2822 if (dst != NULL)
2823 home_replace(buf, src, dst, len, TRUE);
2824 return dst;
2825}
2826
2827/*
2828 * Compare two file names and return:
2829 * FPC_SAME if they both exist and are the same file.
2830 * FPC_SAMEX if they both don't exist and have the same file name.
2831 * FPC_DIFF if they both exist and are different files.
2832 * FPC_NOTX if they both don't exist.
2833 * FPC_DIFFX if one of them doesn't exist.
2834 * For the first name environment variables are expanded if "expandenv" is
2835 * TRUE.
2836 */
2837 int
2838fullpathcmp(
2839 char_u *s1,
2840 char_u *s2,
2841 int checkname, // when both don't exist, check file names
2842 int expandenv)
2843{
2844#ifdef UNIX
2845 char_u exp1[MAXPATHL];
2846 char_u full1[MAXPATHL];
2847 char_u full2[MAXPATHL];
2848 stat_T st1, st2;
2849 int r1, r2;
2850
2851 if (expandenv)
2852 expand_env(s1, exp1, MAXPATHL);
2853 else
2854 vim_strncpy(exp1, s1, MAXPATHL - 1);
2855 r1 = mch_stat((char *)exp1, &st1);
2856 r2 = mch_stat((char *)s2, &st2);
2857 if (r1 != 0 && r2 != 0)
2858 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002859 // if mch_stat() doesn't work, may compare the names
Bram Moolenaar26262f82019-09-04 20:59:15 +02002860 if (checkname)
2861 {
2862 if (fnamecmp(exp1, s2) == 0)
2863 return FPC_SAMEX;
2864 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
2865 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
2866 if (r1 == OK && r2 == OK && fnamecmp(full1, full2) == 0)
2867 return FPC_SAMEX;
2868 }
2869 return FPC_NOTX;
2870 }
2871 if (r1 != 0 || r2 != 0)
2872 return FPC_DIFFX;
2873 if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
2874 return FPC_SAME;
2875 return FPC_DIFF;
2876#else
2877 char_u *exp1; // expanded s1
2878 char_u *full1; // full path of s1
2879 char_u *full2; // full path of s2
2880 int retval = FPC_DIFF;
2881 int r1, r2;
2882
2883 // allocate one buffer to store three paths (alloc()/free() is slow!)
2884 if ((exp1 = alloc(MAXPATHL * 3)) != NULL)
2885 {
2886 full1 = exp1 + MAXPATHL;
2887 full2 = full1 + MAXPATHL;
2888
2889 if (expandenv)
2890 expand_env(s1, exp1, MAXPATHL);
2891 else
2892 vim_strncpy(exp1, s1, MAXPATHL - 1);
2893 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
2894 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
2895
2896 // If vim_FullName() fails, the file probably doesn't exist.
2897 if (r1 != OK && r2 != OK)
2898 {
2899 if (checkname && fnamecmp(exp1, s2) == 0)
2900 retval = FPC_SAMEX;
2901 else
2902 retval = FPC_NOTX;
2903 }
2904 else if (r1 != OK || r2 != OK)
2905 retval = FPC_DIFFX;
2906 else if (fnamecmp(full1, full2))
2907 retval = FPC_DIFF;
2908 else
2909 retval = FPC_SAME;
2910 vim_free(exp1);
2911 }
2912 return retval;
2913#endif
2914}
2915
2916/*
2917 * Get the tail of a path: the file name.
2918 * When the path ends in a path separator the tail is the NUL after it.
2919 * Fail safe: never returns NULL.
2920 */
2921 char_u *
2922gettail(char_u *fname)
2923{
2924 char_u *p1, *p2;
2925
2926 if (fname == NULL)
2927 return (char_u *)"";
2928 for (p1 = p2 = get_past_head(fname); *p2; ) // find last part of path
2929 {
2930 if (vim_ispathsep_nocolon(*p2))
2931 p1 = p2 + 1;
2932 MB_PTR_ADV(p2);
2933 }
2934 return p1;
2935}
2936
2937/*
2938 * Get pointer to tail of "fname", including path separators. Putting a NUL
2939 * here leaves the directory name. Takes care of "c:/" and "//".
2940 * Always returns a valid pointer.
2941 */
2942 char_u *
2943gettail_sep(char_u *fname)
2944{
2945 char_u *p;
2946 char_u *t;
2947
2948 p = get_past_head(fname); // don't remove the '/' from "c:/file"
2949 t = gettail(fname);
2950 while (t > p && after_pathsep(fname, t))
2951 --t;
2952#ifdef VMS
2953 // path separator is part of the path
2954 ++t;
2955#endif
2956 return t;
2957}
2958
2959/*
2960 * get the next path component (just after the next path separator).
2961 */
2962 char_u *
2963getnextcomp(char_u *fname)
2964{
2965 while (*fname && !vim_ispathsep(*fname))
2966 MB_PTR_ADV(fname);
2967 if (*fname)
2968 ++fname;
2969 return fname;
2970}
2971
2972/*
2973 * Get a pointer to one character past the head of a path name.
2974 * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
2975 * If there is no head, path is returned.
2976 */
2977 char_u *
2978get_past_head(char_u *path)
2979{
2980 char_u *retval;
2981
2982#if defined(MSWIN)
2983 // may skip "c:"
Keith Thompson184f71c2024-01-04 21:19:04 +01002984 if (SAFE_isalpha(path[0]) && path[1] == ':')
Bram Moolenaar26262f82019-09-04 20:59:15 +02002985 retval = path + 2;
2986 else
2987 retval = path;
2988#else
2989# if defined(AMIGA)
2990 // may skip "label:"
2991 retval = vim_strchr(path, ':');
2992 if (retval == NULL)
2993 retval = path;
2994# else // Unix
2995 retval = path;
2996# endif
2997#endif
2998
2999 while (vim_ispathsep(*retval))
3000 ++retval;
3001
3002 return retval;
3003}
3004
3005/*
3006 * Return TRUE if 'c' is a path separator.
3007 * Note that for MS-Windows this includes the colon.
3008 */
3009 int
3010vim_ispathsep(int c)
3011{
3012#ifdef UNIX
3013 return (c == '/'); // UNIX has ':' inside file names
3014#else
3015# ifdef BACKSLASH_IN_FILENAME
3016 return (c == ':' || c == '/' || c == '\\');
3017# else
3018# ifdef VMS
3019 // server"user passwd"::device:[full.path.name]fname.extension;version"
3020 return (c == ':' || c == '[' || c == ']' || c == '/'
3021 || c == '<' || c == '>' || c == '"' );
3022# else
3023 return (c == ':' || c == '/');
3024# endif // VMS
3025# endif
3026#endif
3027}
3028
3029/*
3030 * Like vim_ispathsep(c), but exclude the colon for MS-Windows.
3031 */
3032 int
3033vim_ispathsep_nocolon(int c)
3034{
3035 return vim_ispathsep(c)
3036#ifdef BACKSLASH_IN_FILENAME
3037 && c != ':'
3038#endif
3039 ;
3040}
3041
3042/*
Bram Moolenaar26262f82019-09-04 20:59:15 +02003043 * Return TRUE if the directory of "fname" exists, FALSE otherwise.
3044 * Also returns TRUE if there is no directory name.
3045 * "fname" must be writable!.
3046 */
3047 int
3048dir_of_file_exists(char_u *fname)
3049{
3050 char_u *p;
3051 int c;
3052 int retval;
3053
3054 p = gettail_sep(fname);
3055 if (p == fname)
3056 return TRUE;
3057 c = *p;
3058 *p = NUL;
3059 retval = mch_isdir(fname);
3060 *p = c;
3061 return retval;
3062}
3063
3064/*
3065 * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally
3066 * and deal with 'fileignorecase'.
3067 */
3068 int
3069vim_fnamecmp(char_u *x, char_u *y)
3070{
3071#ifdef BACKSLASH_IN_FILENAME
3072 return vim_fnamencmp(x, y, MAXPATHL);
3073#else
3074 if (p_fic)
3075 return MB_STRICMP(x, y);
3076 return STRCMP(x, y);
3077#endif
3078}
3079
3080 int
3081vim_fnamencmp(char_u *x, char_u *y, size_t len)
3082{
3083#ifdef BACKSLASH_IN_FILENAME
3084 char_u *px = x;
3085 char_u *py = y;
3086 int cx = NUL;
3087 int cy = NUL;
3088
3089 while (len > 0)
3090 {
3091 cx = PTR2CHAR(px);
3092 cy = PTR2CHAR(py);
3093 if (cx == NUL || cy == NUL
3094 || ((p_fic ? MB_TOLOWER(cx) != MB_TOLOWER(cy) : cx != cy)
3095 && !(cx == '/' && cy == '\\')
3096 && !(cx == '\\' && cy == '/')))
3097 break;
Bram Moolenaar1614a142019-10-06 22:00:13 +02003098 len -= mb_ptr2len(px);
3099 px += mb_ptr2len(px);
3100 py += mb_ptr2len(py);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003101 }
3102 if (len == 0)
3103 return 0;
3104 return (cx - cy);
3105#else
3106 if (p_fic)
3107 return MB_STRNICMP(x, y, len);
3108 return STRNCMP(x, y, len);
3109#endif
3110}
3111
3112/*
3113 * Concatenate file names fname1 and fname2 into allocated memory.
3114 * Only add a '/' or '\\' when 'sep' is TRUE and it is necessary.
3115 */
3116 char_u *
3117concat_fnames(char_u *fname1, char_u *fname2, int sep)
3118{
3119 char_u *dest;
3120
Christian Brabandt6cc30272024-12-13 17:54:33 +01003121 dest = alloc(STRLEN(fname1) + STRLEN(fname2) + 3);
Yegappan Lakshmanan1cfb14a2023-01-09 19:04:23 +00003122 if (dest == NULL)
3123 return NULL;
3124
Christian Brabandt6cc30272024-12-13 17:54:33 +01003125 STRCPY(dest, fname1);
3126 if (sep)
3127 add_pathsep(dest);
3128 STRCAT(dest, fname2);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003129 return dest;
3130}
3131
3132/*
3133 * Add a path separator to a file name, unless it already ends in a path
3134 * separator.
3135 */
3136 void
3137add_pathsep(char_u *p)
3138{
Christian Brabandt6cc30272024-12-13 17:54:33 +01003139 if (*p != NUL && !after_pathsep(p, p + STRLEN(p)))
3140 STRCAT(p, PATHSEPSTR);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003141}
3142
3143/*
3144 * FullName_save - Make an allocated copy of a full file name.
3145 * Returns NULL when out of memory.
3146 */
3147 char_u *
3148FullName_save(
3149 char_u *fname,
3150 int force) // force expansion, even when it already looks
3151 // like a full path name
3152{
3153 char_u *buf;
3154 char_u *new_fname = NULL;
3155
3156 if (fname == NULL)
3157 return NULL;
3158
3159 buf = alloc(MAXPATHL);
Yegappan Lakshmanan1cfb14a2023-01-09 19:04:23 +00003160 if (buf == NULL)
3161 return NULL;
3162
3163 if (vim_FullName(fname, buf, MAXPATHL, force) != FAIL)
3164 new_fname = vim_strsave(buf);
3165 else
3166 new_fname = vim_strsave(fname);
3167 vim_free(buf);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003168 return new_fname;
3169}
3170
3171/*
3172 * return TRUE if "fname" exists.
3173 */
3174 int
3175vim_fexists(char_u *fname)
3176{
3177 stat_T st;
3178
3179 if (mch_stat((char *)fname, &st))
3180 return FALSE;
3181 return TRUE;
3182}
3183
3184/*
3185 * Invoke expand_wildcards() for one pattern.
3186 * Expand items like "%:h" before the expansion.
3187 * Returns OK or FAIL.
3188 */
3189 int
3190expand_wildcards_eval(
3191 char_u **pat, // pointer to input pattern
3192 int *num_file, // resulting number of files
3193 char_u ***file, // array of resulting files
3194 int flags) // EW_DIR, etc.
3195{
3196 int ret = FAIL;
3197 char_u *eval_pat = NULL;
3198 char_u *exp_pat = *pat;
Bram Moolenaarf5724372022-09-02 19:45:15 +01003199 char *ignored_msg;
Mike Williams51024bb2024-05-30 07:46:30 +02003200 size_t usedlen;
Bram Moolenaarf5724372022-09-02 19:45:15 +01003201 int is_cur_alt_file = *exp_pat == '%' || *exp_pat == '#';
3202 int star_follows = FALSE;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003203
Bram Moolenaarf5724372022-09-02 19:45:15 +01003204 if (is_cur_alt_file || *exp_pat == '<')
Bram Moolenaar26262f82019-09-04 20:59:15 +02003205 {
3206 ++emsg_off;
3207 eval_pat = eval_vars(exp_pat, exp_pat, &usedlen,
Bram Moolenaara96edb72022-04-28 17:52:24 +01003208 NULL, &ignored_msg, NULL, TRUE);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003209 --emsg_off;
3210 if (eval_pat != NULL)
Bram Moolenaarf5724372022-09-02 19:45:15 +01003211 {
3212 star_follows = STRCMP(exp_pat + usedlen, "*") == 0;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003213 exp_pat = concat_str(eval_pat, exp_pat + usedlen);
Bram Moolenaarf5724372022-09-02 19:45:15 +01003214 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02003215 }
3216
3217 if (exp_pat != NULL)
3218 ret = expand_wildcards(1, &exp_pat, num_file, file, flags);
3219
3220 if (eval_pat != NULL)
3221 {
Bram Moolenaarf5724372022-09-02 19:45:15 +01003222 if (*num_file == 0 && is_cur_alt_file && star_follows)
3223 {
3224 // Expanding "%" or "#" and the file does not exist: Add the
3225 // pattern anyway (without the star) so that this works for remote
3226 // files and non-file buffer names.
3227 *file = ALLOC_ONE(char_u *);
3228 if (*file != NULL)
3229 {
3230 **file = eval_pat;
3231 eval_pat = NULL;
3232 *num_file = 1;
3233 ret = OK;
3234 }
3235 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02003236 vim_free(exp_pat);
3237 vim_free(eval_pat);
3238 }
3239
3240 return ret;
3241}
3242
3243/*
3244 * Expand wildcards. Calls gen_expand_wildcards() and removes files matching
3245 * 'wildignore'.
3246 * Returns OK or FAIL. When FAIL then "num_files" won't be set.
3247 */
3248 int
3249expand_wildcards(
3250 int num_pat, // number of input patterns
3251 char_u **pat, // array of input patterns
3252 int *num_files, // resulting number of files
3253 char_u ***files, // array of resulting files
3254 int flags) // EW_DIR, etc.
3255{
3256 int retval;
3257 int i, j;
3258 char_u *p;
3259 int non_suf_match; // number without matching suffix
3260
3261 retval = gen_expand_wildcards(num_pat, pat, num_files, files, flags);
3262
3263 // When keeping all matches, return here
3264 if ((flags & EW_KEEPALL) || retval == FAIL)
3265 return retval;
3266
Bram Moolenaar26262f82019-09-04 20:59:15 +02003267 /*
3268 * Remove names that match 'wildignore'.
3269 */
3270 if (*p_wig)
3271 {
3272 char_u *ffname;
3273
3274 // check all files in (*files)[]
3275 for (i = 0; i < *num_files; ++i)
3276 {
3277 ffname = FullName_save((*files)[i], FALSE);
3278 if (ffname == NULL) // out of memory
3279 break;
3280# ifdef VMS
3281 vms_remove_version(ffname);
3282# endif
3283 if (match_file_list(p_wig, (*files)[i], ffname))
3284 {
3285 // remove this matching file from the list
3286 vim_free((*files)[i]);
3287 for (j = i; j + 1 < *num_files; ++j)
3288 (*files)[j] = (*files)[j + 1];
3289 --*num_files;
3290 --i;
3291 }
3292 vim_free(ffname);
3293 }
3294
3295 // If the number of matches is now zero, we fail.
3296 if (*num_files == 0)
3297 {
3298 VIM_CLEAR(*files);
3299 return FAIL;
3300 }
3301 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02003302
3303 /*
3304 * Move the names where 'suffixes' match to the end.
Bram Moolenaar57e95172022-08-20 19:26:14 +01003305 * Skip when interrupted, the result probably won't be used.
Bram Moolenaar26262f82019-09-04 20:59:15 +02003306 */
Bram Moolenaar57e95172022-08-20 19:26:14 +01003307 if (*num_files > 1 && !got_int)
Bram Moolenaar26262f82019-09-04 20:59:15 +02003308 {
3309 non_suf_match = 0;
3310 for (i = 0; i < *num_files; ++i)
3311 {
3312 if (!match_suffix((*files)[i]))
3313 {
3314 /*
3315 * Move the name without matching suffix to the front
3316 * of the list.
3317 */
3318 p = (*files)[i];
3319 for (j = i; j > non_suf_match; --j)
3320 (*files)[j] = (*files)[j - 1];
3321 (*files)[non_suf_match++] = p;
3322 }
3323 }
3324 }
3325
3326 return retval;
3327}
3328
3329/*
3330 * Return TRUE if "fname" matches with an entry in 'suffixes'.
3331 */
3332 int
3333match_suffix(char_u *fname)
3334{
3335 int fnamelen, setsuflen;
3336 char_u *setsuf;
3337#define MAXSUFLEN 30 // maximum length of a file suffix
3338 char_u suf_buf[MAXSUFLEN];
3339
3340 fnamelen = (int)STRLEN(fname);
3341 setsuflen = 0;
3342 for (setsuf = p_su; *setsuf; )
3343 {
3344 setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
3345 if (setsuflen == 0)
3346 {
3347 char_u *tail = gettail(fname);
3348
3349 // empty entry: match name without a '.'
3350 if (vim_strchr(tail, '.') == NULL)
3351 {
3352 setsuflen = 1;
3353 break;
3354 }
3355 }
3356 else
3357 {
3358 if (fnamelen >= setsuflen
3359 && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
3360 (size_t)setsuflen) == 0)
3361 break;
3362 setsuflen = 0;
3363 }
3364 }
3365 return (setsuflen != 0);
3366}
3367
3368#ifdef VIM_BACKTICK
3369
3370/*
3371 * Return TRUE if we can expand this backtick thing here.
3372 */
3373 static int
3374vim_backtick(char_u *p)
3375{
3376 return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
3377}
3378
3379/*
3380 * Expand an item in `backticks` by executing it as a command.
3381 * Currently only works when pat[] starts and ends with a `.
3382 * Returns number of file names found, -1 if an error is encountered.
3383 */
3384 static int
3385expand_backtick(
3386 garray_T *gap,
3387 char_u *pat,
3388 int flags) // EW_* flags
3389{
3390 char_u *p;
3391 char_u *cmd;
3392 char_u *buffer;
3393 int cnt = 0;
3394 int i;
3395
3396 // Create the command: lop off the backticks.
Bram Moolenaar71ccd032020-06-12 22:59:11 +02003397 cmd = vim_strnsave(pat + 1, STRLEN(pat) - 2);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003398 if (cmd == NULL)
3399 return -1;
3400
3401#ifdef FEAT_EVAL
3402 if (*cmd == '=') // `={expr}`: Expand expression
Bram Moolenaara4e0b972022-10-01 19:43:52 +01003403 buffer = eval_to_string(cmd + 1, TRUE, FALSE);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003404 else
3405#endif
3406 buffer = get_cmd_output(cmd, NULL,
3407 (flags & EW_SILENT) ? SHELL_SILENT : 0, NULL);
3408 vim_free(cmd);
3409 if (buffer == NULL)
3410 return -1;
3411
3412 cmd = buffer;
3413 while (*cmd != NUL)
3414 {
3415 cmd = skipwhite(cmd); // skip over white space
3416 p = cmd;
3417 while (*p != NUL && *p != '\r' && *p != '\n') // skip over entry
3418 ++p;
3419 // add an entry if it is not empty
3420 if (p > cmd)
3421 {
3422 i = *p;
3423 *p = NUL;
3424 addfile(gap, cmd, flags);
3425 *p = i;
3426 ++cnt;
3427 }
3428 cmd = p;
3429 while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
3430 ++cmd;
3431 }
3432
3433 vim_free(buffer);
3434 return cnt;
3435}
3436#endif // VIM_BACKTICK
3437
Christian Brabandt6cc30272024-12-13 17:54:33 +01003438#if defined(MSWIN)
Bram Moolenaar26262f82019-09-04 20:59:15 +02003439/*
Christian Brabandt6cc30272024-12-13 17:54:33 +01003440 * File name expansion code for MS-DOS, Win16 and Win32. It's here because
Bram Moolenaar26262f82019-09-04 20:59:15 +02003441 * it's shared between these systems.
3442 */
3443
3444/*
Christian Brabandt6cc30272024-12-13 17:54:33 +01003445 * comparison function for qsort in dos_expandpath()
Bram Moolenaar26262f82019-09-04 20:59:15 +02003446 */
3447 static int
3448pstrcmp(const void *a, const void *b)
3449{
3450 return (pathcmp(*(char **)a, *(char **)b, -1));
3451}
3452
3453/*
3454 * Recursively expand one path component into all matching files and/or
3455 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
3456 * Return the number of matches found.
3457 * "path" has backslashes before chars that are not to be expanded, starting
3458 * at "path[wildoff]".
3459 * Return the number of matches found.
Christian Brabandt6cc30272024-12-13 17:54:33 +01003460 * NOTE: much of this is identical to unix_expandpath(), keep in sync!
Bram Moolenaar26262f82019-09-04 20:59:15 +02003461 */
Christian Brabandt6cc30272024-12-13 17:54:33 +01003462 static int
3463dos_expandpath(
Bram Moolenaar26262f82019-09-04 20:59:15 +02003464 garray_T *gap,
Christian Brabandt6cc30272024-12-13 17:54:33 +01003465 char_u *path,
3466 int wildoff,
3467 int flags, // EW_* flags
3468 int didstar) // expanded "**" once already
Bram Moolenaar26262f82019-09-04 20:59:15 +02003469{
Christian Brabandt6cc30272024-12-13 17:54:33 +01003470 char_u *buf;
3471 char_u *path_end;
3472 char_u *p, *s, *e;
3473 int start_len = gap->ga_len;
3474 char_u *pat;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003475 regmatch_T regmatch;
Christian Brabandt6cc30272024-12-13 17:54:33 +01003476 int starts_with_dot;
3477 int matches;
3478 int len;
3479 int starstar = FALSE;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003480 static int stardepth = 0; // depth for "**" expansion
Christian Brabandt6cc30272024-12-13 17:54:33 +01003481 HANDLE hFind = INVALID_HANDLE_VALUE;
3482 WIN32_FIND_DATAW wfb;
3483 WCHAR *wn = NULL; // UCS-2 name, NULL when not used.
3484 char_u *matchname;
3485 int ok;
3486 char_u *p_alt;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003487
3488 // Expanding "**" may take a long time, check for CTRL-C.
3489 if (stardepth > 0)
3490 {
3491 ui_breakcheck();
3492 if (got_int)
3493 return 0;
3494 }
3495
Christian Brabandt6cc30272024-12-13 17:54:33 +01003496 // Make room for file name. When doing encoding conversion the actual
3497 // length may be quite a bit longer, thus use the maximum possible length.
Bram Moolenaar26262f82019-09-04 20:59:15 +02003498 buf = alloc(MAXPATHL);
3499 if (buf == NULL)
3500 return 0;
3501
3502 /*
3503 * Find the first part in the path name that contains a wildcard or a ~1.
Christian Brabandt6cc30272024-12-13 17:54:33 +01003504 * Copy it into buf, including the preceding characters.
Bram Moolenaar26262f82019-09-04 20:59:15 +02003505 */
3506 p = buf;
3507 s = buf;
3508 e = NULL;
3509 path_end = path;
3510 while (*path_end != NUL)
3511 {
3512 // May ignore a wildcard that has a backslash before it; it will
3513 // be removed by rem_backslash() or file_pat_to_reg_pat() below.
3514 if (path_end >= path + wildoff && rem_backslash(path_end))
3515 *p++ = *path_end++;
Christian Brabandt6cc30272024-12-13 17:54:33 +01003516 else if (*path_end == '\\' || *path_end == ':' || *path_end == '/')
Bram Moolenaar26262f82019-09-04 20:59:15 +02003517 {
3518 if (e != NULL)
3519 break;
3520 s = p + 1;
3521 }
3522 else if (path_end >= path + wildoff
Christian Brabandt6cc30272024-12-13 17:54:33 +01003523 && vim_strchr((char_u *)"*?[~", *path_end) != NULL)
Bram Moolenaar26262f82019-09-04 20:59:15 +02003524 e = p;
3525 if (has_mbyte)
3526 {
Christian Brabandt6cc30272024-12-13 17:54:33 +01003527 len = (*mb_ptr2len)(path_end);
3528 STRNCPY(p, path_end, len);
3529 p += len;
3530 path_end += len;
3531 }
3532 else
3533 *p++ = *path_end++;
3534 }
3535 e = p;
3536 *e = NUL;
3537
3538 // now we have one wildcard component between s and e
3539 // Remove backslashes between "wildoff" and the start of the wildcard
3540 // component.
3541 for (p = buf + wildoff; p < s; ++p)
3542 if (rem_backslash(p))
3543 {
3544 STRMOVE(p, p + 1);
3545 --e;
3546 --s;
3547 }
3548
3549 // Check for "**" between "s" and "e".
3550 for (p = s; p < e; ++p)
3551 if (p[0] == '*' && p[1] == '*')
3552 starstar = TRUE;
3553
3554 starts_with_dot = *s == '.';
3555 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
3556 if (pat == NULL)
3557 {
3558 vim_free(buf);
3559 return 0;
3560 }
3561
3562 // compile the regexp into a program
3563 if (flags & (EW_NOERROR | EW_NOTWILD))
3564 ++emsg_silent;
3565 regmatch.rm_ic = TRUE; // Always ignore case
3566 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
3567 if (flags & (EW_NOERROR | EW_NOTWILD))
3568 --emsg_silent;
3569 vim_free(pat);
3570
3571 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
3572 {
3573 vim_free(buf);
3574 return 0;
3575 }
3576
3577 // remember the pattern or file name being looked for
3578 matchname = vim_strsave(s);
3579
3580 // If "**" is by itself, this is the first time we encounter it and more
3581 // is following then find matches without any directory.
3582 if (!didstar && stardepth < 100 && starstar && e - s == 2
3583 && *path_end == '/')
3584 {
3585 STRCPY(s, path_end + 1);
3586 ++stardepth;
3587 (void)dos_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
3588 --stardepth;
3589 }
3590
3591 // Scan all files in the directory with "dir/ *.*"
3592 STRCPY(s, "*.*");
3593 wn = enc_to_utf16(buf, NULL);
3594 if (wn != NULL)
3595 hFind = FindFirstFileW(wn, &wfb);
3596 ok = (hFind != INVALID_HANDLE_VALUE);
3597
3598 while (ok)
3599 {
3600 p = utf16_to_enc(wfb.cFileName, NULL); // p is allocated here
3601
3602 if (p == NULL)
3603 break; // out of memory
3604
3605 // Do not use the alternate filename when the file name ends in '~',
3606 // because it picks up backup files: short name for "foo.vim~" is
3607 // "foo~1.vim", which matches "*.vim".
3608 if (*wfb.cAlternateFileName == NUL || p[STRLEN(p) - 1] == '~')
3609 p_alt = NULL;
3610 else
3611 p_alt = utf16_to_enc(wfb.cAlternateFileName, NULL);
3612
3613 // Ignore entries starting with a dot, unless when asked for. Accept
3614 // all entries found with "matchname".
3615 if ((p[0] != '.' || starts_with_dot
3616 || ((flags & EW_DODOT)
3617 && p[1] != NUL && (p[1] != '.' || p[2] != NUL)))
3618 && (matchname == NULL
3619 || (regmatch.regprog != NULL
3620 && (vim_regexec(&regmatch, p, (colnr_T)0)
3621 || (p_alt != NULL
3622 && vim_regexec(&regmatch, p_alt, (colnr_T)0))))
3623 || ((flags & EW_NOTWILD)
3624 && fnamencmp(path + (s - buf), p, e - s) == 0)))
3625 {
3626 STRCPY(s, p);
3627 len = (int)STRLEN(buf);
3628
3629 if (starstar && stardepth < 100
3630 && (wfb.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
3631 {
3632 // For "**" in the pattern first go deeper in the tree to
3633 // find matches.
3634 STRCPY(buf + len, "/**");
3635 STRCPY(buf + len + 3, path_end);
3636 ++stardepth;
3637 (void)dos_expandpath(gap, buf, len + 1, flags, TRUE);
3638 --stardepth;
3639 }
3640
3641 STRCPY(buf + len, path_end);
3642 if (mch_has_exp_wildcard(path_end))
3643 {
3644 // need to expand another component of the path
3645 // remove backslashes for the remaining components only
3646 (void)dos_expandpath(gap, buf, len + 1, flags, FALSE);
3647 }
3648 else
3649 {
3650 stat_T sb;
3651
3652 // no more wildcards, check if there is a match
3653 // remove backslashes for the remaining components only
3654 if (*path_end != 0)
3655 backslash_halve(buf + len + 1);
3656 // add existing file
3657 if ((flags & EW_ALLLINKS) ? mch_lstat((char *)buf, &sb) >= 0
3658 : mch_getperm(buf) >= 0)
3659 addfile(gap, buf, flags);
3660 }
3661 }
3662
3663 vim_free(p_alt);
3664 vim_free(p);
3665 ok = FindNextFileW(hFind, &wfb);
3666 }
3667
3668 FindClose(hFind);
3669 vim_free(wn);
3670 vim_free(buf);
3671 vim_regfree(regmatch.regprog);
3672 vim_free(matchname);
3673
3674 matches = gap->ga_len - start_len;
3675 if (matches > 0)
3676 qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
3677 sizeof(char_u *), pstrcmp);
3678 return matches;
3679}
3680
3681 int
3682mch_expandpath(
3683 garray_T *gap,
3684 char_u *path,
3685 int flags) // EW_* flags
3686{
3687 return dos_expandpath(gap, path, 0, flags, FALSE);
3688}
3689#endif // MSWIN
3690
3691#if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \
3692 || defined(PROTO)
3693/*
3694 * Unix style wildcard expansion code.
3695 * It's here because it's used both for Unix and Mac.
3696 */
3697 static int
3698pstrcmp(const void *a, const void *b)
3699{
3700 return (pathcmp(*(char **)a, *(char **)b, -1));
3701}
3702
3703/*
3704 * Recursively expand one path component into all matching files and/or
3705 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
3706 * "path" has backslashes before chars that are not to be expanded, starting
3707 * at "path + wildoff".
3708 * Return the number of matches found.
3709 * NOTE: much of this is identical to dos_expandpath(), keep in sync!
3710 */
3711 int
3712unix_expandpath(
3713 garray_T *gap,
3714 char_u *path,
3715 int wildoff,
3716 int flags, // EW_* flags
3717 int didstar) // expanded "**" once already
3718{
3719 char_u *buf;
3720 char_u *path_end;
3721 char_u *p, *s, *e;
3722 int start_len = gap->ga_len;
3723 char_u *pat;
3724 regmatch_T regmatch;
3725 int starts_with_dot;
3726 int matches;
3727 int len;
3728 int starstar = FALSE;
3729 static int stardepth = 0; // depth for "**" expansion
3730
3731 DIR *dirp;
3732 struct dirent *dp;
3733
3734 // Expanding "**" may take a long time, check for CTRL-C.
3735 if (stardepth > 0)
3736 {
3737 ui_breakcheck();
3738 if (got_int)
3739 return 0;
3740 }
3741
3742 // make room for file name (a bit too much to stay on the safe side)
3743 size_t buflen = STRLEN(path) + MAXPATHL;
3744 buf = alloc(buflen);
3745 if (buf == NULL)
3746 return 0;
3747
3748 /*
3749 * Find the first part in the path name that contains a wildcard.
3750 * When EW_ICASE is set every letter is considered to be a wildcard.
3751 * Copy it into "buf", including the preceding characters.
3752 */
3753 p = buf;
3754 s = buf;
3755 e = NULL;
3756 path_end = path;
3757 while (*path_end != NUL)
3758 {
3759 // May ignore a wildcard that has a backslash before it; it will
3760 // be removed by rem_backslash() or file_pat_to_reg_pat() below.
3761 if (path_end >= path + wildoff && rem_backslash(path_end))
3762 *p++ = *path_end++;
3763 else if (*path_end == '/')
3764 {
3765 if (e != NULL)
3766 break;
3767 s = p + 1;
3768 }
3769 else if (path_end >= path + wildoff
3770 && (vim_strchr((char_u *)"*?[{~$", *path_end) != NULL
3771 || (!p_fic && (flags & EW_ICASE)
3772 && vim_isalpha(PTR2CHAR(path_end)))))
3773 e = p;
3774 if (has_mbyte)
3775 {
3776 len = (*mb_ptr2len)(path_end);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003777 STRNCPY(p, path_end, len);
3778 p += len;
3779 path_end += len;
3780 }
3781 else
3782 *p++ = *path_end++;
3783 }
3784 e = p;
3785 *e = NUL;
3786
3787 // Now we have one wildcard component between "s" and "e".
3788 // Remove backslashes between "wildoff" and the start of the wildcard
3789 // component.
Christian Brabandt6cc30272024-12-13 17:54:33 +01003790 for (p = buf + wildoff; p < s; ++p)
3791 if (rem_backslash(p))
Bram Moolenaar26262f82019-09-04 20:59:15 +02003792 {
Christian Brabandt6cc30272024-12-13 17:54:33 +01003793 STRMOVE(p, p + 1);
3794 --e;
3795 --s;
3796 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02003797
3798 // Check for "**" between "s" and "e".
3799 for (p = s; p < e; ++p)
3800 if (p[0] == '*' && p[1] == '*')
3801 starstar = TRUE;
3802
3803 // convert the file pattern to a regexp pattern
3804 starts_with_dot = *s == '.';
3805 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
3806 if (pat == NULL)
3807 {
3808 vim_free(buf);
3809 return 0;
3810 }
3811
3812 // compile the regexp into a program
3813 if (flags & EW_ICASE)
Christian Brabandt6cc30272024-12-13 17:54:33 +01003814 regmatch.rm_ic = TRUE; // 'wildignorecase' set
Bram Moolenaar26262f82019-09-04 20:59:15 +02003815 else
Christian Brabandt6cc30272024-12-13 17:54:33 +01003816 regmatch.rm_ic = p_fic; // ignore case when 'fileignorecase' is set
Bram Moolenaar26262f82019-09-04 20:59:15 +02003817 if (flags & (EW_NOERROR | EW_NOTWILD))
3818 ++emsg_silent;
3819 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
3820 if (flags & (EW_NOERROR | EW_NOTWILD))
3821 --emsg_silent;
3822 vim_free(pat);
3823
3824 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
3825 {
3826 vim_free(buf);
3827 return 0;
3828 }
3829
3830 // If "**" is by itself, this is the first time we encounter it and more
3831 // is following then find matches without any directory.
Christian Brabandt6cc30272024-12-13 17:54:33 +01003832 if (!didstar && stardepth < 100 && starstar && e - s == 2
3833 && *path_end == '/')
Bram Moolenaar26262f82019-09-04 20:59:15 +02003834 {
3835 STRCPY(s, path_end + 1);
3836 ++stardepth;
Christian Brabandt6cc30272024-12-13 17:54:33 +01003837 (void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003838 --stardepth;
3839 }
3840
3841 // open the directory for scanning
3842 *s = NUL;
3843 dirp = opendir(*buf == NUL ? "." : (char *)buf);
3844
3845 // Find all matching entries
Christian Brabandt6cc30272024-12-13 17:54:33 +01003846 if (dirp != NULL)
Bram Moolenaar26262f82019-09-04 20:59:15 +02003847 {
Bram Moolenaar57e95172022-08-20 19:26:14 +01003848 while (!got_int)
Bram Moolenaar26262f82019-09-04 20:59:15 +02003849 {
3850 dp = readdir(dirp);
3851 if (dp == NULL)
3852 break;
Christian Brabandt6cc30272024-12-13 17:54:33 +01003853 if ((dp->d_name[0] != '.' || starts_with_dot
3854 || ((flags & EW_DODOT)
3855 && dp->d_name[1] != NUL
3856 && (dp->d_name[1] != '.' || dp->d_name[2] != NUL)))
3857 && ((regmatch.regprog != NULL && vim_regexec(&regmatch,
3858 (char_u *)dp->d_name, (colnr_T)0))
John Marriotte29c8ba2024-12-13 13:58:53 +01003859 || ((flags & EW_NOTWILD)
Christian Brabandt6cc30272024-12-13 17:54:33 +01003860 && fnamencmp(path + (s - buf), dp->d_name, e - s) == 0)))
John Marriotte29c8ba2024-12-13 13:58:53 +01003861 {
Christian Brabandt6cc30272024-12-13 17:54:33 +01003862 vim_strncpy(s, (char_u *)dp->d_name, buflen - (s - buf) - 1);
3863 len = STRLEN(buf);
John Marriotte29c8ba2024-12-13 13:58:53 +01003864
Christian Brabandt6cc30272024-12-13 17:54:33 +01003865 if (starstar && stardepth < 100)
Bram Moolenaar26262f82019-09-04 20:59:15 +02003866 {
3867 // For "**" in the pattern first go deeper in the tree to
3868 // find matches.
Christian Brabandt6cc30272024-12-13 17:54:33 +01003869 vim_snprintf((char *)buf + len, buflen - len,
3870 "/**%s", path_end);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003871 ++stardepth;
3872 (void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
3873 --stardepth;
3874 }
3875
Christian Brabandt6cc30272024-12-13 17:54:33 +01003876 vim_snprintf((char *)buf + len, buflen - len, "%s", path_end);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003877 if (mch_has_exp_wildcard(path_end)) // handle more wildcards
3878 {
3879 // need to expand another component of the path
3880 // remove backslashes for the remaining components only
3881 (void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
3882 }
3883 else
3884 {
3885 stat_T sb;
3886
3887 // no more wildcards, check if there is a match
3888 // remove backslashes for the remaining components only
3889 if (*path_end != NUL)
3890 backslash_halve(buf + len + 1);
3891 // add existing file or symbolic link
3892 if ((flags & EW_ALLLINKS) ? mch_lstat((char *)buf, &sb) >= 0
Christian Brabandt6cc30272024-12-13 17:54:33 +01003893 : mch_getperm(buf) >= 0)
Bram Moolenaar26262f82019-09-04 20:59:15 +02003894 {
3895#ifdef MACOS_CONVERT
3896 size_t precomp_len = STRLEN(buf)+1;
3897 char_u *precomp_buf =
3898 mac_precompose_path(buf, precomp_len, &precomp_len);
3899
3900 if (precomp_buf)
3901 {
3902 mch_memmove(buf, precomp_buf, precomp_len);
3903 vim_free(precomp_buf);
3904 }
3905#endif
3906 addfile(gap, buf, flags);
3907 }
3908 }
3909 }
3910 }
3911
3912 closedir(dirp);
3913 }
3914
3915 vim_free(buf);
3916 vim_regfree(regmatch.regprog);
3917
Bram Moolenaar57e95172022-08-20 19:26:14 +01003918 // When interrupted the matches probably won't be used and sorting can be
3919 // slow, thus skip it.
Bram Moolenaar26262f82019-09-04 20:59:15 +02003920 matches = gap->ga_len - start_len;
Bram Moolenaar57e95172022-08-20 19:26:14 +01003921 if (matches > 0 && !got_int)
Bram Moolenaar26262f82019-09-04 20:59:15 +02003922 qsort(((char_u **)gap->ga_data) + start_len, matches,
Christian Brabandt6cc30272024-12-13 17:54:33 +01003923 sizeof(char_u *), pstrcmp);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003924 return matches;
3925}
3926#endif
3927
3928/*
3929 * Return TRUE if "p" contains what looks like an environment variable.
3930 * Allowing for escaping.
3931 */
3932 static int
3933has_env_var(char_u *p)
3934{
3935 for ( ; *p; MB_PTR_ADV(p))
3936 {
3937 if (*p == '\\' && p[1] != NUL)
3938 ++p;
3939 else if (vim_strchr((char_u *)
3940#if defined(MSWIN)
3941 "$%"
3942#else
3943 "$"
3944#endif
3945 , *p) != NULL)
3946 return TRUE;
3947 }
3948 return FALSE;
3949}
3950
3951#ifdef SPECIAL_WILDCHAR
3952/*
3953 * Return TRUE if "p" contains a special wildcard character, one that Vim
3954 * cannot expand, requires using a shell.
3955 */
3956 static int
3957has_special_wildchar(char_u *p)
3958{
3959 for ( ; *p; MB_PTR_ADV(p))
3960 {
3961 // Disallow line break characters.
3962 if (*p == '\r' || *p == '\n')
3963 break;
3964 // Allow for escaping.
3965 if (*p == '\\' && p[1] != NUL && p[1] != '\r' && p[1] != '\n')
3966 ++p;
3967 else if (vim_strchr((char_u *)SPECIAL_WILDCHAR, *p) != NULL)
3968 {
3969 // A { must be followed by a matching }.
3970 if (*p == '{' && vim_strchr(p, '}') == NULL)
3971 continue;
3972 // A quote and backtick must be followed by another one.
3973 if ((*p == '`' || *p == '\'') && vim_strchr(p, *p) == NULL)
3974 continue;
3975 return TRUE;
3976 }
3977 }
3978 return FALSE;
3979}
3980#endif
3981
3982/*
3983 * Generic wildcard expansion code.
3984 *
3985 * Characters in "pat" that should not be expanded must be preceded with a
3986 * backslash. E.g., "/path\ with\ spaces/my\*star*"
3987 *
3988 * Return FAIL when no single file was found. In this case "num_file" is not
3989 * set, and "file" may contain an error message.
3990 * Return OK when some files found. "num_file" is set to the number of
3991 * matches, "file" to the array of matches. Call FreeWild() later.
3992 */
3993 int
3994gen_expand_wildcards(
3995 int num_pat, // number of input patterns
3996 char_u **pat, // array of input patterns
3997 int *num_file, // resulting number of files
3998 char_u ***file, // array of resulting files
3999 int flags) // EW_* flags
4000{
4001 int i;
4002 garray_T ga;
4003 char_u *p;
4004 static int recursive = FALSE;
4005 int add_pat;
4006 int retval = OK;
Bram Moolenaar26262f82019-09-04 20:59:15 +02004007 int did_expand_in_path = FALSE;
LemonBoya20bf692024-07-11 22:35:53 +02004008 char_u *path_option = *curbuf->b_p_path == NUL ?
4009 p_path : curbuf->b_p_path;
Bram Moolenaar26262f82019-09-04 20:59:15 +02004010
4011 /*
4012 * expand_env() is called to expand things like "~user". If this fails,
4013 * it calls ExpandOne(), which brings us back here. In this case, always
4014 * call the machine specific expansion function, if possible. Otherwise,
4015 * return FAIL.
4016 */
4017 if (recursive)
4018#ifdef SPECIAL_WILDCHAR
4019 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
4020#else
4021 return FAIL;
4022#endif
4023
4024#ifdef SPECIAL_WILDCHAR
4025 /*
4026 * If there are any special wildcard characters which we cannot handle
4027 * here, call machine specific function for all the expansion. This
4028 * avoids starting the shell for each argument separately.
4029 * For `=expr` do use the internal function.
4030 */
4031 for (i = 0; i < num_pat; i++)
4032 {
4033 if (has_special_wildchar(pat[i])
4034# ifdef VIM_BACKTICK
4035 && !(vim_backtick(pat[i]) && pat[i][1] == '=')
4036# endif
4037 )
4038 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
4039 }
4040#endif
4041
4042 recursive = TRUE;
4043
4044 /*
4045 * The matching file names are stored in a growarray. Init it empty.
4046 */
Bram Moolenaar04935fb2022-01-08 16:19:22 +00004047 ga_init2(&ga, sizeof(char_u *), 30);
Bram Moolenaar26262f82019-09-04 20:59:15 +02004048
Bram Moolenaar57e95172022-08-20 19:26:14 +01004049 for (i = 0; i < num_pat && !got_int; ++i)
Bram Moolenaar26262f82019-09-04 20:59:15 +02004050 {
4051 add_pat = -1;
4052 p = pat[i];
4053
4054#ifdef VIM_BACKTICK
4055 if (vim_backtick(p))
4056 {
4057 add_pat = expand_backtick(&ga, p, flags);
4058 if (add_pat == -1)
4059 retval = FAIL;
4060 }
4061 else
4062#endif
4063 {
4064 /*
4065 * First expand environment variables, "~/" and "~user/".
4066 */
4067 if ((has_env_var(p) && !(flags & EW_NOTENV)) || *p == '~')
4068 {
4069 p = expand_env_save_opt(p, TRUE);
4070 if (p == NULL)
4071 p = pat[i];
4072#ifdef UNIX
4073 /*
4074 * On Unix, if expand_env() can't expand an environment
4075 * variable, use the shell to do that. Discard previously
4076 * found file names and start all over again.
4077 */
4078 else if (has_env_var(p) || *p == '~')
4079 {
4080 vim_free(p);
4081 ga_clear_strings(&ga);
4082 i = mch_expand_wildcards(num_pat, pat, num_file, file,
4083 flags|EW_KEEPDOLLAR);
4084 recursive = FALSE;
4085 return i;
4086 }
4087#endif
4088 }
4089
4090 /*
LemonBoya3157a42022-04-03 11:58:31 +01004091 * If there are wildcards or case-insensitive expansion is
4092 * required: Expand file names and add each match to the list. If
4093 * there is no match, and EW_NOTFOUND is given, add the pattern.
4094 * Otherwise: Add the file name if it exists or when EW_NOTFOUND is
4095 * given.
Bram Moolenaar26262f82019-09-04 20:59:15 +02004096 */
LemonBoya3157a42022-04-03 11:58:31 +01004097 if (mch_has_exp_wildcard(p) || (flags & EW_ICASE))
Bram Moolenaar26262f82019-09-04 20:59:15 +02004098 {
LemonBoya20bf692024-07-11 22:35:53 +02004099 if ((flags & (EW_PATH | EW_CDPATH))
Bram Moolenaar26262f82019-09-04 20:59:15 +02004100 && !mch_isFullName(p)
4101 && !(p[0] == '.'
4102 && (vim_ispathsep(p[1])
4103 || (p[1] == '.' && vim_ispathsep(p[2]))))
4104 )
4105 {
4106 // :find completion where 'path' is used.
4107 // Recursiveness is OK here.
4108 recursive = FALSE;
4109 add_pat = expand_in_path(&ga, p, flags);
4110 recursive = TRUE;
4111 did_expand_in_path = TRUE;
4112 }
4113 else
Bram Moolenaar26262f82019-09-04 20:59:15 +02004114 add_pat = mch_expandpath(&ga, p, flags);
4115 }
4116 }
4117
4118 if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
4119 {
4120 char_u *t = backslash_halve_save(p);
4121
4122 // When EW_NOTFOUND is used, always add files and dirs. Makes
4123 // "vim c:/" work.
4124 if (flags & EW_NOTFOUND)
4125 addfile(&ga, t, flags | EW_DIR | EW_FILE);
4126 else
4127 addfile(&ga, t, flags);
4128
4129 if (t != p)
4130 vim_free(t);
4131 }
4132
LemonBoya20bf692024-07-11 22:35:53 +02004133 if (did_expand_in_path && ga.ga_len > 0 && (flags & (EW_PATH | EW_CDPATH)))
4134 uniquefy_paths(&ga, p, path_option);
Bram Moolenaar26262f82019-09-04 20:59:15 +02004135 if (p != pat[i])
4136 vim_free(p);
4137 }
4138
Bram Moolenaar566cc8c2020-06-29 21:14:51 +02004139 // When returning FAIL the array must be freed here.
4140 if (retval == FAIL)
Yegappan Lakshmanan2b74b682022-04-03 21:30:32 +01004141 ga_clear_strings(&ga);
Bram Moolenaar566cc8c2020-06-29 21:14:51 +02004142
Bram Moolenaar26262f82019-09-04 20:59:15 +02004143 *num_file = ga.ga_len;
Bram Moolenaar566cc8c2020-06-29 21:14:51 +02004144 *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data
4145 : (char_u **)_("no matches");
Bram Moolenaar26262f82019-09-04 20:59:15 +02004146
4147 recursive = FALSE;
4148
4149 return ((flags & EW_EMPTYOK) || ga.ga_data != NULL) ? retval : FAIL;
4150}
4151
4152/*
4153 * Add a file to a file list. Accepted flags:
4154 * EW_DIR add directories
4155 * EW_FILE add files
4156 * EW_EXEC add executable files
4157 * EW_NOTFOUND add even when it doesn't exist
4158 * EW_ADDSLASH add slash after directory name
4159 * EW_ALLLINKS add symlink also when the referred file does not exist
4160 */
4161 void
4162addfile(
4163 garray_T *gap,
Bram Moolenaar217e1b82019-12-01 21:41:28 +01004164 char_u *f, // filename
Bram Moolenaar26262f82019-09-04 20:59:15 +02004165 int flags)
4166{
4167 char_u *p;
4168 int isdir;
4169 stat_T sb;
4170
4171 // if the file/dir/link doesn't exist, may not add it
4172 if (!(flags & EW_NOTFOUND) && ((flags & EW_ALLLINKS)
4173 ? mch_lstat((char *)f, &sb) < 0 : mch_getperm(f) < 0))
4174 return;
4175
4176#ifdef FNAME_ILLEGAL
4177 // if the file/dir contains illegal characters, don't add it
4178 if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
4179 return;
4180#endif
4181
4182 isdir = mch_isdir(f);
4183 if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
4184 return;
4185
4186 // If the file isn't executable, may not add it. Do accept directories.
4187 // When invoked from expand_shellcmd() do not use $PATH.
4188 if (!isdir && (flags & EW_EXEC)
4189 && !mch_can_exe(f, NULL, !(flags & EW_SHELLCMD)))
4190 return;
4191
4192 // Make room for another item in the file list.
4193 if (ga_grow(gap, 1) == FAIL)
4194 return;
4195
4196 p = alloc(STRLEN(f) + 1 + isdir);
4197 if (p == NULL)
4198 return;
4199
4200 STRCPY(p, f);
4201#ifdef BACKSLASH_IN_FILENAME
4202 slash_adjust(p);
4203#endif
4204 /*
4205 * Append a slash or backslash after directory names if none is present.
4206 */
Bram Moolenaar26262f82019-09-04 20:59:15 +02004207 if (isdir && (flags & EW_ADDSLASH))
4208 add_pathsep(p);
Bram Moolenaar26262f82019-09-04 20:59:15 +02004209 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
4210}
4211
4212/*
4213 * Free the list of files returned by expand_wildcards() or other expansion
4214 * functions.
4215 */
4216 void
4217FreeWild(int count, char_u **files)
4218{
4219 if (count <= 0 || files == NULL)
4220 return;
4221 while (count--)
4222 vim_free(files[count]);
4223 vim_free(files);
4224}
4225
4226/*
4227 * Compare path "p[]" to "q[]".
4228 * If "maxlen" >= 0 compare "p[maxlen]" to "q[maxlen]"
4229 * Return value like strcmp(p, q), but consider path separators.
4230 */
4231 int
4232pathcmp(const char *p, const char *q, int maxlen)
4233{
4234 int i, j;
4235 int c1, c2;
4236 const char *s = NULL;
4237
4238 for (i = 0, j = 0; maxlen < 0 || (i < maxlen && j < maxlen);)
4239 {
4240 c1 = PTR2CHAR((char_u *)p + i);
4241 c2 = PTR2CHAR((char_u *)q + j);
4242
4243 // End of "p": check if "q" also ends or just has a slash.
4244 if (c1 == NUL)
4245 {
4246 if (c2 == NUL) // full match
4247 return 0;
4248 s = q;
4249 i = j;
4250 break;
4251 }
4252
4253 // End of "q": check if "p" just has a slash.
4254 if (c2 == NUL)
4255 {
4256 s = p;
4257 break;
4258 }
4259
4260 if ((p_fic ? MB_TOUPPER(c1) != MB_TOUPPER(c2) : c1 != c2)
4261#ifdef BACKSLASH_IN_FILENAME
4262 // consider '/' and '\\' to be equal
4263 && !((c1 == '/' && c2 == '\\')
4264 || (c1 == '\\' && c2 == '/'))
4265#endif
4266 )
4267 {
4268 if (vim_ispathsep(c1))
4269 return -1;
4270 if (vim_ispathsep(c2))
4271 return 1;
4272 return p_fic ? MB_TOUPPER(c1) - MB_TOUPPER(c2)
4273 : c1 - c2; // no match
4274 }
4275
Bram Moolenaar1614a142019-10-06 22:00:13 +02004276 i += mb_ptr2len((char_u *)p + i);
4277 j += mb_ptr2len((char_u *)q + j);
Bram Moolenaar26262f82019-09-04 20:59:15 +02004278 }
4279 if (s == NULL) // "i" or "j" ran into "maxlen"
4280 return 0;
4281
4282 c1 = PTR2CHAR((char_u *)s + i);
Bram Moolenaar1614a142019-10-06 22:00:13 +02004283 c2 = PTR2CHAR((char_u *)s + i + mb_ptr2len((char_u *)s + i));
Bram Moolenaar26262f82019-09-04 20:59:15 +02004284 // ignore a trailing slash, but not "//" or ":/"
4285 if (c2 == NUL
4286 && i > 0
4287 && !after_pathsep((char_u *)s, (char_u *)s + i)
4288#ifdef BACKSLASH_IN_FILENAME
4289 && (c1 == '/' || c1 == '\\')
4290#else
4291 && c1 == '/'
4292#endif
4293 )
4294 return 0; // match with trailing slash
4295 if (s == q)
4296 return -1; // no match
4297 return 1;
4298}
4299
4300/*
4301 * Return TRUE if "name" is a full (absolute) path name or URL.
4302 */
4303 int
4304vim_isAbsName(char_u *name)
4305{
4306 return (path_with_url(name) != 0 || mch_isFullName(name));
4307}
4308
4309/*
4310 * Get absolute file name into buffer "buf[len]".
4311 *
4312 * return FAIL for failure, OK otherwise
4313 */
4314 int
4315vim_FullName(
4316 char_u *fname,
4317 char_u *buf,
4318 int len,
4319 int force) // force expansion even when already absolute
4320{
4321 int retval = OK;
4322 int url;
4323
4324 *buf = NUL;
4325 if (fname == NULL)
4326 return FAIL;
4327
4328 url = path_with_url(fname);
4329 if (!url)
4330 retval = mch_FullName(fname, buf, len, force);
4331 if (url || retval == FAIL)
4332 {
4333 // something failed; use the file name (truncate when too long)
4334 vim_strncpy(buf, fname, len - 1);
4335 }
4336#if defined(MSWIN)
4337 slash_adjust(buf);
4338#endif
4339 return retval;
4340}