blob: 12e76b444ad7cdd6b72bb24404cb021915490405 [file] [log] [blame]
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001/* 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/*
11 * findfile.c: Search for files in directories listed in 'path'
12 */
13
14#include "vim.h"
15
16/*
17 * File searching functions for 'path', 'tags' and 'cdpath' options.
18 * External visible functions:
19 * vim_findfile_init() creates/initialises the search context
20 * vim_findfile_free_visited() free list of visited files/dirs of search
21 * context
22 * vim_findfile() find a file in the search context
23 * vim_findfile_cleanup() cleanup/free search context created by
24 * vim_findfile_init()
25 *
26 * All static functions and variables start with 'ff_'
27 *
28 * In general it works like this:
29 * First you create yourself a search context by calling vim_findfile_init().
30 * It is possible to give a search context from a previous call to
31 * vim_findfile_init(), so it can be reused. After this you call vim_findfile()
32 * until you are satisfied with the result or it returns NULL. On every call it
33 * returns the next file which matches the conditions given to
34 * vim_findfile_init(). If it doesn't find a next file it returns NULL.
35 *
36 * It is possible to call vim_findfile_init() again to reinitialise your search
37 * with some new parameters. Don't forget to pass your old search context to
38 * it, so it can reuse it and especially reuse the list of already visited
39 * directories. If you want to delete the list of already visited directories
40 * simply call vim_findfile_free_visited().
41 *
42 * When you are done call vim_findfile_cleanup() to free the search context.
43 *
44 * The function vim_findfile_init() has a long comment, which describes the
45 * needed parameters.
46 *
47 *
48 *
49 * ATTENTION:
50 * ==========
51 * Also we use an allocated search context here, this functions are NOT
52 * thread-safe!!!!!
53 *
54 * To minimize parameter passing (or because I'm to lazy), only the
55 * external visible functions get a search context as a parameter. This is
56 * then assigned to a static global, which is used throughout the local
57 * functions.
58 */
59
60/*
61 * type for the directory search stack
62 */
63typedef struct ff_stack
64{
65 struct ff_stack *ffs_prev;
66
67 // the fix part (no wildcards) and the part containing the wildcards
68 // of the search path
69 char_u *ffs_fix_path;
70#ifdef FEAT_PATH_EXTRA
71 char_u *ffs_wc_path;
72#endif
73
74 // files/dirs found in the above directory, matched by the first wildcard
75 // of wc_part
76 char_u **ffs_filearray;
77 int ffs_filearray_size;
78 char_u ffs_filearray_cur; // needed for partly handled dirs
79
80 // to store status of partly handled directories
81 // 0: we work on this directory for the first time
82 // 1: this directory was partly searched in an earlier step
83 int ffs_stage;
84
85 // How deep are we in the directory tree?
86 // Counts backward from value of level parameter to vim_findfile_init
87 int ffs_level;
88
89 // Did we already expand '**' to an empty string?
90 int ffs_star_star_empty;
91} ff_stack_T;
92
93/*
94 * type for already visited directories or files.
95 */
96typedef struct ff_visited
97{
98 struct ff_visited *ffv_next;
99
100#ifdef FEAT_PATH_EXTRA
101 // Visited directories are different if the wildcard string are
102 // different. So we have to save it.
103 char_u *ffv_wc_path;
104#endif
105 // for unix use inode etc for comparison (needed because of links), else
106 // use filename.
107#ifdef UNIX
108 int ffv_dev_valid; // ffv_dev and ffv_ino were set
109 dev_t ffv_dev; // device number
110 ino_t ffv_ino; // inode number
111#endif
112 // The memory for this struct is allocated according to the length of
113 // ffv_fname.
114 char_u ffv_fname[1]; // actually longer
115} ff_visited_T;
116
117/*
118 * We might have to manage several visited lists during a search.
119 * This is especially needed for the tags option. If tags is set to:
120 * "./++/tags,./++/TAGS,++/tags" (replace + with *)
121 * So we have to do 3 searches:
122 * 1) search from the current files directory downward for the file "tags"
123 * 2) search from the current files directory downward for the file "TAGS"
124 * 3) search from Vims current directory downwards for the file "tags"
125 * As you can see, the first and the third search are for the same file, so for
126 * the third search we can use the visited list of the first search. For the
127 * second search we must start from a empty visited list.
128 * The struct ff_visited_list_hdr is used to manage a linked list of already
129 * visited lists.
130 */
131typedef struct ff_visited_list_hdr
132{
133 struct ff_visited_list_hdr *ffvl_next;
134
135 // the filename the attached visited list is for
136 char_u *ffvl_filename;
137
138 ff_visited_T *ffvl_visited_list;
139
140} ff_visited_list_hdr_T;
141
142
143/*
144 * '**' can be expanded to several directory levels.
145 * Set the default maximum depth.
146 */
147#define FF_MAX_STAR_STAR_EXPAND ((char_u)30)
148
149/*
150 * The search context:
151 * ffsc_stack_ptr: the stack for the dirs to search
152 * ffsc_visited_list: the currently active visited list
153 * ffsc_dir_visited_list: the currently active visited list for search dirs
154 * ffsc_visited_lists_list: the list of all visited lists
155 * ffsc_dir_visited_lists_list: the list of all visited lists for search dirs
156 * ffsc_file_to_search: the file to search for
157 * ffsc_start_dir: the starting directory, if search path was relative
158 * ffsc_fix_path: the fix part of the given path (without wildcards)
159 * Needed for upward search.
160 * ffsc_wc_path: the part of the given path containing wildcards
161 * ffsc_level: how many levels of dirs to search downwards
162 * ffsc_stopdirs_v: array of stop directories for upward search
163 * ffsc_find_what: FINDFILE_BOTH, FINDFILE_DIR or FINDFILE_FILE
164 * ffsc_tagfile: searching for tags file, don't use 'suffixesadd'
165 */
166typedef struct ff_search_ctx_T
167{
168 ff_stack_T *ffsc_stack_ptr;
169 ff_visited_list_hdr_T *ffsc_visited_list;
170 ff_visited_list_hdr_T *ffsc_dir_visited_list;
171 ff_visited_list_hdr_T *ffsc_visited_lists_list;
172 ff_visited_list_hdr_T *ffsc_dir_visited_lists_list;
173 char_u *ffsc_file_to_search;
174 char_u *ffsc_start_dir;
175 char_u *ffsc_fix_path;
176#ifdef FEAT_PATH_EXTRA
177 char_u *ffsc_wc_path;
178 int ffsc_level;
179 char_u **ffsc_stopdirs_v;
180#endif
181 int ffsc_find_what;
182 int ffsc_tagfile;
183} ff_search_ctx_T;
184
185// locally needed functions
186#ifdef FEAT_PATH_EXTRA
187static int ff_check_visited(ff_visited_T **, char_u *, char_u *);
188#else
189static int ff_check_visited(ff_visited_T **, char_u *);
190#endif
Bram Moolenaar5843f5f2019-08-20 20:13:45 +0200191static void vim_findfile_free_visited(void *search_ctx_arg);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100192static void vim_findfile_free_visited_list(ff_visited_list_hdr_T **list_headp);
193static void ff_free_visited_list(ff_visited_T *vl);
194static ff_visited_list_hdr_T* ff_get_visited_list(char_u *, ff_visited_list_hdr_T **list_headp);
195
196static void ff_push(ff_search_ctx_T *search_ctx, ff_stack_T *stack_ptr);
197static ff_stack_T *ff_pop(ff_search_ctx_T *search_ctx);
198static void ff_clear(ff_search_ctx_T *search_ctx);
199static void ff_free_stack_element(ff_stack_T *stack_ptr);
200#ifdef FEAT_PATH_EXTRA
201static ff_stack_T *ff_create_stack_element(char_u *, char_u *, int, int);
202#else
203static ff_stack_T *ff_create_stack_element(char_u *, int, int);
204#endif
205#ifdef FEAT_PATH_EXTRA
206static int ff_path_in_stoplist(char_u *, int, char_u **);
207#endif
208
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100209static char_u *ff_expand_buffer = NULL; // used for expanding filenames
210
211#if 0
212/*
213 * if someone likes findfirst/findnext, here are the functions
214 * NOT TESTED!!
215 */
216
217static void *ff_fn_search_context = NULL;
218
219 char_u *
220vim_findfirst(char_u *path, char_u *filename, int level)
221{
222 ff_fn_search_context =
223 vim_findfile_init(path, filename, NULL, level, TRUE, FALSE,
224 ff_fn_search_context, rel_fname);
225 if (NULL == ff_fn_search_context)
226 return NULL;
227 else
228 return vim_findnext()
229}
230
231 char_u *
232vim_findnext(void)
233{
234 char_u *ret = vim_findfile(ff_fn_search_context);
235
236 if (NULL == ret)
237 {
238 vim_findfile_cleanup(ff_fn_search_context);
239 ff_fn_search_context = NULL;
240 }
241 return ret;
242}
243#endif
244
245/*
246 * Initialization routine for vim_findfile().
247 *
248 * Returns the newly allocated search context or NULL if an error occurred.
249 *
250 * Don't forget to clean up by calling vim_findfile_cleanup() if you are done
251 * with the search context.
252 *
253 * Find the file 'filename' in the directory 'path'.
254 * The parameter 'path' may contain wildcards. If so only search 'level'
255 * directories deep. The parameter 'level' is the absolute maximum and is
256 * not related to restricts given to the '**' wildcard. If 'level' is 100
257 * and you use '**200' vim_findfile() will stop after 100 levels.
258 *
259 * 'filename' cannot contain wildcards! It is used as-is, no backslashes to
260 * escape special characters.
261 *
262 * If 'stopdirs' is not NULL and nothing is found downward, the search is
263 * restarted on the next higher directory level. This is repeated until the
264 * start-directory of a search is contained in 'stopdirs'. 'stopdirs' has the
265 * format ";*<dirname>*\(;<dirname>\)*;\=$".
266 *
267 * If the 'path' is relative, the starting dir for the search is either VIM's
268 * current dir or if the path starts with "./" the current files dir.
269 * If the 'path' is absolute, the starting dir is that part of the path before
270 * the first wildcard.
271 *
272 * Upward search is only done on the starting dir.
273 *
274 * If 'free_visited' is TRUE the list of already visited files/directories is
275 * cleared. Set this to FALSE if you just want to search from another
276 * directory, but want to be sure that no directory from a previous search is
277 * searched again. This is useful if you search for a file at different places.
278 * The list of visited files/dirs can also be cleared with the function
279 * vim_findfile_free_visited().
280 *
281 * Set the parameter 'find_what' to FINDFILE_DIR if you want to search for
282 * directories only, FINDFILE_FILE for files only, FINDFILE_BOTH for both.
283 *
284 * A search context returned by a previous call to vim_findfile_init() can be
285 * passed in the parameter "search_ctx_arg". This context is reused and
286 * reinitialized with the new parameters. The list of already visited
287 * directories from this context is only deleted if the parameter
288 * "free_visited" is true. Be aware that the passed "search_ctx_arg" is freed
289 * if the reinitialization fails.
290 *
291 * If you don't have a search context from a previous call "search_ctx_arg"
292 * must be NULL.
293 *
294 * This function silently ignores a few errors, vim_findfile() will have
295 * limited functionality then.
296 */
297 void *
298vim_findfile_init(
299 char_u *path,
300 char_u *filename,
301 char_u *stopdirs UNUSED,
302 int level,
303 int free_visited,
304 int find_what,
305 void *search_ctx_arg,
306 int tagfile, // expanding names of tags files
307 char_u *rel_fname) // file name to use for "."
308{
309#ifdef FEAT_PATH_EXTRA
310 char_u *wc_part;
311#endif
312 ff_stack_T *sptr;
313 ff_search_ctx_T *search_ctx;
314
315 // If a search context is given by the caller, reuse it, else allocate a
316 // new one.
317 if (search_ctx_arg != NULL)
318 search_ctx = search_ctx_arg;
319 else
320 {
Bram Moolenaara80faa82020-04-12 19:37:17 +0200321 search_ctx = ALLOC_CLEAR_ONE(ff_search_ctx_T);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100322 if (search_ctx == NULL)
323 goto error_return;
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100324 }
325 search_ctx->ffsc_find_what = find_what;
326 search_ctx->ffsc_tagfile = tagfile;
327
328 // clear the search context, but NOT the visited lists
329 ff_clear(search_ctx);
330
331 // clear visited list if wanted
332 if (free_visited == TRUE)
333 vim_findfile_free_visited(search_ctx);
334 else
335 {
336 // Reuse old visited lists. Get the visited list for the given
337 // filename. If no list for the current filename exists, creates a new
338 // one.
339 search_ctx->ffsc_visited_list = ff_get_visited_list(filename,
340 &search_ctx->ffsc_visited_lists_list);
341 if (search_ctx->ffsc_visited_list == NULL)
342 goto error_return;
343 search_ctx->ffsc_dir_visited_list = ff_get_visited_list(filename,
344 &search_ctx->ffsc_dir_visited_lists_list);
345 if (search_ctx->ffsc_dir_visited_list == NULL)
346 goto error_return;
347 }
348
349 if (ff_expand_buffer == NULL)
350 {
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200351 ff_expand_buffer = alloc(MAXPATHL);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100352 if (ff_expand_buffer == NULL)
353 goto error_return;
354 }
355
356 // Store information on starting dir now if path is relative.
357 // If path is absolute, we do that later.
358 if (path[0] == '.'
359 && (vim_ispathsep(path[1]) || path[1] == NUL)
360 && (!tagfile || vim_strchr(p_cpo, CPO_DOTTAG) == NULL)
361 && rel_fname != NULL)
362 {
363 int len = (int)(gettail(rel_fname) - rel_fname);
364
365 if (!vim_isAbsName(rel_fname) && len + 1 < MAXPATHL)
366 {
367 // Make the start dir an absolute path name.
368 vim_strncpy(ff_expand_buffer, rel_fname, len);
369 search_ctx->ffsc_start_dir = FullName_save(ff_expand_buffer, FALSE);
370 }
371 else
372 search_ctx->ffsc_start_dir = vim_strnsave(rel_fname, len);
373 if (search_ctx->ffsc_start_dir == NULL)
374 goto error_return;
375 if (*++path != NUL)
376 ++path;
377 }
378 else if (*path == NUL || !vim_isAbsName(path))
379 {
380#ifdef BACKSLASH_IN_FILENAME
381 // "c:dir" needs "c:" to be expanded, otherwise use current dir
382 if (*path != NUL && path[1] == ':')
383 {
384 char_u drive[3];
385
386 drive[0] = path[0];
387 drive[1] = ':';
388 drive[2] = NUL;
389 if (vim_FullName(drive, ff_expand_buffer, MAXPATHL, TRUE) == FAIL)
390 goto error_return;
391 path += 2;
392 }
393 else
394#endif
395 if (mch_dirname(ff_expand_buffer, MAXPATHL) == FAIL)
396 goto error_return;
397
398 search_ctx->ffsc_start_dir = vim_strsave(ff_expand_buffer);
399 if (search_ctx->ffsc_start_dir == NULL)
400 goto error_return;
401
402#ifdef BACKSLASH_IN_FILENAME
403 // A path that starts with "/dir" is relative to the drive, not to the
404 // directory (but not for "//machine/dir"). Only use the drive name.
405 if ((*path == '/' || *path == '\\')
406 && path[1] != path[0]
407 && search_ctx->ffsc_start_dir[1] == ':')
408 search_ctx->ffsc_start_dir[2] = NUL;
409#endif
410 }
411
412#ifdef FEAT_PATH_EXTRA
413 /*
414 * If stopdirs are given, split them into an array of pointers.
415 * If this fails (mem allocation), there is no upward search at all or a
416 * stop directory is not recognized -> continue silently.
417 * If stopdirs just contains a ";" or is empty,
418 * search_ctx->ffsc_stopdirs_v will only contain a NULL pointer. This
419 * is handled as unlimited upward search. See function
420 * ff_path_in_stoplist() for details.
421 */
422 if (stopdirs != NULL)
423 {
424 char_u *walker = stopdirs;
425 int dircount;
426
427 while (*walker == ';')
428 walker++;
429
430 dircount = 1;
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200431 search_ctx->ffsc_stopdirs_v = ALLOC_ONE(char_u *);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100432
433 if (search_ctx->ffsc_stopdirs_v != NULL)
434 {
435 do
436 {
437 char_u *helper;
438 void *ptr;
439
440 helper = walker;
441 ptr = vim_realloc(search_ctx->ffsc_stopdirs_v,
442 (dircount + 1) * sizeof(char_u *));
443 if (ptr)
444 search_ctx->ffsc_stopdirs_v = ptr;
445 else
446 // ignore, keep what we have and continue
447 break;
448 walker = vim_strchr(walker, ';');
449 if (walker)
450 {
451 search_ctx->ffsc_stopdirs_v[dircount-1] =
Bram Moolenaar71ccd032020-06-12 22:59:11 +0200452 vim_strnsave(helper, walker - helper);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100453 walker++;
454 }
455 else
456 // this might be "", which means ascent till top
457 // of directory tree.
458 search_ctx->ffsc_stopdirs_v[dircount-1] =
459 vim_strsave(helper);
460
461 dircount++;
462
463 } while (walker != NULL);
464 search_ctx->ffsc_stopdirs_v[dircount-1] = NULL;
465 }
466 }
467#endif
468
469#ifdef FEAT_PATH_EXTRA
470 search_ctx->ffsc_level = level;
471
472 /*
473 * split into:
474 * -fix path
475 * -wildcard_stuff (might be NULL)
476 */
477 wc_part = vim_strchr(path, '*');
478 if (wc_part != NULL)
479 {
480 int llevel;
481 int len;
482 char *errpt;
483
484 // save the fix part of the path
Bram Moolenaar71ccd032020-06-12 22:59:11 +0200485 search_ctx->ffsc_fix_path = vim_strnsave(path, wc_part - path);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100486
487 /*
488 * copy wc_path and add restricts to the '**' wildcard.
489 * The octet after a '**' is used as a (binary) counter.
490 * So '**3' is transposed to '**^C' ('^C' is ASCII value 3)
491 * or '**76' is transposed to '**N'( 'N' is ASCII value 76).
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100492 * If no restrict is given after '**' the default is used.
493 * Due to this technique the path looks awful if you print it as a
494 * string.
495 */
496 len = 0;
497 while (*wc_part != NUL)
498 {
499 if (len + 5 >= MAXPATHL)
500 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +0000501 emsg(_(e_path_too_long_for_completion));
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100502 break;
503 }
504 if (STRNCMP(wc_part, "**", 2) == 0)
505 {
506 ff_expand_buffer[len++] = *wc_part++;
507 ff_expand_buffer[len++] = *wc_part++;
508
509 llevel = strtol((char *)wc_part, &errpt, 10);
510 if ((char_u *)errpt != wc_part && llevel > 0 && llevel < 255)
511 ff_expand_buffer[len++] = llevel;
512 else if ((char_u *)errpt != wc_part && llevel == 0)
513 // restrict is 0 -> remove already added '**'
514 len -= 2;
515 else
516 ff_expand_buffer[len++] = FF_MAX_STAR_STAR_EXPAND;
517 wc_part = (char_u *)errpt;
518 if (*wc_part != NUL && !vim_ispathsep(*wc_part))
519 {
Bram Moolenaareaaac012022-01-02 17:00:40 +0000520 semsg(_(e_invalid_path_number_must_be_at_end_of_path_or_be_followed_by_str), PATHSEPSTR);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100521 goto error_return;
522 }
523 }
524 else
525 ff_expand_buffer[len++] = *wc_part++;
526 }
527 ff_expand_buffer[len] = NUL;
528 search_ctx->ffsc_wc_path = vim_strsave(ff_expand_buffer);
529
530 if (search_ctx->ffsc_wc_path == NULL)
531 goto error_return;
532 }
533 else
534#endif
535 search_ctx->ffsc_fix_path = vim_strsave(path);
536
537 if (search_ctx->ffsc_start_dir == NULL)
538 {
539 // store the fix part as startdir.
540 // This is needed if the parameter path is fully qualified.
541 search_ctx->ffsc_start_dir = vim_strsave(search_ctx->ffsc_fix_path);
542 if (search_ctx->ffsc_start_dir == NULL)
543 goto error_return;
544 search_ctx->ffsc_fix_path[0] = NUL;
545 }
546
547 // create an absolute path
548 if (STRLEN(search_ctx->ffsc_start_dir)
549 + STRLEN(search_ctx->ffsc_fix_path) + 3 >= MAXPATHL)
550 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +0000551 emsg(_(e_path_too_long_for_completion));
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100552 goto error_return;
553 }
554 STRCPY(ff_expand_buffer, search_ctx->ffsc_start_dir);
555 add_pathsep(ff_expand_buffer);
556 {
557 int eb_len = (int)STRLEN(ff_expand_buffer);
558 char_u *buf = alloc(eb_len
559 + (int)STRLEN(search_ctx->ffsc_fix_path) + 1);
560
561 STRCPY(buf, ff_expand_buffer);
562 STRCPY(buf + eb_len, search_ctx->ffsc_fix_path);
563 if (mch_isdir(buf))
564 {
565 STRCAT(ff_expand_buffer, search_ctx->ffsc_fix_path);
566 add_pathsep(ff_expand_buffer);
567 }
568#ifdef FEAT_PATH_EXTRA
569 else
570 {
571 char_u *p = gettail(search_ctx->ffsc_fix_path);
572 char_u *wc_path = NULL;
573 char_u *temp = NULL;
574 int len = 0;
575
576 if (p > search_ctx->ffsc_fix_path)
577 {
Christian Brabandt7a4ca322021-07-25 15:08:05 +0200578 // do not add '..' to the path and start upwards searching
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100579 len = (int)(p - search_ctx->ffsc_fix_path) - 1;
Christian Brabandt7a4ca322021-07-25 15:08:05 +0200580 if ((len >= 2
581 && STRNCMP(search_ctx->ffsc_fix_path, "..", 2) == 0)
582 && (len == 2
583 || search_ctx->ffsc_fix_path[2] == PATHSEP))
584 {
585 vim_free(buf);
586 goto error_return;
587 }
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100588 STRNCAT(ff_expand_buffer, search_ctx->ffsc_fix_path, len);
589 add_pathsep(ff_expand_buffer);
590 }
591 else
592 len = (int)STRLEN(search_ctx->ffsc_fix_path);
593
594 if (search_ctx->ffsc_wc_path != NULL)
595 {
596 wc_path = vim_strsave(search_ctx->ffsc_wc_path);
Bram Moolenaar51e14382019-05-25 20:21:28 +0200597 temp = alloc(STRLEN(search_ctx->ffsc_wc_path)
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100598 + STRLEN(search_ctx->ffsc_fix_path + len)
Bram Moolenaar51e14382019-05-25 20:21:28 +0200599 + 1);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100600 if (temp == NULL || wc_path == NULL)
601 {
602 vim_free(buf);
603 vim_free(temp);
604 vim_free(wc_path);
605 goto error_return;
606 }
607
608 STRCPY(temp, search_ctx->ffsc_fix_path + len);
609 STRCAT(temp, search_ctx->ffsc_wc_path);
610 vim_free(search_ctx->ffsc_wc_path);
611 vim_free(wc_path);
612 search_ctx->ffsc_wc_path = temp;
613 }
614 }
615#endif
616 vim_free(buf);
617 }
618
619 sptr = ff_create_stack_element(ff_expand_buffer,
620#ifdef FEAT_PATH_EXTRA
621 search_ctx->ffsc_wc_path,
622#endif
623 level, 0);
624
625 if (sptr == NULL)
626 goto error_return;
627
628 ff_push(search_ctx, sptr);
629
630 search_ctx->ffsc_file_to_search = vim_strsave(filename);
631 if (search_ctx->ffsc_file_to_search == NULL)
632 goto error_return;
633
634 return search_ctx;
635
636error_return:
637 /*
638 * We clear the search context now!
639 * Even when the caller gave us a (perhaps valid) context we free it here,
640 * as we might have already destroyed it.
641 */
642 vim_findfile_cleanup(search_ctx);
643 return NULL;
644}
645
646#if defined(FEAT_PATH_EXTRA) || defined(PROTO)
647/*
648 * Get the stopdir string. Check that ';' is not escaped.
649 */
650 char_u *
651vim_findfile_stopdir(char_u *buf)
652{
653 char_u *r_ptr = buf;
654
655 while (*r_ptr != NUL && *r_ptr != ';')
656 {
657 if (r_ptr[0] == '\\' && r_ptr[1] == ';')
658 {
659 // Overwrite the escape char,
660 // use STRLEN(r_ptr) to move the trailing '\0'.
661 STRMOVE(r_ptr, r_ptr + 1);
662 r_ptr++;
663 }
664 r_ptr++;
665 }
666 if (*r_ptr == ';')
667 {
668 *r_ptr = 0;
669 r_ptr++;
670 }
671 else if (*r_ptr == NUL)
672 r_ptr = NULL;
673 return r_ptr;
674}
675#endif
676
677/*
678 * Clean up the given search context. Can handle a NULL pointer.
679 */
680 void
681vim_findfile_cleanup(void *ctx)
682{
683 if (ctx == NULL)
684 return;
685
686 vim_findfile_free_visited(ctx);
687 ff_clear(ctx);
688 vim_free(ctx);
689}
690
691/*
692 * Find a file in a search context.
693 * The search context was created with vim_findfile_init() above.
694 * Return a pointer to an allocated file name or NULL if nothing found.
695 * To get all matching files call this function until you get NULL.
696 *
697 * If the passed search_context is NULL, NULL is returned.
698 *
699 * The search algorithm is depth first. To change this replace the
700 * stack with a list (don't forget to leave partly searched directories on the
701 * top of the list).
702 */
703 char_u *
704vim_findfile(void *search_ctx_arg)
705{
706 char_u *file_path;
707#ifdef FEAT_PATH_EXTRA
708 char_u *rest_of_wildcards;
709 char_u *path_end = NULL;
710#endif
711 ff_stack_T *stackp;
712#if defined(FEAT_SEARCHPATH) || defined(FEAT_PATH_EXTRA)
713 int len;
714#endif
715 int i;
716 char_u *p;
717#ifdef FEAT_SEARCHPATH
718 char_u *suf;
719#endif
720 ff_search_ctx_T *search_ctx;
721
722 if (search_ctx_arg == NULL)
723 return NULL;
724
725 search_ctx = (ff_search_ctx_T *)search_ctx_arg;
726
727 /*
728 * filepath is used as buffer for various actions and as the storage to
729 * return a found filename.
730 */
Bram Moolenaar51e14382019-05-25 20:21:28 +0200731 if ((file_path = alloc(MAXPATHL)) == NULL)
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100732 return NULL;
733
734#ifdef FEAT_PATH_EXTRA
735 // store the end of the start dir -- needed for upward search
736 if (search_ctx->ffsc_start_dir != NULL)
737 path_end = &search_ctx->ffsc_start_dir[
738 STRLEN(search_ctx->ffsc_start_dir)];
739#endif
740
741#ifdef FEAT_PATH_EXTRA
742 // upward search loop
743 for (;;)
744 {
745#endif
746 // downward search loop
747 for (;;)
748 {
Dominique Pelleaf4a61a2021-12-27 17:21:41 +0000749 // check if user wants to stop the search
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100750 ui_breakcheck();
751 if (got_int)
752 break;
753
754 // get directory to work on from stack
755 stackp = ff_pop(search_ctx);
756 if (stackp == NULL)
757 break;
758
759 /*
760 * TODO: decide if we leave this test in
761 *
762 * GOOD: don't search a directory(-tree) twice.
763 * BAD: - check linked list for every new directory entered.
764 * - check for double files also done below
765 *
766 * Here we check if we already searched this directory.
767 * We already searched a directory if:
768 * 1) The directory is the same.
769 * 2) We would use the same wildcard string.
770 *
771 * Good if you have links on same directory via several ways
772 * or you have selfreferences in directories (e.g. SuSE Linux 6.3:
773 * /etc/rc.d/init.d is linked to /etc/rc.d -> endless loop)
774 *
775 * This check is only needed for directories we work on for the
776 * first time (hence stackp->ff_filearray == NULL)
777 */
778 if (stackp->ffs_filearray == NULL
779 && ff_check_visited(&search_ctx->ffsc_dir_visited_list
780 ->ffvl_visited_list,
781 stackp->ffs_fix_path
782#ifdef FEAT_PATH_EXTRA
783 , stackp->ffs_wc_path
784#endif
785 ) == FAIL)
786 {
787#ifdef FF_VERBOSE
788 if (p_verbose >= 5)
789 {
790 verbose_enter_scroll();
791 smsg("Already Searched: %s (%s)",
792 stackp->ffs_fix_path, stackp->ffs_wc_path);
793 // don't overwrite this either
794 msg_puts("\n");
795 verbose_leave_scroll();
796 }
797#endif
798 ff_free_stack_element(stackp);
799 continue;
800 }
801#ifdef FF_VERBOSE
802 else if (p_verbose >= 5)
803 {
804 verbose_enter_scroll();
805 smsg("Searching: %s (%s)",
806 stackp->ffs_fix_path, stackp->ffs_wc_path);
807 // don't overwrite this either
808 msg_puts("\n");
809 verbose_leave_scroll();
810 }
811#endif
812
813 // check depth
814 if (stackp->ffs_level <= 0)
815 {
816 ff_free_stack_element(stackp);
817 continue;
818 }
819
820 file_path[0] = NUL;
821
822 /*
823 * If no filearray till now expand wildcards
824 * The function expand_wildcards() can handle an array of paths
825 * and all possible expands are returned in one array. We use this
826 * to handle the expansion of '**' into an empty string.
827 */
828 if (stackp->ffs_filearray == NULL)
829 {
830 char_u *dirptrs[2];
831
832 // we use filepath to build the path expand_wildcards() should
833 // expand.
834 dirptrs[0] = file_path;
835 dirptrs[1] = NULL;
836
837 // if we have a start dir copy it in
838 if (!vim_isAbsName(stackp->ffs_fix_path)
839 && search_ctx->ffsc_start_dir)
840 {
841 if (STRLEN(search_ctx->ffsc_start_dir) + 1 < MAXPATHL)
842 {
843 STRCPY(file_path, search_ctx->ffsc_start_dir);
844 add_pathsep(file_path);
845 }
846 else
847 {
848 ff_free_stack_element(stackp);
849 goto fail;
850 }
851 }
852
853 // append the fix part of the search path
854 if (STRLEN(file_path) + STRLEN(stackp->ffs_fix_path) + 1
855 < MAXPATHL)
856 {
857 STRCAT(file_path, stackp->ffs_fix_path);
858 add_pathsep(file_path);
859 }
860 else
861 {
862 ff_free_stack_element(stackp);
863 goto fail;
864 }
865
866#ifdef FEAT_PATH_EXTRA
867 rest_of_wildcards = stackp->ffs_wc_path;
868 if (*rest_of_wildcards != NUL)
869 {
870 len = (int)STRLEN(file_path);
871 if (STRNCMP(rest_of_wildcards, "**", 2) == 0)
872 {
873 // pointer to the restrict byte
874 // The restrict byte is not a character!
875 p = rest_of_wildcards + 2;
876
877 if (*p > 0)
878 {
879 (*p)--;
880 if (len + 1 < MAXPATHL)
881 file_path[len++] = '*';
882 else
883 {
884 ff_free_stack_element(stackp);
885 goto fail;
886 }
887 }
888
889 if (*p == 0)
890 {
891 // remove '**<numb> from wildcards
892 STRMOVE(rest_of_wildcards, rest_of_wildcards + 3);
893 }
894 else
895 rest_of_wildcards += 3;
896
897 if (stackp->ffs_star_star_empty == 0)
898 {
899 // if not done before, expand '**' to empty
900 stackp->ffs_star_star_empty = 1;
901 dirptrs[1] = stackp->ffs_fix_path;
902 }
903 }
904
905 /*
906 * Here we copy until the next path separator or the end of
907 * the path. If we stop at a path separator, there is
908 * still something else left. This is handled below by
909 * pushing every directory returned from expand_wildcards()
910 * on the stack again for further search.
911 */
912 while (*rest_of_wildcards
913 && !vim_ispathsep(*rest_of_wildcards))
914 if (len + 1 < MAXPATHL)
915 file_path[len++] = *rest_of_wildcards++;
916 else
917 {
918 ff_free_stack_element(stackp);
919 goto fail;
920 }
921
922 file_path[len] = NUL;
923 if (vim_ispathsep(*rest_of_wildcards))
924 rest_of_wildcards++;
925 }
926#endif
927
928 /*
929 * Expand wildcards like "*" and "$VAR".
930 * If the path is a URL don't try this.
931 */
932 if (path_with_url(dirptrs[0]))
933 {
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200934 stackp->ffs_filearray = ALLOC_ONE(char_u *);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100935 if (stackp->ffs_filearray != NULL
936 && (stackp->ffs_filearray[0]
937 = vim_strsave(dirptrs[0])) != NULL)
938 stackp->ffs_filearray_size = 1;
939 else
940 stackp->ffs_filearray_size = 0;
941 }
942 else
943 // Add EW_NOTWILD because the expanded path may contain
944 // wildcard characters that are to be taken literally.
945 // This is a bit of a hack.
946 expand_wildcards((dirptrs[1] == NULL) ? 1 : 2, dirptrs,
947 &stackp->ffs_filearray_size,
948 &stackp->ffs_filearray,
949 EW_DIR|EW_ADDSLASH|EW_SILENT|EW_NOTWILD);
950
951 stackp->ffs_filearray_cur = 0;
952 stackp->ffs_stage = 0;
953 }
954#ifdef FEAT_PATH_EXTRA
955 else
956 rest_of_wildcards = &stackp->ffs_wc_path[
957 STRLEN(stackp->ffs_wc_path)];
958#endif
959
960 if (stackp->ffs_stage == 0)
961 {
962 // this is the first time we work on this directory
963#ifdef FEAT_PATH_EXTRA
964 if (*rest_of_wildcards == NUL)
965#endif
966 {
967 /*
968 * We don't have further wildcards to expand, so we have to
969 * check for the final file now.
970 */
971 for (i = stackp->ffs_filearray_cur;
972 i < stackp->ffs_filearray_size; ++i)
973 {
974 if (!path_with_url(stackp->ffs_filearray[i])
975 && !mch_isdir(stackp->ffs_filearray[i]))
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100976 continue; // not a directory
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100977
978 // prepare the filename to be checked for existence
979 // below
980 if (STRLEN(stackp->ffs_filearray[i]) + 1
981 + STRLEN(search_ctx->ffsc_file_to_search)
982 < MAXPATHL)
983 {
984 STRCPY(file_path, stackp->ffs_filearray[i]);
985 add_pathsep(file_path);
986 STRCAT(file_path, search_ctx->ffsc_file_to_search);
987 }
988 else
989 {
990 ff_free_stack_element(stackp);
991 goto fail;
992 }
993
994 /*
995 * Try without extra suffix and then with suffixes
996 * from 'suffixesadd'.
997 */
998#ifdef FEAT_SEARCHPATH
999 len = (int)STRLEN(file_path);
1000 if (search_ctx->ffsc_tagfile)
1001 suf = (char_u *)"";
1002 else
1003 suf = curbuf->b_p_sua;
1004 for (;;)
1005#endif
1006 {
1007 // if file exists and we didn't already find it
1008 if ((path_with_url(file_path)
1009 || (mch_getperm(file_path) >= 0
1010 && (search_ctx->ffsc_find_what
1011 == FINDFILE_BOTH
1012 || ((search_ctx->ffsc_find_what
1013 == FINDFILE_DIR)
1014 == mch_isdir(file_path)))))
1015#ifndef FF_VERBOSE
1016 && (ff_check_visited(
1017 &search_ctx->ffsc_visited_list->ffvl_visited_list,
1018 file_path
1019#ifdef FEAT_PATH_EXTRA
1020 , (char_u *)""
1021#endif
1022 ) == OK)
1023#endif
1024 )
1025 {
1026#ifdef FF_VERBOSE
1027 if (ff_check_visited(
1028 &search_ctx->ffsc_visited_list->ffvl_visited_list,
1029 file_path
1030#ifdef FEAT_PATH_EXTRA
1031 , (char_u *)""
1032#endif
1033 ) == FAIL)
1034 {
1035 if (p_verbose >= 5)
1036 {
1037 verbose_enter_scroll();
1038 smsg("Already: %s",
1039 file_path);
1040 // don't overwrite this either
1041 msg_puts("\n");
1042 verbose_leave_scroll();
1043 }
1044 continue;
1045 }
1046#endif
1047
1048 // push dir to examine rest of subdirs later
1049 stackp->ffs_filearray_cur = i + 1;
1050 ff_push(search_ctx, stackp);
1051
1052 if (!path_with_url(file_path))
1053 simplify_filename(file_path);
1054 if (mch_dirname(ff_expand_buffer, MAXPATHL)
1055 == OK)
1056 {
1057 p = shorten_fname(file_path,
1058 ff_expand_buffer);
1059 if (p != NULL)
1060 STRMOVE(file_path, p);
1061 }
1062#ifdef FF_VERBOSE
1063 if (p_verbose >= 5)
1064 {
1065 verbose_enter_scroll();
1066 smsg("HIT: %s", file_path);
1067 // don't overwrite this either
1068 msg_puts("\n");
1069 verbose_leave_scroll();
1070 }
1071#endif
1072 return file_path;
1073 }
1074
1075#ifdef FEAT_SEARCHPATH
1076 // Not found or found already, try next suffix.
1077 if (*suf == NUL)
1078 break;
1079 copy_option_part(&suf, file_path + len,
1080 MAXPATHL - len, ",");
1081#endif
1082 }
1083 }
1084 }
1085#ifdef FEAT_PATH_EXTRA
1086 else
1087 {
1088 /*
1089 * still wildcards left, push the directories for further
1090 * search
1091 */
1092 for (i = stackp->ffs_filearray_cur;
1093 i < stackp->ffs_filearray_size; ++i)
1094 {
1095 if (!mch_isdir(stackp->ffs_filearray[i]))
1096 continue; // not a directory
1097
1098 ff_push(search_ctx,
1099 ff_create_stack_element(
1100 stackp->ffs_filearray[i],
1101 rest_of_wildcards,
1102 stackp->ffs_level - 1, 0));
1103 }
1104 }
1105#endif
1106 stackp->ffs_filearray_cur = 0;
1107 stackp->ffs_stage = 1;
1108 }
1109
1110#ifdef FEAT_PATH_EXTRA
1111 /*
1112 * if wildcards contains '**' we have to descent till we reach the
1113 * leaves of the directory tree.
1114 */
1115 if (STRNCMP(stackp->ffs_wc_path, "**", 2) == 0)
1116 {
1117 for (i = stackp->ffs_filearray_cur;
1118 i < stackp->ffs_filearray_size; ++i)
1119 {
1120 if (fnamecmp(stackp->ffs_filearray[i],
1121 stackp->ffs_fix_path) == 0)
1122 continue; // don't repush same directory
1123 if (!mch_isdir(stackp->ffs_filearray[i]))
1124 continue; // not a directory
1125 ff_push(search_ctx,
1126 ff_create_stack_element(stackp->ffs_filearray[i],
1127 stackp->ffs_wc_path, stackp->ffs_level - 1, 1));
1128 }
1129 }
1130#endif
1131
1132 // we are done with the current directory
1133 ff_free_stack_element(stackp);
1134
1135 }
1136
1137#ifdef FEAT_PATH_EXTRA
1138 // If we reached this, we didn't find anything downwards.
1139 // Let's check if we should do an upward search.
1140 if (search_ctx->ffsc_start_dir
1141 && search_ctx->ffsc_stopdirs_v != NULL && !got_int)
1142 {
1143 ff_stack_T *sptr;
1144
1145 // is the last starting directory in the stop list?
1146 if (ff_path_in_stoplist(search_ctx->ffsc_start_dir,
1147 (int)(path_end - search_ctx->ffsc_start_dir),
1148 search_ctx->ffsc_stopdirs_v) == TRUE)
1149 break;
1150
1151 // cut of last dir
1152 while (path_end > search_ctx->ffsc_start_dir
1153 && vim_ispathsep(*path_end))
1154 path_end--;
1155 while (path_end > search_ctx->ffsc_start_dir
1156 && !vim_ispathsep(path_end[-1]))
1157 path_end--;
1158 *path_end = 0;
1159 path_end--;
1160
1161 if (*search_ctx->ffsc_start_dir == 0)
1162 break;
1163
1164 if (STRLEN(search_ctx->ffsc_start_dir) + 1
1165 + STRLEN(search_ctx->ffsc_fix_path) < MAXPATHL)
1166 {
1167 STRCPY(file_path, search_ctx->ffsc_start_dir);
1168 add_pathsep(file_path);
1169 STRCAT(file_path, search_ctx->ffsc_fix_path);
1170 }
1171 else
1172 goto fail;
1173
1174 // create a new stack entry
1175 sptr = ff_create_stack_element(file_path,
1176 search_ctx->ffsc_wc_path, search_ctx->ffsc_level, 0);
1177 if (sptr == NULL)
1178 break;
1179 ff_push(search_ctx, sptr);
1180 }
1181 else
1182 break;
1183 }
1184#endif
1185
1186fail:
1187 vim_free(file_path);
1188 return NULL;
1189}
1190
1191/*
1192 * Free the list of lists of visited files and directories
1193 * Can handle it if the passed search_context is NULL;
1194 */
Bram Moolenaar5843f5f2019-08-20 20:13:45 +02001195 static void
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001196vim_findfile_free_visited(void *search_ctx_arg)
1197{
1198 ff_search_ctx_T *search_ctx;
1199
1200 if (search_ctx_arg == NULL)
1201 return;
1202
1203 search_ctx = (ff_search_ctx_T *)search_ctx_arg;
1204 vim_findfile_free_visited_list(&search_ctx->ffsc_visited_lists_list);
1205 vim_findfile_free_visited_list(&search_ctx->ffsc_dir_visited_lists_list);
1206}
1207
1208 static void
1209vim_findfile_free_visited_list(ff_visited_list_hdr_T **list_headp)
1210{
1211 ff_visited_list_hdr_T *vp;
1212
1213 while (*list_headp != NULL)
1214 {
1215 vp = (*list_headp)->ffvl_next;
1216 ff_free_visited_list((*list_headp)->ffvl_visited_list);
1217
1218 vim_free((*list_headp)->ffvl_filename);
1219 vim_free(*list_headp);
1220 *list_headp = vp;
1221 }
1222 *list_headp = NULL;
1223}
1224
1225 static void
1226ff_free_visited_list(ff_visited_T *vl)
1227{
1228 ff_visited_T *vp;
1229
1230 while (vl != NULL)
1231 {
1232 vp = vl->ffv_next;
1233#ifdef FEAT_PATH_EXTRA
1234 vim_free(vl->ffv_wc_path);
1235#endif
1236 vim_free(vl);
1237 vl = vp;
1238 }
1239 vl = NULL;
1240}
1241
1242/*
1243 * Returns the already visited list for the given filename. If none is found it
1244 * allocates a new one.
1245 */
1246 static ff_visited_list_hdr_T*
1247ff_get_visited_list(
1248 char_u *filename,
1249 ff_visited_list_hdr_T **list_headp)
1250{
1251 ff_visited_list_hdr_T *retptr = NULL;
1252
1253 // check if a visited list for the given filename exists
1254 if (*list_headp != NULL)
1255 {
1256 retptr = *list_headp;
1257 while (retptr != NULL)
1258 {
1259 if (fnamecmp(filename, retptr->ffvl_filename) == 0)
1260 {
1261#ifdef FF_VERBOSE
1262 if (p_verbose >= 5)
1263 {
1264 verbose_enter_scroll();
1265 smsg("ff_get_visited_list: FOUND list for %s",
1266 filename);
1267 // don't overwrite this either
1268 msg_puts("\n");
1269 verbose_leave_scroll();
1270 }
1271#endif
1272 return retptr;
1273 }
1274 retptr = retptr->ffvl_next;
1275 }
1276 }
1277
1278#ifdef FF_VERBOSE
1279 if (p_verbose >= 5)
1280 {
1281 verbose_enter_scroll();
1282 smsg("ff_get_visited_list: new list for %s", filename);
1283 // don't overwrite this either
1284 msg_puts("\n");
1285 verbose_leave_scroll();
1286 }
1287#endif
1288
1289 /*
1290 * if we reach this we didn't find a list and we have to allocate new list
1291 */
Bram Moolenaarc799fe22019-05-28 23:08:19 +02001292 retptr = ALLOC_ONE(ff_visited_list_hdr_T);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001293 if (retptr == NULL)
1294 return NULL;
1295
1296 retptr->ffvl_visited_list = NULL;
1297 retptr->ffvl_filename = vim_strsave(filename);
1298 if (retptr->ffvl_filename == NULL)
1299 {
1300 vim_free(retptr);
1301 return NULL;
1302 }
1303 retptr->ffvl_next = *list_headp;
1304 *list_headp = retptr;
1305
1306 return retptr;
1307}
1308
1309#ifdef FEAT_PATH_EXTRA
1310/*
1311 * check if two wildcard paths are equal. Returns TRUE or FALSE.
1312 * They are equal if:
1313 * - both paths are NULL
1314 * - they have the same length
1315 * - char by char comparison is OK
1316 * - the only differences are in the counters behind a '**', so
1317 * '**\20' is equal to '**\24'
1318 */
1319 static int
1320ff_wc_equal(char_u *s1, char_u *s2)
1321{
1322 int i, j;
1323 int c1 = NUL;
1324 int c2 = NUL;
1325 int prev1 = NUL;
1326 int prev2 = NUL;
1327
1328 if (s1 == s2)
1329 return TRUE;
1330
1331 if (s1 == NULL || s2 == NULL)
1332 return FALSE;
1333
1334 for (i = 0, j = 0; s1[i] != NUL && s2[j] != NUL;)
1335 {
1336 c1 = PTR2CHAR(s1 + i);
1337 c2 = PTR2CHAR(s2 + j);
1338
1339 if ((p_fic ? MB_TOLOWER(c1) != MB_TOLOWER(c2) : c1 != c2)
1340 && (prev1 != '*' || prev2 != '*'))
1341 return FALSE;
1342 prev2 = prev1;
1343 prev1 = c1;
1344
Bram Moolenaar1614a142019-10-06 22:00:13 +02001345 i += mb_ptr2len(s1 + i);
1346 j += mb_ptr2len(s2 + j);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001347 }
1348 return s1[i] == s2[j];
1349}
1350#endif
1351
1352/*
1353 * maintains the list of already visited files and dirs
1354 * returns FAIL if the given file/dir is already in the list
1355 * returns OK if it is newly added
1356 *
1357 * TODO: What to do on memory allocation problems?
1358 * -> return TRUE - Better the file is found several times instead of
1359 * never.
1360 */
1361 static int
1362ff_check_visited(
1363 ff_visited_T **visited_list,
1364 char_u *fname
1365#ifdef FEAT_PATH_EXTRA
1366 , char_u *wc_path
1367#endif
1368 )
1369{
1370 ff_visited_T *vp;
1371#ifdef UNIX
1372 stat_T st;
1373 int url = FALSE;
1374#endif
1375
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00001376 // For a URL we only compare the name, otherwise we compare the
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001377 // device/inode (unix) or the full path name (not Unix).
1378 if (path_with_url(fname))
1379 {
1380 vim_strncpy(ff_expand_buffer, fname, MAXPATHL - 1);
1381#ifdef UNIX
1382 url = TRUE;
1383#endif
1384 }
1385 else
1386 {
1387 ff_expand_buffer[0] = NUL;
1388#ifdef UNIX
1389 if (mch_stat((char *)fname, &st) < 0)
1390#else
1391 if (vim_FullName(fname, ff_expand_buffer, MAXPATHL, TRUE) == FAIL)
1392#endif
1393 return FAIL;
1394 }
1395
1396 // check against list of already visited files
1397 for (vp = *visited_list; vp != NULL; vp = vp->ffv_next)
1398 {
1399 if (
1400#ifdef UNIX
1401 !url ? (vp->ffv_dev_valid && vp->ffv_dev == st.st_dev
1402 && vp->ffv_ino == st.st_ino)
1403 :
1404#endif
1405 fnamecmp(vp->ffv_fname, ff_expand_buffer) == 0
1406 )
1407 {
1408#ifdef FEAT_PATH_EXTRA
1409 // are the wildcard parts equal
1410 if (ff_wc_equal(vp->ffv_wc_path, wc_path) == TRUE)
1411#endif
1412 // already visited
1413 return FAIL;
1414 }
1415 }
1416
1417 /*
1418 * New file/dir. Add it to the list of visited files/dirs.
1419 */
Bram Moolenaarc799fe22019-05-28 23:08:19 +02001420 vp = alloc(sizeof(ff_visited_T) + STRLEN(ff_expand_buffer));
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001421
1422 if (vp != NULL)
1423 {
1424#ifdef UNIX
1425 if (!url)
1426 {
1427 vp->ffv_dev_valid = TRUE;
1428 vp->ffv_ino = st.st_ino;
1429 vp->ffv_dev = st.st_dev;
1430 vp->ffv_fname[0] = NUL;
1431 }
1432 else
1433 {
1434 vp->ffv_dev_valid = FALSE;
1435#endif
1436 STRCPY(vp->ffv_fname, ff_expand_buffer);
1437#ifdef UNIX
1438 }
1439#endif
1440#ifdef FEAT_PATH_EXTRA
1441 if (wc_path != NULL)
1442 vp->ffv_wc_path = vim_strsave(wc_path);
1443 else
1444 vp->ffv_wc_path = NULL;
1445#endif
1446
1447 vp->ffv_next = *visited_list;
1448 *visited_list = vp;
1449 }
1450
1451 return OK;
1452}
1453
1454/*
1455 * create stack element from given path pieces
1456 */
1457 static ff_stack_T *
1458ff_create_stack_element(
1459 char_u *fix_part,
1460#ifdef FEAT_PATH_EXTRA
1461 char_u *wc_part,
1462#endif
1463 int level,
1464 int star_star_empty)
1465{
1466 ff_stack_T *new;
1467
Bram Moolenaarc799fe22019-05-28 23:08:19 +02001468 new = ALLOC_ONE(ff_stack_T);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001469 if (new == NULL)
1470 return NULL;
1471
1472 new->ffs_prev = NULL;
1473 new->ffs_filearray = NULL;
1474 new->ffs_filearray_size = 0;
1475 new->ffs_filearray_cur = 0;
1476 new->ffs_stage = 0;
1477 new->ffs_level = level;
1478 new->ffs_star_star_empty = star_star_empty;
1479
1480 // the following saves NULL pointer checks in vim_findfile
1481 if (fix_part == NULL)
1482 fix_part = (char_u *)"";
1483 new->ffs_fix_path = vim_strsave(fix_part);
1484
1485#ifdef FEAT_PATH_EXTRA
1486 if (wc_part == NULL)
1487 wc_part = (char_u *)"";
1488 new->ffs_wc_path = vim_strsave(wc_part);
1489#endif
1490
1491 if (new->ffs_fix_path == NULL
1492#ifdef FEAT_PATH_EXTRA
1493 || new->ffs_wc_path == NULL
1494#endif
1495 )
1496 {
1497 ff_free_stack_element(new);
1498 new = NULL;
1499 }
1500
1501 return new;
1502}
1503
1504/*
1505 * Push a dir on the directory stack.
1506 */
1507 static void
1508ff_push(ff_search_ctx_T *search_ctx, ff_stack_T *stack_ptr)
1509{
1510 // check for NULL pointer, not to return an error to the user, but
1511 // to prevent a crash
1512 if (stack_ptr != NULL)
1513 {
1514 stack_ptr->ffs_prev = search_ctx->ffsc_stack_ptr;
1515 search_ctx->ffsc_stack_ptr = stack_ptr;
1516 }
1517}
1518
1519/*
1520 * Pop a dir from the directory stack.
1521 * Returns NULL if stack is empty.
1522 */
1523 static ff_stack_T *
1524ff_pop(ff_search_ctx_T *search_ctx)
1525{
1526 ff_stack_T *sptr;
1527
1528 sptr = search_ctx->ffsc_stack_ptr;
1529 if (search_ctx->ffsc_stack_ptr != NULL)
1530 search_ctx->ffsc_stack_ptr = search_ctx->ffsc_stack_ptr->ffs_prev;
1531
1532 return sptr;
1533}
1534
1535/*
1536 * free the given stack element
1537 */
1538 static void
1539ff_free_stack_element(ff_stack_T *stack_ptr)
1540{
1541 // vim_free handles possible NULL pointers
1542 vim_free(stack_ptr->ffs_fix_path);
1543#ifdef FEAT_PATH_EXTRA
1544 vim_free(stack_ptr->ffs_wc_path);
1545#endif
1546
1547 if (stack_ptr->ffs_filearray != NULL)
1548 FreeWild(stack_ptr->ffs_filearray_size, stack_ptr->ffs_filearray);
1549
1550 vim_free(stack_ptr);
1551}
1552
1553/*
1554 * Clear the search context, but NOT the visited list.
1555 */
1556 static void
1557ff_clear(ff_search_ctx_T *search_ctx)
1558{
1559 ff_stack_T *sptr;
1560
1561 // clear up stack
1562 while ((sptr = ff_pop(search_ctx)) != NULL)
1563 ff_free_stack_element(sptr);
1564
1565 vim_free(search_ctx->ffsc_file_to_search);
1566 vim_free(search_ctx->ffsc_start_dir);
1567 vim_free(search_ctx->ffsc_fix_path);
1568#ifdef FEAT_PATH_EXTRA
1569 vim_free(search_ctx->ffsc_wc_path);
1570#endif
1571
1572#ifdef FEAT_PATH_EXTRA
1573 if (search_ctx->ffsc_stopdirs_v != NULL)
1574 {
1575 int i = 0;
1576
1577 while (search_ctx->ffsc_stopdirs_v[i] != NULL)
1578 {
1579 vim_free(search_ctx->ffsc_stopdirs_v[i]);
1580 i++;
1581 }
1582 vim_free(search_ctx->ffsc_stopdirs_v);
1583 }
1584 search_ctx->ffsc_stopdirs_v = NULL;
1585#endif
1586
1587 // reset everything
1588 search_ctx->ffsc_file_to_search = NULL;
1589 search_ctx->ffsc_start_dir = NULL;
1590 search_ctx->ffsc_fix_path = NULL;
1591#ifdef FEAT_PATH_EXTRA
1592 search_ctx->ffsc_wc_path = NULL;
1593 search_ctx->ffsc_level = 0;
1594#endif
1595}
1596
1597#ifdef FEAT_PATH_EXTRA
1598/*
1599 * check if the given path is in the stopdirs
1600 * returns TRUE if yes else FALSE
1601 */
1602 static int
1603ff_path_in_stoplist(char_u *path, int path_len, char_u **stopdirs_v)
1604{
1605 int i = 0;
1606
1607 // eat up trailing path separators, except the first
1608 while (path_len > 1 && vim_ispathsep(path[path_len - 1]))
1609 path_len--;
1610
1611 // if no path consider it as match
1612 if (path_len == 0)
1613 return TRUE;
1614
1615 for (i = 0; stopdirs_v[i] != NULL; i++)
1616 {
1617 if ((int)STRLEN(stopdirs_v[i]) > path_len)
1618 {
1619 // match for parent directory. So '/home' also matches
1620 // '/home/rks'. Check for PATHSEP in stopdirs_v[i], else
1621 // '/home/r' would also match '/home/rks'
1622 if (fnamencmp(stopdirs_v[i], path, path_len) == 0
1623 && vim_ispathsep(stopdirs_v[i][path_len]))
1624 return TRUE;
1625 }
1626 else
1627 {
1628 if (fnamecmp(stopdirs_v[i], path) == 0)
1629 return TRUE;
1630 }
1631 }
1632 return FALSE;
1633}
1634#endif
1635
1636#if defined(FEAT_SEARCHPATH) || defined(PROTO)
1637/*
1638 * Find the file name "ptr[len]" in the path. Also finds directory names.
1639 *
1640 * On the first call set the parameter 'first' to TRUE to initialize
1641 * the search. For repeating calls to FALSE.
1642 *
1643 * Repeating calls will return other files called 'ptr[len]' from the path.
1644 *
1645 * Only on the first call 'ptr' and 'len' are used. For repeating calls they
1646 * don't need valid values.
1647 *
1648 * If nothing found on the first call the option FNAME_MESS will issue the
1649 * message:
1650 * 'Can't find file "<file>" in path'
1651 * On repeating calls:
1652 * 'No more file "<file>" found in path'
1653 *
1654 * options:
1655 * FNAME_MESS give error message when not found
1656 *
1657 * Uses NameBuff[]!
1658 *
1659 * Returns an allocated string for the file name. NULL for error.
1660 *
1661 */
1662 char_u *
1663find_file_in_path(
1664 char_u *ptr, // file name
1665 int len, // length of file name
1666 int options,
1667 int first, // use count'th matching file name
1668 char_u *rel_fname) // file name searching relative to
1669{
1670 return find_file_in_path_option(ptr, len, options, first,
1671 *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path,
1672 FINDFILE_BOTH, rel_fname, curbuf->b_p_sua);
1673}
1674
1675static char_u *ff_file_to_find = NULL;
1676static void *fdip_search_ctx = NULL;
1677
1678# if defined(EXITFREE) || defined(PROTO)
1679 void
1680free_findfile(void)
1681{
1682 vim_free(ff_file_to_find);
1683 vim_findfile_cleanup(fdip_search_ctx);
1684 vim_free(ff_expand_buffer);
1685}
1686# endif
1687
1688/*
1689 * Find the directory name "ptr[len]" in the path.
1690 *
1691 * options:
1692 * FNAME_MESS give error message when not found
1693 * FNAME_UNESC unescape backslashes.
1694 *
1695 * Uses NameBuff[]!
1696 *
1697 * Returns an allocated string for the file name. NULL for error.
1698 */
1699 char_u *
1700find_directory_in_path(
1701 char_u *ptr, // file name
1702 int len, // length of file name
1703 int options,
1704 char_u *rel_fname) // file name searching relative to
1705{
1706 return find_file_in_path_option(ptr, len, options, TRUE, p_cdpath,
1707 FINDFILE_DIR, rel_fname, (char_u *)"");
1708}
1709
1710 char_u *
1711find_file_in_path_option(
1712 char_u *ptr, // file name
1713 int len, // length of file name
1714 int options,
1715 int first, // use count'th matching file name
1716 char_u *path_option, // p_path or p_cdpath
1717 int find_what, // FINDFILE_FILE, _DIR or _BOTH
1718 char_u *rel_fname, // file name we are looking relative to.
1719 char_u *suffixes) // list of suffixes, 'suffixesadd' option
1720{
1721 static char_u *dir;
1722 static int did_findfile_init = FALSE;
1723 char_u save_char;
1724 char_u *file_name = NULL;
1725 char_u *buf = NULL;
1726 int rel_to_curdir;
1727# ifdef AMIGA
1728 struct Process *proc = (struct Process *)FindTask(0L);
1729 APTR save_winptr = proc->pr_WindowPtr;
1730
1731 // Avoid a requester here for a volume that doesn't exist.
1732 proc->pr_WindowPtr = (APTR)-1L;
1733# endif
1734
1735 if (first == TRUE)
1736 {
Bram Moolenaare015d992021-11-17 19:01:53 +00001737 if (len == 0)
1738 return NULL;
1739
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001740 // copy file name into NameBuff, expanding environment variables
1741 save_char = ptr[len];
1742 ptr[len] = NUL;
1743 expand_env_esc(ptr, NameBuff, MAXPATHL, FALSE, TRUE, NULL);
1744 ptr[len] = save_char;
1745
1746 vim_free(ff_file_to_find);
1747 ff_file_to_find = vim_strsave(NameBuff);
1748 if (ff_file_to_find == NULL) // out of memory
1749 {
1750 file_name = NULL;
1751 goto theend;
1752 }
1753 if (options & FNAME_UNESC)
1754 {
1755 // Change all "\ " to " ".
1756 for (ptr = ff_file_to_find; *ptr != NUL; ++ptr)
1757 if (ptr[0] == '\\' && ptr[1] == ' ')
1758 mch_memmove(ptr, ptr + 1, STRLEN(ptr));
1759 }
1760 }
1761
1762 rel_to_curdir = (ff_file_to_find[0] == '.'
1763 && (ff_file_to_find[1] == NUL
1764 || vim_ispathsep(ff_file_to_find[1])
1765 || (ff_file_to_find[1] == '.'
1766 && (ff_file_to_find[2] == NUL
1767 || vim_ispathsep(ff_file_to_find[2])))));
1768 if (vim_isAbsName(ff_file_to_find)
1769 // "..", "../path", "." and "./path": don't use the path_option
1770 || rel_to_curdir
1771# if defined(MSWIN)
1772 // handle "\tmp" as absolute path
1773 || vim_ispathsep(ff_file_to_find[0])
1774 // handle "c:name" as absolute path
1775 || (ff_file_to_find[0] != NUL && ff_file_to_find[1] == ':')
1776# endif
1777# ifdef AMIGA
1778 // handle ":tmp" as absolute path
1779 || ff_file_to_find[0] == ':'
1780# endif
1781 )
1782 {
1783 /*
1784 * Absolute path, no need to use "path_option".
1785 * If this is not a first call, return NULL. We already returned a
1786 * filename on the first call.
1787 */
1788 if (first == TRUE)
1789 {
1790 int l;
1791 int run;
1792
1793 if (path_with_url(ff_file_to_find))
1794 {
1795 file_name = vim_strsave(ff_file_to_find);
1796 goto theend;
1797 }
1798
1799 // When FNAME_REL flag given first use the directory of the file.
1800 // Otherwise or when this fails use the current directory.
1801 for (run = 1; run <= 2; ++run)
1802 {
1803 l = (int)STRLEN(ff_file_to_find);
1804 if (run == 1
1805 && rel_to_curdir
1806 && (options & FNAME_REL)
1807 && rel_fname != NULL
1808 && STRLEN(rel_fname) + l < MAXPATHL)
1809 {
1810 STRCPY(NameBuff, rel_fname);
1811 STRCPY(gettail(NameBuff), ff_file_to_find);
1812 l = (int)STRLEN(NameBuff);
1813 }
1814 else
1815 {
1816 STRCPY(NameBuff, ff_file_to_find);
1817 run = 2;
1818 }
1819
1820 // When the file doesn't exist, try adding parts of
1821 // 'suffixesadd'.
1822 buf = suffixes;
1823 for (;;)
1824 {
1825 if (mch_getperm(NameBuff) >= 0
1826 && (find_what == FINDFILE_BOTH
1827 || ((find_what == FINDFILE_DIR)
1828 == mch_isdir(NameBuff))))
1829 {
1830 file_name = vim_strsave(NameBuff);
1831 goto theend;
1832 }
1833 if (*buf == NUL)
1834 break;
1835 copy_option_part(&buf, NameBuff + l, MAXPATHL - l, ",");
1836 }
1837 }
1838 }
1839 }
1840 else
1841 {
1842 /*
1843 * Loop over all paths in the 'path' or 'cdpath' option.
1844 * When "first" is set, first setup to the start of the option.
1845 * Otherwise continue to find the next match.
1846 */
1847 if (first == TRUE)
1848 {
1849 // vim_findfile_free_visited can handle a possible NULL pointer
1850 vim_findfile_free_visited(fdip_search_ctx);
1851 dir = path_option;
1852 did_findfile_init = FALSE;
1853 }
1854
1855 for (;;)
1856 {
1857 if (did_findfile_init)
1858 {
1859 file_name = vim_findfile(fdip_search_ctx);
1860 if (file_name != NULL)
1861 break;
1862
1863 did_findfile_init = FALSE;
1864 }
1865 else
1866 {
1867 char_u *r_ptr;
1868
1869 if (dir == NULL || *dir == NUL)
1870 {
1871 // We searched all paths of the option, now we can
1872 // free the search context.
1873 vim_findfile_cleanup(fdip_search_ctx);
1874 fdip_search_ctx = NULL;
1875 break;
1876 }
1877
Bram Moolenaar51e14382019-05-25 20:21:28 +02001878 if ((buf = alloc(MAXPATHL)) == NULL)
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001879 break;
1880
1881 // copy next path
1882 buf[0] = 0;
1883 copy_option_part(&dir, buf, MAXPATHL, " ,");
1884
1885# ifdef FEAT_PATH_EXTRA
1886 // get the stopdir string
1887 r_ptr = vim_findfile_stopdir(buf);
1888# else
1889 r_ptr = NULL;
1890# endif
1891 fdip_search_ctx = vim_findfile_init(buf, ff_file_to_find,
1892 r_ptr, 100, FALSE, find_what,
1893 fdip_search_ctx, FALSE, rel_fname);
1894 if (fdip_search_ctx != NULL)
1895 did_findfile_init = TRUE;
1896 vim_free(buf);
1897 }
1898 }
1899 }
1900 if (file_name == NULL && (options & FNAME_MESS))
1901 {
1902 if (first == TRUE)
1903 {
1904 if (find_what == FINDFILE_DIR)
Bram Moolenaareaaac012022-01-02 17:00:40 +00001905 semsg(_(e_cant_find_directory_str_in_cdpath),
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001906 ff_file_to_find);
1907 else
Bram Moolenaareaaac012022-01-02 17:00:40 +00001908 semsg(_(e_cant_find_file_str_in_path),
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001909 ff_file_to_find);
1910 }
1911 else
1912 {
1913 if (find_what == FINDFILE_DIR)
Bram Moolenaareaaac012022-01-02 17:00:40 +00001914 semsg(_(e_no_more_directory_str_found_in_cdpath),
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001915 ff_file_to_find);
1916 else
Bram Moolenaareaaac012022-01-02 17:00:40 +00001917 semsg(_(e_no_more_file_str_found_in_path),
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001918 ff_file_to_find);
1919 }
1920 }
1921
1922theend:
1923# ifdef AMIGA
1924 proc->pr_WindowPtr = save_winptr;
1925# endif
1926 return file_name;
1927}
1928
1929/*
1930 * Get the file name at the cursor.
1931 * If Visual mode is active, use the selected text if it's in one line.
1932 * Returns the name in allocated memory, NULL for failure.
1933 */
1934 char_u *
1935grab_file_name(long count, linenr_T *file_lnum)
1936{
1937 int options = FNAME_MESS|FNAME_EXP|FNAME_REL|FNAME_UNESC;
1938
1939 if (VIsual_active)
1940 {
1941 int len;
1942 char_u *ptr;
1943
1944 if (get_visual_text(NULL, &ptr, &len) == FAIL)
1945 return NULL;
Bram Moolenaarefd5d8a2020-09-14 19:11:45 +02001946 // Only recognize ":123" here
1947 if (file_lnum != NULL && ptr[len] == ':' && isdigit(ptr[len + 1]))
1948 {
1949 char_u *p = ptr + len + 1;
1950
1951 *file_lnum = getdigits(&p);
1952 }
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001953 return find_file_name_in_path(ptr, len, options,
1954 count, curbuf->b_ffname);
1955 }
1956 return file_name_at_cursor(options | FNAME_HYP, count, file_lnum);
1957}
1958
1959/*
1960 * Return the file name under or after the cursor.
1961 *
1962 * The 'path' option is searched if the file name is not absolute.
1963 * The string returned has been alloc'ed and should be freed by the caller.
1964 * NULL is returned if the file name or file is not found.
1965 *
1966 * options:
1967 * FNAME_MESS give error messages
1968 * FNAME_EXP expand to path
1969 * FNAME_HYP check for hypertext link
1970 * FNAME_INCL apply "includeexpr"
1971 */
1972 char_u *
1973file_name_at_cursor(int options, long count, linenr_T *file_lnum)
1974{
1975 return file_name_in_line(ml_get_curline(),
1976 curwin->w_cursor.col, options, count, curbuf->b_ffname,
1977 file_lnum);
1978}
1979
1980/*
1981 * Return the name of the file under or after ptr[col].
1982 * Otherwise like file_name_at_cursor().
1983 */
1984 char_u *
1985file_name_in_line(
1986 char_u *line,
1987 int col,
1988 int options,
1989 long count,
1990 char_u *rel_fname, // file we are searching relative to
1991 linenr_T *file_lnum) // line number after the file name
1992{
1993 char_u *ptr;
1994 int len;
1995 int in_type = TRUE;
1996 int is_url = FALSE;
1997
1998 /*
1999 * search forward for what could be the start of a file name
2000 */
2001 ptr = line + col;
2002 while (*ptr != NUL && !vim_isfilec(*ptr))
2003 MB_PTR_ADV(ptr);
2004 if (*ptr == NUL) // nothing found
2005 {
2006 if (options & FNAME_MESS)
Bram Moolenaarac78dd42022-01-02 19:25:26 +00002007 emsg(_(e_no_file_name_under_cursor));
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002008 return NULL;
2009 }
2010
2011 /*
2012 * Search backward for first char of the file name.
2013 * Go one char back to ":" before "//" even when ':' is not in 'isfname'.
2014 */
2015 while (ptr > line)
2016 {
2017 if (has_mbyte && (len = (*mb_head_off)(line, ptr - 1)) > 0)
2018 ptr -= len + 1;
2019 else if (vim_isfilec(ptr[-1])
2020 || ((options & FNAME_HYP) && path_is_url(ptr - 1)))
2021 --ptr;
2022 else
2023 break;
2024 }
2025
2026 /*
2027 * Search forward for the last char of the file name.
2028 * Also allow "://" when ':' is not in 'isfname'.
2029 */
2030 len = 0;
2031 while (vim_isfilec(ptr[len]) || (ptr[len] == '\\' && ptr[len + 1] == ' ')
2032 || ((options & FNAME_HYP) && path_is_url(ptr + len))
Bram Moolenaarcbef8e12019-03-09 12:32:56 +01002033 || (is_url && vim_strchr((char_u *)":?&=", ptr[len]) != NULL))
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002034 {
Bram Moolenaarcbef8e12019-03-09 12:32:56 +01002035 // After type:// we also include :, ?, & and = as valid characters, so that
2036 // http://google.com:8080?q=this&that=ok works.
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002037 if ((ptr[len] >= 'A' && ptr[len] <= 'Z') || (ptr[len] >= 'a' && ptr[len] <= 'z'))
2038 {
2039 if (in_type && path_is_url(ptr + len + 1))
2040 is_url = TRUE;
2041 }
2042 else
2043 in_type = FALSE;
2044
2045 if (ptr[len] == '\\')
2046 // Skip over the "\" in "\ ".
2047 ++len;
2048 if (has_mbyte)
2049 len += (*mb_ptr2len)(ptr + len);
2050 else
2051 ++len;
2052 }
2053
2054 /*
2055 * If there is trailing punctuation, remove it.
2056 * But don't remove "..", could be a directory name.
2057 */
2058 if (len > 2 && vim_strchr((char_u *)".,:;!", ptr[len - 1]) != NULL
2059 && ptr[len - 2] != '.')
2060 --len;
2061
2062 if (file_lnum != NULL)
2063 {
2064 char_u *p;
Bram Moolenaar64e74c92019-12-22 15:38:06 +01002065 char *line_english = " line ";
2066 char *line_transl = _(line_msg);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002067
Bram Moolenaar64e74c92019-12-22 15:38:06 +01002068 // Get the number after the file name and a separator character.
2069 // Also accept " line 999" with and without the same translation as
2070 // used in last_set_msg().
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002071 p = ptr + len;
Bram Moolenaar64e74c92019-12-22 15:38:06 +01002072 if (STRNCMP(p, line_english, STRLEN(line_english)) == 0)
2073 p += STRLEN(line_english);
2074 else if (STRNCMP(p, line_transl, STRLEN(line_transl)) == 0)
2075 p += STRLEN(line_transl);
2076 else
2077 p = skipwhite(p);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002078 if (*p != NUL)
2079 {
2080 if (!isdigit(*p))
2081 ++p; // skip the separator
2082 p = skipwhite(p);
2083 if (isdigit(*p))
2084 *file_lnum = (int)getdigits(&p);
2085 }
2086 }
2087
2088 return find_file_name_in_path(ptr, len, options, count, rel_fname);
2089}
2090
2091# if defined(FEAT_FIND_ID) && defined(FEAT_EVAL)
2092 static char_u *
2093eval_includeexpr(char_u *ptr, int len)
2094{
2095 char_u *res;
Bram Moolenaar47bcc5f2022-01-22 20:19:22 +00002096 sctx_T save_sctx = current_sctx;
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002097
2098 set_vim_var_string(VV_FNAME, ptr, len);
Bram Moolenaar47bcc5f2022-01-22 20:19:22 +00002099 current_sctx = curbuf->b_p_script_ctx[BV_INEX];
2100
Bram Moolenaarb171fb12020-06-24 20:34:03 +02002101 res = eval_to_string_safe(curbuf->b_p_inex,
Bram Moolenaar47bcc5f2022-01-22 20:19:22 +00002102 was_set_insecurely((char_u *)"includeexpr", OPT_LOCAL), TRUE);
2103
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002104 set_vim_var_string(VV_FNAME, NULL, 0);
Bram Moolenaar47bcc5f2022-01-22 20:19:22 +00002105 current_sctx = save_sctx;
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002106 return res;
2107}
2108# endif
2109
2110/*
2111 * Return the name of the file ptr[len] in 'path'.
2112 * Otherwise like file_name_at_cursor().
2113 */
2114 char_u *
2115find_file_name_in_path(
2116 char_u *ptr,
2117 int len,
2118 int options,
2119 long count,
2120 char_u *rel_fname) // file we are searching relative to
2121{
2122 char_u *file_name;
2123 int c;
2124# if defined(FEAT_FIND_ID) && defined(FEAT_EVAL)
2125 char_u *tofree = NULL;
Bram Moolenaar615ddd52021-11-17 18:00:31 +00002126# endif
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002127
Bram Moolenaar615ddd52021-11-17 18:00:31 +00002128 if (len == 0)
2129 return NULL;
2130
2131# if defined(FEAT_FIND_ID) && defined(FEAT_EVAL)
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002132 if ((options & FNAME_INCL) && *curbuf->b_p_inex != NUL)
2133 {
2134 tofree = eval_includeexpr(ptr, len);
2135 if (tofree != NULL)
2136 {
2137 ptr = tofree;
2138 len = (int)STRLEN(ptr);
2139 }
2140 }
2141# endif
2142
2143 if (options & FNAME_EXP)
2144 {
2145 file_name = find_file_in_path(ptr, len, options & ~FNAME_MESS,
2146 TRUE, rel_fname);
2147
2148# if defined(FEAT_FIND_ID) && defined(FEAT_EVAL)
2149 /*
2150 * If the file could not be found in a normal way, try applying
2151 * 'includeexpr' (unless done already).
2152 */
2153 if (file_name == NULL
2154 && !(options & FNAME_INCL) && *curbuf->b_p_inex != NUL)
2155 {
2156 tofree = eval_includeexpr(ptr, len);
2157 if (tofree != NULL)
2158 {
2159 ptr = tofree;
2160 len = (int)STRLEN(ptr);
2161 file_name = find_file_in_path(ptr, len, options & ~FNAME_MESS,
2162 TRUE, rel_fname);
2163 }
2164 }
2165# endif
2166 if (file_name == NULL && (options & FNAME_MESS))
2167 {
2168 c = ptr[len];
2169 ptr[len] = NUL;
Bram Moolenaarac78dd42022-01-02 19:25:26 +00002170 semsg(_(e_cant_find_file_str_in_path_2), ptr);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002171 ptr[len] = c;
2172 }
2173
2174 // Repeat finding the file "count" times. This matters when it
2175 // appears several times in the path.
2176 while (file_name != NULL && --count > 0)
2177 {
2178 vim_free(file_name);
2179 file_name = find_file_in_path(ptr, len, options, FALSE, rel_fname);
2180 }
2181 }
2182 else
2183 file_name = vim_strnsave(ptr, len);
2184
2185# if defined(FEAT_FIND_ID) && defined(FEAT_EVAL)
2186 vim_free(tofree);
2187# endif
2188
2189 return file_name;
2190}
2191
2192/*
2193 * Return the end of the directory name, on the first path
2194 * separator:
2195 * "/path/file", "/path/dir/", "/path//dir", "/file"
2196 * ^ ^ ^ ^
2197 */
2198 static char_u *
2199gettail_dir(char_u *fname)
2200{
2201 char_u *dir_end = fname;
2202 char_u *next_dir_end = fname;
2203 int look_for_sep = TRUE;
2204 char_u *p;
2205
2206 for (p = fname; *p != NUL; )
2207 {
2208 if (vim_ispathsep(*p))
2209 {
2210 if (look_for_sep)
2211 {
2212 next_dir_end = p;
2213 look_for_sep = FALSE;
2214 }
2215 }
2216 else
2217 {
2218 if (!look_for_sep)
2219 dir_end = next_dir_end;
2220 look_for_sep = TRUE;
2221 }
2222 MB_PTR_ADV(p);
2223 }
2224 return dir_end;
2225}
2226
2227/*
2228 * return TRUE if 'c' is a path list separator.
2229 */
2230 int
2231vim_ispathlistsep(int c)
2232{
2233# ifdef UNIX
2234 return (c == ':');
2235# else
2236 return (c == ';'); // might not be right for every system...
2237# endif
2238}
2239
2240/*
2241 * Moves "*psep" back to the previous path separator in "path".
2242 * Returns FAIL is "*psep" ends up at the beginning of "path".
2243 */
2244 static int
2245find_previous_pathsep(char_u *path, char_u **psep)
2246{
2247 // skip the current separator
2248 if (*psep > path && vim_ispathsep(**psep))
2249 --*psep;
2250
2251 // find the previous separator
2252 while (*psep > path)
2253 {
2254 if (vim_ispathsep(**psep))
2255 return OK;
2256 MB_PTR_BACK(path, *psep);
2257 }
2258
2259 return FAIL;
2260}
2261
2262/*
2263 * Returns TRUE if "maybe_unique" is unique wrt other_paths in "gap".
2264 * "maybe_unique" is the end portion of "((char_u **)gap->ga_data)[i]".
2265 */
2266 static int
2267is_unique(char_u *maybe_unique, garray_T *gap, int i)
2268{
2269 int j;
2270 int candidate_len;
2271 int other_path_len;
2272 char_u **other_paths = (char_u **)gap->ga_data;
2273 char_u *rival;
2274
2275 for (j = 0; j < gap->ga_len; j++)
2276 {
2277 if (j == i)
2278 continue; // don't compare it with itself
2279
2280 candidate_len = (int)STRLEN(maybe_unique);
2281 other_path_len = (int)STRLEN(other_paths[j]);
2282 if (other_path_len < candidate_len)
2283 continue; // it's different when it's shorter
2284
2285 rival = other_paths[j] + other_path_len - candidate_len;
2286 if (fnamecmp(maybe_unique, rival) == 0
2287 && (rival == other_paths[j] || vim_ispathsep(*(rival - 1))))
2288 return FALSE; // match
2289 }
2290
2291 return TRUE; // no match found
2292}
2293
2294/*
2295 * Split the 'path' option into an array of strings in garray_T. Relative
2296 * paths are expanded to their equivalent fullpath. This includes the "."
2297 * (relative to current buffer directory) and empty path (relative to current
2298 * directory) notations.
2299 *
2300 * TODO: handle upward search (;) and path limiter (**N) notations by
2301 * expanding each into their equivalent path(s).
2302 */
2303 static void
2304expand_path_option(char_u *curdir, garray_T *gap)
2305{
2306 char_u *path_option = *curbuf->b_p_path == NUL
2307 ? p_path : curbuf->b_p_path;
2308 char_u *buf;
2309 char_u *p;
2310 int len;
2311
Bram Moolenaar51e14382019-05-25 20:21:28 +02002312 if ((buf = alloc(MAXPATHL)) == NULL)
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002313 return;
2314
2315 while (*path_option != NUL)
2316 {
2317 copy_option_part(&path_option, buf, MAXPATHL, " ,");
2318
2319 if (buf[0] == '.' && (buf[1] == NUL || vim_ispathsep(buf[1])))
2320 {
2321 // Relative to current buffer:
2322 // "/path/file" + "." -> "/path/"
2323 // "/path/file" + "./subdir" -> "/path/subdir"
2324 if (curbuf->b_ffname == NULL)
2325 continue;
2326 p = gettail(curbuf->b_ffname);
2327 len = (int)(p - curbuf->b_ffname);
2328 if (len + (int)STRLEN(buf) >= MAXPATHL)
2329 continue;
2330 if (buf[1] == NUL)
2331 buf[len] = NUL;
2332 else
2333 STRMOVE(buf + len, buf + 2);
2334 mch_memmove(buf, curbuf->b_ffname, len);
2335 simplify_filename(buf);
2336 }
2337 else if (buf[0] == NUL)
2338 // relative to current directory
2339 STRCPY(buf, curdir);
2340 else if (path_with_url(buf))
2341 // URL can't be used here
2342 continue;
2343 else if (!mch_isFullName(buf))
2344 {
2345 // Expand relative path to their full path equivalent
2346 len = (int)STRLEN(curdir);
2347 if (len + (int)STRLEN(buf) + 3 > MAXPATHL)
2348 continue;
2349 STRMOVE(buf + len + 1, buf);
2350 STRCPY(buf, curdir);
2351 buf[len] = PATHSEP;
2352 simplify_filename(buf);
2353 }
2354
2355 if (ga_grow(gap, 1) == FAIL)
2356 break;
2357
2358# if defined(MSWIN)
2359 // Avoid the path ending in a backslash, it fails when a comma is
2360 // appended.
2361 len = (int)STRLEN(buf);
2362 if (buf[len - 1] == '\\')
2363 buf[len - 1] = '/';
2364# endif
2365
2366 p = vim_strsave(buf);
2367 if (p == NULL)
2368 break;
2369 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
2370 }
2371
2372 vim_free(buf);
2373}
2374
2375/*
2376 * Returns a pointer to the file or directory name in "fname" that matches the
2377 * longest path in "ga"p, or NULL if there is no match. For example:
2378 *
2379 * path: /foo/bar/baz
2380 * fname: /foo/bar/baz/quux.txt
2381 * returns: ^this
2382 */
2383 static char_u *
2384get_path_cutoff(char_u *fname, garray_T *gap)
2385{
2386 int i;
2387 int maxlen = 0;
2388 char_u **path_part = (char_u **)gap->ga_data;
2389 char_u *cutoff = NULL;
2390
2391 for (i = 0; i < gap->ga_len; i++)
2392 {
2393 int j = 0;
2394
2395 while ((fname[j] == path_part[i][j]
2396# if defined(MSWIN)
2397 || (vim_ispathsep(fname[j]) && vim_ispathsep(path_part[i][j]))
2398# endif
2399 ) && fname[j] != NUL && path_part[i][j] != NUL)
2400 j++;
2401 if (j > maxlen)
2402 {
2403 maxlen = j;
2404 cutoff = &fname[j];
2405 }
2406 }
2407
2408 // skip to the file or directory name
2409 if (cutoff != NULL)
2410 while (vim_ispathsep(*cutoff))
2411 MB_PTR_ADV(cutoff);
2412
2413 return cutoff;
2414}
2415
2416/*
2417 * Sorts, removes duplicates and modifies all the fullpath names in "gap" so
2418 * that they are unique with respect to each other while conserving the part
2419 * that matches the pattern. Beware, this is at least O(n^2) wrt "gap->ga_len".
2420 */
2421 void
2422uniquefy_paths(garray_T *gap, char_u *pattern)
2423{
2424 int i;
2425 int len;
2426 char_u **fnames = (char_u **)gap->ga_data;
2427 int sort_again = FALSE;
2428 char_u *pat;
2429 char_u *file_pattern;
2430 char_u *curdir;
2431 regmatch_T regmatch;
2432 garray_T path_ga;
2433 char_u **in_curdir = NULL;
2434 char_u *short_name;
2435
2436 remove_duplicates(gap);
Bram Moolenaar04935fb2022-01-08 16:19:22 +00002437 ga_init2(&path_ga, sizeof(char_u *), 1);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002438
2439 /*
2440 * We need to prepend a '*' at the beginning of file_pattern so that the
2441 * regex matches anywhere in the path. FIXME: is this valid for all
2442 * possible patterns?
2443 */
2444 len = (int)STRLEN(pattern);
2445 file_pattern = alloc(len + 2);
2446 if (file_pattern == NULL)
2447 return;
2448 file_pattern[0] = '*';
2449 file_pattern[1] = NUL;
2450 STRCAT(file_pattern, pattern);
2451 pat = file_pat_to_reg_pat(file_pattern, NULL, NULL, TRUE);
2452 vim_free(file_pattern);
2453 if (pat == NULL)
2454 return;
2455
2456 regmatch.rm_ic = TRUE; // always ignore case
2457 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
2458 vim_free(pat);
2459 if (regmatch.regprog == NULL)
2460 return;
2461
Bram Moolenaar51e14382019-05-25 20:21:28 +02002462 if ((curdir = alloc(MAXPATHL)) == NULL)
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002463 goto theend;
2464 mch_dirname(curdir, MAXPATHL);
2465 expand_path_option(curdir, &path_ga);
2466
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002467 in_curdir = ALLOC_CLEAR_MULT(char_u *, gap->ga_len);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002468 if (in_curdir == NULL)
2469 goto theend;
2470
2471 for (i = 0; i < gap->ga_len && !got_int; i++)
2472 {
2473 char_u *path = fnames[i];
2474 int is_in_curdir;
2475 char_u *dir_end = gettail_dir(path);
2476 char_u *pathsep_p;
2477 char_u *path_cutoff;
2478
2479 len = (int)STRLEN(path);
2480 is_in_curdir = fnamencmp(curdir, path, dir_end - path) == 0
2481 && curdir[dir_end - path] == NUL;
2482 if (is_in_curdir)
2483 in_curdir[i] = vim_strsave(path);
2484
2485 // Shorten the filename while maintaining its uniqueness
2486 path_cutoff = get_path_cutoff(path, &path_ga);
2487
2488 // Don't assume all files can be reached without path when search
2489 // pattern starts with star star slash, so only remove path_cutoff
2490 // when possible.
2491 if (pattern[0] == '*' && pattern[1] == '*'
2492 && vim_ispathsep_nocolon(pattern[2])
2493 && path_cutoff != NULL
2494 && vim_regexec(&regmatch, path_cutoff, (colnr_T)0)
2495 && is_unique(path_cutoff, gap, i))
2496 {
2497 sort_again = TRUE;
2498 mch_memmove(path, path_cutoff, STRLEN(path_cutoff) + 1);
2499 }
2500 else
2501 {
2502 // Here all files can be reached without path, so get shortest
2503 // unique path. We start at the end of the path.
2504 pathsep_p = path + len - 1;
2505
2506 while (find_previous_pathsep(path, &pathsep_p))
2507 if (vim_regexec(&regmatch, pathsep_p + 1, (colnr_T)0)
2508 && is_unique(pathsep_p + 1, gap, i)
2509 && path_cutoff != NULL && pathsep_p + 1 >= path_cutoff)
2510 {
2511 sort_again = TRUE;
2512 mch_memmove(path, pathsep_p + 1, STRLEN(pathsep_p));
2513 break;
2514 }
2515 }
2516
2517 if (mch_isFullName(path))
2518 {
2519 /*
2520 * Last resort: shorten relative to curdir if possible.
2521 * 'possible' means:
2522 * 1. It is under the current directory.
2523 * 2. The result is actually shorter than the original.
2524 *
2525 * Before curdir After
2526 * /foo/bar/file.txt /foo/bar ./file.txt
2527 * c:\foo\bar\file.txt c:\foo\bar .\file.txt
2528 * /file.txt / /file.txt
2529 * c:\file.txt c:\ .\file.txt
2530 */
2531 short_name = shorten_fname(path, curdir);
2532 if (short_name != NULL && short_name > path + 1
2533# if defined(MSWIN)
2534 // On windows,
2535 // shorten_fname("c:\a\a.txt", "c:\a\b")
2536 // returns "\a\a.txt", which is not really the short
2537 // name, hence:
2538 && !vim_ispathsep(*short_name)
2539# endif
2540 )
2541 {
2542 STRCPY(path, ".");
2543 add_pathsep(path);
2544 STRMOVE(path + STRLEN(path), short_name);
2545 }
2546 }
2547 ui_breakcheck();
2548 }
2549
2550 // Shorten filenames in /in/current/directory/{filename}
2551 for (i = 0; i < gap->ga_len && !got_int; i++)
2552 {
2553 char_u *rel_path;
2554 char_u *path = in_curdir[i];
2555
2556 if (path == NULL)
2557 continue;
2558
2559 // If the {filename} is not unique, change it to ./{filename}.
2560 // Else reduce it to {filename}
2561 short_name = shorten_fname(path, curdir);
2562 if (short_name == NULL)
2563 short_name = path;
2564 if (is_unique(short_name, gap, i))
2565 {
2566 STRCPY(fnames[i], short_name);
2567 continue;
2568 }
2569
Bram Moolenaar51e14382019-05-25 20:21:28 +02002570 rel_path = alloc(STRLEN(short_name) + STRLEN(PATHSEPSTR) + 2);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002571 if (rel_path == NULL)
2572 goto theend;
2573 STRCPY(rel_path, ".");
2574 add_pathsep(rel_path);
2575 STRCAT(rel_path, short_name);
2576
2577 vim_free(fnames[i]);
2578 fnames[i] = rel_path;
2579 sort_again = TRUE;
2580 ui_breakcheck();
2581 }
2582
2583theend:
2584 vim_free(curdir);
2585 if (in_curdir != NULL)
2586 {
2587 for (i = 0; i < gap->ga_len; i++)
2588 vim_free(in_curdir[i]);
2589 vim_free(in_curdir);
2590 }
2591 ga_clear_strings(&path_ga);
2592 vim_regfree(regmatch.regprog);
2593
2594 if (sort_again)
2595 remove_duplicates(gap);
2596}
2597
2598/*
2599 * Calls globpath() with 'path' values for the given pattern and stores the
2600 * result in "gap".
2601 * Returns the total number of matches.
2602 */
2603 int
2604expand_in_path(
2605 garray_T *gap,
2606 char_u *pattern,
2607 int flags) // EW_* flags
2608{
2609 char_u *curdir;
2610 garray_T path_ga;
2611 char_u *paths = NULL;
2612 int glob_flags = 0;
2613
Bram Moolenaar964b3742019-05-24 18:54:09 +02002614 if ((curdir = alloc(MAXPATHL)) == NULL)
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002615 return 0;
2616 mch_dirname(curdir, MAXPATHL);
2617
Bram Moolenaar04935fb2022-01-08 16:19:22 +00002618 ga_init2(&path_ga, sizeof(char_u *), 1);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002619 expand_path_option(curdir, &path_ga);
2620 vim_free(curdir);
2621 if (path_ga.ga_len == 0)
2622 return 0;
2623
2624 paths = ga_concat_strings(&path_ga, ",");
2625 ga_clear_strings(&path_ga);
2626 if (paths == NULL)
2627 return 0;
2628
2629 if (flags & EW_ICASE)
2630 glob_flags |= WILD_ICASE;
2631 if (flags & EW_ADDSLASH)
2632 glob_flags |= WILD_ADD_SLASH;
2633 globpath(paths, pattern, gap, glob_flags);
2634 vim_free(paths);
2635
2636 return gap->ga_len;
2637}
2638
2639#endif // FEAT_SEARCHPATH
Bram Moolenaarb4a60202019-03-31 19:40:07 +02002640
2641/*
2642 * Converts a file name into a canonical form. It simplifies a file name into
2643 * its simplest form by stripping out unneeded components, if any. The
2644 * resulting file name is simplified in place and will either be the same
2645 * length as that supplied, or shorter.
2646 */
2647 void
2648simplify_filename(char_u *filename)
2649{
2650#ifndef AMIGA // Amiga doesn't have "..", it uses "/"
2651 int components = 0;
2652 char_u *p, *tail, *start;
2653 int stripping_disabled = FALSE;
2654 int relative = TRUE;
2655
2656 p = filename;
2657# ifdef BACKSLASH_IN_FILENAME
Yegappan Lakshmanan6df0f272021-12-16 13:06:10 +00002658 if (p[0] != NUL && p[1] == ':') // skip "x:"
Bram Moolenaarb4a60202019-03-31 19:40:07 +02002659 p += 2;
2660# endif
2661
2662 if (vim_ispathsep(*p))
2663 {
2664 relative = FALSE;
2665 do
2666 ++p;
2667 while (vim_ispathsep(*p));
2668 }
2669 start = p; // remember start after "c:/" or "/" or "///"
Bram Moolenaarfdcbe3c2020-06-15 21:41:56 +02002670#ifdef UNIX
2671 // Posix says that "//path" is unchanged but "///path" is "/path".
2672 if (start > filename + 2)
2673 {
2674 STRMOVE(filename + 1, p);
2675 start = p = filename + 1;
2676 }
2677#endif
Bram Moolenaarb4a60202019-03-31 19:40:07 +02002678
2679 do
2680 {
2681 // At this point "p" is pointing to the char following a single "/"
2682 // or "p" is at the "start" of the (absolute or relative) path name.
2683# ifdef VMS
2684 // VMS allows device:[path] - don't strip the [ in directory
2685 if ((*p == '[' || *p == '<') && p > filename && p[-1] == ':')
2686 {
2687 // :[ or :< composition: vms directory component
2688 ++components;
2689 p = getnextcomp(p + 1);
2690 }
2691 // allow remote calls as host"user passwd"::device:[path]
2692 else if (p[0] == ':' && p[1] == ':' && p > filename && p[-1] == '"' )
2693 {
2694 // ":: composition: vms host/passwd component
2695 ++components;
2696 p = getnextcomp(p + 2);
2697 }
2698 else
2699# endif
2700 if (vim_ispathsep(*p))
2701 STRMOVE(p, p + 1); // remove duplicate "/"
2702 else if (p[0] == '.' && (vim_ispathsep(p[1]) || p[1] == NUL))
2703 {
2704 if (p == start && relative)
2705 p += 1 + (p[1] != NUL); // keep single "." or leading "./"
2706 else
2707 {
2708 // Strip "./" or ".///". If we are at the end of the file name
2709 // and there is no trailing path separator, either strip "/." if
2710 // we are after "start", or strip "." if we are at the beginning
2711 // of an absolute path name .
2712 tail = p + 1;
2713 if (p[1] != NUL)
2714 while (vim_ispathsep(*tail))
2715 MB_PTR_ADV(tail);
2716 else if (p > start)
2717 --p; // strip preceding path separator
2718 STRMOVE(p, tail);
2719 }
2720 }
2721 else if (p[0] == '.' && p[1] == '.' &&
2722 (vim_ispathsep(p[2]) || p[2] == NUL))
2723 {
2724 // Skip to after ".." or "../" or "..///".
2725 tail = p + 2;
2726 while (vim_ispathsep(*tail))
2727 MB_PTR_ADV(tail);
2728
2729 if (components > 0) // strip one preceding component
2730 {
2731 int do_strip = FALSE;
2732 char_u saved_char;
2733 stat_T st;
2734
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002735 // Don't strip for an erroneous file name.
Bram Moolenaarb4a60202019-03-31 19:40:07 +02002736 if (!stripping_disabled)
2737 {
2738 // If the preceding component does not exist in the file
2739 // system, we strip it. On Unix, we don't accept a symbolic
2740 // link that refers to a non-existent file.
2741 saved_char = p[-1];
2742 p[-1] = NUL;
2743# ifdef UNIX
2744 if (mch_lstat((char *)filename, &st) < 0)
2745# else
2746 if (mch_stat((char *)filename, &st) < 0)
2747# endif
2748 do_strip = TRUE;
2749 p[-1] = saved_char;
2750
2751 --p;
2752 // Skip back to after previous '/'.
2753 while (p > start && !after_pathsep(start, p))
2754 MB_PTR_BACK(start, p);
2755
2756 if (!do_strip)
2757 {
2758 // If the component exists in the file system, check
2759 // that stripping it won't change the meaning of the
2760 // file name. First get information about the
2761 // unstripped file name. This may fail if the component
2762 // to strip is not a searchable directory (but a regular
2763 // file, for instance), since the trailing "/.." cannot
2764 // be applied then. We don't strip it then since we
2765 // don't want to replace an erroneous file name by
2766 // a valid one, and we disable stripping of later
2767 // components.
2768 saved_char = *tail;
2769 *tail = NUL;
2770 if (mch_stat((char *)filename, &st) >= 0)
2771 do_strip = TRUE;
2772 else
2773 stripping_disabled = TRUE;
2774 *tail = saved_char;
2775# ifdef UNIX
2776 if (do_strip)
2777 {
2778 stat_T new_st;
2779
2780 // On Unix, the check for the unstripped file name
2781 // above works also for a symbolic link pointing to
2782 // a searchable directory. But then the parent of
2783 // the directory pointed to by the link must be the
2784 // same as the stripped file name. (The latter
2785 // exists in the file system since it is the
2786 // component's parent directory.)
2787 if (p == start && relative)
2788 (void)mch_stat(".", &new_st);
2789 else
2790 {
2791 saved_char = *p;
2792 *p = NUL;
2793 (void)mch_stat((char *)filename, &new_st);
2794 *p = saved_char;
2795 }
2796
2797 if (new_st.st_ino != st.st_ino ||
2798 new_st.st_dev != st.st_dev)
2799 {
2800 do_strip = FALSE;
2801 // We don't disable stripping of later
2802 // components since the unstripped path name is
2803 // still valid.
2804 }
2805 }
2806# endif
2807 }
2808 }
2809
2810 if (!do_strip)
2811 {
2812 // Skip the ".." or "../" and reset the counter for the
2813 // components that might be stripped later on.
2814 p = tail;
2815 components = 0;
2816 }
2817 else
2818 {
2819 // Strip previous component. If the result would get empty
2820 // and there is no trailing path separator, leave a single
2821 // "." instead. If we are at the end of the file name and
2822 // there is no trailing path separator and a preceding
2823 // component is left after stripping, strip its trailing
2824 // path separator as well.
2825 if (p == start && relative && tail[-1] == '.')
2826 {
2827 *p++ = '.';
2828 *p = NUL;
2829 }
2830 else
2831 {
2832 if (p > start && tail[-1] == '.')
2833 --p;
2834 STRMOVE(p, tail); // strip previous component
2835 }
2836
2837 --components;
2838 }
2839 }
2840 else if (p == start && !relative) // leading "/.." or "/../"
2841 STRMOVE(p, tail); // strip ".." or "../"
2842 else
2843 {
2844 if (p == start + 2 && p[-2] == '.') // leading "./../"
2845 {
2846 STRMOVE(p - 2, p); // strip leading "./"
2847 tail -= 2;
2848 }
2849 p = tail; // skip to char after ".." or "../"
2850 }
2851 }
2852 else
2853 {
2854 ++components; // simple path component
2855 p = getnextcomp(p);
2856 }
2857 } while (*p != NUL);
2858#endif // !AMIGA
2859}
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002860
2861#if defined(FEAT_EVAL) || defined(PROTO)
2862/*
2863 * "simplify()" function
2864 */
2865 void
2866f_simplify(typval_T *argvars, typval_T *rettv)
2867{
2868 char_u *p;
2869
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02002870 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
2871 return;
2872
Bram Moolenaar3cfa5b12021-06-06 14:14:39 +02002873 p = tv_get_string_strict(&argvars[0]);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002874 rettv->vval.v_string = vim_strsave(p);
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002875 simplify_filename(rettv->vval.v_string); // simplify in place
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002876 rettv->v_type = VAR_STRING;
2877}
2878#endif // FEAT_EVAL