blob: 729884252716a8d66c2b09e554cd3f736a3c1be5 [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{
John Marriotte29c8ba2024-12-13 13:58:53 +010032 int l;
Bram Moolenaar3f396972019-10-30 04:10:06 +010033 WCHAR *newbuf;
34 WCHAR *wfname;
Bram Moolenaarb005cd82019-09-04 15:54:55 +020035
John Marriotte29c8ba2024-12-13 13:58:53 +010036 newbuf = alloc(MAXPATHL * sizeof(*newbuf));
Bram Moolenaar3f396972019-10-30 04:10:06 +010037 if (newbuf == NULL)
38 return FAIL;
39
40 wfname = enc_to_utf16(*fnamep, NULL);
41 if (wfname == NULL)
42 {
43 vim_free(newbuf);
44 return FAIL;
45 }
46
John Marriotte29c8ba2024-12-13 13:58:53 +010047 l = GetShortPathNameW(wfname, newbuf, MAXPATHL);
48 if (l > MAXPATHL - 1)
Bram Moolenaarb005cd82019-09-04 15:54:55 +020049 {
Bram Moolenaar26262f82019-09-04 20:59:15 +020050 // If that doesn't work (not enough space), then save the string
51 // and try again with a new buffer big enough.
Bram Moolenaar3f396972019-10-30 04:10:06 +010052 WCHAR *newbuf_t = newbuf;
53 newbuf = vim_realloc(newbuf, (l + 1) * sizeof(*newbuf));
Bram Moolenaarb005cd82019-09-04 15:54:55 +020054 if (newbuf == NULL)
Bram Moolenaar3f396972019-10-30 04:10:06 +010055 {
56 vim_free(wfname);
57 vim_free(newbuf_t);
Bram Moolenaarb005cd82019-09-04 15:54:55 +020058 return FAIL;
Bram Moolenaar3f396972019-10-30 04:10:06 +010059 }
Bram Moolenaar26262f82019-09-04 20:59:15 +020060 // Really should always succeed, as the buffer is big enough.
Bram Moolenaar3f396972019-10-30 04:10:06 +010061 l = GetShortPathNameW(wfname, newbuf, l+1);
Bram Moolenaarb005cd82019-09-04 15:54:55 +020062 }
Bram Moolenaar3f396972019-10-30 04:10:06 +010063 if (l != 0)
64 {
65 char_u *p = utf16_to_enc(newbuf, NULL);
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +020066
Bram Moolenaar3f396972019-10-30 04:10:06 +010067 if (p != NULL)
68 {
69 vim_free(*bufp);
70 *fnamep = *bufp = p;
71 }
72 else
73 {
74 vim_free(wfname);
75 vim_free(newbuf);
76 return FAIL;
77 }
78 }
79 vim_free(wfname);
80 vim_free(newbuf);
Bram Moolenaarb005cd82019-09-04 15:54:55 +020081
Bram Moolenaar2ade7142019-11-04 20:36:50 +010082 *fnamelen = l == 0 ? l : (int)STRLEN(*bufp);
Bram Moolenaarb005cd82019-09-04 15:54:55 +020083 return OK;
84}
85
86/*
87 * Get the short path (8.3) for the filename in "fname". The converted
88 * path is returned in "bufp".
89 *
90 * Some of the directories specified in "fname" may not exist. This function
91 * will shorten the existing directories at the beginning of the path and then
92 * append the remaining non-existing path.
93 *
94 * fname - Pointer to the filename to shorten. On return, contains the
95 * pointer to the shortened pathname
96 * bufp - Pointer to an allocated buffer for the filename.
97 * fnamelen - Length of the filename pointed to by fname
98 *
99 * Returns OK on success (or nothing done) and FAIL on failure (out of memory).
100 */
101 static int
102shortpath_for_invalid_fname(
103 char_u **fname,
104 char_u **bufp,
105 int *fnamelen)
106{
John Marriotte29c8ba2024-12-13 13:58:53 +0100107 char_u *short_fname = NULL, *save_fname = NULL, *pbuf_unused = NULL;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200108 char_u *endp, *save_endp;
109 char_u ch;
110 int old_len, len;
111 int new_len, sfx_len;
112 int retval = OK;
113
Bram Moolenaar26262f82019-09-04 20:59:15 +0200114 // Make a copy
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200115 old_len = *fnamelen;
116 save_fname = vim_strnsave(*fname, old_len);
John Marriotte29c8ba2024-12-13 13:58:53 +0100117 if (save_fname == NULL)
118 {
119 retval = FAIL;
120 goto theend;
121 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200122 pbuf_unused = NULL;
123 short_fname = NULL;
124
Bram Moolenaar26262f82019-09-04 20:59:15 +0200125 endp = save_fname + old_len - 1; // Find the end of the copy
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200126 save_endp = endp;
127
128 /*
129 * Try shortening the supplied path till it succeeds by removing one
130 * directory at a time from the tail of the path.
131 */
132 len = 0;
133 for (;;)
134 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200135 // go back one path-separator
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200136 while (endp > save_fname && !after_pathsep(save_fname, endp + 1))
137 --endp;
138 if (endp <= save_fname)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200139 break; // processed the complete path
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200140
141 /*
142 * Replace the path separator with a NUL and try to shorten the
143 * resulting path.
144 */
145 ch = *endp;
John Marriotte29c8ba2024-12-13 13:58:53 +0100146 *endp = NUL;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200147 short_fname = save_fname;
John Marriotte29c8ba2024-12-13 13:58:53 +0100148 len = (int)(endp - save_fname) + 1;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200149 if (get_short_pathname(&short_fname, &pbuf_unused, &len) == FAIL)
150 {
151 retval = FAIL;
152 goto theend;
153 }
Bram Moolenaar26262f82019-09-04 20:59:15 +0200154 *endp = ch; // preserve the string
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200155
156 if (len > 0)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200157 break; // successfully shortened the path
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200158
Bram Moolenaar26262f82019-09-04 20:59:15 +0200159 // failed to shorten the path. Skip the path separator
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200160 --endp;
161 }
162
163 if (len > 0)
164 {
165 /*
166 * Succeeded in shortening the path. Now concatenate the shortened
167 * path with the remaining path at the tail.
168 */
169
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100170 // Compute the length of the new path.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200171 sfx_len = (int)(save_endp - endp) + 1;
172 new_len = len + sfx_len;
173
174 *fnamelen = new_len;
175 vim_free(*bufp);
176 if (new_len > old_len)
177 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200178 // There is not enough space in the currently allocated string,
179 // copy it to a buffer big enough.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200180 *fname = *bufp = vim_strnsave(short_fname, new_len);
181 if (*fname == NULL)
182 {
183 retval = FAIL;
184 goto theend;
185 }
186 }
187 else
188 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200189 // Transfer short_fname to the main buffer (it's big enough),
190 // unless get_short_pathname() did its work in-place.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200191 *fname = *bufp = save_fname;
192 if (short_fname != save_fname)
Christian Brabandt81da16b2022-03-10 12:24:02 +0000193 STRNCPY(save_fname, short_fname, len);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200194 save_fname = NULL;
195 }
196
Bram Moolenaar26262f82019-09-04 20:59:15 +0200197 // concat the not-shortened part of the path
Yegappan Lakshmanana34b4462022-06-11 10:43:26 +0100198 if ((*fname + len) != endp)
199 vim_strncpy(*fname + len, endp, sfx_len);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200200 (*fname)[new_len] = NUL;
201 }
202
203theend:
204 vim_free(pbuf_unused);
205 vim_free(save_fname);
206
207 return retval;
208}
209
210/*
211 * Get a pathname for a partial path.
212 * Returns OK for success, FAIL for failure.
213 */
214 static int
215shortpath_for_partial(
216 char_u **fnamep,
217 char_u **bufp,
218 int *fnamelen)
219{
220 int sepcount, len, tflen;
221 char_u *p;
222 char_u *pbuf, *tfname;
223 int hasTilde;
224
Bram Moolenaar26262f82019-09-04 20:59:15 +0200225 // Count up the path separators from the RHS.. so we know which part
226 // of the path to return.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200227 sepcount = 0;
228 for (p = *fnamep; p < *fnamep + *fnamelen; MB_PTR_ADV(p))
229 if (vim_ispathsep(*p))
230 ++sepcount;
231
John Marriotte29c8ba2024-12-13 13:58:53 +0100232 // Need full path first (use expand_env_save() to remove a "~/")
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200233 hasTilde = (**fnamep == '~');
234 if (hasTilde)
235 pbuf = tfname = expand_env_save(*fnamep);
236 else
237 pbuf = tfname = FullName_save(*fnamep, FALSE);
238
239 len = tflen = (int)STRLEN(tfname);
240
241 if (get_short_pathname(&tfname, &pbuf, &len) == FAIL)
242 return FAIL;
243
244 if (len == 0)
245 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200246 // Don't have a valid filename, so shorten the rest of the
247 // path if we can. This CAN give us invalid 8.3 filenames, but
248 // there's not a lot of point in guessing what it might be.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200249 len = tflen;
250 if (shortpath_for_invalid_fname(&tfname, &pbuf, &len) == FAIL)
251 return FAIL;
252 }
253
Bram Moolenaar26262f82019-09-04 20:59:15 +0200254 // Count the paths backward to find the beginning of the desired string.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200255 for (p = tfname + len - 1; p >= tfname; --p)
256 {
257 if (has_mbyte)
258 p -= mb_head_off(tfname, p);
259 if (vim_ispathsep(*p))
260 {
261 if (sepcount == 0 || (hasTilde && sepcount == 1))
262 break;
263 else
264 sepcount --;
265 }
266 }
267 if (hasTilde)
268 {
269 --p;
270 if (p >= tfname)
271 *p = '~';
272 else
273 return FAIL;
274 }
275 else
276 ++p;
277
Bram Moolenaar26262f82019-09-04 20:59:15 +0200278 // Copy in the string - p indexes into tfname - allocated at pbuf
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200279 vim_free(*bufp);
John Marriotte29c8ba2024-12-13 13:58:53 +0100280 *fnamelen = (int)((tfname + len) - p);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200281 *bufp = pbuf;
282 *fnamep = p;
283
284 return OK;
285}
286#endif // MSWIN
287
288/*
289 * Adjust a filename, according to a string of modifiers.
290 * *fnamep must be NUL terminated when called. When returning, the length is
291 * determined by *fnamelen.
292 * Returns VALID_ flags or -1 for failure.
293 * When there is an error, *fnamep is set to NULL.
294 */
295 int
296modify_fname(
297 char_u *src, // string with modifiers
298 int tilde_file, // "~" is a file name, not $HOME
Mike Williams51024bb2024-05-30 07:46:30 +0200299 size_t *usedlen, // characters after src that are used
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200300 char_u **fnamep, // file name so far
301 char_u **bufp, // buffer for allocated file name or NULL
302 int *fnamelen) // length of fnamep
303{
304 int valid = 0;
305 char_u *tail;
306 char_u *s, *p, *pbuf;
307 char_u dirname[MAXPATHL];
308 int c;
309 int has_fullname = 0;
Bram Moolenaard816cd92020-02-04 22:23:09 +0100310 int has_homerelative = 0;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200311#ifdef MSWIN
312 char_u *fname_start = *fnamep;
313 int has_shortname = 0;
314#endif
315
316repeat:
Bram Moolenaar26262f82019-09-04 20:59:15 +0200317 // ":p" - full path/file_name
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200318 if (src[*usedlen] == ':' && src[*usedlen + 1] == 'p')
319 {
320 has_fullname = 1;
321
322 valid |= VALID_PATH;
323 *usedlen += 2;
324
Bram Moolenaar26262f82019-09-04 20:59:15 +0200325 // Expand "~/path" for all systems and "~user/path" for Unix and VMS
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200326 if ((*fnamep)[0] == '~'
327#if !defined(UNIX) && !(defined(VMS) && defined(USER_HOME))
328 && ((*fnamep)[1] == '/'
329# ifdef BACKSLASH_IN_FILENAME
330 || (*fnamep)[1] == '\\'
331# endif
332 || (*fnamep)[1] == NUL)
333#endif
334 && !(tilde_file && (*fnamep)[1] == NUL)
335 )
336 {
337 *fnamep = expand_env_save(*fnamep);
Bram Moolenaar26262f82019-09-04 20:59:15 +0200338 vim_free(*bufp); // free any allocated file name
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200339 *bufp = *fnamep;
340 if (*fnamep == NULL)
341 return -1;
342 }
343
Bram Moolenaar26262f82019-09-04 20:59:15 +0200344 // When "/." or "/.." is used: force expansion to get rid of it.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200345 for (p = *fnamep; *p != NUL; MB_PTR_ADV(p))
346 {
347 if (vim_ispathsep(*p)
348 && p[1] == '.'
349 && (p[2] == NUL
350 || vim_ispathsep(p[2])
351 || (p[2] == '.'
352 && (p[3] == NUL || vim_ispathsep(p[3])))))
353 break;
354 }
355
Bram Moolenaar26262f82019-09-04 20:59:15 +0200356 // FullName_save() is slow, don't use it when not needed.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200357 if (*p != NUL || !vim_isAbsName(*fnamep))
358 {
359 *fnamep = FullName_save(*fnamep, *p != NUL);
Bram Moolenaar26262f82019-09-04 20:59:15 +0200360 vim_free(*bufp); // free any allocated file name
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200361 *bufp = *fnamep;
362 if (*fnamep == NULL)
363 return -1;
364 }
365
366#ifdef MSWIN
367# if _WIN32_WINNT >= 0x0500
368 if (vim_strchr(*fnamep, '~') != NULL)
369 {
370 // Expand 8.3 filename to full path. Needed to make sure the same
371 // file does not have two different names.
372 // Note: problem does not occur if _WIN32_WINNT < 0x0500.
373 WCHAR *wfname = enc_to_utf16(*fnamep, NULL);
374 WCHAR buf[_MAX_PATH];
375
376 if (wfname != NULL)
377 {
378 if (GetLongPathNameW(wfname, buf, _MAX_PATH))
379 {
K.Takata54119102022-02-03 13:33:03 +0000380 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200381
K.Takata54119102022-02-03 13:33:03 +0000382 if (q != NULL)
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200383 {
384 vim_free(*bufp); // free any allocated file name
K.Takata54119102022-02-03 13:33:03 +0000385 *bufp = *fnamep = q;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200386 }
387 }
388 vim_free(wfname);
389 }
390 }
391# endif
392#endif
Bram Moolenaar26262f82019-09-04 20:59:15 +0200393 // Append a path separator to a directory.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200394 if (mch_isdir(*fnamep))
395 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200396 // Make room for one or two extra characters.
Bram Moolenaar71ccd032020-06-12 22:59:11 +0200397 *fnamep = vim_strnsave(*fnamep, STRLEN(*fnamep) + 2);
Bram Moolenaar26262f82019-09-04 20:59:15 +0200398 vim_free(*bufp); // free any allocated file name
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200399 *bufp = *fnamep;
400 if (*fnamep == NULL)
401 return -1;
402 add_pathsep(*fnamep);
403 }
404 }
405
Bram Moolenaar26262f82019-09-04 20:59:15 +0200406 // ":." - path relative to the current directory
407 // ":~" - path relative to the home directory
408 // ":8" - shortname path - postponed till after
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200409 while (src[*usedlen] == ':'
410 && ((c = src[*usedlen + 1]) == '.' || c == '~' || c == '8'))
411 {
412 *usedlen += 2;
413 if (c == '8')
414 {
415#ifdef MSWIN
Bram Moolenaar26262f82019-09-04 20:59:15 +0200416 has_shortname = 1; // Postpone this.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200417#endif
418 continue;
419 }
420 pbuf = NULL;
John Marriotte29c8ba2024-12-13 13:58:53 +0100421 // Need full path first (use expand_env_save() to remove a "~/")
Bram Moolenaard816cd92020-02-04 22:23:09 +0100422 if (!has_fullname && !has_homerelative)
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200423 {
=?UTF-8?q?Dundar=20G=C3=B6c?=78a84042022-02-09 15:20:39 +0000424 if (**fnamep == '~')
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200425 p = pbuf = expand_env_save(*fnamep);
426 else
427 p = pbuf = FullName_save(*fnamep, FALSE);
428 }
429 else
430 p = *fnamep;
431
432 has_fullname = 0;
433
434 if (p != NULL)
435 {
436 if (c == '.')
437 {
Bram Moolenaard816cd92020-02-04 22:23:09 +0100438 size_t namelen;
439
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200440 mch_dirname(dirname, MAXPATHL);
Bram Moolenaard816cd92020-02-04 22:23:09 +0100441 if (has_homerelative)
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200442 {
Bram Moolenaard816cd92020-02-04 22:23:09 +0100443 s = vim_strsave(dirname);
444 if (s != NULL)
445 {
446 home_replace(NULL, s, dirname, MAXPATHL, TRUE);
447 vim_free(s);
448 }
449 }
450 namelen = STRLEN(dirname);
451
452 // Do not call shorten_fname() here since it removes the prefix
453 // even though the path does not have a prefix.
454 if (fnamencmp(p, dirname, namelen) == 0)
455 {
456 p += namelen;
Bram Moolenaara78e9c62020-02-05 21:14:00 +0100457 if (vim_ispathsep(*p))
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200458 {
Bram Moolenaara78e9c62020-02-05 21:14:00 +0100459 while (*p && vim_ispathsep(*p))
460 ++p;
461 *fnamep = p;
462 if (pbuf != NULL)
463 {
464 // free any allocated file name
465 vim_free(*bufp);
466 *bufp = pbuf;
467 pbuf = NULL;
468 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200469 }
470 }
471 }
472 else
473 {
474 home_replace(NULL, p, dirname, MAXPATHL, TRUE);
Bram Moolenaar26262f82019-09-04 20:59:15 +0200475 // Only replace it when it starts with '~'
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200476 if (*dirname == '~')
477 {
478 s = vim_strsave(dirname);
479 if (s != NULL)
480 {
481 *fnamep = s;
482 vim_free(*bufp);
483 *bufp = s;
Bram Moolenaard816cd92020-02-04 22:23:09 +0100484 has_homerelative = TRUE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200485 }
486 }
487 }
488 vim_free(pbuf);
489 }
490 }
491
492 tail = gettail(*fnamep);
493 *fnamelen = (int)STRLEN(*fnamep);
494
Bram Moolenaar26262f82019-09-04 20:59:15 +0200495 // ":h" - head, remove "/file_name", can be repeated
496 // Don't remove the first "/" or "c:\"
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200497 while (src[*usedlen] == ':' && src[*usedlen + 1] == 'h')
498 {
499 valid |= VALID_HEAD;
500 *usedlen += 2;
501 s = get_past_head(*fnamep);
502 while (tail > s && after_pathsep(s, tail))
503 MB_PTR_BACK(*fnamep, tail);
504 *fnamelen = (int)(tail - *fnamep);
505#ifdef VMS
506 if (*fnamelen > 0)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200507 *fnamelen += 1; // the path separator is part of the path
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200508#endif
509 if (*fnamelen == 0)
510 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200511 // Result is empty. Turn it into "." to make ":cd %:h" work.
John Marriotte29c8ba2024-12-13 13:58:53 +0100512 p = vim_strnsave((char_u *)".", 1);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200513 if (p == NULL)
514 return -1;
515 vim_free(*bufp);
516 *bufp = *fnamep = tail = p;
517 *fnamelen = 1;
518 }
519 else
520 {
521 while (tail > s && !after_pathsep(s, tail))
522 MB_PTR_BACK(*fnamep, tail);
523 }
524 }
525
Bram Moolenaar26262f82019-09-04 20:59:15 +0200526 // ":8" - shortname
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200527 if (src[*usedlen] == ':' && src[*usedlen + 1] == '8')
528 {
529 *usedlen += 2;
530#ifdef MSWIN
531 has_shortname = 1;
532#endif
533 }
534
535#ifdef MSWIN
536 /*
537 * Handle ":8" after we have done 'heads' and before we do 'tails'.
538 */
539 if (has_shortname)
540 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200541 // Copy the string if it is shortened by :h and when it wasn't copied
542 // yet, because we are going to change it in place. Avoids changing
543 // the buffer name for "%:8".
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200544 if (*fnamelen < (int)STRLEN(*fnamep) || *fnamep == fname_start)
545 {
546 p = vim_strnsave(*fnamep, *fnamelen);
547 if (p == NULL)
548 return -1;
549 vim_free(*bufp);
550 *bufp = *fnamep = p;
551 }
552
Bram Moolenaar26262f82019-09-04 20:59:15 +0200553 // Split into two implementations - makes it easier. First is where
554 // there isn't a full name already, second is where there is.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200555 if (!has_fullname && !vim_isAbsName(*fnamep))
556 {
557 if (shortpath_for_partial(fnamep, bufp, fnamelen) == FAIL)
558 return -1;
559 }
560 else
561 {
562 int l = *fnamelen;
563
Bram Moolenaar26262f82019-09-04 20:59:15 +0200564 // Simple case, already have the full-name.
565 // Nearly always shorter, so try first time.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200566 if (get_short_pathname(fnamep, bufp, &l) == FAIL)
567 return -1;
568
569 if (l == 0)
570 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200571 // Couldn't find the filename, search the paths.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200572 l = *fnamelen;
573 if (shortpath_for_invalid_fname(fnamep, bufp, &l) == FAIL)
574 return -1;
575 }
576 *fnamelen = l;
577 }
578 }
579#endif // MSWIN
580
Bram Moolenaar26262f82019-09-04 20:59:15 +0200581 // ":t" - tail, just the basename
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200582 if (src[*usedlen] == ':' && src[*usedlen + 1] == 't')
583 {
584 *usedlen += 2;
585 *fnamelen -= (int)(tail - *fnamep);
586 *fnamep = tail;
587 }
588
Bram Moolenaar26262f82019-09-04 20:59:15 +0200589 // ":e" - extension, can be repeated
590 // ":r" - root, without extension, can be repeated
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200591 while (src[*usedlen] == ':'
592 && (src[*usedlen + 1] == 'e' || src[*usedlen + 1] == 'r'))
593 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200594 // find a '.' in the tail:
595 // - for second :e: before the current fname
596 // - otherwise: The last '.'
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200597 if (src[*usedlen + 1] == 'e' && *fnamep > tail)
598 s = *fnamep - 2;
599 else
600 s = *fnamep + *fnamelen - 1;
601 for ( ; s > tail; --s)
602 if (s[0] == '.')
603 break;
Bram Moolenaar26262f82019-09-04 20:59:15 +0200604 if (src[*usedlen + 1] == 'e') // :e
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200605 {
606 if (s > tail)
607 {
608 *fnamelen += (int)(*fnamep - (s + 1));
609 *fnamep = s + 1;
610#ifdef VMS
Bram Moolenaar26262f82019-09-04 20:59:15 +0200611 // cut version from the extension
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200612 s = *fnamep + *fnamelen - 1;
613 for ( ; s > *fnamep; --s)
614 if (s[0] == ';')
615 break;
616 if (s > *fnamep)
617 *fnamelen = s - *fnamep;
618#endif
619 }
620 else if (*fnamep <= tail)
621 *fnamelen = 0;
622 }
Bram Moolenaar26262f82019-09-04 20:59:15 +0200623 else // :r
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200624 {
Bram Moolenaarb1892952019-10-08 23:26:50 +0200625 char_u *limit = *fnamep;
626
627 if (limit < tail)
628 limit = tail;
629 if (s > limit) // remove one extension
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200630 *fnamelen = (int)(s - *fnamep);
631 }
632 *usedlen += 2;
633 }
634
Bram Moolenaar26262f82019-09-04 20:59:15 +0200635 // ":s?pat?foo?" - substitute
636 // ":gs?pat?foo?" - global substitute
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200637 if (src[*usedlen] == ':'
638 && (src[*usedlen + 1] == 's'
639 || (src[*usedlen + 1] == 'g' && src[*usedlen + 2] == 's')))
640 {
641 char_u *str;
642 char_u *pat;
643 char_u *sub;
644 int sep;
645 char_u *flags;
646 int didit = FALSE;
647
648 flags = (char_u *)"";
649 s = src + *usedlen + 2;
650 if (src[*usedlen + 1] == 'g')
651 {
652 flags = (char_u *)"g";
653 ++s;
654 }
655
656 sep = *s++;
657 if (sep)
658 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200659 // find end of pattern
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200660 p = vim_strchr(s, sep);
661 if (p != NULL)
662 {
Bram Moolenaar71ccd032020-06-12 22:59:11 +0200663 pat = vim_strnsave(s, p - s);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200664 if (pat != NULL)
665 {
666 s = p + 1;
Bram Moolenaar26262f82019-09-04 20:59:15 +0200667 // find end of substitution
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200668 p = vim_strchr(s, sep);
669 if (p != NULL)
670 {
Bram Moolenaar71ccd032020-06-12 22:59:11 +0200671 sub = vim_strnsave(s, p - s);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200672 str = vim_strnsave(*fnamep, *fnamelen);
673 if (sub != NULL && str != NULL)
674 {
John Marriottbd4614f2024-11-18 20:25:21 +0100675 size_t slen;
676
Mike Williams51024bb2024-05-30 07:46:30 +0200677 *usedlen = p + 1 - src;
John Marriottbd4614f2024-11-18 20:25:21 +0100678 s = do_string_sub(str, *fnamelen, pat, sub, NULL, flags, &slen);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200679 if (s != NULL)
680 {
681 *fnamep = s;
John Marriottbd4614f2024-11-18 20:25:21 +0100682 *fnamelen = slen;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200683 vim_free(*bufp);
684 *bufp = s;
685 didit = TRUE;
686 }
687 }
688 vim_free(sub);
689 vim_free(str);
690 }
691 vim_free(pat);
692 }
693 }
Bram Moolenaar26262f82019-09-04 20:59:15 +0200694 // after using ":s", repeat all the modifiers
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200695 if (didit)
696 goto repeat;
697 }
698 }
699
700 if (src[*usedlen] == ':' && src[*usedlen + 1] == 'S')
701 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200702 // vim_strsave_shellescape() needs a NUL terminated string.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200703 c = (*fnamep)[*fnamelen];
704 if (c != NUL)
705 (*fnamep)[*fnamelen] = NUL;
706 p = vim_strsave_shellescape(*fnamep, FALSE, FALSE);
707 if (c != NUL)
708 (*fnamep)[*fnamelen] = c;
709 if (p == NULL)
710 return -1;
711 vim_free(*bufp);
712 *bufp = *fnamep = p;
713 *fnamelen = (int)STRLEN(p);
714 *usedlen += 2;
715 }
716
717 return valid;
718}
719
Bram Moolenaar273af492020-09-25 23:49:01 +0200720/*
721 * Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
722 * "trim_len" specifies how many characters to keep for each directory.
723 * Must be 1 or more.
724 * It's done in-place.
725 */
726 static void
727shorten_dir_len(char_u *str, int trim_len)
728{
729 char_u *tail, *s, *d;
730 int skip = FALSE;
731 int dirchunk_len = 0;
732
733 tail = gettail(str);
734 d = str;
735 for (s = str; ; ++s)
736 {
737 if (s >= tail) // copy the whole tail
738 {
739 *d++ = *s;
740 if (*s == NUL)
741 break;
742 }
743 else if (vim_ispathsep(*s)) // copy '/' and next char
744 {
745 *d++ = *s;
746 skip = FALSE;
747 dirchunk_len = 0;
748 }
749 else if (!skip)
750 {
751 *d++ = *s; // copy next char
752 if (*s != '~' && *s != '.') // and leading "~" and "."
753 {
754 ++dirchunk_len; // only count word chars for the size
755
756 // keep copying chars until we have our preferred length (or
757 // until the above if/else branches move us along)
758 if (dirchunk_len >= trim_len)
759 skip = TRUE;
760 }
761
762 if (has_mbyte)
763 {
764 int l = mb_ptr2len(s);
765
766 while (--l > 0)
767 *d++ = *++s;
768 }
769 }
770 }
771}
772
773/*
774 * Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
775 * It's done in-place.
776 */
777 void
778shorten_dir(char_u *str)
779{
780 shorten_dir_len(str, 1);
781}
782
Bram Moolenaar022f9ef2022-07-02 17:36:31 +0100783/*
784 * Return TRUE if "fname" is a readable file.
785 */
786 int
787file_is_readable(char_u *fname)
788{
789 int fd;
790
791#ifndef O_NONBLOCK
792# define O_NONBLOCK 0
793#endif
794 if (*fname && !mch_isdir(fname)
795 && (fd = mch_open((char *)fname, O_RDONLY | O_NONBLOCK, 0)) >= 0)
796 {
797 close(fd);
798 return TRUE;
799 }
800 return FALSE;
801}
802
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200803#if defined(FEAT_EVAL) || defined(PROTO)
804
805/*
806 * "chdir(dir)" function
807 */
808 void
809f_chdir(typval_T *argvars, typval_T *rettv)
810{
811 char_u *cwd;
812 cdscope_T scope = CDSCOPE_GLOBAL;
813
814 rettv->v_type = VAR_STRING;
815 rettv->vval.v_string = NULL;
816
817 if (argvars[0].v_type != VAR_STRING)
Bram Moolenaarc5809432021-03-27 21:23:30 +0100818 {
Bram Moolenaard816cd92020-02-04 22:23:09 +0100819 // Returning an empty string means it failed.
Bram Moolenaar002bc792020-06-05 22:33:42 +0200820 // No error message, for historic reasons.
Bram Moolenaarc5809432021-03-27 21:23:30 +0100821 if (in_vim9script())
822 (void) check_for_string_arg(argvars, 0);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200823 return;
Bram Moolenaarc5809432021-03-27 21:23:30 +0100824 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200825
826 // Return the current directory
827 cwd = alloc(MAXPATHL);
828 if (cwd != NULL)
829 {
830 if (mch_dirname(cwd, MAXPATHL) != FAIL)
831 {
832#ifdef BACKSLASH_IN_FILENAME
833 slash_adjust(cwd);
834#endif
835 rettv->vval.v_string = vim_strsave(cwd);
836 }
837 vim_free(cwd);
838 }
839
840 if (curwin->w_localdir != NULL)
841 scope = CDSCOPE_WINDOW;
842 else if (curtab->tp_localdir != NULL)
843 scope = CDSCOPE_TABPAGE;
844
845 if (!changedir_func(argvars[0].vval.v_string, TRUE, scope))
846 // Directory change failed
847 VIM_CLEAR(rettv->vval.v_string);
848}
849
850/*
851 * "delete()" function
852 */
853 void
854f_delete(typval_T *argvars, typval_T *rettv)
855{
856 char_u nbuf[NUMBUFLEN];
857 char_u *name;
858 char_u *flags;
859
860 rettv->vval.v_number = -1;
861 if (check_restricted() || check_secure())
862 return;
863
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +0200864 if (in_vim9script()
865 && (check_for_string_arg(argvars, 0) == FAIL
866 || check_for_opt_string_arg(argvars, 1) == FAIL))
867 return;
868
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200869 name = tv_get_string(&argvars[0]);
870 if (name == NULL || *name == NUL)
871 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +0000872 emsg(_(e_invalid_argument));
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200873 return;
874 }
875
876 if (argvars[1].v_type != VAR_UNKNOWN)
877 flags = tv_get_string_buf(&argvars[1], nbuf);
878 else
879 flags = (char_u *)"";
880
881 if (*flags == NUL)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200882 // delete a file
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200883 rettv->vval.v_number = mch_remove(name) == 0 ? 0 : -1;
884 else if (STRCMP(flags, "d") == 0)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200885 // delete an empty directory
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200886 rettv->vval.v_number = mch_rmdir(name) == 0 ? 0 : -1;
887 else if (STRCMP(flags, "rf") == 0)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200888 // delete a directory recursively
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200889 rettv->vval.v_number = delete_recursive(name);
890 else
Bram Moolenaar108010a2021-06-27 22:03:33 +0200891 semsg(_(e_invalid_expression_str), flags);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200892}
893
894/*
895 * "executable()" function
896 */
897 void
898f_executable(typval_T *argvars, typval_T *rettv)
899{
Bram Moolenaar32105ae2021-03-27 18:59:25 +0100900 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100901 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200902
Bram Moolenaar26262f82019-09-04 20:59:15 +0200903 // Check in $PATH and also check directly if there is a directory name.
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100904 rettv->vval.v_number = mch_can_exe(tv_get_string(&argvars[0]), NULL, TRUE);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200905}
906
907/*
908 * "exepath()" function
909 */
910 void
911f_exepath(typval_T *argvars, typval_T *rettv)
912{
913 char_u *p = NULL;
914
Bram Moolenaar32105ae2021-03-27 18:59:25 +0100915 if (in_vim9script() && check_for_nonempty_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100916 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200917 (void)mch_can_exe(tv_get_string(&argvars[0]), &p, TRUE);
918 rettv->v_type = VAR_STRING;
919 rettv->vval.v_string = p;
920}
921
922/*
923 * "filereadable()" function
924 */
925 void
926f_filereadable(typval_T *argvars, typval_T *rettv)
927{
Bram Moolenaar32105ae2021-03-27 18:59:25 +0100928 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100929 return;
Bram Moolenaar4dea2d92022-03-31 11:37:57 +0100930 rettv->vval.v_number = file_is_readable(tv_get_string(&argvars[0]));
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200931}
932
933/*
934 * Return 0 for not writable, 1 for writable file, 2 for a dir which we have
935 * rights to write into.
936 */
937 void
938f_filewritable(typval_T *argvars, typval_T *rettv)
939{
Bram Moolenaar32105ae2021-03-27 18:59:25 +0100940 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100941 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200942 rettv->vval.v_number = filewritable(tv_get_string(&argvars[0]));
943}
944
Bram Moolenaar840d16f2019-09-10 21:27:18 +0200945 static void
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200946findfilendir(
Yee Cheng China7767072023-04-16 20:13:12 +0100947 typval_T *argvars,
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200948 typval_T *rettv,
Yee Cheng China7767072023-04-16 20:13:12 +0100949 int find_what)
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200950{
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200951 char_u *fname;
952 char_u *fresult = NULL;
953 char_u *path = *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path;
954 char_u *p;
955 char_u pathbuf[NUMBUFLEN];
956 int count = 1;
957 int first = TRUE;
958 int error = FALSE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200959
960 rettv->vval.v_string = NULL;
961 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +0200962 if (in_vim9script()
963 && (check_for_nonempty_string_arg(argvars, 0) == FAIL
964 || check_for_opt_string_arg(argvars, 1) == FAIL
965 || (argvars[1].v_type != VAR_UNKNOWN
966 && check_for_opt_number_arg(argvars, 2) == FAIL)))
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100967 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200968
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200969 fname = tv_get_string(&argvars[0]);
970
971 if (argvars[1].v_type != VAR_UNKNOWN)
972 {
973 p = tv_get_string_buf_chk(&argvars[1], pathbuf);
974 if (p == NULL)
975 error = TRUE;
976 else
977 {
978 if (*p != NUL)
979 path = p;
980
981 if (argvars[2].v_type != VAR_UNKNOWN)
982 count = (int)tv_get_number_chk(&argvars[2], &error);
983 }
984 }
985
986 if (count < 0 && rettv_list_alloc(rettv) == FAIL)
987 error = TRUE;
988
989 if (*fname != NUL && !error)
990 {
Bram Moolenaar5145c9a2023-03-11 13:55:53 +0000991 char_u *file_to_find = NULL;
992 char *search_ctx = NULL;
993
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200994 do
995 {
996 if (rettv->v_type == VAR_STRING || rettv->v_type == VAR_LIST)
997 vim_free(fresult);
998 fresult = find_file_in_path_option(first ? fname : NULL,
999 first ? (int)STRLEN(fname) : 0,
1000 0, first, path,
1001 find_what,
1002 curbuf->b_ffname,
1003 find_what == FINDFILE_DIR
Bram Moolenaar5145c9a2023-03-11 13:55:53 +00001004 ? (char_u *)"" : curbuf->b_p_sua,
1005 &file_to_find, &search_ctx);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001006 first = FALSE;
1007
1008 if (fresult != NULL && rettv->v_type == VAR_LIST)
1009 list_append_string(rettv->vval.v_list, fresult, -1);
1010
1011 } while ((rettv->v_type == VAR_LIST || --count > 0) && fresult != NULL);
Bram Moolenaar5145c9a2023-03-11 13:55:53 +00001012
1013 vim_free(file_to_find);
1014 vim_findfile_cleanup(search_ctx);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001015 }
1016
1017 if (rettv->v_type == VAR_STRING)
1018 rettv->vval.v_string = fresult;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001019}
1020
1021/*
1022 * "finddir({fname}[, {path}[, {count}]])" function
1023 */
1024 void
1025f_finddir(typval_T *argvars, typval_T *rettv)
1026{
1027 findfilendir(argvars, rettv, FINDFILE_DIR);
1028}
1029
1030/*
1031 * "findfile({fname}[, {path}[, {count}]])" function
1032 */
1033 void
1034f_findfile(typval_T *argvars, typval_T *rettv)
1035{
1036 findfilendir(argvars, rettv, FINDFILE_FILE);
1037}
1038
1039/*
1040 * "fnamemodify({fname}, {mods})" function
1041 */
1042 void
1043f_fnamemodify(typval_T *argvars, typval_T *rettv)
1044{
1045 char_u *fname;
1046 char_u *mods;
Mike Williams51024bb2024-05-30 07:46:30 +02001047 size_t usedlen = 0;
Bram Moolenaarc5308522020-12-13 12:25:35 +01001048 int len = 0;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001049 char_u *fbuf = NULL;
1050 char_u buf[NUMBUFLEN];
1051
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001052 if (in_vim9script()
1053 && (check_for_string_arg(argvars, 0) == FAIL
1054 || check_for_string_arg(argvars, 1) == FAIL))
Bram Moolenaar7bb4e742020-12-09 12:41:50 +01001055 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001056
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001057 fname = tv_get_string_chk(&argvars[0]);
1058 mods = tv_get_string_buf_chk(&argvars[1], buf);
Bram Moolenaarc5308522020-12-13 12:25:35 +01001059 if (mods == NULL || fname == NULL)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001060 fname = NULL;
Bram Moolenaarc5308522020-12-13 12:25:35 +01001061 else
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001062 {
1063 len = (int)STRLEN(fname);
Bram Moolenaarc5308522020-12-13 12:25:35 +01001064 if (mods != NULL && *mods != NUL)
1065 (void)modify_fname(mods, FALSE, &usedlen, &fname, &fbuf, &len);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001066 }
1067
1068 rettv->v_type = VAR_STRING;
1069 if (fname == NULL)
1070 rettv->vval.v_string = NULL;
1071 else
1072 rettv->vval.v_string = vim_strnsave(fname, len);
1073 vim_free(fbuf);
1074}
1075
1076/*
1077 * "getcwd()" function
1078 *
1079 * Return the current working directory of a window in a tab page.
1080 * First optional argument 'winnr' is the window number or -1 and the second
1081 * optional argument 'tabnr' is the tab page number.
1082 *
1083 * If no arguments are supplied, then return the directory of the current
1084 * window.
1085 * If only 'winnr' is specified and is not -1 or 0 then return the directory of
1086 * the specified window.
1087 * If 'winnr' is 0 then return the directory of the current window.
1088 * If both 'winnr and 'tabnr' are specified and 'winnr' is -1 then return the
1089 * directory of the specified tab page. Otherwise return the directory of the
1090 * specified window in the specified tab page.
1091 * If the window or the tab page doesn't exist then return NULL.
1092 */
1093 void
1094f_getcwd(typval_T *argvars, typval_T *rettv)
1095{
1096 win_T *wp = NULL;
1097 tabpage_T *tp = NULL;
1098 char_u *cwd;
1099 int global = FALSE;
1100
1101 rettv->v_type = VAR_STRING;
1102 rettv->vval.v_string = NULL;
1103
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001104 if (in_vim9script()
1105 && (check_for_opt_number_arg(argvars, 0) == FAIL
1106 || (argvars[0].v_type != VAR_UNKNOWN
1107 && check_for_opt_number_arg(argvars, 1) == FAIL)))
1108 return;
1109
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001110 if (argvars[0].v_type == VAR_NUMBER
1111 && argvars[0].vval.v_number == -1
1112 && argvars[1].v_type == VAR_UNKNOWN)
1113 global = TRUE;
1114 else
1115 wp = find_tabwin(&argvars[0], &argvars[1], &tp);
1116
Bram Moolenaar851c7a62021-11-18 20:47:31 +00001117 if (wp != NULL && wp->w_localdir != NULL
1118 && argvars[0].v_type != VAR_UNKNOWN)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001119 rettv->vval.v_string = vim_strsave(wp->w_localdir);
Bram Moolenaar851c7a62021-11-18 20:47:31 +00001120 else if (tp != NULL && tp->tp_localdir != NULL
1121 && argvars[0].v_type != VAR_UNKNOWN)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001122 rettv->vval.v_string = vim_strsave(tp->tp_localdir);
1123 else if (wp != NULL || tp != NULL || global)
1124 {
Bram Moolenaar851c7a62021-11-18 20:47:31 +00001125 if (globaldir != NULL && argvars[0].v_type != VAR_UNKNOWN)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001126 rettv->vval.v_string = vim_strsave(globaldir);
1127 else
1128 {
1129 cwd = alloc(MAXPATHL);
1130 if (cwd != NULL)
1131 {
1132 if (mch_dirname(cwd, MAXPATHL) != FAIL)
1133 rettv->vval.v_string = vim_strsave(cwd);
1134 vim_free(cwd);
1135 }
1136 }
1137 }
1138#ifdef BACKSLASH_IN_FILENAME
1139 if (rettv->vval.v_string != NULL)
1140 slash_adjust(rettv->vval.v_string);
1141#endif
1142}
1143
1144/*
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001145 * Convert "st" to file permission string.
1146 */
1147 char_u *
1148getfpermst(stat_T *st, char_u *perm)
1149{
1150 char_u flags[] = "rwx";
1151 int i;
1152
1153 for (i = 0; i < 9; i++)
1154 {
1155 if (st->st_mode & (1 << (8 - i)))
1156 perm[i] = flags[i % 3];
1157 else
1158 perm[i] = '-';
1159 }
1160 return perm;
1161}
1162
1163/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001164 * "getfperm({fname})" function
1165 */
1166 void
1167f_getfperm(typval_T *argvars, typval_T *rettv)
1168{
1169 char_u *fname;
1170 stat_T st;
1171 char_u *perm = NULL;
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001172 char_u permbuf[] = "---------";
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001173
Bram Moolenaar32105ae2021-03-27 18:59:25 +01001174 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +01001175 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001176
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001177 fname = tv_get_string(&argvars[0]);
1178
1179 rettv->v_type = VAR_STRING;
1180 if (mch_stat((char *)fname, &st) >= 0)
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001181 perm = vim_strsave(getfpermst(&st, permbuf));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001182 rettv->vval.v_string = perm;
1183}
1184
1185/*
1186 * "getfsize({fname})" function
1187 */
1188 void
1189f_getfsize(typval_T *argvars, typval_T *rettv)
1190{
1191 char_u *fname;
1192 stat_T st;
1193
Bram Moolenaar32105ae2021-03-27 18:59:25 +01001194 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +01001195 return;
1196
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001197 fname = tv_get_string(&argvars[0]);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001198 if (mch_stat((char *)fname, &st) >= 0)
1199 {
1200 if (mch_isdir(fname))
1201 rettv->vval.v_number = 0;
1202 else
1203 {
1204 rettv->vval.v_number = (varnumber_T)st.st_size;
1205
Bram Moolenaar26262f82019-09-04 20:59:15 +02001206 // non-perfect check for overflow
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001207 if ((off_T)rettv->vval.v_number != (off_T)st.st_size)
1208 rettv->vval.v_number = -2;
1209 }
1210 }
1211 else
1212 rettv->vval.v_number = -1;
1213}
1214
1215/*
1216 * "getftime({fname})" function
1217 */
1218 void
1219f_getftime(typval_T *argvars, typval_T *rettv)
1220{
1221 char_u *fname;
1222 stat_T st;
1223
Bram Moolenaar32105ae2021-03-27 18:59:25 +01001224 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +01001225 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001226
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001227 fname = tv_get_string(&argvars[0]);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001228 if (mch_stat((char *)fname, &st) >= 0)
1229 rettv->vval.v_number = (varnumber_T)st.st_mtime;
1230 else
1231 rettv->vval.v_number = -1;
1232}
1233
1234/*
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001235 * Convert "st" to file type string.
1236 */
1237 char_u *
1238getftypest(stat_T *st)
1239{
1240 char *t;
1241
1242 if (S_ISREG(st->st_mode))
1243 t = "file";
1244 else if (S_ISDIR(st->st_mode))
1245 t = "dir";
1246 else if (S_ISLNK(st->st_mode))
1247 t = "link";
1248 else if (S_ISBLK(st->st_mode))
1249 t = "bdev";
1250 else if (S_ISCHR(st->st_mode))
1251 t = "cdev";
1252 else if (S_ISFIFO(st->st_mode))
1253 t = "fifo";
1254 else if (S_ISSOCK(st->st_mode))
1255 t = "socket";
1256 else
1257 t = "other";
1258 return (char_u*)t;
1259}
1260
1261/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001262 * "getftype({fname})" function
1263 */
1264 void
1265f_getftype(typval_T *argvars, typval_T *rettv)
1266{
1267 char_u *fname;
1268 stat_T st;
1269 char_u *type = NULL;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001270
Bram Moolenaar32105ae2021-03-27 18:59:25 +01001271 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +01001272 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001273
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001274 fname = tv_get_string(&argvars[0]);
1275
1276 rettv->v_type = VAR_STRING;
1277 if (mch_lstat((char *)fname, &st) >= 0)
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001278 type = vim_strsave(getftypest(&st));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001279 rettv->vval.v_string = type;
1280}
1281
1282/*
1283 * "glob()" function
1284 */
1285 void
1286f_glob(typval_T *argvars, typval_T *rettv)
1287{
1288 int options = WILD_SILENT|WILD_USE_NL;
1289 expand_T xpc;
1290 int error = FALSE;
1291
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02001292 if (in_vim9script()
1293 && (check_for_string_arg(argvars, 0) == FAIL
1294 || check_for_opt_bool_arg(argvars, 1) == FAIL
1295 || (argvars[1].v_type != VAR_UNKNOWN
1296 && (check_for_opt_bool_arg(argvars, 2) == FAIL
1297 || (argvars[2].v_type != VAR_UNKNOWN
1298 && check_for_opt_bool_arg(argvars, 3) == FAIL)))))
1299 return;
1300
Bram Moolenaar26262f82019-09-04 20:59:15 +02001301 // When the optional second argument is non-zero, don't remove matches
1302 // for 'wildignore' and don't put matches for 'suffixes' at the end.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001303 rettv->v_type = VAR_STRING;
1304 if (argvars[1].v_type != VAR_UNKNOWN)
1305 {
Bram Moolenaar5892ea12020-09-02 21:53:11 +02001306 if (tv_get_bool_chk(&argvars[1], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001307 options |= WILD_KEEP_ALL;
1308 if (argvars[2].v_type != VAR_UNKNOWN)
1309 {
Bram Moolenaar5892ea12020-09-02 21:53:11 +02001310 if (tv_get_bool_chk(&argvars[2], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001311 rettv_list_set(rettv, NULL);
1312 if (argvars[3].v_type != VAR_UNKNOWN
Bram Moolenaar5892ea12020-09-02 21:53:11 +02001313 && tv_get_bool_chk(&argvars[3], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001314 options |= WILD_ALLLINKS;
1315 }
1316 }
1317 if (!error)
1318 {
1319 ExpandInit(&xpc);
1320 xpc.xp_context = EXPAND_FILES;
1321 if (p_wic)
1322 options += WILD_ICASE;
1323 if (rettv->v_type == VAR_STRING)
1324 rettv->vval.v_string = ExpandOne(&xpc, tv_get_string(&argvars[0]),
1325 NULL, options, WILD_ALL);
Bram Moolenaar8088ae92022-06-20 11:38:17 +01001326 else if (rettv_list_alloc(rettv) == OK)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001327 {
1328 int i;
1329
1330 ExpandOne(&xpc, tv_get_string(&argvars[0]),
1331 NULL, options, WILD_ALL_KEEP);
1332 for (i = 0; i < xpc.xp_numfiles; i++)
1333 list_append_string(rettv->vval.v_list, xpc.xp_files[i], -1);
1334
1335 ExpandCleanup(&xpc);
1336 }
1337 }
1338 else
1339 rettv->vval.v_string = NULL;
1340}
1341
1342/*
1343 * "glob2regpat()" function
1344 */
1345 void
1346f_glob2regpat(typval_T *argvars, typval_T *rettv)
1347{
Bram Moolenaar3cfa5b12021-06-06 14:14:39 +02001348 char_u buf[NUMBUFLEN];
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001349 char_u *pat;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001350
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001351 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
1352 return;
1353
1354 pat = tv_get_string_buf_chk_strict(&argvars[0], buf, in_vim9script());
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001355 rettv->v_type = VAR_STRING;
1356 rettv->vval.v_string = (pat == NULL)
1357 ? NULL : file_pat_to_reg_pat(pat, NULL, NULL, FALSE);
1358}
1359
1360/*
1361 * "globpath()" function
1362 */
1363 void
1364f_globpath(typval_T *argvars, typval_T *rettv)
1365{
1366 int flags = WILD_IGNORE_COMPLETESLASH;
1367 char_u buf1[NUMBUFLEN];
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02001368 char_u *file;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001369 int error = FALSE;
1370 garray_T ga;
1371 int i;
1372
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02001373 if (in_vim9script()
1374 && (check_for_string_arg(argvars, 0) == FAIL
1375 || check_for_string_arg(argvars, 1) == FAIL
1376 || check_for_opt_bool_arg(argvars, 2) == FAIL
1377 || (argvars[2].v_type != VAR_UNKNOWN
1378 && (check_for_opt_bool_arg(argvars, 3) == FAIL
1379 || (argvars[3].v_type != VAR_UNKNOWN
1380 && check_for_opt_bool_arg(argvars, 4) == FAIL)))))
1381 return;
1382
1383 file = tv_get_string_buf_chk(&argvars[1], buf1);
1384
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001385 // When the optional second argument is non-zero, don't remove matches
1386 // for 'wildignore' and don't put matches for 'suffixes' at the end.
1387 rettv->v_type = VAR_STRING;
1388 if (argvars[2].v_type != VAR_UNKNOWN)
1389 {
Bram Moolenaarf966ce52020-09-02 21:57:07 +02001390 if (tv_get_bool_chk(&argvars[2], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001391 flags |= WILD_KEEP_ALL;
1392 if (argvars[3].v_type != VAR_UNKNOWN)
1393 {
Bram Moolenaarf966ce52020-09-02 21:57:07 +02001394 if (tv_get_bool_chk(&argvars[3], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001395 rettv_list_set(rettv, NULL);
1396 if (argvars[4].v_type != VAR_UNKNOWN
Bram Moolenaarf966ce52020-09-02 21:57:07 +02001397 && tv_get_bool_chk(&argvars[4], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001398 flags |= WILD_ALLLINKS;
1399 }
1400 }
1401 if (file != NULL && !error)
1402 {
Bram Moolenaar04935fb2022-01-08 16:19:22 +00001403 ga_init2(&ga, sizeof(char_u *), 10);
zeertzjq3770f4c2023-01-22 18:38:51 +00001404 globpath(tv_get_string(&argvars[0]), file, &ga, flags, FALSE);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001405 if (rettv->v_type == VAR_STRING)
1406 rettv->vval.v_string = ga_concat_strings(&ga, "\n");
Bram Moolenaar8088ae92022-06-20 11:38:17 +01001407 else if (rettv_list_alloc(rettv) == OK)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001408 for (i = 0; i < ga.ga_len; ++i)
1409 list_append_string(rettv->vval.v_list,
1410 ((char_u **)(ga.ga_data))[i], -1);
1411 ga_clear_strings(&ga);
1412 }
1413 else
1414 rettv->vval.v_string = NULL;
1415}
1416
1417/*
1418 * "isdirectory()" function
1419 */
1420 void
1421f_isdirectory(typval_T *argvars, typval_T *rettv)
1422{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001423 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
1424 return;
1425
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001426 rettv->vval.v_number = mch_isdir(tv_get_string(&argvars[0]));
1427}
1428
1429/*
LemonBoydca1d402022-04-28 15:26:33 +01001430 * "isabsolutepath()" function
1431 */
1432 void
1433f_isabsolutepath(typval_T *argvars, typval_T *rettv)
1434{
1435 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
1436 return;
1437
1438 rettv->vval.v_number = mch_isFullName(tv_get_string_strict(&argvars[0]));
1439}
1440
1441/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001442 * Create the directory in which "dir" is located, and higher levels when
1443 * needed.
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001444 * Set "created" to the full name of the first created directory. It will be
1445 * NULL until that happens.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001446 * Return OK or FAIL.
1447 */
1448 static int
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001449mkdir_recurse(char_u *dir, int prot, char_u **created)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001450{
1451 char_u *p;
1452 char_u *updir;
1453 int r = FAIL;
1454
Bram Moolenaar26262f82019-09-04 20:59:15 +02001455 // Get end of directory name in "dir".
1456 // We're done when it's "/" or "c:/".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001457 p = gettail_sep(dir);
1458 if (p <= get_past_head(dir))
1459 return OK;
1460
Bram Moolenaar26262f82019-09-04 20:59:15 +02001461 // If the directory exists we're done. Otherwise: create it.
Bram Moolenaar71ccd032020-06-12 22:59:11 +02001462 updir = vim_strnsave(dir, p - dir);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001463 if (updir == NULL)
1464 return FAIL;
1465 if (mch_isdir(updir))
1466 r = OK;
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001467 else if (mkdir_recurse(updir, prot, created) == OK)
1468 {
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001469 r = vim_mkdir_emsg(updir, prot);
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001470 if (r == OK && created != NULL && *created == NULL)
1471 *created = FullName_save(updir, FALSE);
1472 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001473 vim_free(updir);
1474 return r;
1475}
1476
1477/*
1478 * "mkdir()" function
1479 */
1480 void
1481f_mkdir(typval_T *argvars, typval_T *rettv)
1482{
1483 char_u *dir;
1484 char_u buf[NUMBUFLEN];
1485 int prot = 0755;
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001486 int defer = FALSE;
1487 int defer_recurse = FALSE;
1488 char_u *created = NULL;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001489
1490 rettv->vval.v_number = FAIL;
1491 if (check_restricted() || check_secure())
1492 return;
1493
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001494 if (in_vim9script()
1495 && (check_for_nonempty_string_arg(argvars, 0) == FAIL
1496 || check_for_opt_string_arg(argvars, 1) == FAIL
1497 || (argvars[1].v_type != VAR_UNKNOWN
1498 && check_for_opt_number_arg(argvars, 2) == FAIL)))
1499 return;
1500
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001501 dir = tv_get_string_buf(&argvars[0], buf);
1502 if (*dir == NUL)
1503 return;
1504
1505 if (*gettail(dir) == NUL)
Bram Moolenaar26262f82019-09-04 20:59:15 +02001506 // remove trailing slashes
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001507 *gettail_sep(dir) = NUL;
1508
1509 if (argvars[1].v_type != VAR_UNKNOWN)
1510 {
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001511 char_u *arg2;
1512
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001513 if (argvars[2].v_type != VAR_UNKNOWN)
1514 {
1515 prot = (int)tv_get_number_chk(&argvars[2], NULL);
1516 if (prot == -1)
1517 return;
1518 }
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001519 arg2 = tv_get_string(&argvars[1]);
1520 defer = vim_strchr(arg2, 'D') != NULL;
1521 defer_recurse = vim_strchr(arg2, 'R') != NULL;
1522 if ((defer || defer_recurse) && !can_add_defer())
1523 return;
1524
1525 if (vim_strchr(arg2, 'p') != NULL)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001526 {
1527 if (mch_isdir(dir))
1528 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001529 // With the "p" flag it's OK if the dir already exists.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001530 rettv->vval.v_number = OK;
1531 return;
1532 }
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001533 mkdir_recurse(dir, prot, defer || defer_recurse ? &created : NULL);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001534 }
1535 }
1536 rettv->vval.v_number = vim_mkdir_emsg(dir, prot);
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001537
1538 // Handle "D" and "R": deferred deletion of the created directory.
1539 if (rettv->vval.v_number == OK
1540 && created == NULL && (defer || defer_recurse))
1541 created = FullName_save(dir, FALSE);
1542 if (created != NULL)
1543 {
1544 typval_T tv[2];
1545
1546 tv[0].v_type = VAR_STRING;
1547 tv[0].v_lock = 0;
1548 tv[0].vval.v_string = created;
1549 tv[1].v_type = VAR_STRING;
1550 tv[1].v_lock = 0;
John Marriotte29c8ba2024-12-13 13:58:53 +01001551 if (defer_recurse)
1552 tv[1].vval.v_string = vim_strnsave((char_u *)"rf", 2);
1553 else
1554 tv[1].vval.v_string = vim_strnsave((char_u *)"d", 1);
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001555 if (tv[0].vval.v_string == NULL || tv[1].vval.v_string == NULL
1556 || add_defer((char_u *)"delete", 2, tv) == FAIL)
1557 {
1558 vim_free(tv[0].vval.v_string);
1559 vim_free(tv[1].vval.v_string);
1560 }
1561 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001562}
1563
1564/*
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02001565 * "pathshorten()" function
1566 */
1567 void
1568f_pathshorten(typval_T *argvars, typval_T *rettv)
1569{
1570 char_u *p;
Bram Moolenaar6a33ef02020-09-25 22:42:48 +02001571 int trim_len = 1;
1572
Yegappan Lakshmanan1a71d312021-07-15 12:49:58 +02001573 if (in_vim9script()
1574 && (check_for_string_arg(argvars, 0) == FAIL
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02001575 || check_for_opt_number_arg(argvars, 1) == FAIL))
Yegappan Lakshmanan1a71d312021-07-15 12:49:58 +02001576 return;
1577
Bram Moolenaar6a33ef02020-09-25 22:42:48 +02001578 if (argvars[1].v_type != VAR_UNKNOWN)
1579 {
1580 trim_len = (int)tv_get_number(&argvars[1]);
1581 if (trim_len < 1)
1582 trim_len = 1;
1583 }
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02001584
1585 rettv->v_type = VAR_STRING;
1586 p = tv_get_string_chk(&argvars[0]);
Bram Moolenaar6a33ef02020-09-25 22:42:48 +02001587
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02001588 if (p == NULL)
1589 rettv->vval.v_string = NULL;
1590 else
1591 {
1592 p = vim_strsave(p);
1593 rettv->vval.v_string = p;
1594 if (p != NULL)
Bram Moolenaar6a33ef02020-09-25 22:42:48 +02001595 shorten_dir_len(p, trim_len);
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02001596 }
1597}
1598
1599/*
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001600 * Common code for readdir_checkitem() and readdirex_checkitem().
1601 * Either "name" or "dict" is NULL.
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001602 */
1603 static int
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001604checkitem_common(void *context, char_u *name, dict_T *dict)
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001605{
1606 typval_T *expr = (typval_T *)context;
1607 typval_T save_val;
1608 typval_T rettv;
1609 typval_T argv[2];
1610 int retval = 0;
1611 int error = FALSE;
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001612
1613 prepare_vimvar(VV_VAL, &save_val);
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001614 if (name != NULL)
1615 {
1616 set_vim_var_string(VV_VAL, name, -1);
1617 argv[0].v_type = VAR_STRING;
1618 argv[0].vval.v_string = name;
1619 }
1620 else
1621 {
1622 set_vim_var_dict(VV_VAL, dict);
1623 argv[0].v_type = VAR_DICT;
1624 argv[0].vval.v_dict = dict;
1625 }
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001626
zeertzjqad0c4422023-08-17 22:15:47 +02001627 if (eval_expr_typval(expr, FALSE, argv, 1, NULL, &rettv) == FAIL)
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001628 goto theend;
1629
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001630 // We want to use -1, but also true/false should be allowed.
1631 if (rettv.v_type == VAR_SPECIAL || rettv.v_type == VAR_BOOL)
1632 {
1633 rettv.v_type = VAR_NUMBER;
1634 rettv.vval.v_number = rettv.vval.v_number == VVAL_TRUE;
1635 }
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001636 retval = tv_get_number_chk(&rettv, &error);
1637 if (error)
1638 retval = -1;
1639 clear_tv(&rettv);
1640
1641theend:
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001642 if (name != NULL)
1643 set_vim_var_string(VV_VAL, NULL, 0);
1644 else
1645 set_vim_var_dict(VV_VAL, NULL);
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001646 restore_vimvar(VV_VAL, &save_val);
1647 return retval;
1648}
1649
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001650/*
1651 * Evaluate "expr" (= "context") for readdir().
1652 */
1653 static int
1654readdir_checkitem(void *context, void *item)
1655{
1656 char_u *name = (char_u *)item;
1657
1658 return checkitem_common(context, name, NULL);
1659}
1660
Bram Moolenaard83392a2022-09-01 12:22:46 +01001661/*
1662 * Process the keys in the Dict argument to the readdir() and readdirex()
1663 * functions. Assumes the Dict argument is the 3rd argument.
1664 */
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001665 static int
Bram Moolenaard83392a2022-09-01 12:22:46 +01001666readdirex_dict_arg(typval_T *argvars, int *cmp)
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001667{
1668 char_u *compare;
1669
Bram Moolenaard83392a2022-09-01 12:22:46 +01001670 if (check_for_nonnull_dict_arg(argvars, 2) == FAIL)
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001671 return FAIL;
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001672
Bram Moolenaard83392a2022-09-01 12:22:46 +01001673 if (dict_has_key(argvars[2].vval.v_dict, "sort"))
1674 compare = dict_get_string(argvars[2].vval.v_dict, "sort", FALSE);
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001675 else
1676 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00001677 semsg(_(e_dictionary_key_str_required), "sort");
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001678 return FAIL;
1679 }
1680
1681 if (STRCMP(compare, (char_u *) "none") == 0)
1682 *cmp = READDIR_SORT_NONE;
1683 else if (STRCMP(compare, (char_u *) "case") == 0)
1684 *cmp = READDIR_SORT_BYTE;
1685 else if (STRCMP(compare, (char_u *) "icase") == 0)
1686 *cmp = READDIR_SORT_IC;
1687 else if (STRCMP(compare, (char_u *) "collate") == 0)
1688 *cmp = READDIR_SORT_COLLATE;
1689 return OK;
1690}
1691
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001692/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001693 * "readdir()" function
1694 */
1695 void
1696f_readdir(typval_T *argvars, typval_T *rettv)
1697{
1698 typval_T *expr;
1699 int ret;
1700 char_u *path;
1701 char_u *p;
1702 garray_T ga;
1703 int i;
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01001704 int sort = READDIR_SORT_BYTE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001705
1706 if (rettv_list_alloc(rettv) == FAIL)
1707 return;
Yegappan Lakshmanan5bca9062021-07-24 21:33:26 +02001708
1709 if (in_vim9script()
1710 && (check_for_string_arg(argvars, 0) == FAIL
1711 || (argvars[1].v_type != VAR_UNKNOWN
1712 && check_for_opt_dict_arg(argvars, 2) == FAIL)))
1713 return;
1714
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001715 path = tv_get_string(&argvars[0]);
1716 expr = &argvars[1];
1717
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001718 if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN &&
Bram Moolenaard83392a2022-09-01 12:22:46 +01001719 readdirex_dict_arg(argvars, &sort) == FAIL)
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001720 return;
1721
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001722 ret = readdir_core(&ga, path, FALSE, (void *)expr,
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001723 (expr->v_type == VAR_UNKNOWN) ? NULL : readdir_checkitem, sort);
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001724 if (ret == OK)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001725 {
1726 for (i = 0; i < ga.ga_len; i++)
1727 {
1728 p = ((char_u **)ga.ga_data)[i];
1729 list_append_string(rettv->vval.v_list, p, -1);
1730 }
1731 }
1732 ga_clear_strings(&ga);
1733}
1734
1735/*
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001736 * Evaluate "expr" (= "context") for readdirex().
1737 */
1738 static int
1739readdirex_checkitem(void *context, void *item)
1740{
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001741 dict_T *dict = (dict_T*)item;
1742
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001743 return checkitem_common(context, NULL, dict);
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001744}
1745
1746/*
1747 * "readdirex()" function
1748 */
1749 void
1750f_readdirex(typval_T *argvars, typval_T *rettv)
1751{
1752 typval_T *expr;
1753 int ret;
1754 char_u *path;
1755 garray_T ga;
1756 int i;
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01001757 int sort = READDIR_SORT_BYTE;
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001758
1759 if (rettv_list_alloc(rettv) == FAIL)
1760 return;
Yegappan Lakshmanan5bca9062021-07-24 21:33:26 +02001761
1762 if (in_vim9script()
1763 && (check_for_string_arg(argvars, 0) == FAIL
1764 || (argvars[1].v_type != VAR_UNKNOWN
1765 && check_for_opt_dict_arg(argvars, 2) == FAIL)))
1766 return;
1767
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001768 path = tv_get_string(&argvars[0]);
1769 expr = &argvars[1];
1770
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001771 if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN &&
Bram Moolenaard83392a2022-09-01 12:22:46 +01001772 readdirex_dict_arg(argvars, &sort) == FAIL)
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001773 return;
1774
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001775 ret = readdir_core(&ga, path, TRUE, (void *)expr,
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001776 (expr->v_type == VAR_UNKNOWN) ? NULL : readdirex_checkitem, sort);
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001777 if (ret == OK)
1778 {
1779 for (i = 0; i < ga.ga_len; i++)
1780 {
1781 dict_T *dict = ((dict_T**)ga.ga_data)[i];
1782 list_append_dict(rettv->vval.v_list, dict);
1783 dict_unref(dict);
1784 }
1785 }
1786 ga_clear(&ga);
1787}
1788
1789/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001790 * "readfile()" function
1791 */
Bram Moolenaarc423ad72021-01-13 20:38:03 +01001792 static void
1793read_file_or_blob(typval_T *argvars, typval_T *rettv, int always_blob)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001794{
1795 int binary = FALSE;
Bram Moolenaarc423ad72021-01-13 20:38:03 +01001796 int blob = always_blob;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001797 int failed = FALSE;
1798 char_u *fname;
1799 FILE *fd;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001800 char_u buf[(IOSIZE/256)*256]; // rounded to avoid odd + 1
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001801 int io_size = sizeof(buf);
Bram Moolenaar26262f82019-09-04 20:59:15 +02001802 int readlen; // size of last fread()
1803 char_u *prev = NULL; // previously read bytes, if any
1804 long prevlen = 0; // length of data in prev
1805 long prevsize = 0; // size of prev buffer
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001806 long maxline = MAXLNUM;
1807 long cnt = 0;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001808 char_u *p; // position in buf
1809 char_u *start; // start of current line
K.Takata11df3ae2022-10-19 14:02:40 +01001810 off_T offset = 0;
1811 off_T size = -1;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001812
1813 if (argvars[1].v_type != VAR_UNKNOWN)
1814 {
K.Takata11df3ae2022-10-19 14:02:40 +01001815 if (always_blob)
1816 {
1817 offset = (off_T)tv_get_number(&argvars[1]);
1818 if (argvars[2].v_type != VAR_UNKNOWN)
1819 size = (off_T)tv_get_number(&argvars[2]);
1820 }
1821 else
1822 {
1823 if (STRCMP(tv_get_string(&argvars[1]), "b") == 0)
1824 binary = TRUE;
1825 if (STRCMP(tv_get_string(&argvars[1]), "B") == 0)
1826 blob = TRUE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001827
K.Takata11df3ae2022-10-19 14:02:40 +01001828 if (argvars[2].v_type != VAR_UNKNOWN)
1829 maxline = (long)tv_get_number(&argvars[2]);
1830 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001831 }
1832
Bram Moolenaar15352dc2020-04-06 21:12:42 +02001833 if ((blob ? rettv_blob_alloc(rettv) : rettv_list_alloc(rettv)) == FAIL)
1834 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001835
Bram Moolenaar26262f82019-09-04 20:59:15 +02001836 // Always open the file in binary mode, library functions have a mind of
1837 // their own about CR-LF conversion.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001838 fname = tv_get_string(&argvars[0]);
Bram Moolenaar15352dc2020-04-06 21:12:42 +02001839
1840 if (mch_isdir(fname))
1841 {
Bram Moolenaar4dea2d92022-03-31 11:37:57 +01001842 semsg(_(e_str_is_directory), fname);
Bram Moolenaar15352dc2020-04-06 21:12:42 +02001843 return;
1844 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001845 if (*fname == NUL || (fd = mch_fopen((char *)fname, READBIN)) == NULL)
1846 {
K.Takata11df3ae2022-10-19 14:02:40 +01001847 semsg(_(e_cant_open_file_str),
1848 *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001849 return;
1850 }
1851
1852 if (blob)
1853 {
K.Takata11df3ae2022-10-19 14:02:40 +01001854 if (read_blob(fd, rettv, offset, size) == FAIL)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00001855 semsg(_(e_cant_read_file_str), fname);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001856 fclose(fd);
1857 return;
1858 }
1859
1860 while (cnt < maxline || maxline < 0)
1861 {
1862 readlen = (int)fread(buf, 1, io_size, fd);
1863
Bram Moolenaar26262f82019-09-04 20:59:15 +02001864 // This for loop processes what was read, but is also entered at end
1865 // of file so that either:
1866 // - an incomplete line gets written
1867 // - a "binary" file gets an empty line at the end if it ends in a
1868 // newline.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001869 for (p = buf, start = buf;
1870 p < buf + readlen || (readlen <= 0 && (prevlen > 0 || binary));
1871 ++p)
1872 {
Dominique Pellef5d639a2022-01-12 15:24:40 +00001873 if (readlen <= 0 || *p == '\n')
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001874 {
1875 listitem_T *li;
1876 char_u *s = NULL;
1877 long_u len = p - start;
1878
Bram Moolenaar26262f82019-09-04 20:59:15 +02001879 // Finished a line. Remove CRs before NL.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001880 if (readlen > 0 && !binary)
1881 {
1882 while (len > 0 && start[len - 1] == '\r')
1883 --len;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001884 // removal may cross back to the "prev" string
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001885 if (len == 0)
1886 while (prevlen > 0 && prev[prevlen - 1] == '\r')
1887 --prevlen;
1888 }
1889 if (prevlen == 0)
Bram Moolenaar71ccd032020-06-12 22:59:11 +02001890 s = vim_strnsave(start, len);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001891 else
1892 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001893 // Change "prev" buffer to be the right size. This way
1894 // the bytes are only copied once, and very long lines are
1895 // allocated only once.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001896 if ((s = vim_realloc(prev, prevlen + len + 1)) != NULL)
1897 {
1898 mch_memmove(s + prevlen, start, len);
1899 s[prevlen + len] = NUL;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001900 prev = NULL; // the list will own the string
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001901 prevlen = prevsize = 0;
1902 }
1903 }
1904 if (s == NULL)
1905 {
1906 do_outofmem_msg((long_u) prevlen + len + 1);
1907 failed = TRUE;
1908 break;
1909 }
1910
1911 if ((li = listitem_alloc()) == NULL)
1912 {
1913 vim_free(s);
1914 failed = TRUE;
1915 break;
1916 }
1917 li->li_tv.v_type = VAR_STRING;
1918 li->li_tv.v_lock = 0;
1919 li->li_tv.vval.v_string = s;
1920 list_append(rettv->vval.v_list, li);
1921
Bram Moolenaar26262f82019-09-04 20:59:15 +02001922 start = p + 1; // step over newline
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001923 if ((++cnt >= maxline && maxline >= 0) || readlen <= 0)
1924 break;
1925 }
1926 else if (*p == NUL)
1927 *p = '\n';
Bram Moolenaar26262f82019-09-04 20:59:15 +02001928 // Check for utf8 "bom"; U+FEFF is encoded as EF BB BF. Do this
1929 // when finding the BF and check the previous two bytes.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001930 else if (*p == 0xbf && enc_utf8 && !binary)
1931 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001932 // Find the two bytes before the 0xbf. If p is at buf, or buf
1933 // + 1, these may be in the "prev" string.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001934 char_u back1 = p >= buf + 1 ? p[-1]
1935 : prevlen >= 1 ? prev[prevlen - 1] : NUL;
1936 char_u back2 = p >= buf + 2 ? p[-2]
1937 : p == buf + 1 && prevlen >= 1 ? prev[prevlen - 1]
1938 : prevlen >= 2 ? prev[prevlen - 2] : NUL;
1939
1940 if (back2 == 0xef && back1 == 0xbb)
1941 {
1942 char_u *dest = p - 2;
1943
Bram Moolenaar26262f82019-09-04 20:59:15 +02001944 // Usually a BOM is at the beginning of a file, and so at
1945 // the beginning of a line; then we can just step over it.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001946 if (start == dest)
1947 start = p + 1;
1948 else
1949 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001950 // have to shuffle buf to close gap
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001951 int adjust_prevlen = 0;
1952
1953 if (dest < buf)
1954 {
Bram Moolenaarc423ad72021-01-13 20:38:03 +01001955 // must be 1 or 2
1956 adjust_prevlen = (int)(buf - dest);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001957 dest = buf;
1958 }
1959 if (readlen > p - buf + 1)
1960 mch_memmove(dest, p + 1, readlen - (p - buf) - 1);
1961 readlen -= 3 - adjust_prevlen;
1962 prevlen -= adjust_prevlen;
1963 p = dest - 1;
1964 }
1965 }
1966 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02001967 } // for
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001968
1969 if (failed || (cnt >= maxline && maxline >= 0) || readlen <= 0)
1970 break;
1971 if (start < p)
1972 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001973 // There's part of a line in buf, store it in "prev".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001974 if (p - start + prevlen >= prevsize)
1975 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001976 // need bigger "prev" buffer
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001977 char_u *newprev;
1978
Bram Moolenaar26262f82019-09-04 20:59:15 +02001979 // A common use case is ordinary text files and "prev" gets a
1980 // fragment of a line, so the first allocation is made
1981 // small, to avoid repeatedly 'allocing' large and
1982 // 'reallocing' small.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001983 if (prevsize == 0)
1984 prevsize = (long)(p - start);
1985 else
1986 {
1987 long grow50pc = (prevsize * 3) / 2;
1988 long growmin = (long)((p - start) * 2 + prevlen);
1989 prevsize = grow50pc > growmin ? grow50pc : growmin;
1990 }
1991 newprev = vim_realloc(prev, prevsize);
1992 if (newprev == NULL)
1993 {
1994 do_outofmem_msg((long_u)prevsize);
1995 failed = TRUE;
1996 break;
1997 }
1998 prev = newprev;
1999 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02002000 // Add the line part to end of "prev".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002001 mch_memmove(prev + prevlen, start, p - start);
2002 prevlen += (long)(p - start);
2003 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02002004 } // while
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002005
Bram Moolenaar26262f82019-09-04 20:59:15 +02002006 // For a negative line count use only the lines at the end of the file,
2007 // free the rest.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002008 if (!failed && maxline < 0)
2009 while (cnt > -maxline)
2010 {
2011 listitem_remove(rettv->vval.v_list, rettv->vval.v_list->lv_first);
2012 --cnt;
2013 }
2014
2015 if (failed)
2016 {
2017 // an empty list is returned on error
2018 list_free(rettv->vval.v_list);
2019 rettv_list_alloc(rettv);
2020 }
2021
2022 vim_free(prev);
2023 fclose(fd);
2024}
2025
2026/*
Bram Moolenaarc423ad72021-01-13 20:38:03 +01002027 * "readblob()" function
2028 */
2029 void
2030f_readblob(typval_T *argvars, typval_T *rettv)
2031{
K.Takata11df3ae2022-10-19 14:02:40 +01002032 if (in_vim9script()
2033 && (check_for_string_arg(argvars, 0) == FAIL
2034 || check_for_opt_number_arg(argvars, 1) == FAIL
2035 || (argvars[1].v_type != VAR_UNKNOWN
2036 && check_for_opt_number_arg(argvars, 2) == FAIL)))
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02002037 return;
2038
Bram Moolenaarc423ad72021-01-13 20:38:03 +01002039 read_file_or_blob(argvars, rettv, TRUE);
2040}
2041
2042/*
2043 * "readfile()" function
2044 */
2045 void
2046f_readfile(typval_T *argvars, typval_T *rettv)
2047{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02002048 if (in_vim9script()
2049 && (check_for_nonempty_string_arg(argvars, 0) == FAIL
2050 || check_for_opt_string_arg(argvars, 1) == FAIL
2051 || (argvars[1].v_type != VAR_UNKNOWN
2052 && check_for_opt_number_arg(argvars, 2) == FAIL)))
2053 return;
2054
Bram Moolenaarc423ad72021-01-13 20:38:03 +01002055 read_file_or_blob(argvars, rettv, FALSE);
2056}
2057
2058/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002059 * "resolve()" function
2060 */
2061 void
2062f_resolve(typval_T *argvars, typval_T *rettv)
2063{
2064 char_u *p;
2065#ifdef HAVE_READLINK
2066 char_u *buf = NULL;
John Marriotte29c8ba2024-12-13 13:58:53 +01002067 char_u *remain = NULL;
2068 int p_was_allocated = FALSE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002069#endif
2070
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02002071 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
2072 return;
2073
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002074 p = tv_get_string(&argvars[0]);
2075#ifdef FEAT_SHORTCUT
2076 {
2077 char_u *v = NULL;
2078
2079 v = mch_resolve_path(p, TRUE);
2080 if (v != NULL)
2081 rettv->vval.v_string = v;
2082 else
2083 rettv->vval.v_string = vim_strsave(p);
2084 }
2085#else
2086# ifdef HAVE_READLINK
2087 {
John Marriotte29c8ba2024-12-13 13:58:53 +01002088 size_t plen;
2089 size_t buflen;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002090 char_u *cpy;
John Marriotte29c8ba2024-12-13 13:58:53 +01002091 size_t cpysize;
2092 char_u *r = NULL; // points to current position in "remain"
2093 size_t rlen = 0; // length of r (excluding the NUL)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002094 char_u *q;
2095 int is_relative_to_current = FALSE;
2096 int has_trailing_pathsep = FALSE;
2097 int limit = 100;
John Marriotte29c8ba2024-12-13 13:58:53 +01002098 size_t len;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002099
John Marriotte29c8ba2024-12-13 13:58:53 +01002100 rettv->vval.v_string = NULL;
2101
2102 plen = STRLEN(p);
2103 p = vim_strnsave(p, plen);
Bram Moolenaar70188f52019-12-23 18:18:52 +01002104 if (p == NULL)
2105 goto fail;
John Marriotte29c8ba2024-12-13 13:58:53 +01002106
2107 p_was_allocated = TRUE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002108 if (p[0] == '.' && (vim_ispathsep(p[1])
2109 || (p[1] == '.' && (vim_ispathsep(p[2])))))
2110 is_relative_to_current = TRUE;
2111
John Marriotte29c8ba2024-12-13 13:58:53 +01002112 if (plen > 1 && after_pathsep(p, p + plen))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002113 {
2114 has_trailing_pathsep = TRUE;
John Marriotte29c8ba2024-12-13 13:58:53 +01002115 p[--plen] = NUL; // the trailing slash breaks readlink()
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002116 }
2117
2118 q = getnextcomp(p);
2119 if (*q != NUL)
2120 {
John Marriotte29c8ba2024-12-13 13:58:53 +01002121 char_u *q_prev = q - 1;
2122
2123 // getnextcomp() finds the first path separator.
2124 // if there is a run of >1 path separators, set all
2125 // but the last in the run to NUL.
2126 while (*q != NUL && vim_ispathsep(*q))
2127 {
2128 *q_prev = NUL;
2129 q_prev = q;
2130 MB_PTR_ADV(q);
2131 }
2132 q = q_prev;
2133
Bram Moolenaar26262f82019-09-04 20:59:15 +02002134 // Separate the first path component in "p", and keep the
2135 // remainder (beginning with the path separator).
John Marriotte29c8ba2024-12-13 13:58:53 +01002136 rlen = (size_t)(plen - (q - p));
2137 r = remain = vim_strnsave(q, rlen);
2138 if (remain == NULL)
2139 rlen = 0;
2140 *q = NUL;
2141 plen -= rlen;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002142 }
2143
2144 buf = alloc(MAXPATHL + 1);
2145 if (buf == NULL)
2146 goto fail;
2147
2148 for (;;)
2149 {
2150 for (;;)
2151 {
John Marriotte29c8ba2024-12-13 13:58:53 +01002152 ssize_t rv = readlink((char *)p, (char *)buf, MAXPATHL);
2153 if (rv <= 0)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002154 break;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002155
2156 if (limit-- == 0)
2157 {
Bram Moolenaara6f79292022-01-04 21:30:47 +00002158 emsg(_(e_too_many_symbolic_links_cycle));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002159 goto fail;
2160 }
2161
John Marriotte29c8ba2024-12-13 13:58:53 +01002162 buflen = (size_t)rv;
2163 buf[buflen] = NUL;
2164
Bram Moolenaar26262f82019-09-04 20:59:15 +02002165 // Ensure that the result will have a trailing path separator
2166 // if the argument has one.
John Marriotte29c8ba2024-12-13 13:58:53 +01002167 if (remain == NULL && has_trailing_pathsep && !after_pathsep(buf, buf + buflen))
2168 {
2169 STRCPY(buf + buflen, PATHSEPSTR);
2170 ++buflen;
2171 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002172
Bram Moolenaar26262f82019-09-04 20:59:15 +02002173 // Separate the first path component in the link value and
2174 // concatenate the remainders.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002175 q = getnextcomp(vim_ispathsep(*buf) ? buf + 1 : buf);
2176 if (*q != NUL)
2177 {
John Marriotte29c8ba2024-12-13 13:58:53 +01002178 char_u *q_prev = q - 1;
2179
2180 // getnextcomp() finds the first path separator.
2181 // if there is a run of >1 path separators, set all
2182 // but the last in the run to NUL.
2183 while (*q != NUL && vim_ispathsep(*q))
2184 {
2185 *q_prev = NUL;
2186 q_prev = q;
2187 MB_PTR_ADV(q);
2188 }
2189 q = q_prev;
2190
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002191 if (remain == NULL)
John Marriotte29c8ba2024-12-13 13:58:53 +01002192 {
2193 rlen = (size_t)(buflen - (q - buf));
2194 r = remain = vim_strnsave(q, rlen);
2195 if (remain == NULL)
2196 rlen = 0;
2197 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002198 else
2199 {
John Marriotte29c8ba2024-12-13 13:58:53 +01002200 len = (size_t)(buflen - (q - buf));
2201 cpysize = (size_t)(len + rlen + 1); // +1 for NUL
2202 cpy = alloc(plen + buflen + 1);
2203 if (cpy == NULL)
2204 goto fail;
2205
2206 rlen = (size_t)vim_snprintf((char *)cpy, cpysize, "%.*s%s", (int)len, q, r);
2207 vim_free(remain);
2208 r = remain = cpy;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002209 }
John Marriotte29c8ba2024-12-13 13:58:53 +01002210 *q = NUL;
2211 buflen = (size_t)(q - buf);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002212 }
2213
2214 q = gettail(p);
2215 if (q > p && *q == NUL)
2216 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002217 // Ignore trailing path separator.
John Marriotte29c8ba2024-12-13 13:58:53 +01002218 plen = (size_t)(q - p - 1);
2219 p[plen] = NUL;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002220 q = gettail(p);
2221 }
2222 if (q > p && !mch_isFullName(buf))
2223 {
John Marriotte29c8ba2024-12-13 13:58:53 +01002224 char_u *tail;
2225
Bram Moolenaar26262f82019-09-04 20:59:15 +02002226 // symlink is relative to directory of argument
John Marriotte29c8ba2024-12-13 13:58:53 +01002227 cpy = alloc(plen + buflen + 1);
2228 if (cpy == NULL)
2229 goto fail;
2230
2231 STRCPY(cpy, p);
2232 tail = gettail(cpy);
2233 if (*tail != NUL)
2234 plen -= (size_t)(plen - (tail - cpy)); // remove portion that will be replaced
2235 STRCPY(tail, buf);
2236 vim_free(p);
2237 p = cpy;
2238 plen += buflen;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002239 }
2240 else
2241 {
2242 vim_free(p);
John Marriotte29c8ba2024-12-13 13:58:53 +01002243 p = vim_strnsave(buf, buflen);
2244 if (p == NULL)
2245 goto fail;
2246
2247 plen = buflen;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002248 }
2249 }
2250
2251 if (remain == NULL)
2252 break;
2253
Bram Moolenaar26262f82019-09-04 20:59:15 +02002254 // Append the first path component of "remain" to "p".
John Marriotte29c8ba2024-12-13 13:58:53 +01002255 q = getnextcomp(r + 1);
2256 len = (size_t)(q - r);
2257 cpysize = (size_t)(plen + len + 1); // +1 for NUL
2258 cpy = alloc(cpysize);
2259 if (cpy == NULL)
2260 goto fail;
2261
2262 plen = (size_t)vim_snprintf((char *)cpy, cpysize, "%s%.*s", p, (int)len, r);
2263 vim_free(p);
2264 p = cpy;
2265
Bram Moolenaar26262f82019-09-04 20:59:15 +02002266 // Shorten "remain".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002267 if (*q != NUL)
John Marriotte29c8ba2024-12-13 13:58:53 +01002268 {
2269 r += len;
2270 rlen -= len;
2271 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002272 else
John Marriotte29c8ba2024-12-13 13:58:53 +01002273 {
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002274 VIM_CLEAR(remain);
John Marriotte29c8ba2024-12-13 13:58:53 +01002275 r = NULL;
2276 rlen = 0;
2277 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002278 }
2279
Bram Moolenaar26262f82019-09-04 20:59:15 +02002280 // If the result is a relative path name, make it explicitly relative to
2281 // the current directory if and only if the argument had this form.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002282 if (!vim_ispathsep(*p))
2283 {
2284 if (is_relative_to_current
2285 && *p != NUL
2286 && !(p[0] == '.'
2287 && (p[1] == NUL
2288 || vim_ispathsep(p[1])
2289 || (p[1] == '.'
2290 && (p[2] == NUL
2291 || vim_ispathsep(p[2]))))))
2292 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002293 // Prepend "./".
John Marriotte29c8ba2024-12-13 13:58:53 +01002294 cpysize = plen + 3; // +2 for "./" and +1 for NUL
2295 cpy = alloc(cpysize);
2296 if (cpy == NULL)
2297 goto fail;
2298
2299 plen = (size_t)vim_snprintf((char *)cpy, cpysize, "./%s", p);
2300 vim_free(p);
2301 p = cpy;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002302 }
2303 else if (!is_relative_to_current)
2304 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002305 // Strip leading "./".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002306 q = p;
2307 while (q[0] == '.' && vim_ispathsep(q[1]))
2308 q += 2;
2309 if (q > p)
John Marriotte29c8ba2024-12-13 13:58:53 +01002310 {
2311 mch_memmove(p, p + 2, (plen - 2) + 1);
2312 plen -= 2;
2313 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002314 }
2315 }
2316
Bram Moolenaar26262f82019-09-04 20:59:15 +02002317 // Ensure that the result will have no trailing path separator
2318 // if the argument had none. But keep "/" or "//".
John Marriotte29c8ba2024-12-13 13:58:53 +01002319 if (!has_trailing_pathsep && after_pathsep(p, p + plen))
2320 *gettail_sep(p) = NUL;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002321
2322 rettv->vval.v_string = p;
2323 }
2324# else
2325 rettv->vval.v_string = vim_strsave(p);
2326# endif
2327#endif
2328
2329 simplify_filename(rettv->vval.v_string);
2330
2331#ifdef HAVE_READLINK
2332fail:
John Marriotte29c8ba2024-12-13 13:58:53 +01002333 if (rettv->vval.v_string == NULL && p_was_allocated)
2334 vim_free(p);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002335 vim_free(buf);
John Marriotte29c8ba2024-12-13 13:58:53 +01002336 vim_free(remain);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002337#endif
2338 rettv->v_type = VAR_STRING;
2339}
2340
2341/*
2342 * "tempname()" function
2343 */
2344 void
2345f_tempname(typval_T *argvars UNUSED, typval_T *rettv)
2346{
2347 static int x = 'A';
2348
2349 rettv->v_type = VAR_STRING;
2350 rettv->vval.v_string = vim_tempname(x, FALSE);
2351
Bram Moolenaar26262f82019-09-04 20:59:15 +02002352 // Advance 'x' to use A-Z and 0-9, so that there are at least 34 different
2353 // names. Skip 'I' and 'O', they are used for shell redirection.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002354 do
2355 {
2356 if (x == 'Z')
2357 x = '0';
2358 else if (x == '9')
2359 x = 'A';
2360 else
Bram Moolenaar424bcae2022-01-31 14:59:41 +00002361 ++x;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002362 } while (x == 'I' || x == 'O');
2363}
2364
2365/*
2366 * "writefile()" function
2367 */
2368 void
2369f_writefile(typval_T *argvars, typval_T *rettv)
2370{
2371 int binary = FALSE;
2372 int append = FALSE;
Bram Moolenaar806a2732022-09-04 15:40:36 +01002373 int defer = FALSE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002374#ifdef HAVE_FSYNC
2375 int do_fsync = p_fs;
2376#endif
2377 char_u *fname;
2378 FILE *fd;
2379 int ret = 0;
2380 listitem_T *li;
2381 list_T *list = NULL;
2382 blob_T *blob = NULL;
2383
2384 rettv->vval.v_number = -1;
2385 if (check_secure())
2386 return;
2387
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02002388 if (in_vim9script()
2389 && (check_for_list_or_blob_arg(argvars, 0) == FAIL
2390 || check_for_string_arg(argvars, 1) == FAIL
2391 || check_for_opt_string_arg(argvars, 2) == FAIL))
2392 return;
2393
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002394 if (argvars[0].v_type == VAR_LIST)
2395 {
2396 list = argvars[0].vval.v_list;
2397 if (list == NULL)
2398 return;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02002399 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002400 FOR_ALL_LIST_ITEMS(list, li)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002401 if (tv_get_string_chk(&li->li_tv) == NULL)
2402 return;
2403 }
2404 else if (argvars[0].v_type == VAR_BLOB)
2405 {
2406 blob = argvars[0].vval.v_blob;
2407 if (blob == NULL)
2408 return;
2409 }
2410 else
2411 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00002412 semsg(_(e_invalid_argument_str),
Bram Moolenaar18a2b872020-03-19 13:08:45 +01002413 _("writefile() first argument must be a List or a Blob"));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002414 return;
2415 }
2416
2417 if (argvars[2].v_type != VAR_UNKNOWN)
2418 {
2419 char_u *arg2 = tv_get_string_chk(&argvars[2]);
2420
2421 if (arg2 == NULL)
2422 return;
2423 if (vim_strchr(arg2, 'b') != NULL)
2424 binary = TRUE;
2425 if (vim_strchr(arg2, 'a') != NULL)
2426 append = TRUE;
Bram Moolenaar806a2732022-09-04 15:40:36 +01002427 if (vim_strchr(arg2, 'D') != NULL)
2428 defer = TRUE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002429#ifdef HAVE_FSYNC
2430 if (vim_strchr(arg2, 's') != NULL)
2431 do_fsync = TRUE;
2432 else if (vim_strchr(arg2, 'S') != NULL)
2433 do_fsync = FALSE;
2434#endif
2435 }
2436
2437 fname = tv_get_string_chk(&argvars[1]);
2438 if (fname == NULL)
2439 return;
2440
Bram Moolenaar6f14da12022-09-07 21:30:44 +01002441 if (defer && !can_add_defer())
Bram Moolenaar806a2732022-09-04 15:40:36 +01002442 return;
Bram Moolenaar806a2732022-09-04 15:40:36 +01002443
Bram Moolenaar26262f82019-09-04 20:59:15 +02002444 // Always open the file in binary mode, library functions have a mind of
2445 // their own about CR-LF conversion.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002446 if (*fname == NUL || (fd = mch_fopen((char *)fname,
2447 append ? APPENDBIN : WRITEBIN)) == NULL)
2448 {
Bram Moolenaar806a2732022-09-04 15:40:36 +01002449 semsg(_(e_cant_create_file_str),
2450 *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002451 ret = -1;
2452 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002453 else
2454 {
Bram Moolenaar806a2732022-09-04 15:40:36 +01002455 if (defer)
2456 {
2457 typval_T tv;
2458
2459 tv.v_type = VAR_STRING;
2460 tv.v_lock = 0;
Bram Moolenaar6f14da12022-09-07 21:30:44 +01002461 tv.vval.v_string = FullName_save(fname, FALSE);
Bram Moolenaar806a2732022-09-04 15:40:36 +01002462 if (tv.vval.v_string == NULL
2463 || add_defer((char_u *)"delete", 1, &tv) == FAIL)
2464 {
2465 ret = -1;
2466 fclose(fd);
2467 (void)mch_remove(fname);
2468 }
2469 }
2470
2471 if (ret == 0)
2472 {
2473 if (blob)
2474 {
2475 if (write_blob(fd, blob) == FAIL)
2476 ret = -1;
2477 }
2478 else
2479 {
2480 if (write_list(fd, list, binary) == FAIL)
2481 ret = -1;
2482 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002483#ifdef HAVE_FSYNC
Bram Moolenaar806a2732022-09-04 15:40:36 +01002484 if (ret == 0 && do_fsync)
2485 // Ignore the error, the user wouldn't know what to do about
2486 // it. May happen for a device.
2487 vim_ignored = vim_fsync(fileno(fd));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002488#endif
Bram Moolenaar806a2732022-09-04 15:40:36 +01002489 fclose(fd);
2490 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002491 }
2492
2493 rettv->vval.v_number = ret;
2494}
2495
2496#endif // FEAT_EVAL
2497
2498#if defined(FEAT_BROWSE) || defined(PROTO)
2499/*
2500 * Generic browse function. Calls gui_mch_browse() when possible.
2501 * Later this may pop-up a non-GUI file selector (external command?).
2502 */
2503 char_u *
2504do_browse(
Bram Moolenaar26262f82019-09-04 20:59:15 +02002505 int flags, // BROWSE_SAVE and BROWSE_DIR
2506 char_u *title, // title for the window
2507 char_u *dflt, // default file name (may include directory)
2508 char_u *ext, // extension added
2509 char_u *initdir, // initial directory, NULL for current dir or
2510 // when using path from "dflt"
2511 char_u *filter, // file name filter
2512 buf_T *buf) // buffer to read/write for
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002513{
2514 char_u *fname;
Bram Moolenaar26262f82019-09-04 20:59:15 +02002515 static char_u *last_dir = NULL; // last used directory
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002516 char_u *tofree = NULL;
Bram Moolenaare1004402020-10-24 20:49:43 +02002517 int save_cmod_flags = cmdmod.cmod_flags;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002518
Bram Moolenaar26262f82019-09-04 20:59:15 +02002519 // Must turn off browse to avoid that autocommands will get the
2520 // flag too!
Bram Moolenaare1004402020-10-24 20:49:43 +02002521 cmdmod.cmod_flags &= ~CMOD_BROWSE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002522
2523 if (title == NULL || *title == NUL)
2524 {
2525 if (flags & BROWSE_DIR)
2526 title = (char_u *)_("Select Directory dialog");
2527 else if (flags & BROWSE_SAVE)
2528 title = (char_u *)_("Save File dialog");
2529 else
2530 title = (char_u *)_("Open File dialog");
2531 }
2532
Bram Moolenaar26262f82019-09-04 20:59:15 +02002533 // When no directory specified, use default file name, default dir, buffer
2534 // dir, last dir or current dir
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002535 if ((initdir == NULL || *initdir == NUL) && dflt != NULL && *dflt != NUL)
2536 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002537 if (mch_isdir(dflt)) // default file name is a directory
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002538 {
2539 initdir = dflt;
2540 dflt = NULL;
2541 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02002542 else if (gettail(dflt) != dflt) // default file name includes a path
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002543 {
2544 tofree = vim_strsave(dflt);
2545 if (tofree != NULL)
2546 {
2547 initdir = tofree;
2548 *gettail(initdir) = NUL;
2549 dflt = gettail(dflt);
2550 }
2551 }
2552 }
2553
2554 if (initdir == NULL || *initdir == NUL)
2555 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002556 // When 'browsedir' is a directory, use it
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002557 if (STRCMP(p_bsdir, "last") != 0
2558 && STRCMP(p_bsdir, "buffer") != 0
2559 && STRCMP(p_bsdir, "current") != 0
2560 && mch_isdir(p_bsdir))
2561 initdir = p_bsdir;
Bram Moolenaar26262f82019-09-04 20:59:15 +02002562 // When saving or 'browsedir' is "buffer", use buffer fname
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002563 else if (((flags & BROWSE_SAVE) || *p_bsdir == 'b')
2564 && buf != NULL && buf->b_ffname != NULL)
2565 {
2566 if (dflt == NULL || *dflt == NUL)
2567 dflt = gettail(curbuf->b_ffname);
2568 tofree = vim_strsave(curbuf->b_ffname);
2569 if (tofree != NULL)
2570 {
2571 initdir = tofree;
2572 *gettail(initdir) = NUL;
2573 }
2574 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02002575 // When 'browsedir' is "last", use dir from last browse
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002576 else if (*p_bsdir == 'l')
2577 initdir = last_dir;
Bram Moolenaar26262f82019-09-04 20:59:15 +02002578 // When 'browsedir is "current", use current directory. This is the
2579 // default already, leave initdir empty.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002580 }
2581
2582# ifdef FEAT_GUI
Bram Moolenaar26262f82019-09-04 20:59:15 +02002583 if (gui.in_use) // when this changes, also adjust f_has()!
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002584 {
2585 if (filter == NULL
2586# ifdef FEAT_EVAL
2587 && (filter = get_var_value((char_u *)"b:browsefilter")) == NULL
2588 && (filter = get_var_value((char_u *)"g:browsefilter")) == NULL
2589# endif
2590 )
2591 filter = BROWSE_FILTER_DEFAULT;
2592 if (flags & BROWSE_DIR)
2593 {
2594# if defined(FEAT_GUI_GTK) || defined(MSWIN)
Bram Moolenaar26262f82019-09-04 20:59:15 +02002595 // For systems that have a directory dialog.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002596 fname = gui_mch_browsedir(title, initdir);
2597# else
Bram Moolenaar26262f82019-09-04 20:59:15 +02002598 // Generic solution for selecting a directory: select a file and
2599 // remove the file name.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002600 fname = gui_mch_browse(0, title, dflt, ext, initdir, (char_u *)"");
2601# endif
2602# if !defined(FEAT_GUI_GTK)
Bram Moolenaar26262f82019-09-04 20:59:15 +02002603 // Win32 adds a dummy file name, others return an arbitrary file
2604 // name. GTK+ 2 returns only the directory,
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002605 if (fname != NULL && *fname != NUL && !mch_isdir(fname))
2606 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002607 // Remove the file name.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002608 char_u *tail = gettail_sep(fname);
2609
2610 if (tail == fname)
Bram Moolenaar26262f82019-09-04 20:59:15 +02002611 *tail++ = '.'; // use current dir
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002612 *tail = NUL;
2613 }
2614# endif
2615 }
2616 else
2617 fname = gui_mch_browse(flags & BROWSE_SAVE,
2618 title, dflt, ext, initdir, (char_u *)_(filter));
2619
Bram Moolenaar26262f82019-09-04 20:59:15 +02002620 // We hang around in the dialog for a while, the user might do some
2621 // things to our files. The Win32 dialog allows deleting or renaming
2622 // a file, check timestamps.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002623 need_check_timestamps = TRUE;
2624 did_check_timestamps = FALSE;
2625 }
2626 else
2627# endif
2628 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002629 // TODO: non-GUI file selector here
Bram Moolenaareaaac012022-01-02 17:00:40 +00002630 emsg(_(e_sorry_no_file_browser_in_console_mode));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002631 fname = NULL;
2632 }
2633
Bram Moolenaar26262f82019-09-04 20:59:15 +02002634 // keep the directory for next time
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002635 if (fname != NULL)
2636 {
2637 vim_free(last_dir);
2638 last_dir = vim_strsave(fname);
2639 if (last_dir != NULL && !(flags & BROWSE_DIR))
2640 {
2641 *gettail(last_dir) = NUL;
2642 if (*last_dir == NUL)
2643 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002644 // filename only returned, must be in current dir
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002645 vim_free(last_dir);
2646 last_dir = alloc(MAXPATHL);
2647 if (last_dir != NULL)
2648 mch_dirname(last_dir, MAXPATHL);
2649 }
2650 }
2651 }
2652
2653 vim_free(tofree);
Bram Moolenaare1004402020-10-24 20:49:43 +02002654 cmdmod.cmod_flags = save_cmod_flags;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002655
2656 return fname;
2657}
2658#endif
2659
2660#if defined(FEAT_EVAL) || defined(PROTO)
2661
2662/*
2663 * "browse(save, title, initdir, default)" function
2664 */
2665 void
2666f_browse(typval_T *argvars UNUSED, typval_T *rettv)
2667{
2668# ifdef FEAT_BROWSE
2669 int save;
2670 char_u *title;
2671 char_u *initdir;
2672 char_u *defname;
2673 char_u buf[NUMBUFLEN];
2674 char_u buf2[NUMBUFLEN];
2675 int error = FALSE;
2676
Bram Moolenaarf28f2ac2021-03-22 22:21:26 +01002677 if (in_vim9script()
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02002678 && (check_for_bool_arg(argvars, 0) == FAIL
2679 || check_for_string_arg(argvars, 1) == FAIL
Bram Moolenaar32105ae2021-03-27 18:59:25 +01002680 || check_for_string_arg(argvars, 2) == FAIL
2681 || check_for_string_arg(argvars, 3) == FAIL))
Bram Moolenaarf28f2ac2021-03-22 22:21:26 +01002682 return;
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02002683
Bram Moolenaar5a049842022-10-08 12:52:09 +01002684 save = (int)tv_get_bool_chk(&argvars[0], &error);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002685 title = tv_get_string_chk(&argvars[1]);
2686 initdir = tv_get_string_buf_chk(&argvars[2], buf);
2687 defname = tv_get_string_buf_chk(&argvars[3], buf2);
2688
2689 if (error || title == NULL || initdir == NULL || defname == NULL)
2690 rettv->vval.v_string = NULL;
2691 else
2692 rettv->vval.v_string =
2693 do_browse(save ? BROWSE_SAVE : 0,
2694 title, defname, NULL, initdir, NULL, curbuf);
2695# else
2696 rettv->vval.v_string = NULL;
2697# endif
2698 rettv->v_type = VAR_STRING;
2699}
2700
2701/*
2702 * "browsedir(title, initdir)" function
2703 */
2704 void
2705f_browsedir(typval_T *argvars UNUSED, typval_T *rettv)
2706{
2707# ifdef FEAT_BROWSE
2708 char_u *title;
2709 char_u *initdir;
2710 char_u buf[NUMBUFLEN];
2711
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02002712 if (in_vim9script()
2713 && (check_for_string_arg(argvars, 0) == FAIL
2714 || check_for_string_arg(argvars, 1) == FAIL))
2715 return;
2716
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002717 title = tv_get_string_chk(&argvars[0]);
2718 initdir = tv_get_string_buf_chk(&argvars[1], buf);
2719
2720 if (title == NULL || initdir == NULL)
2721 rettv->vval.v_string = NULL;
2722 else
2723 rettv->vval.v_string = do_browse(BROWSE_DIR,
2724 title, NULL, NULL, initdir, NULL, curbuf);
2725# else
2726 rettv->vval.v_string = NULL;
2727# endif
2728 rettv->v_type = VAR_STRING;
2729}
2730
Shougo Matsushita60c87432024-06-03 22:59:27 +02002731/*
2732 * "filecopy()" function
2733 */
2734 void
2735f_filecopy(typval_T *argvars, typval_T *rettv)
2736{
2737 char_u *from;
2738 stat_T st;
2739
2740 rettv->vval.v_number = FALSE;
2741
2742 if (check_restricted() || check_secure()
2743 || check_for_string_arg(argvars, 0) == FAIL
2744 || check_for_string_arg(argvars, 1) == FAIL)
2745 return;
2746
2747 from = tv_get_string(&argvars[0]);
2748
2749 if (mch_lstat((char *)from, &st) >= 0
2750 && (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)))
2751 rettv->vval.v_number = vim_copyfile(
2752 tv_get_string(&argvars[0]),
2753 tv_get_string(&argvars[1])) == OK ? TRUE : FALSE;
2754}
2755
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002756#endif // FEAT_EVAL
Bram Moolenaar26262f82019-09-04 20:59:15 +02002757
2758/*
2759 * Replace home directory by "~" in each space or comma separated file name in
2760 * 'src'.
2761 * If anything fails (except when out of space) dst equals src.
2762 */
2763 void
2764home_replace(
2765 buf_T *buf, // when not NULL, check for help files
2766 char_u *src, // input file name
2767 char_u *dst, // where to put the result
2768 int dstlen, // maximum length of the result
2769 int one) // if TRUE, only replace one file name, include
2770 // spaces and commas in the file name.
2771{
2772 size_t dirlen = 0, envlen = 0;
2773 size_t len;
2774 char_u *homedir_env, *homedir_env_orig;
2775 char_u *p;
2776
2777 if (src == NULL)
2778 {
2779 *dst = NUL;
2780 return;
2781 }
2782
2783 /*
2784 * If the file is a help file, remove the path completely.
2785 */
2786 if (buf != NULL && buf->b_help)
2787 {
2788 vim_snprintf((char *)dst, dstlen, "%s", gettail(src));
2789 return;
2790 }
2791
2792 /*
2793 * We check both the value of the $HOME environment variable and the
2794 * "real" home directory.
2795 */
2796 if (homedir != NULL)
2797 dirlen = STRLEN(homedir);
2798
2799#ifdef VMS
2800 homedir_env_orig = homedir_env = mch_getenv((char_u *)"SYS$LOGIN");
2801#else
2802 homedir_env_orig = homedir_env = mch_getenv((char_u *)"HOME");
2803#endif
2804#ifdef MSWIN
2805 if (homedir_env == NULL)
2806 homedir_env_orig = homedir_env = mch_getenv((char_u *)"USERPROFILE");
2807#endif
2808 // Empty is the same as not set.
2809 if (homedir_env != NULL && *homedir_env == NUL)
2810 homedir_env = NULL;
2811
2812 if (homedir_env != NULL && *homedir_env == '~')
2813 {
Mike Williams51024bb2024-05-30 07:46:30 +02002814 size_t usedlen = 0;
Bram Moolenaar26262f82019-09-04 20:59:15 +02002815 int flen;
2816 char_u *fbuf = NULL;
2817
2818 flen = (int)STRLEN(homedir_env);
2819 (void)modify_fname((char_u *)":p", FALSE, &usedlen,
2820 &homedir_env, &fbuf, &flen);
2821 flen = (int)STRLEN(homedir_env);
2822 if (flen > 0 && vim_ispathsep(homedir_env[flen - 1]))
2823 // Remove the trailing / that is added to a directory.
2824 homedir_env[flen - 1] = NUL;
2825 }
2826
2827 if (homedir_env != NULL)
2828 envlen = STRLEN(homedir_env);
2829
2830 if (!one)
2831 src = skipwhite(src);
2832 while (*src && dstlen > 0)
2833 {
2834 /*
2835 * Here we are at the beginning of a file name.
2836 * First, check to see if the beginning of the file name matches
2837 * $HOME or the "real" home directory. Check that there is a '/'
2838 * after the match (so that if e.g. the file is "/home/pieter/bla",
2839 * and the home directory is "/home/piet", the file does not end up
2840 * as "~er/bla" (which would seem to indicate the file "bla" in user
2841 * er's home directory)).
2842 */
2843 p = homedir;
2844 len = dirlen;
2845 for (;;)
2846 {
2847 if ( len
2848 && fnamencmp(src, p, len) == 0
2849 && (vim_ispathsep(src[len])
2850 || (!one && (src[len] == ',' || src[len] == ' '))
2851 || src[len] == NUL))
2852 {
2853 src += len;
2854 if (--dstlen > 0)
2855 *dst++ = '~';
2856
Bram Moolenaar0e390f42020-06-10 13:12:28 +02002857 // Do not add directory separator into dst, because dst is
2858 // expected to just return the directory name without the
2859 // directory separator '/'.
Bram Moolenaar26262f82019-09-04 20:59:15 +02002860 break;
2861 }
2862 if (p == homedir_env)
2863 break;
2864 p = homedir_env;
2865 len = envlen;
2866 }
2867
2868 // if (!one) skip to separator: space or comma
2869 while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0)
2870 *dst++ = *src++;
2871 // skip separator
2872 while ((*src == ' ' || *src == ',') && --dstlen > 0)
2873 *dst++ = *src++;
2874 }
2875 // if (dstlen == 0) out of space, what to do???
2876
2877 *dst = NUL;
2878
2879 if (homedir_env != homedir_env_orig)
2880 vim_free(homedir_env);
2881}
2882
2883/*
2884 * Like home_replace, store the replaced string in allocated memory.
2885 * When something fails, NULL is returned.
2886 */
2887 char_u *
2888home_replace_save(
2889 buf_T *buf, // when not NULL, check for help files
2890 char_u *src) // input file name
2891{
2892 char_u *dst;
2893 unsigned len;
2894
2895 len = 3; // space for "~/" and trailing NUL
2896 if (src != NULL) // just in case
2897 len += (unsigned)STRLEN(src);
2898 dst = alloc(len);
2899 if (dst != NULL)
2900 home_replace(buf, src, dst, len, TRUE);
2901 return dst;
2902}
2903
2904/*
2905 * Compare two file names and return:
2906 * FPC_SAME if they both exist and are the same file.
2907 * FPC_SAMEX if they both don't exist and have the same file name.
2908 * FPC_DIFF if they both exist and are different files.
2909 * FPC_NOTX if they both don't exist.
2910 * FPC_DIFFX if one of them doesn't exist.
2911 * For the first name environment variables are expanded if "expandenv" is
2912 * TRUE.
2913 */
2914 int
2915fullpathcmp(
2916 char_u *s1,
2917 char_u *s2,
2918 int checkname, // when both don't exist, check file names
2919 int expandenv)
2920{
2921#ifdef UNIX
2922 char_u exp1[MAXPATHL];
2923 char_u full1[MAXPATHL];
2924 char_u full2[MAXPATHL];
2925 stat_T st1, st2;
2926 int r1, r2;
2927
2928 if (expandenv)
2929 expand_env(s1, exp1, MAXPATHL);
2930 else
2931 vim_strncpy(exp1, s1, MAXPATHL - 1);
2932 r1 = mch_stat((char *)exp1, &st1);
2933 r2 = mch_stat((char *)s2, &st2);
2934 if (r1 != 0 && r2 != 0)
2935 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002936 // if mch_stat() doesn't work, may compare the names
Bram Moolenaar26262f82019-09-04 20:59:15 +02002937 if (checkname)
2938 {
2939 if (fnamecmp(exp1, s2) == 0)
2940 return FPC_SAMEX;
2941 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
2942 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
2943 if (r1 == OK && r2 == OK && fnamecmp(full1, full2) == 0)
2944 return FPC_SAMEX;
2945 }
2946 return FPC_NOTX;
2947 }
2948 if (r1 != 0 || r2 != 0)
2949 return FPC_DIFFX;
2950 if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
2951 return FPC_SAME;
2952 return FPC_DIFF;
2953#else
2954 char_u *exp1; // expanded s1
2955 char_u *full1; // full path of s1
2956 char_u *full2; // full path of s2
2957 int retval = FPC_DIFF;
2958 int r1, r2;
2959
2960 // allocate one buffer to store three paths (alloc()/free() is slow!)
2961 if ((exp1 = alloc(MAXPATHL * 3)) != NULL)
2962 {
2963 full1 = exp1 + MAXPATHL;
2964 full2 = full1 + MAXPATHL;
2965
2966 if (expandenv)
2967 expand_env(s1, exp1, MAXPATHL);
2968 else
2969 vim_strncpy(exp1, s1, MAXPATHL - 1);
2970 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
2971 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
2972
2973 // If vim_FullName() fails, the file probably doesn't exist.
2974 if (r1 != OK && r2 != OK)
2975 {
2976 if (checkname && fnamecmp(exp1, s2) == 0)
2977 retval = FPC_SAMEX;
2978 else
2979 retval = FPC_NOTX;
2980 }
2981 else if (r1 != OK || r2 != OK)
2982 retval = FPC_DIFFX;
2983 else if (fnamecmp(full1, full2))
2984 retval = FPC_DIFF;
2985 else
2986 retval = FPC_SAME;
2987 vim_free(exp1);
2988 }
2989 return retval;
2990#endif
2991}
2992
2993/*
2994 * Get the tail of a path: the file name.
2995 * When the path ends in a path separator the tail is the NUL after it.
2996 * Fail safe: never returns NULL.
2997 */
2998 char_u *
2999gettail(char_u *fname)
3000{
3001 char_u *p1, *p2;
3002
3003 if (fname == NULL)
3004 return (char_u *)"";
3005 for (p1 = p2 = get_past_head(fname); *p2; ) // find last part of path
3006 {
3007 if (vim_ispathsep_nocolon(*p2))
3008 p1 = p2 + 1;
3009 MB_PTR_ADV(p2);
3010 }
3011 return p1;
3012}
3013
3014/*
3015 * Get pointer to tail of "fname", including path separators. Putting a NUL
3016 * here leaves the directory name. Takes care of "c:/" and "//".
3017 * Always returns a valid pointer.
3018 */
3019 char_u *
3020gettail_sep(char_u *fname)
3021{
3022 char_u *p;
3023 char_u *t;
3024
3025 p = get_past_head(fname); // don't remove the '/' from "c:/file"
3026 t = gettail(fname);
3027 while (t > p && after_pathsep(fname, t))
3028 --t;
3029#ifdef VMS
3030 // path separator is part of the path
3031 ++t;
3032#endif
3033 return t;
3034}
3035
3036/*
3037 * get the next path component (just after the next path separator).
3038 */
3039 char_u *
3040getnextcomp(char_u *fname)
3041{
3042 while (*fname && !vim_ispathsep(*fname))
3043 MB_PTR_ADV(fname);
John Marriotte29c8ba2024-12-13 13:58:53 +01003044
Bram Moolenaar26262f82019-09-04 20:59:15 +02003045 if (*fname)
3046 ++fname;
3047 return fname;
3048}
3049
3050/*
3051 * Get a pointer to one character past the head of a path name.
3052 * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
3053 * If there is no head, path is returned.
3054 */
3055 char_u *
3056get_past_head(char_u *path)
3057{
3058 char_u *retval;
3059
3060#if defined(MSWIN)
3061 // may skip "c:"
Keith Thompson184f71c2024-01-04 21:19:04 +01003062 if (SAFE_isalpha(path[0]) && path[1] == ':')
Bram Moolenaar26262f82019-09-04 20:59:15 +02003063 retval = path + 2;
3064 else
3065 retval = path;
3066#else
3067# if defined(AMIGA)
3068 // may skip "label:"
3069 retval = vim_strchr(path, ':');
3070 if (retval == NULL)
3071 retval = path;
3072# else // Unix
3073 retval = path;
3074# endif
3075#endif
3076
3077 while (vim_ispathsep(*retval))
3078 ++retval;
3079
3080 return retval;
3081}
3082
3083/*
3084 * Return TRUE if 'c' is a path separator.
3085 * Note that for MS-Windows this includes the colon.
3086 */
3087 int
3088vim_ispathsep(int c)
3089{
3090#ifdef UNIX
3091 return (c == '/'); // UNIX has ':' inside file names
3092#else
3093# ifdef BACKSLASH_IN_FILENAME
3094 return (c == ':' || c == '/' || c == '\\');
3095# else
3096# ifdef VMS
3097 // server"user passwd"::device:[full.path.name]fname.extension;version"
3098 return (c == ':' || c == '[' || c == ']' || c == '/'
3099 || c == '<' || c == '>' || c == '"' );
3100# else
3101 return (c == ':' || c == '/');
3102# endif // VMS
3103# endif
3104#endif
3105}
3106
3107/*
3108 * Like vim_ispathsep(c), but exclude the colon for MS-Windows.
3109 */
3110 int
3111vim_ispathsep_nocolon(int c)
3112{
3113 return vim_ispathsep(c)
3114#ifdef BACKSLASH_IN_FILENAME
3115 && c != ':'
3116#endif
3117 ;
3118}
3119
3120/*
Bram Moolenaar26262f82019-09-04 20:59:15 +02003121 * Return TRUE if the directory of "fname" exists, FALSE otherwise.
3122 * Also returns TRUE if there is no directory name.
3123 * "fname" must be writable!.
3124 */
3125 int
3126dir_of_file_exists(char_u *fname)
3127{
3128 char_u *p;
3129 int c;
3130 int retval;
3131
3132 p = gettail_sep(fname);
3133 if (p == fname)
3134 return TRUE;
3135 c = *p;
3136 *p = NUL;
3137 retval = mch_isdir(fname);
3138 *p = c;
3139 return retval;
3140}
3141
3142/*
3143 * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally
3144 * and deal with 'fileignorecase'.
3145 */
3146 int
3147vim_fnamecmp(char_u *x, char_u *y)
3148{
3149#ifdef BACKSLASH_IN_FILENAME
3150 return vim_fnamencmp(x, y, MAXPATHL);
3151#else
3152 if (p_fic)
3153 return MB_STRICMP(x, y);
3154 return STRCMP(x, y);
3155#endif
3156}
3157
3158 int
3159vim_fnamencmp(char_u *x, char_u *y, size_t len)
3160{
3161#ifdef BACKSLASH_IN_FILENAME
3162 char_u *px = x;
3163 char_u *py = y;
3164 int cx = NUL;
3165 int cy = NUL;
3166
3167 while (len > 0)
3168 {
3169 cx = PTR2CHAR(px);
3170 cy = PTR2CHAR(py);
3171 if (cx == NUL || cy == NUL
3172 || ((p_fic ? MB_TOLOWER(cx) != MB_TOLOWER(cy) : cx != cy)
3173 && !(cx == '/' && cy == '\\')
3174 && !(cx == '\\' && cy == '/')))
3175 break;
Bram Moolenaar1614a142019-10-06 22:00:13 +02003176 len -= mb_ptr2len(px);
3177 px += mb_ptr2len(px);
3178 py += mb_ptr2len(py);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003179 }
3180 if (len == 0)
3181 return 0;
3182 return (cx - cy);
3183#else
3184 if (p_fic)
3185 return MB_STRNICMP(x, y, len);
3186 return STRNCMP(x, y, len);
3187#endif
3188}
3189
3190/*
3191 * Concatenate file names fname1 and fname2 into allocated memory.
3192 * Only add a '/' or '\\' when 'sep' is TRUE and it is necessary.
3193 */
3194 char_u *
3195concat_fnames(char_u *fname1, char_u *fname2, int sep)
3196{
John Marriotte29c8ba2024-12-13 13:58:53 +01003197 size_t fname1len = STRLEN(fname1);
3198 size_t destsize = fname1len + STRLEN(fname2) + 3;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003199 char_u *dest;
3200
John Marriotte29c8ba2024-12-13 13:58:53 +01003201 dest = alloc(destsize);
Yegappan Lakshmanan1cfb14a2023-01-09 19:04:23 +00003202 if (dest == NULL)
3203 return NULL;
3204
John Marriotte29c8ba2024-12-13 13:58:53 +01003205 vim_snprintf((char *)dest, destsize, "%s%s%s",
3206 fname1,
3207 (sep && !after_pathsep(fname1, fname1 + fname1len)) ? PATHSEPSTR : "",
3208 fname2);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003209 return dest;
3210}
3211
3212/*
3213 * Add a path separator to a file name, unless it already ends in a path
3214 * separator.
3215 */
3216 void
3217add_pathsep(char_u *p)
3218{
John Marriotte29c8ba2024-12-13 13:58:53 +01003219 size_t plen;
3220
3221 if (p == NULL || *p == NUL)
3222 return;
3223
3224 plen = STRLEN(p);
3225 if (!after_pathsep(p, p + plen))
3226 STRCPY(p + plen, PATHSEPSTR);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003227}
3228
3229/*
3230 * FullName_save - Make an allocated copy of a full file name.
3231 * Returns NULL when out of memory.
3232 */
3233 char_u *
3234FullName_save(
3235 char_u *fname,
3236 int force) // force expansion, even when it already looks
3237 // like a full path name
3238{
3239 char_u *buf;
3240 char_u *new_fname = NULL;
3241
3242 if (fname == NULL)
3243 return NULL;
3244
3245 buf = alloc(MAXPATHL);
Yegappan Lakshmanan1cfb14a2023-01-09 19:04:23 +00003246 if (buf == NULL)
3247 return NULL;
3248
3249 if (vim_FullName(fname, buf, MAXPATHL, force) != FAIL)
3250 new_fname = vim_strsave(buf);
3251 else
3252 new_fname = vim_strsave(fname);
3253 vim_free(buf);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003254 return new_fname;
3255}
3256
3257/*
3258 * return TRUE if "fname" exists.
3259 */
3260 int
3261vim_fexists(char_u *fname)
3262{
3263 stat_T st;
3264
3265 if (mch_stat((char *)fname, &st))
3266 return FALSE;
3267 return TRUE;
3268}
3269
3270/*
3271 * Invoke expand_wildcards() for one pattern.
3272 * Expand items like "%:h" before the expansion.
3273 * Returns OK or FAIL.
3274 */
3275 int
3276expand_wildcards_eval(
3277 char_u **pat, // pointer to input pattern
3278 int *num_file, // resulting number of files
3279 char_u ***file, // array of resulting files
3280 int flags) // EW_DIR, etc.
3281{
3282 int ret = FAIL;
3283 char_u *eval_pat = NULL;
3284 char_u *exp_pat = *pat;
Bram Moolenaarf5724372022-09-02 19:45:15 +01003285 char *ignored_msg;
Mike Williams51024bb2024-05-30 07:46:30 +02003286 size_t usedlen;
Bram Moolenaarf5724372022-09-02 19:45:15 +01003287 int is_cur_alt_file = *exp_pat == '%' || *exp_pat == '#';
3288 int star_follows = FALSE;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003289
Bram Moolenaarf5724372022-09-02 19:45:15 +01003290 if (is_cur_alt_file || *exp_pat == '<')
Bram Moolenaar26262f82019-09-04 20:59:15 +02003291 {
3292 ++emsg_off;
3293 eval_pat = eval_vars(exp_pat, exp_pat, &usedlen,
Bram Moolenaara96edb72022-04-28 17:52:24 +01003294 NULL, &ignored_msg, NULL, TRUE);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003295 --emsg_off;
3296 if (eval_pat != NULL)
Bram Moolenaarf5724372022-09-02 19:45:15 +01003297 {
3298 star_follows = STRCMP(exp_pat + usedlen, "*") == 0;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003299 exp_pat = concat_str(eval_pat, exp_pat + usedlen);
Bram Moolenaarf5724372022-09-02 19:45:15 +01003300 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02003301 }
3302
3303 if (exp_pat != NULL)
3304 ret = expand_wildcards(1, &exp_pat, num_file, file, flags);
3305
3306 if (eval_pat != NULL)
3307 {
Bram Moolenaarf5724372022-09-02 19:45:15 +01003308 if (*num_file == 0 && is_cur_alt_file && star_follows)
3309 {
3310 // Expanding "%" or "#" and the file does not exist: Add the
3311 // pattern anyway (without the star) so that this works for remote
3312 // files and non-file buffer names.
3313 *file = ALLOC_ONE(char_u *);
3314 if (*file != NULL)
3315 {
3316 **file = eval_pat;
3317 eval_pat = NULL;
3318 *num_file = 1;
3319 ret = OK;
3320 }
3321 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02003322 vim_free(exp_pat);
3323 vim_free(eval_pat);
3324 }
3325
3326 return ret;
3327}
3328
3329/*
3330 * Expand wildcards. Calls gen_expand_wildcards() and removes files matching
3331 * 'wildignore'.
3332 * Returns OK or FAIL. When FAIL then "num_files" won't be set.
3333 */
3334 int
3335expand_wildcards(
3336 int num_pat, // number of input patterns
3337 char_u **pat, // array of input patterns
3338 int *num_files, // resulting number of files
3339 char_u ***files, // array of resulting files
3340 int flags) // EW_DIR, etc.
3341{
3342 int retval;
3343 int i, j;
3344 char_u *p;
3345 int non_suf_match; // number without matching suffix
3346
3347 retval = gen_expand_wildcards(num_pat, pat, num_files, files, flags);
3348
3349 // When keeping all matches, return here
3350 if ((flags & EW_KEEPALL) || retval == FAIL)
3351 return retval;
3352
Bram Moolenaar26262f82019-09-04 20:59:15 +02003353 /*
3354 * Remove names that match 'wildignore'.
3355 */
3356 if (*p_wig)
3357 {
3358 char_u *ffname;
3359
3360 // check all files in (*files)[]
3361 for (i = 0; i < *num_files; ++i)
3362 {
3363 ffname = FullName_save((*files)[i], FALSE);
3364 if (ffname == NULL) // out of memory
3365 break;
3366# ifdef VMS
3367 vms_remove_version(ffname);
3368# endif
3369 if (match_file_list(p_wig, (*files)[i], ffname))
3370 {
3371 // remove this matching file from the list
3372 vim_free((*files)[i]);
3373 for (j = i; j + 1 < *num_files; ++j)
3374 (*files)[j] = (*files)[j + 1];
3375 --*num_files;
3376 --i;
3377 }
3378 vim_free(ffname);
3379 }
3380
3381 // If the number of matches is now zero, we fail.
3382 if (*num_files == 0)
3383 {
3384 VIM_CLEAR(*files);
3385 return FAIL;
3386 }
3387 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02003388
3389 /*
3390 * Move the names where 'suffixes' match to the end.
Bram Moolenaar57e95172022-08-20 19:26:14 +01003391 * Skip when interrupted, the result probably won't be used.
Bram Moolenaar26262f82019-09-04 20:59:15 +02003392 */
Bram Moolenaar57e95172022-08-20 19:26:14 +01003393 if (*num_files > 1 && !got_int)
Bram Moolenaar26262f82019-09-04 20:59:15 +02003394 {
3395 non_suf_match = 0;
3396 for (i = 0; i < *num_files; ++i)
3397 {
3398 if (!match_suffix((*files)[i]))
3399 {
3400 /*
3401 * Move the name without matching suffix to the front
3402 * of the list.
3403 */
3404 p = (*files)[i];
3405 for (j = i; j > non_suf_match; --j)
3406 (*files)[j] = (*files)[j - 1];
3407 (*files)[non_suf_match++] = p;
3408 }
3409 }
3410 }
3411
3412 return retval;
3413}
3414
3415/*
3416 * Return TRUE if "fname" matches with an entry in 'suffixes'.
3417 */
3418 int
3419match_suffix(char_u *fname)
3420{
3421 int fnamelen, setsuflen;
3422 char_u *setsuf;
3423#define MAXSUFLEN 30 // maximum length of a file suffix
3424 char_u suf_buf[MAXSUFLEN];
3425
3426 fnamelen = (int)STRLEN(fname);
3427 setsuflen = 0;
3428 for (setsuf = p_su; *setsuf; )
3429 {
3430 setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
3431 if (setsuflen == 0)
3432 {
3433 char_u *tail = gettail(fname);
3434
3435 // empty entry: match name without a '.'
3436 if (vim_strchr(tail, '.') == NULL)
3437 {
3438 setsuflen = 1;
3439 break;
3440 }
3441 }
3442 else
3443 {
3444 if (fnamelen >= setsuflen
3445 && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
3446 (size_t)setsuflen) == 0)
3447 break;
3448 setsuflen = 0;
3449 }
3450 }
3451 return (setsuflen != 0);
3452}
3453
3454#ifdef VIM_BACKTICK
3455
3456/*
3457 * Return TRUE if we can expand this backtick thing here.
3458 */
3459 static int
3460vim_backtick(char_u *p)
3461{
3462 return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
3463}
3464
3465/*
3466 * Expand an item in `backticks` by executing it as a command.
3467 * Currently only works when pat[] starts and ends with a `.
3468 * Returns number of file names found, -1 if an error is encountered.
3469 */
3470 static int
3471expand_backtick(
3472 garray_T *gap,
3473 char_u *pat,
3474 int flags) // EW_* flags
3475{
3476 char_u *p;
3477 char_u *cmd;
3478 char_u *buffer;
3479 int cnt = 0;
3480 int i;
3481
3482 // Create the command: lop off the backticks.
Bram Moolenaar71ccd032020-06-12 22:59:11 +02003483 cmd = vim_strnsave(pat + 1, STRLEN(pat) - 2);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003484 if (cmd == NULL)
3485 return -1;
3486
3487#ifdef FEAT_EVAL
3488 if (*cmd == '=') // `={expr}`: Expand expression
Bram Moolenaara4e0b972022-10-01 19:43:52 +01003489 buffer = eval_to_string(cmd + 1, TRUE, FALSE);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003490 else
3491#endif
3492 buffer = get_cmd_output(cmd, NULL,
3493 (flags & EW_SILENT) ? SHELL_SILENT : 0, NULL);
3494 vim_free(cmd);
3495 if (buffer == NULL)
3496 return -1;
3497
3498 cmd = buffer;
3499 while (*cmd != NUL)
3500 {
3501 cmd = skipwhite(cmd); // skip over white space
3502 p = cmd;
3503 while (*p != NUL && *p != '\r' && *p != '\n') // skip over entry
3504 ++p;
3505 // add an entry if it is not empty
3506 if (p > cmd)
3507 {
3508 i = *p;
3509 *p = NUL;
3510 addfile(gap, cmd, flags);
3511 *p = i;
3512 ++cnt;
3513 }
3514 cmd = p;
3515 while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
3516 ++cmd;
3517 }
3518
3519 vim_free(buffer);
3520 return cnt;
3521}
3522#endif // VIM_BACKTICK
3523
John Marriotte29c8ba2024-12-13 13:58:53 +01003524#if defined(MSWIN) || (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) || defined(PROTO)
Bram Moolenaar26262f82019-09-04 20:59:15 +02003525/*
John Marriotte29c8ba2024-12-13 13:58:53 +01003526 * File name expansion code for Unix, Mac, MS-DOS, Win16 and Win32. It's here because
Bram Moolenaar26262f82019-09-04 20:59:15 +02003527 * it's shared between these systems.
3528 */
3529
3530/*
John Marriotte29c8ba2024-12-13 13:58:53 +01003531 * comparison function for qsort in unix_expandpath()
Bram Moolenaar26262f82019-09-04 20:59:15 +02003532 */
3533 static int
3534pstrcmp(const void *a, const void *b)
3535{
3536 return (pathcmp(*(char **)a, *(char **)b, -1));
3537}
3538
3539/*
3540 * Recursively expand one path component into all matching files and/or
3541 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
3542 * Return the number of matches found.
3543 * "path" has backslashes before chars that are not to be expanded, starting
3544 * at "path[wildoff]".
3545 * Return the number of matches found.
Bram Moolenaar26262f82019-09-04 20:59:15 +02003546 */
John Marriotte29c8ba2024-12-13 13:58:53 +01003547 int
3548unix_expandpath(
Bram Moolenaar26262f82019-09-04 20:59:15 +02003549 garray_T *gap,
John Marriotte29c8ba2024-12-13 13:58:53 +01003550 char_u *path,
3551 int wildoff,
3552 int flags, // EW_* flags
3553 int didstar) // expanded "**" once already
Bram Moolenaar26262f82019-09-04 20:59:15 +02003554{
John Marriotte29c8ba2024-12-13 13:58:53 +01003555 char_u *buf;
3556 char_u *path_end;
3557 size_t basepathlen; // length of non-variable portion of the path
3558 size_t wildcardlen; // length of wildcard segment
3559 char_u *p, *s, *e;
3560 int start_len = gap->ga_len;
3561 char_u *pat;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003562 regmatch_T regmatch;
John Marriotte29c8ba2024-12-13 13:58:53 +01003563 int starts_with_dot;
3564 int matches; // number of matches found
3565 int starstar = FALSE;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003566 static int stardepth = 0; // depth for "**" expansion
John Marriotte29c8ba2024-12-13 13:58:53 +01003567#ifdef MSWIN
3568 HANDLE hFind = INVALID_HANDLE_VALUE;
3569 WIN32_FIND_DATAW wfb;
3570 WCHAR *wn = NULL; // UCS-2 name, NULL when not used.
3571#else
3572 DIR *dirp;
3573#endif
3574 int ok;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003575
3576 // Expanding "**" may take a long time, check for CTRL-C.
3577 if (stardepth > 0)
3578 {
3579 ui_breakcheck();
3580 if (got_int)
3581 return 0;
3582 }
3583
John Marriotte29c8ba2024-12-13 13:58:53 +01003584 // Make room for file name. When doing encoding conversion the actual
3585 // length may be quite a bit longer.
Bram Moolenaar26262f82019-09-04 20:59:15 +02003586 buf = alloc(MAXPATHL);
3587 if (buf == NULL)
3588 return 0;
3589
3590 /*
3591 * Find the first part in the path name that contains a wildcard or a ~1.
Bram Moolenaar26262f82019-09-04 20:59:15 +02003592 * Copy it into "buf", including the preceding characters.
John Marriotte29c8ba2024-12-13 13:58:53 +01003593 * Note: for unix, when EW_ICASE is set every letter is considered to be a wildcard.
Bram Moolenaar26262f82019-09-04 20:59:15 +02003594 */
3595 p = buf;
3596 s = buf;
3597 e = NULL;
3598 path_end = path;
3599 while (*path_end != NUL)
3600 {
3601 // May ignore a wildcard that has a backslash before it; it will
3602 // be removed by rem_backslash() or file_pat_to_reg_pat() below.
3603 if (path_end >= path + wildoff && rem_backslash(path_end))
3604 *p++ = *path_end++;
John Marriotte29c8ba2024-12-13 13:58:53 +01003605 else if (vim_ispathsep(*path_end))
Bram Moolenaar26262f82019-09-04 20:59:15 +02003606 {
3607 if (e != NULL)
3608 break;
3609 s = p + 1;
3610 }
3611 else if (path_end >= path + wildoff
John Marriotte29c8ba2024-12-13 13:58:53 +01003612#ifdef MSWIN
3613 && vim_strchr((char_u *)"*?[~", *path_end) != NULL
3614#else
3615 && (vim_strchr((char_u *)"*?[{~$", *path_end) != NULL
3616 || (!p_fic && (flags & EW_ICASE)
3617 && vim_isalpha(PTR2CHAR(path_end))))
3618#endif
3619 )
Bram Moolenaar26262f82019-09-04 20:59:15 +02003620 e = p;
3621 if (has_mbyte)
3622 {
John Marriotte29c8ba2024-12-13 13:58:53 +01003623 int len = (*mb_ptr2len)(path_end);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003624 STRNCPY(p, path_end, len);
3625 p += len;
3626 path_end += len;
3627 }
3628 else
3629 *p++ = *path_end++;
3630 }
3631 e = p;
3632 *e = NUL;
3633
3634 // Now we have one wildcard component between "s" and "e".
3635 // Remove backslashes between "wildoff" and the start of the wildcard
3636 // component.
John Marriotte29c8ba2024-12-13 13:58:53 +01003637 p = buf + wildoff;
3638 if (p < s)
3639 {
3640 size_t psize = STRLEN(p) + 1;
3641
3642 do
Bram Moolenaar26262f82019-09-04 20:59:15 +02003643 {
John Marriotte29c8ba2024-12-13 13:58:53 +01003644 if (!rem_backslash(p))
3645 ++p;
3646 else
3647 {
3648 mch_memmove(p, p + 1, psize);
3649 --e;
3650 --s;
3651 }
3652 --psize;
3653 } while (p < s);
3654 }
3655
3656 basepathlen = (size_t)(s - buf);
3657 wildcardlen = (size_t)(e - s);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003658
3659 // Check for "**" between "s" and "e".
3660 for (p = s; p < e; ++p)
3661 if (p[0] == '*' && p[1] == '*')
John Marriotte29c8ba2024-12-13 13:58:53 +01003662 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02003663 starstar = TRUE;
John Marriotte29c8ba2024-12-13 13:58:53 +01003664 break;
3665 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02003666
3667 // convert the file pattern to a regexp pattern
3668 starts_with_dot = *s == '.';
3669 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
3670 if (pat == NULL)
3671 {
3672 vim_free(buf);
3673 return 0;
3674 }
3675
3676 // compile the regexp into a program
John Marriotte29c8ba2024-12-13 13:58:53 +01003677#ifdef MSWIN
3678 regmatch.rm_ic = TRUE; // Always ignore case
3679#else
Bram Moolenaar26262f82019-09-04 20:59:15 +02003680 if (flags & EW_ICASE)
John Marriotte29c8ba2024-12-13 13:58:53 +01003681 regmatch.rm_ic = TRUE; // 'wildignorecase' set
Bram Moolenaar26262f82019-09-04 20:59:15 +02003682 else
John Marriotte29c8ba2024-12-13 13:58:53 +01003683 regmatch.rm_ic = p_fic; // ignore case when 'fileignorecase' is set
3684#endif
Bram Moolenaar26262f82019-09-04 20:59:15 +02003685 if (flags & (EW_NOERROR | EW_NOTWILD))
3686 ++emsg_silent;
3687 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
3688 if (flags & (EW_NOERROR | EW_NOTWILD))
3689 --emsg_silent;
3690 vim_free(pat);
3691
3692 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
3693 {
3694 vim_free(buf);
3695 return 0;
3696 }
3697
3698 // If "**" is by itself, this is the first time we encounter it and more
3699 // is following then find matches without any directory.
John Marriotte29c8ba2024-12-13 13:58:53 +01003700 if (!didstar && stardepth < 100 && starstar && wildcardlen == 2
3701 && *path_end == '/')
Bram Moolenaar26262f82019-09-04 20:59:15 +02003702 {
3703 STRCPY(s, path_end + 1);
3704 ++stardepth;
John Marriotte29c8ba2024-12-13 13:58:53 +01003705 (void)unix_expandpath(gap, buf, (int)basepathlen, flags, TRUE);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003706 --stardepth;
3707 }
3708
John Marriotte29c8ba2024-12-13 13:58:53 +01003709#ifdef MSWIN
3710 // open the directory for scanning
3711 STRCPY(s, "*.*");
3712 wn = enc_to_utf16(buf, NULL);
3713 if (wn != NULL)
3714 hFind = FindFirstFileW(wn, &wfb);
3715 ok = (hFind != INVALID_HANDLE_VALUE);
3716#else
Bram Moolenaar26262f82019-09-04 20:59:15 +02003717 // open the directory for scanning
3718 *s = NUL;
3719 dirp = opendir(*buf == NUL ? "." : (char *)buf);
John Marriotte29c8ba2024-12-13 13:58:53 +01003720 ok = (dirp != NULL);
3721#endif
Bram Moolenaar26262f82019-09-04 20:59:15 +02003722
3723 // Find all matching entries
John Marriotte29c8ba2024-12-13 13:58:53 +01003724 if (ok)
Bram Moolenaar26262f82019-09-04 20:59:15 +02003725 {
John Marriotte29c8ba2024-12-13 13:58:53 +01003726 char_u *d_name;
3727#ifdef MSWIN
3728 char_u *d_name_alt;
3729 // remember the pattern or file name being looked for
3730 char_u *matchname = vim_strnsave(s, basepathlen);
3731#else
3732 struct dirent *dp;
3733#endif
3734
Bram Moolenaar57e95172022-08-20 19:26:14 +01003735 while (!got_int)
Bram Moolenaar26262f82019-09-04 20:59:15 +02003736 {
John Marriotte29c8ba2024-12-13 13:58:53 +01003737#ifdef MSWIN
3738 d_name = utf16_to_enc(wfb.cFileName, NULL); // p is allocated here
3739 if (d_name == NULL)
3740 break; // out of memory
3741
3742 // Do not use the alternate filename when the file name ends in '~',
3743 // because it picks up backup files: short name for "foo.vim~" is
3744 // "foo~1.vim", which matches "*.vim".
3745 if (*wfb.cAlternateFileName == NUL || d_name[STRLEN(d_name) - 1] == '~')
3746 d_name_alt = NULL;
3747 else
3748 d_name_alt = utf16_to_enc(wfb.cAlternateFileName, NULL);
3749#else
Bram Moolenaar26262f82019-09-04 20:59:15 +02003750 dp = readdir(dirp);
3751 if (dp == NULL)
3752 break;
John Marriotte29c8ba2024-12-13 13:58:53 +01003753 d_name = (char_u *)dp->d_name;
3754#endif
Bram Moolenaar26262f82019-09-04 20:59:15 +02003755
John Marriotte29c8ba2024-12-13 13:58:53 +01003756 // Ignore entries starting with a dot, unless when asked for. For MSWIN accept
3757 // all entries found with "matchname".
3758 if (
3759 (d_name[0] != '.' || starts_with_dot || (
3760 (flags & EW_DODOT) && d_name[1] != NUL &&
3761 (d_name[1] != '.' || d_name[2] != NUL)))
3762 && (
3763#ifdef MSWIN
3764 matchname == NULL ||
3765#endif
3766 (regmatch.regprog != NULL
3767 && vim_regexec(&regmatch, (char_u *)d_name, (colnr_T)0))
3768#ifdef MSWIN
3769 || (d_name_alt != NULL
3770 && vim_regexec(&regmatch, d_name_alt, (colnr_T)0))
3771#endif
3772 || ((flags & EW_NOTWILD)
3773 && fnamencmp(path + basepathlen, d_name, wildcardlen) == 0))
3774 )
3775 {
3776 int len = (int)basepathlen + vim_snprintf((char *)s, (size_t)(MAXPATHL - (basepathlen + 1)), "%s", d_name);
3777
3778 if (starstar && stardepth < 100
3779#ifdef MSWIN
3780 && (wfb.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
3781#endif
3782 )
Bram Moolenaar26262f82019-09-04 20:59:15 +02003783 {
3784 // For "**" in the pattern first go deeper in the tree to
3785 // find matches.
John Marriotte29c8ba2024-12-13 13:58:53 +01003786 vim_snprintf((char *)buf + len, (size_t)(MAXPATHL - len),
3787 "/**%s", path_end);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003788 ++stardepth;
3789 (void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
3790 --stardepth;
3791 }
3792
John Marriotte29c8ba2024-12-13 13:58:53 +01003793 vim_snprintf((char *)buf + len, (size_t)(MAXPATHL - len), "%s", path_end);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003794 if (mch_has_exp_wildcard(path_end)) // handle more wildcards
3795 {
3796 // need to expand another component of the path
3797 // remove backslashes for the remaining components only
3798 (void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
3799 }
3800 else
3801 {
3802 stat_T sb;
3803
3804 // no more wildcards, check if there is a match
3805 // remove backslashes for the remaining components only
3806 if (*path_end != NUL)
3807 backslash_halve(buf + len + 1);
3808 // add existing file or symbolic link
3809 if ((flags & EW_ALLLINKS) ? mch_lstat((char *)buf, &sb) >= 0
John Marriotte29c8ba2024-12-13 13:58:53 +01003810 : mch_getperm(buf) >= 0)
Bram Moolenaar26262f82019-09-04 20:59:15 +02003811 {
3812#ifdef MACOS_CONVERT
3813 size_t precomp_len = STRLEN(buf)+1;
3814 char_u *precomp_buf =
3815 mac_precompose_path(buf, precomp_len, &precomp_len);
3816
3817 if (precomp_buf)
3818 {
3819 mch_memmove(buf, precomp_buf, precomp_len);
3820 vim_free(precomp_buf);
3821 }
3822#endif
3823 addfile(gap, buf, flags);
3824 }
3825 }
3826 }
John Marriotte29c8ba2024-12-13 13:58:53 +01003827
3828#ifdef MSWIN
3829 vim_free(d_name);
3830 if (!FindNextFileW(hFind, &wfb))
3831 break;
3832#endif
Bram Moolenaar26262f82019-09-04 20:59:15 +02003833 }
3834
John Marriotte29c8ba2024-12-13 13:58:53 +01003835#ifdef MSWIN
3836 FindClose(hFind);
3837 vim_free(matchname);
3838 vim_free(d_name_alt);
3839#else
Bram Moolenaar26262f82019-09-04 20:59:15 +02003840 closedir(dirp);
John Marriotte29c8ba2024-12-13 13:58:53 +01003841#endif
Bram Moolenaar26262f82019-09-04 20:59:15 +02003842 }
3843
John Marriotte29c8ba2024-12-13 13:58:53 +01003844#ifdef MSWIN
3845 vim_free(wn);
3846#endif
Bram Moolenaar26262f82019-09-04 20:59:15 +02003847 vim_free(buf);
3848 vim_regfree(regmatch.regprog);
3849
Bram Moolenaar57e95172022-08-20 19:26:14 +01003850 // When interrupted the matches probably won't be used and sorting can be
3851 // slow, thus skip it.
Bram Moolenaar26262f82019-09-04 20:59:15 +02003852 matches = gap->ga_len - start_len;
Bram Moolenaar57e95172022-08-20 19:26:14 +01003853 if (matches > 0 && !got_int)
Bram Moolenaar26262f82019-09-04 20:59:15 +02003854 qsort(((char_u **)gap->ga_data) + start_len, matches,
John Marriotte29c8ba2024-12-13 13:58:53 +01003855 sizeof(char_u *), pstrcmp);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003856 return matches;
3857}
John Marriotte29c8ba2024-12-13 13:58:53 +01003858
3859/*
3860 * Expand a path into all matching files and/or directories. Handles "*",
3861 * "?", "[a-z]", "**", etc where appropriate for the platform.
3862 * "path" has backslashes before chars that are not to be expanded.
3863 * Returns the number of matches found.
3864 */
3865 int
3866mch_expandpath(
3867 garray_T *gap,
3868 char_u *path,
3869 int flags) // EW_* flags
3870{
3871 return unix_expandpath(gap, path, 0, flags, FALSE);
3872}
Bram Moolenaar26262f82019-09-04 20:59:15 +02003873#endif
3874
3875/*
3876 * Return TRUE if "p" contains what looks like an environment variable.
3877 * Allowing for escaping.
3878 */
3879 static int
3880has_env_var(char_u *p)
3881{
3882 for ( ; *p; MB_PTR_ADV(p))
3883 {
3884 if (*p == '\\' && p[1] != NUL)
3885 ++p;
3886 else if (vim_strchr((char_u *)
3887#if defined(MSWIN)
3888 "$%"
3889#else
3890 "$"
3891#endif
3892 , *p) != NULL)
3893 return TRUE;
3894 }
3895 return FALSE;
3896}
3897
3898#ifdef SPECIAL_WILDCHAR
3899/*
3900 * Return TRUE if "p" contains a special wildcard character, one that Vim
3901 * cannot expand, requires using a shell.
3902 */
3903 static int
3904has_special_wildchar(char_u *p)
3905{
3906 for ( ; *p; MB_PTR_ADV(p))
3907 {
3908 // Disallow line break characters.
3909 if (*p == '\r' || *p == '\n')
3910 break;
3911 // Allow for escaping.
3912 if (*p == '\\' && p[1] != NUL && p[1] != '\r' && p[1] != '\n')
3913 ++p;
3914 else if (vim_strchr((char_u *)SPECIAL_WILDCHAR, *p) != NULL)
3915 {
3916 // A { must be followed by a matching }.
3917 if (*p == '{' && vim_strchr(p, '}') == NULL)
3918 continue;
3919 // A quote and backtick must be followed by another one.
3920 if ((*p == '`' || *p == '\'') && vim_strchr(p, *p) == NULL)
3921 continue;
3922 return TRUE;
3923 }
3924 }
3925 return FALSE;
3926}
3927#endif
3928
3929/*
3930 * Generic wildcard expansion code.
3931 *
3932 * Characters in "pat" that should not be expanded must be preceded with a
3933 * backslash. E.g., "/path\ with\ spaces/my\*star*"
3934 *
3935 * Return FAIL when no single file was found. In this case "num_file" is not
3936 * set, and "file" may contain an error message.
3937 * Return OK when some files found. "num_file" is set to the number of
3938 * matches, "file" to the array of matches. Call FreeWild() later.
3939 */
3940 int
3941gen_expand_wildcards(
3942 int num_pat, // number of input patterns
3943 char_u **pat, // array of input patterns
3944 int *num_file, // resulting number of files
3945 char_u ***file, // array of resulting files
3946 int flags) // EW_* flags
3947{
3948 int i;
3949 garray_T ga;
3950 char_u *p;
3951 static int recursive = FALSE;
3952 int add_pat;
3953 int retval = OK;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003954 int did_expand_in_path = FALSE;
LemonBoya20bf692024-07-11 22:35:53 +02003955 char_u *path_option = *curbuf->b_p_path == NUL ?
3956 p_path : curbuf->b_p_path;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003957
3958 /*
3959 * expand_env() is called to expand things like "~user". If this fails,
3960 * it calls ExpandOne(), which brings us back here. In this case, always
3961 * call the machine specific expansion function, if possible. Otherwise,
3962 * return FAIL.
3963 */
3964 if (recursive)
3965#ifdef SPECIAL_WILDCHAR
3966 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
3967#else
3968 return FAIL;
3969#endif
3970
3971#ifdef SPECIAL_WILDCHAR
3972 /*
3973 * If there are any special wildcard characters which we cannot handle
3974 * here, call machine specific function for all the expansion. This
3975 * avoids starting the shell for each argument separately.
3976 * For `=expr` do use the internal function.
3977 */
3978 for (i = 0; i < num_pat; i++)
3979 {
3980 if (has_special_wildchar(pat[i])
3981# ifdef VIM_BACKTICK
3982 && !(vim_backtick(pat[i]) && pat[i][1] == '=')
3983# endif
3984 )
3985 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
3986 }
3987#endif
3988
3989 recursive = TRUE;
3990
3991 /*
3992 * The matching file names are stored in a growarray. Init it empty.
3993 */
Bram Moolenaar04935fb2022-01-08 16:19:22 +00003994 ga_init2(&ga, sizeof(char_u *), 30);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003995
Bram Moolenaar57e95172022-08-20 19:26:14 +01003996 for (i = 0; i < num_pat && !got_int; ++i)
Bram Moolenaar26262f82019-09-04 20:59:15 +02003997 {
3998 add_pat = -1;
3999 p = pat[i];
4000
4001#ifdef VIM_BACKTICK
4002 if (vim_backtick(p))
4003 {
4004 add_pat = expand_backtick(&ga, p, flags);
4005 if (add_pat == -1)
4006 retval = FAIL;
4007 }
4008 else
4009#endif
4010 {
4011 /*
4012 * First expand environment variables, "~/" and "~user/".
4013 */
4014 if ((has_env_var(p) && !(flags & EW_NOTENV)) || *p == '~')
4015 {
4016 p = expand_env_save_opt(p, TRUE);
4017 if (p == NULL)
4018 p = pat[i];
4019#ifdef UNIX
4020 /*
4021 * On Unix, if expand_env() can't expand an environment
4022 * variable, use the shell to do that. Discard previously
4023 * found file names and start all over again.
4024 */
4025 else if (has_env_var(p) || *p == '~')
4026 {
4027 vim_free(p);
4028 ga_clear_strings(&ga);
4029 i = mch_expand_wildcards(num_pat, pat, num_file, file,
4030 flags|EW_KEEPDOLLAR);
4031 recursive = FALSE;
4032 return i;
4033 }
4034#endif
4035 }
4036
4037 /*
LemonBoya3157a42022-04-03 11:58:31 +01004038 * If there are wildcards or case-insensitive expansion is
4039 * required: Expand file names and add each match to the list. If
4040 * there is no match, and EW_NOTFOUND is given, add the pattern.
4041 * Otherwise: Add the file name if it exists or when EW_NOTFOUND is
4042 * given.
Bram Moolenaar26262f82019-09-04 20:59:15 +02004043 */
LemonBoya3157a42022-04-03 11:58:31 +01004044 if (mch_has_exp_wildcard(p) || (flags & EW_ICASE))
Bram Moolenaar26262f82019-09-04 20:59:15 +02004045 {
LemonBoya20bf692024-07-11 22:35:53 +02004046 if ((flags & (EW_PATH | EW_CDPATH))
Bram Moolenaar26262f82019-09-04 20:59:15 +02004047 && !mch_isFullName(p)
4048 && !(p[0] == '.'
4049 && (vim_ispathsep(p[1])
4050 || (p[1] == '.' && vim_ispathsep(p[2]))))
4051 )
4052 {
4053 // :find completion where 'path' is used.
4054 // Recursiveness is OK here.
4055 recursive = FALSE;
4056 add_pat = expand_in_path(&ga, p, flags);
4057 recursive = TRUE;
4058 did_expand_in_path = TRUE;
4059 }
4060 else
Bram Moolenaar26262f82019-09-04 20:59:15 +02004061 add_pat = mch_expandpath(&ga, p, flags);
4062 }
4063 }
4064
4065 if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
4066 {
4067 char_u *t = backslash_halve_save(p);
4068
4069 // When EW_NOTFOUND is used, always add files and dirs. Makes
4070 // "vim c:/" work.
4071 if (flags & EW_NOTFOUND)
4072 addfile(&ga, t, flags | EW_DIR | EW_FILE);
4073 else
4074 addfile(&ga, t, flags);
4075
4076 if (t != p)
4077 vim_free(t);
4078 }
4079
LemonBoya20bf692024-07-11 22:35:53 +02004080 if (did_expand_in_path && ga.ga_len > 0 && (flags & (EW_PATH | EW_CDPATH)))
4081 uniquefy_paths(&ga, p, path_option);
Bram Moolenaar26262f82019-09-04 20:59:15 +02004082 if (p != pat[i])
4083 vim_free(p);
4084 }
4085
Bram Moolenaar566cc8c2020-06-29 21:14:51 +02004086 // When returning FAIL the array must be freed here.
4087 if (retval == FAIL)
Yegappan Lakshmanan2b74b682022-04-03 21:30:32 +01004088 ga_clear_strings(&ga);
Bram Moolenaar566cc8c2020-06-29 21:14:51 +02004089
Bram Moolenaar26262f82019-09-04 20:59:15 +02004090 *num_file = ga.ga_len;
Bram Moolenaar566cc8c2020-06-29 21:14:51 +02004091 *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data
4092 : (char_u **)_("no matches");
Bram Moolenaar26262f82019-09-04 20:59:15 +02004093
4094 recursive = FALSE;
4095
4096 return ((flags & EW_EMPTYOK) || ga.ga_data != NULL) ? retval : FAIL;
4097}
4098
4099/*
4100 * Add a file to a file list. Accepted flags:
4101 * EW_DIR add directories
4102 * EW_FILE add files
4103 * EW_EXEC add executable files
4104 * EW_NOTFOUND add even when it doesn't exist
4105 * EW_ADDSLASH add slash after directory name
4106 * EW_ALLLINKS add symlink also when the referred file does not exist
4107 */
4108 void
4109addfile(
4110 garray_T *gap,
Bram Moolenaar217e1b82019-12-01 21:41:28 +01004111 char_u *f, // filename
Bram Moolenaar26262f82019-09-04 20:59:15 +02004112 int flags)
4113{
4114 char_u *p;
4115 int isdir;
4116 stat_T sb;
4117
4118 // if the file/dir/link doesn't exist, may not add it
4119 if (!(flags & EW_NOTFOUND) && ((flags & EW_ALLLINKS)
4120 ? mch_lstat((char *)f, &sb) < 0 : mch_getperm(f) < 0))
4121 return;
4122
4123#ifdef FNAME_ILLEGAL
4124 // if the file/dir contains illegal characters, don't add it
4125 if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
4126 return;
4127#endif
4128
4129 isdir = mch_isdir(f);
4130 if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
4131 return;
4132
4133 // If the file isn't executable, may not add it. Do accept directories.
4134 // When invoked from expand_shellcmd() do not use $PATH.
4135 if (!isdir && (flags & EW_EXEC)
4136 && !mch_can_exe(f, NULL, !(flags & EW_SHELLCMD)))
4137 return;
4138
4139 // Make room for another item in the file list.
4140 if (ga_grow(gap, 1) == FAIL)
4141 return;
4142
4143 p = alloc(STRLEN(f) + 1 + isdir);
4144 if (p == NULL)
4145 return;
4146
4147 STRCPY(p, f);
4148#ifdef BACKSLASH_IN_FILENAME
4149 slash_adjust(p);
4150#endif
4151 /*
4152 * Append a slash or backslash after directory names if none is present.
4153 */
Bram Moolenaar26262f82019-09-04 20:59:15 +02004154 if (isdir && (flags & EW_ADDSLASH))
4155 add_pathsep(p);
Bram Moolenaar26262f82019-09-04 20:59:15 +02004156 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
4157}
4158
4159/*
4160 * Free the list of files returned by expand_wildcards() or other expansion
4161 * functions.
4162 */
4163 void
4164FreeWild(int count, char_u **files)
4165{
4166 if (count <= 0 || files == NULL)
4167 return;
4168 while (count--)
4169 vim_free(files[count]);
4170 vim_free(files);
4171}
4172
4173/*
4174 * Compare path "p[]" to "q[]".
4175 * If "maxlen" >= 0 compare "p[maxlen]" to "q[maxlen]"
4176 * Return value like strcmp(p, q), but consider path separators.
4177 */
4178 int
4179pathcmp(const char *p, const char *q, int maxlen)
4180{
4181 int i, j;
4182 int c1, c2;
4183 const char *s = NULL;
4184
4185 for (i = 0, j = 0; maxlen < 0 || (i < maxlen && j < maxlen);)
4186 {
4187 c1 = PTR2CHAR((char_u *)p + i);
4188 c2 = PTR2CHAR((char_u *)q + j);
4189
4190 // End of "p": check if "q" also ends or just has a slash.
4191 if (c1 == NUL)
4192 {
4193 if (c2 == NUL) // full match
4194 return 0;
4195 s = q;
4196 i = j;
4197 break;
4198 }
4199
4200 // End of "q": check if "p" just has a slash.
4201 if (c2 == NUL)
4202 {
4203 s = p;
4204 break;
4205 }
4206
4207 if ((p_fic ? MB_TOUPPER(c1) != MB_TOUPPER(c2) : c1 != c2)
4208#ifdef BACKSLASH_IN_FILENAME
4209 // consider '/' and '\\' to be equal
4210 && !((c1 == '/' && c2 == '\\')
4211 || (c1 == '\\' && c2 == '/'))
4212#endif
4213 )
4214 {
4215 if (vim_ispathsep(c1))
4216 return -1;
4217 if (vim_ispathsep(c2))
4218 return 1;
4219 return p_fic ? MB_TOUPPER(c1) - MB_TOUPPER(c2)
4220 : c1 - c2; // no match
4221 }
4222
Bram Moolenaar1614a142019-10-06 22:00:13 +02004223 i += mb_ptr2len((char_u *)p + i);
4224 j += mb_ptr2len((char_u *)q + j);
Bram Moolenaar26262f82019-09-04 20:59:15 +02004225 }
4226 if (s == NULL) // "i" or "j" ran into "maxlen"
4227 return 0;
4228
4229 c1 = PTR2CHAR((char_u *)s + i);
Bram Moolenaar1614a142019-10-06 22:00:13 +02004230 c2 = PTR2CHAR((char_u *)s + i + mb_ptr2len((char_u *)s + i));
Bram Moolenaar26262f82019-09-04 20:59:15 +02004231 // ignore a trailing slash, but not "//" or ":/"
4232 if (c2 == NUL
4233 && i > 0
4234 && !after_pathsep((char_u *)s, (char_u *)s + i)
4235#ifdef BACKSLASH_IN_FILENAME
4236 && (c1 == '/' || c1 == '\\')
4237#else
4238 && c1 == '/'
4239#endif
4240 )
4241 return 0; // match with trailing slash
4242 if (s == q)
4243 return -1; // no match
4244 return 1;
4245}
4246
4247/*
4248 * Return TRUE if "name" is a full (absolute) path name or URL.
4249 */
4250 int
4251vim_isAbsName(char_u *name)
4252{
4253 return (path_with_url(name) != 0 || mch_isFullName(name));
4254}
4255
4256/*
4257 * Get absolute file name into buffer "buf[len]".
4258 *
4259 * return FAIL for failure, OK otherwise
4260 */
4261 int
4262vim_FullName(
4263 char_u *fname,
4264 char_u *buf,
4265 int len,
4266 int force) // force expansion even when already absolute
4267{
4268 int retval = OK;
4269 int url;
4270
4271 *buf = NUL;
4272 if (fname == NULL)
4273 return FAIL;
4274
4275 url = path_with_url(fname);
4276 if (!url)
4277 retval = mch_FullName(fname, buf, len, force);
4278 if (url || retval == FAIL)
4279 {
4280 // something failed; use the file name (truncate when too long)
4281 vim_strncpy(buf, fname, len - 1);
4282 }
4283#if defined(MSWIN)
4284 slash_adjust(buf);
4285#endif
4286 return retval;
4287}