blob: 246a81898a5063d316a02a5e05a1f45f556ac819 [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 * ==========
Christian Brabandtee17b6f2023-09-09 11:23:50 +020051 * Also we use an allocated search context here, these functions are NOT
52 * thread-safe!
Bram Moolenaar5fd0f502019-02-13 23:13:28 +010053 *
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;
Bram Moolenaar5fd0f502019-02-13 23:13:28 +010070 char_u *ffs_wc_path;
Bram Moolenaar5fd0f502019-02-13 23:13:28 +010071
72 // files/dirs found in the above directory, matched by the first wildcard
73 // of wc_part
74 char_u **ffs_filearray;
75 int ffs_filearray_size;
John Drouhard95fca122022-08-01 11:38:17 +010076 int ffs_filearray_cur; // needed for partly handled dirs
Bram Moolenaar5fd0f502019-02-13 23:13:28 +010077
78 // to store status of partly handled directories
79 // 0: we work on this directory for the first time
80 // 1: this directory was partly searched in an earlier step
81 int ffs_stage;
82
83 // How deep are we in the directory tree?
84 // Counts backward from value of level parameter to vim_findfile_init
85 int ffs_level;
86
87 // Did we already expand '**' to an empty string?
88 int ffs_star_star_empty;
89} ff_stack_T;
90
91/*
92 * type for already visited directories or files.
93 */
94typedef struct ff_visited
95{
96 struct ff_visited *ffv_next;
97
Bram Moolenaar5fd0f502019-02-13 23:13:28 +010098 // Visited directories are different if the wildcard string are
99 // different. So we have to save it.
100 char_u *ffv_wc_path;
Bram Moolenaar2bd9dbc2022-08-25 18:12:06 +0100101
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100102 // for unix use inode etc for comparison (needed because of links), else
103 // use filename.
104#ifdef UNIX
105 int ffv_dev_valid; // ffv_dev and ffv_ino were set
106 dev_t ffv_dev; // device number
107 ino_t ffv_ino; // inode number
108#endif
109 // The memory for this struct is allocated according to the length of
110 // ffv_fname.
111 char_u ffv_fname[1]; // actually longer
112} ff_visited_T;
113
114/*
115 * We might have to manage several visited lists during a search.
116 * This is especially needed for the tags option. If tags is set to:
117 * "./++/tags,./++/TAGS,++/tags" (replace + with *)
118 * So we have to do 3 searches:
119 * 1) search from the current files directory downward for the file "tags"
120 * 2) search from the current files directory downward for the file "TAGS"
121 * 3) search from Vims current directory downwards for the file "tags"
122 * As you can see, the first and the third search are for the same file, so for
123 * the third search we can use the visited list of the first search. For the
124 * second search we must start from a empty visited list.
125 * The struct ff_visited_list_hdr is used to manage a linked list of already
126 * visited lists.
127 */
128typedef struct ff_visited_list_hdr
129{
130 struct ff_visited_list_hdr *ffvl_next;
131
132 // the filename the attached visited list is for
133 char_u *ffvl_filename;
134
135 ff_visited_T *ffvl_visited_list;
136
137} ff_visited_list_hdr_T;
138
139
140/*
141 * '**' can be expanded to several directory levels.
142 * Set the default maximum depth.
143 */
144#define FF_MAX_STAR_STAR_EXPAND ((char_u)30)
145
146/*
147 * The search context:
148 * ffsc_stack_ptr: the stack for the dirs to search
149 * ffsc_visited_list: the currently active visited list
150 * ffsc_dir_visited_list: the currently active visited list for search dirs
151 * ffsc_visited_lists_list: the list of all visited lists
152 * ffsc_dir_visited_lists_list: the list of all visited lists for search dirs
153 * ffsc_file_to_search: the file to search for
154 * ffsc_start_dir: the starting directory, if search path was relative
155 * ffsc_fix_path: the fix part of the given path (without wildcards)
156 * Needed for upward search.
157 * ffsc_wc_path: the part of the given path containing wildcards
158 * ffsc_level: how many levels of dirs to search downwards
159 * ffsc_stopdirs_v: array of stop directories for upward search
160 * ffsc_find_what: FINDFILE_BOTH, FINDFILE_DIR or FINDFILE_FILE
161 * ffsc_tagfile: searching for tags file, don't use 'suffixesadd'
162 */
163typedef struct ff_search_ctx_T
164{
165 ff_stack_T *ffsc_stack_ptr;
166 ff_visited_list_hdr_T *ffsc_visited_list;
167 ff_visited_list_hdr_T *ffsc_dir_visited_list;
168 ff_visited_list_hdr_T *ffsc_visited_lists_list;
169 ff_visited_list_hdr_T *ffsc_dir_visited_lists_list;
170 char_u *ffsc_file_to_search;
171 char_u *ffsc_start_dir;
172 char_u *ffsc_fix_path;
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100173 char_u *ffsc_wc_path;
174 int ffsc_level;
175 char_u **ffsc_stopdirs_v;
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100176 int ffsc_find_what;
177 int ffsc_tagfile;
178} ff_search_ctx_T;
179
180// locally needed functions
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100181static int ff_check_visited(ff_visited_T **, char_u *, char_u *);
Bram Moolenaar5843f5f2019-08-20 20:13:45 +0200182static void vim_findfile_free_visited(void *search_ctx_arg);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100183static void vim_findfile_free_visited_list(ff_visited_list_hdr_T **list_headp);
184static void ff_free_visited_list(ff_visited_T *vl);
185static ff_visited_list_hdr_T* ff_get_visited_list(char_u *, ff_visited_list_hdr_T **list_headp);
186
187static void ff_push(ff_search_ctx_T *search_ctx, ff_stack_T *stack_ptr);
188static ff_stack_T *ff_pop(ff_search_ctx_T *search_ctx);
189static void ff_clear(ff_search_ctx_T *search_ctx);
190static void ff_free_stack_element(ff_stack_T *stack_ptr);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100191static ff_stack_T *ff_create_stack_element(char_u *, char_u *, int, int);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100192static int ff_path_in_stoplist(char_u *, int, char_u **);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100193
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100194static char_u *ff_expand_buffer = NULL; // used for expanding filenames
195
196#if 0
197/*
198 * if someone likes findfirst/findnext, here are the functions
199 * NOT TESTED!!
200 */
201
202static void *ff_fn_search_context = NULL;
203
204 char_u *
205vim_findfirst(char_u *path, char_u *filename, int level)
206{
207 ff_fn_search_context =
208 vim_findfile_init(path, filename, NULL, level, TRUE, FALSE,
209 ff_fn_search_context, rel_fname);
210 if (NULL == ff_fn_search_context)
211 return NULL;
212 else
213 return vim_findnext()
214}
215
216 char_u *
217vim_findnext(void)
218{
219 char_u *ret = vim_findfile(ff_fn_search_context);
220
221 if (NULL == ret)
222 {
223 vim_findfile_cleanup(ff_fn_search_context);
224 ff_fn_search_context = NULL;
225 }
226 return ret;
227}
228#endif
229
230/*
231 * Initialization routine for vim_findfile().
232 *
233 * Returns the newly allocated search context or NULL if an error occurred.
234 *
235 * Don't forget to clean up by calling vim_findfile_cleanup() if you are done
236 * with the search context.
237 *
238 * Find the file 'filename' in the directory 'path'.
239 * The parameter 'path' may contain wildcards. If so only search 'level'
240 * directories deep. The parameter 'level' is the absolute maximum and is
241 * not related to restricts given to the '**' wildcard. If 'level' is 100
242 * and you use '**200' vim_findfile() will stop after 100 levels.
243 *
244 * 'filename' cannot contain wildcards! It is used as-is, no backslashes to
245 * escape special characters.
246 *
247 * If 'stopdirs' is not NULL and nothing is found downward, the search is
248 * restarted on the next higher directory level. This is repeated until the
249 * start-directory of a search is contained in 'stopdirs'. 'stopdirs' has the
250 * format ";*<dirname>*\(;<dirname>\)*;\=$".
251 *
252 * If the 'path' is relative, the starting dir for the search is either VIM's
253 * current dir or if the path starts with "./" the current files dir.
254 * If the 'path' is absolute, the starting dir is that part of the path before
255 * the first wildcard.
256 *
257 * Upward search is only done on the starting dir.
258 *
259 * If 'free_visited' is TRUE the list of already visited files/directories is
260 * cleared. Set this to FALSE if you just want to search from another
261 * directory, but want to be sure that no directory from a previous search is
262 * searched again. This is useful if you search for a file at different places.
263 * The list of visited files/dirs can also be cleared with the function
264 * vim_findfile_free_visited().
265 *
266 * Set the parameter 'find_what' to FINDFILE_DIR if you want to search for
267 * directories only, FINDFILE_FILE for files only, FINDFILE_BOTH for both.
268 *
269 * A search context returned by a previous call to vim_findfile_init() can be
270 * passed in the parameter "search_ctx_arg". This context is reused and
271 * reinitialized with the new parameters. The list of already visited
272 * directories from this context is only deleted if the parameter
273 * "free_visited" is true. Be aware that the passed "search_ctx_arg" is freed
274 * if the reinitialization fails.
275 *
276 * If you don't have a search context from a previous call "search_ctx_arg"
277 * must be NULL.
278 *
279 * This function silently ignores a few errors, vim_findfile() will have
280 * limited functionality then.
281 */
282 void *
283vim_findfile_init(
284 char_u *path,
285 char_u *filename,
286 char_u *stopdirs UNUSED,
287 int level,
288 int free_visited,
289 int find_what,
290 void *search_ctx_arg,
291 int tagfile, // expanding names of tags files
292 char_u *rel_fname) // file name to use for "."
293{
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100294 char_u *wc_part;
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100295 ff_stack_T *sptr;
296 ff_search_ctx_T *search_ctx;
297
298 // If a search context is given by the caller, reuse it, else allocate a
299 // new one.
300 if (search_ctx_arg != NULL)
301 search_ctx = search_ctx_arg;
302 else
303 {
Bram Moolenaara80faa82020-04-12 19:37:17 +0200304 search_ctx = ALLOC_CLEAR_ONE(ff_search_ctx_T);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100305 if (search_ctx == NULL)
306 goto error_return;
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100307 }
308 search_ctx->ffsc_find_what = find_what;
309 search_ctx->ffsc_tagfile = tagfile;
310
311 // clear the search context, but NOT the visited lists
312 ff_clear(search_ctx);
313
314 // clear visited list if wanted
315 if (free_visited == TRUE)
316 vim_findfile_free_visited(search_ctx);
317 else
318 {
319 // Reuse old visited lists. Get the visited list for the given
320 // filename. If no list for the current filename exists, creates a new
321 // one.
322 search_ctx->ffsc_visited_list = ff_get_visited_list(filename,
323 &search_ctx->ffsc_visited_lists_list);
324 if (search_ctx->ffsc_visited_list == NULL)
325 goto error_return;
326 search_ctx->ffsc_dir_visited_list = ff_get_visited_list(filename,
327 &search_ctx->ffsc_dir_visited_lists_list);
328 if (search_ctx->ffsc_dir_visited_list == NULL)
329 goto error_return;
330 }
331
332 if (ff_expand_buffer == NULL)
333 {
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200334 ff_expand_buffer = alloc(MAXPATHL);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100335 if (ff_expand_buffer == NULL)
336 goto error_return;
337 }
338
339 // Store information on starting dir now if path is relative.
340 // If path is absolute, we do that later.
341 if (path[0] == '.'
342 && (vim_ispathsep(path[1]) || path[1] == NUL)
343 && (!tagfile || vim_strchr(p_cpo, CPO_DOTTAG) == NULL)
344 && rel_fname != NULL)
345 {
346 int len = (int)(gettail(rel_fname) - rel_fname);
347
348 if (!vim_isAbsName(rel_fname) && len + 1 < MAXPATHL)
349 {
350 // Make the start dir an absolute path name.
351 vim_strncpy(ff_expand_buffer, rel_fname, len);
352 search_ctx->ffsc_start_dir = FullName_save(ff_expand_buffer, FALSE);
353 }
354 else
355 search_ctx->ffsc_start_dir = vim_strnsave(rel_fname, len);
356 if (search_ctx->ffsc_start_dir == NULL)
357 goto error_return;
358 if (*++path != NUL)
359 ++path;
360 }
361 else if (*path == NUL || !vim_isAbsName(path))
362 {
363#ifdef BACKSLASH_IN_FILENAME
364 // "c:dir" needs "c:" to be expanded, otherwise use current dir
365 if (*path != NUL && path[1] == ':')
366 {
367 char_u drive[3];
368
369 drive[0] = path[0];
370 drive[1] = ':';
371 drive[2] = NUL;
372 if (vim_FullName(drive, ff_expand_buffer, MAXPATHL, TRUE) == FAIL)
373 goto error_return;
374 path += 2;
375 }
376 else
377#endif
378 if (mch_dirname(ff_expand_buffer, MAXPATHL) == FAIL)
379 goto error_return;
380
381 search_ctx->ffsc_start_dir = vim_strsave(ff_expand_buffer);
382 if (search_ctx->ffsc_start_dir == NULL)
383 goto error_return;
384
385#ifdef BACKSLASH_IN_FILENAME
386 // A path that starts with "/dir" is relative to the drive, not to the
387 // directory (but not for "//machine/dir"). Only use the drive name.
388 if ((*path == '/' || *path == '\\')
389 && path[1] != path[0]
390 && search_ctx->ffsc_start_dir[1] == ':')
391 search_ctx->ffsc_start_dir[2] = NUL;
392#endif
393 }
394
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100395 /*
396 * If stopdirs are given, split them into an array of pointers.
397 * If this fails (mem allocation), there is no upward search at all or a
398 * stop directory is not recognized -> continue silently.
399 * If stopdirs just contains a ";" or is empty,
400 * search_ctx->ffsc_stopdirs_v will only contain a NULL pointer. This
401 * is handled as unlimited upward search. See function
402 * ff_path_in_stoplist() for details.
403 */
404 if (stopdirs != NULL)
405 {
406 char_u *walker = stopdirs;
407 int dircount;
408
409 while (*walker == ';')
410 walker++;
411
412 dircount = 1;
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200413 search_ctx->ffsc_stopdirs_v = ALLOC_ONE(char_u *);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100414
415 if (search_ctx->ffsc_stopdirs_v != NULL)
416 {
417 do
418 {
419 char_u *helper;
420 void *ptr;
421
422 helper = walker;
423 ptr = vim_realloc(search_ctx->ffsc_stopdirs_v,
424 (dircount + 1) * sizeof(char_u *));
425 if (ptr)
426 search_ctx->ffsc_stopdirs_v = ptr;
427 else
428 // ignore, keep what we have and continue
429 break;
430 walker = vim_strchr(walker, ';');
431 if (walker)
432 {
433 search_ctx->ffsc_stopdirs_v[dircount-1] =
Bram Moolenaar71ccd032020-06-12 22:59:11 +0200434 vim_strnsave(helper, walker - helper);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100435 walker++;
436 }
437 else
438 // this might be "", which means ascent till top
439 // of directory tree.
440 search_ctx->ffsc_stopdirs_v[dircount-1] =
441 vim_strsave(helper);
442
443 dircount++;
444
445 } while (walker != NULL);
446 search_ctx->ffsc_stopdirs_v[dircount-1] = NULL;
447 }
448 }
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100449
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100450 search_ctx->ffsc_level = level;
451
452 /*
453 * split into:
454 * -fix path
455 * -wildcard_stuff (might be NULL)
456 */
457 wc_part = vim_strchr(path, '*');
458 if (wc_part != NULL)
459 {
460 int llevel;
461 int len;
462 char *errpt;
463
464 // save the fix part of the path
Bram Moolenaar71ccd032020-06-12 22:59:11 +0200465 search_ctx->ffsc_fix_path = vim_strnsave(path, wc_part - path);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100466
467 /*
468 * copy wc_path and add restricts to the '**' wildcard.
469 * The octet after a '**' is used as a (binary) counter.
470 * So '**3' is transposed to '**^C' ('^C' is ASCII value 3)
471 * or '**76' is transposed to '**N'( 'N' is ASCII value 76).
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100472 * If no restrict is given after '**' the default is used.
473 * Due to this technique the path looks awful if you print it as a
474 * string.
475 */
476 len = 0;
477 while (*wc_part != NUL)
478 {
479 if (len + 5 >= MAXPATHL)
480 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +0000481 emsg(_(e_path_too_long_for_completion));
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100482 break;
483 }
484 if (STRNCMP(wc_part, "**", 2) == 0)
485 {
486 ff_expand_buffer[len++] = *wc_part++;
487 ff_expand_buffer[len++] = *wc_part++;
488
489 llevel = strtol((char *)wc_part, &errpt, 10);
490 if ((char_u *)errpt != wc_part && llevel > 0 && llevel < 255)
491 ff_expand_buffer[len++] = llevel;
492 else if ((char_u *)errpt != wc_part && llevel == 0)
493 // restrict is 0 -> remove already added '**'
494 len -= 2;
495 else
496 ff_expand_buffer[len++] = FF_MAX_STAR_STAR_EXPAND;
497 wc_part = (char_u *)errpt;
498 if (*wc_part != NUL && !vim_ispathsep(*wc_part))
499 {
Bram Moolenaareaaac012022-01-02 17:00:40 +0000500 semsg(_(e_invalid_path_number_must_be_at_end_of_path_or_be_followed_by_str), PATHSEPSTR);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100501 goto error_return;
502 }
503 }
504 else
505 ff_expand_buffer[len++] = *wc_part++;
506 }
507 ff_expand_buffer[len] = NUL;
508 search_ctx->ffsc_wc_path = vim_strsave(ff_expand_buffer);
509
510 if (search_ctx->ffsc_wc_path == NULL)
511 goto error_return;
512 }
513 else
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100514 search_ctx->ffsc_fix_path = vim_strsave(path);
515
516 if (search_ctx->ffsc_start_dir == NULL)
517 {
518 // store the fix part as startdir.
519 // This is needed if the parameter path is fully qualified.
520 search_ctx->ffsc_start_dir = vim_strsave(search_ctx->ffsc_fix_path);
521 if (search_ctx->ffsc_start_dir == NULL)
522 goto error_return;
523 search_ctx->ffsc_fix_path[0] = NUL;
524 }
525
526 // create an absolute path
527 if (STRLEN(search_ctx->ffsc_start_dir)
528 + STRLEN(search_ctx->ffsc_fix_path) + 3 >= MAXPATHL)
529 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +0000530 emsg(_(e_path_too_long_for_completion));
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100531 goto error_return;
532 }
533 STRCPY(ff_expand_buffer, search_ctx->ffsc_start_dir);
534 add_pathsep(ff_expand_buffer);
535 {
536 int eb_len = (int)STRLEN(ff_expand_buffer);
537 char_u *buf = alloc(eb_len
538 + (int)STRLEN(search_ctx->ffsc_fix_path) + 1);
539
540 STRCPY(buf, ff_expand_buffer);
541 STRCPY(buf + eb_len, search_ctx->ffsc_fix_path);
542 if (mch_isdir(buf))
543 {
544 STRCAT(ff_expand_buffer, search_ctx->ffsc_fix_path);
545 add_pathsep(ff_expand_buffer);
546 }
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100547 else
548 {
549 char_u *p = gettail(search_ctx->ffsc_fix_path);
550 char_u *wc_path = NULL;
551 char_u *temp = NULL;
552 int len = 0;
553
554 if (p > search_ctx->ffsc_fix_path)
555 {
Christian Brabandt7a4ca322021-07-25 15:08:05 +0200556 // do not add '..' to the path and start upwards searching
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100557 len = (int)(p - search_ctx->ffsc_fix_path) - 1;
Christian Brabandt7a4ca322021-07-25 15:08:05 +0200558 if ((len >= 2
559 && STRNCMP(search_ctx->ffsc_fix_path, "..", 2) == 0)
560 && (len == 2
561 || search_ctx->ffsc_fix_path[2] == PATHSEP))
562 {
563 vim_free(buf);
564 goto error_return;
565 }
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100566 STRNCAT(ff_expand_buffer, search_ctx->ffsc_fix_path, len);
567 add_pathsep(ff_expand_buffer);
568 }
569 else
570 len = (int)STRLEN(search_ctx->ffsc_fix_path);
571
572 if (search_ctx->ffsc_wc_path != NULL)
573 {
574 wc_path = vim_strsave(search_ctx->ffsc_wc_path);
Bram Moolenaar51e14382019-05-25 20:21:28 +0200575 temp = alloc(STRLEN(search_ctx->ffsc_wc_path)
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100576 + STRLEN(search_ctx->ffsc_fix_path + len)
Bram Moolenaar51e14382019-05-25 20:21:28 +0200577 + 1);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100578 if (temp == NULL || wc_path == NULL)
579 {
580 vim_free(buf);
581 vim_free(temp);
582 vim_free(wc_path);
583 goto error_return;
584 }
585
586 STRCPY(temp, search_ctx->ffsc_fix_path + len);
587 STRCAT(temp, search_ctx->ffsc_wc_path);
588 vim_free(search_ctx->ffsc_wc_path);
589 vim_free(wc_path);
590 search_ctx->ffsc_wc_path = temp;
591 }
592 }
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100593 vim_free(buf);
594 }
595
596 sptr = ff_create_stack_element(ff_expand_buffer,
Bram Moolenaar2bd9dbc2022-08-25 18:12:06 +0100597 search_ctx->ffsc_wc_path, level, 0);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100598
599 if (sptr == NULL)
600 goto error_return;
601
602 ff_push(search_ctx, sptr);
603
604 search_ctx->ffsc_file_to_search = vim_strsave(filename);
605 if (search_ctx->ffsc_file_to_search == NULL)
606 goto error_return;
607
608 return search_ctx;
609
610error_return:
611 /*
612 * We clear the search context now!
613 * Even when the caller gave us a (perhaps valid) context we free it here,
614 * as we might have already destroyed it.
615 */
616 vim_findfile_cleanup(search_ctx);
617 return NULL;
618}
619
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100620/*
621 * Get the stopdir string. Check that ';' is not escaped.
622 */
623 char_u *
624vim_findfile_stopdir(char_u *buf)
625{
626 char_u *r_ptr = buf;
627
628 while (*r_ptr != NUL && *r_ptr != ';')
629 {
630 if (r_ptr[0] == '\\' && r_ptr[1] == ';')
631 {
632 // Overwrite the escape char,
633 // use STRLEN(r_ptr) to move the trailing '\0'.
634 STRMOVE(r_ptr, r_ptr + 1);
635 r_ptr++;
636 }
637 r_ptr++;
638 }
639 if (*r_ptr == ';')
640 {
641 *r_ptr = 0;
642 r_ptr++;
643 }
644 else if (*r_ptr == NUL)
645 r_ptr = NULL;
646 return r_ptr;
647}
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100648
649/*
650 * Clean up the given search context. Can handle a NULL pointer.
651 */
652 void
653vim_findfile_cleanup(void *ctx)
654{
655 if (ctx == NULL)
656 return;
657
658 vim_findfile_free_visited(ctx);
659 ff_clear(ctx);
660 vim_free(ctx);
661}
662
663/*
664 * Find a file in a search context.
665 * The search context was created with vim_findfile_init() above.
666 * Return a pointer to an allocated file name or NULL if nothing found.
667 * To get all matching files call this function until you get NULL.
668 *
669 * If the passed search_context is NULL, NULL is returned.
670 *
671 * The search algorithm is depth first. To change this replace the
672 * stack with a list (don't forget to leave partly searched directories on the
673 * top of the list).
674 */
675 char_u *
676vim_findfile(void *search_ctx_arg)
677{
678 char_u *file_path;
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100679 char_u *rest_of_wildcards;
680 char_u *path_end = NULL;
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100681 ff_stack_T *stackp;
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100682 int len;
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100683 int i;
684 char_u *p;
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100685 char_u *suf;
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100686 ff_search_ctx_T *search_ctx;
687
688 if (search_ctx_arg == NULL)
689 return NULL;
690
691 search_ctx = (ff_search_ctx_T *)search_ctx_arg;
692
693 /*
694 * filepath is used as buffer for various actions and as the storage to
695 * return a found filename.
696 */
Bram Moolenaar51e14382019-05-25 20:21:28 +0200697 if ((file_path = alloc(MAXPATHL)) == NULL)
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100698 return NULL;
699
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100700 // store the end of the start dir -- needed for upward search
701 if (search_ctx->ffsc_start_dir != NULL)
702 path_end = &search_ctx->ffsc_start_dir[
703 STRLEN(search_ctx->ffsc_start_dir)];
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100704
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100705 // upward search loop
706 for (;;)
707 {
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100708 // downward search loop
709 for (;;)
710 {
Dominique Pelleaf4a61a2021-12-27 17:21:41 +0000711 // check if user wants to stop the search
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100712 ui_breakcheck();
713 if (got_int)
714 break;
715
716 // get directory to work on from stack
717 stackp = ff_pop(search_ctx);
718 if (stackp == NULL)
719 break;
720
721 /*
722 * TODO: decide if we leave this test in
723 *
724 * GOOD: don't search a directory(-tree) twice.
725 * BAD: - check linked list for every new directory entered.
726 * - check for double files also done below
727 *
728 * Here we check if we already searched this directory.
729 * We already searched a directory if:
730 * 1) The directory is the same.
731 * 2) We would use the same wildcard string.
732 *
733 * Good if you have links on same directory via several ways
734 * or you have selfreferences in directories (e.g. SuSE Linux 6.3:
735 * /etc/rc.d/init.d is linked to /etc/rc.d -> endless loop)
736 *
737 * This check is only needed for directories we work on for the
738 * first time (hence stackp->ff_filearray == NULL)
739 */
740 if (stackp->ffs_filearray == NULL
741 && ff_check_visited(&search_ctx->ffsc_dir_visited_list
742 ->ffvl_visited_list,
Bram Moolenaar2bd9dbc2022-08-25 18:12:06 +0100743 stackp->ffs_fix_path, stackp->ffs_wc_path) == FAIL)
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100744 {
745#ifdef FF_VERBOSE
746 if (p_verbose >= 5)
747 {
748 verbose_enter_scroll();
749 smsg("Already Searched: %s (%s)",
750 stackp->ffs_fix_path, stackp->ffs_wc_path);
751 // don't overwrite this either
752 msg_puts("\n");
753 verbose_leave_scroll();
754 }
755#endif
756 ff_free_stack_element(stackp);
757 continue;
758 }
759#ifdef FF_VERBOSE
760 else if (p_verbose >= 5)
761 {
762 verbose_enter_scroll();
763 smsg("Searching: %s (%s)",
764 stackp->ffs_fix_path, stackp->ffs_wc_path);
765 // don't overwrite this either
766 msg_puts("\n");
767 verbose_leave_scroll();
768 }
769#endif
770
771 // check depth
772 if (stackp->ffs_level <= 0)
773 {
774 ff_free_stack_element(stackp);
775 continue;
776 }
777
778 file_path[0] = NUL;
779
780 /*
781 * If no filearray till now expand wildcards
782 * The function expand_wildcards() can handle an array of paths
783 * and all possible expands are returned in one array. We use this
784 * to handle the expansion of '**' into an empty string.
785 */
786 if (stackp->ffs_filearray == NULL)
787 {
788 char_u *dirptrs[2];
789
790 // we use filepath to build the path expand_wildcards() should
791 // expand.
792 dirptrs[0] = file_path;
793 dirptrs[1] = NULL;
794
795 // if we have a start dir copy it in
796 if (!vim_isAbsName(stackp->ffs_fix_path)
797 && search_ctx->ffsc_start_dir)
798 {
799 if (STRLEN(search_ctx->ffsc_start_dir) + 1 < MAXPATHL)
800 {
801 STRCPY(file_path, search_ctx->ffsc_start_dir);
802 add_pathsep(file_path);
803 }
804 else
805 {
806 ff_free_stack_element(stackp);
807 goto fail;
808 }
809 }
810
811 // append the fix part of the search path
812 if (STRLEN(file_path) + STRLEN(stackp->ffs_fix_path) + 1
813 < MAXPATHL)
814 {
815 STRCAT(file_path, stackp->ffs_fix_path);
816 add_pathsep(file_path);
817 }
818 else
819 {
820 ff_free_stack_element(stackp);
821 goto fail;
822 }
823
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100824 rest_of_wildcards = stackp->ffs_wc_path;
825 if (*rest_of_wildcards != NUL)
826 {
827 len = (int)STRLEN(file_path);
828 if (STRNCMP(rest_of_wildcards, "**", 2) == 0)
829 {
830 // pointer to the restrict byte
831 // The restrict byte is not a character!
832 p = rest_of_wildcards + 2;
833
834 if (*p > 0)
835 {
836 (*p)--;
837 if (len + 1 < MAXPATHL)
838 file_path[len++] = '*';
839 else
840 {
841 ff_free_stack_element(stackp);
842 goto fail;
843 }
844 }
845
846 if (*p == 0)
847 {
848 // remove '**<numb> from wildcards
849 STRMOVE(rest_of_wildcards, rest_of_wildcards + 3);
850 }
851 else
852 rest_of_wildcards += 3;
853
854 if (stackp->ffs_star_star_empty == 0)
855 {
856 // if not done before, expand '**' to empty
857 stackp->ffs_star_star_empty = 1;
858 dirptrs[1] = stackp->ffs_fix_path;
859 }
860 }
861
862 /*
863 * Here we copy until the next path separator or the end of
864 * the path. If we stop at a path separator, there is
865 * still something else left. This is handled below by
866 * pushing every directory returned from expand_wildcards()
867 * on the stack again for further search.
868 */
869 while (*rest_of_wildcards
870 && !vim_ispathsep(*rest_of_wildcards))
871 if (len + 1 < MAXPATHL)
872 file_path[len++] = *rest_of_wildcards++;
873 else
874 {
875 ff_free_stack_element(stackp);
876 goto fail;
877 }
878
879 file_path[len] = NUL;
880 if (vim_ispathsep(*rest_of_wildcards))
881 rest_of_wildcards++;
882 }
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100883
884 /*
885 * Expand wildcards like "*" and "$VAR".
886 * If the path is a URL don't try this.
887 */
888 if (path_with_url(dirptrs[0]))
889 {
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200890 stackp->ffs_filearray = ALLOC_ONE(char_u *);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100891 if (stackp->ffs_filearray != NULL
892 && (stackp->ffs_filearray[0]
893 = vim_strsave(dirptrs[0])) != NULL)
894 stackp->ffs_filearray_size = 1;
895 else
896 stackp->ffs_filearray_size = 0;
897 }
898 else
899 // Add EW_NOTWILD because the expanded path may contain
900 // wildcard characters that are to be taken literally.
901 // This is a bit of a hack.
902 expand_wildcards((dirptrs[1] == NULL) ? 1 : 2, dirptrs,
903 &stackp->ffs_filearray_size,
904 &stackp->ffs_filearray,
905 EW_DIR|EW_ADDSLASH|EW_SILENT|EW_NOTWILD);
906
907 stackp->ffs_filearray_cur = 0;
908 stackp->ffs_stage = 0;
909 }
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100910 else
911 rest_of_wildcards = &stackp->ffs_wc_path[
912 STRLEN(stackp->ffs_wc_path)];
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100913
914 if (stackp->ffs_stage == 0)
915 {
916 // this is the first time we work on this directory
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100917 if (*rest_of_wildcards == NUL)
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100918 {
919 /*
920 * We don't have further wildcards to expand, so we have to
921 * check for the final file now.
922 */
923 for (i = stackp->ffs_filearray_cur;
924 i < stackp->ffs_filearray_size; ++i)
925 {
926 if (!path_with_url(stackp->ffs_filearray[i])
927 && !mch_isdir(stackp->ffs_filearray[i]))
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100928 continue; // not a directory
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100929
930 // prepare the filename to be checked for existence
931 // below
932 if (STRLEN(stackp->ffs_filearray[i]) + 1
933 + STRLEN(search_ctx->ffsc_file_to_search)
934 < MAXPATHL)
935 {
936 STRCPY(file_path, stackp->ffs_filearray[i]);
937 add_pathsep(file_path);
938 STRCAT(file_path, search_ctx->ffsc_file_to_search);
939 }
940 else
941 {
942 ff_free_stack_element(stackp);
943 goto fail;
944 }
945
946 /*
947 * Try without extra suffix and then with suffixes
948 * from 'suffixesadd'.
949 */
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100950 len = (int)STRLEN(file_path);
951 if (search_ctx->ffsc_tagfile)
952 suf = (char_u *)"";
953 else
954 suf = curbuf->b_p_sua;
955 for (;;)
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100956 {
957 // if file exists and we didn't already find it
958 if ((path_with_url(file_path)
959 || (mch_getperm(file_path) >= 0
960 && (search_ctx->ffsc_find_what
961 == FINDFILE_BOTH
962 || ((search_ctx->ffsc_find_what
963 == FINDFILE_DIR)
964 == mch_isdir(file_path)))))
965#ifndef FF_VERBOSE
966 && (ff_check_visited(
Bram Moolenaar2bd9dbc2022-08-25 18:12:06 +0100967 &search_ctx->ffsc_visited_list
968 ->ffvl_visited_list,
969 file_path, (char_u *)"") == OK)
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100970#endif
971 )
972 {
973#ifdef FF_VERBOSE
974 if (ff_check_visited(
Bram Moolenaar2bd9dbc2022-08-25 18:12:06 +0100975 &search_ctx->ffsc_visited_list
976 ->ffvl_visited_list,
977 file_path, (char_u *)"") == FAIL)
Bram Moolenaar5fd0f502019-02-13 23:13:28 +0100978 {
979 if (p_verbose >= 5)
980 {
981 verbose_enter_scroll();
982 smsg("Already: %s",
983 file_path);
984 // don't overwrite this either
985 msg_puts("\n");
986 verbose_leave_scroll();
987 }
988 continue;
989 }
990#endif
991
992 // push dir to examine rest of subdirs later
993 stackp->ffs_filearray_cur = i + 1;
994 ff_push(search_ctx, stackp);
995
996 if (!path_with_url(file_path))
997 simplify_filename(file_path);
998 if (mch_dirname(ff_expand_buffer, MAXPATHL)
999 == OK)
1000 {
1001 p = shorten_fname(file_path,
1002 ff_expand_buffer);
1003 if (p != NULL)
1004 STRMOVE(file_path, p);
1005 }
1006#ifdef FF_VERBOSE
1007 if (p_verbose >= 5)
1008 {
1009 verbose_enter_scroll();
1010 smsg("HIT: %s", file_path);
1011 // don't overwrite this either
1012 msg_puts("\n");
1013 verbose_leave_scroll();
1014 }
1015#endif
1016 return file_path;
1017 }
1018
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001019 // Not found or found already, try next suffix.
1020 if (*suf == NUL)
1021 break;
1022 copy_option_part(&suf, file_path + len,
1023 MAXPATHL - len, ",");
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001024 }
1025 }
1026 }
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001027 else
1028 {
1029 /*
1030 * still wildcards left, push the directories for further
1031 * search
1032 */
1033 for (i = stackp->ffs_filearray_cur;
1034 i < stackp->ffs_filearray_size; ++i)
1035 {
1036 if (!mch_isdir(stackp->ffs_filearray[i]))
1037 continue; // not a directory
1038
1039 ff_push(search_ctx,
1040 ff_create_stack_element(
1041 stackp->ffs_filearray[i],
1042 rest_of_wildcards,
1043 stackp->ffs_level - 1, 0));
1044 }
1045 }
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001046 stackp->ffs_filearray_cur = 0;
1047 stackp->ffs_stage = 1;
1048 }
1049
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001050 /*
1051 * if wildcards contains '**' we have to descent till we reach the
1052 * leaves of the directory tree.
1053 */
1054 if (STRNCMP(stackp->ffs_wc_path, "**", 2) == 0)
1055 {
1056 for (i = stackp->ffs_filearray_cur;
1057 i < stackp->ffs_filearray_size; ++i)
1058 {
1059 if (fnamecmp(stackp->ffs_filearray[i],
1060 stackp->ffs_fix_path) == 0)
1061 continue; // don't repush same directory
1062 if (!mch_isdir(stackp->ffs_filearray[i]))
1063 continue; // not a directory
1064 ff_push(search_ctx,
1065 ff_create_stack_element(stackp->ffs_filearray[i],
1066 stackp->ffs_wc_path, stackp->ffs_level - 1, 1));
1067 }
1068 }
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001069
1070 // we are done with the current directory
1071 ff_free_stack_element(stackp);
1072
1073 }
1074
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001075 // If we reached this, we didn't find anything downwards.
1076 // Let's check if we should do an upward search.
1077 if (search_ctx->ffsc_start_dir
1078 && search_ctx->ffsc_stopdirs_v != NULL && !got_int)
1079 {
1080 ff_stack_T *sptr;
1081
1082 // is the last starting directory in the stop list?
1083 if (ff_path_in_stoplist(search_ctx->ffsc_start_dir,
1084 (int)(path_end - search_ctx->ffsc_start_dir),
1085 search_ctx->ffsc_stopdirs_v) == TRUE)
1086 break;
1087
1088 // cut of last dir
1089 while (path_end > search_ctx->ffsc_start_dir
1090 && vim_ispathsep(*path_end))
1091 path_end--;
1092 while (path_end > search_ctx->ffsc_start_dir
1093 && !vim_ispathsep(path_end[-1]))
1094 path_end--;
1095 *path_end = 0;
1096 path_end--;
1097
1098 if (*search_ctx->ffsc_start_dir == 0)
1099 break;
1100
1101 if (STRLEN(search_ctx->ffsc_start_dir) + 1
1102 + STRLEN(search_ctx->ffsc_fix_path) < MAXPATHL)
1103 {
1104 STRCPY(file_path, search_ctx->ffsc_start_dir);
1105 add_pathsep(file_path);
1106 STRCAT(file_path, search_ctx->ffsc_fix_path);
1107 }
1108 else
1109 goto fail;
1110
1111 // create a new stack entry
1112 sptr = ff_create_stack_element(file_path,
1113 search_ctx->ffsc_wc_path, search_ctx->ffsc_level, 0);
1114 if (sptr == NULL)
1115 break;
1116 ff_push(search_ctx, sptr);
1117 }
1118 else
1119 break;
1120 }
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001121
1122fail:
1123 vim_free(file_path);
1124 return NULL;
1125}
1126
1127/*
1128 * Free the list of lists of visited files and directories
1129 * Can handle it if the passed search_context is NULL;
1130 */
Bram Moolenaar5843f5f2019-08-20 20:13:45 +02001131 static void
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001132vim_findfile_free_visited(void *search_ctx_arg)
1133{
1134 ff_search_ctx_T *search_ctx;
1135
1136 if (search_ctx_arg == NULL)
1137 return;
1138
1139 search_ctx = (ff_search_ctx_T *)search_ctx_arg;
1140 vim_findfile_free_visited_list(&search_ctx->ffsc_visited_lists_list);
1141 vim_findfile_free_visited_list(&search_ctx->ffsc_dir_visited_lists_list);
1142}
1143
1144 static void
1145vim_findfile_free_visited_list(ff_visited_list_hdr_T **list_headp)
1146{
1147 ff_visited_list_hdr_T *vp;
1148
1149 while (*list_headp != NULL)
1150 {
1151 vp = (*list_headp)->ffvl_next;
1152 ff_free_visited_list((*list_headp)->ffvl_visited_list);
1153
1154 vim_free((*list_headp)->ffvl_filename);
1155 vim_free(*list_headp);
1156 *list_headp = vp;
1157 }
1158 *list_headp = NULL;
1159}
1160
1161 static void
1162ff_free_visited_list(ff_visited_T *vl)
1163{
1164 ff_visited_T *vp;
1165
1166 while (vl != NULL)
1167 {
1168 vp = vl->ffv_next;
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001169 vim_free(vl->ffv_wc_path);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001170 vim_free(vl);
1171 vl = vp;
1172 }
1173 vl = NULL;
1174}
1175
1176/*
1177 * Returns the already visited list for the given filename. If none is found it
1178 * allocates a new one.
1179 */
1180 static ff_visited_list_hdr_T*
1181ff_get_visited_list(
1182 char_u *filename,
1183 ff_visited_list_hdr_T **list_headp)
1184{
1185 ff_visited_list_hdr_T *retptr = NULL;
1186
1187 // check if a visited list for the given filename exists
1188 if (*list_headp != NULL)
1189 {
1190 retptr = *list_headp;
1191 while (retptr != NULL)
1192 {
1193 if (fnamecmp(filename, retptr->ffvl_filename) == 0)
1194 {
1195#ifdef FF_VERBOSE
1196 if (p_verbose >= 5)
1197 {
1198 verbose_enter_scroll();
1199 smsg("ff_get_visited_list: FOUND list for %s",
1200 filename);
1201 // don't overwrite this either
1202 msg_puts("\n");
1203 verbose_leave_scroll();
1204 }
1205#endif
1206 return retptr;
1207 }
1208 retptr = retptr->ffvl_next;
1209 }
1210 }
1211
1212#ifdef FF_VERBOSE
1213 if (p_verbose >= 5)
1214 {
1215 verbose_enter_scroll();
1216 smsg("ff_get_visited_list: new list for %s", filename);
1217 // don't overwrite this either
1218 msg_puts("\n");
1219 verbose_leave_scroll();
1220 }
1221#endif
1222
1223 /*
1224 * if we reach this we didn't find a list and we have to allocate new list
1225 */
Bram Moolenaarc799fe22019-05-28 23:08:19 +02001226 retptr = ALLOC_ONE(ff_visited_list_hdr_T);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001227 if (retptr == NULL)
1228 return NULL;
1229
1230 retptr->ffvl_visited_list = NULL;
1231 retptr->ffvl_filename = vim_strsave(filename);
1232 if (retptr->ffvl_filename == NULL)
1233 {
1234 vim_free(retptr);
1235 return NULL;
1236 }
1237 retptr->ffvl_next = *list_headp;
1238 *list_headp = retptr;
1239
1240 return retptr;
1241}
1242
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001243/*
1244 * check if two wildcard paths are equal. Returns TRUE or FALSE.
1245 * They are equal if:
1246 * - both paths are NULL
1247 * - they have the same length
1248 * - char by char comparison is OK
1249 * - the only differences are in the counters behind a '**', so
1250 * '**\20' is equal to '**\24'
1251 */
1252 static int
1253ff_wc_equal(char_u *s1, char_u *s2)
1254{
1255 int i, j;
1256 int c1 = NUL;
1257 int c2 = NUL;
1258 int prev1 = NUL;
1259 int prev2 = NUL;
1260
1261 if (s1 == s2)
1262 return TRUE;
1263
1264 if (s1 == NULL || s2 == NULL)
1265 return FALSE;
1266
1267 for (i = 0, j = 0; s1[i] != NUL && s2[j] != NUL;)
1268 {
1269 c1 = PTR2CHAR(s1 + i);
1270 c2 = PTR2CHAR(s2 + j);
1271
1272 if ((p_fic ? MB_TOLOWER(c1) != MB_TOLOWER(c2) : c1 != c2)
1273 && (prev1 != '*' || prev2 != '*'))
1274 return FALSE;
1275 prev2 = prev1;
1276 prev1 = c1;
1277
Bram Moolenaar1614a142019-10-06 22:00:13 +02001278 i += mb_ptr2len(s1 + i);
1279 j += mb_ptr2len(s2 + j);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001280 }
1281 return s1[i] == s2[j];
1282}
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001283
1284/*
1285 * maintains the list of already visited files and dirs
1286 * returns FAIL if the given file/dir is already in the list
1287 * returns OK if it is newly added
1288 *
1289 * TODO: What to do on memory allocation problems?
1290 * -> return TRUE - Better the file is found several times instead of
1291 * never.
1292 */
1293 static int
1294ff_check_visited(
1295 ff_visited_T **visited_list,
Bram Moolenaar2bd9dbc2022-08-25 18:12:06 +01001296 char_u *fname,
1297 char_u *wc_path)
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001298{
1299 ff_visited_T *vp;
1300#ifdef UNIX
1301 stat_T st;
1302 int url = FALSE;
1303#endif
1304
Dominique Pelleaf4a61a2021-12-27 17:21:41 +00001305 // For a URL we only compare the name, otherwise we compare the
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001306 // device/inode (unix) or the full path name (not Unix).
1307 if (path_with_url(fname))
1308 {
1309 vim_strncpy(ff_expand_buffer, fname, MAXPATHL - 1);
1310#ifdef UNIX
1311 url = TRUE;
1312#endif
1313 }
1314 else
1315 {
1316 ff_expand_buffer[0] = NUL;
1317#ifdef UNIX
1318 if (mch_stat((char *)fname, &st) < 0)
1319#else
1320 if (vim_FullName(fname, ff_expand_buffer, MAXPATHL, TRUE) == FAIL)
1321#endif
1322 return FAIL;
1323 }
1324
1325 // check against list of already visited files
1326 for (vp = *visited_list; vp != NULL; vp = vp->ffv_next)
1327 {
1328 if (
1329#ifdef UNIX
1330 !url ? (vp->ffv_dev_valid && vp->ffv_dev == st.st_dev
1331 && vp->ffv_ino == st.st_ino)
1332 :
1333#endif
1334 fnamecmp(vp->ffv_fname, ff_expand_buffer) == 0
1335 )
1336 {
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001337 // are the wildcard parts equal
1338 if (ff_wc_equal(vp->ffv_wc_path, wc_path) == TRUE)
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001339 // already visited
1340 return FAIL;
1341 }
1342 }
1343
1344 /*
1345 * New file/dir. Add it to the list of visited files/dirs.
1346 */
zeertzjq1b438a82023-02-01 13:11:15 +00001347 vp = alloc(
1348 offsetof(ff_visited_T, ffv_fname) + STRLEN(ff_expand_buffer) + 1);
Yegappan Lakshmanan1cfb14a2023-01-09 19:04:23 +00001349 if (vp == NULL)
1350 return OK;
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001351
Yegappan Lakshmanan1cfb14a2023-01-09 19:04:23 +00001352#ifdef UNIX
1353 if (!url)
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001354 {
Yegappan Lakshmanan1cfb14a2023-01-09 19:04:23 +00001355 vp->ffv_dev_valid = TRUE;
1356 vp->ffv_ino = st.st_ino;
1357 vp->ffv_dev = st.st_dev;
1358 vp->ffv_fname[0] = NUL;
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001359 }
Yegappan Lakshmanan1cfb14a2023-01-09 19:04:23 +00001360 else
1361 {
1362 vp->ffv_dev_valid = FALSE;
1363#endif
1364 STRCPY(vp->ffv_fname, ff_expand_buffer);
1365#ifdef UNIX
1366 }
1367#endif
1368 if (wc_path != NULL)
1369 vp->ffv_wc_path = vim_strsave(wc_path);
1370 else
1371 vp->ffv_wc_path = NULL;
1372
1373 vp->ffv_next = *visited_list;
1374 *visited_list = vp;
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001375
1376 return OK;
1377}
1378
1379/*
1380 * create stack element from given path pieces
1381 */
1382 static ff_stack_T *
1383ff_create_stack_element(
1384 char_u *fix_part,
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001385 char_u *wc_part,
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001386 int level,
1387 int star_star_empty)
1388{
1389 ff_stack_T *new;
1390
Bram Moolenaarc799fe22019-05-28 23:08:19 +02001391 new = ALLOC_ONE(ff_stack_T);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001392 if (new == NULL)
1393 return NULL;
1394
1395 new->ffs_prev = NULL;
1396 new->ffs_filearray = NULL;
1397 new->ffs_filearray_size = 0;
1398 new->ffs_filearray_cur = 0;
1399 new->ffs_stage = 0;
1400 new->ffs_level = level;
1401 new->ffs_star_star_empty = star_star_empty;
1402
1403 // the following saves NULL pointer checks in vim_findfile
1404 if (fix_part == NULL)
1405 fix_part = (char_u *)"";
1406 new->ffs_fix_path = vim_strsave(fix_part);
1407
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001408 if (wc_part == NULL)
1409 wc_part = (char_u *)"";
1410 new->ffs_wc_path = vim_strsave(wc_part);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001411
Bram Moolenaar2bd9dbc2022-08-25 18:12:06 +01001412 if (new->ffs_fix_path == NULL || new->ffs_wc_path == NULL)
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001413 {
1414 ff_free_stack_element(new);
1415 new = NULL;
1416 }
1417
1418 return new;
1419}
1420
1421/*
1422 * Push a dir on the directory stack.
1423 */
1424 static void
1425ff_push(ff_search_ctx_T *search_ctx, ff_stack_T *stack_ptr)
1426{
1427 // check for NULL pointer, not to return an error to the user, but
1428 // to prevent a crash
Yegappan Lakshmanan7f8b2552023-01-08 13:44:24 +00001429 if (stack_ptr == NULL)
1430 return;
1431
1432 stack_ptr->ffs_prev = search_ctx->ffsc_stack_ptr;
1433 search_ctx->ffsc_stack_ptr = stack_ptr;
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001434}
1435
1436/*
1437 * Pop a dir from the directory stack.
1438 * Returns NULL if stack is empty.
1439 */
1440 static ff_stack_T *
1441ff_pop(ff_search_ctx_T *search_ctx)
1442{
1443 ff_stack_T *sptr;
1444
1445 sptr = search_ctx->ffsc_stack_ptr;
1446 if (search_ctx->ffsc_stack_ptr != NULL)
1447 search_ctx->ffsc_stack_ptr = search_ctx->ffsc_stack_ptr->ffs_prev;
1448
1449 return sptr;
1450}
1451
1452/*
1453 * free the given stack element
1454 */
1455 static void
1456ff_free_stack_element(ff_stack_T *stack_ptr)
1457{
1458 // vim_free handles possible NULL pointers
1459 vim_free(stack_ptr->ffs_fix_path);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001460 vim_free(stack_ptr->ffs_wc_path);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001461
1462 if (stack_ptr->ffs_filearray != NULL)
1463 FreeWild(stack_ptr->ffs_filearray_size, stack_ptr->ffs_filearray);
1464
1465 vim_free(stack_ptr);
1466}
1467
1468/*
1469 * Clear the search context, but NOT the visited list.
1470 */
1471 static void
1472ff_clear(ff_search_ctx_T *search_ctx)
1473{
1474 ff_stack_T *sptr;
1475
1476 // clear up stack
1477 while ((sptr = ff_pop(search_ctx)) != NULL)
1478 ff_free_stack_element(sptr);
1479
1480 vim_free(search_ctx->ffsc_file_to_search);
1481 vim_free(search_ctx->ffsc_start_dir);
1482 vim_free(search_ctx->ffsc_fix_path);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001483 vim_free(search_ctx->ffsc_wc_path);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001484
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001485 if (search_ctx->ffsc_stopdirs_v != NULL)
1486 {
1487 int i = 0;
1488
1489 while (search_ctx->ffsc_stopdirs_v[i] != NULL)
1490 {
1491 vim_free(search_ctx->ffsc_stopdirs_v[i]);
1492 i++;
1493 }
1494 vim_free(search_ctx->ffsc_stopdirs_v);
1495 }
1496 search_ctx->ffsc_stopdirs_v = NULL;
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001497
1498 // reset everything
1499 search_ctx->ffsc_file_to_search = NULL;
1500 search_ctx->ffsc_start_dir = NULL;
1501 search_ctx->ffsc_fix_path = NULL;
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001502 search_ctx->ffsc_wc_path = NULL;
1503 search_ctx->ffsc_level = 0;
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001504}
1505
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001506/*
1507 * check if the given path is in the stopdirs
1508 * returns TRUE if yes else FALSE
1509 */
1510 static int
1511ff_path_in_stoplist(char_u *path, int path_len, char_u **stopdirs_v)
1512{
1513 int i = 0;
1514
1515 // eat up trailing path separators, except the first
1516 while (path_len > 1 && vim_ispathsep(path[path_len - 1]))
1517 path_len--;
1518
1519 // if no path consider it as match
1520 if (path_len == 0)
1521 return TRUE;
1522
1523 for (i = 0; stopdirs_v[i] != NULL; i++)
1524 {
1525 if ((int)STRLEN(stopdirs_v[i]) > path_len)
1526 {
1527 // match for parent directory. So '/home' also matches
1528 // '/home/rks'. Check for PATHSEP in stopdirs_v[i], else
1529 // '/home/r' would also match '/home/rks'
1530 if (fnamencmp(stopdirs_v[i], path, path_len) == 0
1531 && vim_ispathsep(stopdirs_v[i][path_len]))
1532 return TRUE;
1533 }
1534 else
1535 {
1536 if (fnamecmp(stopdirs_v[i], path) == 0)
1537 return TRUE;
1538 }
1539 }
1540 return FALSE;
1541}
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001542
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001543/*
1544 * Find the file name "ptr[len]" in the path. Also finds directory names.
1545 *
1546 * On the first call set the parameter 'first' to TRUE to initialize
1547 * the search. For repeating calls to FALSE.
1548 *
1549 * Repeating calls will return other files called 'ptr[len]' from the path.
1550 *
1551 * Only on the first call 'ptr' and 'len' are used. For repeating calls they
1552 * don't need valid values.
1553 *
1554 * If nothing found on the first call the option FNAME_MESS will issue the
1555 * message:
1556 * 'Can't find file "<file>" in path'
1557 * On repeating calls:
1558 * 'No more file "<file>" found in path'
1559 *
1560 * options:
1561 * FNAME_MESS give error message when not found
1562 *
1563 * Uses NameBuff[]!
1564 *
1565 * Returns an allocated string for the file name. NULL for error.
1566 *
1567 */
1568 char_u *
1569find_file_in_path(
1570 char_u *ptr, // file name
1571 int len, // length of file name
1572 int options,
1573 int first, // use count'th matching file name
Bram Moolenaar5145c9a2023-03-11 13:55:53 +00001574 char_u *rel_fname, // file name searching relative to
1575 char_u **file_to_find, // in/out: modified copy of file name
1576 char **search_ctx) // in/out: state of the search
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001577{
1578 return find_file_in_path_option(ptr, len, options, first,
1579 *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path,
Bram Moolenaar5145c9a2023-03-11 13:55:53 +00001580 FINDFILE_BOTH, rel_fname, curbuf->b_p_sua,
1581 file_to_find, search_ctx);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001582}
1583
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001584# if defined(EXITFREE) || defined(PROTO)
1585 void
1586free_findfile(void)
1587{
Bram Moolenaar5145c9a2023-03-11 13:55:53 +00001588 VIM_CLEAR(ff_expand_buffer);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001589}
1590# endif
1591
1592/*
1593 * Find the directory name "ptr[len]" in the path.
1594 *
1595 * options:
1596 * FNAME_MESS give error message when not found
1597 * FNAME_UNESC unescape backslashes.
1598 *
1599 * Uses NameBuff[]!
1600 *
1601 * Returns an allocated string for the file name. NULL for error.
1602 */
1603 char_u *
1604find_directory_in_path(
1605 char_u *ptr, // file name
1606 int len, // length of file name
1607 int options,
Bram Moolenaar5145c9a2023-03-11 13:55:53 +00001608 char_u *rel_fname, // file name searching relative to
1609 char_u **file_to_find, // in/out: modified copy of file name
1610 char **search_ctx) // in/out: state of the search
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001611{
1612 return find_file_in_path_option(ptr, len, options, TRUE, p_cdpath,
Bram Moolenaar5145c9a2023-03-11 13:55:53 +00001613 FINDFILE_DIR, rel_fname, (char_u *)"",
1614 file_to_find, search_ctx);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001615}
1616
1617 char_u *
1618find_file_in_path_option(
1619 char_u *ptr, // file name
1620 int len, // length of file name
1621 int options,
1622 int first, // use count'th matching file name
1623 char_u *path_option, // p_path or p_cdpath
1624 int find_what, // FINDFILE_FILE, _DIR or _BOTH
1625 char_u *rel_fname, // file name we are looking relative to.
Bram Moolenaar5145c9a2023-03-11 13:55:53 +00001626 char_u *suffixes, // list of suffixes, 'suffixesadd' option
1627 char_u **file_to_find, // in/out: modified copy of file name
1628 char **search_ctx_arg) // in/out: state of the search
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001629{
Bram Moolenaar5145c9a2023-03-11 13:55:53 +00001630 ff_search_ctx_T **search_ctx = (ff_search_ctx_T **)search_ctx_arg;
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001631 static char_u *dir;
1632 static int did_findfile_init = FALSE;
1633 char_u save_char;
1634 char_u *file_name = NULL;
1635 char_u *buf = NULL;
1636 int rel_to_curdir;
1637# ifdef AMIGA
1638 struct Process *proc = (struct Process *)FindTask(0L);
1639 APTR save_winptr = proc->pr_WindowPtr;
1640
1641 // Avoid a requester here for a volume that doesn't exist.
1642 proc->pr_WindowPtr = (APTR)-1L;
1643# endif
1644
1645 if (first == TRUE)
1646 {
Bram Moolenaare015d992021-11-17 19:01:53 +00001647 if (len == 0)
1648 return NULL;
1649
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001650 // copy file name into NameBuff, expanding environment variables
1651 save_char = ptr[len];
1652 ptr[len] = NUL;
1653 expand_env_esc(ptr, NameBuff, MAXPATHL, FALSE, TRUE, NULL);
1654 ptr[len] = save_char;
1655
Bram Moolenaar5145c9a2023-03-11 13:55:53 +00001656 vim_free(*file_to_find);
1657 *file_to_find = vim_strsave(NameBuff);
1658 if (*file_to_find == NULL) // out of memory
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001659 {
1660 file_name = NULL;
1661 goto theend;
1662 }
1663 if (options & FNAME_UNESC)
1664 {
1665 // Change all "\ " to " ".
Bram Moolenaar5145c9a2023-03-11 13:55:53 +00001666 for (ptr = *file_to_find; *ptr != NUL; ++ptr)
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001667 if (ptr[0] == '\\' && ptr[1] == ' ')
1668 mch_memmove(ptr, ptr + 1, STRLEN(ptr));
1669 }
1670 }
1671
Bram Moolenaar5145c9a2023-03-11 13:55:53 +00001672 rel_to_curdir = ((*file_to_find)[0] == '.'
1673 && ((*file_to_find)[1] == NUL
1674 || vim_ispathsep((*file_to_find)[1])
1675 || ((*file_to_find)[1] == '.'
1676 && ((*file_to_find)[2] == NUL
1677 || vim_ispathsep((*file_to_find)[2])))));
1678 if (vim_isAbsName(*file_to_find)
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001679 // "..", "../path", "." and "./path": don't use the path_option
1680 || rel_to_curdir
1681# if defined(MSWIN)
1682 // handle "\tmp" as absolute path
Bram Moolenaar5145c9a2023-03-11 13:55:53 +00001683 || vim_ispathsep((*file_to_find)[0])
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001684 // handle "c:name" as absolute path
Bram Moolenaar5145c9a2023-03-11 13:55:53 +00001685 || ((*file_to_find)[0] != NUL && (*file_to_find)[1] == ':')
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001686# endif
1687# ifdef AMIGA
1688 // handle ":tmp" as absolute path
Bram Moolenaar5145c9a2023-03-11 13:55:53 +00001689 || (*file_to_find)[0] == ':'
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001690# endif
1691 )
1692 {
1693 /*
1694 * Absolute path, no need to use "path_option".
1695 * If this is not a first call, return NULL. We already returned a
1696 * filename on the first call.
1697 */
1698 if (first == TRUE)
1699 {
1700 int l;
1701 int run;
1702
Bram Moolenaar5145c9a2023-03-11 13:55:53 +00001703 if (path_with_url(*file_to_find))
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001704 {
Bram Moolenaar5145c9a2023-03-11 13:55:53 +00001705 file_name = vim_strsave(*file_to_find);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001706 goto theend;
1707 }
1708
1709 // When FNAME_REL flag given first use the directory of the file.
1710 // Otherwise or when this fails use the current directory.
1711 for (run = 1; run <= 2; ++run)
1712 {
Bram Moolenaar5145c9a2023-03-11 13:55:53 +00001713 l = (int)STRLEN(*file_to_find);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001714 if (run == 1
1715 && rel_to_curdir
1716 && (options & FNAME_REL)
1717 && rel_fname != NULL
1718 && STRLEN(rel_fname) + l < MAXPATHL)
1719 {
1720 STRCPY(NameBuff, rel_fname);
Bram Moolenaar5145c9a2023-03-11 13:55:53 +00001721 STRCPY(gettail(NameBuff), *file_to_find);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001722 l = (int)STRLEN(NameBuff);
1723 }
1724 else
1725 {
Bram Moolenaar5145c9a2023-03-11 13:55:53 +00001726 STRCPY(NameBuff, *file_to_find);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001727 run = 2;
1728 }
1729
1730 // When the file doesn't exist, try adding parts of
1731 // 'suffixesadd'.
1732 buf = suffixes;
1733 for (;;)
1734 {
1735 if (mch_getperm(NameBuff) >= 0
1736 && (find_what == FINDFILE_BOTH
1737 || ((find_what == FINDFILE_DIR)
1738 == mch_isdir(NameBuff))))
1739 {
1740 file_name = vim_strsave(NameBuff);
1741 goto theend;
1742 }
1743 if (*buf == NUL)
1744 break;
1745 copy_option_part(&buf, NameBuff + l, MAXPATHL - l, ",");
1746 }
1747 }
1748 }
1749 }
1750 else
1751 {
1752 /*
1753 * Loop over all paths in the 'path' or 'cdpath' option.
1754 * When "first" is set, first setup to the start of the option.
1755 * Otherwise continue to find the next match.
1756 */
1757 if (first == TRUE)
1758 {
1759 // vim_findfile_free_visited can handle a possible NULL pointer
Bram Moolenaar5145c9a2023-03-11 13:55:53 +00001760 vim_findfile_free_visited(*search_ctx);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001761 dir = path_option;
1762 did_findfile_init = FALSE;
1763 }
1764
1765 for (;;)
1766 {
1767 if (did_findfile_init)
1768 {
Bram Moolenaar5145c9a2023-03-11 13:55:53 +00001769 file_name = vim_findfile(*search_ctx);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001770 if (file_name != NULL)
1771 break;
1772
1773 did_findfile_init = FALSE;
1774 }
1775 else
1776 {
1777 char_u *r_ptr;
1778
1779 if (dir == NULL || *dir == NUL)
1780 {
1781 // We searched all paths of the option, now we can
1782 // free the search context.
Bram Moolenaar5145c9a2023-03-11 13:55:53 +00001783 vim_findfile_cleanup(*search_ctx);
1784 *search_ctx = NULL;
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001785 break;
1786 }
1787
Bram Moolenaar51e14382019-05-25 20:21:28 +02001788 if ((buf = alloc(MAXPATHL)) == NULL)
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001789 break;
1790
1791 // copy next path
1792 buf[0] = 0;
1793 copy_option_part(&dir, buf, MAXPATHL, " ,");
1794
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001795 // get the stopdir string
1796 r_ptr = vim_findfile_stopdir(buf);
Bram Moolenaar5145c9a2023-03-11 13:55:53 +00001797 *search_ctx = vim_findfile_init(buf, *file_to_find,
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001798 r_ptr, 100, FALSE, find_what,
Bram Moolenaar5145c9a2023-03-11 13:55:53 +00001799 *search_ctx, FALSE, rel_fname);
1800 if (*search_ctx != NULL)
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001801 did_findfile_init = TRUE;
1802 vim_free(buf);
1803 }
1804 }
1805 }
1806 if (file_name == NULL && (options & FNAME_MESS))
1807 {
1808 if (first == TRUE)
1809 {
1810 if (find_what == FINDFILE_DIR)
Bram Moolenaar5145c9a2023-03-11 13:55:53 +00001811 semsg(_(e_cant_find_directory_str_in_cdpath), *file_to_find);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001812 else
Bram Moolenaar5145c9a2023-03-11 13:55:53 +00001813 semsg(_(e_cant_find_file_str_in_path), *file_to_find);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001814 }
1815 else
1816 {
1817 if (find_what == FINDFILE_DIR)
Bram Moolenaareaaac012022-01-02 17:00:40 +00001818 semsg(_(e_no_more_directory_str_found_in_cdpath),
Bram Moolenaar5145c9a2023-03-11 13:55:53 +00001819 *file_to_find);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001820 else
Bram Moolenaar5145c9a2023-03-11 13:55:53 +00001821 semsg(_(e_no_more_file_str_found_in_path), *file_to_find);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001822 }
1823 }
1824
1825theend:
1826# ifdef AMIGA
1827 proc->pr_WindowPtr = save_winptr;
1828# endif
1829 return file_name;
1830}
1831
1832/*
1833 * Get the file name at the cursor.
1834 * If Visual mode is active, use the selected text if it's in one line.
1835 * Returns the name in allocated memory, NULL for failure.
1836 */
1837 char_u *
1838grab_file_name(long count, linenr_T *file_lnum)
1839{
1840 int options = FNAME_MESS|FNAME_EXP|FNAME_REL|FNAME_UNESC;
1841
1842 if (VIsual_active)
1843 {
1844 int len;
1845 char_u *ptr;
1846
1847 if (get_visual_text(NULL, &ptr, &len) == FAIL)
1848 return NULL;
Bram Moolenaarefd5d8a2020-09-14 19:11:45 +02001849 // Only recognize ":123" here
1850 if (file_lnum != NULL && ptr[len] == ':' && isdigit(ptr[len + 1]))
1851 {
1852 char_u *p = ptr + len + 1;
1853
1854 *file_lnum = getdigits(&p);
1855 }
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001856 return find_file_name_in_path(ptr, len, options,
1857 count, curbuf->b_ffname);
1858 }
1859 return file_name_at_cursor(options | FNAME_HYP, count, file_lnum);
1860}
1861
1862/*
1863 * Return the file name under or after the cursor.
1864 *
1865 * The 'path' option is searched if the file name is not absolute.
1866 * The string returned has been alloc'ed and should be freed by the caller.
1867 * NULL is returned if the file name or file is not found.
1868 *
1869 * options:
1870 * FNAME_MESS give error messages
1871 * FNAME_EXP expand to path
1872 * FNAME_HYP check for hypertext link
1873 * FNAME_INCL apply "includeexpr"
1874 */
1875 char_u *
1876file_name_at_cursor(int options, long count, linenr_T *file_lnum)
1877{
1878 return file_name_in_line(ml_get_curline(),
1879 curwin->w_cursor.col, options, count, curbuf->b_ffname,
1880 file_lnum);
1881}
1882
1883/*
1884 * Return the name of the file under or after ptr[col].
1885 * Otherwise like file_name_at_cursor().
1886 */
1887 char_u *
1888file_name_in_line(
1889 char_u *line,
1890 int col,
1891 int options,
1892 long count,
1893 char_u *rel_fname, // file we are searching relative to
1894 linenr_T *file_lnum) // line number after the file name
1895{
1896 char_u *ptr;
1897 int len;
1898 int in_type = TRUE;
1899 int is_url = FALSE;
1900
1901 /*
1902 * search forward for what could be the start of a file name
1903 */
1904 ptr = line + col;
1905 while (*ptr != NUL && !vim_isfilec(*ptr))
1906 MB_PTR_ADV(ptr);
1907 if (*ptr == NUL) // nothing found
1908 {
1909 if (options & FNAME_MESS)
Bram Moolenaarac78dd42022-01-02 19:25:26 +00001910 emsg(_(e_no_file_name_under_cursor));
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001911 return NULL;
1912 }
1913
1914 /*
1915 * Search backward for first char of the file name.
1916 * Go one char back to ":" before "//" even when ':' is not in 'isfname'.
1917 */
1918 while (ptr > line)
1919 {
1920 if (has_mbyte && (len = (*mb_head_off)(line, ptr - 1)) > 0)
1921 ptr -= len + 1;
1922 else if (vim_isfilec(ptr[-1])
1923 || ((options & FNAME_HYP) && path_is_url(ptr - 1)))
1924 --ptr;
1925 else
1926 break;
1927 }
1928
1929 /*
1930 * Search forward for the last char of the file name.
1931 * Also allow "://" when ':' is not in 'isfname'.
1932 */
1933 len = 0;
1934 while (vim_isfilec(ptr[len]) || (ptr[len] == '\\' && ptr[len + 1] == ' ')
Bram Moolenaar747f1102022-09-18 13:06:41 +01001935 || ((options & FNAME_HYP) && path_is_url(ptr + len))
1936 || (is_url && vim_strchr((char_u *)":?&=", ptr[len]) != NULL))
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001937 {
Bram Moolenaar747f1102022-09-18 13:06:41 +01001938 // After type:// we also include :, ?, & and = as valid characters, so
1939 // that http://google.com:8080?q=this&that=ok works.
1940 if ((ptr[len] >= 'A' && ptr[len] <= 'Z')
1941 || (ptr[len] >= 'a' && ptr[len] <= 'z'))
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001942 {
1943 if (in_type && path_is_url(ptr + len + 1))
1944 is_url = TRUE;
1945 }
1946 else
1947 in_type = FALSE;
1948
1949 if (ptr[len] == '\\')
1950 // Skip over the "\" in "\ ".
1951 ++len;
1952 if (has_mbyte)
1953 len += (*mb_ptr2len)(ptr + len);
1954 else
1955 ++len;
1956 }
1957
1958 /*
1959 * If there is trailing punctuation, remove it.
1960 * But don't remove "..", could be a directory name.
1961 */
1962 if (len > 2 && vim_strchr((char_u *)".,:;!", ptr[len - 1]) != NULL
1963 && ptr[len - 2] != '.')
1964 --len;
1965
1966 if (file_lnum != NULL)
1967 {
1968 char_u *p;
Bram Moolenaar64e74c92019-12-22 15:38:06 +01001969 char *line_english = " line ";
1970 char *line_transl = _(line_msg);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001971
Bram Moolenaar64e74c92019-12-22 15:38:06 +01001972 // Get the number after the file name and a separator character.
1973 // Also accept " line 999" with and without the same translation as
1974 // used in last_set_msg().
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001975 p = ptr + len;
Bram Moolenaar64e74c92019-12-22 15:38:06 +01001976 if (STRNCMP(p, line_english, STRLEN(line_english)) == 0)
1977 p += STRLEN(line_english);
1978 else if (STRNCMP(p, line_transl, STRLEN(line_transl)) == 0)
1979 p += STRLEN(line_transl);
1980 else
1981 p = skipwhite(p);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001982 if (*p != NUL)
1983 {
1984 if (!isdigit(*p))
1985 ++p; // skip the separator
1986 p = skipwhite(p);
1987 if (isdigit(*p))
1988 *file_lnum = (int)getdigits(&p);
1989 }
1990 }
1991
1992 return find_file_name_in_path(ptr, len, options, count, rel_fname);
1993}
1994
1995# if defined(FEAT_FIND_ID) && defined(FEAT_EVAL)
1996 static char_u *
1997eval_includeexpr(char_u *ptr, int len)
1998{
1999 char_u *res;
Bram Moolenaar47bcc5f2022-01-22 20:19:22 +00002000 sctx_T save_sctx = current_sctx;
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002001
2002 set_vim_var_string(VV_FNAME, ptr, len);
Bram Moolenaar47bcc5f2022-01-22 20:19:22 +00002003 current_sctx = curbuf->b_p_script_ctx[BV_INEX];
2004
Bram Moolenaarb171fb12020-06-24 20:34:03 +02002005 res = eval_to_string_safe(curbuf->b_p_inex,
Bram Moolenaara4e0b972022-10-01 19:43:52 +01002006 was_set_insecurely((char_u *)"includeexpr", OPT_LOCAL),
2007 TRUE, TRUE);
Bram Moolenaar47bcc5f2022-01-22 20:19:22 +00002008
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002009 set_vim_var_string(VV_FNAME, NULL, 0);
Bram Moolenaar47bcc5f2022-01-22 20:19:22 +00002010 current_sctx = save_sctx;
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002011 return res;
2012}
2013# endif
2014
2015/*
2016 * Return the name of the file ptr[len] in 'path'.
2017 * Otherwise like file_name_at_cursor().
2018 */
2019 char_u *
2020find_file_name_in_path(
2021 char_u *ptr,
2022 int len,
2023 int options,
2024 long count,
2025 char_u *rel_fname) // file we are searching relative to
2026{
2027 char_u *file_name;
2028 int c;
2029# if defined(FEAT_FIND_ID) && defined(FEAT_EVAL)
2030 char_u *tofree = NULL;
Bram Moolenaar615ddd52021-11-17 18:00:31 +00002031# endif
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002032
Bram Moolenaar615ddd52021-11-17 18:00:31 +00002033 if (len == 0)
2034 return NULL;
2035
2036# if defined(FEAT_FIND_ID) && defined(FEAT_EVAL)
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002037 if ((options & FNAME_INCL) && *curbuf->b_p_inex != NUL)
2038 {
2039 tofree = eval_includeexpr(ptr, len);
2040 if (tofree != NULL)
2041 {
2042 ptr = tofree;
2043 len = (int)STRLEN(ptr);
2044 }
2045 }
2046# endif
2047
2048 if (options & FNAME_EXP)
2049 {
Bram Moolenaar5145c9a2023-03-11 13:55:53 +00002050 char_u *file_to_find = NULL;
2051 char *search_ctx = NULL;
2052
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002053 file_name = find_file_in_path(ptr, len, options & ~FNAME_MESS,
Bram Moolenaar5145c9a2023-03-11 13:55:53 +00002054 TRUE, rel_fname, &file_to_find, &search_ctx);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002055
2056# if defined(FEAT_FIND_ID) && defined(FEAT_EVAL)
2057 /*
2058 * If the file could not be found in a normal way, try applying
2059 * 'includeexpr' (unless done already).
2060 */
2061 if (file_name == NULL
2062 && !(options & FNAME_INCL) && *curbuf->b_p_inex != NUL)
2063 {
2064 tofree = eval_includeexpr(ptr, len);
2065 if (tofree != NULL)
2066 {
2067 ptr = tofree;
2068 len = (int)STRLEN(ptr);
2069 file_name = find_file_in_path(ptr, len, options & ~FNAME_MESS,
Bram Moolenaar5145c9a2023-03-11 13:55:53 +00002070 TRUE, rel_fname, &file_to_find, &search_ctx);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002071 }
2072 }
2073# endif
2074 if (file_name == NULL && (options & FNAME_MESS))
2075 {
2076 c = ptr[len];
2077 ptr[len] = NUL;
Bram Moolenaarac78dd42022-01-02 19:25:26 +00002078 semsg(_(e_cant_find_file_str_in_path_2), ptr);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002079 ptr[len] = c;
2080 }
2081
2082 // Repeat finding the file "count" times. This matters when it
2083 // appears several times in the path.
2084 while (file_name != NULL && --count > 0)
2085 {
2086 vim_free(file_name);
Bram Moolenaar5145c9a2023-03-11 13:55:53 +00002087 file_name = find_file_in_path(ptr, len, options, FALSE, rel_fname,
2088 &file_to_find, &search_ctx);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002089 }
Bram Moolenaar5145c9a2023-03-11 13:55:53 +00002090
2091 vim_free(file_to_find);
2092 vim_findfile_cleanup(search_ctx);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002093 }
2094 else
2095 file_name = vim_strnsave(ptr, len);
2096
2097# if defined(FEAT_FIND_ID) && defined(FEAT_EVAL)
2098 vim_free(tofree);
2099# endif
2100
2101 return file_name;
2102}
2103
2104/*
2105 * Return the end of the directory name, on the first path
2106 * separator:
2107 * "/path/file", "/path/dir/", "/path//dir", "/file"
2108 * ^ ^ ^ ^
2109 */
2110 static char_u *
2111gettail_dir(char_u *fname)
2112{
2113 char_u *dir_end = fname;
2114 char_u *next_dir_end = fname;
2115 int look_for_sep = TRUE;
2116 char_u *p;
2117
2118 for (p = fname; *p != NUL; )
2119 {
2120 if (vim_ispathsep(*p))
2121 {
2122 if (look_for_sep)
2123 {
2124 next_dir_end = p;
2125 look_for_sep = FALSE;
2126 }
2127 }
2128 else
2129 {
2130 if (!look_for_sep)
2131 dir_end = next_dir_end;
2132 look_for_sep = TRUE;
2133 }
2134 MB_PTR_ADV(p);
2135 }
2136 return dir_end;
2137}
2138
2139/*
2140 * return TRUE if 'c' is a path list separator.
2141 */
2142 int
2143vim_ispathlistsep(int c)
2144{
2145# ifdef UNIX
2146 return (c == ':');
2147# else
2148 return (c == ';'); // might not be right for every system...
2149# endif
2150}
2151
2152/*
2153 * Moves "*psep" back to the previous path separator in "path".
2154 * Returns FAIL is "*psep" ends up at the beginning of "path".
2155 */
2156 static int
2157find_previous_pathsep(char_u *path, char_u **psep)
2158{
2159 // skip the current separator
2160 if (*psep > path && vim_ispathsep(**psep))
2161 --*psep;
2162
2163 // find the previous separator
2164 while (*psep > path)
2165 {
2166 if (vim_ispathsep(**psep))
2167 return OK;
2168 MB_PTR_BACK(path, *psep);
2169 }
2170
2171 return FAIL;
2172}
2173
2174/*
2175 * Returns TRUE if "maybe_unique" is unique wrt other_paths in "gap".
2176 * "maybe_unique" is the end portion of "((char_u **)gap->ga_data)[i]".
2177 */
2178 static int
2179is_unique(char_u *maybe_unique, garray_T *gap, int i)
2180{
2181 int j;
2182 int candidate_len;
2183 int other_path_len;
2184 char_u **other_paths = (char_u **)gap->ga_data;
2185 char_u *rival;
2186
2187 for (j = 0; j < gap->ga_len; j++)
2188 {
2189 if (j == i)
2190 continue; // don't compare it with itself
2191
2192 candidate_len = (int)STRLEN(maybe_unique);
2193 other_path_len = (int)STRLEN(other_paths[j]);
2194 if (other_path_len < candidate_len)
2195 continue; // it's different when it's shorter
2196
2197 rival = other_paths[j] + other_path_len - candidate_len;
2198 if (fnamecmp(maybe_unique, rival) == 0
2199 && (rival == other_paths[j] || vim_ispathsep(*(rival - 1))))
2200 return FALSE; // match
2201 }
2202
2203 return TRUE; // no match found
2204}
2205
2206/*
2207 * Split the 'path' option into an array of strings in garray_T. Relative
2208 * paths are expanded to their equivalent fullpath. This includes the "."
2209 * (relative to current buffer directory) and empty path (relative to current
2210 * directory) notations.
2211 *
2212 * TODO: handle upward search (;) and path limiter (**N) notations by
2213 * expanding each into their equivalent path(s).
2214 */
2215 static void
2216expand_path_option(char_u *curdir, garray_T *gap)
2217{
2218 char_u *path_option = *curbuf->b_p_path == NUL
2219 ? p_path : curbuf->b_p_path;
2220 char_u *buf;
2221 char_u *p;
2222 int len;
2223
Bram Moolenaar51e14382019-05-25 20:21:28 +02002224 if ((buf = alloc(MAXPATHL)) == NULL)
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002225 return;
2226
2227 while (*path_option != NUL)
2228 {
2229 copy_option_part(&path_option, buf, MAXPATHL, " ,");
2230
2231 if (buf[0] == '.' && (buf[1] == NUL || vim_ispathsep(buf[1])))
2232 {
2233 // Relative to current buffer:
2234 // "/path/file" + "." -> "/path/"
2235 // "/path/file" + "./subdir" -> "/path/subdir"
2236 if (curbuf->b_ffname == NULL)
2237 continue;
2238 p = gettail(curbuf->b_ffname);
2239 len = (int)(p - curbuf->b_ffname);
2240 if (len + (int)STRLEN(buf) >= MAXPATHL)
2241 continue;
2242 if (buf[1] == NUL)
2243 buf[len] = NUL;
2244 else
2245 STRMOVE(buf + len, buf + 2);
2246 mch_memmove(buf, curbuf->b_ffname, len);
2247 simplify_filename(buf);
2248 }
2249 else if (buf[0] == NUL)
2250 // relative to current directory
2251 STRCPY(buf, curdir);
2252 else if (path_with_url(buf))
2253 // URL can't be used here
2254 continue;
2255 else if (!mch_isFullName(buf))
2256 {
2257 // Expand relative path to their full path equivalent
2258 len = (int)STRLEN(curdir);
2259 if (len + (int)STRLEN(buf) + 3 > MAXPATHL)
2260 continue;
2261 STRMOVE(buf + len + 1, buf);
2262 STRCPY(buf, curdir);
2263 buf[len] = PATHSEP;
2264 simplify_filename(buf);
2265 }
2266
2267 if (ga_grow(gap, 1) == FAIL)
2268 break;
2269
2270# if defined(MSWIN)
2271 // Avoid the path ending in a backslash, it fails when a comma is
2272 // appended.
2273 len = (int)STRLEN(buf);
2274 if (buf[len - 1] == '\\')
2275 buf[len - 1] = '/';
2276# endif
2277
2278 p = vim_strsave(buf);
2279 if (p == NULL)
2280 break;
2281 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
2282 }
2283
2284 vim_free(buf);
2285}
2286
2287/*
2288 * Returns a pointer to the file or directory name in "fname" that matches the
2289 * longest path in "ga"p, or NULL if there is no match. For example:
2290 *
2291 * path: /foo/bar/baz
2292 * fname: /foo/bar/baz/quux.txt
2293 * returns: ^this
2294 */
2295 static char_u *
2296get_path_cutoff(char_u *fname, garray_T *gap)
2297{
2298 int i;
2299 int maxlen = 0;
2300 char_u **path_part = (char_u **)gap->ga_data;
2301 char_u *cutoff = NULL;
2302
2303 for (i = 0; i < gap->ga_len; i++)
2304 {
2305 int j = 0;
2306
2307 while ((fname[j] == path_part[i][j]
2308# if defined(MSWIN)
2309 || (vim_ispathsep(fname[j]) && vim_ispathsep(path_part[i][j]))
2310# endif
2311 ) && fname[j] != NUL && path_part[i][j] != NUL)
2312 j++;
2313 if (j > maxlen)
2314 {
2315 maxlen = j;
2316 cutoff = &fname[j];
2317 }
2318 }
2319
2320 // skip to the file or directory name
2321 if (cutoff != NULL)
2322 while (vim_ispathsep(*cutoff))
2323 MB_PTR_ADV(cutoff);
2324
2325 return cutoff;
2326}
2327
2328/*
2329 * Sorts, removes duplicates and modifies all the fullpath names in "gap" so
2330 * that they are unique with respect to each other while conserving the part
2331 * that matches the pattern. Beware, this is at least O(n^2) wrt "gap->ga_len".
2332 */
2333 void
2334uniquefy_paths(garray_T *gap, char_u *pattern)
2335{
2336 int i;
2337 int len;
2338 char_u **fnames = (char_u **)gap->ga_data;
2339 int sort_again = FALSE;
2340 char_u *pat;
2341 char_u *file_pattern;
2342 char_u *curdir;
2343 regmatch_T regmatch;
2344 garray_T path_ga;
2345 char_u **in_curdir = NULL;
2346 char_u *short_name;
2347
2348 remove_duplicates(gap);
Bram Moolenaar04935fb2022-01-08 16:19:22 +00002349 ga_init2(&path_ga, sizeof(char_u *), 1);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002350
2351 /*
2352 * We need to prepend a '*' at the beginning of file_pattern so that the
2353 * regex matches anywhere in the path. FIXME: is this valid for all
2354 * possible patterns?
2355 */
2356 len = (int)STRLEN(pattern);
2357 file_pattern = alloc(len + 2);
2358 if (file_pattern == NULL)
2359 return;
2360 file_pattern[0] = '*';
2361 file_pattern[1] = NUL;
2362 STRCAT(file_pattern, pattern);
2363 pat = file_pat_to_reg_pat(file_pattern, NULL, NULL, TRUE);
2364 vim_free(file_pattern);
2365 if (pat == NULL)
2366 return;
2367
2368 regmatch.rm_ic = TRUE; // always ignore case
2369 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
2370 vim_free(pat);
2371 if (regmatch.regprog == NULL)
2372 return;
2373
Bram Moolenaar51e14382019-05-25 20:21:28 +02002374 if ((curdir = alloc(MAXPATHL)) == NULL)
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002375 goto theend;
2376 mch_dirname(curdir, MAXPATHL);
2377 expand_path_option(curdir, &path_ga);
2378
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002379 in_curdir = ALLOC_CLEAR_MULT(char_u *, gap->ga_len);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002380 if (in_curdir == NULL)
2381 goto theend;
2382
2383 for (i = 0; i < gap->ga_len && !got_int; i++)
2384 {
2385 char_u *path = fnames[i];
2386 int is_in_curdir;
2387 char_u *dir_end = gettail_dir(path);
2388 char_u *pathsep_p;
2389 char_u *path_cutoff;
2390
2391 len = (int)STRLEN(path);
2392 is_in_curdir = fnamencmp(curdir, path, dir_end - path) == 0
2393 && curdir[dir_end - path] == NUL;
2394 if (is_in_curdir)
2395 in_curdir[i] = vim_strsave(path);
2396
2397 // Shorten the filename while maintaining its uniqueness
2398 path_cutoff = get_path_cutoff(path, &path_ga);
2399
2400 // Don't assume all files can be reached without path when search
2401 // pattern starts with star star slash, so only remove path_cutoff
2402 // when possible.
2403 if (pattern[0] == '*' && pattern[1] == '*'
2404 && vim_ispathsep_nocolon(pattern[2])
2405 && path_cutoff != NULL
2406 && vim_regexec(&regmatch, path_cutoff, (colnr_T)0)
2407 && is_unique(path_cutoff, gap, i))
2408 {
2409 sort_again = TRUE;
2410 mch_memmove(path, path_cutoff, STRLEN(path_cutoff) + 1);
2411 }
2412 else
2413 {
2414 // Here all files can be reached without path, so get shortest
2415 // unique path. We start at the end of the path.
2416 pathsep_p = path + len - 1;
2417
2418 while (find_previous_pathsep(path, &pathsep_p))
2419 if (vim_regexec(&regmatch, pathsep_p + 1, (colnr_T)0)
2420 && is_unique(pathsep_p + 1, gap, i)
2421 && path_cutoff != NULL && pathsep_p + 1 >= path_cutoff)
2422 {
2423 sort_again = TRUE;
2424 mch_memmove(path, pathsep_p + 1, STRLEN(pathsep_p));
2425 break;
2426 }
2427 }
2428
2429 if (mch_isFullName(path))
2430 {
2431 /*
2432 * Last resort: shorten relative to curdir if possible.
2433 * 'possible' means:
2434 * 1. It is under the current directory.
2435 * 2. The result is actually shorter than the original.
2436 *
2437 * Before curdir After
2438 * /foo/bar/file.txt /foo/bar ./file.txt
2439 * c:\foo\bar\file.txt c:\foo\bar .\file.txt
2440 * /file.txt / /file.txt
2441 * c:\file.txt c:\ .\file.txt
2442 */
2443 short_name = shorten_fname(path, curdir);
2444 if (short_name != NULL && short_name > path + 1
2445# if defined(MSWIN)
2446 // On windows,
2447 // shorten_fname("c:\a\a.txt", "c:\a\b")
2448 // returns "\a\a.txt", which is not really the short
2449 // name, hence:
2450 && !vim_ispathsep(*short_name)
2451# endif
2452 )
2453 {
2454 STRCPY(path, ".");
2455 add_pathsep(path);
2456 STRMOVE(path + STRLEN(path), short_name);
2457 }
2458 }
2459 ui_breakcheck();
2460 }
2461
2462 // Shorten filenames in /in/current/directory/{filename}
2463 for (i = 0; i < gap->ga_len && !got_int; i++)
2464 {
2465 char_u *rel_path;
2466 char_u *path = in_curdir[i];
2467
2468 if (path == NULL)
2469 continue;
2470
2471 // If the {filename} is not unique, change it to ./{filename}.
2472 // Else reduce it to {filename}
2473 short_name = shorten_fname(path, curdir);
2474 if (short_name == NULL)
2475 short_name = path;
2476 if (is_unique(short_name, gap, i))
2477 {
2478 STRCPY(fnames[i], short_name);
2479 continue;
2480 }
2481
Bram Moolenaar51e14382019-05-25 20:21:28 +02002482 rel_path = alloc(STRLEN(short_name) + STRLEN(PATHSEPSTR) + 2);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002483 if (rel_path == NULL)
2484 goto theend;
2485 STRCPY(rel_path, ".");
2486 add_pathsep(rel_path);
2487 STRCAT(rel_path, short_name);
2488
2489 vim_free(fnames[i]);
2490 fnames[i] = rel_path;
2491 sort_again = TRUE;
2492 ui_breakcheck();
2493 }
2494
2495theend:
2496 vim_free(curdir);
2497 if (in_curdir != NULL)
2498 {
2499 for (i = 0; i < gap->ga_len; i++)
2500 vim_free(in_curdir[i]);
2501 vim_free(in_curdir);
2502 }
2503 ga_clear_strings(&path_ga);
2504 vim_regfree(regmatch.regprog);
2505
2506 if (sort_again)
2507 remove_duplicates(gap);
2508}
2509
2510/*
2511 * Calls globpath() with 'path' values for the given pattern and stores the
2512 * result in "gap".
2513 * Returns the total number of matches.
2514 */
2515 int
2516expand_in_path(
2517 garray_T *gap,
2518 char_u *pattern,
2519 int flags) // EW_* flags
2520{
2521 char_u *curdir;
2522 garray_T path_ga;
2523 char_u *paths = NULL;
2524 int glob_flags = 0;
2525
Bram Moolenaar964b3742019-05-24 18:54:09 +02002526 if ((curdir = alloc(MAXPATHL)) == NULL)
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002527 return 0;
2528 mch_dirname(curdir, MAXPATHL);
2529
Bram Moolenaar04935fb2022-01-08 16:19:22 +00002530 ga_init2(&path_ga, sizeof(char_u *), 1);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002531 expand_path_option(curdir, &path_ga);
2532 vim_free(curdir);
2533 if (path_ga.ga_len == 0)
2534 return 0;
2535
2536 paths = ga_concat_strings(&path_ga, ",");
2537 ga_clear_strings(&path_ga);
2538 if (paths == NULL)
2539 return 0;
2540
2541 if (flags & EW_ICASE)
2542 glob_flags |= WILD_ICASE;
2543 if (flags & EW_ADDSLASH)
2544 glob_flags |= WILD_ADD_SLASH;
zeertzjq3770f4c2023-01-22 18:38:51 +00002545 globpath(paths, pattern, gap, glob_flags, FALSE);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002546 vim_free(paths);
2547
2548 return gap->ga_len;
2549}
2550
Bram Moolenaarb4a60202019-03-31 19:40:07 +02002551
2552/*
2553 * Converts a file name into a canonical form. It simplifies a file name into
2554 * its simplest form by stripping out unneeded components, if any. The
2555 * resulting file name is simplified in place and will either be the same
2556 * length as that supplied, or shorter.
2557 */
2558 void
2559simplify_filename(char_u *filename)
2560{
2561#ifndef AMIGA // Amiga doesn't have "..", it uses "/"
2562 int components = 0;
2563 char_u *p, *tail, *start;
2564 int stripping_disabled = FALSE;
2565 int relative = TRUE;
2566
2567 p = filename;
2568# ifdef BACKSLASH_IN_FILENAME
Yegappan Lakshmanan6df0f272021-12-16 13:06:10 +00002569 if (p[0] != NUL && p[1] == ':') // skip "x:"
Bram Moolenaarb4a60202019-03-31 19:40:07 +02002570 p += 2;
2571# endif
2572
2573 if (vim_ispathsep(*p))
2574 {
2575 relative = FALSE;
2576 do
2577 ++p;
2578 while (vim_ispathsep(*p));
2579 }
2580 start = p; // remember start after "c:/" or "/" or "///"
Bram Moolenaarfdcbe3c2020-06-15 21:41:56 +02002581#ifdef UNIX
2582 // Posix says that "//path" is unchanged but "///path" is "/path".
2583 if (start > filename + 2)
2584 {
2585 STRMOVE(filename + 1, p);
2586 start = p = filename + 1;
2587 }
2588#endif
Bram Moolenaarb4a60202019-03-31 19:40:07 +02002589
2590 do
2591 {
2592 // At this point "p" is pointing to the char following a single "/"
2593 // or "p" is at the "start" of the (absolute or relative) path name.
2594# ifdef VMS
2595 // VMS allows device:[path] - don't strip the [ in directory
2596 if ((*p == '[' || *p == '<') && p > filename && p[-1] == ':')
2597 {
2598 // :[ or :< composition: vms directory component
2599 ++components;
2600 p = getnextcomp(p + 1);
2601 }
2602 // allow remote calls as host"user passwd"::device:[path]
2603 else if (p[0] == ':' && p[1] == ':' && p > filename && p[-1] == '"' )
2604 {
2605 // ":: composition: vms host/passwd component
2606 ++components;
2607 p = getnextcomp(p + 2);
2608 }
2609 else
2610# endif
2611 if (vim_ispathsep(*p))
2612 STRMOVE(p, p + 1); // remove duplicate "/"
2613 else if (p[0] == '.' && (vim_ispathsep(p[1]) || p[1] == NUL))
2614 {
2615 if (p == start && relative)
2616 p += 1 + (p[1] != NUL); // keep single "." or leading "./"
2617 else
2618 {
2619 // Strip "./" or ".///". If we are at the end of the file name
2620 // and there is no trailing path separator, either strip "/." if
2621 // we are after "start", or strip "." if we are at the beginning
2622 // of an absolute path name .
2623 tail = p + 1;
2624 if (p[1] != NUL)
2625 while (vim_ispathsep(*tail))
2626 MB_PTR_ADV(tail);
2627 else if (p > start)
2628 --p; // strip preceding path separator
2629 STRMOVE(p, tail);
2630 }
2631 }
2632 else if (p[0] == '.' && p[1] == '.' &&
2633 (vim_ispathsep(p[2]) || p[2] == NUL))
2634 {
2635 // Skip to after ".." or "../" or "..///".
2636 tail = p + 2;
2637 while (vim_ispathsep(*tail))
2638 MB_PTR_ADV(tail);
2639
2640 if (components > 0) // strip one preceding component
2641 {
2642 int do_strip = FALSE;
2643 char_u saved_char;
2644 stat_T st;
2645
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002646 // Don't strip for an erroneous file name.
Bram Moolenaarb4a60202019-03-31 19:40:07 +02002647 if (!stripping_disabled)
2648 {
2649 // If the preceding component does not exist in the file
2650 // system, we strip it. On Unix, we don't accept a symbolic
2651 // link that refers to a non-existent file.
2652 saved_char = p[-1];
2653 p[-1] = NUL;
2654# ifdef UNIX
2655 if (mch_lstat((char *)filename, &st) < 0)
2656# else
2657 if (mch_stat((char *)filename, &st) < 0)
2658# endif
2659 do_strip = TRUE;
2660 p[-1] = saved_char;
2661
2662 --p;
2663 // Skip back to after previous '/'.
2664 while (p > start && !after_pathsep(start, p))
2665 MB_PTR_BACK(start, p);
2666
2667 if (!do_strip)
2668 {
2669 // If the component exists in the file system, check
2670 // that stripping it won't change the meaning of the
2671 // file name. First get information about the
2672 // unstripped file name. This may fail if the component
2673 // to strip is not a searchable directory (but a regular
2674 // file, for instance), since the trailing "/.." cannot
2675 // be applied then. We don't strip it then since we
2676 // don't want to replace an erroneous file name by
2677 // a valid one, and we disable stripping of later
2678 // components.
2679 saved_char = *tail;
2680 *tail = NUL;
2681 if (mch_stat((char *)filename, &st) >= 0)
2682 do_strip = TRUE;
2683 else
2684 stripping_disabled = TRUE;
2685 *tail = saved_char;
2686# ifdef UNIX
2687 if (do_strip)
2688 {
2689 stat_T new_st;
2690
2691 // On Unix, the check for the unstripped file name
2692 // above works also for a symbolic link pointing to
2693 // a searchable directory. But then the parent of
2694 // the directory pointed to by the link must be the
2695 // same as the stripped file name. (The latter
2696 // exists in the file system since it is the
2697 // component's parent directory.)
2698 if (p == start && relative)
2699 (void)mch_stat(".", &new_st);
2700 else
2701 {
2702 saved_char = *p;
2703 *p = NUL;
2704 (void)mch_stat((char *)filename, &new_st);
2705 *p = saved_char;
2706 }
2707
2708 if (new_st.st_ino != st.st_ino ||
2709 new_st.st_dev != st.st_dev)
2710 {
2711 do_strip = FALSE;
2712 // We don't disable stripping of later
2713 // components since the unstripped path name is
2714 // still valid.
2715 }
2716 }
2717# endif
2718 }
2719 }
2720
2721 if (!do_strip)
2722 {
2723 // Skip the ".." or "../" and reset the counter for the
2724 // components that might be stripped later on.
2725 p = tail;
2726 components = 0;
2727 }
2728 else
2729 {
2730 // Strip previous component. If the result would get empty
2731 // and there is no trailing path separator, leave a single
2732 // "." instead. If we are at the end of the file name and
2733 // there is no trailing path separator and a preceding
2734 // component is left after stripping, strip its trailing
2735 // path separator as well.
2736 if (p == start && relative && tail[-1] == '.')
2737 {
2738 *p++ = '.';
2739 *p = NUL;
2740 }
2741 else
2742 {
2743 if (p > start && tail[-1] == '.')
2744 --p;
2745 STRMOVE(p, tail); // strip previous component
2746 }
2747
2748 --components;
2749 }
2750 }
2751 else if (p == start && !relative) // leading "/.." or "/../"
2752 STRMOVE(p, tail); // strip ".." or "../"
2753 else
2754 {
2755 if (p == start + 2 && p[-2] == '.') // leading "./../"
2756 {
2757 STRMOVE(p - 2, p); // strip leading "./"
2758 tail -= 2;
2759 }
2760 p = tail; // skip to char after ".." or "../"
2761 }
2762 }
2763 else
2764 {
2765 ++components; // simple path component
2766 p = getnextcomp(p);
2767 }
2768 } while (*p != NUL);
2769#endif // !AMIGA
2770}
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002771
2772#if defined(FEAT_EVAL) || defined(PROTO)
2773/*
2774 * "simplify()" function
2775 */
2776 void
2777f_simplify(typval_T *argvars, typval_T *rettv)
2778{
2779 char_u *p;
2780
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02002781 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
2782 return;
2783
Bram Moolenaar3cfa5b12021-06-06 14:14:39 +02002784 p = tv_get_string_strict(&argvars[0]);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002785 rettv->vval.v_string = vim_strsave(p);
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002786 simplify_filename(rettv->vval.v_string); // simplify in place
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002787 rettv->v_type = VAR_STRING;
2788}
2789#endif // FEAT_EVAL