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