blob: 0671d0f2d1efa66cc102fd2c9f1ddaab90371195 [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
Yegappan Lakshmanan00d34592024-12-25 10:20:51 +010030get_short_pathname(char_u **fnamep, char_u **bufp, size_t *fnamelen)
Bram Moolenaarb005cd82019-09-04 15:54:55 +020031{
Christian Brabandt6cc30272024-12-13 17:54:33 +010032 int l, len;
Bram Moolenaar3f396972019-10-30 04:10:06 +010033 WCHAR *newbuf;
34 WCHAR *wfname;
Bram Moolenaarb005cd82019-09-04 15:54:55 +020035
Christian Brabandt6cc30272024-12-13 17:54:33 +010036 len = MAXPATHL;
37 newbuf = malloc(len * sizeof(*newbuf));
Bram Moolenaar3f396972019-10-30 04:10:06 +010038 if (newbuf == NULL)
39 return FAIL;
40
41 wfname = enc_to_utf16(*fnamep, NULL);
42 if (wfname == NULL)
43 {
44 vim_free(newbuf);
45 return FAIL;
46 }
47
Christian Brabandt6cc30272024-12-13 17:54:33 +010048 l = GetShortPathNameW(wfname, newbuf, len);
49 if (l > len - 1)
Bram Moolenaarb005cd82019-09-04 15:54:55 +020050 {
Bram Moolenaar26262f82019-09-04 20:59:15 +020051 // If that doesn't work (not enough space), then save the string
52 // and try again with a new buffer big enough.
Bram Moolenaar3f396972019-10-30 04:10:06 +010053 WCHAR *newbuf_t = newbuf;
54 newbuf = vim_realloc(newbuf, (l + 1) * sizeof(*newbuf));
Bram Moolenaarb005cd82019-09-04 15:54:55 +020055 if (newbuf == NULL)
Bram Moolenaar3f396972019-10-30 04:10:06 +010056 {
57 vim_free(wfname);
58 vim_free(newbuf_t);
Bram Moolenaarb005cd82019-09-04 15:54:55 +020059 return FAIL;
Bram Moolenaar3f396972019-10-30 04:10:06 +010060 }
Bram Moolenaar26262f82019-09-04 20:59:15 +020061 // Really should always succeed, as the buffer is big enough.
Bram Moolenaar3f396972019-10-30 04:10:06 +010062 l = GetShortPathNameW(wfname, newbuf, l+1);
Bram Moolenaarb005cd82019-09-04 15:54:55 +020063 }
Bram Moolenaar3f396972019-10-30 04:10:06 +010064 if (l != 0)
65 {
66 char_u *p = utf16_to_enc(newbuf, NULL);
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +020067
Bram Moolenaar3f396972019-10-30 04:10:06 +010068 if (p != NULL)
69 {
70 vim_free(*bufp);
71 *fnamep = *bufp = p;
72 }
73 else
74 {
75 vim_free(wfname);
76 vim_free(newbuf);
77 return FAIL;
78 }
79 }
80 vim_free(wfname);
81 vim_free(newbuf);
Bram Moolenaarb005cd82019-09-04 15:54:55 +020082
Yegappan Lakshmanan00d34592024-12-25 10:20:51 +010083 *fnamelen = l == 0 ? l : STRLEN(*bufp);
Bram Moolenaarb005cd82019-09-04 15:54:55 +020084 return OK;
85}
86
87/*
88 * Get the short path (8.3) for the filename in "fname". The converted
89 * path is returned in "bufp".
90 *
91 * Some of the directories specified in "fname" may not exist. This function
92 * will shorten the existing directories at the beginning of the path and then
93 * append the remaining non-existing path.
94 *
95 * fname - Pointer to the filename to shorten. On return, contains the
96 * pointer to the shortened pathname
97 * bufp - Pointer to an allocated buffer for the filename.
98 * fnamelen - Length of the filename pointed to by fname
99 *
100 * Returns OK on success (or nothing done) and FAIL on failure (out of memory).
101 */
102 static int
103shortpath_for_invalid_fname(
104 char_u **fname,
105 char_u **bufp,
Yegappan Lakshmanan00d34592024-12-25 10:20:51 +0100106 size_t *fnamelen)
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200107{
Christian Brabandt6cc30272024-12-13 17:54:33 +0100108 char_u *short_fname, *save_fname, *pbuf_unused;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200109 char_u *endp, *save_endp;
110 char_u ch;
Yegappan Lakshmanan00d34592024-12-25 10:20:51 +0100111 size_t old_len;
112 size_t len;
113 size_t new_len, sfx_len;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200114 int retval = OK;
115
Bram Moolenaar26262f82019-09-04 20:59:15 +0200116 // Make a copy
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200117 old_len = *fnamelen;
118 save_fname = vim_strnsave(*fname, old_len);
119 pbuf_unused = NULL;
120 short_fname = NULL;
121
Bram Moolenaar26262f82019-09-04 20:59:15 +0200122 endp = save_fname + old_len - 1; // Find the end of the copy
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200123 save_endp = endp;
124
125 /*
126 * Try shortening the supplied path till it succeeds by removing one
127 * directory at a time from the tail of the path.
128 */
129 len = 0;
130 for (;;)
131 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200132 // go back one path-separator
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200133 while (endp > save_fname && !after_pathsep(save_fname, endp + 1))
134 --endp;
135 if (endp <= save_fname)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200136 break; // processed the complete path
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200137
138 /*
139 * Replace the path separator with a NUL and try to shorten the
140 * resulting path.
141 */
142 ch = *endp;
Christian Brabandt6cc30272024-12-13 17:54:33 +0100143 *endp = 0;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200144 short_fname = save_fname;
Yegappan Lakshmanan00d34592024-12-25 10:20:51 +0100145 len = STRLEN(short_fname) + 1;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200146 if (get_short_pathname(&short_fname, &pbuf_unused, &len) == FAIL)
147 {
148 retval = FAIL;
149 goto theend;
150 }
Bram Moolenaar26262f82019-09-04 20:59:15 +0200151 *endp = ch; // preserve the string
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200152
153 if (len > 0)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200154 break; // successfully shortened the path
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200155
Bram Moolenaar26262f82019-09-04 20:59:15 +0200156 // failed to shorten the path. Skip the path separator
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200157 --endp;
158 }
159
160 if (len > 0)
161 {
162 /*
163 * Succeeded in shortening the path. Now concatenate the shortened
164 * path with the remaining path at the tail.
165 */
166
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100167 // Compute the length of the new path.
Yegappan Lakshmanan00d34592024-12-25 10:20:51 +0100168 sfx_len = (save_endp - endp) + 1;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200169 new_len = len + sfx_len;
170
171 *fnamelen = new_len;
172 vim_free(*bufp);
173 if (new_len > old_len)
174 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200175 // There is not enough space in the currently allocated string,
176 // copy it to a buffer big enough.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200177 *fname = *bufp = vim_strnsave(short_fname, new_len);
178 if (*fname == NULL)
179 {
180 retval = FAIL;
181 goto theend;
182 }
183 }
184 else
185 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200186 // Transfer short_fname to the main buffer (it's big enough),
187 // unless get_short_pathname() did its work in-place.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200188 *fname = *bufp = save_fname;
189 if (short_fname != save_fname)
Christian Brabandt81da16b2022-03-10 12:24:02 +0000190 STRNCPY(save_fname, short_fname, len);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200191 save_fname = NULL;
192 }
193
Bram Moolenaar26262f82019-09-04 20:59:15 +0200194 // concat the not-shortened part of the path
Yegappan Lakshmanana34b4462022-06-11 10:43:26 +0100195 if ((*fname + len) != endp)
196 vim_strncpy(*fname + len, endp, sfx_len);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200197 (*fname)[new_len] = NUL;
198 }
199
200theend:
201 vim_free(pbuf_unused);
202 vim_free(save_fname);
203
204 return retval;
205}
206
207/*
208 * Get a pathname for a partial path.
209 * Returns OK for success, FAIL for failure.
210 */
211 static int
212shortpath_for_partial(
213 char_u **fnamep,
214 char_u **bufp,
Yegappan Lakshmanan00d34592024-12-25 10:20:51 +0100215 size_t *fnamelen)
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200216{
Yegappan Lakshmanan00d34592024-12-25 10:20:51 +0100217 int sepcount;
218 size_t len, tflen;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200219 char_u *p;
220 char_u *pbuf, *tfname;
221 int hasTilde;
222
Bram Moolenaar26262f82019-09-04 20:59:15 +0200223 // Count up the path separators from the RHS.. so we know which part
224 // of the path to return.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200225 sepcount = 0;
226 for (p = *fnamep; p < *fnamep + *fnamelen; MB_PTR_ADV(p))
227 if (vim_ispathsep(*p))
228 ++sepcount;
229
Christian Brabandt6cc30272024-12-13 17:54:33 +0100230 // Need full path first (use expand_env() to remove a "~/")
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200231 hasTilde = (**fnamep == '~');
232 if (hasTilde)
233 pbuf = tfname = expand_env_save(*fnamep);
234 else
235 pbuf = tfname = FullName_save(*fnamep, FALSE);
236
Yegappan Lakshmanan00d34592024-12-25 10:20:51 +0100237 len = tflen = STRLEN(tfname);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200238
239 if (get_short_pathname(&tfname, &pbuf, &len) == FAIL)
240 return FAIL;
241
242 if (len == 0)
243 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200244 // Don't have a valid filename, so shorten the rest of the
245 // path if we can. This CAN give us invalid 8.3 filenames, but
246 // there's not a lot of point in guessing what it might be.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200247 len = tflen;
248 if (shortpath_for_invalid_fname(&tfname, &pbuf, &len) == FAIL)
249 return FAIL;
250 }
251
Bram Moolenaar26262f82019-09-04 20:59:15 +0200252 // Count the paths backward to find the beginning of the desired string.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200253 for (p = tfname + len - 1; p >= tfname; --p)
254 {
255 if (has_mbyte)
256 p -= mb_head_off(tfname, p);
257 if (vim_ispathsep(*p))
258 {
259 if (sepcount == 0 || (hasTilde && sepcount == 1))
260 break;
261 else
262 sepcount --;
263 }
264 }
265 if (hasTilde)
266 {
267 --p;
268 if (p >= tfname)
269 *p = '~';
270 else
271 return FAIL;
272 }
273 else
274 ++p;
275
Bram Moolenaar26262f82019-09-04 20:59:15 +0200276 // Copy in the string - p indexes into tfname - allocated at pbuf
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200277 vim_free(*bufp);
Yegappan Lakshmanan00d34592024-12-25 10:20:51 +0100278 *fnamelen = STRLEN(p);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200279 *bufp = pbuf;
280 *fnamep = p;
281
282 return OK;
283}
284#endif // MSWIN
285
286/*
287 * Adjust a filename, according to a string of modifiers.
288 * *fnamep must be NUL terminated when called. When returning, the length is
289 * determined by *fnamelen.
290 * Returns VALID_ flags or -1 for failure.
291 * When there is an error, *fnamep is set to NULL.
292 */
293 int
294modify_fname(
295 char_u *src, // string with modifiers
296 int tilde_file, // "~" is a file name, not $HOME
Mike Williams51024bb2024-05-30 07:46:30 +0200297 size_t *usedlen, // characters after src that are used
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200298 char_u **fnamep, // file name so far
299 char_u **bufp, // buffer for allocated file name or NULL
Yegappan Lakshmanan00d34592024-12-25 10:20:51 +0100300 size_t *fnamelen) // length of fnamep
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200301{
302 int valid = 0;
303 char_u *tail;
304 char_u *s, *p, *pbuf;
305 char_u dirname[MAXPATHL];
306 int c;
307 int has_fullname = 0;
Bram Moolenaard816cd92020-02-04 22:23:09 +0100308 int has_homerelative = 0;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200309#ifdef MSWIN
310 char_u *fname_start = *fnamep;
311 int has_shortname = 0;
312#endif
313
314repeat:
Bram Moolenaar26262f82019-09-04 20:59:15 +0200315 // ":p" - full path/file_name
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200316 if (src[*usedlen] == ':' && src[*usedlen + 1] == 'p')
317 {
318 has_fullname = 1;
319
320 valid |= VALID_PATH;
321 *usedlen += 2;
322
Bram Moolenaar26262f82019-09-04 20:59:15 +0200323 // Expand "~/path" for all systems and "~user/path" for Unix and VMS
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200324 if ((*fnamep)[0] == '~'
325#if !defined(UNIX) && !(defined(VMS) && defined(USER_HOME))
326 && ((*fnamep)[1] == '/'
327# ifdef BACKSLASH_IN_FILENAME
328 || (*fnamep)[1] == '\\'
329# endif
330 || (*fnamep)[1] == NUL)
331#endif
332 && !(tilde_file && (*fnamep)[1] == NUL)
333 )
334 {
335 *fnamep = expand_env_save(*fnamep);
Bram Moolenaar26262f82019-09-04 20:59:15 +0200336 vim_free(*bufp); // free any allocated file name
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200337 *bufp = *fnamep;
338 if (*fnamep == NULL)
339 return -1;
340 }
341
Bram Moolenaar26262f82019-09-04 20:59:15 +0200342 // When "/." or "/.." is used: force expansion to get rid of it.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200343 for (p = *fnamep; *p != NUL; MB_PTR_ADV(p))
344 {
345 if (vim_ispathsep(*p)
346 && p[1] == '.'
347 && (p[2] == NUL
348 || vim_ispathsep(p[2])
349 || (p[2] == '.'
350 && (p[3] == NUL || vim_ispathsep(p[3])))))
351 break;
352 }
353
Bram Moolenaar26262f82019-09-04 20:59:15 +0200354 // FullName_save() is slow, don't use it when not needed.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200355 if (*p != NUL || !vim_isAbsName(*fnamep))
356 {
357 *fnamep = FullName_save(*fnamep, *p != NUL);
Bram Moolenaar26262f82019-09-04 20:59:15 +0200358 vim_free(*bufp); // free any allocated file name
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200359 *bufp = *fnamep;
360 if (*fnamep == NULL)
361 return -1;
362 }
363
364#ifdef MSWIN
365# if _WIN32_WINNT >= 0x0500
366 if (vim_strchr(*fnamep, '~') != NULL)
367 {
368 // Expand 8.3 filename to full path. Needed to make sure the same
369 // file does not have two different names.
370 // Note: problem does not occur if _WIN32_WINNT < 0x0500.
371 WCHAR *wfname = enc_to_utf16(*fnamep, NULL);
372 WCHAR buf[_MAX_PATH];
373
374 if (wfname != NULL)
375 {
376 if (GetLongPathNameW(wfname, buf, _MAX_PATH))
377 {
K.Takata54119102022-02-03 13:33:03 +0000378 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200379
K.Takata54119102022-02-03 13:33:03 +0000380 if (q != NULL)
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200381 {
382 vim_free(*bufp); // free any allocated file name
K.Takata54119102022-02-03 13:33:03 +0000383 *bufp = *fnamep = q;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200384 }
385 }
386 vim_free(wfname);
387 }
388 }
389# endif
390#endif
Bram Moolenaar26262f82019-09-04 20:59:15 +0200391 // Append a path separator to a directory.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200392 if (mch_isdir(*fnamep))
393 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200394 // Make room for one or two extra characters.
Bram Moolenaar71ccd032020-06-12 22:59:11 +0200395 *fnamep = vim_strnsave(*fnamep, STRLEN(*fnamep) + 2);
Bram Moolenaar26262f82019-09-04 20:59:15 +0200396 vim_free(*bufp); // free any allocated file name
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200397 *bufp = *fnamep;
398 if (*fnamep == NULL)
399 return -1;
400 add_pathsep(*fnamep);
401 }
402 }
403
Bram Moolenaar26262f82019-09-04 20:59:15 +0200404 // ":." - path relative to the current directory
405 // ":~" - path relative to the home directory
406 // ":8" - shortname path - postponed till after
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200407 while (src[*usedlen] == ':'
408 && ((c = src[*usedlen + 1]) == '.' || c == '~' || c == '8'))
409 {
410 *usedlen += 2;
411 if (c == '8')
412 {
413#ifdef MSWIN
Bram Moolenaar26262f82019-09-04 20:59:15 +0200414 has_shortname = 1; // Postpone this.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200415#endif
416 continue;
417 }
418 pbuf = NULL;
Christian Brabandt6cc30272024-12-13 17:54:33 +0100419 // Need full path first (use expand_env() to remove a "~/")
Bram Moolenaard816cd92020-02-04 22:23:09 +0100420 if (!has_fullname && !has_homerelative)
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200421 {
=?UTF-8?q?Dundar=20G=C3=B6c?=78a84042022-02-09 15:20:39 +0000422 if (**fnamep == '~')
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200423 p = pbuf = expand_env_save(*fnamep);
424 else
425 p = pbuf = FullName_save(*fnamep, FALSE);
426 }
427 else
428 p = *fnamep;
429
430 has_fullname = 0;
431
432 if (p != NULL)
433 {
434 if (c == '.')
435 {
Bram Moolenaard816cd92020-02-04 22:23:09 +0100436 size_t namelen;
437
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200438 mch_dirname(dirname, MAXPATHL);
Bram Moolenaard816cd92020-02-04 22:23:09 +0100439 if (has_homerelative)
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200440 {
Bram Moolenaard816cd92020-02-04 22:23:09 +0100441 s = vim_strsave(dirname);
442 if (s != NULL)
443 {
444 home_replace(NULL, s, dirname, MAXPATHL, TRUE);
445 vim_free(s);
446 }
447 }
448 namelen = STRLEN(dirname);
449
450 // Do not call shorten_fname() here since it removes the prefix
451 // even though the path does not have a prefix.
452 if (fnamencmp(p, dirname, namelen) == 0)
453 {
454 p += namelen;
Bram Moolenaara78e9c62020-02-05 21:14:00 +0100455 if (vim_ispathsep(*p))
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200456 {
Bram Moolenaara78e9c62020-02-05 21:14:00 +0100457 while (*p && vim_ispathsep(*p))
458 ++p;
459 *fnamep = p;
460 if (pbuf != NULL)
461 {
462 // free any allocated file name
463 vim_free(*bufp);
464 *bufp = pbuf;
465 pbuf = NULL;
466 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200467 }
468 }
469 }
470 else
471 {
472 home_replace(NULL, p, dirname, MAXPATHL, TRUE);
Bram Moolenaar26262f82019-09-04 20:59:15 +0200473 // Only replace it when it starts with '~'
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200474 if (*dirname == '~')
475 {
476 s = vim_strsave(dirname);
477 if (s != NULL)
478 {
479 *fnamep = s;
480 vim_free(*bufp);
481 *bufp = s;
Bram Moolenaard816cd92020-02-04 22:23:09 +0100482 has_homerelative = TRUE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200483 }
484 }
485 }
486 vim_free(pbuf);
487 }
488 }
489
490 tail = gettail(*fnamep);
Yegappan Lakshmanan00d34592024-12-25 10:20:51 +0100491 *fnamelen = STRLEN(*fnamep);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200492
Bram Moolenaar26262f82019-09-04 20:59:15 +0200493 // ":h" - head, remove "/file_name", can be repeated
494 // Don't remove the first "/" or "c:\"
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200495 while (src[*usedlen] == ':' && src[*usedlen + 1] == 'h')
496 {
497 valid |= VALID_HEAD;
498 *usedlen += 2;
499 s = get_past_head(*fnamep);
500 while (tail > s && after_pathsep(s, tail))
501 MB_PTR_BACK(*fnamep, tail);
Yegappan Lakshmanan00d34592024-12-25 10:20:51 +0100502 *fnamelen = tail - *fnamep;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200503#ifdef VMS
504 if (*fnamelen > 0)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200505 *fnamelen += 1; // the path separator is part of the path
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200506#endif
507 if (*fnamelen == 0)
508 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200509 // Result is empty. Turn it into "." to make ":cd %:h" work.
Christian Brabandt6cc30272024-12-13 17:54:33 +0100510 p = vim_strsave((char_u *)".");
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200511 if (p == NULL)
512 return -1;
513 vim_free(*bufp);
514 *bufp = *fnamep = tail = p;
515 *fnamelen = 1;
516 }
517 else
518 {
519 while (tail > s && !after_pathsep(s, tail))
520 MB_PTR_BACK(*fnamep, tail);
521 }
522 }
523
Bram Moolenaar26262f82019-09-04 20:59:15 +0200524 // ":8" - shortname
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200525 if (src[*usedlen] == ':' && src[*usedlen + 1] == '8')
526 {
527 *usedlen += 2;
528#ifdef MSWIN
529 has_shortname = 1;
530#endif
531 }
532
533#ifdef MSWIN
534 /*
535 * Handle ":8" after we have done 'heads' and before we do 'tails'.
536 */
537 if (has_shortname)
538 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200539 // Copy the string if it is shortened by :h and when it wasn't copied
540 // yet, because we are going to change it in place. Avoids changing
541 // the buffer name for "%:8".
Yegappan Lakshmanan00d34592024-12-25 10:20:51 +0100542 if (*fnamelen < STRLEN(*fnamep) || *fnamep == fname_start)
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200543 {
544 p = vim_strnsave(*fnamep, *fnamelen);
545 if (p == NULL)
546 return -1;
547 vim_free(*bufp);
548 *bufp = *fnamep = p;
549 }
550
Bram Moolenaar26262f82019-09-04 20:59:15 +0200551 // Split into two implementations - makes it easier. First is where
552 // there isn't a full name already, second is where there is.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200553 if (!has_fullname && !vim_isAbsName(*fnamep))
554 {
555 if (shortpath_for_partial(fnamep, bufp, fnamelen) == FAIL)
556 return -1;
557 }
558 else
559 {
Yegappan Lakshmanan00d34592024-12-25 10:20:51 +0100560 size_t l = *fnamelen;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200561
Bram Moolenaar26262f82019-09-04 20:59:15 +0200562 // Simple case, already have the full-name.
563 // Nearly always shorter, so try first time.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200564 if (get_short_pathname(fnamep, bufp, &l) == FAIL)
565 return -1;
566
567 if (l == 0)
568 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200569 // Couldn't find the filename, search the paths.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200570 l = *fnamelen;
571 if (shortpath_for_invalid_fname(fnamep, bufp, &l) == FAIL)
572 return -1;
573 }
574 *fnamelen = l;
575 }
576 }
577#endif // MSWIN
578
Bram Moolenaar26262f82019-09-04 20:59:15 +0200579 // ":t" - tail, just the basename
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200580 if (src[*usedlen] == ':' && src[*usedlen + 1] == 't')
581 {
582 *usedlen += 2;
Yegappan Lakshmanan00d34592024-12-25 10:20:51 +0100583 *fnamelen -= tail - *fnamep;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200584 *fnamep = tail;
585 }
586
Bram Moolenaar26262f82019-09-04 20:59:15 +0200587 // ":e" - extension, can be repeated
588 // ":r" - root, without extension, can be repeated
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200589 while (src[*usedlen] == ':'
590 && (src[*usedlen + 1] == 'e' || src[*usedlen + 1] == 'r'))
591 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200592 // find a '.' in the tail:
593 // - for second :e: before the current fname
594 // - otherwise: The last '.'
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200595 if (src[*usedlen + 1] == 'e' && *fnamep > tail)
596 s = *fnamep - 2;
597 else
598 s = *fnamep + *fnamelen - 1;
599 for ( ; s > tail; --s)
600 if (s[0] == '.')
601 break;
Bram Moolenaar26262f82019-09-04 20:59:15 +0200602 if (src[*usedlen + 1] == 'e') // :e
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200603 {
604 if (s > tail)
605 {
Yegappan Lakshmanan00d34592024-12-25 10:20:51 +0100606 *fnamelen += (*fnamep - (s + 1));
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200607 *fnamep = s + 1;
608#ifdef VMS
Bram Moolenaar26262f82019-09-04 20:59:15 +0200609 // cut version from the extension
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200610 s = *fnamep + *fnamelen - 1;
611 for ( ; s > *fnamep; --s)
612 if (s[0] == ';')
613 break;
614 if (s > *fnamep)
615 *fnamelen = s - *fnamep;
616#endif
617 }
618 else if (*fnamep <= tail)
619 *fnamelen = 0;
620 }
Bram Moolenaar26262f82019-09-04 20:59:15 +0200621 else // :r
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200622 {
Bram Moolenaarb1892952019-10-08 23:26:50 +0200623 char_u *limit = *fnamep;
624
625 if (limit < tail)
626 limit = tail;
627 if (s > limit) // remove one extension
Yegappan Lakshmanan00d34592024-12-25 10:20:51 +0100628 *fnamelen = s - *fnamep;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200629 }
630 *usedlen += 2;
631 }
632
Bram Moolenaar26262f82019-09-04 20:59:15 +0200633 // ":s?pat?foo?" - substitute
634 // ":gs?pat?foo?" - global substitute
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200635 if (src[*usedlen] == ':'
636 && (src[*usedlen + 1] == 's'
637 || (src[*usedlen + 1] == 'g' && src[*usedlen + 2] == 's')))
638 {
639 char_u *str;
640 char_u *pat;
641 char_u *sub;
642 int sep;
643 char_u *flags;
644 int didit = FALSE;
645
646 flags = (char_u *)"";
647 s = src + *usedlen + 2;
648 if (src[*usedlen + 1] == 'g')
649 {
650 flags = (char_u *)"g";
651 ++s;
652 }
653
654 sep = *s++;
655 if (sep)
656 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200657 // find end of pattern
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200658 p = vim_strchr(s, sep);
659 if (p != NULL)
660 {
Bram Moolenaar71ccd032020-06-12 22:59:11 +0200661 pat = vim_strnsave(s, p - s);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200662 if (pat != NULL)
663 {
664 s = p + 1;
Bram Moolenaar26262f82019-09-04 20:59:15 +0200665 // find end of substitution
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200666 p = vim_strchr(s, sep);
667 if (p != NULL)
668 {
Bram Moolenaar71ccd032020-06-12 22:59:11 +0200669 sub = vim_strnsave(s, p - s);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200670 str = vim_strnsave(*fnamep, *fnamelen);
671 if (sub != NULL && str != NULL)
672 {
John Marriottbd4614f2024-11-18 20:25:21 +0100673 size_t slen;
674
Mike Williams51024bb2024-05-30 07:46:30 +0200675 *usedlen = p + 1 - src;
John Marriottbd4614f2024-11-18 20:25:21 +0100676 s = do_string_sub(str, *fnamelen, pat, sub, NULL, flags, &slen);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200677 if (s != NULL)
678 {
679 *fnamep = s;
Yegappan Lakshmanan00d34592024-12-25 10:20:51 +0100680 *fnamelen = slen;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200681 vim_free(*bufp);
682 *bufp = s;
683 didit = TRUE;
684 }
685 }
686 vim_free(sub);
687 vim_free(str);
688 }
689 vim_free(pat);
690 }
691 }
Bram Moolenaar26262f82019-09-04 20:59:15 +0200692 // after using ":s", repeat all the modifiers
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200693 if (didit)
694 goto repeat;
695 }
696 }
697
698 if (src[*usedlen] == ':' && src[*usedlen + 1] == 'S')
699 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200700 // vim_strsave_shellescape() needs a NUL terminated string.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200701 c = (*fnamep)[*fnamelen];
702 if (c != NUL)
703 (*fnamep)[*fnamelen] = NUL;
704 p = vim_strsave_shellescape(*fnamep, FALSE, FALSE);
705 if (c != NUL)
706 (*fnamep)[*fnamelen] = c;
707 if (p == NULL)
708 return -1;
709 vim_free(*bufp);
710 *bufp = *fnamep = p;
Yegappan Lakshmanan00d34592024-12-25 10:20:51 +0100711 *fnamelen = STRLEN(p);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200712 *usedlen += 2;
713 }
714
715 return valid;
716}
717
Bram Moolenaar273af492020-09-25 23:49:01 +0200718/*
719 * Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
720 * "trim_len" specifies how many characters to keep for each directory.
721 * Must be 1 or more.
722 * It's done in-place.
723 */
724 static void
725shorten_dir_len(char_u *str, int trim_len)
726{
727 char_u *tail, *s, *d;
728 int skip = FALSE;
729 int dirchunk_len = 0;
730
731 tail = gettail(str);
732 d = str;
733 for (s = str; ; ++s)
734 {
735 if (s >= tail) // copy the whole tail
736 {
737 *d++ = *s;
738 if (*s == NUL)
739 break;
740 }
741 else if (vim_ispathsep(*s)) // copy '/' and next char
742 {
743 *d++ = *s;
744 skip = FALSE;
745 dirchunk_len = 0;
746 }
747 else if (!skip)
748 {
749 *d++ = *s; // copy next char
750 if (*s != '~' && *s != '.') // and leading "~" and "."
751 {
752 ++dirchunk_len; // only count word chars for the size
753
754 // keep copying chars until we have our preferred length (or
755 // until the above if/else branches move us along)
756 if (dirchunk_len >= trim_len)
757 skip = TRUE;
758 }
759
760 if (has_mbyte)
761 {
762 int l = mb_ptr2len(s);
763
764 while (--l > 0)
765 *d++ = *++s;
766 }
767 }
768 }
769}
770
771/*
772 * Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
773 * It's done in-place.
774 */
775 void
776shorten_dir(char_u *str)
777{
778 shorten_dir_len(str, 1);
779}
780
Bram Moolenaar022f9ef2022-07-02 17:36:31 +0100781/*
782 * Return TRUE if "fname" is a readable file.
783 */
784 int
785file_is_readable(char_u *fname)
786{
787 int fd;
788
789#ifndef O_NONBLOCK
790# define O_NONBLOCK 0
791#endif
792 if (*fname && !mch_isdir(fname)
793 && (fd = mch_open((char *)fname, O_RDONLY | O_NONBLOCK, 0)) >= 0)
794 {
795 close(fd);
796 return TRUE;
797 }
798 return FALSE;
799}
800
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200801#if defined(FEAT_EVAL) || defined(PROTO)
802
803/*
804 * "chdir(dir)" function
805 */
806 void
807f_chdir(typval_T *argvars, typval_T *rettv)
808{
809 char_u *cwd;
810 cdscope_T scope = CDSCOPE_GLOBAL;
811
812 rettv->v_type = VAR_STRING;
813 rettv->vval.v_string = NULL;
814
815 if (argvars[0].v_type != VAR_STRING)
Bram Moolenaarc5809432021-03-27 21:23:30 +0100816 {
Bram Moolenaard816cd92020-02-04 22:23:09 +0100817 // Returning an empty string means it failed.
Bram Moolenaar002bc792020-06-05 22:33:42 +0200818 // No error message, for historic reasons.
Bram Moolenaarc5809432021-03-27 21:23:30 +0100819 if (in_vim9script())
820 (void) check_for_string_arg(argvars, 0);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200821 return;
Bram Moolenaarc5809432021-03-27 21:23:30 +0100822 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200823
824 // Return the current directory
825 cwd = alloc(MAXPATHL);
826 if (cwd != NULL)
827 {
828 if (mch_dirname(cwd, MAXPATHL) != FAIL)
829 {
830#ifdef BACKSLASH_IN_FILENAME
831 slash_adjust(cwd);
832#endif
833 rettv->vval.v_string = vim_strsave(cwd);
834 }
835 vim_free(cwd);
836 }
837
838 if (curwin->w_localdir != NULL)
839 scope = CDSCOPE_WINDOW;
840 else if (curtab->tp_localdir != NULL)
841 scope = CDSCOPE_TABPAGE;
842
843 if (!changedir_func(argvars[0].vval.v_string, TRUE, scope))
844 // Directory change failed
845 VIM_CLEAR(rettv->vval.v_string);
846}
847
848/*
849 * "delete()" function
850 */
851 void
852f_delete(typval_T *argvars, typval_T *rettv)
853{
854 char_u nbuf[NUMBUFLEN];
855 char_u *name;
856 char_u *flags;
857
858 rettv->vval.v_number = -1;
859 if (check_restricted() || check_secure())
860 return;
861
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +0200862 if (in_vim9script()
863 && (check_for_string_arg(argvars, 0) == FAIL
864 || check_for_opt_string_arg(argvars, 1) == FAIL))
865 return;
866
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200867 name = tv_get_string(&argvars[0]);
868 if (name == NULL || *name == NUL)
869 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +0000870 emsg(_(e_invalid_argument));
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200871 return;
872 }
873
874 if (argvars[1].v_type != VAR_UNKNOWN)
875 flags = tv_get_string_buf(&argvars[1], nbuf);
876 else
877 flags = (char_u *)"";
878
879 if (*flags == NUL)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200880 // delete a file
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200881 rettv->vval.v_number = mch_remove(name) == 0 ? 0 : -1;
882 else if (STRCMP(flags, "d") == 0)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200883 // delete an empty directory
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200884 rettv->vval.v_number = mch_rmdir(name) == 0 ? 0 : -1;
885 else if (STRCMP(flags, "rf") == 0)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200886 // delete a directory recursively
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200887 rettv->vval.v_number = delete_recursive(name);
888 else
Bram Moolenaar108010a2021-06-27 22:03:33 +0200889 semsg(_(e_invalid_expression_str), flags);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200890}
891
892/*
893 * "executable()" function
894 */
895 void
896f_executable(typval_T *argvars, typval_T *rettv)
897{
Bram Moolenaar32105ae2021-03-27 18:59:25 +0100898 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100899 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200900
Bram Moolenaar26262f82019-09-04 20:59:15 +0200901 // Check in $PATH and also check directly if there is a directory name.
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100902 rettv->vval.v_number = mch_can_exe(tv_get_string(&argvars[0]), NULL, TRUE);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200903}
904
905/*
906 * "exepath()" function
907 */
908 void
909f_exepath(typval_T *argvars, typval_T *rettv)
910{
911 char_u *p = NULL;
912
Bram Moolenaar32105ae2021-03-27 18:59:25 +0100913 if (in_vim9script() && check_for_nonempty_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100914 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200915 (void)mch_can_exe(tv_get_string(&argvars[0]), &p, TRUE);
916 rettv->v_type = VAR_STRING;
917 rettv->vval.v_string = p;
918}
919
920/*
921 * "filereadable()" function
922 */
923 void
924f_filereadable(typval_T *argvars, typval_T *rettv)
925{
Bram Moolenaar32105ae2021-03-27 18:59:25 +0100926 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100927 return;
Bram Moolenaar4dea2d92022-03-31 11:37:57 +0100928 rettv->vval.v_number = file_is_readable(tv_get_string(&argvars[0]));
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200929}
930
931/*
932 * Return 0 for not writable, 1 for writable file, 2 for a dir which we have
933 * rights to write into.
934 */
935 void
936f_filewritable(typval_T *argvars, typval_T *rettv)
937{
Bram Moolenaar32105ae2021-03-27 18:59:25 +0100938 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100939 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200940 rettv->vval.v_number = filewritable(tv_get_string(&argvars[0]));
941}
942
Bram Moolenaar840d16f2019-09-10 21:27:18 +0200943 static void
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200944findfilendir(
Yee Cheng China7767072023-04-16 20:13:12 +0100945 typval_T *argvars,
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200946 typval_T *rettv,
Yee Cheng China7767072023-04-16 20:13:12 +0100947 int find_what)
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200948{
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200949 char_u *fname;
950 char_u *fresult = NULL;
951 char_u *path = *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path;
952 char_u *p;
953 char_u pathbuf[NUMBUFLEN];
954 int count = 1;
955 int first = TRUE;
956 int error = FALSE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200957
958 rettv->vval.v_string = NULL;
959 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +0200960 if (in_vim9script()
961 && (check_for_nonempty_string_arg(argvars, 0) == FAIL
962 || check_for_opt_string_arg(argvars, 1) == FAIL
963 || (argvars[1].v_type != VAR_UNKNOWN
964 && check_for_opt_number_arg(argvars, 2) == FAIL)))
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100965 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200966
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200967 fname = tv_get_string(&argvars[0]);
968
969 if (argvars[1].v_type != VAR_UNKNOWN)
970 {
971 p = tv_get_string_buf_chk(&argvars[1], pathbuf);
972 if (p == NULL)
973 error = TRUE;
974 else
975 {
976 if (*p != NUL)
977 path = p;
978
979 if (argvars[2].v_type != VAR_UNKNOWN)
980 count = (int)tv_get_number_chk(&argvars[2], &error);
981 }
982 }
983
984 if (count < 0 && rettv_list_alloc(rettv) == FAIL)
985 error = TRUE;
986
987 if (*fname != NUL && !error)
988 {
Bram Moolenaar5145c9a2023-03-11 13:55:53 +0000989 char_u *file_to_find = NULL;
990 char *search_ctx = NULL;
991
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200992 do
993 {
994 if (rettv->v_type == VAR_STRING || rettv->v_type == VAR_LIST)
995 vim_free(fresult);
996 fresult = find_file_in_path_option(first ? fname : NULL,
997 first ? (int)STRLEN(fname) : 0,
998 0, first, path,
999 find_what,
1000 curbuf->b_ffname,
1001 find_what == FINDFILE_DIR
Bram Moolenaar5145c9a2023-03-11 13:55:53 +00001002 ? (char_u *)"" : curbuf->b_p_sua,
1003 &file_to_find, &search_ctx);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001004 first = FALSE;
1005
1006 if (fresult != NULL && rettv->v_type == VAR_LIST)
1007 list_append_string(rettv->vval.v_list, fresult, -1);
1008
1009 } while ((rettv->v_type == VAR_LIST || --count > 0) && fresult != NULL);
Bram Moolenaar5145c9a2023-03-11 13:55:53 +00001010
1011 vim_free(file_to_find);
1012 vim_findfile_cleanup(search_ctx);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001013 }
1014
1015 if (rettv->v_type == VAR_STRING)
1016 rettv->vval.v_string = fresult;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001017}
1018
1019/*
1020 * "finddir({fname}[, {path}[, {count}]])" function
1021 */
1022 void
1023f_finddir(typval_T *argvars, typval_T *rettv)
1024{
1025 findfilendir(argvars, rettv, FINDFILE_DIR);
1026}
1027
1028/*
1029 * "findfile({fname}[, {path}[, {count}]])" function
1030 */
1031 void
1032f_findfile(typval_T *argvars, typval_T *rettv)
1033{
1034 findfilendir(argvars, rettv, FINDFILE_FILE);
1035}
1036
1037/*
1038 * "fnamemodify({fname}, {mods})" function
1039 */
1040 void
1041f_fnamemodify(typval_T *argvars, typval_T *rettv)
1042{
1043 char_u *fname;
1044 char_u *mods;
Mike Williams51024bb2024-05-30 07:46:30 +02001045 size_t usedlen = 0;
Yegappan Lakshmanan00d34592024-12-25 10:20:51 +01001046 size_t len = 0;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001047 char_u *fbuf = NULL;
1048 char_u buf[NUMBUFLEN];
1049
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001050 if (in_vim9script()
1051 && (check_for_string_arg(argvars, 0) == FAIL
1052 || check_for_string_arg(argvars, 1) == FAIL))
Bram Moolenaar7bb4e742020-12-09 12:41:50 +01001053 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001054
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001055 fname = tv_get_string_chk(&argvars[0]);
1056 mods = tv_get_string_buf_chk(&argvars[1], buf);
Bram Moolenaarc5308522020-12-13 12:25:35 +01001057 if (mods == NULL || fname == NULL)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001058 fname = NULL;
Bram Moolenaarc5308522020-12-13 12:25:35 +01001059 else
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001060 {
Yegappan Lakshmanan00d34592024-12-25 10:20:51 +01001061 len = STRLEN(fname);
Bram Moolenaarc5308522020-12-13 12:25:35 +01001062 if (mods != NULL && *mods != NUL)
1063 (void)modify_fname(mods, FALSE, &usedlen, &fname, &fbuf, &len);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001064 }
1065
1066 rettv->v_type = VAR_STRING;
1067 if (fname == NULL)
1068 rettv->vval.v_string = NULL;
1069 else
1070 rettv->vval.v_string = vim_strnsave(fname, len);
1071 vim_free(fbuf);
1072}
1073
1074/*
1075 * "getcwd()" function
1076 *
1077 * Return the current working directory of a window in a tab page.
1078 * First optional argument 'winnr' is the window number or -1 and the second
1079 * optional argument 'tabnr' is the tab page number.
1080 *
1081 * If no arguments are supplied, then return the directory of the current
1082 * window.
1083 * If only 'winnr' is specified and is not -1 or 0 then return the directory of
1084 * the specified window.
1085 * If 'winnr' is 0 then return the directory of the current window.
1086 * If both 'winnr and 'tabnr' are specified and 'winnr' is -1 then return the
1087 * directory of the specified tab page. Otherwise return the directory of the
1088 * specified window in the specified tab page.
1089 * If the window or the tab page doesn't exist then return NULL.
1090 */
1091 void
1092f_getcwd(typval_T *argvars, typval_T *rettv)
1093{
1094 win_T *wp = NULL;
1095 tabpage_T *tp = NULL;
1096 char_u *cwd;
1097 int global = FALSE;
1098
1099 rettv->v_type = VAR_STRING;
1100 rettv->vval.v_string = NULL;
1101
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001102 if (in_vim9script()
1103 && (check_for_opt_number_arg(argvars, 0) == FAIL
1104 || (argvars[0].v_type != VAR_UNKNOWN
1105 && check_for_opt_number_arg(argvars, 1) == FAIL)))
1106 return;
1107
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001108 if (argvars[0].v_type == VAR_NUMBER
1109 && argvars[0].vval.v_number == -1
1110 && argvars[1].v_type == VAR_UNKNOWN)
1111 global = TRUE;
1112 else
1113 wp = find_tabwin(&argvars[0], &argvars[1], &tp);
1114
Bram Moolenaar851c7a62021-11-18 20:47:31 +00001115 if (wp != NULL && wp->w_localdir != NULL
1116 && argvars[0].v_type != VAR_UNKNOWN)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001117 rettv->vval.v_string = vim_strsave(wp->w_localdir);
Bram Moolenaar851c7a62021-11-18 20:47:31 +00001118 else if (tp != NULL && tp->tp_localdir != NULL
1119 && argvars[0].v_type != VAR_UNKNOWN)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001120 rettv->vval.v_string = vim_strsave(tp->tp_localdir);
1121 else if (wp != NULL || tp != NULL || global)
1122 {
Bram Moolenaar851c7a62021-11-18 20:47:31 +00001123 if (globaldir != NULL && argvars[0].v_type != VAR_UNKNOWN)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001124 rettv->vval.v_string = vim_strsave(globaldir);
1125 else
1126 {
1127 cwd = alloc(MAXPATHL);
1128 if (cwd != NULL)
1129 {
1130 if (mch_dirname(cwd, MAXPATHL) != FAIL)
1131 rettv->vval.v_string = vim_strsave(cwd);
1132 vim_free(cwd);
1133 }
1134 }
1135 }
1136#ifdef BACKSLASH_IN_FILENAME
1137 if (rettv->vval.v_string != NULL)
1138 slash_adjust(rettv->vval.v_string);
1139#endif
1140}
1141
1142/*
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001143 * Convert "st" to file permission string.
1144 */
1145 char_u *
1146getfpermst(stat_T *st, char_u *perm)
1147{
1148 char_u flags[] = "rwx";
1149 int i;
1150
1151 for (i = 0; i < 9; i++)
1152 {
1153 if (st->st_mode & (1 << (8 - i)))
1154 perm[i] = flags[i % 3];
1155 else
1156 perm[i] = '-';
1157 }
1158 return perm;
1159}
1160
1161/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001162 * "getfperm({fname})" function
1163 */
1164 void
1165f_getfperm(typval_T *argvars, typval_T *rettv)
1166{
1167 char_u *fname;
1168 stat_T st;
1169 char_u *perm = NULL;
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001170 char_u permbuf[] = "---------";
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001171
Bram Moolenaar32105ae2021-03-27 18:59:25 +01001172 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +01001173 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001174
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001175 fname = tv_get_string(&argvars[0]);
1176
1177 rettv->v_type = VAR_STRING;
1178 if (mch_stat((char *)fname, &st) >= 0)
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001179 perm = vim_strsave(getfpermst(&st, permbuf));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001180 rettv->vval.v_string = perm;
1181}
1182
1183/*
1184 * "getfsize({fname})" function
1185 */
1186 void
1187f_getfsize(typval_T *argvars, typval_T *rettv)
1188{
1189 char_u *fname;
1190 stat_T st;
1191
Bram Moolenaar32105ae2021-03-27 18:59:25 +01001192 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +01001193 return;
1194
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001195 fname = tv_get_string(&argvars[0]);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001196 if (mch_stat((char *)fname, &st) >= 0)
1197 {
1198 if (mch_isdir(fname))
1199 rettv->vval.v_number = 0;
1200 else
1201 {
1202 rettv->vval.v_number = (varnumber_T)st.st_size;
1203
Bram Moolenaar26262f82019-09-04 20:59:15 +02001204 // non-perfect check for overflow
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001205 if ((off_T)rettv->vval.v_number != (off_T)st.st_size)
1206 rettv->vval.v_number = -2;
1207 }
1208 }
1209 else
1210 rettv->vval.v_number = -1;
1211}
1212
1213/*
1214 * "getftime({fname})" function
1215 */
1216 void
1217f_getftime(typval_T *argvars, typval_T *rettv)
1218{
1219 char_u *fname;
1220 stat_T st;
1221
Bram Moolenaar32105ae2021-03-27 18:59:25 +01001222 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +01001223 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001224
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001225 fname = tv_get_string(&argvars[0]);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001226 if (mch_stat((char *)fname, &st) >= 0)
1227 rettv->vval.v_number = (varnumber_T)st.st_mtime;
1228 else
1229 rettv->vval.v_number = -1;
1230}
1231
1232/*
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001233 * Convert "st" to file type string.
1234 */
1235 char_u *
1236getftypest(stat_T *st)
1237{
1238 char *t;
1239
1240 if (S_ISREG(st->st_mode))
1241 t = "file";
1242 else if (S_ISDIR(st->st_mode))
1243 t = "dir";
1244 else if (S_ISLNK(st->st_mode))
1245 t = "link";
1246 else if (S_ISBLK(st->st_mode))
1247 t = "bdev";
1248 else if (S_ISCHR(st->st_mode))
1249 t = "cdev";
1250 else if (S_ISFIFO(st->st_mode))
1251 t = "fifo";
1252 else if (S_ISSOCK(st->st_mode))
1253 t = "socket";
1254 else
1255 t = "other";
1256 return (char_u*)t;
1257}
1258
1259/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001260 * "getftype({fname})" function
1261 */
1262 void
1263f_getftype(typval_T *argvars, typval_T *rettv)
1264{
1265 char_u *fname;
1266 stat_T st;
1267 char_u *type = NULL;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001268
Bram Moolenaar32105ae2021-03-27 18:59:25 +01001269 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +01001270 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001271
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001272 fname = tv_get_string(&argvars[0]);
1273
1274 rettv->v_type = VAR_STRING;
1275 if (mch_lstat((char *)fname, &st) >= 0)
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001276 type = vim_strsave(getftypest(&st));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001277 rettv->vval.v_string = type;
1278}
1279
1280/*
1281 * "glob()" function
1282 */
1283 void
1284f_glob(typval_T *argvars, typval_T *rettv)
1285{
1286 int options = WILD_SILENT|WILD_USE_NL;
1287 expand_T xpc;
1288 int error = FALSE;
1289
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02001290 if (in_vim9script()
1291 && (check_for_string_arg(argvars, 0) == FAIL
1292 || check_for_opt_bool_arg(argvars, 1) == FAIL
1293 || (argvars[1].v_type != VAR_UNKNOWN
1294 && (check_for_opt_bool_arg(argvars, 2) == FAIL
1295 || (argvars[2].v_type != VAR_UNKNOWN
1296 && check_for_opt_bool_arg(argvars, 3) == FAIL)))))
1297 return;
1298
Bram Moolenaar26262f82019-09-04 20:59:15 +02001299 // When the optional second argument is non-zero, don't remove matches
1300 // for 'wildignore' and don't put matches for 'suffixes' at the end.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001301 rettv->v_type = VAR_STRING;
1302 if (argvars[1].v_type != VAR_UNKNOWN)
1303 {
Bram Moolenaar5892ea12020-09-02 21:53:11 +02001304 if (tv_get_bool_chk(&argvars[1], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001305 options |= WILD_KEEP_ALL;
1306 if (argvars[2].v_type != VAR_UNKNOWN)
1307 {
Bram Moolenaar5892ea12020-09-02 21:53:11 +02001308 if (tv_get_bool_chk(&argvars[2], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001309 rettv_list_set(rettv, NULL);
1310 if (argvars[3].v_type != VAR_UNKNOWN
Bram Moolenaar5892ea12020-09-02 21:53:11 +02001311 && tv_get_bool_chk(&argvars[3], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001312 options |= WILD_ALLLINKS;
1313 }
1314 }
1315 if (!error)
1316 {
1317 ExpandInit(&xpc);
1318 xpc.xp_context = EXPAND_FILES;
1319 if (p_wic)
1320 options += WILD_ICASE;
1321 if (rettv->v_type == VAR_STRING)
1322 rettv->vval.v_string = ExpandOne(&xpc, tv_get_string(&argvars[0]),
1323 NULL, options, WILD_ALL);
Bram Moolenaar8088ae92022-06-20 11:38:17 +01001324 else if (rettv_list_alloc(rettv) == OK)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001325 {
1326 int i;
1327
1328 ExpandOne(&xpc, tv_get_string(&argvars[0]),
1329 NULL, options, WILD_ALL_KEEP);
1330 for (i = 0; i < xpc.xp_numfiles; i++)
1331 list_append_string(rettv->vval.v_list, xpc.xp_files[i], -1);
1332
1333 ExpandCleanup(&xpc);
1334 }
1335 }
1336 else
1337 rettv->vval.v_string = NULL;
1338}
1339
1340/*
1341 * "glob2regpat()" function
1342 */
1343 void
1344f_glob2regpat(typval_T *argvars, typval_T *rettv)
1345{
Bram Moolenaar3cfa5b12021-06-06 14:14:39 +02001346 char_u buf[NUMBUFLEN];
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001347 char_u *pat;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001348
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001349 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
1350 return;
1351
1352 pat = tv_get_string_buf_chk_strict(&argvars[0], buf, in_vim9script());
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001353 rettv->v_type = VAR_STRING;
1354 rettv->vval.v_string = (pat == NULL)
1355 ? NULL : file_pat_to_reg_pat(pat, NULL, NULL, FALSE);
1356}
1357
1358/*
1359 * "globpath()" function
1360 */
1361 void
1362f_globpath(typval_T *argvars, typval_T *rettv)
1363{
1364 int flags = WILD_IGNORE_COMPLETESLASH;
1365 char_u buf1[NUMBUFLEN];
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02001366 char_u *file;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001367 int error = FALSE;
1368 garray_T ga;
1369 int i;
1370
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02001371 if (in_vim9script()
1372 && (check_for_string_arg(argvars, 0) == FAIL
1373 || check_for_string_arg(argvars, 1) == FAIL
1374 || check_for_opt_bool_arg(argvars, 2) == FAIL
1375 || (argvars[2].v_type != VAR_UNKNOWN
1376 && (check_for_opt_bool_arg(argvars, 3) == FAIL
1377 || (argvars[3].v_type != VAR_UNKNOWN
1378 && check_for_opt_bool_arg(argvars, 4) == FAIL)))))
1379 return;
1380
1381 file = tv_get_string_buf_chk(&argvars[1], buf1);
1382
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001383 // When the optional second argument is non-zero, don't remove matches
1384 // for 'wildignore' and don't put matches for 'suffixes' at the end.
1385 rettv->v_type = VAR_STRING;
1386 if (argvars[2].v_type != VAR_UNKNOWN)
1387 {
Bram Moolenaarf966ce52020-09-02 21:57:07 +02001388 if (tv_get_bool_chk(&argvars[2], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001389 flags |= WILD_KEEP_ALL;
1390 if (argvars[3].v_type != VAR_UNKNOWN)
1391 {
Bram Moolenaarf966ce52020-09-02 21:57:07 +02001392 if (tv_get_bool_chk(&argvars[3], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001393 rettv_list_set(rettv, NULL);
1394 if (argvars[4].v_type != VAR_UNKNOWN
Bram Moolenaarf966ce52020-09-02 21:57:07 +02001395 && tv_get_bool_chk(&argvars[4], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001396 flags |= WILD_ALLLINKS;
1397 }
1398 }
1399 if (file != NULL && !error)
1400 {
Bram Moolenaar04935fb2022-01-08 16:19:22 +00001401 ga_init2(&ga, sizeof(char_u *), 10);
zeertzjq3770f4c2023-01-22 18:38:51 +00001402 globpath(tv_get_string(&argvars[0]), file, &ga, flags, FALSE);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001403 if (rettv->v_type == VAR_STRING)
1404 rettv->vval.v_string = ga_concat_strings(&ga, "\n");
Bram Moolenaar8088ae92022-06-20 11:38:17 +01001405 else if (rettv_list_alloc(rettv) == OK)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001406 for (i = 0; i < ga.ga_len; ++i)
1407 list_append_string(rettv->vval.v_list,
1408 ((char_u **)(ga.ga_data))[i], -1);
1409 ga_clear_strings(&ga);
1410 }
1411 else
1412 rettv->vval.v_string = NULL;
1413}
1414
1415/*
1416 * "isdirectory()" function
1417 */
1418 void
1419f_isdirectory(typval_T *argvars, typval_T *rettv)
1420{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001421 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
1422 return;
1423
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001424 rettv->vval.v_number = mch_isdir(tv_get_string(&argvars[0]));
1425}
1426
1427/*
LemonBoydca1d402022-04-28 15:26:33 +01001428 * "isabsolutepath()" function
1429 */
1430 void
1431f_isabsolutepath(typval_T *argvars, typval_T *rettv)
1432{
1433 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
1434 return;
1435
1436 rettv->vval.v_number = mch_isFullName(tv_get_string_strict(&argvars[0]));
1437}
1438
1439/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001440 * Create the directory in which "dir" is located, and higher levels when
1441 * needed.
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001442 * Set "created" to the full name of the first created directory. It will be
1443 * NULL until that happens.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001444 * Return OK or FAIL.
1445 */
1446 static int
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001447mkdir_recurse(char_u *dir, int prot, char_u **created)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001448{
1449 char_u *p;
1450 char_u *updir;
1451 int r = FAIL;
1452
Bram Moolenaar26262f82019-09-04 20:59:15 +02001453 // Get end of directory name in "dir".
1454 // We're done when it's "/" or "c:/".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001455 p = gettail_sep(dir);
1456 if (p <= get_past_head(dir))
1457 return OK;
1458
Bram Moolenaar26262f82019-09-04 20:59:15 +02001459 // If the directory exists we're done. Otherwise: create it.
Bram Moolenaar71ccd032020-06-12 22:59:11 +02001460 updir = vim_strnsave(dir, p - dir);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001461 if (updir == NULL)
1462 return FAIL;
1463 if (mch_isdir(updir))
1464 r = OK;
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001465 else if (mkdir_recurse(updir, prot, created) == OK)
1466 {
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001467 r = vim_mkdir_emsg(updir, prot);
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001468 if (r == OK && created != NULL && *created == NULL)
1469 *created = FullName_save(updir, FALSE);
1470 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001471 vim_free(updir);
1472 return r;
1473}
1474
1475/*
1476 * "mkdir()" function
1477 */
1478 void
1479f_mkdir(typval_T *argvars, typval_T *rettv)
1480{
1481 char_u *dir;
1482 char_u buf[NUMBUFLEN];
1483 int prot = 0755;
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001484 int defer = FALSE;
1485 int defer_recurse = FALSE;
1486 char_u *created = NULL;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001487
1488 rettv->vval.v_number = FAIL;
1489 if (check_restricted() || check_secure())
1490 return;
1491
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001492 if (in_vim9script()
1493 && (check_for_nonempty_string_arg(argvars, 0) == FAIL
1494 || check_for_opt_string_arg(argvars, 1) == FAIL
1495 || (argvars[1].v_type != VAR_UNKNOWN
1496 && check_for_opt_number_arg(argvars, 2) == FAIL)))
1497 return;
1498
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001499 dir = tv_get_string_buf(&argvars[0], buf);
1500 if (*dir == NUL)
1501 return;
1502
1503 if (*gettail(dir) == NUL)
Bram Moolenaar26262f82019-09-04 20:59:15 +02001504 // remove trailing slashes
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001505 *gettail_sep(dir) = NUL;
1506
1507 if (argvars[1].v_type != VAR_UNKNOWN)
1508 {
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001509 char_u *arg2;
1510
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001511 if (argvars[2].v_type != VAR_UNKNOWN)
1512 {
1513 prot = (int)tv_get_number_chk(&argvars[2], NULL);
1514 if (prot == -1)
1515 return;
1516 }
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001517 arg2 = tv_get_string(&argvars[1]);
1518 defer = vim_strchr(arg2, 'D') != NULL;
1519 defer_recurse = vim_strchr(arg2, 'R') != NULL;
1520 if ((defer || defer_recurse) && !can_add_defer())
1521 return;
1522
1523 if (vim_strchr(arg2, 'p') != NULL)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001524 {
1525 if (mch_isdir(dir))
1526 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001527 // With the "p" flag it's OK if the dir already exists.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001528 rettv->vval.v_number = OK;
1529 return;
1530 }
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001531 mkdir_recurse(dir, prot, defer || defer_recurse ? &created : NULL);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001532 }
1533 }
1534 rettv->vval.v_number = vim_mkdir_emsg(dir, prot);
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001535
1536 // Handle "D" and "R": deferred deletion of the created directory.
1537 if (rettv->vval.v_number == OK
1538 && created == NULL && (defer || defer_recurse))
1539 created = FullName_save(dir, FALSE);
1540 if (created != NULL)
1541 {
1542 typval_T tv[2];
1543
1544 tv[0].v_type = VAR_STRING;
1545 tv[0].v_lock = 0;
1546 tv[0].vval.v_string = created;
1547 tv[1].v_type = VAR_STRING;
1548 tv[1].v_lock = 0;
Christian Brabandt6cc30272024-12-13 17:54:33 +01001549 tv[1].vval.v_string = vim_strsave(
1550 (char_u *)(defer_recurse ? "rf" : "d"));
Bram Moolenaar6f14da12022-09-07 21:30:44 +01001551 if (tv[0].vval.v_string == NULL || tv[1].vval.v_string == NULL
1552 || add_defer((char_u *)"delete", 2, tv) == FAIL)
1553 {
1554 vim_free(tv[0].vval.v_string);
1555 vim_free(tv[1].vval.v_string);
1556 }
1557 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001558}
1559
1560/*
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02001561 * "pathshorten()" function
1562 */
1563 void
1564f_pathshorten(typval_T *argvars, typval_T *rettv)
1565{
1566 char_u *p;
Bram Moolenaar6a33ef02020-09-25 22:42:48 +02001567 int trim_len = 1;
1568
Yegappan Lakshmanan1a71d312021-07-15 12:49:58 +02001569 if (in_vim9script()
1570 && (check_for_string_arg(argvars, 0) == FAIL
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02001571 || check_for_opt_number_arg(argvars, 1) == FAIL))
Yegappan Lakshmanan1a71d312021-07-15 12:49:58 +02001572 return;
1573
Bram Moolenaar6a33ef02020-09-25 22:42:48 +02001574 if (argvars[1].v_type != VAR_UNKNOWN)
1575 {
1576 trim_len = (int)tv_get_number(&argvars[1]);
1577 if (trim_len < 1)
1578 trim_len = 1;
1579 }
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02001580
1581 rettv->v_type = VAR_STRING;
1582 p = tv_get_string_chk(&argvars[0]);
Bram Moolenaar6a33ef02020-09-25 22:42:48 +02001583
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02001584 if (p == NULL)
1585 rettv->vval.v_string = NULL;
1586 else
1587 {
1588 p = vim_strsave(p);
1589 rettv->vval.v_string = p;
1590 if (p != NULL)
Bram Moolenaar6a33ef02020-09-25 22:42:48 +02001591 shorten_dir_len(p, trim_len);
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02001592 }
1593}
1594
1595/*
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001596 * Common code for readdir_checkitem() and readdirex_checkitem().
1597 * Either "name" or "dict" is NULL.
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001598 */
1599 static int
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001600checkitem_common(void *context, char_u *name, dict_T *dict)
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001601{
1602 typval_T *expr = (typval_T *)context;
1603 typval_T save_val;
1604 typval_T rettv;
1605 typval_T argv[2];
1606 int retval = 0;
1607 int error = FALSE;
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001608
1609 prepare_vimvar(VV_VAL, &save_val);
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001610 if (name != NULL)
1611 {
1612 set_vim_var_string(VV_VAL, name, -1);
1613 argv[0].v_type = VAR_STRING;
1614 argv[0].vval.v_string = name;
1615 }
1616 else
1617 {
1618 set_vim_var_dict(VV_VAL, dict);
1619 argv[0].v_type = VAR_DICT;
1620 argv[0].vval.v_dict = dict;
1621 }
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001622
zeertzjqad0c4422023-08-17 22:15:47 +02001623 if (eval_expr_typval(expr, FALSE, argv, 1, NULL, &rettv) == FAIL)
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001624 goto theend;
1625
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001626 // We want to use -1, but also true/false should be allowed.
1627 if (rettv.v_type == VAR_SPECIAL || rettv.v_type == VAR_BOOL)
1628 {
1629 rettv.v_type = VAR_NUMBER;
1630 rettv.vval.v_number = rettv.vval.v_number == VVAL_TRUE;
1631 }
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001632 retval = tv_get_number_chk(&rettv, &error);
1633 if (error)
1634 retval = -1;
1635 clear_tv(&rettv);
1636
1637theend:
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001638 if (name != NULL)
1639 set_vim_var_string(VV_VAL, NULL, 0);
1640 else
1641 set_vim_var_dict(VV_VAL, NULL);
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001642 restore_vimvar(VV_VAL, &save_val);
1643 return retval;
1644}
1645
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001646/*
1647 * Evaluate "expr" (= "context") for readdir().
1648 */
1649 static int
1650readdir_checkitem(void *context, void *item)
1651{
1652 char_u *name = (char_u *)item;
1653
1654 return checkitem_common(context, name, NULL);
1655}
1656
Bram Moolenaard83392a2022-09-01 12:22:46 +01001657/*
1658 * Process the keys in the Dict argument to the readdir() and readdirex()
1659 * functions. Assumes the Dict argument is the 3rd argument.
1660 */
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001661 static int
Bram Moolenaard83392a2022-09-01 12:22:46 +01001662readdirex_dict_arg(typval_T *argvars, int *cmp)
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001663{
1664 char_u *compare;
1665
Bram Moolenaard83392a2022-09-01 12:22:46 +01001666 if (check_for_nonnull_dict_arg(argvars, 2) == FAIL)
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001667 return FAIL;
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001668
Bram Moolenaard83392a2022-09-01 12:22:46 +01001669 if (dict_has_key(argvars[2].vval.v_dict, "sort"))
1670 compare = dict_get_string(argvars[2].vval.v_dict, "sort", FALSE);
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001671 else
1672 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00001673 semsg(_(e_dictionary_key_str_required), "sort");
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001674 return FAIL;
1675 }
1676
1677 if (STRCMP(compare, (char_u *) "none") == 0)
1678 *cmp = READDIR_SORT_NONE;
1679 else if (STRCMP(compare, (char_u *) "case") == 0)
1680 *cmp = READDIR_SORT_BYTE;
1681 else if (STRCMP(compare, (char_u *) "icase") == 0)
1682 *cmp = READDIR_SORT_IC;
1683 else if (STRCMP(compare, (char_u *) "collate") == 0)
1684 *cmp = READDIR_SORT_COLLATE;
1685 return OK;
1686}
1687
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001688/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001689 * "readdir()" function
1690 */
1691 void
1692f_readdir(typval_T *argvars, typval_T *rettv)
1693{
1694 typval_T *expr;
1695 int ret;
1696 char_u *path;
1697 char_u *p;
1698 garray_T ga;
1699 int i;
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01001700 int sort = READDIR_SORT_BYTE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001701
1702 if (rettv_list_alloc(rettv) == FAIL)
1703 return;
Yegappan Lakshmanan5bca9062021-07-24 21:33:26 +02001704
1705 if (in_vim9script()
1706 && (check_for_string_arg(argvars, 0) == FAIL
1707 || (argvars[1].v_type != VAR_UNKNOWN
1708 && check_for_opt_dict_arg(argvars, 2) == FAIL)))
1709 return;
1710
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001711 path = tv_get_string(&argvars[0]);
1712 expr = &argvars[1];
1713
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001714 if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN &&
Bram Moolenaard83392a2022-09-01 12:22:46 +01001715 readdirex_dict_arg(argvars, &sort) == FAIL)
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001716 return;
1717
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001718 ret = readdir_core(&ga, path, FALSE, (void *)expr,
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001719 (expr->v_type == VAR_UNKNOWN) ? NULL : readdir_checkitem, sort);
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001720 if (ret == OK)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001721 {
1722 for (i = 0; i < ga.ga_len; i++)
1723 {
1724 p = ((char_u **)ga.ga_data)[i];
1725 list_append_string(rettv->vval.v_list, p, -1);
1726 }
1727 }
1728 ga_clear_strings(&ga);
1729}
1730
1731/*
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001732 * Evaluate "expr" (= "context") for readdirex().
1733 */
1734 static int
1735readdirex_checkitem(void *context, void *item)
1736{
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001737 dict_T *dict = (dict_T*)item;
1738
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001739 return checkitem_common(context, NULL, dict);
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001740}
1741
1742/*
1743 * "readdirex()" function
1744 */
1745 void
1746f_readdirex(typval_T *argvars, typval_T *rettv)
1747{
1748 typval_T *expr;
1749 int ret;
1750 char_u *path;
1751 garray_T ga;
1752 int i;
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01001753 int sort = READDIR_SORT_BYTE;
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001754
1755 if (rettv_list_alloc(rettv) == FAIL)
1756 return;
Yegappan Lakshmanan5bca9062021-07-24 21:33:26 +02001757
1758 if (in_vim9script()
1759 && (check_for_string_arg(argvars, 0) == FAIL
1760 || (argvars[1].v_type != VAR_UNKNOWN
1761 && check_for_opt_dict_arg(argvars, 2) == FAIL)))
1762 return;
1763
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001764 path = tv_get_string(&argvars[0]);
1765 expr = &argvars[1];
1766
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001767 if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN &&
Bram Moolenaard83392a2022-09-01 12:22:46 +01001768 readdirex_dict_arg(argvars, &sort) == FAIL)
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001769 return;
1770
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001771 ret = readdir_core(&ga, path, TRUE, (void *)expr,
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001772 (expr->v_type == VAR_UNKNOWN) ? NULL : readdirex_checkitem, sort);
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001773 if (ret == OK)
1774 {
1775 for (i = 0; i < ga.ga_len; i++)
1776 {
1777 dict_T *dict = ((dict_T**)ga.ga_data)[i];
1778 list_append_dict(rettv->vval.v_list, dict);
1779 dict_unref(dict);
1780 }
1781 }
1782 ga_clear(&ga);
1783}
1784
1785/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001786 * "readfile()" function
1787 */
Bram Moolenaarc423ad72021-01-13 20:38:03 +01001788 static void
1789read_file_or_blob(typval_T *argvars, typval_T *rettv, int always_blob)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001790{
1791 int binary = FALSE;
Bram Moolenaarc423ad72021-01-13 20:38:03 +01001792 int blob = always_blob;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001793 int failed = FALSE;
1794 char_u *fname;
1795 FILE *fd;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001796 char_u buf[(IOSIZE/256)*256]; // rounded to avoid odd + 1
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001797 int io_size = sizeof(buf);
Bram Moolenaar26262f82019-09-04 20:59:15 +02001798 int readlen; // size of last fread()
1799 char_u *prev = NULL; // previously read bytes, if any
1800 long prevlen = 0; // length of data in prev
1801 long prevsize = 0; // size of prev buffer
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001802 long maxline = MAXLNUM;
1803 long cnt = 0;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001804 char_u *p; // position in buf
1805 char_u *start; // start of current line
K.Takata11df3ae2022-10-19 14:02:40 +01001806 off_T offset = 0;
1807 off_T size = -1;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001808
1809 if (argvars[1].v_type != VAR_UNKNOWN)
1810 {
K.Takata11df3ae2022-10-19 14:02:40 +01001811 if (always_blob)
1812 {
1813 offset = (off_T)tv_get_number(&argvars[1]);
1814 if (argvars[2].v_type != VAR_UNKNOWN)
1815 size = (off_T)tv_get_number(&argvars[2]);
1816 }
1817 else
1818 {
1819 if (STRCMP(tv_get_string(&argvars[1]), "b") == 0)
1820 binary = TRUE;
1821 if (STRCMP(tv_get_string(&argvars[1]), "B") == 0)
1822 blob = TRUE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001823
K.Takata11df3ae2022-10-19 14:02:40 +01001824 if (argvars[2].v_type != VAR_UNKNOWN)
1825 maxline = (long)tv_get_number(&argvars[2]);
1826 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001827 }
1828
Bram Moolenaar15352dc2020-04-06 21:12:42 +02001829 if ((blob ? rettv_blob_alloc(rettv) : rettv_list_alloc(rettv)) == FAIL)
1830 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001831
Bram Moolenaar26262f82019-09-04 20:59:15 +02001832 // Always open the file in binary mode, library functions have a mind of
1833 // their own about CR-LF conversion.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001834 fname = tv_get_string(&argvars[0]);
Bram Moolenaar15352dc2020-04-06 21:12:42 +02001835
1836 if (mch_isdir(fname))
1837 {
Bram Moolenaar4dea2d92022-03-31 11:37:57 +01001838 semsg(_(e_str_is_directory), fname);
Bram Moolenaar15352dc2020-04-06 21:12:42 +02001839 return;
1840 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001841 if (*fname == NUL || (fd = mch_fopen((char *)fname, READBIN)) == NULL)
1842 {
K.Takata11df3ae2022-10-19 14:02:40 +01001843 semsg(_(e_cant_open_file_str),
1844 *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001845 return;
1846 }
1847
1848 if (blob)
1849 {
K.Takata11df3ae2022-10-19 14:02:40 +01001850 if (read_blob(fd, rettv, offset, size) == FAIL)
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00001851 semsg(_(e_cant_read_file_str), fname);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001852 fclose(fd);
1853 return;
1854 }
1855
1856 while (cnt < maxline || maxline < 0)
1857 {
1858 readlen = (int)fread(buf, 1, io_size, fd);
1859
Bram Moolenaar26262f82019-09-04 20:59:15 +02001860 // This for loop processes what was read, but is also entered at end
1861 // of file so that either:
1862 // - an incomplete line gets written
1863 // - a "binary" file gets an empty line at the end if it ends in a
1864 // newline.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001865 for (p = buf, start = buf;
1866 p < buf + readlen || (readlen <= 0 && (prevlen > 0 || binary));
1867 ++p)
1868 {
Dominique Pellef5d639a2022-01-12 15:24:40 +00001869 if (readlen <= 0 || *p == '\n')
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001870 {
1871 listitem_T *li;
1872 char_u *s = NULL;
1873 long_u len = p - start;
1874
Bram Moolenaar26262f82019-09-04 20:59:15 +02001875 // Finished a line. Remove CRs before NL.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001876 if (readlen > 0 && !binary)
1877 {
1878 while (len > 0 && start[len - 1] == '\r')
1879 --len;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001880 // removal may cross back to the "prev" string
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001881 if (len == 0)
1882 while (prevlen > 0 && prev[prevlen - 1] == '\r')
1883 --prevlen;
1884 }
1885 if (prevlen == 0)
Bram Moolenaar71ccd032020-06-12 22:59:11 +02001886 s = vim_strnsave(start, len);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001887 else
1888 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001889 // Change "prev" buffer to be the right size. This way
1890 // the bytes are only copied once, and very long lines are
1891 // allocated only once.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001892 if ((s = vim_realloc(prev, prevlen + len + 1)) != NULL)
1893 {
1894 mch_memmove(s + prevlen, start, len);
1895 s[prevlen + len] = NUL;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001896 prev = NULL; // the list will own the string
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001897 prevlen = prevsize = 0;
1898 }
1899 }
1900 if (s == NULL)
1901 {
1902 do_outofmem_msg((long_u) prevlen + len + 1);
1903 failed = TRUE;
1904 break;
1905 }
1906
1907 if ((li = listitem_alloc()) == NULL)
1908 {
1909 vim_free(s);
1910 failed = TRUE;
1911 break;
1912 }
1913 li->li_tv.v_type = VAR_STRING;
1914 li->li_tv.v_lock = 0;
1915 li->li_tv.vval.v_string = s;
1916 list_append(rettv->vval.v_list, li);
1917
Bram Moolenaar26262f82019-09-04 20:59:15 +02001918 start = p + 1; // step over newline
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001919 if ((++cnt >= maxline && maxline >= 0) || readlen <= 0)
1920 break;
1921 }
1922 else if (*p == NUL)
1923 *p = '\n';
Bram Moolenaar26262f82019-09-04 20:59:15 +02001924 // Check for utf8 "bom"; U+FEFF is encoded as EF BB BF. Do this
1925 // when finding the BF and check the previous two bytes.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001926 else if (*p == 0xbf && enc_utf8 && !binary)
1927 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001928 // Find the two bytes before the 0xbf. If p is at buf, or buf
1929 // + 1, these may be in the "prev" string.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001930 char_u back1 = p >= buf + 1 ? p[-1]
1931 : prevlen >= 1 ? prev[prevlen - 1] : NUL;
1932 char_u back2 = p >= buf + 2 ? p[-2]
1933 : p == buf + 1 && prevlen >= 1 ? prev[prevlen - 1]
1934 : prevlen >= 2 ? prev[prevlen - 2] : NUL;
1935
1936 if (back2 == 0xef && back1 == 0xbb)
1937 {
1938 char_u *dest = p - 2;
1939
Bram Moolenaar26262f82019-09-04 20:59:15 +02001940 // Usually a BOM is at the beginning of a file, and so at
1941 // the beginning of a line; then we can just step over it.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001942 if (start == dest)
1943 start = p + 1;
1944 else
1945 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001946 // have to shuffle buf to close gap
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001947 int adjust_prevlen = 0;
1948
1949 if (dest < buf)
1950 {
Bram Moolenaarc423ad72021-01-13 20:38:03 +01001951 // must be 1 or 2
1952 adjust_prevlen = (int)(buf - dest);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001953 dest = buf;
1954 }
1955 if (readlen > p - buf + 1)
1956 mch_memmove(dest, p + 1, readlen - (p - buf) - 1);
1957 readlen -= 3 - adjust_prevlen;
1958 prevlen -= adjust_prevlen;
1959 p = dest - 1;
1960 }
1961 }
1962 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02001963 } // for
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001964
1965 if (failed || (cnt >= maxline && maxline >= 0) || readlen <= 0)
1966 break;
1967 if (start < p)
1968 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001969 // There's part of a line in buf, store it in "prev".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001970 if (p - start + prevlen >= prevsize)
1971 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001972 // need bigger "prev" buffer
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001973 char_u *newprev;
1974
Bram Moolenaar26262f82019-09-04 20:59:15 +02001975 // A common use case is ordinary text files and "prev" gets a
1976 // fragment of a line, so the first allocation is made
1977 // small, to avoid repeatedly 'allocing' large and
1978 // 'reallocing' small.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001979 if (prevsize == 0)
1980 prevsize = (long)(p - start);
1981 else
1982 {
1983 long grow50pc = (prevsize * 3) / 2;
1984 long growmin = (long)((p - start) * 2 + prevlen);
1985 prevsize = grow50pc > growmin ? grow50pc : growmin;
1986 }
1987 newprev = vim_realloc(prev, prevsize);
1988 if (newprev == NULL)
1989 {
1990 do_outofmem_msg((long_u)prevsize);
1991 failed = TRUE;
1992 break;
1993 }
1994 prev = newprev;
1995 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02001996 // Add the line part to end of "prev".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001997 mch_memmove(prev + prevlen, start, p - start);
1998 prevlen += (long)(p - start);
1999 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02002000 } // while
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002001
Bram Moolenaar26262f82019-09-04 20:59:15 +02002002 // For a negative line count use only the lines at the end of the file,
2003 // free the rest.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002004 if (!failed && maxline < 0)
2005 while (cnt > -maxline)
2006 {
2007 listitem_remove(rettv->vval.v_list, rettv->vval.v_list->lv_first);
2008 --cnt;
2009 }
2010
2011 if (failed)
2012 {
2013 // an empty list is returned on error
2014 list_free(rettv->vval.v_list);
2015 rettv_list_alloc(rettv);
2016 }
2017
2018 vim_free(prev);
2019 fclose(fd);
2020}
2021
2022/*
Bram Moolenaarc423ad72021-01-13 20:38:03 +01002023 * "readblob()" function
2024 */
2025 void
2026f_readblob(typval_T *argvars, typval_T *rettv)
2027{
K.Takata11df3ae2022-10-19 14:02:40 +01002028 if (in_vim9script()
2029 && (check_for_string_arg(argvars, 0) == FAIL
2030 || check_for_opt_number_arg(argvars, 1) == FAIL
2031 || (argvars[1].v_type != VAR_UNKNOWN
2032 && check_for_opt_number_arg(argvars, 2) == FAIL)))
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02002033 return;
2034
Bram Moolenaarc423ad72021-01-13 20:38:03 +01002035 read_file_or_blob(argvars, rettv, TRUE);
2036}
2037
2038/*
2039 * "readfile()" function
2040 */
2041 void
2042f_readfile(typval_T *argvars, typval_T *rettv)
2043{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02002044 if (in_vim9script()
2045 && (check_for_nonempty_string_arg(argvars, 0) == FAIL
2046 || check_for_opt_string_arg(argvars, 1) == FAIL
2047 || (argvars[1].v_type != VAR_UNKNOWN
2048 && check_for_opt_number_arg(argvars, 2) == FAIL)))
2049 return;
2050
Bram Moolenaarc423ad72021-01-13 20:38:03 +01002051 read_file_or_blob(argvars, rettv, FALSE);
2052}
2053
2054/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002055 * "resolve()" function
2056 */
2057 void
2058f_resolve(typval_T *argvars, typval_T *rettv)
2059{
2060 char_u *p;
2061#ifdef HAVE_READLINK
2062 char_u *buf = NULL;
2063#endif
2064
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02002065 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
2066 return;
2067
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002068 p = tv_get_string(&argvars[0]);
2069#ifdef FEAT_SHORTCUT
2070 {
2071 char_u *v = NULL;
2072
2073 v = mch_resolve_path(p, TRUE);
2074 if (v != NULL)
2075 rettv->vval.v_string = v;
2076 else
2077 rettv->vval.v_string = vim_strsave(p);
2078 }
2079#else
2080# ifdef HAVE_READLINK
2081 {
2082 char_u *cpy;
Christian Brabandt6cc30272024-12-13 17:54:33 +01002083 int len;
2084 char_u *remain = NULL;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002085 char_u *q;
2086 int is_relative_to_current = FALSE;
2087 int has_trailing_pathsep = FALSE;
2088 int limit = 100;
2089
Christian Brabandt6cc30272024-12-13 17:54:33 +01002090 p = vim_strsave(p);
Bram Moolenaar70188f52019-12-23 18:18:52 +01002091 if (p == NULL)
2092 goto fail;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002093 if (p[0] == '.' && (vim_ispathsep(p[1])
2094 || (p[1] == '.' && (vim_ispathsep(p[2])))))
2095 is_relative_to_current = TRUE;
2096
Christian Brabandt6cc30272024-12-13 17:54:33 +01002097 len = STRLEN(p);
2098 if (len > 1 && after_pathsep(p, p + len))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002099 {
2100 has_trailing_pathsep = TRUE;
Christian Brabandt6cc30272024-12-13 17:54:33 +01002101 p[len - 1] = NUL; // the trailing slash breaks readlink()
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002102 }
2103
2104 q = getnextcomp(p);
2105 if (*q != NUL)
2106 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002107 // Separate the first path component in "p", and keep the
2108 // remainder (beginning with the path separator).
Christian Brabandt6cc30272024-12-13 17:54:33 +01002109 remain = vim_strsave(q - 1);
2110 q[-1] = NUL;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002111 }
2112
2113 buf = alloc(MAXPATHL + 1);
2114 if (buf == NULL)
Christian Brabandt6cc30272024-12-13 17:54:33 +01002115 {
2116 vim_free(p);
2117 vim_free(remain);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002118 goto fail;
Christian Brabandt6cc30272024-12-13 17:54:33 +01002119 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002120
2121 for (;;)
2122 {
2123 for (;;)
2124 {
Christian Brabandt6cc30272024-12-13 17:54:33 +01002125 len = readlink((char *)p, (char *)buf, MAXPATHL);
2126 if (len <= 0)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002127 break;
Christian Brabandt6cc30272024-12-13 17:54:33 +01002128 buf[len] = NUL;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002129
2130 if (limit-- == 0)
2131 {
Christian Brabandt6cc30272024-12-13 17:54:33 +01002132 vim_free(p);
2133 vim_free(remain);
Bram Moolenaara6f79292022-01-04 21:30:47 +00002134 emsg(_(e_too_many_symbolic_links_cycle));
Christian Brabandt6cc30272024-12-13 17:54:33 +01002135 rettv->vval.v_string = NULL;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002136 goto fail;
2137 }
2138
Bram Moolenaar26262f82019-09-04 20:59:15 +02002139 // Ensure that the result will have a trailing path separator
2140 // if the argument has one.
Christian Brabandt6cc30272024-12-13 17:54:33 +01002141 if (remain == NULL && has_trailing_pathsep)
2142 add_pathsep(buf);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002143
Bram Moolenaar26262f82019-09-04 20:59:15 +02002144 // Separate the first path component in the link value and
2145 // concatenate the remainders.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002146 q = getnextcomp(vim_ispathsep(*buf) ? buf + 1 : buf);
2147 if (*q != NUL)
2148 {
2149 if (remain == NULL)
Christian Brabandt6cc30272024-12-13 17:54:33 +01002150 remain = vim_strsave(q - 1);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002151 else
2152 {
Christian Brabandt6cc30272024-12-13 17:54:33 +01002153 cpy = concat_str(q - 1, remain);
2154 if (cpy != NULL)
2155 {
2156 vim_free(remain);
2157 remain = cpy;
2158 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002159 }
Christian Brabandt6cc30272024-12-13 17:54:33 +01002160 q[-1] = NUL;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002161 }
2162
2163 q = gettail(p);
2164 if (q > p && *q == NUL)
2165 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002166 // Ignore trailing path separator.
Christian Brabandt6cc30272024-12-13 17:54:33 +01002167 p[q - p - 1] = NUL;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002168 q = gettail(p);
2169 }
2170 if (q > p && !mch_isFullName(buf))
2171 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002172 // symlink is relative to directory of argument
Christian Brabandt6cc30272024-12-13 17:54:33 +01002173 cpy = alloc(STRLEN(p) + STRLEN(buf) + 1);
2174 if (cpy != NULL)
2175 {
2176 STRCPY(cpy, p);
2177 STRCPY(gettail(cpy), buf);
2178 vim_free(p);
2179 p = cpy;
2180 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002181 }
2182 else
2183 {
2184 vim_free(p);
Christian Brabandt6cc30272024-12-13 17:54:33 +01002185 p = vim_strsave(buf);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002186 }
2187 }
2188
2189 if (remain == NULL)
2190 break;
2191
Bram Moolenaar26262f82019-09-04 20:59:15 +02002192 // Append the first path component of "remain" to "p".
Christian Brabandt6cc30272024-12-13 17:54:33 +01002193 q = getnextcomp(remain + 1);
2194 len = q - remain - (*q != NUL);
2195 cpy = vim_strnsave(p, STRLEN(p) + len);
2196 if (cpy != NULL)
2197 {
2198 STRNCAT(cpy, remain, len);
2199 vim_free(p);
2200 p = cpy;
2201 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02002202 // Shorten "remain".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002203 if (*q != NUL)
Christian Brabandt6cc30272024-12-13 17:54:33 +01002204 STRMOVE(remain, q - 1);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002205 else
2206 VIM_CLEAR(remain);
2207 }
2208
Bram Moolenaar26262f82019-09-04 20:59:15 +02002209 // If the result is a relative path name, make it explicitly relative to
2210 // the current directory if and only if the argument had this form.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002211 if (!vim_ispathsep(*p))
2212 {
2213 if (is_relative_to_current
2214 && *p != NUL
2215 && !(p[0] == '.'
2216 && (p[1] == NUL
2217 || vim_ispathsep(p[1])
2218 || (p[1] == '.'
2219 && (p[2] == NUL
2220 || vim_ispathsep(p[2]))))))
2221 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002222 // Prepend "./".
Christian Brabandt6cc30272024-12-13 17:54:33 +01002223 cpy = concat_str((char_u *)"./", p);
2224 if (cpy != NULL)
2225 {
2226 vim_free(p);
2227 p = cpy;
2228 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002229 }
2230 else if (!is_relative_to_current)
2231 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002232 // Strip leading "./".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002233 q = p;
2234 while (q[0] == '.' && vim_ispathsep(q[1]))
2235 q += 2;
2236 if (q > p)
Christian Brabandt6cc30272024-12-13 17:54:33 +01002237 STRMOVE(p, p + 2);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002238 }
2239 }
2240
Bram Moolenaar26262f82019-09-04 20:59:15 +02002241 // Ensure that the result will have no trailing path separator
2242 // if the argument had none. But keep "/" or "//".
Christian Brabandt6cc30272024-12-13 17:54:33 +01002243 if (!has_trailing_pathsep)
2244 {
2245 q = p + STRLEN(p);
2246 if (after_pathsep(p, q))
2247 *gettail_sep(p) = NUL;
2248 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002249
2250 rettv->vval.v_string = p;
2251 }
2252# else
2253 rettv->vval.v_string = vim_strsave(p);
2254# endif
2255#endif
2256
2257 simplify_filename(rettv->vval.v_string);
2258
2259#ifdef HAVE_READLINK
2260fail:
2261 vim_free(buf);
2262#endif
2263 rettv->v_type = VAR_STRING;
2264}
2265
2266/*
2267 * "tempname()" function
2268 */
2269 void
2270f_tempname(typval_T *argvars UNUSED, typval_T *rettv)
2271{
2272 static int x = 'A';
2273
2274 rettv->v_type = VAR_STRING;
2275 rettv->vval.v_string = vim_tempname(x, FALSE);
2276
Bram Moolenaar26262f82019-09-04 20:59:15 +02002277 // Advance 'x' to use A-Z and 0-9, so that there are at least 34 different
2278 // names. Skip 'I' and 'O', they are used for shell redirection.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002279 do
2280 {
2281 if (x == 'Z')
2282 x = '0';
2283 else if (x == '9')
2284 x = 'A';
2285 else
Bram Moolenaar424bcae2022-01-31 14:59:41 +00002286 ++x;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002287 } while (x == 'I' || x == 'O');
2288}
2289
2290/*
2291 * "writefile()" function
2292 */
2293 void
2294f_writefile(typval_T *argvars, typval_T *rettv)
2295{
2296 int binary = FALSE;
2297 int append = FALSE;
Bram Moolenaar806a2732022-09-04 15:40:36 +01002298 int defer = FALSE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002299#ifdef HAVE_FSYNC
2300 int do_fsync = p_fs;
2301#endif
2302 char_u *fname;
2303 FILE *fd;
2304 int ret = 0;
2305 listitem_T *li;
2306 list_T *list = NULL;
2307 blob_T *blob = NULL;
2308
2309 rettv->vval.v_number = -1;
2310 if (check_secure())
2311 return;
2312
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02002313 if (in_vim9script()
2314 && (check_for_list_or_blob_arg(argvars, 0) == FAIL
2315 || check_for_string_arg(argvars, 1) == FAIL
2316 || check_for_opt_string_arg(argvars, 2) == FAIL))
2317 return;
2318
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002319 if (argvars[0].v_type == VAR_LIST)
2320 {
2321 list = argvars[0].vval.v_list;
2322 if (list == NULL)
2323 return;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02002324 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002325 FOR_ALL_LIST_ITEMS(list, li)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002326 if (tv_get_string_chk(&li->li_tv) == NULL)
2327 return;
2328 }
2329 else if (argvars[0].v_type == VAR_BLOB)
2330 {
2331 blob = argvars[0].vval.v_blob;
2332 if (blob == NULL)
2333 return;
2334 }
2335 else
2336 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00002337 semsg(_(e_invalid_argument_str),
Bram Moolenaar18a2b872020-03-19 13:08:45 +01002338 _("writefile() first argument must be a List or a Blob"));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002339 return;
2340 }
2341
2342 if (argvars[2].v_type != VAR_UNKNOWN)
2343 {
2344 char_u *arg2 = tv_get_string_chk(&argvars[2]);
2345
2346 if (arg2 == NULL)
2347 return;
2348 if (vim_strchr(arg2, 'b') != NULL)
2349 binary = TRUE;
2350 if (vim_strchr(arg2, 'a') != NULL)
2351 append = TRUE;
Bram Moolenaar806a2732022-09-04 15:40:36 +01002352 if (vim_strchr(arg2, 'D') != NULL)
2353 defer = TRUE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002354#ifdef HAVE_FSYNC
2355 if (vim_strchr(arg2, 's') != NULL)
2356 do_fsync = TRUE;
2357 else if (vim_strchr(arg2, 'S') != NULL)
2358 do_fsync = FALSE;
2359#endif
2360 }
2361
2362 fname = tv_get_string_chk(&argvars[1]);
2363 if (fname == NULL)
2364 return;
2365
Bram Moolenaar6f14da12022-09-07 21:30:44 +01002366 if (defer && !can_add_defer())
Bram Moolenaar806a2732022-09-04 15:40:36 +01002367 return;
Bram Moolenaar806a2732022-09-04 15:40:36 +01002368
Bram Moolenaar26262f82019-09-04 20:59:15 +02002369 // Always open the file in binary mode, library functions have a mind of
2370 // their own about CR-LF conversion.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002371 if (*fname == NUL || (fd = mch_fopen((char *)fname,
2372 append ? APPENDBIN : WRITEBIN)) == NULL)
2373 {
Bram Moolenaar806a2732022-09-04 15:40:36 +01002374 semsg(_(e_cant_create_file_str),
2375 *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002376 ret = -1;
2377 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002378 else
2379 {
Bram Moolenaar806a2732022-09-04 15:40:36 +01002380 if (defer)
2381 {
2382 typval_T tv;
2383
2384 tv.v_type = VAR_STRING;
2385 tv.v_lock = 0;
Bram Moolenaar6f14da12022-09-07 21:30:44 +01002386 tv.vval.v_string = FullName_save(fname, FALSE);
Bram Moolenaar806a2732022-09-04 15:40:36 +01002387 if (tv.vval.v_string == NULL
2388 || add_defer((char_u *)"delete", 1, &tv) == FAIL)
2389 {
2390 ret = -1;
2391 fclose(fd);
2392 (void)mch_remove(fname);
2393 }
2394 }
2395
2396 if (ret == 0)
2397 {
2398 if (blob)
2399 {
2400 if (write_blob(fd, blob) == FAIL)
2401 ret = -1;
2402 }
2403 else
2404 {
2405 if (write_list(fd, list, binary) == FAIL)
2406 ret = -1;
2407 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002408#ifdef HAVE_FSYNC
Bram Moolenaar806a2732022-09-04 15:40:36 +01002409 if (ret == 0 && do_fsync)
2410 // Ignore the error, the user wouldn't know what to do about
2411 // it. May happen for a device.
2412 vim_ignored = vim_fsync(fileno(fd));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002413#endif
Bram Moolenaar806a2732022-09-04 15:40:36 +01002414 fclose(fd);
2415 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002416 }
2417
2418 rettv->vval.v_number = ret;
2419}
2420
2421#endif // FEAT_EVAL
2422
2423#if defined(FEAT_BROWSE) || defined(PROTO)
2424/*
2425 * Generic browse function. Calls gui_mch_browse() when possible.
2426 * Later this may pop-up a non-GUI file selector (external command?).
2427 */
2428 char_u *
2429do_browse(
Bram Moolenaar26262f82019-09-04 20:59:15 +02002430 int flags, // BROWSE_SAVE and BROWSE_DIR
2431 char_u *title, // title for the window
2432 char_u *dflt, // default file name (may include directory)
2433 char_u *ext, // extension added
2434 char_u *initdir, // initial directory, NULL for current dir or
2435 // when using path from "dflt"
2436 char_u *filter, // file name filter
2437 buf_T *buf) // buffer to read/write for
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002438{
2439 char_u *fname;
Bram Moolenaar26262f82019-09-04 20:59:15 +02002440 static char_u *last_dir = NULL; // last used directory
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002441 char_u *tofree = NULL;
Bram Moolenaare1004402020-10-24 20:49:43 +02002442 int save_cmod_flags = cmdmod.cmod_flags;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002443
Bram Moolenaar26262f82019-09-04 20:59:15 +02002444 // Must turn off browse to avoid that autocommands will get the
2445 // flag too!
Bram Moolenaare1004402020-10-24 20:49:43 +02002446 cmdmod.cmod_flags &= ~CMOD_BROWSE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002447
2448 if (title == NULL || *title == NUL)
2449 {
2450 if (flags & BROWSE_DIR)
2451 title = (char_u *)_("Select Directory dialog");
2452 else if (flags & BROWSE_SAVE)
2453 title = (char_u *)_("Save File dialog");
2454 else
2455 title = (char_u *)_("Open File dialog");
2456 }
2457
Bram Moolenaar26262f82019-09-04 20:59:15 +02002458 // When no directory specified, use default file name, default dir, buffer
2459 // dir, last dir or current dir
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002460 if ((initdir == NULL || *initdir == NUL) && dflt != NULL && *dflt != NUL)
2461 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002462 if (mch_isdir(dflt)) // default file name is a directory
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002463 {
2464 initdir = dflt;
2465 dflt = NULL;
2466 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02002467 else if (gettail(dflt) != dflt) // default file name includes a path
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002468 {
2469 tofree = vim_strsave(dflt);
2470 if (tofree != NULL)
2471 {
2472 initdir = tofree;
2473 *gettail(initdir) = NUL;
2474 dflt = gettail(dflt);
2475 }
2476 }
2477 }
2478
2479 if (initdir == NULL || *initdir == NUL)
2480 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002481 // When 'browsedir' is a directory, use it
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002482 if (STRCMP(p_bsdir, "last") != 0
2483 && STRCMP(p_bsdir, "buffer") != 0
2484 && STRCMP(p_bsdir, "current") != 0
2485 && mch_isdir(p_bsdir))
2486 initdir = p_bsdir;
Bram Moolenaar26262f82019-09-04 20:59:15 +02002487 // When saving or 'browsedir' is "buffer", use buffer fname
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002488 else if (((flags & BROWSE_SAVE) || *p_bsdir == 'b')
2489 && buf != NULL && buf->b_ffname != NULL)
2490 {
2491 if (dflt == NULL || *dflt == NUL)
2492 dflt = gettail(curbuf->b_ffname);
2493 tofree = vim_strsave(curbuf->b_ffname);
2494 if (tofree != NULL)
2495 {
2496 initdir = tofree;
2497 *gettail(initdir) = NUL;
2498 }
2499 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02002500 // When 'browsedir' is "last", use dir from last browse
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002501 else if (*p_bsdir == 'l')
2502 initdir = last_dir;
Bram Moolenaar26262f82019-09-04 20:59:15 +02002503 // When 'browsedir is "current", use current directory. This is the
2504 // default already, leave initdir empty.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002505 }
2506
2507# ifdef FEAT_GUI
Bram Moolenaar26262f82019-09-04 20:59:15 +02002508 if (gui.in_use) // when this changes, also adjust f_has()!
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002509 {
2510 if (filter == NULL
2511# ifdef FEAT_EVAL
2512 && (filter = get_var_value((char_u *)"b:browsefilter")) == NULL
2513 && (filter = get_var_value((char_u *)"g:browsefilter")) == NULL
2514# endif
2515 )
2516 filter = BROWSE_FILTER_DEFAULT;
2517 if (flags & BROWSE_DIR)
2518 {
2519# if defined(FEAT_GUI_GTK) || defined(MSWIN)
Bram Moolenaar26262f82019-09-04 20:59:15 +02002520 // For systems that have a directory dialog.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002521 fname = gui_mch_browsedir(title, initdir);
2522# else
Bram Moolenaar26262f82019-09-04 20:59:15 +02002523 // Generic solution for selecting a directory: select a file and
2524 // remove the file name.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002525 fname = gui_mch_browse(0, title, dflt, ext, initdir, (char_u *)"");
2526# endif
2527# if !defined(FEAT_GUI_GTK)
Bram Moolenaar26262f82019-09-04 20:59:15 +02002528 // Win32 adds a dummy file name, others return an arbitrary file
2529 // name. GTK+ 2 returns only the directory,
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002530 if (fname != NULL && *fname != NUL && !mch_isdir(fname))
2531 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002532 // Remove the file name.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002533 char_u *tail = gettail_sep(fname);
2534
2535 if (tail == fname)
Bram Moolenaar26262f82019-09-04 20:59:15 +02002536 *tail++ = '.'; // use current dir
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002537 *tail = NUL;
2538 }
2539# endif
2540 }
2541 else
2542 fname = gui_mch_browse(flags & BROWSE_SAVE,
2543 title, dflt, ext, initdir, (char_u *)_(filter));
2544
Bram Moolenaar26262f82019-09-04 20:59:15 +02002545 // We hang around in the dialog for a while, the user might do some
2546 // things to our files. The Win32 dialog allows deleting or renaming
2547 // a file, check timestamps.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002548 need_check_timestamps = TRUE;
2549 did_check_timestamps = FALSE;
2550 }
2551 else
2552# endif
2553 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002554 // TODO: non-GUI file selector here
Bram Moolenaareaaac012022-01-02 17:00:40 +00002555 emsg(_(e_sorry_no_file_browser_in_console_mode));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002556 fname = NULL;
2557 }
2558
Bram Moolenaar26262f82019-09-04 20:59:15 +02002559 // keep the directory for next time
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002560 if (fname != NULL)
2561 {
2562 vim_free(last_dir);
2563 last_dir = vim_strsave(fname);
2564 if (last_dir != NULL && !(flags & BROWSE_DIR))
2565 {
2566 *gettail(last_dir) = NUL;
2567 if (*last_dir == NUL)
2568 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002569 // filename only returned, must be in current dir
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002570 vim_free(last_dir);
2571 last_dir = alloc(MAXPATHL);
2572 if (last_dir != NULL)
2573 mch_dirname(last_dir, MAXPATHL);
2574 }
2575 }
2576 }
2577
2578 vim_free(tofree);
Bram Moolenaare1004402020-10-24 20:49:43 +02002579 cmdmod.cmod_flags = save_cmod_flags;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002580
2581 return fname;
2582}
2583#endif
2584
2585#if defined(FEAT_EVAL) || defined(PROTO)
2586
2587/*
2588 * "browse(save, title, initdir, default)" function
2589 */
2590 void
2591f_browse(typval_T *argvars UNUSED, typval_T *rettv)
2592{
2593# ifdef FEAT_BROWSE
2594 int save;
2595 char_u *title;
2596 char_u *initdir;
2597 char_u *defname;
2598 char_u buf[NUMBUFLEN];
2599 char_u buf2[NUMBUFLEN];
2600 int error = FALSE;
2601
Bram Moolenaarf28f2ac2021-03-22 22:21:26 +01002602 if (in_vim9script()
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02002603 && (check_for_bool_arg(argvars, 0) == FAIL
2604 || check_for_string_arg(argvars, 1) == FAIL
Bram Moolenaar32105ae2021-03-27 18:59:25 +01002605 || check_for_string_arg(argvars, 2) == FAIL
2606 || check_for_string_arg(argvars, 3) == FAIL))
Bram Moolenaarf28f2ac2021-03-22 22:21:26 +01002607 return;
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02002608
Bram Moolenaar5a049842022-10-08 12:52:09 +01002609 save = (int)tv_get_bool_chk(&argvars[0], &error);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002610 title = tv_get_string_chk(&argvars[1]);
2611 initdir = tv_get_string_buf_chk(&argvars[2], buf);
2612 defname = tv_get_string_buf_chk(&argvars[3], buf2);
2613
2614 if (error || title == NULL || initdir == NULL || defname == NULL)
2615 rettv->vval.v_string = NULL;
2616 else
2617 rettv->vval.v_string =
2618 do_browse(save ? BROWSE_SAVE : 0,
2619 title, defname, NULL, initdir, NULL, curbuf);
2620# else
2621 rettv->vval.v_string = NULL;
2622# endif
2623 rettv->v_type = VAR_STRING;
2624}
2625
2626/*
2627 * "browsedir(title, initdir)" function
2628 */
2629 void
2630f_browsedir(typval_T *argvars UNUSED, typval_T *rettv)
2631{
2632# ifdef FEAT_BROWSE
2633 char_u *title;
2634 char_u *initdir;
2635 char_u buf[NUMBUFLEN];
2636
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02002637 if (in_vim9script()
2638 && (check_for_string_arg(argvars, 0) == FAIL
2639 || check_for_string_arg(argvars, 1) == FAIL))
2640 return;
2641
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002642 title = tv_get_string_chk(&argvars[0]);
2643 initdir = tv_get_string_buf_chk(&argvars[1], buf);
2644
2645 if (title == NULL || initdir == NULL)
2646 rettv->vval.v_string = NULL;
2647 else
2648 rettv->vval.v_string = do_browse(BROWSE_DIR,
2649 title, NULL, NULL, initdir, NULL, curbuf);
2650# else
2651 rettv->vval.v_string = NULL;
2652# endif
2653 rettv->v_type = VAR_STRING;
2654}
2655
Shougo Matsushita60c87432024-06-03 22:59:27 +02002656/*
2657 * "filecopy()" function
2658 */
2659 void
2660f_filecopy(typval_T *argvars, typval_T *rettv)
2661{
2662 char_u *from;
2663 stat_T st;
2664
2665 rettv->vval.v_number = FALSE;
2666
2667 if (check_restricted() || check_secure()
2668 || check_for_string_arg(argvars, 0) == FAIL
2669 || check_for_string_arg(argvars, 1) == FAIL)
2670 return;
2671
2672 from = tv_get_string(&argvars[0]);
2673
2674 if (mch_lstat((char *)from, &st) >= 0
2675 && (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)))
2676 rettv->vval.v_number = vim_copyfile(
2677 tv_get_string(&argvars[0]),
2678 tv_get_string(&argvars[1])) == OK ? TRUE : FALSE;
2679}
2680
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002681#endif // FEAT_EVAL
Bram Moolenaar26262f82019-09-04 20:59:15 +02002682
2683/*
2684 * Replace home directory by "~" in each space or comma separated file name in
2685 * 'src'.
2686 * If anything fails (except when out of space) dst equals src.
2687 */
2688 void
2689home_replace(
2690 buf_T *buf, // when not NULL, check for help files
2691 char_u *src, // input file name
2692 char_u *dst, // where to put the result
2693 int dstlen, // maximum length of the result
2694 int one) // if TRUE, only replace one file name, include
2695 // spaces and commas in the file name.
2696{
2697 size_t dirlen = 0, envlen = 0;
2698 size_t len;
2699 char_u *homedir_env, *homedir_env_orig;
2700 char_u *p;
2701
2702 if (src == NULL)
2703 {
2704 *dst = NUL;
2705 return;
2706 }
2707
2708 /*
2709 * If the file is a help file, remove the path completely.
2710 */
2711 if (buf != NULL && buf->b_help)
2712 {
2713 vim_snprintf((char *)dst, dstlen, "%s", gettail(src));
2714 return;
2715 }
2716
2717 /*
2718 * We check both the value of the $HOME environment variable and the
2719 * "real" home directory.
2720 */
2721 if (homedir != NULL)
2722 dirlen = STRLEN(homedir);
2723
2724#ifdef VMS
2725 homedir_env_orig = homedir_env = mch_getenv((char_u *)"SYS$LOGIN");
2726#else
2727 homedir_env_orig = homedir_env = mch_getenv((char_u *)"HOME");
2728#endif
2729#ifdef MSWIN
2730 if (homedir_env == NULL)
2731 homedir_env_orig = homedir_env = mch_getenv((char_u *)"USERPROFILE");
2732#endif
2733 // Empty is the same as not set.
2734 if (homedir_env != NULL && *homedir_env == NUL)
2735 homedir_env = NULL;
2736
2737 if (homedir_env != NULL && *homedir_env == '~')
2738 {
Mike Williams51024bb2024-05-30 07:46:30 +02002739 size_t usedlen = 0;
Yegappan Lakshmanan00d34592024-12-25 10:20:51 +01002740 size_t flen;
Bram Moolenaar26262f82019-09-04 20:59:15 +02002741 char_u *fbuf = NULL;
2742
Yegappan Lakshmanan00d34592024-12-25 10:20:51 +01002743 flen = STRLEN(homedir_env);
Bram Moolenaar26262f82019-09-04 20:59:15 +02002744 (void)modify_fname((char_u *)":p", FALSE, &usedlen,
2745 &homedir_env, &fbuf, &flen);
Yegappan Lakshmanan00d34592024-12-25 10:20:51 +01002746 flen = STRLEN(homedir_env);
Bram Moolenaar26262f82019-09-04 20:59:15 +02002747 if (flen > 0 && vim_ispathsep(homedir_env[flen - 1]))
2748 // Remove the trailing / that is added to a directory.
2749 homedir_env[flen - 1] = NUL;
2750 }
2751
2752 if (homedir_env != NULL)
2753 envlen = STRLEN(homedir_env);
2754
2755 if (!one)
2756 src = skipwhite(src);
2757 while (*src && dstlen > 0)
2758 {
2759 /*
2760 * Here we are at the beginning of a file name.
2761 * First, check to see if the beginning of the file name matches
2762 * $HOME or the "real" home directory. Check that there is a '/'
2763 * after the match (so that if e.g. the file is "/home/pieter/bla",
2764 * and the home directory is "/home/piet", the file does not end up
2765 * as "~er/bla" (which would seem to indicate the file "bla" in user
2766 * er's home directory)).
2767 */
2768 p = homedir;
2769 len = dirlen;
2770 for (;;)
2771 {
2772 if ( len
2773 && fnamencmp(src, p, len) == 0
2774 && (vim_ispathsep(src[len])
2775 || (!one && (src[len] == ',' || src[len] == ' '))
2776 || src[len] == NUL))
2777 {
2778 src += len;
2779 if (--dstlen > 0)
2780 *dst++ = '~';
2781
Bram Moolenaar0e390f42020-06-10 13:12:28 +02002782 // Do not add directory separator into dst, because dst is
2783 // expected to just return the directory name without the
2784 // directory separator '/'.
Bram Moolenaar26262f82019-09-04 20:59:15 +02002785 break;
2786 }
2787 if (p == homedir_env)
2788 break;
2789 p = homedir_env;
2790 len = envlen;
2791 }
2792
2793 // if (!one) skip to separator: space or comma
2794 while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0)
2795 *dst++ = *src++;
2796 // skip separator
2797 while ((*src == ' ' || *src == ',') && --dstlen > 0)
2798 *dst++ = *src++;
2799 }
2800 // if (dstlen == 0) out of space, what to do???
2801
2802 *dst = NUL;
2803
2804 if (homedir_env != homedir_env_orig)
2805 vim_free(homedir_env);
2806}
2807
2808/*
2809 * Like home_replace, store the replaced string in allocated memory.
2810 * When something fails, NULL is returned.
2811 */
2812 char_u *
2813home_replace_save(
2814 buf_T *buf, // when not NULL, check for help files
2815 char_u *src) // input file name
2816{
2817 char_u *dst;
2818 unsigned len;
2819
2820 len = 3; // space for "~/" and trailing NUL
2821 if (src != NULL) // just in case
2822 len += (unsigned)STRLEN(src);
2823 dst = alloc(len);
2824 if (dst != NULL)
2825 home_replace(buf, src, dst, len, TRUE);
2826 return dst;
2827}
2828
2829/*
2830 * Compare two file names and return:
2831 * FPC_SAME if they both exist and are the same file.
2832 * FPC_SAMEX if they both don't exist and have the same file name.
2833 * FPC_DIFF if they both exist and are different files.
2834 * FPC_NOTX if they both don't exist.
2835 * FPC_DIFFX if one of them doesn't exist.
2836 * For the first name environment variables are expanded if "expandenv" is
2837 * TRUE.
2838 */
2839 int
2840fullpathcmp(
2841 char_u *s1,
2842 char_u *s2,
2843 int checkname, // when both don't exist, check file names
2844 int expandenv)
2845{
2846#ifdef UNIX
2847 char_u exp1[MAXPATHL];
2848 char_u full1[MAXPATHL];
2849 char_u full2[MAXPATHL];
2850 stat_T st1, st2;
2851 int r1, r2;
2852
2853 if (expandenv)
2854 expand_env(s1, exp1, MAXPATHL);
2855 else
2856 vim_strncpy(exp1, s1, MAXPATHL - 1);
2857 r1 = mch_stat((char *)exp1, &st1);
2858 r2 = mch_stat((char *)s2, &st2);
2859 if (r1 != 0 && r2 != 0)
2860 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002861 // if mch_stat() doesn't work, may compare the names
Bram Moolenaar26262f82019-09-04 20:59:15 +02002862 if (checkname)
2863 {
2864 if (fnamecmp(exp1, s2) == 0)
2865 return FPC_SAMEX;
2866 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
2867 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
2868 if (r1 == OK && r2 == OK && fnamecmp(full1, full2) == 0)
2869 return FPC_SAMEX;
2870 }
2871 return FPC_NOTX;
2872 }
2873 if (r1 != 0 || r2 != 0)
2874 return FPC_DIFFX;
2875 if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
2876 return FPC_SAME;
2877 return FPC_DIFF;
2878#else
2879 char_u *exp1; // expanded s1
2880 char_u *full1; // full path of s1
2881 char_u *full2; // full path of s2
2882 int retval = FPC_DIFF;
2883 int r1, r2;
2884
2885 // allocate one buffer to store three paths (alloc()/free() is slow!)
2886 if ((exp1 = alloc(MAXPATHL * 3)) != NULL)
2887 {
2888 full1 = exp1 + MAXPATHL;
2889 full2 = full1 + MAXPATHL;
2890
2891 if (expandenv)
2892 expand_env(s1, exp1, MAXPATHL);
2893 else
2894 vim_strncpy(exp1, s1, MAXPATHL - 1);
2895 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
2896 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
2897
2898 // If vim_FullName() fails, the file probably doesn't exist.
2899 if (r1 != OK && r2 != OK)
2900 {
2901 if (checkname && fnamecmp(exp1, s2) == 0)
2902 retval = FPC_SAMEX;
2903 else
2904 retval = FPC_NOTX;
2905 }
2906 else if (r1 != OK || r2 != OK)
2907 retval = FPC_DIFFX;
2908 else if (fnamecmp(full1, full2))
2909 retval = FPC_DIFF;
2910 else
2911 retval = FPC_SAME;
2912 vim_free(exp1);
2913 }
2914 return retval;
2915#endif
2916}
2917
2918/*
2919 * Get the tail of a path: the file name.
2920 * When the path ends in a path separator the tail is the NUL after it.
2921 * Fail safe: never returns NULL.
2922 */
2923 char_u *
2924gettail(char_u *fname)
2925{
2926 char_u *p1, *p2;
2927
2928 if (fname == NULL)
2929 return (char_u *)"";
2930 for (p1 = p2 = get_past_head(fname); *p2; ) // find last part of path
2931 {
2932 if (vim_ispathsep_nocolon(*p2))
2933 p1 = p2 + 1;
2934 MB_PTR_ADV(p2);
2935 }
2936 return p1;
2937}
2938
2939/*
2940 * Get pointer to tail of "fname", including path separators. Putting a NUL
2941 * here leaves the directory name. Takes care of "c:/" and "//".
2942 * Always returns a valid pointer.
2943 */
2944 char_u *
2945gettail_sep(char_u *fname)
2946{
2947 char_u *p;
2948 char_u *t;
2949
2950 p = get_past_head(fname); // don't remove the '/' from "c:/file"
2951 t = gettail(fname);
2952 while (t > p && after_pathsep(fname, t))
2953 --t;
2954#ifdef VMS
2955 // path separator is part of the path
2956 ++t;
2957#endif
2958 return t;
2959}
2960
2961/*
2962 * get the next path component (just after the next path separator).
2963 */
2964 char_u *
2965getnextcomp(char_u *fname)
2966{
2967 while (*fname && !vim_ispathsep(*fname))
2968 MB_PTR_ADV(fname);
2969 if (*fname)
2970 ++fname;
2971 return fname;
2972}
2973
2974/*
2975 * Get a pointer to one character past the head of a path name.
2976 * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
2977 * If there is no head, path is returned.
2978 */
2979 char_u *
2980get_past_head(char_u *path)
2981{
2982 char_u *retval;
2983
2984#if defined(MSWIN)
2985 // may skip "c:"
Keith Thompson184f71c2024-01-04 21:19:04 +01002986 if (SAFE_isalpha(path[0]) && path[1] == ':')
Bram Moolenaar26262f82019-09-04 20:59:15 +02002987 retval = path + 2;
2988 else
2989 retval = path;
2990#else
2991# if defined(AMIGA)
2992 // may skip "label:"
2993 retval = vim_strchr(path, ':');
2994 if (retval == NULL)
2995 retval = path;
2996# else // Unix
2997 retval = path;
2998# endif
2999#endif
3000
3001 while (vim_ispathsep(*retval))
3002 ++retval;
3003
3004 return retval;
3005}
3006
3007/*
3008 * Return TRUE if 'c' is a path separator.
3009 * Note that for MS-Windows this includes the colon.
3010 */
3011 int
3012vim_ispathsep(int c)
3013{
3014#ifdef UNIX
3015 return (c == '/'); // UNIX has ':' inside file names
3016#else
3017# ifdef BACKSLASH_IN_FILENAME
3018 return (c == ':' || c == '/' || c == '\\');
3019# else
3020# ifdef VMS
3021 // server"user passwd"::device:[full.path.name]fname.extension;version"
3022 return (c == ':' || c == '[' || c == ']' || c == '/'
3023 || c == '<' || c == '>' || c == '"' );
3024# else
3025 return (c == ':' || c == '/');
3026# endif // VMS
3027# endif
3028#endif
3029}
3030
3031/*
3032 * Like vim_ispathsep(c), but exclude the colon for MS-Windows.
3033 */
3034 int
3035vim_ispathsep_nocolon(int c)
3036{
3037 return vim_ispathsep(c)
3038#ifdef BACKSLASH_IN_FILENAME
3039 && c != ':'
3040#endif
3041 ;
3042}
3043
3044/*
Bram Moolenaar26262f82019-09-04 20:59:15 +02003045 * Return TRUE if the directory of "fname" exists, FALSE otherwise.
3046 * Also returns TRUE if there is no directory name.
3047 * "fname" must be writable!.
3048 */
3049 int
3050dir_of_file_exists(char_u *fname)
3051{
3052 char_u *p;
3053 int c;
3054 int retval;
3055
3056 p = gettail_sep(fname);
3057 if (p == fname)
3058 return TRUE;
3059 c = *p;
3060 *p = NUL;
3061 retval = mch_isdir(fname);
3062 *p = c;
3063 return retval;
3064}
3065
3066/*
3067 * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally
3068 * and deal with 'fileignorecase'.
3069 */
3070 int
3071vim_fnamecmp(char_u *x, char_u *y)
3072{
3073#ifdef BACKSLASH_IN_FILENAME
3074 return vim_fnamencmp(x, y, MAXPATHL);
3075#else
3076 if (p_fic)
3077 return MB_STRICMP(x, y);
3078 return STRCMP(x, y);
3079#endif
3080}
3081
3082 int
3083vim_fnamencmp(char_u *x, char_u *y, size_t len)
3084{
3085#ifdef BACKSLASH_IN_FILENAME
3086 char_u *px = x;
3087 char_u *py = y;
3088 int cx = NUL;
3089 int cy = NUL;
3090
3091 while (len > 0)
3092 {
3093 cx = PTR2CHAR(px);
3094 cy = PTR2CHAR(py);
3095 if (cx == NUL || cy == NUL
3096 || ((p_fic ? MB_TOLOWER(cx) != MB_TOLOWER(cy) : cx != cy)
3097 && !(cx == '/' && cy == '\\')
3098 && !(cx == '\\' && cy == '/')))
3099 break;
Bram Moolenaar1614a142019-10-06 22:00:13 +02003100 len -= mb_ptr2len(px);
3101 px += mb_ptr2len(px);
3102 py += mb_ptr2len(py);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003103 }
3104 if (len == 0)
3105 return 0;
3106 return (cx - cy);
3107#else
3108 if (p_fic)
3109 return MB_STRNICMP(x, y, len);
3110 return STRNCMP(x, y, len);
3111#endif
3112}
3113
3114/*
3115 * Concatenate file names fname1 and fname2 into allocated memory.
3116 * Only add a '/' or '\\' when 'sep' is TRUE and it is necessary.
3117 */
3118 char_u *
3119concat_fnames(char_u *fname1, char_u *fname2, int sep)
3120{
3121 char_u *dest;
3122
Christian Brabandt6cc30272024-12-13 17:54:33 +01003123 dest = alloc(STRLEN(fname1) + STRLEN(fname2) + 3);
Yegappan Lakshmanan1cfb14a2023-01-09 19:04:23 +00003124 if (dest == NULL)
3125 return NULL;
3126
Christian Brabandt6cc30272024-12-13 17:54:33 +01003127 STRCPY(dest, fname1);
3128 if (sep)
3129 add_pathsep(dest);
3130 STRCAT(dest, fname2);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003131 return dest;
3132}
3133
3134/*
3135 * Add a path separator to a file name, unless it already ends in a path
3136 * separator.
3137 */
3138 void
3139add_pathsep(char_u *p)
3140{
Christian Brabandt6cc30272024-12-13 17:54:33 +01003141 if (*p != NUL && !after_pathsep(p, p + STRLEN(p)))
3142 STRCAT(p, PATHSEPSTR);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003143}
3144
3145/*
3146 * FullName_save - Make an allocated copy of a full file name.
3147 * Returns NULL when out of memory.
3148 */
3149 char_u *
3150FullName_save(
3151 char_u *fname,
3152 int force) // force expansion, even when it already looks
3153 // like a full path name
3154{
3155 char_u *buf;
3156 char_u *new_fname = NULL;
3157
3158 if (fname == NULL)
3159 return NULL;
3160
3161 buf = alloc(MAXPATHL);
Yegappan Lakshmanan1cfb14a2023-01-09 19:04:23 +00003162 if (buf == NULL)
3163 return NULL;
3164
3165 if (vim_FullName(fname, buf, MAXPATHL, force) != FAIL)
3166 new_fname = vim_strsave(buf);
3167 else
3168 new_fname = vim_strsave(fname);
3169 vim_free(buf);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003170 return new_fname;
3171}
3172
3173/*
3174 * return TRUE if "fname" exists.
3175 */
3176 int
3177vim_fexists(char_u *fname)
3178{
3179 stat_T st;
3180
3181 if (mch_stat((char *)fname, &st))
3182 return FALSE;
3183 return TRUE;
3184}
3185
3186/*
3187 * Invoke expand_wildcards() for one pattern.
3188 * Expand items like "%:h" before the expansion.
3189 * Returns OK or FAIL.
3190 */
3191 int
3192expand_wildcards_eval(
3193 char_u **pat, // pointer to input pattern
3194 int *num_file, // resulting number of files
3195 char_u ***file, // array of resulting files
3196 int flags) // EW_DIR, etc.
3197{
3198 int ret = FAIL;
3199 char_u *eval_pat = NULL;
3200 char_u *exp_pat = *pat;
Bram Moolenaarf5724372022-09-02 19:45:15 +01003201 char *ignored_msg;
Mike Williams51024bb2024-05-30 07:46:30 +02003202 size_t usedlen;
Bram Moolenaarf5724372022-09-02 19:45:15 +01003203 int is_cur_alt_file = *exp_pat == '%' || *exp_pat == '#';
3204 int star_follows = FALSE;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003205
Bram Moolenaarf5724372022-09-02 19:45:15 +01003206 if (is_cur_alt_file || *exp_pat == '<')
Bram Moolenaar26262f82019-09-04 20:59:15 +02003207 {
3208 ++emsg_off;
3209 eval_pat = eval_vars(exp_pat, exp_pat, &usedlen,
Bram Moolenaara96edb72022-04-28 17:52:24 +01003210 NULL, &ignored_msg, NULL, TRUE);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003211 --emsg_off;
3212 if (eval_pat != NULL)
Bram Moolenaarf5724372022-09-02 19:45:15 +01003213 {
3214 star_follows = STRCMP(exp_pat + usedlen, "*") == 0;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003215 exp_pat = concat_str(eval_pat, exp_pat + usedlen);
Bram Moolenaarf5724372022-09-02 19:45:15 +01003216 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02003217 }
3218
3219 if (exp_pat != NULL)
3220 ret = expand_wildcards(1, &exp_pat, num_file, file, flags);
3221
3222 if (eval_pat != NULL)
3223 {
Bram Moolenaarf5724372022-09-02 19:45:15 +01003224 if (*num_file == 0 && is_cur_alt_file && star_follows)
3225 {
3226 // Expanding "%" or "#" and the file does not exist: Add the
3227 // pattern anyway (without the star) so that this works for remote
3228 // files and non-file buffer names.
3229 *file = ALLOC_ONE(char_u *);
3230 if (*file != NULL)
3231 {
3232 **file = eval_pat;
3233 eval_pat = NULL;
3234 *num_file = 1;
3235 ret = OK;
3236 }
3237 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02003238 vim_free(exp_pat);
3239 vim_free(eval_pat);
3240 }
3241
3242 return ret;
3243}
3244
3245/*
3246 * Expand wildcards. Calls gen_expand_wildcards() and removes files matching
3247 * 'wildignore'.
3248 * Returns OK or FAIL. When FAIL then "num_files" won't be set.
3249 */
3250 int
3251expand_wildcards(
3252 int num_pat, // number of input patterns
3253 char_u **pat, // array of input patterns
3254 int *num_files, // resulting number of files
3255 char_u ***files, // array of resulting files
3256 int flags) // EW_DIR, etc.
3257{
3258 int retval;
3259 int i, j;
3260 char_u *p;
3261 int non_suf_match; // number without matching suffix
3262
3263 retval = gen_expand_wildcards(num_pat, pat, num_files, files, flags);
3264
3265 // When keeping all matches, return here
3266 if ((flags & EW_KEEPALL) || retval == FAIL)
3267 return retval;
3268
Bram Moolenaar26262f82019-09-04 20:59:15 +02003269 /*
3270 * Remove names that match 'wildignore'.
3271 */
3272 if (*p_wig)
3273 {
3274 char_u *ffname;
3275
3276 // check all files in (*files)[]
3277 for (i = 0; i < *num_files; ++i)
3278 {
3279 ffname = FullName_save((*files)[i], FALSE);
3280 if (ffname == NULL) // out of memory
3281 break;
3282# ifdef VMS
3283 vms_remove_version(ffname);
3284# endif
3285 if (match_file_list(p_wig, (*files)[i], ffname))
3286 {
3287 // remove this matching file from the list
3288 vim_free((*files)[i]);
3289 for (j = i; j + 1 < *num_files; ++j)
3290 (*files)[j] = (*files)[j + 1];
3291 --*num_files;
3292 --i;
3293 }
3294 vim_free(ffname);
3295 }
3296
3297 // If the number of matches is now zero, we fail.
3298 if (*num_files == 0)
3299 {
3300 VIM_CLEAR(*files);
3301 return FAIL;
3302 }
3303 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02003304
3305 /*
3306 * Move the names where 'suffixes' match to the end.
Bram Moolenaar57e95172022-08-20 19:26:14 +01003307 * Skip when interrupted, the result probably won't be used.
Bram Moolenaar26262f82019-09-04 20:59:15 +02003308 */
Bram Moolenaar57e95172022-08-20 19:26:14 +01003309 if (*num_files > 1 && !got_int)
Bram Moolenaar26262f82019-09-04 20:59:15 +02003310 {
3311 non_suf_match = 0;
3312 for (i = 0; i < *num_files; ++i)
3313 {
3314 if (!match_suffix((*files)[i]))
3315 {
3316 /*
3317 * Move the name without matching suffix to the front
3318 * of the list.
3319 */
3320 p = (*files)[i];
3321 for (j = i; j > non_suf_match; --j)
3322 (*files)[j] = (*files)[j - 1];
3323 (*files)[non_suf_match++] = p;
3324 }
3325 }
3326 }
3327
3328 return retval;
3329}
3330
3331/*
3332 * Return TRUE if "fname" matches with an entry in 'suffixes'.
3333 */
3334 int
3335match_suffix(char_u *fname)
3336{
3337 int fnamelen, setsuflen;
3338 char_u *setsuf;
3339#define MAXSUFLEN 30 // maximum length of a file suffix
3340 char_u suf_buf[MAXSUFLEN];
3341
3342 fnamelen = (int)STRLEN(fname);
3343 setsuflen = 0;
3344 for (setsuf = p_su; *setsuf; )
3345 {
3346 setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
3347 if (setsuflen == 0)
3348 {
3349 char_u *tail = gettail(fname);
3350
3351 // empty entry: match name without a '.'
3352 if (vim_strchr(tail, '.') == NULL)
3353 {
3354 setsuflen = 1;
3355 break;
3356 }
3357 }
3358 else
3359 {
3360 if (fnamelen >= setsuflen
3361 && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
3362 (size_t)setsuflen) == 0)
3363 break;
3364 setsuflen = 0;
3365 }
3366 }
3367 return (setsuflen != 0);
3368}
3369
3370#ifdef VIM_BACKTICK
3371
3372/*
3373 * Return TRUE if we can expand this backtick thing here.
3374 */
3375 static int
3376vim_backtick(char_u *p)
3377{
3378 return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
3379}
3380
3381/*
3382 * Expand an item in `backticks` by executing it as a command.
3383 * Currently only works when pat[] starts and ends with a `.
3384 * Returns number of file names found, -1 if an error is encountered.
3385 */
3386 static int
3387expand_backtick(
3388 garray_T *gap,
3389 char_u *pat,
3390 int flags) // EW_* flags
3391{
3392 char_u *p;
3393 char_u *cmd;
3394 char_u *buffer;
3395 int cnt = 0;
3396 int i;
3397
3398 // Create the command: lop off the backticks.
Bram Moolenaar71ccd032020-06-12 22:59:11 +02003399 cmd = vim_strnsave(pat + 1, STRLEN(pat) - 2);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003400 if (cmd == NULL)
3401 return -1;
3402
3403#ifdef FEAT_EVAL
3404 if (*cmd == '=') // `={expr}`: Expand expression
Bram Moolenaara4e0b972022-10-01 19:43:52 +01003405 buffer = eval_to_string(cmd + 1, TRUE, FALSE);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003406 else
3407#endif
3408 buffer = get_cmd_output(cmd, NULL,
3409 (flags & EW_SILENT) ? SHELL_SILENT : 0, NULL);
3410 vim_free(cmd);
3411 if (buffer == NULL)
3412 return -1;
3413
3414 cmd = buffer;
3415 while (*cmd != NUL)
3416 {
3417 cmd = skipwhite(cmd); // skip over white space
3418 p = cmd;
3419 while (*p != NUL && *p != '\r' && *p != '\n') // skip over entry
3420 ++p;
3421 // add an entry if it is not empty
3422 if (p > cmd)
3423 {
3424 i = *p;
3425 *p = NUL;
3426 addfile(gap, cmd, flags);
3427 *p = i;
3428 ++cnt;
3429 }
3430 cmd = p;
3431 while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
3432 ++cmd;
3433 }
3434
3435 vim_free(buffer);
3436 return cnt;
3437}
3438#endif // VIM_BACKTICK
3439
Christian Brabandt6cc30272024-12-13 17:54:33 +01003440#if defined(MSWIN)
Bram Moolenaar26262f82019-09-04 20:59:15 +02003441/*
Christian Brabandt6cc30272024-12-13 17:54:33 +01003442 * File name expansion code for MS-DOS, Win16 and Win32. It's here because
Bram Moolenaar26262f82019-09-04 20:59:15 +02003443 * it's shared between these systems.
3444 */
3445
3446/*
Christian Brabandt6cc30272024-12-13 17:54:33 +01003447 * comparison function for qsort in dos_expandpath()
Bram Moolenaar26262f82019-09-04 20:59:15 +02003448 */
3449 static int
3450pstrcmp(const void *a, const void *b)
3451{
3452 return (pathcmp(*(char **)a, *(char **)b, -1));
3453}
3454
3455/*
3456 * Recursively expand one path component into all matching files and/or
3457 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
3458 * Return the number of matches found.
3459 * "path" has backslashes before chars that are not to be expanded, starting
3460 * at "path[wildoff]".
3461 * Return the number of matches found.
Christian Brabandt6cc30272024-12-13 17:54:33 +01003462 * NOTE: much of this is identical to unix_expandpath(), keep in sync!
Bram Moolenaar26262f82019-09-04 20:59:15 +02003463 */
Christian Brabandt6cc30272024-12-13 17:54:33 +01003464 static int
3465dos_expandpath(
Bram Moolenaar26262f82019-09-04 20:59:15 +02003466 garray_T *gap,
Christian Brabandt6cc30272024-12-13 17:54:33 +01003467 char_u *path,
3468 int wildoff,
3469 int flags, // EW_* flags
3470 int didstar) // expanded "**" once already
Bram Moolenaar26262f82019-09-04 20:59:15 +02003471{
Christian Brabandt6cc30272024-12-13 17:54:33 +01003472 char_u *buf;
3473 char_u *path_end;
3474 char_u *p, *s, *e;
3475 int start_len = gap->ga_len;
3476 char_u *pat;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003477 regmatch_T regmatch;
Christian Brabandt6cc30272024-12-13 17:54:33 +01003478 int starts_with_dot;
3479 int matches;
3480 int len;
3481 int starstar = FALSE;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003482 static int stardepth = 0; // depth for "**" expansion
Christian Brabandt6cc30272024-12-13 17:54:33 +01003483 HANDLE hFind = INVALID_HANDLE_VALUE;
3484 WIN32_FIND_DATAW wfb;
3485 WCHAR *wn = NULL; // UCS-2 name, NULL when not used.
3486 char_u *matchname;
3487 int ok;
3488 char_u *p_alt;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003489
3490 // Expanding "**" may take a long time, check for CTRL-C.
3491 if (stardepth > 0)
3492 {
3493 ui_breakcheck();
3494 if (got_int)
3495 return 0;
3496 }
3497
Christian Brabandt6cc30272024-12-13 17:54:33 +01003498 // Make room for file name. When doing encoding conversion the actual
3499 // length may be quite a bit longer, thus use the maximum possible length.
Bram Moolenaar26262f82019-09-04 20:59:15 +02003500 buf = alloc(MAXPATHL);
3501 if (buf == NULL)
3502 return 0;
3503
3504 /*
3505 * Find the first part in the path name that contains a wildcard or a ~1.
Christian Brabandt6cc30272024-12-13 17:54:33 +01003506 * Copy it into buf, including the preceding characters.
Bram Moolenaar26262f82019-09-04 20:59:15 +02003507 */
3508 p = buf;
3509 s = buf;
3510 e = NULL;
3511 path_end = path;
3512 while (*path_end != NUL)
3513 {
3514 // May ignore a wildcard that has a backslash before it; it will
3515 // be removed by rem_backslash() or file_pat_to_reg_pat() below.
3516 if (path_end >= path + wildoff && rem_backslash(path_end))
3517 *p++ = *path_end++;
Christian Brabandt6cc30272024-12-13 17:54:33 +01003518 else if (*path_end == '\\' || *path_end == ':' || *path_end == '/')
Bram Moolenaar26262f82019-09-04 20:59:15 +02003519 {
3520 if (e != NULL)
3521 break;
3522 s = p + 1;
3523 }
3524 else if (path_end >= path + wildoff
Christian Brabandt6cc30272024-12-13 17:54:33 +01003525 && vim_strchr((char_u *)"*?[~", *path_end) != NULL)
Bram Moolenaar26262f82019-09-04 20:59:15 +02003526 e = p;
3527 if (has_mbyte)
3528 {
Christian Brabandt6cc30272024-12-13 17:54:33 +01003529 len = (*mb_ptr2len)(path_end);
3530 STRNCPY(p, path_end, len);
3531 p += len;
3532 path_end += len;
3533 }
3534 else
3535 *p++ = *path_end++;
3536 }
3537 e = p;
3538 *e = NUL;
3539
3540 // now we have one wildcard component between s and e
3541 // Remove backslashes between "wildoff" and the start of the wildcard
3542 // component.
3543 for (p = buf + wildoff; p < s; ++p)
3544 if (rem_backslash(p))
3545 {
3546 STRMOVE(p, p + 1);
3547 --e;
3548 --s;
3549 }
3550
3551 // Check for "**" between "s" and "e".
3552 for (p = s; p < e; ++p)
3553 if (p[0] == '*' && p[1] == '*')
3554 starstar = TRUE;
3555
3556 starts_with_dot = *s == '.';
3557 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
3558 if (pat == NULL)
3559 {
3560 vim_free(buf);
3561 return 0;
3562 }
3563
3564 // compile the regexp into a program
3565 if (flags & (EW_NOERROR | EW_NOTWILD))
3566 ++emsg_silent;
3567 regmatch.rm_ic = TRUE; // Always ignore case
3568 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
3569 if (flags & (EW_NOERROR | EW_NOTWILD))
3570 --emsg_silent;
3571 vim_free(pat);
3572
3573 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
3574 {
3575 vim_free(buf);
3576 return 0;
3577 }
3578
3579 // remember the pattern or file name being looked for
3580 matchname = vim_strsave(s);
3581
3582 // If "**" is by itself, this is the first time we encounter it and more
3583 // is following then find matches without any directory.
3584 if (!didstar && stardepth < 100 && starstar && e - s == 2
3585 && *path_end == '/')
3586 {
3587 STRCPY(s, path_end + 1);
3588 ++stardepth;
3589 (void)dos_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
3590 --stardepth;
3591 }
3592
3593 // Scan all files in the directory with "dir/ *.*"
3594 STRCPY(s, "*.*");
3595 wn = enc_to_utf16(buf, NULL);
3596 if (wn != NULL)
3597 hFind = FindFirstFileW(wn, &wfb);
3598 ok = (hFind != INVALID_HANDLE_VALUE);
3599
3600 while (ok)
3601 {
3602 p = utf16_to_enc(wfb.cFileName, NULL); // p is allocated here
3603
3604 if (p == NULL)
3605 break; // out of memory
3606
3607 // Do not use the alternate filename when the file name ends in '~',
3608 // because it picks up backup files: short name for "foo.vim~" is
3609 // "foo~1.vim", which matches "*.vim".
3610 if (*wfb.cAlternateFileName == NUL || p[STRLEN(p) - 1] == '~')
3611 p_alt = NULL;
3612 else
3613 p_alt = utf16_to_enc(wfb.cAlternateFileName, NULL);
3614
3615 // Ignore entries starting with a dot, unless when asked for. Accept
3616 // all entries found with "matchname".
3617 if ((p[0] != '.' || starts_with_dot
3618 || ((flags & EW_DODOT)
3619 && p[1] != NUL && (p[1] != '.' || p[2] != NUL)))
3620 && (matchname == NULL
3621 || (regmatch.regprog != NULL
3622 && (vim_regexec(&regmatch, p, (colnr_T)0)
3623 || (p_alt != NULL
3624 && vim_regexec(&regmatch, p_alt, (colnr_T)0))))
3625 || ((flags & EW_NOTWILD)
3626 && fnamencmp(path + (s - buf), p, e - s) == 0)))
3627 {
3628 STRCPY(s, p);
3629 len = (int)STRLEN(buf);
3630
3631 if (starstar && stardepth < 100
3632 && (wfb.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
3633 {
3634 // For "**" in the pattern first go deeper in the tree to
3635 // find matches.
3636 STRCPY(buf + len, "/**");
3637 STRCPY(buf + len + 3, path_end);
3638 ++stardepth;
3639 (void)dos_expandpath(gap, buf, len + 1, flags, TRUE);
3640 --stardepth;
3641 }
3642
3643 STRCPY(buf + len, path_end);
3644 if (mch_has_exp_wildcard(path_end))
3645 {
3646 // need to expand another component of the path
3647 // remove backslashes for the remaining components only
3648 (void)dos_expandpath(gap, buf, len + 1, flags, FALSE);
3649 }
3650 else
3651 {
3652 stat_T sb;
3653
3654 // no more wildcards, check if there is a match
3655 // remove backslashes for the remaining components only
3656 if (*path_end != 0)
3657 backslash_halve(buf + len + 1);
3658 // add existing file
3659 if ((flags & EW_ALLLINKS) ? mch_lstat((char *)buf, &sb) >= 0
3660 : mch_getperm(buf) >= 0)
3661 addfile(gap, buf, flags);
3662 }
3663 }
3664
3665 vim_free(p_alt);
3666 vim_free(p);
3667 ok = FindNextFileW(hFind, &wfb);
3668 }
3669
3670 FindClose(hFind);
3671 vim_free(wn);
3672 vim_free(buf);
3673 vim_regfree(regmatch.regprog);
3674 vim_free(matchname);
3675
3676 matches = gap->ga_len - start_len;
3677 if (matches > 0)
3678 qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
3679 sizeof(char_u *), pstrcmp);
3680 return matches;
3681}
3682
3683 int
3684mch_expandpath(
3685 garray_T *gap,
3686 char_u *path,
3687 int flags) // EW_* flags
3688{
3689 return dos_expandpath(gap, path, 0, flags, FALSE);
3690}
3691#endif // MSWIN
3692
3693#if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \
3694 || defined(PROTO)
3695/*
3696 * Unix style wildcard expansion code.
3697 * It's here because it's used both for Unix and Mac.
3698 */
3699 static int
3700pstrcmp(const void *a, const void *b)
3701{
3702 return (pathcmp(*(char **)a, *(char **)b, -1));
3703}
3704
3705/*
3706 * Recursively expand one path component into all matching files and/or
3707 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
3708 * "path" has backslashes before chars that are not to be expanded, starting
3709 * at "path + wildoff".
3710 * Return the number of matches found.
3711 * NOTE: much of this is identical to dos_expandpath(), keep in sync!
3712 */
3713 int
3714unix_expandpath(
3715 garray_T *gap,
3716 char_u *path,
3717 int wildoff,
3718 int flags, // EW_* flags
3719 int didstar) // expanded "**" once already
3720{
3721 char_u *buf;
3722 char_u *path_end;
3723 char_u *p, *s, *e;
3724 int start_len = gap->ga_len;
3725 char_u *pat;
3726 regmatch_T regmatch;
3727 int starts_with_dot;
3728 int matches;
3729 int len;
3730 int starstar = FALSE;
3731 static int stardepth = 0; // depth for "**" expansion
3732
3733 DIR *dirp;
3734 struct dirent *dp;
3735
3736 // Expanding "**" may take a long time, check for CTRL-C.
3737 if (stardepth > 0)
3738 {
3739 ui_breakcheck();
3740 if (got_int)
3741 return 0;
3742 }
3743
3744 // make room for file name (a bit too much to stay on the safe side)
3745 size_t buflen = STRLEN(path) + MAXPATHL;
3746 buf = alloc(buflen);
3747 if (buf == NULL)
3748 return 0;
3749
3750 /*
3751 * Find the first part in the path name that contains a wildcard.
3752 * When EW_ICASE is set every letter is considered to be a wildcard.
3753 * Copy it into "buf", including the preceding characters.
3754 */
3755 p = buf;
3756 s = buf;
3757 e = NULL;
3758 path_end = path;
3759 while (*path_end != NUL)
3760 {
3761 // May ignore a wildcard that has a backslash before it; it will
3762 // be removed by rem_backslash() or file_pat_to_reg_pat() below.
3763 if (path_end >= path + wildoff && rem_backslash(path_end))
3764 *p++ = *path_end++;
3765 else if (*path_end == '/')
3766 {
3767 if (e != NULL)
3768 break;
3769 s = p + 1;
3770 }
3771 else if (path_end >= path + wildoff
3772 && (vim_strchr((char_u *)"*?[{~$", *path_end) != NULL
3773 || (!p_fic && (flags & EW_ICASE)
3774 && vim_isalpha(PTR2CHAR(path_end)))))
3775 e = p;
3776 if (has_mbyte)
3777 {
3778 len = (*mb_ptr2len)(path_end);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003779 STRNCPY(p, path_end, len);
3780 p += len;
3781 path_end += len;
3782 }
3783 else
3784 *p++ = *path_end++;
3785 }
3786 e = p;
3787 *e = NUL;
3788
3789 // Now we have one wildcard component between "s" and "e".
3790 // Remove backslashes between "wildoff" and the start of the wildcard
3791 // component.
Christian Brabandt6cc30272024-12-13 17:54:33 +01003792 for (p = buf + wildoff; p < s; ++p)
3793 if (rem_backslash(p))
Bram Moolenaar26262f82019-09-04 20:59:15 +02003794 {
Christian Brabandt6cc30272024-12-13 17:54:33 +01003795 STRMOVE(p, p + 1);
3796 --e;
3797 --s;
3798 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02003799
3800 // Check for "**" between "s" and "e".
3801 for (p = s; p < e; ++p)
3802 if (p[0] == '*' && p[1] == '*')
3803 starstar = TRUE;
3804
3805 // convert the file pattern to a regexp pattern
3806 starts_with_dot = *s == '.';
3807 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
3808 if (pat == NULL)
3809 {
3810 vim_free(buf);
3811 return 0;
3812 }
3813
3814 // compile the regexp into a program
3815 if (flags & EW_ICASE)
Christian Brabandt6cc30272024-12-13 17:54:33 +01003816 regmatch.rm_ic = TRUE; // 'wildignorecase' set
Bram Moolenaar26262f82019-09-04 20:59:15 +02003817 else
Christian Brabandt6cc30272024-12-13 17:54:33 +01003818 regmatch.rm_ic = p_fic; // ignore case when 'fileignorecase' is set
Bram Moolenaar26262f82019-09-04 20:59:15 +02003819 if (flags & (EW_NOERROR | EW_NOTWILD))
3820 ++emsg_silent;
3821 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
3822 if (flags & (EW_NOERROR | EW_NOTWILD))
3823 --emsg_silent;
3824 vim_free(pat);
3825
3826 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
3827 {
3828 vim_free(buf);
3829 return 0;
3830 }
3831
3832 // If "**" is by itself, this is the first time we encounter it and more
3833 // is following then find matches without any directory.
Christian Brabandt6cc30272024-12-13 17:54:33 +01003834 if (!didstar && stardepth < 100 && starstar && e - s == 2
3835 && *path_end == '/')
Bram Moolenaar26262f82019-09-04 20:59:15 +02003836 {
3837 STRCPY(s, path_end + 1);
3838 ++stardepth;
Christian Brabandt6cc30272024-12-13 17:54:33 +01003839 (void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003840 --stardepth;
3841 }
3842
3843 // open the directory for scanning
3844 *s = NUL;
3845 dirp = opendir(*buf == NUL ? "." : (char *)buf);
3846
3847 // Find all matching entries
Christian Brabandt6cc30272024-12-13 17:54:33 +01003848 if (dirp != NULL)
Bram Moolenaar26262f82019-09-04 20:59:15 +02003849 {
Bram Moolenaar57e95172022-08-20 19:26:14 +01003850 while (!got_int)
Bram Moolenaar26262f82019-09-04 20:59:15 +02003851 {
3852 dp = readdir(dirp);
3853 if (dp == NULL)
3854 break;
Christian Brabandt6cc30272024-12-13 17:54:33 +01003855 if ((dp->d_name[0] != '.' || starts_with_dot
3856 || ((flags & EW_DODOT)
3857 && dp->d_name[1] != NUL
3858 && (dp->d_name[1] != '.' || dp->d_name[2] != NUL)))
3859 && ((regmatch.regprog != NULL && vim_regexec(&regmatch,
3860 (char_u *)dp->d_name, (colnr_T)0))
John Marriotte29c8ba2024-12-13 13:58:53 +01003861 || ((flags & EW_NOTWILD)
Christian Brabandt6cc30272024-12-13 17:54:33 +01003862 && fnamencmp(path + (s - buf), dp->d_name, e - s) == 0)))
John Marriotte29c8ba2024-12-13 13:58:53 +01003863 {
Christian Brabandt6cc30272024-12-13 17:54:33 +01003864 vim_strncpy(s, (char_u *)dp->d_name, buflen - (s - buf) - 1);
3865 len = STRLEN(buf);
John Marriotte29c8ba2024-12-13 13:58:53 +01003866
Christian Brabandt6cc30272024-12-13 17:54:33 +01003867 if (starstar && stardepth < 100)
Bram Moolenaar26262f82019-09-04 20:59:15 +02003868 {
3869 // For "**" in the pattern first go deeper in the tree to
3870 // find matches.
Christian Brabandt6cc30272024-12-13 17:54:33 +01003871 vim_snprintf((char *)buf + len, buflen - len,
3872 "/**%s", path_end);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003873 ++stardepth;
3874 (void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
3875 --stardepth;
3876 }
3877
Christian Brabandt6cc30272024-12-13 17:54:33 +01003878 vim_snprintf((char *)buf + len, buflen - len, "%s", path_end);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003879 if (mch_has_exp_wildcard(path_end)) // handle more wildcards
3880 {
3881 // need to expand another component of the path
3882 // remove backslashes for the remaining components only
3883 (void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
3884 }
3885 else
3886 {
3887 stat_T sb;
3888
3889 // no more wildcards, check if there is a match
3890 // remove backslashes for the remaining components only
3891 if (*path_end != NUL)
3892 backslash_halve(buf + len + 1);
3893 // add existing file or symbolic link
3894 if ((flags & EW_ALLLINKS) ? mch_lstat((char *)buf, &sb) >= 0
Christian Brabandt6cc30272024-12-13 17:54:33 +01003895 : mch_getperm(buf) >= 0)
Bram Moolenaar26262f82019-09-04 20:59:15 +02003896 {
3897#ifdef MACOS_CONVERT
3898 size_t precomp_len = STRLEN(buf)+1;
3899 char_u *precomp_buf =
3900 mac_precompose_path(buf, precomp_len, &precomp_len);
3901
3902 if (precomp_buf)
3903 {
3904 mch_memmove(buf, precomp_buf, precomp_len);
3905 vim_free(precomp_buf);
3906 }
3907#endif
3908 addfile(gap, buf, flags);
3909 }
3910 }
3911 }
3912 }
3913
3914 closedir(dirp);
3915 }
3916
3917 vim_free(buf);
3918 vim_regfree(regmatch.regprog);
3919
Bram Moolenaar57e95172022-08-20 19:26:14 +01003920 // When interrupted the matches probably won't be used and sorting can be
3921 // slow, thus skip it.
Bram Moolenaar26262f82019-09-04 20:59:15 +02003922 matches = gap->ga_len - start_len;
Bram Moolenaar57e95172022-08-20 19:26:14 +01003923 if (matches > 0 && !got_int)
Bram Moolenaar26262f82019-09-04 20:59:15 +02003924 qsort(((char_u **)gap->ga_data) + start_len, matches,
Christian Brabandt6cc30272024-12-13 17:54:33 +01003925 sizeof(char_u *), pstrcmp);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003926 return matches;
3927}
3928#endif
3929
3930/*
3931 * Return TRUE if "p" contains what looks like an environment variable.
3932 * Allowing for escaping.
3933 */
3934 static int
3935has_env_var(char_u *p)
3936{
3937 for ( ; *p; MB_PTR_ADV(p))
3938 {
3939 if (*p == '\\' && p[1] != NUL)
3940 ++p;
3941 else if (vim_strchr((char_u *)
3942#if defined(MSWIN)
3943 "$%"
3944#else
3945 "$"
3946#endif
3947 , *p) != NULL)
3948 return TRUE;
3949 }
3950 return FALSE;
3951}
3952
3953#ifdef SPECIAL_WILDCHAR
3954/*
3955 * Return TRUE if "p" contains a special wildcard character, one that Vim
3956 * cannot expand, requires using a shell.
3957 */
3958 static int
3959has_special_wildchar(char_u *p)
3960{
3961 for ( ; *p; MB_PTR_ADV(p))
3962 {
3963 // Disallow line break characters.
3964 if (*p == '\r' || *p == '\n')
3965 break;
3966 // Allow for escaping.
3967 if (*p == '\\' && p[1] != NUL && p[1] != '\r' && p[1] != '\n')
3968 ++p;
3969 else if (vim_strchr((char_u *)SPECIAL_WILDCHAR, *p) != NULL)
3970 {
3971 // A { must be followed by a matching }.
3972 if (*p == '{' && vim_strchr(p, '}') == NULL)
3973 continue;
3974 // A quote and backtick must be followed by another one.
3975 if ((*p == '`' || *p == '\'') && vim_strchr(p, *p) == NULL)
3976 continue;
3977 return TRUE;
3978 }
3979 }
3980 return FALSE;
3981}
3982#endif
3983
3984/*
3985 * Generic wildcard expansion code.
3986 *
3987 * Characters in "pat" that should not be expanded must be preceded with a
3988 * backslash. E.g., "/path\ with\ spaces/my\*star*"
3989 *
3990 * Return FAIL when no single file was found. In this case "num_file" is not
3991 * set, and "file" may contain an error message.
3992 * Return OK when some files found. "num_file" is set to the number of
3993 * matches, "file" to the array of matches. Call FreeWild() later.
3994 */
3995 int
3996gen_expand_wildcards(
3997 int num_pat, // number of input patterns
3998 char_u **pat, // array of input patterns
3999 int *num_file, // resulting number of files
4000 char_u ***file, // array of resulting files
4001 int flags) // EW_* flags
4002{
4003 int i;
4004 garray_T ga;
4005 char_u *p;
4006 static int recursive = FALSE;
4007 int add_pat;
4008 int retval = OK;
Bram Moolenaar26262f82019-09-04 20:59:15 +02004009 int did_expand_in_path = FALSE;
LemonBoya20bf692024-07-11 22:35:53 +02004010 char_u *path_option = *curbuf->b_p_path == NUL ?
4011 p_path : curbuf->b_p_path;
Bram Moolenaar26262f82019-09-04 20:59:15 +02004012
4013 /*
4014 * expand_env() is called to expand things like "~user". If this fails,
4015 * it calls ExpandOne(), which brings us back here. In this case, always
4016 * call the machine specific expansion function, if possible. Otherwise,
4017 * return FAIL.
4018 */
4019 if (recursive)
4020#ifdef SPECIAL_WILDCHAR
4021 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
4022#else
4023 return FAIL;
4024#endif
4025
4026#ifdef SPECIAL_WILDCHAR
4027 /*
4028 * If there are any special wildcard characters which we cannot handle
4029 * here, call machine specific function for all the expansion. This
4030 * avoids starting the shell for each argument separately.
4031 * For `=expr` do use the internal function.
4032 */
4033 for (i = 0; i < num_pat; i++)
4034 {
4035 if (has_special_wildchar(pat[i])
4036# ifdef VIM_BACKTICK
4037 && !(vim_backtick(pat[i]) && pat[i][1] == '=')
4038# endif
4039 )
4040 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
4041 }
4042#endif
4043
4044 recursive = TRUE;
4045
4046 /*
4047 * The matching file names are stored in a growarray. Init it empty.
4048 */
Bram Moolenaar04935fb2022-01-08 16:19:22 +00004049 ga_init2(&ga, sizeof(char_u *), 30);
Bram Moolenaar26262f82019-09-04 20:59:15 +02004050
Bram Moolenaar57e95172022-08-20 19:26:14 +01004051 for (i = 0; i < num_pat && !got_int; ++i)
Bram Moolenaar26262f82019-09-04 20:59:15 +02004052 {
4053 add_pat = -1;
4054 p = pat[i];
4055
4056#ifdef VIM_BACKTICK
4057 if (vim_backtick(p))
4058 {
4059 add_pat = expand_backtick(&ga, p, flags);
4060 if (add_pat == -1)
4061 retval = FAIL;
4062 }
4063 else
4064#endif
4065 {
4066 /*
4067 * First expand environment variables, "~/" and "~user/".
4068 */
4069 if ((has_env_var(p) && !(flags & EW_NOTENV)) || *p == '~')
4070 {
4071 p = expand_env_save_opt(p, TRUE);
4072 if (p == NULL)
4073 p = pat[i];
4074#ifdef UNIX
4075 /*
4076 * On Unix, if expand_env() can't expand an environment
4077 * variable, use the shell to do that. Discard previously
4078 * found file names and start all over again.
4079 */
4080 else if (has_env_var(p) || *p == '~')
4081 {
4082 vim_free(p);
4083 ga_clear_strings(&ga);
4084 i = mch_expand_wildcards(num_pat, pat, num_file, file,
4085 flags|EW_KEEPDOLLAR);
4086 recursive = FALSE;
4087 return i;
4088 }
4089#endif
4090 }
4091
4092 /*
LemonBoya3157a42022-04-03 11:58:31 +01004093 * If there are wildcards or case-insensitive expansion is
4094 * required: Expand file names and add each match to the list. If
4095 * there is no match, and EW_NOTFOUND is given, add the pattern.
4096 * Otherwise: Add the file name if it exists or when EW_NOTFOUND is
4097 * given.
Bram Moolenaar26262f82019-09-04 20:59:15 +02004098 */
LemonBoya3157a42022-04-03 11:58:31 +01004099 if (mch_has_exp_wildcard(p) || (flags & EW_ICASE))
Bram Moolenaar26262f82019-09-04 20:59:15 +02004100 {
LemonBoya20bf692024-07-11 22:35:53 +02004101 if ((flags & (EW_PATH | EW_CDPATH))
Bram Moolenaar26262f82019-09-04 20:59:15 +02004102 && !mch_isFullName(p)
4103 && !(p[0] == '.'
4104 && (vim_ispathsep(p[1])
4105 || (p[1] == '.' && vim_ispathsep(p[2]))))
4106 )
4107 {
4108 // :find completion where 'path' is used.
4109 // Recursiveness is OK here.
4110 recursive = FALSE;
4111 add_pat = expand_in_path(&ga, p, flags);
4112 recursive = TRUE;
4113 did_expand_in_path = TRUE;
4114 }
4115 else
Bram Moolenaar26262f82019-09-04 20:59:15 +02004116 add_pat = mch_expandpath(&ga, p, flags);
4117 }
4118 }
4119
4120 if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
4121 {
4122 char_u *t = backslash_halve_save(p);
4123
4124 // When EW_NOTFOUND is used, always add files and dirs. Makes
4125 // "vim c:/" work.
4126 if (flags & EW_NOTFOUND)
4127 addfile(&ga, t, flags | EW_DIR | EW_FILE);
4128 else
4129 addfile(&ga, t, flags);
4130
4131 if (t != p)
4132 vim_free(t);
4133 }
4134
LemonBoya20bf692024-07-11 22:35:53 +02004135 if (did_expand_in_path && ga.ga_len > 0 && (flags & (EW_PATH | EW_CDPATH)))
4136 uniquefy_paths(&ga, p, path_option);
Bram Moolenaar26262f82019-09-04 20:59:15 +02004137 if (p != pat[i])
4138 vim_free(p);
4139 }
4140
Bram Moolenaar566cc8c2020-06-29 21:14:51 +02004141 // When returning FAIL the array must be freed here.
4142 if (retval == FAIL)
Yegappan Lakshmanan2b74b682022-04-03 21:30:32 +01004143 ga_clear_strings(&ga);
Bram Moolenaar566cc8c2020-06-29 21:14:51 +02004144
Bram Moolenaar26262f82019-09-04 20:59:15 +02004145 *num_file = ga.ga_len;
Bram Moolenaar566cc8c2020-06-29 21:14:51 +02004146 *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data
4147 : (char_u **)_("no matches");
Bram Moolenaar26262f82019-09-04 20:59:15 +02004148
4149 recursive = FALSE;
4150
4151 return ((flags & EW_EMPTYOK) || ga.ga_data != NULL) ? retval : FAIL;
4152}
4153
4154/*
4155 * Add a file to a file list. Accepted flags:
4156 * EW_DIR add directories
4157 * EW_FILE add files
4158 * EW_EXEC add executable files
4159 * EW_NOTFOUND add even when it doesn't exist
4160 * EW_ADDSLASH add slash after directory name
4161 * EW_ALLLINKS add symlink also when the referred file does not exist
4162 */
4163 void
4164addfile(
4165 garray_T *gap,
Bram Moolenaar217e1b82019-12-01 21:41:28 +01004166 char_u *f, // filename
Bram Moolenaar26262f82019-09-04 20:59:15 +02004167 int flags)
4168{
4169 char_u *p;
4170 int isdir;
4171 stat_T sb;
4172
4173 // if the file/dir/link doesn't exist, may not add it
4174 if (!(flags & EW_NOTFOUND) && ((flags & EW_ALLLINKS)
4175 ? mch_lstat((char *)f, &sb) < 0 : mch_getperm(f) < 0))
4176 return;
4177
4178#ifdef FNAME_ILLEGAL
4179 // if the file/dir contains illegal characters, don't add it
4180 if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
4181 return;
4182#endif
4183
4184 isdir = mch_isdir(f);
4185 if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
4186 return;
4187
4188 // If the file isn't executable, may not add it. Do accept directories.
4189 // When invoked from expand_shellcmd() do not use $PATH.
4190 if (!isdir && (flags & EW_EXEC)
4191 && !mch_can_exe(f, NULL, !(flags & EW_SHELLCMD)))
4192 return;
4193
4194 // Make room for another item in the file list.
4195 if (ga_grow(gap, 1) == FAIL)
4196 return;
4197
4198 p = alloc(STRLEN(f) + 1 + isdir);
4199 if (p == NULL)
4200 return;
4201
4202 STRCPY(p, f);
4203#ifdef BACKSLASH_IN_FILENAME
4204 slash_adjust(p);
4205#endif
4206 /*
4207 * Append a slash or backslash after directory names if none is present.
4208 */
Bram Moolenaar26262f82019-09-04 20:59:15 +02004209 if (isdir && (flags & EW_ADDSLASH))
4210 add_pathsep(p);
Bram Moolenaar26262f82019-09-04 20:59:15 +02004211 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
4212}
4213
4214/*
4215 * Free the list of files returned by expand_wildcards() or other expansion
4216 * functions.
4217 */
4218 void
4219FreeWild(int count, char_u **files)
4220{
4221 if (count <= 0 || files == NULL)
4222 return;
4223 while (count--)
4224 vim_free(files[count]);
4225 vim_free(files);
4226}
4227
4228/*
4229 * Compare path "p[]" to "q[]".
4230 * If "maxlen" >= 0 compare "p[maxlen]" to "q[maxlen]"
4231 * Return value like strcmp(p, q), but consider path separators.
4232 */
4233 int
4234pathcmp(const char *p, const char *q, int maxlen)
4235{
4236 int i, j;
4237 int c1, c2;
4238 const char *s = NULL;
4239
4240 for (i = 0, j = 0; maxlen < 0 || (i < maxlen && j < maxlen);)
4241 {
4242 c1 = PTR2CHAR((char_u *)p + i);
4243 c2 = PTR2CHAR((char_u *)q + j);
4244
4245 // End of "p": check if "q" also ends or just has a slash.
4246 if (c1 == NUL)
4247 {
4248 if (c2 == NUL) // full match
4249 return 0;
4250 s = q;
4251 i = j;
4252 break;
4253 }
4254
4255 // End of "q": check if "p" just has a slash.
4256 if (c2 == NUL)
4257 {
4258 s = p;
4259 break;
4260 }
4261
4262 if ((p_fic ? MB_TOUPPER(c1) != MB_TOUPPER(c2) : c1 != c2)
4263#ifdef BACKSLASH_IN_FILENAME
4264 // consider '/' and '\\' to be equal
4265 && !((c1 == '/' && c2 == '\\')
4266 || (c1 == '\\' && c2 == '/'))
4267#endif
4268 )
4269 {
4270 if (vim_ispathsep(c1))
4271 return -1;
4272 if (vim_ispathsep(c2))
4273 return 1;
4274 return p_fic ? MB_TOUPPER(c1) - MB_TOUPPER(c2)
4275 : c1 - c2; // no match
4276 }
4277
Bram Moolenaar1614a142019-10-06 22:00:13 +02004278 i += mb_ptr2len((char_u *)p + i);
4279 j += mb_ptr2len((char_u *)q + j);
Bram Moolenaar26262f82019-09-04 20:59:15 +02004280 }
4281 if (s == NULL) // "i" or "j" ran into "maxlen"
4282 return 0;
4283
4284 c1 = PTR2CHAR((char_u *)s + i);
Bram Moolenaar1614a142019-10-06 22:00:13 +02004285 c2 = PTR2CHAR((char_u *)s + i + mb_ptr2len((char_u *)s + i));
Bram Moolenaar26262f82019-09-04 20:59:15 +02004286 // ignore a trailing slash, but not "//" or ":/"
4287 if (c2 == NUL
4288 && i > 0
4289 && !after_pathsep((char_u *)s, (char_u *)s + i)
4290#ifdef BACKSLASH_IN_FILENAME
4291 && (c1 == '/' || c1 == '\\')
4292#else
4293 && c1 == '/'
4294#endif
4295 )
4296 return 0; // match with trailing slash
4297 if (s == q)
4298 return -1; // no match
4299 return 1;
4300}
4301
4302/*
4303 * Return TRUE if "name" is a full (absolute) path name or URL.
4304 */
4305 int
4306vim_isAbsName(char_u *name)
4307{
4308 return (path_with_url(name) != 0 || mch_isFullName(name));
4309}
4310
4311/*
4312 * Get absolute file name into buffer "buf[len]".
4313 *
4314 * return FAIL for failure, OK otherwise
4315 */
4316 int
4317vim_FullName(
4318 char_u *fname,
4319 char_u *buf,
4320 int len,
4321 int force) // force expansion even when already absolute
4322{
4323 int retval = OK;
4324 int url;
4325
4326 *buf = NUL;
4327 if (fname == NULL)
4328 return FAIL;
4329
4330 url = path_with_url(fname);
4331 if (!url)
4332 retval = mch_FullName(fname, buf, len, force);
4333 if (url || retval == FAIL)
4334 {
4335 // something failed; use the file name (truncate when too long)
4336 vim_strncpy(buf, fname, len - 1);
4337 }
4338#if defined(MSWIN)
4339 slash_adjust(buf);
4340#endif
4341 return retval;
4342}