robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
65.7 KiB1947 linesraw
1// File searching functions for 'path', 'tags' and 'cdpath' options.
2//
3// External visible functions:
4//   vim_findfile_init()          creates/initialises the search context
5//   vim_findfile_free_visited()  free list of visited files/dirs of search
6//                                context
7//   vim_findfile()               find a file in the search context
8//   vim_findfile_cleanup()       cleanup/free search context created by
9//                                vim_findfile_init()
10//
11// All static functions and variables start with 'ff_'
12//
13// In general it works like this:
14// First you create yourself a search context by calling vim_findfile_init().
15// It is possible to give a search context from a previous call to
16// vim_findfile_init(), so it can be reused. After this you call vim_findfile()
17// until you are satisfied with the result or it returns NULL. On every call it
18// returns the next file which matches the conditions given to
19// vim_findfile_init(). If it doesn't find a next file it returns NULL.
20//
21// It is possible to call vim_findfile_init() again to reinitialise your search
22// with some new parameters. Don't forget to pass your old search context to
23// it, so it can reuse it and especially reuse the list of already visited
24// directories. If you want to delete the list of already visited directories
25// simply call vim_findfile_free_visited().
26//
27// When you are done call vim_findfile_cleanup() to free the search context.
28//
29// The function vim_findfile_init() has a long comment, which describes the
30// needed parameters.
31//
32//
33//
34// ATTENTION:
35// ==========
36// We use an allocated search context, these functions are NOT thread-safe!!!!!
37//
38// To minimize parameter passing (or because I'm too lazy), only the
39// external visible functions get a search context as a parameter. This is
40// then assigned to a static global, which is used throughout the local
41// functions.
42
43#include <assert.h>
44#include <ctype.h>
45#include <inttypes.h>
46#include <limits.h>
47#include <stdbool.h>
48#include <stddef.h>
49#include <stdio.h>
50#include <stdlib.h>
51#include <string.h>
52
53#include "nvim/api/private/defs.h"
54#include "nvim/api/private/helpers.h"
55#include "nvim/ascii_defs.h"
56#include "nvim/autocmd.h"
57#include "nvim/autocmd_defs.h"
58#include "nvim/buffer_defs.h"
59#include "nvim/charset.h"
60#include "nvim/cursor.h"
61#include "nvim/errors.h"
62#include "nvim/eval.h"
63#include "nvim/eval/typval.h"
64#include "nvim/eval/typval_defs.h"
65#include "nvim/eval/vars.h"
66#include "nvim/file_search.h"
67#include "nvim/gettext_defs.h"
68#include "nvim/globals.h"
69#include "nvim/macros_defs.h"
70#include "nvim/mbyte.h"
71#include "nvim/memory.h"
72#include "nvim/message.h"
73#include "nvim/normal.h"
74#include "nvim/option.h"
75#include "nvim/option_defs.h"
76#include "nvim/option_vars.h"
77#include "nvim/os/fs.h"
78#include "nvim/os/fs_defs.h"
79#include "nvim/os/input.h"
80#include "nvim/os/os.h"
81#include "nvim/os/os_defs.h"
82#include "nvim/path.h"
83#include "nvim/strings.h"
84#include "nvim/vim_defs.h"
85
86static String ff_expand_buffer = STRING_INIT;  // used for expanding filenames
87
88// type for the directory search stack
89typedef struct ff_stack {
90  struct ff_stack *ffs_prev;
91
92  // the fix part (no wildcards) and the part containing the wildcards
93  // of the search path
94  String ffs_fix_path;
95  String ffs_wc_path;
96
97  // files/dirs found in the above directory, matched by the first wildcard
98  // of wc_part
99  char **ffs_filearray;
100  int ffs_filearray_size;
101  int ffs_filearray_cur;                  // needed for partly handled dirs
102
103  // to store status of partly handled directories
104  // 0: we work on this directory for the first time
105  // 1: this directory was partly searched in an earlier step
106  int ffs_stage;
107
108  // How deep are we in the directory tree?
109  // Counts backward from value of level parameter to vim_findfile_init
110  int ffs_level;
111
112  // Did we already expand '**' to an empty string?
113  int ffs_star_star_empty;
114} ff_stack_T;
115
116// type for already visited directories or files.
117typedef struct ff_visited {
118  struct ff_visited *ffv_next;
119
120  // Visited directories are different if the wildcard string are
121  // different. So we have to save it.
122  char *ffv_wc_path;
123
124  // use FileID for comparison (needed because of links), else use filename.
125  bool file_id_valid;
126  FileID file_id;
127  // The memory for this struct is allocated according to the length of
128  // ffv_fname.
129  char ffv_fname[];
130} ff_visited_T;
131
132// We might have to manage several visited lists during a search.
133// This is especially needed for the tags option. If tags is set to:
134//      "./++/tags,./++/TAGS,++/tags"  (replace + with *)
135// So we have to do 3 searches:
136//   1) search from the current files directory downward for the file "tags"
137//   2) search from the current files directory downward for the file "TAGS"
138//   3) search from Vims current directory downwards for the file "tags"
139// As you can see, the first and the third search are for the same file, so for
140// the third search we can use the visited list of the first search. For the
141// second search we must start from an empty visited list.
142// The struct ff_visited_list_hdr is used to manage a linked list of already
143// visited lists.
144typedef struct ff_visited_list_hdr {
145  struct ff_visited_list_hdr *ffvl_next;
146
147  // the filename the attached visited list is for
148  char *ffvl_filename;
149
150  ff_visited_T *ffvl_visited_list;
151} ff_visited_list_hdr_T;
152
153// '**' can be expanded to several directory levels.
154// Set the default maximum depth.
155#define FF_MAX_STAR_STAR_EXPAND 30
156
157// The search context:
158//   ffsc_stack_ptr:    the stack for the dirs to search
159//   ffsc_visited_list: the currently active visited list
160//   ffsc_dir_visited_list: the currently active visited list for search dirs
161//   ffsc_visited_lists_list: the list of all visited lists
162//   ffsc_dir_visited_lists_list: the list of all visited lists for search dirs
163//   ffsc_file_to_search:     the file to search for
164//   ffsc_start_dir:    the starting directory, if search path was relative
165//   ffsc_fix_path:     the fix part of the given path (without wildcards)
166//                      Needed for upward search.
167//   ffsc_wc_path:      the part of the given path containing wildcards
168//   ffsc_level:        how many levels of dirs to search downwards
169//   ffsc_stopdirs_v:   array of stop directories for upward search
170//   ffsc_find_what:    FINDFILE_BOTH, FINDFILE_DIR or FINDFILE_FILE
171//   ffsc_tagfile:      searching for tags file, don't use 'suffixesadd'
172typedef struct {
173  ff_stack_T *ffsc_stack_ptr;
174  ff_visited_list_hdr_T *ffsc_visited_list;
175  ff_visited_list_hdr_T *ffsc_dir_visited_list;
176  ff_visited_list_hdr_T *ffsc_visited_lists_list;
177  ff_visited_list_hdr_T *ffsc_dir_visited_lists_list;
178  String ffsc_file_to_search;
179  String ffsc_start_dir;
180  String ffsc_fix_path;
181  String ffsc_wc_path;
182  int ffsc_level;
183  String *ffsc_stopdirs_v;
184  int ffsc_find_what;
185  int ffsc_tagfile;
186} ff_search_ctx_T;
187
188// locally needed functions
189
190#include "file_search.c.generated.h"
191
192static const char e_path_too_long_for_completion[]
193  = N_("E854: Path too long for completion");
194
195/// Initialization routine for vim_findfile().
196///
197/// Returns the newly allocated search context or NULL if an error occurred.
198///
199/// Don't forget to clean up by calling vim_findfile_cleanup() if you are done
200/// with the search context.
201///
202/// Find the file 'filename' in the directory 'path'.
203/// The parameter 'path' may contain wildcards. If so only search 'level'
204/// directories deep. The parameter 'level' is the absolute maximum and is
205/// not related to restricts given to the '**' wildcard. If 'level' is 100
206/// and you use '**200' vim_findfile() will stop after 100 levels.
207///
208/// 'filename' cannot contain wildcards!  It is used as-is, no backslashes to
209/// escape special characters.
210///
211/// If 'stopdirs' is not NULL and nothing is found downward, the search is
212/// restarted on the next higher directory level. This is repeated until the
213/// start-directory of a search is contained in 'stopdirs'. 'stopdirs' has the
214/// format ";*<dirname>*\(;<dirname>\)*;\=$".
215///
216/// If the 'path' is relative, the starting dir for the search is either VIM's
217/// current dir or if the path starts with "./" the current files dir.
218/// If the 'path' is absolute, the starting dir is that part of the path before
219/// the first wildcard.
220///
221/// Upward search is only done on the starting dir.
222///
223/// If 'free_visited' is true the list of already visited files/directories is
224/// cleared. Set this to false if you just want to search from another
225/// directory, but want to be sure that no directory from a previous search is
226/// searched again. This is useful if you search for a file at different places.
227/// The list of visited files/dirs can also be cleared with the function
228/// vim_findfile_free_visited().
229///
230/// Set the parameter 'find_what' to FINDFILE_DIR if you want to search for
231/// directories only, FINDFILE_FILE for files only, FINDFILE_BOTH for both.
232///
233/// A search context returned by a previous call to vim_findfile_init() can be
234/// passed in the parameter "search_ctx_arg".  This context is reused and
235/// reinitialized with the new parameters.  The list of already visited
236/// directories from this context is only deleted if the parameter
237/// "free_visited" is true.  Be aware that the passed "search_ctx_arg" is freed
238/// if the reinitialization fails.
239///
240/// If you don't have a search context from a previous call "search_ctx_arg"
241/// must be NULL.
242///
243/// This function silently ignores a few errors, vim_findfile() will have
244/// limited functionality then.
245///
246/// @param tagfile  expanding names of tags files
247/// @param rel_fname  file name to use for "."
248void *vim_findfile_init(char *path, char *filename, size_t filenamelen, char *stopdirs, int level,
249                        int free_visited, int find_what, void *search_ctx_arg, int tagfile,
250                        char *rel_fname)
251{
252  ff_stack_T *sptr;
253  ff_search_ctx_T *search_ctx;
254
255  // If a search context is given by the caller, reuse it, else allocate a
256  // new one.
257  if (search_ctx_arg != NULL) {
258    search_ctx = search_ctx_arg;
259  } else {
260    search_ctx = xcalloc(1, sizeof(ff_search_ctx_T));
261  }
262  search_ctx->ffsc_find_what = find_what;
263  search_ctx->ffsc_tagfile = tagfile;
264
265  // clear the search context, but NOT the visited lists
266  ff_clear(search_ctx);
267
268  // clear visited list if wanted
269  if (free_visited == true) {
270    vim_findfile_free_visited(search_ctx);
271  } else {
272    // Reuse old visited lists. Get the visited list for the given
273    // filename. If no list for the current filename exists, creates a new
274    // one.
275    search_ctx->ffsc_visited_list
276      = ff_get_visited_list(filename, filenamelen,
277                            &search_ctx->ffsc_visited_lists_list);
278    if (search_ctx->ffsc_visited_list == NULL) {
279      goto error_return;
280    }
281    search_ctx->ffsc_dir_visited_list
282      = ff_get_visited_list(filename, filenamelen,
283                            &search_ctx->ffsc_dir_visited_lists_list);
284    if (search_ctx->ffsc_dir_visited_list == NULL) {
285      goto error_return;
286    }
287  }
288
289  if (ff_expand_buffer.data == NULL) {
290    ff_expand_buffer.size = 0;
291    ff_expand_buffer.data = xmalloc(MAXPATHL);
292  }
293
294  // Store information on starting dir now if path is relative.
295  // If path is absolute, we do that later.
296  if (path[0] == '.'
297      && (vim_ispathsep(path[1]) || path[1] == NUL)
298      && (!tagfile || vim_strchr(p_cpo, kCpoDottag) == NULL)
299      && rel_fname != NULL) {
300    size_t len = (size_t)(path_tail(rel_fname) - rel_fname);
301
302    if (!vim_isAbsName(rel_fname) && len + 1 < MAXPATHL) {
303      // Make the start dir an absolute path name.
304      xmemcpyz(ff_expand_buffer.data, rel_fname, len);
305      ff_expand_buffer.size = len;
306      search_ctx->ffsc_start_dir = cstr_as_string(FullName_save(ff_expand_buffer.data, false));
307    } else {
308      search_ctx->ffsc_start_dir = cbuf_to_string(rel_fname, len);
309    }
310    if (*++path != NUL) {
311      path++;
312    }
313  } else if (*path == NUL || !vim_isAbsName(path)) {
314#ifdef BACKSLASH_IN_FILENAME
315    // "c:dir" needs "c:" to be expanded, otherwise use current dir
316    if (*path != NUL && path[1] == ':') {
317      char drive[3];
318
319      drive[0] = path[0];
320      drive[1] = ':';
321      drive[2] = NUL;
322      if (vim_FullName(drive, ff_expand_buffer.data, MAXPATHL, true) == FAIL) {
323        goto error_return;
324      }
325      path += 2;
326    } else
327#endif
328    if (os_dirname(ff_expand_buffer.data, MAXPATHL) == FAIL) {
329      goto error_return;
330    }
331    ff_expand_buffer.size = strlen(ff_expand_buffer.data);
332
333    search_ctx->ffsc_start_dir = copy_string(ff_expand_buffer, NULL);
334  }
335
336  // If stopdirs are given, split them into an array of pointers.
337  // If this fails (mem allocation), there is no upward search at all or a
338  // stop directory is not recognized -> continue silently.
339  // If stopdirs just contains a ";" or is empty,
340  // search_ctx->ffsc_stopdirs_v will only contain a  NULL pointer. This
341  // is handled as unlimited upward search.  See function
342  // ff_path_in_stoplist() for details.
343  if (stopdirs != NULL) {
344    char *walker = stopdirs;
345
346    while (*walker == ';') {
347      walker++;
348    }
349
350    size_t dircount = 1;
351    search_ctx->ffsc_stopdirs_v = xmalloc(sizeof(String));
352
353    do {
354      char *helper = walker;
355      void *ptr = xrealloc(search_ctx->ffsc_stopdirs_v,
356                           (dircount + 1) * sizeof(String));
357      search_ctx->ffsc_stopdirs_v = ptr;
358      walker = vim_strchr(walker, ';');
359      assert(!walker || walker - helper >= 0);
360      size_t len = walker ? (size_t)(walker - helper) : strlen(helper);
361      // "" means ascent till top of directory tree.
362      if (*helper != NUL && !vim_isAbsName(helper) && len + 1 < MAXPATHL) {
363        // Make the stop dir an absolute path name.
364        xmemcpyz(ff_expand_buffer.data, helper, len);
365        ff_expand_buffer.size = len;
366        search_ctx->ffsc_stopdirs_v[dircount - 1] = cstr_as_string(FullName_save(helper, len));
367      } else {
368        search_ctx->ffsc_stopdirs_v[dircount - 1] = cbuf_to_string(helper, len);
369      }
370      if (walker) {
371        walker++;
372      }
373      dircount++;
374    } while (walker != NULL);
375
376    search_ctx->ffsc_stopdirs_v[dircount - 1] = NULL_STRING;
377  }
378
379  search_ctx->ffsc_level = level;
380
381  // split into:
382  //  -fix path
383  //  -wildcard_stuff (might be NULL)
384  char *wc_part = vim_strchr(path, '*');
385  if (wc_part != NULL) {
386    int64_t llevel;
387    char *errpt;
388
389    // save the fix part of the path
390    assert(wc_part - path >= 0);
391    search_ctx->ffsc_fix_path = cbuf_to_string(path, (size_t)(wc_part - path));
392
393    // copy wc_path and add restricts to the '**' wildcard.
394    // The octet after a '**' is used as a (binary) counter.
395    // So '**3' is transposed to '**^C' ('^C' is ASCII value 3)
396    // or '**76' is transposed to '**N'( 'N' is ASCII value 76).
397    // If no restrict is given after '**' the default is used.
398    // Due to this technique the path looks awful if you print it as a
399    // string.
400    ff_expand_buffer.size = 0;
401    while (*wc_part != NUL) {
402      if (ff_expand_buffer.size + 5 >= MAXPATHL) {
403        emsg(_(e_path_too_long_for_completion));
404        break;
405      }
406      if (strncmp(wc_part, "**", 2) == 0) {
407        ff_expand_buffer.data[ff_expand_buffer.size++] = *wc_part++;
408        ff_expand_buffer.data[ff_expand_buffer.size++] = *wc_part++;
409
410        errpt = wc_part;
411        // Use def=255 so that overflow/too-large values keep the "max expand" behavior.
412        llevel = getdigits(&errpt, false, 255);
413        if (errpt != wc_part && llevel > 0 && llevel < 255) {
414          ff_expand_buffer.data[ff_expand_buffer.size++] = (char)llevel;
415        } else if (errpt != wc_part && llevel == 0) {
416          // restrict is 0 -> remove already added '**'
417          ff_expand_buffer.size -= 2;
418        } else {
419          ff_expand_buffer.data[ff_expand_buffer.size++] = FF_MAX_STAR_STAR_EXPAND;
420        }
421        wc_part = errpt;
422        if (*wc_part != NUL && !vim_ispathsep(*wc_part)) {
423          semsg(_(
424                 "E343: Invalid path: '**[number]' must be at the end of the path or be followed by '%s'."),
425                PATHSEPSTR);
426          goto error_return;
427        }
428      } else {
429        ff_expand_buffer.data[ff_expand_buffer.size++] = *wc_part++;
430      }
431    }
432    ff_expand_buffer.data[ff_expand_buffer.size] = NUL;
433    search_ctx->ffsc_wc_path = copy_string(ff_expand_buffer, false);
434  } else {
435    search_ctx->ffsc_fix_path = cstr_to_string(path);
436  }
437
438  if (search_ctx->ffsc_start_dir.data == NULL) {
439    // store the fix part as startdir.
440    // This is needed if the parameter path is fully qualified.
441    search_ctx->ffsc_start_dir = copy_string(search_ctx->ffsc_fix_path, false);
442    search_ctx->ffsc_fix_path.data[0] = NUL;
443    search_ctx->ffsc_fix_path.size = 0;
444  }
445
446  // create an absolute path
447  if (search_ctx->ffsc_start_dir.size
448      + search_ctx->ffsc_fix_path.size + 3 >= MAXPATHL) {
449    emsg(_(e_path_too_long_for_completion));
450    goto error_return;
451  }
452
453  bool add_sep = !after_pathsep(search_ctx->ffsc_start_dir.data,
454                                search_ctx->ffsc_start_dir.data + search_ctx->ffsc_start_dir.size);
455  ff_expand_buffer.size = (size_t)vim_snprintf(ff_expand_buffer.data,
456                                               MAXPATHL,
457                                               "%s%s",
458                                               search_ctx->ffsc_start_dir.data,
459                                               add_sep ? PATHSEPSTR : "");
460  assert(ff_expand_buffer.size < MAXPATHL);
461
462  {
463    size_t bufsize = ff_expand_buffer.size + search_ctx->ffsc_fix_path.size + 1;
464    char *buf = xmalloc(bufsize);
465
466    vim_snprintf(buf,
467                 bufsize,
468                 "%s%s",
469                 ff_expand_buffer.data,
470                 search_ctx->ffsc_fix_path.data);
471    if (os_isdir(buf)) {
472      if (search_ctx->ffsc_fix_path.size > 0) {
473        add_sep = !after_pathsep(search_ctx->ffsc_fix_path.data,
474                                 search_ctx->ffsc_fix_path.data + search_ctx->ffsc_fix_path.size);
475        ff_expand_buffer.size += (size_t)vim_snprintf(ff_expand_buffer.data + ff_expand_buffer.size,
476                                                      MAXPATHL - ff_expand_buffer.size,
477                                                      "%s%s",
478                                                      search_ctx->ffsc_fix_path.data,
479                                                      add_sep ? PATHSEPSTR : "");
480        assert(ff_expand_buffer.size < MAXPATHL);
481      }
482    } else {
483      char *p = path_tail(search_ctx->ffsc_fix_path.data);
484      int len = (int)search_ctx->ffsc_fix_path.size;
485
486      if (p > search_ctx->ffsc_fix_path.data) {
487        // do not add '..' to the path and start upwards searching
488        len = (int)(p - search_ctx->ffsc_fix_path.data) - 1;
489        if ((len >= 2 && strncmp(search_ctx->ffsc_fix_path.data, "..", 2) == 0)
490            && (len == 2 || search_ctx->ffsc_fix_path.data[2] == PATHSEP)) {
491          xfree(buf);
492          goto error_return;
493        }
494
495        add_sep = !after_pathsep(search_ctx->ffsc_fix_path.data,
496                                 search_ctx->ffsc_fix_path.data + search_ctx->ffsc_fix_path.size);
497        ff_expand_buffer.size += (size_t)vim_snprintf(ff_expand_buffer.data + ff_expand_buffer.size,
498                                                      MAXPATHL - ff_expand_buffer.size,
499                                                      "%.*s%s",
500                                                      len,
501                                                      search_ctx->ffsc_fix_path.data,
502                                                      add_sep ? PATHSEPSTR : "");
503        assert(ff_expand_buffer.size < MAXPATHL);
504      }
505
506      if (search_ctx->ffsc_wc_path.data != NULL) {
507        size_t tempsize = (search_ctx->ffsc_fix_path.size - (size_t)len)
508                          + search_ctx->ffsc_wc_path.size + 1;
509        char *temp = xmalloc(tempsize);
510        search_ctx->ffsc_wc_path.size = (size_t)vim_snprintf(temp,
511                                                             tempsize,
512                                                             "%s%s",
513                                                             search_ctx->ffsc_fix_path.data + len,
514                                                             search_ctx->ffsc_wc_path.data);
515        assert(search_ctx->ffsc_wc_path.size < tempsize);
516        xfree(search_ctx->ffsc_wc_path.data);
517        search_ctx->ffsc_wc_path.data = temp;
518      }
519    }
520    xfree(buf);
521  }
522
523  sptr = ff_create_stack_element(ff_expand_buffer.data,
524                                 ff_expand_buffer.size,
525                                 search_ctx->ffsc_wc_path.data,
526                                 search_ctx->ffsc_wc_path.size,
527                                 level, 0);
528
529  ff_push(search_ctx, sptr);
530  search_ctx->ffsc_file_to_search = cbuf_to_string(filename, filenamelen);
531  return search_ctx;
532
533error_return:
534  // We clear the search context now!
535  // Even when the caller gave us a (perhaps valid) context we free it here,
536  // as we might have already destroyed it.
537  vim_findfile_cleanup(search_ctx);
538  return NULL;
539}
540
541/// @return  the stopdir string.  Check that ';' is not escaped.
542char *vim_findfile_stopdir(char *buf)
543{
544  for (; *buf != NUL && *buf != ';' && (buf[0] != '\\' || buf[1] != ';'); buf++) {}
545  char *dst = buf;
546  if (*buf == ';') {
547    goto is_semicolon;
548  }
549  if (*buf == NUL) {
550    goto is_nul;
551  }
552  goto start;
553  while (*buf != NUL && *buf != ';') {
554    if (buf[0] == '\\' && buf[1] == ';') {
555start:
556      // Overwrite the escape char.
557      *dst++ = ';';
558      buf += 2;
559    } else {
560      *dst++ = *buf++;
561    }
562  }
563  assert(dst < buf);
564  *dst = NUL;
565  if (*buf == ';') {
566is_semicolon:
567    *buf = NUL;
568    buf++;
569  } else {  // if (*buf == NUL)
570is_nul:
571    buf = NULL;
572  }
573  return buf;
574}
575
576/// Clean up the given search context. Can handle a NULL pointer.
577void vim_findfile_cleanup(void *ctx)
578{
579  if (ctx == NULL) {
580    return;
581  }
582
583  vim_findfile_free_visited(ctx);
584  ff_clear(ctx);
585  xfree(ctx);
586}
587
588/// Find a file in a search context.
589/// The search context was created with vim_findfile_init() above.
590///
591/// To get all matching files call this function until you get NULL.
592///
593/// If the passed search_context is NULL, NULL is returned.
594///
595/// The search algorithm is depth first. To change this replace the
596/// stack with a list (don't forget to leave partly searched directories on the
597/// top of the list).
598///
599/// @return  a pointer to an allocated file name or,
600///          NULL if nothing found.
601char *vim_findfile(void *search_ctx_arg)
602{
603  String rest_of_wildcards;
604  char *path_end = NULL;
605  ff_stack_T *stackp = NULL;
606
607  if (search_ctx_arg == NULL) {
608    return NULL;
609  }
610
611  ff_search_ctx_T *search_ctx = (ff_search_ctx_T *)search_ctx_arg;
612
613  // filepath is used as buffer for various actions and as the storage to
614  // return a found filename.
615  String file_path = { .data = xmalloc(MAXPATHL) };
616
617  // store the end of the start dir -- needed for upward search
618  if (search_ctx->ffsc_start_dir.data != NULL) {
619    path_end = &search_ctx->ffsc_start_dir.data[search_ctx->ffsc_start_dir.size];
620  }
621
622  // upward search loop
623  while (true) {
624    // downward search loop
625    while (true) {
626      // check if user wants to stop the search
627      os_breakcheck();
628      if (got_int) {
629        break;
630      }
631
632      // get directory to work on from stack
633      stackp = ff_pop(search_ctx);
634      if (stackp == NULL) {
635        break;
636      }
637
638      // TODO(vim): decide if we leave this test in
639      //
640      // GOOD: don't search a directory(-tree) twice.
641      // BAD:  - check linked list for every new directory entered.
642      //       - check for double files also done below
643      //
644      // Here we check if we already searched this directory.
645      // We already searched a directory if:
646      // 1) The directory is the same.
647      // 2) We would use the same wildcard string.
648      //
649      // Good if you have links on same directory via several ways
650      //  or you have selfreferences in directories (e.g. SuSE Linux 6.3:
651      //  /etc/rc.d/init.d is linked to /etc/rc.d -> endless loop)
652      //
653      // This check is only needed for directories we work on for the
654      // first time (hence stackp->ff_filearray == NULL)
655      if (stackp->ffs_filearray == NULL
656          && ff_check_visited(&search_ctx->ffsc_dir_visited_list->ffvl_visited_list,
657                              stackp->ffs_fix_path.data, stackp->ffs_fix_path.size,
658                              stackp->ffs_wc_path.data, stackp->ffs_wc_path.size) == FAIL) {
659#ifdef FF_VERBOSE
660        if (p_verbose >= 5) {
661          verbose_enter_scroll();
662          smsg(0, "Already Searched: %s (%s)",
663               stackp->ffs_fix_path.data, stackp->ffs_wc_path.data);
664          msg_puts("\n");  // don't overwrite this either
665          verbose_leave_scroll();
666        }
667#endif
668        ff_free_stack_element(stackp);
669        continue;
670#ifdef FF_VERBOSE
671      } else if (p_verbose >= 5) {
672        verbose_enter_scroll();
673        smsg(0, "Searching: %s (%s)",
674             stackp->ffs_fix_path.data, stackp->ffs_wc_path.data);
675        msg_puts("\n");  // don't overwrite this either
676        verbose_leave_scroll();
677#endif
678      }
679
680      // check depth
681      if (stackp->ffs_level <= 0) {
682        ff_free_stack_element(stackp);
683        continue;
684      }
685
686      file_path.data[0] = NUL;
687      file_path.size = 0;
688
689      // If no filearray till now expand wildcards
690      // The function expand_wildcards() can handle an array of paths
691      // and all possible expands are returned in one array. We use this
692      // to handle the expansion of '**' into an empty string.
693      if (stackp->ffs_filearray == NULL) {
694        char *dirptrs[2];
695
696        // we use filepath to build the path expand_wildcards() should expand.
697        dirptrs[0] = file_path.data;
698        dirptrs[1] = NULL;
699
700        // if we have a start dir copy it in
701        if (!vim_isAbsName(stackp->ffs_fix_path.data)
702            && search_ctx->ffsc_start_dir.data) {
703          if (search_ctx->ffsc_start_dir.size + 1 >= MAXPATHL) {
704            ff_free_stack_element(stackp);
705            goto fail;
706          }
707          bool add_sep = !after_pathsep(search_ctx->ffsc_start_dir.data,
708                                        search_ctx->ffsc_start_dir.data
709                                        + search_ctx->ffsc_start_dir.size);
710          file_path.size = (size_t)vim_snprintf(file_path.data,
711                                                MAXPATHL,
712                                                "%s%s",
713                                                search_ctx->ffsc_start_dir.data,
714                                                add_sep ? PATHSEPSTR : "");
715          if (file_path.size >= MAXPATHL) {
716            ff_free_stack_element(stackp);
717            goto fail;
718          }
719        }
720
721        // append the fix part of the search path
722        if (file_path.size + stackp->ffs_fix_path.size + 1 >= MAXPATHL) {
723          ff_free_stack_element(stackp);
724          goto fail;
725        }
726        bool add_sep = !after_pathsep(stackp->ffs_fix_path.data,
727                                      stackp->ffs_fix_path.data + stackp->ffs_fix_path.size);
728        file_path.size += (size_t)vim_snprintf(file_path.data + file_path.size,
729                                               MAXPATHL - file_path.size,
730                                               "%s%s",
731                                               stackp->ffs_fix_path.data,
732                                               add_sep ? PATHSEPSTR : "");
733        if (file_path.size >= MAXPATHL) {
734          ff_free_stack_element(stackp);
735          goto fail;
736        }
737
738        rest_of_wildcards = stackp->ffs_wc_path;
739        if (*rest_of_wildcards.data != NUL) {
740          if (strncmp(rest_of_wildcards.data, "**", 2) == 0) {
741            // pointer to the restrict byte
742            // The restrict byte is not a character!
743            char *p = rest_of_wildcards.data + 2;
744
745            if (*p > 0) {
746              (*p)--;
747              if (file_path.size + 1 >= MAXPATHL) {
748                ff_free_stack_element(stackp);
749                goto fail;
750              }
751              file_path.data[file_path.size++] = '*';
752            }
753
754            if (*p == 0) {
755              // remove '**<numb> from wildcards
756              memmove(rest_of_wildcards.data,
757                      rest_of_wildcards.data + 3,
758                      (rest_of_wildcards.size - 3) + 1);    // +1 for NUL
759              rest_of_wildcards.size -= 3;
760              stackp->ffs_wc_path.size = rest_of_wildcards.size;
761            } else {
762              rest_of_wildcards.data += 3;
763              rest_of_wildcards.size -= 3;
764            }
765
766            if (stackp->ffs_star_star_empty == 0) {
767              // if not done before, expand '**' to empty
768              stackp->ffs_star_star_empty = 1;
769              dirptrs[1] = stackp->ffs_fix_path.data;
770            }
771          }
772
773          // Here we copy until the next path separator or the end of
774          // the path. If we stop at a path separator, there is
775          // still something else left. This is handled below by
776          // pushing every directory returned from expand_wildcards()
777          // on the stack again for further search.
778          while (*rest_of_wildcards.data
779                 && !vim_ispathsep(*rest_of_wildcards.data)) {
780            if (file_path.size + 1 >= MAXPATHL) {
781              ff_free_stack_element(stackp);
782              goto fail;
783            }
784            file_path.data[file_path.size++] = *rest_of_wildcards.data++;
785            rest_of_wildcards.size--;
786          }
787
788          file_path.data[file_path.size] = NUL;
789          if (vim_ispathsep(*rest_of_wildcards.data)) {
790            rest_of_wildcards.data++;
791            rest_of_wildcards.size--;
792          }
793        }
794
795        // Expand wildcards like "*" and "$VAR".
796        // If the path is a URL don't try this.
797        if (path_with_url(dirptrs[0])) {
798          stackp->ffs_filearray = xmalloc(sizeof(char *));
799          stackp->ffs_filearray[0] = xmemdupz(dirptrs[0], file_path.size);
800          stackp->ffs_filearray_size = 1;
801        } else {
802          // Add EW_NOTWILD because the expanded path may contain
803          // wildcard characters that are to be taken literally.
804          // This is a bit of a hack.
805          expand_wildcards((dirptrs[1] == NULL) ? 1 : 2, dirptrs,
806                           &stackp->ffs_filearray_size,
807                           &stackp->ffs_filearray,
808                           EW_DIR|EW_ADDSLASH|EW_SILENT|EW_NOTWILD);
809        }
810
811        stackp->ffs_filearray_cur = 0;
812        stackp->ffs_stage = 0;
813      } else {
814        rest_of_wildcards.data = &stackp->ffs_wc_path.data[stackp->ffs_wc_path.size];
815        rest_of_wildcards.size = 0;
816      }
817
818      if (stackp->ffs_stage == 0) {
819        // this is the first time we work on this directory
820        if (*rest_of_wildcards.data == NUL) {
821          // We don't have further wildcards to expand, so we have to
822          // check for the final file now.
823          for (int i = stackp->ffs_filearray_cur; i < stackp->ffs_filearray_size; i++) {
824            if (!path_with_url(stackp->ffs_filearray[i])
825                && !os_isdir(stackp->ffs_filearray[i])) {
826              continue;                 // not a directory
827            }
828            // prepare the filename to be checked for existence below
829            size_t len = strlen(stackp->ffs_filearray[i]);
830            if (len + 1 + search_ctx->ffsc_file_to_search.size >= MAXPATHL) {
831              ff_free_stack_element(stackp);
832              goto fail;
833            }
834            bool add_sep = !after_pathsep(stackp->ffs_filearray[i],
835                                          stackp->ffs_filearray[i] + len);
836            file_path.size = (size_t)vim_snprintf(file_path.data,
837                                                  MAXPATHL,
838                                                  "%s%s%s",
839                                                  stackp->ffs_filearray[i],
840                                                  add_sep ? PATHSEPSTR : "",
841                                                  search_ctx->ffsc_file_to_search.data);
842            if (file_path.size >= MAXPATHL) {
843              ff_free_stack_element(stackp);
844              goto fail;
845            }
846
847            // Try without extra suffix and then with suffixes
848            // from 'suffixesadd'.
849            len = file_path.size;
850            char *suf = search_ctx->ffsc_tagfile ? "" : curbuf->b_p_sua;
851            while (true) {
852              // if file exists and we didn't already find it
853              if ((path_with_url(file_path.data)
854                   || (os_path_exists(file_path.data)
855                       && (search_ctx->ffsc_find_what == FINDFILE_BOTH
856                           || ((search_ctx->ffsc_find_what == FINDFILE_DIR)
857                               == os_isdir(file_path.data)))))
858#ifndef FF_VERBOSE
859                  && (ff_check_visited(&search_ctx->ffsc_visited_list->ffvl_visited_list,
860                                       file_path.data, file_path.size, "", 0) == OK)
861#endif
862                  ) {
863#ifdef FF_VERBOSE
864                if (ff_check_visited(&search_ctx->ffsc_visited_list->ffvl_visited_list,
865                                     file_path.data, file_path.size, "", 0) == FAIL) {
866                  if (p_verbose >= 5) {
867                    verbose_enter_scroll();
868                    smsg(0, "Already: %s", file_path.data);
869                    msg_puts("\n");  // don't overwrite this either
870                    verbose_leave_scroll();
871                  }
872                  continue;
873                }
874#endif
875
876                // push dir to examine rest of subdirs later
877                assert(i < INT_MAX);
878                stackp->ffs_filearray_cur = i + 1;
879                ff_push(search_ctx, stackp);
880
881                if (!path_with_url(file_path.data)) {
882                  file_path.size = simplify_filename(file_path.data);
883                }
884
885                if (os_dirname(ff_expand_buffer.data, MAXPATHL) == OK) {
886                  ff_expand_buffer.size = strlen(ff_expand_buffer.data);
887                  char *p = path_shorten_fname(file_path.data, ff_expand_buffer.data);
888                  if (p != NULL) {
889                    memmove(file_path.data, p,
890                            (size_t)((file_path.data + file_path.size) - p) + 1);  // +1 for NUL
891                    file_path.size -= (size_t)(p - file_path.data);
892                  }
893                }
894#ifdef FF_VERBOSE
895                if (p_verbose >= 5) {
896                  verbose_enter_scroll();
897                  smsg(0, "HIT: %s", file_path.data);
898                  msg_puts("\n");  // don't overwrite this either
899                  verbose_leave_scroll();
900                }
901#endif
902                return file_path.data;
903              }
904
905              // Not found or found already, try next suffix.
906              if (*suf == NUL) {
907                break;
908              }
909              assert(MAXPATHL >= file_path.size);
910              file_path.size = len + copy_option_part(&suf, file_path.data + len,
911                                                      MAXPATHL - len, ",");
912            }
913          }
914        } else {
915          // still wildcards left, push the directories for further search
916          for (int i = stackp->ffs_filearray_cur; i < stackp->ffs_filearray_size; i++) {
917            if (!os_isdir(stackp->ffs_filearray[i])) {
918              continue;                 // not a directory
919            }
920            ff_push(search_ctx,
921                    ff_create_stack_element(stackp->ffs_filearray[i],
922                                            strlen(stackp->ffs_filearray[i]),
923                                            rest_of_wildcards.data,
924                                            rest_of_wildcards.size,
925                                            stackp->ffs_level - 1, 0));
926          }
927        }
928        stackp->ffs_filearray_cur = 0;
929        stackp->ffs_stage = 1;
930      }
931
932      // if wildcards contains '**' we have to descent till we reach the
933      // leaves of the directory tree.
934      if (strncmp(stackp->ffs_wc_path.data, "**", 2) == 0) {
935        for (int i = stackp->ffs_filearray_cur;
936             i < stackp->ffs_filearray_size; i++) {
937          if (path_equal(stackp->ffs_filearray[i],
938                         stackp->ffs_fix_path.data, kPathCmpLiteral)) {
939            continue;             // don't repush same directory
940          }
941          if (!os_isdir(stackp->ffs_filearray[i])) {
942            continue;               // not a directory
943          }
944          ff_push(search_ctx,
945                  ff_create_stack_element(stackp->ffs_filearray[i],
946                                          strlen(stackp->ffs_filearray[i]),
947                                          stackp->ffs_wc_path.data,
948                                          stackp->ffs_wc_path.size,
949                                          stackp->ffs_level - 1, 1));
950        }
951      }
952
953      // we are done with the current directory
954      ff_free_stack_element(stackp);
955    }
956
957    // If we reached this, we didn't find anything downwards.
958    // Let's check if we should do an upward search.
959    if (search_ctx->ffsc_start_dir.data
960        && search_ctx->ffsc_stopdirs_v != NULL && !got_int) {
961      ff_stack_T *sptr;
962      // path_end may point to the NUL or the previous path separator
963      ptrdiff_t plen = (path_end - search_ctx->ffsc_start_dir.data) + (*path_end != NUL);
964
965      // is the last starting directory in the stop list?
966      if (ff_path_in_stoplist(search_ctx->ffsc_start_dir.data,
967                              (size_t)plen, search_ctx->ffsc_stopdirs_v)) {
968        break;
969      }
970
971      // cut of last dir
972      while (path_end > search_ctx->ffsc_start_dir.data && vim_ispathsep(*path_end)) {
973        path_end--;
974      }
975      while (path_end > search_ctx->ffsc_start_dir.data && !vim_ispathsep(path_end[-1])) {
976        path_end--;
977      }
978      *path_end = NUL;
979
980      // we may have shortened search_ctx->ffsc_start_dir, so update it's length
981      search_ctx->ffsc_start_dir.size = (size_t)(path_end - search_ctx->ffsc_start_dir.data);
982      path_end--;
983
984      if (*search_ctx->ffsc_start_dir.data == NUL) {
985        break;
986      }
987
988      if (search_ctx->ffsc_start_dir.size + 1
989          + search_ctx->ffsc_fix_path.size >= MAXPATHL) {
990        goto fail;
991      }
992      bool add_sep = !after_pathsep(search_ctx->ffsc_start_dir.data,
993                                    search_ctx->ffsc_start_dir.data
994                                    + search_ctx->ffsc_start_dir.size);
995      file_path.size = (size_t)vim_snprintf(file_path.data,
996                                            MAXPATHL,
997                                            "%s%s%s",
998                                            search_ctx->ffsc_start_dir.data,
999                                            add_sep ? PATHSEPSTR : "",
1000                                            search_ctx->ffsc_fix_path.data);
1001      if (file_path.size >= MAXPATHL) {
1002        goto fail;
1003      }
1004
1005      // create a new stack entry
1006      sptr = ff_create_stack_element(file_path.data,
1007                                     file_path.size,
1008                                     search_ctx->ffsc_wc_path.data,
1009                                     search_ctx->ffsc_wc_path.size,
1010                                     search_ctx->ffsc_level, 0);
1011      ff_push(search_ctx, sptr);
1012    } else {
1013      break;
1014    }
1015  }
1016
1017fail:
1018  xfree(file_path.data);
1019  return NULL;
1020}
1021
1022/// Free the list of lists of visited files and directories
1023/// Can handle it if the passed search_context is NULL;
1024static void vim_findfile_free_visited(void *search_ctx_arg)
1025{
1026  if (search_ctx_arg == NULL) {
1027    return;
1028  }
1029
1030  ff_search_ctx_T *search_ctx = (ff_search_ctx_T *)search_ctx_arg;
1031  vim_findfile_free_visited_list(&search_ctx->ffsc_visited_lists_list);
1032  vim_findfile_free_visited_list(&search_ctx->ffsc_dir_visited_lists_list);
1033}
1034
1035static void vim_findfile_free_visited_list(ff_visited_list_hdr_T **list_headp)
1036{
1037  ff_visited_list_hdr_T *vp;
1038
1039  while (*list_headp != NULL) {
1040    vp = (*list_headp)->ffvl_next;
1041    ff_free_visited_list((*list_headp)->ffvl_visited_list);
1042
1043    xfree((*list_headp)->ffvl_filename);
1044    xfree(*list_headp);
1045    *list_headp = vp;
1046  }
1047  *list_headp = NULL;
1048}
1049
1050static void ff_free_visited_list(ff_visited_T *vl)
1051{
1052  ff_visited_T *vp;
1053
1054  while (vl != NULL) {
1055    vp = vl->ffv_next;
1056    xfree(vl->ffv_wc_path);
1057    xfree(vl);
1058    vl = vp;
1059  }
1060  vl = NULL;
1061}
1062
1063/// @return  the already visited list for the given filename. If none is found it
1064///          allocates a new one.
1065static ff_visited_list_hdr_T *ff_get_visited_list(char *filename, size_t filenamelen,
1066                                                  ff_visited_list_hdr_T **list_headp)
1067{
1068  ff_visited_list_hdr_T *retptr = NULL;
1069
1070  // check if a visited list for the given filename exists
1071  if (*list_headp != NULL) {
1072    retptr = *list_headp;
1073    while (retptr != NULL) {
1074      if (path_equal(filename, retptr->ffvl_filename, kPathCmpLiteral)) {
1075#ifdef FF_VERBOSE
1076        if (p_verbose >= 5) {
1077          verbose_enter_scroll();
1078          smsg(0, "ff_get_visited_list: FOUND list for %s", filename);
1079          msg_puts("\n");  // don't overwrite this either
1080          verbose_leave_scroll();
1081        }
1082#endif
1083        return retptr;
1084      }
1085      retptr = retptr->ffvl_next;
1086    }
1087  }
1088
1089#ifdef FF_VERBOSE
1090  if (p_verbose >= 5) {
1091    verbose_enter_scroll();
1092    smsg(0, "ff_get_visited_list: new list for %s", filename);
1093    msg_puts("\n");  // don't overwrite this either
1094    verbose_leave_scroll();
1095  }
1096#endif
1097
1098  // if we reach this we didn't find a list and we have to allocate new list
1099  retptr = xmalloc(sizeof(*retptr));
1100
1101  retptr->ffvl_visited_list = NULL;
1102  retptr->ffvl_filename = xmemdupz(filename, filenamelen);
1103  retptr->ffvl_next = *list_headp;
1104  *list_headp = retptr;
1105
1106  return retptr;
1107}
1108
1109/// Check if two wildcard paths are equal.
1110/// They are equal if:
1111///  - both paths are NULL
1112///  - they have the same length
1113///  - char by char comparison is OK
1114///  - the only differences are in the counters behind a '**', so
1115///    '**\20' is equal to '**\24'
1116static bool ff_wc_equal(char *s1, char *s2)
1117{
1118  int i, j;
1119  int prev1 = NUL;
1120  int prev2 = NUL;
1121
1122  if (s1 == s2) {
1123    return true;
1124  }
1125
1126  if (s1 == NULL || s2 == NULL) {
1127    return false;
1128  }
1129
1130  for (i = 0, j = 0; s1[i] != NUL && s2[j] != NUL;) {
1131    int c1 = utf_ptr2char(s1 + i);
1132    int c2 = utf_ptr2char(s2 + j);
1133
1134    if ((p_fic ? mb_tolower(c1) != mb_tolower(c2) : c1 != c2)
1135        && (prev1 != '*' || prev2 != '*')) {
1136      return false;
1137    }
1138    prev2 = prev1;
1139    prev1 = c1;
1140
1141    i += utfc_ptr2len(s1 + i);
1142    j += utfc_ptr2len(s2 + j);
1143  }
1144  return s1[i] == s2[j];
1145}
1146
1147/// maintains the list of already visited files and dirs
1148///
1149/// @return  FAIL if the given file/dir is already in the list or,
1150///          OK if it is newly added
1151static int ff_check_visited(ff_visited_T **visited_list, char *fname, size_t fnamelen,
1152                            char *wc_path, size_t wc_pathlen)
1153{
1154  ff_visited_T *vp;
1155  bool url = false;
1156
1157  FileID file_id;
1158  // For a URL we only compare the name, otherwise we compare the
1159  // device/inode.
1160  if (path_with_url(fname)) {
1161    xmemcpyz(ff_expand_buffer.data, fname, fnamelen);
1162    ff_expand_buffer.size = fnamelen;
1163    url = true;
1164  } else {
1165    ff_expand_buffer.data[0] = NUL;
1166    ff_expand_buffer.size = 0;
1167    if (!os_fileid(fname, &file_id)) {
1168      return FAIL;
1169    }
1170  }
1171
1172  // check against list of already visited files
1173  for (vp = *visited_list; vp != NULL; vp = vp->ffv_next) {
1174    if ((url && path_equal(vp->ffv_fname, ff_expand_buffer.data, kPathCmpLiteral))
1175        || (!url && vp->file_id_valid
1176            && os_fileid_equal(&(vp->file_id), &file_id))) {
1177      // are the wildcard parts equal
1178      if (ff_wc_equal(vp->ffv_wc_path, wc_path)) {
1179        // already visited
1180        return FAIL;
1181      }
1182    }
1183  }
1184
1185  // New file/dir.  Add it to the list of visited files/dirs.
1186  vp = xmalloc(offsetof(ff_visited_T, ffv_fname) + ff_expand_buffer.size + 1);
1187
1188  if (!url) {
1189    vp->file_id_valid = true;
1190    vp->file_id = file_id;
1191    vp->ffv_fname[0] = NUL;
1192  } else {
1193    vp->file_id_valid = false;
1194    STRCPY(vp->ffv_fname, ff_expand_buffer.data);
1195  }
1196
1197  if (wc_path != NULL) {
1198    vp->ffv_wc_path = xmemdupz(wc_path, wc_pathlen);
1199  } else {
1200    vp->ffv_wc_path = NULL;
1201  }
1202
1203  vp->ffv_next = *visited_list;
1204  *visited_list = vp;
1205
1206  return OK;
1207}
1208
1209/// create stack element from given path pieces
1210static ff_stack_T *ff_create_stack_element(char *fix_part, size_t fix_partlen, char *wc_part,
1211                                           size_t wc_partlen, int level, int star_star_empty)
1212{
1213  ff_stack_T *stack = xmalloc(sizeof(ff_stack_T));
1214
1215  stack->ffs_prev = NULL;
1216  stack->ffs_filearray = NULL;
1217  stack->ffs_filearray_size = 0;
1218  stack->ffs_filearray_cur = 0;
1219  stack->ffs_stage = 0;
1220  stack->ffs_level = level;
1221  stack->ffs_star_star_empty = star_star_empty;
1222
1223  // the following saves NULL pointer checks in vim_findfile
1224  if (fix_part == NULL) {
1225    fix_part = "";
1226    fix_partlen = 0;
1227  }
1228  stack->ffs_fix_path = cbuf_to_string(fix_part, fix_partlen);
1229
1230  if (wc_part == NULL) {
1231    wc_part = "";
1232    wc_partlen = 0;
1233  }
1234  stack->ffs_wc_path = cbuf_to_string(wc_part, wc_partlen);
1235
1236  return stack;
1237}
1238
1239/// Push a dir on the directory stack.
1240static void ff_push(ff_search_ctx_T *search_ctx, ff_stack_T *stack_ptr)
1241{
1242  // check for NULL pointer, not to return an error to the user, but
1243  // to prevent a crash
1244  if (stack_ptr == NULL) {
1245    return;
1246  }
1247
1248  stack_ptr->ffs_prev = search_ctx->ffsc_stack_ptr;
1249  search_ctx->ffsc_stack_ptr = stack_ptr;
1250}
1251
1252/// Pop a dir from the directory stack.
1253///
1254/// @return  NULL if stack is empty.
1255static ff_stack_T *ff_pop(ff_search_ctx_T *search_ctx)
1256{
1257  ff_stack_T *sptr = search_ctx->ffsc_stack_ptr;
1258  if (search_ctx->ffsc_stack_ptr != NULL) {
1259    search_ctx->ffsc_stack_ptr = search_ctx->ffsc_stack_ptr->ffs_prev;
1260  }
1261
1262  return sptr;
1263}
1264
1265/// free the given stack element
1266static void ff_free_stack_element(ff_stack_T *const stack_ptr)
1267{
1268  if (stack_ptr == NULL) {
1269    return;
1270  }
1271
1272  // API_CLEAR_STRING handles possible NULL pointers
1273  API_CLEAR_STRING(stack_ptr->ffs_fix_path);
1274  API_CLEAR_STRING(stack_ptr->ffs_wc_path);
1275
1276  if (stack_ptr->ffs_filearray != NULL) {
1277    FreeWild(stack_ptr->ffs_filearray_size, stack_ptr->ffs_filearray);
1278  }
1279
1280  xfree(stack_ptr);
1281}
1282
1283/// Clear the search context, but NOT the visited list.
1284static void ff_clear(ff_search_ctx_T *search_ctx)
1285{
1286  ff_stack_T *sptr;
1287
1288  // clear up stack
1289  while ((sptr = ff_pop(search_ctx)) != NULL) {
1290    ff_free_stack_element(sptr);
1291  }
1292
1293  if (search_ctx->ffsc_stopdirs_v != NULL) {
1294    int i = 0;
1295
1296    while (search_ctx->ffsc_stopdirs_v[i].data != NULL) {
1297      xfree(search_ctx->ffsc_stopdirs_v[i].data);
1298      i++;
1299    }
1300    XFREE_CLEAR(search_ctx->ffsc_stopdirs_v);
1301  }
1302
1303  // reset everything
1304  API_CLEAR_STRING(search_ctx->ffsc_file_to_search);
1305  API_CLEAR_STRING(search_ctx->ffsc_start_dir);
1306  API_CLEAR_STRING(search_ctx->ffsc_fix_path);
1307  API_CLEAR_STRING(search_ctx->ffsc_wc_path);
1308  search_ctx->ffsc_level = 0;
1309}
1310
1311/// check if the given path is in the stopdirs
1312///
1313/// @return  true if yes else false
1314static bool ff_path_in_stoplist(char *path, size_t path_len, String *stopdirs_v)
1315{
1316  // eat up trailing path separators, except the first
1317  while (path_len > 1 && vim_ispathsep(path[path_len - 1])) {
1318    path_len--;
1319  }
1320
1321  // if no path consider it as match
1322  if (path_len == 0) {
1323    return true;
1324  }
1325
1326  for (int i = 0; stopdirs_v[i].data != NULL; i++) {
1327    // match for parent directory. So '/home' also matches
1328    // '/home/rks'. Check for PATHSEP in stopdirs_v[i], else
1329    // '/home/r' would also match '/home/rks'
1330    if (path_cmp(p_fic, stopdirs_v[i].data, path, path_len) == 0
1331        && (stopdirs_v[i].size <= path_len
1332            || vim_ispathsep(stopdirs_v[i].data[path_len]))) {
1333      return true;
1334    }
1335  }
1336
1337  return false;
1338}
1339
1340/// Find the file name "ptr[len]" in the path.  Also finds directory names.
1341///
1342/// On the first call set the parameter 'first' to true to initialize
1343/// the search.  For repeating calls to false.
1344///
1345/// Repeating calls will return other files called 'ptr[len]' from the path.
1346///
1347/// Only on the first call 'ptr' and 'len' are used.  For repeating calls they
1348/// don't need valid values.
1349///
1350/// If nothing found on the first call the option FNAME_MESS will issue the
1351/// message:
1352///          'Can't find file "<file>" in path'
1353/// On repeating calls:
1354///          'No more file "<file>" found in path'
1355///
1356/// options:
1357/// FNAME_MESS       give error message when not found
1358///
1359/// Uses NameBuff[]!
1360///
1361/// @param ptr  file name
1362/// @param len  length of file name
1363/// @param first  use count'th matching file name
1364/// @param rel_fname  file name searching relative to
1365/// @param[in,out] file_to_find  modified copy of file name
1366/// @param[in,out] search_ctx  state of the search
1367///
1368/// @return  an allocated string for the file name.  NULL for error.
1369char *find_file_in_path(char *ptr, size_t len, int options, int first, char *rel_fname,
1370                        char **file_to_find, char **search_ctx)
1371{
1372  return find_file_in_path_option(ptr, len, options, first,
1373                                  (*curbuf->b_p_path == NUL
1374                                   ? p_path
1375                                   : curbuf->b_p_path),
1376                                  FINDFILE_BOTH, rel_fname, curbuf->b_p_sua,
1377                                  file_to_find, search_ctx);
1378}
1379
1380#ifdef EXITFREE
1381void free_findfile(void)
1382{
1383  API_CLEAR_STRING(ff_expand_buffer);
1384}
1385#endif
1386
1387/// Find the directory name "ptr[len]" in the path.
1388///
1389/// options:
1390/// FNAME_MESS       give error message when not found
1391/// FNAME_UNESC      unescape backslashes
1392///
1393/// Uses NameBuff[]!
1394///
1395/// @param ptr  file name
1396/// @param len  length of file name
1397/// @param rel_fname  file name searching relative to
1398/// @param[in,out] file_to_find  modified copy of file name
1399/// @param[in,out] search_ctx  state of the search
1400///
1401/// @return  an allocated string for the file name.  NULL for error.
1402char *find_directory_in_path(char *ptr, size_t len, int options, char *rel_fname,
1403                             char **file_to_find, char **search_ctx)
1404{
1405  return find_file_in_path_option(ptr, len, options, true, p_cdpath,
1406                                  FINDFILE_DIR, rel_fname, "",
1407                                  file_to_find, search_ctx);
1408}
1409
1410/// @param ptr  file name
1411/// @param len  length of file name
1412/// @param first  use count'th matching file name
1413/// @param path_option  p_path or p_cdpath
1414/// @param find_what  FINDFILE_FILE, _DIR or _BOTH
1415/// @param rel_fname  file name we are looking relative to.
1416/// @param suffixes  list of suffixes, 'suffixesadd' option
1417/// @param[in,out] file_to_find  modified copy of file name
1418/// @param[in,out] search_ctx_arg  state of the search
1419char *find_file_in_path_option(char *ptr, size_t len, int options, int first, char *path_option,
1420                               int find_what, char *rel_fname, char *suffixes, char **file_to_find,
1421                               char **search_ctx_arg)
1422{
1423  ff_search_ctx_T **search_ctx = (ff_search_ctx_T **)search_ctx_arg;
1424  static char *dir;
1425  static bool did_findfile_init = false;
1426  char *file_name = NULL;
1427  static size_t file_to_findlen = 0;
1428
1429  if (rel_fname != NULL && path_with_url(rel_fname)) {
1430    // Do not attempt to search "relative" to a URL. #6009
1431    rel_fname = NULL;
1432  }
1433
1434  if (first == true) {
1435    if (len == 0) {
1436      return NULL;
1437    }
1438
1439    // copy file name into NameBuff, expanding environment variables
1440    char save_char = ptr[len];
1441    ptr[len] = NUL;
1442    file_to_findlen = expand_env_esc(ptr, NameBuff, MAXPATHL, NULL, true, NULL);
1443    ptr[len] = save_char;
1444
1445    xfree(*file_to_find);
1446    *file_to_find = xmemdupz(NameBuff, file_to_findlen);
1447    if (options & FNAME_UNESC) {
1448      // Change all "\ " to " ".
1449      for (ptr = *file_to_find; *ptr != NUL; ptr++) {
1450        if (ptr[0] == '\\' && ptr[1] == ' ') {
1451          memmove(ptr, ptr + 1,
1452                  (size_t)((*file_to_find + file_to_findlen) - (ptr + 1)) + 1);
1453          file_to_findlen--;
1454        }
1455      }
1456    }
1457  }
1458
1459  bool rel_to_curdir = ((*file_to_find)[0] == '.'
1460                        && ((*file_to_find)[1] == NUL
1461                            || vim_ispathsep((*file_to_find)[1])
1462                            || ((*file_to_find)[1] == '.'
1463                                && ((*file_to_find)[2] == NUL
1464                                    || vim_ispathsep((*file_to_find)[2])))));
1465  if (vim_isAbsName(*file_to_find)
1466      // "..", "../path", "." and "./path": don't use the path_option
1467      || rel_to_curdir
1468#ifdef MSWIN
1469      // handle "\tmp" as absolute path
1470      || vim_ispathsep((*file_to_find)[0])
1471      // handle "c:name" as absolute path
1472      || ((*file_to_find)[0] != NUL && (*file_to_find)[1] == ':')
1473#endif
1474      ) {
1475    // Absolute path, no need to use "path_option".
1476    // If this is not a first call, return NULL.  We already returned a
1477    // filename on the first call.
1478    if (first == true) {
1479      if (path_with_url(*file_to_find)) {
1480        file_name = xmemdupz(*file_to_find, file_to_findlen);
1481        goto theend;
1482      }
1483
1484      size_t rel_fnamelen = rel_fname != NULL ? strlen(rel_fname) : 0;
1485
1486      // When FNAME_REL flag given first use the directory of the file.
1487      // Otherwise or when this fails use the current directory.
1488      for (int run = 1; run <= 2; run++) {
1489        size_t l = file_to_findlen;
1490        if (run == 1
1491            && rel_to_curdir
1492            && (options & FNAME_REL)
1493            && rel_fname != NULL
1494            && rel_fnamelen + l < MAXPATHL) {
1495          l = (size_t)vim_snprintf(NameBuff,
1496                                   MAXPATHL,
1497                                   "%.*s%s",
1498                                   (int)(path_tail(rel_fname) - rel_fname),
1499                                   rel_fname,
1500                                   *file_to_find);
1501          assert(l < MAXPATHL);
1502        } else {
1503          STRCPY(NameBuff, *file_to_find);
1504          run = 2;
1505        }
1506
1507        // When the file doesn't exist, try adding parts of 'suffixesadd'.
1508        char *suffix = suffixes;
1509        while (true) {
1510          if ((os_path_exists(NameBuff)
1511               && (find_what == FINDFILE_BOTH
1512                   || ((find_what == FINDFILE_DIR) == os_isdir(NameBuff))))) {
1513            file_name = xmemdupz(NameBuff, simplify_filename(NameBuff));
1514            goto theend;
1515          }
1516          if (*suffix == NUL) {
1517            break;
1518          }
1519          assert(MAXPATHL >= l);
1520          copy_option_part(&suffix, NameBuff + l, MAXPATHL - l, ",");
1521        }
1522      }
1523    }
1524  } else {
1525    // Loop over all paths in the 'path' or 'cdpath' option.
1526    // When "first" is set, first setup to the start of the option.
1527    // Otherwise continue to find the next match.
1528    if (first == true) {
1529      // vim_findfile_free_visited can handle a possible NULL pointer
1530      vim_findfile_free_visited(*search_ctx);
1531      dir = path_option;
1532      did_findfile_init = false;
1533    }
1534
1535    while (true) {
1536      if (did_findfile_init) {
1537        file_name = vim_findfile(*search_ctx);
1538        if (file_name != NULL) {
1539          break;
1540        }
1541
1542        did_findfile_init = false;
1543      } else {
1544        char *r_ptr;
1545
1546        if (dir == NULL || *dir == NUL) {
1547          // We searched all paths of the option, now we can free the search context.
1548          vim_findfile_cleanup(*search_ctx);
1549          *search_ctx = NULL;
1550          break;
1551        }
1552
1553        char *buf = xmalloc(MAXPATHL);
1554
1555        // copy next path
1556        buf[0] = NUL;
1557        copy_option_part(&dir, buf, MAXPATHL, " ,");
1558
1559        // get the stopdir string
1560        r_ptr = vim_findfile_stopdir(buf);
1561        *search_ctx = vim_findfile_init(buf, *file_to_find, file_to_findlen,
1562                                        r_ptr, 100, false, find_what,
1563                                        *search_ctx, false, rel_fname);
1564        if (*search_ctx != NULL) {
1565          did_findfile_init = true;
1566        }
1567        xfree(buf);
1568      }
1569    }
1570  }
1571  if (file_name == NULL && (options & FNAME_MESS)) {
1572    if (first == true) {
1573      if (find_what == FINDFILE_DIR) {
1574        semsg(_(e_cant_find_directory_str_in_cdpath), *file_to_find);
1575      } else {
1576        semsg(_(e_cant_find_file_str_in_path), *file_to_find);
1577      }
1578    } else {
1579      if (find_what == FINDFILE_DIR) {
1580        semsg(_(e_no_more_directory_str_found_in_cdpath), *file_to_find);
1581      } else {
1582        semsg(_(e_no_more_file_str_found_in_path), *file_to_find);
1583      }
1584    }
1585  }
1586
1587theend:
1588  return file_name;
1589}
1590
1591/// Get the file name at the cursor.
1592/// If Visual mode is active, use the selected text if it's in one line.
1593/// Returns the name in allocated memory, NULL for failure.
1594char *grab_file_name(int count, linenr_T *file_lnum)
1595{
1596  int options = FNAME_MESS | FNAME_EXP | FNAME_REL | FNAME_UNESC;
1597  char *fname;
1598  if (Visual.active) {
1599    size_t len;
1600    char *ptr;
1601    if (get_visual_text(NULL, &ptr, &len) == FAIL) {
1602      return NULL;
1603    }
1604    // Only recognize ":123" here
1605    if (file_lnum != NULL && ptr[len] == ':' && isdigit((uint8_t)ptr[len + 1])) {
1606      char *p = ptr + len + 1;
1607
1608      *file_lnum = getdigits_int32(&p, false, 0);
1609    }
1610    fname = find_file_name_in_path(ptr, len, options, count, curbuf->b_ffname);
1611  } else {
1612    fname = file_name_at_cursor(options | FNAME_HYP, count, file_lnum);
1613  }
1614  TO_SLASH(fname);
1615  return fname;
1616}
1617
1618/// Return the file name under or after the cursor.
1619///
1620/// The 'path' option is searched if the file name is not absolute.
1621/// The string returned has been alloc'ed and should be freed by the caller.
1622/// NULL is returned if the file name or file is not found.
1623///
1624/// options:
1625/// FNAME_MESS       give error messages
1626/// FNAME_EXP        expand to path
1627/// FNAME_HYP        check for hypertext link
1628/// FNAME_INCL       apply "includeexpr"
1629char *file_name_at_cursor(int options, int count, linenr_T *file_lnum)
1630{
1631  return file_name_in_line(get_cursor_line_ptr(),
1632                           curwin->w_cursor.col, options, count, curbuf->b_ffname,
1633                           file_lnum);
1634}
1635
1636/// @param rel_fname  file we are searching relative to
1637/// @param file_lnum  line number after the file name
1638///
1639/// @return  the name of the file under or after ptr[col].
1640///
1641/// Otherwise like file_name_at_cursor().
1642char *file_name_in_line(char *line, int col, int options, int count, char *rel_fname,
1643                        linenr_T *file_lnum)
1644{
1645  // search forward for what could be the start of a file name
1646  char *ptr = line + col;
1647  while (*ptr != NUL && !vim_isfilec((uint8_t)(*ptr))) {
1648    MB_PTR_ADV(ptr);
1649  }
1650  if (*ptr == NUL) {            // nothing found
1651    if (options & FNAME_MESS) {
1652      emsg(_("E446: No file name under cursor"));
1653    }
1654    return NULL;
1655  }
1656
1657  size_t len;
1658  bool in_type = true;
1659  bool is_url = false;
1660
1661  // Search backward for first char of the file name.
1662  // Go one char back to ":" before "//", or to the drive letter before ":\" (even if ":"
1663  // is not in 'isfname').
1664  while (ptr > line) {
1665    if ((len = (size_t)(utf_head_off(line, ptr - 1))) > 0) {
1666      ptr -= len + 1;
1667    } else if (vim_isfilec((uint8_t)ptr[-1]) || ((options & FNAME_HYP) && path_is_url(ptr - 1))) {
1668      ptr--;
1669    } else {
1670      break;
1671    }
1672  }
1673
1674  // Search forward for the last char of the file name.
1675  // Also allow ":/" when ':' is not in 'isfname'.
1676  // TODO(justinmk): Check for driveletter "x:/" at start, regardless of 'isfname'.
1677  len = path_has_drive_letter(ptr, strlen(ptr)) ? 2 : 0;
1678  while (vim_isfilec((uint8_t)ptr[len]) || (ptr[len] == '\\' && ptr[len + 1] == ' ')
1679         || ((options & FNAME_HYP) && path_is_url(ptr + len))
1680         || (is_url && vim_strchr(":?&=", (uint8_t)ptr[len]) != NULL)) {
1681    // After type:// we also include :, ?, & and = as valid characters, so that
1682    // http://google.com:8080?q=this&that=ok works.
1683    if ((ptr[len] >= 'A' && ptr[len] <= 'Z') || (ptr[len] >= 'a' && ptr[len] <= 'z')) {
1684      if (in_type && path_is_url(ptr + len + 1)) {
1685        is_url = true;
1686      }
1687    } else {
1688      in_type = false;
1689    }
1690
1691    if (ptr[len] == '\\' && ptr[len + 1] == ' ') {
1692      // Skip over the "\" in "\ ".
1693      len++;
1694    }
1695    len += (size_t)(utfc_ptr2len(ptr + len));
1696  }
1697
1698  // If there is trailing punctuation, remove it.
1699  // But don't remove "..", could be a directory name.
1700  if (len > 2 && vim_strchr(".,:;!", (uint8_t)ptr[len - 1]) != NULL
1701      && ptr[len - 2] != '.') {
1702    len--;
1703  }
1704
1705  if (file_lnum != NULL) {
1706    const char *match_text = " line ";  // english
1707    size_t match_textlen = 6;
1708
1709    // Get the number after the file name and a separator character.
1710    // Also accept " line 999" with and without the same translation as
1711    // used in last_set_msg().
1712    char *p = ptr + len;
1713    if (strncmp(p, match_text, match_textlen) == 0) {
1714      p += match_textlen;
1715    } else {
1716      // no match with english, try localized
1717      match_text = _(line_msg);
1718      match_textlen = strlen(match_text);
1719      if (strncmp(p, match_text, match_textlen) == 0) {
1720        p += match_textlen;
1721      } else {
1722        p = skipwhite(p);
1723      }
1724    }
1725    if (*p != NUL) {
1726      if (!isdigit((uint8_t)(*p))) {
1727        p++;                        // skip the separator
1728      }
1729      p = skipwhite(p);
1730      if (isdigit((uint8_t)(*p))) {
1731        *file_lnum = (linenr_T)getdigits_long(&p, false, 0);
1732      }
1733    }
1734  }
1735
1736  return find_file_name_in_path(ptr, len, options, count, rel_fname);
1737}
1738
1739static char *eval_includeexpr(const char *const ptr, const size_t len)
1740{
1741  const sctx_T save_sctx = current_sctx;
1742  set_vim_var_string(VV_FNAME, ptr, (ptrdiff_t)len);
1743  current_sctx = curbuf->b_p_script_ctx[kBufOptIncludeexpr];
1744
1745  const bool use_sandbox = was_set_insecurely(curwin, kOptIncludeexpr, OPT_LOCAL);
1746  typval_T tv;
1747  char *res = NULL;
1748  if (eval_expr_option_tv(&curbuf->b_p_inex, use_sandbox, &tv)) {
1749    res = xstrdup(tv_get_string(&tv));
1750    tv_clear(&tv);
1751  }
1752
1753  set_vim_var_string(VV_FNAME, NULL, 0);
1754  current_sctx = save_sctx;
1755  return res;
1756}
1757
1758/// Return the name of the file ptr[len] in 'path'.
1759/// Otherwise like file_name_at_cursor().
1760///
1761/// @param rel_fname  file we are searching relative to
1762char *find_file_name_in_path(char *ptr, size_t len, int options, long count, char *rel_fname)
1763{
1764  char *file_name;
1765  char *tofree = NULL;
1766
1767  if (len == 0) {
1768    return NULL;
1769  }
1770
1771  if ((options & FNAME_HYP) && len > 6 && strncmp(ptr, "file:/",
1772                                                  6) == 0 && !vim_ispathsep(ptr[6])) {
1773    size_t off = path_has_drive_letter(ptr + 6, len - 6) ? 6 : 5;
1774    ptr += off;
1775    len -= off;
1776  }
1777
1778  if ((options & FNAME_INCL) && curbuf->b_p_inex.type != kCallbackNone) {
1779    tofree = eval_includeexpr(ptr, len);
1780    if (tofree != NULL) {
1781      ptr = tofree;
1782      len = strlen(ptr);
1783    }
1784  }
1785
1786  if (options & FNAME_EXP) {
1787    char *file_to_find = NULL;
1788    char *search_ctx = NULL;
1789
1790    file_name = find_file_in_path(ptr, len, options & ~FNAME_MESS,
1791                                  true, rel_fname, &file_to_find, &search_ctx);
1792
1793    // If the file could not be found in a normal way, try applying
1794    // 'includeexpr' (unless done already).
1795    if (file_name == NULL
1796        && !(options & FNAME_INCL) && curbuf->b_p_inex.type != kCallbackNone) {
1797      tofree = eval_includeexpr(ptr, len);
1798      if (tofree != NULL) {
1799        ptr = tofree;
1800        len = strlen(ptr);
1801        file_name = find_file_in_path(ptr, len, options & ~FNAME_MESS,
1802                                      true, rel_fname, &file_to_find, &search_ctx);
1803      }
1804    }
1805    if (file_name == NULL && (options & FNAME_MESS)) {
1806      char c = ptr[len];
1807      ptr[len] = NUL;
1808      semsg(_("E447: Can't find file \"%s\" in path"), ptr);
1809      ptr[len] = c;
1810    }
1811
1812    // Repeat finding the file "count" times.  This matters when it
1813    // appears several times in the path.
1814    while (file_name != NULL && --count > 0) {
1815      xfree(file_name);
1816      file_name = find_file_in_path(ptr, len, options, false, rel_fname,
1817                                    &file_to_find, &search_ctx);
1818    }
1819
1820    xfree(file_to_find);
1821    vim_findfile_cleanup(search_ctx);
1822  } else {
1823    file_name = xstrnsave(ptr, len);
1824  }
1825
1826  xfree(tofree);
1827
1828  return file_name;
1829}
1830
1831void do_autocmd_dirchanged(char *new_dir, CdScope scope, CdCause cause, bool pre)
1832{
1833  static bool recursive = false;
1834
1835  event_T event = pre ? EVENT_DIRCHANGEDPRE : EVENT_DIRCHANGED;
1836
1837  if (recursive || !has_event(event)) {
1838    // No autocommand was defined or we changed
1839    // the directory from this autocommand.
1840    return;
1841  }
1842
1843  recursive = true;
1844
1845  save_v_event_T save_v_event;
1846  dict_T *dict = get_v_event(&save_v_event);
1847  char buf[8];
1848
1849  switch (scope) {
1850  case kCdScopeGlobal:
1851    snprintf(buf, sizeof(buf), "global");
1852    break;
1853  case kCdScopeTabpage:
1854    snprintf(buf, sizeof(buf), "tabpage");
1855    break;
1856  case kCdScopeBuffer:
1857    snprintf(buf, sizeof(buf), "buffer");
1858    break;
1859  case kCdScopeWindow:
1860    snprintf(buf, sizeof(buf), "window");
1861    break;
1862  case kCdScopeInvalid:
1863    // Should never happen.
1864    abort();
1865  }
1866
1867  if (pre) {
1868    tv_dict_add_str(dict, S_LEN("directory"), new_dir);
1869  } else {
1870    tv_dict_add_str(dict, S_LEN("cwd"), new_dir);
1871  }
1872  tv_dict_add_str(dict, S_LEN("scope"), buf);
1873  tv_dict_add_bool(dict, S_LEN("changed_window"), cause == kCdCauseWindow);
1874  tv_dict_set_keys_readonly(dict);
1875
1876  switch (cause) {
1877  case kCdCauseManual:
1878  case kCdCauseWindow:
1879  case kCdCauseBuffer:
1880    break;
1881  case kCdCauseAuto:
1882    snprintf(buf, sizeof(buf), "auto");
1883    break;
1884  case kCdCauseOther:
1885    // Should never happen.
1886    abort();
1887  }
1888
1889  apply_autocmds(event, buf, new_dir, false, curbuf);
1890
1891  restore_v_event(dict, &save_v_event);
1892
1893  recursive = false;
1894}
1895
1896/// Change to a file's directory.
1897/// Caller must call shorten_fnames()!
1898///
1899/// @return  OK or FAIL
1900int vim_chdirfile(char *fname, CdCause cause)
1901{
1902  char dir[MAXPATHL];
1903
1904  xstrlcpy(dir, fname, MAXPATHL);
1905  *path_tail_with_sep(dir) = NUL;
1906
1907  if (os_dirname(NameBuff, sizeof(NameBuff)) != OK) {
1908    NameBuff[0] = NUL;
1909  }
1910
1911  if (path_equal(dir, NameBuff, kPathCmpLiteral)) {
1912    // nothing to do
1913    return OK;
1914  }
1915
1916  if (cause != kCdCauseOther) {
1917    do_autocmd_dirchanged(dir, kCdScopeWindow, cause, true);
1918  }
1919
1920  if (os_chdir(dir) != 0) {
1921    return FAIL;
1922  }
1923
1924  if (cause != kCdCauseOther) {
1925    do_autocmd_dirchanged(dir, kCdScopeWindow, cause, false);
1926  }
1927
1928  return OK;
1929}
1930
1931/// Change directory to "new_dir". Search 'cdpath' for relative directory names.
1932int vim_chdir(char *new_dir)
1933{
1934  char *file_to_find = NULL;
1935  char *search_ctx = NULL;
1936  char *dir_name = find_directory_in_path(new_dir, strlen(new_dir), FNAME_MESS,
1937                                          curbuf->b_ffname, &file_to_find, &search_ctx);
1938  xfree(file_to_find);
1939  vim_findfile_cleanup(search_ctx);
1940  if (dir_name == NULL) {
1941    return -1;
1942  }
1943
1944  int r = os_chdir(dir_name);
1945  xfree(dir_name);
1946  return r;
1947}