robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1// eval/vars.c: functions for dealing with variables 2 3#include <assert.h> 4#include <ctype.h> 5#include <stdbool.h> 6#include <stddef.h> 7#include <stdint.h> 8#include <stdlib.h> 9#include <string.h> 10#include <uv.h> 11 12#include "nvim/ascii_defs.h" 13#include "nvim/autocmd.h" 14#include "nvim/autocmd_defs.h" 15#include "nvim/buffer_defs.h" 16#include "nvim/charset.h" 17#include "nvim/context.h" 18#include "nvim/drawscreen.h" 19#include "nvim/errors.h" 20#include "nvim/eval.h" 21#include "nvim/eval/encode.h" 22#include "nvim/eval/funcs.h" 23#include "nvim/eval/typval.h" 24#include "nvim/eval/typval_defs.h" 25#include "nvim/eval/userfunc.h" 26#include "nvim/eval/vars.h" 27#include "nvim/eval/window.h" 28#include "nvim/eval_defs.h" 29#include "nvim/ex_cmds.h" 30#include "nvim/ex_cmds_defs.h" 31#include "nvim/ex_docmd.h" 32#include "nvim/ex_eval.h" 33#include "nvim/garray.h" 34#include "nvim/gettext_defs.h" 35#include "nvim/globals.h" 36#include "nvim/hashtab.h" 37#include "nvim/lua/executor.h" 38#include "nvim/macros_defs.h" 39#include "nvim/mbyte.h" 40#include "nvim/memory.h" 41#include "nvim/message.h" 42#include "nvim/option.h" 43#include "nvim/option_defs.h" 44#include "nvim/optionstr.h" 45#include "nvim/os/os.h" 46#include "nvim/register.h" 47#include "nvim/runtime.h" 48#include "nvim/search.h" 49#include "nvim/strings.h" 50#include "nvim/types_defs.h" 51#include "nvim/version.h" 52#include "nvim/vim_defs.h" 53#include "nvim/window.h" 54 55typedef int (* ex_unletlock_callback )(lval_T * ,char * ,exarg_T * ,int ); 56 57#include "eval/vars.c.generated.h" 58 59// TODO(ZyX-I): Remove DICT_MAXNEST, make users be non-recursive instead 60 61#define DICT_MAXNEST 100 // maximum nesting of lists and dicts 62 63static const char * e_letunexp = N_ ("E18: Unexpected characters in :let" ); 64static const char e_double_semicolon_in_list_of_variables [] 65= N_ ("E452: Double ; in list of variables" ); 66static const char * e_lock_unlock = N_ ("E940: Cannot lock or unlock variable %s" ); 67static const char e_setting_v_str_to_value_with_wrong_type [] 68= N_ ("E963: Setting v:%s to value with wrong type" ); 69static const char e_missing_end_marker_str []= N_ ("E990: Missing end marker '%s'" ); 70static const char e_cannot_use_heredoc_here []= N_ ("E991: Cannot use =<< here" ); 71 72/// Variable used for g: 73static ScopeDictDictItem globvars_var ; 74static dict_T globvardict ;// Dict with g: variables 75/// g: value 76#define globvarht globvardict.dv_hashtab 77 78/// Old Vim variables such as "v:version" are also available without the "v:". 79/// Also in functions. We need a special hashtable for them. 80static hashtab_T compat_hashtab ; 81 82// values for vv_flags: 83#define VV_COMPAT 1 // compatible, also used without "v:" 84#define VV_RO 2 // read-only 85#define VV_RO_SBX 4 // read-only in the sandbox 86 87#define VV (idx ,name ,type ,flags ) \ 88 [idx] = { \ 89 .vv_name = (name), \ 90 .vv_di = { \ 91 .di_tv = { .v_type = (type) }, \ 92 .di_flags = 0, \ 93 .di_key = name, \ 94 }, \ 95 .vv_flags = (flags), \ 96 } 97 98#define VIMVAR_KEY_LEN 16 // Maximum length of the key of v:variables 99 100// Array to hold the value of v: variables. 101// The value is in a dictitem, so that it can also be used in the v: scope. 102// The reason to use this table anyway is for very quick access to the 103// variables with the VV_ defines. 104static struct vimvar { 105char * vv_name ;///< Name of the variable, without v:. 106TV_DICTITEM_STRUCT (VIMVAR_KEY_LEN + 1 )vv_di ;///< Value and name for key (max 16 chars). 107char vv_flags ;///< Flags: #VV_COMPAT, #VV_RO, #VV_RO_SBX. 108}vimvars []= { 109// VV_ tails differing from upcased string literals: 110// VV_CC_FROM "charconvert_from" 111// VV_CC_TO "charconvert_to" 112// VV_SEND_SERVER "servername" 113// VV_REG "register" 114// VV_OP "operator" 115VV (VV_COUNT ,"count" ,VAR_NUMBER ,VV_RO ), 116VV (VV_COUNT1 ,"count1" ,VAR_NUMBER ,VV_RO ), 117VV (VV_PREVCOUNT ,"prevcount" ,VAR_NUMBER ,VV_RO ), 118VV (VV_ERRMSG ,"errmsg" ,VAR_STRING ,0 ), 119VV (VV_WARNINGMSG ,"warningmsg" ,VAR_STRING ,0 ), 120VV (VV_STATUSMSG ,"statusmsg" ,VAR_STRING ,0 ), 121VV (VV_SHELL_ERROR ,"shell_error" ,VAR_NUMBER ,VV_RO ), 122VV (VV_THIS_SESSION ,"this_session" ,VAR_STRING ,0 ), 123VV (VV_VERSION ,"version" ,VAR_NUMBER ,VV_COMPAT + VV_RO ), 124VV (VV_LNUM ,"lnum" ,VAR_NUMBER ,VV_RO_SBX ), 125VV (VV_TERMRESPONSE ,"termresponse" ,VAR_STRING ,VV_RO ), 126VV (VV_TERMREQUEST ,"termrequest" ,VAR_STRING ,VV_RO ), 127VV (VV_FNAME ,"fname" ,VAR_STRING ,VV_RO ), 128VV (VV_LANG ,"lang" ,VAR_STRING ,VV_RO ), 129VV (VV_LC_TIME ,"lc_time" ,VAR_STRING ,VV_RO ), 130VV (VV_CTYPE ,"ctype" ,VAR_STRING ,VV_RO ), 131VV (VV_CC_FROM ,"charconvert_from" ,VAR_STRING ,VV_RO ), 132VV (VV_CC_TO ,"charconvert_to" ,VAR_STRING ,VV_RO ), 133VV (VV_FNAME_IN ,"fname_in" ,VAR_STRING ,VV_RO ), 134VV (VV_FNAME_OUT ,"fname_out" ,VAR_STRING ,VV_RO ), 135VV (VV_FNAME_NEW ,"fname_new" ,VAR_STRING ,VV_RO ), 136VV (VV_FNAME_DIFF ,"fname_diff" ,VAR_STRING ,VV_RO ), 137VV (VV_CMDARG ,"cmdarg" ,VAR_STRING ,VV_RO ), 138VV (VV_FOLDSTART ,"foldstart" ,VAR_NUMBER ,VV_RO_SBX ), 139VV (VV_FOLDEND ,"foldend" ,VAR_NUMBER ,VV_RO_SBX ), 140VV (VV_FOLDDASHES ,"folddashes" ,VAR_STRING ,VV_RO_SBX ), 141VV (VV_FOLDLEVEL ,"foldlevel" ,VAR_NUMBER ,VV_RO_SBX ), 142VV (VV_PROGNAME ,"progname" ,VAR_STRING ,VV_RO ), 143VV (VV_SEND_SERVER ,"servername" ,VAR_STRING ,VV_RO ), 144VV (VV_DYING ,"dying" ,VAR_NUMBER ,VV_RO ), 145VV (VV_EXCEPTION ,"exception" ,VAR_STRING ,VV_RO ), 146VV (VV_THROWPOINT ,"throwpoint" ,VAR_STRING ,VV_RO ), 147VV (VV_REG ,"register" ,VAR_STRING ,VV_RO ), 148VV (VV_CMDBANG ,"cmdbang" ,VAR_NUMBER ,VV_RO ), 149VV (VV_INSERTMODE ,"insertmode" ,VAR_STRING ,VV_RO ), 150VV (VV_VAL ,"val" ,VAR_UNKNOWN ,VV_RO ), 151VV (VV_KEY ,"key" ,VAR_UNKNOWN ,VV_RO ), 152VV (VV_PROFILING ,"profiling" ,VAR_NUMBER ,VV_RO ), 153VV (VV_FCS_REASON ,"fcs_reason" ,VAR_STRING ,VV_RO ), 154VV (VV_FCS_CHOICE ,"fcs_choice" ,VAR_STRING ,0 ), 155VV (VV_BEVAL_BUFNR ,"beval_bufnr" ,VAR_NUMBER ,VV_RO ), 156VV (VV_BEVAL_WINNR ,"beval_winnr" ,VAR_NUMBER ,VV_RO ), 157VV (VV_BEVAL_WINID ,"beval_winid" ,VAR_NUMBER ,VV_RO ), 158VV (VV_BEVAL_LNUM ,"beval_lnum" ,VAR_NUMBER ,VV_RO ), 159VV (VV_BEVAL_COL ,"beval_col" ,VAR_NUMBER ,VV_RO ), 160VV (VV_BEVAL_TEXT ,"beval_text" ,VAR_STRING ,VV_RO ), 161VV (VV_SCROLLSTART ,"scrollstart" ,VAR_STRING ,0 ), 162VV (VV_SWAPNAME ,"swapname" ,VAR_STRING ,VV_RO ), 163VV (VV_SWAPCHOICE ,"swapchoice" ,VAR_STRING ,0 ), 164VV (VV_SWAPCOMMAND ,"swapcommand" ,VAR_STRING ,VV_RO ), 165VV (VV_CHAR ,"char" ,VAR_STRING ,0 ), 166VV (VV_MOUSE_WIN ,"mouse_win" ,VAR_NUMBER ,0 ), 167VV (VV_MOUSE_WINID ,"mouse_winid" ,VAR_NUMBER ,0 ), 168VV (VV_MOUSE_LNUM ,"mouse_lnum" ,VAR_NUMBER ,0 ), 169VV (VV_MOUSE_COL ,"mouse_col" ,VAR_NUMBER ,0 ), 170VV (VV_OP ,"operator" ,VAR_STRING ,VV_RO ), 171VV (VV_SEARCHFORWARD ,"searchforward" ,VAR_NUMBER ,0 ), 172VV (VV_HLSEARCH ,"hlsearch" ,VAR_NUMBER ,0 ), 173VV (VV_OLDFILES ,"oldfiles" ,VAR_LIST ,0 ), 174VV (VV_WINDOWID ,"windowid" ,VAR_NUMBER ,VV_RO_SBX ), 175VV (VV_PROGPATH ,"progpath" ,VAR_STRING ,VV_RO ), 176VV (VV_COMPLETED_ITEM ,"completed_item" ,VAR_DICT ,0 ), 177VV (VV_OPTION_NEW ,"option_new" ,VAR_STRING ,VV_RO ), 178VV (VV_OPTION_OLD ,"option_old" ,VAR_STRING ,VV_RO ), 179VV (VV_OPTION_OLDLOCAL ,"option_oldlocal" ,VAR_STRING ,VV_RO ), 180VV (VV_OPTION_OLDGLOBAL ,"option_oldglobal" ,VAR_STRING ,VV_RO ), 181VV (VV_OPTION_COMMAND ,"option_command" ,VAR_STRING ,VV_RO ), 182VV (VV_OPTION_TYPE ,"option_type" ,VAR_STRING ,VV_RO ), 183VV (VV_ERRORS ,"errors" ,VAR_LIST ,0 ), 184VV (VV_FALSE ,"false" ,VAR_BOOL ,VV_RO ), 185VV (VV_TRUE ,"true" ,VAR_BOOL ,VV_RO ), 186VV (VV_NULL ,"null" ,VAR_SPECIAL ,VV_RO ), 187VV (VV_NUMBERMAX ,"numbermax" ,VAR_NUMBER ,VV_RO ), 188VV (VV_NUMBERMIN ,"numbermin" ,VAR_NUMBER ,VV_RO ), 189VV (VV_NUMBERSIZE ,"numbersize" ,VAR_NUMBER ,VV_RO ), 190VV (VV_VIM_DID_ENTER ,"vim_did_enter" ,VAR_NUMBER ,VV_RO ), 191VV (VV_TESTING ,"testing" ,VAR_NUMBER ,0 ), 192VV (VV_TYPE_NUMBER ,"t_number" ,VAR_NUMBER ,VV_RO ), 193VV (VV_TYPE_STRING ,"t_string" ,VAR_NUMBER ,VV_RO ), 194VV (VV_TYPE_FUNC ,"t_func" ,VAR_NUMBER ,VV_RO ), 195VV (VV_TYPE_LIST ,"t_list" ,VAR_NUMBER ,VV_RO ), 196VV (VV_TYPE_DICT ,"t_dict" ,VAR_NUMBER ,VV_RO ), 197VV (VV_TYPE_FLOAT ,"t_float" ,VAR_NUMBER ,VV_RO ), 198VV (VV_TYPE_BOOL ,"t_bool" ,VAR_NUMBER ,VV_RO ), 199VV (VV_TYPE_BLOB ,"t_blob" ,VAR_NUMBER ,VV_RO ), 200VV (VV_EVENT ,"event" ,VAR_DICT ,VV_RO ), 201VV (VV_VERSIONLONG ,"versionlong" ,VAR_NUMBER ,VV_RO ), 202VV (VV_ECHOSPACE ,"echospace" ,VAR_NUMBER ,VV_RO ), 203VV (VV_ARGF ,"argf" ,VAR_LIST ,VV_RO ), 204VV (VV_ARGV ,"argv" ,VAR_LIST ,VV_RO ), 205VV (VV_COLLATE ,"collate" ,VAR_STRING ,VV_RO ), 206VV (VV_EXITING ,"exiting" ,VAR_NUMBER ,VV_RO ), 207VV (VV_MAXCOL ,"maxcol" ,VAR_NUMBER ,VV_RO ), 208VV (VV_STACKTRACE ,"stacktrace" ,VAR_LIST ,VV_RO ), 209VV (VV_VIM_DID_INIT ,"vim_did_init" ,VAR_NUMBER ,VV_RO ), 210// Neovim 211VV (VV_STDERR ,"stderr" ,VAR_NUMBER ,VV_RO ), 212VV (VV_MSGPACK_TYPES ,"msgpack_types" ,VAR_DICT ,VV_RO ), 213VV (VV__NULL_STRING ,"_null_string" ,VAR_STRING ,VV_RO ), 214VV (VV__NULL_LIST ,"_null_list" ,VAR_LIST ,VV_RO ), 215VV (VV__NULL_DICT ,"_null_dict" ,VAR_DICT ,VV_RO ), 216VV (VV__NULL_BLOB ,"_null_blob" ,VAR_BLOB ,VV_RO ), 217VV (VV_LUA ,"lua" ,VAR_PARTIAL ,VV_RO ), 218VV (VV_RELNUM ,"relnum" ,VAR_NUMBER ,VV_RO ), 219VV (VV_VIRTNUM ,"virtnum" ,VAR_NUMBER ,VV_RO ), 220VV (VV_STARTTIME ,"starttime" ,VAR_NUMBER ,VV_RO ), 221VV (VV_EXITREASON ,"exitreason" ,VAR_STRING ,VV_RO ), 222VV (VV_USERACTIVE ,"useractive" ,VAR_NUMBER ,VV_RO ), 223VV (VV_STARTREASON ,"startreason" ,VAR_STRING ,VV_RO ), 224}; 225#undef VV 226 227// shorthand 228#define vv_type vv_di.di_tv.v_type 229#define vv_str vv_di.di_tv.vval.v_string 230#define vv_list vv_di.di_tv.vval.v_list 231#define vv_tv vv_di.di_tv 232 233/// Variable used for v: 234static ScopeDictDictItem vimvars_var ; 235static dict_T vimvardict ;// Dict with v: variables 236/// v: hashtab 237#define vimvarht vimvardict.dv_hashtab 238 239static const char * const msgpack_type_names []= { 240 [kMPNil ]= "nil" , 241 [kMPBoolean ]= "boolean" , 242 [kMPInteger ]= "integer" , 243 [kMPFloat ]= "float" , 244 [kMPString ]= "string" , 245 [kMPArray ]= "array" , 246 [kMPMap ]= "map" , 247 [kMPExt ]= "ext" , 248}; 249const list_T * eval_msgpack_type_lists []= { 250 [kMPNil ]= NULL , 251 [kMPBoolean ]= NULL , 252 [kMPInteger ]= NULL , 253 [kMPFloat ]= NULL , 254 [kMPString ]= NULL , 255 [kMPArray ]= NULL , 256 [kMPMap ]= NULL , 257 [kMPExt ]= NULL , 258}; 259 260#define SCRIPT_SV (id ) (SCRIPT_ITEM(id)->sn_vars) 261#define SCRIPT_VARS (id ) (SCRIPT_SV(id)->sv_dict.dv_hashtab) 262 263void evalvars_init (void ) 264{ 265init_var_dict (get_globvar_dict (),& globvars_var ,VAR_DEF_SCOPE ); 266init_var_dict (& vimvardict ,& vimvars_var ,VAR_SCOPE ); 267vimvardict .dv_lock = VAR_FIXED ; 268hash_init (& compat_hashtab ); 269 270for (size_t i = 0 ;i < ARRAY_SIZE (vimvars );i ++ ) { 271struct vimvar * p = & vimvars [i ]; 272if (p -> vv_flags & VV_RO ) { 273p -> vv_di .di_flags = DI_FLAGS_RO |DI_FLAGS_FIX ; 274 }else if (p -> vv_flags & VV_RO_SBX ) { 275p -> vv_di .di_flags = DI_FLAGS_RO_SBX |DI_FLAGS_FIX ; 276 }else { 277p -> vv_di .di_flags = DI_FLAGS_FIX ; 278 } 279 280// add to v: scope dict, unless the value is not always available 281if (p -> vv_type != VAR_UNKNOWN ) { 282hash_add (& vimvarht ,p -> vv_di .di_key ); 283 } 284if (p -> vv_flags & VV_COMPAT ) { 285// add to compat scope dict 286hash_add (& compat_hashtab ,p -> vv_di .di_key ); 287 } 288 } 289const int vim_version = min_vim_version (); 290set_vim_var_nr (VV_VERSION ,vim_version ); 291set_vim_var_nr (VV_VERSIONLONG ,vim_version * 10000 + highest_patch ()); 292 293dict_T * const msgpack_types_dict = tv_dict_alloc (); 294for (size_t i = 0 ;i < ARRAY_SIZE (msgpack_type_names );i ++ ) { 295list_T * const type_list = tv_list_alloc (0 ); 296tv_list_set_lock (type_list ,VAR_FIXED ); 297tv_list_ref (type_list ); 298dictitem_T * const di = tv_dict_item_alloc (msgpack_type_names [i ]); 299di -> di_flags |=DI_FLAGS_RO |DI_FLAGS_FIX ; 300di -> di_tv = (typval_T ) { 301 .v_type = VAR_LIST , 302 .vval = { .v_list = type_list , }, 303 }; 304eval_msgpack_type_lists [i ]= type_list ; 305if (tv_dict_add (msgpack_types_dict ,di )== FAIL ) { 306// There must not be duplicate items in this dictionary by definition. 307abort (); 308 } 309 } 310msgpack_types_dict -> dv_lock = VAR_FIXED ; 311 312set_vim_var_dict (VV_MSGPACK_TYPES ,msgpack_types_dict ); 313set_vim_var_dict (VV_COMPLETED_ITEM ,tv_dict_alloc_lock (VAR_FIXED )); 314 315set_vim_var_dict (VV_EVENT ,tv_dict_alloc_lock (VAR_FIXED )); 316set_vim_var_list (VV_ERRORS ,tv_list_alloc (kListLenUnknown )); 317set_vim_var_nr (VV_STDERR ,CHAN_STDERR ); 318set_vim_var_nr (VV_SEARCHFORWARD ,1 ); 319set_vim_var_nr (VV_HLSEARCH ,1 ); 320set_vim_var_nr (VV_COUNT1 ,1 ); 321set_vim_var_string (VV_STARTREASON ,S_LEN ("normal" )); 322set_vim_var_special (VV_EXITING ,kSpecialVarNull ); 323 324set_vim_var_nr (VV_TYPE_NUMBER ,VAR_TYPE_NUMBER ); 325set_vim_var_nr (VV_TYPE_STRING ,VAR_TYPE_STRING ); 326set_vim_var_nr (VV_TYPE_FUNC ,VAR_TYPE_FUNC ); 327set_vim_var_nr (VV_TYPE_LIST ,VAR_TYPE_LIST ); 328set_vim_var_nr (VV_TYPE_DICT ,VAR_TYPE_DICT ); 329set_vim_var_nr (VV_TYPE_FLOAT ,VAR_TYPE_FLOAT ); 330set_vim_var_nr (VV_TYPE_BOOL ,VAR_TYPE_BOOL ); 331set_vim_var_nr (VV_TYPE_BLOB ,VAR_TYPE_BLOB ); 332 333set_vim_var_bool (VV_FALSE ,kBoolVarFalse ); 334set_vim_var_bool (VV_TRUE ,kBoolVarTrue ); 335set_vim_var_special (VV_NULL ,kSpecialVarNull ); 336set_vim_var_nr (VV_NUMBERMAX ,VARNUMBER_MAX ); 337set_vim_var_nr (VV_NUMBERMIN ,VARNUMBER_MIN ); 338set_vim_var_nr (VV_NUMBERSIZE ,sizeof (varnumber_T )* 8 ); 339set_vim_var_nr (VV_MAXCOL ,MAXCOL ); 340 341set_vim_var_nr (VV_ECHOSPACE ,sc_col - 1 ); 342 343// vimvars[VV_LUA].vv_type = VAR_PARTIAL; 344partial_T * vvlua_partial = xcalloc (1 ,sizeof (partial_T )); 345// this value shouldn't be printed, but if it is, do not crash 346vvlua_partial -> pt_name = xmallocz (0 ); 347vvlua_partial -> pt_refcount ++ ; 348set_vim_var_partial (VV_LUA ,vvlua_partial ); 349 350set_reg_var (0 );// default for v:register is not 0 but '"' 351 352// Set v:startreason via environment variable 353const char * startreason = os_getenv_noalloc (ENV_STARTREASON ); 354if (strequal (startreason ,"restart!" )|| strequal (startreason ,"restart" )) { 355set_vim_var_string (VV_STARTREASON ,startreason ,-1 ); 356 } 357if (os_env_exists (ENV_STARTREASON , false)) { 358os_unsetenv (ENV_STARTREASON ); 359 } 360} 361 362#ifdef EXITFREE 363void evalvars_clear (void ) 364{ 365for (size_t i = 0 ;i < ARRAY_SIZE (vimvars );i ++ ) { 366struct vimvar * p = & vimvars [i ]; 367if (p -> vv_di .di_tv .v_type == VAR_STRING ) { 368XFREE_CLEAR (p -> vv_str ); 369 }else if (p -> vv_di .di_tv .v_type == VAR_LIST ) { 370tv_list_unref (p -> vv_list ); 371p -> vv_list = NULL ; 372 } 373 } 374 375partial_unref (get_vim_var_partial (VV_LUA )); 376set_vim_var_partial (VV_LUA ,NULL ); 377hash_clear (& vimvarht ); 378hash_init (& vimvarht );// garbage_collect() will access it 379hash_clear (& compat_hashtab ); 380 381// global variables 382vars_clear (get_globvar_ht ()); 383 384// Script-local variables. Clear all the variables here. 385// The scriptvar_T is cleared later in free_scriptnames(), because a 386// variable in one script might hold a reference to the whole scope of 387// another script. 388for (int i = 1 ;i <=script_items .ga_len ;i ++ ) { 389vars_clear (& SCRIPT_VARS (i )); 390 } 391} 392#endif 393 394int garbage_collect_globvars (int copyID ) 395{ 396return set_ref_in_ht (& globvarht ,copyID ,NULL ); 397} 398 399bool garbage_collect_vimvars (int copyID ) 400{ 401return set_ref_in_ht (& vimvarht ,copyID ,NULL ); 402} 403 404bool garbage_collect_scriptvars (int copyID ) 405{ 406bool abort = false; 407 408for (int i = 1 ;i <=script_items .ga_len ;i ++ ) { 409abort = abort || set_ref_in_ht (& SCRIPT_VARS (i ),copyID ,NULL ); 410 } 411 412return abort ; 413} 414 415/// Set an internal variable to a string value. Creates the variable if it does 416/// not already exist. 417void set_internal_string_var (const char * name ,char * value )// NOLINT(readability-non-const-parameter) 418FUNC_ATTR_NONNULL_ARG (1 ) 419{ 420typval_T tv = { 421 .v_type = VAR_STRING , 422 .vval .v_string = value , 423 }; 424 425set_var (name ,strlen (name ),& tv , true); 426} 427 428int eval_charconvert (const char * const enc_from ,const char * const enc_to , 429const char * const fname_from ,const char * const fname_to ) 430{ 431const sctx_T saved_sctx = current_sctx ; 432 433set_vim_var_string (VV_CC_FROM ,enc_from ,-1 ); 434set_vim_var_string (VV_CC_TO ,enc_to ,-1 ); 435set_vim_var_string (VV_FNAME_IN ,fname_from ,-1 ); 436set_vim_var_string (VV_FNAME_OUT ,fname_to ,-1 ); 437sctx_T * ctx = get_option_sctx (kOptCharconvert ); 438if (ctx != NULL ) { 439current_sctx = * ctx ; 440 } 441 442bool err = false; 443typval_T tv ; 444typval_T argv [1 ]; 445if (!callback_call (& p_ccv ,0 ,argv ,& tv )) { 446err = true; 447 }else { 448if (tv_get_number_chk (& tv ,NULL )!= 0 ) { 449err = true; 450 } 451tv_clear (& tv ); 452 } 453 454set_vim_var_string (VV_CC_FROM ,NULL ,-1 ); 455set_vim_var_string (VV_CC_TO ,NULL ,-1 ); 456set_vim_var_string (VV_FNAME_IN ,NULL ,-1 ); 457set_vim_var_string (VV_FNAME_OUT ,NULL ,-1 ); 458current_sctx = saved_sctx ; 459 460if (err ) { 461return FAIL ; 462 } 463return OK ; 464} 465 466void eval_diff (const char * const origfile ,const char * const newfile ,const char * const outfile ) 467{ 468const sctx_T saved_sctx = current_sctx ; 469set_vim_var_string (VV_FNAME_IN ,origfile ,-1 ); 470set_vim_var_string (VV_FNAME_NEW ,newfile ,-1 ); 471set_vim_var_string (VV_FNAME_OUT ,outfile ,-1 ); 472 473sctx_T * ctx = get_option_sctx (kOptDiffexpr ); 474if (ctx != NULL ) { 475current_sctx = * ctx ; 476 } 477 478// errors are ignored 479typval_T tv ; 480typval_T argv [1 ]; 481if (callback_call (& p_dex ,0 ,argv ,& tv )) { 482tv_clear (& tv ); 483 } 484 485set_vim_var_string (VV_FNAME_IN ,NULL ,-1 ); 486set_vim_var_string (VV_FNAME_NEW ,NULL ,-1 ); 487set_vim_var_string (VV_FNAME_OUT ,NULL ,-1 ); 488current_sctx = saved_sctx ; 489} 490 491void eval_patch (const char * const origfile ,const char * const difffile ,const char * const outfile ) 492{ 493const sctx_T saved_sctx = current_sctx ; 494set_vim_var_string (VV_FNAME_IN ,origfile ,-1 ); 495set_vim_var_string (VV_FNAME_DIFF ,difffile ,-1 ); 496set_vim_var_string (VV_FNAME_OUT ,outfile ,-1 ); 497 498sctx_T * ctx = get_option_sctx (kOptPatchexpr ); 499if (ctx != NULL ) { 500current_sctx = * ctx ; 501 } 502 503// errors are ignored 504typval_T tv ; 505typval_T argv [1 ]; 506if (callback_call (& p_pex ,0 ,argv ,& tv )) { 507tv_clear (& tv ); 508 } 509 510set_vim_var_string (VV_FNAME_IN ,NULL ,-1 ); 511set_vim_var_string (VV_FNAME_DIFF ,NULL ,-1 ); 512set_vim_var_string (VV_FNAME_OUT ,NULL ,-1 ); 513current_sctx = saved_sctx ; 514} 515 516/// Evaluate an expression to a list with suggestions. 517/// For the "expr:" part of 'spellsuggest'. 518/// 519/// @return NULL when there is an error. 520list_T * eval_spell_expr (char * badword ,char * expr ) 521{ 522typval_T save_val ; 523typval_T rettv ; 524list_T * list = NULL ; 525char * p = skipwhite (expr ); 526const sctx_T saved_sctx = current_sctx ; 527 528// Set "v:val" to the bad word. 529prepare_vimvar (VV_VAL ,& save_val ); 530set_vim_var_string (VV_VAL ,badword ,-1 ); 531if (p_verbose == 0 ) { 532emsg_off ++ ; 533 } 534sctx_T * ctx = get_option_sctx (kOptSpellsuggest ); 535if (ctx != NULL ) { 536current_sctx = * ctx ; 537 } 538 539int r = may_call_simple_func (p ,& rettv ); 540if (r == NOTDONE ) { 541r = eval1 (& p ,& rettv ,& EVALARG_EVALUATE ); 542 } 543if (r == OK ) { 544if (rettv .v_type != VAR_LIST ) { 545tv_clear (& rettv ); 546 }else { 547list = rettv .vval .v_list ; 548 } 549 } 550 551if (p_verbose == 0 ) { 552emsg_off -- ; 553 } 554tv_clear (get_vim_var_tv (VV_VAL )); 555restore_vimvar (VV_VAL ,& save_val ); 556current_sctx = saved_sctx ; 557 558return list ; 559} 560 561/// Get spell word from an entry from spellsuggest=expr: 562/// 563/// Entry in question is supposed to be a list (to be checked by the caller) 564/// with two items: a word and a score represented as an unsigned number 565/// (whether it actually is unsigned is not checked). 566/// 567/// Used to get the good word and score from the eval_spell_expr() result. 568/// 569/// @param[in] list List to get values from. 570/// @param[out] ret_word Suggested word. Not initialized if return value is 571/// -1. 572/// 573/// @return -1 in case of error, score otherwise. 574int get_spellword (list_T * const list ,const char ** ret_word ) 575{ 576if (tv_list_len (list )!= 2 ) { 577emsg (_ ("E5700: Expression from 'spellsuggest' must yield lists with " 578"exactly two values" )); 579return -1 ; 580 } 581* ret_word = tv_list_find_str (list ,0 ); 582if (* ret_word == NULL ) { 583return -1 ; 584 } 585return (int )tv_list_find_nr (list ,-1 ,NULL ); 586} 587 588/// Prepare v: variable "idx" to be used. 589/// Save the current typeval in "save_tv" and clear it. 590/// When not used yet add the variable to the v: hashtable. 591void prepare_vimvar (int idx ,typval_T * save_tv ) 592{ 593* save_tv = vimvars [idx ].vv_tv ; 594vimvars [idx ].vv_str = NULL ;// don't free it now 595if (vimvars [idx ].vv_type == VAR_UNKNOWN ) { 596hash_add (& vimvarht ,vimvars [idx ].vv_di .di_key ); 597 } 598} 599 600/// Restore v: variable "idx" to typeval "save_tv". 601/// Note that the v: variable must have been cleared already. 602/// When no longer defined, remove the variable from the v: hashtable. 603void restore_vimvar (int idx ,typval_T * save_tv ) 604{ 605vimvars [idx ].vv_tv = * save_tv ; 606if (vimvars [idx ].vv_type != VAR_UNKNOWN ) { 607return ; 608 } 609 610hashitem_T * hi = hash_find (& vimvarht ,vimvars [idx ].vv_di .di_key ); 611if (HASHITEM_EMPTY (hi )) { 612internal_error ("restore_vimvar()" ); 613 }else { 614hash_remove (& vimvarht ,hi ); 615 } 616} 617 618/// List Vim variables. 619static void list_vim_vars (int * first ) 620{ 621list_hashtable_vars (& vimvarht ,"v:" , false,first ); 622} 623 624/// List script-local variables, if there is a script. 625static void list_script_vars (int * first ) 626{ 627if (current_sctx .sc_sid > 0 && current_sctx .sc_sid <=script_items .ga_len ) { 628list_hashtable_vars (& SCRIPT_VARS (current_sctx .sc_sid ),"s:" , false,first ); 629 } 630} 631 632/// Evaluate one Vim expression {expr} in string "p" and append the 633/// resulting string to "gap". "p" points to the opening "{". 634/// When "evaluate" is false only skip over the expression. 635/// Return a pointer to the character after "}", NULL for an error. 636char * eval_one_expr_in_str (char * p ,garray_T * gap ,bool evaluate ) 637{ 638char * block_start = skipwhite (p + 1 );// skip the opening { 639char * block_end = block_start ; 640 641if (* block_start == NUL ) { 642semsg (_ (e_missing_close_curly_str ),p ); 643return NULL ; 644 } 645if (skip_expr (& block_end ,NULL )== FAIL ) { 646return NULL ; 647 } 648block_end = skipwhite (block_end ); 649if (* block_end != '}' ) { 650semsg (_ (e_missing_close_curly_str ),p ); 651return NULL ; 652 } 653if (evaluate ) { 654* block_end = NUL ; 655char * expr_val = eval_to_string (block_start , false, false); 656* block_end = '}' ; 657if (expr_val == NULL ) { 658return NULL ; 659 } 660ga_concat (gap ,expr_val ); 661xfree (expr_val ); 662 } 663 664return block_end + 1 ; 665} 666 667/// Evaluate all the Vim expressions {expr} in "str" and return the resulting 668/// string in allocated memory. "{{" is reduced to "{" and "}}" to "}". 669/// Used for a heredoc assignment. 670/// Returns NULL for an error. 671static char * eval_all_expr_in_str (char * str ) 672{ 673garray_T ga ; 674ga_init (& ga ,1 ,80 ); 675char * p = str ; 676 677while (* p != NUL ) { 678bool escaped_brace = false; 679 680// Look for a block start. 681char * lit_start = p ; 682while (* p != '{' && * p != '}' && * p != NUL ) { 683p ++ ; 684 } 685 686if (* p != NUL && * p == p [1 ]) { 687// Escaped brace, unescape and continue. 688// Include the brace in the literal string. 689p ++ ; 690escaped_brace = true; 691 }else if (* p == '}' ) { 692semsg (_ (e_stray_closing_curly_str ),str ); 693ga_clear (& ga ); 694return NULL ; 695 } 696 697// Append the literal part. 698ga_concat_len (& ga ,lit_start , (size_t )(p - lit_start )); 699 700if (* p == NUL ) { 701break ; 702 } 703 704if (escaped_brace ) { 705// Skip the second brace. 706p ++ ; 707continue ; 708 } 709 710// Evaluate the expression and append the result. 711p = eval_one_expr_in_str (p ,& ga , true); 712if (p == NULL ) { 713ga_clear (& ga ); 714return NULL ; 715 } 716 } 717ga_append (& ga ,NUL ); 718 719return ga .ga_data ; 720} 721 722/// Get a list of lines from a HERE document. The here document is a list of 723/// lines surrounded by a marker. 724/// cmd << {marker} 725/// {line1} 726/// {line2} 727/// .... 728/// {marker} 729/// 730/// The {marker} is a string. If the optional 'trim' word is supplied before the 731/// marker, then the leading indentation before the lines (matching the 732/// indentation in the 'cmd' line) is stripped. 733/// 734/// When getting lines for an embedded script (e.g. python, lua, perl, ruby, 735/// tcl, mzscheme), "script_get" is set to true. In this case, if the marker is 736/// missing, then '.' is accepted as a marker. 737/// 738/// @return a List with {lines} or NULL on failure. 739list_T * heredoc_get (exarg_T * eap ,char * cmd ,bool script_get ) 740{ 741char * marker ; 742int marker_indent_len = 0 ; 743int text_indent_len = 0 ; 744char * text_indent = NULL ; 745char dot []= "." ; 746bool heredoc_in_string = false; 747char * line_arg = NULL ; 748char * nl_ptr = vim_strchr (cmd ,'\n' ); 749 750if (nl_ptr != NULL ) { 751heredoc_in_string = true; 752line_arg = nl_ptr + 1 ; 753* nl_ptr = NUL ; 754 }else if (eap -> ea_getline == NULL ) { 755emsg (_ (e_cannot_use_heredoc_here )); 756return NULL ; 757 } 758 759// Check for the optional 'trim' word before the marker 760cmd = skipwhite (cmd ); 761bool evalstr = false; 762bool eval_failed = false; 763while (true) { 764if (strncmp (cmd ,"trim" ,4 )== 0 765&& (cmd [4 ]== NUL || ascii_iswhite (cmd [4 ]))) { 766cmd = skipwhite (cmd + 4 ); 767 768// Trim the indentation from all the lines in the here document. 769// The amount of indentation trimmed is the same as the indentation 770// of the first line after the :let command line. To find the end 771// marker the indent of the :let command line is trimmed. 772char * p = * eap -> cmdlinep ; 773while (ascii_iswhite (* p )) { 774p ++ ; 775marker_indent_len ++ ; 776 } 777text_indent_len = -1 ; 778 779continue ; 780 } 781if (strncmp (cmd ,"eval" ,4 )== 0 782&& (cmd [4 ]== NUL || ascii_iswhite (cmd [4 ]))) { 783cmd = skipwhite (cmd + 4 ); 784evalstr = true; 785continue ; 786 } 787break ; 788 } 789 790const char comment_char = '"' ; 791// The marker is the next word. 792if (* cmd != NUL && * cmd != comment_char ) { 793marker = skipwhite (cmd ); 794char * p = skiptowhite (marker ); 795if (* skipwhite (p )!= NUL && * skipwhite (p )!= comment_char ) { 796semsg (_ (e_trailing_arg ),p ); 797return NULL ; 798 } 799* p = NUL ; 800if (!script_get && islower ((uint8_t )(* marker ))) { 801emsg (_ ("E221: Marker cannot start with lower case letter" )); 802return NULL ; 803 } 804 }else { 805// When getting lines for an embedded script, if the marker is missing, 806// accept '.' as the marker. 807if (script_get ) { 808marker = dot ; 809 }else { 810emsg (_ ("E172: Missing marker" )); 811return NULL ; 812 } 813 } 814 815char * theline = NULL ; 816list_T * l = tv_list_alloc (0 ); 817while (true) { 818int mi = 0 ; 819int ti = 0 ; 820 821if (heredoc_in_string ) { 822// heredoc in a string separated by newlines. Get the next line 823// from the string. 824 825if (* line_arg == NUL ) { 826if (!script_get ) { 827semsg (_ (e_missing_end_marker_str ),marker ); 828 } 829break ; 830 } 831 832theline = line_arg ; 833char * next_line = vim_strchr (theline ,'\n' ); 834if (next_line == NULL ) { 835line_arg += strlen (line_arg ); 836 }else { 837* next_line = NUL ; 838line_arg = next_line + 1 ; 839 } 840 }else { 841xfree (theline ); 842theline = eap -> ea_getline (NUL ,eap -> cookie ,0 , false); 843if (theline == NULL ) { 844if (!script_get ) { 845semsg (_ (e_missing_end_marker_str ),marker ); 846 } 847break ; 848 } 849 } 850 851// with "trim": skip the indent matching the :let line to find the 852// marker 853if (marker_indent_len > 0 854&& strncmp (theline ,* eap -> cmdlinep , (size_t )marker_indent_len )== 0 ) { 855mi = marker_indent_len ; 856 } 857if (strcmp (marker ,theline + mi )== 0 ) { 858break ; 859 } 860 861// If expression evaluation failed in the heredoc, then skip till the 862// end marker. 863if (eval_failed ) { 864continue ; 865 } 866 867if (text_indent_len == -1 && * theline != NUL ) { 868// set the text indent from the first line. 869char * p = theline ; 870text_indent_len = 0 ; 871while (ascii_iswhite (* p )) { 872p ++ ; 873text_indent_len ++ ; 874 } 875text_indent = xmemdupz (theline , (size_t )text_indent_len ); 876 } 877// with "trim": skip the indent matching the first line 878if (text_indent != NULL ) { 879for (ti = 0 ;ti < text_indent_len ;ti ++ ) { 880if (theline [ti ]!= text_indent [ti ]) { 881break ; 882 } 883 } 884 } 885 886char * str = theline + ti ; 887if (evalstr && !eap -> skip ) { 888str = eval_all_expr_in_str (str ); 889if (str == NULL ) { 890// expression evaluation failed 891eval_failed = true; 892continue ; 893 } 894tv_list_append_allocated_string (l ,str ); 895 }else { 896tv_list_append_string (l ,str ,-1 ); 897 } 898 } 899if (heredoc_in_string ) { 900// Next command follows the heredoc in the string. 901eap -> nextcmd = line_arg ; 902 }else { 903xfree (theline ); 904 } 905xfree (text_indent ); 906 907if (eval_failed ) { 908// expression evaluation in the heredoc failed 909tv_list_free (l ); 910return NULL ; 911 } 912return l ; 913} 914 915/// ":let" list all variable values 916/// ":let var1 var2" list variable values 917/// ":let var = expr" assignment command. 918/// ":let var += expr" assignment command. 919/// ":let var -= expr" assignment command. 920/// ":let var *= expr" assignment command. 921/// ":let var /= expr" assignment command. 922/// ":let var %= expr" assignment command. 923/// ":let var .= expr" assignment command. 924/// ":let var ..= expr" assignment command. 925/// ":let [var1, var2] = expr" unpack list. 926/// ":let [name, ..., ; lastname] = expr" unpack list. 927/// 928/// ":cons[t] var = expr1" define constant 929/// ":cons[t] [name1, name2, ...] = expr1" define constants unpacking list 930/// ":cons[t] [name, ..., ; lastname] = expr" define constants unpacking list 931void ex_let (exarg_T * eap ) 932{ 933const bool is_const = eap -> cmdidx == CMD_const ; 934char * arg = eap -> arg ; 935char * expr = NULL ; 936typval_T rettv ; 937int var_count = 0 ; 938int semicolon = 0 ; 939char op [2 ]; 940const char * argend ; 941int first = true; 942 943argend = skip_var_list (arg ,& var_count ,& semicolon , false); 944if (argend == NULL ) { 945return ; 946 } 947expr = skipwhite (argend ); 948bool concat = strncmp (expr ,"..=" ,3 )== 0 ; 949bool has_assign = * expr == '=' || (vim_strchr ("+-*/%." , (uint8_t )(* expr ))!= NULL 950&& expr [1 ]== '=' ); 951if (!has_assign && !concat ) { 952// ":let" without "=": list variables 953if (* arg == '[' ) { 954emsg (_ (e_invarg )); 955 }else if (!ends_excmd (* arg )) { 956// ":let var1 var2" 957arg = (char * )list_arg_vars (eap ,arg ,& first ); 958 }else if (!eap -> skip ) { 959// ":let" 960list_glob_vars (& first ); 961list_buf_vars (& first ); 962list_win_vars (& first ); 963list_tab_vars (& first ); 964list_script_vars (& first ); 965list_func_vars (& first ); 966list_vim_vars (& first ); 967 } 968eap -> nextcmd = check_nextcmd (arg ); 969return ; 970 } 971 972if (expr [0 ]== '=' && expr [1 ]== '<' && expr [2 ]== '<' ) { 973// HERE document 974list_T * l = heredoc_get (eap ,expr + 3 , false); 975if (l != NULL ) { 976tv_list_set_ret (& rettv ,l ); 977if (!eap -> skip ) { 978op [0 ]= '=' ; 979op [1 ]= NUL ; 980ex_let_vars (eap -> arg ,& rettv , false,semicolon ,var_count ,is_const ,op ); 981 } 982tv_clear (& rettv ); 983 } 984return ; 985 } 986 987rettv .v_type = VAR_UNKNOWN ; 988 989op [0 ]= '=' ; 990op [1 ]= NUL ; 991if (* expr != '=' ) { 992if (vim_strchr ("+-*/%." , (uint8_t )(* expr ))!= NULL ) { 993op [0 ]= * expr ;// +=, -=, *=, /=, %= or .= 994if (expr [0 ]== '.' && expr [1 ]== '.' ) {// ..= 995expr ++ ; 996 } 997 } 998expr += 2 ; 999 }else { 1000expr += 1 ; 1001 } 1002 1003expr = skipwhite (expr ); 1004 1005if (eap -> skip ) { 1006emsg_skip ++ ; 1007 } 1008evalarg_T evalarg ; 1009fill_evalarg_from_eap (& evalarg ,eap ,eap -> skip ); 1010int eval_res = eval0 (expr ,& rettv ,eap ,& evalarg ); 1011if (eap -> skip ) { 1012emsg_skip -- ; 1013 } 1014clear_evalarg (& evalarg ,eap ); 1015 1016if (!eap -> skip && eval_res != FAIL ) { 1017ex_let_vars (eap -> arg ,& rettv , false,semicolon ,var_count ,is_const ,op ); 1018 } 1019if (eval_res != FAIL ) { 1020tv_clear (& rettv ); 1021 } 1022} 1023 1024/// Assign the typevalue "tv" to the variable or variables at "arg_start". 1025/// Handles both "var" with any type and "[var, var; var]" with a list type. 1026/// When "op" is not NULL it points to a string with characters that 1027/// must appear after the variable(s). Use "+", "-" or "." for add, subtract 1028/// or concatenate. 1029/// 1030/// @param copy copy values from "tv", don't move 1031/// @param semicolon from skip_var_list() 1032/// @param var_count from skip_var_list() 1033/// @param is_const lock variables for :const 1034/// 1035/// @return OK or FAIL; 1036int ex_let_vars (char * arg_start ,typval_T * tv ,int copy ,int semicolon ,int var_count ,int is_const , 1037char * op ) 1038{ 1039char * arg = arg_start ; 1040typval_T ltv ; 1041 1042if (* arg != '[' ) { 1043// ":let var = expr" or ":for var in list" 1044if (ex_let_one (arg ,tv ,copy ,is_const ,op ,op )== NULL ) { 1045return FAIL ; 1046 } 1047return OK ; 1048 } 1049 1050// ":let [v1, v2] = list" or ":for [v1, v2] in listlist" 1051if (tv -> v_type != VAR_LIST ) { 1052emsg (_ (e_listreq )); 1053return FAIL ; 1054 } 1055list_T * const l = tv -> vval .v_list ; 1056 1057const int len = tv_list_len (l ); 1058if (semicolon == 0 && var_count < len ) { 1059emsg (_ ("E687: Less targets than List items" )); 1060return FAIL ; 1061 } 1062if (var_count - semicolon > len ) { 1063emsg (_ ("E688: More targets than List items" )); 1064return FAIL ; 1065 } 1066// List l may actually be NULL, but it should fail with E688 or even earlier 1067// if you try to do ":let [] = v:_null_list". 1068assert (l != NULL ); 1069 1070listitem_T * item = tv_list_first (l ); 1071size_t rest_len = (size_t )tv_list_len (l ); 1072while (* arg != ']' ) { 1073arg = skipwhite (arg + 1 ); 1074arg = ex_let_one (arg ,TV_LIST_ITEM_TV (item ), true,is_const ,",;]" ,op ); 1075if (arg == NULL ) { 1076return FAIL ; 1077 } 1078rest_len -- ; 1079 1080item = TV_LIST_ITEM_NEXT (l ,item ); 1081arg = skipwhite (arg ); 1082if (* arg == ';' ) { 1083// Put the rest of the list (may be empty) in the var after ';'. 1084// Create a new list for this. 1085list_T * const rest_list = tv_list_alloc ((ptrdiff_t )rest_len ); 1086while (item != NULL ) { 1087tv_list_append_tv (rest_list ,TV_LIST_ITEM_TV (item )); 1088item = TV_LIST_ITEM_NEXT (l ,item ); 1089 } 1090 1091ltv .v_type = VAR_LIST ; 1092ltv .v_lock = VAR_UNLOCKED ; 1093ltv .vval .v_list = rest_list ; 1094tv_list_ref (rest_list ); 1095 1096arg = ex_let_one (skipwhite (arg + 1 ),& ltv , false,is_const ,"]" ,op ); 1097tv_clear (& ltv ); 1098if (arg == NULL ) { 1099return FAIL ; 1100 } 1101break ; 1102 }else if (* arg != ',' && * arg != ']' ) { 1103internal_error ("ex_let_vars()" ); 1104return FAIL ; 1105 } 1106 } 1107 1108return OK ; 1109} 1110 1111/// Skip over assignable variable "var" or list of variables "[var, var]". 1112/// Used for ":let varvar = expr" and ":for varvar in expr". 1113/// For "[var, var]" increment "*var_count" for each variable. 1114/// for "[var, var; var]" set "semicolon" to 1. 1115/// If "silent" is true do not give an "invalid argument" error message. 1116/// 1117/// @return NULL for an error. 1118const char * skip_var_list (const char * arg ,int * var_count ,int * semicolon ,bool silent ) 1119{ 1120if (* arg == '[' ) { 1121const char * s ; 1122// "[var, var]": find the matching ']'. 1123const char * p = arg ; 1124while (true) { 1125p = skipwhite (p + 1 );// skip whites after '[', ';' or ',' 1126s = skip_var_one (p ); 1127if (s == p ) { 1128if (!silent ) { 1129semsg (_ (e_invarg2 ),p ); 1130 } 1131return NULL ; 1132 } 1133 (* var_count )++ ; 1134 1135p = skipwhite (s ); 1136if (* p == ']' ) { 1137break ; 1138 }else if (* p == ';' ) { 1139if (* semicolon == 1 ) { 1140if (!silent ) { 1141emsg (_ (e_double_semicolon_in_list_of_variables )); 1142 } 1143return NULL ; 1144 } 1145* semicolon = 1 ; 1146 }else if (* p != ',' ) { 1147if (!silent ) { 1148semsg (_ (e_invarg2 ),p ); 1149 } 1150return NULL ; 1151 } 1152 } 1153return p + 1 ; 1154 } 1155return skip_var_one (arg ); 1156} 1157 1158/// Skip one (assignable) variable name, including @r, $VAR, &option, d.key, 1159/// l[idx]. 1160static const char * skip_var_one (const char * arg ) 1161{ 1162if (* arg == '@' && arg [1 ]!= NUL ) { 1163return arg + 2 ; 1164 } 1165return find_name_end (* arg == '$' || * arg == '&' ?arg + 1 :arg , 1166NULL ,NULL ,FNE_INCL_BR |FNE_CHECK_START ); 1167} 1168 1169/// List variables for hashtab "ht" with prefix "prefix". 1170/// 1171/// @param empty if true also list NULL strings as empty strings. 1172void list_hashtable_vars (hashtab_T * ht ,const char * prefix ,int empty ,int * first ) 1173{ 1174hashitem_T * hi ; 1175dictitem_T * di ; 1176int todo ; 1177 1178todo = (int )ht -> ht_used ; 1179for (hi = ht -> ht_array ;todo > 0 && !got_int ;hi ++ ) { 1180if (!HASHITEM_EMPTY (hi )) { 1181todo -- ; 1182di = TV_DICT_HI2DI (hi ); 1183char buf [IOSIZE ]; 1184 1185// apply :filter /pat/ to variable name 1186xstrlcpy (buf ,prefix ,IOSIZE ); 1187xstrlcat (buf ,di -> di_key ,IOSIZE ); 1188if (message_filtered (buf )) { 1189continue ; 1190 } 1191 1192if (empty || di -> di_tv .v_type != VAR_STRING 1193|| di -> di_tv .vval .v_string != NULL ) { 1194list_one_var (di ,prefix ,first ); 1195 } 1196 } 1197 } 1198} 1199 1200/// List global variables. 1201static void list_glob_vars (int * first ) 1202{ 1203list_hashtable_vars (& globvarht ,"" , true,first ); 1204} 1205 1206/// List buffer variables. 1207static void list_buf_vars (int * first ) 1208{ 1209list_hashtable_vars (& curbuf -> b_vars -> dv_hashtab ,"b:" , true,first ); 1210} 1211 1212/// List window variables. 1213static void list_win_vars (int * first ) 1214{ 1215list_hashtable_vars (& curwin -> w_vars -> dv_hashtab ,"w:" , true,first ); 1216} 1217 1218/// List tab page variables. 1219static void list_tab_vars (int * first ) 1220{ 1221list_hashtable_vars (& curtab -> tp_vars -> dv_hashtab ,"t:" , true,first ); 1222} 1223 1224/// List variables in "arg". 1225static const char * list_arg_vars (exarg_T * eap ,const char * arg ,int * first ) 1226{ 1227bool error = false; 1228int len ; 1229const char * name ; 1230const char * name_start ; 1231typval_T tv ; 1232 1233while (!ends_excmd (* arg )&& !got_int ) { 1234if (error || eap -> skip ) { 1235arg = find_name_end (arg ,NULL ,NULL ,FNE_INCL_BR |FNE_CHECK_START ); 1236if (!ascii_iswhite (* arg )&& !ends_excmd (* arg )) { 1237emsg_severe = true; 1238semsg (_ (e_trailing_arg ),arg ); 1239break ; 1240 } 1241 }else { 1242// get_name_len() takes care of expanding curly braces 1243name_start = name = arg ; 1244char * tofree ; 1245len = get_name_len (& arg ,& tofree , true, true); 1246if (len <=0 ) { 1247// This is mainly to keep test 49 working: when expanding 1248// curly braces fails overrule the exception error message. 1249if (len < 0 && !aborting ()) { 1250emsg_severe = true; 1251semsg (_ (e_invarg2 ),arg ); 1252break ; 1253 } 1254error = true; 1255 }else { 1256if (tofree != NULL ) { 1257name = tofree ; 1258 } 1259if (eval_variable (name ,len ,& tv ,NULL , true, false)== FAIL ) { 1260error = true; 1261 }else { 1262// handle d.key, l[idx], f(expr) 1263const char * const arg_subsc = arg ; 1264if (handle_subscript (& arg ,& tv ,& EVALARG_EVALUATE , true)== FAIL ) { 1265error = true; 1266 }else { 1267if (arg == arg_subsc && len == 2 && name [1 ]== ':' ) { 1268switch (* name ) { 1269case 'g' : 1270list_glob_vars (first );break ; 1271case 'b' : 1272list_buf_vars (first );break ; 1273case 'w' : 1274list_win_vars (first );break ; 1275case 't' : 1276list_tab_vars (first );break ; 1277case 'v' : 1278list_vim_vars (first );break ; 1279case 's' : 1280list_script_vars (first );break ; 1281case 'l' : 1282list_func_vars (first );break ; 1283default : 1284semsg (_ ("E738: Can't list variables for %s" ),name ); 1285 } 1286 }else { 1287char * const s = encode_tv2echo (& tv ,NULL ); 1288const char * const used_name = (arg == arg_subsc 1289 ?name 1290 :name_start ); 1291assert (used_name != NULL ); 1292const ptrdiff_t name_size = (used_name == tofree 1293 ? (ptrdiff_t )strlen (used_name ) 1294 : (arg - used_name )); 1295list_one_var_a ("" ,used_name ,name_size , 1296tv .v_type ,s == NULL ?"" :s ,first ); 1297xfree (s ); 1298 } 1299tv_clear (& tv ); 1300 } 1301 } 1302 } 1303 1304xfree (tofree ); 1305 } 1306 1307arg = skipwhite (arg ); 1308 } 1309 1310return arg ; 1311} 1312 1313/// Set an environment variable, part of ex_let_one(). 1314static char * ex_let_env (char * arg ,typval_T * const tv ,const bool is_const , 1315const char * const endchars ,const char * const op ) 1316FUNC_ATTR_NONNULL_ARG (1 ,2 )FUNC_ATTR_WARN_UNUSED_RESULT 1317{ 1318if (is_const ) { 1319emsg (_ ("E996: Cannot lock an environment variable" )); 1320return NULL ; 1321 } 1322 1323// Find the end of the name. 1324char * arg_end = NULL ; 1325arg ++ ; 1326char * name = arg ; 1327int len = get_env_len ((const char ** )& arg ); 1328if (len == 0 ) { 1329semsg (_ (e_invarg2 ),name - 1 ); 1330 }else { 1331if (op != NULL && vim_strchr ("+-*/%" , (uint8_t )(* op ))!= NULL ) { 1332semsg (_ (e_letwrong ),op ); 1333 }else if (endchars != NULL 1334&& vim_strchr (endchars , (uint8_t )(* skipwhite (arg )))== NULL ) { 1335emsg (_ (e_letunexp )); 1336 }else if (!check_secure ()) { 1337char * tofree = NULL ; 1338const char c1 = name [len ]; 1339name [len ]= NUL ; 1340const char * p = tv_get_string_chk (tv ); 1341if (p != NULL && op != NULL && * op == '.' ) { 1342char * s = vim_getenv (name ); 1343if (s != NULL ) { 1344tofree = concat_str (s ,p ); 1345p = tofree ; 1346xfree (s ); 1347 } 1348 } 1349if (p != NULL ) { 1350vim_setenv_ext (name ,p ); 1351arg_end = arg ; 1352 } 1353name [len ]= c1 ; 1354xfree (tofree ); 1355 } 1356 } 1357return arg_end ; 1358} 1359 1360/// Set an option, part of ex_let_one(). 1361static char * ex_let_option (char * arg ,typval_T * const tv ,const bool is_const , 1362const char * const endchars ,const char * const op ) 1363FUNC_ATTR_NONNULL_ARG (1 ,2 )FUNC_ATTR_WARN_UNUSED_RESULT 1364{ 1365if (is_const ) { 1366emsg (_ ("E996: Cannot lock an option" )); 1367return NULL ; 1368 } 1369 1370// Find the end of the name. 1371char * arg_end = NULL ; 1372OptIndex opt_idx ; 1373int opt_flags ; 1374 1375char * const p = (char * )find_option_var_end ((const char ** )& arg ,& opt_idx ,& opt_flags ); 1376 1377if (p == NULL || (endchars != NULL && vim_strchr (endchars , (uint8_t )(* skipwhite (p )))== NULL )) { 1378emsg (_ (e_letunexp )); 1379return NULL ; 1380 } 1381 1382const char c1 = * p ; 1383* p = NUL ; 1384 1385bool is_tty_opt = is_tty_option (arg ); 1386bool hidden = is_option_hidden (opt_idx ); 1387Object curval = is_tty_opt ?get_tty_option (arg ) :get_option_value (opt_idx ,opt_flags ); 1388Object newval = NIL ; 1389 1390if (curval .type == kObjectTypeNil ) { 1391semsg (_ (e_unknown_option2 ),arg ); 1392 gototheend ; 1393 } 1394if (op != NULL && * op != '=' 1395&& ((curval .type != kObjectTypeString && * op == '.' ) 1396|| (curval .type == kObjectTypeString && * op != '.' ))) { 1397semsg (_ (e_letwrong ),op ); 1398 gototheend ; 1399 } 1400 1401bool error ; 1402newval = opt_from_tv (tv ,opt_idx ,arg ,& error ); 1403if (error ) { 1404 gototheend ; 1405 } 1406 1407// Global-local w/ unset local: assigning -1 unsets it again, so `curval` and `newval` may differ. 1408// in type. Apply a compound operator only to concrete same-kind values. 1409const bool is_num = (curval .type == kObjectTypeInteger || curval .type == kObjectTypeBoolean ) 1410&& (newval .type == kObjectTypeInteger || newval .type == kObjectTypeBoolean ); 1411const bool is_string = curval .type == kObjectTypeString && newval .type == kObjectTypeString ; 1412 1413if (op != NULL && * op != '=' ) { 1414if (!hidden && is_num ) {// number or bool 1415OptInt cur_n = curval .type == kObjectTypeInteger ?curval .data .integer :curval .data .boolean ; 1416OptInt new_n = newval .type == kObjectTypeInteger ?newval .data .integer :newval .data .boolean ; 1417 1418switch (* op ) { 1419case '+' : 1420new_n = cur_n + new_n ;break ; 1421case '-' : 1422new_n = cur_n - new_n ;break ; 1423case '*' : 1424new_n = cur_n * new_n ;break ; 1425case '/' : 1426new_n = num_divide (cur_n ,new_n );break ; 1427case '%' : 1428new_n = num_modulus (cur_n ,new_n );break ; 1429 } 1430 1431if (curval .type == kObjectTypeInteger ) { 1432newval = INTEGER_OBJ (new_n ); 1433 }else { 1434newval = opt_from_tristate (TRISTATE_FROM_INT (new_n )); 1435 } 1436 }else if (!hidden && is_string ) {// string 1437const char * curval_data = curval .data .string .data ; 1438const char * newval_data = newval .data .string .data ; 1439 1440if (curval_data != NULL && newval_data != NULL ) { 1441Object newval_old = newval ; 1442newval = CSTR_AS_OBJ (concat_str (curval_data ,newval_data )); 1443optval_free (newval_old ); 1444 } 1445 } 1446 } 1447 1448arg_end = p ; 1449// Ignore TTY assignments after validation for compatibility with old vimrcs. 1450if (!is_tty_opt ) { 1451set_option_value_give_err (opt_idx ,newval ,opt_flags ); 1452 } 1453 1454theend : 1455* p = c1 ; 1456optval_free (curval ); 1457optval_free (newval ); 1458return arg_end ; 1459} 1460 1461/// Set a register, part of ex_let_one(). 1462static char * ex_let_register (char * arg ,typval_T * const tv ,const bool is_const , 1463const char * const endchars ,const char * const op ) 1464FUNC_ATTR_NONNULL_ARG (1 ,2 )FUNC_ATTR_WARN_UNUSED_RESULT 1465{ 1466if (is_const ) { 1467emsg (_ ("E996: Cannot lock a register" )); 1468return NULL ; 1469 } 1470 1471char * arg_end = NULL ; 1472arg ++ ; 1473if (op != NULL && vim_strchr ("+-*/%" , (uint8_t )(* op ))!= NULL ) { 1474semsg (_ (e_letwrong ),op ); 1475 }else if (endchars != NULL 1476&& vim_strchr (endchars , (uint8_t )(* skipwhite (arg + 1 )))== NULL ) { 1477emsg (_ (e_letunexp )); 1478 }else { 1479char * ptofree = NULL ; 1480const char * p = tv_get_string_chk (tv ); 1481if (p != NULL && op != NULL && * op == '.' ) { 1482char * s = get_reg_contents (* arg == '@' ?'"' :* arg ,kGRegExprSrc ); 1483if (s != NULL ) { 1484ptofree = concat_str (s ,p ); 1485p = ptofree ; 1486xfree (s ); 1487 } 1488 } 1489if (p != NULL ) { 1490write_reg_contents (* arg == '@' ?'"' :* arg ,p , (ssize_t )strlen (p ), false); 1491arg_end = arg + 1 ; 1492 } 1493xfree (ptofree ); 1494 } 1495return arg_end ; 1496} 1497 1498/// Set one item of `:let var = expr` or `:let [v1, v2] = list` to its value 1499/// 1500/// @param[in] arg Start of the variable name. 1501/// @param[in] tv Value to assign to the variable. 1502/// @param[in] copy If true, copy value from `tv`. 1503/// @param[in] endchars Valid characters after variable name or NULL. 1504/// @param[in] op Operation performed: *op is `+`, `-`, `.` for `+=`, etc. 1505/// NULL for `=`. 1506/// 1507/// @return a pointer to the char just after the var name or NULL in case of 1508/// error. 1509static char * ex_let_one (char * arg ,typval_T * const tv ,const bool copy ,const bool is_const , 1510const char * const endchars ,const char * const op ) 1511FUNC_ATTR_NONNULL_ARG (1 ,2 )FUNC_ATTR_WARN_UNUSED_RESULT 1512{ 1513char * arg_end = NULL ; 1514 1515if (* arg == '$' ) { 1516// ":let $VAR = expr": Set environment variable. 1517return ex_let_env (arg ,tv ,is_const ,endchars ,op ); 1518 }else if (* arg == '&' ) { 1519// ":let &option = expr": Set option value. 1520// ":let &l:option = expr": Set local option value. 1521// ":let &g:option = expr": Set global option value. 1522return ex_let_option (arg ,tv ,is_const ,endchars ,op ); 1523 }else if (* arg == '@' ) { 1524// ":let @r = expr": Set register contents. 1525return ex_let_register (arg ,tv ,is_const ,endchars ,op ); 1526 }else if (eval_isnamec1 (* arg )|| * arg == '{' ) { 1527// ":let var = expr": Set internal variable. 1528// ":let {expr} = expr": Idem, name made with curly braces 1529lval_T lv ; 1530char * const p = get_lval (arg ,tv ,& lv , false, false,0 ,FNE_CHECK_START ); 1531if (p != NULL && lv .ll_name != NULL ) { 1532if (endchars != NULL && vim_strchr (endchars , (uint8_t )(* skipwhite (p )))== NULL ) { 1533emsg (_ (e_letunexp )); 1534 }else { 1535set_var_lval (& lv ,p ,tv ,copy ,is_const ,op ); 1536arg_end = p ; 1537 } 1538 } 1539clear_lval (& lv ); 1540 }else { 1541semsg (_ (e_invarg2 ),arg ); 1542 } 1543 1544return arg_end ; 1545} 1546 1547/// ":unlet[!] var1 ... " command. 1548void ex_unlet (exarg_T * eap ) 1549{ 1550ex_unletlock (eap ,eap -> arg ,0 ,eap -> forceit ?GLV_QUIET :0 ,do_unlet_var ); 1551} 1552 1553/// ":lockvar" and ":unlockvar" commands 1554void ex_lockvar (exarg_T * eap ) 1555{ 1556char * arg = eap -> arg ; 1557int deep = 2 ; 1558 1559if (eap -> forceit ) { 1560deep = -1 ; 1561 }else if (ascii_isdigit (* arg )) { 1562deep = getdigits_int (& arg , false,-1 ); 1563arg = skipwhite (arg ); 1564 } 1565 1566ex_unletlock (eap ,arg ,deep ,0 ,do_lock_var ); 1567} 1568 1569/// Common parsing logic for :unlet, :lockvar and :unlockvar. 1570/// 1571/// Invokes `callback` afterwards if successful and `eap->skip == false`. 1572/// 1573/// @param[in] eap Ex command arguments for the command. 1574/// @param[in] argstart Start of the string argument for the command. 1575/// @param[in] deep Levels to (un)lock for :(un)lockvar, -1 to (un)lock 1576/// everything. 1577/// @param[in] callback Appropriate handler for the command. 1578static void ex_unletlock (exarg_T * eap ,char * argstart ,int deep ,int glv_flags , 1579ex_unletlock_callback callback ) 1580FUNC_ATTR_NONNULL_ALL 1581{ 1582char * arg = argstart ; 1583char * name_end ; 1584bool error = false; 1585lval_T lv ; 1586 1587do { 1588if (* arg == '$' ) { 1589lv .ll_name = arg ; 1590lv .ll_tv = NULL ; 1591arg ++ ; 1592if (get_env_len ((const char ** )& arg )== 0 ) { 1593semsg (_ (e_invarg2 ),arg - 1 ); 1594return ; 1595 } 1596assert (* lv .ll_name == '$' );// suppress clang "Uninitialized argument value" 1597if (!error && !eap -> skip && callback (& lv ,arg ,eap ,deep )== FAIL ) { 1598error = true; 1599 } 1600name_end = arg ; 1601 }else { 1602// Parse the name and find the end. 1603name_end = get_lval (arg ,NULL ,& lv , true,eap -> skip || error , 1604glv_flags ,FNE_CHECK_START ); 1605if (lv .ll_name == NULL ) { 1606error = true;// error, but continue parsing. 1607 } 1608if (name_end == NULL 1609|| (!ascii_iswhite (* name_end )&& !ends_excmd (* name_end ))) { 1610if (name_end != NULL ) { 1611emsg_severe = true; 1612semsg (_ (e_trailing_arg ),name_end ); 1613 } 1614if (!(eap -> skip || error )) { 1615clear_lval (& lv ); 1616 } 1617break ; 1618 } 1619 1620if (!error && !eap -> skip && callback (& lv ,name_end ,eap ,deep )== FAIL ) { 1621error = true; 1622 } 1623 1624if (!eap -> skip ) { 1625clear_lval (& lv ); 1626 } 1627 } 1628arg = skipwhite (name_end ); 1629 }while (!ends_excmd (* arg )); 1630 1631eap -> nextcmd = check_nextcmd (arg ); 1632} 1633 1634/// Unlet a variable indicated by `lp`. 1635/// 1636/// @param[in] lp The lvalue. 1637/// @param[in] name_end End of the string argument for the command. 1638/// @param[in] eap Ex command arguments for :unlet. 1639/// @param[in] deep Unused. 1640/// 1641/// @return OK on success, or FAIL on failure. 1642static int do_unlet_var (lval_T * lp ,char * name_end ,exarg_T * eap ,int deep FUNC_ATTR_UNUSED ) 1643FUNC_ATTR_NONNULL_ALL 1644{ 1645int forceit = eap -> forceit ; 1646int ret = OK ; 1647 1648if (lp -> ll_tv == NULL ) { 1649int cc = (uint8_t )(* name_end ); 1650* name_end = NUL ; 1651 1652// Environment variable, normal name or expanded name. 1653if (* lp -> ll_name == '$' ) { 1654vim_unsetenv_ext (lp -> ll_name + 1 ); 1655 }else if (do_unlet (lp -> ll_name ,lp -> ll_name_len ,forceit )== FAIL ) { 1656ret = FAIL ; 1657 } 1658* name_end = (char )cc ; 1659 }else if ((lp -> ll_list != NULL 1660// ll_list is not NULL when lvalue is not in a list, NULL lists 1661// yield E689. 1662&& value_check_lock (tv_list_locked (lp -> ll_list ), 1663lp -> ll_name , 1664lp -> ll_name_len )) 1665|| (lp -> ll_dict != NULL 1666&& value_check_lock (lp -> ll_dict -> dv_lock , 1667lp -> ll_name , 1668lp -> ll_name_len ))) { 1669return FAIL ; 1670 }else if (lp -> ll_range ) { 1671tv_list_unlet_range (lp -> ll_list ,lp -> ll_li ,lp -> ll_n1 , !lp -> ll_empty2 ,lp -> ll_n2 ); 1672 }else if (lp -> ll_list != NULL ) { 1673// unlet a List item. 1674tv_list_item_remove (lp -> ll_list ,lp -> ll_li ); 1675 }else { 1676// unlet a Dict item. 1677dict_T * d = lp -> ll_dict ; 1678assert (d != NULL ); 1679dictitem_T * di = lp -> ll_di ; 1680bool watched = tv_dict_is_watched (d ); 1681char * key = NULL ; 1682typval_T oldtv ; 1683 1684if (watched ) { 1685tv_copy (& di -> di_tv ,& oldtv ); 1686// need to save key because dictitem_remove will free it 1687key = xstrdup (di -> di_key ); 1688 } 1689 1690tv_dict_item_remove (d ,di ); 1691 1692if (watched ) { 1693tv_dict_watcher_notify (d ,key ,NULL ,& oldtv ); 1694tv_clear (& oldtv ); 1695xfree (key ); 1696 } 1697 } 1698 1699return ret ; 1700} 1701 1702/// Unlet one item or a range of items from a list. 1703/// Return OK or FAIL. 1704static void tv_list_unlet_range (list_T * const l ,listitem_T * const li_first ,const int n1_arg , 1705const bool has_n2 ,const int n2 ) 1706{ 1707assert (l != NULL ); 1708// Delete a range of List items. 1709listitem_T * li_last = li_first ; 1710int n1 = n1_arg ; 1711while (true) { 1712listitem_T * const li = TV_LIST_ITEM_NEXT (l ,li_last ); 1713n1 ++ ; 1714if (li == NULL || (has_n2 && n2 < n1 )) { 1715break ; 1716 } 1717li_last = li ; 1718 } 1719tv_list_remove_items (l ,li_first ,li_last ); 1720} 1721 1722/// unlet a variable 1723/// 1724/// @param[in] name Variable name to unlet. 1725/// @param[in] name_len Variable name length. 1726/// @param[in] forceit If true, do not complain if variable doesn’t exist. 1727/// 1728/// @return OK if it existed, FAIL otherwise. 1729int do_unlet (const char * const name ,const size_t name_len ,const bool forceit ) 1730FUNC_ATTR_NONNULL_ALL 1731{ 1732const char * varname = NULL ;// init to shut up gcc 1733dict_T * dict ; 1734hashtab_T * ht = find_var_ht_dict (name ,name_len ,& varname ,& dict ); 1735 1736if (ht != NULL && * varname != NUL ) { 1737dict_T * d = get_current_funccal_dict (ht ); 1738if (d == NULL ) { 1739if (ht == & globvarht ) { 1740d = & globvardict ; 1741 }else if (ht == & compat_hashtab ) { 1742d = & vimvardict ; 1743 }else { 1744dictitem_T * const di = find_var_in_ht (ht ,* name ,"" ,0 , false); 1745d = di -> di_tv .vval .v_dict ; 1746 } 1747if (d == NULL ) { 1748internal_error ("do_unlet()" ); 1749return FAIL ; 1750 } 1751 } 1752 1753hashitem_T * hi = hash_find (ht ,varname ); 1754if (HASHITEM_EMPTY (hi )) { 1755hi = find_hi_in_scoped_ht (name ,& ht ); 1756 } 1757if (hi != NULL && !HASHITEM_EMPTY (hi )) { 1758dictitem_T * const di = TV_DICT_HI2DI (hi ); 1759if (var_check_fixed (di -> di_flags ,name ,TV_CSTRING ) 1760|| var_check_ro (di -> di_flags ,name ,TV_CSTRING ) 1761|| value_check_lock (d -> dv_lock ,name ,TV_CSTRING )) { 1762return FAIL ; 1763 } 1764 1765if (value_check_lock (d -> dv_lock ,name ,TV_CSTRING )) { 1766return FAIL ; 1767 } 1768 1769typval_T oldtv ; 1770bool watched = tv_dict_is_watched (dict ); 1771 1772if (watched ) { 1773tv_copy (& di -> di_tv ,& oldtv ); 1774 } 1775 1776delete_var (ht ,hi ); 1777 1778if (watched ) { 1779tv_dict_watcher_notify (dict ,varname ,NULL ,& oldtv ); 1780tv_clear (& oldtv ); 1781 } 1782return OK ; 1783 } 1784 } 1785if (forceit ) { 1786return OK ; 1787 } 1788semsg (_ ("E108: No such variable: \"%s\"" ),name ); 1789return FAIL ; 1790} 1791 1792/// Lock or unlock variable indicated by `lp`. 1793/// 1794/// Locks if `eap->cmdidx == CMD_lockvar`, unlocks otherwise. 1795/// 1796/// @param[in] lp The lvalue. 1797/// @param[in] name_end Unused. 1798/// @param[in] eap Ex command arguments for :(un)lockvar. 1799/// @param[in] deep Levels to (un)lock, -1 to (un)lock everything. 1800/// 1801/// @return OK on success, or FAIL on failure. 1802static int do_lock_var (lval_T * lp ,char * name_end FUNC_ATTR_UNUSED ,exarg_T * eap ,int deep ) 1803FUNC_ATTR_NONNULL_ARG (1 ,3 ) 1804{ 1805bool lock = eap -> cmdidx == CMD_lockvar ; 1806int ret = OK ; 1807 1808if (lp -> ll_tv == NULL ) { 1809if (* lp -> ll_name == '$' ) { 1810semsg (_ (e_lock_unlock ),lp -> ll_name ); 1811ret = FAIL ; 1812 }else { 1813// Normal name or expanded name. 1814dictitem_T * const di = find_var (lp -> ll_name ,lp -> ll_name_len ,NULL , 1815 true); 1816if (di == NULL ) { 1817ret = FAIL ; 1818 }else if ((di -> di_flags & DI_FLAGS_FIX ) 1819&& di -> di_tv .v_type != VAR_DICT 1820&& di -> di_tv .v_type != VAR_LIST ) { 1821// For historical reasons this error is not given for Lists and 1822// Dictionaries. E.g. b: dictionary may be locked/unlocked. 1823semsg (_ (e_lock_unlock ),lp -> ll_name ); 1824ret = FAIL ; 1825 }else { 1826if (lock ) { 1827di -> di_flags |=DI_FLAGS_LOCK ; 1828 }else { 1829di -> di_flags &= (uint8_t )(~DI_FLAGS_LOCK ); 1830 } 1831if (deep != 0 ) { 1832tv_item_lock (& di -> di_tv ,deep ,lock , false); 1833 } 1834 } 1835 } 1836 }else if (deep == 0 ) { 1837// nothing to do 1838 }else if (lp -> ll_range ) { 1839listitem_T * li = lp -> ll_li ; 1840 1841// (un)lock a range of List items. 1842while (li != NULL && (lp -> ll_empty2 || lp -> ll_n2 >=lp -> ll_n1 )) { 1843tv_item_lock (TV_LIST_ITEM_TV (li ),deep ,lock , false); 1844li = TV_LIST_ITEM_NEXT (lp -> ll_list ,li ); 1845lp -> ll_n1 ++ ; 1846 } 1847 }else if (lp -> ll_list != NULL ) { 1848// (un)lock a List item. 1849tv_item_lock (TV_LIST_ITEM_TV (lp -> ll_li ),deep ,lock , false); 1850 }else { 1851// (un)lock a Dict item. 1852tv_item_lock (& lp -> ll_di -> di_tv ,deep ,lock , false); 1853 } 1854 1855return ret ; 1856} 1857 1858/// Delete all "menutrans_" variables. 1859void del_menutrans_vars (void ) 1860{ 1861hash_lock (& globvarht ); 1862HASHTAB_ITER (& globvarht ,hi , { 1863if (strncmp (hi -> hi_key ,"menutrans_" ,10 )== 0 ) { 1864delete_var (& globvarht ,hi ); 1865 } 1866 }); 1867hash_unlock (& globvarht ); 1868} 1869 1870/// @return global variable dictionary 1871dict_T * get_globvar_dict (void ) 1872FUNC_ATTR_PURE FUNC_ATTR_NONNULL_RET 1873{ 1874return & globvardict ; 1875} 1876 1877/// @return global variable hash table 1878hashtab_T * get_globvar_ht (void ) 1879{ 1880return & globvarht ; 1881} 1882 1883/// @return v: variable dictionary 1884dict_T * get_vimvar_dict (void ) 1885FUNC_ATTR_PURE FUNC_ATTR_NONNULL_RET 1886{ 1887return & vimvardict ; 1888} 1889 1890/// Set v:variable to tv. 1891/// 1892/// @param[in] idx Index of variable to set. 1893/// @param[in] val Value to set to. Will be copied. 1894void set_vim_var_tv (const VimVarIndex idx ,typval_T * const tv ) 1895{ 1896typval_T * tv_out = get_vim_var_tv (idx ); 1897tv_clear (tv_out ); 1898tv_copy (tv ,tv_out ); 1899} 1900 1901char * get_vim_var_name (const VimVarIndex idx ) 1902FUNC_ATTR_NONNULL_RET 1903{ 1904return vimvars [idx ].vv_name ; 1905} 1906 1907/// Get typval_T v: variable value. 1908typval_T * get_vim_var_tv (const VimVarIndex idx ) 1909{ 1910return & vimvars [idx ].vv_tv ; 1911} 1912 1913/// Get number v: variable value. 1914varnumber_T get_vim_var_nr (const VimVarIndex idx )FUNC_ATTR_PURE 1915{ 1916typval_T * tv = get_vim_var_tv (idx ); 1917return tv -> vval .v_number ; 1918} 1919 1920/// Get List v: variable value. Caller must take care of reference count when 1921/// needed. 1922list_T * get_vim_var_list (const VimVarIndex idx )FUNC_ATTR_PURE 1923{ 1924typval_T * tv = get_vim_var_tv (idx ); 1925return tv -> vval .v_list ; 1926} 1927 1928/// Get Dictionary v: variable value. Caller must take care of reference count 1929/// when needed. 1930dict_T * get_vim_var_dict (const VimVarIndex idx )FUNC_ATTR_PURE 1931{ 1932typval_T * tv = get_vim_var_tv (idx ); 1933return tv -> vval .v_dict ; 1934} 1935 1936/// Get string v: variable value. Uses a static buffer, can only be used once. 1937/// If the String variable has never been set, return an empty string. 1938/// Never returns NULL. 1939char * get_vim_var_str (const VimVarIndex idx ) 1940FUNC_ATTR_PURE FUNC_ATTR_NONNULL_RET 1941{ 1942return (char * )tv_get_string (get_vim_var_tv (idx )); 1943} 1944 1945/// Get Partial v: variable value. Caller must take care of reference count 1946/// when needed. 1947partial_T * get_vim_var_partial (const VimVarIndex idx )FUNC_ATTR_PURE 1948{ 1949typval_T * tv = get_vim_var_tv (idx ); 1950return tv -> vval .v_partial ; 1951} 1952 1953/// Local string buffer for the next two functions to store a variable name 1954/// with its prefix. Allocated in cat_prefix_varname(), freed later in 1955/// get_user_var_name(). 1956 1957static char * varnamebuf = NULL ; 1958static size_t varnamebuflen = 0 ; 1959 1960/// Function to concatenate a prefix and a variable name. 1961char * cat_prefix_varname (int prefix ,const char * name ) 1962FUNC_ATTR_NONNULL_ALL 1963{ 1964size_t len = strlen (name )+ 3 ; 1965 1966if (len > varnamebuflen ) { 1967xfree (varnamebuf ); 1968len += 10 ;// some additional space 1969varnamebuf = xmalloc (len ); 1970varnamebuflen = len ; 1971 } 1972* varnamebuf = (char )prefix ; 1973varnamebuf [1 ]= ':' ; 1974STRCPY (varnamebuf + 2 ,name ); 1975return varnamebuf ; 1976} 1977 1978/// Function given to ExpandGeneric() to obtain the list of user defined 1979/// (global/buffer/window/built-in) variable names. 1980char * get_user_var_name (expand_T * xp ,int idx ) 1981{ 1982static size_t gdone ; 1983static size_t bdone ; 1984static size_t wdone ; 1985static size_t tdone ; 1986static size_t vidx ; 1987static hashitem_T * hi ; 1988 1989if (idx == 0 ) { 1990gdone = bdone = wdone = vidx = 0 ; 1991tdone = 0 ; 1992 } 1993 1994// Global variables 1995if (gdone < globvarht .ht_used ) { 1996if (gdone ++ == 0 ) { 1997hi = globvarht .ht_array ; 1998 }else { 1999hi ++ ; 2000 } 2001while (HASHITEM_EMPTY (hi )) { 2002hi ++ ; 2003 } 2004if (strncmp ("g:" ,xp -> xp_pattern ,2 )== 0 ) { 2005return cat_prefix_varname ('g' ,hi -> hi_key ); 2006 } 2007return hi -> hi_key ; 2008 } 2009 2010// b: variables 2011const hashtab_T * ht = & prevwin_curwin ()-> w_buffer -> b_vars -> dv_hashtab ; 2012if (bdone < ht -> ht_used ) { 2013if (bdone ++ == 0 ) { 2014hi = ht -> ht_array ; 2015 }else { 2016hi ++ ; 2017 } 2018while (HASHITEM_EMPTY (hi )) { 2019hi ++ ; 2020 } 2021return cat_prefix_varname ('b' ,hi -> hi_key ); 2022 } 2023 2024// w: variables 2025ht = & prevwin_curwin ()-> w_vars -> dv_hashtab ; 2026if (wdone < ht -> ht_used ) { 2027if (wdone ++ == 0 ) { 2028hi = ht -> ht_array ; 2029 }else { 2030hi ++ ; 2031 } 2032while (HASHITEM_EMPTY (hi )) { 2033hi ++ ; 2034 } 2035return cat_prefix_varname ('w' ,hi -> hi_key ); 2036 } 2037 2038// t: variables 2039ht = & curtab -> tp_vars -> dv_hashtab ; 2040if (tdone < ht -> ht_used ) { 2041if (tdone ++ == 0 ) { 2042hi = ht -> ht_array ; 2043 }else { 2044hi ++ ; 2045 } 2046while (HASHITEM_EMPTY (hi )) { 2047hi ++ ; 2048 } 2049return cat_prefix_varname ('t' ,hi -> hi_key ); 2050 } 2051 2052// v: variables 2053if (vidx < ARRAY_SIZE (vimvars )) { 2054return cat_prefix_varname ('v' ,get_vim_var_name ((VimVarIndex )vidx ++ )); 2055 } 2056 2057XFREE_CLEAR (varnamebuf ); 2058varnamebuflen = 0 ; 2059return NULL ; 2060} 2061 2062/// Set type of v: variable to the given type. 2063/// 2064/// @param[in] idx Index of variable to set. 2065/// @param[in] type Type to set to. 2066void set_vim_var_type (const VimVarIndex idx ,const VarType type ) 2067{ 2068typval_T * tv = get_vim_var_tv (idx ); 2069tv -> v_type = type ; 2070} 2071 2072/// Set number v: variable to the given value 2073/// Note that this does not set the type, use set_vim_var_type() for that. 2074/// 2075/// @param[in] idx Index of variable to set. 2076/// @param[in] val Value to set to. 2077void set_vim_var_nr (const VimVarIndex idx ,const varnumber_T val ) 2078{ 2079typval_T * tv = get_vim_var_tv (idx ); 2080tv_clear (tv ); 2081tv -> vval .v_number = val ; 2082} 2083 2084/// Set boolean v: {true, false} to the given value 2085/// 2086/// @param[in] idx Index of variable to set. 2087/// @param[in] val Value to set to. 2088void set_vim_var_bool (const VimVarIndex idx ,const BoolVarValue val ) 2089{ 2090typval_T * tv = get_vim_var_tv (idx ); 2091tv_clear (tv ); 2092tv -> v_type = VAR_BOOL ; 2093tv -> vval .v_bool = val ; 2094} 2095 2096/// Set special v: variable to the given value 2097/// 2098/// @param[in] idx Index of variable to set. 2099/// @param[in] val Value to set to. 2100void set_vim_var_special (const VimVarIndex idx ,const SpecialVarValue val ) 2101{ 2102typval_T * tv = get_vim_var_tv (idx ); 2103tv_clear (tv ); 2104tv -> v_type = VAR_SPECIAL ; 2105tv -> vval .v_special = val ; 2106} 2107 2108/// Set v:char to character "c". 2109void set_vim_var_char (int c ) 2110{ 2111char buf [MB_MAXCHAR + 1 ]; 2112int buflen = utf_char2bytes (c ,buf ); 2113buf [buflen ]= NUL ; 2114set_vim_var_string (VV_CHAR ,buf ,buflen ); 2115} 2116 2117/// Set string v: variable to the given string 2118/// 2119/// @param[in] idx Index of variable to set. 2120/// @param[in] val Value to set to. Will be copied. 2121/// @param[in] len Length of that value or -1 in which case strlen() will be 2122/// used. 2123void set_vim_var_string (const VimVarIndex idx ,const char * const val ,const ptrdiff_t len ) 2124{ 2125typval_T * tv = get_vim_var_tv (idx ); 2126tv_clear (tv ); 2127tv -> v_type = VAR_STRING ; 2128if (val == NULL ) { 2129tv -> vval .v_string = NULL ; 2130 }else if (len == -1 ) { 2131tv -> vval .v_string = xstrdup (val ); 2132 }else { 2133tv -> vval .v_string = xstrndup (val , (size_t )len ); 2134 } 2135} 2136 2137/// Set list v: variable to the given list 2138/// 2139/// @param[in] idx Index of variable to set. 2140/// @param[in,out] val Value to set to. Reference count will be incremented. 2141void set_vim_var_list (const VimVarIndex idx ,list_T * const val ) 2142{ 2143typval_T * tv = get_vim_var_tv (idx ); 2144tv_clear (tv ); 2145tv -> v_type = VAR_LIST ; 2146tv -> vval .v_list = val ; 2147if (val != NULL ) { 2148tv_list_ref (val ); 2149 } 2150} 2151 2152/// Set Dictionary v: variable to the given dictionary 2153/// 2154/// @param[in] idx Index of variable to set. 2155/// @param[in,out] val Value to set to. Reference count will be incremented. 2156/// Also keys of the dictionary will be made read-only. 2157void set_vim_var_dict (const VimVarIndex idx ,dict_T * const val ) 2158{ 2159typval_T * tv = get_vim_var_tv (idx ); 2160tv_clear (tv ); 2161tv -> v_type = VAR_DICT ; 2162tv -> vval .v_dict = val ; 2163if (val == NULL ) { 2164return ; 2165 } 2166 2167val -> dv_refcount ++ ; 2168// Set readonly 2169tv_dict_set_keys_readonly (val ); 2170} 2171 2172/// Set partial v: variable to the given value 2173/// Note that this does not set the type, use set_vim_var_type() for that. 2174/// 2175/// @param[in] idx Index of variable to set. 2176/// @param[in] val Value to set to. 2177void set_vim_var_partial (const VimVarIndex idx ,partial_T * val ) 2178{ 2179typval_T * tv = get_vim_var_tv (idx ); 2180tv -> vval .v_partial = val ; 2181} 2182 2183/// Set v:register if needed. 2184void set_reg_var (int c ) 2185{ 2186char regname [2 ]; 2187 2188if (c == 0 || c == ' ' ) { 2189regname [0 ]= '"' ; 2190 }else { 2191regname [0 ]= (char )c ; 2192 } 2193regname [1 ]= NUL ; 2194// Avoid free/alloc when the value is already right. 2195typval_T * tv = get_vim_var_tv (VV_REG ); 2196if (tv -> vval .v_string == NULL || tv -> vval .v_string [0 ]!= c ) { 2197set_vim_var_string (VV_REG ,regname ,1 ); 2198 } 2199} 2200 2201/// Get or set v:exception. If "oldval" == NULL, return the current value. 2202/// Otherwise, restore the value to "oldval" and return NULL. 2203/// Must always be called in pairs to save and restore v:exception! Does not 2204/// take care of memory allocations. 2205char * v_exception (char * oldval ) 2206{ 2207typval_T * tv = get_vim_var_tv (VV_EXCEPTION ); 2208if (oldval == NULL ) { 2209return tv -> vval .v_string ; 2210 } 2211 2212tv -> vval .v_string = oldval ; 2213return NULL ; 2214} 2215 2216/// Set v:cmdarg. 2217/// If "eap" != NULL, use "eap" to generate the value and return the old value. 2218/// If "oldarg" != NULL, restore the value to "oldarg" and return NULL. 2219/// Must always be called in pairs! 2220char * set_cmdarg (exarg_T * eap ,char * oldarg ) 2221{ 2222typval_T * tv = get_vim_var_tv (VV_CMDARG ); 2223char * oldval = tv -> vval .v_string ; 2224if (eap == NULL ) { 2225 gotoerror ; 2226 } 2227 2228size_t len = 0 ; 2229if (eap -> force_bin == FORCE_BIN ) { 2230len += 6 ;// " ++bin" 2231 }else if (eap -> force_bin == FORCE_NOBIN ) { 2232len += 8 ;// " ++nobin" 2233 } 2234 2235if (eap -> read_edit ) { 2236len += 7 ;// " ++edit" 2237 } 2238 2239if (eap -> force_ff != 0 ) { 2240len += 10 ;// " ++ff=unix" 2241 } 2242if (eap -> force_enc != 0 ) { 2243len += strlen (eap -> cmd + eap -> force_enc )+ 7 ; 2244 } 2245if (eap -> bad_char != 0 ) { 2246len += 7 + 4 ;// " ++bad=" + "keep" or "drop" 2247 } 2248if (eap -> mkdir_p != 0 ) { 2249len += 4 ;// " ++p" 2250 } 2251 2252const size_t newval_len = len + 1 ; 2253char * newval = xmalloc (newval_len ); 2254size_t xlen = 0 ; 2255int rc = 0 ; 2256 2257if (eap -> force_bin == FORCE_BIN ) { 2258rc = snprintf (newval ,newval_len ," ++bin" ); 2259 }else if (eap -> force_bin == FORCE_NOBIN ) { 2260rc = snprintf (newval ,newval_len ," ++nobin" ); 2261 }else { 2262* newval = NUL ; 2263 } 2264if (rc < 0 ) { 2265 gotoerror ; 2266 } 2267xlen += (size_t )rc ; 2268 2269if (eap -> read_edit ) { 2270rc = snprintf (newval + xlen ,newval_len - xlen ," ++edit" ); 2271if (rc < 0 ) { 2272 gotoerror ; 2273 } 2274xlen += (size_t )rc ; 2275 } 2276 2277if (eap -> force_ff != 0 ) { 2278rc = snprintf (newval + xlen , 2279newval_len - xlen , 2280" ++ff=%s" , 2281eap -> force_ff == 'u' ?"unix" 2282 :eap -> force_ff == 'd' ?"dos" :"mac" ); 2283if (rc < 0 ) { 2284 gotoerror ; 2285 } 2286xlen += (size_t )rc ; 2287 } 2288if (eap -> force_enc != 0 ) { 2289rc = snprintf (newval + xlen ,newval_len - xlen ," ++enc=%s" ,eap -> cmd + eap -> force_enc ); 2290if (rc < 0 ) { 2291 gotoerror ; 2292 } 2293xlen += (size_t )rc ; 2294 } 2295 2296if (eap -> bad_char == BAD_KEEP ) { 2297rc = snprintf (newval + xlen ,newval_len - xlen ," ++bad=keep" ); 2298if (rc < 0 ) { 2299 gotoerror ; 2300 } 2301xlen += (size_t )rc ; 2302 }else if (eap -> bad_char == BAD_DROP ) { 2303rc = snprintf (newval + xlen ,newval_len - xlen ," ++bad=drop" ); 2304if (rc < 0 ) { 2305 gotoerror ; 2306 } 2307xlen += (size_t )rc ; 2308 }else if (eap -> bad_char != 0 ) { 2309rc = snprintf (newval + xlen ,newval_len - xlen ," ++bad=%c" ,eap -> bad_char ); 2310if (rc < 0 ) { 2311 gotoerror ; 2312 } 2313xlen += (size_t )rc ; 2314 } 2315 2316if (eap -> mkdir_p != 0 ) { 2317rc = snprintf (newval + xlen ,newval_len - xlen ," ++p" ); 2318if (rc < 0 ) { 2319 gotoerror ; 2320 } 2321xlen += (size_t )rc ; 2322 } 2323assert (xlen <=newval_len ); 2324 2325tv -> vval .v_string = newval ; 2326return oldval ; 2327 2328error : 2329xfree (oldval ); 2330tv -> vval .v_string = oldarg ; 2331return NULL ; 2332} 2333 2334/// Get or set v:throwpoint. If "oldval" == NULL, return the current value. 2335/// Otherwise, restore the value to "oldval" and return NULL. 2336/// Must always be called in pairs to save and restore v:throwpoint! Does not 2337/// take care of memory allocations. 2338char * v_throwpoint (char * oldval ) 2339{ 2340typval_T * tv = get_vim_var_tv (VV_THROWPOINT ); 2341if (oldval == NULL ) { 2342return tv -> vval .v_string ; 2343 } 2344 2345tv -> vval .v_string = oldval ; 2346return NULL ; 2347} 2348 2349/// Set v:count to "count" and v:count1 to "count1". 2350/// 2351/// @param set_prevcount if true, first set v:prevcount from v:count. 2352void set_vcount (int64_t count ,int64_t count1 ,bool set_prevcount ) 2353{ 2354if (set_prevcount ) { 2355get_vim_var_tv (VV_PREVCOUNT )-> vval .v_number = get_vim_var_nr (VV_COUNT ); 2356 } 2357get_vim_var_tv (VV_COUNT )-> vval .v_number = count ; 2358get_vim_var_tv (VV_COUNT1 )-> vval .v_number = count1 ; 2359} 2360 2361/// Get the value of internal variable "name". 2362/// Return OK or FAIL. If OK is returned "rettv" must be cleared. 2363/// 2364/// @param len length of "name" 2365/// @param rettv NULL when only checking existence 2366/// @param dip non-NULL when typval's dict item is needed 2367/// @param verbose may give error message 2368/// @param no_autoload do not use script autoloading 2369int eval_variable (const char * name ,int len ,typval_T * rettv ,dictitem_T ** dip ,bool verbose , 2370bool no_autoload ) 2371{ 2372int ret = OK ; 2373typval_T * tv = NULL ; 2374dictitem_T * v ; 2375 2376v = find_var (name , (size_t )len ,NULL ,no_autoload ); 2377if (v != NULL ) { 2378tv = & v -> di_tv ; 2379if (dip != NULL ) { 2380* dip = v ; 2381 } 2382 } 2383 2384if (tv == NULL ) { 2385if (rettv != NULL && verbose ) { 2386semsg (_ ("E121: Undefined variable: %.*s" ),len ,name ); 2387 } 2388ret = FAIL ; 2389 }else if (rettv != NULL ) { 2390tv_copy (tv ,rettv ); 2391 } 2392 2393return ret ; 2394} 2395 2396/// Check if variable "name[len]" is a local variable or an argument. 2397/// If so, "*eval_lavars_used" is set to true. 2398void check_vars (const char * name ,size_t len ) 2399{ 2400if (eval_lavars_used == NULL ) { 2401return ; 2402 } 2403 2404const char * varname ; 2405hashtab_T * ht = find_var_ht (name ,len ,& varname ); 2406 2407if (ht == get_funccal_local_ht ()|| ht == get_funccal_args_ht ()) { 2408if (find_var (name ,len ,NULL , true)!= NULL ) { 2409* eval_lavars_used = true; 2410 } 2411 } 2412} 2413 2414/// Find variable "name" in the list of variables. 2415/// Careful: "a:0" variables don't have a name. 2416/// When "htp" is not NULL we are writing to the variable, set "htp" to the 2417/// hashtab_T used. 2418/// 2419/// @return a pointer to it if found, NULL if not found. 2420dictitem_T * find_var (const char * const name ,const size_t name_len ,hashtab_T ** htp , 2421int no_autoload ) 2422{ 2423const char * varname ; 2424hashtab_T * const ht = find_var_ht (name ,name_len ,& varname ); 2425if (htp != NULL ) { 2426* htp = ht ; 2427 } 2428if (ht == NULL ) { 2429return NULL ; 2430 } 2431dictitem_T * const ret = find_var_in_ht (ht ,* name , 2432varname , 2433name_len - (size_t )(varname - name ), 2434no_autoload || htp != NULL ); 2435if (ret != NULL ) { 2436return ret ; 2437 } 2438 2439// Search in parent scope for lambda 2440return find_var_in_scoped_ht (name ,name_len ,no_autoload || htp != NULL ); 2441} 2442 2443/// Find variable in hashtab. 2444/// When "varname" is empty returns curwin/curtab/etc vars dictionary. 2445/// 2446/// @param[in] ht Hashtab to find variable in. 2447/// @param[in] htname Hashtab name (first character). 2448/// @param[in] varname Variable name. 2449/// @param[in] varname_len Variable name length. 2450/// @param[in] no_autoload If true then autoload scripts will not be sourced 2451/// if autoload variable was not found. 2452/// 2453/// @return pointer to the dictionary item with the found variable or NULL if it 2454/// was not found. 2455dictitem_T * find_var_in_ht (hashtab_T * const ht ,int htname ,const char * const varname , 2456const size_t varname_len ,int no_autoload ) 2457FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL 2458{ 2459if (varname_len == 0 ) { 2460// Must be something like "s:", otherwise "ht" would be NULL. 2461switch (htname ) { 2462case 's' : 2463return (dictitem_T * )& SCRIPT_SV (current_sctx .sc_sid )-> sv_var ; 2464case 'g' : 2465return (dictitem_T * )& globvars_var ; 2466case 'v' : 2467return (dictitem_T * )& vimvars_var ; 2468case 'b' : 2469return (dictitem_T * )& curbuf -> b_bufvar ; 2470case 'w' : 2471return (dictitem_T * )& curwin -> w_winvar ; 2472case 't' : 2473return (dictitem_T * )& curtab -> tp_winvar ; 2474case 'l' : 2475return get_funccal_local_var (); 2476case 'a' : 2477return get_funccal_args_var (); 2478 } 2479return NULL ; 2480 } 2481 2482hashitem_T * hi = hash_find_len (ht ,varname ,varname_len ); 2483if (HASHITEM_EMPTY (hi )) { 2484// For global variables we may try auto-loading the script. If it 2485// worked find the variable again. Don't auto-load a script if it was 2486// loaded already, otherwise it would be loaded every time when 2487// checking if a function name is a Funcref variable. 2488if (ht == get_globvar_ht ()&& !no_autoload ) { 2489// Note: script_autoload() may make "hi" invalid. It must either 2490// be obtained again or not used. 2491if (!script_autoload (varname ,varname_len , false)|| aborting ()) { 2492return NULL ; 2493 } 2494hi = hash_find_len (ht ,varname ,varname_len ); 2495 } 2496if (HASHITEM_EMPTY (hi )) { 2497return NULL ; 2498 } 2499 } 2500return TV_DICT_HI2DI (hi ); 2501} 2502 2503/// Finds the dict (g:, l:, s:, …) and hashtable used for a variable. 2504/// 2505/// Assigns SID if s: scope is accessed from Lua or anonymous Vimscript. #15994 2506/// 2507/// @param[in] name Variable name, possibly with scope prefix. 2508/// @param[in] name_len Variable name length. 2509/// @param[out] varname Will be set to the start of the name without scope 2510/// prefix. 2511/// @param[out] d Scope dictionary. 2512/// 2513/// @return Scope hashtab, NULL if name is not valid. 2514static hashtab_T * find_var_ht_dict (const char * name ,const size_t name_len ,const char ** varname , 2515dict_T ** d ) 2516{ 2517* d = NULL ; 2518 2519if (name_len == 0 ) { 2520return NULL ; 2521 } 2522if (name_len == 1 || name [1 ]!= ':' ) { 2523// name has implicit scope 2524if (name [0 ]== ':' || name [0 ]== AUTOLOAD_CHAR ) { 2525// The name must not start with a colon or #. 2526return NULL ; 2527 } 2528* varname = name ; 2529 2530// "version" is "v:version" in all scopes 2531hashitem_T * hi = hash_find_len (& compat_hashtab ,name ,name_len ); 2532if (!HASHITEM_EMPTY (hi )) { 2533return & compat_hashtab ; 2534 } 2535 2536* d = get_funccal_local_dict (); 2537if (* d != NULL ) {// local variable 2538 gotoend ; 2539 } 2540 2541* d = get_globvar_dict ();// global variable 2542 gotoend ; 2543 } 2544 2545* varname = name + 2 ; 2546if (* name == 'g' ) {// global variable 2547* d = get_globvar_dict (); 2548 }else if (name_len > 2 2549&& (memchr (name + 2 ,':' ,name_len - 2 )!= NULL 2550|| memchr (name + 2 ,AUTOLOAD_CHAR ,name_len - 2 )!= NULL )) { 2551// There must be no ':' or '#' in the rest of the name if g: was not used 2552return NULL ; 2553 } 2554 2555if (* name == 'b' ) {// buffer variable 2556* d = curbuf -> b_vars ; 2557 }else if (* name == 'w' ) {// window variable 2558* d = curwin -> w_vars ; 2559 }else if (* name == 't' ) {// tab page variable 2560* d = curtab -> tp_vars ; 2561 }else if (* name == 'v' ) {// v: variable 2562* d = get_vimvar_dict (); 2563 }else if (* name == 'a' ) {// a: function argument 2564* d = get_funccal_args_dict (); 2565 }else if (* name == 'l' ) {// l: local variable 2566* d = get_funccal_local_dict (); 2567 }else if (* name == 's' // script variable 2568&& (current_sctx .sc_sid > 0 || current_sctx .sc_sid == SID_STR 2569|| current_sctx .sc_sid == SID_LUA ) 2570&& current_sctx .sc_sid <=script_items .ga_len ) { 2571// For anonymous scripts without a script item, create one now so script vars can be used 2572// Try to resolve lua filename & linenr so it can be shown in last-set messages. 2573nlua_set_sctx (& current_sctx ); 2574if (current_sctx .sc_sid == SID_STR || current_sctx .sc_sid == SID_LUA ) { 2575// Create SID if s: scope is accessed from Lua or anon Vimscript. #15994 2576new_script_item (NULL ,& current_sctx .sc_sid ); 2577 } 2578* d = & SCRIPT_SV (current_sctx .sc_sid )-> sv_dict ; 2579 } 2580 2581end : 2582return * d ?& (* d )-> dv_hashtab :NULL ; 2583} 2584 2585/// Find the hashtable used for a variable 2586/// 2587/// @param[in] name Variable name, possibly with scope prefix. 2588/// @param[in] name_len Variable name length. 2589/// @param[out] varname Will be set to the start of the name without scope 2590/// prefix. 2591/// 2592/// @return Scope hashtab, NULL if name is not valid. 2593hashtab_T * find_var_ht (const char * name ,const size_t name_len ,const char ** varname ) 2594{ 2595dict_T * d ; 2596return find_var_ht_dict (name ,name_len ,varname ,& d ); 2597} 2598 2599/// @return the string value of a (global/local) variable or 2600/// NULL when it doesn't exist. 2601/// 2602/// @see tv_get_string() for how long the pointer remains valid. 2603char * get_var_value (const char * const name ) 2604{ 2605dictitem_T * v ; 2606 2607v = find_var (name ,strlen (name ),NULL , false); 2608if (v == NULL ) { 2609return NULL ; 2610 } 2611return (char * )tv_get_string (& v -> di_tv ); 2612} 2613 2614/// Allocate a new hashtab for a sourced script. It will be used while 2615/// sourcing this script and when executing functions defined in the script. 2616void new_script_vars (scid_T id ) 2617{ 2618scriptvar_T * sv = xcalloc (1 ,sizeof (scriptvar_T )); 2619init_var_dict (& sv -> sv_dict ,& sv -> sv_var ,VAR_SCOPE ); 2620SCRIPT_ITEM (id )-> sn_vars = sv ; 2621} 2622 2623/// Initialize dictionary "dict" as a scope and set variable "dict_var" to 2624/// point to it. 2625void init_var_dict (dict_T * dict ,ScopeDictDictItem * dict_var ,ScopeType scope ) 2626{ 2627hash_init (& dict -> dv_hashtab ); 2628dict -> dv_lock = VAR_UNLOCKED ; 2629dict -> dv_scope = scope ; 2630dict -> dv_refcount = DO_NOT_FREE_CNT ; 2631dict -> dv_copyID = 0 ; 2632dict_var -> di_tv .vval .v_dict = dict ; 2633dict_var -> di_tv .v_type = VAR_DICT ; 2634dict_var -> di_tv .v_lock = VAR_FIXED ; 2635dict_var -> di_flags = DI_FLAGS_RO |DI_FLAGS_FIX ; 2636dict_var -> di_key [0 ]= NUL ; 2637QUEUE_INIT (& dict -> watchers ); 2638} 2639 2640/// Unreference a dictionary initialized by init_var_dict(). 2641void unref_var_dict (dict_T * dict ) 2642{ 2643// Now the dict needs to be freed if no one else is using it, go back to 2644// normal reference counting. 2645dict -> dv_refcount -= DO_NOT_FREE_CNT - 1 ; 2646tv_dict_unref (dict ); 2647} 2648 2649/// Clean up a list of internal variables. 2650/// Frees all allocated variables and the value they contain. 2651/// Clears hashtab "ht", does not free it. 2652void vars_clear (hashtab_T * ht ) 2653{ 2654vars_clear_ext (ht , true); 2655} 2656 2657/// Like vars_clear(), but only free the value if "free_val" is true. 2658void vars_clear_ext (hashtab_T * ht ,bool free_val ) 2659{ 2660int todo ; 2661hashitem_T * hi ; 2662dictitem_T * v ; 2663 2664hash_lock (ht ); 2665todo = (int )ht -> ht_used ; 2666for (hi = ht -> ht_array ;todo > 0 ;hi ++ ) { 2667if (!HASHITEM_EMPTY (hi )) { 2668todo -- ; 2669 2670// Free the variable. Don't remove it from the hashtab, 2671// ht_array might change then. hash_clear() takes care of it 2672// later. 2673v = TV_DICT_HI2DI (hi ); 2674if (free_val ) { 2675tv_clear (& v -> di_tv ); 2676 } 2677if (v -> di_flags & DI_FLAGS_ALLOC ) { 2678xfree (v ); 2679 } 2680 } 2681 } 2682hash_clear (ht ); 2683hash_init (ht ); 2684} 2685 2686/// Delete a variable from hashtab "ht" at item "hi". 2687/// Clear the variable value and free the dictitem. 2688static void delete_var (hashtab_T * ht ,hashitem_T * hi ) 2689{ 2690dictitem_T * di = TV_DICT_HI2DI (hi ); 2691 2692hash_remove (ht ,hi ); 2693tv_clear (& di -> di_tv ); 2694xfree (di ); 2695} 2696 2697/// List the value of one internal variable. 2698static void list_one_var (dictitem_T * v ,const char * prefix ,int * first ) 2699{ 2700char * const s = encode_tv2echo (& v -> di_tv ,NULL ); 2701list_one_var_a (prefix ,v -> di_key , (ptrdiff_t )strlen (v -> di_key ), 2702v -> di_tv .v_type , (s == NULL ?"" :s ),first ); 2703xfree (s ); 2704} 2705 2706/// @param[in] name_len Length of the name. May be -1, in this case strlen() 2707/// will be used. 2708/// @param[in,out] first When true clear rest of screen and set to false. 2709static void list_one_var_a (const char * prefix ,const char * name ,const ptrdiff_t name_len , 2710const VarType type ,const char * string ,int * first ) 2711{ 2712if (* first ) { 2713msg_ext_set_kind ("list_cmd" ); 2714msg_start (); 2715 }else { 2716msg_putchar ('\n' ); 2717 } 2718// don't use msg() to avoid overwriting "v:statusmsg" 2719if (* prefix != NUL ) { 2720msg_puts (prefix ); 2721 } 2722if (name != NULL ) {// "a:" vars don't have a name stored 2723msg_puts_len (name ,name_len ,0 , false); 2724 } 2725msg_putchar (' ' ); 2726msg_advance (22 ); 2727if (type == VAR_NUMBER ) { 2728msg_putchar ('#' ); 2729 }else if (type == VAR_FUNC || type == VAR_PARTIAL ) { 2730msg_putchar ('*' ); 2731 }else if (type == VAR_LIST ) { 2732msg_putchar ('[' ); 2733if (* string == '[' ) { 2734string ++ ; 2735 } 2736 }else if (type == VAR_DICT ) { 2737msg_putchar ('{' ); 2738if (* string == '{' ) { 2739string ++ ; 2740 } 2741 }else { 2742msg_putchar (' ' ); 2743 } 2744 2745msg_outtrans (string ,0 , false); 2746 2747if (type == VAR_FUNC || type == VAR_PARTIAL ) { 2748msg_puts ("()" ); 2749 } 2750if (* first ) { 2751msg_clr_eos (); 2752* first = false; 2753 } 2754} 2755 2756/// Additional handling for setting a v: variable. 2757/// 2758/// @return true if the variable should be set normally, 2759/// false if nothing else needs to be done. 2760bool before_set_vvar (const char * const varname ,dictitem_T * const di ,typval_T * const tv , 2761const bool copy ,const bool watched ,bool * const type_error ) 2762{ 2763if (di -> di_tv .v_type == VAR_STRING ) { 2764typval_T oldtv = TV_INITIAL_VALUE ; 2765if (watched ) { 2766tv_copy (& di -> di_tv ,& oldtv ); 2767 } 2768XFREE_CLEAR (di -> di_tv .vval .v_string ); 2769if (copy || tv -> v_type != VAR_STRING ) { 2770const char * const val = tv_get_string (tv ); 2771// Careful: when assigning to v:errmsg and tv_get_string() 2772// causes an error message the variable will already be set. 2773if (di -> di_tv .vval .v_string == NULL ) { 2774di -> di_tv .vval .v_string = xstrdup (val ); 2775 } 2776 }else { 2777// Take over the string to avoid an extra alloc/free. 2778di -> di_tv .vval .v_string = tv -> vval .v_string ; 2779tv -> vval .v_string = NULL ; 2780 } 2781// Notify watchers 2782if (watched ) { 2783tv_dict_watcher_notify (& vimvardict ,varname ,& di -> di_tv ,& oldtv ); 2784tv_clear (& oldtv ); 2785 } 2786return false; 2787 }else if (di -> di_tv .v_type == VAR_NUMBER ) { 2788typval_T oldtv = TV_INITIAL_VALUE ; 2789if (watched ) { 2790tv_copy (& di -> di_tv ,& oldtv ); 2791 } 2792di -> di_tv .vval .v_number = tv_get_number (tv ); 2793if (strcmp (varname ,"searchforward" )== 0 ) { 2794set_search_direction (di -> di_tv .vval .v_number ?'/' :'?' ); 2795 }else if (strcmp (varname ,"hlsearch" )== 0 ) { 2796Search .no_hlsearch = !di -> di_tv .vval .v_number ; 2797redraw_all_later (UPD_SOME_VALID ); 2798 } 2799// Notify watchers 2800if (watched ) { 2801tv_dict_watcher_notify (& vimvardict ,varname ,& di -> di_tv ,& oldtv ); 2802tv_clear (& oldtv ); 2803 } 2804return false; 2805 }else if (di -> di_tv .v_type != tv -> v_type ) { 2806* type_error = true; 2807return false; 2808 } 2809return true; 2810} 2811 2812/// Set variable to the given value 2813/// 2814/// If the variable already exists, the value is updated. Otherwise the variable 2815/// is created. 2816/// 2817/// @param[in] name Variable name to set. 2818/// @param[in] name_len Length of the variable name. 2819/// @param tv Variable value. 2820/// @param[in] copy True if value in tv is to be copied. 2821void set_var (const char * name ,const size_t name_len ,typval_T * const tv ,const bool copy ) 2822FUNC_ATTR_NONNULL_ALL 2823{ 2824set_var_const (name ,name_len ,tv ,copy , false); 2825} 2826 2827/// Set variable to the given value 2828/// 2829/// If the variable already exists, the value is updated. Otherwise the variable 2830/// is created. 2831/// 2832/// @param[in] name Variable name to set. 2833/// @param[in] name_len Length of the variable name. 2834/// @param tv Variable value. 2835/// @param[in] copy True if value in tv is to be copied. 2836/// @param[in] is_const True if value in tv is to be locked. 2837void set_var_const (const char * name ,const size_t name_len ,typval_T * const tv ,const bool copy , 2838const bool is_const ) 2839FUNC_ATTR_NONNULL_ALL 2840{ 2841const char * varname ; 2842dict_T * dict ; 2843hashtab_T * ht = find_var_ht_dict (name ,name_len ,& varname ,& dict ); 2844const bool watched = tv_dict_is_watched (dict ); 2845 2846if (ht == NULL || * varname == NUL ) { 2847semsg (_ (e_illvar ),name ); 2848return ; 2849 } 2850const size_t varname_len = name_len - (size_t )(varname - name ); 2851dictitem_T * di = find_var_in_ht (ht ,0 ,varname ,varname_len , true); 2852 2853// Search in parent scope which is possible to reference from lambda 2854if (di == NULL ) { 2855di = find_var_in_scoped_ht (name ,name_len , true); 2856 } 2857 2858if (tv_is_func (* tv )&& var_wrong_func_name (name ,di == NULL )) { 2859return ; 2860 } 2861 2862typval_T oldtv = TV_INITIAL_VALUE ; 2863if (di != NULL ) { 2864if (is_const ) { 2865emsg (_ (e_cannot_mod )); 2866return ; 2867 } 2868 2869// Check in this order for backwards compatibility: 2870// - Whether the variable is read-only 2871// - Whether the variable value is locked 2872// - Whether the variable is locked 2873if (var_check_ro (di -> di_flags ,name ,name_len ) 2874|| value_check_lock (di -> di_tv .v_lock ,name ,name_len ) 2875|| var_check_lock (di -> di_flags ,name ,name_len )) { 2876return ; 2877 } 2878 2879// existing variable, need to clear the value 2880 2881// Handle setting internal v: variables separately where needed to 2882// prevent changing the type. 2883bool type_error = false; 2884if (ht == & vimvarht 2885&& !before_set_vvar (varname ,di ,tv ,copy ,watched ,& type_error )) { 2886if (type_error ) { 2887semsg (_ (e_setting_v_str_to_value_with_wrong_type ),varname ); 2888 } 2889return ; 2890 } 2891 2892if (watched ) { 2893tv_copy (& di -> di_tv ,& oldtv ); 2894 } 2895tv_clear (& di -> di_tv ); 2896 }else {// Add a new variable. 2897// Can't add "v:" or "a:" variable. 2898if (ht == & vimvarht || ht == get_funccal_args_ht ()) { 2899semsg (_ (e_illvar ),name ); 2900return ; 2901 } 2902 2903// Make sure the variable name is valid. 2904if (!valid_varname (varname )) { 2905return ; 2906 } 2907 2908// Make sure dict is valid 2909assert (dict != NULL ); 2910 2911di = xmalloc (offsetof(dictitem_T ,di_key )+ varname_len + 1 ); 2912memcpy (di -> di_key ,varname ,varname_len + 1 ); 2913if (hash_add (ht ,di -> di_key )== FAIL ) { 2914xfree (di ); 2915return ; 2916 } 2917di -> di_flags = DI_FLAGS_ALLOC ; 2918if (is_const ) { 2919di -> di_flags |=DI_FLAGS_LOCK ; 2920 } 2921 } 2922 2923if (copy || tv -> v_type == VAR_NUMBER || tv -> v_type == VAR_FLOAT ) { 2924tv_copy (tv ,& di -> di_tv ); 2925 }else { 2926di -> di_tv = * tv ; 2927di -> di_tv .v_lock = VAR_UNLOCKED ; 2928tv_init (tv ); 2929 } 2930 2931if (watched ) { 2932tv_dict_watcher_notify (dict ,di -> di_key ,& di -> di_tv ,& oldtv ); 2933tv_clear (& oldtv ); 2934 } 2935 2936if (is_const ) { 2937// Like :lockvar! name: lock the value and what it contains, but only 2938// if the reference count is up to one. That locks only literal 2939// values. 2940tv_item_lock (& di -> di_tv ,DICT_MAXNEST , true, true); 2941 } 2942} 2943 2944/// Check whether variable is read-only (DI_FLAGS_RO, DI_FLAGS_RO_SBX) 2945/// 2946/// Also gives an error message. 2947/// 2948/// @param[in] flags di_flags attribute value. 2949/// @param[in] name Variable name, for use in error message. 2950/// @param[in] name_len Variable name length. Use #TV_TRANSLATE to translate 2951/// variable name and compute the length. Use #TV_CSTRING 2952/// to compute the length with strlen() without 2953/// translating. 2954/// 2955/// Both #TV_… values are used for optimization purposes: 2956/// variable name with its length is needed only in case 2957/// of error, when no error occurs computing them is 2958/// a waste of CPU resources. This especially applies to 2959/// gettext. 2960/// 2961/// @return True if variable is read-only: either always or in sandbox when 2962/// sandbox is enabled, false otherwise. 2963bool var_check_ro (const int flags ,const char * name ,size_t name_len ) 2964FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL 2965{ 2966const char * error_message = NULL ; 2967if (flags & DI_FLAGS_RO ) { 2968error_message = N_ (e_cannot_change_readonly_variable_str ); 2969 }else if ((flags & DI_FLAGS_RO_SBX )&& sandbox ) { 2970error_message = N_ (e_cannot_set_variable_in_sandbox_str ); 2971 } 2972 2973if (error_message == NULL ) { 2974return false; 2975 } 2976if (name_len == TV_TRANSLATE ) { 2977name = _ (name ); 2978name_len = strlen (name ); 2979 }else if (name_len == TV_CSTRING ) { 2980name_len = strlen (name ); 2981 } 2982 2983semsg (_ (error_message ), (int )name_len ,name ); 2984 2985return true; 2986} 2987 2988/// Return true if di_flags "flags" indicates variable "name" is locked. 2989/// Also give an error message. 2990bool var_check_lock (const int flags ,const char * name ,size_t name_len ) 2991{ 2992if (!(flags & DI_FLAGS_LOCK )) { 2993return false; 2994 } 2995 2996if (name_len == TV_TRANSLATE ) { 2997name = _ (name ); 2998name_len = strlen (name ); 2999 }else if (name_len == TV_CSTRING ) { 3000name_len = strlen (name ); 3001 } 3002 3003semsg (_ ("E1122: Variable is locked: %.*s" ), (int )name_len ,name ); 3004 3005return true; 3006} 3007 3008/// Check whether variable is fixed (DI_FLAGS_FIX) 3009/// 3010/// Also gives an error message. 3011/// 3012/// @param[in] flags di_flags attribute value. 3013/// @param[in] name Variable name, for use in error message. 3014/// @param[in] name_len Variable name length. Use #TV_TRANSLATE to translate 3015/// variable name and compute the length. Use #TV_CSTRING 3016/// to compute the length with strlen() without 3017/// translating. 3018/// 3019/// Both #TV_… values are used for optimization purposes: 3020/// variable name with its length is needed only in case 3021/// of error, when no error occurs computing them is 3022/// a waste of CPU resources. This especially applies to 3023/// gettext. 3024/// 3025/// @return True if variable is fixed, false otherwise. 3026bool var_check_fixed (const int flags ,const char * name ,size_t name_len ) 3027FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL 3028{ 3029if (flags & DI_FLAGS_FIX ) { 3030if (name_len == TV_TRANSLATE ) { 3031name = _ (name ); 3032name_len = strlen (name ); 3033 }else if (name_len == TV_CSTRING ) { 3034name_len = strlen (name ); 3035 } 3036semsg (_ (e_cannot_delete_variable_str ), (int )name_len ,name ); 3037return true; 3038 } 3039return false; 3040} 3041 3042/// Check if name is a valid name to assign funcref to 3043/// 3044/// @param[in] name Possible function/funcref name. 3045/// @param[in] new_var True if it is a name for a variable. 3046/// 3047/// @return false in case of success, true in case of failure. Also gives an 3048/// error message if appropriate. 3049bool var_wrong_func_name (const char * const name ,const bool new_var ) 3050FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT 3051{ 3052// Allow for w: b: s: and t:. 3053// Allow autoload variable. 3054if (!(vim_strchr ("wbst" , (uint8_t )name [0 ])!= NULL && name [1 ]== ':' ) 3055&& !ASCII_ISUPPER ((name [0 ]!= NUL && name [1 ]== ':' ) ?name [2 ] :name [0 ]) 3056&& vim_strchr (name ,'#' )== NULL ) { 3057semsg (_ ("E704: Funcref variable name must start with a capital: %s" ),name ); 3058return true; 3059 } 3060// Don't allow hiding a function. When "v" is not NULL we might be 3061// assigning another function to the same var, the type is checked 3062// below. 3063if (new_var && function_exists (name , false)) { 3064semsg (_ ("E705: Variable name conflicts with existing function: %s" ),name ); 3065return true; 3066 } 3067return false; 3068} 3069 3070/// Check if a variable name is valid 3071/// 3072/// @param[in] varname Variable name to check. 3073/// 3074/// @return false when variable name is not valid, true when it is. Also gives 3075/// an error message if appropriate. 3076bool valid_varname (const char * varname ) 3077FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT 3078{ 3079for (const char * p = varname ;* p != NUL ;p ++ ) { 3080if (!eval_isnamec1 ((int )(uint8_t )(* p )) 3081&& (p == varname || !ascii_isdigit (* p )) 3082&& * p != AUTOLOAD_CHAR ) { 3083semsg (_ (e_illvar ),varname ); 3084return false; 3085 } 3086 } 3087return true; 3088} 3089 3090/// Implements the logic to retrieve local variable and option values. 3091/// Used by "getwinvar()" "gettabvar()" "gettabwinvar()" "getbufvar()". 3092/// 3093/// @param deftv default value if not found 3094/// @param htname 't'ab, 'w'indow or 'b'uffer local 3095/// @param tp can be NULL 3096/// @param buf ignored if htname is not 'b' 3097static void get_var_from (const char * varname ,typval_T * rettv ,typval_T * deftv ,int htname , 3098tabpage_T * tp ,win_T * win ,buf_T * buf ) 3099{ 3100bool done = false; 3101const bool do_change_curbuf = buf != NULL && htname == 'b' ; 3102 3103emsg_off ++ ; 3104 3105rettv -> v_type = VAR_STRING ; 3106rettv -> vval .v_string = NULL ; 3107 3108if (varname != NULL && tp != NULL && win != NULL && (htname != 'b' || buf != NULL )) { 3109// Set curwin to be our win, temporarily. Also set the tabpage, 3110// otherwise the window is not valid. Only do this when needed, 3111// autocommands get blocked. 3112// If we have a buffer reference avoid the switching, we're saving and 3113// restoring curbuf directly. 3114const bool need_switch_win = !(tp == curtab && win == curwin )&& !do_change_curbuf ; 3115CtxSwitch switchwin ; 3116if (!need_switch_win || ctx_switch (& switchwin ,win ,tp ,NULL ,kCtxNoEvents |kCtxNoDisplay )) { 3117if (* varname == '&' && htname != 't' ) { 3118buf_T * const save_curbuf = curbuf ; 3119 3120// Change curbuf so the option is read from the correct buffer. 3121if (do_change_curbuf ) { 3122curbuf = buf ; 3123 } 3124 3125if (varname [1 ]== NUL ) { 3126// get all window-local or buffer-local options in a dict 3127dict_T * opts = get_winbuf_options (htname == 'b' ); 3128 3129if (opts != NULL ) { 3130tv_dict_set_ret (rettv ,opts ); 3131done = true; 3132 } 3133 }else if (eval_option (& varname ,rettv , true)== OK ) { 3134// Local option 3135done = true; 3136 } 3137 3138curbuf = save_curbuf ; 3139 }else if (* varname == NUL ) { 3140const ScopeDictDictItem * v ; 3141// Empty string: return a dict with all the local variables. 3142if (htname == 'b' ) { 3143v = & buf -> b_bufvar ; 3144 }else if (htname == 'w' ) { 3145v = & win -> w_winvar ; 3146 }else { 3147v = & tp -> tp_winvar ; 3148 } 3149tv_copy (& v -> di_tv ,rettv ); 3150done = true; 3151 }else { 3152hashtab_T * ht ; 3153 3154if (htname == 'b' ) { 3155ht = & buf -> b_vars -> dv_hashtab ; 3156 }else if (htname == 'w' ) { 3157ht = & win -> w_vars -> dv_hashtab ; 3158 }else { 3159ht = & tp -> tp_vars -> dv_hashtab ; 3160 } 3161 3162// Look up the variable. 3163const dictitem_T * const v = find_var_in_ht (ht ,htname ,varname ,strlen (varname ), false); 3164if (v != NULL ) { 3165tv_copy (& v -> di_tv ,rettv ); 3166done = true; 3167 } 3168 } 3169 } 3170 3171if (need_switch_win ) { 3172// restore previous notion of curwin 3173ctx_restore (& switchwin ); 3174 } 3175 } 3176 3177if (!done && deftv -> v_type != VAR_UNKNOWN ) { 3178// use the default value 3179tv_copy (deftv ,rettv ); 3180 } 3181 3182emsg_off -- ; 3183} 3184 3185/// getwinvar() and gettabwinvar() 3186/// 3187/// @param off 1 for gettabwinvar() 3188static void getwinvar (typval_T * argvars ,typval_T * rettv ,int off ) 3189{ 3190tabpage_T * tp ; 3191 3192if (off == 1 ) { 3193tp = find_tabpage ((int )tv_get_number_chk (& argvars [0 ],NULL )); 3194 }else { 3195tp = curtab ; 3196 } 3197win_T * const win = find_win_by_nr (& argvars [off ],tp ); 3198const char * const varname = tv_get_string_chk (& argvars [off + 1 ]); 3199 3200get_var_from (varname ,rettv ,& argvars [off + 2 ],'w' ,tp ,win ,NULL ); 3201} 3202 3203/// Converts a typval to a structured option value. 3204/// 3205/// @param[in] tv typval to convert. 3206/// @param[in] option Option name. 3207/// @param[in] flags Option flags. 3208/// @param[out] error Whether an error occurred. 3209/// 3210/// @return Structured option, or NIL if invalid option name. Must be freed by caller. 3211static Object opt_from_tv (typval_T * tv ,OptIndex opt_idx ,const char * option ,bool * error ) 3212{ 3213Object value = NIL ; 3214char nbuf [NUMBUFLEN ]; 3215bool err = false; 3216const bool is_tty_opt = is_tty_option (option ); 3217const bool option_has_bool = !is_tty_opt && option_has_type (opt_idx ,kObjectTypeBoolean ); 3218const bool option_has_num = !is_tty_opt && option_has_type (opt_idx ,kObjectTypeInteger ); 3219const bool option_has_str = is_tty_opt || option_has_type (opt_idx ,kObjectTypeString ); 3220 3221if (!is_tty_opt && (get_option (opt_idx )-> flags & kOptFlagFunc )&& tv_is_func (* tv )) { 3222// If the option can be set to a function reference or a lambda 3223// and the passed value is a function reference, then convert it to 3224// the name (string) of the function reference. 3225char * strval = encode_tv2string (tv ,NULL ); 3226err = strval == NULL ; 3227value = CSTR_AS_OBJ (strval ); 3228 }else if (option_has_bool || option_has_num ) { 3229varnumber_T n = option_has_num ?tv_get_number_chk (tv ,& err ) :tv_get_bool_chk (tv ,& err ); 3230// This could be either "0" or a string that's not a number. 3231// So we need to check if it's actually a number. 3232if (!err && tv -> v_type == VAR_STRING && n == 0 ) { 3233unsigned idx ; 3234for (idx = 0 ;tv -> vval .v_string != NULL && tv -> vval .v_string [idx ]== '0' ;idx ++ ) {} 3235if (idx == 0 || tv -> vval .v_string [idx ]!= NUL ) { 3236// There's another character after zeros or the string is empty. 3237// In both cases, we are trying to set a num option using a string. 3238err = true; 3239semsg (_ ("E521: Number required: &%s = '%s'" ),option , 3240tv -> vval .v_string == NULL ?"" :tv -> vval .v_string ); 3241 } 3242 } 3243value = option_has_num ?INTEGER_OBJ ((OptInt )n ) :opt_from_tristate (TRISTATE_FROM_INT (n )); 3244 }else if (option_has_str ) { 3245// Avoid setting string option to a boolean or a special value. 3246if (tv -> v_type != VAR_BOOL && tv -> v_type != VAR_SPECIAL ) { 3247const char * strval = tv_get_string_buf_chk (tv ,nbuf ); 3248err = strval == NULL ; 3249value = CSTR_TO_OBJ (strval ); 3250 }else { 3251err = true; 3252emsg (_ (e_string_required )); 3253 } 3254 }else { 3255abort ();// This should never happen. 3256 } 3257 3258if (error != NULL ) { 3259* error = err ; 3260 } 3261return value ; 3262} 3263 3264/// Converts an option value to typval. The result is independent of `value` (which is neither 3265/// consumed nor aliased): tv_clear() the result, and release `value` per its own ownership. 3266/// 3267/// @param[in] value Option value to convert. 3268/// @param numbool Whether to convert boolean values to number. 3269/// Used for backwards compatibility. 3270/// 3271/// @return Object converted to typval. 3272typval_T opt_to_tv (Object value ,bool numbool ) 3273{ 3274typval_T rettv = { .v_type = VAR_SPECIAL , .vval = { .v_special = kSpecialVarNull } }; 3275 3276switch (value .type ) { 3277case kObjectTypeUnset : 3278// Legacy numbool callers (e.g. `&l:autoread` unset global-local boolean) 3279// expect the kNone; otherwise an unset value is v:null. 3280if (numbool ) { 3281rettv .v_type = VAR_NUMBER ; 3282rettv .vval .v_number = kNone ; 3283 } 3284break ; 3285case kObjectTypeNil : 3286break ;// Return v:null. 3287case kObjectTypeBoolean : 3288if (numbool ) { 3289rettv .v_type = VAR_NUMBER ; 3290rettv .vval .v_number = value .data .boolean ; 3291 }else { 3292rettv .v_type = VAR_BOOL ; 3293rettv .vval .v_bool = value .data .boolean ?kBoolVarTrue :kBoolVarFalse ; 3294 } 3295break ; 3296case kObjectTypeInteger : 3297rettv .v_type = VAR_NUMBER ; 3298rettv .vval .v_number = value .data .integer ; 3299break ; 3300case kObjectTypeString : 3301rettv .v_type = VAR_STRING ; 3302rettv .vval .v_string = value .data .string .data != NULL ?xstrdup (value .data .string .data ) :NULL ; 3303break ; 3304case kObjectTypeLuaRef : 3305// Lua callback option (e.g. 'operatorfunc'): show a human-readable hint (same as `:map` does). 3306rettv .v_type = VAR_STRING ; 3307rettv .vval .v_string = nlua_funcref_str (value .data .luaref ,NULL , true); 3308break ; 3309default : 3310abort ();// Should never happen. 3311 } 3312 3313return rettv ; 3314} 3315 3316/// Set option "varname" to the value of "varp" for the current buffer/window. 3317static void set_option_from_tv (const char * varname ,typval_T * varp ) 3318{ 3319OptIndex opt_idx = find_option (varname ); 3320if (opt_idx == kOptInvalid ) { 3321semsg (_ (e_unknown_option2 ),varname ); 3322return ; 3323 } 3324 3325bool error = false; 3326Object value = opt_from_tv (varp ,opt_idx ,varname ,& error ); 3327 3328if (!error ) { 3329const CharBuf errbuf = { (char [IOSIZE ]){0 },IOSIZE }; 3330const char * errmsg = set_option_value (opt_idx ,value ,OPT_LOCAL , true,& errbuf ); 3331 3332if (errmsg ) { 3333emsg (errmsg ); 3334 } 3335 } 3336optval_free (value ); 3337} 3338 3339/// "setwinvar()" and "settabwinvar()" functions 3340static void setwinvar (typval_T * argvars ,int off ) 3341{ 3342if (check_secure ()) { 3343return ; 3344 } 3345 3346tabpage_T * tp = NULL ; 3347if (off == 1 ) { 3348tp = find_tabpage ((int )tv_get_number_chk (& argvars [0 ],NULL )); 3349 }else { 3350tp = curtab ; 3351 } 3352win_T * const win = find_win_by_nr (& argvars [off ],tp ); 3353const char * varname = tv_get_string_chk (& argvars [off + 1 ]); 3354typval_T * varp = & argvars [off + 2 ]; 3355 3356if (win == NULL || varname == NULL ) { 3357return ; 3358 } 3359 3360bool need_switch_win = !(tp == curtab && win == curwin ); 3361CtxSwitch switchwin ; 3362if (!need_switch_win || ctx_switch (& switchwin ,win ,tp ,NULL ,kCtxNoEvents |kCtxNoDisplay )) { 3363if (* varname == '&' ) { 3364set_option_from_tv (varname + 1 ,varp ); 3365 }else { 3366const size_t varname_len = strlen (varname ); 3367char * const winvarname = xmalloc (varname_len + 3 ); 3368memcpy (winvarname ,"w:" ,2 ); 3369memcpy (winvarname + 2 ,varname ,varname_len + 1 ); 3370set_var (winvarname ,varname_len + 2 ,varp , true); 3371xfree (winvarname ); 3372 } 3373 } 3374if (need_switch_win ) { 3375ctx_restore (& switchwin ); 3376 } 3377} 3378 3379// reset v:option_new, v:option_old, v:option_oldlocal, v:option_oldglobal, 3380// v:option_type, and v:option_command. 3381void reset_v_option_vars (void ) 3382{ 3383set_vim_var_string (VV_OPTION_NEW ,NULL ,-1 ); 3384set_vim_var_string (VV_OPTION_OLD ,NULL ,-1 ); 3385set_vim_var_string (VV_OPTION_OLDLOCAL ,NULL ,-1 ); 3386set_vim_var_string (VV_OPTION_OLDGLOBAL ,NULL ,-1 ); 3387set_vim_var_string (VV_OPTION_COMMAND ,NULL ,-1 ); 3388set_vim_var_string (VV_OPTION_TYPE ,NULL ,-1 ); 3389} 3390 3391/// Add an assert error to v:errors. 3392void assert_error (garray_T * gap ) 3393{ 3394typval_T * tv = get_vim_var_tv (VV_ERRORS ); 3395 3396if (tv -> v_type != VAR_LIST || tv -> vval .v_list == NULL ) { 3397// Make sure v:errors is a list. 3398set_vim_var_list (VV_ERRORS ,tv_list_alloc (1 )); 3399 } 3400tv_list_append_string (get_vim_var_list (VV_ERRORS ),gap -> ga_data , (ptrdiff_t )gap -> ga_len ); 3401} 3402 3403bool var_exists (const char * var ) 3404FUNC_ATTR_NONNULL_ALL 3405{ 3406char * tofree ; 3407bool n = false; 3408 3409// get_name_len() takes care of expanding curly braces 3410const char * name = var ; 3411const int len = get_name_len (& var ,& tofree , true, false); 3412if (len > 0 ) { 3413typval_T tv ; 3414 3415if (tofree != NULL ) { 3416name = tofree ; 3417 } 3418n = eval_variable (name ,len ,& tv ,NULL , false, true)== OK ; 3419if (n ) { 3420// Handle d.key, l[idx], f(expr). 3421n = handle_subscript (& var ,& tv ,& EVALARG_EVALUATE , false)== OK ; 3422if (n ) { 3423tv_clear (& tv ); 3424 } 3425 } 3426 } 3427if (* var != NUL ) { 3428n = false; 3429 } 3430 3431xfree (tofree ); 3432return n ; 3433} 3434 3435static lval_T * redir_lval = NULL ; 3436static garray_T redir_ga ;// Only valid when redir_lval is not NULL. 3437static char * redir_endp = NULL ; 3438static char * redir_varname = NULL ; 3439 3440/// Start recording command output to a variable 3441/// 3442/// @param append append to an existing variable 3443/// 3444/// @return OK if successfully completed the setup. FAIL otherwise. 3445int var_redir_start (char * name ,bool append ) 3446{ 3447// Catch a bad name early. 3448if (!eval_isnamec1 (* name )) { 3449emsg (_ (e_invarg )); 3450return FAIL ; 3451 } 3452 3453// Make a copy of the name, it is used in redir_lval until redir ends. 3454redir_varname = xstrdup (name ); 3455 3456redir_lval = xcalloc (1 ,sizeof (lval_T )); 3457 3458// The output is stored in growarray "redir_ga" until redirection ends. 3459ga_init (& redir_ga , (int )sizeof (char ),500 ); 3460 3461// Parse the variable name (can be a dict or list entry). 3462redir_endp = get_lval (redir_varname ,NULL ,redir_lval , false, false, 34630 ,FNE_CHECK_START ); 3464if (redir_endp == NULL || redir_lval -> ll_name == NULL 3465|| * redir_endp != NUL ) { 3466clear_lval (redir_lval ); 3467if (redir_endp != NULL && * redir_endp != NUL ) { 3468// Trailing characters are present after the variable name 3469semsg (_ (e_trailing_arg ),redir_endp ); 3470 }else { 3471semsg (_ (e_invarg2 ),name ); 3472 } 3473redir_endp = NULL ;// don't store a value, only cleanup 3474var_redir_stop (); 3475return FAIL ; 3476 } 3477 3478// check if we can write to the variable: set it to or append an empty 3479// string 3480const int called_emsg_before = called_emsg ; 3481did_emsg = false; 3482typval_T tv ; 3483tv .v_type = VAR_STRING ; 3484tv .vval .v_string = "" ; 3485if (append ) { 3486set_var_lval (redir_lval ,redir_endp ,& tv , true, false,"." ); 3487 }else { 3488set_var_lval (redir_lval ,redir_endp ,& tv , true, false,"=" ); 3489 } 3490clear_lval (redir_lval ); 3491if (called_emsg > called_emsg_before ) { 3492redir_endp = NULL ;// don't store a value, only cleanup 3493var_redir_stop (); 3494return FAIL ; 3495 } 3496 3497return OK ; 3498} 3499 3500/// Append "value[value_len]" to the variable set by var_redir_start(). 3501/// The actual appending is postponed until redirection ends, because the value 3502/// appended may in fact be the string we write to, changing it may cause freed 3503/// memory to be used: 3504/// :redir => foo 3505/// :let foo 3506/// :redir END 3507void var_redir_str (const char * value ,int value_len ) 3508{ 3509if (redir_lval == NULL ) { 3510return ; 3511 } 3512 3513int len ; 3514if (value_len == -1 ) { 3515len = (int )strlen (value );// Append the entire string 3516 }else { 3517len = value_len ;// Append only "value_len" characters 3518 } 3519 3520ga_grow (& redir_ga ,len ); 3521memmove ((char * )redir_ga .ga_data + redir_ga .ga_len ,value , (size_t )len ); 3522redir_ga .ga_len += len ; 3523} 3524 3525/// Stop redirecting command output to a variable. 3526/// Frees the allocated memory. 3527void var_redir_stop (void ) 3528{ 3529if (redir_lval != NULL ) { 3530// If there was no error: assign the text to the variable. 3531if (redir_endp != NULL ) { 3532ga_append (& redir_ga ,NUL );// Append the trailing NUL. 3533typval_T tv ; 3534tv .v_type = VAR_STRING ; 3535tv .vval .v_string = redir_ga .ga_data ; 3536// Call get_lval() again, if it's inside a Dict or List it may 3537// have changed. 3538redir_endp = get_lval (redir_varname ,NULL ,redir_lval , 3539 false, false,0 ,FNE_CHECK_START ); 3540if (redir_endp != NULL && redir_lval -> ll_name != NULL ) { 3541set_var_lval (redir_lval ,redir_endp ,& tv , false, false,"." ); 3542 } 3543clear_lval (redir_lval ); 3544 } 3545 3546// free the collected output 3547XFREE_CLEAR (redir_ga .ga_data ); 3548 3549XFREE_CLEAR (redir_lval ); 3550 } 3551XFREE_CLEAR (redir_varname ); 3552} 3553 3554/// "gettabvar()" function 3555void f_gettabvar (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 3556{ 3557const char * const varname = tv_get_string_chk (& argvars [1 ]); 3558tabpage_T * const tp = find_tabpage ((int )tv_get_number_chk (& argvars [0 ],NULL )); 3559win_T * win = NULL ; 3560 3561if (tp != NULL ) { 3562win = tp == curtab || tp -> tp_firstwin == NULL ?firstwin :tp -> tp_firstwin ; 3563 } 3564 3565get_var_from (varname ,rettv ,& argvars [2 ],'t' ,tp ,win ,NULL ); 3566} 3567 3568/// "gettabwinvar()" function 3569void f_gettabwinvar (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 3570{ 3571getwinvar (argvars ,rettv ,1 ); 3572} 3573 3574/// "getwinvar()" function 3575void f_getwinvar (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 3576{ 3577getwinvar (argvars ,rettv ,0 ); 3578} 3579 3580/// "getbufvar()" function 3581void f_getbufvar (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 3582{ 3583const char * const varname = tv_get_string_chk (& argvars [1 ]); 3584buf_T * const buf = tv_get_buf_from_arg (& argvars [0 ]); 3585 3586get_var_from (varname ,rettv ,& argvars [2 ],'b' ,curtab ,curwin ,buf ); 3587} 3588 3589/// "settabvar()" function 3590void f_settabvar (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 3591{ 3592if (check_secure ()) { 3593return ; 3594 } 3595 3596tabpage_T * const tp = find_tabpage ((int )tv_get_number_chk (& argvars [0 ],NULL )); 3597const char * const varname = tv_get_string_chk (& argvars [1 ]); 3598typval_T * const varp = & argvars [2 ]; 3599 3600if (varname == NULL || tp == NULL ) { 3601return ; 3602 } 3603 3604tabpage_T * const save_curtab = curtab ; 3605tabpage_T * const save_lu_tp = lastused_tabpage ; 3606goto_tabpage_tp (tp , false, false); 3607 3608const size_t varname_len = strlen (varname ); 3609char * const tabvarname = xmalloc (varname_len + 3 ); 3610memcpy (tabvarname ,"t:" ,2 ); 3611memcpy (tabvarname + 2 ,varname ,varname_len + 1 ); 3612set_var (tabvarname ,varname_len + 2 ,varp , true); 3613xfree (tabvarname ); 3614 3615// Restore current tabpage and last accessed tabpage. 3616if (valid_tabpage (save_curtab )) { 3617goto_tabpage_tp (save_curtab , false, false); 3618if (valid_tabpage (save_lu_tp )) { 3619lastused_tabpage = save_lu_tp ; 3620 } 3621 } 3622} 3623 3624/// "settabwinvar()" function 3625void f_settabwinvar (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 3626{ 3627setwinvar (argvars ,1 ); 3628} 3629 3630/// "setwinvar()" function 3631void f_setwinvar (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 3632{ 3633setwinvar (argvars ,0 ); 3634} 3635 3636/// "setbufvar()" function 3637void f_setbufvar (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 3638{ 3639if (check_secure () 3640|| !tv_check_str_or_nr (& argvars [0 ])) { 3641return ; 3642 } 3643const char * varname = tv_get_string_chk (& argvars [1 ]); 3644buf_T * const buf = tv_get_buf (& argvars [0 ], false); 3645typval_T * varp = & argvars [2 ]; 3646 3647if (buf == NULL || varname == NULL ) { 3648return ; 3649 } 3650 3651if (* varname == '&' ) { 3652CtxSwitch aco = {0 }; 3653 3654// Set curbuf to be our buf, temporarily. 3655ctx_switch (& aco ,NULL ,NULL ,buf ,0 ); 3656 3657set_option_from_tv (varname + 1 ,varp ); 3658 3659// reset notion of buffer 3660ctx_restore (& aco ); 3661 }else { 3662const size_t varname_len = strlen (varname ); 3663char * const bufvarname = xmalloc (varname_len + 3 ); 3664buf_T * const save_curbuf = curbuf ; 3665curbuf = buf ; 3666memcpy (bufvarname ,"b:" ,2 ); 3667memcpy (bufvarname + 2 ,varname ,varname_len + 1 ); 3668set_var (bufvarname ,varname_len + 2 ,varp , true); 3669xfree (bufvarname ); 3670curbuf = save_curbuf ; 3671 } 3672}