blob: 347612a802805b372e4d6340f0aa20111e680730 [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 Moolenaard816cd92020-02-04 22:23:09 +0100791 // Returning an empty string means it failed.
Bram Moolenaar002bc792020-06-05 22:33:42 +0200792 // No error message, for historic reasons.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200793 return;
794
795 // Return the current directory
796 cwd = alloc(MAXPATHL);
797 if (cwd != NULL)
798 {
799 if (mch_dirname(cwd, MAXPATHL) != FAIL)
800 {
801#ifdef BACKSLASH_IN_FILENAME
802 slash_adjust(cwd);
803#endif
804 rettv->vval.v_string = vim_strsave(cwd);
805 }
806 vim_free(cwd);
807 }
808
809 if (curwin->w_localdir != NULL)
810 scope = CDSCOPE_WINDOW;
811 else if (curtab->tp_localdir != NULL)
812 scope = CDSCOPE_TABPAGE;
813
814 if (!changedir_func(argvars[0].vval.v_string, TRUE, scope))
815 // Directory change failed
816 VIM_CLEAR(rettv->vval.v_string);
817}
818
819/*
820 * "delete()" function
821 */
822 void
823f_delete(typval_T *argvars, typval_T *rettv)
824{
825 char_u nbuf[NUMBUFLEN];
826 char_u *name;
827 char_u *flags;
828
829 rettv->vval.v_number = -1;
830 if (check_restricted() || check_secure())
831 return;
832
833 name = tv_get_string(&argvars[0]);
834 if (name == NULL || *name == NUL)
835 {
836 emsg(_(e_invarg));
837 return;
838 }
839
840 if (argvars[1].v_type != VAR_UNKNOWN)
841 flags = tv_get_string_buf(&argvars[1], nbuf);
842 else
843 flags = (char_u *)"";
844
845 if (*flags == NUL)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200846 // delete a file
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200847 rettv->vval.v_number = mch_remove(name) == 0 ? 0 : -1;
848 else if (STRCMP(flags, "d") == 0)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200849 // delete an empty directory
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200850 rettv->vval.v_number = mch_rmdir(name) == 0 ? 0 : -1;
851 else if (STRCMP(flags, "rf") == 0)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200852 // delete a directory recursively
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200853 rettv->vval.v_number = delete_recursive(name);
854 else
855 semsg(_(e_invexpr2), flags);
856}
857
858/*
859 * "executable()" function
860 */
861 void
862f_executable(typval_T *argvars, typval_T *rettv)
863{
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100864 if (in_vim9script() && check_for_string(&argvars[0]) == FAIL)
865 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200866
Bram Moolenaar26262f82019-09-04 20:59:15 +0200867 // Check in $PATH and also check directly if there is a directory name.
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100868 rettv->vval.v_number = mch_can_exe(tv_get_string(&argvars[0]), NULL, TRUE);
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200869}
870
871/*
872 * "exepath()" function
873 */
874 void
875f_exepath(typval_T *argvars, typval_T *rettv)
876{
877 char_u *p = NULL;
878
Bram Moolenaar2a9d5d32020-12-12 18:58:40 +0100879 if (in_vim9script() && check_for_nonempty_string(&argvars[0]) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100880 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200881 (void)mch_can_exe(tv_get_string(&argvars[0]), &p, TRUE);
882 rettv->v_type = VAR_STRING;
883 rettv->vval.v_string = p;
884}
885
886/*
887 * "filereadable()" function
888 */
889 void
890f_filereadable(typval_T *argvars, typval_T *rettv)
891{
892 int fd;
893 char_u *p;
894 int n;
895
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100896 if (in_vim9script() && check_for_string(&argvars[0]) == FAIL)
897 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200898#ifndef O_NONBLOCK
899# define O_NONBLOCK 0
900#endif
901 p = tv_get_string(&argvars[0]);
902 if (*p && !mch_isdir(p) && (fd = mch_open((char *)p,
903 O_RDONLY | O_NONBLOCK, 0)) >= 0)
904 {
905 n = TRUE;
906 close(fd);
907 }
908 else
909 n = FALSE;
910
911 rettv->vval.v_number = n;
912}
913
914/*
915 * Return 0 for not writable, 1 for writable file, 2 for a dir which we have
916 * rights to write into.
917 */
918 void
919f_filewritable(typval_T *argvars, typval_T *rettv)
920{
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100921 if (in_vim9script() && check_for_string(&argvars[0]) == FAIL)
922 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200923 rettv->vval.v_number = filewritable(tv_get_string(&argvars[0]));
924}
925
Bram Moolenaar840d16f2019-09-10 21:27:18 +0200926 static void
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200927findfilendir(
928 typval_T *argvars UNUSED,
929 typval_T *rettv,
930 int find_what UNUSED)
931{
932#ifdef FEAT_SEARCHPATH
933 char_u *fname;
934 char_u *fresult = NULL;
935 char_u *path = *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path;
936 char_u *p;
937 char_u pathbuf[NUMBUFLEN];
938 int count = 1;
939 int first = TRUE;
940 int error = FALSE;
941#endif
942
943 rettv->vval.v_string = NULL;
944 rettv->v_type = VAR_STRING;
Bram Moolenaar2a9d5d32020-12-12 18:58:40 +0100945 if (in_vim9script() && check_for_nonempty_string(&argvars[0]) == FAIL)
Bram Moolenaar7bb4e742020-12-09 12:41:50 +0100946 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200947
948#ifdef FEAT_SEARCHPATH
949 fname = tv_get_string(&argvars[0]);
950
951 if (argvars[1].v_type != VAR_UNKNOWN)
952 {
953 p = tv_get_string_buf_chk(&argvars[1], pathbuf);
954 if (p == NULL)
955 error = TRUE;
956 else
957 {
958 if (*p != NUL)
959 path = p;
960
961 if (argvars[2].v_type != VAR_UNKNOWN)
962 count = (int)tv_get_number_chk(&argvars[2], &error);
963 }
964 }
965
966 if (count < 0 && rettv_list_alloc(rettv) == FAIL)
967 error = TRUE;
968
969 if (*fname != NUL && !error)
970 {
971 do
972 {
973 if (rettv->v_type == VAR_STRING || rettv->v_type == VAR_LIST)
974 vim_free(fresult);
975 fresult = find_file_in_path_option(first ? fname : NULL,
976 first ? (int)STRLEN(fname) : 0,
977 0, first, path,
978 find_what,
979 curbuf->b_ffname,
980 find_what == FINDFILE_DIR
981 ? (char_u *)"" : curbuf->b_p_sua);
982 first = FALSE;
983
984 if (fresult != NULL && rettv->v_type == VAR_LIST)
985 list_append_string(rettv->vval.v_list, fresult, -1);
986
987 } while ((rettv->v_type == VAR_LIST || --count > 0) && fresult != NULL);
988 }
989
990 if (rettv->v_type == VAR_STRING)
991 rettv->vval.v_string = fresult;
992#endif
993}
994
995/*
996 * "finddir({fname}[, {path}[, {count}]])" function
997 */
998 void
999f_finddir(typval_T *argvars, typval_T *rettv)
1000{
1001 findfilendir(argvars, rettv, FINDFILE_DIR);
1002}
1003
1004/*
1005 * "findfile({fname}[, {path}[, {count}]])" function
1006 */
1007 void
1008f_findfile(typval_T *argvars, typval_T *rettv)
1009{
1010 findfilendir(argvars, rettv, FINDFILE_FILE);
1011}
1012
1013/*
1014 * "fnamemodify({fname}, {mods})" function
1015 */
1016 void
1017f_fnamemodify(typval_T *argvars, typval_T *rettv)
1018{
1019 char_u *fname;
1020 char_u *mods;
1021 int usedlen = 0;
1022 int len;
1023 char_u *fbuf = NULL;
1024 char_u buf[NUMBUFLEN];
1025
Bram Moolenaar7bb4e742020-12-09 12:41:50 +01001026 if (in_vim9script() && (check_for_string(&argvars[0]) == FAIL
1027 || check_for_string(&argvars[1]) == FAIL))
1028 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001029 fname = tv_get_string_chk(&argvars[0]);
1030 mods = tv_get_string_buf_chk(&argvars[1], buf);
Bram Moolenaar2a9d5d32020-12-12 18:58:40 +01001031 if (fname == NULL)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001032 fname = NULL;
Bram Moolenaar2a9d5d32020-12-12 18:58:40 +01001033 else if (mods != NULL && *mods != NUL)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001034 {
1035 len = (int)STRLEN(fname);
1036 (void)modify_fname(mods, FALSE, &usedlen, &fname, &fbuf, &len);
1037 }
1038
1039 rettv->v_type = VAR_STRING;
1040 if (fname == NULL)
1041 rettv->vval.v_string = NULL;
1042 else
1043 rettv->vval.v_string = vim_strnsave(fname, len);
1044 vim_free(fbuf);
1045}
1046
1047/*
1048 * "getcwd()" function
1049 *
1050 * Return the current working directory of a window in a tab page.
1051 * First optional argument 'winnr' is the window number or -1 and the second
1052 * optional argument 'tabnr' is the tab page number.
1053 *
1054 * If no arguments are supplied, then return the directory of the current
1055 * window.
1056 * If only 'winnr' is specified and is not -1 or 0 then return the directory of
1057 * the specified window.
1058 * If 'winnr' is 0 then return the directory of the current window.
1059 * If both 'winnr and 'tabnr' are specified and 'winnr' is -1 then return the
1060 * directory of the specified tab page. Otherwise return the directory of the
1061 * specified window in the specified tab page.
1062 * If the window or the tab page doesn't exist then return NULL.
1063 */
1064 void
1065f_getcwd(typval_T *argvars, typval_T *rettv)
1066{
1067 win_T *wp = NULL;
1068 tabpage_T *tp = NULL;
1069 char_u *cwd;
1070 int global = FALSE;
1071
1072 rettv->v_type = VAR_STRING;
1073 rettv->vval.v_string = NULL;
1074
1075 if (argvars[0].v_type == VAR_NUMBER
1076 && argvars[0].vval.v_number == -1
1077 && argvars[1].v_type == VAR_UNKNOWN)
1078 global = TRUE;
1079 else
1080 wp = find_tabwin(&argvars[0], &argvars[1], &tp);
1081
1082 if (wp != NULL && wp->w_localdir != NULL)
1083 rettv->vval.v_string = vim_strsave(wp->w_localdir);
1084 else if (tp != NULL && tp->tp_localdir != NULL)
1085 rettv->vval.v_string = vim_strsave(tp->tp_localdir);
1086 else if (wp != NULL || tp != NULL || global)
1087 {
1088 if (globaldir != NULL)
1089 rettv->vval.v_string = vim_strsave(globaldir);
1090 else
1091 {
1092 cwd = alloc(MAXPATHL);
1093 if (cwd != NULL)
1094 {
1095 if (mch_dirname(cwd, MAXPATHL) != FAIL)
1096 rettv->vval.v_string = vim_strsave(cwd);
1097 vim_free(cwd);
1098 }
1099 }
1100 }
1101#ifdef BACKSLASH_IN_FILENAME
1102 if (rettv->vval.v_string != NULL)
1103 slash_adjust(rettv->vval.v_string);
1104#endif
1105}
1106
1107/*
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001108 * Convert "st" to file permission string.
1109 */
1110 char_u *
1111getfpermst(stat_T *st, char_u *perm)
1112{
1113 char_u flags[] = "rwx";
1114 int i;
1115
1116 for (i = 0; i < 9; i++)
1117 {
1118 if (st->st_mode & (1 << (8 - i)))
1119 perm[i] = flags[i % 3];
1120 else
1121 perm[i] = '-';
1122 }
1123 return perm;
1124}
1125
1126/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001127 * "getfperm({fname})" function
1128 */
1129 void
1130f_getfperm(typval_T *argvars, typval_T *rettv)
1131{
1132 char_u *fname;
1133 stat_T st;
1134 char_u *perm = NULL;
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001135 char_u permbuf[] = "---------";
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001136
Bram Moolenaar7bb4e742020-12-09 12:41:50 +01001137 if (in_vim9script() && check_for_string(&argvars[0]) == FAIL)
1138 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001139 fname = tv_get_string(&argvars[0]);
1140
1141 rettv->v_type = VAR_STRING;
1142 if (mch_stat((char *)fname, &st) >= 0)
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001143 perm = vim_strsave(getfpermst(&st, permbuf));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001144 rettv->vval.v_string = perm;
1145}
1146
1147/*
1148 * "getfsize({fname})" function
1149 */
1150 void
1151f_getfsize(typval_T *argvars, typval_T *rettv)
1152{
1153 char_u *fname;
1154 stat_T st;
1155
Bram Moolenaar7bb4e742020-12-09 12:41:50 +01001156 if (in_vim9script() && check_for_string(&argvars[0]) == FAIL)
1157 return;
1158
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001159 fname = tv_get_string(&argvars[0]);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001160 if (mch_stat((char *)fname, &st) >= 0)
1161 {
1162 if (mch_isdir(fname))
1163 rettv->vval.v_number = 0;
1164 else
1165 {
1166 rettv->vval.v_number = (varnumber_T)st.st_size;
1167
Bram Moolenaar26262f82019-09-04 20:59:15 +02001168 // non-perfect check for overflow
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001169 if ((off_T)rettv->vval.v_number != (off_T)st.st_size)
1170 rettv->vval.v_number = -2;
1171 }
1172 }
1173 else
1174 rettv->vval.v_number = -1;
1175}
1176
1177/*
1178 * "getftime({fname})" function
1179 */
1180 void
1181f_getftime(typval_T *argvars, typval_T *rettv)
1182{
1183 char_u *fname;
1184 stat_T st;
1185
Bram Moolenaar7bb4e742020-12-09 12:41:50 +01001186 if (in_vim9script() && check_for_string(&argvars[0]) == FAIL)
1187 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001188 fname = tv_get_string(&argvars[0]);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001189 if (mch_stat((char *)fname, &st) >= 0)
1190 rettv->vval.v_number = (varnumber_T)st.st_mtime;
1191 else
1192 rettv->vval.v_number = -1;
1193}
1194
1195/*
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001196 * Convert "st" to file type string.
1197 */
1198 char_u *
1199getftypest(stat_T *st)
1200{
1201 char *t;
1202
1203 if (S_ISREG(st->st_mode))
1204 t = "file";
1205 else if (S_ISDIR(st->st_mode))
1206 t = "dir";
1207 else if (S_ISLNK(st->st_mode))
1208 t = "link";
1209 else if (S_ISBLK(st->st_mode))
1210 t = "bdev";
1211 else if (S_ISCHR(st->st_mode))
1212 t = "cdev";
1213 else if (S_ISFIFO(st->st_mode))
1214 t = "fifo";
1215 else if (S_ISSOCK(st->st_mode))
1216 t = "socket";
1217 else
1218 t = "other";
1219 return (char_u*)t;
1220}
1221
1222/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001223 * "getftype({fname})" function
1224 */
1225 void
1226f_getftype(typval_T *argvars, typval_T *rettv)
1227{
1228 char_u *fname;
1229 stat_T st;
1230 char_u *type = NULL;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001231
Bram Moolenaar7bb4e742020-12-09 12:41:50 +01001232 if (in_vim9script() && check_for_string(&argvars[0]) == FAIL)
1233 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001234 fname = tv_get_string(&argvars[0]);
1235
1236 rettv->v_type = VAR_STRING;
1237 if (mch_lstat((char *)fname, &st) >= 0)
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001238 type = vim_strsave(getftypest(&st));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001239 rettv->vval.v_string = type;
1240}
1241
1242/*
1243 * "glob()" function
1244 */
1245 void
1246f_glob(typval_T *argvars, typval_T *rettv)
1247{
1248 int options = WILD_SILENT|WILD_USE_NL;
1249 expand_T xpc;
1250 int error = FALSE;
1251
Bram Moolenaar26262f82019-09-04 20:59:15 +02001252 // When the optional second argument is non-zero, don't remove matches
1253 // for 'wildignore' and don't put matches for 'suffixes' at the end.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001254 rettv->v_type = VAR_STRING;
1255 if (argvars[1].v_type != VAR_UNKNOWN)
1256 {
Bram Moolenaar5892ea12020-09-02 21:53:11 +02001257 if (tv_get_bool_chk(&argvars[1], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001258 options |= WILD_KEEP_ALL;
1259 if (argvars[2].v_type != VAR_UNKNOWN)
1260 {
Bram Moolenaar5892ea12020-09-02 21:53:11 +02001261 if (tv_get_bool_chk(&argvars[2], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001262 rettv_list_set(rettv, NULL);
1263 if (argvars[3].v_type != VAR_UNKNOWN
Bram Moolenaar5892ea12020-09-02 21:53:11 +02001264 && tv_get_bool_chk(&argvars[3], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001265 options |= WILD_ALLLINKS;
1266 }
1267 }
1268 if (!error)
1269 {
1270 ExpandInit(&xpc);
1271 xpc.xp_context = EXPAND_FILES;
1272 if (p_wic)
1273 options += WILD_ICASE;
1274 if (rettv->v_type == VAR_STRING)
1275 rettv->vval.v_string = ExpandOne(&xpc, tv_get_string(&argvars[0]),
1276 NULL, options, WILD_ALL);
1277 else if (rettv_list_alloc(rettv) != FAIL)
1278 {
1279 int i;
1280
1281 ExpandOne(&xpc, tv_get_string(&argvars[0]),
1282 NULL, options, WILD_ALL_KEEP);
1283 for (i = 0; i < xpc.xp_numfiles; i++)
1284 list_append_string(rettv->vval.v_list, xpc.xp_files[i], -1);
1285
1286 ExpandCleanup(&xpc);
1287 }
1288 }
1289 else
1290 rettv->vval.v_string = NULL;
1291}
1292
1293/*
1294 * "glob2regpat()" function
1295 */
1296 void
1297f_glob2regpat(typval_T *argvars, typval_T *rettv)
1298{
1299 char_u *pat = tv_get_string_chk(&argvars[0]);
1300
1301 rettv->v_type = VAR_STRING;
1302 rettv->vval.v_string = (pat == NULL)
1303 ? NULL : file_pat_to_reg_pat(pat, NULL, NULL, FALSE);
1304}
1305
1306/*
1307 * "globpath()" function
1308 */
1309 void
1310f_globpath(typval_T *argvars, typval_T *rettv)
1311{
1312 int flags = WILD_IGNORE_COMPLETESLASH;
1313 char_u buf1[NUMBUFLEN];
1314 char_u *file = tv_get_string_buf_chk(&argvars[1], buf1);
1315 int error = FALSE;
1316 garray_T ga;
1317 int i;
1318
1319 // When the optional second argument is non-zero, don't remove matches
1320 // for 'wildignore' and don't put matches for 'suffixes' at the end.
1321 rettv->v_type = VAR_STRING;
1322 if (argvars[2].v_type != VAR_UNKNOWN)
1323 {
Bram Moolenaarf966ce52020-09-02 21:57:07 +02001324 if (tv_get_bool_chk(&argvars[2], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001325 flags |= WILD_KEEP_ALL;
1326 if (argvars[3].v_type != VAR_UNKNOWN)
1327 {
Bram Moolenaarf966ce52020-09-02 21:57:07 +02001328 if (tv_get_bool_chk(&argvars[3], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001329 rettv_list_set(rettv, NULL);
1330 if (argvars[4].v_type != VAR_UNKNOWN
Bram Moolenaarf966ce52020-09-02 21:57:07 +02001331 && tv_get_bool_chk(&argvars[4], &error))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001332 flags |= WILD_ALLLINKS;
1333 }
1334 }
1335 if (file != NULL && !error)
1336 {
1337 ga_init2(&ga, (int)sizeof(char_u *), 10);
1338 globpath(tv_get_string(&argvars[0]), file, &ga, flags);
1339 if (rettv->v_type == VAR_STRING)
1340 rettv->vval.v_string = ga_concat_strings(&ga, "\n");
1341 else if (rettv_list_alloc(rettv) != FAIL)
1342 for (i = 0; i < ga.ga_len; ++i)
1343 list_append_string(rettv->vval.v_list,
1344 ((char_u **)(ga.ga_data))[i], -1);
1345 ga_clear_strings(&ga);
1346 }
1347 else
1348 rettv->vval.v_string = NULL;
1349}
1350
1351/*
1352 * "isdirectory()" function
1353 */
1354 void
1355f_isdirectory(typval_T *argvars, typval_T *rettv)
1356{
1357 rettv->vval.v_number = mch_isdir(tv_get_string(&argvars[0]));
1358}
1359
1360/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001361 * Create the directory in which "dir" is located, and higher levels when
1362 * needed.
1363 * Return OK or FAIL.
1364 */
1365 static int
1366mkdir_recurse(char_u *dir, int prot)
1367{
1368 char_u *p;
1369 char_u *updir;
1370 int r = FAIL;
1371
Bram Moolenaar26262f82019-09-04 20:59:15 +02001372 // Get end of directory name in "dir".
1373 // We're done when it's "/" or "c:/".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001374 p = gettail_sep(dir);
1375 if (p <= get_past_head(dir))
1376 return OK;
1377
Bram Moolenaar26262f82019-09-04 20:59:15 +02001378 // If the directory exists we're done. Otherwise: create it.
Bram Moolenaar71ccd032020-06-12 22:59:11 +02001379 updir = vim_strnsave(dir, p - dir);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001380 if (updir == NULL)
1381 return FAIL;
1382 if (mch_isdir(updir))
1383 r = OK;
1384 else if (mkdir_recurse(updir, prot) == OK)
1385 r = vim_mkdir_emsg(updir, prot);
1386 vim_free(updir);
1387 return r;
1388}
1389
1390/*
1391 * "mkdir()" function
1392 */
1393 void
1394f_mkdir(typval_T *argvars, typval_T *rettv)
1395{
1396 char_u *dir;
1397 char_u buf[NUMBUFLEN];
1398 int prot = 0755;
1399
1400 rettv->vval.v_number = FAIL;
1401 if (check_restricted() || check_secure())
1402 return;
1403
1404 dir = tv_get_string_buf(&argvars[0], buf);
1405 if (*dir == NUL)
1406 return;
1407
1408 if (*gettail(dir) == NUL)
Bram Moolenaar26262f82019-09-04 20:59:15 +02001409 // remove trailing slashes
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001410 *gettail_sep(dir) = NUL;
1411
1412 if (argvars[1].v_type != VAR_UNKNOWN)
1413 {
1414 if (argvars[2].v_type != VAR_UNKNOWN)
1415 {
1416 prot = (int)tv_get_number_chk(&argvars[2], NULL);
1417 if (prot == -1)
1418 return;
1419 }
1420 if (STRCMP(tv_get_string(&argvars[1]), "p") == 0)
1421 {
1422 if (mch_isdir(dir))
1423 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001424 // With the "p" flag it's OK if the dir already exists.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001425 rettv->vval.v_number = OK;
1426 return;
1427 }
1428 mkdir_recurse(dir, prot);
1429 }
1430 }
1431 rettv->vval.v_number = vim_mkdir_emsg(dir, prot);
1432}
1433
1434/*
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02001435 * "pathshorten()" function
1436 */
1437 void
1438f_pathshorten(typval_T *argvars, typval_T *rettv)
1439{
1440 char_u *p;
Bram Moolenaar6a33ef02020-09-25 22:42:48 +02001441 int trim_len = 1;
1442
1443 if (argvars[1].v_type != VAR_UNKNOWN)
1444 {
1445 trim_len = (int)tv_get_number(&argvars[1]);
1446 if (trim_len < 1)
1447 trim_len = 1;
1448 }
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02001449
1450 rettv->v_type = VAR_STRING;
1451 p = tv_get_string_chk(&argvars[0]);
Bram Moolenaar6a33ef02020-09-25 22:42:48 +02001452
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02001453 if (p == NULL)
1454 rettv->vval.v_string = NULL;
1455 else
1456 {
1457 p = vim_strsave(p);
1458 rettv->vval.v_string = p;
1459 if (p != NULL)
Bram Moolenaar6a33ef02020-09-25 22:42:48 +02001460 shorten_dir_len(p, trim_len);
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02001461 }
1462}
1463
1464/*
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001465 * Common code for readdir_checkitem() and readdirex_checkitem().
1466 * Either "name" or "dict" is NULL.
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001467 */
1468 static int
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001469checkitem_common(void *context, char_u *name, dict_T *dict)
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001470{
1471 typval_T *expr = (typval_T *)context;
1472 typval_T save_val;
1473 typval_T rettv;
1474 typval_T argv[2];
1475 int retval = 0;
1476 int error = FALSE;
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001477
1478 prepare_vimvar(VV_VAL, &save_val);
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001479 if (name != NULL)
1480 {
1481 set_vim_var_string(VV_VAL, name, -1);
1482 argv[0].v_type = VAR_STRING;
1483 argv[0].vval.v_string = name;
1484 }
1485 else
1486 {
1487 set_vim_var_dict(VV_VAL, dict);
1488 argv[0].v_type = VAR_DICT;
1489 argv[0].vval.v_dict = dict;
1490 }
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001491
1492 if (eval_expr_typval(expr, argv, 1, &rettv) == FAIL)
1493 goto theend;
1494
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001495 // We want to use -1, but also true/false should be allowed.
1496 if (rettv.v_type == VAR_SPECIAL || rettv.v_type == VAR_BOOL)
1497 {
1498 rettv.v_type = VAR_NUMBER;
1499 rettv.vval.v_number = rettv.vval.v_number == VVAL_TRUE;
1500 }
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001501 retval = tv_get_number_chk(&rettv, &error);
1502 if (error)
1503 retval = -1;
1504 clear_tv(&rettv);
1505
1506theend:
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001507 if (name != NULL)
1508 set_vim_var_string(VV_VAL, NULL, 0);
1509 else
1510 set_vim_var_dict(VV_VAL, NULL);
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001511 restore_vimvar(VV_VAL, &save_val);
1512 return retval;
1513}
1514
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001515/*
1516 * Evaluate "expr" (= "context") for readdir().
1517 */
1518 static int
1519readdir_checkitem(void *context, void *item)
1520{
1521 char_u *name = (char_u *)item;
1522
1523 return checkitem_common(context, name, NULL);
1524}
1525
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001526 static int
1527readdirex_dict_arg(typval_T *tv, int *cmp)
1528{
1529 char_u *compare;
1530
1531 if (tv->v_type != VAR_DICT)
1532 {
1533 emsg(_(e_dictreq));
1534 return FAIL;
1535 }
1536
1537 if (dict_find(tv->vval.v_dict, (char_u *)"sort", -1) != NULL)
1538 compare = dict_get_string(tv->vval.v_dict, (char_u *)"sort", FALSE);
1539 else
1540 {
1541 semsg(_(e_no_dict_key), "sort");
1542 return FAIL;
1543 }
1544
1545 if (STRCMP(compare, (char_u *) "none") == 0)
1546 *cmp = READDIR_SORT_NONE;
1547 else if (STRCMP(compare, (char_u *) "case") == 0)
1548 *cmp = READDIR_SORT_BYTE;
1549 else if (STRCMP(compare, (char_u *) "icase") == 0)
1550 *cmp = READDIR_SORT_IC;
1551 else if (STRCMP(compare, (char_u *) "collate") == 0)
1552 *cmp = READDIR_SORT_COLLATE;
1553 return OK;
1554}
1555
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001556/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001557 * "readdir()" function
1558 */
1559 void
1560f_readdir(typval_T *argvars, typval_T *rettv)
1561{
1562 typval_T *expr;
1563 int ret;
1564 char_u *path;
1565 char_u *p;
1566 garray_T ga;
1567 int i;
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001568 int sort = READDIR_SORT_BYTE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001569
1570 if (rettv_list_alloc(rettv) == FAIL)
1571 return;
1572 path = tv_get_string(&argvars[0]);
1573 expr = &argvars[1];
1574
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001575 if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN &&
1576 readdirex_dict_arg(&argvars[2], &sort) == FAIL)
1577 return;
1578
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001579 ret = readdir_core(&ga, path, FALSE, (void *)expr,
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001580 (expr->v_type == VAR_UNKNOWN) ? NULL : readdir_checkitem, sort);
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001581 if (ret == OK)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001582 {
1583 for (i = 0; i < ga.ga_len; i++)
1584 {
1585 p = ((char_u **)ga.ga_data)[i];
1586 list_append_string(rettv->vval.v_list, p, -1);
1587 }
1588 }
1589 ga_clear_strings(&ga);
1590}
1591
1592/*
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001593 * Evaluate "expr" (= "context") for readdirex().
1594 */
1595 static int
1596readdirex_checkitem(void *context, void *item)
1597{
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001598 dict_T *dict = (dict_T*)item;
1599
Bram Moolenaarf8abbf32020-08-19 16:00:06 +02001600 return checkitem_common(context, NULL, dict);
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001601}
1602
1603/*
1604 * "readdirex()" function
1605 */
1606 void
1607f_readdirex(typval_T *argvars, typval_T *rettv)
1608{
1609 typval_T *expr;
1610 int ret;
1611 char_u *path;
1612 garray_T ga;
1613 int i;
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001614 int sort = READDIR_SORT_BYTE;
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001615
1616 if (rettv_list_alloc(rettv) == FAIL)
1617 return;
1618 path = tv_get_string(&argvars[0]);
1619 expr = &argvars[1];
1620
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001621 if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN &&
1622 readdirex_dict_arg(&argvars[2], &sort) == FAIL)
1623 return;
1624
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001625 ret = readdir_core(&ga, path, TRUE, (void *)expr,
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02001626 (expr->v_type == VAR_UNKNOWN) ? NULL : readdirex_checkitem, sort);
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001627 if (ret == OK)
1628 {
1629 for (i = 0; i < ga.ga_len; i++)
1630 {
1631 dict_T *dict = ((dict_T**)ga.ga_data)[i];
1632 list_append_dict(rettv->vval.v_list, dict);
1633 dict_unref(dict);
1634 }
1635 }
1636 ga_clear(&ga);
1637}
1638
1639/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001640 * "readfile()" function
1641 */
1642 void
1643f_readfile(typval_T *argvars, typval_T *rettv)
1644{
1645 int binary = FALSE;
1646 int blob = FALSE;
1647 int failed = FALSE;
1648 char_u *fname;
1649 FILE *fd;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001650 char_u buf[(IOSIZE/256)*256]; // rounded to avoid odd + 1
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001651 int io_size = sizeof(buf);
Bram Moolenaar26262f82019-09-04 20:59:15 +02001652 int readlen; // size of last fread()
1653 char_u *prev = NULL; // previously read bytes, if any
1654 long prevlen = 0; // length of data in prev
1655 long prevsize = 0; // size of prev buffer
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001656 long maxline = MAXLNUM;
1657 long cnt = 0;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001658 char_u *p; // position in buf
1659 char_u *start; // start of current line
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001660
1661 if (argvars[1].v_type != VAR_UNKNOWN)
1662 {
1663 if (STRCMP(tv_get_string(&argvars[1]), "b") == 0)
1664 binary = TRUE;
1665 if (STRCMP(tv_get_string(&argvars[1]), "B") == 0)
1666 blob = TRUE;
1667
1668 if (argvars[2].v_type != VAR_UNKNOWN)
1669 maxline = (long)tv_get_number(&argvars[2]);
1670 }
1671
Bram Moolenaar15352dc2020-04-06 21:12:42 +02001672 if ((blob ? rettv_blob_alloc(rettv) : rettv_list_alloc(rettv)) == FAIL)
1673 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001674
Bram Moolenaar26262f82019-09-04 20:59:15 +02001675 // Always open the file in binary mode, library functions have a mind of
1676 // their own about CR-LF conversion.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001677 fname = tv_get_string(&argvars[0]);
Bram Moolenaar15352dc2020-04-06 21:12:42 +02001678
1679 if (mch_isdir(fname))
1680 {
1681 semsg(_(e_isadir2), fname);
1682 return;
1683 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001684 if (*fname == NUL || (fd = mch_fopen((char *)fname, READBIN)) == NULL)
1685 {
1686 semsg(_(e_notopen), *fname == NUL ? (char_u *)_("<empty>") : fname);
1687 return;
1688 }
1689
1690 if (blob)
1691 {
1692 if (read_blob(fd, rettv->vval.v_blob) == FAIL)
1693 {
Bram Moolenaar15352dc2020-04-06 21:12:42 +02001694 semsg(_(e_notread), fname);
1695 // An empty blob is returned on error.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001696 blob_free(rettv->vval.v_blob);
Bram Moolenaar15352dc2020-04-06 21:12:42 +02001697 rettv->vval.v_blob = NULL;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001698 }
1699 fclose(fd);
1700 return;
1701 }
1702
1703 while (cnt < maxline || maxline < 0)
1704 {
1705 readlen = (int)fread(buf, 1, io_size, fd);
1706
Bram Moolenaar26262f82019-09-04 20:59:15 +02001707 // This for loop processes what was read, but is also entered at end
1708 // of file so that either:
1709 // - an incomplete line gets written
1710 // - a "binary" file gets an empty line at the end if it ends in a
1711 // newline.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001712 for (p = buf, start = buf;
1713 p < buf + readlen || (readlen <= 0 && (prevlen > 0 || binary));
1714 ++p)
1715 {
1716 if (*p == '\n' || readlen <= 0)
1717 {
1718 listitem_T *li;
1719 char_u *s = NULL;
1720 long_u len = p - start;
1721
Bram Moolenaar26262f82019-09-04 20:59:15 +02001722 // Finished a line. Remove CRs before NL.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001723 if (readlen > 0 && !binary)
1724 {
1725 while (len > 0 && start[len - 1] == '\r')
1726 --len;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001727 // removal may cross back to the "prev" string
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001728 if (len == 0)
1729 while (prevlen > 0 && prev[prevlen - 1] == '\r')
1730 --prevlen;
1731 }
1732 if (prevlen == 0)
Bram Moolenaar71ccd032020-06-12 22:59:11 +02001733 s = vim_strnsave(start, len);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001734 else
1735 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001736 // Change "prev" buffer to be the right size. This way
1737 // the bytes are only copied once, and very long lines are
1738 // allocated only once.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001739 if ((s = vim_realloc(prev, prevlen + len + 1)) != NULL)
1740 {
1741 mch_memmove(s + prevlen, start, len);
1742 s[prevlen + len] = NUL;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001743 prev = NULL; // the list will own the string
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001744 prevlen = prevsize = 0;
1745 }
1746 }
1747 if (s == NULL)
1748 {
1749 do_outofmem_msg((long_u) prevlen + len + 1);
1750 failed = TRUE;
1751 break;
1752 }
1753
1754 if ((li = listitem_alloc()) == NULL)
1755 {
1756 vim_free(s);
1757 failed = TRUE;
1758 break;
1759 }
1760 li->li_tv.v_type = VAR_STRING;
1761 li->li_tv.v_lock = 0;
1762 li->li_tv.vval.v_string = s;
1763 list_append(rettv->vval.v_list, li);
1764
Bram Moolenaar26262f82019-09-04 20:59:15 +02001765 start = p + 1; // step over newline
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001766 if ((++cnt >= maxline && maxline >= 0) || readlen <= 0)
1767 break;
1768 }
1769 else if (*p == NUL)
1770 *p = '\n';
Bram Moolenaar26262f82019-09-04 20:59:15 +02001771 // Check for utf8 "bom"; U+FEFF is encoded as EF BB BF. Do this
1772 // when finding the BF and check the previous two bytes.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001773 else if (*p == 0xbf && enc_utf8 && !binary)
1774 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001775 // Find the two bytes before the 0xbf. If p is at buf, or buf
1776 // + 1, these may be in the "prev" string.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001777 char_u back1 = p >= buf + 1 ? p[-1]
1778 : prevlen >= 1 ? prev[prevlen - 1] : NUL;
1779 char_u back2 = p >= buf + 2 ? p[-2]
1780 : p == buf + 1 && prevlen >= 1 ? prev[prevlen - 1]
1781 : prevlen >= 2 ? prev[prevlen - 2] : NUL;
1782
1783 if (back2 == 0xef && back1 == 0xbb)
1784 {
1785 char_u *dest = p - 2;
1786
Bram Moolenaar26262f82019-09-04 20:59:15 +02001787 // Usually a BOM is at the beginning of a file, and so at
1788 // the beginning of a line; then we can just step over it.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001789 if (start == dest)
1790 start = p + 1;
1791 else
1792 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001793 // have to shuffle buf to close gap
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001794 int adjust_prevlen = 0;
1795
1796 if (dest < buf)
1797 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001798 adjust_prevlen = (int)(buf - dest); // must be 1 or 2
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001799 dest = buf;
1800 }
1801 if (readlen > p - buf + 1)
1802 mch_memmove(dest, p + 1, readlen - (p - buf) - 1);
1803 readlen -= 3 - adjust_prevlen;
1804 prevlen -= adjust_prevlen;
1805 p = dest - 1;
1806 }
1807 }
1808 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02001809 } // for
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001810
1811 if (failed || (cnt >= maxline && maxline >= 0) || readlen <= 0)
1812 break;
1813 if (start < p)
1814 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001815 // There's part of a line in buf, store it in "prev".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001816 if (p - start + prevlen >= prevsize)
1817 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001818 // need bigger "prev" buffer
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001819 char_u *newprev;
1820
Bram Moolenaar26262f82019-09-04 20:59:15 +02001821 // A common use case is ordinary text files and "prev" gets a
1822 // fragment of a line, so the first allocation is made
1823 // small, to avoid repeatedly 'allocing' large and
1824 // 'reallocing' small.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001825 if (prevsize == 0)
1826 prevsize = (long)(p - start);
1827 else
1828 {
1829 long grow50pc = (prevsize * 3) / 2;
1830 long growmin = (long)((p - start) * 2 + prevlen);
1831 prevsize = grow50pc > growmin ? grow50pc : growmin;
1832 }
1833 newprev = vim_realloc(prev, prevsize);
1834 if (newprev == NULL)
1835 {
1836 do_outofmem_msg((long_u)prevsize);
1837 failed = TRUE;
1838 break;
1839 }
1840 prev = newprev;
1841 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02001842 // Add the line part to end of "prev".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001843 mch_memmove(prev + prevlen, start, p - start);
1844 prevlen += (long)(p - start);
1845 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02001846 } // while
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001847
Bram Moolenaar26262f82019-09-04 20:59:15 +02001848 // For a negative line count use only the lines at the end of the file,
1849 // free the rest.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001850 if (!failed && maxline < 0)
1851 while (cnt > -maxline)
1852 {
1853 listitem_remove(rettv->vval.v_list, rettv->vval.v_list->lv_first);
1854 --cnt;
1855 }
1856
1857 if (failed)
1858 {
1859 // an empty list is returned on error
1860 list_free(rettv->vval.v_list);
1861 rettv_list_alloc(rettv);
1862 }
1863
1864 vim_free(prev);
1865 fclose(fd);
1866}
1867
1868/*
1869 * "resolve()" function
1870 */
1871 void
1872f_resolve(typval_T *argvars, typval_T *rettv)
1873{
1874 char_u *p;
1875#ifdef HAVE_READLINK
1876 char_u *buf = NULL;
1877#endif
1878
1879 p = tv_get_string(&argvars[0]);
1880#ifdef FEAT_SHORTCUT
1881 {
1882 char_u *v = NULL;
1883
1884 v = mch_resolve_path(p, TRUE);
1885 if (v != NULL)
1886 rettv->vval.v_string = v;
1887 else
1888 rettv->vval.v_string = vim_strsave(p);
1889 }
1890#else
1891# ifdef HAVE_READLINK
1892 {
1893 char_u *cpy;
1894 int len;
1895 char_u *remain = NULL;
1896 char_u *q;
1897 int is_relative_to_current = FALSE;
1898 int has_trailing_pathsep = FALSE;
1899 int limit = 100;
1900
1901 p = vim_strsave(p);
Bram Moolenaar70188f52019-12-23 18:18:52 +01001902 if (p == NULL)
1903 goto fail;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001904 if (p[0] == '.' && (vim_ispathsep(p[1])
1905 || (p[1] == '.' && (vim_ispathsep(p[2])))))
1906 is_relative_to_current = TRUE;
1907
1908 len = STRLEN(p);
Bram Moolenaar50c4e9e2020-10-05 20:38:06 +02001909 if (len > 1 && after_pathsep(p, p + len))
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001910 {
1911 has_trailing_pathsep = TRUE;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001912 p[len - 1] = NUL; // the trailing slash breaks readlink()
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001913 }
1914
1915 q = getnextcomp(p);
1916 if (*q != NUL)
1917 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001918 // Separate the first path component in "p", and keep the
1919 // remainder (beginning with the path separator).
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001920 remain = vim_strsave(q - 1);
1921 q[-1] = NUL;
1922 }
1923
1924 buf = alloc(MAXPATHL + 1);
1925 if (buf == NULL)
Bram Moolenaar70188f52019-12-23 18:18:52 +01001926 {
1927 vim_free(p);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001928 goto fail;
Bram Moolenaar70188f52019-12-23 18:18:52 +01001929 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001930
1931 for (;;)
1932 {
1933 for (;;)
1934 {
1935 len = readlink((char *)p, (char *)buf, MAXPATHL);
1936 if (len <= 0)
1937 break;
1938 buf[len] = NUL;
1939
1940 if (limit-- == 0)
1941 {
1942 vim_free(p);
1943 vim_free(remain);
1944 emsg(_("E655: Too many symbolic links (cycle?)"));
1945 rettv->vval.v_string = NULL;
1946 goto fail;
1947 }
1948
Bram Moolenaar26262f82019-09-04 20:59:15 +02001949 // Ensure that the result will have a trailing path separator
1950 // if the argument has one.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001951 if (remain == NULL && has_trailing_pathsep)
1952 add_pathsep(buf);
1953
Bram Moolenaar26262f82019-09-04 20:59:15 +02001954 // Separate the first path component in the link value and
1955 // concatenate the remainders.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001956 q = getnextcomp(vim_ispathsep(*buf) ? buf + 1 : buf);
1957 if (*q != NUL)
1958 {
1959 if (remain == NULL)
1960 remain = vim_strsave(q - 1);
1961 else
1962 {
1963 cpy = concat_str(q - 1, remain);
1964 if (cpy != NULL)
1965 {
1966 vim_free(remain);
1967 remain = cpy;
1968 }
1969 }
1970 q[-1] = NUL;
1971 }
1972
1973 q = gettail(p);
1974 if (q > p && *q == NUL)
1975 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001976 // Ignore trailing path separator.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001977 q[-1] = NUL;
1978 q = gettail(p);
1979 }
1980 if (q > p && !mch_isFullName(buf))
1981 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001982 // symlink is relative to directory of argument
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001983 cpy = alloc(STRLEN(p) + STRLEN(buf) + 1);
1984 if (cpy != NULL)
1985 {
1986 STRCPY(cpy, p);
1987 STRCPY(gettail(cpy), buf);
1988 vim_free(p);
1989 p = cpy;
1990 }
1991 }
1992 else
1993 {
1994 vim_free(p);
1995 p = vim_strsave(buf);
1996 }
1997 }
1998
1999 if (remain == NULL)
2000 break;
2001
Bram Moolenaar26262f82019-09-04 20:59:15 +02002002 // Append the first path component of "remain" to "p".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002003 q = getnextcomp(remain + 1);
2004 len = q - remain - (*q != NUL);
2005 cpy = vim_strnsave(p, STRLEN(p) + len);
2006 if (cpy != NULL)
2007 {
2008 STRNCAT(cpy, remain, len);
2009 vim_free(p);
2010 p = cpy;
2011 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02002012 // Shorten "remain".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002013 if (*q != NUL)
2014 STRMOVE(remain, q - 1);
2015 else
2016 VIM_CLEAR(remain);
2017 }
2018
Bram Moolenaar26262f82019-09-04 20:59:15 +02002019 // If the result is a relative path name, make it explicitly relative to
2020 // the current directory if and only if the argument had this form.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002021 if (!vim_ispathsep(*p))
2022 {
2023 if (is_relative_to_current
2024 && *p != NUL
2025 && !(p[0] == '.'
2026 && (p[1] == NUL
2027 || vim_ispathsep(p[1])
2028 || (p[1] == '.'
2029 && (p[2] == NUL
2030 || vim_ispathsep(p[2]))))))
2031 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002032 // Prepend "./".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002033 cpy = concat_str((char_u *)"./", p);
2034 if (cpy != NULL)
2035 {
2036 vim_free(p);
2037 p = cpy;
2038 }
2039 }
2040 else if (!is_relative_to_current)
2041 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002042 // Strip leading "./".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002043 q = p;
2044 while (q[0] == '.' && vim_ispathsep(q[1]))
2045 q += 2;
2046 if (q > p)
2047 STRMOVE(p, p + 2);
2048 }
2049 }
2050
Bram Moolenaar26262f82019-09-04 20:59:15 +02002051 // Ensure that the result will have no trailing path separator
2052 // if the argument had none. But keep "/" or "//".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002053 if (!has_trailing_pathsep)
2054 {
2055 q = p + STRLEN(p);
2056 if (after_pathsep(p, q))
2057 *gettail_sep(p) = NUL;
2058 }
2059
2060 rettv->vval.v_string = p;
2061 }
2062# else
2063 rettv->vval.v_string = vim_strsave(p);
2064# endif
2065#endif
2066
2067 simplify_filename(rettv->vval.v_string);
2068
2069#ifdef HAVE_READLINK
2070fail:
2071 vim_free(buf);
2072#endif
2073 rettv->v_type = VAR_STRING;
2074}
2075
2076/*
2077 * "tempname()" function
2078 */
2079 void
2080f_tempname(typval_T *argvars UNUSED, typval_T *rettv)
2081{
2082 static int x = 'A';
2083
2084 rettv->v_type = VAR_STRING;
2085 rettv->vval.v_string = vim_tempname(x, FALSE);
2086
Bram Moolenaar26262f82019-09-04 20:59:15 +02002087 // Advance 'x' to use A-Z and 0-9, so that there are at least 34 different
2088 // names. Skip 'I' and 'O', they are used for shell redirection.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002089 do
2090 {
2091 if (x == 'Z')
2092 x = '0';
2093 else if (x == '9')
2094 x = 'A';
2095 else
2096 {
2097#ifdef EBCDIC
2098 if (x == 'I')
2099 x = 'J';
2100 else if (x == 'R')
2101 x = 'S';
2102 else
2103#endif
2104 ++x;
2105 }
2106 } while (x == 'I' || x == 'O');
2107}
2108
2109/*
2110 * "writefile()" function
2111 */
2112 void
2113f_writefile(typval_T *argvars, typval_T *rettv)
2114{
2115 int binary = FALSE;
2116 int append = FALSE;
2117#ifdef HAVE_FSYNC
2118 int do_fsync = p_fs;
2119#endif
2120 char_u *fname;
2121 FILE *fd;
2122 int ret = 0;
2123 listitem_T *li;
2124 list_T *list = NULL;
2125 blob_T *blob = NULL;
2126
2127 rettv->vval.v_number = -1;
2128 if (check_secure())
2129 return;
2130
2131 if (argvars[0].v_type == VAR_LIST)
2132 {
2133 list = argvars[0].vval.v_list;
2134 if (list == NULL)
2135 return;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02002136 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002137 FOR_ALL_LIST_ITEMS(list, li)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002138 if (tv_get_string_chk(&li->li_tv) == NULL)
2139 return;
2140 }
2141 else if (argvars[0].v_type == VAR_BLOB)
2142 {
2143 blob = argvars[0].vval.v_blob;
2144 if (blob == NULL)
2145 return;
2146 }
2147 else
2148 {
Bram Moolenaar18a2b872020-03-19 13:08:45 +01002149 semsg(_(e_invarg2),
2150 _("writefile() first argument must be a List or a Blob"));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002151 return;
2152 }
2153
2154 if (argvars[2].v_type != VAR_UNKNOWN)
2155 {
2156 char_u *arg2 = tv_get_string_chk(&argvars[2]);
2157
2158 if (arg2 == NULL)
2159 return;
2160 if (vim_strchr(arg2, 'b') != NULL)
2161 binary = TRUE;
2162 if (vim_strchr(arg2, 'a') != NULL)
2163 append = TRUE;
2164#ifdef HAVE_FSYNC
2165 if (vim_strchr(arg2, 's') != NULL)
2166 do_fsync = TRUE;
2167 else if (vim_strchr(arg2, 'S') != NULL)
2168 do_fsync = FALSE;
2169#endif
2170 }
2171
2172 fname = tv_get_string_chk(&argvars[1]);
2173 if (fname == NULL)
2174 return;
2175
Bram Moolenaar26262f82019-09-04 20:59:15 +02002176 // Always open the file in binary mode, library functions have a mind of
2177 // their own about CR-LF conversion.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002178 if (*fname == NUL || (fd = mch_fopen((char *)fname,
2179 append ? APPENDBIN : WRITEBIN)) == NULL)
2180 {
2181 semsg(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
2182 ret = -1;
2183 }
2184 else if (blob)
2185 {
2186 if (write_blob(fd, blob) == FAIL)
2187 ret = -1;
2188#ifdef HAVE_FSYNC
2189 else if (do_fsync)
2190 // Ignore the error, the user wouldn't know what to do about it.
2191 // May happen for a device.
2192 vim_ignored = vim_fsync(fileno(fd));
2193#endif
2194 fclose(fd);
2195 }
2196 else
2197 {
2198 if (write_list(fd, list, binary) == FAIL)
2199 ret = -1;
2200#ifdef HAVE_FSYNC
2201 else if (do_fsync)
Bram Moolenaar26262f82019-09-04 20:59:15 +02002202 // Ignore the error, the user wouldn't know what to do about it.
2203 // May happen for a device.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002204 vim_ignored = vim_fsync(fileno(fd));
2205#endif
2206 fclose(fd);
2207 }
2208
2209 rettv->vval.v_number = ret;
2210}
2211
2212#endif // FEAT_EVAL
2213
2214#if defined(FEAT_BROWSE) || defined(PROTO)
2215/*
2216 * Generic browse function. Calls gui_mch_browse() when possible.
2217 * Later this may pop-up a non-GUI file selector (external command?).
2218 */
2219 char_u *
2220do_browse(
Bram Moolenaar26262f82019-09-04 20:59:15 +02002221 int flags, // BROWSE_SAVE and BROWSE_DIR
2222 char_u *title, // title for the window
2223 char_u *dflt, // default file name (may include directory)
2224 char_u *ext, // extension added
2225 char_u *initdir, // initial directory, NULL for current dir or
2226 // when using path from "dflt"
2227 char_u *filter, // file name filter
2228 buf_T *buf) // buffer to read/write for
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002229{
2230 char_u *fname;
Bram Moolenaar26262f82019-09-04 20:59:15 +02002231 static char_u *last_dir = NULL; // last used directory
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002232 char_u *tofree = NULL;
Bram Moolenaare1004402020-10-24 20:49:43 +02002233 int save_cmod_flags = cmdmod.cmod_flags;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002234
Bram Moolenaar26262f82019-09-04 20:59:15 +02002235 // Must turn off browse to avoid that autocommands will get the
2236 // flag too!
Bram Moolenaare1004402020-10-24 20:49:43 +02002237 cmdmod.cmod_flags &= ~CMOD_BROWSE;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002238
2239 if (title == NULL || *title == NUL)
2240 {
2241 if (flags & BROWSE_DIR)
2242 title = (char_u *)_("Select Directory dialog");
2243 else if (flags & BROWSE_SAVE)
2244 title = (char_u *)_("Save File dialog");
2245 else
2246 title = (char_u *)_("Open File dialog");
2247 }
2248
Bram Moolenaar26262f82019-09-04 20:59:15 +02002249 // When no directory specified, use default file name, default dir, buffer
2250 // dir, last dir or current dir
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002251 if ((initdir == NULL || *initdir == NUL) && dflt != NULL && *dflt != NUL)
2252 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002253 if (mch_isdir(dflt)) // default file name is a directory
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002254 {
2255 initdir = dflt;
2256 dflt = NULL;
2257 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02002258 else if (gettail(dflt) != dflt) // default file name includes a path
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002259 {
2260 tofree = vim_strsave(dflt);
2261 if (tofree != NULL)
2262 {
2263 initdir = tofree;
2264 *gettail(initdir) = NUL;
2265 dflt = gettail(dflt);
2266 }
2267 }
2268 }
2269
2270 if (initdir == NULL || *initdir == NUL)
2271 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002272 // When 'browsedir' is a directory, use it
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002273 if (STRCMP(p_bsdir, "last") != 0
2274 && STRCMP(p_bsdir, "buffer") != 0
2275 && STRCMP(p_bsdir, "current") != 0
2276 && mch_isdir(p_bsdir))
2277 initdir = p_bsdir;
Bram Moolenaar26262f82019-09-04 20:59:15 +02002278 // When saving or 'browsedir' is "buffer", use buffer fname
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002279 else if (((flags & BROWSE_SAVE) || *p_bsdir == 'b')
2280 && buf != NULL && buf->b_ffname != NULL)
2281 {
2282 if (dflt == NULL || *dflt == NUL)
2283 dflt = gettail(curbuf->b_ffname);
2284 tofree = vim_strsave(curbuf->b_ffname);
2285 if (tofree != NULL)
2286 {
2287 initdir = tofree;
2288 *gettail(initdir) = NUL;
2289 }
2290 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02002291 // When 'browsedir' is "last", use dir from last browse
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002292 else if (*p_bsdir == 'l')
2293 initdir = last_dir;
Bram Moolenaar26262f82019-09-04 20:59:15 +02002294 // When 'browsedir is "current", use current directory. This is the
2295 // default already, leave initdir empty.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002296 }
2297
2298# ifdef FEAT_GUI
Bram Moolenaar26262f82019-09-04 20:59:15 +02002299 if (gui.in_use) // when this changes, also adjust f_has()!
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002300 {
2301 if (filter == NULL
2302# ifdef FEAT_EVAL
2303 && (filter = get_var_value((char_u *)"b:browsefilter")) == NULL
2304 && (filter = get_var_value((char_u *)"g:browsefilter")) == NULL
2305# endif
2306 )
2307 filter = BROWSE_FILTER_DEFAULT;
2308 if (flags & BROWSE_DIR)
2309 {
2310# if defined(FEAT_GUI_GTK) || defined(MSWIN)
Bram Moolenaar26262f82019-09-04 20:59:15 +02002311 // For systems that have a directory dialog.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002312 fname = gui_mch_browsedir(title, initdir);
2313# else
Bram Moolenaar26262f82019-09-04 20:59:15 +02002314 // Generic solution for selecting a directory: select a file and
2315 // remove the file name.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002316 fname = gui_mch_browse(0, title, dflt, ext, initdir, (char_u *)"");
2317# endif
2318# if !defined(FEAT_GUI_GTK)
Bram Moolenaar26262f82019-09-04 20:59:15 +02002319 // Win32 adds a dummy file name, others return an arbitrary file
2320 // name. GTK+ 2 returns only the directory,
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002321 if (fname != NULL && *fname != NUL && !mch_isdir(fname))
2322 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002323 // Remove the file name.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002324 char_u *tail = gettail_sep(fname);
2325
2326 if (tail == fname)
Bram Moolenaar26262f82019-09-04 20:59:15 +02002327 *tail++ = '.'; // use current dir
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002328 *tail = NUL;
2329 }
2330# endif
2331 }
2332 else
2333 fname = gui_mch_browse(flags & BROWSE_SAVE,
2334 title, dflt, ext, initdir, (char_u *)_(filter));
2335
Bram Moolenaar26262f82019-09-04 20:59:15 +02002336 // We hang around in the dialog for a while, the user might do some
2337 // things to our files. The Win32 dialog allows deleting or renaming
2338 // a file, check timestamps.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002339 need_check_timestamps = TRUE;
2340 did_check_timestamps = FALSE;
2341 }
2342 else
2343# endif
2344 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002345 // TODO: non-GUI file selector here
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002346 emsg(_("E338: Sorry, no file browser in console mode"));
2347 fname = NULL;
2348 }
2349
Bram Moolenaar26262f82019-09-04 20:59:15 +02002350 // keep the directory for next time
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002351 if (fname != NULL)
2352 {
2353 vim_free(last_dir);
2354 last_dir = vim_strsave(fname);
2355 if (last_dir != NULL && !(flags & BROWSE_DIR))
2356 {
2357 *gettail(last_dir) = NUL;
2358 if (*last_dir == NUL)
2359 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002360 // filename only returned, must be in current dir
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002361 vim_free(last_dir);
2362 last_dir = alloc(MAXPATHL);
2363 if (last_dir != NULL)
2364 mch_dirname(last_dir, MAXPATHL);
2365 }
2366 }
2367 }
2368
2369 vim_free(tofree);
Bram Moolenaare1004402020-10-24 20:49:43 +02002370 cmdmod.cmod_flags = save_cmod_flags;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002371
2372 return fname;
2373}
2374#endif
2375
2376#if defined(FEAT_EVAL) || defined(PROTO)
2377
2378/*
2379 * "browse(save, title, initdir, default)" function
2380 */
2381 void
2382f_browse(typval_T *argvars UNUSED, typval_T *rettv)
2383{
2384# ifdef FEAT_BROWSE
2385 int save;
2386 char_u *title;
2387 char_u *initdir;
2388 char_u *defname;
2389 char_u buf[NUMBUFLEN];
2390 char_u buf2[NUMBUFLEN];
2391 int error = FALSE;
2392
2393 save = (int)tv_get_number_chk(&argvars[0], &error);
2394 title = tv_get_string_chk(&argvars[1]);
2395 initdir = tv_get_string_buf_chk(&argvars[2], buf);
2396 defname = tv_get_string_buf_chk(&argvars[3], buf2);
2397
2398 if (error || title == NULL || initdir == NULL || defname == NULL)
2399 rettv->vval.v_string = NULL;
2400 else
2401 rettv->vval.v_string =
2402 do_browse(save ? BROWSE_SAVE : 0,
2403 title, defname, NULL, initdir, NULL, curbuf);
2404# else
2405 rettv->vval.v_string = NULL;
2406# endif
2407 rettv->v_type = VAR_STRING;
2408}
2409
2410/*
2411 * "browsedir(title, initdir)" function
2412 */
2413 void
2414f_browsedir(typval_T *argvars UNUSED, typval_T *rettv)
2415{
2416# ifdef FEAT_BROWSE
2417 char_u *title;
2418 char_u *initdir;
2419 char_u buf[NUMBUFLEN];
2420
2421 title = tv_get_string_chk(&argvars[0]);
2422 initdir = tv_get_string_buf_chk(&argvars[1], buf);
2423
2424 if (title == NULL || initdir == NULL)
2425 rettv->vval.v_string = NULL;
2426 else
2427 rettv->vval.v_string = do_browse(BROWSE_DIR,
2428 title, NULL, NULL, initdir, NULL, curbuf);
2429# else
2430 rettv->vval.v_string = NULL;
2431# endif
2432 rettv->v_type = VAR_STRING;
2433}
2434
2435#endif // FEAT_EVAL
Bram Moolenaar26262f82019-09-04 20:59:15 +02002436
2437/*
2438 * Replace home directory by "~" in each space or comma separated file name in
2439 * 'src'.
2440 * If anything fails (except when out of space) dst equals src.
2441 */
2442 void
2443home_replace(
2444 buf_T *buf, // when not NULL, check for help files
2445 char_u *src, // input file name
2446 char_u *dst, // where to put the result
2447 int dstlen, // maximum length of the result
2448 int one) // if TRUE, only replace one file name, include
2449 // spaces and commas in the file name.
2450{
2451 size_t dirlen = 0, envlen = 0;
2452 size_t len;
2453 char_u *homedir_env, *homedir_env_orig;
2454 char_u *p;
2455
2456 if (src == NULL)
2457 {
2458 *dst = NUL;
2459 return;
2460 }
2461
2462 /*
2463 * If the file is a help file, remove the path completely.
2464 */
2465 if (buf != NULL && buf->b_help)
2466 {
2467 vim_snprintf((char *)dst, dstlen, "%s", gettail(src));
2468 return;
2469 }
2470
2471 /*
2472 * We check both the value of the $HOME environment variable and the
2473 * "real" home directory.
2474 */
2475 if (homedir != NULL)
2476 dirlen = STRLEN(homedir);
2477
2478#ifdef VMS
2479 homedir_env_orig = homedir_env = mch_getenv((char_u *)"SYS$LOGIN");
2480#else
2481 homedir_env_orig = homedir_env = mch_getenv((char_u *)"HOME");
2482#endif
2483#ifdef MSWIN
2484 if (homedir_env == NULL)
2485 homedir_env_orig = homedir_env = mch_getenv((char_u *)"USERPROFILE");
2486#endif
2487 // Empty is the same as not set.
2488 if (homedir_env != NULL && *homedir_env == NUL)
2489 homedir_env = NULL;
2490
2491 if (homedir_env != NULL && *homedir_env == '~')
2492 {
2493 int usedlen = 0;
2494 int flen;
2495 char_u *fbuf = NULL;
2496
2497 flen = (int)STRLEN(homedir_env);
2498 (void)modify_fname((char_u *)":p", FALSE, &usedlen,
2499 &homedir_env, &fbuf, &flen);
2500 flen = (int)STRLEN(homedir_env);
2501 if (flen > 0 && vim_ispathsep(homedir_env[flen - 1]))
2502 // Remove the trailing / that is added to a directory.
2503 homedir_env[flen - 1] = NUL;
2504 }
2505
2506 if (homedir_env != NULL)
2507 envlen = STRLEN(homedir_env);
2508
2509 if (!one)
2510 src = skipwhite(src);
2511 while (*src && dstlen > 0)
2512 {
2513 /*
2514 * Here we are at the beginning of a file name.
2515 * First, check to see if the beginning of the file name matches
2516 * $HOME or the "real" home directory. Check that there is a '/'
2517 * after the match (so that if e.g. the file is "/home/pieter/bla",
2518 * and the home directory is "/home/piet", the file does not end up
2519 * as "~er/bla" (which would seem to indicate the file "bla" in user
2520 * er's home directory)).
2521 */
2522 p = homedir;
2523 len = dirlen;
2524 for (;;)
2525 {
2526 if ( len
2527 && fnamencmp(src, p, len) == 0
2528 && (vim_ispathsep(src[len])
2529 || (!one && (src[len] == ',' || src[len] == ' '))
2530 || src[len] == NUL))
2531 {
2532 src += len;
2533 if (--dstlen > 0)
2534 *dst++ = '~';
2535
Bram Moolenaar0e390f42020-06-10 13:12:28 +02002536 // Do not add directory separator into dst, because dst is
2537 // expected to just return the directory name without the
2538 // directory separator '/'.
Bram Moolenaar26262f82019-09-04 20:59:15 +02002539 break;
2540 }
2541 if (p == homedir_env)
2542 break;
2543 p = homedir_env;
2544 len = envlen;
2545 }
2546
2547 // if (!one) skip to separator: space or comma
2548 while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0)
2549 *dst++ = *src++;
2550 // skip separator
2551 while ((*src == ' ' || *src == ',') && --dstlen > 0)
2552 *dst++ = *src++;
2553 }
2554 // if (dstlen == 0) out of space, what to do???
2555
2556 *dst = NUL;
2557
2558 if (homedir_env != homedir_env_orig)
2559 vim_free(homedir_env);
2560}
2561
2562/*
2563 * Like home_replace, store the replaced string in allocated memory.
2564 * When something fails, NULL is returned.
2565 */
2566 char_u *
2567home_replace_save(
2568 buf_T *buf, // when not NULL, check for help files
2569 char_u *src) // input file name
2570{
2571 char_u *dst;
2572 unsigned len;
2573
2574 len = 3; // space for "~/" and trailing NUL
2575 if (src != NULL) // just in case
2576 len += (unsigned)STRLEN(src);
2577 dst = alloc(len);
2578 if (dst != NULL)
2579 home_replace(buf, src, dst, len, TRUE);
2580 return dst;
2581}
2582
2583/*
2584 * Compare two file names and return:
2585 * FPC_SAME if they both exist and are the same file.
2586 * FPC_SAMEX if they both don't exist and have the same file name.
2587 * FPC_DIFF if they both exist and are different files.
2588 * FPC_NOTX if they both don't exist.
2589 * FPC_DIFFX if one of them doesn't exist.
2590 * For the first name environment variables are expanded if "expandenv" is
2591 * TRUE.
2592 */
2593 int
2594fullpathcmp(
2595 char_u *s1,
2596 char_u *s2,
2597 int checkname, // when both don't exist, check file names
2598 int expandenv)
2599{
2600#ifdef UNIX
2601 char_u exp1[MAXPATHL];
2602 char_u full1[MAXPATHL];
2603 char_u full2[MAXPATHL];
2604 stat_T st1, st2;
2605 int r1, r2;
2606
2607 if (expandenv)
2608 expand_env(s1, exp1, MAXPATHL);
2609 else
2610 vim_strncpy(exp1, s1, MAXPATHL - 1);
2611 r1 = mch_stat((char *)exp1, &st1);
2612 r2 = mch_stat((char *)s2, &st2);
2613 if (r1 != 0 && r2 != 0)
2614 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002615 // if mch_stat() doesn't work, may compare the names
Bram Moolenaar26262f82019-09-04 20:59:15 +02002616 if (checkname)
2617 {
2618 if (fnamecmp(exp1, s2) == 0)
2619 return FPC_SAMEX;
2620 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
2621 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
2622 if (r1 == OK && r2 == OK && fnamecmp(full1, full2) == 0)
2623 return FPC_SAMEX;
2624 }
2625 return FPC_NOTX;
2626 }
2627 if (r1 != 0 || r2 != 0)
2628 return FPC_DIFFX;
2629 if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
2630 return FPC_SAME;
2631 return FPC_DIFF;
2632#else
2633 char_u *exp1; // expanded s1
2634 char_u *full1; // full path of s1
2635 char_u *full2; // full path of s2
2636 int retval = FPC_DIFF;
2637 int r1, r2;
2638
2639 // allocate one buffer to store three paths (alloc()/free() is slow!)
2640 if ((exp1 = alloc(MAXPATHL * 3)) != NULL)
2641 {
2642 full1 = exp1 + MAXPATHL;
2643 full2 = full1 + MAXPATHL;
2644
2645 if (expandenv)
2646 expand_env(s1, exp1, MAXPATHL);
2647 else
2648 vim_strncpy(exp1, s1, MAXPATHL - 1);
2649 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
2650 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
2651
2652 // If vim_FullName() fails, the file probably doesn't exist.
2653 if (r1 != OK && r2 != OK)
2654 {
2655 if (checkname && fnamecmp(exp1, s2) == 0)
2656 retval = FPC_SAMEX;
2657 else
2658 retval = FPC_NOTX;
2659 }
2660 else if (r1 != OK || r2 != OK)
2661 retval = FPC_DIFFX;
2662 else if (fnamecmp(full1, full2))
2663 retval = FPC_DIFF;
2664 else
2665 retval = FPC_SAME;
2666 vim_free(exp1);
2667 }
2668 return retval;
2669#endif
2670}
2671
2672/*
2673 * Get the tail of a path: the file name.
2674 * When the path ends in a path separator the tail is the NUL after it.
2675 * Fail safe: never returns NULL.
2676 */
2677 char_u *
2678gettail(char_u *fname)
2679{
2680 char_u *p1, *p2;
2681
2682 if (fname == NULL)
2683 return (char_u *)"";
2684 for (p1 = p2 = get_past_head(fname); *p2; ) // find last part of path
2685 {
2686 if (vim_ispathsep_nocolon(*p2))
2687 p1 = p2 + 1;
2688 MB_PTR_ADV(p2);
2689 }
2690 return p1;
2691}
2692
2693/*
2694 * Get pointer to tail of "fname", including path separators. Putting a NUL
2695 * here leaves the directory name. Takes care of "c:/" and "//".
2696 * Always returns a valid pointer.
2697 */
2698 char_u *
2699gettail_sep(char_u *fname)
2700{
2701 char_u *p;
2702 char_u *t;
2703
2704 p = get_past_head(fname); // don't remove the '/' from "c:/file"
2705 t = gettail(fname);
2706 while (t > p && after_pathsep(fname, t))
2707 --t;
2708#ifdef VMS
2709 // path separator is part of the path
2710 ++t;
2711#endif
2712 return t;
2713}
2714
2715/*
2716 * get the next path component (just after the next path separator).
2717 */
2718 char_u *
2719getnextcomp(char_u *fname)
2720{
2721 while (*fname && !vim_ispathsep(*fname))
2722 MB_PTR_ADV(fname);
2723 if (*fname)
2724 ++fname;
2725 return fname;
2726}
2727
2728/*
2729 * Get a pointer to one character past the head of a path name.
2730 * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
2731 * If there is no head, path is returned.
2732 */
2733 char_u *
2734get_past_head(char_u *path)
2735{
2736 char_u *retval;
2737
2738#if defined(MSWIN)
2739 // may skip "c:"
2740 if (isalpha(path[0]) && path[1] == ':')
2741 retval = path + 2;
2742 else
2743 retval = path;
2744#else
2745# if defined(AMIGA)
2746 // may skip "label:"
2747 retval = vim_strchr(path, ':');
2748 if (retval == NULL)
2749 retval = path;
2750# else // Unix
2751 retval = path;
2752# endif
2753#endif
2754
2755 while (vim_ispathsep(*retval))
2756 ++retval;
2757
2758 return retval;
2759}
2760
2761/*
2762 * Return TRUE if 'c' is a path separator.
2763 * Note that for MS-Windows this includes the colon.
2764 */
2765 int
2766vim_ispathsep(int c)
2767{
2768#ifdef UNIX
2769 return (c == '/'); // UNIX has ':' inside file names
2770#else
2771# ifdef BACKSLASH_IN_FILENAME
2772 return (c == ':' || c == '/' || c == '\\');
2773# else
2774# ifdef VMS
2775 // server"user passwd"::device:[full.path.name]fname.extension;version"
2776 return (c == ':' || c == '[' || c == ']' || c == '/'
2777 || c == '<' || c == '>' || c == '"' );
2778# else
2779 return (c == ':' || c == '/');
2780# endif // VMS
2781# endif
2782#endif
2783}
2784
2785/*
2786 * Like vim_ispathsep(c), but exclude the colon for MS-Windows.
2787 */
2788 int
2789vim_ispathsep_nocolon(int c)
2790{
2791 return vim_ispathsep(c)
2792#ifdef BACKSLASH_IN_FILENAME
2793 && c != ':'
2794#endif
2795 ;
2796}
2797
2798/*
Bram Moolenaar26262f82019-09-04 20:59:15 +02002799 * Return TRUE if the directory of "fname" exists, FALSE otherwise.
2800 * Also returns TRUE if there is no directory name.
2801 * "fname" must be writable!.
2802 */
2803 int
2804dir_of_file_exists(char_u *fname)
2805{
2806 char_u *p;
2807 int c;
2808 int retval;
2809
2810 p = gettail_sep(fname);
2811 if (p == fname)
2812 return TRUE;
2813 c = *p;
2814 *p = NUL;
2815 retval = mch_isdir(fname);
2816 *p = c;
2817 return retval;
2818}
2819
2820/*
2821 * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally
2822 * and deal with 'fileignorecase'.
2823 */
2824 int
2825vim_fnamecmp(char_u *x, char_u *y)
2826{
2827#ifdef BACKSLASH_IN_FILENAME
2828 return vim_fnamencmp(x, y, MAXPATHL);
2829#else
2830 if (p_fic)
2831 return MB_STRICMP(x, y);
2832 return STRCMP(x, y);
2833#endif
2834}
2835
2836 int
2837vim_fnamencmp(char_u *x, char_u *y, size_t len)
2838{
2839#ifdef BACKSLASH_IN_FILENAME
2840 char_u *px = x;
2841 char_u *py = y;
2842 int cx = NUL;
2843 int cy = NUL;
2844
2845 while (len > 0)
2846 {
2847 cx = PTR2CHAR(px);
2848 cy = PTR2CHAR(py);
2849 if (cx == NUL || cy == NUL
2850 || ((p_fic ? MB_TOLOWER(cx) != MB_TOLOWER(cy) : cx != cy)
2851 && !(cx == '/' && cy == '\\')
2852 && !(cx == '\\' && cy == '/')))
2853 break;
Bram Moolenaar1614a142019-10-06 22:00:13 +02002854 len -= mb_ptr2len(px);
2855 px += mb_ptr2len(px);
2856 py += mb_ptr2len(py);
Bram Moolenaar26262f82019-09-04 20:59:15 +02002857 }
2858 if (len == 0)
2859 return 0;
2860 return (cx - cy);
2861#else
2862 if (p_fic)
2863 return MB_STRNICMP(x, y, len);
2864 return STRNCMP(x, y, len);
2865#endif
2866}
2867
2868/*
2869 * Concatenate file names fname1 and fname2 into allocated memory.
2870 * Only add a '/' or '\\' when 'sep' is TRUE and it is necessary.
2871 */
2872 char_u *
2873concat_fnames(char_u *fname1, char_u *fname2, int sep)
2874{
2875 char_u *dest;
2876
2877 dest = alloc(STRLEN(fname1) + STRLEN(fname2) + 3);
2878 if (dest != NULL)
2879 {
2880 STRCPY(dest, fname1);
2881 if (sep)
2882 add_pathsep(dest);
2883 STRCAT(dest, fname2);
2884 }
2885 return dest;
2886}
2887
2888/*
2889 * Add a path separator to a file name, unless it already ends in a path
2890 * separator.
2891 */
2892 void
2893add_pathsep(char_u *p)
2894{
2895 if (*p != NUL && !after_pathsep(p, p + STRLEN(p)))
2896 STRCAT(p, PATHSEPSTR);
2897}
2898
2899/*
2900 * FullName_save - Make an allocated copy of a full file name.
2901 * Returns NULL when out of memory.
2902 */
2903 char_u *
2904FullName_save(
2905 char_u *fname,
2906 int force) // force expansion, even when it already looks
2907 // like a full path name
2908{
2909 char_u *buf;
2910 char_u *new_fname = NULL;
2911
2912 if (fname == NULL)
2913 return NULL;
2914
2915 buf = alloc(MAXPATHL);
2916 if (buf != NULL)
2917 {
2918 if (vim_FullName(fname, buf, MAXPATHL, force) != FAIL)
2919 new_fname = vim_strsave(buf);
2920 else
2921 new_fname = vim_strsave(fname);
2922 vim_free(buf);
2923 }
2924 return new_fname;
2925}
2926
2927/*
2928 * return TRUE if "fname" exists.
2929 */
2930 int
2931vim_fexists(char_u *fname)
2932{
2933 stat_T st;
2934
2935 if (mch_stat((char *)fname, &st))
2936 return FALSE;
2937 return TRUE;
2938}
2939
2940/*
2941 * Invoke expand_wildcards() for one pattern.
2942 * Expand items like "%:h" before the expansion.
2943 * Returns OK or FAIL.
2944 */
2945 int
2946expand_wildcards_eval(
2947 char_u **pat, // pointer to input pattern
2948 int *num_file, // resulting number of files
2949 char_u ***file, // array of resulting files
2950 int flags) // EW_DIR, etc.
2951{
2952 int ret = FAIL;
2953 char_u *eval_pat = NULL;
2954 char_u *exp_pat = *pat;
2955 char *ignored_msg;
2956 int usedlen;
2957
2958 if (*exp_pat == '%' || *exp_pat == '#' || *exp_pat == '<')
2959 {
2960 ++emsg_off;
2961 eval_pat = eval_vars(exp_pat, exp_pat, &usedlen,
2962 NULL, &ignored_msg, NULL);
2963 --emsg_off;
2964 if (eval_pat != NULL)
2965 exp_pat = concat_str(eval_pat, exp_pat + usedlen);
2966 }
2967
2968 if (exp_pat != NULL)
2969 ret = expand_wildcards(1, &exp_pat, num_file, file, flags);
2970
2971 if (eval_pat != NULL)
2972 {
2973 vim_free(exp_pat);
2974 vim_free(eval_pat);
2975 }
2976
2977 return ret;
2978}
2979
2980/*
2981 * Expand wildcards. Calls gen_expand_wildcards() and removes files matching
2982 * 'wildignore'.
2983 * Returns OK or FAIL. When FAIL then "num_files" won't be set.
2984 */
2985 int
2986expand_wildcards(
2987 int num_pat, // number of input patterns
2988 char_u **pat, // array of input patterns
2989 int *num_files, // resulting number of files
2990 char_u ***files, // array of resulting files
2991 int flags) // EW_DIR, etc.
2992{
2993 int retval;
2994 int i, j;
2995 char_u *p;
2996 int non_suf_match; // number without matching suffix
2997
2998 retval = gen_expand_wildcards(num_pat, pat, num_files, files, flags);
2999
3000 // When keeping all matches, return here
3001 if ((flags & EW_KEEPALL) || retval == FAIL)
3002 return retval;
3003
3004#ifdef FEAT_WILDIGN
3005 /*
3006 * Remove names that match 'wildignore'.
3007 */
3008 if (*p_wig)
3009 {
3010 char_u *ffname;
3011
3012 // check all files in (*files)[]
3013 for (i = 0; i < *num_files; ++i)
3014 {
3015 ffname = FullName_save((*files)[i], FALSE);
3016 if (ffname == NULL) // out of memory
3017 break;
3018# ifdef VMS
3019 vms_remove_version(ffname);
3020# endif
3021 if (match_file_list(p_wig, (*files)[i], ffname))
3022 {
3023 // remove this matching file from the list
3024 vim_free((*files)[i]);
3025 for (j = i; j + 1 < *num_files; ++j)
3026 (*files)[j] = (*files)[j + 1];
3027 --*num_files;
3028 --i;
3029 }
3030 vim_free(ffname);
3031 }
3032
3033 // If the number of matches is now zero, we fail.
3034 if (*num_files == 0)
3035 {
3036 VIM_CLEAR(*files);
3037 return FAIL;
3038 }
3039 }
3040#endif
3041
3042 /*
3043 * Move the names where 'suffixes' match to the end.
3044 */
3045 if (*num_files > 1)
3046 {
3047 non_suf_match = 0;
3048 for (i = 0; i < *num_files; ++i)
3049 {
3050 if (!match_suffix((*files)[i]))
3051 {
3052 /*
3053 * Move the name without matching suffix to the front
3054 * of the list.
3055 */
3056 p = (*files)[i];
3057 for (j = i; j > non_suf_match; --j)
3058 (*files)[j] = (*files)[j - 1];
3059 (*files)[non_suf_match++] = p;
3060 }
3061 }
3062 }
3063
3064 return retval;
3065}
3066
3067/*
3068 * Return TRUE if "fname" matches with an entry in 'suffixes'.
3069 */
3070 int
3071match_suffix(char_u *fname)
3072{
3073 int fnamelen, setsuflen;
3074 char_u *setsuf;
3075#define MAXSUFLEN 30 // maximum length of a file suffix
3076 char_u suf_buf[MAXSUFLEN];
3077
3078 fnamelen = (int)STRLEN(fname);
3079 setsuflen = 0;
3080 for (setsuf = p_su; *setsuf; )
3081 {
3082 setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
3083 if (setsuflen == 0)
3084 {
3085 char_u *tail = gettail(fname);
3086
3087 // empty entry: match name without a '.'
3088 if (vim_strchr(tail, '.') == NULL)
3089 {
3090 setsuflen = 1;
3091 break;
3092 }
3093 }
3094 else
3095 {
3096 if (fnamelen >= setsuflen
3097 && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
3098 (size_t)setsuflen) == 0)
3099 break;
3100 setsuflen = 0;
3101 }
3102 }
3103 return (setsuflen != 0);
3104}
3105
3106#ifdef VIM_BACKTICK
3107
3108/*
3109 * Return TRUE if we can expand this backtick thing here.
3110 */
3111 static int
3112vim_backtick(char_u *p)
3113{
3114 return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
3115}
3116
3117/*
3118 * Expand an item in `backticks` by executing it as a command.
3119 * Currently only works when pat[] starts and ends with a `.
3120 * Returns number of file names found, -1 if an error is encountered.
3121 */
3122 static int
3123expand_backtick(
3124 garray_T *gap,
3125 char_u *pat,
3126 int flags) // EW_* flags
3127{
3128 char_u *p;
3129 char_u *cmd;
3130 char_u *buffer;
3131 int cnt = 0;
3132 int i;
3133
3134 // Create the command: lop off the backticks.
Bram Moolenaar71ccd032020-06-12 22:59:11 +02003135 cmd = vim_strnsave(pat + 1, STRLEN(pat) - 2);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003136 if (cmd == NULL)
3137 return -1;
3138
3139#ifdef FEAT_EVAL
3140 if (*cmd == '=') // `={expr}`: Expand expression
Bram Moolenaarb171fb12020-06-24 20:34:03 +02003141 buffer = eval_to_string(cmd + 1, TRUE);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003142 else
3143#endif
3144 buffer = get_cmd_output(cmd, NULL,
3145 (flags & EW_SILENT) ? SHELL_SILENT : 0, NULL);
3146 vim_free(cmd);
3147 if (buffer == NULL)
3148 return -1;
3149
3150 cmd = buffer;
3151 while (*cmd != NUL)
3152 {
3153 cmd = skipwhite(cmd); // skip over white space
3154 p = cmd;
3155 while (*p != NUL && *p != '\r' && *p != '\n') // skip over entry
3156 ++p;
3157 // add an entry if it is not empty
3158 if (p > cmd)
3159 {
3160 i = *p;
3161 *p = NUL;
3162 addfile(gap, cmd, flags);
3163 *p = i;
3164 ++cnt;
3165 }
3166 cmd = p;
3167 while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
3168 ++cmd;
3169 }
3170
3171 vim_free(buffer);
3172 return cnt;
3173}
3174#endif // VIM_BACKTICK
3175
3176#if defined(MSWIN)
3177/*
3178 * File name expansion code for MS-DOS, Win16 and Win32. It's here because
3179 * it's shared between these systems.
3180 */
3181
3182/*
3183 * comparison function for qsort in dos_expandpath()
3184 */
3185 static int
3186pstrcmp(const void *a, const void *b)
3187{
3188 return (pathcmp(*(char **)a, *(char **)b, -1));
3189}
3190
3191/*
3192 * Recursively expand one path component into all matching files and/or
3193 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
3194 * Return the number of matches found.
3195 * "path" has backslashes before chars that are not to be expanded, starting
3196 * at "path[wildoff]".
3197 * Return the number of matches found.
3198 * NOTE: much of this is identical to unix_expandpath(), keep in sync!
3199 */
3200 static int
3201dos_expandpath(
3202 garray_T *gap,
3203 char_u *path,
3204 int wildoff,
3205 int flags, // EW_* flags
3206 int didstar) // expanded "**" once already
3207{
3208 char_u *buf;
3209 char_u *path_end;
3210 char_u *p, *s, *e;
3211 int start_len = gap->ga_len;
3212 char_u *pat;
3213 regmatch_T regmatch;
3214 int starts_with_dot;
3215 int matches;
3216 int len;
3217 int starstar = FALSE;
3218 static int stardepth = 0; // depth for "**" expansion
3219 HANDLE hFind = INVALID_HANDLE_VALUE;
3220 WIN32_FIND_DATAW wfb;
3221 WCHAR *wn = NULL; // UCS-2 name, NULL when not used.
3222 char_u *matchname;
3223 int ok;
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003224 char_u *p_alt;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003225
3226 // Expanding "**" may take a long time, check for CTRL-C.
3227 if (stardepth > 0)
3228 {
3229 ui_breakcheck();
3230 if (got_int)
3231 return 0;
3232 }
3233
3234 // Make room for file name. When doing encoding conversion the actual
3235 // length may be quite a bit longer, thus use the maximum possible length.
3236 buf = alloc(MAXPATHL);
3237 if (buf == NULL)
3238 return 0;
3239
3240 /*
3241 * Find the first part in the path name that contains a wildcard or a ~1.
3242 * Copy it into buf, including the preceding characters.
3243 */
3244 p = buf;
3245 s = buf;
3246 e = NULL;
3247 path_end = path;
3248 while (*path_end != NUL)
3249 {
3250 // May ignore a wildcard that has a backslash before it; it will
3251 // be removed by rem_backslash() or file_pat_to_reg_pat() below.
3252 if (path_end >= path + wildoff && rem_backslash(path_end))
3253 *p++ = *path_end++;
3254 else if (*path_end == '\\' || *path_end == ':' || *path_end == '/')
3255 {
3256 if (e != NULL)
3257 break;
3258 s = p + 1;
3259 }
3260 else if (path_end >= path + wildoff
3261 && vim_strchr((char_u *)"*?[~", *path_end) != NULL)
3262 e = p;
3263 if (has_mbyte)
3264 {
3265 len = (*mb_ptr2len)(path_end);
3266 STRNCPY(p, path_end, len);
3267 p += len;
3268 path_end += len;
3269 }
3270 else
3271 *p++ = *path_end++;
3272 }
3273 e = p;
3274 *e = NUL;
3275
3276 // now we have one wildcard component between s and e
3277 // Remove backslashes between "wildoff" and the start of the wildcard
3278 // component.
3279 for (p = buf + wildoff; p < s; ++p)
3280 if (rem_backslash(p))
3281 {
3282 STRMOVE(p, p + 1);
3283 --e;
3284 --s;
3285 }
3286
3287 // Check for "**" between "s" and "e".
3288 for (p = s; p < e; ++p)
3289 if (p[0] == '*' && p[1] == '*')
3290 starstar = TRUE;
3291
3292 starts_with_dot = *s == '.';
3293 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
3294 if (pat == NULL)
3295 {
3296 vim_free(buf);
3297 return 0;
3298 }
3299
3300 // compile the regexp into a program
3301 if (flags & (EW_NOERROR | EW_NOTWILD))
3302 ++emsg_silent;
3303 regmatch.rm_ic = TRUE; // Always ignore case
3304 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
3305 if (flags & (EW_NOERROR | EW_NOTWILD))
3306 --emsg_silent;
3307 vim_free(pat);
3308
3309 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
3310 {
3311 vim_free(buf);
3312 return 0;
3313 }
3314
3315 // remember the pattern or file name being looked for
3316 matchname = vim_strsave(s);
3317
3318 // If "**" is by itself, this is the first time we encounter it and more
3319 // is following then find matches without any directory.
3320 if (!didstar && stardepth < 100 && starstar && e - s == 2
3321 && *path_end == '/')
3322 {
3323 STRCPY(s, path_end + 1);
3324 ++stardepth;
3325 (void)dos_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
3326 --stardepth;
3327 }
3328
3329 // Scan all files in the directory with "dir/ *.*"
3330 STRCPY(s, "*.*");
3331 wn = enc_to_utf16(buf, NULL);
3332 if (wn != NULL)
3333 hFind = FindFirstFileW(wn, &wfb);
3334 ok = (hFind != INVALID_HANDLE_VALUE);
3335
3336 while (ok)
3337 {
3338 p = utf16_to_enc(wfb.cFileName, NULL); // p is allocated here
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003339
Bram Moolenaar26262f82019-09-04 20:59:15 +02003340 if (p == NULL)
3341 break; // out of memory
3342
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003343 if (*wfb.cAlternateFileName == NUL)
Bram Moolenaar40655d52020-04-06 23:49:50 +02003344 p_alt = NULL;
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003345 else
3346 p_alt = utf16_to_enc(wfb.cAlternateFileName, NULL);
3347
Bram Moolenaar26262f82019-09-04 20:59:15 +02003348 // Ignore entries starting with a dot, unless when asked for. Accept
3349 // all entries found with "matchname".
3350 if ((p[0] != '.' || starts_with_dot
3351 || ((flags & EW_DODOT)
3352 && p[1] != NUL && (p[1] != '.' || p[2] != NUL)))
3353 && (matchname == NULL
3354 || (regmatch.regprog != NULL
Bram Moolenaar40655d52020-04-06 23:49:50 +02003355 && (vim_regexec(&regmatch, p, (colnr_T)0)
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003356 || (p_alt != NULL
Bram Moolenaar40655d52020-04-06 23:49:50 +02003357 && vim_regexec(&regmatch, p_alt, (colnr_T)0))))
Bram Moolenaar26262f82019-09-04 20:59:15 +02003358 || ((flags & EW_NOTWILD)
3359 && fnamencmp(path + (s - buf), p, e - s) == 0)))
3360 {
3361 STRCPY(s, p);
3362 len = (int)STRLEN(buf);
3363
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003364 if (starstar && stardepth < 100
3365 && (wfb.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
Bram Moolenaar26262f82019-09-04 20:59:15 +02003366 {
3367 // For "**" in the pattern first go deeper in the tree to
3368 // find matches.
3369 STRCPY(buf + len, "/**");
3370 STRCPY(buf + len + 3, path_end);
3371 ++stardepth;
3372 (void)dos_expandpath(gap, buf, len + 1, flags, TRUE);
3373 --stardepth;
3374 }
3375
3376 STRCPY(buf + len, path_end);
3377 if (mch_has_exp_wildcard(path_end))
3378 {
3379 // need to expand another component of the path
3380 // remove backslashes for the remaining components only
3381 (void)dos_expandpath(gap, buf, len + 1, flags, FALSE);
3382 }
3383 else
3384 {
3385 // no more wildcards, check if there is a match
3386 // remove backslashes for the remaining components only
3387 if (*path_end != 0)
3388 backslash_halve(buf + len + 1);
3389 if (mch_getperm(buf) >= 0) // add existing file
3390 addfile(gap, buf, flags);
3391 }
3392 }
3393
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003394 vim_free(p_alt);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003395 vim_free(p);
3396 ok = FindNextFileW(hFind, &wfb);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003397 }
3398
3399 FindClose(hFind);
3400 vim_free(wn);
3401 vim_free(buf);
3402 vim_regfree(regmatch.regprog);
3403 vim_free(matchname);
3404
3405 matches = gap->ga_len - start_len;
3406 if (matches > 0)
3407 qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
3408 sizeof(char_u *), pstrcmp);
3409 return matches;
3410}
3411
3412 int
3413mch_expandpath(
3414 garray_T *gap,
3415 char_u *path,
3416 int flags) // EW_* flags
3417{
3418 return dos_expandpath(gap, path, 0, flags, FALSE);
3419}
3420#endif // MSWIN
3421
3422#if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \
3423 || defined(PROTO)
3424/*
3425 * Unix style wildcard expansion code.
3426 * It's here because it's used both for Unix and Mac.
3427 */
3428 static int
3429pstrcmp(const void *a, const void *b)
3430{
3431 return (pathcmp(*(char **)a, *(char **)b, -1));
3432}
3433
3434/*
3435 * Recursively expand one path component into all matching files and/or
3436 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
3437 * "path" has backslashes before chars that are not to be expanded, starting
3438 * at "path + wildoff".
3439 * Return the number of matches found.
3440 * NOTE: much of this is identical to dos_expandpath(), keep in sync!
3441 */
3442 int
3443unix_expandpath(
3444 garray_T *gap,
3445 char_u *path,
3446 int wildoff,
3447 int flags, // EW_* flags
3448 int didstar) // expanded "**" once already
3449{
3450 char_u *buf;
3451 char_u *path_end;
3452 char_u *p, *s, *e;
3453 int start_len = gap->ga_len;
3454 char_u *pat;
3455 regmatch_T regmatch;
3456 int starts_with_dot;
3457 int matches;
3458 int len;
3459 int starstar = FALSE;
3460 static int stardepth = 0; // depth for "**" expansion
3461
3462 DIR *dirp;
3463 struct dirent *dp;
3464
3465 // Expanding "**" may take a long time, check for CTRL-C.
3466 if (stardepth > 0)
3467 {
3468 ui_breakcheck();
3469 if (got_int)
3470 return 0;
3471 }
3472
3473 // make room for file name
3474 buf = alloc(STRLEN(path) + BASENAMELEN + 5);
3475 if (buf == NULL)
3476 return 0;
3477
3478 /*
3479 * Find the first part in the path name that contains a wildcard.
3480 * When EW_ICASE is set every letter is considered to be a wildcard.
3481 * Copy it into "buf", including the preceding characters.
3482 */
3483 p = buf;
3484 s = buf;
3485 e = NULL;
3486 path_end = path;
3487 while (*path_end != NUL)
3488 {
3489 // May ignore a wildcard that has a backslash before it; it will
3490 // be removed by rem_backslash() or file_pat_to_reg_pat() below.
3491 if (path_end >= path + wildoff && rem_backslash(path_end))
3492 *p++ = *path_end++;
3493 else if (*path_end == '/')
3494 {
3495 if (e != NULL)
3496 break;
3497 s = p + 1;
3498 }
3499 else if (path_end >= path + wildoff
3500 && (vim_strchr((char_u *)"*?[{~$", *path_end) != NULL
3501 || (!p_fic && (flags & EW_ICASE)
3502 && isalpha(PTR2CHAR(path_end)))))
3503 e = p;
3504 if (has_mbyte)
3505 {
3506 len = (*mb_ptr2len)(path_end);
3507 STRNCPY(p, path_end, len);
3508 p += len;
3509 path_end += len;
3510 }
3511 else
3512 *p++ = *path_end++;
3513 }
3514 e = p;
3515 *e = NUL;
3516
3517 // Now we have one wildcard component between "s" and "e".
3518 // Remove backslashes between "wildoff" and the start of the wildcard
3519 // component.
3520 for (p = buf + wildoff; p < s; ++p)
3521 if (rem_backslash(p))
3522 {
3523 STRMOVE(p, p + 1);
3524 --e;
3525 --s;
3526 }
3527
3528 // Check for "**" between "s" and "e".
3529 for (p = s; p < e; ++p)
3530 if (p[0] == '*' && p[1] == '*')
3531 starstar = TRUE;
3532
3533 // convert the file pattern to a regexp pattern
3534 starts_with_dot = *s == '.';
3535 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
3536 if (pat == NULL)
3537 {
3538 vim_free(buf);
3539 return 0;
3540 }
3541
3542 // compile the regexp into a program
3543 if (flags & EW_ICASE)
3544 regmatch.rm_ic = TRUE; // 'wildignorecase' set
3545 else
3546 regmatch.rm_ic = p_fic; // ignore case when 'fileignorecase' is set
3547 if (flags & (EW_NOERROR | EW_NOTWILD))
3548 ++emsg_silent;
3549 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
3550 if (flags & (EW_NOERROR | EW_NOTWILD))
3551 --emsg_silent;
3552 vim_free(pat);
3553
3554 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
3555 {
3556 vim_free(buf);
3557 return 0;
3558 }
3559
3560 // If "**" is by itself, this is the first time we encounter it and more
3561 // is following then find matches without any directory.
3562 if (!didstar && stardepth < 100 && starstar && e - s == 2
3563 && *path_end == '/')
3564 {
3565 STRCPY(s, path_end + 1);
3566 ++stardepth;
3567 (void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
3568 --stardepth;
3569 }
3570
3571 // open the directory for scanning
3572 *s = NUL;
3573 dirp = opendir(*buf == NUL ? "." : (char *)buf);
3574
3575 // Find all matching entries
3576 if (dirp != NULL)
3577 {
3578 for (;;)
3579 {
3580 dp = readdir(dirp);
3581 if (dp == NULL)
3582 break;
3583 if ((dp->d_name[0] != '.' || starts_with_dot
3584 || ((flags & EW_DODOT)
3585 && dp->d_name[1] != NUL
3586 && (dp->d_name[1] != '.' || dp->d_name[2] != NUL)))
3587 && ((regmatch.regprog != NULL && vim_regexec(&regmatch,
3588 (char_u *)dp->d_name, (colnr_T)0))
3589 || ((flags & EW_NOTWILD)
3590 && fnamencmp(path + (s - buf), dp->d_name, e - s) == 0)))
3591 {
3592 STRCPY(s, dp->d_name);
3593 len = STRLEN(buf);
3594
3595 if (starstar && stardepth < 100)
3596 {
3597 // For "**" in the pattern first go deeper in the tree to
3598 // find matches.
3599 STRCPY(buf + len, "/**");
3600 STRCPY(buf + len + 3, path_end);
3601 ++stardepth;
3602 (void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
3603 --stardepth;
3604 }
3605
3606 STRCPY(buf + len, path_end);
3607 if (mch_has_exp_wildcard(path_end)) // handle more wildcards
3608 {
3609 // need to expand another component of the path
3610 // remove backslashes for the remaining components only
3611 (void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
3612 }
3613 else
3614 {
3615 stat_T sb;
3616
3617 // no more wildcards, check if there is a match
3618 // remove backslashes for the remaining components only
3619 if (*path_end != NUL)
3620 backslash_halve(buf + len + 1);
3621 // add existing file or symbolic link
3622 if ((flags & EW_ALLLINKS) ? mch_lstat((char *)buf, &sb) >= 0
3623 : mch_getperm(buf) >= 0)
3624 {
3625#ifdef MACOS_CONVERT
3626 size_t precomp_len = STRLEN(buf)+1;
3627 char_u *precomp_buf =
3628 mac_precompose_path(buf, precomp_len, &precomp_len);
3629
3630 if (precomp_buf)
3631 {
3632 mch_memmove(buf, precomp_buf, precomp_len);
3633 vim_free(precomp_buf);
3634 }
3635#endif
3636 addfile(gap, buf, flags);
3637 }
3638 }
3639 }
3640 }
3641
3642 closedir(dirp);
3643 }
3644
3645 vim_free(buf);
3646 vim_regfree(regmatch.regprog);
3647
3648 matches = gap->ga_len - start_len;
3649 if (matches > 0)
3650 qsort(((char_u **)gap->ga_data) + start_len, matches,
3651 sizeof(char_u *), pstrcmp);
3652 return matches;
3653}
3654#endif
3655
3656/*
3657 * Return TRUE if "p" contains what looks like an environment variable.
3658 * Allowing for escaping.
3659 */
3660 static int
3661has_env_var(char_u *p)
3662{
3663 for ( ; *p; MB_PTR_ADV(p))
3664 {
3665 if (*p == '\\' && p[1] != NUL)
3666 ++p;
3667 else if (vim_strchr((char_u *)
3668#if defined(MSWIN)
3669 "$%"
3670#else
3671 "$"
3672#endif
3673 , *p) != NULL)
3674 return TRUE;
3675 }
3676 return FALSE;
3677}
3678
3679#ifdef SPECIAL_WILDCHAR
3680/*
3681 * Return TRUE if "p" contains a special wildcard character, one that Vim
3682 * cannot expand, requires using a shell.
3683 */
3684 static int
3685has_special_wildchar(char_u *p)
3686{
3687 for ( ; *p; MB_PTR_ADV(p))
3688 {
3689 // Disallow line break characters.
3690 if (*p == '\r' || *p == '\n')
3691 break;
3692 // Allow for escaping.
3693 if (*p == '\\' && p[1] != NUL && p[1] != '\r' && p[1] != '\n')
3694 ++p;
3695 else if (vim_strchr((char_u *)SPECIAL_WILDCHAR, *p) != NULL)
3696 {
3697 // A { must be followed by a matching }.
3698 if (*p == '{' && vim_strchr(p, '}') == NULL)
3699 continue;
3700 // A quote and backtick must be followed by another one.
3701 if ((*p == '`' || *p == '\'') && vim_strchr(p, *p) == NULL)
3702 continue;
3703 return TRUE;
3704 }
3705 }
3706 return FALSE;
3707}
3708#endif
3709
3710/*
3711 * Generic wildcard expansion code.
3712 *
3713 * Characters in "pat" that should not be expanded must be preceded with a
3714 * backslash. E.g., "/path\ with\ spaces/my\*star*"
3715 *
3716 * Return FAIL when no single file was found. In this case "num_file" is not
3717 * set, and "file" may contain an error message.
3718 * Return OK when some files found. "num_file" is set to the number of
3719 * matches, "file" to the array of matches. Call FreeWild() later.
3720 */
3721 int
3722gen_expand_wildcards(
3723 int num_pat, // number of input patterns
3724 char_u **pat, // array of input patterns
3725 int *num_file, // resulting number of files
3726 char_u ***file, // array of resulting files
3727 int flags) // EW_* flags
3728{
3729 int i;
3730 garray_T ga;
3731 char_u *p;
3732 static int recursive = FALSE;
3733 int add_pat;
3734 int retval = OK;
3735#if defined(FEAT_SEARCHPATH)
3736 int did_expand_in_path = FALSE;
3737#endif
3738
3739 /*
3740 * expand_env() is called to expand things like "~user". If this fails,
3741 * it calls ExpandOne(), which brings us back here. In this case, always
3742 * call the machine specific expansion function, if possible. Otherwise,
3743 * return FAIL.
3744 */
3745 if (recursive)
3746#ifdef SPECIAL_WILDCHAR
3747 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
3748#else
3749 return FAIL;
3750#endif
3751
3752#ifdef SPECIAL_WILDCHAR
3753 /*
3754 * If there are any special wildcard characters which we cannot handle
3755 * here, call machine specific function for all the expansion. This
3756 * avoids starting the shell for each argument separately.
3757 * For `=expr` do use the internal function.
3758 */
3759 for (i = 0; i < num_pat; i++)
3760 {
3761 if (has_special_wildchar(pat[i])
3762# ifdef VIM_BACKTICK
3763 && !(vim_backtick(pat[i]) && pat[i][1] == '=')
3764# endif
3765 )
3766 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
3767 }
3768#endif
3769
3770 recursive = TRUE;
3771
3772 /*
3773 * The matching file names are stored in a growarray. Init it empty.
3774 */
3775 ga_init2(&ga, (int)sizeof(char_u *), 30);
3776
3777 for (i = 0; i < num_pat; ++i)
3778 {
3779 add_pat = -1;
3780 p = pat[i];
3781
3782#ifdef VIM_BACKTICK
3783 if (vim_backtick(p))
3784 {
3785 add_pat = expand_backtick(&ga, p, flags);
3786 if (add_pat == -1)
3787 retval = FAIL;
3788 }
3789 else
3790#endif
3791 {
3792 /*
3793 * First expand environment variables, "~/" and "~user/".
3794 */
3795 if ((has_env_var(p) && !(flags & EW_NOTENV)) || *p == '~')
3796 {
3797 p = expand_env_save_opt(p, TRUE);
3798 if (p == NULL)
3799 p = pat[i];
3800#ifdef UNIX
3801 /*
3802 * On Unix, if expand_env() can't expand an environment
3803 * variable, use the shell to do that. Discard previously
3804 * found file names and start all over again.
3805 */
3806 else if (has_env_var(p) || *p == '~')
3807 {
3808 vim_free(p);
3809 ga_clear_strings(&ga);
3810 i = mch_expand_wildcards(num_pat, pat, num_file, file,
3811 flags|EW_KEEPDOLLAR);
3812 recursive = FALSE;
3813 return i;
3814 }
3815#endif
3816 }
3817
3818 /*
3819 * If there are wildcards: Expand file names and add each match to
3820 * the list. If there is no match, and EW_NOTFOUND is given, add
3821 * the pattern.
3822 * If there are no wildcards: Add the file name if it exists or
3823 * when EW_NOTFOUND is given.
3824 */
3825 if (mch_has_exp_wildcard(p))
3826 {
3827#if defined(FEAT_SEARCHPATH)
3828 if ((flags & EW_PATH)
3829 && !mch_isFullName(p)
3830 && !(p[0] == '.'
3831 && (vim_ispathsep(p[1])
3832 || (p[1] == '.' && vim_ispathsep(p[2]))))
3833 )
3834 {
3835 // :find completion where 'path' is used.
3836 // Recursiveness is OK here.
3837 recursive = FALSE;
3838 add_pat = expand_in_path(&ga, p, flags);
3839 recursive = TRUE;
3840 did_expand_in_path = TRUE;
3841 }
3842 else
3843#endif
3844 add_pat = mch_expandpath(&ga, p, flags);
3845 }
3846 }
3847
3848 if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
3849 {
3850 char_u *t = backslash_halve_save(p);
3851
3852 // When EW_NOTFOUND is used, always add files and dirs. Makes
3853 // "vim c:/" work.
3854 if (flags & EW_NOTFOUND)
3855 addfile(&ga, t, flags | EW_DIR | EW_FILE);
3856 else
3857 addfile(&ga, t, flags);
3858
3859 if (t != p)
3860 vim_free(t);
3861 }
3862
3863#if defined(FEAT_SEARCHPATH)
3864 if (did_expand_in_path && ga.ga_len > 0 && (flags & EW_PATH))
3865 uniquefy_paths(&ga, p);
3866#endif
3867 if (p != pat[i])
3868 vim_free(p);
3869 }
3870
Bram Moolenaar566cc8c2020-06-29 21:14:51 +02003871 // When returning FAIL the array must be freed here.
3872 if (retval == FAIL)
3873 ga_clear(&ga);
3874
Bram Moolenaar26262f82019-09-04 20:59:15 +02003875 *num_file = ga.ga_len;
Bram Moolenaar566cc8c2020-06-29 21:14:51 +02003876 *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data
3877 : (char_u **)_("no matches");
Bram Moolenaar26262f82019-09-04 20:59:15 +02003878
3879 recursive = FALSE;
3880
3881 return ((flags & EW_EMPTYOK) || ga.ga_data != NULL) ? retval : FAIL;
3882}
3883
3884/*
3885 * Add a file to a file list. Accepted flags:
3886 * EW_DIR add directories
3887 * EW_FILE add files
3888 * EW_EXEC add executable files
3889 * EW_NOTFOUND add even when it doesn't exist
3890 * EW_ADDSLASH add slash after directory name
3891 * EW_ALLLINKS add symlink also when the referred file does not exist
3892 */
3893 void
3894addfile(
3895 garray_T *gap,
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003896 char_u *f, // filename
Bram Moolenaar26262f82019-09-04 20:59:15 +02003897 int flags)
3898{
3899 char_u *p;
3900 int isdir;
3901 stat_T sb;
3902
3903 // if the file/dir/link doesn't exist, may not add it
3904 if (!(flags & EW_NOTFOUND) && ((flags & EW_ALLLINKS)
3905 ? mch_lstat((char *)f, &sb) < 0 : mch_getperm(f) < 0))
3906 return;
3907
3908#ifdef FNAME_ILLEGAL
3909 // if the file/dir contains illegal characters, don't add it
3910 if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
3911 return;
3912#endif
3913
3914 isdir = mch_isdir(f);
3915 if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
3916 return;
3917
3918 // If the file isn't executable, may not add it. Do accept directories.
3919 // When invoked from expand_shellcmd() do not use $PATH.
3920 if (!isdir && (flags & EW_EXEC)
3921 && !mch_can_exe(f, NULL, !(flags & EW_SHELLCMD)))
3922 return;
3923
3924 // Make room for another item in the file list.
3925 if (ga_grow(gap, 1) == FAIL)
3926 return;
3927
3928 p = alloc(STRLEN(f) + 1 + isdir);
3929 if (p == NULL)
3930 return;
3931
3932 STRCPY(p, f);
3933#ifdef BACKSLASH_IN_FILENAME
3934 slash_adjust(p);
3935#endif
3936 /*
3937 * Append a slash or backslash after directory names if none is present.
3938 */
3939#ifndef DONT_ADD_PATHSEP_TO_DIR
3940 if (isdir && (flags & EW_ADDSLASH))
3941 add_pathsep(p);
3942#endif
3943 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
3944}
3945
3946/*
3947 * Free the list of files returned by expand_wildcards() or other expansion
3948 * functions.
3949 */
3950 void
3951FreeWild(int count, char_u **files)
3952{
3953 if (count <= 0 || files == NULL)
3954 return;
3955 while (count--)
3956 vim_free(files[count]);
3957 vim_free(files);
3958}
3959
3960/*
3961 * Compare path "p[]" to "q[]".
3962 * If "maxlen" >= 0 compare "p[maxlen]" to "q[maxlen]"
3963 * Return value like strcmp(p, q), but consider path separators.
3964 */
3965 int
3966pathcmp(const char *p, const char *q, int maxlen)
3967{
3968 int i, j;
3969 int c1, c2;
3970 const char *s = NULL;
3971
3972 for (i = 0, j = 0; maxlen < 0 || (i < maxlen && j < maxlen);)
3973 {
3974 c1 = PTR2CHAR((char_u *)p + i);
3975 c2 = PTR2CHAR((char_u *)q + j);
3976
3977 // End of "p": check if "q" also ends or just has a slash.
3978 if (c1 == NUL)
3979 {
3980 if (c2 == NUL) // full match
3981 return 0;
3982 s = q;
3983 i = j;
3984 break;
3985 }
3986
3987 // End of "q": check if "p" just has a slash.
3988 if (c2 == NUL)
3989 {
3990 s = p;
3991 break;
3992 }
3993
3994 if ((p_fic ? MB_TOUPPER(c1) != MB_TOUPPER(c2) : c1 != c2)
3995#ifdef BACKSLASH_IN_FILENAME
3996 // consider '/' and '\\' to be equal
3997 && !((c1 == '/' && c2 == '\\')
3998 || (c1 == '\\' && c2 == '/'))
3999#endif
4000 )
4001 {
4002 if (vim_ispathsep(c1))
4003 return -1;
4004 if (vim_ispathsep(c2))
4005 return 1;
4006 return p_fic ? MB_TOUPPER(c1) - MB_TOUPPER(c2)
4007 : c1 - c2; // no match
4008 }
4009
Bram Moolenaar1614a142019-10-06 22:00:13 +02004010 i += mb_ptr2len((char_u *)p + i);
4011 j += mb_ptr2len((char_u *)q + j);
Bram Moolenaar26262f82019-09-04 20:59:15 +02004012 }
4013 if (s == NULL) // "i" or "j" ran into "maxlen"
4014 return 0;
4015
4016 c1 = PTR2CHAR((char_u *)s + i);
Bram Moolenaar1614a142019-10-06 22:00:13 +02004017 c2 = PTR2CHAR((char_u *)s + i + mb_ptr2len((char_u *)s + i));
Bram Moolenaar26262f82019-09-04 20:59:15 +02004018 // ignore a trailing slash, but not "//" or ":/"
4019 if (c2 == NUL
4020 && i > 0
4021 && !after_pathsep((char_u *)s, (char_u *)s + i)
4022#ifdef BACKSLASH_IN_FILENAME
4023 && (c1 == '/' || c1 == '\\')
4024#else
4025 && c1 == '/'
4026#endif
4027 )
4028 return 0; // match with trailing slash
4029 if (s == q)
4030 return -1; // no match
4031 return 1;
4032}
4033
4034/*
4035 * Return TRUE if "name" is a full (absolute) path name or URL.
4036 */
4037 int
4038vim_isAbsName(char_u *name)
4039{
4040 return (path_with_url(name) != 0 || mch_isFullName(name));
4041}
4042
4043/*
4044 * Get absolute file name into buffer "buf[len]".
4045 *
4046 * return FAIL for failure, OK otherwise
4047 */
4048 int
4049vim_FullName(
4050 char_u *fname,
4051 char_u *buf,
4052 int len,
4053 int force) // force expansion even when already absolute
4054{
4055 int retval = OK;
4056 int url;
4057
4058 *buf = NUL;
4059 if (fname == NULL)
4060 return FAIL;
4061
4062 url = path_with_url(fname);
4063 if (!url)
4064 retval = mch_FullName(fname, buf, len, force);
4065 if (url || retval == FAIL)
4066 {
4067 // something failed; use the file name (truncate when too long)
4068 vim_strncpy(buf, fname, len - 1);
4069 }
4070#if defined(MSWIN)
4071 slash_adjust(buf);
4072#endif
4073 return retval;
4074}