blob: 654d03aab0553c52b50cd451d103dc4d05dd4828 [file] [log] [blame]
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001/* vi:set ts=8 sts=4 sw=4 noet:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
Bram Moolenaar9810cfb2019-12-11 21:23:00 +010011 * filepath.c: dealing with file names and paths.
Bram Moolenaarb005cd82019-09-04 15:54:55 +020012 */
13
14#include "vim.h"
15
16#ifdef MSWIN
17/*
18 * Functions for ":8" filename modifier: get 8.3 version of a filename.
19 */
20
21/*
22 * Get the short path (8.3) for the filename in "fnamep".
23 * Only works for a valid file name.
24 * When the path gets longer "fnamep" is changed and the allocated buffer
25 * is put in "bufp".
26 * *fnamelen is the length of "fnamep" and set to 0 for a nonexistent path.
27 * Returns OK on success, FAIL on failure.
28 */
29 static int
30get_short_pathname(char_u **fnamep, char_u **bufp, int *fnamelen)
31{
32 int l, len;
Bram Moolenaar3f396972019-10-30 04:10:06 +010033 WCHAR *newbuf;
34 WCHAR *wfname;
Bram Moolenaarb005cd82019-09-04 15:54:55 +020035
Bram Moolenaar3f396972019-10-30 04:10:06 +010036 len = MAXPATHL;
37 newbuf = malloc(len * sizeof(*newbuf));
38 if (newbuf == NULL)
39 return FAIL;
40
41 wfname = enc_to_utf16(*fnamep, NULL);
42 if (wfname == NULL)
43 {
44 vim_free(newbuf);
45 return FAIL;
46 }
47
48 l = GetShortPathNameW(wfname, newbuf, len);
Bram Moolenaarb005cd82019-09-04 15:54:55 +020049 if (l > len - 1)
50 {
Bram Moolenaar26262f82019-09-04 20:59:15 +020051 // If that doesn't work (not enough space), then save the string
52 // and try again with a new buffer big enough.
Bram Moolenaar3f396972019-10-30 04:10:06 +010053 WCHAR *newbuf_t = newbuf;
54 newbuf = vim_realloc(newbuf, (l + 1) * sizeof(*newbuf));
Bram Moolenaarb005cd82019-09-04 15:54:55 +020055 if (newbuf == NULL)
Bram Moolenaar3f396972019-10-30 04:10:06 +010056 {
57 vim_free(wfname);
58 vim_free(newbuf_t);
Bram Moolenaarb005cd82019-09-04 15:54:55 +020059 return FAIL;
Bram Moolenaar3f396972019-10-30 04:10:06 +010060 }
Bram Moolenaar26262f82019-09-04 20:59:15 +020061 // Really should always succeed, as the buffer is big enough.
Bram Moolenaar3f396972019-10-30 04:10:06 +010062 l = GetShortPathNameW(wfname, newbuf, l+1);
Bram Moolenaarb005cd82019-09-04 15:54:55 +020063 }
Bram Moolenaar3f396972019-10-30 04:10:06 +010064 if (l != 0)
65 {
66 char_u *p = utf16_to_enc(newbuf, NULL);
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +020067
Bram Moolenaar3f396972019-10-30 04:10:06 +010068 if (p != NULL)
69 {
70 vim_free(*bufp);
71 *fnamep = *bufp = p;
72 }
73 else
74 {
75 vim_free(wfname);
76 vim_free(newbuf);
77 return FAIL;
78 }
79 }
80 vim_free(wfname);
81 vim_free(newbuf);
Bram Moolenaarb005cd82019-09-04 15:54:55 +020082
Bram Moolenaar2ade7142019-11-04 20:36:50 +010083 *fnamelen = l == 0 ? l : (int)STRLEN(*bufp);
Bram Moolenaarb005cd82019-09-04 15:54:55 +020084 return OK;
85}
86
87/*
88 * Get the short path (8.3) for the filename in "fname". The converted
89 * path is returned in "bufp".
90 *
91 * Some of the directories specified in "fname" may not exist. This function
92 * will shorten the existing directories at the beginning of the path and then
93 * append the remaining non-existing path.
94 *
95 * fname - Pointer to the filename to shorten. On return, contains the
96 * pointer to the shortened pathname
97 * bufp - Pointer to an allocated buffer for the filename.
98 * fnamelen - Length of the filename pointed to by fname
99 *
100 * Returns OK on success (or nothing done) and FAIL on failure (out of memory).
101 */
102 static int
103shortpath_for_invalid_fname(
104 char_u **fname,
105 char_u **bufp,
106 int *fnamelen)
107{
108 char_u *short_fname, *save_fname, *pbuf_unused;
109 char_u *endp, *save_endp;
110 char_u ch;
111 int old_len, len;
112 int new_len, sfx_len;
113 int retval = OK;
114
Bram Moolenaar26262f82019-09-04 20:59:15 +0200115 // Make a copy
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200116 old_len = *fnamelen;
117 save_fname = vim_strnsave(*fname, old_len);
118 pbuf_unused = NULL;
119 short_fname = NULL;
120
Bram Moolenaar26262f82019-09-04 20:59:15 +0200121 endp = save_fname + old_len - 1; // Find the end of the copy
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200122 save_endp = endp;
123
124 /*
125 * Try shortening the supplied path till it succeeds by removing one
126 * directory at a time from the tail of the path.
127 */
128 len = 0;
129 for (;;)
130 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200131 // go back one path-separator
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200132 while (endp > save_fname && !after_pathsep(save_fname, endp + 1))
133 --endp;
134 if (endp <= save_fname)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200135 break; // processed the complete path
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200136
137 /*
138 * Replace the path separator with a NUL and try to shorten the
139 * resulting path.
140 */
141 ch = *endp;
142 *endp = 0;
143 short_fname = save_fname;
144 len = (int)STRLEN(short_fname) + 1;
145 if (get_short_pathname(&short_fname, &pbuf_unused, &len) == FAIL)
146 {
147 retval = FAIL;
148 goto theend;
149 }
Bram Moolenaar26262f82019-09-04 20:59:15 +0200150 *endp = ch; // preserve the string
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200151
152 if (len > 0)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200153 break; // successfully shortened the path
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200154
Bram Moolenaar26262f82019-09-04 20:59:15 +0200155 // failed to shorten the path. Skip the path separator
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200156 --endp;
157 }
158
159 if (len > 0)
160 {
161 /*
162 * Succeeded in shortening the path. Now concatenate the shortened
163 * path with the remaining path at the tail.
164 */
165
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100166 // Compute the length of the new path.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200167 sfx_len = (int)(save_endp - endp) + 1;
168 new_len = len + sfx_len;
169
170 *fnamelen = new_len;
171 vim_free(*bufp);
172 if (new_len > old_len)
173 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200174 // There is not enough space in the currently allocated string,
175 // copy it to a buffer big enough.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200176 *fname = *bufp = vim_strnsave(short_fname, new_len);
177 if (*fname == NULL)
178 {
179 retval = FAIL;
180 goto theend;
181 }
182 }
183 else
184 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200185 // Transfer short_fname to the main buffer (it's big enough),
186 // unless get_short_pathname() did its work in-place.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200187 *fname = *bufp = save_fname;
188 if (short_fname != save_fname)
Christian Brabandt81da16b2022-03-10 12:24:02 +0000189 STRNCPY(save_fname, short_fname, len);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200190 save_fname = NULL;
191 }
192
Bram Moolenaar26262f82019-09-04 20:59:15 +0200193 // concat the not-shortened part of the path
Yegappan Lakshmanana34b4462022-06-11 10:43:26 +0100194 if ((*fname + len) != endp)
195 vim_strncpy(*fname + len, endp, sfx_len);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200196 (*fname)[new_len] = NUL;
197 }
198
199theend:
200 vim_free(pbuf_unused);
201 vim_free(save_fname);
202
203 return retval;
204}
205
206/*
207 * Get a pathname for a partial path.
208 * Returns OK for success, FAIL for failure.
209 */
210 static int
211shortpath_for_partial(
212 char_u **fnamep,
213 char_u **bufp,
214 int *fnamelen)
215{
216 int sepcount, len, tflen;
217 char_u *p;
218 char_u *pbuf, *tfname;
219 int hasTilde;
220
Bram Moolenaar26262f82019-09-04 20:59:15 +0200221 // Count up the path separators from the RHS.. so we know which part
222 // of the path to return.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200223 sepcount = 0;
224 for (p = *fnamep; p < *fnamep + *fnamelen; MB_PTR_ADV(p))
225 if (vim_ispathsep(*p))
226 ++sepcount;
227
Bram Moolenaar26262f82019-09-04 20:59:15 +0200228 // Need full path first (use expand_env() to remove a "~/")
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200229 hasTilde = (**fnamep == '~');
230 if (hasTilde)
231 pbuf = tfname = expand_env_save(*fnamep);
232 else
233 pbuf = tfname = FullName_save(*fnamep, FALSE);
234
235 len = tflen = (int)STRLEN(tfname);
236
237 if (get_short_pathname(&tfname, &pbuf, &len) == FAIL)
238 return FAIL;
239
240 if (len == 0)
241 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200242 // Don't have a valid filename, so shorten the rest of the
243 // path if we can. This CAN give us invalid 8.3 filenames, but
244 // there's not a lot of point in guessing what it might be.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200245 len = tflen;
246 if (shortpath_for_invalid_fname(&tfname, &pbuf, &len) == FAIL)
247 return FAIL;
248 }
249
Bram Moolenaar26262f82019-09-04 20:59:15 +0200250 // Count the paths backward to find the beginning of the desired string.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200251 for (p = tfname + len - 1; p >= tfname; --p)
252 {
253 if (has_mbyte)
254 p -= mb_head_off(tfname, p);
255 if (vim_ispathsep(*p))
256 {
257 if (sepcount == 0 || (hasTilde && sepcount == 1))
258 break;
259 else
260 sepcount --;
261 }
262 }
263 if (hasTilde)
264 {
265 --p;
266 if (p >= tfname)
267 *p = '~';
268 else
269 return FAIL;
270 }
271 else
272 ++p;
273
Bram Moolenaar26262f82019-09-04 20:59:15 +0200274 // Copy in the string - p indexes into tfname - allocated at pbuf
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200275 vim_free(*bufp);
276 *fnamelen = (int)STRLEN(p);
277 *bufp = pbuf;
278 *fnamep = p;
279
280 return OK;
281}
282#endif // MSWIN
283
284/*
285 * Adjust a filename, according to a string of modifiers.
286 * *fnamep must be NUL terminated when called. When returning, the length is
287 * determined by *fnamelen.
288 * Returns VALID_ flags or -1 for failure.
289 * When there is an error, *fnamep is set to NULL.
290 */
291 int
292modify_fname(
293 char_u *src, // string with modifiers
294 int tilde_file, // "~" is a file name, not $HOME
295 int *usedlen, // characters after src that are used
296 char_u **fnamep, // file name so far
297 char_u **bufp, // buffer for allocated file name or NULL
298 int *fnamelen) // length of fnamep
299{
300 int valid = 0;
301 char_u *tail;
302 char_u *s, *p, *pbuf;
303 char_u dirname[MAXPATHL];
304 int c;
305 int has_fullname = 0;
Bram Moolenaard816cd92020-02-04 22:23:09 +0100306 int has_homerelative = 0;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200307#ifdef MSWIN
308 char_u *fname_start = *fnamep;
309 int has_shortname = 0;
310#endif
311
312repeat:
Bram Moolenaar26262f82019-09-04 20:59:15 +0200313 // ":p" - full path/file_name
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200314 if (src[*usedlen] == ':' && src[*usedlen + 1] == 'p')
315 {
316 has_fullname = 1;
317
318 valid |= VALID_PATH;
319 *usedlen += 2;
320
Bram Moolenaar26262f82019-09-04 20:59:15 +0200321 // Expand "~/path" for all systems and "~user/path" for Unix and VMS
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200322 if ((*fnamep)[0] == '~'
323#if !defined(UNIX) && !(defined(VMS) && defined(USER_HOME))
324 && ((*fnamep)[1] == '/'
325# ifdef BACKSLASH_IN_FILENAME
326 || (*fnamep)[1] == '\\'
327# endif
328 || (*fnamep)[1] == NUL)
329#endif
330 && !(tilde_file && (*fnamep)[1] == NUL)
331 )
332 {
333 *fnamep = expand_env_save(*fnamep);
Bram Moolenaar26262f82019-09-04 20:59:15 +0200334 vim_free(*bufp); // free any allocated file name
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200335 *bufp = *fnamep;
336 if (*fnamep == NULL)
337 return -1;
338 }
339
Bram Moolenaar26262f82019-09-04 20:59:15 +0200340 // When "/." or "/.." is used: force expansion to get rid of it.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200341 for (p = *fnamep; *p != NUL; MB_PTR_ADV(p))
342 {
343 if (vim_ispathsep(*p)
344 && p[1] == '.'
345 && (p[2] == NUL
346 || vim_ispathsep(p[2])
347 || (p[2] == '.'
348 && (p[3] == NUL || vim_ispathsep(p[3])))))
349 break;
350 }
351
Bram Moolenaar26262f82019-09-04 20:59:15 +0200352 // FullName_save() is slow, don't use it when not needed.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200353 if (*p != NUL || !vim_isAbsName(*fnamep))
354 {
355 *fnamep = FullName_save(*fnamep, *p != NUL);
Bram Moolenaar26262f82019-09-04 20:59:15 +0200356 vim_free(*bufp); // free any allocated file name
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200357 *bufp = *fnamep;
358 if (*fnamep == NULL)
359 return -1;
360 }
361
362#ifdef MSWIN
363# if _WIN32_WINNT >= 0x0500
364 if (vim_strchr(*fnamep, '~') != NULL)
365 {
366 // Expand 8.3 filename to full path. Needed to make sure the same
367 // file does not have two different names.
368 // Note: problem does not occur if _WIN32_WINNT < 0x0500.
369 WCHAR *wfname = enc_to_utf16(*fnamep, NULL);
370 WCHAR buf[_MAX_PATH];
371
372 if (wfname != NULL)
373 {
374 if (GetLongPathNameW(wfname, buf, _MAX_PATH))
375 {
K.Takata54119102022-02-03 13:33:03 +0000376 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200377
K.Takata54119102022-02-03 13:33:03 +0000378 if (q != NULL)
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200379 {
380 vim_free(*bufp); // free any allocated file name
K.Takata54119102022-02-03 13:33:03 +0000381 *bufp = *fnamep = q;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200382 }
383 }
384 vim_free(wfname);
385 }
386 }
387# endif
388#endif
Bram Moolenaar26262f82019-09-04 20:59:15 +0200389 // Append a path separator to a directory.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200390 if (mch_isdir(*fnamep))
391 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200392 // Make room for one or two extra characters.
Bram Moolenaar71ccd032020-06-12 22:59:11 +0200393 *fnamep = vim_strnsave(*fnamep, STRLEN(*fnamep) + 2);
Bram Moolenaar26262f82019-09-04 20:59:15 +0200394 vim_free(*bufp); // free any allocated file name
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200395 *bufp = *fnamep;
396 if (*fnamep == NULL)
397 return -1;
398 add_pathsep(*fnamep);
399 }
400 }
401
Bram Moolenaar26262f82019-09-04 20:59:15 +0200402 // ":." - path relative to the current directory
403 // ":~" - path relative to the home directory
404 // ":8" - shortname path - postponed till after
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200405 while (src[*usedlen] == ':'
406 && ((c = src[*usedlen + 1]) == '.' || c == '~' || c == '8'))
407 {
408 *usedlen += 2;
409 if (c == '8')
410 {
411#ifdef MSWIN
Bram Moolenaar26262f82019-09-04 20:59:15 +0200412 has_shortname = 1; // Postpone this.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200413#endif
414 continue;
415 }
416 pbuf = NULL;
Bram Moolenaar26262f82019-09-04 20:59:15 +0200417 // Need full path first (use expand_env() to remove a "~/")
Bram Moolenaard816cd92020-02-04 22:23:09 +0100418 if (!has_fullname && !has_homerelative)
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200419 {
=?UTF-8?q?Dundar=20G=C3=B6c?=78a84042022-02-09 15:20:39 +0000420 if (**fnamep == '~')
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200421 p = pbuf = expand_env_save(*fnamep);
422 else
423 p = pbuf = FullName_save(*fnamep, FALSE);
424 }
425 else
426 p = *fnamep;
427
428 has_fullname = 0;
429
430 if (p != NULL)
431 {
432 if (c == '.')
433 {
Bram Moolenaard816cd92020-02-04 22:23:09 +0100434 size_t namelen;
435
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200436 mch_dirname(dirname, MAXPATHL);
Bram Moolenaard816cd92020-02-04 22:23:09 +0100437 if (has_homerelative)
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200438 {
Bram Moolenaard816cd92020-02-04 22:23:09 +0100439 s = vim_strsave(dirname);
440 if (s != NULL)
441 {
442 home_replace(NULL, s, dirname, MAXPATHL, TRUE);
443 vim_free(s);
444 }
445 }
446 namelen = STRLEN(dirname);
447
448 // Do not call shorten_fname() here since it removes the prefix
449 // even though the path does not have a prefix.
450 if (fnamencmp(p, dirname, namelen) == 0)
451 {
452 p += namelen;
Bram Moolenaara78e9c62020-02-05 21:14:00 +0100453 if (vim_ispathsep(*p))
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200454 {
Bram Moolenaara78e9c62020-02-05 21:14:00 +0100455 while (*p && vim_ispathsep(*p))
456 ++p;
457 *fnamep = p;
458 if (pbuf != NULL)
459 {
460 // free any allocated file name
461 vim_free(*bufp);
462 *bufp = pbuf;
463 pbuf = NULL;
464 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200465 }
466 }
467 }
468 else
469 {
470 home_replace(NULL, p, dirname, MAXPATHL, TRUE);
Bram Moolenaar26262f82019-09-04 20:59:15 +0200471 // Only replace it when it starts with '~'
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200472 if (*dirname == '~')
473 {
474 s = vim_strsave(dirname);
475 if (s != NULL)
476 {
477 *fnamep = s;
478 vim_free(*bufp);
479 *bufp = s;
Bram Moolenaard816cd92020-02-04 22:23:09 +0100480 has_homerelative = TRUE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200481 }
482 }
483 }
484 vim_free(pbuf);
485 }
486 }
487
488 tail = gettail(*fnamep);
489 *fnamelen = (int)STRLEN(*fnamep);
490
Bram Moolenaar26262f82019-09-04 20:59:15 +0200491 // ":h" - head, remove "/file_name", can be repeated
492 // Don't remove the first "/" or "c:\"
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200493 while (src[*usedlen] == ':' && src[*usedlen + 1] == 'h')
494 {
495 valid |= VALID_HEAD;
496 *usedlen += 2;
497 s = get_past_head(*fnamep);
498 while (tail > s && after_pathsep(s, tail))
499 MB_PTR_BACK(*fnamep, tail);
500 *fnamelen = (int)(tail - *fnamep);
501#ifdef VMS
502 if (*fnamelen > 0)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200503 *fnamelen += 1; // the path separator is part of the path
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200504#endif
505 if (*fnamelen == 0)
506 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200507 // Result is empty. Turn it into "." to make ":cd %:h" work.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200508 p = vim_strsave((char_u *)".");
509 if (p == NULL)
510 return -1;
511 vim_free(*bufp);
512 *bufp = *fnamep = tail = p;
513 *fnamelen = 1;
514 }
515 else
516 {
517 while (tail > s && !after_pathsep(s, tail))
518 MB_PTR_BACK(*fnamep, tail);
519 }
520 }
521
Bram Moolenaar26262f82019-09-04 20:59:15 +0200522 // ":8" - shortname
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200523 if (src[*usedlen] == ':' && src[*usedlen + 1] == '8')
524 {
525 *usedlen += 2;
526#ifdef MSWIN
527 has_shortname = 1;
528#endif
529 }
530
531#ifdef MSWIN
532 /*
533 * Handle ":8" after we have done 'heads' and before we do 'tails'.
534 */
535 if (has_shortname)
536 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200537 // Copy the string if it is shortened by :h and when it wasn't copied
538 // yet, because we are going to change it in place. Avoids changing
539 // the buffer name for "%:8".
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200540 if (*fnamelen < (int)STRLEN(*fnamep) || *fnamep == fname_start)
541 {
542 p = vim_strnsave(*fnamep, *fnamelen);
543 if (p == NULL)
544 return -1;
545 vim_free(*bufp);
546 *bufp = *fnamep = p;
547 }
548
Bram Moolenaar26262f82019-09-04 20:59:15 +0200549 // Split into two implementations - makes it easier. First is where
550 // there isn't a full name already, second is where there is.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200551 if (!has_fullname && !vim_isAbsName(*fnamep))
552 {
553 if (shortpath_for_partial(fnamep, bufp, fnamelen) == FAIL)
554 return -1;
555 }
556 else
557 {
558 int l = *fnamelen;
559
Bram Moolenaar26262f82019-09-04 20:59:15 +0200560 // Simple case, already have the full-name.
561 // Nearly always shorter, so try first time.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200562 if (get_short_pathname(fnamep, bufp, &l) == FAIL)
563 return -1;
564
565 if (l == 0)
566 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200567 // Couldn't find the filename, search the paths.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200568 l = *fnamelen;
569 if (shortpath_for_invalid_fname(fnamep, bufp, &l) == FAIL)
570 return -1;
571 }
572 *fnamelen = l;
573 }
574 }
575#endif // MSWIN
576
Bram Moolenaar26262f82019-09-04 20:59:15 +0200577 // ":t" - tail, just the basename
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200578 if (src[*usedlen] == ':' && src[*usedlen + 1] == 't')
579 {
580 *usedlen += 2;
581 *fnamelen -= (int)(tail - *fnamep);
582 *fnamep = tail;
583 }
584
Bram Moolenaar26262f82019-09-04 20:59:15 +0200585 // ":e" - extension, can be repeated
586 // ":r" - root, without extension, can be repeated
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200587 while (src[*usedlen] == ':'
588 && (src[*usedlen + 1] == 'e' || src[*usedlen + 1] == 'r'))
589 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200590 // find a '.' in the tail:
591 // - for second :e: before the current fname
592 // - otherwise: The last '.'
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200593 if (src[*usedlen + 1] == 'e' && *fnamep > tail)
594 s = *fnamep - 2;
595 else
596 s = *fnamep + *fnamelen - 1;
597 for ( ; s > tail; --s)
598 if (s[0] == '.')
599 break;
Bram Moolenaar26262f82019-09-04 20:59:15 +0200600 if (src[*usedlen + 1] == 'e') // :e
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200601 {
602 if (s > tail)
603 {
604 *fnamelen += (int)(*fnamep - (s + 1));
605 *fnamep = s + 1;
606#ifdef VMS
Bram Moolenaar26262f82019-09-04 20:59:15 +0200607 // cut version from the extension
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200608 s = *fnamep + *fnamelen - 1;
609 for ( ; s > *fnamep; --s)
610 if (s[0] == ';')
611 break;
612 if (s > *fnamep)
613 *fnamelen = s - *fnamep;
614#endif
615 }
616 else if (*fnamep <= tail)
617 *fnamelen = 0;
618 }
Bram Moolenaar26262f82019-09-04 20:59:15 +0200619 else // :r
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200620 {
Bram Moolenaarb1892952019-10-08 23:26:50 +0200621 char_u *limit = *fnamep;
622
623 if (limit < tail)
624 limit = tail;
625 if (s > limit) // remove one extension
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200626 *fnamelen = (int)(s - *fnamep);
627 }
628 *usedlen += 2;
629 }
630
Bram Moolenaar26262f82019-09-04 20:59:15 +0200631 // ":s?pat?foo?" - substitute
632 // ":gs?pat?foo?" - global substitute
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200633 if (src[*usedlen] == ':'
634 && (src[*usedlen + 1] == 's'
635 || (src[*usedlen + 1] == 'g' && src[*usedlen + 2] == 's')))
636 {
637 char_u *str;
638 char_u *pat;
639 char_u *sub;
640 int sep;
641 char_u *flags;
642 int didit = FALSE;
643
644 flags = (char_u *)"";
645 s = src + *usedlen + 2;
646 if (src[*usedlen + 1] == 'g')
647 {
648 flags = (char_u *)"g";
649 ++s;
650 }
651
652 sep = *s++;
653 if (sep)
654 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200655 // find end of pattern
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200656 p = vim_strchr(s, sep);
657 if (p != NULL)
658 {
Bram Moolenaar71ccd032020-06-12 22:59:11 +0200659 pat = vim_strnsave(s, p - s);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200660 if (pat != NULL)
661 {
662 s = p + 1;
Bram Moolenaar26262f82019-09-04 20:59:15 +0200663 // find end of substitution
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200664 p = vim_strchr(s, sep);
665 if (p != NULL)
666 {
Bram Moolenaar71ccd032020-06-12 22:59:11 +0200667 sub = vim_strnsave(s, p - s);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200668 str = vim_strnsave(*fnamep, *fnamelen);
669 if (sub != NULL && str != NULL)
670 {
671 *usedlen = (int)(p + 1 - src);
672 s = do_string_sub(str, pat, sub, NULL, flags);
673 if (s != NULL)
674 {
675 *fnamep = s;
676 *fnamelen = (int)STRLEN(s);
677 vim_free(*bufp);
678 *bufp = s;
679 didit = TRUE;
680 }
681 }
682 vim_free(sub);
683 vim_free(str);
684 }
685 vim_free(pat);
686 }
687 }
Bram Moolenaar26262f82019-09-04 20:59:15 +0200688 // after using ":s", repeat all the modifiers
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200689 if (didit)
690 goto repeat;
691 }
692 }
693
694 if (src[*usedlen] == ':' && src[*usedlen + 1] == 'S')
695 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200696 // vim_strsave_shellescape() needs a NUL terminated string.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200697 c = (*fnamep)[*fnamelen];
698 if (c != NUL)
699 (*fnamep)[*fnamelen] = NUL;
700 p = vim_strsave_shellescape(*fnamep, FALSE, FALSE);
701 if (c != NUL)
702 (*fnamep)[*fnamelen] = c;
703 if (p == NULL)
704 return -1;
705 vim_free(*bufp);
706 *bufp = *fnamep = p;
707 *fnamelen = (int)STRLEN(p);
708 *usedlen += 2;
709 }
710
711 return valid;
712}
713
Bram Moolenaar273af492020-09-25 23:49:01 +0200714/*
715 * Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
716 * "trim_len" specifies how many characters to keep for each directory.
717 * Must be 1 or more.
718 * It's done in-place.
719 */
720 static void
721shorten_dir_len(char_u *str, int trim_len)
722{
723 char_u *tail, *s, *d;
724 int skip = FALSE;
725 int dirchunk_len = 0;
726
727 tail = gettail(str);
728 d = str;
729 for (s = str; ; ++s)
730 {
731 if (s >= tail) // copy the whole tail
732 {
733 *d++ = *s;
734 if (*s == NUL)
735 break;
736 }
737 else if (vim_ispathsep(*s)) // copy '/' and next char
738 {
739 *d++ = *s;
740 skip = FALSE;
741 dirchunk_len = 0;
742 }
743 else if (!skip)
744 {
745 *d++ = *s; // copy next char
746 if (*s != '~' && *s != '.') // and leading "~" and "."
747 {
748 ++dirchunk_len; // only count word chars for the size
749
750 // keep copying chars until we have our preferred length (or
751 // until the above if/else branches move us along)
752 if (dirchunk_len >= trim_len)
753 skip = TRUE;
754 }
755
756 if (has_mbyte)
757 {
758 int l = mb_ptr2len(s);
759
760 while (--l > 0)
761 *d++ = *++s;
762 }
763 }
764 }
765}
766
767/*
768 * Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
769 * It's done in-place.
770 */
771 void
772shorten_dir(char_u *str)
773{
774 shorten_dir_len(str, 1);
775}
776
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200777#if defined(FEAT_EVAL) || defined(PROTO)
778
779/*
780 * "chdir(dir)" function
781 */
782 void
783f_chdir(typval_T *argvars, typval_T *rettv)
784{
785 char_u *cwd;
786 cdscope_T scope = CDSCOPE_GLOBAL;
787
788 rettv->v_type = VAR_STRING;
789 rettv->vval.v_string = NULL;
790
791 if (argvars[0].v_type != VAR_STRING)
Bram Moolenaarc5809432021-03-27 21:23:30 +0100792 {
Bram Moolenaard816cd92020-02-04 22:23:09 +0100793 // Returning an empty string means it failed.
Bram Moolenaar002bc792020-06-05 22:33:42 +0200794 // No error message, for historic reasons.
Bram Moolenaarc5809432021-03-27 21:23:30 +0100795 if (in_vim9script())
796 (void) check_for_string_arg(argvars, 0);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200797 return;
Bram Moolenaarc5809432021-03-27 21:23:30 +0100798 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200799
800 // Return the current directory
801 cwd = alloc(MAXPATHL);
802 if (cwd != NULL)
803 {
804 if (mch_dirname(cwd, MAXPATHL) != FAIL)
805 {
806#ifdef BACKSLASH_IN_FILENAME
807 slash_adjust(cwd);
808#endif
809 rettv->vval.v_string = vim_strsave(cwd);
810 }
811 vim_free(cwd);
812 }
813
814 if (curwin->w_localdir != NULL)
815 scope = CDSCOPE_WINDOW;
816 else if (curtab->tp_localdir != NULL)
817 scope = CDSCOPE_TABPAGE;
818
819 if (!changedir_func(argvars[0].vval.v_string, TRUE, scope))
820 // Directory change failed
821 VIM_CLEAR(rettv->vval.v_string);
822}
823
824/*
825 * "delete()" function
826 */
827 void
828f_delete(typval_T *argvars, typval_T *rettv)
829{
830 char_u nbuf[NUMBUFLEN];
831 char_u *name;
832 char_u *flags;
833
834 rettv->vval.v_number = -1;
835 if (check_restricted() || check_secure())
836 return;
837
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +0200838 if (in_vim9script()
839 && (check_for_string_arg(argvars, 0) == FAIL
840 || check_for_opt_string_arg(argvars, 1) == FAIL))
841 return;
842
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200843 name = tv_get_string(&argvars[0]);
844 if (name == NULL || *name == NUL)
845 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +0000846 emsg(_(e_invalid_argument));
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200847 return;
848 }
849
850 if (argvars[1].v_type != VAR_UNKNOWN)
851 flags = tv_get_string_buf(&argvars[1], nbuf);
852 else
853 flags = (char_u *)"";
854
855 if (*flags == NUL)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200856 // delete a file
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200857 rettv->vval.v_number = mch_remove(name) == 0 ? 0 : -1;
858 else if (STRCMP(flags, "d") == 0)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200859 // delete an empty directory
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200860 rettv->vval.v_number = mch_rmdir(name) == 0 ? 0 : -1;
861 else if (STRCMP(flags, "rf") == 0)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200862 // delete a directory recursively
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200863 rettv->vval.v_number = delete_recursive(name);
864 else
Bram Moolenaar108010a2021-06-27 22:03:33 +0200865 semsg(_(e_invalid_expression_str), flags);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200866}
867
868/*
869 * "executable()" function
870 */
871 void
872f_executable(typval_T *argvars, typval_T *rettv)
873{
Bram Moolenaar32105ae2021-03-27 18:59:25 +0100874 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100875 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200876
Bram Moolenaar26262f82019-09-04 20:59:15 +0200877 // Check in $PATH and also check directly if there is a directory name.
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100878 rettv->vval.v_number = mch_can_exe(tv_get_string(&argvars[0]), NULL, TRUE);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200879}
880
881/*
882 * "exepath()" function
883 */
884 void
885f_exepath(typval_T *argvars, typval_T *rettv)
886{
887 char_u *p = NULL;
888
Bram Moolenaar32105ae2021-03-27 18:59:25 +0100889 if (in_vim9script() && check_for_nonempty_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100890 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200891 (void)mch_can_exe(tv_get_string(&argvars[0]), &p, TRUE);
892 rettv->v_type = VAR_STRING;
893 rettv->vval.v_string = p;
894}
895
896/*
Bram Moolenaar4dea2d92022-03-31 11:37:57 +0100897 * Return TRUE if "fname" is a readable file.
898 */
899 int
900file_is_readable(char_u *fname)
901{
902 int fd;
903
904#ifndef O_NONBLOCK
905# define O_NONBLOCK 0
906#endif
907 if (*fname && !mch_isdir(fname)
908 && (fd = mch_open((char *)fname, O_RDONLY | O_NONBLOCK, 0)) >= 0)
909 {
910 close(fd);
911 return TRUE;
912 }
913 return FALSE;
914}
915
916/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200917 * "filereadable()" function
918 */
919 void
920f_filereadable(typval_T *argvars, typval_T *rettv)
921{
Bram Moolenaar32105ae2021-03-27 18:59:25 +0100922 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100923 return;
Bram Moolenaar4dea2d92022-03-31 11:37:57 +0100924 rettv->vval.v_number = file_is_readable(tv_get_string(&argvars[0]));
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200925}
926
927/*
928 * Return 0 for not writable, 1 for writable file, 2 for a dir which we have
929 * rights to write into.
930 */
931 void
932f_filewritable(typval_T *argvars, typval_T *rettv)
933{
Bram Moolenaar32105ae2021-03-27 18:59:25 +0100934 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100935 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200936 rettv->vval.v_number = filewritable(tv_get_string(&argvars[0]));
937}
938
Bram Moolenaar840d16f2019-09-10 21:27:18 +0200939 static void
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200940findfilendir(
941 typval_T *argvars UNUSED,
942 typval_T *rettv,
943 int find_what UNUSED)
944{
945#ifdef FEAT_SEARCHPATH
946 char_u *fname;
947 char_u *fresult = NULL;
948 char_u *path = *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path;
949 char_u *p;
950 char_u pathbuf[NUMBUFLEN];
951 int count = 1;
952 int first = TRUE;
953 int error = FALSE;
954#endif
955
956 rettv->vval.v_string = NULL;
957 rettv->v_type = VAR_STRING;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +0200958 if (in_vim9script()
959 && (check_for_nonempty_string_arg(argvars, 0) == FAIL
960 || check_for_opt_string_arg(argvars, 1) == FAIL
961 || (argvars[1].v_type != VAR_UNKNOWN
962 && check_for_opt_number_arg(argvars, 2) == FAIL)))
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100963 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200964
965#ifdef FEAT_SEARCHPATH
966 fname = tv_get_string(&argvars[0]);
967
968 if (argvars[1].v_type != VAR_UNKNOWN)
969 {
970 p = tv_get_string_buf_chk(&argvars[1], pathbuf);
971 if (p == NULL)
972 error = TRUE;
973 else
974 {
975 if (*p != NUL)
976 path = p;
977
978 if (argvars[2].v_type != VAR_UNKNOWN)
979 count = (int)tv_get_number_chk(&argvars[2], &error);
980 }
981 }
982
983 if (count < 0 && rettv_list_alloc(rettv) == FAIL)
984 error = TRUE;
985
986 if (*fname != NUL && !error)
987 {
988 do
989 {
990 if (rettv->v_type == VAR_STRING || rettv->v_type == VAR_LIST)
991 vim_free(fresult);
992 fresult = find_file_in_path_option(first ? fname : NULL,
993 first ? (int)STRLEN(fname) : 0,
994 0, first, path,
995 find_what,
996 curbuf->b_ffname,
997 find_what == FINDFILE_DIR
998 ? (char_u *)"" : curbuf->b_p_sua);
999 first = FALSE;
1000
1001 if (fresult != NULL && rettv->v_type == VAR_LIST)
1002 list_append_string(rettv->vval.v_list, fresult, -1);
1003
1004 } while ((rettv->v_type == VAR_LIST || --count > 0) && fresult != NULL);
1005 }
1006
1007 if (rettv->v_type == VAR_STRING)
1008 rettv->vval.v_string = fresult;
1009#endif
1010}
1011
1012/*
1013 * "finddir({fname}[, {path}[, {count}]])" function
1014 */
1015 void
1016f_finddir(typval_T *argvars, typval_T *rettv)
1017{
1018 findfilendir(argvars, rettv, FINDFILE_DIR);
1019}
1020
1021/*
1022 * "findfile({fname}[, {path}[, {count}]])" function
1023 */
1024 void
1025f_findfile(typval_T *argvars, typval_T *rettv)
1026{
1027 findfilendir(argvars, rettv, FINDFILE_FILE);
1028}
1029
1030/*
1031 * "fnamemodify({fname}, {mods})" function
1032 */
1033 void
1034f_fnamemodify(typval_T *argvars, typval_T *rettv)
1035{
1036 char_u *fname;
1037 char_u *mods;
1038 int usedlen = 0;
Bram Moolenaarc5308522020-12-13 12:25:35 +01001039 int len = 0;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001040 char_u *fbuf = NULL;
1041 char_u buf[NUMBUFLEN];
1042
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001043 if (in_vim9script()
1044 && (check_for_string_arg(argvars, 0) == FAIL
1045 || check_for_string_arg(argvars, 1) == FAIL))
Bram Moolenaar7bb4e742020-12-09 12:41:50 +01001046 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001047
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001048 fname = tv_get_string_chk(&argvars[0]);
1049 mods = tv_get_string_buf_chk(&argvars[1], buf);
Bram Moolenaarc5308522020-12-13 12:25:35 +01001050 if (mods == NULL || fname == NULL)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001051 fname = NULL;
Bram Moolenaarc5308522020-12-13 12:25:35 +01001052 else
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001053 {
1054 len = (int)STRLEN(fname);
Bram Moolenaarc5308522020-12-13 12:25:35 +01001055 if (mods != NULL && *mods != NUL)
1056 (void)modify_fname(mods, FALSE, &usedlen, &fname, &fbuf, &len);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001057 }
1058
1059 rettv->v_type = VAR_STRING;
1060 if (fname == NULL)
1061 rettv->vval.v_string = NULL;
1062 else
1063 rettv->vval.v_string = vim_strnsave(fname, len);
1064 vim_free(fbuf);
1065}
1066
1067/*
1068 * "getcwd()" function
1069 *
1070 * Return the current working directory of a window in a tab page.
1071 * First optional argument 'winnr' is the window number or -1 and the second
1072 * optional argument 'tabnr' is the tab page number.
1073 *
1074 * If no arguments are supplied, then return the directory of the current
1075 * window.
1076 * If only 'winnr' is specified and is not -1 or 0 then return the directory of
1077 * the specified window.
1078 * If 'winnr' is 0 then return the directory of the current window.
1079 * If both 'winnr and 'tabnr' are specified and 'winnr' is -1 then return the
1080 * directory of the specified tab page. Otherwise return the directory of the
1081 * specified window in the specified tab page.
1082 * If the window or the tab page doesn't exist then return NULL.
1083 */
1084 void
1085f_getcwd(typval_T *argvars, typval_T *rettv)
1086{
1087 win_T *wp = NULL;
1088 tabpage_T *tp = NULL;
1089 char_u *cwd;
1090 int global = FALSE;
1091
1092 rettv->v_type = VAR_STRING;
1093 rettv->vval.v_string = NULL;
1094
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001095 if (in_vim9script()
1096 && (check_for_opt_number_arg(argvars, 0) == FAIL
1097 || (argvars[0].v_type != VAR_UNKNOWN
1098 && check_for_opt_number_arg(argvars, 1) == FAIL)))
1099 return;
1100
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001101 if (argvars[0].v_type == VAR_NUMBER
1102 && argvars[0].vval.v_number == -1
1103 && argvars[1].v_type == VAR_UNKNOWN)
1104 global = TRUE;
1105 else
1106 wp = find_tabwin(&argvars[0], &argvars[1], &tp);
1107
Bram Moolenaar851c7a62021-11-18 20:47:31 +00001108 if (wp != NULL && wp->w_localdir != NULL
1109 && argvars[0].v_type != VAR_UNKNOWN)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001110 rettv->vval.v_string = vim_strsave(wp->w_localdir);
Bram Moolenaar851c7a62021-11-18 20:47:31 +00001111 else if (tp != NULL && tp->tp_localdir != NULL
1112 && argvars[0].v_type != VAR_UNKNOWN)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001113 rettv->vval.v_string = vim_strsave(tp->tp_localdir);
1114 else if (wp != NULL || tp != NULL || global)
1115 {
Bram Moolenaar851c7a62021-11-18 20:47:31 +00001116 if (globaldir != NULL && argvars[0].v_type != VAR_UNKNOWN)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001117 rettv->vval.v_string = vim_strsave(globaldir);
1118 else
1119 {
1120 cwd = alloc(MAXPATHL);
1121 if (cwd != NULL)
1122 {
1123 if (mch_dirname(cwd, MAXPATHL) != FAIL)
1124 rettv->vval.v_string = vim_strsave(cwd);
1125 vim_free(cwd);
1126 }
1127 }
1128 }
1129#ifdef BACKSLASH_IN_FILENAME
1130 if (rettv->vval.v_string != NULL)
1131 slash_adjust(rettv->vval.v_string);
1132#endif
1133}
1134
1135/*
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001136 * Convert "st" to file permission string.
1137 */
1138 char_u *
1139getfpermst(stat_T *st, char_u *perm)
1140{
1141 char_u flags[] = "rwx";
1142 int i;
1143
1144 for (i = 0; i < 9; i++)
1145 {
1146 if (st->st_mode & (1 << (8 - i)))
1147 perm[i] = flags[i % 3];
1148 else
1149 perm[i] = '-';
1150 }
1151 return perm;
1152}
1153
1154/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001155 * "getfperm({fname})" function
1156 */
1157 void
1158f_getfperm(typval_T *argvars, typval_T *rettv)
1159{
1160 char_u *fname;
1161 stat_T st;
1162 char_u *perm = NULL;
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001163 char_u permbuf[] = "---------";
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001164
Bram Moolenaar32105ae2021-03-27 18:59:25 +01001165 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +01001166 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001167
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001168 fname = tv_get_string(&argvars[0]);
1169
1170 rettv->v_type = VAR_STRING;
1171 if (mch_stat((char *)fname, &st) >= 0)
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001172 perm = vim_strsave(getfpermst(&st, permbuf));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001173 rettv->vval.v_string = perm;
1174}
1175
1176/*
1177 * "getfsize({fname})" function
1178 */
1179 void
1180f_getfsize(typval_T *argvars, typval_T *rettv)
1181{
1182 char_u *fname;
1183 stat_T st;
1184
Bram Moolenaar32105ae2021-03-27 18:59:25 +01001185 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +01001186 return;
1187
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001188 fname = tv_get_string(&argvars[0]);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001189 if (mch_stat((char *)fname, &st) >= 0)
1190 {
1191 if (mch_isdir(fname))
1192 rettv->vval.v_number = 0;
1193 else
1194 {
1195 rettv->vval.v_number = (varnumber_T)st.st_size;
1196
Bram Moolenaar26262f82019-09-04 20:59:15 +02001197 // non-perfect check for overflow
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001198 if ((off_T)rettv->vval.v_number != (off_T)st.st_size)
1199 rettv->vval.v_number = -2;
1200 }
1201 }
1202 else
1203 rettv->vval.v_number = -1;
1204}
1205
1206/*
1207 * "getftime({fname})" function
1208 */
1209 void
1210f_getftime(typval_T *argvars, typval_T *rettv)
1211{
1212 char_u *fname;
1213 stat_T st;
1214
Bram Moolenaar32105ae2021-03-27 18:59:25 +01001215 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +01001216 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001217
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001218 fname = tv_get_string(&argvars[0]);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001219 if (mch_stat((char *)fname, &st) >= 0)
1220 rettv->vval.v_number = (varnumber_T)st.st_mtime;
1221 else
1222 rettv->vval.v_number = -1;
1223}
1224
1225/*
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001226 * Convert "st" to file type string.
1227 */
1228 char_u *
1229getftypest(stat_T *st)
1230{
1231 char *t;
1232
1233 if (S_ISREG(st->st_mode))
1234 t = "file";
1235 else if (S_ISDIR(st->st_mode))
1236 t = "dir";
1237 else if (S_ISLNK(st->st_mode))
1238 t = "link";
1239 else if (S_ISBLK(st->st_mode))
1240 t = "bdev";
1241 else if (S_ISCHR(st->st_mode))
1242 t = "cdev";
1243 else if (S_ISFIFO(st->st_mode))
1244 t = "fifo";
1245 else if (S_ISSOCK(st->st_mode))
1246 t = "socket";
1247 else
1248 t = "other";
1249 return (char_u*)t;
1250}
1251
1252/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001253 * "getftype({fname})" function
1254 */
1255 void
1256f_getftype(typval_T *argvars, typval_T *rettv)
1257{
1258 char_u *fname;
1259 stat_T st;
1260 char_u *type = NULL;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001261
Bram Moolenaar32105ae2021-03-27 18:59:25 +01001262 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +01001263 return;
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001264
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001265 fname = tv_get_string(&argvars[0]);
1266
1267 rettv->v_type = VAR_STRING;
1268 if (mch_lstat((char *)fname, &st) >= 0)
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001269 type = vim_strsave(getftypest(&st));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001270 rettv->vval.v_string = type;
1271}
1272
1273/*
1274 * "glob()" function
1275 */
1276 void
1277f_glob(typval_T *argvars, typval_T *rettv)
1278{
1279 int options = WILD_SILENT|WILD_USE_NL;
1280 expand_T xpc;
1281 int error = FALSE;
1282
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02001283 if (in_vim9script()
1284 && (check_for_string_arg(argvars, 0) == FAIL
1285 || check_for_opt_bool_arg(argvars, 1) == FAIL
1286 || (argvars[1].v_type != VAR_UNKNOWN
1287 && (check_for_opt_bool_arg(argvars, 2) == FAIL
1288 || (argvars[2].v_type != VAR_UNKNOWN
1289 && check_for_opt_bool_arg(argvars, 3) == FAIL)))))
1290 return;
1291
Bram Moolenaar26262f82019-09-04 20:59:15 +02001292 // When the optional second argument is non-zero, don't remove matches
1293 // for 'wildignore' and don't put matches for 'suffixes' at the end.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001294 rettv->v_type = VAR_STRING;
1295 if (argvars[1].v_type != VAR_UNKNOWN)
1296 {
Bram Moolenaar5892ea12020-09-02 21:53:11 +02001297 if (tv_get_bool_chk(&argvars[1], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001298 options |= WILD_KEEP_ALL;
1299 if (argvars[2].v_type != VAR_UNKNOWN)
1300 {
Bram Moolenaar5892ea12020-09-02 21:53:11 +02001301 if (tv_get_bool_chk(&argvars[2], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001302 rettv_list_set(rettv, NULL);
1303 if (argvars[3].v_type != VAR_UNKNOWN
Bram Moolenaar5892ea12020-09-02 21:53:11 +02001304 && tv_get_bool_chk(&argvars[3], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001305 options |= WILD_ALLLINKS;
1306 }
1307 }
1308 if (!error)
1309 {
1310 ExpandInit(&xpc);
1311 xpc.xp_context = EXPAND_FILES;
1312 if (p_wic)
1313 options += WILD_ICASE;
1314 if (rettv->v_type == VAR_STRING)
1315 rettv->vval.v_string = ExpandOne(&xpc, tv_get_string(&argvars[0]),
1316 NULL, options, WILD_ALL);
1317 else if (rettv_list_alloc(rettv) != FAIL)
1318 {
1319 int i;
1320
1321 ExpandOne(&xpc, tv_get_string(&argvars[0]),
1322 NULL, options, WILD_ALL_KEEP);
1323 for (i = 0; i < xpc.xp_numfiles; i++)
1324 list_append_string(rettv->vval.v_list, xpc.xp_files[i], -1);
1325
1326 ExpandCleanup(&xpc);
1327 }
1328 }
1329 else
1330 rettv->vval.v_string = NULL;
1331}
1332
1333/*
1334 * "glob2regpat()" function
1335 */
1336 void
1337f_glob2regpat(typval_T *argvars, typval_T *rettv)
1338{
Bram Moolenaar3cfa5b12021-06-06 14:14:39 +02001339 char_u buf[NUMBUFLEN];
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001340 char_u *pat;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001341
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001342 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
1343 return;
1344
1345 pat = tv_get_string_buf_chk_strict(&argvars[0], buf, in_vim9script());
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001346 rettv->v_type = VAR_STRING;
1347 rettv->vval.v_string = (pat == NULL)
1348 ? NULL : file_pat_to_reg_pat(pat, NULL, NULL, FALSE);
1349}
1350
1351/*
1352 * "globpath()" function
1353 */
1354 void
1355f_globpath(typval_T *argvars, typval_T *rettv)
1356{
1357 int flags = WILD_IGNORE_COMPLETESLASH;
1358 char_u buf1[NUMBUFLEN];
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02001359 char_u *file;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001360 int error = FALSE;
1361 garray_T ga;
1362 int i;
1363
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02001364 if (in_vim9script()
1365 && (check_for_string_arg(argvars, 0) == FAIL
1366 || check_for_string_arg(argvars, 1) == FAIL
1367 || check_for_opt_bool_arg(argvars, 2) == FAIL
1368 || (argvars[2].v_type != VAR_UNKNOWN
1369 && (check_for_opt_bool_arg(argvars, 3) == FAIL
1370 || (argvars[3].v_type != VAR_UNKNOWN
1371 && check_for_opt_bool_arg(argvars, 4) == FAIL)))))
1372 return;
1373
1374 file = tv_get_string_buf_chk(&argvars[1], buf1);
1375
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001376 // When the optional second argument is non-zero, don't remove matches
1377 // for 'wildignore' and don't put matches for 'suffixes' at the end.
1378 rettv->v_type = VAR_STRING;
1379 if (argvars[2].v_type != VAR_UNKNOWN)
1380 {
Bram Moolenaarf966ce52020-09-02 21:57:07 +02001381 if (tv_get_bool_chk(&argvars[2], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001382 flags |= WILD_KEEP_ALL;
1383 if (argvars[3].v_type != VAR_UNKNOWN)
1384 {
Bram Moolenaarf966ce52020-09-02 21:57:07 +02001385 if (tv_get_bool_chk(&argvars[3], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001386 rettv_list_set(rettv, NULL);
1387 if (argvars[4].v_type != VAR_UNKNOWN
Bram Moolenaarf966ce52020-09-02 21:57:07 +02001388 && tv_get_bool_chk(&argvars[4], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001389 flags |= WILD_ALLLINKS;
1390 }
1391 }
1392 if (file != NULL && !error)
1393 {
Bram Moolenaar04935fb2022-01-08 16:19:22 +00001394 ga_init2(&ga, sizeof(char_u *), 10);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001395 globpath(tv_get_string(&argvars[0]), file, &ga, flags);
1396 if (rettv->v_type == VAR_STRING)
1397 rettv->vval.v_string = ga_concat_strings(&ga, "\n");
1398 else if (rettv_list_alloc(rettv) != FAIL)
1399 for (i = 0; i < ga.ga_len; ++i)
1400 list_append_string(rettv->vval.v_list,
1401 ((char_u **)(ga.ga_data))[i], -1);
1402 ga_clear_strings(&ga);
1403 }
1404 else
1405 rettv->vval.v_string = NULL;
1406}
1407
1408/*
1409 * "isdirectory()" function
1410 */
1411 void
1412f_isdirectory(typval_T *argvars, typval_T *rettv)
1413{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001414 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
1415 return;
1416
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001417 rettv->vval.v_number = mch_isdir(tv_get_string(&argvars[0]));
1418}
1419
1420/*
LemonBoydca1d402022-04-28 15:26:33 +01001421 * "isabsolutepath()" function
1422 */
1423 void
1424f_isabsolutepath(typval_T *argvars, typval_T *rettv)
1425{
1426 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
1427 return;
1428
1429 rettv->vval.v_number = mch_isFullName(tv_get_string_strict(&argvars[0]));
1430}
1431
1432/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001433 * Create the directory in which "dir" is located, and higher levels when
1434 * needed.
1435 * Return OK or FAIL.
1436 */
1437 static int
1438mkdir_recurse(char_u *dir, int prot)
1439{
1440 char_u *p;
1441 char_u *updir;
1442 int r = FAIL;
1443
Bram Moolenaar26262f82019-09-04 20:59:15 +02001444 // Get end of directory name in "dir".
1445 // We're done when it's "/" or "c:/".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001446 p = gettail_sep(dir);
1447 if (p <= get_past_head(dir))
1448 return OK;
1449
Bram Moolenaar26262f82019-09-04 20:59:15 +02001450 // If the directory exists we're done. Otherwise: create it.
Bram Moolenaar71ccd032020-06-12 22:59:11 +02001451 updir = vim_strnsave(dir, p - dir);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001452 if (updir == NULL)
1453 return FAIL;
1454 if (mch_isdir(updir))
1455 r = OK;
1456 else if (mkdir_recurse(updir, prot) == OK)
1457 r = vim_mkdir_emsg(updir, prot);
1458 vim_free(updir);
1459 return r;
1460}
1461
1462/*
1463 * "mkdir()" function
1464 */
1465 void
1466f_mkdir(typval_T *argvars, typval_T *rettv)
1467{
1468 char_u *dir;
1469 char_u buf[NUMBUFLEN];
1470 int prot = 0755;
1471
1472 rettv->vval.v_number = FAIL;
1473 if (check_restricted() || check_secure())
1474 return;
1475
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001476 if (in_vim9script()
1477 && (check_for_nonempty_string_arg(argvars, 0) == FAIL
1478 || check_for_opt_string_arg(argvars, 1) == FAIL
1479 || (argvars[1].v_type != VAR_UNKNOWN
1480 && check_for_opt_number_arg(argvars, 2) == FAIL)))
1481 return;
1482
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001483 dir = tv_get_string_buf(&argvars[0], buf);
1484 if (*dir == NUL)
1485 return;
1486
1487 if (*gettail(dir) == NUL)
Bram Moolenaar26262f82019-09-04 20:59:15 +02001488 // remove trailing slashes
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001489 *gettail_sep(dir) = NUL;
1490
1491 if (argvars[1].v_type != VAR_UNKNOWN)
1492 {
1493 if (argvars[2].v_type != VAR_UNKNOWN)
1494 {
1495 prot = (int)tv_get_number_chk(&argvars[2], NULL);
1496 if (prot == -1)
1497 return;
1498 }
1499 if (STRCMP(tv_get_string(&argvars[1]), "p") == 0)
1500 {
1501 if (mch_isdir(dir))
1502 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001503 // With the "p" flag it's OK if the dir already exists.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001504 rettv->vval.v_number = OK;
1505 return;
1506 }
1507 mkdir_recurse(dir, prot);
1508 }
1509 }
1510 rettv->vval.v_number = vim_mkdir_emsg(dir, prot);
1511}
1512
1513/*
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02001514 * "pathshorten()" function
1515 */
1516 void
1517f_pathshorten(typval_T *argvars, typval_T *rettv)
1518{
1519 char_u *p;
Bram Moolenaar6a33ef02020-09-25 22:42:48 +02001520 int trim_len = 1;
1521
Yegappan Lakshmanan1a71d312021-07-15 12:49:58 +02001522 if (in_vim9script()
1523 && (check_for_string_arg(argvars, 0) == FAIL
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02001524 || check_for_opt_number_arg(argvars, 1) == FAIL))
Yegappan Lakshmanan1a71d312021-07-15 12:49:58 +02001525 return;
1526
Bram Moolenaar6a33ef02020-09-25 22:42:48 +02001527 if (argvars[1].v_type != VAR_UNKNOWN)
1528 {
1529 trim_len = (int)tv_get_number(&argvars[1]);
1530 if (trim_len < 1)
1531 trim_len = 1;
1532 }
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02001533
1534 rettv->v_type = VAR_STRING;
1535 p = tv_get_string_chk(&argvars[0]);
Bram Moolenaar6a33ef02020-09-25 22:42:48 +02001536
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02001537 if (p == NULL)
1538 rettv->vval.v_string = NULL;
1539 else
1540 {
1541 p = vim_strsave(p);
1542 rettv->vval.v_string = p;
1543 if (p != NULL)
Bram Moolenaar6a33ef02020-09-25 22:42:48 +02001544 shorten_dir_len(p, trim_len);
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02001545 }
1546}
1547
1548/*
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001549 * Common code for readdir_checkitem() and readdirex_checkitem().
1550 * Either "name" or "dict" is NULL.
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001551 */
1552 static int
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001553checkitem_common(void *context, char_u *name, dict_T *dict)
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001554{
1555 typval_T *expr = (typval_T *)context;
1556 typval_T save_val;
1557 typval_T rettv;
1558 typval_T argv[2];
1559 int retval = 0;
1560 int error = FALSE;
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001561
1562 prepare_vimvar(VV_VAL, &save_val);
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001563 if (name != NULL)
1564 {
1565 set_vim_var_string(VV_VAL, name, -1);
1566 argv[0].v_type = VAR_STRING;
1567 argv[0].vval.v_string = name;
1568 }
1569 else
1570 {
1571 set_vim_var_dict(VV_VAL, dict);
1572 argv[0].v_type = VAR_DICT;
1573 argv[0].vval.v_dict = dict;
1574 }
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001575
1576 if (eval_expr_typval(expr, argv, 1, &rettv) == FAIL)
1577 goto theend;
1578
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001579 // We want to use -1, but also true/false should be allowed.
1580 if (rettv.v_type == VAR_SPECIAL || rettv.v_type == VAR_BOOL)
1581 {
1582 rettv.v_type = VAR_NUMBER;
1583 rettv.vval.v_number = rettv.vval.v_number == VVAL_TRUE;
1584 }
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001585 retval = tv_get_number_chk(&rettv, &error);
1586 if (error)
1587 retval = -1;
1588 clear_tv(&rettv);
1589
1590theend:
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001591 if (name != NULL)
1592 set_vim_var_string(VV_VAL, NULL, 0);
1593 else
1594 set_vim_var_dict(VV_VAL, NULL);
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001595 restore_vimvar(VV_VAL, &save_val);
1596 return retval;
1597}
1598
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001599/*
1600 * Evaluate "expr" (= "context") for readdir().
1601 */
1602 static int
1603readdir_checkitem(void *context, void *item)
1604{
1605 char_u *name = (char_u *)item;
1606
1607 return checkitem_common(context, name, NULL);
1608}
1609
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001610 static int
1611readdirex_dict_arg(typval_T *tv, int *cmp)
1612{
1613 char_u *compare;
1614
1615 if (tv->v_type != VAR_DICT)
1616 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00001617 emsg(_(e_dictionary_required));
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001618 return FAIL;
1619 }
1620
Yegappan Lakshmanan4829c1c2022-04-04 15:16:54 +01001621 if (dict_has_key(tv->vval.v_dict, "sort"))
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001622 compare = dict_get_string(tv->vval.v_dict, (char_u *)"sort", FALSE);
1623 else
1624 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00001625 semsg(_(e_dictionary_key_str_required), "sort");
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001626 return FAIL;
1627 }
1628
1629 if (STRCMP(compare, (char_u *) "none") == 0)
1630 *cmp = READDIR_SORT_NONE;
1631 else if (STRCMP(compare, (char_u *) "case") == 0)
1632 *cmp = READDIR_SORT_BYTE;
1633 else if (STRCMP(compare, (char_u *) "icase") == 0)
1634 *cmp = READDIR_SORT_IC;
1635 else if (STRCMP(compare, (char_u *) "collate") == 0)
1636 *cmp = READDIR_SORT_COLLATE;
1637 return OK;
1638}
1639
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001640/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001641 * "readdir()" function
1642 */
1643 void
1644f_readdir(typval_T *argvars, typval_T *rettv)
1645{
1646 typval_T *expr;
1647 int ret;
1648 char_u *path;
1649 char_u *p;
1650 garray_T ga;
1651 int i;
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01001652 int sort = READDIR_SORT_BYTE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001653
1654 if (rettv_list_alloc(rettv) == FAIL)
1655 return;
Yegappan Lakshmanan5bca9062021-07-24 21:33:26 +02001656
1657 if (in_vim9script()
1658 && (check_for_string_arg(argvars, 0) == FAIL
1659 || (argvars[1].v_type != VAR_UNKNOWN
1660 && check_for_opt_dict_arg(argvars, 2) == FAIL)))
1661 return;
1662
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001663 path = tv_get_string(&argvars[0]);
1664 expr = &argvars[1];
1665
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001666 if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN &&
1667 readdirex_dict_arg(&argvars[2], &sort) == FAIL)
1668 return;
1669
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001670 ret = readdir_core(&ga, path, FALSE, (void *)expr,
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001671 (expr->v_type == VAR_UNKNOWN) ? NULL : readdir_checkitem, sort);
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001672 if (ret == OK)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001673 {
1674 for (i = 0; i < ga.ga_len; i++)
1675 {
1676 p = ((char_u **)ga.ga_data)[i];
1677 list_append_string(rettv->vval.v_list, p, -1);
1678 }
1679 }
1680 ga_clear_strings(&ga);
1681}
1682
1683/*
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001684 * Evaluate "expr" (= "context") for readdirex().
1685 */
1686 static int
1687readdirex_checkitem(void *context, void *item)
1688{
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001689 dict_T *dict = (dict_T*)item;
1690
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001691 return checkitem_common(context, NULL, dict);
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001692}
1693
1694/*
1695 * "readdirex()" function
1696 */
1697 void
1698f_readdirex(typval_T *argvars, typval_T *rettv)
1699{
1700 typval_T *expr;
1701 int ret;
1702 char_u *path;
1703 garray_T ga;
1704 int i;
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01001705 int sort = READDIR_SORT_BYTE;
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001706
1707 if (rettv_list_alloc(rettv) == FAIL)
1708 return;
Yegappan Lakshmanan5bca9062021-07-24 21:33:26 +02001709
1710 if (in_vim9script()
1711 && (check_for_string_arg(argvars, 0) == FAIL
1712 || (argvars[1].v_type != VAR_UNKNOWN
1713 && check_for_opt_dict_arg(argvars, 2) == FAIL)))
1714 return;
1715
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001716 path = tv_get_string(&argvars[0]);
1717 expr = &argvars[1];
1718
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001719 if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN &&
1720 readdirex_dict_arg(&argvars[2], &sort) == FAIL)
1721 return;
1722
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001723 ret = readdir_core(&ga, path, TRUE, (void *)expr,
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001724 (expr->v_type == VAR_UNKNOWN) ? NULL : readdirex_checkitem, sort);
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001725 if (ret == OK)
1726 {
1727 for (i = 0; i < ga.ga_len; i++)
1728 {
1729 dict_T *dict = ((dict_T**)ga.ga_data)[i];
1730 list_append_dict(rettv->vval.v_list, dict);
1731 dict_unref(dict);
1732 }
1733 }
1734 ga_clear(&ga);
1735}
1736
1737/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001738 * "readfile()" function
1739 */
Bram Moolenaarc423ad72021-01-13 20:38:03 +01001740 static void
1741read_file_or_blob(typval_T *argvars, typval_T *rettv, int always_blob)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001742{
1743 int binary = FALSE;
Bram Moolenaarc423ad72021-01-13 20:38:03 +01001744 int blob = always_blob;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001745 int failed = FALSE;
1746 char_u *fname;
1747 FILE *fd;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001748 char_u buf[(IOSIZE/256)*256]; // rounded to avoid odd + 1
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001749 int io_size = sizeof(buf);
Bram Moolenaar26262f82019-09-04 20:59:15 +02001750 int readlen; // size of last fread()
1751 char_u *prev = NULL; // previously read bytes, if any
1752 long prevlen = 0; // length of data in prev
1753 long prevsize = 0; // size of prev buffer
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001754 long maxline = MAXLNUM;
1755 long cnt = 0;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001756 char_u *p; // position in buf
1757 char_u *start; // start of current line
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001758
1759 if (argvars[1].v_type != VAR_UNKNOWN)
1760 {
1761 if (STRCMP(tv_get_string(&argvars[1]), "b") == 0)
1762 binary = TRUE;
1763 if (STRCMP(tv_get_string(&argvars[1]), "B") == 0)
1764 blob = TRUE;
1765
1766 if (argvars[2].v_type != VAR_UNKNOWN)
1767 maxline = (long)tv_get_number(&argvars[2]);
1768 }
1769
Bram Moolenaar15352dc2020-04-06 21:12:42 +02001770 if ((blob ? rettv_blob_alloc(rettv) : rettv_list_alloc(rettv)) == FAIL)
1771 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001772
Bram Moolenaar26262f82019-09-04 20:59:15 +02001773 // Always open the file in binary mode, library functions have a mind of
1774 // their own about CR-LF conversion.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001775 fname = tv_get_string(&argvars[0]);
Bram Moolenaar15352dc2020-04-06 21:12:42 +02001776
1777 if (mch_isdir(fname))
1778 {
Bram Moolenaar4dea2d92022-03-31 11:37:57 +01001779 semsg(_(e_str_is_directory), fname);
Bram Moolenaar15352dc2020-04-06 21:12:42 +02001780 return;
1781 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001782 if (*fname == NUL || (fd = mch_fopen((char *)fname, READBIN)) == NULL)
1783 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00001784 semsg(_(e_cant_open_file_str), *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001785 return;
1786 }
1787
1788 if (blob)
1789 {
1790 if (read_blob(fd, rettv->vval.v_blob) == FAIL)
1791 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00001792 semsg(_(e_cant_read_file_str), fname);
Bram Moolenaar15352dc2020-04-06 21:12:42 +02001793 // An empty blob is returned on error.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001794 blob_free(rettv->vval.v_blob);
Bram Moolenaar15352dc2020-04-06 21:12:42 +02001795 rettv->vval.v_blob = NULL;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001796 }
1797 fclose(fd);
1798 return;
1799 }
1800
1801 while (cnt < maxline || maxline < 0)
1802 {
1803 readlen = (int)fread(buf, 1, io_size, fd);
1804
Bram Moolenaar26262f82019-09-04 20:59:15 +02001805 // This for loop processes what was read, but is also entered at end
1806 // of file so that either:
1807 // - an incomplete line gets written
1808 // - a "binary" file gets an empty line at the end if it ends in a
1809 // newline.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001810 for (p = buf, start = buf;
1811 p < buf + readlen || (readlen <= 0 && (prevlen > 0 || binary));
1812 ++p)
1813 {
Dominique Pellef5d639a2022-01-12 15:24:40 +00001814 if (readlen <= 0 || *p == '\n')
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001815 {
1816 listitem_T *li;
1817 char_u *s = NULL;
1818 long_u len = p - start;
1819
Bram Moolenaar26262f82019-09-04 20:59:15 +02001820 // Finished a line. Remove CRs before NL.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001821 if (readlen > 0 && !binary)
1822 {
1823 while (len > 0 && start[len - 1] == '\r')
1824 --len;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001825 // removal may cross back to the "prev" string
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001826 if (len == 0)
1827 while (prevlen > 0 && prev[prevlen - 1] == '\r')
1828 --prevlen;
1829 }
1830 if (prevlen == 0)
Bram Moolenaar71ccd032020-06-12 22:59:11 +02001831 s = vim_strnsave(start, len);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001832 else
1833 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001834 // Change "prev" buffer to be the right size. This way
1835 // the bytes are only copied once, and very long lines are
1836 // allocated only once.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001837 if ((s = vim_realloc(prev, prevlen + len + 1)) != NULL)
1838 {
1839 mch_memmove(s + prevlen, start, len);
1840 s[prevlen + len] = NUL;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001841 prev = NULL; // the list will own the string
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001842 prevlen = prevsize = 0;
1843 }
1844 }
1845 if (s == NULL)
1846 {
1847 do_outofmem_msg((long_u) prevlen + len + 1);
1848 failed = TRUE;
1849 break;
1850 }
1851
1852 if ((li = listitem_alloc()) == NULL)
1853 {
1854 vim_free(s);
1855 failed = TRUE;
1856 break;
1857 }
1858 li->li_tv.v_type = VAR_STRING;
1859 li->li_tv.v_lock = 0;
1860 li->li_tv.vval.v_string = s;
1861 list_append(rettv->vval.v_list, li);
1862
Bram Moolenaar26262f82019-09-04 20:59:15 +02001863 start = p + 1; // step over newline
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001864 if ((++cnt >= maxline && maxline >= 0) || readlen <= 0)
1865 break;
1866 }
1867 else if (*p == NUL)
1868 *p = '\n';
Bram Moolenaar26262f82019-09-04 20:59:15 +02001869 // Check for utf8 "bom"; U+FEFF is encoded as EF BB BF. Do this
1870 // when finding the BF and check the previous two bytes.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001871 else if (*p == 0xbf && enc_utf8 && !binary)
1872 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001873 // Find the two bytes before the 0xbf. If p is at buf, or buf
1874 // + 1, these may be in the "prev" string.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001875 char_u back1 = p >= buf + 1 ? p[-1]
1876 : prevlen >= 1 ? prev[prevlen - 1] : NUL;
1877 char_u back2 = p >= buf + 2 ? p[-2]
1878 : p == buf + 1 && prevlen >= 1 ? prev[prevlen - 1]
1879 : prevlen >= 2 ? prev[prevlen - 2] : NUL;
1880
1881 if (back2 == 0xef && back1 == 0xbb)
1882 {
1883 char_u *dest = p - 2;
1884
Bram Moolenaar26262f82019-09-04 20:59:15 +02001885 // Usually a BOM is at the beginning of a file, and so at
1886 // the beginning of a line; then we can just step over it.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001887 if (start == dest)
1888 start = p + 1;
1889 else
1890 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001891 // have to shuffle buf to close gap
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001892 int adjust_prevlen = 0;
1893
1894 if (dest < buf)
1895 {
Bram Moolenaarc423ad72021-01-13 20:38:03 +01001896 // must be 1 or 2
1897 adjust_prevlen = (int)(buf - dest);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001898 dest = buf;
1899 }
1900 if (readlen > p - buf + 1)
1901 mch_memmove(dest, p + 1, readlen - (p - buf) - 1);
1902 readlen -= 3 - adjust_prevlen;
1903 prevlen -= adjust_prevlen;
1904 p = dest - 1;
1905 }
1906 }
1907 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02001908 } // for
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001909
1910 if (failed || (cnt >= maxline && maxline >= 0) || readlen <= 0)
1911 break;
1912 if (start < p)
1913 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001914 // There's part of a line in buf, store it in "prev".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001915 if (p - start + prevlen >= prevsize)
1916 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001917 // need bigger "prev" buffer
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001918 char_u *newprev;
1919
Bram Moolenaar26262f82019-09-04 20:59:15 +02001920 // A common use case is ordinary text files and "prev" gets a
1921 // fragment of a line, so the first allocation is made
1922 // small, to avoid repeatedly 'allocing' large and
1923 // 'reallocing' small.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001924 if (prevsize == 0)
1925 prevsize = (long)(p - start);
1926 else
1927 {
1928 long grow50pc = (prevsize * 3) / 2;
1929 long growmin = (long)((p - start) * 2 + prevlen);
1930 prevsize = grow50pc > growmin ? grow50pc : growmin;
1931 }
1932 newprev = vim_realloc(prev, prevsize);
1933 if (newprev == NULL)
1934 {
1935 do_outofmem_msg((long_u)prevsize);
1936 failed = TRUE;
1937 break;
1938 }
1939 prev = newprev;
1940 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02001941 // Add the line part to end of "prev".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001942 mch_memmove(prev + prevlen, start, p - start);
1943 prevlen += (long)(p - start);
1944 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02001945 } // while
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001946
Bram Moolenaar26262f82019-09-04 20:59:15 +02001947 // For a negative line count use only the lines at the end of the file,
1948 // free the rest.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001949 if (!failed && maxline < 0)
1950 while (cnt > -maxline)
1951 {
1952 listitem_remove(rettv->vval.v_list, rettv->vval.v_list->lv_first);
1953 --cnt;
1954 }
1955
1956 if (failed)
1957 {
1958 // an empty list is returned on error
1959 list_free(rettv->vval.v_list);
1960 rettv_list_alloc(rettv);
1961 }
1962
1963 vim_free(prev);
1964 fclose(fd);
1965}
1966
1967/*
Bram Moolenaarc423ad72021-01-13 20:38:03 +01001968 * "readblob()" function
1969 */
1970 void
1971f_readblob(typval_T *argvars, typval_T *rettv)
1972{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001973 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
1974 return;
1975
Bram Moolenaarc423ad72021-01-13 20:38:03 +01001976 read_file_or_blob(argvars, rettv, TRUE);
1977}
1978
1979/*
1980 * "readfile()" function
1981 */
1982 void
1983f_readfile(typval_T *argvars, typval_T *rettv)
1984{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02001985 if (in_vim9script()
1986 && (check_for_nonempty_string_arg(argvars, 0) == FAIL
1987 || check_for_opt_string_arg(argvars, 1) == FAIL
1988 || (argvars[1].v_type != VAR_UNKNOWN
1989 && check_for_opt_number_arg(argvars, 2) == FAIL)))
1990 return;
1991
Bram Moolenaarc423ad72021-01-13 20:38:03 +01001992 read_file_or_blob(argvars, rettv, FALSE);
1993}
1994
1995/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001996 * "resolve()" function
1997 */
1998 void
1999f_resolve(typval_T *argvars, typval_T *rettv)
2000{
2001 char_u *p;
2002#ifdef HAVE_READLINK
2003 char_u *buf = NULL;
2004#endif
2005
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02002006 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
2007 return;
2008
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002009 p = tv_get_string(&argvars[0]);
2010#ifdef FEAT_SHORTCUT
2011 {
2012 char_u *v = NULL;
2013
2014 v = mch_resolve_path(p, TRUE);
2015 if (v != NULL)
2016 rettv->vval.v_string = v;
2017 else
2018 rettv->vval.v_string = vim_strsave(p);
2019 }
2020#else
2021# ifdef HAVE_READLINK
2022 {
2023 char_u *cpy;
2024 int len;
2025 char_u *remain = NULL;
2026 char_u *q;
2027 int is_relative_to_current = FALSE;
2028 int has_trailing_pathsep = FALSE;
2029 int limit = 100;
2030
2031 p = vim_strsave(p);
Bram Moolenaar70188f52019-12-23 18:18:52 +01002032 if (p == NULL)
2033 goto fail;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002034 if (p[0] == '.' && (vim_ispathsep(p[1])
2035 || (p[1] == '.' && (vim_ispathsep(p[2])))))
2036 is_relative_to_current = TRUE;
2037
2038 len = STRLEN(p);
Bram Moolenaar50c4e9e2020-10-05 20:38:06 +02002039 if (len > 1 && after_pathsep(p, p + len))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002040 {
2041 has_trailing_pathsep = TRUE;
Bram Moolenaar26262f82019-09-04 20:59:15 +02002042 p[len - 1] = NUL; // the trailing slash breaks readlink()
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002043 }
2044
2045 q = getnextcomp(p);
2046 if (*q != NUL)
2047 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002048 // Separate the first path component in "p", and keep the
2049 // remainder (beginning with the path separator).
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002050 remain = vim_strsave(q - 1);
2051 q[-1] = NUL;
2052 }
2053
2054 buf = alloc(MAXPATHL + 1);
2055 if (buf == NULL)
Bram Moolenaar70188f52019-12-23 18:18:52 +01002056 {
2057 vim_free(p);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002058 goto fail;
Bram Moolenaar70188f52019-12-23 18:18:52 +01002059 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002060
2061 for (;;)
2062 {
2063 for (;;)
2064 {
2065 len = readlink((char *)p, (char *)buf, MAXPATHL);
2066 if (len <= 0)
2067 break;
2068 buf[len] = NUL;
2069
2070 if (limit-- == 0)
2071 {
2072 vim_free(p);
2073 vim_free(remain);
Bram Moolenaara6f79292022-01-04 21:30:47 +00002074 emsg(_(e_too_many_symbolic_links_cycle));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002075 rettv->vval.v_string = NULL;
2076 goto fail;
2077 }
2078
Bram Moolenaar26262f82019-09-04 20:59:15 +02002079 // Ensure that the result will have a trailing path separator
2080 // if the argument has one.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002081 if (remain == NULL && has_trailing_pathsep)
2082 add_pathsep(buf);
2083
Bram Moolenaar26262f82019-09-04 20:59:15 +02002084 // Separate the first path component in the link value and
2085 // concatenate the remainders.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002086 q = getnextcomp(vim_ispathsep(*buf) ? buf + 1 : buf);
2087 if (*q != NUL)
2088 {
2089 if (remain == NULL)
2090 remain = vim_strsave(q - 1);
2091 else
2092 {
2093 cpy = concat_str(q - 1, remain);
2094 if (cpy != NULL)
2095 {
2096 vim_free(remain);
2097 remain = cpy;
2098 }
2099 }
2100 q[-1] = NUL;
2101 }
2102
2103 q = gettail(p);
2104 if (q > p && *q == NUL)
2105 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002106 // Ignore trailing path separator.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002107 q[-1] = NUL;
2108 q = gettail(p);
2109 }
2110 if (q > p && !mch_isFullName(buf))
2111 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002112 // symlink is relative to directory of argument
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002113 cpy = alloc(STRLEN(p) + STRLEN(buf) + 1);
2114 if (cpy != NULL)
2115 {
2116 STRCPY(cpy, p);
2117 STRCPY(gettail(cpy), buf);
2118 vim_free(p);
2119 p = cpy;
2120 }
2121 }
2122 else
2123 {
2124 vim_free(p);
2125 p = vim_strsave(buf);
2126 }
2127 }
2128
2129 if (remain == NULL)
2130 break;
2131
Bram Moolenaar26262f82019-09-04 20:59:15 +02002132 // Append the first path component of "remain" to "p".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002133 q = getnextcomp(remain + 1);
2134 len = q - remain - (*q != NUL);
2135 cpy = vim_strnsave(p, STRLEN(p) + len);
2136 if (cpy != NULL)
2137 {
2138 STRNCAT(cpy, remain, len);
2139 vim_free(p);
2140 p = cpy;
2141 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02002142 // Shorten "remain".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002143 if (*q != NUL)
2144 STRMOVE(remain, q - 1);
2145 else
2146 VIM_CLEAR(remain);
2147 }
2148
Bram Moolenaar26262f82019-09-04 20:59:15 +02002149 // If the result is a relative path name, make it explicitly relative to
2150 // the current directory if and only if the argument had this form.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002151 if (!vim_ispathsep(*p))
2152 {
2153 if (is_relative_to_current
2154 && *p != NUL
2155 && !(p[0] == '.'
2156 && (p[1] == NUL
2157 || vim_ispathsep(p[1])
2158 || (p[1] == '.'
2159 && (p[2] == NUL
2160 || vim_ispathsep(p[2]))))))
2161 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002162 // Prepend "./".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002163 cpy = concat_str((char_u *)"./", p);
2164 if (cpy != NULL)
2165 {
2166 vim_free(p);
2167 p = cpy;
2168 }
2169 }
2170 else if (!is_relative_to_current)
2171 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002172 // Strip leading "./".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002173 q = p;
2174 while (q[0] == '.' && vim_ispathsep(q[1]))
2175 q += 2;
2176 if (q > p)
2177 STRMOVE(p, p + 2);
2178 }
2179 }
2180
Bram Moolenaar26262f82019-09-04 20:59:15 +02002181 // Ensure that the result will have no trailing path separator
2182 // if the argument had none. But keep "/" or "//".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002183 if (!has_trailing_pathsep)
2184 {
2185 q = p + STRLEN(p);
2186 if (after_pathsep(p, q))
2187 *gettail_sep(p) = NUL;
2188 }
2189
2190 rettv->vval.v_string = p;
2191 }
2192# else
2193 rettv->vval.v_string = vim_strsave(p);
2194# endif
2195#endif
2196
2197 simplify_filename(rettv->vval.v_string);
2198
2199#ifdef HAVE_READLINK
2200fail:
2201 vim_free(buf);
2202#endif
2203 rettv->v_type = VAR_STRING;
2204}
2205
2206/*
2207 * "tempname()" function
2208 */
2209 void
2210f_tempname(typval_T *argvars UNUSED, typval_T *rettv)
2211{
2212 static int x = 'A';
2213
2214 rettv->v_type = VAR_STRING;
2215 rettv->vval.v_string = vim_tempname(x, FALSE);
2216
Bram Moolenaar26262f82019-09-04 20:59:15 +02002217 // Advance 'x' to use A-Z and 0-9, so that there are at least 34 different
2218 // names. Skip 'I' and 'O', they are used for shell redirection.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002219 do
2220 {
2221 if (x == 'Z')
2222 x = '0';
2223 else if (x == '9')
2224 x = 'A';
2225 else
Bram Moolenaar424bcae2022-01-31 14:59:41 +00002226 ++x;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002227 } while (x == 'I' || x == 'O');
2228}
2229
2230/*
2231 * "writefile()" function
2232 */
2233 void
2234f_writefile(typval_T *argvars, typval_T *rettv)
2235{
2236 int binary = FALSE;
2237 int append = FALSE;
2238#ifdef HAVE_FSYNC
2239 int do_fsync = p_fs;
2240#endif
2241 char_u *fname;
2242 FILE *fd;
2243 int ret = 0;
2244 listitem_T *li;
2245 list_T *list = NULL;
2246 blob_T *blob = NULL;
2247
2248 rettv->vval.v_number = -1;
2249 if (check_secure())
2250 return;
2251
Yegappan Lakshmanan0ad871d2021-07-23 20:37:56 +02002252 if (in_vim9script()
2253 && (check_for_list_or_blob_arg(argvars, 0) == FAIL
2254 || check_for_string_arg(argvars, 1) == FAIL
2255 || check_for_opt_string_arg(argvars, 2) == FAIL))
2256 return;
2257
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002258 if (argvars[0].v_type == VAR_LIST)
2259 {
2260 list = argvars[0].vval.v_list;
2261 if (list == NULL)
2262 return;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02002263 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002264 FOR_ALL_LIST_ITEMS(list, li)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002265 if (tv_get_string_chk(&li->li_tv) == NULL)
2266 return;
2267 }
2268 else if (argvars[0].v_type == VAR_BLOB)
2269 {
2270 blob = argvars[0].vval.v_blob;
2271 if (blob == NULL)
2272 return;
2273 }
2274 else
2275 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00002276 semsg(_(e_invalid_argument_str),
Bram Moolenaar18a2b872020-03-19 13:08:45 +01002277 _("writefile() first argument must be a List or a Blob"));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002278 return;
2279 }
2280
2281 if (argvars[2].v_type != VAR_UNKNOWN)
2282 {
2283 char_u *arg2 = tv_get_string_chk(&argvars[2]);
2284
2285 if (arg2 == NULL)
2286 return;
2287 if (vim_strchr(arg2, 'b') != NULL)
2288 binary = TRUE;
2289 if (vim_strchr(arg2, 'a') != NULL)
2290 append = TRUE;
2291#ifdef HAVE_FSYNC
2292 if (vim_strchr(arg2, 's') != NULL)
2293 do_fsync = TRUE;
2294 else if (vim_strchr(arg2, 'S') != NULL)
2295 do_fsync = FALSE;
2296#endif
2297 }
2298
2299 fname = tv_get_string_chk(&argvars[1]);
2300 if (fname == NULL)
2301 return;
2302
Bram Moolenaar26262f82019-09-04 20:59:15 +02002303 // Always open the file in binary mode, library functions have a mind of
2304 // their own about CR-LF conversion.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002305 if (*fname == NUL || (fd = mch_fopen((char *)fname,
2306 append ? APPENDBIN : WRITEBIN)) == NULL)
2307 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00002308 semsg(_(e_cant_create_file_str), *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002309 ret = -1;
2310 }
2311 else if (blob)
2312 {
2313 if (write_blob(fd, blob) == FAIL)
2314 ret = -1;
2315#ifdef HAVE_FSYNC
2316 else if (do_fsync)
2317 // Ignore the error, the user wouldn't know what to do about it.
2318 // May happen for a device.
2319 vim_ignored = vim_fsync(fileno(fd));
2320#endif
2321 fclose(fd);
2322 }
2323 else
2324 {
2325 if (write_list(fd, list, binary) == FAIL)
2326 ret = -1;
2327#ifdef HAVE_FSYNC
2328 else if (do_fsync)
Bram Moolenaar26262f82019-09-04 20:59:15 +02002329 // Ignore the error, the user wouldn't know what to do about it.
2330 // May happen for a device.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002331 vim_ignored = vim_fsync(fileno(fd));
2332#endif
2333 fclose(fd);
2334 }
2335
2336 rettv->vval.v_number = ret;
2337}
2338
2339#endif // FEAT_EVAL
2340
2341#if defined(FEAT_BROWSE) || defined(PROTO)
2342/*
2343 * Generic browse function. Calls gui_mch_browse() when possible.
2344 * Later this may pop-up a non-GUI file selector (external command?).
2345 */
2346 char_u *
2347do_browse(
Bram Moolenaar26262f82019-09-04 20:59:15 +02002348 int flags, // BROWSE_SAVE and BROWSE_DIR
2349 char_u *title, // title for the window
2350 char_u *dflt, // default file name (may include directory)
2351 char_u *ext, // extension added
2352 char_u *initdir, // initial directory, NULL for current dir or
2353 // when using path from "dflt"
2354 char_u *filter, // file name filter
2355 buf_T *buf) // buffer to read/write for
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002356{
2357 char_u *fname;
Bram Moolenaar26262f82019-09-04 20:59:15 +02002358 static char_u *last_dir = NULL; // last used directory
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002359 char_u *tofree = NULL;
Bram Moolenaare1004402020-10-24 20:49:43 +02002360 int save_cmod_flags = cmdmod.cmod_flags;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002361
Bram Moolenaar26262f82019-09-04 20:59:15 +02002362 // Must turn off browse to avoid that autocommands will get the
2363 // flag too!
Bram Moolenaare1004402020-10-24 20:49:43 +02002364 cmdmod.cmod_flags &= ~CMOD_BROWSE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002365
2366 if (title == NULL || *title == NUL)
2367 {
2368 if (flags & BROWSE_DIR)
2369 title = (char_u *)_("Select Directory dialog");
2370 else if (flags & BROWSE_SAVE)
2371 title = (char_u *)_("Save File dialog");
2372 else
2373 title = (char_u *)_("Open File dialog");
2374 }
2375
Bram Moolenaar26262f82019-09-04 20:59:15 +02002376 // When no directory specified, use default file name, default dir, buffer
2377 // dir, last dir or current dir
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002378 if ((initdir == NULL || *initdir == NUL) && dflt != NULL && *dflt != NUL)
2379 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002380 if (mch_isdir(dflt)) // default file name is a directory
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002381 {
2382 initdir = dflt;
2383 dflt = NULL;
2384 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02002385 else if (gettail(dflt) != dflt) // default file name includes a path
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002386 {
2387 tofree = vim_strsave(dflt);
2388 if (tofree != NULL)
2389 {
2390 initdir = tofree;
2391 *gettail(initdir) = NUL;
2392 dflt = gettail(dflt);
2393 }
2394 }
2395 }
2396
2397 if (initdir == NULL || *initdir == NUL)
2398 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002399 // When 'browsedir' is a directory, use it
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002400 if (STRCMP(p_bsdir, "last") != 0
2401 && STRCMP(p_bsdir, "buffer") != 0
2402 && STRCMP(p_bsdir, "current") != 0
2403 && mch_isdir(p_bsdir))
2404 initdir = p_bsdir;
Bram Moolenaar26262f82019-09-04 20:59:15 +02002405 // When saving or 'browsedir' is "buffer", use buffer fname
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002406 else if (((flags & BROWSE_SAVE) || *p_bsdir == 'b')
2407 && buf != NULL && buf->b_ffname != NULL)
2408 {
2409 if (dflt == NULL || *dflt == NUL)
2410 dflt = gettail(curbuf->b_ffname);
2411 tofree = vim_strsave(curbuf->b_ffname);
2412 if (tofree != NULL)
2413 {
2414 initdir = tofree;
2415 *gettail(initdir) = NUL;
2416 }
2417 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02002418 // When 'browsedir' is "last", use dir from last browse
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002419 else if (*p_bsdir == 'l')
2420 initdir = last_dir;
Bram Moolenaar26262f82019-09-04 20:59:15 +02002421 // When 'browsedir is "current", use current directory. This is the
2422 // default already, leave initdir empty.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002423 }
2424
2425# ifdef FEAT_GUI
Bram Moolenaar26262f82019-09-04 20:59:15 +02002426 if (gui.in_use) // when this changes, also adjust f_has()!
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002427 {
2428 if (filter == NULL
2429# ifdef FEAT_EVAL
2430 && (filter = get_var_value((char_u *)"b:browsefilter")) == NULL
2431 && (filter = get_var_value((char_u *)"g:browsefilter")) == NULL
2432# endif
2433 )
2434 filter = BROWSE_FILTER_DEFAULT;
2435 if (flags & BROWSE_DIR)
2436 {
2437# if defined(FEAT_GUI_GTK) || defined(MSWIN)
Bram Moolenaar26262f82019-09-04 20:59:15 +02002438 // For systems that have a directory dialog.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002439 fname = gui_mch_browsedir(title, initdir);
2440# else
Bram Moolenaar26262f82019-09-04 20:59:15 +02002441 // Generic solution for selecting a directory: select a file and
2442 // remove the file name.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002443 fname = gui_mch_browse(0, title, dflt, ext, initdir, (char_u *)"");
2444# endif
2445# if !defined(FEAT_GUI_GTK)
Bram Moolenaar26262f82019-09-04 20:59:15 +02002446 // Win32 adds a dummy file name, others return an arbitrary file
2447 // name. GTK+ 2 returns only the directory,
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002448 if (fname != NULL && *fname != NUL && !mch_isdir(fname))
2449 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002450 // Remove the file name.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002451 char_u *tail = gettail_sep(fname);
2452
2453 if (tail == fname)
Bram Moolenaar26262f82019-09-04 20:59:15 +02002454 *tail++ = '.'; // use current dir
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002455 *tail = NUL;
2456 }
2457# endif
2458 }
2459 else
2460 fname = gui_mch_browse(flags & BROWSE_SAVE,
2461 title, dflt, ext, initdir, (char_u *)_(filter));
2462
Bram Moolenaar26262f82019-09-04 20:59:15 +02002463 // We hang around in the dialog for a while, the user might do some
2464 // things to our files. The Win32 dialog allows deleting or renaming
2465 // a file, check timestamps.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002466 need_check_timestamps = TRUE;
2467 did_check_timestamps = FALSE;
2468 }
2469 else
2470# endif
2471 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002472 // TODO: non-GUI file selector here
Bram Moolenaareaaac012022-01-02 17:00:40 +00002473 emsg(_(e_sorry_no_file_browser_in_console_mode));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002474 fname = NULL;
2475 }
2476
Bram Moolenaar26262f82019-09-04 20:59:15 +02002477 // keep the directory for next time
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002478 if (fname != NULL)
2479 {
2480 vim_free(last_dir);
2481 last_dir = vim_strsave(fname);
2482 if (last_dir != NULL && !(flags & BROWSE_DIR))
2483 {
2484 *gettail(last_dir) = NUL;
2485 if (*last_dir == NUL)
2486 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002487 // filename only returned, must be in current dir
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002488 vim_free(last_dir);
2489 last_dir = alloc(MAXPATHL);
2490 if (last_dir != NULL)
2491 mch_dirname(last_dir, MAXPATHL);
2492 }
2493 }
2494 }
2495
2496 vim_free(tofree);
Bram Moolenaare1004402020-10-24 20:49:43 +02002497 cmdmod.cmod_flags = save_cmod_flags;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002498
2499 return fname;
2500}
2501#endif
2502
2503#if defined(FEAT_EVAL) || defined(PROTO)
2504
2505/*
2506 * "browse(save, title, initdir, default)" function
2507 */
2508 void
2509f_browse(typval_T *argvars UNUSED, typval_T *rettv)
2510{
2511# ifdef FEAT_BROWSE
2512 int save;
2513 char_u *title;
2514 char_u *initdir;
2515 char_u *defname;
2516 char_u buf[NUMBUFLEN];
2517 char_u buf2[NUMBUFLEN];
2518 int error = FALSE;
2519
Bram Moolenaarf28f2ac2021-03-22 22:21:26 +01002520 if (in_vim9script()
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02002521 && (check_for_bool_arg(argvars, 0) == FAIL
2522 || check_for_string_arg(argvars, 1) == FAIL
Bram Moolenaar32105ae2021-03-27 18:59:25 +01002523 || check_for_string_arg(argvars, 2) == FAIL
2524 || check_for_string_arg(argvars, 3) == FAIL))
Bram Moolenaarf28f2ac2021-03-22 22:21:26 +01002525 return;
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02002526
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002527 save = (int)tv_get_number_chk(&argvars[0], &error);
2528 title = tv_get_string_chk(&argvars[1]);
2529 initdir = tv_get_string_buf_chk(&argvars[2], buf);
2530 defname = tv_get_string_buf_chk(&argvars[3], buf2);
2531
2532 if (error || title == NULL || initdir == NULL || defname == NULL)
2533 rettv->vval.v_string = NULL;
2534 else
2535 rettv->vval.v_string =
2536 do_browse(save ? BROWSE_SAVE : 0,
2537 title, defname, NULL, initdir, NULL, curbuf);
2538# else
2539 rettv->vval.v_string = NULL;
2540# endif
2541 rettv->v_type = VAR_STRING;
2542}
2543
2544/*
2545 * "browsedir(title, initdir)" function
2546 */
2547 void
2548f_browsedir(typval_T *argvars UNUSED, typval_T *rettv)
2549{
2550# ifdef FEAT_BROWSE
2551 char_u *title;
2552 char_u *initdir;
2553 char_u buf[NUMBUFLEN];
2554
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02002555 if (in_vim9script()
2556 && (check_for_string_arg(argvars, 0) == FAIL
2557 || check_for_string_arg(argvars, 1) == FAIL))
2558 return;
2559
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002560 title = tv_get_string_chk(&argvars[0]);
2561 initdir = tv_get_string_buf_chk(&argvars[1], buf);
2562
2563 if (title == NULL || initdir == NULL)
2564 rettv->vval.v_string = NULL;
2565 else
2566 rettv->vval.v_string = do_browse(BROWSE_DIR,
2567 title, NULL, NULL, initdir, NULL, curbuf);
2568# else
2569 rettv->vval.v_string = NULL;
2570# endif
2571 rettv->v_type = VAR_STRING;
2572}
2573
2574#endif // FEAT_EVAL
Bram Moolenaar26262f82019-09-04 20:59:15 +02002575
2576/*
2577 * Replace home directory by "~" in each space or comma separated file name in
2578 * 'src'.
2579 * If anything fails (except when out of space) dst equals src.
2580 */
2581 void
2582home_replace(
2583 buf_T *buf, // when not NULL, check for help files
2584 char_u *src, // input file name
2585 char_u *dst, // where to put the result
2586 int dstlen, // maximum length of the result
2587 int one) // if TRUE, only replace one file name, include
2588 // spaces and commas in the file name.
2589{
2590 size_t dirlen = 0, envlen = 0;
2591 size_t len;
2592 char_u *homedir_env, *homedir_env_orig;
2593 char_u *p;
2594
2595 if (src == NULL)
2596 {
2597 *dst = NUL;
2598 return;
2599 }
2600
2601 /*
2602 * If the file is a help file, remove the path completely.
2603 */
2604 if (buf != NULL && buf->b_help)
2605 {
2606 vim_snprintf((char *)dst, dstlen, "%s", gettail(src));
2607 return;
2608 }
2609
2610 /*
2611 * We check both the value of the $HOME environment variable and the
2612 * "real" home directory.
2613 */
2614 if (homedir != NULL)
2615 dirlen = STRLEN(homedir);
2616
2617#ifdef VMS
2618 homedir_env_orig = homedir_env = mch_getenv((char_u *)"SYS$LOGIN");
2619#else
2620 homedir_env_orig = homedir_env = mch_getenv((char_u *)"HOME");
2621#endif
2622#ifdef MSWIN
2623 if (homedir_env == NULL)
2624 homedir_env_orig = homedir_env = mch_getenv((char_u *)"USERPROFILE");
2625#endif
2626 // Empty is the same as not set.
2627 if (homedir_env != NULL && *homedir_env == NUL)
2628 homedir_env = NULL;
2629
2630 if (homedir_env != NULL && *homedir_env == '~')
2631 {
2632 int usedlen = 0;
2633 int flen;
2634 char_u *fbuf = NULL;
2635
2636 flen = (int)STRLEN(homedir_env);
2637 (void)modify_fname((char_u *)":p", FALSE, &usedlen,
2638 &homedir_env, &fbuf, &flen);
2639 flen = (int)STRLEN(homedir_env);
2640 if (flen > 0 && vim_ispathsep(homedir_env[flen - 1]))
2641 // Remove the trailing / that is added to a directory.
2642 homedir_env[flen - 1] = NUL;
2643 }
2644
2645 if (homedir_env != NULL)
2646 envlen = STRLEN(homedir_env);
2647
2648 if (!one)
2649 src = skipwhite(src);
2650 while (*src && dstlen > 0)
2651 {
2652 /*
2653 * Here we are at the beginning of a file name.
2654 * First, check to see if the beginning of the file name matches
2655 * $HOME or the "real" home directory. Check that there is a '/'
2656 * after the match (so that if e.g. the file is "/home/pieter/bla",
2657 * and the home directory is "/home/piet", the file does not end up
2658 * as "~er/bla" (which would seem to indicate the file "bla" in user
2659 * er's home directory)).
2660 */
2661 p = homedir;
2662 len = dirlen;
2663 for (;;)
2664 {
2665 if ( len
2666 && fnamencmp(src, p, len) == 0
2667 && (vim_ispathsep(src[len])
2668 || (!one && (src[len] == ',' || src[len] == ' '))
2669 || src[len] == NUL))
2670 {
2671 src += len;
2672 if (--dstlen > 0)
2673 *dst++ = '~';
2674
Bram Moolenaar0e390f42020-06-10 13:12:28 +02002675 // Do not add directory separator into dst, because dst is
2676 // expected to just return the directory name without the
2677 // directory separator '/'.
Bram Moolenaar26262f82019-09-04 20:59:15 +02002678 break;
2679 }
2680 if (p == homedir_env)
2681 break;
2682 p = homedir_env;
2683 len = envlen;
2684 }
2685
2686 // if (!one) skip to separator: space or comma
2687 while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0)
2688 *dst++ = *src++;
2689 // skip separator
2690 while ((*src == ' ' || *src == ',') && --dstlen > 0)
2691 *dst++ = *src++;
2692 }
2693 // if (dstlen == 0) out of space, what to do???
2694
2695 *dst = NUL;
2696
2697 if (homedir_env != homedir_env_orig)
2698 vim_free(homedir_env);
2699}
2700
2701/*
2702 * Like home_replace, store the replaced string in allocated memory.
2703 * When something fails, NULL is returned.
2704 */
2705 char_u *
2706home_replace_save(
2707 buf_T *buf, // when not NULL, check for help files
2708 char_u *src) // input file name
2709{
2710 char_u *dst;
2711 unsigned len;
2712
2713 len = 3; // space for "~/" and trailing NUL
2714 if (src != NULL) // just in case
2715 len += (unsigned)STRLEN(src);
2716 dst = alloc(len);
2717 if (dst != NULL)
2718 home_replace(buf, src, dst, len, TRUE);
2719 return dst;
2720}
2721
2722/*
2723 * Compare two file names and return:
2724 * FPC_SAME if they both exist and are the same file.
2725 * FPC_SAMEX if they both don't exist and have the same file name.
2726 * FPC_DIFF if they both exist and are different files.
2727 * FPC_NOTX if they both don't exist.
2728 * FPC_DIFFX if one of them doesn't exist.
2729 * For the first name environment variables are expanded if "expandenv" is
2730 * TRUE.
2731 */
2732 int
2733fullpathcmp(
2734 char_u *s1,
2735 char_u *s2,
2736 int checkname, // when both don't exist, check file names
2737 int expandenv)
2738{
2739#ifdef UNIX
2740 char_u exp1[MAXPATHL];
2741 char_u full1[MAXPATHL];
2742 char_u full2[MAXPATHL];
2743 stat_T st1, st2;
2744 int r1, r2;
2745
2746 if (expandenv)
2747 expand_env(s1, exp1, MAXPATHL);
2748 else
2749 vim_strncpy(exp1, s1, MAXPATHL - 1);
2750 r1 = mch_stat((char *)exp1, &st1);
2751 r2 = mch_stat((char *)s2, &st2);
2752 if (r1 != 0 && r2 != 0)
2753 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002754 // if mch_stat() doesn't work, may compare the names
Bram Moolenaar26262f82019-09-04 20:59:15 +02002755 if (checkname)
2756 {
2757 if (fnamecmp(exp1, s2) == 0)
2758 return FPC_SAMEX;
2759 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
2760 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
2761 if (r1 == OK && r2 == OK && fnamecmp(full1, full2) == 0)
2762 return FPC_SAMEX;
2763 }
2764 return FPC_NOTX;
2765 }
2766 if (r1 != 0 || r2 != 0)
2767 return FPC_DIFFX;
2768 if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
2769 return FPC_SAME;
2770 return FPC_DIFF;
2771#else
2772 char_u *exp1; // expanded s1
2773 char_u *full1; // full path of s1
2774 char_u *full2; // full path of s2
2775 int retval = FPC_DIFF;
2776 int r1, r2;
2777
2778 // allocate one buffer to store three paths (alloc()/free() is slow!)
2779 if ((exp1 = alloc(MAXPATHL * 3)) != NULL)
2780 {
2781 full1 = exp1 + MAXPATHL;
2782 full2 = full1 + MAXPATHL;
2783
2784 if (expandenv)
2785 expand_env(s1, exp1, MAXPATHL);
2786 else
2787 vim_strncpy(exp1, s1, MAXPATHL - 1);
2788 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
2789 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
2790
2791 // If vim_FullName() fails, the file probably doesn't exist.
2792 if (r1 != OK && r2 != OK)
2793 {
2794 if (checkname && fnamecmp(exp1, s2) == 0)
2795 retval = FPC_SAMEX;
2796 else
2797 retval = FPC_NOTX;
2798 }
2799 else if (r1 != OK || r2 != OK)
2800 retval = FPC_DIFFX;
2801 else if (fnamecmp(full1, full2))
2802 retval = FPC_DIFF;
2803 else
2804 retval = FPC_SAME;
2805 vim_free(exp1);
2806 }
2807 return retval;
2808#endif
2809}
2810
2811/*
2812 * Get the tail of a path: the file name.
2813 * When the path ends in a path separator the tail is the NUL after it.
2814 * Fail safe: never returns NULL.
2815 */
2816 char_u *
2817gettail(char_u *fname)
2818{
2819 char_u *p1, *p2;
2820
2821 if (fname == NULL)
2822 return (char_u *)"";
2823 for (p1 = p2 = get_past_head(fname); *p2; ) // find last part of path
2824 {
2825 if (vim_ispathsep_nocolon(*p2))
2826 p1 = p2 + 1;
2827 MB_PTR_ADV(p2);
2828 }
2829 return p1;
2830}
2831
2832/*
2833 * Get pointer to tail of "fname", including path separators. Putting a NUL
2834 * here leaves the directory name. Takes care of "c:/" and "//".
2835 * Always returns a valid pointer.
2836 */
2837 char_u *
2838gettail_sep(char_u *fname)
2839{
2840 char_u *p;
2841 char_u *t;
2842
2843 p = get_past_head(fname); // don't remove the '/' from "c:/file"
2844 t = gettail(fname);
2845 while (t > p && after_pathsep(fname, t))
2846 --t;
2847#ifdef VMS
2848 // path separator is part of the path
2849 ++t;
2850#endif
2851 return t;
2852}
2853
2854/*
2855 * get the next path component (just after the next path separator).
2856 */
2857 char_u *
2858getnextcomp(char_u *fname)
2859{
2860 while (*fname && !vim_ispathsep(*fname))
2861 MB_PTR_ADV(fname);
2862 if (*fname)
2863 ++fname;
2864 return fname;
2865}
2866
2867/*
2868 * Get a pointer to one character past the head of a path name.
2869 * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
2870 * If there is no head, path is returned.
2871 */
2872 char_u *
2873get_past_head(char_u *path)
2874{
2875 char_u *retval;
2876
2877#if defined(MSWIN)
2878 // may skip "c:"
2879 if (isalpha(path[0]) && path[1] == ':')
2880 retval = path + 2;
2881 else
2882 retval = path;
2883#else
2884# if defined(AMIGA)
2885 // may skip "label:"
2886 retval = vim_strchr(path, ':');
2887 if (retval == NULL)
2888 retval = path;
2889# else // Unix
2890 retval = path;
2891# endif
2892#endif
2893
2894 while (vim_ispathsep(*retval))
2895 ++retval;
2896
2897 return retval;
2898}
2899
2900/*
2901 * Return TRUE if 'c' is a path separator.
2902 * Note that for MS-Windows this includes the colon.
2903 */
2904 int
2905vim_ispathsep(int c)
2906{
2907#ifdef UNIX
2908 return (c == '/'); // UNIX has ':' inside file names
2909#else
2910# ifdef BACKSLASH_IN_FILENAME
2911 return (c == ':' || c == '/' || c == '\\');
2912# else
2913# ifdef VMS
2914 // server"user passwd"::device:[full.path.name]fname.extension;version"
2915 return (c == ':' || c == '[' || c == ']' || c == '/'
2916 || c == '<' || c == '>' || c == '"' );
2917# else
2918 return (c == ':' || c == '/');
2919# endif // VMS
2920# endif
2921#endif
2922}
2923
2924/*
2925 * Like vim_ispathsep(c), but exclude the colon for MS-Windows.
2926 */
2927 int
2928vim_ispathsep_nocolon(int c)
2929{
2930 return vim_ispathsep(c)
2931#ifdef BACKSLASH_IN_FILENAME
2932 && c != ':'
2933#endif
2934 ;
2935}
2936
2937/*
Bram Moolenaar26262f82019-09-04 20:59:15 +02002938 * Return TRUE if the directory of "fname" exists, FALSE otherwise.
2939 * Also returns TRUE if there is no directory name.
2940 * "fname" must be writable!.
2941 */
2942 int
2943dir_of_file_exists(char_u *fname)
2944{
2945 char_u *p;
2946 int c;
2947 int retval;
2948
2949 p = gettail_sep(fname);
2950 if (p == fname)
2951 return TRUE;
2952 c = *p;
2953 *p = NUL;
2954 retval = mch_isdir(fname);
2955 *p = c;
2956 return retval;
2957}
2958
2959/*
2960 * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally
2961 * and deal with 'fileignorecase'.
2962 */
2963 int
2964vim_fnamecmp(char_u *x, char_u *y)
2965{
2966#ifdef BACKSLASH_IN_FILENAME
2967 return vim_fnamencmp(x, y, MAXPATHL);
2968#else
2969 if (p_fic)
2970 return MB_STRICMP(x, y);
2971 return STRCMP(x, y);
2972#endif
2973}
2974
2975 int
2976vim_fnamencmp(char_u *x, char_u *y, size_t len)
2977{
2978#ifdef BACKSLASH_IN_FILENAME
2979 char_u *px = x;
2980 char_u *py = y;
2981 int cx = NUL;
2982 int cy = NUL;
2983
2984 while (len > 0)
2985 {
2986 cx = PTR2CHAR(px);
2987 cy = PTR2CHAR(py);
2988 if (cx == NUL || cy == NUL
2989 || ((p_fic ? MB_TOLOWER(cx) != MB_TOLOWER(cy) : cx != cy)
2990 && !(cx == '/' && cy == '\\')
2991 && !(cx == '\\' && cy == '/')))
2992 break;
Bram Moolenaar1614a142019-10-06 22:00:13 +02002993 len -= mb_ptr2len(px);
2994 px += mb_ptr2len(px);
2995 py += mb_ptr2len(py);
Bram Moolenaar26262f82019-09-04 20:59:15 +02002996 }
2997 if (len == 0)
2998 return 0;
2999 return (cx - cy);
3000#else
3001 if (p_fic)
3002 return MB_STRNICMP(x, y, len);
3003 return STRNCMP(x, y, len);
3004#endif
3005}
3006
3007/*
3008 * Concatenate file names fname1 and fname2 into allocated memory.
3009 * Only add a '/' or '\\' when 'sep' is TRUE and it is necessary.
3010 */
3011 char_u *
3012concat_fnames(char_u *fname1, char_u *fname2, int sep)
3013{
3014 char_u *dest;
3015
3016 dest = alloc(STRLEN(fname1) + STRLEN(fname2) + 3);
3017 if (dest != NULL)
3018 {
3019 STRCPY(dest, fname1);
3020 if (sep)
3021 add_pathsep(dest);
3022 STRCAT(dest, fname2);
3023 }
3024 return dest;
3025}
3026
3027/*
3028 * Add a path separator to a file name, unless it already ends in a path
3029 * separator.
3030 */
3031 void
3032add_pathsep(char_u *p)
3033{
3034 if (*p != NUL && !after_pathsep(p, p + STRLEN(p)))
3035 STRCAT(p, PATHSEPSTR);
3036}
3037
3038/*
3039 * FullName_save - Make an allocated copy of a full file name.
3040 * Returns NULL when out of memory.
3041 */
3042 char_u *
3043FullName_save(
3044 char_u *fname,
3045 int force) // force expansion, even when it already looks
3046 // like a full path name
3047{
3048 char_u *buf;
3049 char_u *new_fname = NULL;
3050
3051 if (fname == NULL)
3052 return NULL;
3053
3054 buf = alloc(MAXPATHL);
3055 if (buf != NULL)
3056 {
3057 if (vim_FullName(fname, buf, MAXPATHL, force) != FAIL)
3058 new_fname = vim_strsave(buf);
3059 else
3060 new_fname = vim_strsave(fname);
3061 vim_free(buf);
3062 }
3063 return new_fname;
3064}
3065
3066/*
3067 * return TRUE if "fname" exists.
3068 */
3069 int
3070vim_fexists(char_u *fname)
3071{
3072 stat_T st;
3073
3074 if (mch_stat((char *)fname, &st))
3075 return FALSE;
3076 return TRUE;
3077}
3078
3079/*
3080 * Invoke expand_wildcards() for one pattern.
3081 * Expand items like "%:h" before the expansion.
3082 * Returns OK or FAIL.
3083 */
3084 int
3085expand_wildcards_eval(
3086 char_u **pat, // pointer to input pattern
3087 int *num_file, // resulting number of files
3088 char_u ***file, // array of resulting files
3089 int flags) // EW_DIR, etc.
3090{
3091 int ret = FAIL;
3092 char_u *eval_pat = NULL;
3093 char_u *exp_pat = *pat;
3094 char *ignored_msg;
3095 int usedlen;
3096
3097 if (*exp_pat == '%' || *exp_pat == '#' || *exp_pat == '<')
3098 {
3099 ++emsg_off;
3100 eval_pat = eval_vars(exp_pat, exp_pat, &usedlen,
Bram Moolenaara96edb72022-04-28 17:52:24 +01003101 NULL, &ignored_msg, NULL, TRUE);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003102 --emsg_off;
3103 if (eval_pat != NULL)
3104 exp_pat = concat_str(eval_pat, exp_pat + usedlen);
3105 }
3106
3107 if (exp_pat != NULL)
3108 ret = expand_wildcards(1, &exp_pat, num_file, file, flags);
3109
3110 if (eval_pat != NULL)
3111 {
3112 vim_free(exp_pat);
3113 vim_free(eval_pat);
3114 }
3115
3116 return ret;
3117}
3118
3119/*
3120 * Expand wildcards. Calls gen_expand_wildcards() and removes files matching
3121 * 'wildignore'.
3122 * Returns OK or FAIL. When FAIL then "num_files" won't be set.
3123 */
3124 int
3125expand_wildcards(
3126 int num_pat, // number of input patterns
3127 char_u **pat, // array of input patterns
3128 int *num_files, // resulting number of files
3129 char_u ***files, // array of resulting files
3130 int flags) // EW_DIR, etc.
3131{
3132 int retval;
3133 int i, j;
3134 char_u *p;
3135 int non_suf_match; // number without matching suffix
3136
3137 retval = gen_expand_wildcards(num_pat, pat, num_files, files, flags);
3138
3139 // When keeping all matches, return here
3140 if ((flags & EW_KEEPALL) || retval == FAIL)
3141 return retval;
3142
3143#ifdef FEAT_WILDIGN
3144 /*
3145 * Remove names that match 'wildignore'.
3146 */
3147 if (*p_wig)
3148 {
3149 char_u *ffname;
3150
3151 // check all files in (*files)[]
3152 for (i = 0; i < *num_files; ++i)
3153 {
3154 ffname = FullName_save((*files)[i], FALSE);
3155 if (ffname == NULL) // out of memory
3156 break;
3157# ifdef VMS
3158 vms_remove_version(ffname);
3159# endif
3160 if (match_file_list(p_wig, (*files)[i], ffname))
3161 {
3162 // remove this matching file from the list
3163 vim_free((*files)[i]);
3164 for (j = i; j + 1 < *num_files; ++j)
3165 (*files)[j] = (*files)[j + 1];
3166 --*num_files;
3167 --i;
3168 }
3169 vim_free(ffname);
3170 }
3171
3172 // If the number of matches is now zero, we fail.
3173 if (*num_files == 0)
3174 {
3175 VIM_CLEAR(*files);
3176 return FAIL;
3177 }
3178 }
3179#endif
3180
3181 /*
3182 * Move the names where 'suffixes' match to the end.
3183 */
3184 if (*num_files > 1)
3185 {
3186 non_suf_match = 0;
3187 for (i = 0; i < *num_files; ++i)
3188 {
3189 if (!match_suffix((*files)[i]))
3190 {
3191 /*
3192 * Move the name without matching suffix to the front
3193 * of the list.
3194 */
3195 p = (*files)[i];
3196 for (j = i; j > non_suf_match; --j)
3197 (*files)[j] = (*files)[j - 1];
3198 (*files)[non_suf_match++] = p;
3199 }
3200 }
3201 }
3202
3203 return retval;
3204}
3205
3206/*
3207 * Return TRUE if "fname" matches with an entry in 'suffixes'.
3208 */
3209 int
3210match_suffix(char_u *fname)
3211{
3212 int fnamelen, setsuflen;
3213 char_u *setsuf;
3214#define MAXSUFLEN 30 // maximum length of a file suffix
3215 char_u suf_buf[MAXSUFLEN];
3216
3217 fnamelen = (int)STRLEN(fname);
3218 setsuflen = 0;
3219 for (setsuf = p_su; *setsuf; )
3220 {
3221 setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
3222 if (setsuflen == 0)
3223 {
3224 char_u *tail = gettail(fname);
3225
3226 // empty entry: match name without a '.'
3227 if (vim_strchr(tail, '.') == NULL)
3228 {
3229 setsuflen = 1;
3230 break;
3231 }
3232 }
3233 else
3234 {
3235 if (fnamelen >= setsuflen
3236 && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
3237 (size_t)setsuflen) == 0)
3238 break;
3239 setsuflen = 0;
3240 }
3241 }
3242 return (setsuflen != 0);
3243}
3244
3245#ifdef VIM_BACKTICK
3246
3247/*
3248 * Return TRUE if we can expand this backtick thing here.
3249 */
3250 static int
3251vim_backtick(char_u *p)
3252{
3253 return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
3254}
3255
3256/*
3257 * Expand an item in `backticks` by executing it as a command.
3258 * Currently only works when pat[] starts and ends with a `.
3259 * Returns number of file names found, -1 if an error is encountered.
3260 */
3261 static int
3262expand_backtick(
3263 garray_T *gap,
3264 char_u *pat,
3265 int flags) // EW_* flags
3266{
3267 char_u *p;
3268 char_u *cmd;
3269 char_u *buffer;
3270 int cnt = 0;
3271 int i;
3272
3273 // Create the command: lop off the backticks.
Bram Moolenaar71ccd032020-06-12 22:59:11 +02003274 cmd = vim_strnsave(pat + 1, STRLEN(pat) - 2);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003275 if (cmd == NULL)
3276 return -1;
3277
3278#ifdef FEAT_EVAL
3279 if (*cmd == '=') // `={expr}`: Expand expression
Bram Moolenaarb171fb12020-06-24 20:34:03 +02003280 buffer = eval_to_string(cmd + 1, TRUE);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003281 else
3282#endif
3283 buffer = get_cmd_output(cmd, NULL,
3284 (flags & EW_SILENT) ? SHELL_SILENT : 0, NULL);
3285 vim_free(cmd);
3286 if (buffer == NULL)
3287 return -1;
3288
3289 cmd = buffer;
3290 while (*cmd != NUL)
3291 {
3292 cmd = skipwhite(cmd); // skip over white space
3293 p = cmd;
3294 while (*p != NUL && *p != '\r' && *p != '\n') // skip over entry
3295 ++p;
3296 // add an entry if it is not empty
3297 if (p > cmd)
3298 {
3299 i = *p;
3300 *p = NUL;
3301 addfile(gap, cmd, flags);
3302 *p = i;
3303 ++cnt;
3304 }
3305 cmd = p;
3306 while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
3307 ++cmd;
3308 }
3309
3310 vim_free(buffer);
3311 return cnt;
3312}
3313#endif // VIM_BACKTICK
3314
3315#if defined(MSWIN)
3316/*
3317 * File name expansion code for MS-DOS, Win16 and Win32. It's here because
3318 * it's shared between these systems.
3319 */
3320
3321/*
3322 * comparison function for qsort in dos_expandpath()
3323 */
3324 static int
3325pstrcmp(const void *a, const void *b)
3326{
3327 return (pathcmp(*(char **)a, *(char **)b, -1));
3328}
3329
3330/*
3331 * Recursively expand one path component into all matching files and/or
3332 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
3333 * Return the number of matches found.
3334 * "path" has backslashes before chars that are not to be expanded, starting
3335 * at "path[wildoff]".
3336 * Return the number of matches found.
3337 * NOTE: much of this is identical to unix_expandpath(), keep in sync!
3338 */
3339 static int
3340dos_expandpath(
3341 garray_T *gap,
3342 char_u *path,
3343 int wildoff,
3344 int flags, // EW_* flags
3345 int didstar) // expanded "**" once already
3346{
3347 char_u *buf;
3348 char_u *path_end;
3349 char_u *p, *s, *e;
3350 int start_len = gap->ga_len;
3351 char_u *pat;
3352 regmatch_T regmatch;
3353 int starts_with_dot;
3354 int matches;
3355 int len;
3356 int starstar = FALSE;
3357 static int stardepth = 0; // depth for "**" expansion
3358 HANDLE hFind = INVALID_HANDLE_VALUE;
3359 WIN32_FIND_DATAW wfb;
3360 WCHAR *wn = NULL; // UCS-2 name, NULL when not used.
3361 char_u *matchname;
3362 int ok;
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003363 char_u *p_alt;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003364
3365 // Expanding "**" may take a long time, check for CTRL-C.
3366 if (stardepth > 0)
3367 {
3368 ui_breakcheck();
3369 if (got_int)
3370 return 0;
3371 }
3372
3373 // Make room for file name. When doing encoding conversion the actual
3374 // length may be quite a bit longer, thus use the maximum possible length.
3375 buf = alloc(MAXPATHL);
3376 if (buf == NULL)
3377 return 0;
3378
3379 /*
3380 * Find the first part in the path name that contains a wildcard or a ~1.
3381 * Copy it into buf, including the preceding characters.
3382 */
3383 p = buf;
3384 s = buf;
3385 e = NULL;
3386 path_end = path;
3387 while (*path_end != NUL)
3388 {
3389 // May ignore a wildcard that has a backslash before it; it will
3390 // be removed by rem_backslash() or file_pat_to_reg_pat() below.
3391 if (path_end >= path + wildoff && rem_backslash(path_end))
3392 *p++ = *path_end++;
3393 else if (*path_end == '\\' || *path_end == ':' || *path_end == '/')
3394 {
3395 if (e != NULL)
3396 break;
3397 s = p + 1;
3398 }
3399 else if (path_end >= path + wildoff
3400 && vim_strchr((char_u *)"*?[~", *path_end) != NULL)
3401 e = p;
3402 if (has_mbyte)
3403 {
3404 len = (*mb_ptr2len)(path_end);
3405 STRNCPY(p, path_end, len);
3406 p += len;
3407 path_end += len;
3408 }
3409 else
3410 *p++ = *path_end++;
3411 }
3412 e = p;
3413 *e = NUL;
3414
3415 // now we have one wildcard component between s and e
3416 // Remove backslashes between "wildoff" and the start of the wildcard
3417 // component.
3418 for (p = buf + wildoff; p < s; ++p)
3419 if (rem_backslash(p))
3420 {
3421 STRMOVE(p, p + 1);
3422 --e;
3423 --s;
3424 }
3425
3426 // Check for "**" between "s" and "e".
3427 for (p = s; p < e; ++p)
3428 if (p[0] == '*' && p[1] == '*')
3429 starstar = TRUE;
3430
3431 starts_with_dot = *s == '.';
3432 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
3433 if (pat == NULL)
3434 {
3435 vim_free(buf);
3436 return 0;
3437 }
3438
3439 // compile the regexp into a program
3440 if (flags & (EW_NOERROR | EW_NOTWILD))
3441 ++emsg_silent;
3442 regmatch.rm_ic = TRUE; // Always ignore case
3443 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
3444 if (flags & (EW_NOERROR | EW_NOTWILD))
3445 --emsg_silent;
3446 vim_free(pat);
3447
3448 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
3449 {
3450 vim_free(buf);
3451 return 0;
3452 }
3453
3454 // remember the pattern or file name being looked for
3455 matchname = vim_strsave(s);
3456
3457 // If "**" is by itself, this is the first time we encounter it and more
3458 // is following then find matches without any directory.
3459 if (!didstar && stardepth < 100 && starstar && e - s == 2
3460 && *path_end == '/')
3461 {
3462 STRCPY(s, path_end + 1);
3463 ++stardepth;
3464 (void)dos_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
3465 --stardepth;
3466 }
3467
3468 // Scan all files in the directory with "dir/ *.*"
3469 STRCPY(s, "*.*");
3470 wn = enc_to_utf16(buf, NULL);
3471 if (wn != NULL)
3472 hFind = FindFirstFileW(wn, &wfb);
3473 ok = (hFind != INVALID_HANDLE_VALUE);
3474
3475 while (ok)
3476 {
3477 p = utf16_to_enc(wfb.cFileName, NULL); // p is allocated here
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003478
Bram Moolenaar26262f82019-09-04 20:59:15 +02003479 if (p == NULL)
3480 break; // out of memory
3481
Bram Moolenaar0dc5f602021-02-07 14:01:35 +01003482 // Do not use the alternate filename when the file name ends in '~',
3483 // because it picks up backup files: short name for "foo.vim~" is
3484 // "foo~1.vim", which matches "*.vim".
3485 if (*wfb.cAlternateFileName == NUL || p[STRLEN(p) - 1] == '~')
Bram Moolenaar40655d52020-04-06 23:49:50 +02003486 p_alt = NULL;
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003487 else
3488 p_alt = utf16_to_enc(wfb.cAlternateFileName, NULL);
3489
Bram Moolenaar26262f82019-09-04 20:59:15 +02003490 // Ignore entries starting with a dot, unless when asked for. Accept
3491 // all entries found with "matchname".
3492 if ((p[0] != '.' || starts_with_dot
3493 || ((flags & EW_DODOT)
3494 && p[1] != NUL && (p[1] != '.' || p[2] != NUL)))
3495 && (matchname == NULL
3496 || (regmatch.regprog != NULL
Bram Moolenaar40655d52020-04-06 23:49:50 +02003497 && (vim_regexec(&regmatch, p, (colnr_T)0)
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003498 || (p_alt != NULL
Bram Moolenaar40655d52020-04-06 23:49:50 +02003499 && vim_regexec(&regmatch, p_alt, (colnr_T)0))))
Bram Moolenaar26262f82019-09-04 20:59:15 +02003500 || ((flags & EW_NOTWILD)
3501 && fnamencmp(path + (s - buf), p, e - s) == 0)))
3502 {
3503 STRCPY(s, p);
3504 len = (int)STRLEN(buf);
3505
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003506 if (starstar && stardepth < 100
3507 && (wfb.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
Bram Moolenaar26262f82019-09-04 20:59:15 +02003508 {
3509 // For "**" in the pattern first go deeper in the tree to
3510 // find matches.
3511 STRCPY(buf + len, "/**");
3512 STRCPY(buf + len + 3, path_end);
3513 ++stardepth;
3514 (void)dos_expandpath(gap, buf, len + 1, flags, TRUE);
3515 --stardepth;
3516 }
3517
3518 STRCPY(buf + len, path_end);
3519 if (mch_has_exp_wildcard(path_end))
3520 {
3521 // need to expand another component of the path
3522 // remove backslashes for the remaining components only
3523 (void)dos_expandpath(gap, buf, len + 1, flags, FALSE);
3524 }
3525 else
3526 {
3527 // no more wildcards, check if there is a match
3528 // remove backslashes for the remaining components only
3529 if (*path_end != 0)
3530 backslash_halve(buf + len + 1);
3531 if (mch_getperm(buf) >= 0) // add existing file
3532 addfile(gap, buf, flags);
3533 }
3534 }
3535
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003536 vim_free(p_alt);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003537 vim_free(p);
3538 ok = FindNextFileW(hFind, &wfb);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003539 }
3540
3541 FindClose(hFind);
3542 vim_free(wn);
3543 vim_free(buf);
3544 vim_regfree(regmatch.regprog);
3545 vim_free(matchname);
3546
3547 matches = gap->ga_len - start_len;
3548 if (matches > 0)
3549 qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
3550 sizeof(char_u *), pstrcmp);
3551 return matches;
3552}
3553
3554 int
3555mch_expandpath(
3556 garray_T *gap,
3557 char_u *path,
3558 int flags) // EW_* flags
3559{
3560 return dos_expandpath(gap, path, 0, flags, FALSE);
3561}
3562#endif // MSWIN
3563
3564#if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \
3565 || defined(PROTO)
3566/*
3567 * Unix style wildcard expansion code.
3568 * It's here because it's used both for Unix and Mac.
3569 */
3570 static int
3571pstrcmp(const void *a, const void *b)
3572{
3573 return (pathcmp(*(char **)a, *(char **)b, -1));
3574}
3575
3576/*
3577 * Recursively expand one path component into all matching files and/or
3578 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
3579 * "path" has backslashes before chars that are not to be expanded, starting
3580 * at "path + wildoff".
3581 * Return the number of matches found.
3582 * NOTE: much of this is identical to dos_expandpath(), keep in sync!
3583 */
3584 int
3585unix_expandpath(
3586 garray_T *gap,
3587 char_u *path,
3588 int wildoff,
3589 int flags, // EW_* flags
3590 int didstar) // expanded "**" once already
3591{
3592 char_u *buf;
Bram Moolenaar386c24c2022-05-16 12:37:36 +01003593 size_t buflen;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003594 char_u *path_end;
3595 char_u *p, *s, *e;
3596 int start_len = gap->ga_len;
3597 char_u *pat;
3598 regmatch_T regmatch;
3599 int starts_with_dot;
3600 int matches;
3601 int len;
3602 int starstar = FALSE;
3603 static int stardepth = 0; // depth for "**" expansion
3604
3605 DIR *dirp;
3606 struct dirent *dp;
3607
3608 // Expanding "**" may take a long time, check for CTRL-C.
3609 if (stardepth > 0)
3610 {
3611 ui_breakcheck();
3612 if (got_int)
3613 return 0;
3614 }
3615
3616 // make room for file name
Bram Moolenaar386c24c2022-05-16 12:37:36 +01003617 buflen = STRLEN(path) + BASENAMELEN + 5;
3618 buf = alloc(buflen);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003619 if (buf == NULL)
3620 return 0;
3621
3622 /*
3623 * Find the first part in the path name that contains a wildcard.
3624 * When EW_ICASE is set every letter is considered to be a wildcard.
3625 * Copy it into "buf", including the preceding characters.
3626 */
3627 p = buf;
3628 s = buf;
3629 e = NULL;
3630 path_end = path;
3631 while (*path_end != NUL)
3632 {
3633 // May ignore a wildcard that has a backslash before it; it will
3634 // be removed by rem_backslash() or file_pat_to_reg_pat() below.
3635 if (path_end >= path + wildoff && rem_backslash(path_end))
3636 *p++ = *path_end++;
3637 else if (*path_end == '/')
3638 {
3639 if (e != NULL)
3640 break;
3641 s = p + 1;
3642 }
3643 else if (path_end >= path + wildoff
3644 && (vim_strchr((char_u *)"*?[{~$", *path_end) != NULL
3645 || (!p_fic && (flags & EW_ICASE)
Bram Moolenaar5921aeb2022-02-19 11:20:12 +00003646 && vim_isalpha(PTR2CHAR(path_end)))))
Bram Moolenaar26262f82019-09-04 20:59:15 +02003647 e = p;
3648 if (has_mbyte)
3649 {
3650 len = (*mb_ptr2len)(path_end);
3651 STRNCPY(p, path_end, len);
3652 p += len;
3653 path_end += len;
3654 }
3655 else
3656 *p++ = *path_end++;
3657 }
3658 e = p;
3659 *e = NUL;
3660
3661 // Now we have one wildcard component between "s" and "e".
3662 // Remove backslashes between "wildoff" and the start of the wildcard
3663 // component.
3664 for (p = buf + wildoff; p < s; ++p)
3665 if (rem_backslash(p))
3666 {
3667 STRMOVE(p, p + 1);
3668 --e;
3669 --s;
3670 }
3671
3672 // Check for "**" between "s" and "e".
3673 for (p = s; p < e; ++p)
3674 if (p[0] == '*' && p[1] == '*')
3675 starstar = TRUE;
3676
3677 // convert the file pattern to a regexp pattern
3678 starts_with_dot = *s == '.';
3679 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
3680 if (pat == NULL)
3681 {
3682 vim_free(buf);
3683 return 0;
3684 }
3685
3686 // compile the regexp into a program
3687 if (flags & EW_ICASE)
3688 regmatch.rm_ic = TRUE; // 'wildignorecase' set
3689 else
3690 regmatch.rm_ic = p_fic; // ignore case when 'fileignorecase' is set
3691 if (flags & (EW_NOERROR | EW_NOTWILD))
3692 ++emsg_silent;
3693 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
3694 if (flags & (EW_NOERROR | EW_NOTWILD))
3695 --emsg_silent;
3696 vim_free(pat);
3697
3698 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
3699 {
3700 vim_free(buf);
3701 return 0;
3702 }
3703
3704 // If "**" is by itself, this is the first time we encounter it and more
3705 // is following then find matches without any directory.
3706 if (!didstar && stardepth < 100 && starstar && e - s == 2
3707 && *path_end == '/')
3708 {
3709 STRCPY(s, path_end + 1);
3710 ++stardepth;
3711 (void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
3712 --stardepth;
3713 }
3714
3715 // open the directory for scanning
3716 *s = NUL;
3717 dirp = opendir(*buf == NUL ? "." : (char *)buf);
3718
3719 // Find all matching entries
3720 if (dirp != NULL)
3721 {
3722 for (;;)
3723 {
3724 dp = readdir(dirp);
3725 if (dp == NULL)
3726 break;
3727 if ((dp->d_name[0] != '.' || starts_with_dot
3728 || ((flags & EW_DODOT)
3729 && dp->d_name[1] != NUL
3730 && (dp->d_name[1] != '.' || dp->d_name[2] != NUL)))
3731 && ((regmatch.regprog != NULL && vim_regexec(&regmatch,
3732 (char_u *)dp->d_name, (colnr_T)0))
3733 || ((flags & EW_NOTWILD)
3734 && fnamencmp(path + (s - buf), dp->d_name, e - s) == 0)))
3735 {
3736 STRCPY(s, dp->d_name);
3737 len = STRLEN(buf);
3738
3739 if (starstar && stardepth < 100)
3740 {
3741 // For "**" in the pattern first go deeper in the tree to
3742 // find matches.
Bram Moolenaar386c24c2022-05-16 12:37:36 +01003743 vim_snprintf((char *)buf + len, buflen - len,
3744 "/**%s", path_end);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003745 ++stardepth;
3746 (void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
3747 --stardepth;
3748 }
3749
Bram Moolenaar386c24c2022-05-16 12:37:36 +01003750 vim_snprintf((char *)buf + len, buflen - len, "%s", path_end);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003751 if (mch_has_exp_wildcard(path_end)) // handle more wildcards
3752 {
3753 // need to expand another component of the path
3754 // remove backslashes for the remaining components only
3755 (void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
3756 }
3757 else
3758 {
3759 stat_T sb;
3760
3761 // no more wildcards, check if there is a match
3762 // remove backslashes for the remaining components only
3763 if (*path_end != NUL)
3764 backslash_halve(buf + len + 1);
3765 // add existing file or symbolic link
3766 if ((flags & EW_ALLLINKS) ? mch_lstat((char *)buf, &sb) >= 0
3767 : mch_getperm(buf) >= 0)
3768 {
3769#ifdef MACOS_CONVERT
3770 size_t precomp_len = STRLEN(buf)+1;
3771 char_u *precomp_buf =
3772 mac_precompose_path(buf, precomp_len, &precomp_len);
3773
3774 if (precomp_buf)
3775 {
3776 mch_memmove(buf, precomp_buf, precomp_len);
3777 vim_free(precomp_buf);
3778 }
3779#endif
3780 addfile(gap, buf, flags);
3781 }
3782 }
3783 }
3784 }
3785
3786 closedir(dirp);
3787 }
3788
3789 vim_free(buf);
3790 vim_regfree(regmatch.regprog);
3791
3792 matches = gap->ga_len - start_len;
3793 if (matches > 0)
3794 qsort(((char_u **)gap->ga_data) + start_len, matches,
3795 sizeof(char_u *), pstrcmp);
3796 return matches;
3797}
3798#endif
3799
3800/*
3801 * Return TRUE if "p" contains what looks like an environment variable.
3802 * Allowing for escaping.
3803 */
3804 static int
3805has_env_var(char_u *p)
3806{
3807 for ( ; *p; MB_PTR_ADV(p))
3808 {
3809 if (*p == '\\' && p[1] != NUL)
3810 ++p;
3811 else if (vim_strchr((char_u *)
3812#if defined(MSWIN)
3813 "$%"
3814#else
3815 "$"
3816#endif
3817 , *p) != NULL)
3818 return TRUE;
3819 }
3820 return FALSE;
3821}
3822
3823#ifdef SPECIAL_WILDCHAR
3824/*
3825 * Return TRUE if "p" contains a special wildcard character, one that Vim
3826 * cannot expand, requires using a shell.
3827 */
3828 static int
3829has_special_wildchar(char_u *p)
3830{
3831 for ( ; *p; MB_PTR_ADV(p))
3832 {
3833 // Disallow line break characters.
3834 if (*p == '\r' || *p == '\n')
3835 break;
3836 // Allow for escaping.
3837 if (*p == '\\' && p[1] != NUL && p[1] != '\r' && p[1] != '\n')
3838 ++p;
3839 else if (vim_strchr((char_u *)SPECIAL_WILDCHAR, *p) != NULL)
3840 {
3841 // A { must be followed by a matching }.
3842 if (*p == '{' && vim_strchr(p, '}') == NULL)
3843 continue;
3844 // A quote and backtick must be followed by another one.
3845 if ((*p == '`' || *p == '\'') && vim_strchr(p, *p) == NULL)
3846 continue;
3847 return TRUE;
3848 }
3849 }
3850 return FALSE;
3851}
3852#endif
3853
3854/*
3855 * Generic wildcard expansion code.
3856 *
3857 * Characters in "pat" that should not be expanded must be preceded with a
3858 * backslash. E.g., "/path\ with\ spaces/my\*star*"
3859 *
3860 * Return FAIL when no single file was found. In this case "num_file" is not
3861 * set, and "file" may contain an error message.
3862 * Return OK when some files found. "num_file" is set to the number of
3863 * matches, "file" to the array of matches. Call FreeWild() later.
3864 */
3865 int
3866gen_expand_wildcards(
3867 int num_pat, // number of input patterns
3868 char_u **pat, // array of input patterns
3869 int *num_file, // resulting number of files
3870 char_u ***file, // array of resulting files
3871 int flags) // EW_* flags
3872{
3873 int i;
3874 garray_T ga;
3875 char_u *p;
3876 static int recursive = FALSE;
3877 int add_pat;
3878 int retval = OK;
3879#if defined(FEAT_SEARCHPATH)
3880 int did_expand_in_path = FALSE;
3881#endif
3882
3883 /*
3884 * expand_env() is called to expand things like "~user". If this fails,
3885 * it calls ExpandOne(), which brings us back here. In this case, always
3886 * call the machine specific expansion function, if possible. Otherwise,
3887 * return FAIL.
3888 */
3889 if (recursive)
3890#ifdef SPECIAL_WILDCHAR
3891 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
3892#else
3893 return FAIL;
3894#endif
3895
3896#ifdef SPECIAL_WILDCHAR
3897 /*
3898 * If there are any special wildcard characters which we cannot handle
3899 * here, call machine specific function for all the expansion. This
3900 * avoids starting the shell for each argument separately.
3901 * For `=expr` do use the internal function.
3902 */
3903 for (i = 0; i < num_pat; i++)
3904 {
3905 if (has_special_wildchar(pat[i])
3906# ifdef VIM_BACKTICK
3907 && !(vim_backtick(pat[i]) && pat[i][1] == '=')
3908# endif
3909 )
3910 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
3911 }
3912#endif
3913
3914 recursive = TRUE;
3915
3916 /*
3917 * The matching file names are stored in a growarray. Init it empty.
3918 */
Bram Moolenaar04935fb2022-01-08 16:19:22 +00003919 ga_init2(&ga, sizeof(char_u *), 30);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003920
3921 for (i = 0; i < num_pat; ++i)
3922 {
3923 add_pat = -1;
3924 p = pat[i];
3925
3926#ifdef VIM_BACKTICK
3927 if (vim_backtick(p))
3928 {
3929 add_pat = expand_backtick(&ga, p, flags);
3930 if (add_pat == -1)
3931 retval = FAIL;
3932 }
3933 else
3934#endif
3935 {
3936 /*
3937 * First expand environment variables, "~/" and "~user/".
3938 */
3939 if ((has_env_var(p) && !(flags & EW_NOTENV)) || *p == '~')
3940 {
3941 p = expand_env_save_opt(p, TRUE);
3942 if (p == NULL)
3943 p = pat[i];
3944#ifdef UNIX
3945 /*
3946 * On Unix, if expand_env() can't expand an environment
3947 * variable, use the shell to do that. Discard previously
3948 * found file names and start all over again.
3949 */
3950 else if (has_env_var(p) || *p == '~')
3951 {
3952 vim_free(p);
3953 ga_clear_strings(&ga);
3954 i = mch_expand_wildcards(num_pat, pat, num_file, file,
3955 flags|EW_KEEPDOLLAR);
3956 recursive = FALSE;
3957 return i;
3958 }
3959#endif
3960 }
3961
3962 /*
LemonBoya3157a42022-04-03 11:58:31 +01003963 * If there are wildcards or case-insensitive expansion is
3964 * required: Expand file names and add each match to the list. If
3965 * there is no match, and EW_NOTFOUND is given, add the pattern.
3966 * Otherwise: Add the file name if it exists or when EW_NOTFOUND is
3967 * given.
Bram Moolenaar26262f82019-09-04 20:59:15 +02003968 */
LemonBoya3157a42022-04-03 11:58:31 +01003969 if (mch_has_exp_wildcard(p) || (flags & EW_ICASE))
Bram Moolenaar26262f82019-09-04 20:59:15 +02003970 {
3971#if defined(FEAT_SEARCHPATH)
3972 if ((flags & EW_PATH)
3973 && !mch_isFullName(p)
3974 && !(p[0] == '.'
3975 && (vim_ispathsep(p[1])
3976 || (p[1] == '.' && vim_ispathsep(p[2]))))
3977 )
3978 {
3979 // :find completion where 'path' is used.
3980 // Recursiveness is OK here.
3981 recursive = FALSE;
3982 add_pat = expand_in_path(&ga, p, flags);
3983 recursive = TRUE;
3984 did_expand_in_path = TRUE;
3985 }
3986 else
3987#endif
3988 add_pat = mch_expandpath(&ga, p, flags);
3989 }
3990 }
3991
3992 if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
3993 {
3994 char_u *t = backslash_halve_save(p);
3995
3996 // When EW_NOTFOUND is used, always add files and dirs. Makes
3997 // "vim c:/" work.
3998 if (flags & EW_NOTFOUND)
3999 addfile(&ga, t, flags | EW_DIR | EW_FILE);
4000 else
4001 addfile(&ga, t, flags);
4002
4003 if (t != p)
4004 vim_free(t);
4005 }
4006
4007#if defined(FEAT_SEARCHPATH)
4008 if (did_expand_in_path && ga.ga_len > 0 && (flags & EW_PATH))
4009 uniquefy_paths(&ga, p);
4010#endif
4011 if (p != pat[i])
4012 vim_free(p);
4013 }
4014
Bram Moolenaar566cc8c2020-06-29 21:14:51 +02004015 // When returning FAIL the array must be freed here.
4016 if (retval == FAIL)
Yegappan Lakshmanan2b74b682022-04-03 21:30:32 +01004017 ga_clear_strings(&ga);
Bram Moolenaar566cc8c2020-06-29 21:14:51 +02004018
Bram Moolenaar26262f82019-09-04 20:59:15 +02004019 *num_file = ga.ga_len;
Bram Moolenaar566cc8c2020-06-29 21:14:51 +02004020 *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data
4021 : (char_u **)_("no matches");
Bram Moolenaar26262f82019-09-04 20:59:15 +02004022
4023 recursive = FALSE;
4024
4025 return ((flags & EW_EMPTYOK) || ga.ga_data != NULL) ? retval : FAIL;
4026}
4027
4028/*
4029 * Add a file to a file list. Accepted flags:
4030 * EW_DIR add directories
4031 * EW_FILE add files
4032 * EW_EXEC add executable files
4033 * EW_NOTFOUND add even when it doesn't exist
4034 * EW_ADDSLASH add slash after directory name
4035 * EW_ALLLINKS add symlink also when the referred file does not exist
4036 */
4037 void
4038addfile(
4039 garray_T *gap,
Bram Moolenaar217e1b82019-12-01 21:41:28 +01004040 char_u *f, // filename
Bram Moolenaar26262f82019-09-04 20:59:15 +02004041 int flags)
4042{
4043 char_u *p;
4044 int isdir;
4045 stat_T sb;
4046
4047 // if the file/dir/link doesn't exist, may not add it
4048 if (!(flags & EW_NOTFOUND) && ((flags & EW_ALLLINKS)
4049 ? mch_lstat((char *)f, &sb) < 0 : mch_getperm(f) < 0))
4050 return;
4051
4052#ifdef FNAME_ILLEGAL
4053 // if the file/dir contains illegal characters, don't add it
4054 if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
4055 return;
4056#endif
4057
4058 isdir = mch_isdir(f);
4059 if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
4060 return;
4061
4062 // If the file isn't executable, may not add it. Do accept directories.
4063 // When invoked from expand_shellcmd() do not use $PATH.
4064 if (!isdir && (flags & EW_EXEC)
4065 && !mch_can_exe(f, NULL, !(flags & EW_SHELLCMD)))
4066 return;
4067
4068 // Make room for another item in the file list.
4069 if (ga_grow(gap, 1) == FAIL)
4070 return;
4071
4072 p = alloc(STRLEN(f) + 1 + isdir);
4073 if (p == NULL)
4074 return;
4075
4076 STRCPY(p, f);
4077#ifdef BACKSLASH_IN_FILENAME
4078 slash_adjust(p);
4079#endif
4080 /*
4081 * Append a slash or backslash after directory names if none is present.
4082 */
4083#ifndef DONT_ADD_PATHSEP_TO_DIR
4084 if (isdir && (flags & EW_ADDSLASH))
4085 add_pathsep(p);
4086#endif
4087 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
4088}
4089
4090/*
4091 * Free the list of files returned by expand_wildcards() or other expansion
4092 * functions.
4093 */
4094 void
4095FreeWild(int count, char_u **files)
4096{
4097 if (count <= 0 || files == NULL)
4098 return;
4099 while (count--)
4100 vim_free(files[count]);
4101 vim_free(files);
4102}
4103
4104/*
4105 * Compare path "p[]" to "q[]".
4106 * If "maxlen" >= 0 compare "p[maxlen]" to "q[maxlen]"
4107 * Return value like strcmp(p, q), but consider path separators.
4108 */
4109 int
4110pathcmp(const char *p, const char *q, int maxlen)
4111{
4112 int i, j;
4113 int c1, c2;
4114 const char *s = NULL;
4115
4116 for (i = 0, j = 0; maxlen < 0 || (i < maxlen && j < maxlen);)
4117 {
4118 c1 = PTR2CHAR((char_u *)p + i);
4119 c2 = PTR2CHAR((char_u *)q + j);
4120
4121 // End of "p": check if "q" also ends or just has a slash.
4122 if (c1 == NUL)
4123 {
4124 if (c2 == NUL) // full match
4125 return 0;
4126 s = q;
4127 i = j;
4128 break;
4129 }
4130
4131 // End of "q": check if "p" just has a slash.
4132 if (c2 == NUL)
4133 {
4134 s = p;
4135 break;
4136 }
4137
4138 if ((p_fic ? MB_TOUPPER(c1) != MB_TOUPPER(c2) : c1 != c2)
4139#ifdef BACKSLASH_IN_FILENAME
4140 // consider '/' and '\\' to be equal
4141 && !((c1 == '/' && c2 == '\\')
4142 || (c1 == '\\' && c2 == '/'))
4143#endif
4144 )
4145 {
4146 if (vim_ispathsep(c1))
4147 return -1;
4148 if (vim_ispathsep(c2))
4149 return 1;
4150 return p_fic ? MB_TOUPPER(c1) - MB_TOUPPER(c2)
4151 : c1 - c2; // no match
4152 }
4153
Bram Moolenaar1614a142019-10-06 22:00:13 +02004154 i += mb_ptr2len((char_u *)p + i);
4155 j += mb_ptr2len((char_u *)q + j);
Bram Moolenaar26262f82019-09-04 20:59:15 +02004156 }
4157 if (s == NULL) // "i" or "j" ran into "maxlen"
4158 return 0;
4159
4160 c1 = PTR2CHAR((char_u *)s + i);
Bram Moolenaar1614a142019-10-06 22:00:13 +02004161 c2 = PTR2CHAR((char_u *)s + i + mb_ptr2len((char_u *)s + i));
Bram Moolenaar26262f82019-09-04 20:59:15 +02004162 // ignore a trailing slash, but not "//" or ":/"
4163 if (c2 == NUL
4164 && i > 0
4165 && !after_pathsep((char_u *)s, (char_u *)s + i)
4166#ifdef BACKSLASH_IN_FILENAME
4167 && (c1 == '/' || c1 == '\\')
4168#else
4169 && c1 == '/'
4170#endif
4171 )
4172 return 0; // match with trailing slash
4173 if (s == q)
4174 return -1; // no match
4175 return 1;
4176}
4177
4178/*
4179 * Return TRUE if "name" is a full (absolute) path name or URL.
4180 */
4181 int
4182vim_isAbsName(char_u *name)
4183{
4184 return (path_with_url(name) != 0 || mch_isFullName(name));
4185}
4186
4187/*
4188 * Get absolute file name into buffer "buf[len]".
4189 *
4190 * return FAIL for failure, OK otherwise
4191 */
4192 int
4193vim_FullName(
4194 char_u *fname,
4195 char_u *buf,
4196 int len,
4197 int force) // force expansion even when already absolute
4198{
4199 int retval = OK;
4200 int url;
4201
4202 *buf = NUL;
4203 if (fname == NULL)
4204 return FAIL;
4205
4206 url = path_with_url(fname);
4207 if (!url)
4208 retval = mch_FullName(fname, buf, len, force);
4209 if (url || retval == FAIL)
4210 {
4211 // something failed; use the file name (truncate when too long)
4212 vim_strncpy(buf, fname, len - 1);
4213 }
4214#if defined(MSWIN)
4215 slash_adjust(buf);
4216#endif
4217 return retval;
4218}