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