blob: ad7b8b03d4ae82d9be063cf7d73e63f2f8ad89a8 [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 Moolenaarb005cd82019-09-04 15:54:55 +0200392 *fnamep = vim_strnsave(*fnamep, (int)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 {
419 if (c == '.' && **fnamep == '~')
420 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 {
658 pat = vim_strnsave(s, (int)(p - s));
659 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 {
666 sub = vim_strnsave(s, (int)(p - s));
667 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
713#if defined(FEAT_EVAL) || defined(PROTO)
714
715/*
716 * "chdir(dir)" function
717 */
718 void
719f_chdir(typval_T *argvars, typval_T *rettv)
720{
721 char_u *cwd;
722 cdscope_T scope = CDSCOPE_GLOBAL;
723
724 rettv->v_type = VAR_STRING;
725 rettv->vval.v_string = NULL;
726
727 if (argvars[0].v_type != VAR_STRING)
Bram Moolenaard816cd92020-02-04 22:23:09 +0100728 // Returning an empty string means it failed.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200729 return;
730
731 // Return the current directory
732 cwd = alloc(MAXPATHL);
733 if (cwd != NULL)
734 {
735 if (mch_dirname(cwd, MAXPATHL) != FAIL)
736 {
737#ifdef BACKSLASH_IN_FILENAME
738 slash_adjust(cwd);
739#endif
740 rettv->vval.v_string = vim_strsave(cwd);
741 }
742 vim_free(cwd);
743 }
744
745 if (curwin->w_localdir != NULL)
746 scope = CDSCOPE_WINDOW;
747 else if (curtab->tp_localdir != NULL)
748 scope = CDSCOPE_TABPAGE;
749
750 if (!changedir_func(argvars[0].vval.v_string, TRUE, scope))
751 // Directory change failed
752 VIM_CLEAR(rettv->vval.v_string);
753}
754
755/*
756 * "delete()" function
757 */
758 void
759f_delete(typval_T *argvars, typval_T *rettv)
760{
761 char_u nbuf[NUMBUFLEN];
762 char_u *name;
763 char_u *flags;
764
765 rettv->vval.v_number = -1;
766 if (check_restricted() || check_secure())
767 return;
768
769 name = tv_get_string(&argvars[0]);
770 if (name == NULL || *name == NUL)
771 {
772 emsg(_(e_invarg));
773 return;
774 }
775
776 if (argvars[1].v_type != VAR_UNKNOWN)
777 flags = tv_get_string_buf(&argvars[1], nbuf);
778 else
779 flags = (char_u *)"";
780
781 if (*flags == NUL)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200782 // delete a file
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200783 rettv->vval.v_number = mch_remove(name) == 0 ? 0 : -1;
784 else if (STRCMP(flags, "d") == 0)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200785 // delete an empty directory
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200786 rettv->vval.v_number = mch_rmdir(name) == 0 ? 0 : -1;
787 else if (STRCMP(flags, "rf") == 0)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200788 // delete a directory recursively
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200789 rettv->vval.v_number = delete_recursive(name);
790 else
791 semsg(_(e_invexpr2), flags);
792}
793
794/*
795 * "executable()" function
796 */
797 void
798f_executable(typval_T *argvars, typval_T *rettv)
799{
800 char_u *name = tv_get_string(&argvars[0]);
801
Bram Moolenaar26262f82019-09-04 20:59:15 +0200802 // Check in $PATH and also check directly if there is a directory name.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200803 rettv->vval.v_number = mch_can_exe(name, NULL, TRUE);
804}
805
806/*
807 * "exepath()" function
808 */
809 void
810f_exepath(typval_T *argvars, typval_T *rettv)
811{
812 char_u *p = NULL;
813
814 (void)mch_can_exe(tv_get_string(&argvars[0]), &p, TRUE);
815 rettv->v_type = VAR_STRING;
816 rettv->vval.v_string = p;
817}
818
819/*
820 * "filereadable()" function
821 */
822 void
823f_filereadable(typval_T *argvars, typval_T *rettv)
824{
825 int fd;
826 char_u *p;
827 int n;
828
829#ifndef O_NONBLOCK
830# define O_NONBLOCK 0
831#endif
832 p = tv_get_string(&argvars[0]);
833 if (*p && !mch_isdir(p) && (fd = mch_open((char *)p,
834 O_RDONLY | O_NONBLOCK, 0)) >= 0)
835 {
836 n = TRUE;
837 close(fd);
838 }
839 else
840 n = FALSE;
841
842 rettv->vval.v_number = n;
843}
844
845/*
846 * Return 0 for not writable, 1 for writable file, 2 for a dir which we have
847 * rights to write into.
848 */
849 void
850f_filewritable(typval_T *argvars, typval_T *rettv)
851{
852 rettv->vval.v_number = filewritable(tv_get_string(&argvars[0]));
853}
854
Bram Moolenaar840d16f2019-09-10 21:27:18 +0200855 static void
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200856findfilendir(
857 typval_T *argvars UNUSED,
858 typval_T *rettv,
859 int find_what UNUSED)
860{
861#ifdef FEAT_SEARCHPATH
862 char_u *fname;
863 char_u *fresult = NULL;
864 char_u *path = *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path;
865 char_u *p;
866 char_u pathbuf[NUMBUFLEN];
867 int count = 1;
868 int first = TRUE;
869 int error = FALSE;
870#endif
871
872 rettv->vval.v_string = NULL;
873 rettv->v_type = VAR_STRING;
874
875#ifdef FEAT_SEARCHPATH
876 fname = tv_get_string(&argvars[0]);
877
878 if (argvars[1].v_type != VAR_UNKNOWN)
879 {
880 p = tv_get_string_buf_chk(&argvars[1], pathbuf);
881 if (p == NULL)
882 error = TRUE;
883 else
884 {
885 if (*p != NUL)
886 path = p;
887
888 if (argvars[2].v_type != VAR_UNKNOWN)
889 count = (int)tv_get_number_chk(&argvars[2], &error);
890 }
891 }
892
893 if (count < 0 && rettv_list_alloc(rettv) == FAIL)
894 error = TRUE;
895
896 if (*fname != NUL && !error)
897 {
898 do
899 {
900 if (rettv->v_type == VAR_STRING || rettv->v_type == VAR_LIST)
901 vim_free(fresult);
902 fresult = find_file_in_path_option(first ? fname : NULL,
903 first ? (int)STRLEN(fname) : 0,
904 0, first, path,
905 find_what,
906 curbuf->b_ffname,
907 find_what == FINDFILE_DIR
908 ? (char_u *)"" : curbuf->b_p_sua);
909 first = FALSE;
910
911 if (fresult != NULL && rettv->v_type == VAR_LIST)
912 list_append_string(rettv->vval.v_list, fresult, -1);
913
914 } while ((rettv->v_type == VAR_LIST || --count > 0) && fresult != NULL);
915 }
916
917 if (rettv->v_type == VAR_STRING)
918 rettv->vval.v_string = fresult;
919#endif
920}
921
922/*
923 * "finddir({fname}[, {path}[, {count}]])" function
924 */
925 void
926f_finddir(typval_T *argvars, typval_T *rettv)
927{
928 findfilendir(argvars, rettv, FINDFILE_DIR);
929}
930
931/*
932 * "findfile({fname}[, {path}[, {count}]])" function
933 */
934 void
935f_findfile(typval_T *argvars, typval_T *rettv)
936{
937 findfilendir(argvars, rettv, FINDFILE_FILE);
938}
939
940/*
941 * "fnamemodify({fname}, {mods})" function
942 */
943 void
944f_fnamemodify(typval_T *argvars, typval_T *rettv)
945{
946 char_u *fname;
947 char_u *mods;
948 int usedlen = 0;
949 int len;
950 char_u *fbuf = NULL;
951 char_u buf[NUMBUFLEN];
952
953 fname = tv_get_string_chk(&argvars[0]);
954 mods = tv_get_string_buf_chk(&argvars[1], buf);
955 if (fname == NULL || mods == NULL)
956 fname = NULL;
957 else
958 {
959 len = (int)STRLEN(fname);
960 (void)modify_fname(mods, FALSE, &usedlen, &fname, &fbuf, &len);
961 }
962
963 rettv->v_type = VAR_STRING;
964 if (fname == NULL)
965 rettv->vval.v_string = NULL;
966 else
967 rettv->vval.v_string = vim_strnsave(fname, len);
968 vim_free(fbuf);
969}
970
971/*
972 * "getcwd()" function
973 *
974 * Return the current working directory of a window in a tab page.
975 * First optional argument 'winnr' is the window number or -1 and the second
976 * optional argument 'tabnr' is the tab page number.
977 *
978 * If no arguments are supplied, then return the directory of the current
979 * window.
980 * If only 'winnr' is specified and is not -1 or 0 then return the directory of
981 * the specified window.
982 * If 'winnr' is 0 then return the directory of the current window.
983 * If both 'winnr and 'tabnr' are specified and 'winnr' is -1 then return the
984 * directory of the specified tab page. Otherwise return the directory of the
985 * specified window in the specified tab page.
986 * If the window or the tab page doesn't exist then return NULL.
987 */
988 void
989f_getcwd(typval_T *argvars, typval_T *rettv)
990{
991 win_T *wp = NULL;
992 tabpage_T *tp = NULL;
993 char_u *cwd;
994 int global = FALSE;
995
996 rettv->v_type = VAR_STRING;
997 rettv->vval.v_string = NULL;
998
999 if (argvars[0].v_type == VAR_NUMBER
1000 && argvars[0].vval.v_number == -1
1001 && argvars[1].v_type == VAR_UNKNOWN)
1002 global = TRUE;
1003 else
1004 wp = find_tabwin(&argvars[0], &argvars[1], &tp);
1005
1006 if (wp != NULL && wp->w_localdir != NULL)
1007 rettv->vval.v_string = vim_strsave(wp->w_localdir);
1008 else if (tp != NULL && tp->tp_localdir != NULL)
1009 rettv->vval.v_string = vim_strsave(tp->tp_localdir);
1010 else if (wp != NULL || tp != NULL || global)
1011 {
1012 if (globaldir != NULL)
1013 rettv->vval.v_string = vim_strsave(globaldir);
1014 else
1015 {
1016 cwd = alloc(MAXPATHL);
1017 if (cwd != NULL)
1018 {
1019 if (mch_dirname(cwd, MAXPATHL) != FAIL)
1020 rettv->vval.v_string = vim_strsave(cwd);
1021 vim_free(cwd);
1022 }
1023 }
1024 }
1025#ifdef BACKSLASH_IN_FILENAME
1026 if (rettv->vval.v_string != NULL)
1027 slash_adjust(rettv->vval.v_string);
1028#endif
1029}
1030
1031/*
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001032 * Convert "st" to file permission string.
1033 */
1034 char_u *
1035getfpermst(stat_T *st, char_u *perm)
1036{
1037 char_u flags[] = "rwx";
1038 int i;
1039
1040 for (i = 0; i < 9; i++)
1041 {
1042 if (st->st_mode & (1 << (8 - i)))
1043 perm[i] = flags[i % 3];
1044 else
1045 perm[i] = '-';
1046 }
1047 return perm;
1048}
1049
1050/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001051 * "getfperm({fname})" function
1052 */
1053 void
1054f_getfperm(typval_T *argvars, typval_T *rettv)
1055{
1056 char_u *fname;
1057 stat_T st;
1058 char_u *perm = NULL;
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001059 char_u permbuf[] = "---------";
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001060
1061 fname = tv_get_string(&argvars[0]);
1062
1063 rettv->v_type = VAR_STRING;
1064 if (mch_stat((char *)fname, &st) >= 0)
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001065 perm = vim_strsave(getfpermst(&st, permbuf));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001066 rettv->vval.v_string = perm;
1067}
1068
1069/*
1070 * "getfsize({fname})" function
1071 */
1072 void
1073f_getfsize(typval_T *argvars, typval_T *rettv)
1074{
1075 char_u *fname;
1076 stat_T st;
1077
1078 fname = tv_get_string(&argvars[0]);
1079
1080 rettv->v_type = VAR_NUMBER;
1081
1082 if (mch_stat((char *)fname, &st) >= 0)
1083 {
1084 if (mch_isdir(fname))
1085 rettv->vval.v_number = 0;
1086 else
1087 {
1088 rettv->vval.v_number = (varnumber_T)st.st_size;
1089
Bram Moolenaar26262f82019-09-04 20:59:15 +02001090 // non-perfect check for overflow
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001091 if ((off_T)rettv->vval.v_number != (off_T)st.st_size)
1092 rettv->vval.v_number = -2;
1093 }
1094 }
1095 else
1096 rettv->vval.v_number = -1;
1097}
1098
1099/*
1100 * "getftime({fname})" function
1101 */
1102 void
1103f_getftime(typval_T *argvars, typval_T *rettv)
1104{
1105 char_u *fname;
1106 stat_T st;
1107
1108 fname = tv_get_string(&argvars[0]);
1109
1110 if (mch_stat((char *)fname, &st) >= 0)
1111 rettv->vval.v_number = (varnumber_T)st.st_mtime;
1112 else
1113 rettv->vval.v_number = -1;
1114}
1115
1116/*
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001117 * Convert "st" to file type string.
1118 */
1119 char_u *
1120getftypest(stat_T *st)
1121{
1122 char *t;
1123
1124 if (S_ISREG(st->st_mode))
1125 t = "file";
1126 else if (S_ISDIR(st->st_mode))
1127 t = "dir";
1128 else if (S_ISLNK(st->st_mode))
1129 t = "link";
1130 else if (S_ISBLK(st->st_mode))
1131 t = "bdev";
1132 else if (S_ISCHR(st->st_mode))
1133 t = "cdev";
1134 else if (S_ISFIFO(st->st_mode))
1135 t = "fifo";
1136 else if (S_ISSOCK(st->st_mode))
1137 t = "socket";
1138 else
1139 t = "other";
1140 return (char_u*)t;
1141}
1142
1143/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001144 * "getftype({fname})" function
1145 */
1146 void
1147f_getftype(typval_T *argvars, typval_T *rettv)
1148{
1149 char_u *fname;
1150 stat_T st;
1151 char_u *type = NULL;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001152
1153 fname = tv_get_string(&argvars[0]);
1154
1155 rettv->v_type = VAR_STRING;
1156 if (mch_lstat((char *)fname, &st) >= 0)
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001157 type = vim_strsave(getftypest(&st));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001158 rettv->vval.v_string = type;
1159}
1160
1161/*
1162 * "glob()" function
1163 */
1164 void
1165f_glob(typval_T *argvars, typval_T *rettv)
1166{
1167 int options = WILD_SILENT|WILD_USE_NL;
1168 expand_T xpc;
1169 int error = FALSE;
1170
Bram Moolenaar26262f82019-09-04 20:59:15 +02001171 // When the optional second argument is non-zero, don't remove matches
1172 // for 'wildignore' and don't put matches for 'suffixes' at the end.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001173 rettv->v_type = VAR_STRING;
1174 if (argvars[1].v_type != VAR_UNKNOWN)
1175 {
1176 if (tv_get_number_chk(&argvars[1], &error))
1177 options |= WILD_KEEP_ALL;
1178 if (argvars[2].v_type != VAR_UNKNOWN)
1179 {
1180 if (tv_get_number_chk(&argvars[2], &error))
1181 rettv_list_set(rettv, NULL);
1182 if (argvars[3].v_type != VAR_UNKNOWN
1183 && tv_get_number_chk(&argvars[3], &error))
1184 options |= WILD_ALLLINKS;
1185 }
1186 }
1187 if (!error)
1188 {
1189 ExpandInit(&xpc);
1190 xpc.xp_context = EXPAND_FILES;
1191 if (p_wic)
1192 options += WILD_ICASE;
1193 if (rettv->v_type == VAR_STRING)
1194 rettv->vval.v_string = ExpandOne(&xpc, tv_get_string(&argvars[0]),
1195 NULL, options, WILD_ALL);
1196 else if (rettv_list_alloc(rettv) != FAIL)
1197 {
1198 int i;
1199
1200 ExpandOne(&xpc, tv_get_string(&argvars[0]),
1201 NULL, options, WILD_ALL_KEEP);
1202 for (i = 0; i < xpc.xp_numfiles; i++)
1203 list_append_string(rettv->vval.v_list, xpc.xp_files[i], -1);
1204
1205 ExpandCleanup(&xpc);
1206 }
1207 }
1208 else
1209 rettv->vval.v_string = NULL;
1210}
1211
1212/*
1213 * "glob2regpat()" function
1214 */
1215 void
1216f_glob2regpat(typval_T *argvars, typval_T *rettv)
1217{
1218 char_u *pat = tv_get_string_chk(&argvars[0]);
1219
1220 rettv->v_type = VAR_STRING;
1221 rettv->vval.v_string = (pat == NULL)
1222 ? NULL : file_pat_to_reg_pat(pat, NULL, NULL, FALSE);
1223}
1224
1225/*
1226 * "globpath()" function
1227 */
1228 void
1229f_globpath(typval_T *argvars, typval_T *rettv)
1230{
1231 int flags = WILD_IGNORE_COMPLETESLASH;
1232 char_u buf1[NUMBUFLEN];
1233 char_u *file = tv_get_string_buf_chk(&argvars[1], buf1);
1234 int error = FALSE;
1235 garray_T ga;
1236 int i;
1237
1238 // When the optional second argument is non-zero, don't remove matches
1239 // for 'wildignore' and don't put matches for 'suffixes' at the end.
1240 rettv->v_type = VAR_STRING;
1241 if (argvars[2].v_type != VAR_UNKNOWN)
1242 {
1243 if (tv_get_number_chk(&argvars[2], &error))
1244 flags |= WILD_KEEP_ALL;
1245 if (argvars[3].v_type != VAR_UNKNOWN)
1246 {
1247 if (tv_get_number_chk(&argvars[3], &error))
1248 rettv_list_set(rettv, NULL);
1249 if (argvars[4].v_type != VAR_UNKNOWN
1250 && tv_get_number_chk(&argvars[4], &error))
1251 flags |= WILD_ALLLINKS;
1252 }
1253 }
1254 if (file != NULL && !error)
1255 {
1256 ga_init2(&ga, (int)sizeof(char_u *), 10);
1257 globpath(tv_get_string(&argvars[0]), file, &ga, flags);
1258 if (rettv->v_type == VAR_STRING)
1259 rettv->vval.v_string = ga_concat_strings(&ga, "\n");
1260 else if (rettv_list_alloc(rettv) != FAIL)
1261 for (i = 0; i < ga.ga_len; ++i)
1262 list_append_string(rettv->vval.v_list,
1263 ((char_u **)(ga.ga_data))[i], -1);
1264 ga_clear_strings(&ga);
1265 }
1266 else
1267 rettv->vval.v_string = NULL;
1268}
1269
1270/*
1271 * "isdirectory()" function
1272 */
1273 void
1274f_isdirectory(typval_T *argvars, typval_T *rettv)
1275{
1276 rettv->vval.v_number = mch_isdir(tv_get_string(&argvars[0]));
1277}
1278
1279/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001280 * Create the directory in which "dir" is located, and higher levels when
1281 * needed.
1282 * Return OK or FAIL.
1283 */
1284 static int
1285mkdir_recurse(char_u *dir, int prot)
1286{
1287 char_u *p;
1288 char_u *updir;
1289 int r = FAIL;
1290
Bram Moolenaar26262f82019-09-04 20:59:15 +02001291 // Get end of directory name in "dir".
1292 // We're done when it's "/" or "c:/".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001293 p = gettail_sep(dir);
1294 if (p <= get_past_head(dir))
1295 return OK;
1296
Bram Moolenaar26262f82019-09-04 20:59:15 +02001297 // If the directory exists we're done. Otherwise: create it.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001298 updir = vim_strnsave(dir, (int)(p - dir));
1299 if (updir == NULL)
1300 return FAIL;
1301 if (mch_isdir(updir))
1302 r = OK;
1303 else if (mkdir_recurse(updir, prot) == OK)
1304 r = vim_mkdir_emsg(updir, prot);
1305 vim_free(updir);
1306 return r;
1307}
1308
1309/*
1310 * "mkdir()" function
1311 */
1312 void
1313f_mkdir(typval_T *argvars, typval_T *rettv)
1314{
1315 char_u *dir;
1316 char_u buf[NUMBUFLEN];
1317 int prot = 0755;
1318
1319 rettv->vval.v_number = FAIL;
1320 if (check_restricted() || check_secure())
1321 return;
1322
1323 dir = tv_get_string_buf(&argvars[0], buf);
1324 if (*dir == NUL)
1325 return;
1326
1327 if (*gettail(dir) == NUL)
Bram Moolenaar26262f82019-09-04 20:59:15 +02001328 // remove trailing slashes
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001329 *gettail_sep(dir) = NUL;
1330
1331 if (argvars[1].v_type != VAR_UNKNOWN)
1332 {
1333 if (argvars[2].v_type != VAR_UNKNOWN)
1334 {
1335 prot = (int)tv_get_number_chk(&argvars[2], NULL);
1336 if (prot == -1)
1337 return;
1338 }
1339 if (STRCMP(tv_get_string(&argvars[1]), "p") == 0)
1340 {
1341 if (mch_isdir(dir))
1342 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001343 // With the "p" flag it's OK if the dir already exists.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001344 rettv->vval.v_number = OK;
1345 return;
1346 }
1347 mkdir_recurse(dir, prot);
1348 }
1349 }
1350 rettv->vval.v_number = vim_mkdir_emsg(dir, prot);
1351}
1352
1353/*
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02001354 * "pathshorten()" function
1355 */
1356 void
1357f_pathshorten(typval_T *argvars, typval_T *rettv)
1358{
1359 char_u *p;
1360
1361 rettv->v_type = VAR_STRING;
1362 p = tv_get_string_chk(&argvars[0]);
1363 if (p == NULL)
1364 rettv->vval.v_string = NULL;
1365 else
1366 {
1367 p = vim_strsave(p);
1368 rettv->vval.v_string = p;
1369 if (p != NULL)
1370 shorten_dir(p);
1371 }
1372}
1373
1374/*
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001375 * Evaluate "expr" (= "context") for readdir().
1376 */
1377 static int
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001378readdir_checkitem(void *context, void *item)
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001379{
1380 typval_T *expr = (typval_T *)context;
1381 typval_T save_val;
1382 typval_T rettv;
1383 typval_T argv[2];
1384 int retval = 0;
1385 int error = FALSE;
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001386 char_u *name = (char_u*)item;
Bram Moolenaar80147dd2020-02-04 22:32:59 +01001387
1388 prepare_vimvar(VV_VAL, &save_val);
1389 set_vim_var_string(VV_VAL, name, -1);
1390 argv[0].v_type = VAR_STRING;
1391 argv[0].vval.v_string = name;
1392
1393 if (eval_expr_typval(expr, argv, 1, &rettv) == FAIL)
1394 goto theend;
1395
1396 retval = tv_get_number_chk(&rettv, &error);
1397 if (error)
1398 retval = -1;
1399 clear_tv(&rettv);
1400
1401theend:
1402 set_vim_var_string(VV_VAL, NULL, 0);
1403 restore_vimvar(VV_VAL, &save_val);
1404 return retval;
1405}
1406
1407/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001408 * "readdir()" function
1409 */
1410 void
1411f_readdir(typval_T *argvars, typval_T *rettv)
1412{
1413 typval_T *expr;
1414 int ret;
1415 char_u *path;
1416 char_u *p;
1417 garray_T ga;
1418 int i;
1419
1420 if (rettv_list_alloc(rettv) == FAIL)
1421 return;
1422 path = tv_get_string(&argvars[0]);
1423 expr = &argvars[1];
1424
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001425 ret = readdir_core(&ga, path, FALSE, (void *)expr,
1426 (expr->v_type == VAR_UNKNOWN) ? NULL : readdir_checkitem);
1427 if (ret == OK)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001428 {
1429 for (i = 0; i < ga.ga_len; i++)
1430 {
1431 p = ((char_u **)ga.ga_data)[i];
1432 list_append_string(rettv->vval.v_list, p, -1);
1433 }
1434 }
1435 ga_clear_strings(&ga);
1436}
1437
1438/*
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02001439 * Evaluate "expr" (= "context") for readdirex().
1440 */
1441 static int
1442readdirex_checkitem(void *context, void *item)
1443{
1444 typval_T *expr = (typval_T *)context;
1445 typval_T save_val;
1446 typval_T rettv;
1447 typval_T argv[2];
1448 int retval = 0;
1449 int error = FALSE;
1450 dict_T *dict = (dict_T*)item;
1451
1452 prepare_vimvar(VV_VAL, &save_val);
1453 set_vim_var_dict(VV_VAL, dict);
1454 argv[0].v_type = VAR_DICT;
1455 argv[0].vval.v_dict = dict;
1456
1457 if (eval_expr_typval(expr, argv, 1, &rettv) == FAIL)
1458 goto theend;
1459
1460 retval = tv_get_number_chk(&rettv, &error);
1461 if (error)
1462 retval = -1;
1463 clear_tv(&rettv);
1464
1465theend:
1466 set_vim_var_dict(VV_VAL, NULL);
1467 restore_vimvar(VV_VAL, &save_val);
1468 return retval;
1469}
1470
1471/*
1472 * "readdirex()" function
1473 */
1474 void
1475f_readdirex(typval_T *argvars, typval_T *rettv)
1476{
1477 typval_T *expr;
1478 int ret;
1479 char_u *path;
1480 garray_T ga;
1481 int i;
1482
1483 if (rettv_list_alloc(rettv) == FAIL)
1484 return;
1485 path = tv_get_string(&argvars[0]);
1486 expr = &argvars[1];
1487
1488 ret = readdir_core(&ga, path, TRUE, (void *)expr,
1489 (expr->v_type == VAR_UNKNOWN) ? NULL : readdirex_checkitem);
1490 if (ret == OK)
1491 {
1492 for (i = 0; i < ga.ga_len; i++)
1493 {
1494 dict_T *dict = ((dict_T**)ga.ga_data)[i];
1495 list_append_dict(rettv->vval.v_list, dict);
1496 dict_unref(dict);
1497 }
1498 }
1499 ga_clear(&ga);
1500}
1501
1502/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001503 * "readfile()" function
1504 */
1505 void
1506f_readfile(typval_T *argvars, typval_T *rettv)
1507{
1508 int binary = FALSE;
1509 int blob = FALSE;
1510 int failed = FALSE;
1511 char_u *fname;
1512 FILE *fd;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001513 char_u buf[(IOSIZE/256)*256]; // rounded to avoid odd + 1
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001514 int io_size = sizeof(buf);
Bram Moolenaar26262f82019-09-04 20:59:15 +02001515 int readlen; // size of last fread()
1516 char_u *prev = NULL; // previously read bytes, if any
1517 long prevlen = 0; // length of data in prev
1518 long prevsize = 0; // size of prev buffer
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001519 long maxline = MAXLNUM;
1520 long cnt = 0;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001521 char_u *p; // position in buf
1522 char_u *start; // start of current line
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001523
1524 if (argvars[1].v_type != VAR_UNKNOWN)
1525 {
1526 if (STRCMP(tv_get_string(&argvars[1]), "b") == 0)
1527 binary = TRUE;
1528 if (STRCMP(tv_get_string(&argvars[1]), "B") == 0)
1529 blob = TRUE;
1530
1531 if (argvars[2].v_type != VAR_UNKNOWN)
1532 maxline = (long)tv_get_number(&argvars[2]);
1533 }
1534
Bram Moolenaar15352dc2020-04-06 21:12:42 +02001535 if ((blob ? rettv_blob_alloc(rettv) : rettv_list_alloc(rettv)) == FAIL)
1536 return;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001537
Bram Moolenaar26262f82019-09-04 20:59:15 +02001538 // Always open the file in binary mode, library functions have a mind of
1539 // their own about CR-LF conversion.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001540 fname = tv_get_string(&argvars[0]);
Bram Moolenaar15352dc2020-04-06 21:12:42 +02001541
1542 if (mch_isdir(fname))
1543 {
1544 semsg(_(e_isadir2), fname);
1545 return;
1546 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001547 if (*fname == NUL || (fd = mch_fopen((char *)fname, READBIN)) == NULL)
1548 {
1549 semsg(_(e_notopen), *fname == NUL ? (char_u *)_("<empty>") : fname);
1550 return;
1551 }
1552
1553 if (blob)
1554 {
1555 if (read_blob(fd, rettv->vval.v_blob) == FAIL)
1556 {
Bram Moolenaar15352dc2020-04-06 21:12:42 +02001557 semsg(_(e_notread), fname);
1558 // An empty blob is returned on error.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001559 blob_free(rettv->vval.v_blob);
Bram Moolenaar15352dc2020-04-06 21:12:42 +02001560 rettv->vval.v_blob = NULL;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001561 }
1562 fclose(fd);
1563 return;
1564 }
1565
1566 while (cnt < maxline || maxline < 0)
1567 {
1568 readlen = (int)fread(buf, 1, io_size, fd);
1569
Bram Moolenaar26262f82019-09-04 20:59:15 +02001570 // This for loop processes what was read, but is also entered at end
1571 // of file so that either:
1572 // - an incomplete line gets written
1573 // - a "binary" file gets an empty line at the end if it ends in a
1574 // newline.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001575 for (p = buf, start = buf;
1576 p < buf + readlen || (readlen <= 0 && (prevlen > 0 || binary));
1577 ++p)
1578 {
1579 if (*p == '\n' || readlen <= 0)
1580 {
1581 listitem_T *li;
1582 char_u *s = NULL;
1583 long_u len = p - start;
1584
Bram Moolenaar26262f82019-09-04 20:59:15 +02001585 // Finished a line. Remove CRs before NL.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001586 if (readlen > 0 && !binary)
1587 {
1588 while (len > 0 && start[len - 1] == '\r')
1589 --len;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001590 // removal may cross back to the "prev" string
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001591 if (len == 0)
1592 while (prevlen > 0 && prev[prevlen - 1] == '\r')
1593 --prevlen;
1594 }
1595 if (prevlen == 0)
1596 s = vim_strnsave(start, (int)len);
1597 else
1598 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001599 // Change "prev" buffer to be the right size. This way
1600 // the bytes are only copied once, and very long lines are
1601 // allocated only once.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001602 if ((s = vim_realloc(prev, prevlen + len + 1)) != NULL)
1603 {
1604 mch_memmove(s + prevlen, start, len);
1605 s[prevlen + len] = NUL;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001606 prev = NULL; // the list will own the string
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001607 prevlen = prevsize = 0;
1608 }
1609 }
1610 if (s == NULL)
1611 {
1612 do_outofmem_msg((long_u) prevlen + len + 1);
1613 failed = TRUE;
1614 break;
1615 }
1616
1617 if ((li = listitem_alloc()) == NULL)
1618 {
1619 vim_free(s);
1620 failed = TRUE;
1621 break;
1622 }
1623 li->li_tv.v_type = VAR_STRING;
1624 li->li_tv.v_lock = 0;
1625 li->li_tv.vval.v_string = s;
1626 list_append(rettv->vval.v_list, li);
1627
Bram Moolenaar26262f82019-09-04 20:59:15 +02001628 start = p + 1; // step over newline
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001629 if ((++cnt >= maxline && maxline >= 0) || readlen <= 0)
1630 break;
1631 }
1632 else if (*p == NUL)
1633 *p = '\n';
Bram Moolenaar26262f82019-09-04 20:59:15 +02001634 // Check for utf8 "bom"; U+FEFF is encoded as EF BB BF. Do this
1635 // when finding the BF and check the previous two bytes.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001636 else if (*p == 0xbf && enc_utf8 && !binary)
1637 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001638 // Find the two bytes before the 0xbf. If p is at buf, or buf
1639 // + 1, these may be in the "prev" string.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001640 char_u back1 = p >= buf + 1 ? p[-1]
1641 : prevlen >= 1 ? prev[prevlen - 1] : NUL;
1642 char_u back2 = p >= buf + 2 ? p[-2]
1643 : p == buf + 1 && prevlen >= 1 ? prev[prevlen - 1]
1644 : prevlen >= 2 ? prev[prevlen - 2] : NUL;
1645
1646 if (back2 == 0xef && back1 == 0xbb)
1647 {
1648 char_u *dest = p - 2;
1649
Bram Moolenaar26262f82019-09-04 20:59:15 +02001650 // Usually a BOM is at the beginning of a file, and so at
1651 // the beginning of a line; then we can just step over it.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001652 if (start == dest)
1653 start = p + 1;
1654 else
1655 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001656 // have to shuffle buf to close gap
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001657 int adjust_prevlen = 0;
1658
1659 if (dest < buf)
1660 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001661 adjust_prevlen = (int)(buf - dest); // must be 1 or 2
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001662 dest = buf;
1663 }
1664 if (readlen > p - buf + 1)
1665 mch_memmove(dest, p + 1, readlen - (p - buf) - 1);
1666 readlen -= 3 - adjust_prevlen;
1667 prevlen -= adjust_prevlen;
1668 p = dest - 1;
1669 }
1670 }
1671 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02001672 } // for
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001673
1674 if (failed || (cnt >= maxline && maxline >= 0) || readlen <= 0)
1675 break;
1676 if (start < p)
1677 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001678 // There's part of a line in buf, store it in "prev".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001679 if (p - start + prevlen >= prevsize)
1680 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001681 // need bigger "prev" buffer
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001682 char_u *newprev;
1683
Bram Moolenaar26262f82019-09-04 20:59:15 +02001684 // A common use case is ordinary text files and "prev" gets a
1685 // fragment of a line, so the first allocation is made
1686 // small, to avoid repeatedly 'allocing' large and
1687 // 'reallocing' small.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001688 if (prevsize == 0)
1689 prevsize = (long)(p - start);
1690 else
1691 {
1692 long grow50pc = (prevsize * 3) / 2;
1693 long growmin = (long)((p - start) * 2 + prevlen);
1694 prevsize = grow50pc > growmin ? grow50pc : growmin;
1695 }
1696 newprev = vim_realloc(prev, prevsize);
1697 if (newprev == NULL)
1698 {
1699 do_outofmem_msg((long_u)prevsize);
1700 failed = TRUE;
1701 break;
1702 }
1703 prev = newprev;
1704 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02001705 // Add the line part to end of "prev".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001706 mch_memmove(prev + prevlen, start, p - start);
1707 prevlen += (long)(p - start);
1708 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02001709 } // while
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001710
Bram Moolenaar26262f82019-09-04 20:59:15 +02001711 // For a negative line count use only the lines at the end of the file,
1712 // free the rest.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001713 if (!failed && maxline < 0)
1714 while (cnt > -maxline)
1715 {
1716 listitem_remove(rettv->vval.v_list, rettv->vval.v_list->lv_first);
1717 --cnt;
1718 }
1719
1720 if (failed)
1721 {
1722 // an empty list is returned on error
1723 list_free(rettv->vval.v_list);
1724 rettv_list_alloc(rettv);
1725 }
1726
1727 vim_free(prev);
1728 fclose(fd);
1729}
1730
1731/*
1732 * "resolve()" function
1733 */
1734 void
1735f_resolve(typval_T *argvars, typval_T *rettv)
1736{
1737 char_u *p;
1738#ifdef HAVE_READLINK
1739 char_u *buf = NULL;
1740#endif
1741
1742 p = tv_get_string(&argvars[0]);
1743#ifdef FEAT_SHORTCUT
1744 {
1745 char_u *v = NULL;
1746
1747 v = mch_resolve_path(p, TRUE);
1748 if (v != NULL)
1749 rettv->vval.v_string = v;
1750 else
1751 rettv->vval.v_string = vim_strsave(p);
1752 }
1753#else
1754# ifdef HAVE_READLINK
1755 {
1756 char_u *cpy;
1757 int len;
1758 char_u *remain = NULL;
1759 char_u *q;
1760 int is_relative_to_current = FALSE;
1761 int has_trailing_pathsep = FALSE;
1762 int limit = 100;
1763
1764 p = vim_strsave(p);
Bram Moolenaar70188f52019-12-23 18:18:52 +01001765 if (p == NULL)
1766 goto fail;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001767 if (p[0] == '.' && (vim_ispathsep(p[1])
1768 || (p[1] == '.' && (vim_ispathsep(p[2])))))
1769 is_relative_to_current = TRUE;
1770
1771 len = STRLEN(p);
1772 if (len > 0 && after_pathsep(p, p + len))
1773 {
1774 has_trailing_pathsep = TRUE;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001775 p[len - 1] = NUL; // the trailing slash breaks readlink()
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001776 }
1777
1778 q = getnextcomp(p);
1779 if (*q != NUL)
1780 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001781 // Separate the first path component in "p", and keep the
1782 // remainder (beginning with the path separator).
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001783 remain = vim_strsave(q - 1);
1784 q[-1] = NUL;
1785 }
1786
1787 buf = alloc(MAXPATHL + 1);
1788 if (buf == NULL)
Bram Moolenaar70188f52019-12-23 18:18:52 +01001789 {
1790 vim_free(p);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001791 goto fail;
Bram Moolenaar70188f52019-12-23 18:18:52 +01001792 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001793
1794 for (;;)
1795 {
1796 for (;;)
1797 {
1798 len = readlink((char *)p, (char *)buf, MAXPATHL);
1799 if (len <= 0)
1800 break;
1801 buf[len] = NUL;
1802
1803 if (limit-- == 0)
1804 {
1805 vim_free(p);
1806 vim_free(remain);
1807 emsg(_("E655: Too many symbolic links (cycle?)"));
1808 rettv->vval.v_string = NULL;
1809 goto fail;
1810 }
1811
Bram Moolenaar26262f82019-09-04 20:59:15 +02001812 // Ensure that the result will have a trailing path separator
1813 // if the argument has one.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001814 if (remain == NULL && has_trailing_pathsep)
1815 add_pathsep(buf);
1816
Bram Moolenaar26262f82019-09-04 20:59:15 +02001817 // Separate the first path component in the link value and
1818 // concatenate the remainders.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001819 q = getnextcomp(vim_ispathsep(*buf) ? buf + 1 : buf);
1820 if (*q != NUL)
1821 {
1822 if (remain == NULL)
1823 remain = vim_strsave(q - 1);
1824 else
1825 {
1826 cpy = concat_str(q - 1, remain);
1827 if (cpy != NULL)
1828 {
1829 vim_free(remain);
1830 remain = cpy;
1831 }
1832 }
1833 q[-1] = NUL;
1834 }
1835
1836 q = gettail(p);
1837 if (q > p && *q == NUL)
1838 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001839 // Ignore trailing path separator.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001840 q[-1] = NUL;
1841 q = gettail(p);
1842 }
1843 if (q > p && !mch_isFullName(buf))
1844 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001845 // symlink is relative to directory of argument
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001846 cpy = alloc(STRLEN(p) + STRLEN(buf) + 1);
1847 if (cpy != NULL)
1848 {
1849 STRCPY(cpy, p);
1850 STRCPY(gettail(cpy), buf);
1851 vim_free(p);
1852 p = cpy;
1853 }
1854 }
1855 else
1856 {
1857 vim_free(p);
1858 p = vim_strsave(buf);
1859 }
1860 }
1861
1862 if (remain == NULL)
1863 break;
1864
Bram Moolenaar26262f82019-09-04 20:59:15 +02001865 // Append the first path component of "remain" to "p".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001866 q = getnextcomp(remain + 1);
1867 len = q - remain - (*q != NUL);
1868 cpy = vim_strnsave(p, STRLEN(p) + len);
1869 if (cpy != NULL)
1870 {
1871 STRNCAT(cpy, remain, len);
1872 vim_free(p);
1873 p = cpy;
1874 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02001875 // Shorten "remain".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001876 if (*q != NUL)
1877 STRMOVE(remain, q - 1);
1878 else
1879 VIM_CLEAR(remain);
1880 }
1881
Bram Moolenaar26262f82019-09-04 20:59:15 +02001882 // If the result is a relative path name, make it explicitly relative to
1883 // the current directory if and only if the argument had this form.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001884 if (!vim_ispathsep(*p))
1885 {
1886 if (is_relative_to_current
1887 && *p != NUL
1888 && !(p[0] == '.'
1889 && (p[1] == NUL
1890 || vim_ispathsep(p[1])
1891 || (p[1] == '.'
1892 && (p[2] == NUL
1893 || vim_ispathsep(p[2]))))))
1894 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001895 // Prepend "./".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001896 cpy = concat_str((char_u *)"./", p);
1897 if (cpy != NULL)
1898 {
1899 vim_free(p);
1900 p = cpy;
1901 }
1902 }
1903 else if (!is_relative_to_current)
1904 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001905 // Strip leading "./".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001906 q = p;
1907 while (q[0] == '.' && vim_ispathsep(q[1]))
1908 q += 2;
1909 if (q > p)
1910 STRMOVE(p, p + 2);
1911 }
1912 }
1913
Bram Moolenaar26262f82019-09-04 20:59:15 +02001914 // Ensure that the result will have no trailing path separator
1915 // if the argument had none. But keep "/" or "//".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001916 if (!has_trailing_pathsep)
1917 {
1918 q = p + STRLEN(p);
1919 if (after_pathsep(p, q))
1920 *gettail_sep(p) = NUL;
1921 }
1922
1923 rettv->vval.v_string = p;
1924 }
1925# else
1926 rettv->vval.v_string = vim_strsave(p);
1927# endif
1928#endif
1929
1930 simplify_filename(rettv->vval.v_string);
1931
1932#ifdef HAVE_READLINK
1933fail:
1934 vim_free(buf);
1935#endif
1936 rettv->v_type = VAR_STRING;
1937}
1938
1939/*
1940 * "tempname()" function
1941 */
1942 void
1943f_tempname(typval_T *argvars UNUSED, typval_T *rettv)
1944{
1945 static int x = 'A';
1946
1947 rettv->v_type = VAR_STRING;
1948 rettv->vval.v_string = vim_tempname(x, FALSE);
1949
Bram Moolenaar26262f82019-09-04 20:59:15 +02001950 // Advance 'x' to use A-Z and 0-9, so that there are at least 34 different
1951 // names. Skip 'I' and 'O', they are used for shell redirection.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001952 do
1953 {
1954 if (x == 'Z')
1955 x = '0';
1956 else if (x == '9')
1957 x = 'A';
1958 else
1959 {
1960#ifdef EBCDIC
1961 if (x == 'I')
1962 x = 'J';
1963 else if (x == 'R')
1964 x = 'S';
1965 else
1966#endif
1967 ++x;
1968 }
1969 } while (x == 'I' || x == 'O');
1970}
1971
1972/*
1973 * "writefile()" function
1974 */
1975 void
1976f_writefile(typval_T *argvars, typval_T *rettv)
1977{
1978 int binary = FALSE;
1979 int append = FALSE;
1980#ifdef HAVE_FSYNC
1981 int do_fsync = p_fs;
1982#endif
1983 char_u *fname;
1984 FILE *fd;
1985 int ret = 0;
1986 listitem_T *li;
1987 list_T *list = NULL;
1988 blob_T *blob = NULL;
1989
1990 rettv->vval.v_number = -1;
1991 if (check_secure())
1992 return;
1993
1994 if (argvars[0].v_type == VAR_LIST)
1995 {
1996 list = argvars[0].vval.v_list;
1997 if (list == NULL)
1998 return;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02001999 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002000 FOR_ALL_LIST_ITEMS(list, li)
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002001 if (tv_get_string_chk(&li->li_tv) == NULL)
2002 return;
2003 }
2004 else if (argvars[0].v_type == VAR_BLOB)
2005 {
2006 blob = argvars[0].vval.v_blob;
2007 if (blob == NULL)
2008 return;
2009 }
2010 else
2011 {
Bram Moolenaar18a2b872020-03-19 13:08:45 +01002012 semsg(_(e_invarg2),
2013 _("writefile() first argument must be a List or a Blob"));
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002014 return;
2015 }
2016
2017 if (argvars[2].v_type != VAR_UNKNOWN)
2018 {
2019 char_u *arg2 = tv_get_string_chk(&argvars[2]);
2020
2021 if (arg2 == NULL)
2022 return;
2023 if (vim_strchr(arg2, 'b') != NULL)
2024 binary = TRUE;
2025 if (vim_strchr(arg2, 'a') != NULL)
2026 append = TRUE;
2027#ifdef HAVE_FSYNC
2028 if (vim_strchr(arg2, 's') != NULL)
2029 do_fsync = TRUE;
2030 else if (vim_strchr(arg2, 'S') != NULL)
2031 do_fsync = FALSE;
2032#endif
2033 }
2034
2035 fname = tv_get_string_chk(&argvars[1]);
2036 if (fname == NULL)
2037 return;
2038
Bram Moolenaar26262f82019-09-04 20:59:15 +02002039 // Always open the file in binary mode, library functions have a mind of
2040 // their own about CR-LF conversion.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002041 if (*fname == NUL || (fd = mch_fopen((char *)fname,
2042 append ? APPENDBIN : WRITEBIN)) == NULL)
2043 {
2044 semsg(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
2045 ret = -1;
2046 }
2047 else if (blob)
2048 {
2049 if (write_blob(fd, blob) == FAIL)
2050 ret = -1;
2051#ifdef HAVE_FSYNC
2052 else if (do_fsync)
2053 // Ignore the error, the user wouldn't know what to do about it.
2054 // May happen for a device.
2055 vim_ignored = vim_fsync(fileno(fd));
2056#endif
2057 fclose(fd);
2058 }
2059 else
2060 {
2061 if (write_list(fd, list, binary) == FAIL)
2062 ret = -1;
2063#ifdef HAVE_FSYNC
2064 else if (do_fsync)
Bram Moolenaar26262f82019-09-04 20:59:15 +02002065 // Ignore the error, the user wouldn't know what to do about it.
2066 // May happen for a device.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002067 vim_ignored = vim_fsync(fileno(fd));
2068#endif
2069 fclose(fd);
2070 }
2071
2072 rettv->vval.v_number = ret;
2073}
2074
2075#endif // FEAT_EVAL
2076
2077#if defined(FEAT_BROWSE) || defined(PROTO)
2078/*
2079 * Generic browse function. Calls gui_mch_browse() when possible.
2080 * Later this may pop-up a non-GUI file selector (external command?).
2081 */
2082 char_u *
2083do_browse(
Bram Moolenaar26262f82019-09-04 20:59:15 +02002084 int flags, // BROWSE_SAVE and BROWSE_DIR
2085 char_u *title, // title for the window
2086 char_u *dflt, // default file name (may include directory)
2087 char_u *ext, // extension added
2088 char_u *initdir, // initial directory, NULL for current dir or
2089 // when using path from "dflt"
2090 char_u *filter, // file name filter
2091 buf_T *buf) // buffer to read/write for
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002092{
2093 char_u *fname;
Bram Moolenaar26262f82019-09-04 20:59:15 +02002094 static char_u *last_dir = NULL; // last used directory
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002095 char_u *tofree = NULL;
2096 int save_browse = cmdmod.browse;
2097
Bram Moolenaar26262f82019-09-04 20:59:15 +02002098 // Must turn off browse to avoid that autocommands will get the
2099 // flag too!
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002100 cmdmod.browse = FALSE;
2101
2102 if (title == NULL || *title == NUL)
2103 {
2104 if (flags & BROWSE_DIR)
2105 title = (char_u *)_("Select Directory dialog");
2106 else if (flags & BROWSE_SAVE)
2107 title = (char_u *)_("Save File dialog");
2108 else
2109 title = (char_u *)_("Open File dialog");
2110 }
2111
Bram Moolenaar26262f82019-09-04 20:59:15 +02002112 // When no directory specified, use default file name, default dir, buffer
2113 // dir, last dir or current dir
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002114 if ((initdir == NULL || *initdir == NUL) && dflt != NULL && *dflt != NUL)
2115 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002116 if (mch_isdir(dflt)) // default file name is a directory
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002117 {
2118 initdir = dflt;
2119 dflt = NULL;
2120 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02002121 else if (gettail(dflt) != dflt) // default file name includes a path
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002122 {
2123 tofree = vim_strsave(dflt);
2124 if (tofree != NULL)
2125 {
2126 initdir = tofree;
2127 *gettail(initdir) = NUL;
2128 dflt = gettail(dflt);
2129 }
2130 }
2131 }
2132
2133 if (initdir == NULL || *initdir == NUL)
2134 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002135 // When 'browsedir' is a directory, use it
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002136 if (STRCMP(p_bsdir, "last") != 0
2137 && STRCMP(p_bsdir, "buffer") != 0
2138 && STRCMP(p_bsdir, "current") != 0
2139 && mch_isdir(p_bsdir))
2140 initdir = p_bsdir;
Bram Moolenaar26262f82019-09-04 20:59:15 +02002141 // When saving or 'browsedir' is "buffer", use buffer fname
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002142 else if (((flags & BROWSE_SAVE) || *p_bsdir == 'b')
2143 && buf != NULL && buf->b_ffname != NULL)
2144 {
2145 if (dflt == NULL || *dflt == NUL)
2146 dflt = gettail(curbuf->b_ffname);
2147 tofree = vim_strsave(curbuf->b_ffname);
2148 if (tofree != NULL)
2149 {
2150 initdir = tofree;
2151 *gettail(initdir) = NUL;
2152 }
2153 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02002154 // When 'browsedir' is "last", use dir from last browse
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002155 else if (*p_bsdir == 'l')
2156 initdir = last_dir;
Bram Moolenaar26262f82019-09-04 20:59:15 +02002157 // When 'browsedir is "current", use current directory. This is the
2158 // default already, leave initdir empty.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002159 }
2160
2161# ifdef FEAT_GUI
Bram Moolenaar26262f82019-09-04 20:59:15 +02002162 if (gui.in_use) // when this changes, also adjust f_has()!
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002163 {
2164 if (filter == NULL
2165# ifdef FEAT_EVAL
2166 && (filter = get_var_value((char_u *)"b:browsefilter")) == NULL
2167 && (filter = get_var_value((char_u *)"g:browsefilter")) == NULL
2168# endif
2169 )
2170 filter = BROWSE_FILTER_DEFAULT;
2171 if (flags & BROWSE_DIR)
2172 {
2173# if defined(FEAT_GUI_GTK) || defined(MSWIN)
Bram Moolenaar26262f82019-09-04 20:59:15 +02002174 // For systems that have a directory dialog.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002175 fname = gui_mch_browsedir(title, initdir);
2176# else
Bram Moolenaar26262f82019-09-04 20:59:15 +02002177 // Generic solution for selecting a directory: select a file and
2178 // remove the file name.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002179 fname = gui_mch_browse(0, title, dflt, ext, initdir, (char_u *)"");
2180# endif
2181# if !defined(FEAT_GUI_GTK)
Bram Moolenaar26262f82019-09-04 20:59:15 +02002182 // Win32 adds a dummy file name, others return an arbitrary file
2183 // name. GTK+ 2 returns only the directory,
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002184 if (fname != NULL && *fname != NUL && !mch_isdir(fname))
2185 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002186 // Remove the file name.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002187 char_u *tail = gettail_sep(fname);
2188
2189 if (tail == fname)
Bram Moolenaar26262f82019-09-04 20:59:15 +02002190 *tail++ = '.'; // use current dir
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002191 *tail = NUL;
2192 }
2193# endif
2194 }
2195 else
2196 fname = gui_mch_browse(flags & BROWSE_SAVE,
2197 title, dflt, ext, initdir, (char_u *)_(filter));
2198
Bram Moolenaar26262f82019-09-04 20:59:15 +02002199 // We hang around in the dialog for a while, the user might do some
2200 // things to our files. The Win32 dialog allows deleting or renaming
2201 // a file, check timestamps.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002202 need_check_timestamps = TRUE;
2203 did_check_timestamps = FALSE;
2204 }
2205 else
2206# endif
2207 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002208 // TODO: non-GUI file selector here
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002209 emsg(_("E338: Sorry, no file browser in console mode"));
2210 fname = NULL;
2211 }
2212
Bram Moolenaar26262f82019-09-04 20:59:15 +02002213 // keep the directory for next time
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002214 if (fname != NULL)
2215 {
2216 vim_free(last_dir);
2217 last_dir = vim_strsave(fname);
2218 if (last_dir != NULL && !(flags & BROWSE_DIR))
2219 {
2220 *gettail(last_dir) = NUL;
2221 if (*last_dir == NUL)
2222 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002223 // filename only returned, must be in current dir
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002224 vim_free(last_dir);
2225 last_dir = alloc(MAXPATHL);
2226 if (last_dir != NULL)
2227 mch_dirname(last_dir, MAXPATHL);
2228 }
2229 }
2230 }
2231
2232 vim_free(tofree);
2233 cmdmod.browse = save_browse;
2234
2235 return fname;
2236}
2237#endif
2238
2239#if defined(FEAT_EVAL) || defined(PROTO)
2240
2241/*
2242 * "browse(save, title, initdir, default)" function
2243 */
2244 void
2245f_browse(typval_T *argvars UNUSED, typval_T *rettv)
2246{
2247# ifdef FEAT_BROWSE
2248 int save;
2249 char_u *title;
2250 char_u *initdir;
2251 char_u *defname;
2252 char_u buf[NUMBUFLEN];
2253 char_u buf2[NUMBUFLEN];
2254 int error = FALSE;
2255
2256 save = (int)tv_get_number_chk(&argvars[0], &error);
2257 title = tv_get_string_chk(&argvars[1]);
2258 initdir = tv_get_string_buf_chk(&argvars[2], buf);
2259 defname = tv_get_string_buf_chk(&argvars[3], buf2);
2260
2261 if (error || title == NULL || initdir == NULL || defname == NULL)
2262 rettv->vval.v_string = NULL;
2263 else
2264 rettv->vval.v_string =
2265 do_browse(save ? BROWSE_SAVE : 0,
2266 title, defname, NULL, initdir, NULL, curbuf);
2267# else
2268 rettv->vval.v_string = NULL;
2269# endif
2270 rettv->v_type = VAR_STRING;
2271}
2272
2273/*
2274 * "browsedir(title, initdir)" function
2275 */
2276 void
2277f_browsedir(typval_T *argvars UNUSED, typval_T *rettv)
2278{
2279# ifdef FEAT_BROWSE
2280 char_u *title;
2281 char_u *initdir;
2282 char_u buf[NUMBUFLEN];
2283
2284 title = tv_get_string_chk(&argvars[0]);
2285 initdir = tv_get_string_buf_chk(&argvars[1], buf);
2286
2287 if (title == NULL || initdir == NULL)
2288 rettv->vval.v_string = NULL;
2289 else
2290 rettv->vval.v_string = do_browse(BROWSE_DIR,
2291 title, NULL, NULL, initdir, NULL, curbuf);
2292# else
2293 rettv->vval.v_string = NULL;
2294# endif
2295 rettv->v_type = VAR_STRING;
2296}
2297
2298#endif // FEAT_EVAL
Bram Moolenaar26262f82019-09-04 20:59:15 +02002299
2300/*
2301 * Replace home directory by "~" in each space or comma separated file name in
2302 * 'src'.
2303 * If anything fails (except when out of space) dst equals src.
2304 */
2305 void
2306home_replace(
2307 buf_T *buf, // when not NULL, check for help files
2308 char_u *src, // input file name
2309 char_u *dst, // where to put the result
2310 int dstlen, // maximum length of the result
2311 int one) // if TRUE, only replace one file name, include
2312 // spaces and commas in the file name.
2313{
2314 size_t dirlen = 0, envlen = 0;
2315 size_t len;
2316 char_u *homedir_env, *homedir_env_orig;
2317 char_u *p;
2318
2319 if (src == NULL)
2320 {
2321 *dst = NUL;
2322 return;
2323 }
2324
2325 /*
2326 * If the file is a help file, remove the path completely.
2327 */
2328 if (buf != NULL && buf->b_help)
2329 {
2330 vim_snprintf((char *)dst, dstlen, "%s", gettail(src));
2331 return;
2332 }
2333
2334 /*
2335 * We check both the value of the $HOME environment variable and the
2336 * "real" home directory.
2337 */
2338 if (homedir != NULL)
2339 dirlen = STRLEN(homedir);
2340
2341#ifdef VMS
2342 homedir_env_orig = homedir_env = mch_getenv((char_u *)"SYS$LOGIN");
2343#else
2344 homedir_env_orig = homedir_env = mch_getenv((char_u *)"HOME");
2345#endif
2346#ifdef MSWIN
2347 if (homedir_env == NULL)
2348 homedir_env_orig = homedir_env = mch_getenv((char_u *)"USERPROFILE");
2349#endif
2350 // Empty is the same as not set.
2351 if (homedir_env != NULL && *homedir_env == NUL)
2352 homedir_env = NULL;
2353
2354 if (homedir_env != NULL && *homedir_env == '~')
2355 {
2356 int usedlen = 0;
2357 int flen;
2358 char_u *fbuf = NULL;
2359
2360 flen = (int)STRLEN(homedir_env);
2361 (void)modify_fname((char_u *)":p", FALSE, &usedlen,
2362 &homedir_env, &fbuf, &flen);
2363 flen = (int)STRLEN(homedir_env);
2364 if (flen > 0 && vim_ispathsep(homedir_env[flen - 1]))
2365 // Remove the trailing / that is added to a directory.
2366 homedir_env[flen - 1] = NUL;
2367 }
2368
2369 if (homedir_env != NULL)
2370 envlen = STRLEN(homedir_env);
2371
2372 if (!one)
2373 src = skipwhite(src);
2374 while (*src && dstlen > 0)
2375 {
2376 /*
2377 * Here we are at the beginning of a file name.
2378 * First, check to see if the beginning of the file name matches
2379 * $HOME or the "real" home directory. Check that there is a '/'
2380 * after the match (so that if e.g. the file is "/home/pieter/bla",
2381 * and the home directory is "/home/piet", the file does not end up
2382 * as "~er/bla" (which would seem to indicate the file "bla" in user
2383 * er's home directory)).
2384 */
2385 p = homedir;
2386 len = dirlen;
2387 for (;;)
2388 {
2389 if ( len
2390 && fnamencmp(src, p, len) == 0
2391 && (vim_ispathsep(src[len])
2392 || (!one && (src[len] == ',' || src[len] == ' '))
2393 || src[len] == NUL))
2394 {
2395 src += len;
2396 if (--dstlen > 0)
2397 *dst++ = '~';
2398
2399 /*
2400 * If it's just the home directory, add "/".
2401 */
2402 if (!vim_ispathsep(src[0]) && --dstlen > 0)
2403 *dst++ = '/';
2404 break;
2405 }
2406 if (p == homedir_env)
2407 break;
2408 p = homedir_env;
2409 len = envlen;
2410 }
2411
2412 // if (!one) skip to separator: space or comma
2413 while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0)
2414 *dst++ = *src++;
2415 // skip separator
2416 while ((*src == ' ' || *src == ',') && --dstlen > 0)
2417 *dst++ = *src++;
2418 }
2419 // if (dstlen == 0) out of space, what to do???
2420
2421 *dst = NUL;
2422
2423 if (homedir_env != homedir_env_orig)
2424 vim_free(homedir_env);
2425}
2426
2427/*
2428 * Like home_replace, store the replaced string in allocated memory.
2429 * When something fails, NULL is returned.
2430 */
2431 char_u *
2432home_replace_save(
2433 buf_T *buf, // when not NULL, check for help files
2434 char_u *src) // input file name
2435{
2436 char_u *dst;
2437 unsigned len;
2438
2439 len = 3; // space for "~/" and trailing NUL
2440 if (src != NULL) // just in case
2441 len += (unsigned)STRLEN(src);
2442 dst = alloc(len);
2443 if (dst != NULL)
2444 home_replace(buf, src, dst, len, TRUE);
2445 return dst;
2446}
2447
2448/*
2449 * Compare two file names and return:
2450 * FPC_SAME if they both exist and are the same file.
2451 * FPC_SAMEX if they both don't exist and have the same file name.
2452 * FPC_DIFF if they both exist and are different files.
2453 * FPC_NOTX if they both don't exist.
2454 * FPC_DIFFX if one of them doesn't exist.
2455 * For the first name environment variables are expanded if "expandenv" is
2456 * TRUE.
2457 */
2458 int
2459fullpathcmp(
2460 char_u *s1,
2461 char_u *s2,
2462 int checkname, // when both don't exist, check file names
2463 int expandenv)
2464{
2465#ifdef UNIX
2466 char_u exp1[MAXPATHL];
2467 char_u full1[MAXPATHL];
2468 char_u full2[MAXPATHL];
2469 stat_T st1, st2;
2470 int r1, r2;
2471
2472 if (expandenv)
2473 expand_env(s1, exp1, MAXPATHL);
2474 else
2475 vim_strncpy(exp1, s1, MAXPATHL - 1);
2476 r1 = mch_stat((char *)exp1, &st1);
2477 r2 = mch_stat((char *)s2, &st2);
2478 if (r1 != 0 && r2 != 0)
2479 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002480 // if mch_stat() doesn't work, may compare the names
Bram Moolenaar26262f82019-09-04 20:59:15 +02002481 if (checkname)
2482 {
2483 if (fnamecmp(exp1, s2) == 0)
2484 return FPC_SAMEX;
2485 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
2486 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
2487 if (r1 == OK && r2 == OK && fnamecmp(full1, full2) == 0)
2488 return FPC_SAMEX;
2489 }
2490 return FPC_NOTX;
2491 }
2492 if (r1 != 0 || r2 != 0)
2493 return FPC_DIFFX;
2494 if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
2495 return FPC_SAME;
2496 return FPC_DIFF;
2497#else
2498 char_u *exp1; // expanded s1
2499 char_u *full1; // full path of s1
2500 char_u *full2; // full path of s2
2501 int retval = FPC_DIFF;
2502 int r1, r2;
2503
2504 // allocate one buffer to store three paths (alloc()/free() is slow!)
2505 if ((exp1 = alloc(MAXPATHL * 3)) != NULL)
2506 {
2507 full1 = exp1 + MAXPATHL;
2508 full2 = full1 + MAXPATHL;
2509
2510 if (expandenv)
2511 expand_env(s1, exp1, MAXPATHL);
2512 else
2513 vim_strncpy(exp1, s1, MAXPATHL - 1);
2514 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
2515 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
2516
2517 // If vim_FullName() fails, the file probably doesn't exist.
2518 if (r1 != OK && r2 != OK)
2519 {
2520 if (checkname && fnamecmp(exp1, s2) == 0)
2521 retval = FPC_SAMEX;
2522 else
2523 retval = FPC_NOTX;
2524 }
2525 else if (r1 != OK || r2 != OK)
2526 retval = FPC_DIFFX;
2527 else if (fnamecmp(full1, full2))
2528 retval = FPC_DIFF;
2529 else
2530 retval = FPC_SAME;
2531 vim_free(exp1);
2532 }
2533 return retval;
2534#endif
2535}
2536
2537/*
2538 * Get the tail of a path: the file name.
2539 * When the path ends in a path separator the tail is the NUL after it.
2540 * Fail safe: never returns NULL.
2541 */
2542 char_u *
2543gettail(char_u *fname)
2544{
2545 char_u *p1, *p2;
2546
2547 if (fname == NULL)
2548 return (char_u *)"";
2549 for (p1 = p2 = get_past_head(fname); *p2; ) // find last part of path
2550 {
2551 if (vim_ispathsep_nocolon(*p2))
2552 p1 = p2 + 1;
2553 MB_PTR_ADV(p2);
2554 }
2555 return p1;
2556}
2557
2558/*
2559 * Get pointer to tail of "fname", including path separators. Putting a NUL
2560 * here leaves the directory name. Takes care of "c:/" and "//".
2561 * Always returns a valid pointer.
2562 */
2563 char_u *
2564gettail_sep(char_u *fname)
2565{
2566 char_u *p;
2567 char_u *t;
2568
2569 p = get_past_head(fname); // don't remove the '/' from "c:/file"
2570 t = gettail(fname);
2571 while (t > p && after_pathsep(fname, t))
2572 --t;
2573#ifdef VMS
2574 // path separator is part of the path
2575 ++t;
2576#endif
2577 return t;
2578}
2579
2580/*
2581 * get the next path component (just after the next path separator).
2582 */
2583 char_u *
2584getnextcomp(char_u *fname)
2585{
2586 while (*fname && !vim_ispathsep(*fname))
2587 MB_PTR_ADV(fname);
2588 if (*fname)
2589 ++fname;
2590 return fname;
2591}
2592
2593/*
2594 * Get a pointer to one character past the head of a path name.
2595 * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
2596 * If there is no head, path is returned.
2597 */
2598 char_u *
2599get_past_head(char_u *path)
2600{
2601 char_u *retval;
2602
2603#if defined(MSWIN)
2604 // may skip "c:"
2605 if (isalpha(path[0]) && path[1] == ':')
2606 retval = path + 2;
2607 else
2608 retval = path;
2609#else
2610# if defined(AMIGA)
2611 // may skip "label:"
2612 retval = vim_strchr(path, ':');
2613 if (retval == NULL)
2614 retval = path;
2615# else // Unix
2616 retval = path;
2617# endif
2618#endif
2619
2620 while (vim_ispathsep(*retval))
2621 ++retval;
2622
2623 return retval;
2624}
2625
2626/*
2627 * Return TRUE if 'c' is a path separator.
2628 * Note that for MS-Windows this includes the colon.
2629 */
2630 int
2631vim_ispathsep(int c)
2632{
2633#ifdef UNIX
2634 return (c == '/'); // UNIX has ':' inside file names
2635#else
2636# ifdef BACKSLASH_IN_FILENAME
2637 return (c == ':' || c == '/' || c == '\\');
2638# else
2639# ifdef VMS
2640 // server"user passwd"::device:[full.path.name]fname.extension;version"
2641 return (c == ':' || c == '[' || c == ']' || c == '/'
2642 || c == '<' || c == '>' || c == '"' );
2643# else
2644 return (c == ':' || c == '/');
2645# endif // VMS
2646# endif
2647#endif
2648}
2649
2650/*
2651 * Like vim_ispathsep(c), but exclude the colon for MS-Windows.
2652 */
2653 int
2654vim_ispathsep_nocolon(int c)
2655{
2656 return vim_ispathsep(c)
2657#ifdef BACKSLASH_IN_FILENAME
2658 && c != ':'
2659#endif
2660 ;
2661}
2662
2663/*
2664 * Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
2665 * It's done in-place.
2666 */
2667 void
2668shorten_dir(char_u *str)
2669{
2670 char_u *tail, *s, *d;
2671 int skip = FALSE;
2672
2673 tail = gettail(str);
2674 d = str;
2675 for (s = str; ; ++s)
2676 {
2677 if (s >= tail) // copy the whole tail
2678 {
2679 *d++ = *s;
2680 if (*s == NUL)
2681 break;
2682 }
2683 else if (vim_ispathsep(*s)) // copy '/' and next char
2684 {
2685 *d++ = *s;
2686 skip = FALSE;
2687 }
2688 else if (!skip)
2689 {
2690 *d++ = *s; // copy next char
2691 if (*s != '~' && *s != '.') // and leading "~" and "."
2692 skip = TRUE;
2693 if (has_mbyte)
2694 {
2695 int l = mb_ptr2len(s);
2696
2697 while (--l > 0)
2698 *d++ = *++s;
2699 }
2700 }
2701 }
2702}
2703
2704/*
2705 * Return TRUE if the directory of "fname" exists, FALSE otherwise.
2706 * Also returns TRUE if there is no directory name.
2707 * "fname" must be writable!.
2708 */
2709 int
2710dir_of_file_exists(char_u *fname)
2711{
2712 char_u *p;
2713 int c;
2714 int retval;
2715
2716 p = gettail_sep(fname);
2717 if (p == fname)
2718 return TRUE;
2719 c = *p;
2720 *p = NUL;
2721 retval = mch_isdir(fname);
2722 *p = c;
2723 return retval;
2724}
2725
2726/*
2727 * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally
2728 * and deal with 'fileignorecase'.
2729 */
2730 int
2731vim_fnamecmp(char_u *x, char_u *y)
2732{
2733#ifdef BACKSLASH_IN_FILENAME
2734 return vim_fnamencmp(x, y, MAXPATHL);
2735#else
2736 if (p_fic)
2737 return MB_STRICMP(x, y);
2738 return STRCMP(x, y);
2739#endif
2740}
2741
2742 int
2743vim_fnamencmp(char_u *x, char_u *y, size_t len)
2744{
2745#ifdef BACKSLASH_IN_FILENAME
2746 char_u *px = x;
2747 char_u *py = y;
2748 int cx = NUL;
2749 int cy = NUL;
2750
2751 while (len > 0)
2752 {
2753 cx = PTR2CHAR(px);
2754 cy = PTR2CHAR(py);
2755 if (cx == NUL || cy == NUL
2756 || ((p_fic ? MB_TOLOWER(cx) != MB_TOLOWER(cy) : cx != cy)
2757 && !(cx == '/' && cy == '\\')
2758 && !(cx == '\\' && cy == '/')))
2759 break;
Bram Moolenaar1614a142019-10-06 22:00:13 +02002760 len -= mb_ptr2len(px);
2761 px += mb_ptr2len(px);
2762 py += mb_ptr2len(py);
Bram Moolenaar26262f82019-09-04 20:59:15 +02002763 }
2764 if (len == 0)
2765 return 0;
2766 return (cx - cy);
2767#else
2768 if (p_fic)
2769 return MB_STRNICMP(x, y, len);
2770 return STRNCMP(x, y, len);
2771#endif
2772}
2773
2774/*
2775 * Concatenate file names fname1 and fname2 into allocated memory.
2776 * Only add a '/' or '\\' when 'sep' is TRUE and it is necessary.
2777 */
2778 char_u *
2779concat_fnames(char_u *fname1, char_u *fname2, int sep)
2780{
2781 char_u *dest;
2782
2783 dest = alloc(STRLEN(fname1) + STRLEN(fname2) + 3);
2784 if (dest != NULL)
2785 {
2786 STRCPY(dest, fname1);
2787 if (sep)
2788 add_pathsep(dest);
2789 STRCAT(dest, fname2);
2790 }
2791 return dest;
2792}
2793
2794/*
2795 * Add a path separator to a file name, unless it already ends in a path
2796 * separator.
2797 */
2798 void
2799add_pathsep(char_u *p)
2800{
2801 if (*p != NUL && !after_pathsep(p, p + STRLEN(p)))
2802 STRCAT(p, PATHSEPSTR);
2803}
2804
2805/*
2806 * FullName_save - Make an allocated copy of a full file name.
2807 * Returns NULL when out of memory.
2808 */
2809 char_u *
2810FullName_save(
2811 char_u *fname,
2812 int force) // force expansion, even when it already looks
2813 // like a full path name
2814{
2815 char_u *buf;
2816 char_u *new_fname = NULL;
2817
2818 if (fname == NULL)
2819 return NULL;
2820
2821 buf = alloc(MAXPATHL);
2822 if (buf != NULL)
2823 {
2824 if (vim_FullName(fname, buf, MAXPATHL, force) != FAIL)
2825 new_fname = vim_strsave(buf);
2826 else
2827 new_fname = vim_strsave(fname);
2828 vim_free(buf);
2829 }
2830 return new_fname;
2831}
2832
2833/*
2834 * return TRUE if "fname" exists.
2835 */
2836 int
2837vim_fexists(char_u *fname)
2838{
2839 stat_T st;
2840
2841 if (mch_stat((char *)fname, &st))
2842 return FALSE;
2843 return TRUE;
2844}
2845
2846/*
2847 * Invoke expand_wildcards() for one pattern.
2848 * Expand items like "%:h" before the expansion.
2849 * Returns OK or FAIL.
2850 */
2851 int
2852expand_wildcards_eval(
2853 char_u **pat, // pointer to input pattern
2854 int *num_file, // resulting number of files
2855 char_u ***file, // array of resulting files
2856 int flags) // EW_DIR, etc.
2857{
2858 int ret = FAIL;
2859 char_u *eval_pat = NULL;
2860 char_u *exp_pat = *pat;
2861 char *ignored_msg;
2862 int usedlen;
2863
2864 if (*exp_pat == '%' || *exp_pat == '#' || *exp_pat == '<')
2865 {
2866 ++emsg_off;
2867 eval_pat = eval_vars(exp_pat, exp_pat, &usedlen,
2868 NULL, &ignored_msg, NULL);
2869 --emsg_off;
2870 if (eval_pat != NULL)
2871 exp_pat = concat_str(eval_pat, exp_pat + usedlen);
2872 }
2873
2874 if (exp_pat != NULL)
2875 ret = expand_wildcards(1, &exp_pat, num_file, file, flags);
2876
2877 if (eval_pat != NULL)
2878 {
2879 vim_free(exp_pat);
2880 vim_free(eval_pat);
2881 }
2882
2883 return ret;
2884}
2885
2886/*
2887 * Expand wildcards. Calls gen_expand_wildcards() and removes files matching
2888 * 'wildignore'.
2889 * Returns OK or FAIL. When FAIL then "num_files" won't be set.
2890 */
2891 int
2892expand_wildcards(
2893 int num_pat, // number of input patterns
2894 char_u **pat, // array of input patterns
2895 int *num_files, // resulting number of files
2896 char_u ***files, // array of resulting files
2897 int flags) // EW_DIR, etc.
2898{
2899 int retval;
2900 int i, j;
2901 char_u *p;
2902 int non_suf_match; // number without matching suffix
2903
2904 retval = gen_expand_wildcards(num_pat, pat, num_files, files, flags);
2905
2906 // When keeping all matches, return here
2907 if ((flags & EW_KEEPALL) || retval == FAIL)
2908 return retval;
2909
2910#ifdef FEAT_WILDIGN
2911 /*
2912 * Remove names that match 'wildignore'.
2913 */
2914 if (*p_wig)
2915 {
2916 char_u *ffname;
2917
2918 // check all files in (*files)[]
2919 for (i = 0; i < *num_files; ++i)
2920 {
2921 ffname = FullName_save((*files)[i], FALSE);
2922 if (ffname == NULL) // out of memory
2923 break;
2924# ifdef VMS
2925 vms_remove_version(ffname);
2926# endif
2927 if (match_file_list(p_wig, (*files)[i], ffname))
2928 {
2929 // remove this matching file from the list
2930 vim_free((*files)[i]);
2931 for (j = i; j + 1 < *num_files; ++j)
2932 (*files)[j] = (*files)[j + 1];
2933 --*num_files;
2934 --i;
2935 }
2936 vim_free(ffname);
2937 }
2938
2939 // If the number of matches is now zero, we fail.
2940 if (*num_files == 0)
2941 {
2942 VIM_CLEAR(*files);
2943 return FAIL;
2944 }
2945 }
2946#endif
2947
2948 /*
2949 * Move the names where 'suffixes' match to the end.
2950 */
2951 if (*num_files > 1)
2952 {
2953 non_suf_match = 0;
2954 for (i = 0; i < *num_files; ++i)
2955 {
2956 if (!match_suffix((*files)[i]))
2957 {
2958 /*
2959 * Move the name without matching suffix to the front
2960 * of the list.
2961 */
2962 p = (*files)[i];
2963 for (j = i; j > non_suf_match; --j)
2964 (*files)[j] = (*files)[j - 1];
2965 (*files)[non_suf_match++] = p;
2966 }
2967 }
2968 }
2969
2970 return retval;
2971}
2972
2973/*
2974 * Return TRUE if "fname" matches with an entry in 'suffixes'.
2975 */
2976 int
2977match_suffix(char_u *fname)
2978{
2979 int fnamelen, setsuflen;
2980 char_u *setsuf;
2981#define MAXSUFLEN 30 // maximum length of a file suffix
2982 char_u suf_buf[MAXSUFLEN];
2983
2984 fnamelen = (int)STRLEN(fname);
2985 setsuflen = 0;
2986 for (setsuf = p_su; *setsuf; )
2987 {
2988 setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
2989 if (setsuflen == 0)
2990 {
2991 char_u *tail = gettail(fname);
2992
2993 // empty entry: match name without a '.'
2994 if (vim_strchr(tail, '.') == NULL)
2995 {
2996 setsuflen = 1;
2997 break;
2998 }
2999 }
3000 else
3001 {
3002 if (fnamelen >= setsuflen
3003 && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
3004 (size_t)setsuflen) == 0)
3005 break;
3006 setsuflen = 0;
3007 }
3008 }
3009 return (setsuflen != 0);
3010}
3011
3012#ifdef VIM_BACKTICK
3013
3014/*
3015 * Return TRUE if we can expand this backtick thing here.
3016 */
3017 static int
3018vim_backtick(char_u *p)
3019{
3020 return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
3021}
3022
3023/*
3024 * Expand an item in `backticks` by executing it as a command.
3025 * Currently only works when pat[] starts and ends with a `.
3026 * Returns number of file names found, -1 if an error is encountered.
3027 */
3028 static int
3029expand_backtick(
3030 garray_T *gap,
3031 char_u *pat,
3032 int flags) // EW_* flags
3033{
3034 char_u *p;
3035 char_u *cmd;
3036 char_u *buffer;
3037 int cnt = 0;
3038 int i;
3039
3040 // Create the command: lop off the backticks.
3041 cmd = vim_strnsave(pat + 1, (int)STRLEN(pat) - 2);
3042 if (cmd == NULL)
3043 return -1;
3044
3045#ifdef FEAT_EVAL
3046 if (*cmd == '=') // `={expr}`: Expand expression
3047 buffer = eval_to_string(cmd + 1, &p, TRUE);
3048 else
3049#endif
3050 buffer = get_cmd_output(cmd, NULL,
3051 (flags & EW_SILENT) ? SHELL_SILENT : 0, NULL);
3052 vim_free(cmd);
3053 if (buffer == NULL)
3054 return -1;
3055
3056 cmd = buffer;
3057 while (*cmd != NUL)
3058 {
3059 cmd = skipwhite(cmd); // skip over white space
3060 p = cmd;
3061 while (*p != NUL && *p != '\r' && *p != '\n') // skip over entry
3062 ++p;
3063 // add an entry if it is not empty
3064 if (p > cmd)
3065 {
3066 i = *p;
3067 *p = NUL;
3068 addfile(gap, cmd, flags);
3069 *p = i;
3070 ++cnt;
3071 }
3072 cmd = p;
3073 while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
3074 ++cmd;
3075 }
3076
3077 vim_free(buffer);
3078 return cnt;
3079}
3080#endif // VIM_BACKTICK
3081
3082#if defined(MSWIN)
3083/*
3084 * File name expansion code for MS-DOS, Win16 and Win32. It's here because
3085 * it's shared between these systems.
3086 */
3087
3088/*
3089 * comparison function for qsort in dos_expandpath()
3090 */
3091 static int
3092pstrcmp(const void *a, const void *b)
3093{
3094 return (pathcmp(*(char **)a, *(char **)b, -1));
3095}
3096
3097/*
3098 * Recursively expand one path component into all matching files and/or
3099 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
3100 * Return the number of matches found.
3101 * "path" has backslashes before chars that are not to be expanded, starting
3102 * at "path[wildoff]".
3103 * Return the number of matches found.
3104 * NOTE: much of this is identical to unix_expandpath(), keep in sync!
3105 */
3106 static int
3107dos_expandpath(
3108 garray_T *gap,
3109 char_u *path,
3110 int wildoff,
3111 int flags, // EW_* flags
3112 int didstar) // expanded "**" once already
3113{
3114 char_u *buf;
3115 char_u *path_end;
3116 char_u *p, *s, *e;
3117 int start_len = gap->ga_len;
3118 char_u *pat;
3119 regmatch_T regmatch;
3120 int starts_with_dot;
3121 int matches;
3122 int len;
3123 int starstar = FALSE;
3124 static int stardepth = 0; // depth for "**" expansion
3125 HANDLE hFind = INVALID_HANDLE_VALUE;
3126 WIN32_FIND_DATAW wfb;
3127 WCHAR *wn = NULL; // UCS-2 name, NULL when not used.
3128 char_u *matchname;
3129 int ok;
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003130 char_u *p_alt;
Bram Moolenaar26262f82019-09-04 20:59:15 +02003131
3132 // Expanding "**" may take a long time, check for CTRL-C.
3133 if (stardepth > 0)
3134 {
3135 ui_breakcheck();
3136 if (got_int)
3137 return 0;
3138 }
3139
3140 // Make room for file name. When doing encoding conversion the actual
3141 // length may be quite a bit longer, thus use the maximum possible length.
3142 buf = alloc(MAXPATHL);
3143 if (buf == NULL)
3144 return 0;
3145
3146 /*
3147 * Find the first part in the path name that contains a wildcard or a ~1.
3148 * Copy it into buf, including the preceding characters.
3149 */
3150 p = buf;
3151 s = buf;
3152 e = NULL;
3153 path_end = path;
3154 while (*path_end != NUL)
3155 {
3156 // May ignore a wildcard that has a backslash before it; it will
3157 // be removed by rem_backslash() or file_pat_to_reg_pat() below.
3158 if (path_end >= path + wildoff && rem_backslash(path_end))
3159 *p++ = *path_end++;
3160 else if (*path_end == '\\' || *path_end == ':' || *path_end == '/')
3161 {
3162 if (e != NULL)
3163 break;
3164 s = p + 1;
3165 }
3166 else if (path_end >= path + wildoff
3167 && vim_strchr((char_u *)"*?[~", *path_end) != NULL)
3168 e = p;
3169 if (has_mbyte)
3170 {
3171 len = (*mb_ptr2len)(path_end);
3172 STRNCPY(p, path_end, len);
3173 p += len;
3174 path_end += len;
3175 }
3176 else
3177 *p++ = *path_end++;
3178 }
3179 e = p;
3180 *e = NUL;
3181
3182 // now we have one wildcard component between s and e
3183 // Remove backslashes between "wildoff" and the start of the wildcard
3184 // component.
3185 for (p = buf + wildoff; p < s; ++p)
3186 if (rem_backslash(p))
3187 {
3188 STRMOVE(p, p + 1);
3189 --e;
3190 --s;
3191 }
3192
3193 // Check for "**" between "s" and "e".
3194 for (p = s; p < e; ++p)
3195 if (p[0] == '*' && p[1] == '*')
3196 starstar = TRUE;
3197
3198 starts_with_dot = *s == '.';
3199 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
3200 if (pat == NULL)
3201 {
3202 vim_free(buf);
3203 return 0;
3204 }
3205
3206 // compile the regexp into a program
3207 if (flags & (EW_NOERROR | EW_NOTWILD))
3208 ++emsg_silent;
3209 regmatch.rm_ic = TRUE; // Always ignore case
3210 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
3211 if (flags & (EW_NOERROR | EW_NOTWILD))
3212 --emsg_silent;
3213 vim_free(pat);
3214
3215 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
3216 {
3217 vim_free(buf);
3218 return 0;
3219 }
3220
3221 // remember the pattern or file name being looked for
3222 matchname = vim_strsave(s);
3223
3224 // If "**" is by itself, this is the first time we encounter it and more
3225 // is following then find matches without any directory.
3226 if (!didstar && stardepth < 100 && starstar && e - s == 2
3227 && *path_end == '/')
3228 {
3229 STRCPY(s, path_end + 1);
3230 ++stardepth;
3231 (void)dos_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
3232 --stardepth;
3233 }
3234
3235 // Scan all files in the directory with "dir/ *.*"
3236 STRCPY(s, "*.*");
3237 wn = enc_to_utf16(buf, NULL);
3238 if (wn != NULL)
3239 hFind = FindFirstFileW(wn, &wfb);
3240 ok = (hFind != INVALID_HANDLE_VALUE);
3241
3242 while (ok)
3243 {
3244 p = utf16_to_enc(wfb.cFileName, NULL); // p is allocated here
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003245
Bram Moolenaar26262f82019-09-04 20:59:15 +02003246 if (p == NULL)
3247 break; // out of memory
3248
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003249 if (*wfb.cAlternateFileName == NUL)
Bram Moolenaar40655d52020-04-06 23:49:50 +02003250 p_alt = NULL;
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003251 else
3252 p_alt = utf16_to_enc(wfb.cAlternateFileName, NULL);
3253
Bram Moolenaar26262f82019-09-04 20:59:15 +02003254 // Ignore entries starting with a dot, unless when asked for. Accept
3255 // all entries found with "matchname".
3256 if ((p[0] != '.' || starts_with_dot
3257 || ((flags & EW_DODOT)
3258 && p[1] != NUL && (p[1] != '.' || p[2] != NUL)))
3259 && (matchname == NULL
3260 || (regmatch.regprog != NULL
Bram Moolenaar40655d52020-04-06 23:49:50 +02003261 && (vim_regexec(&regmatch, p, (colnr_T)0)
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003262 || (p_alt != NULL
Bram Moolenaar40655d52020-04-06 23:49:50 +02003263 && vim_regexec(&regmatch, p_alt, (colnr_T)0))))
Bram Moolenaar26262f82019-09-04 20:59:15 +02003264 || ((flags & EW_NOTWILD)
3265 && fnamencmp(path + (s - buf), p, e - s) == 0)))
3266 {
3267 STRCPY(s, p);
3268 len = (int)STRLEN(buf);
3269
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003270 if (starstar && stardepth < 100
3271 && (wfb.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
Bram Moolenaar26262f82019-09-04 20:59:15 +02003272 {
3273 // For "**" in the pattern first go deeper in the tree to
3274 // find matches.
3275 STRCPY(buf + len, "/**");
3276 STRCPY(buf + len + 3, path_end);
3277 ++stardepth;
3278 (void)dos_expandpath(gap, buf, len + 1, flags, TRUE);
3279 --stardepth;
3280 }
3281
3282 STRCPY(buf + len, path_end);
3283 if (mch_has_exp_wildcard(path_end))
3284 {
3285 // need to expand another component of the path
3286 // remove backslashes for the remaining components only
3287 (void)dos_expandpath(gap, buf, len + 1, flags, FALSE);
3288 }
3289 else
3290 {
3291 // no more wildcards, check if there is a match
3292 // remove backslashes for the remaining components only
3293 if (*path_end != 0)
3294 backslash_halve(buf + len + 1);
3295 if (mch_getperm(buf) >= 0) // add existing file
3296 addfile(gap, buf, flags);
3297 }
3298 }
3299
Bram Moolenaarc74fbfe2020-04-06 22:56:28 +02003300 vim_free(p_alt);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003301 vim_free(p);
3302 ok = FindNextFileW(hFind, &wfb);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003303 }
3304
3305 FindClose(hFind);
3306 vim_free(wn);
3307 vim_free(buf);
3308 vim_regfree(regmatch.regprog);
3309 vim_free(matchname);
3310
3311 matches = gap->ga_len - start_len;
3312 if (matches > 0)
3313 qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
3314 sizeof(char_u *), pstrcmp);
3315 return matches;
3316}
3317
3318 int
3319mch_expandpath(
3320 garray_T *gap,
3321 char_u *path,
3322 int flags) // EW_* flags
3323{
3324 return dos_expandpath(gap, path, 0, flags, FALSE);
3325}
3326#endif // MSWIN
3327
3328#if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \
3329 || defined(PROTO)
3330/*
3331 * Unix style wildcard expansion code.
3332 * It's here because it's used both for Unix and Mac.
3333 */
3334 static int
3335pstrcmp(const void *a, const void *b)
3336{
3337 return (pathcmp(*(char **)a, *(char **)b, -1));
3338}
3339
3340/*
3341 * Recursively expand one path component into all matching files and/or
3342 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
3343 * "path" has backslashes before chars that are not to be expanded, starting
3344 * at "path + wildoff".
3345 * Return the number of matches found.
3346 * NOTE: much of this is identical to dos_expandpath(), keep in sync!
3347 */
3348 int
3349unix_expandpath(
3350 garray_T *gap,
3351 char_u *path,
3352 int wildoff,
3353 int flags, // EW_* flags
3354 int didstar) // expanded "**" once already
3355{
3356 char_u *buf;
3357 char_u *path_end;
3358 char_u *p, *s, *e;
3359 int start_len = gap->ga_len;
3360 char_u *pat;
3361 regmatch_T regmatch;
3362 int starts_with_dot;
3363 int matches;
3364 int len;
3365 int starstar = FALSE;
3366 static int stardepth = 0; // depth for "**" expansion
3367
3368 DIR *dirp;
3369 struct dirent *dp;
3370
3371 // Expanding "**" may take a long time, check for CTRL-C.
3372 if (stardepth > 0)
3373 {
3374 ui_breakcheck();
3375 if (got_int)
3376 return 0;
3377 }
3378
3379 // make room for file name
3380 buf = alloc(STRLEN(path) + BASENAMELEN + 5);
3381 if (buf == NULL)
3382 return 0;
3383
3384 /*
3385 * Find the first part in the path name that contains a wildcard.
3386 * When EW_ICASE is set every letter is considered to be a wildcard.
3387 * Copy it into "buf", including the preceding characters.
3388 */
3389 p = buf;
3390 s = buf;
3391 e = NULL;
3392 path_end = path;
3393 while (*path_end != NUL)
3394 {
3395 // May ignore a wildcard that has a backslash before it; it will
3396 // be removed by rem_backslash() or file_pat_to_reg_pat() below.
3397 if (path_end >= path + wildoff && rem_backslash(path_end))
3398 *p++ = *path_end++;
3399 else if (*path_end == '/')
3400 {
3401 if (e != NULL)
3402 break;
3403 s = p + 1;
3404 }
3405 else if (path_end >= path + wildoff
3406 && (vim_strchr((char_u *)"*?[{~$", *path_end) != NULL
3407 || (!p_fic && (flags & EW_ICASE)
3408 && isalpha(PTR2CHAR(path_end)))))
3409 e = p;
3410 if (has_mbyte)
3411 {
3412 len = (*mb_ptr2len)(path_end);
3413 STRNCPY(p, path_end, len);
3414 p += len;
3415 path_end += len;
3416 }
3417 else
3418 *p++ = *path_end++;
3419 }
3420 e = p;
3421 *e = NUL;
3422
3423 // Now we have one wildcard component between "s" and "e".
3424 // Remove backslashes between "wildoff" and the start of the wildcard
3425 // component.
3426 for (p = buf + wildoff; p < s; ++p)
3427 if (rem_backslash(p))
3428 {
3429 STRMOVE(p, p + 1);
3430 --e;
3431 --s;
3432 }
3433
3434 // Check for "**" between "s" and "e".
3435 for (p = s; p < e; ++p)
3436 if (p[0] == '*' && p[1] == '*')
3437 starstar = TRUE;
3438
3439 // convert the file pattern to a regexp pattern
3440 starts_with_dot = *s == '.';
3441 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
3442 if (pat == NULL)
3443 {
3444 vim_free(buf);
3445 return 0;
3446 }
3447
3448 // compile the regexp into a program
3449 if (flags & EW_ICASE)
3450 regmatch.rm_ic = TRUE; // 'wildignorecase' set
3451 else
3452 regmatch.rm_ic = p_fic; // ignore case when 'fileignorecase' is set
3453 if (flags & (EW_NOERROR | EW_NOTWILD))
3454 ++emsg_silent;
3455 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
3456 if (flags & (EW_NOERROR | EW_NOTWILD))
3457 --emsg_silent;
3458 vim_free(pat);
3459
3460 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
3461 {
3462 vim_free(buf);
3463 return 0;
3464 }
3465
3466 // If "**" is by itself, this is the first time we encounter it and more
3467 // is following then find matches without any directory.
3468 if (!didstar && stardepth < 100 && starstar && e - s == 2
3469 && *path_end == '/')
3470 {
3471 STRCPY(s, path_end + 1);
3472 ++stardepth;
3473 (void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
3474 --stardepth;
3475 }
3476
3477 // open the directory for scanning
3478 *s = NUL;
3479 dirp = opendir(*buf == NUL ? "." : (char *)buf);
3480
3481 // Find all matching entries
3482 if (dirp != NULL)
3483 {
3484 for (;;)
3485 {
3486 dp = readdir(dirp);
3487 if (dp == NULL)
3488 break;
3489 if ((dp->d_name[0] != '.' || starts_with_dot
3490 || ((flags & EW_DODOT)
3491 && dp->d_name[1] != NUL
3492 && (dp->d_name[1] != '.' || dp->d_name[2] != NUL)))
3493 && ((regmatch.regprog != NULL && vim_regexec(&regmatch,
3494 (char_u *)dp->d_name, (colnr_T)0))
3495 || ((flags & EW_NOTWILD)
3496 && fnamencmp(path + (s - buf), dp->d_name, e - s) == 0)))
3497 {
3498 STRCPY(s, dp->d_name);
3499 len = STRLEN(buf);
3500
3501 if (starstar && stardepth < 100)
3502 {
3503 // For "**" in the pattern first go deeper in the tree to
3504 // find matches.
3505 STRCPY(buf + len, "/**");
3506 STRCPY(buf + len + 3, path_end);
3507 ++stardepth;
3508 (void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
3509 --stardepth;
3510 }
3511
3512 STRCPY(buf + len, path_end);
3513 if (mch_has_exp_wildcard(path_end)) // handle more wildcards
3514 {
3515 // need to expand another component of the path
3516 // remove backslashes for the remaining components only
3517 (void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
3518 }
3519 else
3520 {
3521 stat_T sb;
3522
3523 // no more wildcards, check if there is a match
3524 // remove backslashes for the remaining components only
3525 if (*path_end != NUL)
3526 backslash_halve(buf + len + 1);
3527 // add existing file or symbolic link
3528 if ((flags & EW_ALLLINKS) ? mch_lstat((char *)buf, &sb) >= 0
3529 : mch_getperm(buf) >= 0)
3530 {
3531#ifdef MACOS_CONVERT
3532 size_t precomp_len = STRLEN(buf)+1;
3533 char_u *precomp_buf =
3534 mac_precompose_path(buf, precomp_len, &precomp_len);
3535
3536 if (precomp_buf)
3537 {
3538 mch_memmove(buf, precomp_buf, precomp_len);
3539 vim_free(precomp_buf);
3540 }
3541#endif
3542 addfile(gap, buf, flags);
3543 }
3544 }
3545 }
3546 }
3547
3548 closedir(dirp);
3549 }
3550
3551 vim_free(buf);
3552 vim_regfree(regmatch.regprog);
3553
3554 matches = gap->ga_len - start_len;
3555 if (matches > 0)
3556 qsort(((char_u **)gap->ga_data) + start_len, matches,
3557 sizeof(char_u *), pstrcmp);
3558 return matches;
3559}
3560#endif
3561
3562/*
3563 * Return TRUE if "p" contains what looks like an environment variable.
3564 * Allowing for escaping.
3565 */
3566 static int
3567has_env_var(char_u *p)
3568{
3569 for ( ; *p; MB_PTR_ADV(p))
3570 {
3571 if (*p == '\\' && p[1] != NUL)
3572 ++p;
3573 else if (vim_strchr((char_u *)
3574#if defined(MSWIN)
3575 "$%"
3576#else
3577 "$"
3578#endif
3579 , *p) != NULL)
3580 return TRUE;
3581 }
3582 return FALSE;
3583}
3584
3585#ifdef SPECIAL_WILDCHAR
3586/*
3587 * Return TRUE if "p" contains a special wildcard character, one that Vim
3588 * cannot expand, requires using a shell.
3589 */
3590 static int
3591has_special_wildchar(char_u *p)
3592{
3593 for ( ; *p; MB_PTR_ADV(p))
3594 {
3595 // Disallow line break characters.
3596 if (*p == '\r' || *p == '\n')
3597 break;
3598 // Allow for escaping.
3599 if (*p == '\\' && p[1] != NUL && p[1] != '\r' && p[1] != '\n')
3600 ++p;
3601 else if (vim_strchr((char_u *)SPECIAL_WILDCHAR, *p) != NULL)
3602 {
3603 // A { must be followed by a matching }.
3604 if (*p == '{' && vim_strchr(p, '}') == NULL)
3605 continue;
3606 // A quote and backtick must be followed by another one.
3607 if ((*p == '`' || *p == '\'') && vim_strchr(p, *p) == NULL)
3608 continue;
3609 return TRUE;
3610 }
3611 }
3612 return FALSE;
3613}
3614#endif
3615
3616/*
3617 * Generic wildcard expansion code.
3618 *
3619 * Characters in "pat" that should not be expanded must be preceded with a
3620 * backslash. E.g., "/path\ with\ spaces/my\*star*"
3621 *
3622 * Return FAIL when no single file was found. In this case "num_file" is not
3623 * set, and "file" may contain an error message.
3624 * Return OK when some files found. "num_file" is set to the number of
3625 * matches, "file" to the array of matches. Call FreeWild() later.
3626 */
3627 int
3628gen_expand_wildcards(
3629 int num_pat, // number of input patterns
3630 char_u **pat, // array of input patterns
3631 int *num_file, // resulting number of files
3632 char_u ***file, // array of resulting files
3633 int flags) // EW_* flags
3634{
3635 int i;
3636 garray_T ga;
3637 char_u *p;
3638 static int recursive = FALSE;
3639 int add_pat;
3640 int retval = OK;
3641#if defined(FEAT_SEARCHPATH)
3642 int did_expand_in_path = FALSE;
3643#endif
3644
3645 /*
3646 * expand_env() is called to expand things like "~user". If this fails,
3647 * it calls ExpandOne(), which brings us back here. In this case, always
3648 * call the machine specific expansion function, if possible. Otherwise,
3649 * return FAIL.
3650 */
3651 if (recursive)
3652#ifdef SPECIAL_WILDCHAR
3653 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
3654#else
3655 return FAIL;
3656#endif
3657
3658#ifdef SPECIAL_WILDCHAR
3659 /*
3660 * If there are any special wildcard characters which we cannot handle
3661 * here, call machine specific function for all the expansion. This
3662 * avoids starting the shell for each argument separately.
3663 * For `=expr` do use the internal function.
3664 */
3665 for (i = 0; i < num_pat; i++)
3666 {
3667 if (has_special_wildchar(pat[i])
3668# ifdef VIM_BACKTICK
3669 && !(vim_backtick(pat[i]) && pat[i][1] == '=')
3670# endif
3671 )
3672 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
3673 }
3674#endif
3675
3676 recursive = TRUE;
3677
3678 /*
3679 * The matching file names are stored in a growarray. Init it empty.
3680 */
3681 ga_init2(&ga, (int)sizeof(char_u *), 30);
3682
3683 for (i = 0; i < num_pat; ++i)
3684 {
3685 add_pat = -1;
3686 p = pat[i];
3687
3688#ifdef VIM_BACKTICK
3689 if (vim_backtick(p))
3690 {
3691 add_pat = expand_backtick(&ga, p, flags);
3692 if (add_pat == -1)
3693 retval = FAIL;
3694 }
3695 else
3696#endif
3697 {
3698 /*
3699 * First expand environment variables, "~/" and "~user/".
3700 */
3701 if ((has_env_var(p) && !(flags & EW_NOTENV)) || *p == '~')
3702 {
3703 p = expand_env_save_opt(p, TRUE);
3704 if (p == NULL)
3705 p = pat[i];
3706#ifdef UNIX
3707 /*
3708 * On Unix, if expand_env() can't expand an environment
3709 * variable, use the shell to do that. Discard previously
3710 * found file names and start all over again.
3711 */
3712 else if (has_env_var(p) || *p == '~')
3713 {
3714 vim_free(p);
3715 ga_clear_strings(&ga);
3716 i = mch_expand_wildcards(num_pat, pat, num_file, file,
3717 flags|EW_KEEPDOLLAR);
3718 recursive = FALSE;
3719 return i;
3720 }
3721#endif
3722 }
3723
3724 /*
3725 * If there are wildcards: Expand file names and add each match to
3726 * the list. If there is no match, and EW_NOTFOUND is given, add
3727 * the pattern.
3728 * If there are no wildcards: Add the file name if it exists or
3729 * when EW_NOTFOUND is given.
3730 */
3731 if (mch_has_exp_wildcard(p))
3732 {
3733#if defined(FEAT_SEARCHPATH)
3734 if ((flags & EW_PATH)
3735 && !mch_isFullName(p)
3736 && !(p[0] == '.'
3737 && (vim_ispathsep(p[1])
3738 || (p[1] == '.' && vim_ispathsep(p[2]))))
3739 )
3740 {
3741 // :find completion where 'path' is used.
3742 // Recursiveness is OK here.
3743 recursive = FALSE;
3744 add_pat = expand_in_path(&ga, p, flags);
3745 recursive = TRUE;
3746 did_expand_in_path = TRUE;
3747 }
3748 else
3749#endif
3750 add_pat = mch_expandpath(&ga, p, flags);
3751 }
3752 }
3753
3754 if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
3755 {
3756 char_u *t = backslash_halve_save(p);
3757
3758 // When EW_NOTFOUND is used, always add files and dirs. Makes
3759 // "vim c:/" work.
3760 if (flags & EW_NOTFOUND)
3761 addfile(&ga, t, flags | EW_DIR | EW_FILE);
3762 else
3763 addfile(&ga, t, flags);
3764
3765 if (t != p)
3766 vim_free(t);
3767 }
3768
3769#if defined(FEAT_SEARCHPATH)
3770 if (did_expand_in_path && ga.ga_len > 0 && (flags & EW_PATH))
3771 uniquefy_paths(&ga, p);
3772#endif
3773 if (p != pat[i])
3774 vim_free(p);
3775 }
3776
3777 *num_file = ga.ga_len;
3778 *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data : (char_u **)"";
3779
3780 recursive = FALSE;
3781
3782 return ((flags & EW_EMPTYOK) || ga.ga_data != NULL) ? retval : FAIL;
3783}
3784
3785/*
3786 * Add a file to a file list. Accepted flags:
3787 * EW_DIR add directories
3788 * EW_FILE add files
3789 * EW_EXEC add executable files
3790 * EW_NOTFOUND add even when it doesn't exist
3791 * EW_ADDSLASH add slash after directory name
3792 * EW_ALLLINKS add symlink also when the referred file does not exist
3793 */
3794 void
3795addfile(
3796 garray_T *gap,
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003797 char_u *f, // filename
Bram Moolenaar26262f82019-09-04 20:59:15 +02003798 int flags)
3799{
3800 char_u *p;
3801 int isdir;
3802 stat_T sb;
3803
3804 // if the file/dir/link doesn't exist, may not add it
3805 if (!(flags & EW_NOTFOUND) && ((flags & EW_ALLLINKS)
3806 ? mch_lstat((char *)f, &sb) < 0 : mch_getperm(f) < 0))
3807 return;
3808
3809#ifdef FNAME_ILLEGAL
3810 // if the file/dir contains illegal characters, don't add it
3811 if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
3812 return;
3813#endif
3814
3815 isdir = mch_isdir(f);
3816 if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
3817 return;
3818
3819 // If the file isn't executable, may not add it. Do accept directories.
3820 // When invoked from expand_shellcmd() do not use $PATH.
3821 if (!isdir && (flags & EW_EXEC)
3822 && !mch_can_exe(f, NULL, !(flags & EW_SHELLCMD)))
3823 return;
3824
3825 // Make room for another item in the file list.
3826 if (ga_grow(gap, 1) == FAIL)
3827 return;
3828
3829 p = alloc(STRLEN(f) + 1 + isdir);
3830 if (p == NULL)
3831 return;
3832
3833 STRCPY(p, f);
3834#ifdef BACKSLASH_IN_FILENAME
3835 slash_adjust(p);
3836#endif
3837 /*
3838 * Append a slash or backslash after directory names if none is present.
3839 */
3840#ifndef DONT_ADD_PATHSEP_TO_DIR
3841 if (isdir && (flags & EW_ADDSLASH))
3842 add_pathsep(p);
3843#endif
3844 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
3845}
3846
3847/*
3848 * Free the list of files returned by expand_wildcards() or other expansion
3849 * functions.
3850 */
3851 void
3852FreeWild(int count, char_u **files)
3853{
3854 if (count <= 0 || files == NULL)
3855 return;
3856 while (count--)
3857 vim_free(files[count]);
3858 vim_free(files);
3859}
3860
3861/*
3862 * Compare path "p[]" to "q[]".
3863 * If "maxlen" >= 0 compare "p[maxlen]" to "q[maxlen]"
3864 * Return value like strcmp(p, q), but consider path separators.
3865 */
3866 int
3867pathcmp(const char *p, const char *q, int maxlen)
3868{
3869 int i, j;
3870 int c1, c2;
3871 const char *s = NULL;
3872
3873 for (i = 0, j = 0; maxlen < 0 || (i < maxlen && j < maxlen);)
3874 {
3875 c1 = PTR2CHAR((char_u *)p + i);
3876 c2 = PTR2CHAR((char_u *)q + j);
3877
3878 // End of "p": check if "q" also ends or just has a slash.
3879 if (c1 == NUL)
3880 {
3881 if (c2 == NUL) // full match
3882 return 0;
3883 s = q;
3884 i = j;
3885 break;
3886 }
3887
3888 // End of "q": check if "p" just has a slash.
3889 if (c2 == NUL)
3890 {
3891 s = p;
3892 break;
3893 }
3894
3895 if ((p_fic ? MB_TOUPPER(c1) != MB_TOUPPER(c2) : c1 != c2)
3896#ifdef BACKSLASH_IN_FILENAME
3897 // consider '/' and '\\' to be equal
3898 && !((c1 == '/' && c2 == '\\')
3899 || (c1 == '\\' && c2 == '/'))
3900#endif
3901 )
3902 {
3903 if (vim_ispathsep(c1))
3904 return -1;
3905 if (vim_ispathsep(c2))
3906 return 1;
3907 return p_fic ? MB_TOUPPER(c1) - MB_TOUPPER(c2)
3908 : c1 - c2; // no match
3909 }
3910
Bram Moolenaar1614a142019-10-06 22:00:13 +02003911 i += mb_ptr2len((char_u *)p + i);
3912 j += mb_ptr2len((char_u *)q + j);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003913 }
3914 if (s == NULL) // "i" or "j" ran into "maxlen"
3915 return 0;
3916
3917 c1 = PTR2CHAR((char_u *)s + i);
Bram Moolenaar1614a142019-10-06 22:00:13 +02003918 c2 = PTR2CHAR((char_u *)s + i + mb_ptr2len((char_u *)s + i));
Bram Moolenaar26262f82019-09-04 20:59:15 +02003919 // ignore a trailing slash, but not "//" or ":/"
3920 if (c2 == NUL
3921 && i > 0
3922 && !after_pathsep((char_u *)s, (char_u *)s + i)
3923#ifdef BACKSLASH_IN_FILENAME
3924 && (c1 == '/' || c1 == '\\')
3925#else
3926 && c1 == '/'
3927#endif
3928 )
3929 return 0; // match with trailing slash
3930 if (s == q)
3931 return -1; // no match
3932 return 1;
3933}
3934
3935/*
3936 * Return TRUE if "name" is a full (absolute) path name or URL.
3937 */
3938 int
3939vim_isAbsName(char_u *name)
3940{
3941 return (path_with_url(name) != 0 || mch_isFullName(name));
3942}
3943
3944/*
3945 * Get absolute file name into buffer "buf[len]".
3946 *
3947 * return FAIL for failure, OK otherwise
3948 */
3949 int
3950vim_FullName(
3951 char_u *fname,
3952 char_u *buf,
3953 int len,
3954 int force) // force expansion even when already absolute
3955{
3956 int retval = OK;
3957 int url;
3958
3959 *buf = NUL;
3960 if (fname == NULL)
3961 return FAIL;
3962
3963 url = path_with_url(fname);
3964 if (!url)
3965 retval = mch_FullName(fname, buf, len, force);
3966 if (url || retval == FAIL)
3967 {
3968 // something failed; use the file name (truncate when too long)
3969 vim_strncpy(buf, fname, len - 1);
3970 }
3971#if defined(MSWIN)
3972 slash_adjust(buf);
3973#endif
3974 return retval;
3975}