robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
95.2 KiB3094 linesraw
1/// @file runtime.c
2///
3/// Management of runtime files (including packages)
4
5#include <assert.h>
6#include <errno.h>
7#include <fcntl.h>
8#include <inttypes.h>
9#include <stdbool.h>
10#include <stddef.h>
11#include <stdio.h>
12#include <string.h>
13#include <uv.h>
14
15#include "klib/kvec.h"
16#include "nvim/api/private/defs.h"
17#include "nvim/api/private/helpers.h"
18#include "nvim/ascii_defs.h"
19#include "nvim/autocmd.h"
20#include "nvim/autocmd_defs.h"
21#include "nvim/buffer_defs.h"
22#include "nvim/charset.h"
23#include "nvim/cmdexpand.h"
24#include "nvim/debugger.h"
25#include "nvim/errors.h"
26#include "nvim/eval.h"
27#include "nvim/eval/typval.h"
28#include "nvim/eval/userfunc.h"
29#include "nvim/eval/vars.h"
30#include "nvim/ex_cmds_defs.h"
31#include "nvim/ex_docmd.h"
32#include "nvim/ex_eval.h"
33#include "nvim/ex_eval_defs.h"
34#include "nvim/garray.h"
35#include "nvim/gettext_defs.h"
36#include "nvim/globals.h"
37#include "nvim/hashtab.h"
38#include "nvim/hashtab_defs.h"
39#include "nvim/input.h"
40#include "nvim/lua/executor.h"
41#include "nvim/macros_defs.h"
42#include "nvim/map_defs.h"
43#include "nvim/mbyte.h"
44#include "nvim/mbyte_defs.h"
45#include "nvim/memline.h"
46#include "nvim/memory.h"
47#include "nvim/memory_defs.h"
48#include "nvim/message.h"
49#include "nvim/option.h"
50#include "nvim/option_defs.h"
51#include "nvim/option_vars.h"
52#include "nvim/os/fs.h"
53#include "nvim/os/input.h"
54#include "nvim/os/os.h"
55#include "nvim/os/os_defs.h"
56#include "nvim/os/stdpaths_defs.h"
57#include "nvim/path.h"
58#include "nvim/pos_defs.h"
59#include "nvim/profile.h"
60#include "nvim/regexp.h"
61#include "nvim/regexp_defs.h"
62#include "nvim/runtime.h"
63#include "nvim/strings.h"
64#include "nvim/types_defs.h"
65#include "nvim/usercmd.h"
66#include "nvim/vim_defs.h"
67#ifdef USE_CRNL
68# include "nvim/highlight.h"
69#endif
70
71/// Structure used to store info for each sourced file.
72/// It is shared between do_source() and getsourceline().
73/// This is required, because it needs to be handed to do_cmdline() and
74/// sourcing can be done recursively.
75typedef struct {
76  FILE *fp;                     ///< opened file for sourcing
77  char *nextline;               ///< if not NULL: line that was read ahead
78  linenr_T sourcing_lnum;       ///< line number of the source file
79  bool finished;                ///< ":finish" used
80  bool source_from_buf_or_str;  ///< true if sourcing from a buffer or string
81  int buf_lnum;                 ///< line number in the buffer or string
82  garray_T buflines;            ///< lines in the buffer or string
83#ifdef USE_CRNL
84  int fileformat;               ///< EOL_UNKNOWN, EOL_UNIX or EOL_DOS
85  bool error;                   ///< true if LF found after CR-LF
86#endif
87  linenr_T breakpoint;          ///< next line with breakpoint or zero
88  char *fname;                  ///< name of sourced file
89  int dbg_tick;                 ///< debug_tick when breakpoint was set
90  int level;                    ///< top nesting level of sourced file
91  vimconv_T conv;               ///< type of conversion
92} source_cookie_T;
93
94typedef struct {
95  char *path;
96  bool after;
97  bool pack_inserted;
98  TriState has_lua;
99  size_t pos_in_rtp;
100} SearchPathItem;
101
102typedef kvec_t(SearchPathItem) RuntimeSearchPath;
103typedef kvec_t(char *) CharVec;
104
105#include "runtime.c.generated.h"
106
107garray_T exestack = { 0, 0, sizeof(estack_T), 50, NULL };
108garray_T script_items = { 0, 0, sizeof(scriptitem_T *), 20, NULL };
109
110/// The names of packages that once were loaded are remembered.
111static garray_T ga_loaded = { 0, 0, sizeof(char *), 4, NULL };
112
113/// last used sequence number for sourcing scripts (current_sctx.sc_seq)
114static int last_current_SID_seq = 0;
115
116/// Initialize the execution stack.
117void estack_init(void)
118{
119  ga_grow(&exestack, 10);
120  estack_T *entry = ((estack_T *)exestack.ga_data) + exestack.ga_len;
121  entry->es_type = ETYPE_TOP;
122  entry->es_name = NULL;
123  entry->es_lnum = 0;
124  entry->es_info.ufunc = NULL;
125  exestack.ga_len++;
126}
127
128/// Add an item to the execution stack.
129/// @return  the new entry
130estack_T *estack_push(etype_T type, char *name, linenr_T lnum)
131{
132  ga_grow(&exestack, 1);
133  estack_T *entry = ((estack_T *)exestack.ga_data) + exestack.ga_len;
134  entry->es_type = type;
135  entry->es_name = name;
136  entry->es_lnum = lnum;
137  entry->es_info.ufunc = NULL;
138  exestack.ga_len++;
139  return entry;
140}
141
142/// Add a user function to the execution stack.
143void estack_push_ufunc(ufunc_T *ufunc, linenr_T lnum)
144{
145  estack_T *entry = estack_push(ETYPE_UFUNC,
146                                ufunc->uf_name_exp != NULL ? ufunc->uf_name_exp : ufunc->uf_name,
147                                lnum);
148  if (entry != NULL) {
149    entry->es_info.ufunc = ufunc;
150  }
151}
152
153/// Take an item off of the execution stack.
154void estack_pop(void)
155{
156  if (exestack.ga_len > 1) {
157    exestack.ga_len--;
158  }
159}
160
161/// Get the current value for <sfile> in allocated memory.
162/// @param which  ESTACK_SFILE for <sfile>, ESTACK_STACK for <stack> or
163///               ESTACK_SCRIPT for <script>.
164char *estack_sfile(estack_arg_T which)
165{
166  const estack_T *entry = ((estack_T *)exestack.ga_data) + exestack.ga_len - 1;
167  if (which == ESTACK_SFILE && entry->es_type != ETYPE_UFUNC) {
168    return entry->es_name != NULL ? xstrdup(entry->es_name) : NULL;
169  }
170
171  // If evaluated in a function or autocommand, return the path of the script
172  // where it is defined, at script level the current script path is returned
173  // instead.
174  if (which == ESTACK_SCRIPT) {
175    // Walk the stack backwards, starting from the current frame.
176    for (int idx = exestack.ga_len - 1; idx >= 0; idx--, entry--) {
177      if (entry->es_type == ETYPE_UFUNC || entry->es_type == ETYPE_AUCMD) {
178        const sctx_T *const def_ctx = (entry->es_type == ETYPE_UFUNC
179                                       ? &entry->es_info.ufunc->uf_script_ctx
180                                       : &entry->es_info.aucmd->script_ctx);
181        return def_ctx->sc_sid > 0
182               ? xstrdup((SCRIPT_ITEM(def_ctx->sc_sid)->sn_name))
183               : NULL;
184      } else if (entry->es_type == ETYPE_SCRIPT) {
185        return xstrdup(entry->es_name);
186      }
187    }
188    return NULL;
189  }
190
191  // Give information about each stack entry up to the root.
192  // For a function we compose the call stack, as it was done in the past:
193  //   "function One[123]..Two[456]..Three"
194  garray_T ga;
195  ga_init(&ga, sizeof(char), 100);
196  etype_T last_type = ETYPE_SCRIPT;
197  for (int idx = 0; idx < exestack.ga_len; idx++) {
198    entry = ((estack_T *)exestack.ga_data) + idx;
199    if (entry->es_name != NULL) {
200      String type_name = STATIC_CSTR_AS_STRING("");
201      String es_name = cstr_as_string(entry->es_name);
202      if (entry->es_type != last_type) {
203        switch (entry->es_type) {
204        case ETYPE_SCRIPT:
205          type_name = STATIC_CSTR_AS_STRING("script "); break;
206        case ETYPE_UFUNC:
207          type_name = STATIC_CSTR_AS_STRING("function "); break;
208        default:
209          break;
210        }
211        last_type = entry->es_type;
212      }
213      linenr_T lnum = idx == exestack.ga_len - 1
214                      ? which == ESTACK_STACK ? SOURCING_LNUM : 0
215                      : entry->es_lnum;
216
217      size_t len = es_name.size + type_name.size + 26;
218      ga_grow(&ga, (int)len);
219      ga_concat_len(&ga, type_name.data, type_name.size);
220      ga_concat_len(&ga, es_name.data, es_name.size);
221      // For the bottom entry of <sfile>: do not add the line number, it is used in
222      // <slnum>.  Also leave it out when the number is not set.
223      if (lnum != 0) {
224        ga.ga_len += (int)vim_snprintf_safelen((char *)ga.ga_data + ga.ga_len,
225                                               (size_t)(ga.ga_maxlen - ga.ga_len),
226                                               "[%" PRIdLINENR "]", lnum);
227      }
228      if (idx != exestack.ga_len - 1) {
229        GA_CONCAT_LITERAL(&ga, "..");
230      }
231    }
232  }
233
234  // Only NUL-terminate when not returning NULL.
235  if (ga.ga_data != NULL) {
236    ga_append(&ga, NUL);
237  }
238  return (char *)ga.ga_data;
239}
240
241static void stacktrace_push_item(list_T *const l, ufunc_T *const fp, const char *const event,
242                                 const linenr_T lnum, char *const filepath)
243{
244  dict_T *const d = tv_dict_alloc_lock(VAR_FIXED);
245  typval_T tv = {
246    .v_type = VAR_DICT,
247    .v_lock = VAR_LOCKED,
248    .vval.v_dict = d,
249  };
250
251  if (fp != NULL) {
252    tv_dict_add_func(d, S_LEN("funcref"), fp);
253  }
254  if (event != NULL) {
255    tv_dict_add_str(d, S_LEN("event"), event);
256  }
257  tv_dict_add_nr(d, S_LEN("lnum"), lnum);
258  tv_dict_add_str(d, S_LEN("filepath"), filepath);
259
260  tv_list_append_tv(l, &tv);
261}
262
263/// Create the stacktrace from exestack.
264list_T *stacktrace_create(void)
265{
266  list_T *const l = tv_list_alloc(exestack.ga_len);
267
268  for (int i = 0; i < exestack.ga_len; i++) {
269    estack_T *const entry = &((estack_T *)exestack.ga_data)[i];
270    linenr_T lnum = entry->es_lnum;
271
272    if (entry->es_type == ETYPE_SCRIPT) {
273      stacktrace_push_item(l, NULL, NULL, lnum, entry->es_name);
274    } else if (entry->es_type == ETYPE_UFUNC) {
275      ufunc_T *const fp = entry->es_info.ufunc;
276      const sctx_T sctx = fp->uf_script_ctx;
277      char *filepath = sctx.sc_sid > 0 ? get_scriptname(sctx, NULL) : "";
278      lnum += sctx.sc_lnum;
279      stacktrace_push_item(l, fp, NULL, lnum, filepath);
280    } else if (entry->es_type == ETYPE_AUCMD) {
281      const sctx_T sctx = entry->es_info.aucmd->script_ctx;
282      char *filepath = sctx.sc_sid > 0 ? get_scriptname(sctx, NULL) : "";
283      lnum += sctx.sc_lnum;
284      stacktrace_push_item(l, NULL, entry->es_name, lnum, filepath);
285    }
286  }
287  return l;
288}
289
290/// getstacktrace() function
291void f_getstacktrace(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
292{
293  tv_list_set_ret(rettv, stacktrace_create());
294}
295
296static bool runtime_search_path_valid = false;
297static bool runtime_search_path_valid_thread = false;
298static int *runtime_search_path_ref = NULL;
299static RuntimeSearchPath runtime_search_path;
300static RuntimeSearchPath runtime_search_path_thread;
301static uv_mutex_t runtime_search_path_mutex;
302
303void runtime_init(void)
304{
305  uv_mutex_init(&runtime_search_path_mutex);
306}
307
308/// Get DIP_ flags from the [where] argument of a :runtime command.
309/// "*argp" is advanced to after the [where] argument.
310static int get_runtime_cmd_flags(char **argp, size_t where_len)
311{
312  char *arg = *argp;
313
314  if (where_len == 0) {
315    return 0;
316  }
317
318  if (strncmp(arg, "START", where_len) == 0) {
319    *argp = skipwhite(arg + where_len);
320    return DIP_START + DIP_NORTP;
321  }
322  if (strncmp(arg, "OPT", where_len) == 0) {
323    *argp = skipwhite(arg + where_len);
324    return DIP_OPT + DIP_NORTP;
325  }
326  if (strncmp(arg, "PACK", where_len) == 0) {
327    *argp = skipwhite(arg + where_len);
328    return DIP_START + DIP_OPT + DIP_NORTP;
329  }
330  if (strncmp(arg, "ALL", where_len) == 0) {
331    *argp = skipwhite(arg + where_len);
332    return DIP_START + DIP_OPT;
333  }
334
335  return 0;
336}
337
338/// ":runtime [where] {name}"
339void ex_runtime(exarg_T *eap)
340{
341  char *arg = eap->arg;
342  int flags = eap->forceit ? DIP_ALL : 0;
343  char *p = skiptowhite(arg);
344  flags += get_runtime_cmd_flags(&arg, (size_t)(p - arg));
345  assert(arg != NULL);  // suppress clang false positive
346  source_runtime(arg, flags);
347}
348
349static int runtime_expand_flags;
350
351/// Set the completion context for the :runtime command.
352void set_context_in_runtime_cmd(expand_T *xp, const char *arg)
353{
354  char *p = skiptowhite(arg);
355  runtime_expand_flags
356    = *p != NUL ? get_runtime_cmd_flags((char **)&arg, (size_t)(p - arg)) : 0;
357  // Skip to the last argument.
358  while (*(p = skiptowhite_esc(arg)) != NUL) {
359    if (runtime_expand_flags == 0) {
360      // When there are multiple arguments and [where] is not specified,
361      // use an unrelated non-zero flag to avoid expanding [where].
362      runtime_expand_flags = DIP_ALL;
363    }
364    arg = skipwhite(p);
365  }
366  xp->xp_context = EXPAND_RUNTIME;
367  xp->xp_pattern = (char *)arg;
368}
369
370/// Source all .vim and .lua files in "fnames" with .vim files being sourced first.
371static bool source_callback_vim_lua(int num_fnames, char **fnames, bool all, void *cookie)
372{
373  bool did_one = false;
374
375  for (int i = 0; i < num_fnames; i++) {
376    if (path_with_extension(fnames[i], "vim")) {
377      do_source(fnames[i], false, DOSO_NONE, cookie);
378      did_one = true;
379      if (!all) {
380        return true;
381      }
382    }
383  }
384
385  for (int i = 0; i < num_fnames; i++) {
386    if (path_with_extension(fnames[i], "lua")) {
387      do_source(fnames[i], false, DOSO_NONE, cookie);
388      did_one = true;
389      if (!all) {
390        return true;
391      }
392    }
393  }
394
395  return did_one;
396}
397
398/// Source all files in "fnames" with .vim files sourced first, .lua files
399/// sourced second, and any remaining files sourced last.
400static bool source_callback(int num_fnames, char **fnames, bool all, void *cookie)
401{
402  bool did_one = source_callback_vim_lua(num_fnames, fnames, all, cookie);
403
404  if (!all && did_one) {
405    return true;
406  }
407
408  for (int i = 0; i < num_fnames; i++) {
409    if (!path_with_extension(fnames[i], "vim")
410        && !path_with_extension(fnames[i], "lua")) {
411      do_source(fnames[i], false, DOSO_NONE, cookie);
412      did_one = true;
413      if (!all) {
414        return true;
415      }
416    }
417  }
418
419  return did_one;
420}
421
422/// Find the patterns in "name" in all directories in "path" and invoke
423/// "callback(fname, cookie)".
424/// "prefix" is prepended to each pattern in "name".
425/// When "flags" has DIP_ALL: source all files, otherwise only the first one.
426/// When "flags" has DIP_DIR: find directories instead of files.
427/// When "flags" has DIP_ERR: give an error message if there is no match.
428///
429/// Return FAIL when no file could be sourced, OK otherwise.
430int do_in_path(const char *path, const char *prefix, char *name, int flags,
431               DoInRuntimepathCB callback, void *cookie)
432  FUNC_ATTR_NONNULL_ARG(1, 2)
433{
434  bool did_one = false;
435
436  // Make a copy of 'runtimepath'.  Invoking the callback may change the
437  // value.
438  char *rtp_copy = xstrdup(path);
439  char *buf = xmallocz(MAXPATHL);
440  {
441    char *tail;
442    if (p_verbose > 10 && name != NULL) {
443      verbose_enter();
444      if (*prefix != NUL) {
445        smsg(0, _("Searching for \"%s\" under \"%s\" in \"%s\""), name, prefix, path);
446      } else {
447        smsg(0, _("Searching for \"%s\" in \"%s\""), name, path);
448      }
449      verbose_leave();
450    }
451
452    bool do_all = (flags & DIP_ALL) != 0;
453
454    // Loop over all entries in 'runtimepath'.
455    char *rtp = rtp_copy;
456    while (*rtp != NUL && (do_all || !did_one)) {
457      // Copy the path from 'runtimepath' to buf[].
458      size_t buflen = copy_option_part(&rtp, buf, MAXPATHL, ",");
459
460      // Skip after or non-after directories.
461      if (flags & (DIP_NOAFTER | DIP_AFTER)) {
462        bool is_after = path_is_after(buf, buflen);
463
464        if ((is_after && (flags & DIP_NOAFTER))
465            || (!is_after && (flags & DIP_AFTER))) {
466          continue;
467        }
468      }
469
470      if (name == NULL) {
471        (*callback)(1, &buf, do_all, cookie);
472        did_one = true;
473      } else if (buflen + 2 + strlen(prefix) + strlen(name) < MAXPATHL) {
474        add_pathsep(buf);
475        strcat(buf, prefix);
476        tail = buf + strlen(buf);
477
478        // Loop over all patterns in "name"
479        char *np = name;
480        while (*np != NUL && (do_all || !did_one)) {
481          // Append the pattern from "name" to buf[].
482          assert(MAXPATHL >= (tail - buf));
483          copy_option_part(&np, tail, (size_t)(MAXPATHL - (tail - buf)), "\t ");
484
485          if (p_verbose > 10) {
486            verbose_enter();
487            smsg(0, _("Searching for \"%s\""), buf);
488            verbose_leave();
489          }
490
491          int ew_flags = ((flags & DIP_DIR) ? EW_DIR : EW_FILE)
492                         | ((flags & DIP_DIRFILE) ? (EW_DIR|EW_FILE) : 0);
493
494          did_one |= gen_expand_wildcards_and_cb(1, &buf, ew_flags, do_all, callback,
495                                                 cookie) == OK;
496        }
497      }
498    }
499  }
500  xfree(buf);
501  xfree(rtp_copy);
502  if (!did_one && name != NULL) {
503    char *basepath = path == p_rtp ? "runtimepath" : "packpath";
504
505    if (flags & DIP_ERR) {
506      semsg(_(e_dirnotf), basepath, name);
507    } else if (p_verbose > 1) {
508      verbose_enter();
509      smsg(0, _("not found in '%s': \"%s\""), basepath, name);
510      verbose_leave();
511    }
512  }
513
514  return did_one ? OK : FAIL;
515}
516
517static RuntimeSearchPath runtime_search_path_get_cached(int *ref)
518  FUNC_ATTR_NONNULL_ALL
519{
520  runtime_search_path_validate();
521
522  *ref = 0;
523  if (runtime_search_path_ref == NULL) {
524    // cached path was unreferenced. keep a ref to
525    // prevent runtime_search_path() to freeing it too early
526    (*ref)++;
527    runtime_search_path_ref = ref;
528  }
529  return runtime_search_path;
530}
531
532static RuntimeSearchPath copy_runtime_search_path(const RuntimeSearchPath src)
533{
534  RuntimeSearchPath dst = KV_INITIAL_VALUE;
535  for (size_t j = 0; j < kv_size(src); j++) {
536    SearchPathItem item = kv_A(src, j);
537    kv_push(dst, ((SearchPathItem){ xstrdup(item.path), item.after, item.pack_inserted,
538                                    item.has_lua, item.pos_in_rtp }));
539  }
540
541  return dst;
542}
543
544static void runtime_search_path_unref(RuntimeSearchPath path, const int *ref)
545  FUNC_ATTR_NONNULL_ALL
546{
547  if (*ref) {
548    if (runtime_search_path_ref == ref) {
549      runtime_search_path_ref = NULL;
550    } else {
551      runtime_search_path_free(path);
552    }
553  }
554}
555
556/// Find the file "name" in all directories in "path" and invoke
557/// "callback(fname, cookie)".
558/// "name" can contain wildcards.
559/// When "flags" has DIP_ALL: source all files, otherwise only the first one.
560/// When "flags" has DIP_DIR: find directories instead of files.
561/// When "flags" has DIP_ERR: give an error message if there is no match.
562///
563/// return FAIL when no file could be sourced, OK otherwise.
564static int do_in_cached_path(char *name, int flags, DoInRuntimepathCB callback, void *cookie)
565{
566  bool did_one = false;
567
568  char buf[MAXPATHL];
569
570  if (p_verbose > 10 && name != NULL) {
571    verbose_enter();
572    smsg(0, _("Searching for \"%s\" in runtime path"), name);
573    verbose_leave();
574  }
575
576  int ref;
577  RuntimeSearchPath path = runtime_search_path_get_cached(&ref);
578
579  bool do_all = (flags & DIP_ALL) != 0;
580
581  // Loop over all entries in cached path
582  for (size_t j = 0; j < kv_size(path); j++) {
583    SearchPathItem item = kv_A(path, j);
584    size_t buflen = strlen(item.path);
585
586    // Skip after or non-after directories.
587    if (flags & (DIP_NOAFTER | DIP_AFTER)) {
588      if ((item.after && (flags & DIP_NOAFTER))
589          || (!item.after && (flags & DIP_AFTER))) {
590        continue;
591      }
592    }
593
594    if (name == NULL) {
595      (*callback)(1, &item.path, do_all, cookie);
596    } else if (buflen + strlen(name) + 2 < MAXPATHL) {
597      STRCPY(buf, item.path);
598      add_pathsep(buf);
599      char *tail = buf + strlen(buf);
600
601      // Loop over all patterns in "name"
602      char *np = name;
603
604      while (*np != NUL && (do_all || !did_one)) {
605        // Append the pattern from "name" to buf[].
606        assert(MAXPATHL >= (tail - buf));
607        copy_option_part(&np, tail, (size_t)(MAXPATHL - (tail - buf)), "\t ");
608
609        if (p_verbose > 10) {
610          verbose_enter();
611          smsg(0, _("Searching for \"%s\""), buf);
612          verbose_leave();
613        }
614
615        int ew_flags = ((flags & DIP_DIR) ? EW_DIR : EW_FILE)
616                       | ((flags & DIP_DIRFILE) ? (EW_DIR|EW_FILE) : 0)
617                       | EW_NOBREAK;
618
619        // Expand wildcards, invoke the callback for each match.
620        char *(pat[]) = { buf };
621        did_one |= gen_expand_wildcards_and_cb(1, pat, ew_flags, do_all, callback, cookie) == OK;
622      }
623    }
624  }
625
626  if (!did_one && name != NULL) {
627    if (flags & DIP_ERR) {
628      semsg(_(e_dirnotf), "runtime path", name);
629    } else if (p_verbose > 1) {
630      verbose_enter();
631      smsg(0, _("not found in runtime path: \"%s\""), name);
632      verbose_leave();
633    }
634  }
635
636  runtime_search_path_unref(path, &ref);
637
638  return did_one ? OK : FAIL;
639}
640
641Array runtime_inspect(Arena *arena)
642{
643  RuntimeSearchPath path = runtime_search_path;
644  Array rv = arena_array(arena, kv_size(path));
645
646  for (size_t i = 0; i < kv_size(path); i++) {
647    SearchPathItem *item = &kv_A(path, i);
648    Dict entry = arena_dict(arena, 5);
649    PUT_C(entry, "path", CSTR_AS_OBJ(item->path));
650    if (item->after) {
651      PUT_C(entry, "after", BOOLEAN_OBJ(true));
652    }
653    if (item->pack_inserted) {
654      PUT_C(entry, "pack_inserted", BOOLEAN_OBJ(true));
655    }
656    if (item->has_lua != kNone) {
657      PUT_C(entry, "has_lua",  BOOLEAN_OBJ(item->has_lua == kTrue));
658    }
659    PUT_C(entry, "pos_in_rtp", INTEGER_OBJ((Integer)item->pos_in_rtp));
660
661    ADD_C(rv, DICT_OBJ(entry));
662  }
663  return rv;
664}
665
666ArrayOf(String) runtime_get_named(bool lua, Array pat, bool all, Arena *arena)
667{
668  int ref;
669  RuntimeSearchPath path = runtime_search_path_get_cached(&ref);
670  static char buf[MAXPATHL];
671
672  ArrayOf(String) rv = runtime_get_named_common(lua, pat, all, path, buf, sizeof buf, arena);
673
674  runtime_search_path_unref(path, &ref);
675  return rv;
676}
677
678ArrayOf(String) runtime_get_named_thread(bool lua, Array pat, bool all)
679{
680  // TODO(bfredl): avoid contention between multiple worker threads?
681  uv_mutex_lock(&runtime_search_path_mutex);
682  static char buf[MAXPATHL];
683  ArrayOf(String) rv = runtime_get_named_common(lua, pat, all, runtime_search_path_thread,
684                                                buf, sizeof buf, NULL);
685  uv_mutex_unlock(&runtime_search_path_mutex);
686  return rv;
687}
688
689static ArrayOf(String) runtime_get_named_common(bool lua, Array pat, bool all,
690                                                RuntimeSearchPath path, char *buf, size_t buf_len,
691                                                Arena *arena)
692{
693  ArrayOf(String) rv = arena_array(arena, kv_size(path) * pat.size);
694  for (size_t i = 0; i < kv_size(path); i++) {
695    SearchPathItem *item = &kv_A(path, i);
696    if (lua) {
697      if (item->has_lua == kNone) {
698        size_t size = (size_t)snprintf(buf, buf_len, "%s/lua/", item->path);
699        item->has_lua = (size < buf_len && os_isdir(buf));
700      }
701      if (item->has_lua == kFalse) {
702        continue;
703      }
704    }
705
706    for (size_t j = 0; j < pat.size; j++) {
707      Object pat_item = pat.items[j];
708      if (pat_item.type == kObjectTypeString) {
709        size_t size = (size_t)snprintf(buf, buf_len, "%s/%s",
710                                       item->path, pat_item.data.string.data);
711        if (size < buf_len) {
712          if (os_file_is_readable(buf)) {
713            TO_SLASH(buf);
714            ADD_C(rv, CSTR_TO_ARENA_OBJ(arena, buf));
715            if (!all) {
716              goto done;
717            }
718          }
719        }
720      }
721    }
722  }
723done:
724  return rv;
725}
726
727/// Find "name" in "path".  When found, invoke the callback function for
728/// it: callback(fname, "cookie")
729/// When "flags" has DIP_ALL repeat for all matches, otherwise only the first
730/// one is used.
731/// Returns OK when at least one match found, FAIL otherwise.
732/// If "name" is NULL calls callback for each entry in "path". Cookie is
733/// passed by reference in this case, setting it to NULL indicates that callback
734/// has done its job.
735int do_in_path_and_pp(char *path, char *name, int flags, DoInRuntimepathCB callback, void *cookie)
736{
737  int done = FAIL;
738
739  if ((flags & DIP_NORTP) == 0) {
740    done |= do_in_path(path, "", (name && !*name) ? NULL : name, flags, callback,
741                       cookie);
742  }
743
744  if ((done == FAIL || (flags & DIP_ALL)) && (flags & DIP_START)) {
745    const char *prefix
746      = (flags & DIP_AFTER) ? "pack/*/start/*/after/" : "pack/*/start/*/";  // NOLINT
747    done |= do_in_path(p_pp, prefix, name, flags & ~DIP_AFTER, callback, cookie);
748
749    if (done == FAIL || (flags & DIP_ALL)) {
750      prefix = (flags & DIP_AFTER) ? "start/*/after/" : "start/*/";  // NOLINT
751      done |= do_in_path(p_pp, prefix, name, flags & ~DIP_AFTER, callback, cookie);
752    }
753  }
754
755  if ((done == FAIL || (flags & DIP_ALL)) && (flags & DIP_OPT)) {
756    done |= do_in_path(p_pp, "pack/*/opt/*/", name, flags, callback, cookie);  // NOLINT
757
758    if (done == FAIL || (flags & DIP_ALL)) {
759      done |= do_in_path(p_pp, "opt/*/", name, flags, callback, cookie);  // NOLINT
760    }
761  }
762
763  return done;
764}
765
766static bool push_path(RuntimeSearchPath *search_path, Set(String) *rtp_used, char *entry,
767                      bool after, size_t pos_in_rtp)
768{
769  String *key_alloc;
770  if (set_put_ref(String, rtp_used, cstr_as_string(entry), &key_alloc)) {
771    *key_alloc = cstr_to_string(entry);
772    kv_push(*search_path, ((SearchPathItem){ key_alloc->data, after, false, kNone, pos_in_rtp }));
773    return true;
774  }
775  return false;
776}
777
778static void expand_rtp_entry(RuntimeSearchPath *search_path, Set(String) *rtp_used, char *entry,
779                             bool after, size_t pos_in_rtp)
780{
781  if (set_has(String, rtp_used, cstr_as_string(entry))) {
782    return;
783  }
784
785  if (!*entry) {
786    push_path(search_path, rtp_used, entry, after, pos_in_rtp);
787  }
788
789  int num_files;
790  char **files;
791  char *(pat[]) = { entry };
792  if (gen_expand_wildcards(1, pat, &num_files, &files, EW_DIR | EW_NOBREAK) == OK) {
793    for (int i = 0; i < num_files; i++) {
794      // reuses position but it is ok, we need to be monotonic but not strictly
795      push_path(search_path, rtp_used, files[i], after, pos_in_rtp);
796    }
797    FreeWild(num_files, files);
798  }
799}
800
801static void expand_pack_entry(RuntimeSearchPath *search_path, Set(String) *rtp_used,
802                              CharVec *after_path, char *pack_entry, size_t pack_entry_len,
803                              size_t pos_in_rtp)
804{
805  static char buf[MAXPATHL];
806  char *(start_pat[]) = { "/pack/*/start/*", "/start/*" };  // NOLINT
807  for (int i = 0; i < 2; i++) {
808    if (pack_entry_len + strlen(start_pat[i]) + 1 > sizeof buf) {
809      continue;
810    }
811    xstrlcpy(buf, pack_entry, sizeof buf);
812    xstrlcpy(buf + pack_entry_len, start_pat[i], sizeof buf - pack_entry_len);
813    expand_rtp_entry(search_path, rtp_used, buf, false, pos_in_rtp);
814    size_t after_size = strlen(buf) + 7;
815    char *after = xmallocz(after_size);
816    xstrlcpy(after, buf, after_size);
817    xstrlcat(after, "/after", after_size);
818    kv_push(*after_path, after);
819  }
820}
821
822static bool path_is_after(char *buf, size_t buflen)
823{
824  // NOTE: we only consider dirs exactly matching "after" to be an AFTER dir.
825  // vim8 considers all dirs like "foo/bar_after", "Xafter" etc, as an
826  // "after" dir in SOME codepaths not in ALL codepaths.
827  return buflen >= 5
828         && (!(buflen >= 6) || vim_ispathsep(buf[buflen - 6]))
829         && strcmp(buf + buflen - 5, "after") == 0;
830}
831
832static RuntimeSearchPath runtime_search_path_build(void)
833{
834  kvec_t(String) pack_entries = KV_INITIAL_VALUE;
835  Map(String, int) pack_used = MAP_INIT;
836  Set(String) rtp_used = SET_INIT;
837  RuntimeSearchPath search_path = KV_INITIAL_VALUE;
838  CharVec after_path = KV_INITIAL_VALUE;
839
840  static char buf[MAXPATHL];
841  for (char *entry = p_pp; *entry != NUL;) {
842    char *cur_entry = entry;
843    size_t buflen = copy_option_part(&entry, buf, MAXPATHL, ",");
844
845    String the_entry = { .data = cur_entry, .size = buflen };
846
847    kv_push(pack_entries, the_entry);
848    map_put(String, int)(&pack_used, the_entry, 0);
849  }
850
851  char *rtp_entry;
852  for (rtp_entry = p_rtp; *rtp_entry != NUL;) {
853    char *cur_entry = rtp_entry;
854    size_t buflen = copy_option_part(&rtp_entry, buf, MAXPATHL, ",");
855
856    if (path_is_after(buf, buflen)) {
857      rtp_entry = cur_entry;
858      break;
859    }
860
861    size_t pos_in_rtp = (size_t)(cur_entry - p_rtp);
862
863    // fact: &rtp entries can contain wild chars
864    expand_rtp_entry(&search_path, &rtp_used, buf, false, pos_in_rtp);
865
866    handle_T *h = map_ref(String, int)(&pack_used, cstr_as_string(buf), NULL);
867    if (h) {
868      (*h)++;
869      expand_pack_entry(&search_path, &rtp_used, &after_path, buf, buflen, pos_in_rtp);
870    }
871  }
872
873  // The following entries were not explicit in rtp.
874  // this is fine, but keep pos_in_rtp monotonic:
875  // use the comma between two entries as a sentinel
876  size_t sentinel_pos_in_rtp = (size_t)(rtp_entry - p_rtp);
877  sentinel_pos_in_rtp -= (sentinel_pos_in_rtp > 0) ? 1 : 0;
878
879  for (size_t i = 0; i < kv_size(pack_entries); i++) {
880    String item = kv_A(pack_entries, i);
881    handle_T h = map_get(String, int)(&pack_used, item);
882    if (h == 0) {
883      expand_pack_entry(&search_path, &rtp_used, &after_path, item.data, item.size,
884                        sentinel_pos_in_rtp);
885    }
886  }
887
888  // "after" packages
889  for (size_t i = 0; i < kv_size(after_path); i++) {
890    expand_rtp_entry(&search_path, &rtp_used, kv_A(after_path, i), true, sentinel_pos_in_rtp);
891    xfree(kv_A(after_path, i));
892  }
893
894  // "after" dirs in rtp
895  for (; *rtp_entry != NUL;) {
896    char *cur_entry = rtp_entry;
897    size_t buflen = copy_option_part(&rtp_entry, buf, MAXPATHL, ",");
898    size_t pos_in_rtp = (size_t)(cur_entry - p_rtp);
899    expand_rtp_entry(&search_path, &rtp_used, buf, path_is_after(buf, buflen), pos_in_rtp);
900  }
901
902  // strings are not owned
903  kv_destroy(pack_entries);
904  kv_destroy(after_path);
905  map_destroy(String, &pack_used);
906  set_destroy(String, &rtp_used);
907
908  return search_path;
909}
910
911const char *did_set_runtimepackpath(optset_T *args)
912{
913  runtime_search_path_valid = false;
914  return NULL;
915}
916
917static void runtime_search_path_free(RuntimeSearchPath path)
918{
919  for (size_t j = 0; j < kv_size(path); j++) {
920    SearchPathItem item = kv_A(path, j);
921    xfree(item.path);
922  }
923  kv_destroy(path);
924}
925
926void runtime_search_path_validate(void)
927{
928  if (!nlua_is_deferred_safe()) {
929    // Cannot rebuild search path in an async context. As a plugin will invoke
930    // itself asynchronously from sync code in the same plugin, the sought
931    // after lua/autoload module will most likely already be in the cached path.
932    // Thus prefer using the stale cache over erroring out in this situation.
933    return;
934  }
935  if (!runtime_search_path_valid) {
936    if (!runtime_search_path_ref) {
937      msg_ext_ui_flush();  // avoid recursion due to UI callback
938      runtime_search_path_free(runtime_search_path);
939    }
940    runtime_search_path = runtime_search_path_build();
941    runtime_search_path_valid = true;
942    runtime_search_path_ref = NULL;  // initially unowned
943    update_runtime_search_path_thread(true);
944  }
945}
946
947void update_runtime_search_path_thread(bool force)
948{
949  if (!force && !(runtime_search_path_valid && !runtime_search_path_valid_thread)) {
950    return;
951  }
952
953  uv_mutex_lock(&runtime_search_path_mutex);
954  runtime_search_path_free(runtime_search_path_thread);
955  runtime_search_path_thread = copy_runtime_search_path(runtime_search_path);
956  uv_mutex_unlock(&runtime_search_path_mutex);
957  runtime_search_path_valid_thread = true;
958}
959
960/// Just like do_in_path_and_pp(), using 'runtimepath' for "path".
961int do_in_runtimepath(char *name, int flags, DoInRuntimepathCB callback, void *cookie)
962{
963  int success = FAIL;
964  if (!(flags & DIP_NORTP)) {
965    success |= do_in_cached_path((name && !*name) ? NULL : name, flags, callback, cookie);
966    flags = (flags & ~DIP_START) | DIP_NORTP;
967  }
968  // TODO(bfredl): we could integrate disabled OPT dirs into the cached path
969  // which would effectivize ":packadd myoptpack" as well
970  if ((flags & (DIP_START|DIP_OPT)) && (success == FAIL || (flags & DIP_ALL))) {
971    success |= do_in_path_and_pp(p_rtp, name, flags, callback, cookie);
972  }
973  return success;
974}
975
976/// Source the file "name" from all directories in 'runtimepath'.
977/// "name" can contain wildcards.
978/// When "flags" has DIP_ALL: source all files, otherwise only the first one.
979///
980/// return FAIL when no file could be sourced, OK otherwise.
981int source_runtime(char *name, int flags)
982{
983  return do_in_runtimepath(name, flags, source_callback, NULL);
984}
985
986/// Just like source_runtime(), but only source vim and lua files
987int source_runtime_vim_lua(char *name, int flags)
988{
989  return do_in_runtimepath(name, flags, source_callback_vim_lua, NULL);
990}
991
992/// Just like source_runtime(), but:
993/// - use "path" instead of 'runtimepath'.
994/// - only source .vim and .lua files
995int source_in_path_vim_lua(char *path, char *name, int flags)
996{
997  return do_in_path_and_pp(path, name, flags, source_callback_vim_lua, NULL);
998}
999
1000/// Expand wildcards in "pats" and invoke callback matches.
1001///
1002/// @param      num_pat  is number of input patterns.
1003/// @param      patx     is an array of pointers to input patterns.
1004/// @param      flags    is a combination of EW_* flags used in
1005///                      expand_wildcards().
1006/// @param      all      invoke callback on all matches or just one
1007/// @param      callback called for each match.
1008/// @param      cookie   context for callback
1009///
1010/// @returns             OK when some files were found, FAIL otherwise.
1011static int gen_expand_wildcards_and_cb(int num_pat, char **pats, int flags, bool all,
1012                                       DoInRuntimepathCB callback, void *cookie)
1013{
1014  int num_files;
1015  char **files;
1016
1017  if (gen_expand_wildcards(num_pat, pats, &num_files, &files, flags) != OK) {
1018    return FAIL;
1019  }
1020
1021  (*callback)(num_files, files, all, cookie);
1022
1023  FreeWild(num_files, files);
1024
1025  return OK;
1026}
1027
1028/// Add the package directory to 'runtimepath'
1029///
1030/// @param fname the package path
1031/// @param is_pack whether the added dir is a "pack/*/start/*/" style package
1032static int add_pack_dir_to_rtp(char *fname, bool is_pack)
1033{
1034  String afterdir = STRING_INIT;
1035  int retval = FAIL;
1036
1037  char *p1 = get_past_head(fname);
1038  char *p2 = p1;
1039  char *p3 = p1;
1040  char *p4 = p1;
1041  for (char *p = p1; *p; MB_PTR_ADV(p)) {
1042    if (vim_ispathsep_nocolon(*p)) {
1043      p4 = p3;
1044      p3 = p2;
1045      p2 = p1;
1046      p1 = p;
1047    }
1048  }
1049
1050  // now we have:
1051  // rtp/pack/name/(start|opt)/name
1052  //    p4   p3   p2           p1
1053  //
1054  // find the part up to "pack" in 'runtimepath'
1055  p4++;  // append pathsep in order to expand symlink
1056  char c = *p4;
1057  *p4 = NUL;
1058  char *const ffname = fix_fname(fname);
1059  *p4 = c;
1060
1061  if (ffname == NULL) {
1062    return FAIL;
1063  }
1064
1065  // Find "ffname" in "p_rtp", ignoring '/' vs '\' differences
1066  // Also stop at the first "after" directory
1067  size_t fname_len = strlen(ffname);
1068  char buf_data[MAXPATHL];
1069  String buf;
1070  buf.data = buf_data;
1071
1072  const char *insp = NULL;
1073  const char *after_insp = NULL;
1074  size_t p_rtp_len = 0;
1075  const char *entry = p_rtp;
1076  while (*entry != NUL) {
1077    const char *cur_entry = entry;
1078    buf.size = copy_option_part((char **)&entry, buf.data, MAXPATHL, ",");
1079
1080    // keep track of p_rtp length as we go to make the strlen() below have less work to do
1081    p_rtp_len += (*(cur_entry + buf.size) == ',') ? buf.size + 1 : buf.size;
1082
1083    char *p = strstr(buf.data, "after");
1084    bool is_after = p != NULL
1085                    && p > buf.data
1086                    && vim_ispathsep(p[-1])
1087                    && (vim_ispathsep(p[5]) || p[5] == NUL || p[5] == ',');
1088
1089    if (is_after) {
1090      if (insp == NULL) {
1091        // Did not find "ffname" before the first "after" directory,
1092        // insert it before this entry.
1093        insp = cur_entry;
1094      }
1095      after_insp = cur_entry;
1096      break;
1097    }
1098
1099    if (insp == NULL) {
1100      add_pathsep(buf.data);
1101      char *const rtp_ffname = fix_fname(buf.data);
1102      if (rtp_ffname == NULL) {
1103        goto theend;
1104      }
1105      if (path_cmp(p_fic, rtp_ffname, ffname, fname_len) == 0) {
1106        // Insert "ffname" after this entry (and comma).
1107        insp = entry;
1108      }
1109      xfree(rtp_ffname);
1110    }
1111  }
1112
1113  // finish measuring the length of p_rtp
1114  p_rtp_len += strlen(p_rtp + p_rtp_len);
1115  if (insp == NULL) {
1116    // Both "fname" and "after" not found, append at the end.
1117    insp = p_rtp + p_rtp_len;
1118  }
1119
1120  // check if rtp/pack/name/start/name/after exists
1121  fname_len = strlen(fname);
1122  afterdir = concat_fnames(cbuf_as_string(fname, fname_len), STATIC_CSTR_AS_STRING("after"), true);
1123  if (is_pack ? !pack_has_entries(afterdir.data) : !os_isdir(afterdir.data)) {
1124    afterdir.size = 0;
1125  }
1126
1127  const size_t new_rtp_capacity = p_rtp_len + fname_len + afterdir.size + 3;
1128  // add two for commas and one more for NUL -----------------------------^
1129  String new_rtp;
1130  new_rtp.data = try_malloc(new_rtp_capacity);
1131  if (new_rtp.data == NULL) {
1132    goto theend;
1133  }
1134
1135  // We now have 'rtp' parts: {keep}{keep_after}{rest}.
1136  // Create new_rtp, first: {keep},{fname}
1137  size_t keep = (size_t)(insp - p_rtp);
1138  size_t first_pos = keep;
1139  memmove(new_rtp.data, p_rtp, keep);
1140  new_rtp.size = keep;
1141  if (*insp == NUL) {
1142    new_rtp.data[new_rtp.size++] = ',';  // add comma before
1143    first_pos++;
1144  }
1145  memmove(new_rtp.data + new_rtp.size, fname, fname_len);
1146  new_rtp.size += fname_len;
1147  if (*insp != NUL) {
1148    new_rtp.data[new_rtp.size++] = ',';  // add comma after
1149  }
1150
1151  size_t after_pos = 0;
1152
1153  if (afterdir.size > 0 && after_insp != NULL) {
1154    size_t keep_after = (size_t)(after_insp - p_rtp);
1155    size_t append_len = keep_after - keep;
1156
1157    // Add to new_rtp: {keep},{fname}{keep_after},{afterdir}
1158    memmove(new_rtp.data + new_rtp.size, p_rtp + keep, append_len);
1159    new_rtp.size += append_len;
1160    memmove(new_rtp.data + new_rtp.size, afterdir.data, afterdir.size);
1161    new_rtp.size += afterdir.size;
1162    new_rtp.data[new_rtp.size++] = ',';
1163    keep = keep_after;
1164    after_pos = keep_after;
1165  }
1166
1167  if (p_rtp[keep] != NUL) {
1168    size_t append_len = p_rtp_len - keep;
1169    // Append rest: {keep},{fname}{keep_after},{afterdir}{rest}
1170    memmove(new_rtp.data + new_rtp.size, p_rtp + keep, append_len + 1);  // add one for NUL
1171    new_rtp.size += append_len;
1172  } else {
1173    new_rtp.data[new_rtp.size] = NUL;
1174  }
1175
1176  if (afterdir.size > 0 && after_insp == NULL) {
1177    // Append afterdir when "after" was not found:
1178    // {keep},{fname}{rest},{afterdir}
1179    new_rtp.data[new_rtp.size++] = ',';
1180    after_pos = new_rtp.size;
1181    memmove(new_rtp.data + new_rtp.size, afterdir.data, afterdir.size + 1);  // add one for NUL
1182    new_rtp.size += afterdir.size;
1183  }
1184
1185  bool was_valid = runtime_search_path_valid;
1186  set_option_value_give_err(kOptRuntimepath, STRING_OBJ(new_rtp), 0);
1187
1188  assert(!runtime_search_path_valid);
1189  // If this is the result of "packadd opt_pack", rebuilding runtime_search_pat
1190  // from scratch is needlessly slow. splice in the package and its afterdir instead.
1191  // But don't do this for "pack/*/start/*" (is_pack=true):
1192  // we want properly expand wildcards in a "start" bundle.
1193  if (was_valid && !is_pack && !runtime_search_path_ref) {
1194    runtime_search_path_valid = true;
1195    runtime_search_path_valid_thread = false;
1196    kv_pushp(runtime_search_path);
1197    ssize_t i = (ssize_t)(kv_size(runtime_search_path)) - 1;
1198
1199    if (afterdir.size > 0) {
1200      kv_pushp(runtime_search_path);
1201      i += 1;
1202      for (; i >= 1; i--) {
1203        if (i > 1 && kv_A(runtime_search_path, i - 2).pos_in_rtp >= after_pos) {
1204          kv_A(runtime_search_path, i) = kv_A(runtime_search_path, i - 2);
1205          kv_A(runtime_search_path, i).pos_in_rtp += fname_len + afterdir.size + 2;
1206        } else {
1207          kv_A(runtime_search_path, i) = (SearchPathItem){
1208            xmemdupz(afterdir.data, afterdir.size), true, true, kNone, after_pos + fname_len + 1,
1209          };
1210          i--;
1211          break;
1212        }
1213      }
1214    }
1215
1216    for (; i >= 0; i--) {
1217      if (i > 0 && kv_A(runtime_search_path, i - 1).pos_in_rtp >= first_pos) {
1218        kv_A(runtime_search_path, i) = kv_A(runtime_search_path, i - 1);
1219        kv_A(runtime_search_path, i).pos_in_rtp += fname_len + 1;
1220      } else {
1221        kv_A(runtime_search_path, i) = (SearchPathItem){
1222          xmemdupz(fname, fname_len), false, true, kNone, first_pos
1223        };
1224        break;
1225      }
1226    }
1227  }
1228  xfree(new_rtp.data);
1229  retval = OK;
1230
1231theend:
1232  xfree(ffname);
1233  xfree(afterdir.data);
1234  return retval;
1235}
1236
1237/// Load scripts in "plugin" directory of the package.
1238/// For opt packages, also load scripts in "ftdetect" (start packages already
1239/// load these from filetype.lua)
1240static int load_pack_plugin(bool opt, char *fname)
1241{
1242  static const char plugpat[] = "%s/plugin/**/*";  // NOLINT
1243  static const char ftpat[] = "%s/ftdetect/*";  // NOLINT
1244
1245  char *const ffname = fix_fname(fname);
1246  size_t len = strlen(ffname) + sizeof(plugpat);
1247  char *pat = xmallocz(len);
1248
1249  vim_snprintf(pat, len, plugpat, ffname);
1250  gen_expand_wildcards_and_cb(1, &pat, EW_FILE, true, source_callback_vim_lua, NULL);
1251
1252  char *cmd = xstrdup("g:did_load_filetypes");
1253
1254  // If runtime/filetype.lua wasn't loaded yet, the scripts will be
1255  // found when it loads.
1256  if (opt && eval_to_number(cmd, false) > 0) {
1257    do_cmdline_cmd("augroup filetypedetect");
1258    vim_snprintf(pat, len, ftpat, ffname);
1259    gen_expand_wildcards_and_cb(1, &pat, EW_FILE, true, source_callback_vim_lua, NULL);
1260    do_cmdline_cmd("augroup END");
1261  }
1262  xfree(cmd);
1263  xfree(pat);
1264  xfree(ffname);
1265
1266  return OK;
1267}
1268
1269// used for "cookie" of add_pack_plugin()
1270static int APP_ADD_DIR;
1271static int APP_LOAD;
1272static int APP_BOTH;
1273
1274static void add_pack_plugins(bool opt, int num_fnames, char **fnames, bool all, void *cookie)
1275{
1276  bool did_one = false;
1277
1278  if (cookie != &APP_LOAD) {
1279    char buf[MAXPATHL];
1280    for (int i = 0; i < num_fnames; i++) {
1281      bool found = false;
1282
1283      const char *p = p_rtp;
1284      while (*p != NUL) {
1285        copy_option_part((char **)&p, buf, MAXPATHL, ",");
1286        if (path_equal(buf, fnames[i], kPathCmpLiteral)) {
1287          found = true;
1288          break;
1289        }
1290      }
1291      if (!found) {
1292        // directory is not yet in 'runtimepath', add it
1293        if (add_pack_dir_to_rtp(fnames[i], false) == FAIL) {
1294          return;
1295        }
1296      }
1297      did_one = true;
1298      if (!all) {
1299        break;
1300      }
1301    }
1302  }
1303
1304  if (!all && did_one) {
1305    return;
1306  }
1307
1308  if (cookie != &APP_ADD_DIR) {
1309    for (int i = 0; i < num_fnames; i++) {
1310      load_pack_plugin(opt, fnames[i]);
1311      if (!all) {
1312        break;
1313      }
1314    }
1315  }
1316}
1317
1318static bool add_start_pack_plugins(int num_fnames, char **fnames, bool all, void *cookie)
1319{
1320  add_pack_plugins(false, num_fnames, fnames, all, cookie);
1321  return num_fnames > 0;
1322}
1323
1324static bool add_opt_pack_plugins(int num_fnames, char **fnames, bool all, void *cookie)
1325{
1326  add_pack_plugins(true, num_fnames, fnames, all, cookie);
1327  return num_fnames > 0;
1328}
1329
1330/// Add all packages in the "start" directory to 'runtimepath'.
1331void add_pack_start_dirs(void)
1332{
1333  do_in_path(p_pp, "", NULL, DIP_ALL + DIP_DIR, add_pack_start_dir, NULL);
1334}
1335
1336static bool pack_has_entries(char *buf)
1337{
1338  int num_files;
1339  char **files;
1340  char *(pat[]) = { buf };
1341  if (gen_expand_wildcards(1, pat, &num_files, &files, EW_DIR) == OK) {
1342    FreeWild(num_files, files);
1343  }
1344  return num_files > 0;
1345}
1346
1347static bool add_pack_start_dir(int num_fnames, char **fnames, bool all, void *cookie)
1348{
1349  static char buf[MAXPATHL];
1350  for (int i = 0; i < num_fnames; i++) {
1351    char *(start_pat[]) = { "/start/*", "/pack/*/start/*" };  // NOLINT
1352    for (int j = 0; j < 2; j++) {
1353      if (strlen(fnames[i]) + strlen(start_pat[j]) + 1 > MAXPATHL) {
1354        continue;
1355      }
1356      xstrlcpy(buf, fnames[i], MAXPATHL);
1357      xstrlcat(buf, start_pat[j], sizeof buf);
1358      if (pack_has_entries(buf)) {
1359        add_pack_dir_to_rtp(buf, true);
1360      }
1361    }
1362
1363    if (!all) {
1364      break;
1365    }
1366  }
1367
1368  return num_fnames > 1;
1369}
1370
1371/// Load plugins from all packages in the "start" directory.
1372void load_start_packages(void)
1373{
1374  did_source_packages = true;
1375  do_in_path(p_pp, "", "pack/*/start/*", DIP_ALL + DIP_DIR,  // NOLINT
1376             add_start_pack_plugins, &APP_LOAD);
1377  do_in_path(p_pp, "", "start/*", DIP_ALL + DIP_DIR,  // NOLINT
1378             add_start_pack_plugins, &APP_LOAD);
1379
1380  update_runtime_search_path_thread(false);
1381}
1382
1383// ":packloadall"
1384// Find plugins in the package directories and source them.
1385void ex_packloadall(exarg_T *eap)
1386{
1387  if (!did_source_packages || eap->forceit) {
1388    // First do a round to add all directories to 'runtimepath', then load
1389    // the plugins. This allows for plugins to use an autoload directory
1390    // of another plugin.
1391    add_pack_start_dirs();
1392    load_start_packages();
1393  }
1394}
1395
1396/// Read all the plugin files at startup
1397void load_plugins(void)
1398{
1399  if (p_lpl) {
1400    char *rtp_copy = p_rtp;
1401    char *const plugin_pattern = "plugin/**/*";  // NOLINT
1402
1403    if (!did_source_packages) {
1404      rtp_copy = xstrdup(p_rtp);
1405      add_pack_start_dirs();
1406    }
1407
1408    // Don't use source_runtime_vim_lua() yet so we can check for :packloadall below.
1409    // NB: after calling this "rtp_copy" may have been freed if it wasn't copied.
1410    source_in_path_vim_lua(rtp_copy, plugin_pattern, DIP_ALL | DIP_NOAFTER);
1411    TIME_MSG("loading rtp plugins");
1412
1413    // Only source "start" packages if not done already with a :packloadall
1414    // command.
1415    if (!did_source_packages) {
1416      xfree(rtp_copy);
1417      load_start_packages();
1418    }
1419    TIME_MSG("loading packages");
1420
1421    source_runtime_vim_lua(plugin_pattern, DIP_ALL | DIP_AFTER);
1422    TIME_MSG("loading after plugins");
1423  }
1424}
1425
1426/// ":packadd[!] {name}"
1427void ex_packadd(exarg_T *eap)
1428{
1429  static const char plugpat[] = "pack/*/%s/%s";  // NOLINT
1430  int res = OK;
1431
1432  const size_t len = sizeof(plugpat) + strlen(eap->arg) + 5;
1433  char *pat = xmallocz(len);
1434  void *cookie = eap->forceit ? &APP_ADD_DIR : &APP_BOTH;
1435
1436  // Only look under "start" when loading packages wasn't done yet.
1437  if (!did_source_packages) {
1438    vim_snprintf(pat, len, plugpat, "start", eap->arg);
1439    res = do_in_path(p_pp, "", pat, DIP_ALL + DIP_DIR,
1440                     add_start_pack_plugins, cookie);
1441  }
1442
1443  // Give a "not found" error if nothing was found in 'start' or 'opt'.
1444  vim_snprintf(pat, len, plugpat, "opt", eap->arg);
1445  do_in_path(p_pp, "", pat, DIP_ALL + DIP_DIR + (res == FAIL ? DIP_ERR : 0),
1446             add_opt_pack_plugins, cookie);
1447
1448  update_runtime_search_path_thread(false);
1449
1450  xfree(pat);
1451}
1452
1453static void ExpandRTDir_int(char *pat, size_t pat_len, int flags, bool keep_ext, garray_T *gap,
1454                            char *dirnames[])
1455{
1456  // TODO(bfredl): this is bullshit, expandpath should not reinvent path logic.
1457  for (int i = 0; dirnames[i] != NULL; i++) {
1458    const size_t buf_len = strlen(dirnames[i]) + pat_len + 64;
1459    char *buf = xmalloc(buf_len);
1460    int glob_flags = 0;
1461    bool expand_dirs = false;
1462    // Build base pattern
1463    snprintf(buf, buf_len, "%s%s%s%s", *dirnames[i] ? dirnames[i] : "", *dirnames[i] ? "/" : "",
1464             pat, "*.{vim,lua}");
1465
1466expand:
1467    if ((flags & DIP_NORTP) == 0) {
1468      globpath(p_rtp, buf, gap, glob_flags, expand_dirs);
1469    }
1470
1471    if (flags & DIP_START) {
1472      // pack/*/start/*/ patterns
1473      snprintf(buf, buf_len, "pack/*/start/*/%s%s%s%s", *dirnames[i] ? dirnames[i] : "",  // NOLINT
1474               *dirnames[i] ? "/" : "", pat, expand_dirs ? "*" : "*.{vim,lua}");
1475      globpath(p_pp, buf, gap, glob_flags, expand_dirs);
1476
1477      // start/*/ patterns
1478      snprintf(buf, buf_len, "start/*/%s%s%s%s", *dirnames[i] ? dirnames[i] : "",  // NOLINT
1479               *dirnames[i] ? "/" : "", pat, expand_dirs ? "*" : "*.{vim,lua}");
1480      globpath(p_pp, buf, gap, glob_flags, expand_dirs);
1481    }
1482
1483    if (flags & DIP_OPT) {
1484      // pack/*/opt/*/ patterns
1485      snprintf(buf, buf_len, "pack/*/opt/*/%s%s%s%s", *dirnames[i] ? dirnames[i] : "",  // NOLINT
1486               *dirnames[i] ? "/" : "", pat, expand_dirs ? "*" : "*.{vim,lua}");
1487      globpath(p_pp, buf, gap, glob_flags, expand_dirs);
1488
1489      // opt/*/ patterns
1490      snprintf(buf, buf_len, "opt/*/%s%s%s%s", *dirnames[i] ? dirnames[i] : "",  // NOLINT
1491               *dirnames[i] ? "/" : "", pat, expand_dirs ? "*" : "*.{vim,lua}");
1492      globpath(p_pp, buf, gap, glob_flags, expand_dirs);
1493    }
1494
1495    // Second round for directories
1496    if (*dirnames[i] == NUL && !expand_dirs) {
1497      snprintf(buf, buf_len, "%s*", pat);
1498      glob_flags = WILD_ADD_SLASH;
1499      expand_dirs = true;
1500      goto expand;
1501    }
1502
1503    xfree(buf);
1504  }
1505
1506  int pat_pathsep_cnt = 0;
1507  for (size_t i = 0; i < pat_len; i++) {
1508    if (vim_ispathsep(pat[i])) {
1509      pat_pathsep_cnt++;
1510    }
1511  }
1512
1513  for (int i = 0; i < gap->ga_len; i++) {
1514    char *match = ((char **)gap->ga_data)[i];
1515    char *s = match;
1516    char *e = s + strlen(s);
1517    if (e - s > 4 && !keep_ext && (STRNICMP(e - 4, ".vim", 4) == 0
1518                                   || STRNICMP(e - 4, ".lua", 4) == 0)) {
1519      e -= 4;
1520      *e = NUL;
1521    }
1522
1523    int match_pathsep_cnt = (e > s && e[-1] == '/') ? -1 : 0;
1524    for (s = e; s > match; MB_PTR_BACK(match, s)) {
1525      if (vim_ispathsep(*s) && ++match_pathsep_cnt > pat_pathsep_cnt) {
1526        break;
1527      }
1528    }
1529    s++;
1530    if (s != match) {
1531      assert((e - s) + 1 >= 0);
1532      memmove(match, s, (size_t)(e - s) + 1);
1533    }
1534  }
1535
1536  if (GA_EMPTY(gap)) {
1537    return;
1538  }
1539
1540  // Sort and remove duplicates which can happen when specifying multiple
1541  // directories in dirnames.
1542  ga_remove_duplicate_strings(gap);
1543}
1544
1545/// Expand color scheme, compiler or filetype names.
1546/// Search from 'runtimepath':
1547///   'runtimepath'/{dirnames}/{pat}.{vim,lua}
1548/// When "flags" has DIP_START: search also from "start" of 'packpath':
1549///   'packpath'/pack/*/start/*/{dirnames}/{pat}.{vim,lua}
1550/// When "flags" has DIP_OPT: search also from "opt" of 'packpath':
1551///   'packpath'/pack/*/opt/*/{dirnames}/{pat}.{vim,lua}
1552/// "dirnames" is an array with one or more directory names.
1553int ExpandRTDir(char *pat, int flags, int *num_file, char ***file, char *dirnames[])
1554{
1555  *num_file = 0;
1556  *file = NULL;
1557
1558  garray_T ga;
1559  ga_init(&ga, (int)sizeof(char *), 10);
1560
1561  ExpandRTDir_int(pat, strlen(pat), flags, false, &ga, dirnames);
1562
1563  if (GA_EMPTY(&ga)) {
1564    return FAIL;
1565  }
1566
1567  *file = ga.ga_data;
1568  *num_file = ga.ga_len;
1569  return OK;
1570}
1571
1572/// Handle command line completion for :runtime command.
1573int expand_runtime_cmd(char *pat, int *numMatches, char ***matches)
1574{
1575  *numMatches = 0;
1576  *matches = NULL;
1577
1578  garray_T ga;
1579  ga_init(&ga, sizeof(char *), 10);
1580
1581  const size_t pat_len = strlen(pat);
1582  char *dirnames[] = { "", NULL };
1583  ExpandRTDir_int(pat, pat_len, runtime_expand_flags, true, &ga, dirnames);
1584
1585  // Try to complete values for [where] argument when none was found.
1586  if (runtime_expand_flags == 0) {
1587    char *where_values[] = { "START", "OPT", "PACK", "ALL" };
1588    for (size_t i = 0; i < ARRAY_SIZE(where_values); i++) {
1589      if (strncmp(pat, where_values[i], pat_len) == 0) {
1590        GA_APPEND(char *, &ga, xstrdup(where_values[i]));
1591      }
1592    }
1593  }
1594
1595  if (GA_EMPTY(&ga)) {
1596    return FAIL;
1597  }
1598
1599  *matches = ga.ga_data;
1600  *numMatches = ga.ga_len;
1601  return OK;
1602}
1603
1604/// Expand loadplugin names:
1605/// 'packpath'/pack/*/opt/{pat}
1606int ExpandPackAddDir(char *pat, int *num_file, char ***file)
1607{
1608  garray_T ga;
1609
1610  *num_file = 0;
1611  *file = NULL;
1612  size_t pat_len = strlen(pat);
1613  ga_init(&ga, (int)sizeof(char *), 10);
1614
1615  size_t buflen = pat_len + 26;
1616  char *s = xmalloc(buflen);
1617  snprintf(s, buflen, "pack/*/opt/%s*", pat);  // NOLINT
1618  globpath(p_pp, s, &ga, 0, true);
1619  snprintf(s, buflen, "opt/%s*", pat);  // NOLINT
1620  globpath(p_pp, s, &ga, 0, true);
1621  xfree(s);
1622
1623  for (int i = 0; i < ga.ga_len; i++) {
1624    char *match = ((char **)ga.ga_data)[i];
1625    s = path_tail(match);
1626    memmove(match, s, strlen(s) + 1);
1627  }
1628
1629  if (GA_EMPTY(&ga)) {
1630    return FAIL;
1631  }
1632
1633  // Sort and remove duplicates which can happen when specifying multiple
1634  // directories in dirnames.
1635  ga_remove_duplicate_strings(&ga);
1636
1637  *file = ga.ga_data;
1638  *num_file = ga.ga_len;
1639  return OK;
1640}
1641
1642/// Append string with escaped commas
1643static char *strcpy_comma_escaped(char *dest, const char *src, const size_t len)
1644  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
1645{
1646  size_t shift = 0;
1647  for (size_t i = 0; i < len; i++) {
1648    if (src[i] == ',') {
1649      dest[i + shift++] = '\\';
1650    }
1651    dest[i + shift] = src[i];
1652  }
1653  return &dest[len + shift];
1654}
1655
1656/// Compute length of a ENV_SEPCHAR-separated value, doubled and with some
1657/// suffixes
1658///
1659/// @param[in]  val  ENV_SEPCHAR-separated array value.
1660/// @param[in]  common_suf_len  Length of the common suffix which is appended to
1661///                             each item in the array, twice.
1662/// @param[in]  single_suf_len  Length of the suffix which is appended to each
1663///                             item in the array once.
1664///
1665/// @return Length of the ENV_SEPCHAR-separated string array that contains each
1666///         item in the original array twice with suffixes with given length
1667///         (common_suf is present after each new item, single_suf is present
1668///         after half of the new items) and with commas after each item, commas
1669///         inside the values are escaped.
1670static inline size_t compute_double_env_sep_len(const char *const val, const size_t common_suf_len,
1671                                                const size_t single_suf_len)
1672  FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE
1673{
1674  if (val == NULL || *val == NUL) {
1675    return 0;
1676  }
1677  size_t ret = 0;
1678  const void *iter = NULL;
1679  do {
1680    size_t dir_len;
1681    const char *dir;
1682    iter = vim_env_iter(ENV_SEPCHAR, val, iter, &dir, &dir_len);
1683    if (dir != NULL && dir_len > 0) {
1684      ret += ((dir_len + memcnt(dir, ',', dir_len) + common_suf_len
1685               + !after_pathsep(dir, dir + dir_len)) * 2
1686              + single_suf_len);
1687    }
1688  } while (iter != NULL);
1689  return ret;
1690}
1691
1692/// Add directories to a ENV_SEPCHAR-separated array from a colon-separated one
1693///
1694/// Commas are escaped in process. To each item PATHSEP "nvim" is appended in
1695/// addition to suf1 and suf2.
1696///
1697/// @param[in,out]  dest  Destination comma-separated array.
1698/// @param[in]  val  Source ENV_SEPCHAR-separated array.
1699/// @param[in]  suf1  If not NULL, suffix appended to destination. Prior to it
1700///                   directory separator is appended. Suffix must not contain
1701///                   commas.
1702/// @param[in]  len1  Length of the suf1.
1703/// @param[in]  suf2  If not NULL, another suffix appended to destination. Again
1704///                   with directory separator behind. Suffix must not contain
1705///                   commas.
1706/// @param[in]  len2  Length of the suf2.
1707/// @param[in]  forward  If true, iterate over val in forward direction.
1708///                      Otherwise in reverse.
1709///
1710/// @return (dest + appended_characters_length)
1711static inline char *add_env_sep_dirs(char *dest, const char *const val, const char *const suf1,
1712                                     const size_t len1, const char *const suf2, const size_t len2,
1713                                     const bool forward)
1714  FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_RET FUNC_ATTR_NONNULL_ARG(1)
1715{
1716  if (val == NULL || *val == NUL) {
1717    return dest;
1718  }
1719  const void *iter = NULL;
1720  const char *appname = get_appname(false);
1721  const size_t appname_len = strlen(appname);
1722  do {
1723    size_t dir_len;
1724    const char *dir;
1725    iter = (forward ? vim_env_iter : vim_env_iter_rev)(ENV_SEPCHAR, val, iter,
1726                                                       &dir, &dir_len);
1727    if (dir != NULL && dir_len > 0) {
1728      dest = strcpy_comma_escaped(dest, dir, dir_len);
1729      if (!after_pathsep(dest - 1, dest)) {
1730        *dest++ = PATHSEP;
1731      }
1732      memmove(dest, appname, appname_len);
1733      dest += appname_len;
1734      if (suf1 != NULL) {
1735        *dest++ = PATHSEP;
1736        memmove(dest, suf1, len1);
1737        dest += len1;
1738        if (suf2 != NULL) {
1739          *dest++ = PATHSEP;
1740          memmove(dest, suf2, len2);
1741          dest += len2;
1742        }
1743      }
1744      *dest++ = ',';
1745    }
1746  } while (iter != NULL);
1747  return dest;
1748}
1749
1750/// Adds directory `dest` to a comma-separated list of directories.
1751///
1752/// Commas in the added directory are escaped.
1753///
1754/// Windows: Appends "nvim-data" instead of "nvim" if `type` is kXDGDataHome.
1755///
1756/// @see get_xdg_home
1757///
1758/// @param[in,out]  dest  Destination comma-separated array.
1759/// @param[in]  dir  Directory to append.
1760/// @param[in]  type  Decides whether to append "nvim" (Win: or "nvim-data").
1761/// @param[in]  suf1  If not NULL, suffix appended to destination. Prior to it
1762///                   directory separator is appended. Suffix must not contain
1763///                   commas.
1764/// @param[in]  len1  Length of the suf1.
1765/// @param[in]  suf2  If not NULL, another suffix appended to destination. Again
1766///                   with directory separator behind. Suffix must not contain
1767///                   commas.
1768/// @param[in]  len2  Length of the suf2.
1769/// @param[in]  forward  If true, iterate over val in forward direction.
1770///                      Otherwise in reverse.
1771///
1772/// @return (dest + appended_characters_length)
1773static inline char *add_dir(char *dest, const char *const dir, const size_t dir_len,
1774                            const XDGVarType type, const char *const suf1, const size_t len1,
1775                            const char *const suf2, const size_t len2)
1776  FUNC_ATTR_NONNULL_RET FUNC_ATTR_NONNULL_ARG(1) FUNC_ATTR_WARN_UNUSED_RESULT
1777{
1778  if (dir == NULL || dir_len == 0) {
1779    return dest;
1780  }
1781  dest = strcpy_comma_escaped(dest, dir,
1782                              after_pathsep(dir - 1, dir + dir_len) == 1 ? dir_len - 1 : dir_len);
1783  bool append_nvim = (type == kXDGDataHome || type == kXDGConfigHome);
1784  if (append_nvim) {
1785    *dest++ = PATHSEP;
1786    const char *appname = get_appname(false);
1787    size_t appname_len = strlen(appname);
1788    assert(appname_len < (IOSIZE - sizeof("-data")));
1789    xmemcpyz(IObuff, appname, appname_len);
1790#ifdef MSWIN
1791    if (type == kXDGDataHome || type == kXDGStateHome) {
1792      xstrlcat(IObuff, "-data", IOSIZE);
1793      appname_len += 5;
1794    }
1795#endif
1796    xmemcpyz(dest, IObuff, appname_len);
1797    dest += appname_len;
1798  }
1799  if (suf1 != NULL) {
1800    *dest++ = PATHSEP;
1801    memmove(dest, suf1, len1);
1802    dest += len1;
1803    if (suf2 != NULL) {
1804      *dest++ = PATHSEP;
1805      memmove(dest, suf2, len2);
1806      dest += len2;
1807    }
1808  }
1809  *dest++ = ',';
1810  return dest;
1811}
1812
1813char *get_lib_dir(void)
1814{
1815  // TODO(bfredl): too fragile? Ideally default_lib_dir would be made empty
1816  // in an appimage build
1817  if (strlen(default_lib_dir) != 0
1818      && os_isdir(default_lib_dir)) {
1819    return xstrdup(default_lib_dir);
1820  }
1821
1822  // Find library path relative to the nvim binary: ../lib/nvim/
1823  char exe_name[MAXPATHL];
1824  vim_get_prefix_from_exepath(exe_name);
1825  if (append_path(exe_name, "lib/nvim", MAXPATHL) == OK) {
1826    return xstrdup(exe_name);
1827  }
1828  return NULL;
1829}
1830
1831/// Determine the startup value for &runtimepath
1832///
1833/// Windows: Uses "…/nvim-data" for kXDGDataHome to avoid storing
1834/// configuration and data files in the same path. #4403
1835///
1836/// @param clean_arg  Nvim was started with --clean.
1837/// @return allocated string with the value
1838char *runtimepath_default(bool clean_arg)
1839{
1840  size_t rtp_size = 0;
1841  char *const data_home = clean_arg
1842                          ? NULL
1843                          : stdpaths_get_xdg_var(kXDGDataHome);
1844  char *const vimconfig = vim_getenv("NVIM_CONFIG");
1845  char *const config_home = (clean_arg || vimconfig != NULL)
1846                            ? NULL
1847                            : stdpaths_get_xdg_var(kXDGConfigHome);
1848  char *const libdir = get_lib_dir();
1849  char *const data_dirs = stdpaths_get_xdg_var(kXDGDataDirs);
1850  char *const config_dirs = stdpaths_get_xdg_var(kXDGConfigDirs);
1851  char *const vimruntime = vim_getenv("VIMRUNTIME");
1852#define SITE_SIZE (sizeof("site") - 1)
1853#define AFTER_SIZE (sizeof("after") - 1)
1854  size_t data_len = 0;
1855  size_t vimconfig_len = 0;
1856  size_t config_len = 0;
1857  size_t vimruntime_len = 0;
1858  size_t libdir_len = 0;
1859  size_t appname_len = strlen(get_appname(false));
1860  if (data_home != NULL) {
1861    data_len = strlen(data_home);
1862    size_t nvim_data_size = appname_len;
1863#ifdef MSWIN
1864    nvim_data_size += sizeof("-data") - 1;  // -1: NULL byte should be ignored
1865#endif
1866    if (data_len != 0) {
1867      rtp_size += ((data_len + memcnt(data_home, ',', data_len)
1868                    + nvim_data_size + 1 + SITE_SIZE + 1
1869                    + !after_pathsep(data_home, data_home + data_len)) * 2
1870                   + AFTER_SIZE + 1);
1871    }
1872  }
1873  if (config_home != NULL) {
1874    config_len = strlen(config_home);
1875    if (config_len != 0) {
1876      rtp_size += ((config_len + memcnt(config_home, ',', config_len)
1877                    + appname_len + 1
1878                    + !after_pathsep(config_home, config_home + config_len)) * 2
1879                   + AFTER_SIZE + 1);
1880    }
1881  }
1882  if (vimconfig != NULL) {
1883    vimconfig_len = strlen(vimconfig);
1884    if (vimconfig_len != 0) {
1885      rtp_size += ((vimconfig_len + memcnt(vimconfig, ',', vimconfig_len)
1886                    + !after_pathsep(vimconfig, vimconfig + vimconfig_len)) * 2
1887                   + AFTER_SIZE + 1);
1888    }
1889  }
1890  if (vimruntime != NULL) {
1891    vimruntime_len = strlen(vimruntime);
1892    if (vimruntime_len != 0) {
1893      rtp_size += vimruntime_len + memcnt(vimruntime, ',', vimruntime_len) + 1;
1894    }
1895  }
1896  if (libdir != NULL) {
1897    libdir_len = strlen(libdir);
1898    if (libdir_len != 0) {
1899      rtp_size += libdir_len + memcnt(libdir, ',', libdir_len) + 1;
1900    }
1901  }
1902  rtp_size += compute_double_env_sep_len(data_dirs,
1903                                         appname_len + 1 + SITE_SIZE + 1,
1904                                         AFTER_SIZE + 1);
1905  rtp_size += compute_double_env_sep_len(config_dirs, appname_len + 1,
1906                                         AFTER_SIZE + 1);
1907  char *rtp = NULL;
1908  if (rtp_size == 0) {
1909    goto freeall;
1910  }
1911  rtp = xmalloc(rtp_size);
1912  char *rtp_cur = rtp;
1913  rtp_cur = add_dir(rtp_cur, vimconfig, vimconfig_len, kXDGNone,
1914                    NULL, 0, NULL, 0);
1915  rtp_cur = add_dir(rtp_cur, config_home, config_len, kXDGConfigHome,
1916                    NULL, 0, NULL, 0);
1917  rtp_cur = add_env_sep_dirs(rtp_cur, config_dirs, NULL, 0, NULL, 0, true);
1918  rtp_cur = add_dir(rtp_cur, data_home, data_len, kXDGDataHome,
1919                    "site", SITE_SIZE, NULL, 0);
1920  rtp_cur = add_env_sep_dirs(rtp_cur, data_dirs, "site", SITE_SIZE, NULL, 0,
1921                             true);
1922  rtp_cur = add_dir(rtp_cur, vimruntime, vimruntime_len, kXDGNone,
1923                    NULL, 0, NULL, 0);
1924  rtp_cur = add_dir(rtp_cur, libdir, libdir_len, kXDGNone, NULL, 0, NULL, 0);
1925  rtp_cur = add_env_sep_dirs(rtp_cur, data_dirs, "site", SITE_SIZE,
1926                             "after", AFTER_SIZE, false);
1927  rtp_cur = add_dir(rtp_cur, data_home, data_len, kXDGDataHome,
1928                    "site", SITE_SIZE, "after", AFTER_SIZE);
1929  rtp_cur = add_env_sep_dirs(rtp_cur, config_dirs, "after", AFTER_SIZE, NULL, 0,
1930                             false);
1931  rtp_cur = add_dir(rtp_cur, vimconfig, vimconfig_len, kXDGNone,
1932                    "after", AFTER_SIZE, NULL, 0);
1933  rtp_cur = add_dir(rtp_cur, config_home, config_len, kXDGConfigHome,
1934                    "after", AFTER_SIZE, NULL, 0);
1935  // Strip trailing comma.
1936  rtp_cur[-1] = NUL;
1937  assert((size_t)(rtp_cur - rtp) == rtp_size);
1938#undef SITE_SIZE
1939#undef AFTER_SIZE
1940freeall:
1941  xfree(data_dirs);
1942  xfree(config_dirs);
1943  xfree(data_home);
1944  xfree(config_home);
1945  xfree(vimconfig);
1946  xfree(vimruntime);
1947  xfree(libdir);
1948
1949  return rtp;
1950}
1951
1952static void cmd_source(char *fname, exarg_T *eap)
1953{
1954  if (*fname != NUL && eap != NULL && eap->addr_count > 0) {
1955    // if a filename is specified to :source, then a range is not allowed
1956    emsg(_(e_norange));
1957    return;
1958  }
1959
1960  if (eap != NULL && *fname == NUL) {
1961    if (eap->forceit) {
1962      // a file name is needed to source normal mode commands
1963      emsg(_(e_argreq));
1964    } else {
1965      // source ex commands from the current buffer
1966      cmd_source_buffer(eap, false);
1967    }
1968  } else if (eap != NULL && eap->forceit) {
1969    // ":source!": read Normal mode commands
1970    // Need to execute the commands directly.  This is required at least
1971    // for:
1972    // - ":g" command busy
1973    // - after ":argdo", ":windo" or ":bufdo"
1974    // - another command follows
1975    // - inside a loop
1976    openscript(fname, global_busy || listcmd_busy || eap->nextcmd != NULL
1977               || eap->cstack->cs_idx >= 0);
1978
1979    // ":source" read ex commands
1980  } else if (do_source(fname, false, DOSO_NONE, NULL) == FAIL) {
1981    semsg(_(e_notopen), fname);
1982  }
1983}
1984
1985/// ":source [{fname}]"
1986void ex_source(exarg_T *eap)
1987{
1988  cmd_source(eap->arg, eap);
1989}
1990
1991/// ":options"
1992void ex_options(exarg_T *eap)
1993{
1994  char buf[500];
1995  bool multi_mods = 0;
1996
1997  buf[0] = NUL;
1998  add_win_cmd_modifiers(buf, &cmdmod, &multi_mods);
1999
2000  os_setenv("OPTWIN_CMD", buf, 1);
2001  cmd_source(SYS_OPTWIN_FILE, NULL);
2002}
2003
2004/// ":source" and associated commands.
2005///
2006/// @return address holding the next breakpoint line for a source cookie
2007linenr_T *source_breakpoint(void *cookie)
2008{
2009  return &((source_cookie_T *)cookie)->breakpoint;
2010}
2011
2012/// @return  the address holding the debug tick for a source cookie.
2013int *source_dbg_tick(void *cookie)
2014{
2015  return &((source_cookie_T *)cookie)->dbg_tick;
2016}
2017
2018/// @return  the nesting level for a source cookie.
2019int source_level(void *cookie)
2020  FUNC_ATTR_PURE
2021{
2022  return ((source_cookie_T *)cookie)->level;
2023}
2024
2025/// Special function to open a file without handle inheritance.
2026/// If possible the handle is closed on exec().
2027static FILE *fopen_noinh_readbin(char *filename)
2028{
2029#ifdef MSWIN
2030  int fd_tmp = os_open(filename, O_RDONLY | O_BINARY | O_NOINHERIT, 0);
2031#else
2032  int fd_tmp = os_open(filename, O_RDONLY, 0);
2033#endif
2034
2035  if (fd_tmp < 0) {
2036    return NULL;
2037  }
2038
2039  os_set_cloexec(fd_tmp);
2040
2041  return fdopen(fd_tmp, READBIN);
2042}
2043
2044/// Concatenate Vimscript line if it starts with a line continuation into a growarray
2045/// (excluding the continuation chars and leading whitespace)
2046///
2047/// @note Growsize of the growarray may be changed to speed up concatenations!
2048///
2049/// @param ga  the growarray to append to
2050/// @param init_growsize  the starting growsize value of the growarray
2051/// @param p  pointer to the beginning of the line to consider
2052/// @param len  the length of this line
2053///
2054/// @return true if this line did begin with a continuation (the next line
2055///         should also be considered, if it exists); false otherwise
2056static bool concat_continued_line(garray_T *const ga, const int init_growsize, const char *const p,
2057                                  size_t len)
2058  FUNC_ATTR_NONNULL_ALL
2059{
2060  const char *const line = skipwhite_len(p, len);
2061  len -= (size_t)(line - p);
2062  // Skip lines starting with '\" ', concat lines starting with '\'
2063  if (len >= 3 && strncmp(line, "\"\\ ", 3) == 0) {
2064    return true;
2065  } else if (len == 0 || line[0] != '\\') {
2066    return false;
2067  }
2068  if (ga->ga_len > init_growsize) {
2069    ga_set_growsize(ga, MIN(ga->ga_len, 8000));
2070  }
2071  ga_concat_len(ga, line + 1, len - 1);
2072  return true;
2073}
2074
2075/// Create a new script item and allocate script-local vars. @see new_script_vars
2076///
2077/// @param  name  File name of the script. NULL for anonymous :source.
2078/// @param[out]  sid_out  SID of the new item.
2079///
2080/// @return  pointer to the created script item.
2081scriptitem_T *new_script_item(char *const name, scid_T *const sid_out)
2082  FUNC_ATTR_NONNULL_RET
2083{
2084  static scid_T last_current_SID = 0;
2085  const scid_T sid = ++last_current_SID;
2086  if (sid_out != NULL) {
2087    *sid_out = sid;
2088  }
2089  ga_grow(&script_items, sid - script_items.ga_len);
2090  while (script_items.ga_len < sid) {
2091    scriptitem_T *si = xcalloc(1, sizeof(scriptitem_T));
2092    script_items.ga_len++;
2093    SCRIPT_ITEM(script_items.ga_len) = si;
2094    si->sn_name = NULL;
2095
2096    // Allocate the local script variables to use for this script.
2097    new_script_vars(script_items.ga_len);
2098
2099    si->sn_prof_on = false;
2100  }
2101  SCRIPT_ITEM(sid)->sn_name = name;
2102  return SCRIPT_ITEM(sid);
2103}
2104
2105/// Initialization for sourcing lines from the current buffer. Reads all the
2106/// lines from the buffer and stores it in the cookie grow array.
2107/// Returns a pointer to the name ":source buffer=<n>" on success and NULL on failure.
2108static char *do_source_buffer_init(source_cookie_T *sp, const exarg_T *eap, bool ex_lua)
2109  FUNC_ATTR_NONNULL_ALL
2110{
2111  if (curbuf == NULL) {
2112    return NULL;
2113  }
2114
2115  char *fname;
2116  if (curbuf->b_ffname != NULL) {
2117    fname = xstrdup(curbuf->b_ffname);
2118  } else {
2119    if (ex_lua) {
2120      // Use ":{range}lua buffer=<num>" as the script name
2121      snprintf(IObuff, IOSIZE, ":{range}lua buffer=%d", curbuf->b_fnum);
2122    } else {
2123      // Use ":source buffer=<num>" as the script name
2124      snprintf(IObuff, IOSIZE, ":source buffer=%d", curbuf->b_fnum);
2125    }
2126    fname = xstrdup(IObuff);
2127  }
2128
2129  ga_init(&sp->buflines, sizeof(char *), 100);
2130  // Copy the lines from the buffer into a grow array
2131  for (linenr_T curr_lnum = eap->line1; curr_lnum <= eap->line2; curr_lnum++) {
2132    GA_APPEND(char *, &sp->buflines, xstrdup(ml_get(curr_lnum)));
2133  }
2134  sp->buf_lnum = 0;
2135  sp->source_from_buf_or_str = true;
2136  // When sourcing a range of lines from a buffer, use buffer line number.
2137  sp->sourcing_lnum = eap->line1 - 1;
2138
2139  return fname;
2140}
2141
2142/// Initialization for sourcing lines from a string. Reads all the
2143/// lines from the string and stores it in the cookie grow array.
2144static void do_source_str_init(source_cookie_T *sp, const char *str)
2145  FUNC_ATTR_NONNULL_ALL
2146{
2147  ga_init(&sp->buflines, sizeof(char *), 100);
2148  // Copy the lines from the string into a grow array
2149  while (*str != NUL) {
2150    const char *eol = skip_to_newline(str);
2151    GA_APPEND(char *, &sp->buflines, xmemdupz(str, (size_t)(eol - str)));
2152    str = eol + (*eol != NUL);
2153  }
2154  sp->buf_lnum = 0;
2155  sp->source_from_buf_or_str = true;
2156}
2157
2158void cmd_source_buffer(const exarg_T *const eap, bool ex_lua)
2159  FUNC_ATTR_NONNULL_ALL
2160{
2161  do_source_ext(NULL, false, DOSO_NONE, NULL, eap, ex_lua, NULL);
2162}
2163
2164/// Executes lines in `str` as Ex commands.
2165///
2166/// @see do_source_ext()
2167int do_source_str(const char *str, char *traceback_name)
2168  FUNC_ATTR_NONNULL_ALL
2169{
2170  char *const sourcing_name = SOURCING_NAME;
2171  const linenr_T sourcing_lnum = SOURCING_LNUM;
2172  char sname_buf[256];
2173  if (sourcing_name != NULL) {
2174    snprintf(sname_buf, sizeof(sname_buf), "%s called at %s:%" PRIdLINENR,
2175             traceback_name, sourcing_name, sourcing_lnum);
2176    traceback_name = sname_buf;
2177  }
2178  return do_source_ext(traceback_name, false, DOSO_NONE, NULL, NULL, false, str);
2179}
2180
2181/// When fname is a .lua file nlua_exec_file() is invoked to source it.
2182/// Otherwise reads the file `fname` and executes its lines as Ex commands.
2183///
2184/// This function may be called recursively!
2185///
2186/// @see do_source_str
2187///
2188/// @param fname        if NULL, source from the current buffer
2189/// @param check_other  check for .vimrc and _vimrc
2190/// @param is_vimrc     DOSO_ value
2191/// @param ret_sid      if not NULL and we loaded the script before, don't load it again
2192/// @param eap          used when sourcing lines from a buffer instead of a file
2193/// @param str          if not NULL, source from the given string
2194///
2195/// @return  FAIL if file could not be opened, OK otherwise
2196///
2197/// If a scriptitem_T was found or created "*ret_sid" is set to the SID.
2198static int do_source_ext(char *const fname, const bool check_other, const int is_vimrc,
2199                         int *const ret_sid, const exarg_T *const eap, const bool ex_lua,
2200                         const char *const str)
2201{
2202  source_cookie_T cookie;
2203  uint8_t *firstline = NULL;
2204  int retval = FAIL;
2205  int save_debug_break_level = debug_break_level;
2206  scriptitem_T *si = NULL;
2207  proftime_T wait_start;
2208  bool trigger_source_post = false;
2209  ESTACK_CHECK_DECLARATION;
2210
2211  CLEAR_FIELD(cookie);
2212  char *fname_exp = NULL;
2213  if (fname == NULL) {
2214    assert(str == NULL);
2215    // sourcing lines from a buffer
2216    fname_exp = do_source_buffer_init(&cookie, eap, ex_lua);
2217    if (fname_exp == NULL) {
2218      return FAIL;
2219    }
2220  } else if (str != NULL) {
2221    do_source_str_init(&cookie, str);
2222    fname_exp = xstrdup(fname);
2223  } else {
2224    char *p = expand_env_save(fname);
2225    if (p == NULL) {
2226      return retval;
2227    }
2228    fname_exp = fix_fname(p);
2229    xfree(p);
2230    if (fname_exp == NULL) {
2231      return retval;
2232    }
2233    if (os_isdir(fname_exp)) {
2234      smsg(0, _("Cannot source a directory: \"%s\""), fname);
2235      goto theend;
2236    }
2237  }
2238
2239  // See if we loaded this script before.
2240  int sid = str != NULL ? SID_STR : find_script_by_name(fname_exp);
2241  if (sid > 0 && ret_sid != NULL) {
2242    // Already loaded and no need to load again, return here.
2243    *ret_sid = sid;
2244    retval = OK;
2245    goto theend;
2246  }
2247
2248  if (str == NULL) {
2249    // Apply SourceCmd autocommands, they should get the file and source it.
2250    if (has_autocmd(EVENT_SOURCECMD, fname_exp, NULL)
2251        && apply_autocmds(EVENT_SOURCECMD, fname_exp, fname_exp,
2252                          false, curbuf)) {
2253      retval = aborting() ? FAIL : OK;
2254      if (retval == OK) {
2255        // Apply SourcePost autocommands.
2256        apply_autocmds(EVENT_SOURCEPOST, fname_exp, fname_exp, false, curbuf);
2257      }
2258      goto theend;
2259    }
2260
2261    // Apply SourcePre autocommands, they may get the file.
2262    apply_autocmds(EVENT_SOURCEPRE, fname_exp, fname_exp, false, curbuf);
2263  }
2264
2265  if (!cookie.source_from_buf_or_str) {
2266    cookie.fp = fopen_noinh_readbin(fname_exp);
2267  }
2268  if (cookie.fp == NULL && check_other) {
2269    // Try again, replacing file name ".nvimrc" by "_nvimrc" or vice versa,
2270    // and ".exrc" by "_exrc" or vice versa.
2271    char *p = path_tail(fname_exp);
2272    if ((*p == '.' || *p == '_')
2273        && (STRICMP(p + 1, "nvimrc") == 0 || STRICMP(p + 1, "exrc") == 0)) {
2274      *p = (*p == '_') ? '.' : '_';
2275      cookie.fp = fopen_noinh_readbin(fname_exp);
2276    }
2277  }
2278
2279  if (cookie.fp == NULL && !cookie.source_from_buf_or_str) {
2280    if (p_verbose > 1) {
2281      verbose_enter();
2282      if (SOURCING_NAME == NULL) {
2283        smsg(0, _("could not source \"%s\""), fname);
2284      } else {
2285        smsg(0, _("line %" PRId64 ": could not source \"%s\""),
2286             (int64_t)SOURCING_LNUM, fname);
2287      }
2288      verbose_leave();
2289    }
2290    goto theend;
2291  }
2292
2293  // The file exists.
2294  // - In verbose mode, give a message.
2295  // - For a vimrc file, may want to call vimrc_found().
2296  if (p_verbose > 1) {
2297    verbose_enter();
2298    if (SOURCING_NAME == NULL) {
2299      smsg(0, _("sourcing \"%s\""), fname);
2300    } else {
2301      smsg(0, _("line %" PRId64 ": sourcing \"%s\""), (int64_t)SOURCING_LNUM, fname);
2302    }
2303    verbose_leave();
2304  }
2305  if (is_vimrc == DOSO_VIMRC) {
2306    vimrc_found(fname_exp, "MYVIMRC");
2307  }
2308
2309#ifdef USE_CRNL
2310  // If no automatic file format: Set default to CR-NL.
2311  if (*p_ffs == NUL) {
2312    cookie.fileformat = EOL_DOS;
2313  } else {
2314    cookie.fileformat = EOL_UNKNOWN;
2315  }
2316#endif
2317
2318  // Check if this script has a breakpoint.
2319  cookie.breakpoint = dbg_find_breakpoint(true, fname_exp, 0);
2320  cookie.fname = fname_exp;
2321  cookie.dbg_tick = debug_tick;
2322
2323  cookie.level = ex_nesting_level;
2324
2325  // start measuring script load time if --startuptime was passed and
2326  // time_fd was successfully opened afterwards.
2327  proftime_T rel_time;
2328  proftime_T start_time;
2329  FILE * const l_time_fd = time_fd;
2330  if (l_time_fd != NULL) {
2331    time_push(&rel_time, &start_time);
2332  }
2333
2334  const int l_do_profiling = do_profiling;
2335  if (l_do_profiling == PROF_YES) {
2336    prof_child_enter(&wait_start);    // entering a child now
2337  }
2338
2339  // Don't use local function variables, if called from a function.
2340  // Also starts profiling timer for nested script.
2341  funccal_entry_T funccalp_entry;
2342  save_funccal(&funccalp_entry);
2343
2344  const sctx_T save_current_sctx = current_sctx;
2345
2346  // Always use a new sequence number.
2347  current_sctx.sc_seq = ++last_current_SID_seq;
2348
2349  if (sid > 0) {
2350    // loading the same script again
2351    si = SCRIPT_ITEM(sid);
2352  } else if (str == NULL) {
2353    // It's new, generate a new SID.
2354    si = new_script_item(fname_exp, &sid);
2355    si->sn_lua = path_with_extension(fname_exp, "lua");
2356    fname_exp = xstrdup(si->sn_name);  // used for autocmd
2357    if (ret_sid != NULL) {
2358      *ret_sid = sid;
2359    }
2360  }
2361  // Sourcing a string doesn't allocate a script item immediately.
2362  assert((si != NULL) == (str == NULL));
2363
2364  // Don't change sc_sid to SID_STR when sourcing a string from a Lua script,
2365  // as keeping the current sc_sid allows more useful :verbose messages.
2366  if (str == NULL || !script_is_lua(current_sctx.sc_sid)) {
2367    current_sctx.sc_sid = sid;
2368    current_sctx.sc_lnum = 0;
2369  }
2370
2371  // Keep the sourcing name/lnum, for recursive calls.
2372  estack_push(ETYPE_SCRIPT, si != NULL ? si->sn_name : fname_exp, 0);
2373  ESTACK_CHECK_SETUP;
2374
2375  if (l_do_profiling == PROF_YES && si != NULL) {
2376    bool forceit = false;
2377
2378    // Check if we do profiling for this script.
2379    if (!si->sn_prof_on && has_profiling(true, si->sn_name, &forceit)) {
2380      profile_init(si);
2381      si->sn_pr_force = forceit;
2382    }
2383    if (si->sn_prof_on) {
2384      si->sn_pr_count++;
2385      si->sn_pr_start = profile_start();
2386      si->sn_pr_children = profile_zero();
2387    }
2388  }
2389
2390  cookie.conv.vc_type = CONV_NONE;              // no conversion
2391
2392  // Check if treesitter detects this range as Lua (for injections like vimdoc codeblocks)
2393  bool ts_lua = false;
2394  if (fname == NULL && eap != NULL && !ex_lua
2395      && !strequal(curbuf->b_p_ft, "lua")
2396      && !(curbuf->b_fname && path_with_extension(curbuf->b_fname, "lua"))) {
2397    MAXSIZE_TEMP_ARRAY(args, 3);
2398    ADD_C(args, INTEGER_OBJ(curbuf->handle));
2399    ADD_C(args, INTEGER_OBJ(eap->line1));
2400    ADD_C(args, INTEGER_OBJ(eap->line2));
2401    Error err = ERROR_INIT;
2402    Object result = NLUA_EXEC_STATIC("return require('vim._core.util').source_is_lua(...)",
2403                                     args, kRetNilBool, NULL, &err);
2404    if (!ERROR_SET(&err) && LUARET_TRUTHY(result)) {
2405      ts_lua = true;
2406    }
2407    api_clear_error(&err);
2408  }
2409
2410  if (fname == NULL
2411      && (ex_lua || ts_lua || strequal(curbuf->b_p_ft, "lua")
2412          || (curbuf->b_fname && path_with_extension(curbuf->b_fname, "lua")))) {
2413    // Source lines from the current buffer as lua
2414    nlua_exec_ga(&cookie.buflines, fname_exp);
2415  } else if (si != NULL && si->sn_lua) {
2416    // Source the file as lua
2417    nlua_exec_file(fname_exp);
2418  } else {
2419    // Read the first line so we can check for a UTF-8 BOM.
2420    firstline = (uint8_t *)getsourceline(0, (void *)&cookie, 0, true);
2421    if (firstline != NULL && strlen((char *)firstline) >= 3 && firstline[0] == 0xef
2422        && firstline[1] == 0xbb && firstline[2] == 0xbf) {
2423      // Found BOM; setup conversion, skip over BOM and recode the line.
2424      convert_setup(&cookie.conv, "utf-8", p_enc);
2425      char *p = string_convert(&cookie.conv, (char *)firstline + 3, NULL);
2426      if (p == NULL) {
2427        p = xstrdup((char *)firstline + 3);
2428      }
2429      xfree(firstline);
2430      firstline = (uint8_t *)p;
2431    }
2432    // Call do_cmdline, which will call getsourceline() to get the lines.
2433    do_cmdline((char *)firstline, getsourceline, (void *)&cookie,
2434               DOCMD_VERBOSE|DOCMD_NOWAIT|DOCMD_REPEAT);
2435  }
2436  retval = OK;
2437
2438  if (l_do_profiling == PROF_YES && si != NULL) {
2439    // Get "si" again, "script_items" may have been reallocated.
2440    si = SCRIPT_ITEM(current_sctx.sc_sid);
2441    if (si->sn_prof_on) {
2442      si->sn_pr_start = profile_end(si->sn_pr_start);
2443      si->sn_pr_start = profile_sub_wait(wait_start, si->sn_pr_start);
2444      si->sn_pr_total = profile_add(si->sn_pr_total, si->sn_pr_start);
2445      si->sn_pr_self = profile_self(si->sn_pr_self, si->sn_pr_start,
2446                                    si->sn_pr_children);
2447    }
2448  }
2449
2450  if (got_int) {
2451    emsg(_(e_interr));
2452  }
2453  ESTACK_CHECK_NOW;
2454  estack_pop();
2455  if (p_verbose > 1) {
2456    verbose_enter();
2457    smsg(0, _("finished sourcing %s"), fname);
2458    if (SOURCING_NAME != NULL) {
2459      smsg(0, _("continuing in %s"), SOURCING_NAME);
2460    }
2461    verbose_leave();
2462  }
2463
2464  if (l_time_fd != NULL) {
2465    vim_snprintf(IObuff, IOSIZE, "sourcing %s", fname);
2466    time_msg(IObuff, &start_time);
2467    time_pop(rel_time);
2468  }
2469
2470  if (!got_int) {
2471    trigger_source_post = true;
2472  }
2473
2474  // After a "finish" in debug mode, need to break at first command of next
2475  // sourced file.
2476  if (save_debug_break_level > ex_nesting_level
2477      && debug_break_level == ex_nesting_level) {
2478    debug_break_level++;
2479  }
2480
2481  current_sctx = save_current_sctx;
2482  restore_funccal();
2483  if (l_do_profiling == PROF_YES) {
2484    prof_child_exit(&wait_start);    // leaving a child now
2485  }
2486  if (cookie.fp != NULL) {
2487    fclose(cookie.fp);
2488  }
2489  if (cookie.source_from_buf_or_str) {
2490    ga_clear_strings(&cookie.buflines);
2491  }
2492  xfree(cookie.nextline);
2493  xfree(firstline);
2494  convert_setup(&cookie.conv, NULL, NULL);
2495
2496  if (str == NULL && trigger_source_post) {
2497    apply_autocmds(EVENT_SOURCEPOST, fname_exp, fname_exp, false, curbuf);
2498  }
2499
2500theend:
2501  xfree(fname_exp);
2502  return retval;
2503}
2504
2505/// @param check_other  check for .vimrc and _vimrc
2506/// @param is_vimrc     DOSO_ value
2507int do_source(char *fname, bool check_other, int is_vimrc, int *ret_sid)
2508{
2509  return do_source_ext(fname, check_other, is_vimrc, ret_sid, NULL, false, NULL);
2510}
2511
2512/// Checks if the script with the given script ID is a Lua script.
2513bool script_is_lua(scid_T sid)
2514{
2515  if (sid == SID_LUA) {
2516    return true;
2517  }
2518  if (!SCRIPT_ID_VALID(sid)) {
2519    return false;
2520  }
2521  return SCRIPT_ITEM(sid)->sn_lua;
2522}
2523
2524/// Find an already loaded script "name".
2525/// If found returns its script ID.  If not found returns -1.
2526int find_script_by_name(char *name)
2527{
2528  assert(script_items.ga_len >= 0);
2529  for (int sid = script_items.ga_len; sid > 0; sid--) {
2530    // We used to check inode here, but that doesn't work:
2531    // - If a script is edited and written, it may get a different
2532    //   inode number, even though to the user it is the same script.
2533    // - If a script is deleted and another script is written, with a
2534    //   different name, the inode may be re-used.
2535    scriptitem_T *si = SCRIPT_ITEM(sid);
2536    if (si->sn_name != NULL && path_equal(si->sn_name, name, kPathCmpLiteral)) {
2537      return sid;
2538    }
2539  }
2540  return -1;
2541}
2542
2543/// ":scriptnames"
2544void ex_scriptnames(exarg_T *eap)
2545{
2546  if (eap->addr_count > 0 || *eap->arg != NUL) {
2547    // :script {scriptId}: edit the script
2548    if (eap->addr_count > 0 && !SCRIPT_ID_VALID(eap->line2)) {
2549      emsg(_(e_invarg));
2550    } else {
2551      if (eap->addr_count > 0) {
2552        eap->arg = SCRIPT_ITEM(eap->line2)->sn_name;
2553      } else {
2554        expand_env(eap->arg, NameBuff, MAXPATHL);
2555        eap->arg = NameBuff;
2556        TO_SLASH(eap->arg);
2557      }
2558      do_exedit(eap, NULL);
2559    }
2560    return;
2561  }
2562
2563  msg_ext_set_kind("list_cmd");
2564  for (int i = 1; i <= script_items.ga_len && !got_int; i++) {
2565    if (SCRIPT_ITEM(i)->sn_name != NULL) {
2566      home_replace(NULL, SCRIPT_ITEM(i)->sn_name, NameBuff, MAXPATHL, true);
2567      vim_snprintf(IObuff, IOSIZE, "%3d: %s", i, NameBuff);
2568      if (!message_filtered(IObuff)) {
2569        if (msg_col > 0) {
2570          msg_putchar('\n');
2571        }
2572        msg_outtrans(IObuff, 0, false);
2573        line_breakcheck();
2574      }
2575    }
2576  }
2577}
2578
2579/// Get a pointer to a script name.  Used for ":verbose set".
2580/// Message appended to "Last set from "
2581///
2582/// @param should_free  if non-NULL and the script name is a file path, call
2583///                     home_replace_save() on it and set *should_free to true.
2584char *get_scriptname(sctx_T script_ctx, bool *should_free)
2585{
2586  if (should_free != NULL) {
2587    *should_free = false;
2588  }
2589
2590  switch (script_ctx.sc_sid) {
2591  case SID_MODELINE:
2592    return _("modeline");
2593  case SID_CMDARG:
2594    return _("--cmd argument");
2595  case SID_CARG:
2596    return _("-c argument");
2597  case SID_ENV:
2598    return _("environment variable");
2599  case SID_ERROR:
2600    return _("error handler");
2601  case SID_WINLAYOUT:
2602    return _("changed window size");
2603  case SID_LUA:
2604    return _("Lua");
2605  case SID_API_CLIENT:
2606    snprintf(IObuff, IOSIZE, _("API client (channel id %" PRIu64 ")"), script_ctx.sc_chan);
2607    return IObuff;
2608  case SID_STR:
2609    return _("anonymous :source");
2610  default: {
2611    char *const sname = SCRIPT_ITEM(script_ctx.sc_sid)->sn_name;
2612    if (sname == NULL) {
2613      snprintf(IObuff, IOSIZE, _("anonymous :source (script id %d)"),
2614               script_ctx.sc_sid);
2615      return IObuff;
2616    }
2617    if (should_free != NULL) {
2618      *should_free = true;
2619      return home_replace_save(NULL, sname);
2620    } else {
2621      return sname;
2622    }
2623  }
2624  }
2625}
2626
2627#ifdef EXITFREE
2628void free_scriptnames(void)
2629{
2630  profile_reset();
2631
2632# define FREE_SCRIPTNAME(item) \
2633  do { \
2634    scriptitem_T *_si = *(item); \
2635    /* the variables themselves are cleared in evalvars_clear() */ \
2636    xfree(_si->sn_vars); \
2637    xfree(_si->sn_name); \
2638    ga_clear(&_si->sn_prl_ga); \
2639    xfree(_si); \
2640  } while (0) \
2641
2642  GA_DEEP_CLEAR(&script_items, scriptitem_T *, FREE_SCRIPTNAME);
2643}
2644#endif
2645
2646void free_autoload_scriptnames(void)
2647{
2648  ga_clear_strings(&ga_loaded);
2649}
2650
2651linenr_T get_sourced_lnum(LineGetter fgetline, void *cookie)
2652  FUNC_ATTR_PURE
2653{
2654  return fgetline == getsourceline
2655         ? ((source_cookie_T *)cookie)->sourcing_lnum
2656         : SOURCING_LNUM;
2657}
2658
2659/// Return a List of script-local functions defined in the script with id "sid".
2660static list_T *get_script_local_funcs(scid_T sid)
2661{
2662  hashtab_T *const functbl = func_tbl_get();
2663  list_T *l = tv_list_alloc((ptrdiff_t)functbl->ht_used);
2664
2665  // Iterate through all the functions in the global function hash table
2666  // looking for functions with script ID "sid".
2667  HASHTAB_ITER(functbl, hi, {
2668    const ufunc_T *const fp = HI2UF(hi);
2669    // Add functions with script id == "sid"
2670    if (fp->uf_script_ctx.sc_sid == sid) {
2671      const char *const name = fp->uf_name_exp != NULL ? fp->uf_name_exp : fp->uf_name;
2672      tv_list_append_string(l, name, -1);
2673    }
2674  });
2675
2676  return l;
2677}
2678
2679/// "getscriptinfo()" function
2680void f_getscriptinfo(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
2681{
2682  tv_list_alloc_ret(rettv, script_items.ga_len);
2683
2684  if (tv_check_for_opt_dict_arg(argvars, 0) == FAIL) {
2685    return;
2686  }
2687
2688  list_T *l = rettv->vval.v_list;
2689
2690  regmatch_T regmatch = {
2691    .regprog = NULL,
2692    .rm_ic = p_ic,
2693  };
2694  bool filterpat = false;
2695  varnumber_T sid = -1;
2696
2697  char *pat = NULL;
2698  if (argvars[0].v_type == VAR_DICT) {
2699    dictitem_T *sid_di = tv_dict_find(argvars[0].vval.v_dict, S_LEN("sid"));
2700    if (sid_di != NULL) {
2701      bool error = false;
2702      sid = tv_get_number_chk(&sid_di->di_tv, &error);
2703      if (error) {
2704        return;
2705      }
2706      if (sid <= 0) {
2707        semsg(_(e_invargNval), "sid", tv_get_string(&sid_di->di_tv));
2708        return;
2709      }
2710    } else {
2711      pat = tv_dict_get_string(argvars[0].vval.v_dict, "name", true);
2712      if (pat != NULL) {
2713        regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
2714      }
2715      if (regmatch.regprog != NULL) {
2716        filterpat = true;
2717      }
2718    }
2719  }
2720
2721  for (varnumber_T i = sid > 0 ? sid : 1;
2722       (i == sid || sid <= 0) && i <= script_items.ga_len; i++) {
2723    scriptitem_T *si = SCRIPT_ITEM(i);
2724
2725    if (si->sn_name == NULL) {
2726      continue;
2727    }
2728
2729    if (filterpat && !vim_regexec(&regmatch, si->sn_name, 0)) {
2730      continue;
2731    }
2732
2733    dict_T *d = tv_dict_alloc();
2734    tv_list_append_dict(l, d);
2735    tv_dict_add_str(d, S_LEN("name"), si->sn_name);
2736    tv_dict_add_nr(d, S_LEN("sid"), i);
2737    tv_dict_add_nr(d, S_LEN("version"), 1);
2738    // Vim9 autoload script (:h vim9-autoload), not applicable to Nvim.
2739    tv_dict_add_bool(d, S_LEN("autoload"), false);
2740
2741    // When a script ID is specified, return information about only the
2742    // specified script, and add the script-local variables and functions.
2743    if (sid > 0) {
2744      dict_T *var_dict = tv_dict_copy(NULL, &si->sn_vars->sv_dict, true, get_copyID());
2745      tv_dict_add_dict(d, S_LEN("variables"), var_dict);
2746      tv_dict_add_list(d, S_LEN("functions"), get_script_local_funcs((scid_T)sid));
2747    }
2748  }
2749
2750  vim_regfree(regmatch.regprog);
2751  xfree(pat);
2752}
2753
2754/// Get one full line from a sourced file.
2755/// Called by do_cmdline() when it's called from do_source().
2756///
2757/// @return pointer to the line in allocated memory, or NULL for end-of-file or
2758///         some error.
2759char *getsourceline(int c, void *cookie, int indent, bool do_concat)
2760{
2761  source_cookie_T *sp = (source_cookie_T *)cookie;
2762  char *line;
2763
2764  // If breakpoints have been added/deleted need to check for it.
2765  if ((sp->dbg_tick < debug_tick) && !sp->source_from_buf_or_str) {
2766    sp->breakpoint = dbg_find_breakpoint(true, sp->fname, SOURCING_LNUM);
2767    sp->dbg_tick = debug_tick;
2768  }
2769  if (do_profiling == PROF_YES) {
2770    script_line_end();
2771  }
2772  // Set the current sourcing line number.
2773  SOURCING_LNUM = sp->sourcing_lnum + 1;
2774  // Get current line.  If there is a read-ahead line, use it, otherwise get
2775  // one now.  "fp" is NULL if actually using a string.
2776  if (sp->finished || (!sp->source_from_buf_or_str && sp->fp == NULL)) {
2777    line = NULL;
2778  } else if (sp->nextline == NULL) {
2779    line = get_one_sourceline(sp);
2780  } else {
2781    line = sp->nextline;
2782    sp->nextline = NULL;
2783    sp->sourcing_lnum++;
2784  }
2785  if (line != NULL && do_profiling == PROF_YES) {
2786    script_line_start();
2787  }
2788
2789  // Only concatenate lines starting with a \ when 'cpoptions' doesn't
2790  // contain the 'C' flag.
2791  if (line != NULL && do_concat && (vim_strchr(p_cpo, kCpoConcat) == NULL)) {
2792    char *p;
2793    // compensate for the one line read-ahead
2794    sp->sourcing_lnum--;
2795
2796    // Get the next line and concatenate it when it starts with a
2797    // backslash. We always need to read the next line, keep it in
2798    // sp->nextline.
2799    // Also check for a comment in between continuation lines: "\ .
2800    sp->nextline = get_one_sourceline(sp);
2801    if (sp->nextline != NULL
2802        && (*(p = skipwhite(sp->nextline)) == '\\'
2803            || (p[0] == '"' && p[1] == '\\' && p[2] == ' '))) {
2804      garray_T ga;
2805
2806      ga_init(&ga, (int)sizeof(char), 400);
2807      ga_concat(&ga, line);
2808      while (sp->nextline != NULL
2809             && concat_continued_line(&ga, 400, sp->nextline, strlen(sp->nextline))) {
2810        xfree(sp->nextline);
2811        sp->nextline = get_one_sourceline(sp);
2812      }
2813      ga_append(&ga, NUL);
2814      xfree(line);
2815      line = ga.ga_data;
2816    }
2817  }
2818
2819  if (line != NULL && sp->conv.vc_type != CONV_NONE) {
2820    // Convert the encoding of the script line.
2821    char *s = string_convert(&sp->conv, line, NULL);
2822    if (s != NULL) {
2823      xfree(line);
2824      line = s;
2825    }
2826  }
2827
2828  // Did we encounter a breakpoint?
2829  if (!sp->source_from_buf_or_str
2830      && sp->breakpoint != 0 && sp->breakpoint <= SOURCING_LNUM) {
2831    dbg_breakpoint(sp->fname, SOURCING_LNUM);
2832    // Find next breakpoint.
2833    sp->breakpoint = dbg_find_breakpoint(true, sp->fname, SOURCING_LNUM);
2834    sp->dbg_tick = debug_tick;
2835  }
2836
2837  return line;
2838}
2839
2840static char *get_one_sourceline(source_cookie_T *sp)
2841{
2842  garray_T ga;
2843  int len;
2844  int c;
2845  char *buf;
2846#ifdef USE_CRNL
2847  bool has_cr;                           // CR-LF found
2848#endif
2849  bool have_read = false;
2850
2851  // use a growarray to store the sourced line
2852  ga_init(&ga, 1, 250);
2853
2854  // Loop until there is a finished line (or end-of-file).
2855  sp->sourcing_lnum++;
2856  while (true) {
2857    // make room to read at least 120 (more) characters
2858    ga_grow(&ga, 120);
2859    if (sp->source_from_buf_or_str) {
2860      if (sp->buf_lnum >= sp->buflines.ga_len) {
2861        break;              // all the lines are processed
2862      }
2863      ga_concat(&ga, ((char **)sp->buflines.ga_data)[sp->buf_lnum]);
2864      sp->buf_lnum++;
2865      ga_grow(&ga, 1);
2866      buf = (char *)ga.ga_data;
2867      buf[ga.ga_len++] = NUL;
2868      len = ga.ga_len;
2869    } else {
2870      buf = ga.ga_data;
2871retry:
2872      errno = 0;
2873      if (fgets(buf + ga.ga_len, ga.ga_maxlen - ga.ga_len, sp->fp) == NULL) {
2874        if (errno == EINTR) {
2875          goto retry;
2876        }
2877        break;
2878      }
2879      len = ga.ga_len + (int)strlen(buf + ga.ga_len);
2880    }
2881#ifdef USE_CRNL
2882    // Ignore a trailing CTRL-Z, when in Dos mode. Only recognize the
2883    // CTRL-Z by its own, or after a NL.
2884    if ((len == 1 || (len >= 2 && buf[len - 2] == '\n'))
2885        && sp->fileformat == EOL_DOS
2886        && buf[len - 1] == Ctrl_Z) {
2887      buf[len - 1] = NUL;
2888      break;
2889    }
2890#endif
2891
2892    have_read = true;
2893    ga.ga_len = len;
2894
2895    // If reading from a file and the line was longer than the buffer, read more.
2896    if (!sp->source_from_buf_or_str
2897        && ga.ga_maxlen - ga.ga_len == 1 && buf[len - 1] != '\n') {
2898      continue;
2899    }
2900
2901    if (len >= 1 && buf[len - 1] == '\n') {     // remove trailing NL
2902#ifdef USE_CRNL
2903      has_cr = (len >= 2 && buf[len - 2] == '\r');
2904      if (sp->fileformat == EOL_UNKNOWN) {
2905        if (has_cr) {
2906          sp->fileformat = EOL_DOS;
2907        } else {
2908          sp->fileformat = EOL_UNIX;
2909        }
2910      }
2911
2912      if (sp->fileformat == EOL_DOS) {
2913        if (has_cr) {               // replace trailing CR
2914          buf[len - 2] = '\n';
2915          len--;
2916          ga.ga_len--;
2917        } else {          // lines like ":map xx yy^M" will have failed
2918          if (!sp->error) {
2919            msg_source(HL_ATTR(HLF_W));
2920            emsg(_("W15: Warning: Wrong line separator, ^M may be missing"));
2921          }
2922          sp->error = true;
2923          sp->fileformat = EOL_UNIX;
2924        }
2925      }
2926#endif
2927      // The '\n' is escaped if there is an odd number of ^V's just
2928      // before it, first set "c" just before the 'V's and then check
2929      // len&c parities (is faster than ((len-c)%2 == 0)) -- Acevedo
2930      for (c = len - 2; c >= 0 && buf[c] == Ctrl_V; c--) {}
2931      if ((len & 1) != (c & 1)) {       // escaped NL, read more
2932        sp->sourcing_lnum++;
2933        continue;
2934      }
2935
2936      buf[len - 1] = NUL;               // remove the NL
2937    }
2938
2939    // Check for ^C here now and then, so recursive :so can be broken.
2940    line_breakcheck();
2941    break;
2942  }
2943
2944  if (have_read) {
2945    return ga.ga_data;
2946  }
2947
2948  xfree(ga.ga_data);
2949  return NULL;
2950}
2951
2952/// Returns true if sourcing a script either from a file or a buffer or a string.
2953/// Otherwise returns false.
2954int sourcing_a_script(exarg_T *eap)
2955{
2956  return getline_equal(eap->ea_getline, eap->cookie, getsourceline);
2957}
2958
2959/// ":scriptencoding": Set encoding conversion for a sourced script.
2960/// Without the multi-byte feature it's simply ignored.
2961void ex_scriptencoding(exarg_T *eap)
2962{
2963  if (!sourcing_a_script(eap)) {
2964    emsg(_("E167: :scriptencoding used outside of a sourced file"));
2965    return;
2966  }
2967
2968  char *name = (*eap->arg != NUL) ? enc_canonize(eap->arg) : eap->arg;
2969
2970  // Setup for conversion from the specified encoding to 'encoding'.
2971  source_cookie_T *sp = (source_cookie_T *)getline_cookie(eap->ea_getline, eap->cookie);
2972  convert_setup(&sp->conv, name, p_enc);
2973
2974  if (name != eap->arg) {
2975    xfree(name);
2976  }
2977}
2978
2979/// ":finish": Mark a sourced file as finished.
2980void ex_finish(exarg_T *eap)
2981{
2982  if (sourcing_a_script(eap)) {
2983    do_finish(eap, false);
2984  } else {
2985    emsg(_("E168: :finish used outside of a sourced file"));
2986  }
2987}
2988
2989/// Mark a sourced file as finished.  Possibly makes the ":finish" pending.
2990/// Also called for a pending finish at the ":endtry" or after returning from
2991/// an extra do_cmdline().  "reanimate" is used in the latter case.
2992void do_finish(exarg_T *eap, bool reanimate)
2993{
2994  if (reanimate) {
2995    ((source_cookie_T *)getline_cookie(eap->ea_getline, eap->cookie))->finished = false;
2996  }
2997
2998  // Cleanup (and deactivate) conditionals, but stop when a try conditional
2999  // not in its finally clause (which then is to be executed next) is found.
3000  // In this case, make the ":finish" pending for execution at the ":endtry".
3001  // Otherwise, finish normally.
3002  int idx = cleanup_conditionals(eap->cstack, 0, true);
3003  if (idx >= 0) {
3004    eap->cstack->cs_pending[idx] = CSTP_FINISH;
3005    report_make_pending(CSTP_FINISH, NULL);
3006  } else {
3007    ((source_cookie_T *)getline_cookie(eap->ea_getline, eap->cookie))->finished = true;
3008  }
3009}
3010
3011/// @return  true when a sourced file had the ":finish" command: Don't give error
3012///          message for missing ":endif".
3013///          false when not sourcing a file.
3014bool source_finished(LineGetter fgetline, void *cookie)
3015{
3016  return getline_equal(fgetline, cookie, getsourceline)
3017         && ((source_cookie_T *)getline_cookie(fgetline, cookie))->finished;
3018}
3019
3020/// Return the autoload script name for a function or variable name
3021/// Caller must make sure that "name" contains AUTOLOAD_CHAR.
3022///
3023/// @param[in]  name  Variable/function name.
3024/// @param[in]  name_len  Name length.
3025///
3026/// @return [allocated] autoload script name.
3027char *autoload_name(const char *const name, const size_t name_len)
3028  FUNC_ATTR_MALLOC FUNC_ATTR_WARN_UNUSED_RESULT
3029{
3030  // Get the script file name: replace '#' with '/', append ".vim".
3031  char *const scriptname = xmalloc(name_len + sizeof("autoload/.vim"));
3032  memcpy(scriptname, "autoload/", sizeof("autoload/") - 1);
3033  memcpy(scriptname + sizeof("autoload/") - 1, name, name_len);
3034  size_t auchar_idx = 0;
3035  for (size_t i = sizeof("autoload/") - 1;
3036       i - sizeof("autoload/") + 1 < name_len;
3037       i++) {
3038    if (scriptname[i] == AUTOLOAD_CHAR) {
3039      scriptname[i] = '/';
3040      auchar_idx = i;
3041    }
3042  }
3043  memcpy(scriptname + auchar_idx, ".vim", sizeof(".vim"));
3044
3045  return scriptname;
3046}
3047
3048/// If name has a package name try autoloading the script for it
3049///
3050/// @param[in]  name  Variable/function name.
3051/// @param[in]  name_len  Name length.
3052/// @param[in]  reload  If true, load script again when already loaded.
3053///
3054/// @return true if a package was loaded.
3055bool script_autoload(const char *const name, const size_t name_len, const bool reload)
3056{
3057  // If there is no '#' after name[0] there is no package name.
3058  const char *p = memchr(name, AUTOLOAD_CHAR, name_len);
3059  if (p == NULL || p == name) {
3060    return false;
3061  }
3062
3063  bool ret = false;
3064  char *tofree = autoload_name(name, name_len);
3065  char *scriptname = tofree;
3066
3067  // Find the name in the list of previously loaded package names.  Skip
3068  // "autoload/", it's always the same.
3069  int i = 0;
3070  for (; i < ga_loaded.ga_len; i++) {
3071    if (strcmp(((char **)ga_loaded.ga_data)[i] + 9, scriptname + 9) == 0) {
3072      break;
3073    }
3074  }
3075  if (!reload && i < ga_loaded.ga_len) {
3076    ret = false;  // Was loaded already.
3077  } else {
3078    // Remember the name if it wasn't loaded already.
3079    if (i == ga_loaded.ga_len) {
3080      GA_APPEND(char *, &ga_loaded, scriptname);
3081      tofree = NULL;
3082    }
3083
3084    // Try loading the package from $VIMRUNTIME/autoload/<name>.vim
3085    // Use "ret_sid" to avoid loading the same script again.
3086    int ret_sid;
3087    if (do_in_runtimepath(scriptname, DIP_START, source_callback, &ret_sid) == OK) {
3088      ret = true;
3089    }
3090  }
3091
3092  xfree(tofree);
3093  return ret;
3094}