blob: 04026a0986acf32bca7d55fc73cf2abc16c53445 [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);
67 if (p != NULL)
68 {
69 vim_free(*bufp);
70 *fnamep = *bufp = p;
71 }
72 else
73 {
74 vim_free(wfname);
75 vim_free(newbuf);
76 return FAIL;
77 }
78 }
79 vim_free(wfname);
80 vim_free(newbuf);
Bram Moolenaarb005cd82019-09-04 15:54:55 +020081
Bram Moolenaar2ade7142019-11-04 20:36:50 +010082 *fnamelen = l == 0 ? l : (int)STRLEN(*bufp);
Bram Moolenaarb005cd82019-09-04 15:54:55 +020083 return OK;
84}
85
86/*
87 * Get the short path (8.3) for the filename in "fname". The converted
88 * path is returned in "bufp".
89 *
90 * Some of the directories specified in "fname" may not exist. This function
91 * will shorten the existing directories at the beginning of the path and then
92 * append the remaining non-existing path.
93 *
94 * fname - Pointer to the filename to shorten. On return, contains the
95 * pointer to the shortened pathname
96 * bufp - Pointer to an allocated buffer for the filename.
97 * fnamelen - Length of the filename pointed to by fname
98 *
99 * Returns OK on success (or nothing done) and FAIL on failure (out of memory).
100 */
101 static int
102shortpath_for_invalid_fname(
103 char_u **fname,
104 char_u **bufp,
105 int *fnamelen)
106{
107 char_u *short_fname, *save_fname, *pbuf_unused;
108 char_u *endp, *save_endp;
109 char_u ch;
110 int old_len, len;
111 int new_len, sfx_len;
112 int retval = OK;
113
Bram Moolenaar26262f82019-09-04 20:59:15 +0200114 // Make a copy
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200115 old_len = *fnamelen;
116 save_fname = vim_strnsave(*fname, old_len);
117 pbuf_unused = NULL;
118 short_fname = NULL;
119
Bram Moolenaar26262f82019-09-04 20:59:15 +0200120 endp = save_fname + old_len - 1; // Find the end of the copy
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200121 save_endp = endp;
122
123 /*
124 * Try shortening the supplied path till it succeeds by removing one
125 * directory at a time from the tail of the path.
126 */
127 len = 0;
128 for (;;)
129 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200130 // go back one path-separator
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200131 while (endp > save_fname && !after_pathsep(save_fname, endp + 1))
132 --endp;
133 if (endp <= save_fname)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200134 break; // processed the complete path
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200135
136 /*
137 * Replace the path separator with a NUL and try to shorten the
138 * resulting path.
139 */
140 ch = *endp;
141 *endp = 0;
142 short_fname = save_fname;
143 len = (int)STRLEN(short_fname) + 1;
144 if (get_short_pathname(&short_fname, &pbuf_unused, &len) == FAIL)
145 {
146 retval = FAIL;
147 goto theend;
148 }
Bram Moolenaar26262f82019-09-04 20:59:15 +0200149 *endp = ch; // preserve the string
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200150
151 if (len > 0)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200152 break; // successfully shortened the path
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200153
Bram Moolenaar26262f82019-09-04 20:59:15 +0200154 // failed to shorten the path. Skip the path separator
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200155 --endp;
156 }
157
158 if (len > 0)
159 {
160 /*
161 * Succeeded in shortening the path. Now concatenate the shortened
162 * path with the remaining path at the tail.
163 */
164
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100165 // Compute the length of the new path.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200166 sfx_len = (int)(save_endp - endp) + 1;
167 new_len = len + sfx_len;
168
169 *fnamelen = new_len;
170 vim_free(*bufp);
171 if (new_len > old_len)
172 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200173 // There is not enough space in the currently allocated string,
174 // copy it to a buffer big enough.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200175 *fname = *bufp = vim_strnsave(short_fname, new_len);
176 if (*fname == NULL)
177 {
178 retval = FAIL;
179 goto theend;
180 }
181 }
182 else
183 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200184 // Transfer short_fname to the main buffer (it's big enough),
185 // unless get_short_pathname() did its work in-place.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200186 *fname = *bufp = save_fname;
187 if (short_fname != save_fname)
188 vim_strncpy(save_fname, short_fname, len);
189 save_fname = NULL;
190 }
191
Bram Moolenaar26262f82019-09-04 20:59:15 +0200192 // concat the not-shortened part of the path
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200193 vim_strncpy(*fname + len, endp, sfx_len);
194 (*fname)[new_len] = NUL;
195 }
196
197theend:
198 vim_free(pbuf_unused);
199 vim_free(save_fname);
200
201 return retval;
202}
203
204/*
205 * Get a pathname for a partial path.
206 * Returns OK for success, FAIL for failure.
207 */
208 static int
209shortpath_for_partial(
210 char_u **fnamep,
211 char_u **bufp,
212 int *fnamelen)
213{
214 int sepcount, len, tflen;
215 char_u *p;
216 char_u *pbuf, *tfname;
217 int hasTilde;
218
Bram Moolenaar26262f82019-09-04 20:59:15 +0200219 // Count up the path separators from the RHS.. so we know which part
220 // of the path to return.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200221 sepcount = 0;
222 for (p = *fnamep; p < *fnamep + *fnamelen; MB_PTR_ADV(p))
223 if (vim_ispathsep(*p))
224 ++sepcount;
225
Bram Moolenaar26262f82019-09-04 20:59:15 +0200226 // Need full path first (use expand_env() to remove a "~/")
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200227 hasTilde = (**fnamep == '~');
228 if (hasTilde)
229 pbuf = tfname = expand_env_save(*fnamep);
230 else
231 pbuf = tfname = FullName_save(*fnamep, FALSE);
232
233 len = tflen = (int)STRLEN(tfname);
234
235 if (get_short_pathname(&tfname, &pbuf, &len) == FAIL)
236 return FAIL;
237
238 if (len == 0)
239 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200240 // Don't have a valid filename, so shorten the rest of the
241 // path if we can. This CAN give us invalid 8.3 filenames, but
242 // there's not a lot of point in guessing what it might be.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200243 len = tflen;
244 if (shortpath_for_invalid_fname(&tfname, &pbuf, &len) == FAIL)
245 return FAIL;
246 }
247
Bram Moolenaar26262f82019-09-04 20:59:15 +0200248 // Count the paths backward to find the beginning of the desired string.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200249 for (p = tfname + len - 1; p >= tfname; --p)
250 {
251 if (has_mbyte)
252 p -= mb_head_off(tfname, p);
253 if (vim_ispathsep(*p))
254 {
255 if (sepcount == 0 || (hasTilde && sepcount == 1))
256 break;
257 else
258 sepcount --;
259 }
260 }
261 if (hasTilde)
262 {
263 --p;
264 if (p >= tfname)
265 *p = '~';
266 else
267 return FAIL;
268 }
269 else
270 ++p;
271
Bram Moolenaar26262f82019-09-04 20:59:15 +0200272 // Copy in the string - p indexes into tfname - allocated at pbuf
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200273 vim_free(*bufp);
274 *fnamelen = (int)STRLEN(p);
275 *bufp = pbuf;
276 *fnamep = p;
277
278 return OK;
279}
280#endif // MSWIN
281
282/*
283 * Adjust a filename, according to a string of modifiers.
284 * *fnamep must be NUL terminated when called. When returning, the length is
285 * determined by *fnamelen.
286 * Returns VALID_ flags or -1 for failure.
287 * When there is an error, *fnamep is set to NULL.
288 */
289 int
290modify_fname(
291 char_u *src, // string with modifiers
292 int tilde_file, // "~" is a file name, not $HOME
293 int *usedlen, // characters after src that are used
294 char_u **fnamep, // file name so far
295 char_u **bufp, // buffer for allocated file name or NULL
296 int *fnamelen) // length of fnamep
297{
298 int valid = 0;
299 char_u *tail;
300 char_u *s, *p, *pbuf;
301 char_u dirname[MAXPATHL];
302 int c;
303 int has_fullname = 0;
304#ifdef MSWIN
305 char_u *fname_start = *fnamep;
306 int has_shortname = 0;
307#endif
308
309repeat:
Bram Moolenaar26262f82019-09-04 20:59:15 +0200310 // ":p" - full path/file_name
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200311 if (src[*usedlen] == ':' && src[*usedlen + 1] == 'p')
312 {
313 has_fullname = 1;
314
315 valid |= VALID_PATH;
316 *usedlen += 2;
317
Bram Moolenaar26262f82019-09-04 20:59:15 +0200318 // Expand "~/path" for all systems and "~user/path" for Unix and VMS
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200319 if ((*fnamep)[0] == '~'
320#if !defined(UNIX) && !(defined(VMS) && defined(USER_HOME))
321 && ((*fnamep)[1] == '/'
322# ifdef BACKSLASH_IN_FILENAME
323 || (*fnamep)[1] == '\\'
324# endif
325 || (*fnamep)[1] == NUL)
326#endif
327 && !(tilde_file && (*fnamep)[1] == NUL)
328 )
329 {
330 *fnamep = expand_env_save(*fnamep);
Bram Moolenaar26262f82019-09-04 20:59:15 +0200331 vim_free(*bufp); // free any allocated file name
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200332 *bufp = *fnamep;
333 if (*fnamep == NULL)
334 return -1;
335 }
336
Bram Moolenaar26262f82019-09-04 20:59:15 +0200337 // When "/." or "/.." is used: force expansion to get rid of it.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200338 for (p = *fnamep; *p != NUL; MB_PTR_ADV(p))
339 {
340 if (vim_ispathsep(*p)
341 && p[1] == '.'
342 && (p[2] == NUL
343 || vim_ispathsep(p[2])
344 || (p[2] == '.'
345 && (p[3] == NUL || vim_ispathsep(p[3])))))
346 break;
347 }
348
Bram Moolenaar26262f82019-09-04 20:59:15 +0200349 // FullName_save() is slow, don't use it when not needed.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200350 if (*p != NUL || !vim_isAbsName(*fnamep))
351 {
352 *fnamep = FullName_save(*fnamep, *p != NUL);
Bram Moolenaar26262f82019-09-04 20:59:15 +0200353 vim_free(*bufp); // free any allocated file name
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200354 *bufp = *fnamep;
355 if (*fnamep == NULL)
356 return -1;
357 }
358
359#ifdef MSWIN
360# if _WIN32_WINNT >= 0x0500
361 if (vim_strchr(*fnamep, '~') != NULL)
362 {
363 // Expand 8.3 filename to full path. Needed to make sure the same
364 // file does not have two different names.
365 // Note: problem does not occur if _WIN32_WINNT < 0x0500.
366 WCHAR *wfname = enc_to_utf16(*fnamep, NULL);
367 WCHAR buf[_MAX_PATH];
368
369 if (wfname != NULL)
370 {
371 if (GetLongPathNameW(wfname, buf, _MAX_PATH))
372 {
373 char_u *p = utf16_to_enc(buf, NULL);
374
375 if (p != NULL)
376 {
377 vim_free(*bufp); // free any allocated file name
378 *bufp = *fnamep = p;
379 }
380 }
381 vim_free(wfname);
382 }
383 }
384# endif
385#endif
Bram Moolenaar26262f82019-09-04 20:59:15 +0200386 // Append a path separator to a directory.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200387 if (mch_isdir(*fnamep))
388 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200389 // Make room for one or two extra characters.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200390 *fnamep = vim_strnsave(*fnamep, (int)STRLEN(*fnamep) + 2);
Bram Moolenaar26262f82019-09-04 20:59:15 +0200391 vim_free(*bufp); // free any allocated file name
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200392 *bufp = *fnamep;
393 if (*fnamep == NULL)
394 return -1;
395 add_pathsep(*fnamep);
396 }
397 }
398
Bram Moolenaar26262f82019-09-04 20:59:15 +0200399 // ":." - path relative to the current directory
400 // ":~" - path relative to the home directory
401 // ":8" - shortname path - postponed till after
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200402 while (src[*usedlen] == ':'
403 && ((c = src[*usedlen + 1]) == '.' || c == '~' || c == '8'))
404 {
405 *usedlen += 2;
406 if (c == '8')
407 {
408#ifdef MSWIN
Bram Moolenaar26262f82019-09-04 20:59:15 +0200409 has_shortname = 1; // Postpone this.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200410#endif
411 continue;
412 }
413 pbuf = NULL;
Bram Moolenaar26262f82019-09-04 20:59:15 +0200414 // Need full path first (use expand_env() to remove a "~/")
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200415 if (!has_fullname)
416 {
417 if (c == '.' && **fnamep == '~')
418 p = pbuf = expand_env_save(*fnamep);
419 else
420 p = pbuf = FullName_save(*fnamep, FALSE);
421 }
422 else
423 p = *fnamep;
424
425 has_fullname = 0;
426
427 if (p != NULL)
428 {
429 if (c == '.')
430 {
431 mch_dirname(dirname, MAXPATHL);
432 s = shorten_fname(p, dirname);
433 if (s != NULL)
434 {
435 *fnamep = s;
436 if (pbuf != NULL)
437 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200438 vim_free(*bufp); // free any allocated file name
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200439 *bufp = pbuf;
440 pbuf = NULL;
441 }
442 }
443 }
444 else
445 {
446 home_replace(NULL, p, dirname, MAXPATHL, TRUE);
Bram Moolenaar26262f82019-09-04 20:59:15 +0200447 // Only replace it when it starts with '~'
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200448 if (*dirname == '~')
449 {
450 s = vim_strsave(dirname);
451 if (s != NULL)
452 {
453 *fnamep = s;
454 vim_free(*bufp);
455 *bufp = s;
456 }
457 }
458 }
459 vim_free(pbuf);
460 }
461 }
462
463 tail = gettail(*fnamep);
464 *fnamelen = (int)STRLEN(*fnamep);
465
Bram Moolenaar26262f82019-09-04 20:59:15 +0200466 // ":h" - head, remove "/file_name", can be repeated
467 // Don't remove the first "/" or "c:\"
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200468 while (src[*usedlen] == ':' && src[*usedlen + 1] == 'h')
469 {
470 valid |= VALID_HEAD;
471 *usedlen += 2;
472 s = get_past_head(*fnamep);
473 while (tail > s && after_pathsep(s, tail))
474 MB_PTR_BACK(*fnamep, tail);
475 *fnamelen = (int)(tail - *fnamep);
476#ifdef VMS
477 if (*fnamelen > 0)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200478 *fnamelen += 1; // the path separator is part of the path
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200479#endif
480 if (*fnamelen == 0)
481 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200482 // Result is empty. Turn it into "." to make ":cd %:h" work.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200483 p = vim_strsave((char_u *)".");
484 if (p == NULL)
485 return -1;
486 vim_free(*bufp);
487 *bufp = *fnamep = tail = p;
488 *fnamelen = 1;
489 }
490 else
491 {
492 while (tail > s && !after_pathsep(s, tail))
493 MB_PTR_BACK(*fnamep, tail);
494 }
495 }
496
Bram Moolenaar26262f82019-09-04 20:59:15 +0200497 // ":8" - shortname
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200498 if (src[*usedlen] == ':' && src[*usedlen + 1] == '8')
499 {
500 *usedlen += 2;
501#ifdef MSWIN
502 has_shortname = 1;
503#endif
504 }
505
506#ifdef MSWIN
507 /*
508 * Handle ":8" after we have done 'heads' and before we do 'tails'.
509 */
510 if (has_shortname)
511 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200512 // Copy the string if it is shortened by :h and when it wasn't copied
513 // yet, because we are going to change it in place. Avoids changing
514 // the buffer name for "%:8".
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200515 if (*fnamelen < (int)STRLEN(*fnamep) || *fnamep == fname_start)
516 {
517 p = vim_strnsave(*fnamep, *fnamelen);
518 if (p == NULL)
519 return -1;
520 vim_free(*bufp);
521 *bufp = *fnamep = p;
522 }
523
Bram Moolenaar26262f82019-09-04 20:59:15 +0200524 // Split into two implementations - makes it easier. First is where
525 // there isn't a full name already, second is where there is.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200526 if (!has_fullname && !vim_isAbsName(*fnamep))
527 {
528 if (shortpath_for_partial(fnamep, bufp, fnamelen) == FAIL)
529 return -1;
530 }
531 else
532 {
533 int l = *fnamelen;
534
Bram Moolenaar26262f82019-09-04 20:59:15 +0200535 // Simple case, already have the full-name.
536 // Nearly always shorter, so try first time.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200537 if (get_short_pathname(fnamep, bufp, &l) == FAIL)
538 return -1;
539
540 if (l == 0)
541 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200542 // Couldn't find the filename, search the paths.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200543 l = *fnamelen;
544 if (shortpath_for_invalid_fname(fnamep, bufp, &l) == FAIL)
545 return -1;
546 }
547 *fnamelen = l;
548 }
549 }
550#endif // MSWIN
551
Bram Moolenaar26262f82019-09-04 20:59:15 +0200552 // ":t" - tail, just the basename
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200553 if (src[*usedlen] == ':' && src[*usedlen + 1] == 't')
554 {
555 *usedlen += 2;
556 *fnamelen -= (int)(tail - *fnamep);
557 *fnamep = tail;
558 }
559
Bram Moolenaar26262f82019-09-04 20:59:15 +0200560 // ":e" - extension, can be repeated
561 // ":r" - root, without extension, can be repeated
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200562 while (src[*usedlen] == ':'
563 && (src[*usedlen + 1] == 'e' || src[*usedlen + 1] == 'r'))
564 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200565 // find a '.' in the tail:
566 // - for second :e: before the current fname
567 // - otherwise: The last '.'
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200568 if (src[*usedlen + 1] == 'e' && *fnamep > tail)
569 s = *fnamep - 2;
570 else
571 s = *fnamep + *fnamelen - 1;
572 for ( ; s > tail; --s)
573 if (s[0] == '.')
574 break;
Bram Moolenaar26262f82019-09-04 20:59:15 +0200575 if (src[*usedlen + 1] == 'e') // :e
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200576 {
577 if (s > tail)
578 {
579 *fnamelen += (int)(*fnamep - (s + 1));
580 *fnamep = s + 1;
581#ifdef VMS
Bram Moolenaar26262f82019-09-04 20:59:15 +0200582 // cut version from the extension
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200583 s = *fnamep + *fnamelen - 1;
584 for ( ; s > *fnamep; --s)
585 if (s[0] == ';')
586 break;
587 if (s > *fnamep)
588 *fnamelen = s - *fnamep;
589#endif
590 }
591 else if (*fnamep <= tail)
592 *fnamelen = 0;
593 }
Bram Moolenaar26262f82019-09-04 20:59:15 +0200594 else // :r
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200595 {
Bram Moolenaarb1892952019-10-08 23:26:50 +0200596 char_u *limit = *fnamep;
597
598 if (limit < tail)
599 limit = tail;
600 if (s > limit) // remove one extension
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200601 *fnamelen = (int)(s - *fnamep);
602 }
603 *usedlen += 2;
604 }
605
Bram Moolenaar26262f82019-09-04 20:59:15 +0200606 // ":s?pat?foo?" - substitute
607 // ":gs?pat?foo?" - global substitute
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200608 if (src[*usedlen] == ':'
609 && (src[*usedlen + 1] == 's'
610 || (src[*usedlen + 1] == 'g' && src[*usedlen + 2] == 's')))
611 {
612 char_u *str;
613 char_u *pat;
614 char_u *sub;
615 int sep;
616 char_u *flags;
617 int didit = FALSE;
618
619 flags = (char_u *)"";
620 s = src + *usedlen + 2;
621 if (src[*usedlen + 1] == 'g')
622 {
623 flags = (char_u *)"g";
624 ++s;
625 }
626
627 sep = *s++;
628 if (sep)
629 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200630 // find end of pattern
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200631 p = vim_strchr(s, sep);
632 if (p != NULL)
633 {
634 pat = vim_strnsave(s, (int)(p - s));
635 if (pat != NULL)
636 {
637 s = p + 1;
Bram Moolenaar26262f82019-09-04 20:59:15 +0200638 // find end of substitution
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200639 p = vim_strchr(s, sep);
640 if (p != NULL)
641 {
642 sub = vim_strnsave(s, (int)(p - s));
643 str = vim_strnsave(*fnamep, *fnamelen);
644 if (sub != NULL && str != NULL)
645 {
646 *usedlen = (int)(p + 1 - src);
647 s = do_string_sub(str, pat, sub, NULL, flags);
648 if (s != NULL)
649 {
650 *fnamep = s;
651 *fnamelen = (int)STRLEN(s);
652 vim_free(*bufp);
653 *bufp = s;
654 didit = TRUE;
655 }
656 }
657 vim_free(sub);
658 vim_free(str);
659 }
660 vim_free(pat);
661 }
662 }
Bram Moolenaar26262f82019-09-04 20:59:15 +0200663 // after using ":s", repeat all the modifiers
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200664 if (didit)
665 goto repeat;
666 }
667 }
668
669 if (src[*usedlen] == ':' && src[*usedlen + 1] == 'S')
670 {
Bram Moolenaar26262f82019-09-04 20:59:15 +0200671 // vim_strsave_shellescape() needs a NUL terminated string.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200672 c = (*fnamep)[*fnamelen];
673 if (c != NUL)
674 (*fnamep)[*fnamelen] = NUL;
675 p = vim_strsave_shellescape(*fnamep, FALSE, FALSE);
676 if (c != NUL)
677 (*fnamep)[*fnamelen] = c;
678 if (p == NULL)
679 return -1;
680 vim_free(*bufp);
681 *bufp = *fnamep = p;
682 *fnamelen = (int)STRLEN(p);
683 *usedlen += 2;
684 }
685
686 return valid;
687}
688
689#if defined(FEAT_EVAL) || defined(PROTO)
690
691/*
692 * "chdir(dir)" function
693 */
694 void
695f_chdir(typval_T *argvars, typval_T *rettv)
696{
697 char_u *cwd;
698 cdscope_T scope = CDSCOPE_GLOBAL;
699
700 rettv->v_type = VAR_STRING;
701 rettv->vval.v_string = NULL;
702
703 if (argvars[0].v_type != VAR_STRING)
704 return;
705
706 // Return the current directory
707 cwd = alloc(MAXPATHL);
708 if (cwd != NULL)
709 {
710 if (mch_dirname(cwd, MAXPATHL) != FAIL)
711 {
712#ifdef BACKSLASH_IN_FILENAME
713 slash_adjust(cwd);
714#endif
715 rettv->vval.v_string = vim_strsave(cwd);
716 }
717 vim_free(cwd);
718 }
719
720 if (curwin->w_localdir != NULL)
721 scope = CDSCOPE_WINDOW;
722 else if (curtab->tp_localdir != NULL)
723 scope = CDSCOPE_TABPAGE;
724
725 if (!changedir_func(argvars[0].vval.v_string, TRUE, scope))
726 // Directory change failed
727 VIM_CLEAR(rettv->vval.v_string);
728}
729
730/*
731 * "delete()" function
732 */
733 void
734f_delete(typval_T *argvars, typval_T *rettv)
735{
736 char_u nbuf[NUMBUFLEN];
737 char_u *name;
738 char_u *flags;
739
740 rettv->vval.v_number = -1;
741 if (check_restricted() || check_secure())
742 return;
743
744 name = tv_get_string(&argvars[0]);
745 if (name == NULL || *name == NUL)
746 {
747 emsg(_(e_invarg));
748 return;
749 }
750
751 if (argvars[1].v_type != VAR_UNKNOWN)
752 flags = tv_get_string_buf(&argvars[1], nbuf);
753 else
754 flags = (char_u *)"";
755
756 if (*flags == NUL)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200757 // delete a file
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200758 rettv->vval.v_number = mch_remove(name) == 0 ? 0 : -1;
759 else if (STRCMP(flags, "d") == 0)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200760 // delete an empty directory
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200761 rettv->vval.v_number = mch_rmdir(name) == 0 ? 0 : -1;
762 else if (STRCMP(flags, "rf") == 0)
Bram Moolenaar26262f82019-09-04 20:59:15 +0200763 // delete a directory recursively
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200764 rettv->vval.v_number = delete_recursive(name);
765 else
766 semsg(_(e_invexpr2), flags);
767}
768
769/*
770 * "executable()" function
771 */
772 void
773f_executable(typval_T *argvars, typval_T *rettv)
774{
775 char_u *name = tv_get_string(&argvars[0]);
776
Bram Moolenaar26262f82019-09-04 20:59:15 +0200777 // Check in $PATH and also check directly if there is a directory name.
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200778 rettv->vval.v_number = mch_can_exe(name, NULL, TRUE);
779}
780
781/*
782 * "exepath()" function
783 */
784 void
785f_exepath(typval_T *argvars, typval_T *rettv)
786{
787 char_u *p = NULL;
788
789 (void)mch_can_exe(tv_get_string(&argvars[0]), &p, TRUE);
790 rettv->v_type = VAR_STRING;
791 rettv->vval.v_string = p;
792}
793
794/*
795 * "filereadable()" function
796 */
797 void
798f_filereadable(typval_T *argvars, typval_T *rettv)
799{
800 int fd;
801 char_u *p;
802 int n;
803
804#ifndef O_NONBLOCK
805# define O_NONBLOCK 0
806#endif
807 p = tv_get_string(&argvars[0]);
808 if (*p && !mch_isdir(p) && (fd = mch_open((char *)p,
809 O_RDONLY | O_NONBLOCK, 0)) >= 0)
810 {
811 n = TRUE;
812 close(fd);
813 }
814 else
815 n = FALSE;
816
817 rettv->vval.v_number = n;
818}
819
820/*
821 * Return 0 for not writable, 1 for writable file, 2 for a dir which we have
822 * rights to write into.
823 */
824 void
825f_filewritable(typval_T *argvars, typval_T *rettv)
826{
827 rettv->vval.v_number = filewritable(tv_get_string(&argvars[0]));
828}
829
Bram Moolenaar840d16f2019-09-10 21:27:18 +0200830 static void
Bram Moolenaarb005cd82019-09-04 15:54:55 +0200831findfilendir(
832 typval_T *argvars UNUSED,
833 typval_T *rettv,
834 int find_what UNUSED)
835{
836#ifdef FEAT_SEARCHPATH
837 char_u *fname;
838 char_u *fresult = NULL;
839 char_u *path = *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path;
840 char_u *p;
841 char_u pathbuf[NUMBUFLEN];
842 int count = 1;
843 int first = TRUE;
844 int error = FALSE;
845#endif
846
847 rettv->vval.v_string = NULL;
848 rettv->v_type = VAR_STRING;
849
850#ifdef FEAT_SEARCHPATH
851 fname = tv_get_string(&argvars[0]);
852
853 if (argvars[1].v_type != VAR_UNKNOWN)
854 {
855 p = tv_get_string_buf_chk(&argvars[1], pathbuf);
856 if (p == NULL)
857 error = TRUE;
858 else
859 {
860 if (*p != NUL)
861 path = p;
862
863 if (argvars[2].v_type != VAR_UNKNOWN)
864 count = (int)tv_get_number_chk(&argvars[2], &error);
865 }
866 }
867
868 if (count < 0 && rettv_list_alloc(rettv) == FAIL)
869 error = TRUE;
870
871 if (*fname != NUL && !error)
872 {
873 do
874 {
875 if (rettv->v_type == VAR_STRING || rettv->v_type == VAR_LIST)
876 vim_free(fresult);
877 fresult = find_file_in_path_option(first ? fname : NULL,
878 first ? (int)STRLEN(fname) : 0,
879 0, first, path,
880 find_what,
881 curbuf->b_ffname,
882 find_what == FINDFILE_DIR
883 ? (char_u *)"" : curbuf->b_p_sua);
884 first = FALSE;
885
886 if (fresult != NULL && rettv->v_type == VAR_LIST)
887 list_append_string(rettv->vval.v_list, fresult, -1);
888
889 } while ((rettv->v_type == VAR_LIST || --count > 0) && fresult != NULL);
890 }
891
892 if (rettv->v_type == VAR_STRING)
893 rettv->vval.v_string = fresult;
894#endif
895}
896
897/*
898 * "finddir({fname}[, {path}[, {count}]])" function
899 */
900 void
901f_finddir(typval_T *argvars, typval_T *rettv)
902{
903 findfilendir(argvars, rettv, FINDFILE_DIR);
904}
905
906/*
907 * "findfile({fname}[, {path}[, {count}]])" function
908 */
909 void
910f_findfile(typval_T *argvars, typval_T *rettv)
911{
912 findfilendir(argvars, rettv, FINDFILE_FILE);
913}
914
915/*
916 * "fnamemodify({fname}, {mods})" function
917 */
918 void
919f_fnamemodify(typval_T *argvars, typval_T *rettv)
920{
921 char_u *fname;
922 char_u *mods;
923 int usedlen = 0;
924 int len;
925 char_u *fbuf = NULL;
926 char_u buf[NUMBUFLEN];
927
928 fname = tv_get_string_chk(&argvars[0]);
929 mods = tv_get_string_buf_chk(&argvars[1], buf);
930 if (fname == NULL || mods == NULL)
931 fname = NULL;
932 else
933 {
934 len = (int)STRLEN(fname);
935 (void)modify_fname(mods, FALSE, &usedlen, &fname, &fbuf, &len);
936 }
937
938 rettv->v_type = VAR_STRING;
939 if (fname == NULL)
940 rettv->vval.v_string = NULL;
941 else
942 rettv->vval.v_string = vim_strnsave(fname, len);
943 vim_free(fbuf);
944}
945
946/*
947 * "getcwd()" function
948 *
949 * Return the current working directory of a window in a tab page.
950 * First optional argument 'winnr' is the window number or -1 and the second
951 * optional argument 'tabnr' is the tab page number.
952 *
953 * If no arguments are supplied, then return the directory of the current
954 * window.
955 * If only 'winnr' is specified and is not -1 or 0 then return the directory of
956 * the specified window.
957 * If 'winnr' is 0 then return the directory of the current window.
958 * If both 'winnr and 'tabnr' are specified and 'winnr' is -1 then return the
959 * directory of the specified tab page. Otherwise return the directory of the
960 * specified window in the specified tab page.
961 * If the window or the tab page doesn't exist then return NULL.
962 */
963 void
964f_getcwd(typval_T *argvars, typval_T *rettv)
965{
966 win_T *wp = NULL;
967 tabpage_T *tp = NULL;
968 char_u *cwd;
969 int global = FALSE;
970
971 rettv->v_type = VAR_STRING;
972 rettv->vval.v_string = NULL;
973
974 if (argvars[0].v_type == VAR_NUMBER
975 && argvars[0].vval.v_number == -1
976 && argvars[1].v_type == VAR_UNKNOWN)
977 global = TRUE;
978 else
979 wp = find_tabwin(&argvars[0], &argvars[1], &tp);
980
981 if (wp != NULL && wp->w_localdir != NULL)
982 rettv->vval.v_string = vim_strsave(wp->w_localdir);
983 else if (tp != NULL && tp->tp_localdir != NULL)
984 rettv->vval.v_string = vim_strsave(tp->tp_localdir);
985 else if (wp != NULL || tp != NULL || global)
986 {
987 if (globaldir != NULL)
988 rettv->vval.v_string = vim_strsave(globaldir);
989 else
990 {
991 cwd = alloc(MAXPATHL);
992 if (cwd != NULL)
993 {
994 if (mch_dirname(cwd, MAXPATHL) != FAIL)
995 rettv->vval.v_string = vim_strsave(cwd);
996 vim_free(cwd);
997 }
998 }
999 }
1000#ifdef BACKSLASH_IN_FILENAME
1001 if (rettv->vval.v_string != NULL)
1002 slash_adjust(rettv->vval.v_string);
1003#endif
1004}
1005
1006/*
1007 * "getfperm({fname})" function
1008 */
1009 void
1010f_getfperm(typval_T *argvars, typval_T *rettv)
1011{
1012 char_u *fname;
1013 stat_T st;
1014 char_u *perm = NULL;
1015 char_u flags[] = "rwx";
1016 int i;
1017
1018 fname = tv_get_string(&argvars[0]);
1019
1020 rettv->v_type = VAR_STRING;
1021 if (mch_stat((char *)fname, &st) >= 0)
1022 {
1023 perm = vim_strsave((char_u *)"---------");
1024 if (perm != NULL)
1025 {
1026 for (i = 0; i < 9; i++)
1027 {
1028 if (st.st_mode & (1 << (8 - i)))
1029 perm[i] = flags[i % 3];
1030 }
1031 }
1032 }
1033 rettv->vval.v_string = perm;
1034}
1035
1036/*
1037 * "getfsize({fname})" function
1038 */
1039 void
1040f_getfsize(typval_T *argvars, typval_T *rettv)
1041{
1042 char_u *fname;
1043 stat_T st;
1044
1045 fname = tv_get_string(&argvars[0]);
1046
1047 rettv->v_type = VAR_NUMBER;
1048
1049 if (mch_stat((char *)fname, &st) >= 0)
1050 {
1051 if (mch_isdir(fname))
1052 rettv->vval.v_number = 0;
1053 else
1054 {
1055 rettv->vval.v_number = (varnumber_T)st.st_size;
1056
Bram Moolenaar26262f82019-09-04 20:59:15 +02001057 // non-perfect check for overflow
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001058 if ((off_T)rettv->vval.v_number != (off_T)st.st_size)
1059 rettv->vval.v_number = -2;
1060 }
1061 }
1062 else
1063 rettv->vval.v_number = -1;
1064}
1065
1066/*
1067 * "getftime({fname})" function
1068 */
1069 void
1070f_getftime(typval_T *argvars, typval_T *rettv)
1071{
1072 char_u *fname;
1073 stat_T st;
1074
1075 fname = tv_get_string(&argvars[0]);
1076
1077 if (mch_stat((char *)fname, &st) >= 0)
1078 rettv->vval.v_number = (varnumber_T)st.st_mtime;
1079 else
1080 rettv->vval.v_number = -1;
1081}
1082
1083/*
1084 * "getftype({fname})" function
1085 */
1086 void
1087f_getftype(typval_T *argvars, typval_T *rettv)
1088{
1089 char_u *fname;
1090 stat_T st;
1091 char_u *type = NULL;
1092 char *t;
1093
1094 fname = tv_get_string(&argvars[0]);
1095
1096 rettv->v_type = VAR_STRING;
1097 if (mch_lstat((char *)fname, &st) >= 0)
1098 {
1099 if (S_ISREG(st.st_mode))
1100 t = "file";
1101 else if (S_ISDIR(st.st_mode))
1102 t = "dir";
1103 else if (S_ISLNK(st.st_mode))
1104 t = "link";
1105 else if (S_ISBLK(st.st_mode))
1106 t = "bdev";
1107 else if (S_ISCHR(st.st_mode))
1108 t = "cdev";
1109 else if (S_ISFIFO(st.st_mode))
1110 t = "fifo";
1111 else if (S_ISSOCK(st.st_mode))
1112 t = "socket";
1113 else
1114 t = "other";
1115 type = vim_strsave((char_u *)t);
1116 }
1117 rettv->vval.v_string = type;
1118}
1119
1120/*
1121 * "glob()" function
1122 */
1123 void
1124f_glob(typval_T *argvars, typval_T *rettv)
1125{
1126 int options = WILD_SILENT|WILD_USE_NL;
1127 expand_T xpc;
1128 int error = FALSE;
1129
Bram Moolenaar26262f82019-09-04 20:59:15 +02001130 // When the optional second argument is non-zero, don't remove matches
1131 // for 'wildignore' and don't put matches for 'suffixes' at the end.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001132 rettv->v_type = VAR_STRING;
1133 if (argvars[1].v_type != VAR_UNKNOWN)
1134 {
1135 if (tv_get_number_chk(&argvars[1], &error))
1136 options |= WILD_KEEP_ALL;
1137 if (argvars[2].v_type != VAR_UNKNOWN)
1138 {
1139 if (tv_get_number_chk(&argvars[2], &error))
1140 rettv_list_set(rettv, NULL);
1141 if (argvars[3].v_type != VAR_UNKNOWN
1142 && tv_get_number_chk(&argvars[3], &error))
1143 options |= WILD_ALLLINKS;
1144 }
1145 }
1146 if (!error)
1147 {
1148 ExpandInit(&xpc);
1149 xpc.xp_context = EXPAND_FILES;
1150 if (p_wic)
1151 options += WILD_ICASE;
1152 if (rettv->v_type == VAR_STRING)
1153 rettv->vval.v_string = ExpandOne(&xpc, tv_get_string(&argvars[0]),
1154 NULL, options, WILD_ALL);
1155 else if (rettv_list_alloc(rettv) != FAIL)
1156 {
1157 int i;
1158
1159 ExpandOne(&xpc, tv_get_string(&argvars[0]),
1160 NULL, options, WILD_ALL_KEEP);
1161 for (i = 0; i < xpc.xp_numfiles; i++)
1162 list_append_string(rettv->vval.v_list, xpc.xp_files[i], -1);
1163
1164 ExpandCleanup(&xpc);
1165 }
1166 }
1167 else
1168 rettv->vval.v_string = NULL;
1169}
1170
1171/*
1172 * "glob2regpat()" function
1173 */
1174 void
1175f_glob2regpat(typval_T *argvars, typval_T *rettv)
1176{
1177 char_u *pat = tv_get_string_chk(&argvars[0]);
1178
1179 rettv->v_type = VAR_STRING;
1180 rettv->vval.v_string = (pat == NULL)
1181 ? NULL : file_pat_to_reg_pat(pat, NULL, NULL, FALSE);
1182}
1183
1184/*
1185 * "globpath()" function
1186 */
1187 void
1188f_globpath(typval_T *argvars, typval_T *rettv)
1189{
1190 int flags = WILD_IGNORE_COMPLETESLASH;
1191 char_u buf1[NUMBUFLEN];
1192 char_u *file = tv_get_string_buf_chk(&argvars[1], buf1);
1193 int error = FALSE;
1194 garray_T ga;
1195 int i;
1196
1197 // When the optional second argument is non-zero, don't remove matches
1198 // for 'wildignore' and don't put matches for 'suffixes' at the end.
1199 rettv->v_type = VAR_STRING;
1200 if (argvars[2].v_type != VAR_UNKNOWN)
1201 {
1202 if (tv_get_number_chk(&argvars[2], &error))
1203 flags |= WILD_KEEP_ALL;
1204 if (argvars[3].v_type != VAR_UNKNOWN)
1205 {
1206 if (tv_get_number_chk(&argvars[3], &error))
1207 rettv_list_set(rettv, NULL);
1208 if (argvars[4].v_type != VAR_UNKNOWN
1209 && tv_get_number_chk(&argvars[4], &error))
1210 flags |= WILD_ALLLINKS;
1211 }
1212 }
1213 if (file != NULL && !error)
1214 {
1215 ga_init2(&ga, (int)sizeof(char_u *), 10);
1216 globpath(tv_get_string(&argvars[0]), file, &ga, flags);
1217 if (rettv->v_type == VAR_STRING)
1218 rettv->vval.v_string = ga_concat_strings(&ga, "\n");
1219 else if (rettv_list_alloc(rettv) != FAIL)
1220 for (i = 0; i < ga.ga_len; ++i)
1221 list_append_string(rettv->vval.v_list,
1222 ((char_u **)(ga.ga_data))[i], -1);
1223 ga_clear_strings(&ga);
1224 }
1225 else
1226 rettv->vval.v_string = NULL;
1227}
1228
1229/*
1230 * "isdirectory()" function
1231 */
1232 void
1233f_isdirectory(typval_T *argvars, typval_T *rettv)
1234{
1235 rettv->vval.v_number = mch_isdir(tv_get_string(&argvars[0]));
1236}
1237
1238/*
1239 * Evaluate "expr" (= "context") for readdir().
1240 */
1241 static int
1242readdir_checkitem(void *context, char_u *name)
1243{
1244 typval_T *expr = (typval_T *)context;
1245 typval_T save_val;
1246 typval_T rettv;
1247 typval_T argv[2];
1248 int retval = 0;
1249 int error = FALSE;
1250
1251 if (expr->v_type == VAR_UNKNOWN)
1252 return 1;
1253
1254 prepare_vimvar(VV_VAL, &save_val);
1255 set_vim_var_string(VV_VAL, name, -1);
1256 argv[0].v_type = VAR_STRING;
1257 argv[0].vval.v_string = name;
1258
1259 if (eval_expr_typval(expr, argv, 1, &rettv) == FAIL)
1260 goto theend;
1261
1262 retval = tv_get_number_chk(&rettv, &error);
1263 if (error)
1264 retval = -1;
1265 clear_tv(&rettv);
1266
1267theend:
1268 set_vim_var_string(VV_VAL, NULL, 0);
1269 restore_vimvar(VV_VAL, &save_val);
1270 return retval;
1271}
1272
1273/*
1274 * Create the directory in which "dir" is located, and higher levels when
1275 * needed.
1276 * Return OK or FAIL.
1277 */
1278 static int
1279mkdir_recurse(char_u *dir, int prot)
1280{
1281 char_u *p;
1282 char_u *updir;
1283 int r = FAIL;
1284
Bram Moolenaar26262f82019-09-04 20:59:15 +02001285 // Get end of directory name in "dir".
1286 // We're done when it's "/" or "c:/".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001287 p = gettail_sep(dir);
1288 if (p <= get_past_head(dir))
1289 return OK;
1290
Bram Moolenaar26262f82019-09-04 20:59:15 +02001291 // If the directory exists we're done. Otherwise: create it.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001292 updir = vim_strnsave(dir, (int)(p - dir));
1293 if (updir == NULL)
1294 return FAIL;
1295 if (mch_isdir(updir))
1296 r = OK;
1297 else if (mkdir_recurse(updir, prot) == OK)
1298 r = vim_mkdir_emsg(updir, prot);
1299 vim_free(updir);
1300 return r;
1301}
1302
1303/*
1304 * "mkdir()" function
1305 */
1306 void
1307f_mkdir(typval_T *argvars, typval_T *rettv)
1308{
1309 char_u *dir;
1310 char_u buf[NUMBUFLEN];
1311 int prot = 0755;
1312
1313 rettv->vval.v_number = FAIL;
1314 if (check_restricted() || check_secure())
1315 return;
1316
1317 dir = tv_get_string_buf(&argvars[0], buf);
1318 if (*dir == NUL)
1319 return;
1320
1321 if (*gettail(dir) == NUL)
Bram Moolenaar26262f82019-09-04 20:59:15 +02001322 // remove trailing slashes
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001323 *gettail_sep(dir) = NUL;
1324
1325 if (argvars[1].v_type != VAR_UNKNOWN)
1326 {
1327 if (argvars[2].v_type != VAR_UNKNOWN)
1328 {
1329 prot = (int)tv_get_number_chk(&argvars[2], NULL);
1330 if (prot == -1)
1331 return;
1332 }
1333 if (STRCMP(tv_get_string(&argvars[1]), "p") == 0)
1334 {
1335 if (mch_isdir(dir))
1336 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001337 // With the "p" flag it's OK if the dir already exists.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001338 rettv->vval.v_number = OK;
1339 return;
1340 }
1341 mkdir_recurse(dir, prot);
1342 }
1343 }
1344 rettv->vval.v_number = vim_mkdir_emsg(dir, prot);
1345}
1346
1347/*
Bram Moolenaaraf7645d2019-09-05 22:33:28 +02001348 * "pathshorten()" function
1349 */
1350 void
1351f_pathshorten(typval_T *argvars, typval_T *rettv)
1352{
1353 char_u *p;
1354
1355 rettv->v_type = VAR_STRING;
1356 p = tv_get_string_chk(&argvars[0]);
1357 if (p == NULL)
1358 rettv->vval.v_string = NULL;
1359 else
1360 {
1361 p = vim_strsave(p);
1362 rettv->vval.v_string = p;
1363 if (p != NULL)
1364 shorten_dir(p);
1365 }
1366}
1367
1368/*
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001369 * "readdir()" function
1370 */
1371 void
1372f_readdir(typval_T *argvars, typval_T *rettv)
1373{
1374 typval_T *expr;
1375 int ret;
1376 char_u *path;
1377 char_u *p;
1378 garray_T ga;
1379 int i;
1380
1381 if (rettv_list_alloc(rettv) == FAIL)
1382 return;
1383 path = tv_get_string(&argvars[0]);
1384 expr = &argvars[1];
1385
1386 ret = readdir_core(&ga, path, (void *)expr, readdir_checkitem);
1387 if (ret == OK && rettv->vval.v_list != NULL && ga.ga_len > 0)
1388 {
1389 for (i = 0; i < ga.ga_len; i++)
1390 {
1391 p = ((char_u **)ga.ga_data)[i];
1392 list_append_string(rettv->vval.v_list, p, -1);
1393 }
1394 }
1395 ga_clear_strings(&ga);
1396}
1397
1398/*
1399 * "readfile()" function
1400 */
1401 void
1402f_readfile(typval_T *argvars, typval_T *rettv)
1403{
1404 int binary = FALSE;
1405 int blob = FALSE;
1406 int failed = FALSE;
1407 char_u *fname;
1408 FILE *fd;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001409 char_u buf[(IOSIZE/256)*256]; // rounded to avoid odd + 1
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001410 int io_size = sizeof(buf);
Bram Moolenaar26262f82019-09-04 20:59:15 +02001411 int readlen; // size of last fread()
1412 char_u *prev = NULL; // previously read bytes, if any
1413 long prevlen = 0; // length of data in prev
1414 long prevsize = 0; // size of prev buffer
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001415 long maxline = MAXLNUM;
1416 long cnt = 0;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001417 char_u *p; // position in buf
1418 char_u *start; // start of current line
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001419
1420 if (argvars[1].v_type != VAR_UNKNOWN)
1421 {
1422 if (STRCMP(tv_get_string(&argvars[1]), "b") == 0)
1423 binary = TRUE;
1424 if (STRCMP(tv_get_string(&argvars[1]), "B") == 0)
1425 blob = TRUE;
1426
1427 if (argvars[2].v_type != VAR_UNKNOWN)
1428 maxline = (long)tv_get_number(&argvars[2]);
1429 }
1430
1431 if (blob)
1432 {
1433 if (rettv_blob_alloc(rettv) == FAIL)
1434 return;
1435 }
1436 else
1437 {
1438 if (rettv_list_alloc(rettv) == FAIL)
1439 return;
1440 }
1441
Bram Moolenaar26262f82019-09-04 20:59:15 +02001442 // Always open the file in binary mode, library functions have a mind of
1443 // their own about CR-LF conversion.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001444 fname = tv_get_string(&argvars[0]);
1445 if (*fname == NUL || (fd = mch_fopen((char *)fname, READBIN)) == NULL)
1446 {
1447 semsg(_(e_notopen), *fname == NUL ? (char_u *)_("<empty>") : fname);
1448 return;
1449 }
1450
1451 if (blob)
1452 {
1453 if (read_blob(fd, rettv->vval.v_blob) == FAIL)
1454 {
1455 emsg("cannot read file");
1456 blob_free(rettv->vval.v_blob);
1457 }
1458 fclose(fd);
1459 return;
1460 }
1461
1462 while (cnt < maxline || maxline < 0)
1463 {
1464 readlen = (int)fread(buf, 1, io_size, fd);
1465
Bram Moolenaar26262f82019-09-04 20:59:15 +02001466 // This for loop processes what was read, but is also entered at end
1467 // of file so that either:
1468 // - an incomplete line gets written
1469 // - a "binary" file gets an empty line at the end if it ends in a
1470 // newline.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001471 for (p = buf, start = buf;
1472 p < buf + readlen || (readlen <= 0 && (prevlen > 0 || binary));
1473 ++p)
1474 {
1475 if (*p == '\n' || readlen <= 0)
1476 {
1477 listitem_T *li;
1478 char_u *s = NULL;
1479 long_u len = p - start;
1480
Bram Moolenaar26262f82019-09-04 20:59:15 +02001481 // Finished a line. Remove CRs before NL.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001482 if (readlen > 0 && !binary)
1483 {
1484 while (len > 0 && start[len - 1] == '\r')
1485 --len;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001486 // removal may cross back to the "prev" string
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001487 if (len == 0)
1488 while (prevlen > 0 && prev[prevlen - 1] == '\r')
1489 --prevlen;
1490 }
1491 if (prevlen == 0)
1492 s = vim_strnsave(start, (int)len);
1493 else
1494 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001495 // Change "prev" buffer to be the right size. This way
1496 // the bytes are only copied once, and very long lines are
1497 // allocated only once.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001498 if ((s = vim_realloc(prev, prevlen + len + 1)) != NULL)
1499 {
1500 mch_memmove(s + prevlen, start, len);
1501 s[prevlen + len] = NUL;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001502 prev = NULL; // the list will own the string
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001503 prevlen = prevsize = 0;
1504 }
1505 }
1506 if (s == NULL)
1507 {
1508 do_outofmem_msg((long_u) prevlen + len + 1);
1509 failed = TRUE;
1510 break;
1511 }
1512
1513 if ((li = listitem_alloc()) == NULL)
1514 {
1515 vim_free(s);
1516 failed = TRUE;
1517 break;
1518 }
1519 li->li_tv.v_type = VAR_STRING;
1520 li->li_tv.v_lock = 0;
1521 li->li_tv.vval.v_string = s;
1522 list_append(rettv->vval.v_list, li);
1523
Bram Moolenaar26262f82019-09-04 20:59:15 +02001524 start = p + 1; // step over newline
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001525 if ((++cnt >= maxline && maxline >= 0) || readlen <= 0)
1526 break;
1527 }
1528 else if (*p == NUL)
1529 *p = '\n';
Bram Moolenaar26262f82019-09-04 20:59:15 +02001530 // Check for utf8 "bom"; U+FEFF is encoded as EF BB BF. Do this
1531 // when finding the BF and check the previous two bytes.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001532 else if (*p == 0xbf && enc_utf8 && !binary)
1533 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001534 // Find the two bytes before the 0xbf. If p is at buf, or buf
1535 // + 1, these may be in the "prev" string.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001536 char_u back1 = p >= buf + 1 ? p[-1]
1537 : prevlen >= 1 ? prev[prevlen - 1] : NUL;
1538 char_u back2 = p >= buf + 2 ? p[-2]
1539 : p == buf + 1 && prevlen >= 1 ? prev[prevlen - 1]
1540 : prevlen >= 2 ? prev[prevlen - 2] : NUL;
1541
1542 if (back2 == 0xef && back1 == 0xbb)
1543 {
1544 char_u *dest = p - 2;
1545
Bram Moolenaar26262f82019-09-04 20:59:15 +02001546 // Usually a BOM is at the beginning of a file, and so at
1547 // the beginning of a line; then we can just step over it.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001548 if (start == dest)
1549 start = p + 1;
1550 else
1551 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001552 // have to shuffle buf to close gap
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001553 int adjust_prevlen = 0;
1554
1555 if (dest < buf)
1556 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001557 adjust_prevlen = (int)(buf - dest); // must be 1 or 2
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001558 dest = buf;
1559 }
1560 if (readlen > p - buf + 1)
1561 mch_memmove(dest, p + 1, readlen - (p - buf) - 1);
1562 readlen -= 3 - adjust_prevlen;
1563 prevlen -= adjust_prevlen;
1564 p = dest - 1;
1565 }
1566 }
1567 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02001568 } // for
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001569
1570 if (failed || (cnt >= maxline && maxline >= 0) || readlen <= 0)
1571 break;
1572 if (start < p)
1573 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001574 // There's part of a line in buf, store it in "prev".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001575 if (p - start + prevlen >= prevsize)
1576 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001577 // need bigger "prev" buffer
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001578 char_u *newprev;
1579
Bram Moolenaar26262f82019-09-04 20:59:15 +02001580 // A common use case is ordinary text files and "prev" gets a
1581 // fragment of a line, so the first allocation is made
1582 // small, to avoid repeatedly 'allocing' large and
1583 // 'reallocing' small.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001584 if (prevsize == 0)
1585 prevsize = (long)(p - start);
1586 else
1587 {
1588 long grow50pc = (prevsize * 3) / 2;
1589 long growmin = (long)((p - start) * 2 + prevlen);
1590 prevsize = grow50pc > growmin ? grow50pc : growmin;
1591 }
1592 newprev = vim_realloc(prev, prevsize);
1593 if (newprev == NULL)
1594 {
1595 do_outofmem_msg((long_u)prevsize);
1596 failed = TRUE;
1597 break;
1598 }
1599 prev = newprev;
1600 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02001601 // Add the line part to end of "prev".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001602 mch_memmove(prev + prevlen, start, p - start);
1603 prevlen += (long)(p - start);
1604 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02001605 } // while
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001606
Bram Moolenaar26262f82019-09-04 20:59:15 +02001607 // For a negative line count use only the lines at the end of the file,
1608 // free the rest.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001609 if (!failed && maxline < 0)
1610 while (cnt > -maxline)
1611 {
1612 listitem_remove(rettv->vval.v_list, rettv->vval.v_list->lv_first);
1613 --cnt;
1614 }
1615
1616 if (failed)
1617 {
1618 // an empty list is returned on error
1619 list_free(rettv->vval.v_list);
1620 rettv_list_alloc(rettv);
1621 }
1622
1623 vim_free(prev);
1624 fclose(fd);
1625}
1626
1627/*
1628 * "resolve()" function
1629 */
1630 void
1631f_resolve(typval_T *argvars, typval_T *rettv)
1632{
1633 char_u *p;
1634#ifdef HAVE_READLINK
1635 char_u *buf = NULL;
1636#endif
1637
1638 p = tv_get_string(&argvars[0]);
1639#ifdef FEAT_SHORTCUT
1640 {
1641 char_u *v = NULL;
1642
1643 v = mch_resolve_path(p, TRUE);
1644 if (v != NULL)
1645 rettv->vval.v_string = v;
1646 else
1647 rettv->vval.v_string = vim_strsave(p);
1648 }
1649#else
1650# ifdef HAVE_READLINK
1651 {
1652 char_u *cpy;
1653 int len;
1654 char_u *remain = NULL;
1655 char_u *q;
1656 int is_relative_to_current = FALSE;
1657 int has_trailing_pathsep = FALSE;
1658 int limit = 100;
1659
1660 p = vim_strsave(p);
Bram Moolenaar70188f52019-12-23 18:18:52 +01001661 if (p == NULL)
1662 goto fail;
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001663 if (p[0] == '.' && (vim_ispathsep(p[1])
1664 || (p[1] == '.' && (vim_ispathsep(p[2])))))
1665 is_relative_to_current = TRUE;
1666
1667 len = STRLEN(p);
1668 if (len > 0 && after_pathsep(p, p + len))
1669 {
1670 has_trailing_pathsep = TRUE;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001671 p[len - 1] = NUL; // the trailing slash breaks readlink()
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001672 }
1673
1674 q = getnextcomp(p);
1675 if (*q != NUL)
1676 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001677 // Separate the first path component in "p", and keep the
1678 // remainder (beginning with the path separator).
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001679 remain = vim_strsave(q - 1);
1680 q[-1] = NUL;
1681 }
1682
1683 buf = alloc(MAXPATHL + 1);
1684 if (buf == NULL)
Bram Moolenaar70188f52019-12-23 18:18:52 +01001685 {
1686 vim_free(p);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001687 goto fail;
Bram Moolenaar70188f52019-12-23 18:18:52 +01001688 }
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001689
1690 for (;;)
1691 {
1692 for (;;)
1693 {
1694 len = readlink((char *)p, (char *)buf, MAXPATHL);
1695 if (len <= 0)
1696 break;
1697 buf[len] = NUL;
1698
1699 if (limit-- == 0)
1700 {
1701 vim_free(p);
1702 vim_free(remain);
1703 emsg(_("E655: Too many symbolic links (cycle?)"));
1704 rettv->vval.v_string = NULL;
1705 goto fail;
1706 }
1707
Bram Moolenaar26262f82019-09-04 20:59:15 +02001708 // Ensure that the result will have a trailing path separator
1709 // if the argument has one.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001710 if (remain == NULL && has_trailing_pathsep)
1711 add_pathsep(buf);
1712
Bram Moolenaar26262f82019-09-04 20:59:15 +02001713 // Separate the first path component in the link value and
1714 // concatenate the remainders.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001715 q = getnextcomp(vim_ispathsep(*buf) ? buf + 1 : buf);
1716 if (*q != NUL)
1717 {
1718 if (remain == NULL)
1719 remain = vim_strsave(q - 1);
1720 else
1721 {
1722 cpy = concat_str(q - 1, remain);
1723 if (cpy != NULL)
1724 {
1725 vim_free(remain);
1726 remain = cpy;
1727 }
1728 }
1729 q[-1] = NUL;
1730 }
1731
1732 q = gettail(p);
1733 if (q > p && *q == NUL)
1734 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001735 // Ignore trailing path separator.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001736 q[-1] = NUL;
1737 q = gettail(p);
1738 }
1739 if (q > p && !mch_isFullName(buf))
1740 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001741 // symlink is relative to directory of argument
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001742 cpy = alloc(STRLEN(p) + STRLEN(buf) + 1);
1743 if (cpy != NULL)
1744 {
1745 STRCPY(cpy, p);
1746 STRCPY(gettail(cpy), buf);
1747 vim_free(p);
1748 p = cpy;
1749 }
1750 }
1751 else
1752 {
1753 vim_free(p);
1754 p = vim_strsave(buf);
1755 }
1756 }
1757
1758 if (remain == NULL)
1759 break;
1760
Bram Moolenaar26262f82019-09-04 20:59:15 +02001761 // Append the first path component of "remain" to "p".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001762 q = getnextcomp(remain + 1);
1763 len = q - remain - (*q != NUL);
1764 cpy = vim_strnsave(p, STRLEN(p) + len);
1765 if (cpy != NULL)
1766 {
1767 STRNCAT(cpy, remain, len);
1768 vim_free(p);
1769 p = cpy;
1770 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02001771 // Shorten "remain".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001772 if (*q != NUL)
1773 STRMOVE(remain, q - 1);
1774 else
1775 VIM_CLEAR(remain);
1776 }
1777
Bram Moolenaar26262f82019-09-04 20:59:15 +02001778 // If the result is a relative path name, make it explicitly relative to
1779 // the current directory if and only if the argument had this form.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001780 if (!vim_ispathsep(*p))
1781 {
1782 if (is_relative_to_current
1783 && *p != NUL
1784 && !(p[0] == '.'
1785 && (p[1] == NUL
1786 || vim_ispathsep(p[1])
1787 || (p[1] == '.'
1788 && (p[2] == NUL
1789 || vim_ispathsep(p[2]))))))
1790 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001791 // Prepend "./".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001792 cpy = concat_str((char_u *)"./", p);
1793 if (cpy != NULL)
1794 {
1795 vim_free(p);
1796 p = cpy;
1797 }
1798 }
1799 else if (!is_relative_to_current)
1800 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02001801 // Strip leading "./".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001802 q = p;
1803 while (q[0] == '.' && vim_ispathsep(q[1]))
1804 q += 2;
1805 if (q > p)
1806 STRMOVE(p, p + 2);
1807 }
1808 }
1809
Bram Moolenaar26262f82019-09-04 20:59:15 +02001810 // Ensure that the result will have no trailing path separator
1811 // if the argument had none. But keep "/" or "//".
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001812 if (!has_trailing_pathsep)
1813 {
1814 q = p + STRLEN(p);
1815 if (after_pathsep(p, q))
1816 *gettail_sep(p) = NUL;
1817 }
1818
1819 rettv->vval.v_string = p;
1820 }
1821# else
1822 rettv->vval.v_string = vim_strsave(p);
1823# endif
1824#endif
1825
1826 simplify_filename(rettv->vval.v_string);
1827
1828#ifdef HAVE_READLINK
1829fail:
1830 vim_free(buf);
1831#endif
1832 rettv->v_type = VAR_STRING;
1833}
1834
1835/*
1836 * "tempname()" function
1837 */
1838 void
1839f_tempname(typval_T *argvars UNUSED, typval_T *rettv)
1840{
1841 static int x = 'A';
1842
1843 rettv->v_type = VAR_STRING;
1844 rettv->vval.v_string = vim_tempname(x, FALSE);
1845
Bram Moolenaar26262f82019-09-04 20:59:15 +02001846 // Advance 'x' to use A-Z and 0-9, so that there are at least 34 different
1847 // names. Skip 'I' and 'O', they are used for shell redirection.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001848 do
1849 {
1850 if (x == 'Z')
1851 x = '0';
1852 else if (x == '9')
1853 x = 'A';
1854 else
1855 {
1856#ifdef EBCDIC
1857 if (x == 'I')
1858 x = 'J';
1859 else if (x == 'R')
1860 x = 'S';
1861 else
1862#endif
1863 ++x;
1864 }
1865 } while (x == 'I' || x == 'O');
1866}
1867
1868/*
1869 * "writefile()" function
1870 */
1871 void
1872f_writefile(typval_T *argvars, typval_T *rettv)
1873{
1874 int binary = FALSE;
1875 int append = FALSE;
1876#ifdef HAVE_FSYNC
1877 int do_fsync = p_fs;
1878#endif
1879 char_u *fname;
1880 FILE *fd;
1881 int ret = 0;
1882 listitem_T *li;
1883 list_T *list = NULL;
1884 blob_T *blob = NULL;
1885
1886 rettv->vval.v_number = -1;
1887 if (check_secure())
1888 return;
1889
1890 if (argvars[0].v_type == VAR_LIST)
1891 {
1892 list = argvars[0].vval.v_list;
1893 if (list == NULL)
1894 return;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001895 range_list_materialize(list);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001896 for (li = list->lv_first; li != NULL; li = li->li_next)
1897 if (tv_get_string_chk(&li->li_tv) == NULL)
1898 return;
1899 }
1900 else if (argvars[0].v_type == VAR_BLOB)
1901 {
1902 blob = argvars[0].vval.v_blob;
1903 if (blob == NULL)
1904 return;
1905 }
1906 else
1907 {
1908 semsg(_(e_invarg2), "writefile()");
1909 return;
1910 }
1911
1912 if (argvars[2].v_type != VAR_UNKNOWN)
1913 {
1914 char_u *arg2 = tv_get_string_chk(&argvars[2]);
1915
1916 if (arg2 == NULL)
1917 return;
1918 if (vim_strchr(arg2, 'b') != NULL)
1919 binary = TRUE;
1920 if (vim_strchr(arg2, 'a') != NULL)
1921 append = TRUE;
1922#ifdef HAVE_FSYNC
1923 if (vim_strchr(arg2, 's') != NULL)
1924 do_fsync = TRUE;
1925 else if (vim_strchr(arg2, 'S') != NULL)
1926 do_fsync = FALSE;
1927#endif
1928 }
1929
1930 fname = tv_get_string_chk(&argvars[1]);
1931 if (fname == NULL)
1932 return;
1933
Bram Moolenaar26262f82019-09-04 20:59:15 +02001934 // Always open the file in binary mode, library functions have a mind of
1935 // their own about CR-LF conversion.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001936 if (*fname == NUL || (fd = mch_fopen((char *)fname,
1937 append ? APPENDBIN : WRITEBIN)) == NULL)
1938 {
1939 semsg(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
1940 ret = -1;
1941 }
1942 else if (blob)
1943 {
1944 if (write_blob(fd, blob) == FAIL)
1945 ret = -1;
1946#ifdef HAVE_FSYNC
1947 else if (do_fsync)
1948 // Ignore the error, the user wouldn't know what to do about it.
1949 // May happen for a device.
1950 vim_ignored = vim_fsync(fileno(fd));
1951#endif
1952 fclose(fd);
1953 }
1954 else
1955 {
1956 if (write_list(fd, list, binary) == FAIL)
1957 ret = -1;
1958#ifdef HAVE_FSYNC
1959 else if (do_fsync)
Bram Moolenaar26262f82019-09-04 20:59:15 +02001960 // Ignore the error, the user wouldn't know what to do about it.
1961 // May happen for a device.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001962 vim_ignored = vim_fsync(fileno(fd));
1963#endif
1964 fclose(fd);
1965 }
1966
1967 rettv->vval.v_number = ret;
1968}
1969
1970#endif // FEAT_EVAL
1971
1972#if defined(FEAT_BROWSE) || defined(PROTO)
1973/*
1974 * Generic browse function. Calls gui_mch_browse() when possible.
1975 * Later this may pop-up a non-GUI file selector (external command?).
1976 */
1977 char_u *
1978do_browse(
Bram Moolenaar26262f82019-09-04 20:59:15 +02001979 int flags, // BROWSE_SAVE and BROWSE_DIR
1980 char_u *title, // title for the window
1981 char_u *dflt, // default file name (may include directory)
1982 char_u *ext, // extension added
1983 char_u *initdir, // initial directory, NULL for current dir or
1984 // when using path from "dflt"
1985 char_u *filter, // file name filter
1986 buf_T *buf) // buffer to read/write for
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001987{
1988 char_u *fname;
Bram Moolenaar26262f82019-09-04 20:59:15 +02001989 static char_u *last_dir = NULL; // last used directory
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001990 char_u *tofree = NULL;
1991 int save_browse = cmdmod.browse;
1992
Bram Moolenaar26262f82019-09-04 20:59:15 +02001993 // Must turn off browse to avoid that autocommands will get the
1994 // flag too!
Bram Moolenaarb005cd82019-09-04 15:54:55 +02001995 cmdmod.browse = FALSE;
1996
1997 if (title == NULL || *title == NUL)
1998 {
1999 if (flags & BROWSE_DIR)
2000 title = (char_u *)_("Select Directory dialog");
2001 else if (flags & BROWSE_SAVE)
2002 title = (char_u *)_("Save File dialog");
2003 else
2004 title = (char_u *)_("Open File dialog");
2005 }
2006
Bram Moolenaar26262f82019-09-04 20:59:15 +02002007 // When no directory specified, use default file name, default dir, buffer
2008 // dir, last dir or current dir
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002009 if ((initdir == NULL || *initdir == NUL) && dflt != NULL && *dflt != NUL)
2010 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002011 if (mch_isdir(dflt)) // default file name is a directory
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002012 {
2013 initdir = dflt;
2014 dflt = NULL;
2015 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02002016 else if (gettail(dflt) != dflt) // default file name includes a path
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002017 {
2018 tofree = vim_strsave(dflt);
2019 if (tofree != NULL)
2020 {
2021 initdir = tofree;
2022 *gettail(initdir) = NUL;
2023 dflt = gettail(dflt);
2024 }
2025 }
2026 }
2027
2028 if (initdir == NULL || *initdir == NUL)
2029 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002030 // When 'browsedir' is a directory, use it
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002031 if (STRCMP(p_bsdir, "last") != 0
2032 && STRCMP(p_bsdir, "buffer") != 0
2033 && STRCMP(p_bsdir, "current") != 0
2034 && mch_isdir(p_bsdir))
2035 initdir = p_bsdir;
Bram Moolenaar26262f82019-09-04 20:59:15 +02002036 // When saving or 'browsedir' is "buffer", use buffer fname
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002037 else if (((flags & BROWSE_SAVE) || *p_bsdir == 'b')
2038 && buf != NULL && buf->b_ffname != NULL)
2039 {
2040 if (dflt == NULL || *dflt == NUL)
2041 dflt = gettail(curbuf->b_ffname);
2042 tofree = vim_strsave(curbuf->b_ffname);
2043 if (tofree != NULL)
2044 {
2045 initdir = tofree;
2046 *gettail(initdir) = NUL;
2047 }
2048 }
Bram Moolenaar26262f82019-09-04 20:59:15 +02002049 // When 'browsedir' is "last", use dir from last browse
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002050 else if (*p_bsdir == 'l')
2051 initdir = last_dir;
Bram Moolenaar26262f82019-09-04 20:59:15 +02002052 // When 'browsedir is "current", use current directory. This is the
2053 // default already, leave initdir empty.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002054 }
2055
2056# ifdef FEAT_GUI
Bram Moolenaar26262f82019-09-04 20:59:15 +02002057 if (gui.in_use) // when this changes, also adjust f_has()!
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002058 {
2059 if (filter == NULL
2060# ifdef FEAT_EVAL
2061 && (filter = get_var_value((char_u *)"b:browsefilter")) == NULL
2062 && (filter = get_var_value((char_u *)"g:browsefilter")) == NULL
2063# endif
2064 )
2065 filter = BROWSE_FILTER_DEFAULT;
2066 if (flags & BROWSE_DIR)
2067 {
2068# if defined(FEAT_GUI_GTK) || defined(MSWIN)
Bram Moolenaar26262f82019-09-04 20:59:15 +02002069 // For systems that have a directory dialog.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002070 fname = gui_mch_browsedir(title, initdir);
2071# else
Bram Moolenaar26262f82019-09-04 20:59:15 +02002072 // Generic solution for selecting a directory: select a file and
2073 // remove the file name.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002074 fname = gui_mch_browse(0, title, dflt, ext, initdir, (char_u *)"");
2075# endif
2076# if !defined(FEAT_GUI_GTK)
Bram Moolenaar26262f82019-09-04 20:59:15 +02002077 // Win32 adds a dummy file name, others return an arbitrary file
2078 // name. GTK+ 2 returns only the directory,
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002079 if (fname != NULL && *fname != NUL && !mch_isdir(fname))
2080 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002081 // Remove the file name.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002082 char_u *tail = gettail_sep(fname);
2083
2084 if (tail == fname)
Bram Moolenaar26262f82019-09-04 20:59:15 +02002085 *tail++ = '.'; // use current dir
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002086 *tail = NUL;
2087 }
2088# endif
2089 }
2090 else
2091 fname = gui_mch_browse(flags & BROWSE_SAVE,
2092 title, dflt, ext, initdir, (char_u *)_(filter));
2093
Bram Moolenaar26262f82019-09-04 20:59:15 +02002094 // We hang around in the dialog for a while, the user might do some
2095 // things to our files. The Win32 dialog allows deleting or renaming
2096 // a file, check timestamps.
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002097 need_check_timestamps = TRUE;
2098 did_check_timestamps = FALSE;
2099 }
2100 else
2101# endif
2102 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002103 // TODO: non-GUI file selector here
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002104 emsg(_("E338: Sorry, no file browser in console mode"));
2105 fname = NULL;
2106 }
2107
Bram Moolenaar26262f82019-09-04 20:59:15 +02002108 // keep the directory for next time
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002109 if (fname != NULL)
2110 {
2111 vim_free(last_dir);
2112 last_dir = vim_strsave(fname);
2113 if (last_dir != NULL && !(flags & BROWSE_DIR))
2114 {
2115 *gettail(last_dir) = NUL;
2116 if (*last_dir == NUL)
2117 {
Bram Moolenaar26262f82019-09-04 20:59:15 +02002118 // filename only returned, must be in current dir
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002119 vim_free(last_dir);
2120 last_dir = alloc(MAXPATHL);
2121 if (last_dir != NULL)
2122 mch_dirname(last_dir, MAXPATHL);
2123 }
2124 }
2125 }
2126
2127 vim_free(tofree);
2128 cmdmod.browse = save_browse;
2129
2130 return fname;
2131}
2132#endif
2133
2134#if defined(FEAT_EVAL) || defined(PROTO)
2135
2136/*
2137 * "browse(save, title, initdir, default)" function
2138 */
2139 void
2140f_browse(typval_T *argvars UNUSED, typval_T *rettv)
2141{
2142# ifdef FEAT_BROWSE
2143 int save;
2144 char_u *title;
2145 char_u *initdir;
2146 char_u *defname;
2147 char_u buf[NUMBUFLEN];
2148 char_u buf2[NUMBUFLEN];
2149 int error = FALSE;
2150
2151 save = (int)tv_get_number_chk(&argvars[0], &error);
2152 title = tv_get_string_chk(&argvars[1]);
2153 initdir = tv_get_string_buf_chk(&argvars[2], buf);
2154 defname = tv_get_string_buf_chk(&argvars[3], buf2);
2155
2156 if (error || title == NULL || initdir == NULL || defname == NULL)
2157 rettv->vval.v_string = NULL;
2158 else
2159 rettv->vval.v_string =
2160 do_browse(save ? BROWSE_SAVE : 0,
2161 title, defname, NULL, initdir, NULL, curbuf);
2162# else
2163 rettv->vval.v_string = NULL;
2164# endif
2165 rettv->v_type = VAR_STRING;
2166}
2167
2168/*
2169 * "browsedir(title, initdir)" function
2170 */
2171 void
2172f_browsedir(typval_T *argvars UNUSED, typval_T *rettv)
2173{
2174# ifdef FEAT_BROWSE
2175 char_u *title;
2176 char_u *initdir;
2177 char_u buf[NUMBUFLEN];
2178
2179 title = tv_get_string_chk(&argvars[0]);
2180 initdir = tv_get_string_buf_chk(&argvars[1], buf);
2181
2182 if (title == NULL || initdir == NULL)
2183 rettv->vval.v_string = NULL;
2184 else
2185 rettv->vval.v_string = do_browse(BROWSE_DIR,
2186 title, NULL, NULL, initdir, NULL, curbuf);
2187# else
2188 rettv->vval.v_string = NULL;
2189# endif
2190 rettv->v_type = VAR_STRING;
2191}
2192
2193#endif // FEAT_EVAL
Bram Moolenaar26262f82019-09-04 20:59:15 +02002194
2195/*
2196 * Replace home directory by "~" in each space or comma separated file name in
2197 * 'src'.
2198 * If anything fails (except when out of space) dst equals src.
2199 */
2200 void
2201home_replace(
2202 buf_T *buf, // when not NULL, check for help files
2203 char_u *src, // input file name
2204 char_u *dst, // where to put the result
2205 int dstlen, // maximum length of the result
2206 int one) // if TRUE, only replace one file name, include
2207 // spaces and commas in the file name.
2208{
2209 size_t dirlen = 0, envlen = 0;
2210 size_t len;
2211 char_u *homedir_env, *homedir_env_orig;
2212 char_u *p;
2213
2214 if (src == NULL)
2215 {
2216 *dst = NUL;
2217 return;
2218 }
2219
2220 /*
2221 * If the file is a help file, remove the path completely.
2222 */
2223 if (buf != NULL && buf->b_help)
2224 {
2225 vim_snprintf((char *)dst, dstlen, "%s", gettail(src));
2226 return;
2227 }
2228
2229 /*
2230 * We check both the value of the $HOME environment variable and the
2231 * "real" home directory.
2232 */
2233 if (homedir != NULL)
2234 dirlen = STRLEN(homedir);
2235
2236#ifdef VMS
2237 homedir_env_orig = homedir_env = mch_getenv((char_u *)"SYS$LOGIN");
2238#else
2239 homedir_env_orig = homedir_env = mch_getenv((char_u *)"HOME");
2240#endif
2241#ifdef MSWIN
2242 if (homedir_env == NULL)
2243 homedir_env_orig = homedir_env = mch_getenv((char_u *)"USERPROFILE");
2244#endif
2245 // Empty is the same as not set.
2246 if (homedir_env != NULL && *homedir_env == NUL)
2247 homedir_env = NULL;
2248
2249 if (homedir_env != NULL && *homedir_env == '~')
2250 {
2251 int usedlen = 0;
2252 int flen;
2253 char_u *fbuf = NULL;
2254
2255 flen = (int)STRLEN(homedir_env);
2256 (void)modify_fname((char_u *)":p", FALSE, &usedlen,
2257 &homedir_env, &fbuf, &flen);
2258 flen = (int)STRLEN(homedir_env);
2259 if (flen > 0 && vim_ispathsep(homedir_env[flen - 1]))
2260 // Remove the trailing / that is added to a directory.
2261 homedir_env[flen - 1] = NUL;
2262 }
2263
2264 if (homedir_env != NULL)
2265 envlen = STRLEN(homedir_env);
2266
2267 if (!one)
2268 src = skipwhite(src);
2269 while (*src && dstlen > 0)
2270 {
2271 /*
2272 * Here we are at the beginning of a file name.
2273 * First, check to see if the beginning of the file name matches
2274 * $HOME or the "real" home directory. Check that there is a '/'
2275 * after the match (so that if e.g. the file is "/home/pieter/bla",
2276 * and the home directory is "/home/piet", the file does not end up
2277 * as "~er/bla" (which would seem to indicate the file "bla" in user
2278 * er's home directory)).
2279 */
2280 p = homedir;
2281 len = dirlen;
2282 for (;;)
2283 {
2284 if ( len
2285 && fnamencmp(src, p, len) == 0
2286 && (vim_ispathsep(src[len])
2287 || (!one && (src[len] == ',' || src[len] == ' '))
2288 || src[len] == NUL))
2289 {
2290 src += len;
2291 if (--dstlen > 0)
2292 *dst++ = '~';
2293
2294 /*
2295 * If it's just the home directory, add "/".
2296 */
2297 if (!vim_ispathsep(src[0]) && --dstlen > 0)
2298 *dst++ = '/';
2299 break;
2300 }
2301 if (p == homedir_env)
2302 break;
2303 p = homedir_env;
2304 len = envlen;
2305 }
2306
2307 // if (!one) skip to separator: space or comma
2308 while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0)
2309 *dst++ = *src++;
2310 // skip separator
2311 while ((*src == ' ' || *src == ',') && --dstlen > 0)
2312 *dst++ = *src++;
2313 }
2314 // if (dstlen == 0) out of space, what to do???
2315
2316 *dst = NUL;
2317
2318 if (homedir_env != homedir_env_orig)
2319 vim_free(homedir_env);
2320}
2321
2322/*
2323 * Like home_replace, store the replaced string in allocated memory.
2324 * When something fails, NULL is returned.
2325 */
2326 char_u *
2327home_replace_save(
2328 buf_T *buf, // when not NULL, check for help files
2329 char_u *src) // input file name
2330{
2331 char_u *dst;
2332 unsigned len;
2333
2334 len = 3; // space for "~/" and trailing NUL
2335 if (src != NULL) // just in case
2336 len += (unsigned)STRLEN(src);
2337 dst = alloc(len);
2338 if (dst != NULL)
2339 home_replace(buf, src, dst, len, TRUE);
2340 return dst;
2341}
2342
2343/*
2344 * Compare two file names and return:
2345 * FPC_SAME if they both exist and are the same file.
2346 * FPC_SAMEX if they both don't exist and have the same file name.
2347 * FPC_DIFF if they both exist and are different files.
2348 * FPC_NOTX if they both don't exist.
2349 * FPC_DIFFX if one of them doesn't exist.
2350 * For the first name environment variables are expanded if "expandenv" is
2351 * TRUE.
2352 */
2353 int
2354fullpathcmp(
2355 char_u *s1,
2356 char_u *s2,
2357 int checkname, // when both don't exist, check file names
2358 int expandenv)
2359{
2360#ifdef UNIX
2361 char_u exp1[MAXPATHL];
2362 char_u full1[MAXPATHL];
2363 char_u full2[MAXPATHL];
2364 stat_T st1, st2;
2365 int r1, r2;
2366
2367 if (expandenv)
2368 expand_env(s1, exp1, MAXPATHL);
2369 else
2370 vim_strncpy(exp1, s1, MAXPATHL - 1);
2371 r1 = mch_stat((char *)exp1, &st1);
2372 r2 = mch_stat((char *)s2, &st2);
2373 if (r1 != 0 && r2 != 0)
2374 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002375 // if mch_stat() doesn't work, may compare the names
Bram Moolenaar26262f82019-09-04 20:59:15 +02002376 if (checkname)
2377 {
2378 if (fnamecmp(exp1, s2) == 0)
2379 return FPC_SAMEX;
2380 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
2381 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
2382 if (r1 == OK && r2 == OK && fnamecmp(full1, full2) == 0)
2383 return FPC_SAMEX;
2384 }
2385 return FPC_NOTX;
2386 }
2387 if (r1 != 0 || r2 != 0)
2388 return FPC_DIFFX;
2389 if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
2390 return FPC_SAME;
2391 return FPC_DIFF;
2392#else
2393 char_u *exp1; // expanded s1
2394 char_u *full1; // full path of s1
2395 char_u *full2; // full path of s2
2396 int retval = FPC_DIFF;
2397 int r1, r2;
2398
2399 // allocate one buffer to store three paths (alloc()/free() is slow!)
2400 if ((exp1 = alloc(MAXPATHL * 3)) != NULL)
2401 {
2402 full1 = exp1 + MAXPATHL;
2403 full2 = full1 + MAXPATHL;
2404
2405 if (expandenv)
2406 expand_env(s1, exp1, MAXPATHL);
2407 else
2408 vim_strncpy(exp1, s1, MAXPATHL - 1);
2409 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
2410 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
2411
2412 // If vim_FullName() fails, the file probably doesn't exist.
2413 if (r1 != OK && r2 != OK)
2414 {
2415 if (checkname && fnamecmp(exp1, s2) == 0)
2416 retval = FPC_SAMEX;
2417 else
2418 retval = FPC_NOTX;
2419 }
2420 else if (r1 != OK || r2 != OK)
2421 retval = FPC_DIFFX;
2422 else if (fnamecmp(full1, full2))
2423 retval = FPC_DIFF;
2424 else
2425 retval = FPC_SAME;
2426 vim_free(exp1);
2427 }
2428 return retval;
2429#endif
2430}
2431
2432/*
2433 * Get the tail of a path: the file name.
2434 * When the path ends in a path separator the tail is the NUL after it.
2435 * Fail safe: never returns NULL.
2436 */
2437 char_u *
2438gettail(char_u *fname)
2439{
2440 char_u *p1, *p2;
2441
2442 if (fname == NULL)
2443 return (char_u *)"";
2444 for (p1 = p2 = get_past_head(fname); *p2; ) // find last part of path
2445 {
2446 if (vim_ispathsep_nocolon(*p2))
2447 p1 = p2 + 1;
2448 MB_PTR_ADV(p2);
2449 }
2450 return p1;
2451}
2452
2453/*
2454 * Get pointer to tail of "fname", including path separators. Putting a NUL
2455 * here leaves the directory name. Takes care of "c:/" and "//".
2456 * Always returns a valid pointer.
2457 */
2458 char_u *
2459gettail_sep(char_u *fname)
2460{
2461 char_u *p;
2462 char_u *t;
2463
2464 p = get_past_head(fname); // don't remove the '/' from "c:/file"
2465 t = gettail(fname);
2466 while (t > p && after_pathsep(fname, t))
2467 --t;
2468#ifdef VMS
2469 // path separator is part of the path
2470 ++t;
2471#endif
2472 return t;
2473}
2474
2475/*
2476 * get the next path component (just after the next path separator).
2477 */
2478 char_u *
2479getnextcomp(char_u *fname)
2480{
2481 while (*fname && !vim_ispathsep(*fname))
2482 MB_PTR_ADV(fname);
2483 if (*fname)
2484 ++fname;
2485 return fname;
2486}
2487
2488/*
2489 * Get a pointer to one character past the head of a path name.
2490 * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
2491 * If there is no head, path is returned.
2492 */
2493 char_u *
2494get_past_head(char_u *path)
2495{
2496 char_u *retval;
2497
2498#if defined(MSWIN)
2499 // may skip "c:"
2500 if (isalpha(path[0]) && path[1] == ':')
2501 retval = path + 2;
2502 else
2503 retval = path;
2504#else
2505# if defined(AMIGA)
2506 // may skip "label:"
2507 retval = vim_strchr(path, ':');
2508 if (retval == NULL)
2509 retval = path;
2510# else // Unix
2511 retval = path;
2512# endif
2513#endif
2514
2515 while (vim_ispathsep(*retval))
2516 ++retval;
2517
2518 return retval;
2519}
2520
2521/*
2522 * Return TRUE if 'c' is a path separator.
2523 * Note that for MS-Windows this includes the colon.
2524 */
2525 int
2526vim_ispathsep(int c)
2527{
2528#ifdef UNIX
2529 return (c == '/'); // UNIX has ':' inside file names
2530#else
2531# ifdef BACKSLASH_IN_FILENAME
2532 return (c == ':' || c == '/' || c == '\\');
2533# else
2534# ifdef VMS
2535 // server"user passwd"::device:[full.path.name]fname.extension;version"
2536 return (c == ':' || c == '[' || c == ']' || c == '/'
2537 || c == '<' || c == '>' || c == '"' );
2538# else
2539 return (c == ':' || c == '/');
2540# endif // VMS
2541# endif
2542#endif
2543}
2544
2545/*
2546 * Like vim_ispathsep(c), but exclude the colon for MS-Windows.
2547 */
2548 int
2549vim_ispathsep_nocolon(int c)
2550{
2551 return vim_ispathsep(c)
2552#ifdef BACKSLASH_IN_FILENAME
2553 && c != ':'
2554#endif
2555 ;
2556}
2557
2558/*
2559 * Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
2560 * It's done in-place.
2561 */
2562 void
2563shorten_dir(char_u *str)
2564{
2565 char_u *tail, *s, *d;
2566 int skip = FALSE;
2567
2568 tail = gettail(str);
2569 d = str;
2570 for (s = str; ; ++s)
2571 {
2572 if (s >= tail) // copy the whole tail
2573 {
2574 *d++ = *s;
2575 if (*s == NUL)
2576 break;
2577 }
2578 else if (vim_ispathsep(*s)) // copy '/' and next char
2579 {
2580 *d++ = *s;
2581 skip = FALSE;
2582 }
2583 else if (!skip)
2584 {
2585 *d++ = *s; // copy next char
2586 if (*s != '~' && *s != '.') // and leading "~" and "."
2587 skip = TRUE;
2588 if (has_mbyte)
2589 {
2590 int l = mb_ptr2len(s);
2591
2592 while (--l > 0)
2593 *d++ = *++s;
2594 }
2595 }
2596 }
2597}
2598
2599/*
2600 * Return TRUE if the directory of "fname" exists, FALSE otherwise.
2601 * Also returns TRUE if there is no directory name.
2602 * "fname" must be writable!.
2603 */
2604 int
2605dir_of_file_exists(char_u *fname)
2606{
2607 char_u *p;
2608 int c;
2609 int retval;
2610
2611 p = gettail_sep(fname);
2612 if (p == fname)
2613 return TRUE;
2614 c = *p;
2615 *p = NUL;
2616 retval = mch_isdir(fname);
2617 *p = c;
2618 return retval;
2619}
2620
2621/*
2622 * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally
2623 * and deal with 'fileignorecase'.
2624 */
2625 int
2626vim_fnamecmp(char_u *x, char_u *y)
2627{
2628#ifdef BACKSLASH_IN_FILENAME
2629 return vim_fnamencmp(x, y, MAXPATHL);
2630#else
2631 if (p_fic)
2632 return MB_STRICMP(x, y);
2633 return STRCMP(x, y);
2634#endif
2635}
2636
2637 int
2638vim_fnamencmp(char_u *x, char_u *y, size_t len)
2639{
2640#ifdef BACKSLASH_IN_FILENAME
2641 char_u *px = x;
2642 char_u *py = y;
2643 int cx = NUL;
2644 int cy = NUL;
2645
2646 while (len > 0)
2647 {
2648 cx = PTR2CHAR(px);
2649 cy = PTR2CHAR(py);
2650 if (cx == NUL || cy == NUL
2651 || ((p_fic ? MB_TOLOWER(cx) != MB_TOLOWER(cy) : cx != cy)
2652 && !(cx == '/' && cy == '\\')
2653 && !(cx == '\\' && cy == '/')))
2654 break;
Bram Moolenaar1614a142019-10-06 22:00:13 +02002655 len -= mb_ptr2len(px);
2656 px += mb_ptr2len(px);
2657 py += mb_ptr2len(py);
Bram Moolenaar26262f82019-09-04 20:59:15 +02002658 }
2659 if (len == 0)
2660 return 0;
2661 return (cx - cy);
2662#else
2663 if (p_fic)
2664 return MB_STRNICMP(x, y, len);
2665 return STRNCMP(x, y, len);
2666#endif
2667}
2668
2669/*
2670 * Concatenate file names fname1 and fname2 into allocated memory.
2671 * Only add a '/' or '\\' when 'sep' is TRUE and it is necessary.
2672 */
2673 char_u *
2674concat_fnames(char_u *fname1, char_u *fname2, int sep)
2675{
2676 char_u *dest;
2677
2678 dest = alloc(STRLEN(fname1) + STRLEN(fname2) + 3);
2679 if (dest != NULL)
2680 {
2681 STRCPY(dest, fname1);
2682 if (sep)
2683 add_pathsep(dest);
2684 STRCAT(dest, fname2);
2685 }
2686 return dest;
2687}
2688
2689/*
2690 * Add a path separator to a file name, unless it already ends in a path
2691 * separator.
2692 */
2693 void
2694add_pathsep(char_u *p)
2695{
2696 if (*p != NUL && !after_pathsep(p, p + STRLEN(p)))
2697 STRCAT(p, PATHSEPSTR);
2698}
2699
2700/*
2701 * FullName_save - Make an allocated copy of a full file name.
2702 * Returns NULL when out of memory.
2703 */
2704 char_u *
2705FullName_save(
2706 char_u *fname,
2707 int force) // force expansion, even when it already looks
2708 // like a full path name
2709{
2710 char_u *buf;
2711 char_u *new_fname = NULL;
2712
2713 if (fname == NULL)
2714 return NULL;
2715
2716 buf = alloc(MAXPATHL);
2717 if (buf != NULL)
2718 {
2719 if (vim_FullName(fname, buf, MAXPATHL, force) != FAIL)
2720 new_fname = vim_strsave(buf);
2721 else
2722 new_fname = vim_strsave(fname);
2723 vim_free(buf);
2724 }
2725 return new_fname;
2726}
2727
2728/*
2729 * return TRUE if "fname" exists.
2730 */
2731 int
2732vim_fexists(char_u *fname)
2733{
2734 stat_T st;
2735
2736 if (mch_stat((char *)fname, &st))
2737 return FALSE;
2738 return TRUE;
2739}
2740
2741/*
2742 * Invoke expand_wildcards() for one pattern.
2743 * Expand items like "%:h" before the expansion.
2744 * Returns OK or FAIL.
2745 */
2746 int
2747expand_wildcards_eval(
2748 char_u **pat, // pointer to input pattern
2749 int *num_file, // resulting number of files
2750 char_u ***file, // array of resulting files
2751 int flags) // EW_DIR, etc.
2752{
2753 int ret = FAIL;
2754 char_u *eval_pat = NULL;
2755 char_u *exp_pat = *pat;
2756 char *ignored_msg;
2757 int usedlen;
2758
2759 if (*exp_pat == '%' || *exp_pat == '#' || *exp_pat == '<')
2760 {
2761 ++emsg_off;
2762 eval_pat = eval_vars(exp_pat, exp_pat, &usedlen,
2763 NULL, &ignored_msg, NULL);
2764 --emsg_off;
2765 if (eval_pat != NULL)
2766 exp_pat = concat_str(eval_pat, exp_pat + usedlen);
2767 }
2768
2769 if (exp_pat != NULL)
2770 ret = expand_wildcards(1, &exp_pat, num_file, file, flags);
2771
2772 if (eval_pat != NULL)
2773 {
2774 vim_free(exp_pat);
2775 vim_free(eval_pat);
2776 }
2777
2778 return ret;
2779}
2780
2781/*
2782 * Expand wildcards. Calls gen_expand_wildcards() and removes files matching
2783 * 'wildignore'.
2784 * Returns OK or FAIL. When FAIL then "num_files" won't be set.
2785 */
2786 int
2787expand_wildcards(
2788 int num_pat, // number of input patterns
2789 char_u **pat, // array of input patterns
2790 int *num_files, // resulting number of files
2791 char_u ***files, // array of resulting files
2792 int flags) // EW_DIR, etc.
2793{
2794 int retval;
2795 int i, j;
2796 char_u *p;
2797 int non_suf_match; // number without matching suffix
2798
2799 retval = gen_expand_wildcards(num_pat, pat, num_files, files, flags);
2800
2801 // When keeping all matches, return here
2802 if ((flags & EW_KEEPALL) || retval == FAIL)
2803 return retval;
2804
2805#ifdef FEAT_WILDIGN
2806 /*
2807 * Remove names that match 'wildignore'.
2808 */
2809 if (*p_wig)
2810 {
2811 char_u *ffname;
2812
2813 // check all files in (*files)[]
2814 for (i = 0; i < *num_files; ++i)
2815 {
2816 ffname = FullName_save((*files)[i], FALSE);
2817 if (ffname == NULL) // out of memory
2818 break;
2819# ifdef VMS
2820 vms_remove_version(ffname);
2821# endif
2822 if (match_file_list(p_wig, (*files)[i], ffname))
2823 {
2824 // remove this matching file from the list
2825 vim_free((*files)[i]);
2826 for (j = i; j + 1 < *num_files; ++j)
2827 (*files)[j] = (*files)[j + 1];
2828 --*num_files;
2829 --i;
2830 }
2831 vim_free(ffname);
2832 }
2833
2834 // If the number of matches is now zero, we fail.
2835 if (*num_files == 0)
2836 {
2837 VIM_CLEAR(*files);
2838 return FAIL;
2839 }
2840 }
2841#endif
2842
2843 /*
2844 * Move the names where 'suffixes' match to the end.
2845 */
2846 if (*num_files > 1)
2847 {
2848 non_suf_match = 0;
2849 for (i = 0; i < *num_files; ++i)
2850 {
2851 if (!match_suffix((*files)[i]))
2852 {
2853 /*
2854 * Move the name without matching suffix to the front
2855 * of the list.
2856 */
2857 p = (*files)[i];
2858 for (j = i; j > non_suf_match; --j)
2859 (*files)[j] = (*files)[j - 1];
2860 (*files)[non_suf_match++] = p;
2861 }
2862 }
2863 }
2864
2865 return retval;
2866}
2867
2868/*
2869 * Return TRUE if "fname" matches with an entry in 'suffixes'.
2870 */
2871 int
2872match_suffix(char_u *fname)
2873{
2874 int fnamelen, setsuflen;
2875 char_u *setsuf;
2876#define MAXSUFLEN 30 // maximum length of a file suffix
2877 char_u suf_buf[MAXSUFLEN];
2878
2879 fnamelen = (int)STRLEN(fname);
2880 setsuflen = 0;
2881 for (setsuf = p_su; *setsuf; )
2882 {
2883 setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
2884 if (setsuflen == 0)
2885 {
2886 char_u *tail = gettail(fname);
2887
2888 // empty entry: match name without a '.'
2889 if (vim_strchr(tail, '.') == NULL)
2890 {
2891 setsuflen = 1;
2892 break;
2893 }
2894 }
2895 else
2896 {
2897 if (fnamelen >= setsuflen
2898 && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
2899 (size_t)setsuflen) == 0)
2900 break;
2901 setsuflen = 0;
2902 }
2903 }
2904 return (setsuflen != 0);
2905}
2906
2907#ifdef VIM_BACKTICK
2908
2909/*
2910 * Return TRUE if we can expand this backtick thing here.
2911 */
2912 static int
2913vim_backtick(char_u *p)
2914{
2915 return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
2916}
2917
2918/*
2919 * Expand an item in `backticks` by executing it as a command.
2920 * Currently only works when pat[] starts and ends with a `.
2921 * Returns number of file names found, -1 if an error is encountered.
2922 */
2923 static int
2924expand_backtick(
2925 garray_T *gap,
2926 char_u *pat,
2927 int flags) // EW_* flags
2928{
2929 char_u *p;
2930 char_u *cmd;
2931 char_u *buffer;
2932 int cnt = 0;
2933 int i;
2934
2935 // Create the command: lop off the backticks.
2936 cmd = vim_strnsave(pat + 1, (int)STRLEN(pat) - 2);
2937 if (cmd == NULL)
2938 return -1;
2939
2940#ifdef FEAT_EVAL
2941 if (*cmd == '=') // `={expr}`: Expand expression
2942 buffer = eval_to_string(cmd + 1, &p, TRUE);
2943 else
2944#endif
2945 buffer = get_cmd_output(cmd, NULL,
2946 (flags & EW_SILENT) ? SHELL_SILENT : 0, NULL);
2947 vim_free(cmd);
2948 if (buffer == NULL)
2949 return -1;
2950
2951 cmd = buffer;
2952 while (*cmd != NUL)
2953 {
2954 cmd = skipwhite(cmd); // skip over white space
2955 p = cmd;
2956 while (*p != NUL && *p != '\r' && *p != '\n') // skip over entry
2957 ++p;
2958 // add an entry if it is not empty
2959 if (p > cmd)
2960 {
2961 i = *p;
2962 *p = NUL;
2963 addfile(gap, cmd, flags);
2964 *p = i;
2965 ++cnt;
2966 }
2967 cmd = p;
2968 while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
2969 ++cmd;
2970 }
2971
2972 vim_free(buffer);
2973 return cnt;
2974}
2975#endif // VIM_BACKTICK
2976
2977#if defined(MSWIN)
2978/*
2979 * File name expansion code for MS-DOS, Win16 and Win32. It's here because
2980 * it's shared between these systems.
2981 */
2982
2983/*
2984 * comparison function for qsort in dos_expandpath()
2985 */
2986 static int
2987pstrcmp(const void *a, const void *b)
2988{
2989 return (pathcmp(*(char **)a, *(char **)b, -1));
2990}
2991
2992/*
2993 * Recursively expand one path component into all matching files and/or
2994 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
2995 * Return the number of matches found.
2996 * "path" has backslashes before chars that are not to be expanded, starting
2997 * at "path[wildoff]".
2998 * Return the number of matches found.
2999 * NOTE: much of this is identical to unix_expandpath(), keep in sync!
3000 */
3001 static int
3002dos_expandpath(
3003 garray_T *gap,
3004 char_u *path,
3005 int wildoff,
3006 int flags, // EW_* flags
3007 int didstar) // expanded "**" once already
3008{
3009 char_u *buf;
3010 char_u *path_end;
3011 char_u *p, *s, *e;
3012 int start_len = gap->ga_len;
3013 char_u *pat;
3014 regmatch_T regmatch;
3015 int starts_with_dot;
3016 int matches;
3017 int len;
3018 int starstar = FALSE;
3019 static int stardepth = 0; // depth for "**" expansion
3020 HANDLE hFind = INVALID_HANDLE_VALUE;
3021 WIN32_FIND_DATAW wfb;
3022 WCHAR *wn = NULL; // UCS-2 name, NULL when not used.
3023 char_u *matchname;
3024 int ok;
3025
3026 // Expanding "**" may take a long time, check for CTRL-C.
3027 if (stardepth > 0)
3028 {
3029 ui_breakcheck();
3030 if (got_int)
3031 return 0;
3032 }
3033
3034 // Make room for file name. When doing encoding conversion the actual
3035 // length may be quite a bit longer, thus use the maximum possible length.
3036 buf = alloc(MAXPATHL);
3037 if (buf == NULL)
3038 return 0;
3039
3040 /*
3041 * Find the first part in the path name that contains a wildcard or a ~1.
3042 * Copy it into buf, including the preceding characters.
3043 */
3044 p = buf;
3045 s = buf;
3046 e = NULL;
3047 path_end = path;
3048 while (*path_end != NUL)
3049 {
3050 // May ignore a wildcard that has a backslash before it; it will
3051 // be removed by rem_backslash() or file_pat_to_reg_pat() below.
3052 if (path_end >= path + wildoff && rem_backslash(path_end))
3053 *p++ = *path_end++;
3054 else if (*path_end == '\\' || *path_end == ':' || *path_end == '/')
3055 {
3056 if (e != NULL)
3057 break;
3058 s = p + 1;
3059 }
3060 else if (path_end >= path + wildoff
3061 && vim_strchr((char_u *)"*?[~", *path_end) != NULL)
3062 e = p;
3063 if (has_mbyte)
3064 {
3065 len = (*mb_ptr2len)(path_end);
3066 STRNCPY(p, path_end, len);
3067 p += len;
3068 path_end += len;
3069 }
3070 else
3071 *p++ = *path_end++;
3072 }
3073 e = p;
3074 *e = NUL;
3075
3076 // now we have one wildcard component between s and e
3077 // Remove backslashes between "wildoff" and the start of the wildcard
3078 // component.
3079 for (p = buf + wildoff; p < s; ++p)
3080 if (rem_backslash(p))
3081 {
3082 STRMOVE(p, p + 1);
3083 --e;
3084 --s;
3085 }
3086
3087 // Check for "**" between "s" and "e".
3088 for (p = s; p < e; ++p)
3089 if (p[0] == '*' && p[1] == '*')
3090 starstar = TRUE;
3091
3092 starts_with_dot = *s == '.';
3093 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
3094 if (pat == NULL)
3095 {
3096 vim_free(buf);
3097 return 0;
3098 }
3099
3100 // compile the regexp into a program
3101 if (flags & (EW_NOERROR | EW_NOTWILD))
3102 ++emsg_silent;
3103 regmatch.rm_ic = TRUE; // Always ignore case
3104 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
3105 if (flags & (EW_NOERROR | EW_NOTWILD))
3106 --emsg_silent;
3107 vim_free(pat);
3108
3109 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
3110 {
3111 vim_free(buf);
3112 return 0;
3113 }
3114
3115 // remember the pattern or file name being looked for
3116 matchname = vim_strsave(s);
3117
3118 // If "**" is by itself, this is the first time we encounter it and more
3119 // is following then find matches without any directory.
3120 if (!didstar && stardepth < 100 && starstar && e - s == 2
3121 && *path_end == '/')
3122 {
3123 STRCPY(s, path_end + 1);
3124 ++stardepth;
3125 (void)dos_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
3126 --stardepth;
3127 }
3128
3129 // Scan all files in the directory with "dir/ *.*"
3130 STRCPY(s, "*.*");
3131 wn = enc_to_utf16(buf, NULL);
3132 if (wn != NULL)
3133 hFind = FindFirstFileW(wn, &wfb);
3134 ok = (hFind != INVALID_HANDLE_VALUE);
3135
3136 while (ok)
3137 {
3138 p = utf16_to_enc(wfb.cFileName, NULL); // p is allocated here
3139 if (p == NULL)
3140 break; // out of memory
3141
3142 // Ignore entries starting with a dot, unless when asked for. Accept
3143 // all entries found with "matchname".
3144 if ((p[0] != '.' || starts_with_dot
3145 || ((flags & EW_DODOT)
3146 && p[1] != NUL && (p[1] != '.' || p[2] != NUL)))
3147 && (matchname == NULL
3148 || (regmatch.regprog != NULL
3149 && vim_regexec(&regmatch, p, (colnr_T)0))
3150 || ((flags & EW_NOTWILD)
3151 && fnamencmp(path + (s - buf), p, e - s) == 0)))
3152 {
3153 STRCPY(s, p);
3154 len = (int)STRLEN(buf);
3155
3156 if (starstar && stardepth < 100)
3157 {
3158 // For "**" in the pattern first go deeper in the tree to
3159 // find matches.
3160 STRCPY(buf + len, "/**");
3161 STRCPY(buf + len + 3, path_end);
3162 ++stardepth;
3163 (void)dos_expandpath(gap, buf, len + 1, flags, TRUE);
3164 --stardepth;
3165 }
3166
3167 STRCPY(buf + len, path_end);
3168 if (mch_has_exp_wildcard(path_end))
3169 {
3170 // need to expand another component of the path
3171 // remove backslashes for the remaining components only
3172 (void)dos_expandpath(gap, buf, len + 1, flags, FALSE);
3173 }
3174 else
3175 {
3176 // no more wildcards, check if there is a match
3177 // remove backslashes for the remaining components only
3178 if (*path_end != 0)
3179 backslash_halve(buf + len + 1);
3180 if (mch_getperm(buf) >= 0) // add existing file
3181 addfile(gap, buf, flags);
3182 }
3183 }
3184
3185 vim_free(p);
3186 ok = FindNextFileW(hFind, &wfb);
3187
3188 // If no more matches and no match was used, try expanding the name
3189 // itself. Finds the long name of a short filename.
3190 if (!ok && matchname != NULL && gap->ga_len == start_len)
3191 {
3192 STRCPY(s, matchname);
3193 FindClose(hFind);
3194 vim_free(wn);
3195 wn = enc_to_utf16(buf, NULL);
3196 if (wn != NULL)
3197 hFind = FindFirstFileW(wn, &wfb);
3198 else
3199 hFind = INVALID_HANDLE_VALUE;
3200 ok = (hFind != INVALID_HANDLE_VALUE);
3201 VIM_CLEAR(matchname);
3202 }
3203 }
3204
3205 FindClose(hFind);
3206 vim_free(wn);
3207 vim_free(buf);
3208 vim_regfree(regmatch.regprog);
3209 vim_free(matchname);
3210
3211 matches = gap->ga_len - start_len;
3212 if (matches > 0)
3213 qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
3214 sizeof(char_u *), pstrcmp);
3215 return matches;
3216}
3217
3218 int
3219mch_expandpath(
3220 garray_T *gap,
3221 char_u *path,
3222 int flags) // EW_* flags
3223{
3224 return dos_expandpath(gap, path, 0, flags, FALSE);
3225}
3226#endif // MSWIN
3227
3228#if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \
3229 || defined(PROTO)
3230/*
3231 * Unix style wildcard expansion code.
3232 * It's here because it's used both for Unix and Mac.
3233 */
3234 static int
3235pstrcmp(const void *a, const void *b)
3236{
3237 return (pathcmp(*(char **)a, *(char **)b, -1));
3238}
3239
3240/*
3241 * Recursively expand one path component into all matching files and/or
3242 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
3243 * "path" has backslashes before chars that are not to be expanded, starting
3244 * at "path + wildoff".
3245 * Return the number of matches found.
3246 * NOTE: much of this is identical to dos_expandpath(), keep in sync!
3247 */
3248 int
3249unix_expandpath(
3250 garray_T *gap,
3251 char_u *path,
3252 int wildoff,
3253 int flags, // EW_* flags
3254 int didstar) // expanded "**" once already
3255{
3256 char_u *buf;
3257 char_u *path_end;
3258 char_u *p, *s, *e;
3259 int start_len = gap->ga_len;
3260 char_u *pat;
3261 regmatch_T regmatch;
3262 int starts_with_dot;
3263 int matches;
3264 int len;
3265 int starstar = FALSE;
3266 static int stardepth = 0; // depth for "**" expansion
3267
3268 DIR *dirp;
3269 struct dirent *dp;
3270
3271 // Expanding "**" may take a long time, check for CTRL-C.
3272 if (stardepth > 0)
3273 {
3274 ui_breakcheck();
3275 if (got_int)
3276 return 0;
3277 }
3278
3279 // make room for file name
3280 buf = alloc(STRLEN(path) + BASENAMELEN + 5);
3281 if (buf == NULL)
3282 return 0;
3283
3284 /*
3285 * Find the first part in the path name that contains a wildcard.
3286 * When EW_ICASE is set every letter is considered to be a wildcard.
3287 * Copy it into "buf", including the preceding characters.
3288 */
3289 p = buf;
3290 s = buf;
3291 e = NULL;
3292 path_end = path;
3293 while (*path_end != NUL)
3294 {
3295 // May ignore a wildcard that has a backslash before it; it will
3296 // be removed by rem_backslash() or file_pat_to_reg_pat() below.
3297 if (path_end >= path + wildoff && rem_backslash(path_end))
3298 *p++ = *path_end++;
3299 else if (*path_end == '/')
3300 {
3301 if (e != NULL)
3302 break;
3303 s = p + 1;
3304 }
3305 else if (path_end >= path + wildoff
3306 && (vim_strchr((char_u *)"*?[{~$", *path_end) != NULL
3307 || (!p_fic && (flags & EW_ICASE)
3308 && isalpha(PTR2CHAR(path_end)))))
3309 e = p;
3310 if (has_mbyte)
3311 {
3312 len = (*mb_ptr2len)(path_end);
3313 STRNCPY(p, path_end, len);
3314 p += len;
3315 path_end += len;
3316 }
3317 else
3318 *p++ = *path_end++;
3319 }
3320 e = p;
3321 *e = NUL;
3322
3323 // Now we have one wildcard component between "s" and "e".
3324 // Remove backslashes between "wildoff" and the start of the wildcard
3325 // component.
3326 for (p = buf + wildoff; p < s; ++p)
3327 if (rem_backslash(p))
3328 {
3329 STRMOVE(p, p + 1);
3330 --e;
3331 --s;
3332 }
3333
3334 // Check for "**" between "s" and "e".
3335 for (p = s; p < e; ++p)
3336 if (p[0] == '*' && p[1] == '*')
3337 starstar = TRUE;
3338
3339 // convert the file pattern to a regexp pattern
3340 starts_with_dot = *s == '.';
3341 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
3342 if (pat == NULL)
3343 {
3344 vim_free(buf);
3345 return 0;
3346 }
3347
3348 // compile the regexp into a program
3349 if (flags & EW_ICASE)
3350 regmatch.rm_ic = TRUE; // 'wildignorecase' set
3351 else
3352 regmatch.rm_ic = p_fic; // ignore case when 'fileignorecase' is set
3353 if (flags & (EW_NOERROR | EW_NOTWILD))
3354 ++emsg_silent;
3355 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
3356 if (flags & (EW_NOERROR | EW_NOTWILD))
3357 --emsg_silent;
3358 vim_free(pat);
3359
3360 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
3361 {
3362 vim_free(buf);
3363 return 0;
3364 }
3365
3366 // If "**" is by itself, this is the first time we encounter it and more
3367 // is following then find matches without any directory.
3368 if (!didstar && stardepth < 100 && starstar && e - s == 2
3369 && *path_end == '/')
3370 {
3371 STRCPY(s, path_end + 1);
3372 ++stardepth;
3373 (void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
3374 --stardepth;
3375 }
3376
3377 // open the directory for scanning
3378 *s = NUL;
3379 dirp = opendir(*buf == NUL ? "." : (char *)buf);
3380
3381 // Find all matching entries
3382 if (dirp != NULL)
3383 {
3384 for (;;)
3385 {
3386 dp = readdir(dirp);
3387 if (dp == NULL)
3388 break;
3389 if ((dp->d_name[0] != '.' || starts_with_dot
3390 || ((flags & EW_DODOT)
3391 && dp->d_name[1] != NUL
3392 && (dp->d_name[1] != '.' || dp->d_name[2] != NUL)))
3393 && ((regmatch.regprog != NULL && vim_regexec(&regmatch,
3394 (char_u *)dp->d_name, (colnr_T)0))
3395 || ((flags & EW_NOTWILD)
3396 && fnamencmp(path + (s - buf), dp->d_name, e - s) == 0)))
3397 {
3398 STRCPY(s, dp->d_name);
3399 len = STRLEN(buf);
3400
3401 if (starstar && stardepth < 100)
3402 {
3403 // For "**" in the pattern first go deeper in the tree to
3404 // find matches.
3405 STRCPY(buf + len, "/**");
3406 STRCPY(buf + len + 3, path_end);
3407 ++stardepth;
3408 (void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
3409 --stardepth;
3410 }
3411
3412 STRCPY(buf + len, path_end);
3413 if (mch_has_exp_wildcard(path_end)) // handle more wildcards
3414 {
3415 // need to expand another component of the path
3416 // remove backslashes for the remaining components only
3417 (void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
3418 }
3419 else
3420 {
3421 stat_T sb;
3422
3423 // no more wildcards, check if there is a match
3424 // remove backslashes for the remaining components only
3425 if (*path_end != NUL)
3426 backslash_halve(buf + len + 1);
3427 // add existing file or symbolic link
3428 if ((flags & EW_ALLLINKS) ? mch_lstat((char *)buf, &sb) >= 0
3429 : mch_getperm(buf) >= 0)
3430 {
3431#ifdef MACOS_CONVERT
3432 size_t precomp_len = STRLEN(buf)+1;
3433 char_u *precomp_buf =
3434 mac_precompose_path(buf, precomp_len, &precomp_len);
3435
3436 if (precomp_buf)
3437 {
3438 mch_memmove(buf, precomp_buf, precomp_len);
3439 vim_free(precomp_buf);
3440 }
3441#endif
3442 addfile(gap, buf, flags);
3443 }
3444 }
3445 }
3446 }
3447
3448 closedir(dirp);
3449 }
3450
3451 vim_free(buf);
3452 vim_regfree(regmatch.regprog);
3453
3454 matches = gap->ga_len - start_len;
3455 if (matches > 0)
3456 qsort(((char_u **)gap->ga_data) + start_len, matches,
3457 sizeof(char_u *), pstrcmp);
3458 return matches;
3459}
3460#endif
3461
3462/*
3463 * Return TRUE if "p" contains what looks like an environment variable.
3464 * Allowing for escaping.
3465 */
3466 static int
3467has_env_var(char_u *p)
3468{
3469 for ( ; *p; MB_PTR_ADV(p))
3470 {
3471 if (*p == '\\' && p[1] != NUL)
3472 ++p;
3473 else if (vim_strchr((char_u *)
3474#if defined(MSWIN)
3475 "$%"
3476#else
3477 "$"
3478#endif
3479 , *p) != NULL)
3480 return TRUE;
3481 }
3482 return FALSE;
3483}
3484
3485#ifdef SPECIAL_WILDCHAR
3486/*
3487 * Return TRUE if "p" contains a special wildcard character, one that Vim
3488 * cannot expand, requires using a shell.
3489 */
3490 static int
3491has_special_wildchar(char_u *p)
3492{
3493 for ( ; *p; MB_PTR_ADV(p))
3494 {
3495 // Disallow line break characters.
3496 if (*p == '\r' || *p == '\n')
3497 break;
3498 // Allow for escaping.
3499 if (*p == '\\' && p[1] != NUL && p[1] != '\r' && p[1] != '\n')
3500 ++p;
3501 else if (vim_strchr((char_u *)SPECIAL_WILDCHAR, *p) != NULL)
3502 {
3503 // A { must be followed by a matching }.
3504 if (*p == '{' && vim_strchr(p, '}') == NULL)
3505 continue;
3506 // A quote and backtick must be followed by another one.
3507 if ((*p == '`' || *p == '\'') && vim_strchr(p, *p) == NULL)
3508 continue;
3509 return TRUE;
3510 }
3511 }
3512 return FALSE;
3513}
3514#endif
3515
3516/*
3517 * Generic wildcard expansion code.
3518 *
3519 * Characters in "pat" that should not be expanded must be preceded with a
3520 * backslash. E.g., "/path\ with\ spaces/my\*star*"
3521 *
3522 * Return FAIL when no single file was found. In this case "num_file" is not
3523 * set, and "file" may contain an error message.
3524 * Return OK when some files found. "num_file" is set to the number of
3525 * matches, "file" to the array of matches. Call FreeWild() later.
3526 */
3527 int
3528gen_expand_wildcards(
3529 int num_pat, // number of input patterns
3530 char_u **pat, // array of input patterns
3531 int *num_file, // resulting number of files
3532 char_u ***file, // array of resulting files
3533 int flags) // EW_* flags
3534{
3535 int i;
3536 garray_T ga;
3537 char_u *p;
3538 static int recursive = FALSE;
3539 int add_pat;
3540 int retval = OK;
3541#if defined(FEAT_SEARCHPATH)
3542 int did_expand_in_path = FALSE;
3543#endif
3544
3545 /*
3546 * expand_env() is called to expand things like "~user". If this fails,
3547 * it calls ExpandOne(), which brings us back here. In this case, always
3548 * call the machine specific expansion function, if possible. Otherwise,
3549 * return FAIL.
3550 */
3551 if (recursive)
3552#ifdef SPECIAL_WILDCHAR
3553 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
3554#else
3555 return FAIL;
3556#endif
3557
3558#ifdef SPECIAL_WILDCHAR
3559 /*
3560 * If there are any special wildcard characters which we cannot handle
3561 * here, call machine specific function for all the expansion. This
3562 * avoids starting the shell for each argument separately.
3563 * For `=expr` do use the internal function.
3564 */
3565 for (i = 0; i < num_pat; i++)
3566 {
3567 if (has_special_wildchar(pat[i])
3568# ifdef VIM_BACKTICK
3569 && !(vim_backtick(pat[i]) && pat[i][1] == '=')
3570# endif
3571 )
3572 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
3573 }
3574#endif
3575
3576 recursive = TRUE;
3577
3578 /*
3579 * The matching file names are stored in a growarray. Init it empty.
3580 */
3581 ga_init2(&ga, (int)sizeof(char_u *), 30);
3582
3583 for (i = 0; i < num_pat; ++i)
3584 {
3585 add_pat = -1;
3586 p = pat[i];
3587
3588#ifdef VIM_BACKTICK
3589 if (vim_backtick(p))
3590 {
3591 add_pat = expand_backtick(&ga, p, flags);
3592 if (add_pat == -1)
3593 retval = FAIL;
3594 }
3595 else
3596#endif
3597 {
3598 /*
3599 * First expand environment variables, "~/" and "~user/".
3600 */
3601 if ((has_env_var(p) && !(flags & EW_NOTENV)) || *p == '~')
3602 {
3603 p = expand_env_save_opt(p, TRUE);
3604 if (p == NULL)
3605 p = pat[i];
3606#ifdef UNIX
3607 /*
3608 * On Unix, if expand_env() can't expand an environment
3609 * variable, use the shell to do that. Discard previously
3610 * found file names and start all over again.
3611 */
3612 else if (has_env_var(p) || *p == '~')
3613 {
3614 vim_free(p);
3615 ga_clear_strings(&ga);
3616 i = mch_expand_wildcards(num_pat, pat, num_file, file,
3617 flags|EW_KEEPDOLLAR);
3618 recursive = FALSE;
3619 return i;
3620 }
3621#endif
3622 }
3623
3624 /*
3625 * If there are wildcards: Expand file names and add each match to
3626 * the list. If there is no match, and EW_NOTFOUND is given, add
3627 * the pattern.
3628 * If there are no wildcards: Add the file name if it exists or
3629 * when EW_NOTFOUND is given.
3630 */
3631 if (mch_has_exp_wildcard(p))
3632 {
3633#if defined(FEAT_SEARCHPATH)
3634 if ((flags & EW_PATH)
3635 && !mch_isFullName(p)
3636 && !(p[0] == '.'
3637 && (vim_ispathsep(p[1])
3638 || (p[1] == '.' && vim_ispathsep(p[2]))))
3639 )
3640 {
3641 // :find completion where 'path' is used.
3642 // Recursiveness is OK here.
3643 recursive = FALSE;
3644 add_pat = expand_in_path(&ga, p, flags);
3645 recursive = TRUE;
3646 did_expand_in_path = TRUE;
3647 }
3648 else
3649#endif
3650 add_pat = mch_expandpath(&ga, p, flags);
3651 }
3652 }
3653
3654 if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
3655 {
3656 char_u *t = backslash_halve_save(p);
3657
3658 // When EW_NOTFOUND is used, always add files and dirs. Makes
3659 // "vim c:/" work.
3660 if (flags & EW_NOTFOUND)
3661 addfile(&ga, t, flags | EW_DIR | EW_FILE);
3662 else
3663 addfile(&ga, t, flags);
3664
3665 if (t != p)
3666 vim_free(t);
3667 }
3668
3669#if defined(FEAT_SEARCHPATH)
3670 if (did_expand_in_path && ga.ga_len > 0 && (flags & EW_PATH))
3671 uniquefy_paths(&ga, p);
3672#endif
3673 if (p != pat[i])
3674 vim_free(p);
3675 }
3676
3677 *num_file = ga.ga_len;
3678 *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data : (char_u **)"";
3679
3680 recursive = FALSE;
3681
3682 return ((flags & EW_EMPTYOK) || ga.ga_data != NULL) ? retval : FAIL;
3683}
3684
3685/*
3686 * Add a file to a file list. Accepted flags:
3687 * EW_DIR add directories
3688 * EW_FILE add files
3689 * EW_EXEC add executable files
3690 * EW_NOTFOUND add even when it doesn't exist
3691 * EW_ADDSLASH add slash after directory name
3692 * EW_ALLLINKS add symlink also when the referred file does not exist
3693 */
3694 void
3695addfile(
3696 garray_T *gap,
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003697 char_u *f, // filename
Bram Moolenaar26262f82019-09-04 20:59:15 +02003698 int flags)
3699{
3700 char_u *p;
3701 int isdir;
3702 stat_T sb;
3703
3704 // if the file/dir/link doesn't exist, may not add it
3705 if (!(flags & EW_NOTFOUND) && ((flags & EW_ALLLINKS)
3706 ? mch_lstat((char *)f, &sb) < 0 : mch_getperm(f) < 0))
3707 return;
3708
3709#ifdef FNAME_ILLEGAL
3710 // if the file/dir contains illegal characters, don't add it
3711 if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
3712 return;
3713#endif
3714
3715 isdir = mch_isdir(f);
3716 if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
3717 return;
3718
3719 // If the file isn't executable, may not add it. Do accept directories.
3720 // When invoked from expand_shellcmd() do not use $PATH.
3721 if (!isdir && (flags & EW_EXEC)
3722 && !mch_can_exe(f, NULL, !(flags & EW_SHELLCMD)))
3723 return;
3724
3725 // Make room for another item in the file list.
3726 if (ga_grow(gap, 1) == FAIL)
3727 return;
3728
3729 p = alloc(STRLEN(f) + 1 + isdir);
3730 if (p == NULL)
3731 return;
3732
3733 STRCPY(p, f);
3734#ifdef BACKSLASH_IN_FILENAME
3735 slash_adjust(p);
3736#endif
3737 /*
3738 * Append a slash or backslash after directory names if none is present.
3739 */
3740#ifndef DONT_ADD_PATHSEP_TO_DIR
3741 if (isdir && (flags & EW_ADDSLASH))
3742 add_pathsep(p);
3743#endif
3744 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
3745}
3746
3747/*
3748 * Free the list of files returned by expand_wildcards() or other expansion
3749 * functions.
3750 */
3751 void
3752FreeWild(int count, char_u **files)
3753{
3754 if (count <= 0 || files == NULL)
3755 return;
3756 while (count--)
3757 vim_free(files[count]);
3758 vim_free(files);
3759}
3760
3761/*
3762 * Compare path "p[]" to "q[]".
3763 * If "maxlen" >= 0 compare "p[maxlen]" to "q[maxlen]"
3764 * Return value like strcmp(p, q), but consider path separators.
3765 */
3766 int
3767pathcmp(const char *p, const char *q, int maxlen)
3768{
3769 int i, j;
3770 int c1, c2;
3771 const char *s = NULL;
3772
3773 for (i = 0, j = 0; maxlen < 0 || (i < maxlen && j < maxlen);)
3774 {
3775 c1 = PTR2CHAR((char_u *)p + i);
3776 c2 = PTR2CHAR((char_u *)q + j);
3777
3778 // End of "p": check if "q" also ends or just has a slash.
3779 if (c1 == NUL)
3780 {
3781 if (c2 == NUL) // full match
3782 return 0;
3783 s = q;
3784 i = j;
3785 break;
3786 }
3787
3788 // End of "q": check if "p" just has a slash.
3789 if (c2 == NUL)
3790 {
3791 s = p;
3792 break;
3793 }
3794
3795 if ((p_fic ? MB_TOUPPER(c1) != MB_TOUPPER(c2) : c1 != c2)
3796#ifdef BACKSLASH_IN_FILENAME
3797 // consider '/' and '\\' to be equal
3798 && !((c1 == '/' && c2 == '\\')
3799 || (c1 == '\\' && c2 == '/'))
3800#endif
3801 )
3802 {
3803 if (vim_ispathsep(c1))
3804 return -1;
3805 if (vim_ispathsep(c2))
3806 return 1;
3807 return p_fic ? MB_TOUPPER(c1) - MB_TOUPPER(c2)
3808 : c1 - c2; // no match
3809 }
3810
Bram Moolenaar1614a142019-10-06 22:00:13 +02003811 i += mb_ptr2len((char_u *)p + i);
3812 j += mb_ptr2len((char_u *)q + j);
Bram Moolenaar26262f82019-09-04 20:59:15 +02003813 }
3814 if (s == NULL) // "i" or "j" ran into "maxlen"
3815 return 0;
3816
3817 c1 = PTR2CHAR((char_u *)s + i);
Bram Moolenaar1614a142019-10-06 22:00:13 +02003818 c2 = PTR2CHAR((char_u *)s + i + mb_ptr2len((char_u *)s + i));
Bram Moolenaar26262f82019-09-04 20:59:15 +02003819 // ignore a trailing slash, but not "//" or ":/"
3820 if (c2 == NUL
3821 && i > 0
3822 && !after_pathsep((char_u *)s, (char_u *)s + i)
3823#ifdef BACKSLASH_IN_FILENAME
3824 && (c1 == '/' || c1 == '\\')
3825#else
3826 && c1 == '/'
3827#endif
3828 )
3829 return 0; // match with trailing slash
3830 if (s == q)
3831 return -1; // no match
3832 return 1;
3833}
3834
3835/*
3836 * Return TRUE if "name" is a full (absolute) path name or URL.
3837 */
3838 int
3839vim_isAbsName(char_u *name)
3840{
3841 return (path_with_url(name) != 0 || mch_isFullName(name));
3842}
3843
3844/*
3845 * Get absolute file name into buffer "buf[len]".
3846 *
3847 * return FAIL for failure, OK otherwise
3848 */
3849 int
3850vim_FullName(
3851 char_u *fname,
3852 char_u *buf,
3853 int len,
3854 int force) // force expansion even when already absolute
3855{
3856 int retval = OK;
3857 int url;
3858
3859 *buf = NUL;
3860 if (fname == NULL)
3861 return FAIL;
3862
3863 url = path_with_url(fname);
3864 if (!url)
3865 retval = mch_FullName(fname, buf, len, force);
3866 if (url || retval == FAIL)
3867 {
3868 // something failed; use the file name (truncate when too long)
3869 vim_strncpy(buf, fname, len - 1);
3870 }
3871#if defined(MSWIN)
3872 slash_adjust(buf);
3873#endif
3874 return retval;
3875}