blob: 69bc8b5f4930f1dc29fcd4d5329c3bdf1241e6a8 [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
859 semsg(_(e_invexpr2), flags);
860}
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
1450 if (argvars[1].v_type != VAR_UNKNOWN)
1451 {
1452 trim_len = (int)tv_get_number(&argvars[1]);
1453 if (trim_len < 1)
1454 trim_len = 1;
1455 }
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02001456
1457 rettv->v_type = VAR_STRING;
1458 p = tv_get_string_chk(&argvars[0]);
Bram Moolenaar6a33ef02020-09-25 22:42:48 +02001459
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02001460 if (p == NULL)
1461 rettv->vval.v_string = NULL;
1462 else
1463 {
1464 p = vim_strsave(p);
1465 rettv->vval.v_string = p;
1466 if (p != NULL)
Bram Moolenaar6a33ef02020-09-25 22:42:48 +02001467 shorten_dir_len(p, trim_len);
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02001468 }
1469}
1470
1471/*
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001472 * Common code for readdir_checkitem() and readdirex_checkitem().
1473 * Either "name" or "dict" is NULL.
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001474 */
1475 static int
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001476checkitem_common(void *context, char_u *name, dict_T *dict)
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001477{
1478 typval_T *expr = (typval_T *)context;
1479 typval_T save_val;
1480 typval_T rettv;
1481 typval_T argv[2];
1482 int retval = 0;
1483 int error = FALSE;
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001484
1485 prepare_vimvar(VV_VAL, &save_val);
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001486 if (name != NULL)
1487 {
1488 set_vim_var_string(VV_VAL, name, -1);
1489 argv[0].v_type = VAR_STRING;
1490 argv[0].vval.v_string = name;
1491 }
1492 else
1493 {
1494 set_vim_var_dict(VV_VAL, dict);
1495 argv[0].v_type = VAR_DICT;
1496 argv[0].vval.v_dict = dict;
1497 }
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001498
1499 if (eval_expr_typval(expr, argv, 1, &rettv) == FAIL)
1500 goto theend;
1501
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001502 // We want to use -1, but also true/false should be allowed.
1503 if (rettv.v_type == VAR_SPECIAL || rettv.v_type == VAR_BOOL)
1504 {
1505 rettv.v_type = VAR_NUMBER;
1506 rettv.vval.v_number = rettv.vval.v_number == VVAL_TRUE;
1507 }
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001508 retval = tv_get_number_chk(&rettv, &error);
1509 if (error)
1510 retval = -1;
1511 clear_tv(&rettv);
1512
1513theend:
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001514 if (name != NULL)
1515 set_vim_var_string(VV_VAL, NULL, 0);
1516 else
1517 set_vim_var_dict(VV_VAL, NULL);
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001518 restore_vimvar(VV_VAL, &save_val);
1519 return retval;
1520}
1521
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001522/*
1523 * Evaluate "expr" (= "context") for readdir().
1524 */
1525 static int
1526readdir_checkitem(void *context, void *item)
1527{
1528 char_u *name = (char_u *)item;
1529
1530 return checkitem_common(context, name, NULL);
1531}
1532
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001533 static int
1534readdirex_dict_arg(typval_T *tv, int *cmp)
1535{
1536 char_u *compare;
1537
1538 if (tv->v_type != VAR_DICT)
1539 {
1540 emsg(_(e_dictreq));
1541 return FAIL;
1542 }
1543
1544 if (dict_find(tv->vval.v_dict, (char_u *)"sort", -1) != NULL)
1545 compare = dict_get_string(tv->vval.v_dict, (char_u *)"sort", FALSE);
1546 else
1547 {
1548 semsg(_(e_no_dict_key), "sort");
1549 return FAIL;
1550 }
1551
1552 if (STRCMP(compare, (char_u *) "none") == 0)
1553 *cmp = READDIR_SORT_NONE;
1554 else if (STRCMP(compare, (char_u *) "case") == 0)
1555 *cmp = READDIR_SORT_BYTE;
1556 else if (STRCMP(compare, (char_u *) "icase") == 0)
1557 *cmp = READDIR_SORT_IC;
1558 else if (STRCMP(compare, (char_u *) "collate") == 0)
1559 *cmp = READDIR_SORT_COLLATE;
1560 return OK;
1561}
1562
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001563/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001564 * "readdir()" function
1565 */
1566 void
1567f_readdir(typval_T *argvars, typval_T *rettv)
1568{
1569 typval_T *expr;
1570 int ret;
1571 char_u *path;
1572 char_u *p;
1573 garray_T ga;
1574 int i;
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001575 int sort = READDIR_SORT_BYTE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001576
1577 if (rettv_list_alloc(rettv) == FAIL)
1578 return;
1579 path = tv_get_string(&argvars[0]);
1580 expr = &argvars[1];
1581
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001582 if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN &&
1583 readdirex_dict_arg(&argvars[2], &sort) == FAIL)
1584 return;
1585
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001586 ret = readdir_core(&ga, path, FALSE, (void *)expr,
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001587 (expr->v_type == VAR_UNKNOWN) ? NULL : readdir_checkitem, sort);
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001588 if (ret == OK)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001589 {
1590 for (i = 0; i < ga.ga_len; i++)
1591 {
1592 p = ((char_u **)ga.ga_data)[i];
1593 list_append_string(rettv->vval.v_list, p, -1);
1594 }
1595 }
1596 ga_clear_strings(&ga);
1597}
1598
1599/*
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001600 * Evaluate "expr" (= "context") for readdirex().
1601 */
1602 static int
1603readdirex_checkitem(void *context, void *item)
1604{
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001605 dict_T *dict = (dict_T*)item;
1606
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001607 return checkitem_common(context, NULL, dict);
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001608}
1609
1610/*
1611 * "readdirex()" function
1612 */
1613 void
1614f_readdirex(typval_T *argvars, typval_T *rettv)
1615{
1616 typval_T *expr;
1617 int ret;
1618 char_u *path;
1619 garray_T ga;
1620 int i;
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001621 int sort = READDIR_SORT_BYTE;
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001622
1623 if (rettv_list_alloc(rettv) == FAIL)
1624 return;
1625 path = tv_get_string(&argvars[0]);
1626 expr = &argvars[1];
1627
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001628 if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN &&
1629 readdirex_dict_arg(&argvars[2], &sort) == FAIL)
1630 return;
1631
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001632 ret = readdir_core(&ga, path, TRUE, (void *)expr,
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001633 (expr->v_type == VAR_UNKNOWN) ? NULL : readdirex_checkitem, sort);
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001634 if (ret == OK)
1635 {
1636 for (i = 0; i < ga.ga_len; i++)
1637 {
1638 dict_T *dict = ((dict_T**)ga.ga_data)[i];
1639 list_append_dict(rettv->vval.v_list, dict);
1640 dict_unref(dict);
1641 }
1642 }
1643 ga_clear(&ga);
1644}
1645
1646/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001647 * "readfile()" function
1648 */
Bram Moolenaarc423ad72021-01-13 20:38:03 +01001649 static void
1650read_file_or_blob(typval_T *argvars, typval_T *rettv, int always_blob)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001651{
1652 int binary = FALSE;
Bram Moolenaarc423ad72021-01-13 20:38:03 +01001653 int blob = always_blob;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001654 int failed = FALSE;
1655 char_u *fname;
1656 FILE *fd;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001657 char_u buf[(IOSIZE/256)*256]; // rounded to avoid odd + 1
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001658 int io_size = sizeof(buf);
Bram Moolenaar26262f82019-09-04 20:59:15 +02001659 int readlen; // size of last fread()
1660 char_u *prev = NULL; // previously read bytes, if any
1661 long prevlen = 0; // length of data in prev
1662 long prevsize = 0; // size of prev buffer
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001663 long maxline = MAXLNUM;
1664 long cnt = 0;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001665 char_u *p; // position in buf
1666 char_u *start; // start of current line
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001667
1668 if (argvars[1].v_type != VAR_UNKNOWN)
1669 {
1670 if (STRCMP(tv_get_string(&argvars[1]), "b") == 0)
1671 binary = TRUE;
1672 if (STRCMP(tv_get_string(&argvars[1]), "B") == 0)
1673 blob = TRUE;
1674
1675 if (argvars[2].v_type != VAR_UNKNOWN)
1676 maxline = (long)tv_get_number(&argvars[2]);
1677 }
1678
Bram Moolenaar15352dc2020-04-06 21:12:42 +02001679 if ((blob ? rettv_blob_alloc(rettv) : rettv_list_alloc(rettv)) == FAIL)
1680 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001681
Bram Moolenaar26262f82019-09-04 20:59:15 +02001682 // Always open the file in binary mode, library functions have a mind of
1683 // their own about CR-LF conversion.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001684 fname = tv_get_string(&argvars[0]);
Bram Moolenaar15352dc2020-04-06 21:12:42 +02001685
1686 if (mch_isdir(fname))
1687 {
1688 semsg(_(e_isadir2), fname);
1689 return;
1690 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001691 if (*fname == NUL || (fd = mch_fopen((char *)fname, READBIN)) == NULL)
1692 {
1693 semsg(_(e_notopen), *fname == NUL ? (char_u *)_("<empty>") : fname);
1694 return;
1695 }
1696
1697 if (blob)
1698 {
1699 if (read_blob(fd, rettv->vval.v_blob) == FAIL)
1700 {
Bram Moolenaar15352dc2020-04-06 21:12:42 +02001701 semsg(_(e_notread), fname);
1702 // An empty blob is returned on error.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001703 blob_free(rettv->vval.v_blob);
Bram Moolenaar15352dc2020-04-06 21:12:42 +02001704 rettv->vval.v_blob = NULL;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001705 }
1706 fclose(fd);
1707 return;
1708 }
1709
1710 while (cnt < maxline || maxline < 0)
1711 {
1712 readlen = (int)fread(buf, 1, io_size, fd);
1713
Bram Moolenaar26262f82019-09-04 20:59:15 +02001714 // This for loop processes what was read, but is also entered at end
1715 // of file so that either:
1716 // - an incomplete line gets written
1717 // - a "binary" file gets an empty line at the end if it ends in a
1718 // newline.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001719 for (p = buf, start = buf;
1720 p < buf + readlen || (readlen <= 0 && (prevlen > 0 || binary));
1721 ++p)
1722 {
1723 if (*p == '\n' || readlen <= 0)
1724 {
1725 listitem_T *li;
1726 char_u *s = NULL;
1727 long_u len = p - start;
1728
Bram Moolenaar26262f82019-09-04 20:59:15 +02001729 // Finished a line. Remove CRs before NL.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001730 if (readlen > 0 && !binary)
1731 {
1732 while (len > 0 && start[len - 1] == '\r')
1733 --len;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001734 // removal may cross back to the "prev" string
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001735 if (len == 0)
1736 while (prevlen > 0 && prev[prevlen - 1] == '\r')
1737 --prevlen;
1738 }
1739 if (prevlen == 0)
Bram Moolenaar71ccd032020-06-12 22:59:11 +02001740 s = vim_strnsave(start, len);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001741 else
1742 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001743 // Change "prev" buffer to be the right size. This way
1744 // the bytes are only copied once, and very long lines are
1745 // allocated only once.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001746 if ((s = vim_realloc(prev, prevlen + len + 1)) != NULL)
1747 {
1748 mch_memmove(s + prevlen, start, len);
1749 s[prevlen + len] = NUL;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001750 prev = NULL; // the list will own the string
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001751 prevlen = prevsize = 0;
1752 }
1753 }
1754 if (s == NULL)
1755 {
1756 do_outofmem_msg((long_u) prevlen + len + 1);
1757 failed = TRUE;
1758 break;
1759 }
1760
1761 if ((li = listitem_alloc()) == NULL)
1762 {
1763 vim_free(s);
1764 failed = TRUE;
1765 break;
1766 }
1767 li->li_tv.v_type = VAR_STRING;
1768 li->li_tv.v_lock = 0;
1769 li->li_tv.vval.v_string = s;
1770 list_append(rettv->vval.v_list, li);
1771
Bram Moolenaar26262f82019-09-04 20:59:15 +02001772 start = p + 1; // step over newline
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001773 if ((++cnt >= maxline && maxline >= 0) || readlen <= 0)
1774 break;
1775 }
1776 else if (*p == NUL)
1777 *p = '\n';
Bram Moolenaar26262f82019-09-04 20:59:15 +02001778 // Check for utf8 "bom"; U+FEFF is encoded as EF BB BF. Do this
1779 // when finding the BF and check the previous two bytes.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001780 else if (*p == 0xbf && enc_utf8 && !binary)
1781 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001782 // Find the two bytes before the 0xbf. If p is at buf, or buf
1783 // + 1, these may be in the "prev" string.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001784 char_u back1 = p >= buf + 1 ? p[-1]
1785 : prevlen >= 1 ? prev[prevlen - 1] : NUL;
1786 char_u back2 = p >= buf + 2 ? p[-2]
1787 : p == buf + 1 && prevlen >= 1 ? prev[prevlen - 1]
1788 : prevlen >= 2 ? prev[prevlen - 2] : NUL;
1789
1790 if (back2 == 0xef && back1 == 0xbb)
1791 {
1792 char_u *dest = p - 2;
1793
Bram Moolenaar26262f82019-09-04 20:59:15 +02001794 // Usually a BOM is at the beginning of a file, and so at
1795 // the beginning of a line; then we can just step over it.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001796 if (start == dest)
1797 start = p + 1;
1798 else
1799 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001800 // have to shuffle buf to close gap
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001801 int adjust_prevlen = 0;
1802
1803 if (dest < buf)
1804 {
Bram Moolenaarc423ad72021-01-13 20:38:03 +01001805 // must be 1 or 2
1806 adjust_prevlen = (int)(buf - dest);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001807 dest = buf;
1808 }
1809 if (readlen > p - buf + 1)
1810 mch_memmove(dest, p + 1, readlen - (p - buf) - 1);
1811 readlen -= 3 - adjust_prevlen;
1812 prevlen -= adjust_prevlen;
1813 p = dest - 1;
1814 }
1815 }
1816 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02001817 } // for
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001818
1819 if (failed || (cnt >= maxline && maxline >= 0) || readlen <= 0)
1820 break;
1821 if (start < p)
1822 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001823 // There's part of a line in buf, store it in "prev".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001824 if (p - start + prevlen >= prevsize)
1825 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001826 // need bigger "prev" buffer
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001827 char_u *newprev;
1828
Bram Moolenaar26262f82019-09-04 20:59:15 +02001829 // A common use case is ordinary text files and "prev" gets a
1830 // fragment of a line, so the first allocation is made
1831 // small, to avoid repeatedly 'allocing' large and
1832 // 'reallocing' small.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001833 if (prevsize == 0)
1834 prevsize = (long)(p - start);
1835 else
1836 {
1837 long grow50pc = (prevsize * 3) / 2;
1838 long growmin = (long)((p - start) * 2 + prevlen);
1839 prevsize = grow50pc > growmin ? grow50pc : growmin;
1840 }
1841 newprev = vim_realloc(prev, prevsize);
1842 if (newprev == NULL)
1843 {
1844 do_outofmem_msg((long_u)prevsize);
1845 failed = TRUE;
1846 break;
1847 }
1848 prev = newprev;
1849 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02001850 // Add the line part to end of "prev".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001851 mch_memmove(prev + prevlen, start, p - start);
1852 prevlen += (long)(p - start);
1853 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02001854 } // while
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001855
Bram Moolenaar26262f82019-09-04 20:59:15 +02001856 // For a negative line count use only the lines at the end of the file,
1857 // free the rest.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001858 if (!failed && maxline < 0)
1859 while (cnt > -maxline)
1860 {
1861 listitem_remove(rettv->vval.v_list, rettv->vval.v_list->lv_first);
1862 --cnt;
1863 }
1864
1865 if (failed)
1866 {
1867 // an empty list is returned on error
1868 list_free(rettv->vval.v_list);
1869 rettv_list_alloc(rettv);
1870 }
1871
1872 vim_free(prev);
1873 fclose(fd);
1874}
1875
1876/*
Bram Moolenaarc423ad72021-01-13 20:38:03 +01001877 * "readblob()" function
1878 */
1879 void
1880f_readblob(typval_T *argvars, typval_T *rettv)
1881{
1882 read_file_or_blob(argvars, rettv, TRUE);
1883}
1884
1885/*
1886 * "readfile()" function
1887 */
1888 void
1889f_readfile(typval_T *argvars, typval_T *rettv)
1890{
1891 read_file_or_blob(argvars, rettv, FALSE);
1892}
1893
1894/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001895 * "resolve()" function
1896 */
1897 void
1898f_resolve(typval_T *argvars, typval_T *rettv)
1899{
1900 char_u *p;
1901#ifdef HAVE_READLINK
1902 char_u *buf = NULL;
1903#endif
1904
1905 p = tv_get_string(&argvars[0]);
1906#ifdef FEAT_SHORTCUT
1907 {
1908 char_u *v = NULL;
1909
1910 v = mch_resolve_path(p, TRUE);
1911 if (v != NULL)
1912 rettv->vval.v_string = v;
1913 else
1914 rettv->vval.v_string = vim_strsave(p);
1915 }
1916#else
1917# ifdef HAVE_READLINK
1918 {
1919 char_u *cpy;
1920 int len;
1921 char_u *remain = NULL;
1922 char_u *q;
1923 int is_relative_to_current = FALSE;
1924 int has_trailing_pathsep = FALSE;
1925 int limit = 100;
1926
1927 p = vim_strsave(p);
Bram Moolenaar70188f52019-12-23 18:18:52 +01001928 if (p == NULL)
1929 goto fail;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001930 if (p[0] == '.' && (vim_ispathsep(p[1])
1931 || (p[1] == '.' && (vim_ispathsep(p[2])))))
1932 is_relative_to_current = TRUE;
1933
1934 len = STRLEN(p);
Bram Moolenaar50c4e9e2020-10-05 20:38:06 +02001935 if (len > 1 && after_pathsep(p, p + len))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001936 {
1937 has_trailing_pathsep = TRUE;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001938 p[len - 1] = NUL; // the trailing slash breaks readlink()
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001939 }
1940
1941 q = getnextcomp(p);
1942 if (*q != NUL)
1943 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001944 // Separate the first path component in "p", and keep the
1945 // remainder (beginning with the path separator).
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001946 remain = vim_strsave(q - 1);
1947 q[-1] = NUL;
1948 }
1949
1950 buf = alloc(MAXPATHL + 1);
1951 if (buf == NULL)
Bram Moolenaar70188f52019-12-23 18:18:52 +01001952 {
1953 vim_free(p);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001954 goto fail;
Bram Moolenaar70188f52019-12-23 18:18:52 +01001955 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001956
1957 for (;;)
1958 {
1959 for (;;)
1960 {
1961 len = readlink((char *)p, (char *)buf, MAXPATHL);
1962 if (len <= 0)
1963 break;
1964 buf[len] = NUL;
1965
1966 if (limit-- == 0)
1967 {
1968 vim_free(p);
1969 vim_free(remain);
1970 emsg(_("E655: Too many symbolic links (cycle?)"));
1971 rettv->vval.v_string = NULL;
1972 goto fail;
1973 }
1974
Bram Moolenaar26262f82019-09-04 20:59:15 +02001975 // Ensure that the result will have a trailing path separator
1976 // if the argument has one.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001977 if (remain == NULL && has_trailing_pathsep)
1978 add_pathsep(buf);
1979
Bram Moolenaar26262f82019-09-04 20:59:15 +02001980 // Separate the first path component in the link value and
1981 // concatenate the remainders.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001982 q = getnextcomp(vim_ispathsep(*buf) ? buf + 1 : buf);
1983 if (*q != NUL)
1984 {
1985 if (remain == NULL)
1986 remain = vim_strsave(q - 1);
1987 else
1988 {
1989 cpy = concat_str(q - 1, remain);
1990 if (cpy != NULL)
1991 {
1992 vim_free(remain);
1993 remain = cpy;
1994 }
1995 }
1996 q[-1] = NUL;
1997 }
1998
1999 q = gettail(p);
2000 if (q > p && *q == NUL)
2001 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002002 // Ignore trailing path separator.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002003 q[-1] = NUL;
2004 q = gettail(p);
2005 }
2006 if (q > p && !mch_isFullName(buf))
2007 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002008 // symlink is relative to directory of argument
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002009 cpy = alloc(STRLEN(p) + STRLEN(buf) + 1);
2010 if (cpy != NULL)
2011 {
2012 STRCPY(cpy, p);
2013 STRCPY(gettail(cpy), buf);
2014 vim_free(p);
2015 p = cpy;
2016 }
2017 }
2018 else
2019 {
2020 vim_free(p);
2021 p = vim_strsave(buf);
2022 }
2023 }
2024
2025 if (remain == NULL)
2026 break;
2027
Bram Moolenaar26262f82019-09-04 20:59:15 +02002028 // Append the first path component of "remain" to "p".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002029 q = getnextcomp(remain + 1);
2030 len = q - remain - (*q != NUL);
2031 cpy = vim_strnsave(p, STRLEN(p) + len);
2032 if (cpy != NULL)
2033 {
2034 STRNCAT(cpy, remain, len);
2035 vim_free(p);
2036 p = cpy;
2037 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02002038 // Shorten "remain".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002039 if (*q != NUL)
2040 STRMOVE(remain, q - 1);
2041 else
2042 VIM_CLEAR(remain);
2043 }
2044
Bram Moolenaar26262f82019-09-04 20:59:15 +02002045 // If the result is a relative path name, make it explicitly relative to
2046 // the current directory if and only if the argument had this form.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002047 if (!vim_ispathsep(*p))
2048 {
2049 if (is_relative_to_current
2050 && *p != NUL
2051 && !(p[0] == '.'
2052 && (p[1] == NUL
2053 || vim_ispathsep(p[1])
2054 || (p[1] == '.'
2055 && (p[2] == NUL
2056 || vim_ispathsep(p[2]))))))
2057 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002058 // Prepend "./".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002059 cpy = concat_str((char_u *)"./", p);
2060 if (cpy != NULL)
2061 {
2062 vim_free(p);
2063 p = cpy;
2064 }
2065 }
2066 else if (!is_relative_to_current)
2067 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002068 // Strip leading "./".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002069 q = p;
2070 while (q[0] == '.' && vim_ispathsep(q[1]))
2071 q += 2;
2072 if (q > p)
2073 STRMOVE(p, p + 2);
2074 }
2075 }
2076
Bram Moolenaar26262f82019-09-04 20:59:15 +02002077 // Ensure that the result will have no trailing path separator
2078 // if the argument had none. But keep "/" or "//".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002079 if (!has_trailing_pathsep)
2080 {
2081 q = p + STRLEN(p);
2082 if (after_pathsep(p, q))
2083 *gettail_sep(p) = NUL;
2084 }
2085
2086 rettv->vval.v_string = p;
2087 }
2088# else
2089 rettv->vval.v_string = vim_strsave(p);
2090# endif
2091#endif
2092
2093 simplify_filename(rettv->vval.v_string);
2094
2095#ifdef HAVE_READLINK
2096fail:
2097 vim_free(buf);
2098#endif
2099 rettv->v_type = VAR_STRING;
2100}
2101
2102/*
2103 * "tempname()" function
2104 */
2105 void
2106f_tempname(typval_T *argvars UNUSED, typval_T *rettv)
2107{
2108 static int x = 'A';
2109
2110 rettv->v_type = VAR_STRING;
2111 rettv->vval.v_string = vim_tempname(x, FALSE);
2112
Bram Moolenaar26262f82019-09-04 20:59:15 +02002113 // Advance 'x' to use A-Z and 0-9, so that there are at least 34 different
2114 // names. Skip 'I' and 'O', they are used for shell redirection.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002115 do
2116 {
2117 if (x == 'Z')
2118 x = '0';
2119 else if (x == '9')
2120 x = 'A';
2121 else
2122 {
2123#ifdef EBCDIC
2124 if (x == 'I')
2125 x = 'J';
2126 else if (x == 'R')
2127 x = 'S';
2128 else
2129#endif
2130 ++x;
2131 }
2132 } while (x == 'I' || x == 'O');
2133}
2134
2135/*
2136 * "writefile()" function
2137 */
2138 void
2139f_writefile(typval_T *argvars, typval_T *rettv)
2140{
2141 int binary = FALSE;
2142 int append = FALSE;
2143#ifdef HAVE_FSYNC
2144 int do_fsync = p_fs;
2145#endif
2146 char_u *fname;
2147 FILE *fd;
2148 int ret = 0;
2149 listitem_T *li;
2150 list_T *list = NULL;
2151 blob_T *blob = NULL;
2152
2153 rettv->vval.v_number = -1;
2154 if (check_secure())
2155 return;
2156
2157 if (argvars[0].v_type == VAR_LIST)
2158 {
2159 list = argvars[0].vval.v_list;
2160 if (list == NULL)
2161 return;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02002162 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002163 FOR_ALL_LIST_ITEMS(list, li)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002164 if (tv_get_string_chk(&li->li_tv) == NULL)
2165 return;
2166 }
2167 else if (argvars[0].v_type == VAR_BLOB)
2168 {
2169 blob = argvars[0].vval.v_blob;
2170 if (blob == NULL)
2171 return;
2172 }
2173 else
2174 {
Bram Moolenaar18a2b872020-03-19 13:08:45 +01002175 semsg(_(e_invarg2),
2176 _("writefile() first argument must be a List or a Blob"));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002177 return;
2178 }
2179
2180 if (argvars[2].v_type != VAR_UNKNOWN)
2181 {
2182 char_u *arg2 = tv_get_string_chk(&argvars[2]);
2183
2184 if (arg2 == NULL)
2185 return;
2186 if (vim_strchr(arg2, 'b') != NULL)
2187 binary = TRUE;
2188 if (vim_strchr(arg2, 'a') != NULL)
2189 append = TRUE;
2190#ifdef HAVE_FSYNC
2191 if (vim_strchr(arg2, 's') != NULL)
2192 do_fsync = TRUE;
2193 else if (vim_strchr(arg2, 'S') != NULL)
2194 do_fsync = FALSE;
2195#endif
2196 }
2197
2198 fname = tv_get_string_chk(&argvars[1]);
2199 if (fname == NULL)
2200 return;
2201
Bram Moolenaar26262f82019-09-04 20:59:15 +02002202 // Always open the file in binary mode, library functions have a mind of
2203 // their own about CR-LF conversion.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002204 if (*fname == NUL || (fd = mch_fopen((char *)fname,
2205 append ? APPENDBIN : WRITEBIN)) == NULL)
2206 {
2207 semsg(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
2208 ret = -1;
2209 }
2210 else if (blob)
2211 {
2212 if (write_blob(fd, blob) == FAIL)
2213 ret = -1;
2214#ifdef HAVE_FSYNC
2215 else if (do_fsync)
2216 // Ignore the error, the user wouldn't know what to do about it.
2217 // May happen for a device.
2218 vim_ignored = vim_fsync(fileno(fd));
2219#endif
2220 fclose(fd);
2221 }
2222 else
2223 {
2224 if (write_list(fd, list, binary) == FAIL)
2225 ret = -1;
2226#ifdef HAVE_FSYNC
2227 else if (do_fsync)
Bram Moolenaar26262f82019-09-04 20:59:15 +02002228 // Ignore the error, the user wouldn't know what to do about it.
2229 // May happen for a device.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002230 vim_ignored = vim_fsync(fileno(fd));
2231#endif
2232 fclose(fd);
2233 }
2234
2235 rettv->vval.v_number = ret;
2236}
2237
2238#endif // FEAT_EVAL
2239
2240#if defined(FEAT_BROWSE) || defined(PROTO)
2241/*
2242 * Generic browse function. Calls gui_mch_browse() when possible.
2243 * Later this may pop-up a non-GUI file selector (external command?).
2244 */
2245 char_u *
2246do_browse(
Bram Moolenaar26262f82019-09-04 20:59:15 +02002247 int flags, // BROWSE_SAVE and BROWSE_DIR
2248 char_u *title, // title for the window
2249 char_u *dflt, // default file name (may include directory)
2250 char_u *ext, // extension added
2251 char_u *initdir, // initial directory, NULL for current dir or
2252 // when using path from "dflt"
2253 char_u *filter, // file name filter
2254 buf_T *buf) // buffer to read/write for
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002255{
2256 char_u *fname;
Bram Moolenaar26262f82019-09-04 20:59:15 +02002257 static char_u *last_dir = NULL; // last used directory
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002258 char_u *tofree = NULL;
Bram Moolenaare1004402020-10-24 20:49:43 +02002259 int save_cmod_flags = cmdmod.cmod_flags;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002260
Bram Moolenaar26262f82019-09-04 20:59:15 +02002261 // Must turn off browse to avoid that autocommands will get the
2262 // flag too!
Bram Moolenaare1004402020-10-24 20:49:43 +02002263 cmdmod.cmod_flags &= ~CMOD_BROWSE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002264
2265 if (title == NULL || *title == NUL)
2266 {
2267 if (flags & BROWSE_DIR)
2268 title = (char_u *)_("Select Directory dialog");
2269 else if (flags & BROWSE_SAVE)
2270 title = (char_u *)_("Save File dialog");
2271 else
2272 title = (char_u *)_("Open File dialog");
2273 }
2274
Bram Moolenaar26262f82019-09-04 20:59:15 +02002275 // When no directory specified, use default file name, default dir, buffer
2276 // dir, last dir or current dir
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002277 if ((initdir == NULL || *initdir == NUL) && dflt != NULL && *dflt != NUL)
2278 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002279 if (mch_isdir(dflt)) // default file name is a directory
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002280 {
2281 initdir = dflt;
2282 dflt = NULL;
2283 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02002284 else if (gettail(dflt) != dflt) // default file name includes a path
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002285 {
2286 tofree = vim_strsave(dflt);
2287 if (tofree != NULL)
2288 {
2289 initdir = tofree;
2290 *gettail(initdir) = NUL;
2291 dflt = gettail(dflt);
2292 }
2293 }
2294 }
2295
2296 if (initdir == NULL || *initdir == NUL)
2297 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002298 // When 'browsedir' is a directory, use it
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002299 if (STRCMP(p_bsdir, "last") != 0
2300 && STRCMP(p_bsdir, "buffer") != 0
2301 && STRCMP(p_bsdir, "current") != 0
2302 && mch_isdir(p_bsdir))
2303 initdir = p_bsdir;
Bram Moolenaar26262f82019-09-04 20:59:15 +02002304 // When saving or 'browsedir' is "buffer", use buffer fname
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002305 else if (((flags & BROWSE_SAVE) || *p_bsdir == 'b')
2306 && buf != NULL && buf->b_ffname != NULL)
2307 {
2308 if (dflt == NULL || *dflt == NUL)
2309 dflt = gettail(curbuf->b_ffname);
2310 tofree = vim_strsave(curbuf->b_ffname);
2311 if (tofree != NULL)
2312 {
2313 initdir = tofree;
2314 *gettail(initdir) = NUL;
2315 }
2316 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02002317 // When 'browsedir' is "last", use dir from last browse
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002318 else if (*p_bsdir == 'l')
2319 initdir = last_dir;
Bram Moolenaar26262f82019-09-04 20:59:15 +02002320 // When 'browsedir is "current", use current directory. This is the
2321 // default already, leave initdir empty.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002322 }
2323
2324# ifdef FEAT_GUI
Bram Moolenaar26262f82019-09-04 20:59:15 +02002325 if (gui.in_use) // when this changes, also adjust f_has()!
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002326 {
2327 if (filter == NULL
2328# ifdef FEAT_EVAL
2329 && (filter = get_var_value((char_u *)"b:browsefilter")) == NULL
2330 && (filter = get_var_value((char_u *)"g:browsefilter")) == NULL
2331# endif
2332 )
2333 filter = BROWSE_FILTER_DEFAULT;
2334 if (flags & BROWSE_DIR)
2335 {
2336# if defined(FEAT_GUI_GTK) || defined(MSWIN)
Bram Moolenaar26262f82019-09-04 20:59:15 +02002337 // For systems that have a directory dialog.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002338 fname = gui_mch_browsedir(title, initdir);
2339# else
Bram Moolenaar26262f82019-09-04 20:59:15 +02002340 // Generic solution for selecting a directory: select a file and
2341 // remove the file name.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002342 fname = gui_mch_browse(0, title, dflt, ext, initdir, (char_u *)"");
2343# endif
2344# if !defined(FEAT_GUI_GTK)
Bram Moolenaar26262f82019-09-04 20:59:15 +02002345 // Win32 adds a dummy file name, others return an arbitrary file
2346 // name. GTK+ 2 returns only the directory,
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002347 if (fname != NULL && *fname != NUL && !mch_isdir(fname))
2348 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002349 // Remove the file name.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002350 char_u *tail = gettail_sep(fname);
2351
2352 if (tail == fname)
Bram Moolenaar26262f82019-09-04 20:59:15 +02002353 *tail++ = '.'; // use current dir
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002354 *tail = NUL;
2355 }
2356# endif
2357 }
2358 else
2359 fname = gui_mch_browse(flags & BROWSE_SAVE,
2360 title, dflt, ext, initdir, (char_u *)_(filter));
2361
Bram Moolenaar26262f82019-09-04 20:59:15 +02002362 // We hang around in the dialog for a while, the user might do some
2363 // things to our files. The Win32 dialog allows deleting or renaming
2364 // a file, check timestamps.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002365 need_check_timestamps = TRUE;
2366 did_check_timestamps = FALSE;
2367 }
2368 else
2369# endif
2370 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002371 // TODO: non-GUI file selector here
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002372 emsg(_("E338: Sorry, no file browser in console mode"));
2373 fname = NULL;
2374 }
2375
Bram Moolenaar26262f82019-09-04 20:59:15 +02002376 // keep the directory for next time
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002377 if (fname != NULL)
2378 {
2379 vim_free(last_dir);
2380 last_dir = vim_strsave(fname);
2381 if (last_dir != NULL && !(flags & BROWSE_DIR))
2382 {
2383 *gettail(last_dir) = NUL;
2384 if (*last_dir == NUL)
2385 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002386 // filename only returned, must be in current dir
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002387 vim_free(last_dir);
2388 last_dir = alloc(MAXPATHL);
2389 if (last_dir != NULL)
2390 mch_dirname(last_dir, MAXPATHL);
2391 }
2392 }
2393 }
2394
2395 vim_free(tofree);
Bram Moolenaare1004402020-10-24 20:49:43 +02002396 cmdmod.cmod_flags = save_cmod_flags;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002397
2398 return fname;
2399}
2400#endif
2401
2402#if defined(FEAT_EVAL) || defined(PROTO)
2403
2404/*
2405 * "browse(save, title, initdir, default)" function
2406 */
2407 void
2408f_browse(typval_T *argvars UNUSED, typval_T *rettv)
2409{
2410# ifdef FEAT_BROWSE
2411 int save;
2412 char_u *title;
2413 char_u *initdir;
2414 char_u *defname;
2415 char_u buf[NUMBUFLEN];
2416 char_u buf2[NUMBUFLEN];
2417 int error = FALSE;
2418
Bram Moolenaarf28f2ac2021-03-22 22:21:26 +01002419 if (in_vim9script()
Bram Moolenaar32105ae2021-03-27 18:59:25 +01002420 && (check_for_string_arg(argvars, 1) == FAIL
2421 || check_for_string_arg(argvars, 2) == FAIL
2422 || check_for_string_arg(argvars, 3) == FAIL))
Bram Moolenaarf28f2ac2021-03-22 22:21:26 +01002423 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002424 save = (int)tv_get_number_chk(&argvars[0], &error);
2425 title = tv_get_string_chk(&argvars[1]);
2426 initdir = tv_get_string_buf_chk(&argvars[2], buf);
2427 defname = tv_get_string_buf_chk(&argvars[3], buf2);
2428
2429 if (error || title == NULL || initdir == NULL || defname == NULL)
2430 rettv->vval.v_string = NULL;
2431 else
2432 rettv->vval.v_string =
2433 do_browse(save ? BROWSE_SAVE : 0,
2434 title, defname, NULL, initdir, NULL, curbuf);
2435# else
2436 rettv->vval.v_string = NULL;
2437# endif
2438 rettv->v_type = VAR_STRING;
2439}
2440
2441/*
2442 * "browsedir(title, initdir)" function
2443 */
2444 void
2445f_browsedir(typval_T *argvars UNUSED, typval_T *rettv)
2446{
2447# ifdef FEAT_BROWSE
2448 char_u *title;
2449 char_u *initdir;
2450 char_u buf[NUMBUFLEN];
2451
2452 title = tv_get_string_chk(&argvars[0]);
2453 initdir = tv_get_string_buf_chk(&argvars[1], buf);
2454
2455 if (title == NULL || initdir == NULL)
2456 rettv->vval.v_string = NULL;
2457 else
2458 rettv->vval.v_string = do_browse(BROWSE_DIR,
2459 title, NULL, NULL, initdir, NULL, curbuf);
2460# else
2461 rettv->vval.v_string = NULL;
2462# endif
2463 rettv->v_type = VAR_STRING;
2464}
2465
2466#endif // FEAT_EVAL
Bram Moolenaar26262f82019-09-04 20:59:15 +02002467
2468/*
2469 * Replace home directory by "~" in each space or comma separated file name in
2470 * 'src'.
2471 * If anything fails (except when out of space) dst equals src.
2472 */
2473 void
2474home_replace(
2475 buf_T *buf, // when not NULL, check for help files
2476 char_u *src, // input file name
2477 char_u *dst, // where to put the result
2478 int dstlen, // maximum length of the result
2479 int one) // if TRUE, only replace one file name, include
2480 // spaces and commas in the file name.
2481{
2482 size_t dirlen = 0, envlen = 0;
2483 size_t len;
2484 char_u *homedir_env, *homedir_env_orig;
2485 char_u *p;
2486
2487 if (src == NULL)
2488 {
2489 *dst = NUL;
2490 return;
2491 }
2492
2493 /*
2494 * If the file is a help file, remove the path completely.
2495 */
2496 if (buf != NULL && buf->b_help)
2497 {
2498 vim_snprintf((char *)dst, dstlen, "%s", gettail(src));
2499 return;
2500 }
2501
2502 /*
2503 * We check both the value of the $HOME environment variable and the
2504 * "real" home directory.
2505 */
2506 if (homedir != NULL)
2507 dirlen = STRLEN(homedir);
2508
2509#ifdef VMS
2510 homedir_env_orig = homedir_env = mch_getenv((char_u *)"SYS$LOGIN");
2511#else
2512 homedir_env_orig = homedir_env = mch_getenv((char_u *)"HOME");
2513#endif
2514#ifdef MSWIN
2515 if (homedir_env == NULL)
2516 homedir_env_orig = homedir_env = mch_getenv((char_u *)"USERPROFILE");
2517#endif
2518 // Empty is the same as not set.
2519 if (homedir_env != NULL && *homedir_env == NUL)
2520 homedir_env = NULL;
2521
2522 if (homedir_env != NULL && *homedir_env == '~')
2523 {
2524 int usedlen = 0;
2525 int flen;
2526 char_u *fbuf = NULL;
2527
2528 flen = (int)STRLEN(homedir_env);
2529 (void)modify_fname((char_u *)":p", FALSE, &usedlen,
2530 &homedir_env, &fbuf, &flen);
2531 flen = (int)STRLEN(homedir_env);
2532 if (flen > 0 && vim_ispathsep(homedir_env[flen - 1]))
2533 // Remove the trailing / that is added to a directory.
2534 homedir_env[flen - 1] = NUL;
2535 }
2536
2537 if (homedir_env != NULL)
2538 envlen = STRLEN(homedir_env);
2539
2540 if (!one)
2541 src = skipwhite(src);
2542 while (*src && dstlen > 0)
2543 {
2544 /*
2545 * Here we are at the beginning of a file name.
2546 * First, check to see if the beginning of the file name matches
2547 * $HOME or the "real" home directory. Check that there is a '/'
2548 * after the match (so that if e.g. the file is "/home/pieter/bla",
2549 * and the home directory is "/home/piet", the file does not end up
2550 * as "~er/bla" (which would seem to indicate the file "bla" in user
2551 * er's home directory)).
2552 */
2553 p = homedir;
2554 len = dirlen;
2555 for (;;)
2556 {
2557 if ( len
2558 && fnamencmp(src, p, len) == 0
2559 && (vim_ispathsep(src[len])
2560 || (!one && (src[len] == ',' || src[len] == ' '))
2561 || src[len] == NUL))
2562 {
2563 src += len;
2564 if (--dstlen > 0)
2565 *dst++ = '~';
2566
Bram Moolenaar0e390f42020-06-10 13:12:28 +02002567 // Do not add directory separator into dst, because dst is
2568 // expected to just return the directory name without the
2569 // directory separator '/'.
Bram Moolenaar26262f82019-09-04 20:59:15 +02002570 break;
2571 }
2572 if (p == homedir_env)
2573 break;
2574 p = homedir_env;
2575 len = envlen;
2576 }
2577
2578 // if (!one) skip to separator: space or comma
2579 while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0)
2580 *dst++ = *src++;
2581 // skip separator
2582 while ((*src == ' ' || *src == ',') && --dstlen > 0)
2583 *dst++ = *src++;
2584 }
2585 // if (dstlen == 0) out of space, what to do???
2586
2587 *dst = NUL;
2588
2589 if (homedir_env != homedir_env_orig)
2590 vim_free(homedir_env);
2591}
2592
2593/*
2594 * Like home_replace, store the replaced string in allocated memory.
2595 * When something fails, NULL is returned.
2596 */
2597 char_u *
2598home_replace_save(
2599 buf_T *buf, // when not NULL, check for help files
2600 char_u *src) // input file name
2601{
2602 char_u *dst;
2603 unsigned len;
2604
2605 len = 3; // space for "~/" and trailing NUL
2606 if (src != NULL) // just in case
2607 len += (unsigned)STRLEN(src);
2608 dst = alloc(len);
2609 if (dst != NULL)
2610 home_replace(buf, src, dst, len, TRUE);
2611 return dst;
2612}
2613
2614/*
2615 * Compare two file names and return:
2616 * FPC_SAME if they both exist and are the same file.
2617 * FPC_SAMEX if they both don't exist and have the same file name.
2618 * FPC_DIFF if they both exist and are different files.
2619 * FPC_NOTX if they both don't exist.
2620 * FPC_DIFFX if one of them doesn't exist.
2621 * For the first name environment variables are expanded if "expandenv" is
2622 * TRUE.
2623 */
2624 int
2625fullpathcmp(
2626 char_u *s1,
2627 char_u *s2,
2628 int checkname, // when both don't exist, check file names
2629 int expandenv)
2630{
2631#ifdef UNIX
2632 char_u exp1[MAXPATHL];
2633 char_u full1[MAXPATHL];
2634 char_u full2[MAXPATHL];
2635 stat_T st1, st2;
2636 int r1, r2;
2637
2638 if (expandenv)
2639 expand_env(s1, exp1, MAXPATHL);
2640 else
2641 vim_strncpy(exp1, s1, MAXPATHL - 1);
2642 r1 = mch_stat((char *)exp1, &st1);
2643 r2 = mch_stat((char *)s2, &st2);
2644 if (r1 != 0 && r2 != 0)
2645 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002646 // if mch_stat() doesn't work, may compare the names
Bram Moolenaar26262f82019-09-04 20:59:15 +02002647 if (checkname)
2648 {
2649 if (fnamecmp(exp1, s2) == 0)
2650 return FPC_SAMEX;
2651 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
2652 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
2653 if (r1 == OK && r2 == OK && fnamecmp(full1, full2) == 0)
2654 return FPC_SAMEX;
2655 }
2656 return FPC_NOTX;
2657 }
2658 if (r1 != 0 || r2 != 0)
2659 return FPC_DIFFX;
2660 if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
2661 return FPC_SAME;
2662 return FPC_DIFF;
2663#else
2664 char_u *exp1; // expanded s1
2665 char_u *full1; // full path of s1
2666 char_u *full2; // full path of s2
2667 int retval = FPC_DIFF;
2668 int r1, r2;
2669
2670 // allocate one buffer to store three paths (alloc()/free() is slow!)
2671 if ((exp1 = alloc(MAXPATHL * 3)) != NULL)
2672 {
2673 full1 = exp1 + MAXPATHL;
2674 full2 = full1 + MAXPATHL;
2675
2676 if (expandenv)
2677 expand_env(s1, exp1, MAXPATHL);
2678 else
2679 vim_strncpy(exp1, s1, MAXPATHL - 1);
2680 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
2681 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
2682
2683 // If vim_FullName() fails, the file probably doesn't exist.
2684 if (r1 != OK && r2 != OK)
2685 {
2686 if (checkname && fnamecmp(exp1, s2) == 0)
2687 retval = FPC_SAMEX;
2688 else
2689 retval = FPC_NOTX;
2690 }
2691 else if (r1 != OK || r2 != OK)
2692 retval = FPC_DIFFX;
2693 else if (fnamecmp(full1, full2))
2694 retval = FPC_DIFF;
2695 else
2696 retval = FPC_SAME;
2697 vim_free(exp1);
2698 }
2699 return retval;
2700#endif
2701}
2702
2703/*
2704 * Get the tail of a path: the file name.
2705 * When the path ends in a path separator the tail is the NUL after it.
2706 * Fail safe: never returns NULL.
2707 */
2708 char_u *
2709gettail(char_u *fname)
2710{
2711 char_u *p1, *p2;
2712
2713 if (fname == NULL)
2714 return (char_u *)"";
2715 for (p1 = p2 = get_past_head(fname); *p2; ) // find last part of path
2716 {
2717 if (vim_ispathsep_nocolon(*p2))
2718 p1 = p2 + 1;
2719 MB_PTR_ADV(p2);
2720 }
2721 return p1;
2722}
2723
2724/*
2725 * Get pointer to tail of "fname", including path separators. Putting a NUL
2726 * here leaves the directory name. Takes care of "c:/" and "//".
2727 * Always returns a valid pointer.
2728 */
2729 char_u *
2730gettail_sep(char_u *fname)
2731{
2732 char_u *p;
2733 char_u *t;
2734
2735 p = get_past_head(fname); // don't remove the '/' from "c:/file"
2736 t = gettail(fname);
2737 while (t > p && after_pathsep(fname, t))
2738 --t;
2739#ifdef VMS
2740 // path separator is part of the path
2741 ++t;
2742#endif
2743 return t;
2744}
2745
2746/*
2747 * get the next path component (just after the next path separator).
2748 */
2749 char_u *
2750getnextcomp(char_u *fname)
2751{
2752 while (*fname && !vim_ispathsep(*fname))
2753 MB_PTR_ADV(fname);
2754 if (*fname)
2755 ++fname;
2756 return fname;
2757}
2758
2759/*
2760 * Get a pointer to one character past the head of a path name.
2761 * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
2762 * If there is no head, path is returned.
2763 */
2764 char_u *
2765get_past_head(char_u *path)
2766{
2767 char_u *retval;
2768
2769#if defined(MSWIN)
2770 // may skip "c:"
2771 if (isalpha(path[0]) && path[1] == ':')
2772 retval = path + 2;
2773 else
2774 retval = path;
2775#else
2776# if defined(AMIGA)
2777 // may skip "label:"
2778 retval = vim_strchr(path, ':');
2779 if (retval == NULL)
2780 retval = path;
2781# else // Unix
2782 retval = path;
2783# endif
2784#endif
2785
2786 while (vim_ispathsep(*retval))
2787 ++retval;
2788
2789 return retval;
2790}
2791
2792/*
2793 * Return TRUE if 'c' is a path separator.
2794 * Note that for MS-Windows this includes the colon.
2795 */
2796 int
2797vim_ispathsep(int c)
2798{
2799#ifdef UNIX
2800 return (c == '/'); // UNIX has ':' inside file names
2801#else
2802# ifdef BACKSLASH_IN_FILENAME
2803 return (c == ':' || c == '/' || c == '\\');
2804# else
2805# ifdef VMS
2806 // server"user passwd"::device:[full.path.name]fname.extension;version"
2807 return (c == ':' || c == '[' || c == ']' || c == '/'
2808 || c == '<' || c == '>' || c == '"' );
2809# else
2810 return (c == ':' || c == '/');
2811# endif // VMS
2812# endif
2813#endif
2814}
2815
2816/*
2817 * Like vim_ispathsep(c), but exclude the colon for MS-Windows.
2818 */
2819 int
2820vim_ispathsep_nocolon(int c)
2821{
2822 return vim_ispathsep(c)
2823#ifdef BACKSLASH_IN_FILENAME
2824 && c != ':'
2825#endif
2826 ;
2827}
2828
2829/*
Bram Moolenaar26262f82019-09-04 20:59:15 +02002830 * Return TRUE if the directory of "fname" exists, FALSE otherwise.
2831 * Also returns TRUE if there is no directory name.
2832 * "fname" must be writable!.
2833 */
2834 int
2835dir_of_file_exists(char_u *fname)
2836{
2837 char_u *p;
2838 int c;
2839 int retval;
2840
2841 p = gettail_sep(fname);
2842 if (p == fname)
2843 return TRUE;
2844 c = *p;
2845 *p = NUL;
2846 retval = mch_isdir(fname);
2847 *p = c;
2848 return retval;
2849}
2850
2851/*
2852 * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally
2853 * and deal with 'fileignorecase'.
2854 */
2855 int
2856vim_fnamecmp(char_u *x, char_u *y)
2857{
2858#ifdef BACKSLASH_IN_FILENAME
2859 return vim_fnamencmp(x, y, MAXPATHL);
2860#else
2861 if (p_fic)
2862 return MB_STRICMP(x, y);
2863 return STRCMP(x, y);
2864#endif
2865}
2866
2867 int
2868vim_fnamencmp(char_u *x, char_u *y, size_t len)
2869{
2870#ifdef BACKSLASH_IN_FILENAME
2871 char_u *px = x;
2872 char_u *py = y;
2873 int cx = NUL;
2874 int cy = NUL;
2875
2876 while (len > 0)
2877 {
2878 cx = PTR2CHAR(px);
2879 cy = PTR2CHAR(py);
2880 if (cx == NUL || cy == NUL
2881 || ((p_fic ? MB_TOLOWER(cx) != MB_TOLOWER(cy) : cx != cy)
2882 && !(cx == '/' && cy == '\\')
2883 && !(cx == '\\' && cy == '/')))
2884 break;
Bram Moolenaar1614a142019-10-06 22:00:13 +02002885 len -= mb_ptr2len(px);
2886 px += mb_ptr2len(px);
2887 py += mb_ptr2len(py);
Bram Moolenaar26262f82019-09-04 20:59:15 +02002888 }
2889 if (len == 0)
2890 return 0;
2891 return (cx - cy);
2892#else
2893 if (p_fic)
2894 return MB_STRNICMP(x, y, len);
2895 return STRNCMP(x, y, len);
2896#endif
2897}
2898
2899/*
2900 * Concatenate file names fname1 and fname2 into allocated memory.
2901 * Only add a '/' or '\\' when 'sep' is TRUE and it is necessary.
2902 */
2903 char_u *
2904concat_fnames(char_u *fname1, char_u *fname2, int sep)
2905{
2906 char_u *dest;
2907
2908 dest = alloc(STRLEN(fname1) + STRLEN(fname2) + 3);
2909 if (dest != NULL)
2910 {
2911 STRCPY(dest, fname1);
2912 if (sep)
2913 add_pathsep(dest);
2914 STRCAT(dest, fname2);
2915 }
2916 return dest;
2917}
2918
2919/*
2920 * Add a path separator to a file name, unless it already ends in a path
2921 * separator.
2922 */
2923 void
2924add_pathsep(char_u *p)
2925{
2926 if (*p != NUL && !after_pathsep(p, p + STRLEN(p)))
2927 STRCAT(p, PATHSEPSTR);
2928}
2929
2930/*
2931 * FullName_save - Make an allocated copy of a full file name.
2932 * Returns NULL when out of memory.
2933 */
2934 char_u *
2935FullName_save(
2936 char_u *fname,
2937 int force) // force expansion, even when it already looks
2938 // like a full path name
2939{
2940 char_u *buf;
2941 char_u *new_fname = NULL;
2942
2943 if (fname == NULL)
2944 return NULL;
2945
2946 buf = alloc(MAXPATHL);
2947 if (buf != NULL)
2948 {
2949 if (vim_FullName(fname, buf, MAXPATHL, force) != FAIL)
2950 new_fname = vim_strsave(buf);
2951 else
2952 new_fname = vim_strsave(fname);
2953 vim_free(buf);
2954 }
2955 return new_fname;
2956}
2957
2958/*
2959 * return TRUE if "fname" exists.
2960 */
2961 int
2962vim_fexists(char_u *fname)
2963{
2964 stat_T st;
2965
2966 if (mch_stat((char *)fname, &st))
2967 return FALSE;
2968 return TRUE;
2969}
2970
2971/*
2972 * Invoke expand_wildcards() for one pattern.
2973 * Expand items like "%:h" before the expansion.
2974 * Returns OK or FAIL.
2975 */
2976 int
2977expand_wildcards_eval(
2978 char_u **pat, // pointer to input pattern
2979 int *num_file, // resulting number of files
2980 char_u ***file, // array of resulting files
2981 int flags) // EW_DIR, etc.
2982{
2983 int ret = FAIL;
2984 char_u *eval_pat = NULL;
2985 char_u *exp_pat = *pat;
2986 char *ignored_msg;
2987 int usedlen;
2988
2989 if (*exp_pat == '%' || *exp_pat == '#' || *exp_pat == '<')
2990 {
2991 ++emsg_off;
2992 eval_pat = eval_vars(exp_pat, exp_pat, &usedlen,
2993 NULL, &ignored_msg, NULL);
2994 --emsg_off;
2995 if (eval_pat != NULL)
2996 exp_pat = concat_str(eval_pat, exp_pat + usedlen);
2997 }
2998
2999 if (exp_pat != NULL)
3000 ret = expand_wildcards(1, &exp_pat, num_file, file, flags);
3001
3002 if (eval_pat != NULL)
3003 {
3004 vim_free(exp_pat);
3005 vim_free(eval_pat);
3006 }
3007
3008 return ret;
3009}
3010
3011/*
3012 * Expand wildcards. Calls gen_expand_wildcards() and removes files matching
3013 * 'wildignore'.
3014 * Returns OK or FAIL. When FAIL then "num_files" won't be set.
3015 */
3016 int
3017expand_wildcards(
3018 int num_pat, // number of input patterns
3019 char_u **pat, // array of input patterns
3020 int *num_files, // resulting number of files
3021 char_u ***files, // array of resulting files
3022 int flags) // EW_DIR, etc.
3023{
3024 int retval;
3025 int i, j;
3026 char_u *p;
3027 int non_suf_match; // number without matching suffix
3028
3029 retval = gen_expand_wildcards(num_pat, pat, num_files, files, flags);
3030
3031 // When keeping all matches, return here
3032 if ((flags & EW_KEEPALL) || retval == FAIL)
3033 return retval;
3034
3035#ifdef FEAT_WILDIGN
3036 /*
3037 * Remove names that match 'wildignore'.
3038 */
3039 if (*p_wig)
3040 {
3041 char_u *ffname;
3042
3043 // check all files in (*files)[]
3044 for (i = 0; i < *num_files; ++i)
3045 {
3046 ffname = FullName_save((*files)[i], FALSE);
3047 if (ffname == NULL) // out of memory
3048 break;
3049# ifdef VMS
3050 vms_remove_version(ffname);
3051# endif
3052 if (match_file_list(p_wig, (*files)[i], ffname))
3053 {
3054 // remove this matching file from the list
3055 vim_free((*files)[i]);
3056 for (j = i; j + 1 < *num_files; ++j)
3057 (*files)[j] = (*files)[j + 1];
3058 --*num_files;
3059 --i;
3060 }
3061 vim_free(ffname);
3062 }
3063
3064 // If the number of matches is now zero, we fail.
3065 if (*num_files == 0)
3066 {
3067 VIM_CLEAR(*files);
3068 return FAIL;
3069 }
3070 }
3071#endif
3072
3073 /*
3074 * Move the names where 'suffixes' match to the end.
3075 */
3076 if (*num_files > 1)
3077 {
3078 non_suf_match = 0;
3079 for (i = 0; i < *num_files; ++i)
3080 {
3081 if (!match_suffix((*files)[i]))
3082 {
3083 /*
3084 * Move the name without matching suffix to the front
3085 * of the list.
3086 */
3087 p = (*files)[i];
3088 for (j = i; j > non_suf_match; --j)
3089 (*files)[j] = (*files)[j - 1];
3090 (*files)[non_suf_match++] = p;
3091 }
3092 }
3093 }
3094
3095 return retval;
3096}
3097
3098/*
3099 * Return TRUE if "fname" matches with an entry in 'suffixes'.
3100 */
3101 int
3102match_suffix(char_u *fname)
3103{
3104 int fnamelen, setsuflen;
3105 char_u *setsuf;
3106#define MAXSUFLEN 30 // maximum length of a file suffix
3107 char_u suf_buf[MAXSUFLEN];
3108
3109 fnamelen = (int)STRLEN(fname);
3110 setsuflen = 0;
3111 for (setsuf = p_su; *setsuf; )
3112 {
3113 setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
3114 if (setsuflen == 0)
3115 {
3116 char_u *tail = gettail(fname);
3117
3118 // empty entry: match name without a '.'
3119 if (vim_strchr(tail, '.') == NULL)
3120 {
3121 setsuflen = 1;
3122 break;
3123 }
3124 }
3125 else
3126 {
3127 if (fnamelen >= setsuflen
3128 && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
3129 (size_t)setsuflen) == 0)
3130 break;
3131 setsuflen = 0;
3132 }
3133 }
3134 return (setsuflen != 0);
3135}
3136
3137#ifdef VIM_BACKTICK
3138
3139/*
3140 * Return TRUE if we can expand this backtick thing here.
3141 */
3142 static int
3143vim_backtick(char_u *p)
3144{
3145 return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
3146}
3147
3148/*
3149 * Expand an item in `backticks` by executing it as a command.
3150 * Currently only works when pat[] starts and ends with a `.
3151 * Returns number of file names found, -1 if an error is encountered.
3152 */
3153 static int
3154expand_backtick(
3155 garray_T *gap,
3156 char_u *pat,
3157 int flags) // EW_* flags
3158{
3159 char_u *p;
3160 char_u *cmd;
3161 char_u *buffer;
3162 int cnt = 0;
3163 int i;
3164
3165 // Create the command: lop off the backticks.
Bram Moolenaar71ccd032020-06-12 22:59:11 +02003166 cmd = vim_strnsave(pat + 1, STRLEN(pat) - 2);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003167 if (cmd == NULL)
3168 return -1;
3169
3170#ifdef FEAT_EVAL
3171 if (*cmd == '=') // `={expr}`: Expand expression
Bram Moolenaarb171fb12020-06-24 20:34:03 +02003172 buffer = eval_to_string(cmd + 1, TRUE);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003173 else
3174#endif
3175 buffer = get_cmd_output(cmd, NULL,
3176 (flags & EW_SILENT) ? SHELL_SILENT : 0, NULL);
3177 vim_free(cmd);
3178 if (buffer == NULL)
3179 return -1;
3180
3181 cmd = buffer;
3182 while (*cmd != NUL)
3183 {
3184 cmd = skipwhite(cmd); // skip over white space
3185 p = cmd;
3186 while (*p != NUL && *p != '\r' && *p != '\n') // skip over entry
3187 ++p;
3188 // add an entry if it is not empty
3189 if (p > cmd)
3190 {
3191 i = *p;
3192 *p = NUL;
3193 addfile(gap, cmd, flags);
3194 *p = i;
3195 ++cnt;
3196 }
3197 cmd = p;
3198 while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
3199 ++cmd;
3200 }
3201
3202 vim_free(buffer);
3203 return cnt;
3204}
3205#endif // VIM_BACKTICK
3206
3207#if defined(MSWIN)
3208/*
3209 * File name expansion code for MS-DOS, Win16 and Win32. It's here because
3210 * it's shared between these systems.
3211 */
3212
3213/*
3214 * comparison function for qsort in dos_expandpath()
3215 */
3216 static int
3217pstrcmp(const void *a, const void *b)
3218{
3219 return (pathcmp(*(char **)a, *(char **)b, -1));
3220}
3221
3222/*
3223 * Recursively expand one path component into all matching files and/or
3224 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
3225 * Return the number of matches found.
3226 * "path" has backslashes before chars that are not to be expanded, starting
3227 * at "path[wildoff]".
3228 * Return the number of matches found.
3229 * NOTE: much of this is identical to unix_expandpath(), keep in sync!
3230 */
3231 static int
3232dos_expandpath(
3233 garray_T *gap,
3234 char_u *path,
3235 int wildoff,
3236 int flags, // EW_* flags
3237 int didstar) // expanded "**" once already
3238{
3239 char_u *buf;
3240 char_u *path_end;
3241 char_u *p, *s, *e;
3242 int start_len = gap->ga_len;
3243 char_u *pat;
3244 regmatch_T regmatch;
3245 int starts_with_dot;
3246 int matches;
3247 int len;
3248 int starstar = FALSE;
3249 static int stardepth = 0; // depth for "**" expansion
3250 HANDLE hFind = INVALID_HANDLE_VALUE;
3251 WIN32_FIND_DATAW wfb;
3252 WCHAR *wn = NULL; // UCS-2 name, NULL when not used.
3253 char_u *matchname;
3254 int ok;
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003255 char_u *p_alt;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003256
3257 // Expanding "**" may take a long time, check for CTRL-C.
3258 if (stardepth > 0)
3259 {
3260 ui_breakcheck();
3261 if (got_int)
3262 return 0;
3263 }
3264
3265 // Make room for file name. When doing encoding conversion the actual
3266 // length may be quite a bit longer, thus use the maximum possible length.
3267 buf = alloc(MAXPATHL);
3268 if (buf == NULL)
3269 return 0;
3270
3271 /*
3272 * Find the first part in the path name that contains a wildcard or a ~1.
3273 * Copy it into buf, including the preceding characters.
3274 */
3275 p = buf;
3276 s = buf;
3277 e = NULL;
3278 path_end = path;
3279 while (*path_end != NUL)
3280 {
3281 // May ignore a wildcard that has a backslash before it; it will
3282 // be removed by rem_backslash() or file_pat_to_reg_pat() below.
3283 if (path_end >= path + wildoff && rem_backslash(path_end))
3284 *p++ = *path_end++;
3285 else if (*path_end == '\\' || *path_end == ':' || *path_end == '/')
3286 {
3287 if (e != NULL)
3288 break;
3289 s = p + 1;
3290 }
3291 else if (path_end >= path + wildoff
3292 && vim_strchr((char_u *)"*?[~", *path_end) != NULL)
3293 e = p;
3294 if (has_mbyte)
3295 {
3296 len = (*mb_ptr2len)(path_end);
3297 STRNCPY(p, path_end, len);
3298 p += len;
3299 path_end += len;
3300 }
3301 else
3302 *p++ = *path_end++;
3303 }
3304 e = p;
3305 *e = NUL;
3306
3307 // now we have one wildcard component between s and e
3308 // Remove backslashes between "wildoff" and the start of the wildcard
3309 // component.
3310 for (p = buf + wildoff; p < s; ++p)
3311 if (rem_backslash(p))
3312 {
3313 STRMOVE(p, p + 1);
3314 --e;
3315 --s;
3316 }
3317
3318 // Check for "**" between "s" and "e".
3319 for (p = s; p < e; ++p)
3320 if (p[0] == '*' && p[1] == '*')
3321 starstar = TRUE;
3322
3323 starts_with_dot = *s == '.';
3324 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
3325 if (pat == NULL)
3326 {
3327 vim_free(buf);
3328 return 0;
3329 }
3330
3331 // compile the regexp into a program
3332 if (flags & (EW_NOERROR | EW_NOTWILD))
3333 ++emsg_silent;
3334 regmatch.rm_ic = TRUE; // Always ignore case
3335 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
3336 if (flags & (EW_NOERROR | EW_NOTWILD))
3337 --emsg_silent;
3338 vim_free(pat);
3339
3340 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
3341 {
3342 vim_free(buf);
3343 return 0;
3344 }
3345
3346 // remember the pattern or file name being looked for
3347 matchname = vim_strsave(s);
3348
3349 // If "**" is by itself, this is the first time we encounter it and more
3350 // is following then find matches without any directory.
3351 if (!didstar && stardepth < 100 && starstar && e - s == 2
3352 && *path_end == '/')
3353 {
3354 STRCPY(s, path_end + 1);
3355 ++stardepth;
3356 (void)dos_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
3357 --stardepth;
3358 }
3359
3360 // Scan all files in the directory with "dir/ *.*"
3361 STRCPY(s, "*.*");
3362 wn = enc_to_utf16(buf, NULL);
3363 if (wn != NULL)
3364 hFind = FindFirstFileW(wn, &wfb);
3365 ok = (hFind != INVALID_HANDLE_VALUE);
3366
3367 while (ok)
3368 {
3369 p = utf16_to_enc(wfb.cFileName, NULL); // p is allocated here
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003370
Bram Moolenaar26262f82019-09-04 20:59:15 +02003371 if (p == NULL)
3372 break; // out of memory
3373
Bram Moolenaar0dc5f602021-02-07 14:01:35 +01003374 // Do not use the alternate filename when the file name ends in '~',
3375 // because it picks up backup files: short name for "foo.vim~" is
3376 // "foo~1.vim", which matches "*.vim".
3377 if (*wfb.cAlternateFileName == NUL || p[STRLEN(p) - 1] == '~')
Bram Moolenaar40655d52020-04-06 23:49:50 +02003378 p_alt = NULL;
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003379 else
3380 p_alt = utf16_to_enc(wfb.cAlternateFileName, NULL);
3381
Bram Moolenaar26262f82019-09-04 20:59:15 +02003382 // Ignore entries starting with a dot, unless when asked for. Accept
3383 // all entries found with "matchname".
3384 if ((p[0] != '.' || starts_with_dot
3385 || ((flags & EW_DODOT)
3386 && p[1] != NUL && (p[1] != '.' || p[2] != NUL)))
3387 && (matchname == NULL
3388 || (regmatch.regprog != NULL
Bram Moolenaar40655d52020-04-06 23:49:50 +02003389 && (vim_regexec(&regmatch, p, (colnr_T)0)
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003390 || (p_alt != NULL
Bram Moolenaar40655d52020-04-06 23:49:50 +02003391 && vim_regexec(&regmatch, p_alt, (colnr_T)0))))
Bram Moolenaar26262f82019-09-04 20:59:15 +02003392 || ((flags & EW_NOTWILD)
3393 && fnamencmp(path + (s - buf), p, e - s) == 0)))
3394 {
3395 STRCPY(s, p);
3396 len = (int)STRLEN(buf);
3397
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003398 if (starstar && stardepth < 100
3399 && (wfb.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
Bram Moolenaar26262f82019-09-04 20:59:15 +02003400 {
3401 // For "**" in the pattern first go deeper in the tree to
3402 // find matches.
3403 STRCPY(buf + len, "/**");
3404 STRCPY(buf + len + 3, path_end);
3405 ++stardepth;
3406 (void)dos_expandpath(gap, buf, len + 1, flags, TRUE);
3407 --stardepth;
3408 }
3409
3410 STRCPY(buf + len, path_end);
3411 if (mch_has_exp_wildcard(path_end))
3412 {
3413 // need to expand another component of the path
3414 // remove backslashes for the remaining components only
3415 (void)dos_expandpath(gap, buf, len + 1, flags, FALSE);
3416 }
3417 else
3418 {
3419 // no more wildcards, check if there is a match
3420 // remove backslashes for the remaining components only
3421 if (*path_end != 0)
3422 backslash_halve(buf + len + 1);
3423 if (mch_getperm(buf) >= 0) // add existing file
3424 addfile(gap, buf, flags);
3425 }
3426 }
3427
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003428 vim_free(p_alt);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003429 vim_free(p);
3430 ok = FindNextFileW(hFind, &wfb);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003431 }
3432
3433 FindClose(hFind);
3434 vim_free(wn);
3435 vim_free(buf);
3436 vim_regfree(regmatch.regprog);
3437 vim_free(matchname);
3438
3439 matches = gap->ga_len - start_len;
3440 if (matches > 0)
3441 qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
3442 sizeof(char_u *), pstrcmp);
3443 return matches;
3444}
3445
3446 int
3447mch_expandpath(
3448 garray_T *gap,
3449 char_u *path,
3450 int flags) // EW_* flags
3451{
3452 return dos_expandpath(gap, path, 0, flags, FALSE);
3453}
3454#endif // MSWIN
3455
3456#if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \
3457 || defined(PROTO)
3458/*
3459 * Unix style wildcard expansion code.
3460 * It's here because it's used both for Unix and Mac.
3461 */
3462 static int
3463pstrcmp(const void *a, const void *b)
3464{
3465 return (pathcmp(*(char **)a, *(char **)b, -1));
3466}
3467
3468/*
3469 * Recursively expand one path component into all matching files and/or
3470 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
3471 * "path" has backslashes before chars that are not to be expanded, starting
3472 * at "path + wildoff".
3473 * Return the number of matches found.
3474 * NOTE: much of this is identical to dos_expandpath(), keep in sync!
3475 */
3476 int
3477unix_expandpath(
3478 garray_T *gap,
3479 char_u *path,
3480 int wildoff,
3481 int flags, // EW_* flags
3482 int didstar) // expanded "**" once already
3483{
3484 char_u *buf;
3485 char_u *path_end;
3486 char_u *p, *s, *e;
3487 int start_len = gap->ga_len;
3488 char_u *pat;
3489 regmatch_T regmatch;
3490 int starts_with_dot;
3491 int matches;
3492 int len;
3493 int starstar = FALSE;
3494 static int stardepth = 0; // depth for "**" expansion
3495
3496 DIR *dirp;
3497 struct dirent *dp;
3498
3499 // Expanding "**" may take a long time, check for CTRL-C.
3500 if (stardepth > 0)
3501 {
3502 ui_breakcheck();
3503 if (got_int)
3504 return 0;
3505 }
3506
3507 // make room for file name
3508 buf = alloc(STRLEN(path) + BASENAMELEN + 5);
3509 if (buf == NULL)
3510 return 0;
3511
3512 /*
3513 * Find the first part in the path name that contains a wildcard.
3514 * When EW_ICASE is set every letter is considered to be a wildcard.
3515 * Copy it into "buf", including the preceding characters.
3516 */
3517 p = buf;
3518 s = buf;
3519 e = NULL;
3520 path_end = path;
3521 while (*path_end != NUL)
3522 {
3523 // May ignore a wildcard that has a backslash before it; it will
3524 // be removed by rem_backslash() or file_pat_to_reg_pat() below.
3525 if (path_end >= path + wildoff && rem_backslash(path_end))
3526 *p++ = *path_end++;
3527 else if (*path_end == '/')
3528 {
3529 if (e != NULL)
3530 break;
3531 s = p + 1;
3532 }
3533 else if (path_end >= path + wildoff
3534 && (vim_strchr((char_u *)"*?[{~$", *path_end) != NULL
3535 || (!p_fic && (flags & EW_ICASE)
3536 && isalpha(PTR2CHAR(path_end)))))
3537 e = p;
3538 if (has_mbyte)
3539 {
3540 len = (*mb_ptr2len)(path_end);
3541 STRNCPY(p, path_end, len);
3542 p += len;
3543 path_end += len;
3544 }
3545 else
3546 *p++ = *path_end++;
3547 }
3548 e = p;
3549 *e = NUL;
3550
3551 // Now we have one wildcard component between "s" and "e".
3552 // Remove backslashes between "wildoff" and the start of the wildcard
3553 // component.
3554 for (p = buf + wildoff; p < s; ++p)
3555 if (rem_backslash(p))
3556 {
3557 STRMOVE(p, p + 1);
3558 --e;
3559 --s;
3560 }
3561
3562 // Check for "**" between "s" and "e".
3563 for (p = s; p < e; ++p)
3564 if (p[0] == '*' && p[1] == '*')
3565 starstar = TRUE;
3566
3567 // convert the file pattern to a regexp pattern
3568 starts_with_dot = *s == '.';
3569 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
3570 if (pat == NULL)
3571 {
3572 vim_free(buf);
3573 return 0;
3574 }
3575
3576 // compile the regexp into a program
3577 if (flags & EW_ICASE)
3578 regmatch.rm_ic = TRUE; // 'wildignorecase' set
3579 else
3580 regmatch.rm_ic = p_fic; // ignore case when 'fileignorecase' is set
3581 if (flags & (EW_NOERROR | EW_NOTWILD))
3582 ++emsg_silent;
3583 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
3584 if (flags & (EW_NOERROR | EW_NOTWILD))
3585 --emsg_silent;
3586 vim_free(pat);
3587
3588 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
3589 {
3590 vim_free(buf);
3591 return 0;
3592 }
3593
3594 // If "**" is by itself, this is the first time we encounter it and more
3595 // is following then find matches without any directory.
3596 if (!didstar && stardepth < 100 && starstar && e - s == 2
3597 && *path_end == '/')
3598 {
3599 STRCPY(s, path_end + 1);
3600 ++stardepth;
3601 (void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
3602 --stardepth;
3603 }
3604
3605 // open the directory for scanning
3606 *s = NUL;
3607 dirp = opendir(*buf == NUL ? "." : (char *)buf);
3608
3609 // Find all matching entries
3610 if (dirp != NULL)
3611 {
3612 for (;;)
3613 {
3614 dp = readdir(dirp);
3615 if (dp == NULL)
3616 break;
3617 if ((dp->d_name[0] != '.' || starts_with_dot
3618 || ((flags & EW_DODOT)
3619 && dp->d_name[1] != NUL
3620 && (dp->d_name[1] != '.' || dp->d_name[2] != NUL)))
3621 && ((regmatch.regprog != NULL && vim_regexec(&regmatch,
3622 (char_u *)dp->d_name, (colnr_T)0))
3623 || ((flags & EW_NOTWILD)
3624 && fnamencmp(path + (s - buf), dp->d_name, e - s) == 0)))
3625 {
3626 STRCPY(s, dp->d_name);
3627 len = STRLEN(buf);
3628
3629 if (starstar && stardepth < 100)
3630 {
3631 // For "**" in the pattern first go deeper in the tree to
3632 // find matches.
3633 STRCPY(buf + len, "/**");
3634 STRCPY(buf + len + 3, path_end);
3635 ++stardepth;
3636 (void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
3637 --stardepth;
3638 }
3639
3640 STRCPY(buf + len, path_end);
3641 if (mch_has_exp_wildcard(path_end)) // handle more wildcards
3642 {
3643 // need to expand another component of the path
3644 // remove backslashes for the remaining components only
3645 (void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
3646 }
3647 else
3648 {
3649 stat_T sb;
3650
3651 // no more wildcards, check if there is a match
3652 // remove backslashes for the remaining components only
3653 if (*path_end != NUL)
3654 backslash_halve(buf + len + 1);
3655 // add existing file or symbolic link
3656 if ((flags & EW_ALLLINKS) ? mch_lstat((char *)buf, &sb) >= 0
3657 : mch_getperm(buf) >= 0)
3658 {
3659#ifdef MACOS_CONVERT
3660 size_t precomp_len = STRLEN(buf)+1;
3661 char_u *precomp_buf =
3662 mac_precompose_path(buf, precomp_len, &precomp_len);
3663
3664 if (precomp_buf)
3665 {
3666 mch_memmove(buf, precomp_buf, precomp_len);
3667 vim_free(precomp_buf);
3668 }
3669#endif
3670 addfile(gap, buf, flags);
3671 }
3672 }
3673 }
3674 }
3675
3676 closedir(dirp);
3677 }
3678
3679 vim_free(buf);
3680 vim_regfree(regmatch.regprog);
3681
3682 matches = gap->ga_len - start_len;
3683 if (matches > 0)
3684 qsort(((char_u **)gap->ga_data) + start_len, matches,
3685 sizeof(char_u *), pstrcmp);
3686 return matches;
3687}
3688#endif
3689
3690/*
3691 * Return TRUE if "p" contains what looks like an environment variable.
3692 * Allowing for escaping.
3693 */
3694 static int
3695has_env_var(char_u *p)
3696{
3697 for ( ; *p; MB_PTR_ADV(p))
3698 {
3699 if (*p == '\\' && p[1] != NUL)
3700 ++p;
3701 else if (vim_strchr((char_u *)
3702#if defined(MSWIN)
3703 "$%"
3704#else
3705 "$"
3706#endif
3707 , *p) != NULL)
3708 return TRUE;
3709 }
3710 return FALSE;
3711}
3712
3713#ifdef SPECIAL_WILDCHAR
3714/*
3715 * Return TRUE if "p" contains a special wildcard character, one that Vim
3716 * cannot expand, requires using a shell.
3717 */
3718 static int
3719has_special_wildchar(char_u *p)
3720{
3721 for ( ; *p; MB_PTR_ADV(p))
3722 {
3723 // Disallow line break characters.
3724 if (*p == '\r' || *p == '\n')
3725 break;
3726 // Allow for escaping.
3727 if (*p == '\\' && p[1] != NUL && p[1] != '\r' && p[1] != '\n')
3728 ++p;
3729 else if (vim_strchr((char_u *)SPECIAL_WILDCHAR, *p) != NULL)
3730 {
3731 // A { must be followed by a matching }.
3732 if (*p == '{' && vim_strchr(p, '}') == NULL)
3733 continue;
3734 // A quote and backtick must be followed by another one.
3735 if ((*p == '`' || *p == '\'') && vim_strchr(p, *p) == NULL)
3736 continue;
3737 return TRUE;
3738 }
3739 }
3740 return FALSE;
3741}
3742#endif
3743
3744/*
3745 * Generic wildcard expansion code.
3746 *
3747 * Characters in "pat" that should not be expanded must be preceded with a
3748 * backslash. E.g., "/path\ with\ spaces/my\*star*"
3749 *
3750 * Return FAIL when no single file was found. In this case "num_file" is not
3751 * set, and "file" may contain an error message.
3752 * Return OK when some files found. "num_file" is set to the number of
3753 * matches, "file" to the array of matches. Call FreeWild() later.
3754 */
3755 int
3756gen_expand_wildcards(
3757 int num_pat, // number of input patterns
3758 char_u **pat, // array of input patterns
3759 int *num_file, // resulting number of files
3760 char_u ***file, // array of resulting files
3761 int flags) // EW_* flags
3762{
3763 int i;
3764 garray_T ga;
3765 char_u *p;
3766 static int recursive = FALSE;
3767 int add_pat;
3768 int retval = OK;
3769#if defined(FEAT_SEARCHPATH)
3770 int did_expand_in_path = FALSE;
3771#endif
3772
3773 /*
3774 * expand_env() is called to expand things like "~user". If this fails,
3775 * it calls ExpandOne(), which brings us back here. In this case, always
3776 * call the machine specific expansion function, if possible. Otherwise,
3777 * return FAIL.
3778 */
3779 if (recursive)
3780#ifdef SPECIAL_WILDCHAR
3781 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
3782#else
3783 return FAIL;
3784#endif
3785
3786#ifdef SPECIAL_WILDCHAR
3787 /*
3788 * If there are any special wildcard characters which we cannot handle
3789 * here, call machine specific function for all the expansion. This
3790 * avoids starting the shell for each argument separately.
3791 * For `=expr` do use the internal function.
3792 */
3793 for (i = 0; i < num_pat; i++)
3794 {
3795 if (has_special_wildchar(pat[i])
3796# ifdef VIM_BACKTICK
3797 && !(vim_backtick(pat[i]) && pat[i][1] == '=')
3798# endif
3799 )
3800 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
3801 }
3802#endif
3803
3804 recursive = TRUE;
3805
3806 /*
3807 * The matching file names are stored in a growarray. Init it empty.
3808 */
3809 ga_init2(&ga, (int)sizeof(char_u *), 30);
3810
3811 for (i = 0; i < num_pat; ++i)
3812 {
3813 add_pat = -1;
3814 p = pat[i];
3815
3816#ifdef VIM_BACKTICK
3817 if (vim_backtick(p))
3818 {
3819 add_pat = expand_backtick(&ga, p, flags);
3820 if (add_pat == -1)
3821 retval = FAIL;
3822 }
3823 else
3824#endif
3825 {
3826 /*
3827 * First expand environment variables, "~/" and "~user/".
3828 */
3829 if ((has_env_var(p) && !(flags & EW_NOTENV)) || *p == '~')
3830 {
3831 p = expand_env_save_opt(p, TRUE);
3832 if (p == NULL)
3833 p = pat[i];
3834#ifdef UNIX
3835 /*
3836 * On Unix, if expand_env() can't expand an environment
3837 * variable, use the shell to do that. Discard previously
3838 * found file names and start all over again.
3839 */
3840 else if (has_env_var(p) || *p == '~')
3841 {
3842 vim_free(p);
3843 ga_clear_strings(&ga);
3844 i = mch_expand_wildcards(num_pat, pat, num_file, file,
3845 flags|EW_KEEPDOLLAR);
3846 recursive = FALSE;
3847 return i;
3848 }
3849#endif
3850 }
3851
3852 /*
3853 * If there are wildcards: Expand file names and add each match to
3854 * the list. If there is no match, and EW_NOTFOUND is given, add
3855 * the pattern.
3856 * If there are no wildcards: Add the file name if it exists or
3857 * when EW_NOTFOUND is given.
3858 */
3859 if (mch_has_exp_wildcard(p))
3860 {
3861#if defined(FEAT_SEARCHPATH)
3862 if ((flags & EW_PATH)
3863 && !mch_isFullName(p)
3864 && !(p[0] == '.'
3865 && (vim_ispathsep(p[1])
3866 || (p[1] == '.' && vim_ispathsep(p[2]))))
3867 )
3868 {
3869 // :find completion where 'path' is used.
3870 // Recursiveness is OK here.
3871 recursive = FALSE;
3872 add_pat = expand_in_path(&ga, p, flags);
3873 recursive = TRUE;
3874 did_expand_in_path = TRUE;
3875 }
3876 else
3877#endif
3878 add_pat = mch_expandpath(&ga, p, flags);
3879 }
3880 }
3881
3882 if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
3883 {
3884 char_u *t = backslash_halve_save(p);
3885
3886 // When EW_NOTFOUND is used, always add files and dirs. Makes
3887 // "vim c:/" work.
3888 if (flags & EW_NOTFOUND)
3889 addfile(&ga, t, flags | EW_DIR | EW_FILE);
3890 else
3891 addfile(&ga, t, flags);
3892
3893 if (t != p)
3894 vim_free(t);
3895 }
3896
3897#if defined(FEAT_SEARCHPATH)
3898 if (did_expand_in_path && ga.ga_len > 0 && (flags & EW_PATH))
3899 uniquefy_paths(&ga, p);
3900#endif
3901 if (p != pat[i])
3902 vim_free(p);
3903 }
3904
Bram Moolenaar566cc8c2020-06-29 21:14:51 +02003905 // When returning FAIL the array must be freed here.
3906 if (retval == FAIL)
3907 ga_clear(&ga);
3908
Bram Moolenaar26262f82019-09-04 20:59:15 +02003909 *num_file = ga.ga_len;
Bram Moolenaar566cc8c2020-06-29 21:14:51 +02003910 *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data
3911 : (char_u **)_("no matches");
Bram Moolenaar26262f82019-09-04 20:59:15 +02003912
3913 recursive = FALSE;
3914
3915 return ((flags & EW_EMPTYOK) || ga.ga_data != NULL) ? retval : FAIL;
3916}
3917
3918/*
3919 * Add a file to a file list. Accepted flags:
3920 * EW_DIR add directories
3921 * EW_FILE add files
3922 * EW_EXEC add executable files
3923 * EW_NOTFOUND add even when it doesn't exist
3924 * EW_ADDSLASH add slash after directory name
3925 * EW_ALLLINKS add symlink also when the referred file does not exist
3926 */
3927 void
3928addfile(
3929 garray_T *gap,
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003930 char_u *f, // filename
Bram Moolenaar26262f82019-09-04 20:59:15 +02003931 int flags)
3932{
3933 char_u *p;
3934 int isdir;
3935 stat_T sb;
3936
3937 // if the file/dir/link doesn't exist, may not add it
3938 if (!(flags & EW_NOTFOUND) && ((flags & EW_ALLLINKS)
3939 ? mch_lstat((char *)f, &sb) < 0 : mch_getperm(f) < 0))
3940 return;
3941
3942#ifdef FNAME_ILLEGAL
3943 // if the file/dir contains illegal characters, don't add it
3944 if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
3945 return;
3946#endif
3947
3948 isdir = mch_isdir(f);
3949 if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
3950 return;
3951
3952 // If the file isn't executable, may not add it. Do accept directories.
3953 // When invoked from expand_shellcmd() do not use $PATH.
3954 if (!isdir && (flags & EW_EXEC)
3955 && !mch_can_exe(f, NULL, !(flags & EW_SHELLCMD)))
3956 return;
3957
3958 // Make room for another item in the file list.
3959 if (ga_grow(gap, 1) == FAIL)
3960 return;
3961
3962 p = alloc(STRLEN(f) + 1 + isdir);
3963 if (p == NULL)
3964 return;
3965
3966 STRCPY(p, f);
3967#ifdef BACKSLASH_IN_FILENAME
3968 slash_adjust(p);
3969#endif
3970 /*
3971 * Append a slash or backslash after directory names if none is present.
3972 */
3973#ifndef DONT_ADD_PATHSEP_TO_DIR
3974 if (isdir && (flags & EW_ADDSLASH))
3975 add_pathsep(p);
3976#endif
3977 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
3978}
3979
3980/*
3981 * Free the list of files returned by expand_wildcards() or other expansion
3982 * functions.
3983 */
3984 void
3985FreeWild(int count, char_u **files)
3986{
3987 if (count <= 0 || files == NULL)
3988 return;
3989 while (count--)
3990 vim_free(files[count]);
3991 vim_free(files);
3992}
3993
3994/*
3995 * Compare path "p[]" to "q[]".
3996 * If "maxlen" >= 0 compare "p[maxlen]" to "q[maxlen]"
3997 * Return value like strcmp(p, q), but consider path separators.
3998 */
3999 int
4000pathcmp(const char *p, const char *q, int maxlen)
4001{
4002 int i, j;
4003 int c1, c2;
4004 const char *s = NULL;
4005
4006 for (i = 0, j = 0; maxlen < 0 || (i < maxlen && j < maxlen);)
4007 {
4008 c1 = PTR2CHAR((char_u *)p + i);
4009 c2 = PTR2CHAR((char_u *)q + j);
4010
4011 // End of "p": check if "q" also ends or just has a slash.
4012 if (c1 == NUL)
4013 {
4014 if (c2 == NUL) // full match
4015 return 0;
4016 s = q;
4017 i = j;
4018 break;
4019 }
4020
4021 // End of "q": check if "p" just has a slash.
4022 if (c2 == NUL)
4023 {
4024 s = p;
4025 break;
4026 }
4027
4028 if ((p_fic ? MB_TOUPPER(c1) != MB_TOUPPER(c2) : c1 != c2)
4029#ifdef BACKSLASH_IN_FILENAME
4030 // consider '/' and '\\' to be equal
4031 && !((c1 == '/' && c2 == '\\')
4032 || (c1 == '\\' && c2 == '/'))
4033#endif
4034 )
4035 {
4036 if (vim_ispathsep(c1))
4037 return -1;
4038 if (vim_ispathsep(c2))
4039 return 1;
4040 return p_fic ? MB_TOUPPER(c1) - MB_TOUPPER(c2)
4041 : c1 - c2; // no match
4042 }
4043
Bram Moolenaar1614a142019-10-06 22:00:13 +02004044 i += mb_ptr2len((char_u *)p + i);
4045 j += mb_ptr2len((char_u *)q + j);
Bram Moolenaar26262f82019-09-04 20:59:15 +02004046 }
4047 if (s == NULL) // "i" or "j" ran into "maxlen"
4048 return 0;
4049
4050 c1 = PTR2CHAR((char_u *)s + i);
Bram Moolenaar1614a142019-10-06 22:00:13 +02004051 c2 = PTR2CHAR((char_u *)s + i + mb_ptr2len((char_u *)s + i));
Bram Moolenaar26262f82019-09-04 20:59:15 +02004052 // ignore a trailing slash, but not "//" or ":/"
4053 if (c2 == NUL
4054 && i > 0
4055 && !after_pathsep((char_u *)s, (char_u *)s + i)
4056#ifdef BACKSLASH_IN_FILENAME
4057 && (c1 == '/' || c1 == '\\')
4058#else
4059 && c1 == '/'
4060#endif
4061 )
4062 return 0; // match with trailing slash
4063 if (s == q)
4064 return -1; // no match
4065 return 1;
4066}
4067
4068/*
4069 * Return TRUE if "name" is a full (absolute) path name or URL.
4070 */
4071 int
4072vim_isAbsName(char_u *name)
4073{
4074 return (path_with_url(name) != 0 || mch_isFullName(name));
4075}
4076
4077/*
4078 * Get absolute file name into buffer "buf[len]".
4079 *
4080 * return FAIL for failure, OK otherwise
4081 */
4082 int
4083vim_FullName(
4084 char_u *fname,
4085 char_u *buf,
4086 int len,
4087 int force) // force expansion even when already absolute
4088{
4089 int retval = OK;
4090 int url;
4091
4092 *buf = NUL;
4093 if (fname == NULL)
4094 return FAIL;
4095
4096 url = path_with_url(fname);
4097 if (!url)
4098 retval = mch_FullName(fname, buf, len, force);
4099 if (url || retval == FAIL)
4100 {
4101 // something failed; use the file name (truncate when too long)
4102 vim_strncpy(buf, fname, len - 1);
4103 }
4104#if defined(MSWIN)
4105 slash_adjust(buf);
4106#endif
4107 return retval;
4108}