xref: /vim-8.2.3635/src/scriptfile.c (revision a0a0c414)
1 /* vi:set ts=8 sts=4 sw=4 noet:
2  *
3  * VIM - Vi IMproved	by Bram Moolenaar
4  *
5  * Do ":help uganda"  in Vim to read copying and usage conditions.
6  * Do ":help credits" in Vim to see a list of people who contributed.
7  * See README.txt for an overview of the Vim source code.
8  */
9 
10 /*
11  * scriptfile.c: functions for dealing with the runtime directories/files
12  */
13 
14 #include "vim.h"
15 
16 #if defined(FEAT_EVAL) || defined(PROTO)
17 // The names of packages that once were loaded are remembered.
18 static garray_T		ga_loaded = {0, 0, sizeof(char_u *), 4, NULL};
19 #endif
20 
21 /*
22  * Initialize the execution stack.
23  */
24     void
25 estack_init(void)
26 {
27     estack_T *entry;
28 
29     if (ga_grow(&exestack, 10) == FAIL)
30 	mch_exit(0);
31     entry = ((estack_T *)exestack.ga_data) + exestack.ga_len;
32     entry->es_type = ETYPE_TOP;
33     entry->es_name = NULL;
34     entry->es_lnum = 0;
35 #ifdef FEAT_EVAL
36     entry->es_info.ufunc = NULL;
37 #endif
38     ++exestack.ga_len;
39 }
40 
41 /*
42  * Add an item to the execution stack.
43  * Returns the new entry or NULL when out of memory.
44  */
45     estack_T *
46 estack_push(etype_T type, char_u *name, long lnum)
47 {
48     estack_T *entry;
49 
50     // If memory allocation fails then we'll pop more than we push, eventually
51     // at the top level it will be OK again.
52     if (ga_grow(&exestack, 1) == OK)
53     {
54 	entry = ((estack_T *)exestack.ga_data) + exestack.ga_len;
55 	entry->es_type = type;
56 	entry->es_name = name;
57 	entry->es_lnum = lnum;
58 #ifdef FEAT_EVAL
59 	entry->es_info.ufunc = NULL;
60 #endif
61 	++exestack.ga_len;
62 	return entry;
63     }
64     return NULL;
65 }
66 
67 #if defined(FEAT_EVAL) || defined(PROTO)
68 /*
69  * Add a user function to the execution stack.
70  */
71     void
72 estack_push_ufunc(ufunc_T *ufunc, long lnum)
73 {
74     estack_T *entry = estack_push(ETYPE_UFUNC,
75 	    ufunc->uf_name_exp != NULL
76 				  ? ufunc->uf_name_exp : ufunc->uf_name, lnum);
77     if (entry != NULL)
78 	entry->es_info.ufunc = ufunc;
79 }
80 
81 /*
82  * Return TRUE if "ufunc" with "lnum" is already at the top of the exe stack.
83  */
84     int
85 estack_top_is_ufunc(ufunc_T *ufunc, long lnum)
86 {
87     estack_T *entry;
88 
89     if (exestack.ga_len == 0)
90 	return FALSE;
91     entry = ((estack_T *)exestack.ga_data) + exestack.ga_len - 1;
92     return entry->es_type == ETYPE_UFUNC
93 	&& STRCMP( entry->es_name, ufunc->uf_name_exp != NULL
94 				    ? ufunc->uf_name_exp : ufunc->uf_name) == 0
95 	&& entry->es_lnum == lnum;
96 }
97 #endif
98 
99 /*
100  * Take an item off of the execution stack.
101  */
102     void
103 estack_pop(void)
104 {
105     if (exestack.ga_len > 1)
106 	--exestack.ga_len;
107 }
108 
109 /*
110  * Get the current value for <sfile> in allocated memory.
111  */
112     char_u *
113 estack_sfile(void)
114 {
115     estack_T	*entry;
116 #ifdef FEAT_EVAL
117     size_t	len;
118     int		idx;
119     char	*res;
120     size_t	done;
121 #endif
122 
123     entry = ((estack_T *)exestack.ga_data) + exestack.ga_len - 1;
124     if (entry->es_name == NULL)
125 	return NULL;
126 #ifdef FEAT_EVAL
127     if (entry->es_info.ufunc == NULL)
128 #endif
129 	return vim_strsave(entry->es_name);
130 
131 #ifdef FEAT_EVAL
132     // For a function we compose the call stack, as it was done in the past:
133     //   "function One[123]..Two[456]..Three"
134     len = STRLEN(entry->es_name) + 10;
135     for (idx = exestack.ga_len - 2; idx >= 0; --idx)
136     {
137 	entry = ((estack_T *)exestack.ga_data) + idx;
138 	if (entry->es_name == NULL || entry->es_info.ufunc == NULL)
139 	{
140 	    ++idx;
141 	    break;
142 	}
143 	len += STRLEN(entry->es_name) + 15;
144     }
145 
146     res = (char *)alloc((int)len);
147     if (res != NULL)
148     {
149 	STRCPY(res, "function ");
150 	while (idx < exestack.ga_len - 1)
151 	{
152 	    done = STRLEN(res);
153 	    entry = ((estack_T *)exestack.ga_data) + idx;
154 	    vim_snprintf(res + done, len - done, "%s[%ld]..",
155 					       entry->es_name, entry->es_lnum);
156 	    ++idx;
157 	}
158 	done = STRLEN(res);
159 	entry = ((estack_T *)exestack.ga_data) + idx;
160 	vim_snprintf(res + done, len - done, "%s", entry->es_name);
161     }
162     return (char_u *)res;
163 #endif
164 }
165 
166 /*
167  * ":runtime [what] {name}"
168  */
169     void
170 ex_runtime(exarg_T *eap)
171 {
172     char_u  *arg = eap->arg;
173     char_u  *p = skiptowhite(arg);
174     int	    len = (int)(p - arg);
175     int	    flags = eap->forceit ? DIP_ALL : 0;
176 
177     if (STRNCMP(arg, "START", len) == 0)
178     {
179 	flags += DIP_START + DIP_NORTP;
180 	arg = skipwhite(arg + len);
181     }
182     else if (STRNCMP(arg, "OPT", len) == 0)
183     {
184 	flags += DIP_OPT + DIP_NORTP;
185 	arg = skipwhite(arg + len);
186     }
187     else if (STRNCMP(arg, "PACK", len) == 0)
188     {
189 	flags += DIP_START + DIP_OPT + DIP_NORTP;
190 	arg = skipwhite(arg + len);
191     }
192     else if (STRNCMP(arg, "ALL", len) == 0)
193     {
194 	flags += DIP_START + DIP_OPT;
195 	arg = skipwhite(arg + len);
196     }
197 
198     source_runtime(arg, flags);
199 }
200 
201     static void
202 source_callback(char_u *fname, void *cookie)
203 {
204     (void)do_source(fname, FALSE, DOSO_NONE, cookie);
205 }
206 
207 /*
208  * Find the file "name" in all directories in "path" and invoke
209  * "callback(fname, cookie)".
210  * "name" can contain wildcards.
211  * When "flags" has DIP_ALL: source all files, otherwise only the first one.
212  * When "flags" has DIP_DIR: find directories instead of files.
213  * When "flags" has DIP_ERR: give an error message if there is no match.
214  *
215  * return FAIL when no file could be sourced, OK otherwise.
216  */
217     int
218 do_in_path(
219     char_u	*path,
220     char_u	*name,
221     int		flags,
222     void	(*callback)(char_u *fname, void *ck),
223     void	*cookie)
224 {
225     char_u	*rtp;
226     char_u	*np;
227     char_u	*buf;
228     char_u	*rtp_copy;
229     char_u	*tail;
230     int		num_files;
231     char_u	**files;
232     int		i;
233     int		did_one = FALSE;
234 #ifdef AMIGA
235     struct Process	*proc = (struct Process *)FindTask(0L);
236     APTR		save_winptr = proc->pr_WindowPtr;
237 
238     // Avoid a requester here for a volume that doesn't exist.
239     proc->pr_WindowPtr = (APTR)-1L;
240 #endif
241 
242     // Make a copy of 'runtimepath'.  Invoking the callback may change the
243     // value.
244     rtp_copy = vim_strsave(path);
245     buf = alloc(MAXPATHL);
246     if (buf != NULL && rtp_copy != NULL)
247     {
248 	if (p_verbose > 10 && name != NULL)
249 	{
250 	    verbose_enter();
251 	    smsg(_("Searching for \"%s\" in \"%s\""),
252 						 (char *)name, (char *)path);
253 	    verbose_leave();
254 	}
255 
256 	// Loop over all entries in 'runtimepath'.
257 	rtp = rtp_copy;
258 	while (*rtp != NUL && ((flags & DIP_ALL) || !did_one))
259 	{
260 	    size_t buflen;
261 
262 	    // Copy the path from 'runtimepath' to buf[].
263 	    copy_option_part(&rtp, buf, MAXPATHL, ",");
264 	    buflen = STRLEN(buf);
265 
266 	    // Skip after or non-after directories.
267 	    if (flags & (DIP_NOAFTER | DIP_AFTER))
268 	    {
269 		int is_after = buflen >= 5
270 				     && STRCMP(buf + buflen - 5, "after") == 0;
271 
272 		if ((is_after && (flags & DIP_NOAFTER))
273 			|| (!is_after && (flags & DIP_AFTER)))
274 		    continue;
275 	    }
276 
277 	    if (name == NULL)
278 	    {
279 		(*callback)(buf, (void *) &cookie);
280 		if (!did_one)
281 		    did_one = (cookie == NULL);
282 	    }
283 	    else if (buflen + STRLEN(name) + 2 < MAXPATHL)
284 	    {
285 		add_pathsep(buf);
286 		tail = buf + STRLEN(buf);
287 
288 		// Loop over all patterns in "name"
289 		np = name;
290 		while (*np != NUL && ((flags & DIP_ALL) || !did_one))
291 		{
292 		    // Append the pattern from "name" to buf[].
293 		    copy_option_part(&np, tail, (int)(MAXPATHL - (tail - buf)),
294 								       "\t ");
295 
296 		    if (p_verbose > 10)
297 		    {
298 			verbose_enter();
299 			smsg(_("Searching for \"%s\""), buf);
300 			verbose_leave();
301 		    }
302 
303 		    // Expand wildcards, invoke the callback for each match.
304 		    if (gen_expand_wildcards(1, &buf, &num_files, &files,
305 				  (flags & DIP_DIR) ? EW_DIR : EW_FILE) == OK)
306 		    {
307 			for (i = 0; i < num_files; ++i)
308 			{
309 			    (*callback)(files[i], cookie);
310 			    did_one = TRUE;
311 			    if (!(flags & DIP_ALL))
312 				break;
313 			}
314 			FreeWild(num_files, files);
315 		    }
316 		}
317 	    }
318 	}
319     }
320     vim_free(buf);
321     vim_free(rtp_copy);
322     if (!did_one && name != NULL)
323     {
324 	char *basepath = path == p_rtp ? "runtimepath" : "packpath";
325 
326 	if (flags & DIP_ERR)
327 	    semsg(_(e_dirnotf), basepath, name);
328 	else if (p_verbose > 0)
329 	{
330 	    verbose_enter();
331 	    smsg(_("not found in '%s': \"%s\""), basepath, name);
332 	    verbose_leave();
333 	}
334     }
335 
336 #ifdef AMIGA
337     proc->pr_WindowPtr = save_winptr;
338 #endif
339 
340     return did_one ? OK : FAIL;
341 }
342 
343 /*
344  * Find "name" in "path".  When found, invoke the callback function for
345  * it: callback(fname, "cookie")
346  * When "flags" has DIP_ALL repeat for all matches, otherwise only the first
347  * one is used.
348  * Returns OK when at least one match found, FAIL otherwise.
349  *
350  * If "name" is NULL calls callback for each entry in "path". Cookie is
351  * passed by reference in this case, setting it to NULL indicates that callback
352  * has done its job.
353  */
354     static int
355 do_in_path_and_pp(
356     char_u	*path,
357     char_u	*name,
358     int		flags,
359     void	(*callback)(char_u *fname, void *ck),
360     void	*cookie)
361 {
362     int		done = FAIL;
363     char_u	*s;
364     int		len;
365     char	*start_dir = "pack/*/start/*/%s";
366     char	*opt_dir = "pack/*/opt/*/%s";
367 
368     if ((flags & DIP_NORTP) == 0)
369 	done = do_in_path(path, name, flags, callback, cookie);
370 
371     if ((done == FAIL || (flags & DIP_ALL)) && (flags & DIP_START))
372     {
373 	len = (int)(STRLEN(start_dir) + STRLEN(name));
374 	s = alloc(len);
375 	if (s == NULL)
376 	    return FAIL;
377 	vim_snprintf((char *)s, len, start_dir, name);
378 	done = do_in_path(p_pp, s, flags, callback, cookie);
379 	vim_free(s);
380     }
381 
382     if ((done == FAIL || (flags & DIP_ALL)) && (flags & DIP_OPT))
383     {
384 	len = (int)(STRLEN(opt_dir) + STRLEN(name));
385 	s = alloc(len);
386 	if (s == NULL)
387 	    return FAIL;
388 	vim_snprintf((char *)s, len, opt_dir, name);
389 	done = do_in_path(p_pp, s, flags, callback, cookie);
390 	vim_free(s);
391     }
392 
393     return done;
394 }
395 
396 /*
397  * Just like do_in_path_and_pp(), using 'runtimepath' for "path".
398  */
399     int
400 do_in_runtimepath(
401     char_u	*name,
402     int		flags,
403     void	(*callback)(char_u *fname, void *ck),
404     void	*cookie)
405 {
406     return do_in_path_and_pp(p_rtp, name, flags, callback, cookie);
407 }
408 
409 /*
410  * Source the file "name" from all directories in 'runtimepath'.
411  * "name" can contain wildcards.
412  * When "flags" has DIP_ALL: source all files, otherwise only the first one.
413  *
414  * return FAIL when no file could be sourced, OK otherwise.
415  */
416     int
417 source_runtime(char_u *name, int flags)
418 {
419     return source_in_path(p_rtp, name, flags, NULL);
420 }
421 
422 /*
423  * Just like source_runtime(), but use "path" instead of 'runtimepath'.
424  */
425     int
426 source_in_path(char_u *path, char_u *name, int flags, int *ret_sid)
427 {
428     return do_in_path_and_pp(path, name, flags, source_callback, ret_sid);
429 }
430 
431 
432 #if defined(FEAT_EVAL) || defined(PROTO)
433 
434 /*
435  * Expand wildcards in "pat" and invoke do_source() for each match.
436  */
437     static void
438 source_all_matches(char_u *pat)
439 {
440     int	    num_files;
441     char_u  **files;
442     int	    i;
443 
444     if (gen_expand_wildcards(1, &pat, &num_files, &files, EW_FILE) == OK)
445     {
446 	for (i = 0; i < num_files; ++i)
447 	    (void)do_source(files[i], FALSE, DOSO_NONE, NULL);
448 	FreeWild(num_files, files);
449     }
450 }
451 
452 /*
453  * Add the package directory to 'runtimepath'.
454  */
455     static int
456 add_pack_dir_to_rtp(char_u *fname)
457 {
458     char_u  *p4, *p3, *p2, *p1, *p;
459     char_u  *entry;
460     char_u  *insp = NULL;
461     int	    c;
462     char_u  *new_rtp;
463     int	    keep;
464     size_t  oldlen;
465     size_t  addlen;
466     size_t  new_rtp_len;
467     char_u  *afterdir = NULL;
468     size_t  afterlen = 0;
469     char_u  *after_insp = NULL;
470     char_u  *ffname = NULL;
471     size_t  fname_len;
472     char_u  *buf = NULL;
473     char_u  *rtp_ffname;
474     int	    match;
475     int	    retval = FAIL;
476 
477     p4 = p3 = p2 = p1 = get_past_head(fname);
478     for (p = p1; *p; MB_PTR_ADV(p))
479 	if (vim_ispathsep_nocolon(*p))
480 	{
481 	    p4 = p3; p3 = p2; p2 = p1; p1 = p;
482 	}
483 
484     // now we have:
485     // rtp/pack/name/start/name
486     //    p4   p3   p2    p1
487     //
488     // find the part up to "pack" in 'runtimepath'
489     c = *++p4; // append pathsep in order to expand symlink
490     *p4 = NUL;
491     ffname = fix_fname(fname);
492     *p4 = c;
493     if (ffname == NULL)
494 	return FAIL;
495 
496     // Find "ffname" in "p_rtp", ignoring '/' vs '\' differences.
497     // Also stop at the first "after" directory.
498     fname_len = STRLEN(ffname);
499     buf = alloc(MAXPATHL);
500     if (buf == NULL)
501 	goto theend;
502     for (entry = p_rtp; *entry != NUL; )
503     {
504 	char_u *cur_entry = entry;
505 
506 	copy_option_part(&entry, buf, MAXPATHL, ",");
507 	if (insp == NULL)
508 	{
509 	    add_pathsep(buf);
510 	    rtp_ffname = fix_fname(buf);
511 	    if (rtp_ffname == NULL)
512 		goto theend;
513 	    match = vim_fnamencmp(rtp_ffname, ffname, fname_len) == 0;
514 	    vim_free(rtp_ffname);
515 	    if (match)
516 		// Insert "ffname" after this entry (and comma).
517 		insp = entry;
518 	}
519 
520 	if ((p = (char_u *)strstr((char *)buf, "after")) != NULL
521 		&& p > buf
522 		&& vim_ispathsep(p[-1])
523 		&& (vim_ispathsep(p[5]) || p[5] == NUL || p[5] == ','))
524 	{
525 	    if (insp == NULL)
526 		// Did not find "ffname" before the first "after" directory,
527 		// insert it before this entry.
528 		insp = cur_entry;
529 	    after_insp = cur_entry;
530 	    break;
531 	}
532     }
533 
534     if (insp == NULL)
535 	// Both "fname" and "after" not found, append at the end.
536 	insp = p_rtp + STRLEN(p_rtp);
537 
538     // check if rtp/pack/name/start/name/after exists
539     afterdir = concat_fnames(fname, (char_u *)"after", TRUE);
540     if (afterdir != NULL && mch_isdir(afterdir))
541 	afterlen = STRLEN(afterdir) + 1; // add one for comma
542 
543     oldlen = STRLEN(p_rtp);
544     addlen = STRLEN(fname) + 1; // add one for comma
545     new_rtp = alloc(oldlen + addlen + afterlen + 1); // add one for NUL
546     if (new_rtp == NULL)
547 	goto theend;
548 
549     // We now have 'rtp' parts: {keep}{keep_after}{rest}.
550     // Create new_rtp, first: {keep},{fname}
551     keep = (int)(insp - p_rtp);
552     mch_memmove(new_rtp, p_rtp, keep);
553     new_rtp_len = keep;
554     if (*insp == NUL)
555 	new_rtp[new_rtp_len++] = ',';  // add comma before
556     mch_memmove(new_rtp + new_rtp_len, fname, addlen - 1);
557     new_rtp_len += addlen - 1;
558     if (*insp != NUL)
559 	new_rtp[new_rtp_len++] = ',';  // add comma after
560 
561     if (afterlen > 0 && after_insp != NULL)
562     {
563 	int keep_after = (int)(after_insp - p_rtp);
564 
565 	// Add to new_rtp: {keep},{fname}{keep_after},{afterdir}
566 	mch_memmove(new_rtp + new_rtp_len, p_rtp + keep,
567 							keep_after - keep);
568 	new_rtp_len += keep_after - keep;
569 	mch_memmove(new_rtp + new_rtp_len, afterdir, afterlen - 1);
570 	new_rtp_len += afterlen - 1;
571 	new_rtp[new_rtp_len++] = ',';
572 	keep = keep_after;
573     }
574 
575     if (p_rtp[keep] != NUL)
576 	// Append rest: {keep},{fname}{keep_after},{afterdir}{rest}
577 	mch_memmove(new_rtp + new_rtp_len, p_rtp + keep, oldlen - keep + 1);
578     else
579 	new_rtp[new_rtp_len] = NUL;
580 
581     if (afterlen > 0 && after_insp == NULL)
582     {
583 	// Append afterdir when "after" was not found:
584 	// {keep},{fname}{rest},{afterdir}
585 	STRCAT(new_rtp, ",");
586 	STRCAT(new_rtp, afterdir);
587     }
588 
589     set_option_value((char_u *)"rtp", 0L, new_rtp, 0);
590     vim_free(new_rtp);
591     retval = OK;
592 
593 theend:
594     vim_free(buf);
595     vim_free(ffname);
596     vim_free(afterdir);
597     return retval;
598 }
599 
600 /*
601  * Load scripts in "plugin" and "ftdetect" directories of the package.
602  */
603     static int
604 load_pack_plugin(char_u *fname)
605 {
606     static char *plugpat = "%s/plugin/**/*.vim";
607     static char *ftpat = "%s/ftdetect/*.vim";
608     int		len;
609     char_u	*ffname = fix_fname(fname);
610     char_u	*pat = NULL;
611     int		retval = FAIL;
612 
613     if (ffname == NULL)
614 	return FAIL;
615     len = (int)STRLEN(ffname) + (int)STRLEN(ftpat);
616     pat = alloc(len);
617     if (pat == NULL)
618 	goto theend;
619     vim_snprintf((char *)pat, len, plugpat, ffname);
620     source_all_matches(pat);
621 
622     {
623 	char_u *cmd = vim_strsave((char_u *)"g:did_load_filetypes");
624 
625 	// If runtime/filetype.vim wasn't loaded yet, the scripts will be
626 	// found when it loads.
627 	if (cmd != NULL && eval_to_number(cmd) > 0)
628 	{
629 	    do_cmdline_cmd((char_u *)"augroup filetypedetect");
630 	    vim_snprintf((char *)pat, len, ftpat, ffname);
631 	    source_all_matches(pat);
632 	    do_cmdline_cmd((char_u *)"augroup END");
633 	}
634 	vim_free(cmd);
635     }
636     vim_free(pat);
637     retval = OK;
638 
639 theend:
640     vim_free(ffname);
641     return retval;
642 }
643 
644 // used for "cookie" of add_pack_plugin()
645 static int APP_ADD_DIR;
646 static int APP_LOAD;
647 static int APP_BOTH;
648 
649     static void
650 add_pack_plugin(char_u *fname, void *cookie)
651 {
652     if (cookie != &APP_LOAD)
653     {
654 	char_u	*buf = alloc(MAXPATHL);
655 	char_u	*p;
656 	int	found = FALSE;
657 
658 	if (buf == NULL)
659 	    return;
660 	p = p_rtp;
661 	while (*p != NUL)
662 	{
663 	    copy_option_part(&p, buf, MAXPATHL, ",");
664 	    if (pathcmp((char *)buf, (char *)fname, -1) == 0)
665 	    {
666 		found = TRUE;
667 		break;
668 	    }
669 	}
670 	vim_free(buf);
671 	if (!found)
672 	    // directory is not yet in 'runtimepath', add it
673 	    if (add_pack_dir_to_rtp(fname) == FAIL)
674 		return;
675     }
676 
677     if (cookie != &APP_ADD_DIR)
678 	load_pack_plugin(fname);
679 }
680 
681 /*
682  * Add all packages in the "start" directory to 'runtimepath'.
683  */
684     void
685 add_pack_start_dirs(void)
686 {
687     do_in_path(p_pp, (char_u *)"pack/*/start/*", DIP_ALL + DIP_DIR,
688 					       add_pack_plugin, &APP_ADD_DIR);
689 }
690 
691 /*
692  * Load plugins from all packages in the "start" directory.
693  */
694     void
695 load_start_packages(void)
696 {
697     did_source_packages = TRUE;
698     do_in_path(p_pp, (char_u *)"pack/*/start/*", DIP_ALL + DIP_DIR,
699 						  add_pack_plugin, &APP_LOAD);
700 }
701 
702 /*
703  * ":packloadall"
704  * Find plugins in the package directories and source them.
705  */
706     void
707 ex_packloadall(exarg_T *eap)
708 {
709     if (!did_source_packages || eap->forceit)
710     {
711 	// First do a round to add all directories to 'runtimepath', then load
712 	// the plugins. This allows for plugins to use an autoload directory
713 	// of another plugin.
714 	add_pack_start_dirs();
715 	load_start_packages();
716     }
717 }
718 
719 /*
720  * ":packadd[!] {name}"
721  */
722     void
723 ex_packadd(exarg_T *eap)
724 {
725     static char *plugpat = "pack/*/%s/%s";
726     int		len;
727     char	*pat;
728     int		round;
729     int		res = OK;
730 
731     // Round 1: use "start", round 2: use "opt".
732     for (round = 1; round <= 2; ++round)
733     {
734 	// Only look under "start" when loading packages wasn't done yet.
735 	if (round == 1 && did_source_packages)
736 	    continue;
737 
738 	len = (int)STRLEN(plugpat) + (int)STRLEN(eap->arg) + 5;
739 	pat = alloc(len);
740 	if (pat == NULL)
741 	    return;
742 	vim_snprintf(pat, len, plugpat, round == 1 ? "start" : "opt", eap->arg);
743 	// The first round don't give a "not found" error, in the second round
744 	// only when nothing was found in the first round.
745 	res = do_in_path(p_pp, (char_u *)pat,
746 		DIP_ALL + DIP_DIR + (round == 2 && res == FAIL ? DIP_ERR : 0),
747 		add_pack_plugin, eap->forceit ? &APP_ADD_DIR : &APP_BOTH);
748 	vim_free(pat);
749     }
750 }
751 #endif
752 
753 /*
754  * Sort "gap" and remove duplicate entries.  "gap" is expected to contain a
755  * list of file names in allocated memory.
756  */
757     void
758 remove_duplicates(garray_T *gap)
759 {
760     int	    i;
761     int	    j;
762     char_u  **fnames = (char_u **)gap->ga_data;
763 
764     sort_strings(fnames, gap->ga_len);
765     for (i = gap->ga_len - 1; i > 0; --i)
766 	if (fnamecmp(fnames[i - 1], fnames[i]) == 0)
767 	{
768 	    vim_free(fnames[i]);
769 	    for (j = i + 1; j < gap->ga_len; ++j)
770 		fnames[j - 1] = fnames[j];
771 	    --gap->ga_len;
772 	}
773 }
774 
775 /*
776  * Expand color scheme, compiler or filetype names.
777  * Search from 'runtimepath':
778  *   'runtimepath'/{dirnames}/{pat}.vim
779  * When "flags" has DIP_START: search also from 'start' of 'packpath':
780  *   'packpath'/pack/ * /start/ * /{dirnames}/{pat}.vim
781  * When "flags" has DIP_OPT: search also from 'opt' of 'packpath':
782  *   'packpath'/pack/ * /opt/ * /{dirnames}/{pat}.vim
783  * "dirnames" is an array with one or more directory names.
784  */
785     int
786 ExpandRTDir(
787     char_u	*pat,
788     int		flags,
789     int		*num_file,
790     char_u	***file,
791     char	*dirnames[])
792 {
793     char_u	*s;
794     char_u	*e;
795     char_u	*match;
796     garray_T	ga;
797     int		i;
798     int		pat_len;
799 
800     *num_file = 0;
801     *file = NULL;
802     pat_len = (int)STRLEN(pat);
803     ga_init2(&ga, (int)sizeof(char *), 10);
804 
805     for (i = 0; dirnames[i] != NULL; ++i)
806     {
807 	s = alloc(STRLEN(dirnames[i]) + pat_len + 7);
808 	if (s == NULL)
809 	{
810 	    ga_clear_strings(&ga);
811 	    return FAIL;
812 	}
813 	sprintf((char *)s, "%s/%s*.vim", dirnames[i], pat);
814 	globpath(p_rtp, s, &ga, 0);
815 	vim_free(s);
816     }
817 
818     if (flags & DIP_START) {
819 	for (i = 0; dirnames[i] != NULL; ++i)
820 	{
821 	    s = alloc(STRLEN(dirnames[i]) + pat_len + 22);
822 	    if (s == NULL)
823 	    {
824 		ga_clear_strings(&ga);
825 		return FAIL;
826 	    }
827 	    sprintf((char *)s, "pack/*/start/*/%s/%s*.vim", dirnames[i], pat);
828 	    globpath(p_pp, s, &ga, 0);
829 	    vim_free(s);
830 	}
831     }
832 
833     if (flags & DIP_OPT) {
834 	for (i = 0; dirnames[i] != NULL; ++i)
835 	{
836 	    s = alloc(STRLEN(dirnames[i]) + pat_len + 20);
837 	    if (s == NULL)
838 	    {
839 		ga_clear_strings(&ga);
840 		return FAIL;
841 	    }
842 	    sprintf((char *)s, "pack/*/opt/*/%s/%s*.vim", dirnames[i], pat);
843 	    globpath(p_pp, s, &ga, 0);
844 	    vim_free(s);
845 	}
846     }
847 
848     for (i = 0; i < ga.ga_len; ++i)
849     {
850 	match = ((char_u **)ga.ga_data)[i];
851 	s = match;
852 	e = s + STRLEN(s);
853 	if (e - 4 > s && STRNICMP(e - 4, ".vim", 4) == 0)
854 	{
855 	    e -= 4;
856 	    for (s = e; s > match; MB_PTR_BACK(match, s))
857 		if (s < match || vim_ispathsep(*s))
858 		    break;
859 	    ++s;
860 	    *e = NUL;
861 	    mch_memmove(match, s, e - s + 1);
862 	}
863     }
864 
865     if (ga.ga_len == 0)
866 	return FAIL;
867 
868     // Sort and remove duplicates which can happen when specifying multiple
869     // directories in dirnames.
870     remove_duplicates(&ga);
871 
872     *file = ga.ga_data;
873     *num_file = ga.ga_len;
874     return OK;
875 }
876 
877 /*
878  * Expand loadplugin names:
879  * 'packpath'/pack/ * /opt/{pat}
880  */
881     int
882 ExpandPackAddDir(
883     char_u	*pat,
884     int		*num_file,
885     char_u	***file)
886 {
887     char_u	*s;
888     char_u	*e;
889     char_u	*match;
890     garray_T	ga;
891     int		i;
892     int		pat_len;
893 
894     *num_file = 0;
895     *file = NULL;
896     pat_len = (int)STRLEN(pat);
897     ga_init2(&ga, (int)sizeof(char *), 10);
898 
899     s = alloc(pat_len + 26);
900     if (s == NULL)
901     {
902 	ga_clear_strings(&ga);
903 	return FAIL;
904     }
905     sprintf((char *)s, "pack/*/opt/%s*", pat);
906     globpath(p_pp, s, &ga, 0);
907     vim_free(s);
908 
909     for (i = 0; i < ga.ga_len; ++i)
910     {
911 	match = ((char_u **)ga.ga_data)[i];
912 	s = gettail(match);
913 	e = s + STRLEN(s);
914 	mch_memmove(match, s, e - s + 1);
915     }
916 
917     if (ga.ga_len == 0)
918 	return FAIL;
919 
920     // Sort and remove duplicates which can happen when specifying multiple
921     // directories in dirnames.
922     remove_duplicates(&ga);
923 
924     *file = ga.ga_data;
925     *num_file = ga.ga_len;
926     return OK;
927 }
928 
929     static void
930 cmd_source(char_u *fname, exarg_T *eap)
931 {
932     if (*fname == NUL)
933 	emsg(_(e_argreq));
934 
935     else if (eap != NULL && eap->forceit)
936 	// ":source!": read Normal mode commands
937 	// Need to execute the commands directly.  This is required at least
938 	// for:
939 	// - ":g" command busy
940 	// - after ":argdo", ":windo" or ":bufdo"
941 	// - another command follows
942 	// - inside a loop
943 	openscript(fname, global_busy || listcmd_busy || eap->nextcmd != NULL
944 #ifdef FEAT_EVAL
945 						 || eap->cstack->cs_idx >= 0
946 #endif
947 						 );
948 
949     // ":source" read ex commands
950     else if (do_source(fname, FALSE, DOSO_NONE, NULL) == FAIL)
951 	semsg(_(e_notopen), fname);
952 }
953 
954 /*
955  * ":source {fname}"
956  */
957     void
958 ex_source(exarg_T *eap)
959 {
960 #ifdef FEAT_BROWSE
961     if (cmdmod.browse)
962     {
963 	char_u *fname = NULL;
964 
965 	fname = do_browse(0, (char_u *)_("Source Vim script"), eap->arg,
966 				      NULL, NULL,
967 				      (char_u *)_(BROWSE_FILTER_MACROS), NULL);
968 	if (fname != NULL)
969 	{
970 	    cmd_source(fname, eap);
971 	    vim_free(fname);
972 	}
973     }
974     else
975 #endif
976 	cmd_source(eap->arg, eap);
977 }
978 
979 #if defined(FEAT_EVAL) || defined(PROTO)
980 /*
981  * ":options"
982  */
983     void
984 ex_options(
985     exarg_T	*eap UNUSED)
986 {
987     char_u  buf[500];
988     int	    multi_mods = 0;
989 
990     buf[0] = NUL;
991     (void)add_win_cmd_modifers(buf, &multi_mods);
992 
993     vim_setenv((char_u *)"OPTWIN_CMD", buf);
994     cmd_source((char_u *)SYS_OPTWIN_FILE, NULL);
995 }
996 #endif
997 
998 /*
999  * ":source" and associated commands.
1000  */
1001 /*
1002  * Structure used to store info for each sourced file.
1003  * It is shared between do_source() and getsourceline().
1004  * This is required, because it needs to be handed to do_cmdline() and
1005  * sourcing can be done recursively.
1006  */
1007 struct source_cookie
1008 {
1009     FILE	*fp;		// opened file for sourcing
1010     char_u	*nextline;	// if not NULL: line that was read ahead
1011     linenr_T	sourcing_lnum;	// line number of the source file
1012     int		finished;	// ":finish" used
1013 #ifdef USE_CRNL
1014     int		fileformat;	// EOL_UNKNOWN, EOL_UNIX or EOL_DOS
1015     int		error;		// TRUE if LF found after CR-LF
1016 #endif
1017 #ifdef FEAT_EVAL
1018     linenr_T	breakpoint;	// next line with breakpoint or zero
1019     char_u	*fname;		// name of sourced file
1020     int		dbg_tick;	// debug_tick when breakpoint was set
1021     int		level;		// top nesting level of sourced file
1022 #endif
1023     vimconv_T	conv;		// type of conversion
1024 };
1025 
1026 #ifdef FEAT_EVAL
1027 /*
1028  * Return the address holding the next breakpoint line for a source cookie.
1029  */
1030     linenr_T *
1031 source_breakpoint(void *cookie)
1032 {
1033     return &((struct source_cookie *)cookie)->breakpoint;
1034 }
1035 
1036 /*
1037  * Return the address holding the debug tick for a source cookie.
1038  */
1039     int *
1040 source_dbg_tick(void *cookie)
1041 {
1042     return &((struct source_cookie *)cookie)->dbg_tick;
1043 }
1044 
1045 /*
1046  * Return the nesting level for a source cookie.
1047  */
1048     int
1049 source_level(void *cookie)
1050 {
1051     return ((struct source_cookie *)cookie)->level;
1052 }
1053 
1054 /*
1055  * Return the readahead line.
1056  */
1057     char_u *
1058 source_nextline(void *cookie)
1059 {
1060     return ((struct source_cookie *)cookie)->nextline;
1061 }
1062 #endif
1063 
1064 #if (defined(MSWIN) && defined(FEAT_CSCOPE)) || defined(HAVE_FD_CLOEXEC)
1065 # define USE_FOPEN_NOINH
1066 /*
1067  * Special function to open a file without handle inheritance.
1068  * When possible the handle is closed on exec().
1069  */
1070     static FILE *
1071 fopen_noinh_readbin(char *filename)
1072 {
1073 # ifdef MSWIN
1074     int	fd_tmp = mch_open(filename, O_RDONLY | O_BINARY | O_NOINHERIT, 0);
1075 # else
1076     int	fd_tmp = mch_open(filename, O_RDONLY, 0);
1077 # endif
1078 
1079     if (fd_tmp == -1)
1080 	return NULL;
1081 
1082 # ifdef HAVE_FD_CLOEXEC
1083     {
1084 	int fdflags = fcntl(fd_tmp, F_GETFD);
1085 	if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)
1086 	    (void)fcntl(fd_tmp, F_SETFD, fdflags | FD_CLOEXEC);
1087     }
1088 # endif
1089 
1090     return fdopen(fd_tmp, READBIN);
1091 }
1092 #endif
1093 
1094 /*
1095  * do_source: Read the file "fname" and execute its lines as EX commands.
1096  * When "ret_sid" is not NULL and we loaded the script before, don't load it
1097  * again.
1098  *
1099  * This function may be called recursively!
1100  *
1101  * Return FAIL if file could not be opened, OK otherwise.
1102  * If a scriptitem_T was found or created "*ret_sid" is set to the SID.
1103  */
1104     int
1105 do_source(
1106     char_u	*fname,
1107     int		check_other,	    // check for .vimrc and _vimrc
1108     int		is_vimrc,	    // DOSO_ value
1109     int		*ret_sid UNUSED)
1110 {
1111     struct source_cookie    cookie;
1112     char_u		    *p;
1113     char_u		    *fname_exp;
1114     char_u		    *firstline = NULL;
1115     int			    retval = FAIL;
1116 #ifdef FEAT_EVAL
1117     sctx_T		    save_current_sctx;
1118     static scid_T	    last_current_SID = 0;
1119     static int		    last_current_SID_seq = 0;
1120     funccal_entry_T	    funccalp_entry;
1121     int			    save_debug_break_level = debug_break_level;
1122     int			    sid;
1123     scriptitem_T	    *si = NULL;
1124 #endif
1125 #ifdef STARTUPTIME
1126     struct timeval	    tv_rel;
1127     struct timeval	    tv_start;
1128 #endif
1129 #ifdef FEAT_PROFILE
1130     proftime_T		    wait_start;
1131 #endif
1132     int			    trigger_source_post = FALSE;
1133     ESTACK_CHECK_DECLARATION
1134 
1135     p = expand_env_save(fname);
1136     if (p == NULL)
1137 	return retval;
1138     fname_exp = fix_fname(p);
1139     vim_free(p);
1140     if (fname_exp == NULL)
1141 	return retval;
1142     if (mch_isdir(fname_exp))
1143     {
1144 	smsg(_("Cannot source a directory: \"%s\""), fname);
1145 	goto theend;
1146     }
1147 
1148 #ifdef FEAT_EVAL
1149     // See if we loaded this script before.
1150     for (sid = script_items.ga_len; sid > 0; --sid)
1151     {
1152 	// We used to check inode here, but that doesn't work:
1153 	// - If a script is edited and written, it may get a different
1154 	//   inode number, even though to the user it is the same script.
1155 	// - If a script is deleted and another script is written, with a
1156 	//   different name, the inode may be re-used.
1157 	si = SCRIPT_ITEM(sid);
1158 	if (si->sn_name != NULL && fnamecmp(si->sn_name, fname_exp) == 0)
1159 		// Found it!
1160 		break;
1161     }
1162     if (sid > 0 && ret_sid != NULL)
1163     {
1164 	// Already loaded and no need to load again, return here.
1165 	*ret_sid = sid;
1166 	retval = OK;
1167 	goto theend;
1168     }
1169 #endif
1170 
1171     // Apply SourceCmd autocommands, they should get the file and source it.
1172     if (has_autocmd(EVENT_SOURCECMD, fname_exp, NULL)
1173 	    && apply_autocmds(EVENT_SOURCECMD, fname_exp, fname_exp,
1174 							       FALSE, curbuf))
1175     {
1176 #ifdef FEAT_EVAL
1177 	retval = aborting() ? FAIL : OK;
1178 #else
1179 	retval = OK;
1180 #endif
1181 	if (retval == OK)
1182 	    // Apply SourcePost autocommands.
1183 	    apply_autocmds(EVENT_SOURCEPOST, fname_exp, fname_exp,
1184 								FALSE, curbuf);
1185 	goto theend;
1186     }
1187 
1188     // Apply SourcePre autocommands, they may get the file.
1189     apply_autocmds(EVENT_SOURCEPRE, fname_exp, fname_exp, FALSE, curbuf);
1190 
1191 #ifdef USE_FOPEN_NOINH
1192     cookie.fp = fopen_noinh_readbin((char *)fname_exp);
1193 #else
1194     cookie.fp = mch_fopen((char *)fname_exp, READBIN);
1195 #endif
1196     if (cookie.fp == NULL && check_other)
1197     {
1198 	// Try again, replacing file name ".vimrc" by "_vimrc" or vice versa,
1199 	// and ".exrc" by "_exrc" or vice versa.
1200 	p = gettail(fname_exp);
1201 	if ((*p == '.' || *p == '_')
1202 		&& (STRICMP(p + 1, "vimrc") == 0
1203 		    || STRICMP(p + 1, "gvimrc") == 0
1204 		    || STRICMP(p + 1, "exrc") == 0))
1205 	{
1206 	    if (*p == '_')
1207 		*p = '.';
1208 	    else
1209 		*p = '_';
1210 #ifdef USE_FOPEN_NOINH
1211 	    cookie.fp = fopen_noinh_readbin((char *)fname_exp);
1212 #else
1213 	    cookie.fp = mch_fopen((char *)fname_exp, READBIN);
1214 #endif
1215 	}
1216     }
1217 
1218     if (cookie.fp == NULL)
1219     {
1220 	if (p_verbose > 0)
1221 	{
1222 	    verbose_enter();
1223 	    if (SOURCING_NAME == NULL)
1224 		smsg(_("could not source \"%s\""), fname);
1225 	    else
1226 		smsg(_("line %ld: could not source \"%s\""),
1227 							SOURCING_LNUM, fname);
1228 	    verbose_leave();
1229 	}
1230 	goto theend;
1231     }
1232 
1233     // The file exists.
1234     // - In verbose mode, give a message.
1235     // - For a vimrc file, may want to set 'compatible', call vimrc_found().
1236     if (p_verbose > 1)
1237     {
1238 	verbose_enter();
1239 	if (SOURCING_NAME == NULL)
1240 	    smsg(_("sourcing \"%s\""), fname);
1241 	else
1242 	    smsg(_("line %ld: sourcing \"%s\""), SOURCING_LNUM, fname);
1243 	verbose_leave();
1244     }
1245     if (is_vimrc == DOSO_VIMRC)
1246 	vimrc_found(fname_exp, (char_u *)"MYVIMRC");
1247     else if (is_vimrc == DOSO_GVIMRC)
1248 	vimrc_found(fname_exp, (char_u *)"MYGVIMRC");
1249 
1250 #ifdef USE_CRNL
1251     // If no automatic file format: Set default to CR-NL.
1252     if (*p_ffs == NUL)
1253 	cookie.fileformat = EOL_DOS;
1254     else
1255 	cookie.fileformat = EOL_UNKNOWN;
1256     cookie.error = FALSE;
1257 #endif
1258 
1259     cookie.nextline = NULL;
1260     cookie.sourcing_lnum = 0;
1261     cookie.finished = FALSE;
1262 
1263 #ifdef FEAT_EVAL
1264     // Check if this script has a breakpoint.
1265     cookie.breakpoint = dbg_find_breakpoint(TRUE, fname_exp, (linenr_T)0);
1266     cookie.fname = fname_exp;
1267     cookie.dbg_tick = debug_tick;
1268 
1269     cookie.level = ex_nesting_level;
1270 #endif
1271 
1272     // Keep the sourcing name/lnum, for recursive calls.
1273     estack_push(ETYPE_SCRIPT, fname_exp, 0);
1274     ESTACK_CHECK_SETUP
1275 
1276 #ifdef STARTUPTIME
1277     if (time_fd != NULL)
1278 	time_push(&tv_rel, &tv_start);
1279 #endif
1280 
1281 #ifdef FEAT_EVAL
1282 # ifdef FEAT_PROFILE
1283     if (do_profiling == PROF_YES)
1284 	prof_child_enter(&wait_start);		// entering a child now
1285 # endif
1286 
1287     // Don't use local function variables, if called from a function.
1288     // Also starts profiling timer for nested script.
1289     save_funccal(&funccalp_entry);
1290 
1291     save_current_sctx = current_sctx;
1292     current_sctx.sc_lnum = 0;
1293     current_sctx.sc_version = 1;  // default script version
1294 
1295     // Check if this script was sourced before to finds its SID.
1296     // Always use a new sequence number.
1297     current_sctx.sc_seq = ++last_current_SID_seq;
1298     if (sid > 0)
1299     {
1300 	hashtab_T	*ht;
1301 	int		is_vim9 = si->sn_version == SCRIPT_VERSION_VIM9;
1302 
1303 	// loading the same script again
1304 	si->sn_had_command = FALSE;
1305 	si->sn_version = 1;
1306 	current_sctx.sc_sid = sid;
1307 
1308 	// In Vim9 script all script-local variables are removed when reloading
1309 	// the same script.  In legacy script they remain but "const" can be
1310 	// set again.
1311 	ht = &SCRIPT_VARS(sid);
1312 	if (is_vim9)
1313 	    hashtab_free_contents(ht);
1314 	else
1315 	{
1316 	    int		todo = (int)ht->ht_used;
1317 	    hashitem_T	*hi;
1318 	    dictitem_T	*di;
1319 
1320 	    for (hi = ht->ht_array; todo > 0; ++hi)
1321 		if (!HASHITEM_EMPTY(hi))
1322 		{
1323 		    --todo;
1324 		    di = HI2DI(hi);
1325 		    di->di_flags |= DI_FLAGS_RELOAD;
1326 		}
1327 	}
1328 
1329 	// old imports are no longer valid
1330 	free_imports(sid);
1331 
1332 	// in Vim9 script functions are marked deleted
1333 	if (is_vim9)
1334 	    delete_script_functions(sid);
1335     }
1336     else
1337     {
1338 	// It's new, generate a new SID.
1339 	current_sctx.sc_sid = ++last_current_SID;
1340 	if (ga_grow(&script_items,
1341 		     (int)(current_sctx.sc_sid - script_items.ga_len)) == FAIL)
1342 	    goto almosttheend;
1343 	while (script_items.ga_len < current_sctx.sc_sid)
1344 	{
1345 	    si = ALLOC_CLEAR_ONE(scriptitem_T);
1346 	    if (si == NULL)
1347 		goto almosttheend;
1348 	    ++script_items.ga_len;
1349 	    SCRIPT_ITEM(script_items.ga_len) = si;
1350 	    si->sn_name = NULL;
1351 	    si->sn_version = 1;
1352 
1353 	    // Allocate the local script variables to use for this script.
1354 	    new_script_vars(script_items.ga_len);
1355 	    ga_init2(&si->sn_var_vals, sizeof(svar_T), 10);
1356 	    ga_init2(&si->sn_imports, sizeof(imported_T), 10);
1357 	    ga_init2(&si->sn_type_list, sizeof(type_T), 10);
1358 # ifdef FEAT_PROFILE
1359 	    si->sn_prof_on = FALSE;
1360 # endif
1361 	}
1362 	si = SCRIPT_ITEM(current_sctx.sc_sid);
1363 	si->sn_name = fname_exp;
1364 	fname_exp = vim_strsave(si->sn_name);  // used for autocmd
1365 	if (ret_sid != NULL)
1366 	    *ret_sid = current_sctx.sc_sid;
1367     }
1368 
1369 # ifdef FEAT_PROFILE
1370     if (do_profiling == PROF_YES)
1371     {
1372 	int	forceit;
1373 
1374 	// Check if we do profiling for this script.
1375 	if (!si->sn_prof_on && has_profiling(TRUE, si->sn_name, &forceit))
1376 	{
1377 	    script_do_profile(si);
1378 	    si->sn_pr_force = forceit;
1379 	}
1380 	if (si->sn_prof_on)
1381 	{
1382 	    ++si->sn_pr_count;
1383 	    profile_start(&si->sn_pr_start);
1384 	    profile_zero(&si->sn_pr_children);
1385 	}
1386     }
1387 # endif
1388 #endif
1389 
1390     cookie.conv.vc_type = CONV_NONE;		// no conversion
1391 
1392     // Read the first line so we can check for a UTF-8 BOM.
1393     firstline = getsourceline(0, (void *)&cookie, 0, TRUE);
1394     if (firstline != NULL && STRLEN(firstline) >= 3 && firstline[0] == 0xef
1395 			      && firstline[1] == 0xbb && firstline[2] == 0xbf)
1396     {
1397 	// Found BOM; setup conversion, skip over BOM and recode the line.
1398 	convert_setup(&cookie.conv, (char_u *)"utf-8", p_enc);
1399 	p = string_convert(&cookie.conv, firstline + 3, NULL);
1400 	if (p == NULL)
1401 	    p = vim_strsave(firstline + 3);
1402 	if (p != NULL)
1403 	{
1404 	    vim_free(firstline);
1405 	    firstline = p;
1406 	}
1407     }
1408 
1409     // Call do_cmdline, which will call getsourceline() to get the lines.
1410     do_cmdline(firstline, getsourceline, (void *)&cookie,
1411 				     DOCMD_VERBOSE|DOCMD_NOWAIT|DOCMD_REPEAT);
1412     retval = OK;
1413 
1414 #ifdef FEAT_PROFILE
1415     if (do_profiling == PROF_YES)
1416     {
1417 	// Get "si" again, "script_items" may have been reallocated.
1418 	si = SCRIPT_ITEM(current_sctx.sc_sid);
1419 	if (si->sn_prof_on)
1420 	{
1421 	    profile_end(&si->sn_pr_start);
1422 	    profile_sub_wait(&wait_start, &si->sn_pr_start);
1423 	    profile_add(&si->sn_pr_total, &si->sn_pr_start);
1424 	    profile_self(&si->sn_pr_self, &si->sn_pr_start,
1425 							 &si->sn_pr_children);
1426 	}
1427     }
1428 #endif
1429 
1430     if (got_int)
1431 	emsg(_(e_interr));
1432     ESTACK_CHECK_NOW
1433     estack_pop();
1434     if (p_verbose > 1)
1435     {
1436 	verbose_enter();
1437 	smsg(_("finished sourcing %s"), fname);
1438 	if (SOURCING_NAME != NULL)
1439 	    smsg(_("continuing in %s"), SOURCING_NAME);
1440 	verbose_leave();
1441     }
1442 #ifdef STARTUPTIME
1443     if (time_fd != NULL)
1444     {
1445 	vim_snprintf((char *)IObuff, IOSIZE, "sourcing %s", fname);
1446 	time_msg((char *)IObuff, &tv_start);
1447 	time_pop(&tv_rel);
1448     }
1449 #endif
1450 
1451     if (!got_int)
1452 	trigger_source_post = TRUE;
1453 
1454 #ifdef FEAT_EVAL
1455     // After a "finish" in debug mode, need to break at first command of next
1456     // sourced file.
1457     if (save_debug_break_level > ex_nesting_level
1458 	    && debug_break_level == ex_nesting_level)
1459 	++debug_break_level;
1460 #endif
1461 
1462 #ifdef FEAT_EVAL
1463 almosttheend:
1464     // Get "si" again, "script_items" may have been reallocated.
1465     si = SCRIPT_ITEM(current_sctx.sc_sid);
1466     if (si->sn_save_cpo != NULL)
1467     {
1468 	free_string_option(p_cpo);
1469 	p_cpo = si->sn_save_cpo;
1470 	si->sn_save_cpo = NULL;
1471     }
1472 
1473     current_sctx = save_current_sctx;
1474     restore_funccal();
1475 # ifdef FEAT_PROFILE
1476     if (do_profiling == PROF_YES)
1477 	prof_child_exit(&wait_start);		// leaving a child now
1478 # endif
1479 #endif
1480     fclose(cookie.fp);
1481     vim_free(cookie.nextline);
1482     vim_free(firstline);
1483     convert_setup(&cookie.conv, NULL, NULL);
1484 
1485     if (trigger_source_post)
1486 	apply_autocmds(EVENT_SOURCEPOST, fname_exp, fname_exp, FALSE, curbuf);
1487 
1488 theend:
1489     vim_free(fname_exp);
1490     return retval;
1491 }
1492 
1493 #if defined(FEAT_EVAL) || defined(PROTO)
1494 
1495 /*
1496  * ":scriptnames"
1497  */
1498     void
1499 ex_scriptnames(exarg_T *eap)
1500 {
1501     int i;
1502 
1503     if (eap->addr_count > 0)
1504     {
1505 	// :script {scriptId}: edit the script
1506 	if (eap->line2 < 1 || eap->line2 > script_items.ga_len)
1507 	    emsg(_(e_invarg));
1508 	else
1509 	{
1510 	    eap->arg = SCRIPT_ITEM(eap->line2)->sn_name;
1511 	    do_exedit(eap, NULL);
1512 	}
1513 	return;
1514     }
1515 
1516     for (i = 1; i <= script_items.ga_len && !got_int; ++i)
1517 	if (SCRIPT_ITEM(i)->sn_name != NULL)
1518 	{
1519 	    home_replace(NULL, SCRIPT_ITEM(i)->sn_name,
1520 						    NameBuff, MAXPATHL, TRUE);
1521 	    smsg("%3d: %s", i, NameBuff);
1522 	}
1523 }
1524 
1525 # if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
1526 /*
1527  * Fix slashes in the list of script names for 'shellslash'.
1528  */
1529     void
1530 scriptnames_slash_adjust(void)
1531 {
1532     int i;
1533 
1534     for (i = 1; i <= script_items.ga_len; ++i)
1535 	if (SCRIPT_ITEM(i)->sn_name != NULL)
1536 	    slash_adjust(SCRIPT_ITEM(i)->sn_name);
1537 }
1538 # endif
1539 
1540 /*
1541  * Get a pointer to a script name.  Used for ":verbose set".
1542  */
1543     char_u *
1544 get_scriptname(scid_T id)
1545 {
1546     if (id == SID_MODELINE)
1547 	return (char_u *)_("modeline");
1548     if (id == SID_CMDARG)
1549 	return (char_u *)_("--cmd argument");
1550     if (id == SID_CARG)
1551 	return (char_u *)_("-c argument");
1552     if (id == SID_ENV)
1553 	return (char_u *)_("environment variable");
1554     if (id == SID_ERROR)
1555 	return (char_u *)_("error handler");
1556     return SCRIPT_ITEM(id)->sn_name;
1557 }
1558 
1559 # if defined(EXITFREE) || defined(PROTO)
1560     void
1561 free_scriptnames(void)
1562 {
1563     int			i;
1564 
1565     for (i = script_items.ga_len; i > 0; --i)
1566     {
1567 	scriptitem_T *si = SCRIPT_ITEM(i);
1568 
1569 	// the variables themselves are cleared in evalvars_clear()
1570 	vim_free(si->sn_vars);
1571 
1572 	vim_free(si->sn_name);
1573 	free_imports(i);
1574 	free_string_option(si->sn_save_cpo);
1575 #  ifdef FEAT_PROFILE
1576 	ga_clear(&si->sn_prl_ga);
1577 #  endif
1578 	vim_free(si);
1579     }
1580     ga_clear(&script_items);
1581 }
1582 
1583     void
1584 free_autoload_scriptnames(void)
1585 {
1586     ga_clear_strings(&ga_loaded);
1587 }
1588 # endif
1589 
1590 #endif
1591 
1592     linenr_T
1593 get_sourced_lnum(char_u *(*fgetline)(int, void *, int, int), void *cookie)
1594 {
1595     return fgetline == getsourceline
1596 			? ((struct source_cookie *)cookie)->sourcing_lnum
1597 			: SOURCING_LNUM;
1598 }
1599 
1600     static char_u *
1601 get_one_sourceline(struct source_cookie *sp)
1602 {
1603     garray_T		ga;
1604     int			len;
1605     int			c;
1606     char_u		*buf;
1607 #ifdef USE_CRNL
1608     int			has_cr;		// CR-LF found
1609 #endif
1610     int			have_read = FALSE;
1611 
1612     // use a growarray to store the sourced line
1613     ga_init2(&ga, 1, 250);
1614 
1615     // Loop until there is a finished line (or end-of-file).
1616     ++sp->sourcing_lnum;
1617     for (;;)
1618     {
1619 	// make room to read at least 120 (more) characters
1620 	if (ga_grow(&ga, 120) == FAIL)
1621 	    break;
1622 	buf = (char_u *)ga.ga_data;
1623 
1624 	if (fgets((char *)buf + ga.ga_len, ga.ga_maxlen - ga.ga_len,
1625 							      sp->fp) == NULL)
1626 	    break;
1627 	len = ga.ga_len + (int)STRLEN(buf + ga.ga_len);
1628 #ifdef USE_CRNL
1629 	// Ignore a trailing CTRL-Z, when in Dos mode.	Only recognize the
1630 	// CTRL-Z by its own, or after a NL.
1631 	if (	   (len == 1 || (len >= 2 && buf[len - 2] == '\n'))
1632 		&& sp->fileformat == EOL_DOS
1633 		&& buf[len - 1] == Ctrl_Z)
1634 	{
1635 	    buf[len - 1] = NUL;
1636 	    break;
1637 	}
1638 #endif
1639 
1640 	have_read = TRUE;
1641 	ga.ga_len = len;
1642 
1643 	// If the line was longer than the buffer, read more.
1644 	if (ga.ga_maxlen - ga.ga_len == 1 && buf[len - 1] != '\n')
1645 	    continue;
1646 
1647 	if (len >= 1 && buf[len - 1] == '\n')	// remove trailing NL
1648 	{
1649 #ifdef USE_CRNL
1650 	    has_cr = (len >= 2 && buf[len - 2] == '\r');
1651 	    if (sp->fileformat == EOL_UNKNOWN)
1652 	    {
1653 		if (has_cr)
1654 		    sp->fileformat = EOL_DOS;
1655 		else
1656 		    sp->fileformat = EOL_UNIX;
1657 	    }
1658 
1659 	    if (sp->fileformat == EOL_DOS)
1660 	    {
1661 		if (has_cr)	    // replace trailing CR
1662 		{
1663 		    buf[len - 2] = '\n';
1664 		    --len;
1665 		    --ga.ga_len;
1666 		}
1667 		else	    // lines like ":map xx yy^M" will have failed
1668 		{
1669 		    if (!sp->error)
1670 		    {
1671 			msg_source(HL_ATTR(HLF_W));
1672 			emsg(_("W15: Warning: Wrong line separator, ^M may be missing"));
1673 		    }
1674 		    sp->error = TRUE;
1675 		    sp->fileformat = EOL_UNIX;
1676 		}
1677 	    }
1678 #endif
1679 	    // The '\n' is escaped if there is an odd number of ^V's just
1680 	    // before it, first set "c" just before the 'V's and then check
1681 	    // len&c parities (is faster than ((len-c)%2 == 0)) -- Acevedo
1682 	    for (c = len - 2; c >= 0 && buf[c] == Ctrl_V; c--)
1683 		;
1684 	    if ((len & 1) != (c & 1))	// escaped NL, read more
1685 	    {
1686 		++sp->sourcing_lnum;
1687 		continue;
1688 	    }
1689 
1690 	    buf[len - 1] = NUL;		// remove the NL
1691 	}
1692 
1693 	// Check for ^C here now and then, so recursive :so can be broken.
1694 	line_breakcheck();
1695 	break;
1696     }
1697 
1698     if (have_read)
1699 	return (char_u *)ga.ga_data;
1700 
1701     vim_free(ga.ga_data);
1702     return NULL;
1703 }
1704 
1705 /*
1706  * Get one full line from a sourced file.
1707  * Called by do_cmdline() when it's called from do_source().
1708  *
1709  * Return a pointer to the line in allocated memory.
1710  * Return NULL for end-of-file or some error.
1711  */
1712     char_u *
1713 getsourceline(int c UNUSED, void *cookie, int indent UNUSED, int do_concat)
1714 {
1715     struct source_cookie *sp = (struct source_cookie *)cookie;
1716     char_u		*line;
1717     char_u		*p;
1718 
1719 #ifdef FEAT_EVAL
1720     // If breakpoints have been added/deleted need to check for it.
1721     if (sp->dbg_tick < debug_tick)
1722     {
1723 	sp->breakpoint = dbg_find_breakpoint(TRUE, sp->fname, SOURCING_LNUM);
1724 	sp->dbg_tick = debug_tick;
1725     }
1726 # ifdef FEAT_PROFILE
1727     if (do_profiling == PROF_YES)
1728 	script_line_end();
1729 # endif
1730 #endif
1731 
1732     // Set the current sourcing line number.
1733     SOURCING_LNUM = sp->sourcing_lnum + 1;
1734 
1735     // Get current line.  If there is a read-ahead line, use it, otherwise get
1736     // one now.
1737     if (sp->finished)
1738 	line = NULL;
1739     else if (sp->nextline == NULL)
1740 	line = get_one_sourceline(sp);
1741     else
1742     {
1743 	line = sp->nextline;
1744 	sp->nextline = NULL;
1745 	++sp->sourcing_lnum;
1746     }
1747 #ifdef FEAT_PROFILE
1748     if (line != NULL && do_profiling == PROF_YES)
1749 	script_line_start();
1750 #endif
1751 
1752     // Only concatenate lines starting with a \ when 'cpoptions' doesn't
1753     // contain the 'C' flag.
1754     if (line != NULL && do_concat && vim_strchr(p_cpo, CPO_CONCAT) == NULL)
1755     {
1756 	// compensate for the one line read-ahead
1757 	--sp->sourcing_lnum;
1758 
1759 	// Get the next line and concatenate it when it starts with a
1760 	// backslash. We always need to read the next line, keep it in
1761 	// sp->nextline.
1762 	/* Also check for a comment in between continuation lines: "\ */
1763 	sp->nextline = get_one_sourceline(sp);
1764 	if (sp->nextline != NULL
1765 		&& (*(p = skipwhite(sp->nextline)) == '\\'
1766 			      || (p[0] == '"' && p[1] == '\\' && p[2] == ' ')))
1767 	{
1768 	    garray_T    ga;
1769 
1770 	    ga_init2(&ga, (int)sizeof(char_u), 400);
1771 	    ga_concat(&ga, line);
1772 	    if (*p == '\\')
1773 		ga_concat(&ga, p + 1);
1774 	    for (;;)
1775 	    {
1776 		vim_free(sp->nextline);
1777 		sp->nextline = get_one_sourceline(sp);
1778 		if (sp->nextline == NULL)
1779 		    break;
1780 		p = skipwhite(sp->nextline);
1781 		if (*p == '\\')
1782 		{
1783 		    // Adjust the growsize to the current length to speed up
1784 		    // concatenating many lines.
1785 		    if (ga.ga_len > 400)
1786 		    {
1787 			if (ga.ga_len > 8000)
1788 			    ga.ga_growsize = 8000;
1789 			else
1790 			    ga.ga_growsize = ga.ga_len;
1791 		    }
1792 		    ga_concat(&ga, p + 1);
1793 		}
1794 		else if (p[0] != '"' || p[1] != '\\' || p[2] != ' ')
1795 		    break;
1796 	    }
1797 	    ga_append(&ga, NUL);
1798 	    vim_free(line);
1799 	    line = ga.ga_data;
1800 	}
1801     }
1802 
1803     if (line != NULL && sp->conv.vc_type != CONV_NONE)
1804     {
1805 	char_u	*s;
1806 
1807 	// Convert the encoding of the script line.
1808 	s = string_convert(&sp->conv, line, NULL);
1809 	if (s != NULL)
1810 	{
1811 	    vim_free(line);
1812 	    line = s;
1813 	}
1814     }
1815 
1816 #ifdef FEAT_EVAL
1817     // Did we encounter a breakpoint?
1818     if (sp->breakpoint != 0 && sp->breakpoint <= SOURCING_LNUM)
1819     {
1820 	dbg_breakpoint(sp->fname, SOURCING_LNUM);
1821 	// Find next breakpoint.
1822 	sp->breakpoint = dbg_find_breakpoint(TRUE, sp->fname, SOURCING_LNUM);
1823 	sp->dbg_tick = debug_tick;
1824     }
1825 #endif
1826 
1827     return line;
1828 }
1829 
1830 /*
1831  * ":scriptencoding": Set encoding conversion for a sourced script.
1832  */
1833     void
1834 ex_scriptencoding(exarg_T *eap)
1835 {
1836     struct source_cookie	*sp;
1837     char_u			*name;
1838 
1839     if (!getline_equal(eap->getline, eap->cookie, getsourceline))
1840     {
1841 	emsg(_("E167: :scriptencoding used outside of a sourced file"));
1842 	return;
1843     }
1844 
1845     if (*eap->arg != NUL)
1846     {
1847 	name = enc_canonize(eap->arg);
1848 	if (name == NULL)	// out of memory
1849 	    return;
1850     }
1851     else
1852 	name = eap->arg;
1853 
1854     // Setup for conversion from the specified encoding to 'encoding'.
1855     sp = (struct source_cookie *)getline_cookie(eap->getline, eap->cookie);
1856     convert_setup(&sp->conv, name, p_enc);
1857 
1858     if (name != eap->arg)
1859 	vim_free(name);
1860 }
1861 
1862 /*
1863  * ":scriptversion": Set Vim script version for a sourced script.
1864  */
1865     void
1866 ex_scriptversion(exarg_T *eap UNUSED)
1867 {
1868 #ifdef FEAT_EVAL
1869     int		nr;
1870 
1871     if (!getline_equal(eap->getline, eap->cookie, getsourceline))
1872     {
1873 	emsg(_("E984: :scriptversion used outside of a sourced file"));
1874 	return;
1875     }
1876     if (current_sctx.sc_version == SCRIPT_VERSION_VIM9)
1877     {
1878 	emsg(_("E1040: Cannot use :scriptversion after :vim9script"));
1879 	return;
1880     }
1881 
1882     nr = getdigits(&eap->arg);
1883     if (nr == 0 || *eap->arg != NUL)
1884 	emsg(_(e_invarg));
1885     else if (nr > SCRIPT_VERSION_MAX)
1886 	semsg(_("E999: scriptversion not supported: %d"), nr);
1887     else
1888     {
1889 	current_sctx.sc_version = nr;
1890 	SCRIPT_ITEM(current_sctx.sc_sid)->sn_version = nr;
1891     }
1892 #endif
1893 }
1894 
1895 #if defined(FEAT_EVAL) || defined(PROTO)
1896 /*
1897  * ":finish": Mark a sourced file as finished.
1898  */
1899     void
1900 ex_finish(exarg_T *eap)
1901 {
1902     if (getline_equal(eap->getline, eap->cookie, getsourceline))
1903 	do_finish(eap, FALSE);
1904     else
1905 	emsg(_("E168: :finish used outside of a sourced file"));
1906 }
1907 
1908 /*
1909  * Mark a sourced file as finished.  Possibly makes the ":finish" pending.
1910  * Also called for a pending finish at the ":endtry" or after returning from
1911  * an extra do_cmdline().  "reanimate" is used in the latter case.
1912  */
1913     void
1914 do_finish(exarg_T *eap, int reanimate)
1915 {
1916     int		idx;
1917 
1918     if (reanimate)
1919 	((struct source_cookie *)getline_cookie(eap->getline,
1920 					      eap->cookie))->finished = FALSE;
1921 
1922     // Cleanup (and inactivate) conditionals, but stop when a try conditional
1923     // not in its finally clause (which then is to be executed next) is found.
1924     // In this case, make the ":finish" pending for execution at the ":endtry".
1925     // Otherwise, finish normally.
1926     idx = cleanup_conditionals(eap->cstack, 0, TRUE);
1927     if (idx >= 0)
1928     {
1929 	eap->cstack->cs_pending[idx] = CSTP_FINISH;
1930 	report_make_pending(CSTP_FINISH, NULL);
1931     }
1932     else
1933 	((struct source_cookie *)getline_cookie(eap->getline,
1934 					       eap->cookie))->finished = TRUE;
1935 }
1936 
1937 
1938 /*
1939  * Return TRUE when a sourced file had the ":finish" command: Don't give error
1940  * message for missing ":endif".
1941  * Return FALSE when not sourcing a file.
1942  */
1943     int
1944 source_finished(
1945     char_u	*(*fgetline)(int, void *, int, int),
1946     void	*cookie)
1947 {
1948     return (getline_equal(fgetline, cookie, getsourceline)
1949 	    && ((struct source_cookie *)getline_cookie(
1950 						fgetline, cookie))->finished);
1951 }
1952 
1953 /*
1954  * Return the autoload script name for a function or variable name.
1955  * Returns NULL when out of memory.
1956  * Caller must make sure that "name" contains AUTOLOAD_CHAR.
1957  */
1958     char_u *
1959 autoload_name(char_u *name)
1960 {
1961     char_u	*p, *q = NULL;
1962     char_u	*scriptname;
1963 
1964     // Get the script file name: replace '#' with '/', append ".vim".
1965     scriptname = alloc(STRLEN(name) + 14);
1966     if (scriptname == NULL)
1967 	return NULL;
1968     STRCPY(scriptname, "autoload/");
1969     STRCAT(scriptname, name);
1970     for (p = scriptname + 9; (p = vim_strchr(p, AUTOLOAD_CHAR)) != NULL;
1971 								    q = p, ++p)
1972 	*p = '/';
1973     STRCPY(q, ".vim");
1974     return scriptname;
1975 }
1976 
1977 /*
1978  * If "name" has a package name try autoloading the script for it.
1979  * Return TRUE if a package was loaded.
1980  */
1981     int
1982 script_autoload(
1983     char_u	*name,
1984     int		reload)	    // load script again when already loaded
1985 {
1986     char_u	*p;
1987     char_u	*scriptname, *tofree;
1988     int		ret = FALSE;
1989     int		i;
1990 
1991     // If there is no '#' after name[0] there is no package name.
1992     p = vim_strchr(name, AUTOLOAD_CHAR);
1993     if (p == NULL || p == name)
1994 	return FALSE;
1995 
1996     tofree = scriptname = autoload_name(name);
1997     if (scriptname == NULL)
1998 	return FALSE;
1999 
2000     // Find the name in the list of previously loaded package names.  Skip
2001     // "autoload/", it's always the same.
2002     for (i = 0; i < ga_loaded.ga_len; ++i)
2003 	if (STRCMP(((char_u **)ga_loaded.ga_data)[i] + 9, scriptname + 9) == 0)
2004 	    break;
2005     if (!reload && i < ga_loaded.ga_len)
2006 	ret = FALSE;	    // was loaded already
2007     else
2008     {
2009 	// Remember the name if it wasn't loaded already.
2010 	if (i == ga_loaded.ga_len && ga_grow(&ga_loaded, 1) == OK)
2011 	{
2012 	    ((char_u **)ga_loaded.ga_data)[ga_loaded.ga_len++] = scriptname;
2013 	    tofree = NULL;
2014 	}
2015 
2016 	// Try loading the package from $VIMRUNTIME/autoload/<name>.vim
2017 	if (source_runtime(scriptname, 0) == OK)
2018 	    ret = TRUE;
2019     }
2020 
2021     vim_free(tofree);
2022     return ret;
2023 }
2024 #endif
2025