blob: 40b5761aeee218460f6cd8fa0d0027d834aeaa65 [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)
189 vim_strncpy(save_fname, short_fname, len);
190 save_fname = NULL;
191 }
192
Bram Moolenaar26262f82019-09-04 20:59:15 +0200193 // concat the not-shortened part of the path
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200194 vim_strncpy(*fname + len, endp, sfx_len);
195 (*fname)[new_len] = NUL;
196 }
197
198theend:
199 vim_free(pbuf_unused);
200 vim_free(save_fname);
201
202 return retval;
203}
204
205/*
206 * Get a pathname for a partial path.
207 * Returns OK for success, FAIL for failure.
208 */
209 static int
210shortpath_for_partial(
211 char_u **fnamep,
212 char_u **bufp,
213 int *fnamelen)
214{
215 int sepcount, len, tflen;
216 char_u *p;
217 char_u *pbuf, *tfname;
218 int hasTilde;
219
Bram Moolenaar26262f82019-09-04 20:59:15 +0200220 // Count up the path separators from the RHS.. so we know which part
221 // of the path to return.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200222 sepcount = 0;
223 for (p = *fnamep; p < *fnamep + *fnamelen; MB_PTR_ADV(p))
224 if (vim_ispathsep(*p))
225 ++sepcount;
226
Bram Moolenaar26262f82019-09-04 20:59:15 +0200227 // Need full path first (use expand_env() to remove a "~/")
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200228 hasTilde = (**fnamep == '~');
229 if (hasTilde)
230 pbuf = tfname = expand_env_save(*fnamep);
231 else
232 pbuf = tfname = FullName_save(*fnamep, FALSE);
233
234 len = tflen = (int)STRLEN(tfname);
235
236 if (get_short_pathname(&tfname, &pbuf, &len) == FAIL)
237 return FAIL;
238
239 if (len == 0)
240 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200241 // Don't have a valid filename, so shorten the rest of the
242 // path if we can. This CAN give us invalid 8.3 filenames, but
243 // there's not a lot of point in guessing what it might be.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200244 len = tflen;
245 if (shortpath_for_invalid_fname(&tfname, &pbuf, &len) == FAIL)
246 return FAIL;
247 }
248
Bram Moolenaar26262f82019-09-04 20:59:15 +0200249 // Count the paths backward to find the beginning of the desired string.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200250 for (p = tfname + len - 1; p >= tfname; --p)
251 {
252 if (has_mbyte)
253 p -= mb_head_off(tfname, p);
254 if (vim_ispathsep(*p))
255 {
256 if (sepcount == 0 || (hasTilde && sepcount == 1))
257 break;
258 else
259 sepcount --;
260 }
261 }
262 if (hasTilde)
263 {
264 --p;
265 if (p >= tfname)
266 *p = '~';
267 else
268 return FAIL;
269 }
270 else
271 ++p;
272
Bram Moolenaar26262f82019-09-04 20:59:15 +0200273 // Copy in the string - p indexes into tfname - allocated at pbuf
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200274 vim_free(*bufp);
275 *fnamelen = (int)STRLEN(p);
276 *bufp = pbuf;
277 *fnamep = p;
278
279 return OK;
280}
281#endif // MSWIN
282
283/*
284 * Adjust a filename, according to a string of modifiers.
285 * *fnamep must be NUL terminated when called. When returning, the length is
286 * determined by *fnamelen.
287 * Returns VALID_ flags or -1 for failure.
288 * When there is an error, *fnamep is set to NULL.
289 */
290 int
291modify_fname(
292 char_u *src, // string with modifiers
293 int tilde_file, // "~" is a file name, not $HOME
294 int *usedlen, // characters after src that are used
295 char_u **fnamep, // file name so far
296 char_u **bufp, // buffer for allocated file name or NULL
297 int *fnamelen) // length of fnamep
298{
299 int valid = 0;
300 char_u *tail;
301 char_u *s, *p, *pbuf;
302 char_u dirname[MAXPATHL];
303 int c;
304 int has_fullname = 0;
Bram Moolenaard816cd92020-02-04 22:23:09 +0100305 int has_homerelative = 0;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200306#ifdef MSWIN
307 char_u *fname_start = *fnamep;
308 int has_shortname = 0;
309#endif
310
311repeat:
Bram Moolenaar26262f82019-09-04 20:59:15 +0200312 // ":p" - full path/file_name
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200313 if (src[*usedlen] == ':' && src[*usedlen + 1] == 'p')
314 {
315 has_fullname = 1;
316
317 valid |= VALID_PATH;
318 *usedlen += 2;
319
Bram Moolenaar26262f82019-09-04 20:59:15 +0200320 // Expand "~/path" for all systems and "~user/path" for Unix and VMS
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200321 if ((*fnamep)[0] == '~'
322#if !defined(UNIX) && !(defined(VMS) && defined(USER_HOME))
323 && ((*fnamep)[1] == '/'
324# ifdef BACKSLASH_IN_FILENAME
325 || (*fnamep)[1] == '\\'
326# endif
327 || (*fnamep)[1] == NUL)
328#endif
329 && !(tilde_file && (*fnamep)[1] == NUL)
330 )
331 {
332 *fnamep = expand_env_save(*fnamep);
Bram Moolenaar26262f82019-09-04 20:59:15 +0200333 vim_free(*bufp); // free any allocated file name
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200334 *bufp = *fnamep;
335 if (*fnamep == NULL)
336 return -1;
337 }
338
Bram Moolenaar26262f82019-09-04 20:59:15 +0200339 // When "/." or "/.." is used: force expansion to get rid of it.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200340 for (p = *fnamep; *p != NUL; MB_PTR_ADV(p))
341 {
342 if (vim_ispathsep(*p)
343 && p[1] == '.'
344 && (p[2] == NUL
345 || vim_ispathsep(p[2])
346 || (p[2] == '.'
347 && (p[3] == NUL || vim_ispathsep(p[3])))))
348 break;
349 }
350
Bram Moolenaar26262f82019-09-04 20:59:15 +0200351 // FullName_save() is slow, don't use it when not needed.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200352 if (*p != NUL || !vim_isAbsName(*fnamep))
353 {
354 *fnamep = FullName_save(*fnamep, *p != NUL);
Bram Moolenaar26262f82019-09-04 20:59:15 +0200355 vim_free(*bufp); // free any allocated file name
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200356 *bufp = *fnamep;
357 if (*fnamep == NULL)
358 return -1;
359 }
360
361#ifdef MSWIN
362# if _WIN32_WINNT >= 0x0500
363 if (vim_strchr(*fnamep, '~') != NULL)
364 {
365 // Expand 8.3 filename to full path. Needed to make sure the same
366 // file does not have two different names.
367 // Note: problem does not occur if _WIN32_WINNT < 0x0500.
368 WCHAR *wfname = enc_to_utf16(*fnamep, NULL);
369 WCHAR buf[_MAX_PATH];
370
371 if (wfname != NULL)
372 {
373 if (GetLongPathNameW(wfname, buf, _MAX_PATH))
374 {
375 char_u *p = utf16_to_enc(buf, NULL);
376
377 if (p != NULL)
378 {
379 vim_free(*bufp); // free any allocated file name
380 *bufp = *fnamep = p;
381 }
382 }
383 vim_free(wfname);
384 }
385 }
386# endif
387#endif
Bram Moolenaar26262f82019-09-04 20:59:15 +0200388 // Append a path separator to a directory.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200389 if (mch_isdir(*fnamep))
390 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200391 // Make room for one or two extra characters.
Bram Moolenaar71ccd032020-06-12 22:59:11 +0200392 *fnamep = vim_strnsave(*fnamep, STRLEN(*fnamep) + 2);
Bram Moolenaar26262f82019-09-04 20:59:15 +0200393 vim_free(*bufp); // free any allocated file name
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200394 *bufp = *fnamep;
395 if (*fnamep == NULL)
396 return -1;
397 add_pathsep(*fnamep);
398 }
399 }
400
Bram Moolenaar26262f82019-09-04 20:59:15 +0200401 // ":." - path relative to the current directory
402 // ":~" - path relative to the home directory
403 // ":8" - shortname path - postponed till after
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200404 while (src[*usedlen] == ':'
405 && ((c = src[*usedlen + 1]) == '.' || c == '~' || c == '8'))
406 {
407 *usedlen += 2;
408 if (c == '8')
409 {
410#ifdef MSWIN
Bram Moolenaar26262f82019-09-04 20:59:15 +0200411 has_shortname = 1; // Postpone this.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200412#endif
413 continue;
414 }
415 pbuf = NULL;
Bram Moolenaar26262f82019-09-04 20:59:15 +0200416 // Need full path first (use expand_env() to remove a "~/")
Bram Moolenaard816cd92020-02-04 22:23:09 +0100417 if (!has_fullname && !has_homerelative)
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200418 {
Bram Moolenaar0e390f42020-06-10 13:12:28 +0200419 if ((c == '.' || c == '~') && **fnamep == '~')
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200420 p = pbuf = expand_env_save(*fnamep);
421 else
422 p = pbuf = FullName_save(*fnamep, FALSE);
423 }
424 else
425 p = *fnamep;
426
427 has_fullname = 0;
428
429 if (p != NULL)
430 {
431 if (c == '.')
432 {
Bram Moolenaard816cd92020-02-04 22:23:09 +0100433 size_t namelen;
434
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200435 mch_dirname(dirname, MAXPATHL);
Bram Moolenaard816cd92020-02-04 22:23:09 +0100436 if (has_homerelative)
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200437 {
Bram Moolenaard816cd92020-02-04 22:23:09 +0100438 s = vim_strsave(dirname);
439 if (s != NULL)
440 {
441 home_replace(NULL, s, dirname, MAXPATHL, TRUE);
442 vim_free(s);
443 }
444 }
445 namelen = STRLEN(dirname);
446
447 // Do not call shorten_fname() here since it removes the prefix
448 // even though the path does not have a prefix.
449 if (fnamencmp(p, dirname, namelen) == 0)
450 {
451 p += namelen;
Bram Moolenaara78e9c62020-02-05 21:14:00 +0100452 if (vim_ispathsep(*p))
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200453 {
Bram Moolenaara78e9c62020-02-05 21:14:00 +0100454 while (*p && vim_ispathsep(*p))
455 ++p;
456 *fnamep = p;
457 if (pbuf != NULL)
458 {
459 // free any allocated file name
460 vim_free(*bufp);
461 *bufp = pbuf;
462 pbuf = NULL;
463 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200464 }
465 }
466 }
467 else
468 {
469 home_replace(NULL, p, dirname, MAXPATHL, TRUE);
Bram Moolenaar26262f82019-09-04 20:59:15 +0200470 // Only replace it when it starts with '~'
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200471 if (*dirname == '~')
472 {
473 s = vim_strsave(dirname);
474 if (s != NULL)
475 {
476 *fnamep = s;
477 vim_free(*bufp);
478 *bufp = s;
Bram Moolenaard816cd92020-02-04 22:23:09 +0100479 has_homerelative = TRUE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200480 }
481 }
482 }
483 vim_free(pbuf);
484 }
485 }
486
487 tail = gettail(*fnamep);
488 *fnamelen = (int)STRLEN(*fnamep);
489
Bram Moolenaar26262f82019-09-04 20:59:15 +0200490 // ":h" - head, remove "/file_name", can be repeated
491 // Don't remove the first "/" or "c:\"
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200492 while (src[*usedlen] == ':' && src[*usedlen + 1] == 'h')
493 {
494 valid |= VALID_HEAD;
495 *usedlen += 2;
496 s = get_past_head(*fnamep);
497 while (tail > s && after_pathsep(s, tail))
498 MB_PTR_BACK(*fnamep, tail);
499 *fnamelen = (int)(tail - *fnamep);
500#ifdef VMS
501 if (*fnamelen > 0)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200502 *fnamelen += 1; // the path separator is part of the path
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200503#endif
504 if (*fnamelen == 0)
505 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200506 // Result is empty. Turn it into "." to make ":cd %:h" work.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200507 p = vim_strsave((char_u *)".");
508 if (p == NULL)
509 return -1;
510 vim_free(*bufp);
511 *bufp = *fnamep = tail = p;
512 *fnamelen = 1;
513 }
514 else
515 {
516 while (tail > s && !after_pathsep(s, tail))
517 MB_PTR_BACK(*fnamep, tail);
518 }
519 }
520
Bram Moolenaar26262f82019-09-04 20:59:15 +0200521 // ":8" - shortname
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200522 if (src[*usedlen] == ':' && src[*usedlen + 1] == '8')
523 {
524 *usedlen += 2;
525#ifdef MSWIN
526 has_shortname = 1;
527#endif
528 }
529
530#ifdef MSWIN
531 /*
532 * Handle ":8" after we have done 'heads' and before we do 'tails'.
533 */
534 if (has_shortname)
535 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200536 // Copy the string if it is shortened by :h and when it wasn't copied
537 // yet, because we are going to change it in place. Avoids changing
538 // the buffer name for "%:8".
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200539 if (*fnamelen < (int)STRLEN(*fnamep) || *fnamep == fname_start)
540 {
541 p = vim_strnsave(*fnamep, *fnamelen);
542 if (p == NULL)
543 return -1;
544 vim_free(*bufp);
545 *bufp = *fnamep = p;
546 }
547
Bram Moolenaar26262f82019-09-04 20:59:15 +0200548 // Split into two implementations - makes it easier. First is where
549 // there isn't a full name already, second is where there is.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200550 if (!has_fullname && !vim_isAbsName(*fnamep))
551 {
552 if (shortpath_for_partial(fnamep, bufp, fnamelen) == FAIL)
553 return -1;
554 }
555 else
556 {
557 int l = *fnamelen;
558
Bram Moolenaar26262f82019-09-04 20:59:15 +0200559 // Simple case, already have the full-name.
560 // Nearly always shorter, so try first time.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200561 if (get_short_pathname(fnamep, bufp, &l) == FAIL)
562 return -1;
563
564 if (l == 0)
565 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200566 // Couldn't find the filename, search the paths.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200567 l = *fnamelen;
568 if (shortpath_for_invalid_fname(fnamep, bufp, &l) == FAIL)
569 return -1;
570 }
571 *fnamelen = l;
572 }
573 }
574#endif // MSWIN
575
Bram Moolenaar26262f82019-09-04 20:59:15 +0200576 // ":t" - tail, just the basename
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200577 if (src[*usedlen] == ':' && src[*usedlen + 1] == 't')
578 {
579 *usedlen += 2;
580 *fnamelen -= (int)(tail - *fnamep);
581 *fnamep = tail;
582 }
583
Bram Moolenaar26262f82019-09-04 20:59:15 +0200584 // ":e" - extension, can be repeated
585 // ":r" - root, without extension, can be repeated
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200586 while (src[*usedlen] == ':'
587 && (src[*usedlen + 1] == 'e' || src[*usedlen + 1] == 'r'))
588 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200589 // find a '.' in the tail:
590 // - for second :e: before the current fname
591 // - otherwise: The last '.'
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200592 if (src[*usedlen + 1] == 'e' && *fnamep > tail)
593 s = *fnamep - 2;
594 else
595 s = *fnamep + *fnamelen - 1;
596 for ( ; s > tail; --s)
597 if (s[0] == '.')
598 break;
Bram Moolenaar26262f82019-09-04 20:59:15 +0200599 if (src[*usedlen + 1] == 'e') // :e
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200600 {
601 if (s > tail)
602 {
603 *fnamelen += (int)(*fnamep - (s + 1));
604 *fnamep = s + 1;
605#ifdef VMS
Bram Moolenaar26262f82019-09-04 20:59:15 +0200606 // cut version from the extension
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200607 s = *fnamep + *fnamelen - 1;
608 for ( ; s > *fnamep; --s)
609 if (s[0] == ';')
610 break;
611 if (s > *fnamep)
612 *fnamelen = s - *fnamep;
613#endif
614 }
615 else if (*fnamep <= tail)
616 *fnamelen = 0;
617 }
Bram Moolenaar26262f82019-09-04 20:59:15 +0200618 else // :r
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200619 {
Bram Moolenaarb1892952019-10-08 23:26:50 +0200620 char_u *limit = *fnamep;
621
622 if (limit < tail)
623 limit = tail;
624 if (s > limit) // remove one extension
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200625 *fnamelen = (int)(s - *fnamep);
626 }
627 *usedlen += 2;
628 }
629
Bram Moolenaar26262f82019-09-04 20:59:15 +0200630 // ":s?pat?foo?" - substitute
631 // ":gs?pat?foo?" - global substitute
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200632 if (src[*usedlen] == ':'
633 && (src[*usedlen + 1] == 's'
634 || (src[*usedlen + 1] == 'g' && src[*usedlen + 2] == 's')))
635 {
636 char_u *str;
637 char_u *pat;
638 char_u *sub;
639 int sep;
640 char_u *flags;
641 int didit = FALSE;
642
643 flags = (char_u *)"";
644 s = src + *usedlen + 2;
645 if (src[*usedlen + 1] == 'g')
646 {
647 flags = (char_u *)"g";
648 ++s;
649 }
650
651 sep = *s++;
652 if (sep)
653 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200654 // find end of pattern
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200655 p = vim_strchr(s, sep);
656 if (p != NULL)
657 {
Bram Moolenaar71ccd032020-06-12 22:59:11 +0200658 pat = vim_strnsave(s, p - s);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200659 if (pat != NULL)
660 {
661 s = p + 1;
Bram Moolenaar26262f82019-09-04 20:59:15 +0200662 // find end of substitution
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200663 p = vim_strchr(s, sep);
664 if (p != NULL)
665 {
Bram Moolenaar71ccd032020-06-12 22:59:11 +0200666 sub = vim_strnsave(s, p - s);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200667 str = vim_strnsave(*fnamep, *fnamelen);
668 if (sub != NULL && str != NULL)
669 {
670 *usedlen = (int)(p + 1 - src);
671 s = do_string_sub(str, pat, sub, NULL, flags);
672 if (s != NULL)
673 {
674 *fnamep = s;
675 *fnamelen = (int)STRLEN(s);
676 vim_free(*bufp);
677 *bufp = s;
678 didit = TRUE;
679 }
680 }
681 vim_free(sub);
682 vim_free(str);
683 }
684 vim_free(pat);
685 }
686 }
Bram Moolenaar26262f82019-09-04 20:59:15 +0200687 // after using ":s", repeat all the modifiers
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200688 if (didit)
689 goto repeat;
690 }
691 }
692
693 if (src[*usedlen] == ':' && src[*usedlen + 1] == 'S')
694 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200695 // vim_strsave_shellescape() needs a NUL terminated string.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200696 c = (*fnamep)[*fnamelen];
697 if (c != NUL)
698 (*fnamep)[*fnamelen] = NUL;
699 p = vim_strsave_shellescape(*fnamep, FALSE, FALSE);
700 if (c != NUL)
701 (*fnamep)[*fnamelen] = c;
702 if (p == NULL)
703 return -1;
704 vim_free(*bufp);
705 *bufp = *fnamep = p;
706 *fnamelen = (int)STRLEN(p);
707 *usedlen += 2;
708 }
709
710 return valid;
711}
712
Bram Moolenaar273af492020-09-25 23:49:01 +0200713/*
714 * Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
715 * "trim_len" specifies how many characters to keep for each directory.
716 * Must be 1 or more.
717 * It's done in-place.
718 */
719 static void
720shorten_dir_len(char_u *str, int trim_len)
721{
722 char_u *tail, *s, *d;
723 int skip = FALSE;
724 int dirchunk_len = 0;
725
726 tail = gettail(str);
727 d = str;
728 for (s = str; ; ++s)
729 {
730 if (s >= tail) // copy the whole tail
731 {
732 *d++ = *s;
733 if (*s == NUL)
734 break;
735 }
736 else if (vim_ispathsep(*s)) // copy '/' and next char
737 {
738 *d++ = *s;
739 skip = FALSE;
740 dirchunk_len = 0;
741 }
742 else if (!skip)
743 {
744 *d++ = *s; // copy next char
745 if (*s != '~' && *s != '.') // and leading "~" and "."
746 {
747 ++dirchunk_len; // only count word chars for the size
748
749 // keep copying chars until we have our preferred length (or
750 // until the above if/else branches move us along)
751 if (dirchunk_len >= trim_len)
752 skip = TRUE;
753 }
754
755 if (has_mbyte)
756 {
757 int l = mb_ptr2len(s);
758
759 while (--l > 0)
760 *d++ = *++s;
761 }
762 }
763 }
764}
765
766/*
767 * Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
768 * It's done in-place.
769 */
770 void
771shorten_dir(char_u *str)
772{
773 shorten_dir_len(str, 1);
774}
775
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200776#if defined(FEAT_EVAL) || defined(PROTO)
777
778/*
779 * "chdir(dir)" function
780 */
781 void
782f_chdir(typval_T *argvars, typval_T *rettv)
783{
784 char_u *cwd;
785 cdscope_T scope = CDSCOPE_GLOBAL;
786
787 rettv->v_type = VAR_STRING;
788 rettv->vval.v_string = NULL;
789
790 if (argvars[0].v_type != VAR_STRING)
Bram Moolenaarc5809432021-03-27 21:23:30 +0100791 {
Bram Moolenaard816cd92020-02-04 22:23:09 +0100792 // Returning an empty string means it failed.
Bram Moolenaar002bc792020-06-05 22:33:42 +0200793 // No error message, for historic reasons.
Bram Moolenaarc5809432021-03-27 21:23:30 +0100794 if (in_vim9script())
795 (void) check_for_string_arg(argvars, 0);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200796 return;
Bram Moolenaarc5809432021-03-27 21:23:30 +0100797 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200798
799 // Return the current directory
800 cwd = alloc(MAXPATHL);
801 if (cwd != NULL)
802 {
803 if (mch_dirname(cwd, MAXPATHL) != FAIL)
804 {
805#ifdef BACKSLASH_IN_FILENAME
806 slash_adjust(cwd);
807#endif
808 rettv->vval.v_string = vim_strsave(cwd);
809 }
810 vim_free(cwd);
811 }
812
813 if (curwin->w_localdir != NULL)
814 scope = CDSCOPE_WINDOW;
815 else if (curtab->tp_localdir != NULL)
816 scope = CDSCOPE_TABPAGE;
817
818 if (!changedir_func(argvars[0].vval.v_string, TRUE, scope))
819 // Directory change failed
820 VIM_CLEAR(rettv->vval.v_string);
821}
822
823/*
824 * "delete()" function
825 */
826 void
827f_delete(typval_T *argvars, typval_T *rettv)
828{
829 char_u nbuf[NUMBUFLEN];
830 char_u *name;
831 char_u *flags;
832
833 rettv->vval.v_number = -1;
834 if (check_restricted() || check_secure())
835 return;
836
837 name = tv_get_string(&argvars[0]);
838 if (name == NULL || *name == NUL)
839 {
840 emsg(_(e_invarg));
841 return;
842 }
843
844 if (argvars[1].v_type != VAR_UNKNOWN)
845 flags = tv_get_string_buf(&argvars[1], nbuf);
846 else
847 flags = (char_u *)"";
848
849 if (*flags == NUL)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200850 // delete a file
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200851 rettv->vval.v_number = mch_remove(name) == 0 ? 0 : -1;
852 else if (STRCMP(flags, "d") == 0)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200853 // delete an empty directory
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200854 rettv->vval.v_number = mch_rmdir(name) == 0 ? 0 : -1;
855 else if (STRCMP(flags, "rf") == 0)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200856 // delete a directory recursively
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200857 rettv->vval.v_number = delete_recursive(name);
858 else
Bram Moolenaar108010a2021-06-27 22:03:33 +0200859 semsg(_(e_invalid_expression_str), flags);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200860}
861
862/*
863 * "executable()" function
864 */
865 void
866f_executable(typval_T *argvars, typval_T *rettv)
867{
Bram Moolenaar32105ae2021-03-27 18:59:25 +0100868 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100869 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200870
Bram Moolenaar26262f82019-09-04 20:59:15 +0200871 // Check in $PATH and also check directly if there is a directory name.
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100872 rettv->vval.v_number = mch_can_exe(tv_get_string(&argvars[0]), NULL, TRUE);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200873}
874
875/*
876 * "exepath()" function
877 */
878 void
879f_exepath(typval_T *argvars, typval_T *rettv)
880{
881 char_u *p = NULL;
882
Bram Moolenaar32105ae2021-03-27 18:59:25 +0100883 if (in_vim9script() && check_for_nonempty_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100884 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200885 (void)mch_can_exe(tv_get_string(&argvars[0]), &p, TRUE);
886 rettv->v_type = VAR_STRING;
887 rettv->vval.v_string = p;
888}
889
890/*
891 * "filereadable()" function
892 */
893 void
894f_filereadable(typval_T *argvars, typval_T *rettv)
895{
896 int fd;
897 char_u *p;
898 int n;
899
Bram Moolenaar32105ae2021-03-27 18:59:25 +0100900 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100901 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200902#ifndef O_NONBLOCK
903# define O_NONBLOCK 0
904#endif
905 p = tv_get_string(&argvars[0]);
906 if (*p && !mch_isdir(p) && (fd = mch_open((char *)p,
907 O_RDONLY | O_NONBLOCK, 0)) >= 0)
908 {
909 n = TRUE;
910 close(fd);
911 }
912 else
913 n = FALSE;
914
915 rettv->vval.v_number = n;
916}
917
918/*
919 * Return 0 for not writable, 1 for writable file, 2 for a dir which we have
920 * rights to write into.
921 */
922 void
923f_filewritable(typval_T *argvars, typval_T *rettv)
924{
Bram Moolenaar32105ae2021-03-27 18:59:25 +0100925 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100926 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200927 rettv->vval.v_number = filewritable(tv_get_string(&argvars[0]));
928}
929
Bram Moolenaar840d16f2019-09-10 21:27:18 +0200930 static void
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200931findfilendir(
932 typval_T *argvars UNUSED,
933 typval_T *rettv,
934 int find_what UNUSED)
935{
936#ifdef FEAT_SEARCHPATH
937 char_u *fname;
938 char_u *fresult = NULL;
939 char_u *path = *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path;
940 char_u *p;
941 char_u pathbuf[NUMBUFLEN];
942 int count = 1;
943 int first = TRUE;
944 int error = FALSE;
945#endif
946
947 rettv->vval.v_string = NULL;
948 rettv->v_type = VAR_STRING;
Bram Moolenaar32105ae2021-03-27 18:59:25 +0100949 if (in_vim9script() && check_for_nonempty_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100950 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200951
952#ifdef FEAT_SEARCHPATH
953 fname = tv_get_string(&argvars[0]);
954
955 if (argvars[1].v_type != VAR_UNKNOWN)
956 {
957 p = tv_get_string_buf_chk(&argvars[1], pathbuf);
958 if (p == NULL)
959 error = TRUE;
960 else
961 {
962 if (*p != NUL)
963 path = p;
964
965 if (argvars[2].v_type != VAR_UNKNOWN)
966 count = (int)tv_get_number_chk(&argvars[2], &error);
967 }
968 }
969
970 if (count < 0 && rettv_list_alloc(rettv) == FAIL)
971 error = TRUE;
972
973 if (*fname != NUL && !error)
974 {
975 do
976 {
977 if (rettv->v_type == VAR_STRING || rettv->v_type == VAR_LIST)
978 vim_free(fresult);
979 fresult = find_file_in_path_option(first ? fname : NULL,
980 first ? (int)STRLEN(fname) : 0,
981 0, first, path,
982 find_what,
983 curbuf->b_ffname,
984 find_what == FINDFILE_DIR
985 ? (char_u *)"" : curbuf->b_p_sua);
986 first = FALSE;
987
988 if (fresult != NULL && rettv->v_type == VAR_LIST)
989 list_append_string(rettv->vval.v_list, fresult, -1);
990
991 } while ((rettv->v_type == VAR_LIST || --count > 0) && fresult != NULL);
992 }
993
994 if (rettv->v_type == VAR_STRING)
995 rettv->vval.v_string = fresult;
996#endif
997}
998
999/*
1000 * "finddir({fname}[, {path}[, {count}]])" function
1001 */
1002 void
1003f_finddir(typval_T *argvars, typval_T *rettv)
1004{
1005 findfilendir(argvars, rettv, FINDFILE_DIR);
1006}
1007
1008/*
1009 * "findfile({fname}[, {path}[, {count}]])" function
1010 */
1011 void
1012f_findfile(typval_T *argvars, typval_T *rettv)
1013{
1014 findfilendir(argvars, rettv, FINDFILE_FILE);
1015}
1016
1017/*
1018 * "fnamemodify({fname}, {mods})" function
1019 */
1020 void
1021f_fnamemodify(typval_T *argvars, typval_T *rettv)
1022{
1023 char_u *fname;
1024 char_u *mods;
1025 int usedlen = 0;
Bram Moolenaarc5308522020-12-13 12:25:35 +01001026 int len = 0;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001027 char_u *fbuf = NULL;
1028 char_u buf[NUMBUFLEN];
1029
Bram Moolenaar32105ae2021-03-27 18:59:25 +01001030 if (in_vim9script() && (check_for_string_arg(argvars, 0) == FAIL
1031 || check_for_string_arg(argvars, 1) == FAIL))
Bram Moolenaar7bb4e742020-12-09 12:41:50 +01001032 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001033 fname = tv_get_string_chk(&argvars[0]);
1034 mods = tv_get_string_buf_chk(&argvars[1], buf);
Bram Moolenaarc5308522020-12-13 12:25:35 +01001035 if (mods == NULL || fname == NULL)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001036 fname = NULL;
Bram Moolenaarc5308522020-12-13 12:25:35 +01001037 else
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001038 {
1039 len = (int)STRLEN(fname);
Bram Moolenaarc5308522020-12-13 12:25:35 +01001040 if (mods != NULL && *mods != NUL)
1041 (void)modify_fname(mods, FALSE, &usedlen, &fname, &fbuf, &len);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001042 }
1043
1044 rettv->v_type = VAR_STRING;
1045 if (fname == NULL)
1046 rettv->vval.v_string = NULL;
1047 else
1048 rettv->vval.v_string = vim_strnsave(fname, len);
1049 vim_free(fbuf);
1050}
1051
1052/*
1053 * "getcwd()" function
1054 *
1055 * Return the current working directory of a window in a tab page.
1056 * First optional argument 'winnr' is the window number or -1 and the second
1057 * optional argument 'tabnr' is the tab page number.
1058 *
1059 * If no arguments are supplied, then return the directory of the current
1060 * window.
1061 * If only 'winnr' is specified and is not -1 or 0 then return the directory of
1062 * the specified window.
1063 * If 'winnr' is 0 then return the directory of the current window.
1064 * If both 'winnr and 'tabnr' are specified and 'winnr' is -1 then return the
1065 * directory of the specified tab page. Otherwise return the directory of the
1066 * specified window in the specified tab page.
1067 * If the window or the tab page doesn't exist then return NULL.
1068 */
1069 void
1070f_getcwd(typval_T *argvars, typval_T *rettv)
1071{
1072 win_T *wp = NULL;
1073 tabpage_T *tp = NULL;
1074 char_u *cwd;
1075 int global = FALSE;
1076
1077 rettv->v_type = VAR_STRING;
1078 rettv->vval.v_string = NULL;
1079
1080 if (argvars[0].v_type == VAR_NUMBER
1081 && argvars[0].vval.v_number == -1
1082 && argvars[1].v_type == VAR_UNKNOWN)
1083 global = TRUE;
1084 else
1085 wp = find_tabwin(&argvars[0], &argvars[1], &tp);
1086
1087 if (wp != NULL && wp->w_localdir != NULL)
1088 rettv->vval.v_string = vim_strsave(wp->w_localdir);
1089 else if (tp != NULL && tp->tp_localdir != NULL)
1090 rettv->vval.v_string = vim_strsave(tp->tp_localdir);
1091 else if (wp != NULL || tp != NULL || global)
1092 {
1093 if (globaldir != NULL)
1094 rettv->vval.v_string = vim_strsave(globaldir);
1095 else
1096 {
1097 cwd = alloc(MAXPATHL);
1098 if (cwd != NULL)
1099 {
1100 if (mch_dirname(cwd, MAXPATHL) != FAIL)
1101 rettv->vval.v_string = vim_strsave(cwd);
1102 vim_free(cwd);
1103 }
1104 }
1105 }
1106#ifdef BACKSLASH_IN_FILENAME
1107 if (rettv->vval.v_string != NULL)
1108 slash_adjust(rettv->vval.v_string);
1109#endif
1110}
1111
1112/*
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001113 * Convert "st" to file permission string.
1114 */
1115 char_u *
1116getfpermst(stat_T *st, char_u *perm)
1117{
1118 char_u flags[] = "rwx";
1119 int i;
1120
1121 for (i = 0; i < 9; i++)
1122 {
1123 if (st->st_mode & (1 << (8 - i)))
1124 perm[i] = flags[i % 3];
1125 else
1126 perm[i] = '-';
1127 }
1128 return perm;
1129}
1130
1131/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001132 * "getfperm({fname})" function
1133 */
1134 void
1135f_getfperm(typval_T *argvars, typval_T *rettv)
1136{
1137 char_u *fname;
1138 stat_T st;
1139 char_u *perm = NULL;
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001140 char_u permbuf[] = "---------";
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001141
Bram Moolenaar32105ae2021-03-27 18:59:25 +01001142 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +01001143 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001144 fname = tv_get_string(&argvars[0]);
1145
1146 rettv->v_type = VAR_STRING;
1147 if (mch_stat((char *)fname, &st) >= 0)
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001148 perm = vim_strsave(getfpermst(&st, permbuf));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001149 rettv->vval.v_string = perm;
1150}
1151
1152/*
1153 * "getfsize({fname})" function
1154 */
1155 void
1156f_getfsize(typval_T *argvars, typval_T *rettv)
1157{
1158 char_u *fname;
1159 stat_T st;
1160
Bram Moolenaar32105ae2021-03-27 18:59:25 +01001161 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +01001162 return;
1163
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001164 fname = tv_get_string(&argvars[0]);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001165 if (mch_stat((char *)fname, &st) >= 0)
1166 {
1167 if (mch_isdir(fname))
1168 rettv->vval.v_number = 0;
1169 else
1170 {
1171 rettv->vval.v_number = (varnumber_T)st.st_size;
1172
Bram Moolenaar26262f82019-09-04 20:59:15 +02001173 // non-perfect check for overflow
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001174 if ((off_T)rettv->vval.v_number != (off_T)st.st_size)
1175 rettv->vval.v_number = -2;
1176 }
1177 }
1178 else
1179 rettv->vval.v_number = -1;
1180}
1181
1182/*
1183 * "getftime({fname})" function
1184 */
1185 void
1186f_getftime(typval_T *argvars, typval_T *rettv)
1187{
1188 char_u *fname;
1189 stat_T st;
1190
Bram Moolenaar32105ae2021-03-27 18:59:25 +01001191 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +01001192 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001193 fname = tv_get_string(&argvars[0]);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001194 if (mch_stat((char *)fname, &st) >= 0)
1195 rettv->vval.v_number = (varnumber_T)st.st_mtime;
1196 else
1197 rettv->vval.v_number = -1;
1198}
1199
1200/*
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001201 * Convert "st" to file type string.
1202 */
1203 char_u *
1204getftypest(stat_T *st)
1205{
1206 char *t;
1207
1208 if (S_ISREG(st->st_mode))
1209 t = "file";
1210 else if (S_ISDIR(st->st_mode))
1211 t = "dir";
1212 else if (S_ISLNK(st->st_mode))
1213 t = "link";
1214 else if (S_ISBLK(st->st_mode))
1215 t = "bdev";
1216 else if (S_ISCHR(st->st_mode))
1217 t = "cdev";
1218 else if (S_ISFIFO(st->st_mode))
1219 t = "fifo";
1220 else if (S_ISSOCK(st->st_mode))
1221 t = "socket";
1222 else
1223 t = "other";
1224 return (char_u*)t;
1225}
1226
1227/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001228 * "getftype({fname})" function
1229 */
1230 void
1231f_getftype(typval_T *argvars, typval_T *rettv)
1232{
1233 char_u *fname;
1234 stat_T st;
1235 char_u *type = NULL;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001236
Bram Moolenaar32105ae2021-03-27 18:59:25 +01001237 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +01001238 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001239 fname = tv_get_string(&argvars[0]);
1240
1241 rettv->v_type = VAR_STRING;
1242 if (mch_lstat((char *)fname, &st) >= 0)
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001243 type = vim_strsave(getftypest(&st));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001244 rettv->vval.v_string = type;
1245}
1246
1247/*
1248 * "glob()" function
1249 */
1250 void
1251f_glob(typval_T *argvars, typval_T *rettv)
1252{
1253 int options = WILD_SILENT|WILD_USE_NL;
1254 expand_T xpc;
1255 int error = FALSE;
1256
Bram Moolenaar26262f82019-09-04 20:59:15 +02001257 // When the optional second argument is non-zero, don't remove matches
1258 // for 'wildignore' and don't put matches for 'suffixes' at the end.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001259 rettv->v_type = VAR_STRING;
1260 if (argvars[1].v_type != VAR_UNKNOWN)
1261 {
Bram Moolenaar5892ea12020-09-02 21:53:11 +02001262 if (tv_get_bool_chk(&argvars[1], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001263 options |= WILD_KEEP_ALL;
1264 if (argvars[2].v_type != VAR_UNKNOWN)
1265 {
Bram Moolenaar5892ea12020-09-02 21:53:11 +02001266 if (tv_get_bool_chk(&argvars[2], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001267 rettv_list_set(rettv, NULL);
1268 if (argvars[3].v_type != VAR_UNKNOWN
Bram Moolenaar5892ea12020-09-02 21:53:11 +02001269 && tv_get_bool_chk(&argvars[3], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001270 options |= WILD_ALLLINKS;
1271 }
1272 }
1273 if (!error)
1274 {
1275 ExpandInit(&xpc);
1276 xpc.xp_context = EXPAND_FILES;
1277 if (p_wic)
1278 options += WILD_ICASE;
1279 if (rettv->v_type == VAR_STRING)
1280 rettv->vval.v_string = ExpandOne(&xpc, tv_get_string(&argvars[0]),
1281 NULL, options, WILD_ALL);
1282 else if (rettv_list_alloc(rettv) != FAIL)
1283 {
1284 int i;
1285
1286 ExpandOne(&xpc, tv_get_string(&argvars[0]),
1287 NULL, options, WILD_ALL_KEEP);
1288 for (i = 0; i < xpc.xp_numfiles; i++)
1289 list_append_string(rettv->vval.v_list, xpc.xp_files[i], -1);
1290
1291 ExpandCleanup(&xpc);
1292 }
1293 }
1294 else
1295 rettv->vval.v_string = NULL;
1296}
1297
1298/*
1299 * "glob2regpat()" function
1300 */
1301 void
1302f_glob2regpat(typval_T *argvars, typval_T *rettv)
1303{
Bram Moolenaar3cfa5b12021-06-06 14:14:39 +02001304 char_u buf[NUMBUFLEN];
1305 char_u *pat = tv_get_string_buf_chk_strict(&argvars[0], buf,
1306 in_vim9script());
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001307
1308 rettv->v_type = VAR_STRING;
1309 rettv->vval.v_string = (pat == NULL)
1310 ? NULL : file_pat_to_reg_pat(pat, NULL, NULL, FALSE);
1311}
1312
1313/*
1314 * "globpath()" function
1315 */
1316 void
1317f_globpath(typval_T *argvars, typval_T *rettv)
1318{
1319 int flags = WILD_IGNORE_COMPLETESLASH;
1320 char_u buf1[NUMBUFLEN];
1321 char_u *file = tv_get_string_buf_chk(&argvars[1], buf1);
1322 int error = FALSE;
1323 garray_T ga;
1324 int i;
1325
1326 // When the optional second argument is non-zero, don't remove matches
1327 // for 'wildignore' and don't put matches for 'suffixes' at the end.
1328 rettv->v_type = VAR_STRING;
1329 if (argvars[2].v_type != VAR_UNKNOWN)
1330 {
Bram Moolenaarf966ce52020-09-02 21:57:07 +02001331 if (tv_get_bool_chk(&argvars[2], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001332 flags |= WILD_KEEP_ALL;
1333 if (argvars[3].v_type != VAR_UNKNOWN)
1334 {
Bram Moolenaarf966ce52020-09-02 21:57:07 +02001335 if (tv_get_bool_chk(&argvars[3], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001336 rettv_list_set(rettv, NULL);
1337 if (argvars[4].v_type != VAR_UNKNOWN
Bram Moolenaarf966ce52020-09-02 21:57:07 +02001338 && tv_get_bool_chk(&argvars[4], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001339 flags |= WILD_ALLLINKS;
1340 }
1341 }
1342 if (file != NULL && !error)
1343 {
1344 ga_init2(&ga, (int)sizeof(char_u *), 10);
1345 globpath(tv_get_string(&argvars[0]), file, &ga, flags);
1346 if (rettv->v_type == VAR_STRING)
1347 rettv->vval.v_string = ga_concat_strings(&ga, "\n");
1348 else if (rettv_list_alloc(rettv) != FAIL)
1349 for (i = 0; i < ga.ga_len; ++i)
1350 list_append_string(rettv->vval.v_list,
1351 ((char_u **)(ga.ga_data))[i], -1);
1352 ga_clear_strings(&ga);
1353 }
1354 else
1355 rettv->vval.v_string = NULL;
1356}
1357
1358/*
1359 * "isdirectory()" function
1360 */
1361 void
1362f_isdirectory(typval_T *argvars, typval_T *rettv)
1363{
1364 rettv->vval.v_number = mch_isdir(tv_get_string(&argvars[0]));
1365}
1366
1367/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001368 * Create the directory in which "dir" is located, and higher levels when
1369 * needed.
1370 * Return OK or FAIL.
1371 */
1372 static int
1373mkdir_recurse(char_u *dir, int prot)
1374{
1375 char_u *p;
1376 char_u *updir;
1377 int r = FAIL;
1378
Bram Moolenaar26262f82019-09-04 20:59:15 +02001379 // Get end of directory name in "dir".
1380 // We're done when it's "/" or "c:/".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001381 p = gettail_sep(dir);
1382 if (p <= get_past_head(dir))
1383 return OK;
1384
Bram Moolenaar26262f82019-09-04 20:59:15 +02001385 // If the directory exists we're done. Otherwise: create it.
Bram Moolenaar71ccd032020-06-12 22:59:11 +02001386 updir = vim_strnsave(dir, p - dir);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001387 if (updir == NULL)
1388 return FAIL;
1389 if (mch_isdir(updir))
1390 r = OK;
1391 else if (mkdir_recurse(updir, prot) == OK)
1392 r = vim_mkdir_emsg(updir, prot);
1393 vim_free(updir);
1394 return r;
1395}
1396
1397/*
1398 * "mkdir()" function
1399 */
1400 void
1401f_mkdir(typval_T *argvars, typval_T *rettv)
1402{
1403 char_u *dir;
1404 char_u buf[NUMBUFLEN];
1405 int prot = 0755;
1406
1407 rettv->vval.v_number = FAIL;
1408 if (check_restricted() || check_secure())
1409 return;
1410
1411 dir = tv_get_string_buf(&argvars[0], buf);
1412 if (*dir == NUL)
1413 return;
1414
1415 if (*gettail(dir) == NUL)
Bram Moolenaar26262f82019-09-04 20:59:15 +02001416 // remove trailing slashes
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001417 *gettail_sep(dir) = NUL;
1418
1419 if (argvars[1].v_type != VAR_UNKNOWN)
1420 {
1421 if (argvars[2].v_type != VAR_UNKNOWN)
1422 {
1423 prot = (int)tv_get_number_chk(&argvars[2], NULL);
1424 if (prot == -1)
1425 return;
1426 }
1427 if (STRCMP(tv_get_string(&argvars[1]), "p") == 0)
1428 {
1429 if (mch_isdir(dir))
1430 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001431 // With the "p" flag it's OK if the dir already exists.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001432 rettv->vval.v_number = OK;
1433 return;
1434 }
1435 mkdir_recurse(dir, prot);
1436 }
1437 }
1438 rettv->vval.v_number = vim_mkdir_emsg(dir, prot);
1439}
1440
1441/*
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02001442 * "pathshorten()" function
1443 */
1444 void
1445f_pathshorten(typval_T *argvars, typval_T *rettv)
1446{
1447 char_u *p;
Bram Moolenaar6a33ef02020-09-25 22:42:48 +02001448 int trim_len = 1;
1449
Yegappan Lakshmanan1a71d312021-07-15 12:49:58 +02001450 if (in_vim9script()
1451 && (check_for_string_arg(argvars, 0) == FAIL
1452 || (argvars[1].v_type != VAR_UNKNOWN
1453 && check_for_number_arg(argvars, 1) == FAIL)))
1454 return;
1455
Bram Moolenaar6a33ef02020-09-25 22:42:48 +02001456 if (argvars[1].v_type != VAR_UNKNOWN)
1457 {
1458 trim_len = (int)tv_get_number(&argvars[1]);
1459 if (trim_len < 1)
1460 trim_len = 1;
1461 }
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02001462
1463 rettv->v_type = VAR_STRING;
1464 p = tv_get_string_chk(&argvars[0]);
Bram Moolenaar6a33ef02020-09-25 22:42:48 +02001465
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02001466 if (p == NULL)
1467 rettv->vval.v_string = NULL;
1468 else
1469 {
1470 p = vim_strsave(p);
1471 rettv->vval.v_string = p;
1472 if (p != NULL)
Bram Moolenaar6a33ef02020-09-25 22:42:48 +02001473 shorten_dir_len(p, trim_len);
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02001474 }
1475}
1476
1477/*
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001478 * Common code for readdir_checkitem() and readdirex_checkitem().
1479 * Either "name" or "dict" is NULL.
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001480 */
1481 static int
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001482checkitem_common(void *context, char_u *name, dict_T *dict)
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001483{
1484 typval_T *expr = (typval_T *)context;
1485 typval_T save_val;
1486 typval_T rettv;
1487 typval_T argv[2];
1488 int retval = 0;
1489 int error = FALSE;
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001490
1491 prepare_vimvar(VV_VAL, &save_val);
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001492 if (name != NULL)
1493 {
1494 set_vim_var_string(VV_VAL, name, -1);
1495 argv[0].v_type = VAR_STRING;
1496 argv[0].vval.v_string = name;
1497 }
1498 else
1499 {
1500 set_vim_var_dict(VV_VAL, dict);
1501 argv[0].v_type = VAR_DICT;
1502 argv[0].vval.v_dict = dict;
1503 }
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001504
1505 if (eval_expr_typval(expr, argv, 1, &rettv) == FAIL)
1506 goto theend;
1507
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001508 // We want to use -1, but also true/false should be allowed.
1509 if (rettv.v_type == VAR_SPECIAL || rettv.v_type == VAR_BOOL)
1510 {
1511 rettv.v_type = VAR_NUMBER;
1512 rettv.vval.v_number = rettv.vval.v_number == VVAL_TRUE;
1513 }
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001514 retval = tv_get_number_chk(&rettv, &error);
1515 if (error)
1516 retval = -1;
1517 clear_tv(&rettv);
1518
1519theend:
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001520 if (name != NULL)
1521 set_vim_var_string(VV_VAL, NULL, 0);
1522 else
1523 set_vim_var_dict(VV_VAL, NULL);
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001524 restore_vimvar(VV_VAL, &save_val);
1525 return retval;
1526}
1527
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001528/*
1529 * Evaluate "expr" (= "context") for readdir().
1530 */
1531 static int
1532readdir_checkitem(void *context, void *item)
1533{
1534 char_u *name = (char_u *)item;
1535
1536 return checkitem_common(context, name, NULL);
1537}
1538
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001539 static int
1540readdirex_dict_arg(typval_T *tv, int *cmp)
1541{
1542 char_u *compare;
1543
1544 if (tv->v_type != VAR_DICT)
1545 {
1546 emsg(_(e_dictreq));
1547 return FAIL;
1548 }
1549
1550 if (dict_find(tv->vval.v_dict, (char_u *)"sort", -1) != NULL)
1551 compare = dict_get_string(tv->vval.v_dict, (char_u *)"sort", FALSE);
1552 else
1553 {
1554 semsg(_(e_no_dict_key), "sort");
1555 return FAIL;
1556 }
1557
1558 if (STRCMP(compare, (char_u *) "none") == 0)
1559 *cmp = READDIR_SORT_NONE;
1560 else if (STRCMP(compare, (char_u *) "case") == 0)
1561 *cmp = READDIR_SORT_BYTE;
1562 else if (STRCMP(compare, (char_u *) "icase") == 0)
1563 *cmp = READDIR_SORT_IC;
1564 else if (STRCMP(compare, (char_u *) "collate") == 0)
1565 *cmp = READDIR_SORT_COLLATE;
1566 return OK;
1567}
1568
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001569/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001570 * "readdir()" function
1571 */
1572 void
1573f_readdir(typval_T *argvars, typval_T *rettv)
1574{
1575 typval_T *expr;
1576 int ret;
1577 char_u *path;
1578 char_u *p;
1579 garray_T ga;
1580 int i;
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001581 int sort = READDIR_SORT_BYTE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001582
1583 if (rettv_list_alloc(rettv) == FAIL)
1584 return;
1585 path = tv_get_string(&argvars[0]);
1586 expr = &argvars[1];
1587
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001588 if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN &&
1589 readdirex_dict_arg(&argvars[2], &sort) == FAIL)
1590 return;
1591
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001592 ret = readdir_core(&ga, path, FALSE, (void *)expr,
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001593 (expr->v_type == VAR_UNKNOWN) ? NULL : readdir_checkitem, sort);
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001594 if (ret == OK)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001595 {
1596 for (i = 0; i < ga.ga_len; i++)
1597 {
1598 p = ((char_u **)ga.ga_data)[i];
1599 list_append_string(rettv->vval.v_list, p, -1);
1600 }
1601 }
1602 ga_clear_strings(&ga);
1603}
1604
1605/*
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001606 * Evaluate "expr" (= "context") for readdirex().
1607 */
1608 static int
1609readdirex_checkitem(void *context, void *item)
1610{
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001611 dict_T *dict = (dict_T*)item;
1612
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001613 return checkitem_common(context, NULL, dict);
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001614}
1615
1616/*
1617 * "readdirex()" function
1618 */
1619 void
1620f_readdirex(typval_T *argvars, typval_T *rettv)
1621{
1622 typval_T *expr;
1623 int ret;
1624 char_u *path;
1625 garray_T ga;
1626 int i;
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001627 int sort = READDIR_SORT_BYTE;
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001628
1629 if (rettv_list_alloc(rettv) == FAIL)
1630 return;
1631 path = tv_get_string(&argvars[0]);
1632 expr = &argvars[1];
1633
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001634 if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN &&
1635 readdirex_dict_arg(&argvars[2], &sort) == FAIL)
1636 return;
1637
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001638 ret = readdir_core(&ga, path, TRUE, (void *)expr,
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001639 (expr->v_type == VAR_UNKNOWN) ? NULL : readdirex_checkitem, sort);
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001640 if (ret == OK)
1641 {
1642 for (i = 0; i < ga.ga_len; i++)
1643 {
1644 dict_T *dict = ((dict_T**)ga.ga_data)[i];
1645 list_append_dict(rettv->vval.v_list, dict);
1646 dict_unref(dict);
1647 }
1648 }
1649 ga_clear(&ga);
1650}
1651
1652/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001653 * "readfile()" function
1654 */
Bram Moolenaarc423ad72021-01-13 20:38:03 +01001655 static void
1656read_file_or_blob(typval_T *argvars, typval_T *rettv, int always_blob)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001657{
1658 int binary = FALSE;
Bram Moolenaarc423ad72021-01-13 20:38:03 +01001659 int blob = always_blob;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001660 int failed = FALSE;
1661 char_u *fname;
1662 FILE *fd;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001663 char_u buf[(IOSIZE/256)*256]; // rounded to avoid odd + 1
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001664 int io_size = sizeof(buf);
Bram Moolenaar26262f82019-09-04 20:59:15 +02001665 int readlen; // size of last fread()
1666 char_u *prev = NULL; // previously read bytes, if any
1667 long prevlen = 0; // length of data in prev
1668 long prevsize = 0; // size of prev buffer
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001669 long maxline = MAXLNUM;
1670 long cnt = 0;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001671 char_u *p; // position in buf
1672 char_u *start; // start of current line
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001673
1674 if (argvars[1].v_type != VAR_UNKNOWN)
1675 {
1676 if (STRCMP(tv_get_string(&argvars[1]), "b") == 0)
1677 binary = TRUE;
1678 if (STRCMP(tv_get_string(&argvars[1]), "B") == 0)
1679 blob = TRUE;
1680
1681 if (argvars[2].v_type != VAR_UNKNOWN)
1682 maxline = (long)tv_get_number(&argvars[2]);
1683 }
1684
Bram Moolenaar15352dc2020-04-06 21:12:42 +02001685 if ((blob ? rettv_blob_alloc(rettv) : rettv_list_alloc(rettv)) == FAIL)
1686 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001687
Bram Moolenaar26262f82019-09-04 20:59:15 +02001688 // Always open the file in binary mode, library functions have a mind of
1689 // their own about CR-LF conversion.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001690 fname = tv_get_string(&argvars[0]);
Bram Moolenaar15352dc2020-04-06 21:12:42 +02001691
1692 if (mch_isdir(fname))
1693 {
Bram Moolenaar108010a2021-06-27 22:03:33 +02001694 semsg(_(e_src_is_directory), fname);
Bram Moolenaar15352dc2020-04-06 21:12:42 +02001695 return;
1696 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001697 if (*fname == NUL || (fd = mch_fopen((char *)fname, READBIN)) == NULL)
1698 {
1699 semsg(_(e_notopen), *fname == NUL ? (char_u *)_("<empty>") : fname);
1700 return;
1701 }
1702
1703 if (blob)
1704 {
1705 if (read_blob(fd, rettv->vval.v_blob) == FAIL)
1706 {
Bram Moolenaar15352dc2020-04-06 21:12:42 +02001707 semsg(_(e_notread), fname);
1708 // An empty blob is returned on error.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001709 blob_free(rettv->vval.v_blob);
Bram Moolenaar15352dc2020-04-06 21:12:42 +02001710 rettv->vval.v_blob = NULL;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001711 }
1712 fclose(fd);
1713 return;
1714 }
1715
1716 while (cnt < maxline || maxline < 0)
1717 {
1718 readlen = (int)fread(buf, 1, io_size, fd);
1719
Bram Moolenaar26262f82019-09-04 20:59:15 +02001720 // This for loop processes what was read, but is also entered at end
1721 // of file so that either:
1722 // - an incomplete line gets written
1723 // - a "binary" file gets an empty line at the end if it ends in a
1724 // newline.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001725 for (p = buf, start = buf;
1726 p < buf + readlen || (readlen <= 0 && (prevlen > 0 || binary));
1727 ++p)
1728 {
1729 if (*p == '\n' || readlen <= 0)
1730 {
1731 listitem_T *li;
1732 char_u *s = NULL;
1733 long_u len = p - start;
1734
Bram Moolenaar26262f82019-09-04 20:59:15 +02001735 // Finished a line. Remove CRs before NL.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001736 if (readlen > 0 && !binary)
1737 {
1738 while (len > 0 && start[len - 1] == '\r')
1739 --len;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001740 // removal may cross back to the "prev" string
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001741 if (len == 0)
1742 while (prevlen > 0 && prev[prevlen - 1] == '\r')
1743 --prevlen;
1744 }
1745 if (prevlen == 0)
Bram Moolenaar71ccd032020-06-12 22:59:11 +02001746 s = vim_strnsave(start, len);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001747 else
1748 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001749 // Change "prev" buffer to be the right size. This way
1750 // the bytes are only copied once, and very long lines are
1751 // allocated only once.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001752 if ((s = vim_realloc(prev, prevlen + len + 1)) != NULL)
1753 {
1754 mch_memmove(s + prevlen, start, len);
1755 s[prevlen + len] = NUL;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001756 prev = NULL; // the list will own the string
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001757 prevlen = prevsize = 0;
1758 }
1759 }
1760 if (s == NULL)
1761 {
1762 do_outofmem_msg((long_u) prevlen + len + 1);
1763 failed = TRUE;
1764 break;
1765 }
1766
1767 if ((li = listitem_alloc()) == NULL)
1768 {
1769 vim_free(s);
1770 failed = TRUE;
1771 break;
1772 }
1773 li->li_tv.v_type = VAR_STRING;
1774 li->li_tv.v_lock = 0;
1775 li->li_tv.vval.v_string = s;
1776 list_append(rettv->vval.v_list, li);
1777
Bram Moolenaar26262f82019-09-04 20:59:15 +02001778 start = p + 1; // step over newline
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001779 if ((++cnt >= maxline && maxline >= 0) || readlen <= 0)
1780 break;
1781 }
1782 else if (*p == NUL)
1783 *p = '\n';
Bram Moolenaar26262f82019-09-04 20:59:15 +02001784 // Check for utf8 "bom"; U+FEFF is encoded as EF BB BF. Do this
1785 // when finding the BF and check the previous two bytes.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001786 else if (*p == 0xbf && enc_utf8 && !binary)
1787 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001788 // Find the two bytes before the 0xbf. If p is at buf, or buf
1789 // + 1, these may be in the "prev" string.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001790 char_u back1 = p >= buf + 1 ? p[-1]
1791 : prevlen >= 1 ? prev[prevlen - 1] : NUL;
1792 char_u back2 = p >= buf + 2 ? p[-2]
1793 : p == buf + 1 && prevlen >= 1 ? prev[prevlen - 1]
1794 : prevlen >= 2 ? prev[prevlen - 2] : NUL;
1795
1796 if (back2 == 0xef && back1 == 0xbb)
1797 {
1798 char_u *dest = p - 2;
1799
Bram Moolenaar26262f82019-09-04 20:59:15 +02001800 // Usually a BOM is at the beginning of a file, and so at
1801 // the beginning of a line; then we can just step over it.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001802 if (start == dest)
1803 start = p + 1;
1804 else
1805 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001806 // have to shuffle buf to close gap
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001807 int adjust_prevlen = 0;
1808
1809 if (dest < buf)
1810 {
Bram Moolenaarc423ad72021-01-13 20:38:03 +01001811 // must be 1 or 2
1812 adjust_prevlen = (int)(buf - dest);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001813 dest = buf;
1814 }
1815 if (readlen > p - buf + 1)
1816 mch_memmove(dest, p + 1, readlen - (p - buf) - 1);
1817 readlen -= 3 - adjust_prevlen;
1818 prevlen -= adjust_prevlen;
1819 p = dest - 1;
1820 }
1821 }
1822 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02001823 } // for
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001824
1825 if (failed || (cnt >= maxline && maxline >= 0) || readlen <= 0)
1826 break;
1827 if (start < p)
1828 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001829 // There's part of a line in buf, store it in "prev".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001830 if (p - start + prevlen >= prevsize)
1831 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001832 // need bigger "prev" buffer
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001833 char_u *newprev;
1834
Bram Moolenaar26262f82019-09-04 20:59:15 +02001835 // A common use case is ordinary text files and "prev" gets a
1836 // fragment of a line, so the first allocation is made
1837 // small, to avoid repeatedly 'allocing' large and
1838 // 'reallocing' small.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001839 if (prevsize == 0)
1840 prevsize = (long)(p - start);
1841 else
1842 {
1843 long grow50pc = (prevsize * 3) / 2;
1844 long growmin = (long)((p - start) * 2 + prevlen);
1845 prevsize = grow50pc > growmin ? grow50pc : growmin;
1846 }
1847 newprev = vim_realloc(prev, prevsize);
1848 if (newprev == NULL)
1849 {
1850 do_outofmem_msg((long_u)prevsize);
1851 failed = TRUE;
1852 break;
1853 }
1854 prev = newprev;
1855 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02001856 // Add the line part to end of "prev".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001857 mch_memmove(prev + prevlen, start, p - start);
1858 prevlen += (long)(p - start);
1859 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02001860 } // while
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001861
Bram Moolenaar26262f82019-09-04 20:59:15 +02001862 // For a negative line count use only the lines at the end of the file,
1863 // free the rest.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001864 if (!failed && maxline < 0)
1865 while (cnt > -maxline)
1866 {
1867 listitem_remove(rettv->vval.v_list, rettv->vval.v_list->lv_first);
1868 --cnt;
1869 }
1870
1871 if (failed)
1872 {
1873 // an empty list is returned on error
1874 list_free(rettv->vval.v_list);
1875 rettv_list_alloc(rettv);
1876 }
1877
1878 vim_free(prev);
1879 fclose(fd);
1880}
1881
1882/*
Bram Moolenaarc423ad72021-01-13 20:38:03 +01001883 * "readblob()" function
1884 */
1885 void
1886f_readblob(typval_T *argvars, typval_T *rettv)
1887{
1888 read_file_or_blob(argvars, rettv, TRUE);
1889}
1890
1891/*
1892 * "readfile()" function
1893 */
1894 void
1895f_readfile(typval_T *argvars, typval_T *rettv)
1896{
1897 read_file_or_blob(argvars, rettv, FALSE);
1898}
1899
1900/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001901 * "resolve()" function
1902 */
1903 void
1904f_resolve(typval_T *argvars, typval_T *rettv)
1905{
1906 char_u *p;
1907#ifdef HAVE_READLINK
1908 char_u *buf = NULL;
1909#endif
1910
1911 p = tv_get_string(&argvars[0]);
1912#ifdef FEAT_SHORTCUT
1913 {
1914 char_u *v = NULL;
1915
1916 v = mch_resolve_path(p, TRUE);
1917 if (v != NULL)
1918 rettv->vval.v_string = v;
1919 else
1920 rettv->vval.v_string = vim_strsave(p);
1921 }
1922#else
1923# ifdef HAVE_READLINK
1924 {
1925 char_u *cpy;
1926 int len;
1927 char_u *remain = NULL;
1928 char_u *q;
1929 int is_relative_to_current = FALSE;
1930 int has_trailing_pathsep = FALSE;
1931 int limit = 100;
1932
1933 p = vim_strsave(p);
Bram Moolenaar70188f52019-12-23 18:18:52 +01001934 if (p == NULL)
1935 goto fail;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001936 if (p[0] == '.' && (vim_ispathsep(p[1])
1937 || (p[1] == '.' && (vim_ispathsep(p[2])))))
1938 is_relative_to_current = TRUE;
1939
1940 len = STRLEN(p);
Bram Moolenaar50c4e9e2020-10-05 20:38:06 +02001941 if (len > 1 && after_pathsep(p, p + len))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001942 {
1943 has_trailing_pathsep = TRUE;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001944 p[len - 1] = NUL; // the trailing slash breaks readlink()
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001945 }
1946
1947 q = getnextcomp(p);
1948 if (*q != NUL)
1949 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001950 // Separate the first path component in "p", and keep the
1951 // remainder (beginning with the path separator).
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001952 remain = vim_strsave(q - 1);
1953 q[-1] = NUL;
1954 }
1955
1956 buf = alloc(MAXPATHL + 1);
1957 if (buf == NULL)
Bram Moolenaar70188f52019-12-23 18:18:52 +01001958 {
1959 vim_free(p);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001960 goto fail;
Bram Moolenaar70188f52019-12-23 18:18:52 +01001961 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001962
1963 for (;;)
1964 {
1965 for (;;)
1966 {
1967 len = readlink((char *)p, (char *)buf, MAXPATHL);
1968 if (len <= 0)
1969 break;
1970 buf[len] = NUL;
1971
1972 if (limit-- == 0)
1973 {
1974 vim_free(p);
1975 vim_free(remain);
1976 emsg(_("E655: Too many symbolic links (cycle?)"));
1977 rettv->vval.v_string = NULL;
1978 goto fail;
1979 }
1980
Bram Moolenaar26262f82019-09-04 20:59:15 +02001981 // Ensure that the result will have a trailing path separator
1982 // if the argument has one.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001983 if (remain == NULL && has_trailing_pathsep)
1984 add_pathsep(buf);
1985
Bram Moolenaar26262f82019-09-04 20:59:15 +02001986 // Separate the first path component in the link value and
1987 // concatenate the remainders.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001988 q = getnextcomp(vim_ispathsep(*buf) ? buf + 1 : buf);
1989 if (*q != NUL)
1990 {
1991 if (remain == NULL)
1992 remain = vim_strsave(q - 1);
1993 else
1994 {
1995 cpy = concat_str(q - 1, remain);
1996 if (cpy != NULL)
1997 {
1998 vim_free(remain);
1999 remain = cpy;
2000 }
2001 }
2002 q[-1] = NUL;
2003 }
2004
2005 q = gettail(p);
2006 if (q > p && *q == NUL)
2007 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002008 // Ignore trailing path separator.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002009 q[-1] = NUL;
2010 q = gettail(p);
2011 }
2012 if (q > p && !mch_isFullName(buf))
2013 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002014 // symlink is relative to directory of argument
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002015 cpy = alloc(STRLEN(p) + STRLEN(buf) + 1);
2016 if (cpy != NULL)
2017 {
2018 STRCPY(cpy, p);
2019 STRCPY(gettail(cpy), buf);
2020 vim_free(p);
2021 p = cpy;
2022 }
2023 }
2024 else
2025 {
2026 vim_free(p);
2027 p = vim_strsave(buf);
2028 }
2029 }
2030
2031 if (remain == NULL)
2032 break;
2033
Bram Moolenaar26262f82019-09-04 20:59:15 +02002034 // Append the first path component of "remain" to "p".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002035 q = getnextcomp(remain + 1);
2036 len = q - remain - (*q != NUL);
2037 cpy = vim_strnsave(p, STRLEN(p) + len);
2038 if (cpy != NULL)
2039 {
2040 STRNCAT(cpy, remain, len);
2041 vim_free(p);
2042 p = cpy;
2043 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02002044 // Shorten "remain".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002045 if (*q != NUL)
2046 STRMOVE(remain, q - 1);
2047 else
2048 VIM_CLEAR(remain);
2049 }
2050
Bram Moolenaar26262f82019-09-04 20:59:15 +02002051 // If the result is a relative path name, make it explicitly relative to
2052 // the current directory if and only if the argument had this form.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002053 if (!vim_ispathsep(*p))
2054 {
2055 if (is_relative_to_current
2056 && *p != NUL
2057 && !(p[0] == '.'
2058 && (p[1] == NUL
2059 || vim_ispathsep(p[1])
2060 || (p[1] == '.'
2061 && (p[2] == NUL
2062 || vim_ispathsep(p[2]))))))
2063 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002064 // Prepend "./".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002065 cpy = concat_str((char_u *)"./", p);
2066 if (cpy != NULL)
2067 {
2068 vim_free(p);
2069 p = cpy;
2070 }
2071 }
2072 else if (!is_relative_to_current)
2073 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002074 // Strip leading "./".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002075 q = p;
2076 while (q[0] == '.' && vim_ispathsep(q[1]))
2077 q += 2;
2078 if (q > p)
2079 STRMOVE(p, p + 2);
2080 }
2081 }
2082
Bram Moolenaar26262f82019-09-04 20:59:15 +02002083 // Ensure that the result will have no trailing path separator
2084 // if the argument had none. But keep "/" or "//".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002085 if (!has_trailing_pathsep)
2086 {
2087 q = p + STRLEN(p);
2088 if (after_pathsep(p, q))
2089 *gettail_sep(p) = NUL;
2090 }
2091
2092 rettv->vval.v_string = p;
2093 }
2094# else
2095 rettv->vval.v_string = vim_strsave(p);
2096# endif
2097#endif
2098
2099 simplify_filename(rettv->vval.v_string);
2100
2101#ifdef HAVE_READLINK
2102fail:
2103 vim_free(buf);
2104#endif
2105 rettv->v_type = VAR_STRING;
2106}
2107
2108/*
2109 * "tempname()" function
2110 */
2111 void
2112f_tempname(typval_T *argvars UNUSED, typval_T *rettv)
2113{
2114 static int x = 'A';
2115
2116 rettv->v_type = VAR_STRING;
2117 rettv->vval.v_string = vim_tempname(x, FALSE);
2118
Bram Moolenaar26262f82019-09-04 20:59:15 +02002119 // Advance 'x' to use A-Z and 0-9, so that there are at least 34 different
2120 // names. Skip 'I' and 'O', they are used for shell redirection.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002121 do
2122 {
2123 if (x == 'Z')
2124 x = '0';
2125 else if (x == '9')
2126 x = 'A';
2127 else
2128 {
2129#ifdef EBCDIC
2130 if (x == 'I')
2131 x = 'J';
2132 else if (x == 'R')
2133 x = 'S';
2134 else
2135#endif
2136 ++x;
2137 }
2138 } while (x == 'I' || x == 'O');
2139}
2140
2141/*
2142 * "writefile()" function
2143 */
2144 void
2145f_writefile(typval_T *argvars, typval_T *rettv)
2146{
2147 int binary = FALSE;
2148 int append = FALSE;
2149#ifdef HAVE_FSYNC
2150 int do_fsync = p_fs;
2151#endif
2152 char_u *fname;
2153 FILE *fd;
2154 int ret = 0;
2155 listitem_T *li;
2156 list_T *list = NULL;
2157 blob_T *blob = NULL;
2158
2159 rettv->vval.v_number = -1;
2160 if (check_secure())
2161 return;
2162
2163 if (argvars[0].v_type == VAR_LIST)
2164 {
2165 list = argvars[0].vval.v_list;
2166 if (list == NULL)
2167 return;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02002168 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002169 FOR_ALL_LIST_ITEMS(list, li)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002170 if (tv_get_string_chk(&li->li_tv) == NULL)
2171 return;
2172 }
2173 else if (argvars[0].v_type == VAR_BLOB)
2174 {
2175 blob = argvars[0].vval.v_blob;
2176 if (blob == NULL)
2177 return;
2178 }
2179 else
2180 {
Bram Moolenaar18a2b872020-03-19 13:08:45 +01002181 semsg(_(e_invarg2),
2182 _("writefile() first argument must be a List or a Blob"));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002183 return;
2184 }
2185
2186 if (argvars[2].v_type != VAR_UNKNOWN)
2187 {
2188 char_u *arg2 = tv_get_string_chk(&argvars[2]);
2189
2190 if (arg2 == NULL)
2191 return;
2192 if (vim_strchr(arg2, 'b') != NULL)
2193 binary = TRUE;
2194 if (vim_strchr(arg2, 'a') != NULL)
2195 append = TRUE;
2196#ifdef HAVE_FSYNC
2197 if (vim_strchr(arg2, 's') != NULL)
2198 do_fsync = TRUE;
2199 else if (vim_strchr(arg2, 'S') != NULL)
2200 do_fsync = FALSE;
2201#endif
2202 }
2203
2204 fname = tv_get_string_chk(&argvars[1]);
2205 if (fname == NULL)
2206 return;
2207
Bram Moolenaar26262f82019-09-04 20:59:15 +02002208 // Always open the file in binary mode, library functions have a mind of
2209 // their own about CR-LF conversion.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002210 if (*fname == NUL || (fd = mch_fopen((char *)fname,
2211 append ? APPENDBIN : WRITEBIN)) == NULL)
2212 {
2213 semsg(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
2214 ret = -1;
2215 }
2216 else if (blob)
2217 {
2218 if (write_blob(fd, blob) == FAIL)
2219 ret = -1;
2220#ifdef HAVE_FSYNC
2221 else if (do_fsync)
2222 // Ignore the error, the user wouldn't know what to do about it.
2223 // May happen for a device.
2224 vim_ignored = vim_fsync(fileno(fd));
2225#endif
2226 fclose(fd);
2227 }
2228 else
2229 {
2230 if (write_list(fd, list, binary) == FAIL)
2231 ret = -1;
2232#ifdef HAVE_FSYNC
2233 else if (do_fsync)
Bram Moolenaar26262f82019-09-04 20:59:15 +02002234 // Ignore the error, the user wouldn't know what to do about it.
2235 // May happen for a device.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002236 vim_ignored = vim_fsync(fileno(fd));
2237#endif
2238 fclose(fd);
2239 }
2240
2241 rettv->vval.v_number = ret;
2242}
2243
2244#endif // FEAT_EVAL
2245
2246#if defined(FEAT_BROWSE) || defined(PROTO)
2247/*
2248 * Generic browse function. Calls gui_mch_browse() when possible.
2249 * Later this may pop-up a non-GUI file selector (external command?).
2250 */
2251 char_u *
2252do_browse(
Bram Moolenaar26262f82019-09-04 20:59:15 +02002253 int flags, // BROWSE_SAVE and BROWSE_DIR
2254 char_u *title, // title for the window
2255 char_u *dflt, // default file name (may include directory)
2256 char_u *ext, // extension added
2257 char_u *initdir, // initial directory, NULL for current dir or
2258 // when using path from "dflt"
2259 char_u *filter, // file name filter
2260 buf_T *buf) // buffer to read/write for
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002261{
2262 char_u *fname;
Bram Moolenaar26262f82019-09-04 20:59:15 +02002263 static char_u *last_dir = NULL; // last used directory
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002264 char_u *tofree = NULL;
Bram Moolenaare1004402020-10-24 20:49:43 +02002265 int save_cmod_flags = cmdmod.cmod_flags;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002266
Bram Moolenaar26262f82019-09-04 20:59:15 +02002267 // Must turn off browse to avoid that autocommands will get the
2268 // flag too!
Bram Moolenaare1004402020-10-24 20:49:43 +02002269 cmdmod.cmod_flags &= ~CMOD_BROWSE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002270
2271 if (title == NULL || *title == NUL)
2272 {
2273 if (flags & BROWSE_DIR)
2274 title = (char_u *)_("Select Directory dialog");
2275 else if (flags & BROWSE_SAVE)
2276 title = (char_u *)_("Save File dialog");
2277 else
2278 title = (char_u *)_("Open File dialog");
2279 }
2280
Bram Moolenaar26262f82019-09-04 20:59:15 +02002281 // When no directory specified, use default file name, default dir, buffer
2282 // dir, last dir or current dir
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002283 if ((initdir == NULL || *initdir == NUL) && dflt != NULL && *dflt != NUL)
2284 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002285 if (mch_isdir(dflt)) // default file name is a directory
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002286 {
2287 initdir = dflt;
2288 dflt = NULL;
2289 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02002290 else if (gettail(dflt) != dflt) // default file name includes a path
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002291 {
2292 tofree = vim_strsave(dflt);
2293 if (tofree != NULL)
2294 {
2295 initdir = tofree;
2296 *gettail(initdir) = NUL;
2297 dflt = gettail(dflt);
2298 }
2299 }
2300 }
2301
2302 if (initdir == NULL || *initdir == NUL)
2303 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002304 // When 'browsedir' is a directory, use it
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002305 if (STRCMP(p_bsdir, "last") != 0
2306 && STRCMP(p_bsdir, "buffer") != 0
2307 && STRCMP(p_bsdir, "current") != 0
2308 && mch_isdir(p_bsdir))
2309 initdir = p_bsdir;
Bram Moolenaar26262f82019-09-04 20:59:15 +02002310 // When saving or 'browsedir' is "buffer", use buffer fname
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002311 else if (((flags & BROWSE_SAVE) || *p_bsdir == 'b')
2312 && buf != NULL && buf->b_ffname != NULL)
2313 {
2314 if (dflt == NULL || *dflt == NUL)
2315 dflt = gettail(curbuf->b_ffname);
2316 tofree = vim_strsave(curbuf->b_ffname);
2317 if (tofree != NULL)
2318 {
2319 initdir = tofree;
2320 *gettail(initdir) = NUL;
2321 }
2322 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02002323 // When 'browsedir' is "last", use dir from last browse
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002324 else if (*p_bsdir == 'l')
2325 initdir = last_dir;
Bram Moolenaar26262f82019-09-04 20:59:15 +02002326 // When 'browsedir is "current", use current directory. This is the
2327 // default already, leave initdir empty.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002328 }
2329
2330# ifdef FEAT_GUI
Bram Moolenaar26262f82019-09-04 20:59:15 +02002331 if (gui.in_use) // when this changes, also adjust f_has()!
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002332 {
2333 if (filter == NULL
2334# ifdef FEAT_EVAL
2335 && (filter = get_var_value((char_u *)"b:browsefilter")) == NULL
2336 && (filter = get_var_value((char_u *)"g:browsefilter")) == NULL
2337# endif
2338 )
2339 filter = BROWSE_FILTER_DEFAULT;
2340 if (flags & BROWSE_DIR)
2341 {
2342# if defined(FEAT_GUI_GTK) || defined(MSWIN)
Bram Moolenaar26262f82019-09-04 20:59:15 +02002343 // For systems that have a directory dialog.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002344 fname = gui_mch_browsedir(title, initdir);
2345# else
Bram Moolenaar26262f82019-09-04 20:59:15 +02002346 // Generic solution for selecting a directory: select a file and
2347 // remove the file name.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002348 fname = gui_mch_browse(0, title, dflt, ext, initdir, (char_u *)"");
2349# endif
2350# if !defined(FEAT_GUI_GTK)
Bram Moolenaar26262f82019-09-04 20:59:15 +02002351 // Win32 adds a dummy file name, others return an arbitrary file
2352 // name. GTK+ 2 returns only the directory,
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002353 if (fname != NULL && *fname != NUL && !mch_isdir(fname))
2354 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002355 // Remove the file name.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002356 char_u *tail = gettail_sep(fname);
2357
2358 if (tail == fname)
Bram Moolenaar26262f82019-09-04 20:59:15 +02002359 *tail++ = '.'; // use current dir
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002360 *tail = NUL;
2361 }
2362# endif
2363 }
2364 else
2365 fname = gui_mch_browse(flags & BROWSE_SAVE,
2366 title, dflt, ext, initdir, (char_u *)_(filter));
2367
Bram Moolenaar26262f82019-09-04 20:59:15 +02002368 // We hang around in the dialog for a while, the user might do some
2369 // things to our files. The Win32 dialog allows deleting or renaming
2370 // a file, check timestamps.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002371 need_check_timestamps = TRUE;
2372 did_check_timestamps = FALSE;
2373 }
2374 else
2375# endif
2376 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002377 // TODO: non-GUI file selector here
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002378 emsg(_("E338: Sorry, no file browser in console mode"));
2379 fname = NULL;
2380 }
2381
Bram Moolenaar26262f82019-09-04 20:59:15 +02002382 // keep the directory for next time
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002383 if (fname != NULL)
2384 {
2385 vim_free(last_dir);
2386 last_dir = vim_strsave(fname);
2387 if (last_dir != NULL && !(flags & BROWSE_DIR))
2388 {
2389 *gettail(last_dir) = NUL;
2390 if (*last_dir == NUL)
2391 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002392 // filename only returned, must be in current dir
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002393 vim_free(last_dir);
2394 last_dir = alloc(MAXPATHL);
2395 if (last_dir != NULL)
2396 mch_dirname(last_dir, MAXPATHL);
2397 }
2398 }
2399 }
2400
2401 vim_free(tofree);
Bram Moolenaare1004402020-10-24 20:49:43 +02002402 cmdmod.cmod_flags = save_cmod_flags;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002403
2404 return fname;
2405}
2406#endif
2407
2408#if defined(FEAT_EVAL) || defined(PROTO)
2409
2410/*
2411 * "browse(save, title, initdir, default)" function
2412 */
2413 void
2414f_browse(typval_T *argvars UNUSED, typval_T *rettv)
2415{
2416# ifdef FEAT_BROWSE
2417 int save;
2418 char_u *title;
2419 char_u *initdir;
2420 char_u *defname;
2421 char_u buf[NUMBUFLEN];
2422 char_u buf2[NUMBUFLEN];
2423 int error = FALSE;
2424
Bram Moolenaarf28f2ac2021-03-22 22:21:26 +01002425 if (in_vim9script()
Bram Moolenaar32105ae2021-03-27 18:59:25 +01002426 && (check_for_string_arg(argvars, 1) == FAIL
2427 || check_for_string_arg(argvars, 2) == FAIL
2428 || check_for_string_arg(argvars, 3) == FAIL))
Bram Moolenaarf28f2ac2021-03-22 22:21:26 +01002429 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002430 save = (int)tv_get_number_chk(&argvars[0], &error);
2431 title = tv_get_string_chk(&argvars[1]);
2432 initdir = tv_get_string_buf_chk(&argvars[2], buf);
2433 defname = tv_get_string_buf_chk(&argvars[3], buf2);
2434
2435 if (error || title == NULL || initdir == NULL || defname == NULL)
2436 rettv->vval.v_string = NULL;
2437 else
2438 rettv->vval.v_string =
2439 do_browse(save ? BROWSE_SAVE : 0,
2440 title, defname, NULL, initdir, NULL, curbuf);
2441# else
2442 rettv->vval.v_string = NULL;
2443# endif
2444 rettv->v_type = VAR_STRING;
2445}
2446
2447/*
2448 * "browsedir(title, initdir)" function
2449 */
2450 void
2451f_browsedir(typval_T *argvars UNUSED, typval_T *rettv)
2452{
2453# ifdef FEAT_BROWSE
2454 char_u *title;
2455 char_u *initdir;
2456 char_u buf[NUMBUFLEN];
2457
2458 title = tv_get_string_chk(&argvars[0]);
2459 initdir = tv_get_string_buf_chk(&argvars[1], buf);
2460
2461 if (title == NULL || initdir == NULL)
2462 rettv->vval.v_string = NULL;
2463 else
2464 rettv->vval.v_string = do_browse(BROWSE_DIR,
2465 title, NULL, NULL, initdir, NULL, curbuf);
2466# else
2467 rettv->vval.v_string = NULL;
2468# endif
2469 rettv->v_type = VAR_STRING;
2470}
2471
2472#endif // FEAT_EVAL
Bram Moolenaar26262f82019-09-04 20:59:15 +02002473
2474/*
2475 * Replace home directory by "~" in each space or comma separated file name in
2476 * 'src'.
2477 * If anything fails (except when out of space) dst equals src.
2478 */
2479 void
2480home_replace(
2481 buf_T *buf, // when not NULL, check for help files
2482 char_u *src, // input file name
2483 char_u *dst, // where to put the result
2484 int dstlen, // maximum length of the result
2485 int one) // if TRUE, only replace one file name, include
2486 // spaces and commas in the file name.
2487{
2488 size_t dirlen = 0, envlen = 0;
2489 size_t len;
2490 char_u *homedir_env, *homedir_env_orig;
2491 char_u *p;
2492
2493 if (src == NULL)
2494 {
2495 *dst = NUL;
2496 return;
2497 }
2498
2499 /*
2500 * If the file is a help file, remove the path completely.
2501 */
2502 if (buf != NULL && buf->b_help)
2503 {
2504 vim_snprintf((char *)dst, dstlen, "%s", gettail(src));
2505 return;
2506 }
2507
2508 /*
2509 * We check both the value of the $HOME environment variable and the
2510 * "real" home directory.
2511 */
2512 if (homedir != NULL)
2513 dirlen = STRLEN(homedir);
2514
2515#ifdef VMS
2516 homedir_env_orig = homedir_env = mch_getenv((char_u *)"SYS$LOGIN");
2517#else
2518 homedir_env_orig = homedir_env = mch_getenv((char_u *)"HOME");
2519#endif
2520#ifdef MSWIN
2521 if (homedir_env == NULL)
2522 homedir_env_orig = homedir_env = mch_getenv((char_u *)"USERPROFILE");
2523#endif
2524 // Empty is the same as not set.
2525 if (homedir_env != NULL && *homedir_env == NUL)
2526 homedir_env = NULL;
2527
2528 if (homedir_env != NULL && *homedir_env == '~')
2529 {
2530 int usedlen = 0;
2531 int flen;
2532 char_u *fbuf = NULL;
2533
2534 flen = (int)STRLEN(homedir_env);
2535 (void)modify_fname((char_u *)":p", FALSE, &usedlen,
2536 &homedir_env, &fbuf, &flen);
2537 flen = (int)STRLEN(homedir_env);
2538 if (flen > 0 && vim_ispathsep(homedir_env[flen - 1]))
2539 // Remove the trailing / that is added to a directory.
2540 homedir_env[flen - 1] = NUL;
2541 }
2542
2543 if (homedir_env != NULL)
2544 envlen = STRLEN(homedir_env);
2545
2546 if (!one)
2547 src = skipwhite(src);
2548 while (*src && dstlen > 0)
2549 {
2550 /*
2551 * Here we are at the beginning of a file name.
2552 * First, check to see if the beginning of the file name matches
2553 * $HOME or the "real" home directory. Check that there is a '/'
2554 * after the match (so that if e.g. the file is "/home/pieter/bla",
2555 * and the home directory is "/home/piet", the file does not end up
2556 * as "~er/bla" (which would seem to indicate the file "bla" in user
2557 * er's home directory)).
2558 */
2559 p = homedir;
2560 len = dirlen;
2561 for (;;)
2562 {
2563 if ( len
2564 && fnamencmp(src, p, len) == 0
2565 && (vim_ispathsep(src[len])
2566 || (!one && (src[len] == ',' || src[len] == ' '))
2567 || src[len] == NUL))
2568 {
2569 src += len;
2570 if (--dstlen > 0)
2571 *dst++ = '~';
2572
Bram Moolenaar0e390f42020-06-10 13:12:28 +02002573 // Do not add directory separator into dst, because dst is
2574 // expected to just return the directory name without the
2575 // directory separator '/'.
Bram Moolenaar26262f82019-09-04 20:59:15 +02002576 break;
2577 }
2578 if (p == homedir_env)
2579 break;
2580 p = homedir_env;
2581 len = envlen;
2582 }
2583
2584 // if (!one) skip to separator: space or comma
2585 while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0)
2586 *dst++ = *src++;
2587 // skip separator
2588 while ((*src == ' ' || *src == ',') && --dstlen > 0)
2589 *dst++ = *src++;
2590 }
2591 // if (dstlen == 0) out of space, what to do???
2592
2593 *dst = NUL;
2594
2595 if (homedir_env != homedir_env_orig)
2596 vim_free(homedir_env);
2597}
2598
2599/*
2600 * Like home_replace, store the replaced string in allocated memory.
2601 * When something fails, NULL is returned.
2602 */
2603 char_u *
2604home_replace_save(
2605 buf_T *buf, // when not NULL, check for help files
2606 char_u *src) // input file name
2607{
2608 char_u *dst;
2609 unsigned len;
2610
2611 len = 3; // space for "~/" and trailing NUL
2612 if (src != NULL) // just in case
2613 len += (unsigned)STRLEN(src);
2614 dst = alloc(len);
2615 if (dst != NULL)
2616 home_replace(buf, src, dst, len, TRUE);
2617 return dst;
2618}
2619
2620/*
2621 * Compare two file names and return:
2622 * FPC_SAME if they both exist and are the same file.
2623 * FPC_SAMEX if they both don't exist and have the same file name.
2624 * FPC_DIFF if they both exist and are different files.
2625 * FPC_NOTX if they both don't exist.
2626 * FPC_DIFFX if one of them doesn't exist.
2627 * For the first name environment variables are expanded if "expandenv" is
2628 * TRUE.
2629 */
2630 int
2631fullpathcmp(
2632 char_u *s1,
2633 char_u *s2,
2634 int checkname, // when both don't exist, check file names
2635 int expandenv)
2636{
2637#ifdef UNIX
2638 char_u exp1[MAXPATHL];
2639 char_u full1[MAXPATHL];
2640 char_u full2[MAXPATHL];
2641 stat_T st1, st2;
2642 int r1, r2;
2643
2644 if (expandenv)
2645 expand_env(s1, exp1, MAXPATHL);
2646 else
2647 vim_strncpy(exp1, s1, MAXPATHL - 1);
2648 r1 = mch_stat((char *)exp1, &st1);
2649 r2 = mch_stat((char *)s2, &st2);
2650 if (r1 != 0 && r2 != 0)
2651 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002652 // if mch_stat() doesn't work, may compare the names
Bram Moolenaar26262f82019-09-04 20:59:15 +02002653 if (checkname)
2654 {
2655 if (fnamecmp(exp1, s2) == 0)
2656 return FPC_SAMEX;
2657 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
2658 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
2659 if (r1 == OK && r2 == OK && fnamecmp(full1, full2) == 0)
2660 return FPC_SAMEX;
2661 }
2662 return FPC_NOTX;
2663 }
2664 if (r1 != 0 || r2 != 0)
2665 return FPC_DIFFX;
2666 if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
2667 return FPC_SAME;
2668 return FPC_DIFF;
2669#else
2670 char_u *exp1; // expanded s1
2671 char_u *full1; // full path of s1
2672 char_u *full2; // full path of s2
2673 int retval = FPC_DIFF;
2674 int r1, r2;
2675
2676 // allocate one buffer to store three paths (alloc()/free() is slow!)
2677 if ((exp1 = alloc(MAXPATHL * 3)) != NULL)
2678 {
2679 full1 = exp1 + MAXPATHL;
2680 full2 = full1 + MAXPATHL;
2681
2682 if (expandenv)
2683 expand_env(s1, exp1, MAXPATHL);
2684 else
2685 vim_strncpy(exp1, s1, MAXPATHL - 1);
2686 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
2687 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
2688
2689 // If vim_FullName() fails, the file probably doesn't exist.
2690 if (r1 != OK && r2 != OK)
2691 {
2692 if (checkname && fnamecmp(exp1, s2) == 0)
2693 retval = FPC_SAMEX;
2694 else
2695 retval = FPC_NOTX;
2696 }
2697 else if (r1 != OK || r2 != OK)
2698 retval = FPC_DIFFX;
2699 else if (fnamecmp(full1, full2))
2700 retval = FPC_DIFF;
2701 else
2702 retval = FPC_SAME;
2703 vim_free(exp1);
2704 }
2705 return retval;
2706#endif
2707}
2708
2709/*
2710 * Get the tail of a path: the file name.
2711 * When the path ends in a path separator the tail is the NUL after it.
2712 * Fail safe: never returns NULL.
2713 */
2714 char_u *
2715gettail(char_u *fname)
2716{
2717 char_u *p1, *p2;
2718
2719 if (fname == NULL)
2720 return (char_u *)"";
2721 for (p1 = p2 = get_past_head(fname); *p2; ) // find last part of path
2722 {
2723 if (vim_ispathsep_nocolon(*p2))
2724 p1 = p2 + 1;
2725 MB_PTR_ADV(p2);
2726 }
2727 return p1;
2728}
2729
2730/*
2731 * Get pointer to tail of "fname", including path separators. Putting a NUL
2732 * here leaves the directory name. Takes care of "c:/" and "//".
2733 * Always returns a valid pointer.
2734 */
2735 char_u *
2736gettail_sep(char_u *fname)
2737{
2738 char_u *p;
2739 char_u *t;
2740
2741 p = get_past_head(fname); // don't remove the '/' from "c:/file"
2742 t = gettail(fname);
2743 while (t > p && after_pathsep(fname, t))
2744 --t;
2745#ifdef VMS
2746 // path separator is part of the path
2747 ++t;
2748#endif
2749 return t;
2750}
2751
2752/*
2753 * get the next path component (just after the next path separator).
2754 */
2755 char_u *
2756getnextcomp(char_u *fname)
2757{
2758 while (*fname && !vim_ispathsep(*fname))
2759 MB_PTR_ADV(fname);
2760 if (*fname)
2761 ++fname;
2762 return fname;
2763}
2764
2765/*
2766 * Get a pointer to one character past the head of a path name.
2767 * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
2768 * If there is no head, path is returned.
2769 */
2770 char_u *
2771get_past_head(char_u *path)
2772{
2773 char_u *retval;
2774
2775#if defined(MSWIN)
2776 // may skip "c:"
2777 if (isalpha(path[0]) && path[1] == ':')
2778 retval = path + 2;
2779 else
2780 retval = path;
2781#else
2782# if defined(AMIGA)
2783 // may skip "label:"
2784 retval = vim_strchr(path, ':');
2785 if (retval == NULL)
2786 retval = path;
2787# else // Unix
2788 retval = path;
2789# endif
2790#endif
2791
2792 while (vim_ispathsep(*retval))
2793 ++retval;
2794
2795 return retval;
2796}
2797
2798/*
2799 * Return TRUE if 'c' is a path separator.
2800 * Note that for MS-Windows this includes the colon.
2801 */
2802 int
2803vim_ispathsep(int c)
2804{
2805#ifdef UNIX
2806 return (c == '/'); // UNIX has ':' inside file names
2807#else
2808# ifdef BACKSLASH_IN_FILENAME
2809 return (c == ':' || c == '/' || c == '\\');
2810# else
2811# ifdef VMS
2812 // server"user passwd"::device:[full.path.name]fname.extension;version"
2813 return (c == ':' || c == '[' || c == ']' || c == '/'
2814 || c == '<' || c == '>' || c == '"' );
2815# else
2816 return (c == ':' || c == '/');
2817# endif // VMS
2818# endif
2819#endif
2820}
2821
2822/*
2823 * Like vim_ispathsep(c), but exclude the colon for MS-Windows.
2824 */
2825 int
2826vim_ispathsep_nocolon(int c)
2827{
2828 return vim_ispathsep(c)
2829#ifdef BACKSLASH_IN_FILENAME
2830 && c != ':'
2831#endif
2832 ;
2833}
2834
2835/*
Bram Moolenaar26262f82019-09-04 20:59:15 +02002836 * Return TRUE if the directory of "fname" exists, FALSE otherwise.
2837 * Also returns TRUE if there is no directory name.
2838 * "fname" must be writable!.
2839 */
2840 int
2841dir_of_file_exists(char_u *fname)
2842{
2843 char_u *p;
2844 int c;
2845 int retval;
2846
2847 p = gettail_sep(fname);
2848 if (p == fname)
2849 return TRUE;
2850 c = *p;
2851 *p = NUL;
2852 retval = mch_isdir(fname);
2853 *p = c;
2854 return retval;
2855}
2856
2857/*
2858 * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally
2859 * and deal with 'fileignorecase'.
2860 */
2861 int
2862vim_fnamecmp(char_u *x, char_u *y)
2863{
2864#ifdef BACKSLASH_IN_FILENAME
2865 return vim_fnamencmp(x, y, MAXPATHL);
2866#else
2867 if (p_fic)
2868 return MB_STRICMP(x, y);
2869 return STRCMP(x, y);
2870#endif
2871}
2872
2873 int
2874vim_fnamencmp(char_u *x, char_u *y, size_t len)
2875{
2876#ifdef BACKSLASH_IN_FILENAME
2877 char_u *px = x;
2878 char_u *py = y;
2879 int cx = NUL;
2880 int cy = NUL;
2881
2882 while (len > 0)
2883 {
2884 cx = PTR2CHAR(px);
2885 cy = PTR2CHAR(py);
2886 if (cx == NUL || cy == NUL
2887 || ((p_fic ? MB_TOLOWER(cx) != MB_TOLOWER(cy) : cx != cy)
2888 && !(cx == '/' && cy == '\\')
2889 && !(cx == '\\' && cy == '/')))
2890 break;
Bram Moolenaar1614a142019-10-06 22:00:13 +02002891 len -= mb_ptr2len(px);
2892 px += mb_ptr2len(px);
2893 py += mb_ptr2len(py);
Bram Moolenaar26262f82019-09-04 20:59:15 +02002894 }
2895 if (len == 0)
2896 return 0;
2897 return (cx - cy);
2898#else
2899 if (p_fic)
2900 return MB_STRNICMP(x, y, len);
2901 return STRNCMP(x, y, len);
2902#endif
2903}
2904
2905/*
2906 * Concatenate file names fname1 and fname2 into allocated memory.
2907 * Only add a '/' or '\\' when 'sep' is TRUE and it is necessary.
2908 */
2909 char_u *
2910concat_fnames(char_u *fname1, char_u *fname2, int sep)
2911{
2912 char_u *dest;
2913
2914 dest = alloc(STRLEN(fname1) + STRLEN(fname2) + 3);
2915 if (dest != NULL)
2916 {
2917 STRCPY(dest, fname1);
2918 if (sep)
2919 add_pathsep(dest);
2920 STRCAT(dest, fname2);
2921 }
2922 return dest;
2923}
2924
2925/*
2926 * Add a path separator to a file name, unless it already ends in a path
2927 * separator.
2928 */
2929 void
2930add_pathsep(char_u *p)
2931{
2932 if (*p != NUL && !after_pathsep(p, p + STRLEN(p)))
2933 STRCAT(p, PATHSEPSTR);
2934}
2935
2936/*
2937 * FullName_save - Make an allocated copy of a full file name.
2938 * Returns NULL when out of memory.
2939 */
2940 char_u *
2941FullName_save(
2942 char_u *fname,
2943 int force) // force expansion, even when it already looks
2944 // like a full path name
2945{
2946 char_u *buf;
2947 char_u *new_fname = NULL;
2948
2949 if (fname == NULL)
2950 return NULL;
2951
2952 buf = alloc(MAXPATHL);
2953 if (buf != NULL)
2954 {
2955 if (vim_FullName(fname, buf, MAXPATHL, force) != FAIL)
2956 new_fname = vim_strsave(buf);
2957 else
2958 new_fname = vim_strsave(fname);
2959 vim_free(buf);
2960 }
2961 return new_fname;
2962}
2963
2964/*
2965 * return TRUE if "fname" exists.
2966 */
2967 int
2968vim_fexists(char_u *fname)
2969{
2970 stat_T st;
2971
2972 if (mch_stat((char *)fname, &st))
2973 return FALSE;
2974 return TRUE;
2975}
2976
2977/*
2978 * Invoke expand_wildcards() for one pattern.
2979 * Expand items like "%:h" before the expansion.
2980 * Returns OK or FAIL.
2981 */
2982 int
2983expand_wildcards_eval(
2984 char_u **pat, // pointer to input pattern
2985 int *num_file, // resulting number of files
2986 char_u ***file, // array of resulting files
2987 int flags) // EW_DIR, etc.
2988{
2989 int ret = FAIL;
2990 char_u *eval_pat = NULL;
2991 char_u *exp_pat = *pat;
2992 char *ignored_msg;
2993 int usedlen;
2994
2995 if (*exp_pat == '%' || *exp_pat == '#' || *exp_pat == '<')
2996 {
2997 ++emsg_off;
2998 eval_pat = eval_vars(exp_pat, exp_pat, &usedlen,
2999 NULL, &ignored_msg, NULL);
3000 --emsg_off;
3001 if (eval_pat != NULL)
3002 exp_pat = concat_str(eval_pat, exp_pat + usedlen);
3003 }
3004
3005 if (exp_pat != NULL)
3006 ret = expand_wildcards(1, &exp_pat, num_file, file, flags);
3007
3008 if (eval_pat != NULL)
3009 {
3010 vim_free(exp_pat);
3011 vim_free(eval_pat);
3012 }
3013
3014 return ret;
3015}
3016
3017/*
3018 * Expand wildcards. Calls gen_expand_wildcards() and removes files matching
3019 * 'wildignore'.
3020 * Returns OK or FAIL. When FAIL then "num_files" won't be set.
3021 */
3022 int
3023expand_wildcards(
3024 int num_pat, // number of input patterns
3025 char_u **pat, // array of input patterns
3026 int *num_files, // resulting number of files
3027 char_u ***files, // array of resulting files
3028 int flags) // EW_DIR, etc.
3029{
3030 int retval;
3031 int i, j;
3032 char_u *p;
3033 int non_suf_match; // number without matching suffix
3034
3035 retval = gen_expand_wildcards(num_pat, pat, num_files, files, flags);
3036
3037 // When keeping all matches, return here
3038 if ((flags & EW_KEEPALL) || retval == FAIL)
3039 return retval;
3040
3041#ifdef FEAT_WILDIGN
3042 /*
3043 * Remove names that match 'wildignore'.
3044 */
3045 if (*p_wig)
3046 {
3047 char_u *ffname;
3048
3049 // check all files in (*files)[]
3050 for (i = 0; i < *num_files; ++i)
3051 {
3052 ffname = FullName_save((*files)[i], FALSE);
3053 if (ffname == NULL) // out of memory
3054 break;
3055# ifdef VMS
3056 vms_remove_version(ffname);
3057# endif
3058 if (match_file_list(p_wig, (*files)[i], ffname))
3059 {
3060 // remove this matching file from the list
3061 vim_free((*files)[i]);
3062 for (j = i; j + 1 < *num_files; ++j)
3063 (*files)[j] = (*files)[j + 1];
3064 --*num_files;
3065 --i;
3066 }
3067 vim_free(ffname);
3068 }
3069
3070 // If the number of matches is now zero, we fail.
3071 if (*num_files == 0)
3072 {
3073 VIM_CLEAR(*files);
3074 return FAIL;
3075 }
3076 }
3077#endif
3078
3079 /*
3080 * Move the names where 'suffixes' match to the end.
3081 */
3082 if (*num_files > 1)
3083 {
3084 non_suf_match = 0;
3085 for (i = 0; i < *num_files; ++i)
3086 {
3087 if (!match_suffix((*files)[i]))
3088 {
3089 /*
3090 * Move the name without matching suffix to the front
3091 * of the list.
3092 */
3093 p = (*files)[i];
3094 for (j = i; j > non_suf_match; --j)
3095 (*files)[j] = (*files)[j - 1];
3096 (*files)[non_suf_match++] = p;
3097 }
3098 }
3099 }
3100
3101 return retval;
3102}
3103
3104/*
3105 * Return TRUE if "fname" matches with an entry in 'suffixes'.
3106 */
3107 int
3108match_suffix(char_u *fname)
3109{
3110 int fnamelen, setsuflen;
3111 char_u *setsuf;
3112#define MAXSUFLEN 30 // maximum length of a file suffix
3113 char_u suf_buf[MAXSUFLEN];
3114
3115 fnamelen = (int)STRLEN(fname);
3116 setsuflen = 0;
3117 for (setsuf = p_su; *setsuf; )
3118 {
3119 setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
3120 if (setsuflen == 0)
3121 {
3122 char_u *tail = gettail(fname);
3123
3124 // empty entry: match name without a '.'
3125 if (vim_strchr(tail, '.') == NULL)
3126 {
3127 setsuflen = 1;
3128 break;
3129 }
3130 }
3131 else
3132 {
3133 if (fnamelen >= setsuflen
3134 && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
3135 (size_t)setsuflen) == 0)
3136 break;
3137 setsuflen = 0;
3138 }
3139 }
3140 return (setsuflen != 0);
3141}
3142
3143#ifdef VIM_BACKTICK
3144
3145/*
3146 * Return TRUE if we can expand this backtick thing here.
3147 */
3148 static int
3149vim_backtick(char_u *p)
3150{
3151 return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
3152}
3153
3154/*
3155 * Expand an item in `backticks` by executing it as a command.
3156 * Currently only works when pat[] starts and ends with a `.
3157 * Returns number of file names found, -1 if an error is encountered.
3158 */
3159 static int
3160expand_backtick(
3161 garray_T *gap,
3162 char_u *pat,
3163 int flags) // EW_* flags
3164{
3165 char_u *p;
3166 char_u *cmd;
3167 char_u *buffer;
3168 int cnt = 0;
3169 int i;
3170
3171 // Create the command: lop off the backticks.
Bram Moolenaar71ccd032020-06-12 22:59:11 +02003172 cmd = vim_strnsave(pat + 1, STRLEN(pat) - 2);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003173 if (cmd == NULL)
3174 return -1;
3175
3176#ifdef FEAT_EVAL
3177 if (*cmd == '=') // `={expr}`: Expand expression
Bram Moolenaarb171fb12020-06-24 20:34:03 +02003178 buffer = eval_to_string(cmd + 1, TRUE);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003179 else
3180#endif
3181 buffer = get_cmd_output(cmd, NULL,
3182 (flags & EW_SILENT) ? SHELL_SILENT : 0, NULL);
3183 vim_free(cmd);
3184 if (buffer == NULL)
3185 return -1;
3186
3187 cmd = buffer;
3188 while (*cmd != NUL)
3189 {
3190 cmd = skipwhite(cmd); // skip over white space
3191 p = cmd;
3192 while (*p != NUL && *p != '\r' && *p != '\n') // skip over entry
3193 ++p;
3194 // add an entry if it is not empty
3195 if (p > cmd)
3196 {
3197 i = *p;
3198 *p = NUL;
3199 addfile(gap, cmd, flags);
3200 *p = i;
3201 ++cnt;
3202 }
3203 cmd = p;
3204 while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
3205 ++cmd;
3206 }
3207
3208 vim_free(buffer);
3209 return cnt;
3210}
3211#endif // VIM_BACKTICK
3212
3213#if defined(MSWIN)
3214/*
3215 * File name expansion code for MS-DOS, Win16 and Win32. It's here because
3216 * it's shared between these systems.
3217 */
3218
3219/*
3220 * comparison function for qsort in dos_expandpath()
3221 */
3222 static int
3223pstrcmp(const void *a, const void *b)
3224{
3225 return (pathcmp(*(char **)a, *(char **)b, -1));
3226}
3227
3228/*
3229 * Recursively expand one path component into all matching files and/or
3230 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
3231 * Return the number of matches found.
3232 * "path" has backslashes before chars that are not to be expanded, starting
3233 * at "path[wildoff]".
3234 * Return the number of matches found.
3235 * NOTE: much of this is identical to unix_expandpath(), keep in sync!
3236 */
3237 static int
3238dos_expandpath(
3239 garray_T *gap,
3240 char_u *path,
3241 int wildoff,
3242 int flags, // EW_* flags
3243 int didstar) // expanded "**" once already
3244{
3245 char_u *buf;
3246 char_u *path_end;
3247 char_u *p, *s, *e;
3248 int start_len = gap->ga_len;
3249 char_u *pat;
3250 regmatch_T regmatch;
3251 int starts_with_dot;
3252 int matches;
3253 int len;
3254 int starstar = FALSE;
3255 static int stardepth = 0; // depth for "**" expansion
3256 HANDLE hFind = INVALID_HANDLE_VALUE;
3257 WIN32_FIND_DATAW wfb;
3258 WCHAR *wn = NULL; // UCS-2 name, NULL when not used.
3259 char_u *matchname;
3260 int ok;
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003261 char_u *p_alt;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003262
3263 // Expanding "**" may take a long time, check for CTRL-C.
3264 if (stardepth > 0)
3265 {
3266 ui_breakcheck();
3267 if (got_int)
3268 return 0;
3269 }
3270
3271 // Make room for file name. When doing encoding conversion the actual
3272 // length may be quite a bit longer, thus use the maximum possible length.
3273 buf = alloc(MAXPATHL);
3274 if (buf == NULL)
3275 return 0;
3276
3277 /*
3278 * Find the first part in the path name that contains a wildcard or a ~1.
3279 * Copy it into buf, including the preceding characters.
3280 */
3281 p = buf;
3282 s = buf;
3283 e = NULL;
3284 path_end = path;
3285 while (*path_end != NUL)
3286 {
3287 // May ignore a wildcard that has a backslash before it; it will
3288 // be removed by rem_backslash() or file_pat_to_reg_pat() below.
3289 if (path_end >= path + wildoff && rem_backslash(path_end))
3290 *p++ = *path_end++;
3291 else if (*path_end == '\\' || *path_end == ':' || *path_end == '/')
3292 {
3293 if (e != NULL)
3294 break;
3295 s = p + 1;
3296 }
3297 else if (path_end >= path + wildoff
3298 && vim_strchr((char_u *)"*?[~", *path_end) != NULL)
3299 e = p;
3300 if (has_mbyte)
3301 {
3302 len = (*mb_ptr2len)(path_end);
3303 STRNCPY(p, path_end, len);
3304 p += len;
3305 path_end += len;
3306 }
3307 else
3308 *p++ = *path_end++;
3309 }
3310 e = p;
3311 *e = NUL;
3312
3313 // now we have one wildcard component between s and e
3314 // Remove backslashes between "wildoff" and the start of the wildcard
3315 // component.
3316 for (p = buf + wildoff; p < s; ++p)
3317 if (rem_backslash(p))
3318 {
3319 STRMOVE(p, p + 1);
3320 --e;
3321 --s;
3322 }
3323
3324 // Check for "**" between "s" and "e".
3325 for (p = s; p < e; ++p)
3326 if (p[0] == '*' && p[1] == '*')
3327 starstar = TRUE;
3328
3329 starts_with_dot = *s == '.';
3330 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
3331 if (pat == NULL)
3332 {
3333 vim_free(buf);
3334 return 0;
3335 }
3336
3337 // compile the regexp into a program
3338 if (flags & (EW_NOERROR | EW_NOTWILD))
3339 ++emsg_silent;
3340 regmatch.rm_ic = TRUE; // Always ignore case
3341 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
3342 if (flags & (EW_NOERROR | EW_NOTWILD))
3343 --emsg_silent;
3344 vim_free(pat);
3345
3346 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
3347 {
3348 vim_free(buf);
3349 return 0;
3350 }
3351
3352 // remember the pattern or file name being looked for
3353 matchname = vim_strsave(s);
3354
3355 // If "**" is by itself, this is the first time we encounter it and more
3356 // is following then find matches without any directory.
3357 if (!didstar && stardepth < 100 && starstar && e - s == 2
3358 && *path_end == '/')
3359 {
3360 STRCPY(s, path_end + 1);
3361 ++stardepth;
3362 (void)dos_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
3363 --stardepth;
3364 }
3365
3366 // Scan all files in the directory with "dir/ *.*"
3367 STRCPY(s, "*.*");
3368 wn = enc_to_utf16(buf, NULL);
3369 if (wn != NULL)
3370 hFind = FindFirstFileW(wn, &wfb);
3371 ok = (hFind != INVALID_HANDLE_VALUE);
3372
3373 while (ok)
3374 {
3375 p = utf16_to_enc(wfb.cFileName, NULL); // p is allocated here
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003376
Bram Moolenaar26262f82019-09-04 20:59:15 +02003377 if (p == NULL)
3378 break; // out of memory
3379
Bram Moolenaar0dc5f602021-02-07 14:01:35 +01003380 // Do not use the alternate filename when the file name ends in '~',
3381 // because it picks up backup files: short name for "foo.vim~" is
3382 // "foo~1.vim", which matches "*.vim".
3383 if (*wfb.cAlternateFileName == NUL || p[STRLEN(p) - 1] == '~')
Bram Moolenaar40655d52020-04-06 23:49:50 +02003384 p_alt = NULL;
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003385 else
3386 p_alt = utf16_to_enc(wfb.cAlternateFileName, NULL);
3387
Bram Moolenaar26262f82019-09-04 20:59:15 +02003388 // Ignore entries starting with a dot, unless when asked for. Accept
3389 // all entries found with "matchname".
3390 if ((p[0] != '.' || starts_with_dot
3391 || ((flags & EW_DODOT)
3392 && p[1] != NUL && (p[1] != '.' || p[2] != NUL)))
3393 && (matchname == NULL
3394 || (regmatch.regprog != NULL
Bram Moolenaar40655d52020-04-06 23:49:50 +02003395 && (vim_regexec(&regmatch, p, (colnr_T)0)
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003396 || (p_alt != NULL
Bram Moolenaar40655d52020-04-06 23:49:50 +02003397 && vim_regexec(&regmatch, p_alt, (colnr_T)0))))
Bram Moolenaar26262f82019-09-04 20:59:15 +02003398 || ((flags & EW_NOTWILD)
3399 && fnamencmp(path + (s - buf), p, e - s) == 0)))
3400 {
3401 STRCPY(s, p);
3402 len = (int)STRLEN(buf);
3403
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003404 if (starstar && stardepth < 100
3405 && (wfb.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
Bram Moolenaar26262f82019-09-04 20:59:15 +02003406 {
3407 // For "**" in the pattern first go deeper in the tree to
3408 // find matches.
3409 STRCPY(buf + len, "/**");
3410 STRCPY(buf + len + 3, path_end);
3411 ++stardepth;
3412 (void)dos_expandpath(gap, buf, len + 1, flags, TRUE);
3413 --stardepth;
3414 }
3415
3416 STRCPY(buf + len, path_end);
3417 if (mch_has_exp_wildcard(path_end))
3418 {
3419 // need to expand another component of the path
3420 // remove backslashes for the remaining components only
3421 (void)dos_expandpath(gap, buf, len + 1, flags, FALSE);
3422 }
3423 else
3424 {
3425 // no more wildcards, check if there is a match
3426 // remove backslashes for the remaining components only
3427 if (*path_end != 0)
3428 backslash_halve(buf + len + 1);
3429 if (mch_getperm(buf) >= 0) // add existing file
3430 addfile(gap, buf, flags);
3431 }
3432 }
3433
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003434 vim_free(p_alt);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003435 vim_free(p);
3436 ok = FindNextFileW(hFind, &wfb);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003437 }
3438
3439 FindClose(hFind);
3440 vim_free(wn);
3441 vim_free(buf);
3442 vim_regfree(regmatch.regprog);
3443 vim_free(matchname);
3444
3445 matches = gap->ga_len - start_len;
3446 if (matches > 0)
3447 qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
3448 sizeof(char_u *), pstrcmp);
3449 return matches;
3450}
3451
3452 int
3453mch_expandpath(
3454 garray_T *gap,
3455 char_u *path,
3456 int flags) // EW_* flags
3457{
3458 return dos_expandpath(gap, path, 0, flags, FALSE);
3459}
3460#endif // MSWIN
3461
3462#if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \
3463 || defined(PROTO)
3464/*
3465 * Unix style wildcard expansion code.
3466 * It's here because it's used both for Unix and Mac.
3467 */
3468 static int
3469pstrcmp(const void *a, const void *b)
3470{
3471 return (pathcmp(*(char **)a, *(char **)b, -1));
3472}
3473
3474/*
3475 * Recursively expand one path component into all matching files and/or
3476 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
3477 * "path" has backslashes before chars that are not to be expanded, starting
3478 * at "path + wildoff".
3479 * Return the number of matches found.
3480 * NOTE: much of this is identical to dos_expandpath(), keep in sync!
3481 */
3482 int
3483unix_expandpath(
3484 garray_T *gap,
3485 char_u *path,
3486 int wildoff,
3487 int flags, // EW_* flags
3488 int didstar) // expanded "**" once already
3489{
3490 char_u *buf;
3491 char_u *path_end;
3492 char_u *p, *s, *e;
3493 int start_len = gap->ga_len;
3494 char_u *pat;
3495 regmatch_T regmatch;
3496 int starts_with_dot;
3497 int matches;
3498 int len;
3499 int starstar = FALSE;
3500 static int stardepth = 0; // depth for "**" expansion
3501
3502 DIR *dirp;
3503 struct dirent *dp;
3504
3505 // Expanding "**" may take a long time, check for CTRL-C.
3506 if (stardepth > 0)
3507 {
3508 ui_breakcheck();
3509 if (got_int)
3510 return 0;
3511 }
3512
3513 // make room for file name
3514 buf = alloc(STRLEN(path) + BASENAMELEN + 5);
3515 if (buf == NULL)
3516 return 0;
3517
3518 /*
3519 * Find the first part in the path name that contains a wildcard.
3520 * When EW_ICASE is set every letter is considered to be a wildcard.
3521 * Copy it into "buf", including the preceding characters.
3522 */
3523 p = buf;
3524 s = buf;
3525 e = NULL;
3526 path_end = path;
3527 while (*path_end != NUL)
3528 {
3529 // May ignore a wildcard that has a backslash before it; it will
3530 // be removed by rem_backslash() or file_pat_to_reg_pat() below.
3531 if (path_end >= path + wildoff && rem_backslash(path_end))
3532 *p++ = *path_end++;
3533 else if (*path_end == '/')
3534 {
3535 if (e != NULL)
3536 break;
3537 s = p + 1;
3538 }
3539 else if (path_end >= path + wildoff
3540 && (vim_strchr((char_u *)"*?[{~$", *path_end) != NULL
3541 || (!p_fic && (flags & EW_ICASE)
3542 && isalpha(PTR2CHAR(path_end)))))
3543 e = p;
3544 if (has_mbyte)
3545 {
3546 len = (*mb_ptr2len)(path_end);
3547 STRNCPY(p, path_end, len);
3548 p += len;
3549 path_end += len;
3550 }
3551 else
3552 *p++ = *path_end++;
3553 }
3554 e = p;
3555 *e = NUL;
3556
3557 // Now we have one wildcard component between "s" and "e".
3558 // Remove backslashes between "wildoff" and the start of the wildcard
3559 // component.
3560 for (p = buf + wildoff; p < s; ++p)
3561 if (rem_backslash(p))
3562 {
3563 STRMOVE(p, p + 1);
3564 --e;
3565 --s;
3566 }
3567
3568 // Check for "**" between "s" and "e".
3569 for (p = s; p < e; ++p)
3570 if (p[0] == '*' && p[1] == '*')
3571 starstar = TRUE;
3572
3573 // convert the file pattern to a regexp pattern
3574 starts_with_dot = *s == '.';
3575 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
3576 if (pat == NULL)
3577 {
3578 vim_free(buf);
3579 return 0;
3580 }
3581
3582 // compile the regexp into a program
3583 if (flags & EW_ICASE)
3584 regmatch.rm_ic = TRUE; // 'wildignorecase' set
3585 else
3586 regmatch.rm_ic = p_fic; // ignore case when 'fileignorecase' is set
3587 if (flags & (EW_NOERROR | EW_NOTWILD))
3588 ++emsg_silent;
3589 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
3590 if (flags & (EW_NOERROR | EW_NOTWILD))
3591 --emsg_silent;
3592 vim_free(pat);
3593
3594 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
3595 {
3596 vim_free(buf);
3597 return 0;
3598 }
3599
3600 // If "**" is by itself, this is the first time we encounter it and more
3601 // is following then find matches without any directory.
3602 if (!didstar && stardepth < 100 && starstar && e - s == 2
3603 && *path_end == '/')
3604 {
3605 STRCPY(s, path_end + 1);
3606 ++stardepth;
3607 (void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
3608 --stardepth;
3609 }
3610
3611 // open the directory for scanning
3612 *s = NUL;
3613 dirp = opendir(*buf == NUL ? "." : (char *)buf);
3614
3615 // Find all matching entries
3616 if (dirp != NULL)
3617 {
3618 for (;;)
3619 {
3620 dp = readdir(dirp);
3621 if (dp == NULL)
3622 break;
3623 if ((dp->d_name[0] != '.' || starts_with_dot
3624 || ((flags & EW_DODOT)
3625 && dp->d_name[1] != NUL
3626 && (dp->d_name[1] != '.' || dp->d_name[2] != NUL)))
3627 && ((regmatch.regprog != NULL && vim_regexec(&regmatch,
3628 (char_u *)dp->d_name, (colnr_T)0))
3629 || ((flags & EW_NOTWILD)
3630 && fnamencmp(path + (s - buf), dp->d_name, e - s) == 0)))
3631 {
3632 STRCPY(s, dp->d_name);
3633 len = STRLEN(buf);
3634
3635 if (starstar && stardepth < 100)
3636 {
3637 // For "**" in the pattern first go deeper in the tree to
3638 // find matches.
3639 STRCPY(buf + len, "/**");
3640 STRCPY(buf + len + 3, path_end);
3641 ++stardepth;
3642 (void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
3643 --stardepth;
3644 }
3645
3646 STRCPY(buf + len, path_end);
3647 if (mch_has_exp_wildcard(path_end)) // handle more wildcards
3648 {
3649 // need to expand another component of the path
3650 // remove backslashes for the remaining components only
3651 (void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
3652 }
3653 else
3654 {
3655 stat_T sb;
3656
3657 // no more wildcards, check if there is a match
3658 // remove backslashes for the remaining components only
3659 if (*path_end != NUL)
3660 backslash_halve(buf + len + 1);
3661 // add existing file or symbolic link
3662 if ((flags & EW_ALLLINKS) ? mch_lstat((char *)buf, &sb) >= 0
3663 : mch_getperm(buf) >= 0)
3664 {
3665#ifdef MACOS_CONVERT
3666 size_t precomp_len = STRLEN(buf)+1;
3667 char_u *precomp_buf =
3668 mac_precompose_path(buf, precomp_len, &precomp_len);
3669
3670 if (precomp_buf)
3671 {
3672 mch_memmove(buf, precomp_buf, precomp_len);
3673 vim_free(precomp_buf);
3674 }
3675#endif
3676 addfile(gap, buf, flags);
3677 }
3678 }
3679 }
3680 }
3681
3682 closedir(dirp);
3683 }
3684
3685 vim_free(buf);
3686 vim_regfree(regmatch.regprog);
3687
3688 matches = gap->ga_len - start_len;
3689 if (matches > 0)
3690 qsort(((char_u **)gap->ga_data) + start_len, matches,
3691 sizeof(char_u *), pstrcmp);
3692 return matches;
3693}
3694#endif
3695
3696/*
3697 * Return TRUE if "p" contains what looks like an environment variable.
3698 * Allowing for escaping.
3699 */
3700 static int
3701has_env_var(char_u *p)
3702{
3703 for ( ; *p; MB_PTR_ADV(p))
3704 {
3705 if (*p == '\\' && p[1] != NUL)
3706 ++p;
3707 else if (vim_strchr((char_u *)
3708#if defined(MSWIN)
3709 "$%"
3710#else
3711 "$"
3712#endif
3713 , *p) != NULL)
3714 return TRUE;
3715 }
3716 return FALSE;
3717}
3718
3719#ifdef SPECIAL_WILDCHAR
3720/*
3721 * Return TRUE if "p" contains a special wildcard character, one that Vim
3722 * cannot expand, requires using a shell.
3723 */
3724 static int
3725has_special_wildchar(char_u *p)
3726{
3727 for ( ; *p; MB_PTR_ADV(p))
3728 {
3729 // Disallow line break characters.
3730 if (*p == '\r' || *p == '\n')
3731 break;
3732 // Allow for escaping.
3733 if (*p == '\\' && p[1] != NUL && p[1] != '\r' && p[1] != '\n')
3734 ++p;
3735 else if (vim_strchr((char_u *)SPECIAL_WILDCHAR, *p) != NULL)
3736 {
3737 // A { must be followed by a matching }.
3738 if (*p == '{' && vim_strchr(p, '}') == NULL)
3739 continue;
3740 // A quote and backtick must be followed by another one.
3741 if ((*p == '`' || *p == '\'') && vim_strchr(p, *p) == NULL)
3742 continue;
3743 return TRUE;
3744 }
3745 }
3746 return FALSE;
3747}
3748#endif
3749
3750/*
3751 * Generic wildcard expansion code.
3752 *
3753 * Characters in "pat" that should not be expanded must be preceded with a
3754 * backslash. E.g., "/path\ with\ spaces/my\*star*"
3755 *
3756 * Return FAIL when no single file was found. In this case "num_file" is not
3757 * set, and "file" may contain an error message.
3758 * Return OK when some files found. "num_file" is set to the number of
3759 * matches, "file" to the array of matches. Call FreeWild() later.
3760 */
3761 int
3762gen_expand_wildcards(
3763 int num_pat, // number of input patterns
3764 char_u **pat, // array of input patterns
3765 int *num_file, // resulting number of files
3766 char_u ***file, // array of resulting files
3767 int flags) // EW_* flags
3768{
3769 int i;
3770 garray_T ga;
3771 char_u *p;
3772 static int recursive = FALSE;
3773 int add_pat;
3774 int retval = OK;
3775#if defined(FEAT_SEARCHPATH)
3776 int did_expand_in_path = FALSE;
3777#endif
3778
3779 /*
3780 * expand_env() is called to expand things like "~user". If this fails,
3781 * it calls ExpandOne(), which brings us back here. In this case, always
3782 * call the machine specific expansion function, if possible. Otherwise,
3783 * return FAIL.
3784 */
3785 if (recursive)
3786#ifdef SPECIAL_WILDCHAR
3787 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
3788#else
3789 return FAIL;
3790#endif
3791
3792#ifdef SPECIAL_WILDCHAR
3793 /*
3794 * If there are any special wildcard characters which we cannot handle
3795 * here, call machine specific function for all the expansion. This
3796 * avoids starting the shell for each argument separately.
3797 * For `=expr` do use the internal function.
3798 */
3799 for (i = 0; i < num_pat; i++)
3800 {
3801 if (has_special_wildchar(pat[i])
3802# ifdef VIM_BACKTICK
3803 && !(vim_backtick(pat[i]) && pat[i][1] == '=')
3804# endif
3805 )
3806 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
3807 }
3808#endif
3809
3810 recursive = TRUE;
3811
3812 /*
3813 * The matching file names are stored in a growarray. Init it empty.
3814 */
3815 ga_init2(&ga, (int)sizeof(char_u *), 30);
3816
3817 for (i = 0; i < num_pat; ++i)
3818 {
3819 add_pat = -1;
3820 p = pat[i];
3821
3822#ifdef VIM_BACKTICK
3823 if (vim_backtick(p))
3824 {
3825 add_pat = expand_backtick(&ga, p, flags);
3826 if (add_pat == -1)
3827 retval = FAIL;
3828 }
3829 else
3830#endif
3831 {
3832 /*
3833 * First expand environment variables, "~/" and "~user/".
3834 */
3835 if ((has_env_var(p) && !(flags & EW_NOTENV)) || *p == '~')
3836 {
3837 p = expand_env_save_opt(p, TRUE);
3838 if (p == NULL)
3839 p = pat[i];
3840#ifdef UNIX
3841 /*
3842 * On Unix, if expand_env() can't expand an environment
3843 * variable, use the shell to do that. Discard previously
3844 * found file names and start all over again.
3845 */
3846 else if (has_env_var(p) || *p == '~')
3847 {
3848 vim_free(p);
3849 ga_clear_strings(&ga);
3850 i = mch_expand_wildcards(num_pat, pat, num_file, file,
3851 flags|EW_KEEPDOLLAR);
3852 recursive = FALSE;
3853 return i;
3854 }
3855#endif
3856 }
3857
3858 /*
3859 * If there are wildcards: Expand file names and add each match to
3860 * the list. If there is no match, and EW_NOTFOUND is given, add
3861 * the pattern.
3862 * If there are no wildcards: Add the file name if it exists or
3863 * when EW_NOTFOUND is given.
3864 */
3865 if (mch_has_exp_wildcard(p))
3866 {
3867#if defined(FEAT_SEARCHPATH)
3868 if ((flags & EW_PATH)
3869 && !mch_isFullName(p)
3870 && !(p[0] == '.'
3871 && (vim_ispathsep(p[1])
3872 || (p[1] == '.' && vim_ispathsep(p[2]))))
3873 )
3874 {
3875 // :find completion where 'path' is used.
3876 // Recursiveness is OK here.
3877 recursive = FALSE;
3878 add_pat = expand_in_path(&ga, p, flags);
3879 recursive = TRUE;
3880 did_expand_in_path = TRUE;
3881 }
3882 else
3883#endif
3884 add_pat = mch_expandpath(&ga, p, flags);
3885 }
3886 }
3887
3888 if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
3889 {
3890 char_u *t = backslash_halve_save(p);
3891
3892 // When EW_NOTFOUND is used, always add files and dirs. Makes
3893 // "vim c:/" work.
3894 if (flags & EW_NOTFOUND)
3895 addfile(&ga, t, flags | EW_DIR | EW_FILE);
3896 else
3897 addfile(&ga, t, flags);
3898
3899 if (t != p)
3900 vim_free(t);
3901 }
3902
3903#if defined(FEAT_SEARCHPATH)
3904 if (did_expand_in_path && ga.ga_len > 0 && (flags & EW_PATH))
3905 uniquefy_paths(&ga, p);
3906#endif
3907 if (p != pat[i])
3908 vim_free(p);
3909 }
3910
Bram Moolenaar566cc8c2020-06-29 21:14:51 +02003911 // When returning FAIL the array must be freed here.
3912 if (retval == FAIL)
3913 ga_clear(&ga);
3914
Bram Moolenaar26262f82019-09-04 20:59:15 +02003915 *num_file = ga.ga_len;
Bram Moolenaar566cc8c2020-06-29 21:14:51 +02003916 *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data
3917 : (char_u **)_("no matches");
Bram Moolenaar26262f82019-09-04 20:59:15 +02003918
3919 recursive = FALSE;
3920
3921 return ((flags & EW_EMPTYOK) || ga.ga_data != NULL) ? retval : FAIL;
3922}
3923
3924/*
3925 * Add a file to a file list. Accepted flags:
3926 * EW_DIR add directories
3927 * EW_FILE add files
3928 * EW_EXEC add executable files
3929 * EW_NOTFOUND add even when it doesn't exist
3930 * EW_ADDSLASH add slash after directory name
3931 * EW_ALLLINKS add symlink also when the referred file does not exist
3932 */
3933 void
3934addfile(
3935 garray_T *gap,
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003936 char_u *f, // filename
Bram Moolenaar26262f82019-09-04 20:59:15 +02003937 int flags)
3938{
3939 char_u *p;
3940 int isdir;
3941 stat_T sb;
3942
3943 // if the file/dir/link doesn't exist, may not add it
3944 if (!(flags & EW_NOTFOUND) && ((flags & EW_ALLLINKS)
3945 ? mch_lstat((char *)f, &sb) < 0 : mch_getperm(f) < 0))
3946 return;
3947
3948#ifdef FNAME_ILLEGAL
3949 // if the file/dir contains illegal characters, don't add it
3950 if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
3951 return;
3952#endif
3953
3954 isdir = mch_isdir(f);
3955 if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
3956 return;
3957
3958 // If the file isn't executable, may not add it. Do accept directories.
3959 // When invoked from expand_shellcmd() do not use $PATH.
3960 if (!isdir && (flags & EW_EXEC)
3961 && !mch_can_exe(f, NULL, !(flags & EW_SHELLCMD)))
3962 return;
3963
3964 // Make room for another item in the file list.
3965 if (ga_grow(gap, 1) == FAIL)
3966 return;
3967
3968 p = alloc(STRLEN(f) + 1 + isdir);
3969 if (p == NULL)
3970 return;
3971
3972 STRCPY(p, f);
3973#ifdef BACKSLASH_IN_FILENAME
3974 slash_adjust(p);
3975#endif
3976 /*
3977 * Append a slash or backslash after directory names if none is present.
3978 */
3979#ifndef DONT_ADD_PATHSEP_TO_DIR
3980 if (isdir && (flags & EW_ADDSLASH))
3981 add_pathsep(p);
3982#endif
3983 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
3984}
3985
3986/*
3987 * Free the list of files returned by expand_wildcards() or other expansion
3988 * functions.
3989 */
3990 void
3991FreeWild(int count, char_u **files)
3992{
3993 if (count <= 0 || files == NULL)
3994 return;
3995 while (count--)
3996 vim_free(files[count]);
3997 vim_free(files);
3998}
3999
4000/*
4001 * Compare path "p[]" to "q[]".
4002 * If "maxlen" >= 0 compare "p[maxlen]" to "q[maxlen]"
4003 * Return value like strcmp(p, q), but consider path separators.
4004 */
4005 int
4006pathcmp(const char *p, const char *q, int maxlen)
4007{
4008 int i, j;
4009 int c1, c2;
4010 const char *s = NULL;
4011
4012 for (i = 0, j = 0; maxlen < 0 || (i < maxlen && j < maxlen);)
4013 {
4014 c1 = PTR2CHAR((char_u *)p + i);
4015 c2 = PTR2CHAR((char_u *)q + j);
4016
4017 // End of "p": check if "q" also ends or just has a slash.
4018 if (c1 == NUL)
4019 {
4020 if (c2 == NUL) // full match
4021 return 0;
4022 s = q;
4023 i = j;
4024 break;
4025 }
4026
4027 // End of "q": check if "p" just has a slash.
4028 if (c2 == NUL)
4029 {
4030 s = p;
4031 break;
4032 }
4033
4034 if ((p_fic ? MB_TOUPPER(c1) != MB_TOUPPER(c2) : c1 != c2)
4035#ifdef BACKSLASH_IN_FILENAME
4036 // consider '/' and '\\' to be equal
4037 && !((c1 == '/' && c2 == '\\')
4038 || (c1 == '\\' && c2 == '/'))
4039#endif
4040 )
4041 {
4042 if (vim_ispathsep(c1))
4043 return -1;
4044 if (vim_ispathsep(c2))
4045 return 1;
4046 return p_fic ? MB_TOUPPER(c1) - MB_TOUPPER(c2)
4047 : c1 - c2; // no match
4048 }
4049
Bram Moolenaar1614a142019-10-06 22:00:13 +02004050 i += mb_ptr2len((char_u *)p + i);
4051 j += mb_ptr2len((char_u *)q + j);
Bram Moolenaar26262f82019-09-04 20:59:15 +02004052 }
4053 if (s == NULL) // "i" or "j" ran into "maxlen"
4054 return 0;
4055
4056 c1 = PTR2CHAR((char_u *)s + i);
Bram Moolenaar1614a142019-10-06 22:00:13 +02004057 c2 = PTR2CHAR((char_u *)s + i + mb_ptr2len((char_u *)s + i));
Bram Moolenaar26262f82019-09-04 20:59:15 +02004058 // ignore a trailing slash, but not "//" or ":/"
4059 if (c2 == NUL
4060 && i > 0
4061 && !after_pathsep((char_u *)s, (char_u *)s + i)
4062#ifdef BACKSLASH_IN_FILENAME
4063 && (c1 == '/' || c1 == '\\')
4064#else
4065 && c1 == '/'
4066#endif
4067 )
4068 return 0; // match with trailing slash
4069 if (s == q)
4070 return -1; // no match
4071 return 1;
4072}
4073
4074/*
4075 * Return TRUE if "name" is a full (absolute) path name or URL.
4076 */
4077 int
4078vim_isAbsName(char_u *name)
4079{
4080 return (path_with_url(name) != 0 || mch_isFullName(name));
4081}
4082
4083/*
4084 * Get absolute file name into buffer "buf[len]".
4085 *
4086 * return FAIL for failure, OK otherwise
4087 */
4088 int
4089vim_FullName(
4090 char_u *fname,
4091 char_u *buf,
4092 int len,
4093 int force) // force expansion even when already absolute
4094{
4095 int retval = OK;
4096 int url;
4097
4098 *buf = NUL;
4099 if (fname == NULL)
4100 return FAIL;
4101
4102 url = path_with_url(fname);
4103 if (!url)
4104 retval = mch_FullName(fname, buf, len, force);
4105 if (url || retval == FAIL)
4106 {
4107 // something failed; use the file name (truncate when too long)
4108 vim_strncpy(buf, fname, len - 1);
4109 }
4110#if defined(MSWIN)
4111 slash_adjust(buf);
4112#endif
4113 return retval;
4114}