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