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