blob: 5751a07270c281cf2111180bd9afa310626db544 [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;
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 */
Bram Moolenaarc799fe22019-05-28 23:08:19 +02001347 vp = alloc(sizeof(ff_visited_T) + STRLEN(ff_expand_buffer));
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001348
1349 if (vp != NULL)
1350 {
1351#ifdef UNIX
1352 if (!url)
1353 {
1354 vp->ffv_dev_valid = TRUE;
1355 vp->ffv_ino = st.st_ino;
1356 vp->ffv_dev = st.st_dev;
1357 vp->ffv_fname[0] = NUL;
1358 }
1359 else
1360 {
1361 vp->ffv_dev_valid = FALSE;
1362#endif
1363 STRCPY(vp->ffv_fname, ff_expand_buffer);
1364#ifdef UNIX
1365 }
1366#endif
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001367 if (wc_path != NULL)
1368 vp->ffv_wc_path = vim_strsave(wc_path);
1369 else
1370 vp->ffv_wc_path = NULL;
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001371
1372 vp->ffv_next = *visited_list;
1373 *visited_list = vp;
1374 }
1375
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
1429 if (stack_ptr != NULL)
1430 {
1431 stack_ptr->ffs_prev = search_ctx->ffsc_stack_ptr;
1432 search_ctx->ffsc_stack_ptr = stack_ptr;
1433 }
1434}
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
1574 char_u *rel_fname) // file name searching relative to
1575{
1576 return find_file_in_path_option(ptr, len, options, first,
1577 *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path,
1578 FINDFILE_BOTH, rel_fname, curbuf->b_p_sua);
1579}
1580
1581static char_u *ff_file_to_find = NULL;
1582static void *fdip_search_ctx = NULL;
1583
1584# if defined(EXITFREE) || defined(PROTO)
1585 void
1586free_findfile(void)
1587{
1588 vim_free(ff_file_to_find);
1589 vim_findfile_cleanup(fdip_search_ctx);
1590 vim_free(ff_expand_buffer);
1591}
1592# endif
1593
1594/*
1595 * Find the directory name "ptr[len]" in the path.
1596 *
1597 * options:
1598 * FNAME_MESS give error message when not found
1599 * FNAME_UNESC unescape backslashes.
1600 *
1601 * Uses NameBuff[]!
1602 *
1603 * Returns an allocated string for the file name. NULL for error.
1604 */
1605 char_u *
1606find_directory_in_path(
1607 char_u *ptr, // file name
1608 int len, // length of file name
1609 int options,
1610 char_u *rel_fname) // file name searching relative to
1611{
1612 return find_file_in_path_option(ptr, len, options, TRUE, p_cdpath,
1613 FINDFILE_DIR, rel_fname, (char_u *)"");
1614}
1615
1616 char_u *
1617find_file_in_path_option(
1618 char_u *ptr, // file name
1619 int len, // length of file name
1620 int options,
1621 int first, // use count'th matching file name
1622 char_u *path_option, // p_path or p_cdpath
1623 int find_what, // FINDFILE_FILE, _DIR or _BOTH
1624 char_u *rel_fname, // file name we are looking relative to.
1625 char_u *suffixes) // list of suffixes, 'suffixesadd' option
1626{
1627 static char_u *dir;
1628 static int did_findfile_init = FALSE;
1629 char_u save_char;
1630 char_u *file_name = NULL;
1631 char_u *buf = NULL;
1632 int rel_to_curdir;
1633# ifdef AMIGA
1634 struct Process *proc = (struct Process *)FindTask(0L);
1635 APTR save_winptr = proc->pr_WindowPtr;
1636
1637 // Avoid a requester here for a volume that doesn't exist.
1638 proc->pr_WindowPtr = (APTR)-1L;
1639# endif
1640
1641 if (first == TRUE)
1642 {
Bram Moolenaare015d992021-11-17 19:01:53 +00001643 if (len == 0)
1644 return NULL;
1645
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001646 // copy file name into NameBuff, expanding environment variables
1647 save_char = ptr[len];
1648 ptr[len] = NUL;
1649 expand_env_esc(ptr, NameBuff, MAXPATHL, FALSE, TRUE, NULL);
1650 ptr[len] = save_char;
1651
1652 vim_free(ff_file_to_find);
1653 ff_file_to_find = vim_strsave(NameBuff);
1654 if (ff_file_to_find == NULL) // out of memory
1655 {
1656 file_name = NULL;
1657 goto theend;
1658 }
1659 if (options & FNAME_UNESC)
1660 {
1661 // Change all "\ " to " ".
1662 for (ptr = ff_file_to_find; *ptr != NUL; ++ptr)
1663 if (ptr[0] == '\\' && ptr[1] == ' ')
1664 mch_memmove(ptr, ptr + 1, STRLEN(ptr));
1665 }
1666 }
1667
1668 rel_to_curdir = (ff_file_to_find[0] == '.'
1669 && (ff_file_to_find[1] == NUL
1670 || vim_ispathsep(ff_file_to_find[1])
1671 || (ff_file_to_find[1] == '.'
1672 && (ff_file_to_find[2] == NUL
1673 || vim_ispathsep(ff_file_to_find[2])))));
1674 if (vim_isAbsName(ff_file_to_find)
1675 // "..", "../path", "." and "./path": don't use the path_option
1676 || rel_to_curdir
1677# if defined(MSWIN)
1678 // handle "\tmp" as absolute path
1679 || vim_ispathsep(ff_file_to_find[0])
1680 // handle "c:name" as absolute path
1681 || (ff_file_to_find[0] != NUL && ff_file_to_find[1] == ':')
1682# endif
1683# ifdef AMIGA
1684 // handle ":tmp" as absolute path
1685 || ff_file_to_find[0] == ':'
1686# endif
1687 )
1688 {
1689 /*
1690 * Absolute path, no need to use "path_option".
1691 * If this is not a first call, return NULL. We already returned a
1692 * filename on the first call.
1693 */
1694 if (first == TRUE)
1695 {
1696 int l;
1697 int run;
1698
1699 if (path_with_url(ff_file_to_find))
1700 {
1701 file_name = vim_strsave(ff_file_to_find);
1702 goto theend;
1703 }
1704
1705 // When FNAME_REL flag given first use the directory of the file.
1706 // Otherwise or when this fails use the current directory.
1707 for (run = 1; run <= 2; ++run)
1708 {
1709 l = (int)STRLEN(ff_file_to_find);
1710 if (run == 1
1711 && rel_to_curdir
1712 && (options & FNAME_REL)
1713 && rel_fname != NULL
1714 && STRLEN(rel_fname) + l < MAXPATHL)
1715 {
1716 STRCPY(NameBuff, rel_fname);
1717 STRCPY(gettail(NameBuff), ff_file_to_find);
1718 l = (int)STRLEN(NameBuff);
1719 }
1720 else
1721 {
1722 STRCPY(NameBuff, ff_file_to_find);
1723 run = 2;
1724 }
1725
1726 // When the file doesn't exist, try adding parts of
1727 // 'suffixesadd'.
1728 buf = suffixes;
1729 for (;;)
1730 {
1731 if (mch_getperm(NameBuff) >= 0
1732 && (find_what == FINDFILE_BOTH
1733 || ((find_what == FINDFILE_DIR)
1734 == mch_isdir(NameBuff))))
1735 {
1736 file_name = vim_strsave(NameBuff);
1737 goto theend;
1738 }
1739 if (*buf == NUL)
1740 break;
1741 copy_option_part(&buf, NameBuff + l, MAXPATHL - l, ",");
1742 }
1743 }
1744 }
1745 }
1746 else
1747 {
1748 /*
1749 * Loop over all paths in the 'path' or 'cdpath' option.
1750 * When "first" is set, first setup to the start of the option.
1751 * Otherwise continue to find the next match.
1752 */
1753 if (first == TRUE)
1754 {
1755 // vim_findfile_free_visited can handle a possible NULL pointer
1756 vim_findfile_free_visited(fdip_search_ctx);
1757 dir = path_option;
1758 did_findfile_init = FALSE;
1759 }
1760
1761 for (;;)
1762 {
1763 if (did_findfile_init)
1764 {
1765 file_name = vim_findfile(fdip_search_ctx);
1766 if (file_name != NULL)
1767 break;
1768
1769 did_findfile_init = FALSE;
1770 }
1771 else
1772 {
1773 char_u *r_ptr;
1774
1775 if (dir == NULL || *dir == NUL)
1776 {
1777 // We searched all paths of the option, now we can
1778 // free the search context.
1779 vim_findfile_cleanup(fdip_search_ctx);
1780 fdip_search_ctx = NULL;
1781 break;
1782 }
1783
Bram Moolenaar51e14382019-05-25 20:21:28 +02001784 if ((buf = alloc(MAXPATHL)) == NULL)
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001785 break;
1786
1787 // copy next path
1788 buf[0] = 0;
1789 copy_option_part(&dir, buf, MAXPATHL, " ,");
1790
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001791 // get the stopdir string
1792 r_ptr = vim_findfile_stopdir(buf);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001793 fdip_search_ctx = vim_findfile_init(buf, ff_file_to_find,
1794 r_ptr, 100, FALSE, find_what,
1795 fdip_search_ctx, FALSE, rel_fname);
1796 if (fdip_search_ctx != NULL)
1797 did_findfile_init = TRUE;
1798 vim_free(buf);
1799 }
1800 }
1801 }
1802 if (file_name == NULL && (options & FNAME_MESS))
1803 {
1804 if (first == TRUE)
1805 {
1806 if (find_what == FINDFILE_DIR)
Bram Moolenaareaaac012022-01-02 17:00:40 +00001807 semsg(_(e_cant_find_directory_str_in_cdpath),
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001808 ff_file_to_find);
1809 else
Bram Moolenaareaaac012022-01-02 17:00:40 +00001810 semsg(_(e_cant_find_file_str_in_path),
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001811 ff_file_to_find);
1812 }
1813 else
1814 {
1815 if (find_what == FINDFILE_DIR)
Bram Moolenaareaaac012022-01-02 17:00:40 +00001816 semsg(_(e_no_more_directory_str_found_in_cdpath),
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001817 ff_file_to_find);
1818 else
Bram Moolenaareaaac012022-01-02 17:00:40 +00001819 semsg(_(e_no_more_file_str_found_in_path),
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001820 ff_file_to_find);
1821 }
1822 }
1823
1824theend:
1825# ifdef AMIGA
1826 proc->pr_WindowPtr = save_winptr;
1827# endif
1828 return file_name;
1829}
1830
1831/*
1832 * Get the file name at the cursor.
1833 * If Visual mode is active, use the selected text if it's in one line.
1834 * Returns the name in allocated memory, NULL for failure.
1835 */
1836 char_u *
1837grab_file_name(long count, linenr_T *file_lnum)
1838{
1839 int options = FNAME_MESS|FNAME_EXP|FNAME_REL|FNAME_UNESC;
1840
1841 if (VIsual_active)
1842 {
1843 int len;
1844 char_u *ptr;
1845
1846 if (get_visual_text(NULL, &ptr, &len) == FAIL)
1847 return NULL;
Bram Moolenaarefd5d8a2020-09-14 19:11:45 +02001848 // Only recognize ":123" here
1849 if (file_lnum != NULL && ptr[len] == ':' && isdigit(ptr[len + 1]))
1850 {
1851 char_u *p = ptr + len + 1;
1852
1853 *file_lnum = getdigits(&p);
1854 }
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001855 return find_file_name_in_path(ptr, len, options,
1856 count, curbuf->b_ffname);
1857 }
1858 return file_name_at_cursor(options | FNAME_HYP, count, file_lnum);
1859}
1860
1861/*
1862 * Return the file name under or after the cursor.
1863 *
1864 * The 'path' option is searched if the file name is not absolute.
1865 * The string returned has been alloc'ed and should be freed by the caller.
1866 * NULL is returned if the file name or file is not found.
1867 *
1868 * options:
1869 * FNAME_MESS give error messages
1870 * FNAME_EXP expand to path
1871 * FNAME_HYP check for hypertext link
1872 * FNAME_INCL apply "includeexpr"
1873 */
1874 char_u *
1875file_name_at_cursor(int options, long count, linenr_T *file_lnum)
1876{
1877 return file_name_in_line(ml_get_curline(),
1878 curwin->w_cursor.col, options, count, curbuf->b_ffname,
1879 file_lnum);
1880}
1881
1882/*
1883 * Return the name of the file under or after ptr[col].
1884 * Otherwise like file_name_at_cursor().
1885 */
1886 char_u *
1887file_name_in_line(
1888 char_u *line,
1889 int col,
1890 int options,
1891 long count,
1892 char_u *rel_fname, // file we are searching relative to
1893 linenr_T *file_lnum) // line number after the file name
1894{
1895 char_u *ptr;
1896 int len;
1897 int in_type = TRUE;
1898 int is_url = FALSE;
1899
1900 /*
1901 * search forward for what could be the start of a file name
1902 */
1903 ptr = line + col;
1904 while (*ptr != NUL && !vim_isfilec(*ptr))
1905 MB_PTR_ADV(ptr);
1906 if (*ptr == NUL) // nothing found
1907 {
1908 if (options & FNAME_MESS)
Bram Moolenaarac78dd42022-01-02 19:25:26 +00001909 emsg(_(e_no_file_name_under_cursor));
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001910 return NULL;
1911 }
1912
1913 /*
1914 * Search backward for first char of the file name.
1915 * Go one char back to ":" before "//" even when ':' is not in 'isfname'.
1916 */
1917 while (ptr > line)
1918 {
1919 if (has_mbyte && (len = (*mb_head_off)(line, ptr - 1)) > 0)
1920 ptr -= len + 1;
1921 else if (vim_isfilec(ptr[-1])
1922 || ((options & FNAME_HYP) && path_is_url(ptr - 1)))
1923 --ptr;
1924 else
1925 break;
1926 }
1927
1928 /*
1929 * Search forward for the last char of the file name.
1930 * Also allow "://" when ':' is not in 'isfname'.
1931 */
1932 len = 0;
1933 while (vim_isfilec(ptr[len]) || (ptr[len] == '\\' && ptr[len + 1] == ' ')
Bram Moolenaar747f1102022-09-18 13:06:41 +01001934 || ((options & FNAME_HYP) && path_is_url(ptr + len))
1935 || (is_url && vim_strchr((char_u *)":?&=", ptr[len]) != NULL))
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001936 {
Bram Moolenaar747f1102022-09-18 13:06:41 +01001937 // After type:// we also include :, ?, & and = as valid characters, so
1938 // that http://google.com:8080?q=this&that=ok works.
1939 if ((ptr[len] >= 'A' && ptr[len] <= 'Z')
1940 || (ptr[len] >= 'a' && ptr[len] <= 'z'))
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001941 {
1942 if (in_type && path_is_url(ptr + len + 1))
1943 is_url = TRUE;
1944 }
1945 else
1946 in_type = FALSE;
1947
1948 if (ptr[len] == '\\')
1949 // Skip over the "\" in "\ ".
1950 ++len;
1951 if (has_mbyte)
1952 len += (*mb_ptr2len)(ptr + len);
1953 else
1954 ++len;
1955 }
1956
1957 /*
1958 * If there is trailing punctuation, remove it.
1959 * But don't remove "..", could be a directory name.
1960 */
1961 if (len > 2 && vim_strchr((char_u *)".,:;!", ptr[len - 1]) != NULL
1962 && ptr[len - 2] != '.')
1963 --len;
1964
1965 if (file_lnum != NULL)
1966 {
1967 char_u *p;
Bram Moolenaar64e74c92019-12-22 15:38:06 +01001968 char *line_english = " line ";
1969 char *line_transl = _(line_msg);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001970
Bram Moolenaar64e74c92019-12-22 15:38:06 +01001971 // Get the number after the file name and a separator character.
1972 // Also accept " line 999" with and without the same translation as
1973 // used in last_set_msg().
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001974 p = ptr + len;
Bram Moolenaar64e74c92019-12-22 15:38:06 +01001975 if (STRNCMP(p, line_english, STRLEN(line_english)) == 0)
1976 p += STRLEN(line_english);
1977 else if (STRNCMP(p, line_transl, STRLEN(line_transl)) == 0)
1978 p += STRLEN(line_transl);
1979 else
1980 p = skipwhite(p);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01001981 if (*p != NUL)
1982 {
1983 if (!isdigit(*p))
1984 ++p; // skip the separator
1985 p = skipwhite(p);
1986 if (isdigit(*p))
1987 *file_lnum = (int)getdigits(&p);
1988 }
1989 }
1990
1991 return find_file_name_in_path(ptr, len, options, count, rel_fname);
1992}
1993
1994# if defined(FEAT_FIND_ID) && defined(FEAT_EVAL)
1995 static char_u *
1996eval_includeexpr(char_u *ptr, int len)
1997{
1998 char_u *res;
Bram Moolenaar47bcc5f2022-01-22 20:19:22 +00001999 sctx_T save_sctx = current_sctx;
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002000
2001 set_vim_var_string(VV_FNAME, ptr, len);
Bram Moolenaar47bcc5f2022-01-22 20:19:22 +00002002 current_sctx = curbuf->b_p_script_ctx[BV_INEX];
2003
Bram Moolenaarb171fb12020-06-24 20:34:03 +02002004 res = eval_to_string_safe(curbuf->b_p_inex,
Bram Moolenaar47bcc5f2022-01-22 20:19:22 +00002005 was_set_insecurely((char_u *)"includeexpr", OPT_LOCAL), TRUE);
2006
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002007 set_vim_var_string(VV_FNAME, NULL, 0);
Bram Moolenaar47bcc5f2022-01-22 20:19:22 +00002008 current_sctx = save_sctx;
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002009 return res;
2010}
2011# endif
2012
2013/*
2014 * Return the name of the file ptr[len] in 'path'.
2015 * Otherwise like file_name_at_cursor().
2016 */
2017 char_u *
2018find_file_name_in_path(
2019 char_u *ptr,
2020 int len,
2021 int options,
2022 long count,
2023 char_u *rel_fname) // file we are searching relative to
2024{
2025 char_u *file_name;
2026 int c;
2027# if defined(FEAT_FIND_ID) && defined(FEAT_EVAL)
2028 char_u *tofree = NULL;
Bram Moolenaar615ddd52021-11-17 18:00:31 +00002029# endif
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002030
Bram Moolenaar615ddd52021-11-17 18:00:31 +00002031 if (len == 0)
2032 return NULL;
2033
2034# if defined(FEAT_FIND_ID) && defined(FEAT_EVAL)
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002035 if ((options & FNAME_INCL) && *curbuf->b_p_inex != NUL)
2036 {
2037 tofree = eval_includeexpr(ptr, len);
2038 if (tofree != NULL)
2039 {
2040 ptr = tofree;
2041 len = (int)STRLEN(ptr);
2042 }
2043 }
2044# endif
2045
2046 if (options & FNAME_EXP)
2047 {
2048 file_name = find_file_in_path(ptr, len, options & ~FNAME_MESS,
2049 TRUE, rel_fname);
2050
2051# if defined(FEAT_FIND_ID) && defined(FEAT_EVAL)
2052 /*
2053 * If the file could not be found in a normal way, try applying
2054 * 'includeexpr' (unless done already).
2055 */
2056 if (file_name == NULL
2057 && !(options & FNAME_INCL) && *curbuf->b_p_inex != NUL)
2058 {
2059 tofree = eval_includeexpr(ptr, len);
2060 if (tofree != NULL)
2061 {
2062 ptr = tofree;
2063 len = (int)STRLEN(ptr);
2064 file_name = find_file_in_path(ptr, len, options & ~FNAME_MESS,
2065 TRUE, rel_fname);
2066 }
2067 }
2068# endif
2069 if (file_name == NULL && (options & FNAME_MESS))
2070 {
2071 c = ptr[len];
2072 ptr[len] = NUL;
Bram Moolenaarac78dd42022-01-02 19:25:26 +00002073 semsg(_(e_cant_find_file_str_in_path_2), ptr);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002074 ptr[len] = c;
2075 }
2076
2077 // Repeat finding the file "count" times. This matters when it
2078 // appears several times in the path.
2079 while (file_name != NULL && --count > 0)
2080 {
2081 vim_free(file_name);
2082 file_name = find_file_in_path(ptr, len, options, FALSE, rel_fname);
2083 }
2084 }
2085 else
2086 file_name = vim_strnsave(ptr, len);
2087
2088# if defined(FEAT_FIND_ID) && defined(FEAT_EVAL)
2089 vim_free(tofree);
2090# endif
2091
2092 return file_name;
2093}
2094
2095/*
2096 * Return the end of the directory name, on the first path
2097 * separator:
2098 * "/path/file", "/path/dir/", "/path//dir", "/file"
2099 * ^ ^ ^ ^
2100 */
2101 static char_u *
2102gettail_dir(char_u *fname)
2103{
2104 char_u *dir_end = fname;
2105 char_u *next_dir_end = fname;
2106 int look_for_sep = TRUE;
2107 char_u *p;
2108
2109 for (p = fname; *p != NUL; )
2110 {
2111 if (vim_ispathsep(*p))
2112 {
2113 if (look_for_sep)
2114 {
2115 next_dir_end = p;
2116 look_for_sep = FALSE;
2117 }
2118 }
2119 else
2120 {
2121 if (!look_for_sep)
2122 dir_end = next_dir_end;
2123 look_for_sep = TRUE;
2124 }
2125 MB_PTR_ADV(p);
2126 }
2127 return dir_end;
2128}
2129
2130/*
2131 * return TRUE if 'c' is a path list separator.
2132 */
2133 int
2134vim_ispathlistsep(int c)
2135{
2136# ifdef UNIX
2137 return (c == ':');
2138# else
2139 return (c == ';'); // might not be right for every system...
2140# endif
2141}
2142
2143/*
2144 * Moves "*psep" back to the previous path separator in "path".
2145 * Returns FAIL is "*psep" ends up at the beginning of "path".
2146 */
2147 static int
2148find_previous_pathsep(char_u *path, char_u **psep)
2149{
2150 // skip the current separator
2151 if (*psep > path && vim_ispathsep(**psep))
2152 --*psep;
2153
2154 // find the previous separator
2155 while (*psep > path)
2156 {
2157 if (vim_ispathsep(**psep))
2158 return OK;
2159 MB_PTR_BACK(path, *psep);
2160 }
2161
2162 return FAIL;
2163}
2164
2165/*
2166 * Returns TRUE if "maybe_unique" is unique wrt other_paths in "gap".
2167 * "maybe_unique" is the end portion of "((char_u **)gap->ga_data)[i]".
2168 */
2169 static int
2170is_unique(char_u *maybe_unique, garray_T *gap, int i)
2171{
2172 int j;
2173 int candidate_len;
2174 int other_path_len;
2175 char_u **other_paths = (char_u **)gap->ga_data;
2176 char_u *rival;
2177
2178 for (j = 0; j < gap->ga_len; j++)
2179 {
2180 if (j == i)
2181 continue; // don't compare it with itself
2182
2183 candidate_len = (int)STRLEN(maybe_unique);
2184 other_path_len = (int)STRLEN(other_paths[j]);
2185 if (other_path_len < candidate_len)
2186 continue; // it's different when it's shorter
2187
2188 rival = other_paths[j] + other_path_len - candidate_len;
2189 if (fnamecmp(maybe_unique, rival) == 0
2190 && (rival == other_paths[j] || vim_ispathsep(*(rival - 1))))
2191 return FALSE; // match
2192 }
2193
2194 return TRUE; // no match found
2195}
2196
2197/*
2198 * Split the 'path' option into an array of strings in garray_T. Relative
2199 * paths are expanded to their equivalent fullpath. This includes the "."
2200 * (relative to current buffer directory) and empty path (relative to current
2201 * directory) notations.
2202 *
2203 * TODO: handle upward search (;) and path limiter (**N) notations by
2204 * expanding each into their equivalent path(s).
2205 */
2206 static void
2207expand_path_option(char_u *curdir, garray_T *gap)
2208{
2209 char_u *path_option = *curbuf->b_p_path == NUL
2210 ? p_path : curbuf->b_p_path;
2211 char_u *buf;
2212 char_u *p;
2213 int len;
2214
Bram Moolenaar51e14382019-05-25 20:21:28 +02002215 if ((buf = alloc(MAXPATHL)) == NULL)
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002216 return;
2217
2218 while (*path_option != NUL)
2219 {
2220 copy_option_part(&path_option, buf, MAXPATHL, " ,");
2221
2222 if (buf[0] == '.' && (buf[1] == NUL || vim_ispathsep(buf[1])))
2223 {
2224 // Relative to current buffer:
2225 // "/path/file" + "." -> "/path/"
2226 // "/path/file" + "./subdir" -> "/path/subdir"
2227 if (curbuf->b_ffname == NULL)
2228 continue;
2229 p = gettail(curbuf->b_ffname);
2230 len = (int)(p - curbuf->b_ffname);
2231 if (len + (int)STRLEN(buf) >= MAXPATHL)
2232 continue;
2233 if (buf[1] == NUL)
2234 buf[len] = NUL;
2235 else
2236 STRMOVE(buf + len, buf + 2);
2237 mch_memmove(buf, curbuf->b_ffname, len);
2238 simplify_filename(buf);
2239 }
2240 else if (buf[0] == NUL)
2241 // relative to current directory
2242 STRCPY(buf, curdir);
2243 else if (path_with_url(buf))
2244 // URL can't be used here
2245 continue;
2246 else if (!mch_isFullName(buf))
2247 {
2248 // Expand relative path to their full path equivalent
2249 len = (int)STRLEN(curdir);
2250 if (len + (int)STRLEN(buf) + 3 > MAXPATHL)
2251 continue;
2252 STRMOVE(buf + len + 1, buf);
2253 STRCPY(buf, curdir);
2254 buf[len] = PATHSEP;
2255 simplify_filename(buf);
2256 }
2257
2258 if (ga_grow(gap, 1) == FAIL)
2259 break;
2260
2261# if defined(MSWIN)
2262 // Avoid the path ending in a backslash, it fails when a comma is
2263 // appended.
2264 len = (int)STRLEN(buf);
2265 if (buf[len - 1] == '\\')
2266 buf[len - 1] = '/';
2267# endif
2268
2269 p = vim_strsave(buf);
2270 if (p == NULL)
2271 break;
2272 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
2273 }
2274
2275 vim_free(buf);
2276}
2277
2278/*
2279 * Returns a pointer to the file or directory name in "fname" that matches the
2280 * longest path in "ga"p, or NULL if there is no match. For example:
2281 *
2282 * path: /foo/bar/baz
2283 * fname: /foo/bar/baz/quux.txt
2284 * returns: ^this
2285 */
2286 static char_u *
2287get_path_cutoff(char_u *fname, garray_T *gap)
2288{
2289 int i;
2290 int maxlen = 0;
2291 char_u **path_part = (char_u **)gap->ga_data;
2292 char_u *cutoff = NULL;
2293
2294 for (i = 0; i < gap->ga_len; i++)
2295 {
2296 int j = 0;
2297
2298 while ((fname[j] == path_part[i][j]
2299# if defined(MSWIN)
2300 || (vim_ispathsep(fname[j]) && vim_ispathsep(path_part[i][j]))
2301# endif
2302 ) && fname[j] != NUL && path_part[i][j] != NUL)
2303 j++;
2304 if (j > maxlen)
2305 {
2306 maxlen = j;
2307 cutoff = &fname[j];
2308 }
2309 }
2310
2311 // skip to the file or directory name
2312 if (cutoff != NULL)
2313 while (vim_ispathsep(*cutoff))
2314 MB_PTR_ADV(cutoff);
2315
2316 return cutoff;
2317}
2318
2319/*
2320 * Sorts, removes duplicates and modifies all the fullpath names in "gap" so
2321 * that they are unique with respect to each other while conserving the part
2322 * that matches the pattern. Beware, this is at least O(n^2) wrt "gap->ga_len".
2323 */
2324 void
2325uniquefy_paths(garray_T *gap, char_u *pattern)
2326{
2327 int i;
2328 int len;
2329 char_u **fnames = (char_u **)gap->ga_data;
2330 int sort_again = FALSE;
2331 char_u *pat;
2332 char_u *file_pattern;
2333 char_u *curdir;
2334 regmatch_T regmatch;
2335 garray_T path_ga;
2336 char_u **in_curdir = NULL;
2337 char_u *short_name;
2338
2339 remove_duplicates(gap);
Bram Moolenaar04935fb2022-01-08 16:19:22 +00002340 ga_init2(&path_ga, sizeof(char_u *), 1);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002341
2342 /*
2343 * We need to prepend a '*' at the beginning of file_pattern so that the
2344 * regex matches anywhere in the path. FIXME: is this valid for all
2345 * possible patterns?
2346 */
2347 len = (int)STRLEN(pattern);
2348 file_pattern = alloc(len + 2);
2349 if (file_pattern == NULL)
2350 return;
2351 file_pattern[0] = '*';
2352 file_pattern[1] = NUL;
2353 STRCAT(file_pattern, pattern);
2354 pat = file_pat_to_reg_pat(file_pattern, NULL, NULL, TRUE);
2355 vim_free(file_pattern);
2356 if (pat == NULL)
2357 return;
2358
2359 regmatch.rm_ic = TRUE; // always ignore case
2360 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
2361 vim_free(pat);
2362 if (regmatch.regprog == NULL)
2363 return;
2364
Bram Moolenaar51e14382019-05-25 20:21:28 +02002365 if ((curdir = alloc(MAXPATHL)) == NULL)
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002366 goto theend;
2367 mch_dirname(curdir, MAXPATHL);
2368 expand_path_option(curdir, &path_ga);
2369
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002370 in_curdir = ALLOC_CLEAR_MULT(char_u *, gap->ga_len);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002371 if (in_curdir == NULL)
2372 goto theend;
2373
2374 for (i = 0; i < gap->ga_len && !got_int; i++)
2375 {
2376 char_u *path = fnames[i];
2377 int is_in_curdir;
2378 char_u *dir_end = gettail_dir(path);
2379 char_u *pathsep_p;
2380 char_u *path_cutoff;
2381
2382 len = (int)STRLEN(path);
2383 is_in_curdir = fnamencmp(curdir, path, dir_end - path) == 0
2384 && curdir[dir_end - path] == NUL;
2385 if (is_in_curdir)
2386 in_curdir[i] = vim_strsave(path);
2387
2388 // Shorten the filename while maintaining its uniqueness
2389 path_cutoff = get_path_cutoff(path, &path_ga);
2390
2391 // Don't assume all files can be reached without path when search
2392 // pattern starts with star star slash, so only remove path_cutoff
2393 // when possible.
2394 if (pattern[0] == '*' && pattern[1] == '*'
2395 && vim_ispathsep_nocolon(pattern[2])
2396 && path_cutoff != NULL
2397 && vim_regexec(&regmatch, path_cutoff, (colnr_T)0)
2398 && is_unique(path_cutoff, gap, i))
2399 {
2400 sort_again = TRUE;
2401 mch_memmove(path, path_cutoff, STRLEN(path_cutoff) + 1);
2402 }
2403 else
2404 {
2405 // Here all files can be reached without path, so get shortest
2406 // unique path. We start at the end of the path.
2407 pathsep_p = path + len - 1;
2408
2409 while (find_previous_pathsep(path, &pathsep_p))
2410 if (vim_regexec(&regmatch, pathsep_p + 1, (colnr_T)0)
2411 && is_unique(pathsep_p + 1, gap, i)
2412 && path_cutoff != NULL && pathsep_p + 1 >= path_cutoff)
2413 {
2414 sort_again = TRUE;
2415 mch_memmove(path, pathsep_p + 1, STRLEN(pathsep_p));
2416 break;
2417 }
2418 }
2419
2420 if (mch_isFullName(path))
2421 {
2422 /*
2423 * Last resort: shorten relative to curdir if possible.
2424 * 'possible' means:
2425 * 1. It is under the current directory.
2426 * 2. The result is actually shorter than the original.
2427 *
2428 * Before curdir After
2429 * /foo/bar/file.txt /foo/bar ./file.txt
2430 * c:\foo\bar\file.txt c:\foo\bar .\file.txt
2431 * /file.txt / /file.txt
2432 * c:\file.txt c:\ .\file.txt
2433 */
2434 short_name = shorten_fname(path, curdir);
2435 if (short_name != NULL && short_name > path + 1
2436# if defined(MSWIN)
2437 // On windows,
2438 // shorten_fname("c:\a\a.txt", "c:\a\b")
2439 // returns "\a\a.txt", which is not really the short
2440 // name, hence:
2441 && !vim_ispathsep(*short_name)
2442# endif
2443 )
2444 {
2445 STRCPY(path, ".");
2446 add_pathsep(path);
2447 STRMOVE(path + STRLEN(path), short_name);
2448 }
2449 }
2450 ui_breakcheck();
2451 }
2452
2453 // Shorten filenames in /in/current/directory/{filename}
2454 for (i = 0; i < gap->ga_len && !got_int; i++)
2455 {
2456 char_u *rel_path;
2457 char_u *path = in_curdir[i];
2458
2459 if (path == NULL)
2460 continue;
2461
2462 // If the {filename} is not unique, change it to ./{filename}.
2463 // Else reduce it to {filename}
2464 short_name = shorten_fname(path, curdir);
2465 if (short_name == NULL)
2466 short_name = path;
2467 if (is_unique(short_name, gap, i))
2468 {
2469 STRCPY(fnames[i], short_name);
2470 continue;
2471 }
2472
Bram Moolenaar51e14382019-05-25 20:21:28 +02002473 rel_path = alloc(STRLEN(short_name) + STRLEN(PATHSEPSTR) + 2);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002474 if (rel_path == NULL)
2475 goto theend;
2476 STRCPY(rel_path, ".");
2477 add_pathsep(rel_path);
2478 STRCAT(rel_path, short_name);
2479
2480 vim_free(fnames[i]);
2481 fnames[i] = rel_path;
2482 sort_again = TRUE;
2483 ui_breakcheck();
2484 }
2485
2486theend:
2487 vim_free(curdir);
2488 if (in_curdir != NULL)
2489 {
2490 for (i = 0; i < gap->ga_len; i++)
2491 vim_free(in_curdir[i]);
2492 vim_free(in_curdir);
2493 }
2494 ga_clear_strings(&path_ga);
2495 vim_regfree(regmatch.regprog);
2496
2497 if (sort_again)
2498 remove_duplicates(gap);
2499}
2500
2501/*
2502 * Calls globpath() with 'path' values for the given pattern and stores the
2503 * result in "gap".
2504 * Returns the total number of matches.
2505 */
2506 int
2507expand_in_path(
2508 garray_T *gap,
2509 char_u *pattern,
2510 int flags) // EW_* flags
2511{
2512 char_u *curdir;
2513 garray_T path_ga;
2514 char_u *paths = NULL;
2515 int glob_flags = 0;
2516
Bram Moolenaar964b3742019-05-24 18:54:09 +02002517 if ((curdir = alloc(MAXPATHL)) == NULL)
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002518 return 0;
2519 mch_dirname(curdir, MAXPATHL);
2520
Bram Moolenaar04935fb2022-01-08 16:19:22 +00002521 ga_init2(&path_ga, sizeof(char_u *), 1);
Bram Moolenaar5fd0f502019-02-13 23:13:28 +01002522 expand_path_option(curdir, &path_ga);
2523 vim_free(curdir);
2524 if (path_ga.ga_len == 0)
2525 return 0;
2526
2527 paths = ga_concat_strings(&path_ga, ",");
2528 ga_clear_strings(&path_ga);
2529 if (paths == NULL)
2530 return 0;
2531
2532 if (flags & EW_ICASE)
2533 glob_flags |= WILD_ICASE;
2534 if (flags & EW_ADDSLASH)
2535 glob_flags |= WILD_ADD_SLASH;
2536 globpath(paths, pattern, gap, glob_flags);
2537 vim_free(paths);
2538
2539 return gap->ga_len;
2540}
2541
Bram Moolenaarb4a60202019-03-31 19:40:07 +02002542
2543/*
2544 * Converts a file name into a canonical form. It simplifies a file name into
2545 * its simplest form by stripping out unneeded components, if any. The
2546 * resulting file name is simplified in place and will either be the same
2547 * length as that supplied, or shorter.
2548 */
2549 void
2550simplify_filename(char_u *filename)
2551{
2552#ifndef AMIGA // Amiga doesn't have "..", it uses "/"
2553 int components = 0;
2554 char_u *p, *tail, *start;
2555 int stripping_disabled = FALSE;
2556 int relative = TRUE;
2557
2558 p = filename;
2559# ifdef BACKSLASH_IN_FILENAME
Yegappan Lakshmanan6df0f272021-12-16 13:06:10 +00002560 if (p[0] != NUL && p[1] == ':') // skip "x:"
Bram Moolenaarb4a60202019-03-31 19:40:07 +02002561 p += 2;
2562# endif
2563
2564 if (vim_ispathsep(*p))
2565 {
2566 relative = FALSE;
2567 do
2568 ++p;
2569 while (vim_ispathsep(*p));
2570 }
2571 start = p; // remember start after "c:/" or "/" or "///"
Bram Moolenaarfdcbe3c2020-06-15 21:41:56 +02002572#ifdef UNIX
2573 // Posix says that "//path" is unchanged but "///path" is "/path".
2574 if (start > filename + 2)
2575 {
2576 STRMOVE(filename + 1, p);
2577 start = p = filename + 1;
2578 }
2579#endif
Bram Moolenaarb4a60202019-03-31 19:40:07 +02002580
2581 do
2582 {
2583 // At this point "p" is pointing to the char following a single "/"
2584 // or "p" is at the "start" of the (absolute or relative) path name.
2585# ifdef VMS
2586 // VMS allows device:[path] - don't strip the [ in directory
2587 if ((*p == '[' || *p == '<') && p > filename && p[-1] == ':')
2588 {
2589 // :[ or :< composition: vms directory component
2590 ++components;
2591 p = getnextcomp(p + 1);
2592 }
2593 // allow remote calls as host"user passwd"::device:[path]
2594 else if (p[0] == ':' && p[1] == ':' && p > filename && p[-1] == '"' )
2595 {
2596 // ":: composition: vms host/passwd component
2597 ++components;
2598 p = getnextcomp(p + 2);
2599 }
2600 else
2601# endif
2602 if (vim_ispathsep(*p))
2603 STRMOVE(p, p + 1); // remove duplicate "/"
2604 else if (p[0] == '.' && (vim_ispathsep(p[1]) || p[1] == NUL))
2605 {
2606 if (p == start && relative)
2607 p += 1 + (p[1] != NUL); // keep single "." or leading "./"
2608 else
2609 {
2610 // Strip "./" or ".///". If we are at the end of the file name
2611 // and there is no trailing path separator, either strip "/." if
2612 // we are after "start", or strip "." if we are at the beginning
2613 // of an absolute path name .
2614 tail = p + 1;
2615 if (p[1] != NUL)
2616 while (vim_ispathsep(*tail))
2617 MB_PTR_ADV(tail);
2618 else if (p > start)
2619 --p; // strip preceding path separator
2620 STRMOVE(p, tail);
2621 }
2622 }
2623 else if (p[0] == '.' && p[1] == '.' &&
2624 (vim_ispathsep(p[2]) || p[2] == NUL))
2625 {
2626 // Skip to after ".." or "../" or "..///".
2627 tail = p + 2;
2628 while (vim_ispathsep(*tail))
2629 MB_PTR_ADV(tail);
2630
2631 if (components > 0) // strip one preceding component
2632 {
2633 int do_strip = FALSE;
2634 char_u saved_char;
2635 stat_T st;
2636
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002637 // Don't strip for an erroneous file name.
Bram Moolenaarb4a60202019-03-31 19:40:07 +02002638 if (!stripping_disabled)
2639 {
2640 // If the preceding component does not exist in the file
2641 // system, we strip it. On Unix, we don't accept a symbolic
2642 // link that refers to a non-existent file.
2643 saved_char = p[-1];
2644 p[-1] = NUL;
2645# ifdef UNIX
2646 if (mch_lstat((char *)filename, &st) < 0)
2647# else
2648 if (mch_stat((char *)filename, &st) < 0)
2649# endif
2650 do_strip = TRUE;
2651 p[-1] = saved_char;
2652
2653 --p;
2654 // Skip back to after previous '/'.
2655 while (p > start && !after_pathsep(start, p))
2656 MB_PTR_BACK(start, p);
2657
2658 if (!do_strip)
2659 {
2660 // If the component exists in the file system, check
2661 // that stripping it won't change the meaning of the
2662 // file name. First get information about the
2663 // unstripped file name. This may fail if the component
2664 // to strip is not a searchable directory (but a regular
2665 // file, for instance), since the trailing "/.." cannot
2666 // be applied then. We don't strip it then since we
2667 // don't want to replace an erroneous file name by
2668 // a valid one, and we disable stripping of later
2669 // components.
2670 saved_char = *tail;
2671 *tail = NUL;
2672 if (mch_stat((char *)filename, &st) >= 0)
2673 do_strip = TRUE;
2674 else
2675 stripping_disabled = TRUE;
2676 *tail = saved_char;
2677# ifdef UNIX
2678 if (do_strip)
2679 {
2680 stat_T new_st;
2681
2682 // On Unix, the check for the unstripped file name
2683 // above works also for a symbolic link pointing to
2684 // a searchable directory. But then the parent of
2685 // the directory pointed to by the link must be the
2686 // same as the stripped file name. (The latter
2687 // exists in the file system since it is the
2688 // component's parent directory.)
2689 if (p == start && relative)
2690 (void)mch_stat(".", &new_st);
2691 else
2692 {
2693 saved_char = *p;
2694 *p = NUL;
2695 (void)mch_stat((char *)filename, &new_st);
2696 *p = saved_char;
2697 }
2698
2699 if (new_st.st_ino != st.st_ino ||
2700 new_st.st_dev != st.st_dev)
2701 {
2702 do_strip = FALSE;
2703 // We don't disable stripping of later
2704 // components since the unstripped path name is
2705 // still valid.
2706 }
2707 }
2708# endif
2709 }
2710 }
2711
2712 if (!do_strip)
2713 {
2714 // Skip the ".." or "../" and reset the counter for the
2715 // components that might be stripped later on.
2716 p = tail;
2717 components = 0;
2718 }
2719 else
2720 {
2721 // Strip previous component. If the result would get empty
2722 // and there is no trailing path separator, leave a single
2723 // "." instead. If we are at the end of the file name and
2724 // there is no trailing path separator and a preceding
2725 // component is left after stripping, strip its trailing
2726 // path separator as well.
2727 if (p == start && relative && tail[-1] == '.')
2728 {
2729 *p++ = '.';
2730 *p = NUL;
2731 }
2732 else
2733 {
2734 if (p > start && tail[-1] == '.')
2735 --p;
2736 STRMOVE(p, tail); // strip previous component
2737 }
2738
2739 --components;
2740 }
2741 }
2742 else if (p == start && !relative) // leading "/.." or "/../"
2743 STRMOVE(p, tail); // strip ".." or "../"
2744 else
2745 {
2746 if (p == start + 2 && p[-2] == '.') // leading "./../"
2747 {
2748 STRMOVE(p - 2, p); // strip leading "./"
2749 tail -= 2;
2750 }
2751 p = tail; // skip to char after ".." or "../"
2752 }
2753 }
2754 else
2755 {
2756 ++components; // simple path component
2757 p = getnextcomp(p);
2758 }
2759 } while (*p != NUL);
2760#endif // !AMIGA
2761}
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002762
2763#if defined(FEAT_EVAL) || defined(PROTO)
2764/*
2765 * "simplify()" function
2766 */
2767 void
2768f_simplify(typval_T *argvars, typval_T *rettv)
2769{
2770 char_u *p;
2771
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02002772 if (in_vim9script() && check_for_string_arg(argvars, 0) == FAIL)
2773 return;
2774
Bram Moolenaar3cfa5b12021-06-06 14:14:39 +02002775 p = tv_get_string_strict(&argvars[0]);
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002776 rettv->vval.v_string = vim_strsave(p);
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002777 simplify_filename(rettv->vval.v_string); // simplify in place
Bram Moolenaarb005cd82019-09-04 15:54:55 +02002778 rettv->v_type = VAR_STRING;
2779}
2780#endif // FEAT_EVAL