robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1// User-settable options. Checklist for adding a new option: 2// - Put it in options.lua 3// - For a global option: Add a variable for it in option_vars.h. 4// - For a buffer or window local option: 5// - Add a variable to the window or buffer struct in buffer_defs.h. 6// - For a window option, add some code to copy_winopt(). 7// - For a window string option, add code to check_winopt() 8// and clear_winopt(). If setting the option needs parsing, 9// add some code to didset_window_options(). 10// - For a buffer option, add some code to buf_copy_options(). 11// - For a buffer string option, add code to check_buf_options(). 12// - If it's a numeric option, add any necessary bounds checks to check_num_option_bounds(). 13// - If it's a list of flags, add some code in do_set(), search for WW_ALL. 14// - If it depends on options values, add it to didset_string_options(). 15// - Add documentation! "desc" in options.lua, and any other related places. 16// - Add an entry in runtime/scripts/optwin.lua. 17 18#define IN_OPTION_C 19#include <assert.h> 20#include <inttypes.h> 21#include <limits.h> 22#include <stdarg.h> 23#include <stdbool.h> 24#include <stdio.h> 25#include <stdlib.h> 26#include <string.h> 27#include <uv.h> 28 29#include "auto/config.h" 30#include "klib/kvec.h" 31#include "nvim/api/extmark.h" 32#include "nvim/api/private/defs.h" 33#include "nvim/api/private/helpers.h" 34#include "nvim/api/private/validate.h" 35#include "nvim/ascii_defs.h" 36#include "nvim/assert_defs.h" 37#include "nvim/autocmd.h" 38#include "nvim/autocmd_defs.h" 39#include "nvim/buffer.h" 40#include "nvim/buffer_defs.h" 41#include "nvim/change.h" 42#include "nvim/charset.h" 43#include "nvim/cmdexpand.h" 44#include "nvim/cmdexpand_defs.h" 45#include "nvim/context.h" 46#include "nvim/cursor_shape.h" 47#include "nvim/decoration_defs.h" 48#include "nvim/decoration_provider.h" 49#include "nvim/diff.h" 50#include "nvim/drawscreen.h" 51#include "nvim/errors.h" 52#include "nvim/eval.h" 53#include "nvim/eval/encode.h" 54#include "nvim/eval/typval.h" 55#include "nvim/eval/typval_defs.h" 56#include "nvim/eval/userfunc.h" 57#include "nvim/eval/vars.h" 58#include "nvim/eval/window.h" 59#include "nvim/ex_cmds_defs.h" 60#include "nvim/ex_docmd.h" 61#include "nvim/ex_getln.h" 62#include "nvim/ex_session.h" 63#include "nvim/fold.h" 64#include "nvim/fuzzy.h" 65#include "nvim/garray.h" 66#include "nvim/garray_defs.h" 67#include "nvim/gettext_defs.h" 68#include "nvim/globals.h" 69#include "nvim/grid_defs.h" 70#include "nvim/highlight.h" 71#include "nvim/highlight_defs.h" 72#include "nvim/highlight_group.h" 73#include "nvim/indent.h" 74#include "nvim/indent_c.h" 75#include "nvim/input_cmdatom.h" 76#include "nvim/insexpand.h" 77#include "nvim/keycodes.h" 78#include "nvim/log.h" 79#include "nvim/lua/executor.h" 80#include "nvim/macros_defs.h" 81#include "nvim/mapping.h" 82#include "nvim/mbyte.h" 83#include "nvim/mcursor.h" 84#include "nvim/memfile.h" 85#include "nvim/memline.h" 86#include "nvim/memory.h" 87#include "nvim/memory_defs.h" 88#include "nvim/message.h" 89#include "nvim/mouse.h" 90#include "nvim/move.h" 91#include "nvim/normal.h" 92#include "nvim/ops.h" 93#include "nvim/option.h" 94#include "nvim/option_defs.h" 95#include "nvim/option_vars.h" 96#include "nvim/optionstr.h" 97#include "nvim/os/input.h" 98#include "nvim/os/lang.h" 99#include "nvim/os/os.h" 100#include "nvim/os/os_defs.h" 101#include "nvim/path.h" 102#include "nvim/popupmenu.h" 103#include "nvim/pos_defs.h" 104#include "nvim/regexp.h" 105#include "nvim/regexp_defs.h" 106#include "nvim/runtime.h" 107#include "nvim/spell.h" 108#include "nvim/spellsuggest.h" 109#include "nvim/state_defs.h" 110#include "nvim/strings.h" 111#include "nvim/tag.h" 112#include "nvim/terminal.h" 113#include "nvim/types_defs.h" 114#include "nvim/ui.h" 115#include "nvim/undo.h" 116#include "nvim/undo_defs.h" 117#include "nvim/vim_defs.h" 118#include "nvim/window.h" 119#include "nvim/winfloat.h" 120 121#ifdef BACKSLASH_IN_FILENAME 122# include "nvim/arglist.h" 123#endif 124 125static const char e_unknown_option [] 126= N_ ("E518: Unknown option" ); 127static const char e_not_allowed_in_modeline [] 128= N_ ("E520: Not allowed in a modeline" ); 129static const char e_not_allowed_in_modeline_when_modelineexpr_is_off [] 130= N_ ("E992: Not allowed in a modeline when 'modelineexpr' is off" ); 131static const char e_number_required_after_equal [] 132= N_ ("E521: Number required after =" ); 133static const char e_preview_window_already_exists [] 134= N_ ("E590: A preview window already exists" ); 135static const char e_cannot_have_negative_or_zero_number_of_quickfix [] 136= N_ ("E1542: Cannot have a negative or zero number of quickfix/location lists" ); 137static const char e_cannot_have_more_than_hundred_quickfix [] 138= N_ ("E1543: Cannot have more than a hundred quickfix/location lists" ); 139 140static char * p_term = NULL ; 141static char * p_ttytype = NULL ; 142 143// Saved values for when 'bin' is set. 144static int p_et_nobin ; 145static int p_ml_nobin ; 146static OptInt p_tw_nobin ; 147static OptInt p_wm_nobin ; 148 149// Saved values for when 'paste' is set. 150static int p_ai_nopaste ; 151static int p_et_nopaste ; 152static OptInt p_sts_nopaste ; 153static OptInt p_tw_nopaste ; 154static OptInt p_wm_nopaste ; 155static char * p_vsts_nopaste ; 156 157#define OPTION_COUNT ARRAY_SIZE(options) 158 159#include "option.c.generated.h" 160 161// options[] is initialized in options.generated.h. 162// The options with a NULL variable are 'hidden': a set command for them is 163// ignored and they are not printed. 164 165#include "options.generated.h" 166#include "options_keysets.generated.h" 167#include "options_map.generated.h" 168 169static int p_bin_dep_opts []= { 170kOptTextwidth ,kOptWrapmargin ,kOptModeline ,kOptExpandtab ,kOptInvalid 171}; 172 173static int p_paste_dep_opts []= { 174kOptAutoindent ,kOptExpandtab ,kOptRuler ,kOptShowmatch ,kOptSmarttab ,kOptSofttabstop , 175kOptTextwidth ,kOptWrapmargin ,kOptRevins ,kOptVarsofttabstop ,kOptInvalid 176}; 177 178void set_init_tablocal (void ) 179{ 180// susy baka: cmdheight calls itself OPT_GLOBAL but is really tablocal! 181p_ch = options [kOptCmdheight ].def_val .data .integer ; 182} 183 184/// Initialize the 'shell' option to a default value. 185static void set_init_default_shell (void ) 186{ 187// Find default value for 'shell' option. 188// Don't use it if it is empty. 189char * shell = os_getenv ("SHELL" ); 190if (shell != NULL ) { 191if (vim_strchr (shell ,' ' )!= NULL ) { 192const size_t len = strlen (shell )+ 3 ;// two quotes and a trailing NUL 193char * const cmd = xmalloc (len ); 194snprintf (cmd ,len ,"\"%s\"" ,shell ); 195set_string_default (kOptShell ,cmd , true); 196 }else { 197set_string_default (kOptShell ,shell , false); 198 } 199xfree (shell ); 200 } 201} 202 203/// Set the default for 'backupskip' to include environment variables for 204/// temp files. 205static void set_init_default_backupskip (void ) 206{ 207#ifdef UNIX 208static char * (names [4 ])= {"" ,"TMPDIR" ,"TEMP" ,"TMP" }; 209#else 210static char * (names [3 ])= {"TMPDIR" ,"TEMP" ,"TMP" }; 211#endif 212garray_T ga ; 213OptIndex opt_idx = kOptBackupskip ; 214 215ga_init (& ga ,1 ,100 ); 216for (size_t i = 0 ;i < ARRAY_SIZE (names );i ++ ) { 217bool mustfree = true; 218char * p ; 219size_t plen ; 220#ifdef UNIX 221if (* names [i ]== NUL ) { 222# ifdef __APPLE__ 223p = "/private/tmp" ; 224plen = STRLEN_LITERAL ("/private/tmp" ); 225# else 226p = "/tmp" ; 227plen = STRLEN_LITERAL ("/tmp" ); 228# endif 229mustfree = false; 230 }else 231#endif 232 { 233p = vim_getenv (names [i ]); 234plen = 0 ;// will be calculated below 235 } 236if (p != NULL && * p != NUL ) { 237bool has_trailing_path_sep = false; 238 239if (plen == 0 ) { 240// the value was retrieved from the environment 241plen = strlen (p ); 242// does the value include a trailing path separator? 243if (after_pathsep (p ,p + plen )) { 244has_trailing_path_sep = true; 245 } 246 } 247 248// item size needs to be large enough to include "/*" and a trailing NUL 249// note: the value (and therefore plen) may already include a path separator 250size_t itemsize = plen + (has_trailing_path_sep ?0 :1 )+ 2 ; 251char * item = xmalloc (itemsize ); 252// add a preceding comma as a separator after the first item 253size_t itemseplen = (ga .ga_len == 0 ) ?0 :1 ; 254 255size_t itemlen = (size_t )vim_snprintf (item ,itemsize ,"%s%s*" ,p , 256has_trailing_path_sep ?"" :PATHSEPSTR ); 257 258if (find_dup_item (ga .ga_data ,item ,itemlen ,options [opt_idx ].flags )== NULL ) { 259ga_grow (& ga , (int )(itemseplen + itemlen + 1 )); 260ga .ga_len += vim_snprintf ((char * )ga .ga_data + ga .ga_len , 261itemseplen + itemlen + 1 , 262"%s%s" , (itemseplen > 0 ) ?"," :"" ,item ); 263 } 264xfree (item ); 265 } 266if (mustfree ) { 267xfree (p ); 268 } 269 } 270if (ga .ga_data != NULL ) { 271set_string_default (kOptBackupskip ,ga .ga_data , true); 272 } 273} 274 275/// Initialize the 'cdpath' option to a default value. 276static void set_init_default_cdpath (void ) 277{ 278char * cdpath = vim_getenv ("CDPATH" ); 279if (cdpath == NULL ) { 280return ; 281 } 282 283char * buf = xmalloc (2 * strlen (cdpath )+ 2 ); 284buf [0 ]= ',' ;// start with ",", current dir first 285int j = 1 ; 286for (int i = 0 ;cdpath [i ]!= NUL ;i ++ ) { 287if (vim_ispathlistsep (cdpath [i ])) { 288buf [j ++ ]= ',' ; 289 }else { 290if (cdpath [i ]== ' ' || cdpath [i ]== ',' ) { 291buf [j ++ ]= '\\' ; 292 } 293buf [j ++ ]= cdpath [i ]; 294 } 295 } 296buf [j ]= NUL ; 297change_option_default (kOptCdpath ,CSTR_AS_OBJ (buf )); 298 299xfree (cdpath ); 300} 301 302/// Expand environment variables and things like "~" for the defaults. 303/// If option_expand() returns non-NULL the variable is expanded. This can 304/// only happen for non-indirect options. 305/// Also set the default to the expanded value, so ":set" does not list 306/// them. 307static void set_init_expand_env (void ) 308{ 309for (OptIndex opt_idx = 0 ;opt_idx < kOptCount ;opt_idx ++ ) { 310vimoption_T * opt = & options [opt_idx ]; 311if (opt -> flags & kOptFlagNoDefExp ) { 312continue ; 313 } 314char * p ; 315if ((opt -> flags & kOptFlagGettext )&& opt -> var != NULL ) { 316p = _ (* (char ** )opt -> var ); 317 }else { 318p = option_expand (opt_idx ,NULL ); 319 } 320if (p != NULL ) { 321Object ov = CSTR_TO_OBJ (p ); 322set_option_varp (opt_idx ,opt -> var ,ov );// Copies `ov`. 323change_option_default (opt_idx ,ov );// Consumes `ov`. 324 } 325 } 326} 327 328/// Initialize the encoding used for "default" in 'fileencodings'. 329static void set_init_fenc_default (void ) 330{ 331// enc_locale() will try to find the encoding of the current locale. 332// This will be used when "default" is used as encoding specifier 333// in 'fileencodings'. 334char * p = enc_locale (); 335if (p == NULL ) { 336// Use utf-8 as "default" if locale encoding can't be detected. 337p = xmemdupz (S_LEN ("utf-8" )); 338 } 339fenc_default = p ; 340} 341 342/// Initialize the options, first part. 343/// 344/// Called only once from main(), just after creating the first buffer. 345/// If "clean_arg" is true, Nvim was started with --clean. 346/// 347/// NOTE: ELOG() etc calls are not allowed here, as log location depends on 348/// env var expansion which depends on expression evaluation and other 349/// editor state initialized here. Do logging in set_init_2 or later. 350void set_init_1 (bool clean_arg ) 351{ 352langmap_init (); 353 354// Allocate the default option values. 355alloc_options_default (); 356 357set_init_default_shell (); 358set_init_default_backupskip (); 359set_init_default_cdpath (); 360 361char * backupdir = stdpaths_user_state_subpath ("backup" ,2 , true); 362const size_t backupdir_len = strlen (backupdir ); 363backupdir = xrealloc (backupdir ,backupdir_len + 3 ); 364memmove (backupdir + 2 ,backupdir ,backupdir_len + 1 ); 365memmove (backupdir ,".," ,2 ); 366set_string_default (kOptBackupdir ,backupdir , true); 367set_string_default (kOptViewdir ,stdpaths_user_state_subpath ("view" ,2 , false), 368 true); 369set_string_default (kOptDirectory ,stdpaths_user_state_subpath ("swap" ,2 , true), 370 true); 371set_string_default (kOptUndodir ,stdpaths_user_state_subpath ("undo" ,2 , true), 372 true); 373set_string_default (kOptPacklockfile ,stdpaths_user_conf_subpath ("nvim-pack-lock.json" ), 374 true); 375// Set default for &runtimepath. All necessary expansions are performed in 376// this function. 377char * rtp = runtimepath_default (clean_arg ); 378if (rtp ) { 379set_string_default (kOptRuntimepath ,rtp , true); 380// Make a copy of 'rtp' for 'packpath' 381set_string_default (kOptPackpath ,rtp , false); 382rtp = NULL ;// ownership taken 383 } 384 385// Set all the options (except the terminal options) to their default 386// value. Also set the global value for local options. 387set_options_default (0 ); 388 389curbuf -> b_p_initialized = true; 390curbuf -> b_p_ac = -1 ; 391curbuf -> b_p_ar = -1 ;// no local 'autoread' value 392curbuf -> b_p_fs = -1 ;// no local 'fsync' value 393curbuf -> b_p_ul = NO_LOCAL_UNDOLEVEL ; 394check_buf_options (curbuf ); 395check_win_options (curwin ); 396check_options (); 397 398// set 'laststatus' 399last_status (false); 400 401// Must be before option_expand(), because that one needs vim_isIDc() 402didset_options (); 403 404// Use the current chartab for the generic chartab. This is not in 405// didset_options() because it only depends on 'encoding'. 406init_spell_chartab (); 407 408// Expand environment variables and things like "~" for the defaults. 409set_init_expand_env (); 410 411// Allow disabling ttyfast during startup to disable features such as 412// automatic background detection over slow connections. 413if (os_env_exists ("NVIM_NOTTYFAST" , false)) { 414set_option_value_give_err (kOptTtyfast ,BOOLEAN_OBJ (false),0 ); 415 } 416 417save_file_ff (curbuf );// Buffer is unchanged 418 419// Detect use of mlterm. 420// Mlterm is a terminal emulator akin to xterm that has some special 421// abilities (bidi namely). 422// NOTE: mlterm's author is being asked to 'set' a variable 423// instead of an environment variable due to inheritance. 424if (os_env_exists ("MLTERM" , false)) { 425set_option_value_give_err (kOptTermbidi ,BOOLEAN_OBJ (true),0 ); 426 } 427 428didset_options2 (); 429 430lang_init (); 431set_init_fenc_default (); 432 433#ifdef HAVE_WORKING_LIBINTL 434// GNU gettext 0.10.37 supports this feature: set the codeset used for 435// translated messages independently from the current locale. 436 (void )bind_textdomain_codeset (PROJECT_NAME ,p_enc ); 437#endif 438 439// Set the default for 'helplang'. 440set_helplang_default (get_mess_lang ()); 441} 442 443/// Get default value for option, based on the option's type and scope. 444/// 445/// @param opt_idx Option index in options[] table. 446/// @param opt_flags Option flags (can be OPT_LOCAL, OPT_GLOBAL or a combination). 447/// 448/// @return Default value for the scope specified by opt_flags. Release with optval_free_read(). 449Object get_option_default (const OptIndex opt_idx ,int opt_flags ) 450{ 451vimoption_T * opt = & options [opt_idx ]; 452bool is_global_local_option = option_is_global_local (opt_idx ); 453 454#ifdef UNIX 455if (opt_idx == kOptModeline && getuid ()== ROOT_UID ) { 456// 'modeline' defaults to off for root. 457return BOOLEAN_OBJ (false); 458 } 459#endif 460 461if ((opt_flags & OPT_LOCAL )&& is_global_local_option ) { 462// Local scope of a global-local option defaults to "unset" (optval_is_unset_local()). 463return UNSET ; 464 } 465 466Object def_val = opt -> def_val ; 467if (option_has_type (opt_idx ,kObjectTypeString )&& !(opt -> flags & kOptFlagNoDefExp )) { 468// For string options, expand environment variables and ~ since the default value was already 469// expanded, only required when an environment variable was set later. 470char * s = option_expand (opt_idx ,def_val .data .string .data ); 471if (s != NULL ) { 472def_val = CSTR_AS_OBJ (s ); 473 } 474 } 475return optval_is_owned (opt_idx ) ?copy_object (def_val ,NULL ) :def_val ; 476} 477 478/// Allocate the default values for all options by copying them from the stack. 479/// This ensures that we don't need to always check if the option default is allocated or not. 480static void alloc_options_default (void ) 481{ 482for (OptIndex opt_idx = 0 ;opt_idx < kOptCount ;opt_idx ++ ) { 483options [opt_idx ].def_val = copy_object (options [opt_idx ].def_val ,NULL ); 484 } 485} 486 487/// Change the default value for an option. 488/// 489/// @param opt_idx Option index in options[] table. 490/// @param value New default value. Must be allocated. 491static void change_option_default (const OptIndex opt_idx ,Object value ) 492{ 493optval_free (options [opt_idx ].def_val ); 494options [opt_idx ].def_val = value ; 495} 496 497/// Set an option to its default value. 498/// This does not take care of side effects! 499/// 500/// @param opt_idx Option index in options[] table. 501/// @param opt_flags Option flags (can be OPT_LOCAL, OPT_GLOBAL or a combination). 502static void set_option_default (const OptIndex opt_idx ,int opt_flags ) 503{ 504bool both = (opt_flags & (OPT_LOCAL |OPT_GLOBAL ))== 0 ; 505Object def_val = get_option_default (opt_idx ,opt_flags ); 506set_option_direct (opt_idx ,def_val ,opt_flags ,current_sctx .sc_sid ); 507optval_free_read (opt_idx ,def_val ); 508 509if (opt_idx == kOptScroll ) { 510win_comp_scroll (curwin ); 511 } 512 513// The default value is not insecure. 514uint32_t * flagsp = insecure_flag (curwin ,opt_idx ,opt_flags ); 515* flagsp = * flagsp & ~(unsigned )kOptFlagInsecure ; 516if (both ) { 517flagsp = insecure_flag (curwin ,opt_idx ,OPT_LOCAL ); 518* flagsp = * flagsp & ~(unsigned )kOptFlagInsecure ; 519 } 520} 521 522/// Set all options (except terminal options) to their default value. 523/// 524/// @param opt_flags Option flags (can be OPT_LOCAL, OPT_GLOBAL or a combination). 525static void set_options_default (int opt_flags ) 526{ 527for (OptIndex opt_idx = 0 ;opt_idx < kOptCount ;opt_idx ++ ) { 528if (!(options [opt_idx ].flags & kOptFlagNoDefault )) { 529set_option_default (opt_idx ,opt_flags ); 530 } 531 } 532 533// The 'scroll' option must be computed for all windows. 534FOR_ALL_TAB_WINDOWS (tp ,wp ) { 535win_comp_scroll (wp ); 536 } 537 538parse_cino (curbuf ); 539} 540 541/// Set the Vi-default value of a string option. 542/// Used for 'sh', 'backupskip' and 'term'. 543/// 544/// @param opt_idx Option index in options[] table. 545/// @param val The value of the option. 546/// @param allocated If true, do not copy default as it was already allocated. 547/// 548/// TODO(famiu): Remove this. 549static void set_string_default (OptIndex opt_idx ,char * val ,bool allocated ) 550FUNC_ATTR_NONNULL_ALL 551{ 552assert (opt_idx != kOptInvalid ); 553change_option_default (opt_idx ,CSTR_AS_OBJ (allocated ?val :xstrdup (val ))); 554} 555 556/// For an option value that contains comma separated items, find "newval" in 557/// "origval". Return NULL if not found. 558static const char * find_dup_item (const char * origval ,const char * newval ,const size_t newvallen , 559uint32_t flags ) 560FUNC_ATTR_NONNULL_ARG (2 ) 561{ 562if (origval == NULL ) { 563return NULL ; 564 } 565 566int bs = 0 ; 567 568for (const char * s = origval ;* s != NUL ;s ++ ) { 569if ((!(flags & kOptFlagComma )|| s == origval || (s [-1 ]== ',' && !(bs & 1 ))) 570&& strncmp (s ,newval ,newvallen )== 0 571&& (!(flags & kOptFlagComma )|| s [newvallen ]== ',' || s [newvallen ]== NUL )) { 572return s ; 573 } 574// Count backslashes. Only a comma with an even number of backslashes 575// or a single backslash preceded by a comma before it is recognized as 576// a separator. 577if ((s > origval + 1 && s [-1 ]== '\\' && s [-2 ]!= ',' ) 578|| (s == origval + 1 && s [-1 ]== '\\' )) { 579bs ++ ; 580 }else { 581bs = 0 ; 582 } 583 } 584return NULL ; 585} 586 587#ifdef EXITFREE 588/// Free all options. 589void free_all_options (void ) 590{ 591for (OptIndex opt_idx = 0 ;opt_idx < kOptCount ;opt_idx ++ ) { 592bool hidden = is_option_hidden (opt_idx ); 593 594if (option_is_global_only (opt_idx )|| hidden ) { 595// global option: free value and default value. 596// hidden option: free default value only. 597if (!hidden ) { 598optval_free (opt_from_varp (opt_idx ,options [opt_idx ].var )); 599 } 600 }else if (!option_is_window_local (opt_idx )) { 601// buffer-local option: free global value. 602optval_free (opt_from_varp (opt_idx ,options [opt_idx ].var )); 603 } 604optval_free (options [opt_idx ].def_val ); 605 } 606free_operatorfunc_option (); 607free_tagfunc_option (); 608free_findfunc_option (); 609XFREE_CLEAR (fenc_default ); 610XFREE_CLEAR (p_term ); 611XFREE_CLEAR (p_ttytype ); 612} 613#endif 614 615/// Initialize the options, part two: After getting Rows and Columns. 616void set_init_2 (bool headless ) 617{ 618// set in set_init_1 but logging is not allowed there 619ILOG ("startup runtimepath/packpath value: %s" ,p_rtp ); 620 621// 'scroll' defaults to half the window height. The stored default is zero, 622// which results in the actual value computed from the window height. 623if (!(options [kOptScroll ].flags & kOptFlagWasSet )) { 624set_option_default (kOptScroll ,OPT_LOCAL ); 625 } 626comp_col (); 627 628// 'window' is only for backwards compatibility with Vi. 629// Default is Rows - 1. 630if (!option_was_set (kOptWindow )) { 631p_window = Rows - 1 ; 632 } 633change_option_default (kOptWindow ,INTEGER_OBJ (Rows - 1 )); 634} 635 636static const struct { 637const char * pat ; 638const char * shcf ; 639const char * sp ; 640const char * srr ; 641const char * sxq ; 642}shell_rules []= { 643#ifdef MSWIN 644 {"cmd" ,"/s /c" ,NULL ,NULL ,"\"" }, 645 {"powershell" ,"-Command" ,NULL ,NULL ,NULL }, 646#endif 647 {"csh" ,NULL ,"|& tee" ,">&" ,NULL }, 648 {"sh" ,NULL ,"2>&1| tee" ,">%s 2>&1" ,NULL }, 649}; 650 651static void change_option_and_default_if_unset (OptIndex idx ,const char * val ) 652{ 653if (val == NULL || options [idx ].flags & kOptFlagWasSet ) { 654return ; 655 } 656Object optval = CSTR_AS_OBJ (val ); 657set_option_direct (idx ,optval ,0 ,SID_NONE ); 658change_option_default (idx ,copy_object (optval ,NULL )); 659} 660 661/// Initialize the options, part three: After reading the .vimrc 662void set_init_3 (void ) 663{ 664parse_shape_opt (SHAPE_CURSOR );// set cursor shapes from 'guicursor' 665 666size_t len ; 667char name [MAXPATHL ]; 668const char * p = invocation_path_tail (p_sh ,& len ); 669xmemcpyz (name ,p ,len ); 670for (size_t i = 0 ;i < ARRAY_SIZE (shell_rules );i ++ ) { 671if (strstr (name ,shell_rules [i ].pat )== NULL ) { 672continue ; 673 } 674change_option_and_default_if_unset (kOptShellcmdflag ,shell_rules [i ].shcf ); 675change_option_and_default_if_unset (kOptShellpipe ,shell_rules [i ].sp ); 676change_option_and_default_if_unset (kOptShellredir ,shell_rules [i ].srr ); 677change_option_and_default_if_unset (kOptShellxquote ,shell_rules [i ].sxq ); 678#ifdef MSWIN 679if (i > 0 && !(options [kOptShellslash ].flags & kOptFlagWasSet )) { 680// Use `/` as path separator on Unix-like shells or powershell on Windows 681set_option_direct (kOptShellslash ,BOOLEAN_OBJ (true),0 ,SID_NONE ); 682change_option_default (kOptShellslash ,BOOLEAN_OBJ (true)); 683 } 684#endif 685break ; 686 } 687 688if (buf_is_empty (curbuf )) { 689// Apply the first entry of 'fileformats' to the initial buffer. 690if (options [kOptFileformats ].flags & kOptFlagWasSet ) { 691set_fileformat (default_fileformat (),OPT_LOCAL ); 692 } 693 } 694 695set_title_defaults ();// 'title', 'icon' 696} 697 698/// When 'helplang' is still at its default value, set it to "lang". 699/// Only the first two characters of "lang" are used. 700void set_helplang_default (const char * lang ) 701{ 702if (lang == NULL ) { 703return ; 704 } 705 706const size_t lang_len = strlen (lang ); 707if (lang_len < 2 ) {// safety check 708return ; 709 } 710if (options [kOptHelplang ].flags & kOptFlagWasSet ) { 711return ; 712 } 713 714free_string_option (p_hlg ); 715p_hlg = xmemdupz (lang ,lang_len ); 716// zh_CN becomes "cn", zh_TW becomes "tw". 717if (STRNICMP (p_hlg ,"zh_" ,3 )== 0 && lang_len >=5 ) { 718p_hlg [0 ]= (char )TOLOWER_ASC (p_hlg [3 ]); 719p_hlg [1 ]= (char )TOLOWER_ASC (p_hlg [4 ]); 720 }else if (lang_len && * p_hlg == 'C' ) { 721// any C like setting, such as C.UTF-8, becomes "en" 722p_hlg [0 ]= 'e' ; 723p_hlg [1 ]= 'n' ; 724 } 725p_hlg [2 ]= NUL ; 726} 727 728/// 'title' and 'icon' only default to true if they have not been set or reset 729/// in .vimrc and we can read the old value. 730/// When 'title' and 'icon' have been reset in .vimrc, we won't even check if 731/// they can be reset. This reduces startup time when using X on a remote 732/// machine. 733void set_title_defaults (void ) 734{ 735// If GUI is (going to be) used, we can always set the window title and 736// icon name. Saves a bit of time, because the X11 display server does 737// not need to be contacted. 738if (!(options [kOptTitle ].flags & kOptFlagWasSet )) { 739change_option_default (kOptTitle ,BOOLEAN_OBJ (false)); 740p_title = 0 ; 741 } 742if (!(options [kOptIcon ].flags & kOptFlagWasSet )) { 743change_option_default (kOptIcon ,BOOLEAN_OBJ (false)); 744p_icon = 0 ; 745 } 746} 747 748void ex_set (exarg_T * eap ) 749{ 750int flags = 0 ; 751 752if (eap -> cmdidx == CMD_setlocal ) { 753flags = OPT_LOCAL ; 754 }else if (eap -> cmdidx == CMD_setglobal ) { 755flags = OPT_GLOBAL ; 756 } 757if (eap -> forceit ) { 758flags |=OPT_ONECOLUMN ; 759 } 760do_set (eap -> arg ,flags ); 761} 762 763/// Copy the new string value into allocated memory for the option. 764/// Can't use set_option_direct(), because we need to remove the backslashes. 765static char * stropt_copy_value (const char * origval ,char ** argp ,set_op_T op , 766uint32_t flags FUNC_ATTR_UNUSED ) 767{ 768char * arg = * argp ; 769 770// get a bit too much 771size_t newlen = strlen (arg )+ 1 ; 772if (op != OP_NONE ) { 773newlen += strlen (origval )+ 1 ; 774 } 775char * newval = xmalloc (newlen ); 776char * s = newval ; 777 778// Copy the string, skip over escaped chars. 779// For MS-Windows backslashes before normal file name characters 780// are not removed, and keep backslash at start, for "\\machine\path", 781// but do remove it for "\\\\machine\\path". 782// The reverse is found in escape_option_str_cmdline(). 783while (* arg != NUL && !ascii_iswhite (* arg )) { 784if (* arg == '\\' && arg [1 ]!= NUL 785#ifdef BACKSLASH_IN_FILENAME 786&& !((flags & kOptFlagExpand ) 787&& vim_isfilec ((uint8_t )arg [1 ]) 788&& !ascii_iswhite (arg [1 ]) 789&& (arg [1 ]!= '\\' 790|| (s == newval && arg [2 ]!= '\\' ))) 791#endif 792 ) { 793arg ++ ;// remove backslash 794 } 795int i = utfc_ptr2len (arg ); 796if (i > 1 ) { 797// copy multibyte char 798memmove (s ,arg , (size_t )i ); 799arg += i ; 800s += i ; 801 }else { 802* s ++ = * arg ++ ; 803 } 804 } 805* s = NUL ; 806 807* argp = arg ; 808return newval ; 809} 810 811/// Expand environment variables and ~ in string option value 'newval'. 812static char * stropt_expand_envvar (OptIndex opt_idx ,const char * origval ,char * newval ,set_op_T op ) 813{ 814char * s = option_expand (opt_idx ,newval ); 815if (s == NULL ) { 816return newval ; 817 } 818 819xfree (newval ); 820uint32_t newlen = (unsigned )strlen (s )+ 1 ; 821if (op != OP_NONE ) { 822newlen += (unsigned )strlen (origval )+ 1 ; 823 } 824newval = xmalloc (newlen ); 825STRCPY (newval ,s ); 826 827return newval ; 828} 829 830/// Concatenate the original and new values of a string option, adding a "," if 831/// needed. 832static void stropt_concat_with_comma (const char * origval ,char * newval ,set_op_T op ,uint32_t flags ) 833{ 834int len = 0 ; 835int comma = ((flags & kOptFlagComma )&& * origval != NUL && * newval != NUL ); 836if (op == OP_ADDING ) { 837len = (int )strlen (origval ); 838// Strip a trailing comma, would get 2. 839if (comma && len > 1 840&& (flags & kOptFlagOneComma )== kOptFlagOneComma 841&& origval [len - 1 ]== ',' 842&& origval [len - 2 ]!= '\\' ) { 843len -- ; 844 } 845memmove (newval + len + comma ,newval ,strlen (newval )+ 1 ); 846memmove (newval ,origval , (size_t )len ); 847 }else { 848len = (int )strlen (newval ); 849STRMOVE (newval + len + comma ,origval ); 850 } 851if (comma ) { 852newval [len ]= ',' ; 853 } 854} 855 856/// Remove a value from a string option. Copy string option value in "origval" 857/// to "newval" and then remove the string "strval" of length "len". 858static void stropt_remove_val (const char * origval ,char * newval ,uint32_t flags ,const char * strval , 859int len ) 860{ 861// Remove newval[] from origval[]. (Note: "len" has been set above 862// and is used here). 863STRCPY (newval ,origval ); 864if (* strval ) { 865// may need to remove a comma 866if (flags & kOptFlagComma ) { 867if (strval == origval ) { 868// include comma after string 869if (strval [len ]== ',' ) { 870len ++ ; 871 } 872 }else { 873// include comma before string 874strval -- ; 875len ++ ; 876 } 877 } 878STRMOVE (newval + (strval - origval ),strval + len ); 879 } 880} 881 882/// Find a comma-separated item in "src" that matches the key part of "key". 883/// The key is the part before ':'. "keylen" is the length including ':'. 884/// Returns a pointer to the found item in "src", or NULL if not found. 885/// Sets "*itemlenp" to the length of the found item (up to ',' or NUL). 886static char * find_key_item (char * src ,char * key ,ptrdiff_t keylen ,ptrdiff_t * itemlenp ) 887{ 888char * p = src ; 889 890while (* p != NUL ) { 891// Check if this item starts with the same key 892if ((p == src || * (p - 1 )== ',' )&& strncmp (p ,key , (size_t )keylen )== 0 ) { 893// Find the end of this item 894char * end = vim_strchr (p ,',' ); 895if (end == NULL ) { 896end = p + strlen (p ); 897 } 898* itemlenp = end - p ; 899return p ; 900 } 901p ++ ; 902 } 903return NULL ; 904} 905 906/// Remove one item of length "itemlen" at position "item" from comma-separated 907/// string "str" in-place. Handles the comma before or after the item. 908static void remove_comma_item (const char * str ,char * item ,ptrdiff_t itemlen ) 909{ 910if (item [itemlen ]== ',' ) { 911// Remove item and trailing comma 912STRMOVE (item ,item + itemlen + 1 ); 913 }else if (item > str && * (item - 1 )== ',' ) { 914// Last item: remove leading comma and item 915STRMOVE (item - 1 ,item + itemlen ); 916 }else { 917// Only item 918* item = NUL ; 919 } 920} 921 922/// Remove all items matching "key" (with ':') from comma-separated string "str" 923/// in-place. If "skip" is not NULL, the item at that position is kept. 924static void remove_key_item (char * str ,char * key ,ptrdiff_t keylen ,const char * skip ) 925{ 926ptrdiff_t itemlen ; 927char * found ; 928 929while ((found = find_key_item (str ,key ,keylen ,& itemlen ))!= NULL ) { 930if (found == skip ) { 931// Search for the next match after this one. 932char * next = found + itemlen ; 933if (* next == ',' ) { 934next ++ ; 935 } 936found = find_key_item (next ,key ,keylen ,& itemlen ); 937if (found == NULL ) { 938break ; 939 } 940 } 941 942remove_comma_item (str ,found ,itemlen ); 943 } 944} 945 946/// Append a comma-separated item to the end of "str" in-place. 947/// Adds a comma before the item if "str" is not empty. 948static void append_item (char * str ,char * item ,ptrdiff_t item_len ) 949{ 950ptrdiff_t len = (ptrdiff_t )strlen (str ); 951 952if (len > 0 ) { 953str [len ++ ]= ',' ; 954 } 955memmove (str + len ,item , (size_t )item_len ); 956str [len + item_len ]= NUL ; 957} 958 959/// Prepend a comma-separated item to the beginning of "str" in-place. 960/// Adds a comma after the item if "str" is not empty. 961static void prepend_item (char * str ,char * item ,ptrdiff_t item_len ) 962{ 963ptrdiff_t len = (ptrdiff_t )strlen (str ); 964int comma = (len > 0 ) ?1 :0 ; 965 966memmove (str + item_len + comma ,str , (size_t )len + 1 ); 967memmove (str ,item , (size_t )item_len ); 968if (comma ) { 969str [item_len ]= ',' ; 970 } 971} 972 973/// For a P_COMMA option: process "key:value" items in "newval" individually. 974/// Each comma-separated item in "newval" is checked against "origval": 975/// 976/// For OP_ADDING/OP_PREPENDING, each item is handled as follows: 977/// - colon item, key exists with different value: replace (remove old, add) 978/// - colon item, exact duplicate: do nothing 979/// - colon item, not found: add to end 980/// - non-colon item, exists: do nothing 981/// - non-colon item, not found: add to end 982/// 983/// For OP_REMOVING, each item is handled as follows: 984/// - colon item: remove by key match 985/// - non-colon item: remove by exact match 986/// 987/// The result is written to "newval". 988/// Returns true if the operation was fully handled (caller should skip the 989/// normal add/remove logic). Returns false if newval is a single non-colon 990/// item, meaning the caller should use the existing code path. 991static bool stropt_handle_keymatch (const char * origval ,char * newval ,set_op_T op ,uint32_t flags ) 992{ 993// Check if newval contains any "key:value" item or multiple 994// comma-separated items. If neither, let the caller use the existing 995// code path. 996if (vim_strchr (newval ,':' )== NULL && vim_strchr (newval ,',' )== NULL ) { 997return false; 998 } 999 1000// Work on a copy of newval for iteration. 1001char * newval_copy = xstrdup (newval ); 1002 1003// Build the result in newval. Start with a copy of origval, then 1004// modify it per-item. newval buffer has room for origval + arg. 1005STRCPY (newval ,origval ); 1006 1007// Process each item individually, modifying newval in-place. 1008char * item_start = newval_copy ; 1009while (true) { 1010char * p = vim_strchr (item_start ,',' ); 1011ptrdiff_t item_len = p == NULL ? (ptrdiff_t )strlen (item_start ) :p - item_start ; 1012 1013if (item_len > 0 ) { 1014char * colon = vim_strchr (item_start ,':' ); 1015if (colon != NULL && colon < item_start + item_len ) { 1016ptrdiff_t keylen = (colon - item_start )+ 1 ; 1017 1018if (op == OP_ADDING || op == OP_PREPENDING ) { 1019ptrdiff_t old_itemlen ; 1020char * found = find_key_item (newval ,item_start ,keylen ,& old_itemlen ); 1021if (found != NULL ) { 1022if (old_itemlen == item_len 1023&& strncmp (found ,item_start , (size_t )item_len )== 0 ) { 1024// Exact duplicate: keep it in place, but 1025// remove other items with the same key. 1026remove_key_item (newval ,item_start ,keylen ,found ); 1027 }else { 1028// Key match with different value: remove all 1029// items with the same key, then add. 1030remove_key_item (newval ,item_start ,keylen ,NULL ); 1031if (op == OP_PREPENDING ) { 1032prepend_item (newval ,item_start ,item_len ); 1033 }else { 1034append_item (newval ,item_start ,item_len ); 1035 } 1036 } 1037 }else { 1038// New item. 1039if (op == OP_PREPENDING ) { 1040prepend_item (newval ,item_start ,item_len ); 1041 }else { 1042append_item (newval ,item_start ,item_len ); 1043 } 1044 } 1045 }else if (op == OP_REMOVING ) { 1046remove_key_item (newval ,item_start ,keylen ,NULL ); 1047 } 1048 }else { 1049if (op == OP_ADDING || op == OP_PREPENDING ) { 1050const char * found = find_dup_item (newval ,item_start , (size_t )item_len , 1051kOptFlagComma ); 1052if (found == NULL ) { 1053// New item. 1054if (op == OP_PREPENDING ) { 1055prepend_item (newval ,item_start ,item_len ); 1056 }else { 1057append_item (newval ,item_start ,item_len ); 1058 } 1059 } 1060// else: exact duplicate — do nothing 1061 }else if (op == OP_REMOVING ) { 1062char * found = (char * )find_dup_item (newval ,item_start , (size_t )item_len , 1063kOptFlagComma ); 1064if (found != NULL ) { 1065remove_comma_item (newval ,found ,item_len ); 1066 } 1067 } 1068 } 1069 } 1070 1071if (p == NULL ) { 1072break ; 1073 } 1074item_start = p + 1 ; 1075 } 1076 1077xfree (newval_copy ); 1078 1079return true; 1080} 1081 1082/// Remove flags that appear twice in the string option value 'newval'. 1083static void stropt_remove_dupflags (char * newval ,uint32_t flags ) 1084{ 1085char * s = newval ; 1086// Remove flags that appear twice. 1087for (s = newval ;* s ;) { 1088// if options have kOptFlagFlagList and kOptFlagOneComma such as 'whichwrap' 1089if (flags & kOptFlagOneComma ) { 1090if (* s != ',' && * (s + 1 )== ',' 1091&& vim_strchr (s + 2 , (uint8_t )(* s ))!= NULL ) { 1092// Remove the duplicated value and the next comma. 1093STRMOVE (s ,s + 2 ); 1094continue ; 1095 } 1096 }else { 1097if ((!(flags & kOptFlagComma )|| * s != ',' ) 1098&& vim_strchr (s + 1 , (uint8_t )(* s ))!= NULL ) { 1099STRMOVE (s ,s + 1 ); 1100continue ; 1101 } 1102 } 1103s ++ ; 1104 } 1105} 1106 1107/// Get the string value specified for a ":set" command. The following set options are supported: 1108/// set {opt}={val} 1109/// set {opt}:{val} 1110static char * stropt_get_newval (OptIndex opt_idx ,char ** argp ,void * varp ,const char * origval , 1111set_op_T * op_arg ) 1112{ 1113char * arg = * argp ; 1114set_op_T op = * op_arg ; 1115char * save_arg = NULL ; 1116char * newval ; 1117const char * s = NULL ; 1118uint32_t flags = options [opt_idx ].flags ; 1119 1120arg ++ ;// jump to after the '=' or ':' 1121 1122// Set 'keywordprg' to ":help" if an empty 1123// value was passed to :set by the user. 1124if (varp == & p_kp && (* arg == NUL || * arg == ' ' )) { 1125save_arg = arg ; 1126arg = ":help" ; 1127 } 1128 1129// Copy the new string into allocated memory. 1130newval = stropt_copy_value (origval ,& arg ,op ,flags ); 1131 1132// Expand environment variables and ~. 1133// Don't do it when adding without inserting a comma. 1134if (op == OP_NONE || (flags & kOptFlagComma )) { 1135newval = stropt_expand_envvar (opt_idx ,origval ,newval ,op ); 1136 } 1137 1138// For kOptFlagComma|kOptFlagColon options with "key:value" items: process each item 1139// individually by matching on the key part. 1140// If handled, skip the normal add/remove logic below. 1141if ((flags & kOptFlagComma )&& (flags & kOptFlagColon )&& op != OP_NONE 1142&& stropt_handle_keymatch (origval ,newval ,op ,flags )) { 1143// fully handled 1144 }else { 1145// locate newval[] in origval[] when removing it and when 1146// adding to avoid duplicates 1147int len = 0 ; 1148if (op == OP_REMOVING || (flags & kOptFlagNoDup )) { 1149len = (int )strlen (newval ); 1150s = find_dup_item (origval ,newval , (size_t )len ,flags ); 1151 1152// do not add if already there 1153if ((op == OP_ADDING || op == OP_PREPENDING )&& s != NULL ) { 1154op = OP_NONE ; 1155STRCPY (newval ,origval ); 1156 } 1157 1158// if no duplicate, move pointer to end of original value 1159if (s == NULL ) { 1160s = origval + (int )strlen (origval ); 1161 } 1162 } 1163 1164// concatenate the two strings; add a ',' if needed 1165if (op == OP_ADDING || op == OP_PREPENDING ) { 1166stropt_concat_with_comma (origval ,newval ,op ,flags ); 1167 }else if (op == OP_REMOVING ) { 1168// Remove newval[] from origval[]. (Note: "len" has been 1169// set above and is used here). 1170stropt_remove_val (origval ,newval ,flags ,s ,len ); 1171 } 1172 } 1173 1174if (flags & kOptFlagFlagList ) { 1175// Remove flags that appear twice. 1176stropt_remove_dupflags (newval ,flags ); 1177 } 1178 1179if (save_arg != NULL ) { 1180arg = save_arg ;// arg was temporarily changed, restore it 1181 } 1182* argp = arg ; 1183* op_arg = op ; 1184 1185return newval ; 1186} 1187 1188static set_op_T get_op (const char * arg ) 1189{ 1190set_op_T op = OP_NONE ; 1191if (* arg != NUL && * (arg + 1 )== '=' ) { 1192if (* arg == '+' ) { 1193op = OP_ADDING ;// "+=" 1194 }else if (* arg == '^' ) { 1195op = OP_PREPENDING ;// "^=" 1196 }else if (* arg == '-' ) { 1197op = OP_REMOVING ;// "-=" 1198 } 1199 } 1200return op ; 1201} 1202 1203static set_prefix_T get_option_prefix (char ** argp ) 1204{ 1205if (strncmp (* argp ,"no" ,2 )== 0 ) { 1206* argp += 2 ; 1207return PREFIX_NO ; 1208 }else if (strncmp (* argp ,"inv" ,3 )== 0 ) { 1209* argp += 3 ; 1210return PREFIX_INV ; 1211 } 1212 1213return PREFIX_NONE ; 1214} 1215 1216static int validate_opt_idx (win_T * win ,OptIndex opt_idx ,int opt_flags ,uint32_t flags , 1217set_prefix_T prefix ,const char ** errmsg ) 1218{ 1219// Only bools can have a prefix of 'inv' or 'no' 1220if (!option_has_type (opt_idx ,kObjectTypeBoolean )&& prefix != PREFIX_NONE ) { 1221* errmsg = e_invarg ; 1222return FAIL ; 1223 } 1224 1225// Skip all options that are not window-local (used when showing 1226// an already loaded buffer in a window). 1227if ((opt_flags & OPT_WINONLY )&& !option_is_window_local (opt_idx )) { 1228return FAIL ; 1229 } 1230 1231// Skip all options that are window-local (used for :vimgrep). 1232if ((opt_flags & OPT_NOWIN )&& option_is_window_local (opt_idx )) { 1233return FAIL ; 1234 } 1235 1236// Disallow changing some options from modelines. 1237if (opt_flags & OPT_MODELINE ) { 1238if (flags & kOptFlagSecure ) { 1239* errmsg = e_not_allowed_in_modeline ; 1240return FAIL ; 1241 } 1242if ((flags & kOptFlagMLE )&& !p_mle ) { 1243* errmsg = e_not_allowed_in_modeline_when_modelineexpr_is_off ; 1244return FAIL ; 1245 } 1246// In diff mode some options are overruled. This avoids that 1247// 'foldmethod' becomes "marker" instead of "diff" and that 1248// "wrap" gets set. 1249if (win -> w_p_diff && (opt_idx == kOptFoldmethod || opt_idx == kOptWrap )) { 1250return FAIL ; 1251 } 1252 } 1253 1254// Disallow changing some options in the sandbox 1255if (sandbox != 0 && (flags & kOptFlagSecure )) { 1256* errmsg = e_sandbox ; 1257return FAIL ; 1258 } 1259 1260return OK ; 1261} 1262 1263/// Skip over the name of a TTY option or keycode option. 1264/// 1265/// @param[in] arg Start of TTY or keycode option name. 1266/// 1267/// @return NULL when option isn't a TTY or keycode option. Otherwise pointer to the char after the 1268/// option name. 1269static const char * find_tty_option_end (const char * arg ) 1270{ 1271if (strequal (arg ,"term" )) { 1272return arg + sizeof ("term" )- 1 ; 1273 }else if (strequal (arg ,"ttytype" )) { 1274return arg + sizeof ("ttytype" )- 1 ; 1275 } 1276 1277const char * p = arg ; 1278bool delimit = false;// whether to delimit < 1279 1280if (arg [0 ]== '<' ) { 1281// look out for <t_>;> 1282delimit = true; 1283p ++ ; 1284 } 1285if (p [0 ]== 't' && p [1 ]== '_' && p [2 ]&& p [3 ]) { 1286// "t_xx" ("t_Co") option. 1287p += 4 ; 1288 }else if (delimit ) { 1289// Search for delimiting >. 1290while (* p != NUL && * p != '>' ) { 1291p ++ ; 1292 } 1293 } 1294// Return NULL when delimiting > is not found. 1295if (delimit ) { 1296if (* p != '>' ) { 1297return NULL ; 1298 } 1299p ++ ; 1300 } 1301 1302return arg == p ?NULL :p ; 1303} 1304 1305/// Skip over the name of an option. 1306/// 1307/// @param[in] arg Start of option name. 1308/// @param[out] opt_idxp Set to option index in options[] table. 1309/// 1310/// @return NULL when no option name found. Otherwise pointer to the char after the option name. 1311const char * find_option_end (const char * arg ,OptIndex * opt_idxp ) 1312{ 1313const char * p ; 1314 1315// Handle TTY and keycode options separately. 1316if ((p = find_tty_option_end (arg ))!= NULL ) { 1317* opt_idxp = kOptInvalid ; 1318return p ; 1319 }else { 1320p = arg ; 1321 } 1322 1323if (!ASCII_ISALPHA (* p )) { 1324* opt_idxp = kOptInvalid ; 1325return NULL ; 1326 } 1327while (ASCII_ISALPHA (* p )) { 1328p ++ ; 1329 } 1330 1331* opt_idxp = find_option_len (arg , (size_t )(p - arg )); 1332return p ; 1333} 1334 1335/// Get new option value from argp. Allocated Object must be freed by caller. 1336/// Can unset local value of an option when ":set {option}<" is used. 1337Object get_option_newval (OptIndex opt_idx ,int opt_flags ,set_prefix_T prefix ,char ** argp , 1338int nextchar ,set_op_T op ,void * varp ,Object * oldval_override , 1339const char ** errmsg ) 1340FUNC_ATTR_WARN_UNUSED_RESULT 1341{ 1342assert (varp != NULL ); 1343 1344vimoption_T * opt = & options [opt_idx ]; 1345char * arg = * argp ; 1346 1347Object newval = NIL ; 1348 1349if (nextchar == '&' ) { 1350// ":set opt&": Reset to default value. 1351// NOTE: Use OPT_GLOBAL instead of opt_flags to ensure we don't use the unset local value for 1352// global-local options when OPT_LOCAL is used. 1353return optval_own (opt_idx ,get_option_default (opt_idx ,OPT_GLOBAL )); 1354 }else if (nextchar == '<' ) { 1355// ":set opt<": Reset to global value. 1356// ":setlocal opt<": Copy global value to local value. 1357if (option_is_global_local (opt_idx )&& !(opt_flags & OPT_LOCAL )) { 1358unset_option_local_value (opt_idx ); 1359 } 1360return get_option_value (opt_idx ,OPT_GLOBAL ); 1361 } 1362 1363// Computed lazily: the ":set opt&"/"opt<" resets above return without needing the old value. 1364Object oldval ; 1365if (oldval_override != NULL ) { 1366// Allow overriding the oldval. This is needed to handle the case where options for 1367// buffers/windows other than curbuf/curwin are updated. It can also support merging arbitrary 1368// values if necessary down the road. 1369oldval = * oldval_override ; 1370 }else { 1371// When setting the local value of a global option, the old value may be the global value. 1372const bool oldval_is_global = option_is_global_local (opt_idx )&& (opt_flags & OPT_LOCAL ); 1373oldval = optval_own (opt_idx ,opt_from_varp (opt_idx ,oldval_is_global ?get_varp (opt ) :varp )); 1374 } 1375 1376switch (oldval .type ) { 1377case kObjectTypeNil : 1378abort (); 1379case kObjectTypeUnset :// Unset local value of a global-local boolean. 1380case kObjectTypeBoolean : { 1381TriState newval_bool ; 1382 1383// ":set opt!": invert (an unset local value stays unset) 1384if (nextchar == '!' ) { 1385newval_bool = oldval .type == 1386kObjectTypeUnset ?kNone : (oldval .data .boolean ?kFalse :kTrue ); 1387 }else { 1388// ":set invopt": invert 1389// ":set opt" or ":set noopt": set or reset 1390if (prefix == PREFIX_INV ) { 1391newval_bool = * (int * )varp ^1 ; 1392 }else { 1393newval_bool = prefix == PREFIX_NO ?0 :1 ; 1394 } 1395 } 1396 1397newval = opt_from_tristate (newval_bool ); 1398break ; 1399 } 1400case kObjectTypeInteger : { 1401OptInt oldval_num = oldval .data .integer ; 1402OptInt newval_num ; 1403 1404// Different ways to set a number option: 1405// <xx> accept special key codes for 'wildchar' or 'wildcharm' 1406// ^x accept ctrl key codes for 'wildchar' or 'wildcharm' 1407// c accept any non-digit for 'wildchar' or 'wildcharm' 1408// [-]0-9 set number 1409// other error 1410arg ++ ; 1411if (((OptInt * )varp == & p_wc || (OptInt * )varp == & p_wcm ) 1412&& (* arg == '<' || * arg == '^' 1413|| (* arg != NUL && (!arg [1 ]|| ascii_iswhite (arg [1 ]))&& !ascii_isdigit (* arg )))) { 1414newval_num = string_to_key (arg ); 1415if (newval_num == 0 ) { 1416* errmsg = e_invarg ; 1417return newval ; 1418 } 1419 }else if (* arg == '-' || ascii_isdigit (* arg )) { 1420int i ; 1421// Allow negative, octal and hex numbers. 1422vim_str2nr (arg ,NULL ,& i ,STR2NR_ALL ,& newval_num ,NULL ,0 , true,NULL ); 1423if (i == 0 || (arg [i ]!= NUL && !ascii_iswhite (arg [i ]))) { 1424* errmsg = e_number_required_after_equal ; 1425return newval ; 1426 } 1427 }else { 1428* errmsg = e_number_required_after_equal ; 1429return newval ; 1430 } 1431 1432if (op == OP_ADDING ) { 1433newval_num = oldval_num + newval_num ; 1434 } 1435if (op == OP_PREPENDING ) { 1436newval_num = oldval_num * newval_num ; 1437 } 1438if (op == OP_REMOVING ) { 1439newval_num = oldval_num - newval_num ; 1440 } 1441 1442newval = INTEGER_OBJ (newval_num ); 1443break ; 1444 } 1445case kObjectTypeString : { 1446// A dict option merges here too: its stored value is already a ":set" string, so =/+=/-= apply 1447// as for any string, and set_option() validates and canonicalizes the result. 1448const char * oldval_str = oldval .data .string .data ; 1449// Get the new value for the option 1450const char * newval_str = stropt_get_newval (opt_idx ,argp ,varp ,oldval_str ,& op ); 1451newval = CSTR_AS_OBJ (newval_str ); 1452break ; 1453 } 1454case kObjectTypeLuaRef : { 1455// "Callback" option (e.g. 'omnifunc') whose current value is a Lua function. The new value is 1456// a plain string (funcname/expr); ":set"-style +=/-= don't apply, so use an empty old value. 1457const char * newval_str = stropt_get_newval (opt_idx ,argp ,varp ,"" ,& op ); 1458newval = CSTR_AS_OBJ (newval_str ); 1459break ; 1460 } 1461default : 1462abort (); 1463 } 1464 1465// oldval (computed above, not overridden) is owned via optval_own(); an override is borrowed. 1466if (oldval_override == NULL ) { 1467optval_free (oldval ); 1468 } 1469return newval ; 1470} 1471 1472static const char * do_one_set_option (int opt_flags ,char ** argp ,bool * did_show , 1473const CharBuf * errbuf ) 1474{ 1475// 1: nothing, 0: "no", 2: "inv" in front of name 1476set_prefix_T prefix = get_option_prefix (argp ); 1477 1478char * arg = * argp ; 1479 1480// find end of name 1481OptIndex opt_idx ; 1482const char * const option_end = find_option_end (arg ,& opt_idx ); 1483 1484if (opt_idx != kOptInvalid ) { 1485assert (option_end >=arg ); 1486 }else if (is_tty_option (arg )) {// Silently ignore TTY options. 1487return NULL ; 1488 }else {// Invalid option name, skip. 1489return e_unknown_option ; 1490 } 1491 1492// Remember character after option name. 1493uint8_t afterchar = (uint8_t )(* option_end ); 1494char * p = (char * )option_end ; 1495 1496// Skip white space, allow ":set ai ?". 1497while (ascii_iswhite (* p )) { 1498p ++ ; 1499 } 1500 1501set_op_T op = get_op (p ); 1502if (op != OP_NONE ) { 1503p ++ ; 1504 } 1505 1506uint8_t nextchar = (uint8_t )(* p );// next non-white char after option name 1507// flags for current option 1508uint32_t flags = options [opt_idx ].flags ; 1509// pointer to variable for current option 1510void * varp = get_varp_scope (& (options [opt_idx ]),opt_flags ); 1511 1512const char * errmsg = NULL ; 1513if (validate_opt_idx (curwin ,opt_idx ,opt_flags ,flags ,prefix ,& errmsg )== FAIL ) { 1514return errmsg ; 1515 } 1516 1517if (vim_strchr ("?=:!&<" ,nextchar )!= NULL ) { 1518* argp = p ; 1519 1520if (nextchar == '&' && (* argp )[1 ]== 'v' && (* argp )[2 ]== 'i' ) { 1521if ((* argp )[3 ]== 'm' ) {// "opt&vim": set to Vim default 1522* argp += 3 ; 1523 }else {// "opt&vi": set to Vi default 1524* argp += 2 ; 1525 } 1526 } 1527if (vim_strchr ("?!&<" ,nextchar )!= NULL 1528&& (* argp )[1 ]!= NUL && !ascii_iswhite ((* argp )[1 ])) { 1529return e_trailing ; 1530 } 1531 } 1532 1533// Allow '=' and ':' as MS-DOS command.com allows only one '=' character per "set" command line. 1534if (nextchar == '?' 1535|| (prefix == PREFIX_NONE && vim_strchr ("=:&<" ,nextchar )== NULL 1536&& !option_has_type (opt_idx ,kObjectTypeBoolean ))) { 1537// print value 1538if (* did_show ) { 1539msg_putchar ('\n' );// cursor below last one 1540 }else { 1541msg_ext_set_kind ("list_cmd" ); 1542gotocmdline (true);// cursor at status line 1543* did_show = true;// remember that we did a line 1544 } 1545showoneopt (& options [opt_idx ],opt_flags ); 1546 1547if (p_verbose > 0 ) { 1548// Mention where the option was last set. 1549if (varp == options [opt_idx ].var ) { 1550last_set_msg (options [opt_idx ].script_ctx ); 1551 }else if (option_has_scope (opt_idx ,kOptScopeWin )) { 1552last_set_msg (curwin -> w_p_script_ctx [option_scope_idx (opt_idx ,kOptScopeWin )]); 1553 }else if (option_has_scope (opt_idx ,kOptScopeBuf )) { 1554last_set_msg (curbuf -> b_p_script_ctx [option_scope_idx (opt_idx ,kOptScopeBuf )]); 1555 } 1556 } 1557 1558if (nextchar != '?' && nextchar != NUL && !ascii_iswhite (afterchar )) { 1559return e_trailing ; 1560 } 1561return NULL ; 1562 } 1563 1564if (option_has_type (opt_idx ,kObjectTypeBoolean )) { 1565if (vim_strchr ("=:" ,nextchar )!= NULL ) { 1566return e_invarg ; 1567 } 1568 1569if (vim_strchr ("!&<" ,nextchar )== NULL && nextchar != NUL && !ascii_iswhite (afterchar )) { 1570return e_trailing ; 1571 } 1572 }else { 1573if (vim_strchr ("=:&<" ,nextchar )== NULL ) { 1574return e_invarg ; 1575 } 1576 } 1577 1578Object newval = get_option_newval (opt_idx ,opt_flags ,prefix ,argp ,nextchar ,op ,varp , 1579NULL ,& errmsg ); 1580 1581if (newval .type == kObjectTypeNil || errmsg != NULL ) { 1582return errmsg ; 1583 } 1584 1585return set_option (opt_idx ,newval ,opt_flags ,0 , false,op == OP_NONE ,errbuf ); 1586} 1587 1588/// Parse 'arg' for option settings. 1589/// 1590/// 'arg' may be IObuff, but only when no errors can be present and option 1591/// does not need to be expanded with option_expand(). 1592/// "opt_flags": 1593/// 0 for ":set" 1594/// OPT_GLOBAL for ":setglobal" 1595/// OPT_LOCAL for ":setlocal" and a modeline 1596/// OPT_MODELINE for a modeline 1597/// OPT_WINONLY to only set window-local options 1598/// OPT_NOWIN to skip setting window-local options 1599/// 1600/// @param arg option string (may be written to!) 1601/// 1602/// @return FAIL if an error is detected, OK otherwise 1603int do_set (char * arg ,int opt_flags ) 1604{ 1605bool did_show = false;// already showed one value 1606 1607if (* arg == NUL ) { 1608showoptions (false,opt_flags ); 1609did_show = true; 1610 }else { 1611while (* arg != NUL ) {// loop to process all options 1612if (strncmp (arg ,"all" ,3 )== 0 && !ASCII_ISALPHA (arg [3 ]) 1613&& !(opt_flags & OPT_MODELINE )) { 1614// ":set all" show all options. 1615// ":set all&" set all options to their default value. 1616arg += 3 ; 1617if (* arg == '&' ) { 1618arg ++ ; 1619// Only for :set command set global value of local options. 1620set_options_default (opt_flags ); 1621didset_options_all (); 1622didset_options (); 1623didset_options2 (); 1624ui_refresh_options (); 1625redraw_all_later (UPD_CLEAR ); 1626 }else { 1627showoptions (true,opt_flags ); 1628did_show = true; 1629 } 1630 }else { 1631char * startarg = arg ;// remember for error message 1632const CharBuf errbuf = { (char [ERR_BUFLEN ]){0 },ERR_BUFLEN }; 1633const char * errmsg = do_one_set_option (opt_flags ,& arg ,& did_show ,& errbuf ); 1634 1635// Advance to next argument. 1636// - skip until a blank found, taking care of backslashes 1637// - skip blanks 1638// - skip one "=val" argument (for hidden options ":set gfn =xx") 1639for (int i = 0 ;i < 2 ;i ++ ) { 1640arg = skiptowhite_esc (arg ); 1641arg = skipwhite (arg ); 1642if (* arg != '=' ) { 1643break ; 1644 } 1645 } 1646 1647if (errmsg != NULL ) { 1648int i = vim_snprintf ((char * )IObuff ,IOSIZE ,"%s" ,_ (errmsg ))+ 2 ; 1649if (i + (arg - startarg )< IOSIZE ) { 1650// append the argument with the error 1651xstrlcpy (IObuff + i - 2 ,": " , (size_t )(IOSIZE - i + 2 )); 1652assert (arg >=startarg ); 1653memmove (IObuff + i ,startarg , (size_t )(arg - startarg )); 1654IObuff [i + (arg - startarg )]= NUL ; 1655 } 1656// make sure all characters are printable 1657trans_characters (IObuff ,IOSIZE ); 1658 1659no_wait_return ++ ;// wait_return() done later 1660emsg (IObuff );// show error highlighted 1661no_wait_return -- ; 1662 1663return FAIL ; 1664 } 1665 } 1666 1667arg = skipwhite (arg ); 1668 } 1669 } 1670 1671if (silent_mode && did_show ) { 1672// After displaying option values in silent mode. 1673silent_mode = false; 1674info_message = true;// use stdout, not stderr 1675msg_putchar ('\n' ); 1676silent_mode = true; 1677info_message = false;// use stdout, not stderr 1678 } 1679 1680return OK ; 1681} 1682 1683// Translate a string like "t_xx", "<t_xx>" or "<S-Tab>" to a key number. 1684// When "has_lt" is true there is a '<' before "*arg_arg". 1685// Returns 0 when the key is not recognized. 1686static int find_key_len (const char * arg_arg ,size_t len ,bool has_lt ) 1687{ 1688int key = 0 ; 1689const char * arg = arg_arg ; 1690 1691// Don't use get_special_key_code() for t_xx, we don't want it to call 1692// add_termcap_entry(). 1693if (len >=4 && arg [0 ]== 't' && arg [1 ]== '_' ) { 1694if (!has_lt || arg [4 ]== '>' ) { 1695key = TERMCAP2KEY ((uint8_t )arg [2 ], (uint8_t )arg [3 ]); 1696 } 1697 }else if (has_lt ) { 1698arg -- ;// put arg at the '<' 1699int modifiers = 0 ; 1700key = find_special_key (& arg ,len + 1 ,& modifiers ,FSK_KEYCODE |FSK_KEEP_X_KEY |FSK_SIMPLIFY , 1701NULL ); 1702if (modifiers ) {// can't handle modifiers here 1703key = 0 ; 1704 } 1705 } 1706return key ; 1707} 1708 1709/// Convert a key name or string into a key value. 1710/// Used for 'cedit', 'wildchar' and 'wildcharm' options. 1711int string_to_key (char * arg ) 1712{ 1713if (* arg == '<' && arg [1 ]) { 1714return find_key_len (arg + 1 ,strlen (arg ), true); 1715 } 1716if (* arg == '^' && arg [1 ]) { 1717int key = CTRL_CHR ((uint8_t )arg [1 ]); 1718if (key == 0 ) {// ^@ is <Nul> 1719key = K_ZERO ; 1720 } 1721return key ; 1722 } 1723return (uint8_t )(* arg ); 1724} 1725 1726// When changing 'title', 'titlestring', 'icon' or 'iconstring', call 1727// maketitle() to create and display it. 1728// When switching the title or icon off, call ui_set_{icon,title}(NULL) to get 1729// the old value back. 1730void did_set_title (void ) 1731{ 1732if (starting != NO_SCREEN ) { 1733maketitle (); 1734 } 1735} 1736 1737/// set_options_bin - called when 'bin' changes value. 1738/// 1739/// @param opt_flags Option flags (can be OPT_LOCAL, OPT_GLOBAL or a combination). 1740void set_options_bin (int oldval ,int newval ,int opt_flags ) 1741{ 1742// The option values that are changed when 'bin' changes are 1743// copied when 'bin is set and restored when 'bin' is reset. 1744if (newval ) { 1745if (!oldval ) {// switched on 1746if (!(opt_flags & OPT_GLOBAL )) { 1747curbuf -> b_p_tw_nobin = curbuf -> b_p_tw ; 1748curbuf -> b_p_wm_nobin = curbuf -> b_p_wm ; 1749curbuf -> b_p_ml_nobin = curbuf -> b_p_ml ; 1750curbuf -> b_p_et_nobin = curbuf -> b_p_et ; 1751 } 1752if (!(opt_flags & OPT_LOCAL )) { 1753p_tw_nobin = p_tw ; 1754p_wm_nobin = p_wm ; 1755p_ml_nobin = p_ml ; 1756p_et_nobin = p_et ; 1757 } 1758 } 1759 1760if (!(opt_flags & OPT_GLOBAL )) { 1761curbuf -> b_p_tw = 0 ;// no automatic line wrap 1762curbuf -> b_p_wm = 0 ;// no automatic line wrap 1763curbuf -> b_p_ml = 0 ;// no modelines 1764curbuf -> b_p_et = 0 ;// no expandtab 1765 } 1766if (!(opt_flags & OPT_LOCAL )) { 1767p_tw = 0 ; 1768p_wm = 0 ; 1769p_ml = false; 1770p_et = false; 1771p_bin = true;// needed when called for the "-b" argument 1772 } 1773 }else if (oldval ) {// switched off 1774if (!(opt_flags & OPT_GLOBAL )) { 1775curbuf -> b_p_tw = curbuf -> b_p_tw_nobin ; 1776curbuf -> b_p_wm = curbuf -> b_p_wm_nobin ; 1777curbuf -> b_p_ml = curbuf -> b_p_ml_nobin ; 1778curbuf -> b_p_et = curbuf -> b_p_et_nobin ; 1779 } 1780if (!(opt_flags & OPT_LOCAL )) { 1781p_tw = p_tw_nobin ; 1782p_wm = p_wm_nobin ; 1783p_ml = p_ml_nobin ; 1784p_et = p_et_nobin ; 1785 } 1786 } 1787 1788// Remember where the dependent option were reset 1789didset_options_sctx (opt_flags ,p_bin_dep_opts ); 1790} 1791 1792/// Expand environment variables for some string options. 1793/// These string options cannot be indirect! 1794/// If "val" is NULL expand the current value of the option. 1795/// Return pointer to NameBuff, or NULL when not expanded. 1796static char * option_expand (OptIndex opt_idx ,const char * val ) 1797{ 1798// if option doesn't need expansion nothing to do 1799if (!(options [opt_idx ].flags & kOptFlagExpand )|| is_option_hidden (opt_idx )) { 1800return NULL ; 1801 } 1802 1803if (val == NULL ) { 1804val = * (char ** )options [opt_idx ].var ; 1805 } 1806 1807// If val is longer than MAXPATHL no meaningful expansion can be done, 1808// expand_env() would truncate the string. 1809if (val == NULL || strlen (val )> MAXPATHL ) { 1810return NULL ; 1811 } 1812 1813// Expanding this with NameBuff, expand_env() must not be passed IObuff. 1814// Escape spaces when expanding 'tags' or 'path', they are used to separate 1815// file names. 1816// For 'spellsuggest' expand after "file:". 1817char ** var = (char ** )options [opt_idx ].var ; 1818bool esc = var == & p_tags || var == & p_path ; 1819expand_env_esc (val ,NameBuff ,MAXPATHL ,esc ? (char * )" \t" :NULL , false, 1820 (char ** )options [opt_idx ].var == & p_sps ?"file:" :NULL ); 1821if (strcmp (NameBuff ,val )== 0 ) {// they are the same 1822return NULL ; 1823 } 1824 1825return NameBuff ; 1826} 1827 1828/// After setting various option values: recompute variables that depend on 1829/// option values. 1830static void didset_options (void ) 1831{ 1832// initialize the tables for 'iskeyword' et.al. 1833buf_init_isk_chartab (curbuf ); 1834init_isf_chartab (); 1835init_isi_chartab (); 1836 1837didset_string_options (); 1838 1839spell_check_sps (); 1840compile_cap_prog (curwin -> w_s ); 1841did_set_spell_option (); 1842// set cedit_key 1843did_set_cedit (NULL ); 1844// initialize the table for 'breakat'. 1845did_set_breakat (NULL ); 1846didset_window_options (curwin , true); 1847} 1848 1849// More side effects of setting options. 1850static void didset_options2 (void ) 1851{ 1852// Initialize the highlight_attr[] table. 1853highlight_changed (); 1854 1855// Parse default for 'fillchars'. 1856set_chars_option (curwin ,curwin -> w_p_fcs ,kFillchars , true,NULL ); 1857 1858// Parse default for 'listchars'. 1859set_chars_option (curwin ,curwin -> w_p_lcs ,kListchars , true,NULL ); 1860 1861// Parse default for 'wildmode'. 1862check_opt_wim (); 1863xfree (curbuf -> b_p_vsts_array ); 1864tabstop_set (curbuf -> b_p_vsts ,& curbuf -> b_p_vsts_array ); 1865xfree (curbuf -> b_p_vts_array ); 1866tabstop_set (curbuf -> b_p_vts ,& curbuf -> b_p_vts_array ); 1867} 1868 1869/// Repair UI state after `:set all&`. 1870/// 1871/// `set_options_default` resets option values via `set_option_default` and 1872/// `set_option_direct` without invoking per-option `did_set` callbacks, so 1873/// UI-derived state (cursor shape, statusline, tabline) can get out of sync. 1874/// This function patches the known cases. 1875/// 1876/// Note: We intentionally do not replay all `did_set` callbacks 1877/// (`opt_did_set_cb`) because they have order-dependent side effects and 1878/// old/new transition logic that does not hold when values are already reset. 1879static void didset_options_all (void ) 1880{ 1881const char * errmsg = parse_shape_opt (SHAPE_CURSOR ); 1882assert (errmsg == NULL ); 1883 (void )errmsg ; 1884last_status (false); 1885win_float_update_statusline (); 1886win_new_screen_rows (); 1887} 1888 1889/// Check for string options that are NULL (normally only termcap options). 1890void check_options (void ) 1891{ 1892for (OptIndex opt_idx = 0 ;opt_idx < kOptCount ;opt_idx ++ ) { 1893if ((option_has_type (opt_idx ,kObjectTypeString ))&& options [opt_idx ].var != NULL ) { 1894check_string_option ((char ** )get_varp (& (options [opt_idx ]))); 1895 } 1896 } 1897} 1898 1899/// Check if option was set insecurely. 1900/// 1901/// @param wp Window. 1902/// @param opt_idx Option index in options[] table. 1903/// @param opt_flags Option flags (can be OPT_LOCAL, OPT_GLOBAL or a combination). 1904/// 1905/// @return True if the option value came from a modeline, secure mode, or the sandbox. 1906int was_set_insecurely (win_T * const wp ,OptIndex opt_idx ,int opt_flags ) 1907{ 1908assert (opt_idx != kOptInvalid ); 1909 1910uint32_t * flagp = insecure_flag (wp ,opt_idx ,opt_flags ); 1911return (* flagp & kOptFlagInsecure )!= 0 ; 1912} 1913 1914/// Get a pointer to the flags used for the kOptFlagInsecure flag of option 1915/// "opt_idx". For some local options a local flags field is used. 1916/// NOTE: Caller must make sure that "wp" is set to the window from which 1917/// the option is used. 1918uint32_t * insecure_flag (win_T * const wp ,OptIndex opt_idx ,int opt_flags ) 1919{ 1920if (opt_flags & OPT_LOCAL ) { 1921assert (wp != NULL ); 1922switch (opt_idx ) { 1923case kOptWrap : 1924return & wp -> w_p_wrap_flags ; 1925case kOptStatusline : 1926return & wp -> w_p_stl_flags ; 1927case kOptWinbar : 1928return & wp -> w_p_wbr_flags ; 1929case kOptFoldexpr : 1930return & wp -> w_p_fde_flags ; 1931case kOptFoldtext : 1932return & wp -> w_p_fdt_flags ; 1933case kOptIndentexpr : 1934return & wp -> w_buffer -> b_p_inde_flags ; 1935case kOptFormatexpr : 1936return & wp -> w_buffer -> b_p_fex_flags ; 1937case kOptIncludeexpr : 1938return & wp -> w_buffer -> b_p_inex_flags ; 1939case kOptComplete : 1940return & wp -> w_buffer -> b_p_cpt_flags ; 1941default : 1942break ; 1943 } 1944 }else { 1945// For global value of window-local options, use flags in w_allbuf_opt. 1946switch (opt_idx ) { 1947case kOptWrap : 1948return & wp -> w_allbuf_opt .wo_wrap_flags ; 1949case kOptFoldexpr : 1950return & wp -> w_allbuf_opt .wo_fde_flags ; 1951case kOptFoldtext : 1952return & wp -> w_allbuf_opt .wo_fdt_flags ; 1953default : 1954break ; 1955 } 1956 } 1957// Nothing special, return global flags field. 1958return & options [opt_idx ].flags ; 1959} 1960 1961/// Redraw the window title and/or tab page text later. 1962void redraw_titles (void ) 1963{ 1964need_maketitle = true; 1965redraw_tabline = true; 1966} 1967 1968/// Return true if "val" is a valid name: only consists of alphanumeric ASCII 1969/// characters or characters in "allowed". 1970bool valid_name (const char * val ,const char * allowed ) 1971FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT 1972{ 1973for (const char * s = val ;* s != NUL ;s ++ ) { 1974if (!ASCII_ISALNUM (* s ) 1975&& vim_strchr (allowed , (uint8_t )(* s ))== NULL ) { 1976return false; 1977 } 1978 } 1979return true; 1980} 1981 1982void check_blending (win_T * wp ) 1983{ 1984wp -> w_grid_alloc .blending = 1985wp -> w_p_winbl > 0 || (wp -> w_floating && wp -> w_config .shadow ); 1986} 1987 1988/// Handle setting `winhighlight' in window "wp" 1989/// 1990/// @param winhl when NULL: use "wp->w_p_winhl" 1991/// @param wp when NULL: only parse "winhl" 1992/// 1993/// @return whether the option value is valid. 1994bool parse_winhl_opt (const char * winhl ,win_T * wp ) 1995{ 1996const char * p = empty_string_option ; 1997if (winhl != NULL ) { 1998p = winhl ; 1999 }else if (wp != NULL ) { 2000p = wp -> w_p_winhl ; 2001 } 2002 2003if (!* p ) { 2004if (wp != NULL && wp -> w_ns_hl_winhl > 0 && wp -> w_ns_hl == wp -> w_ns_hl_winhl ) { 2005wp -> w_ns_hl = 0 ; 2006wp -> w_hl_needs_update = true; 2007 } 2008 2009return true; 2010 } 2011 2012int ns_hl = 0 ; 2013if (wp != NULL ) { 2014if (wp -> w_ns_hl_winhl == 0 ) { 2015wp -> w_ns_hl_winhl = (int )nvim_create_namespace (NULL_STRING ); 2016 }else { 2017// Namespace already exists. Invalidate existing items. 2018DecorProvider * dp = get_decor_provider (wp -> w_ns_hl_winhl , true); 2019dp -> hl_valid ++ ; 2020 } 2021ns_hl = wp -> w_ns_hl_winhl ; 2022if (wp -> w_ns_hl <=0 ) { 2023wp -> w_ns_hl = wp -> w_ns_hl_winhl ; 2024 } 2025 } 2026 2027const char * key ,* val ; 2028size_t keylen ,vallen ; 2029while (option_next_keyval (& p ,& key ,& keylen ,& val ,& vallen )) { 2030if (val == NULL ) { 2031return false;// every part must be "group:hl" 2032 } 2033int hl_id = vallen ?syn_check_group (val ,vallen ) :-1 ; 2034if (hl_id == 0 ) { 2035return false; 2036 } 2037int hl_id_link = keylen ?syn_check_group (key ,keylen ) :0 ; 2038if (hl_id_link == 0 ) { 2039return false; 2040 } 2041 2042if (wp != NULL ) { 2043HlAttrs attrs = HLATTRS_INIT ; 2044attrs .rgb_ae_attr |=HL_GLOBAL ; 2045ns_hl_def (ns_hl ,hl_id_link ,attrs ,hl_id ,NULL ); 2046 } 2047 } 2048 2049if (wp != NULL ) { 2050wp -> w_hl_needs_update = true; 2051 } 2052return true; 2053} 2054 2055/// Get the script context of global option at index opt_idx. 2056sctx_T * get_option_sctx (OptIndex opt_idx ) 2057{ 2058assert (opt_idx != kOptInvalid ); 2059return & options [opt_idx ].script_ctx ; 2060} 2061 2062/// Set the script_ctx for an option, taking care of setting the buffer- or 2063/// window-local value. 2064void set_option_sctx (OptIndex opt_idx ,int opt_flags ,sctx_T script_ctx ) 2065{ 2066bool both = (opt_flags & (OPT_LOCAL |OPT_GLOBAL ))== 0 ; 2067 2068// Modeline already has the line number set. 2069if (!(opt_flags & OPT_MODELINE )) { 2070script_ctx .sc_lnum += SOURCING_LNUM ; 2071 } 2072nlua_set_sctx (& script_ctx ); 2073 2074// Remember where the option was set. For local options need to do that 2075// in the buffer or window structure. 2076if (both || (opt_flags & OPT_GLOBAL )|| option_is_global_only (opt_idx )) { 2077options [opt_idx ].script_ctx = script_ctx ; 2078 } 2079if (both || (opt_flags & OPT_LOCAL )) { 2080if (option_has_scope (opt_idx ,kOptScopeBuf )) { 2081curbuf -> b_p_script_ctx [option_scope_idx (opt_idx ,kOptScopeBuf )]= script_ctx ; 2082 }else if ((option_has_scope (opt_idx ,kOptScopeWin ))) { 2083curwin -> w_p_script_ctx [option_scope_idx (opt_idx ,kOptScopeWin )]= script_ctx ; 2084if (both ) { 2085// also setting the "all buffers" value 2086curwin -> w_allbuf_opt .wo_script_ctx [option_scope_idx (opt_idx ,kOptScopeWin )]= script_ctx ; 2087 } 2088 } 2089 } 2090} 2091 2092/// Execute OptionSet autocmd now (not deferred). 2093void apply_optionset_autocmd_now (OptIndex opt_idx ,int opt_flags ,Object oldval ,Object oldval_g , 2094Object oldval_l ,Object newval ) 2095{ 2096// Don't do this while starting up or recursively. 2097if (starting || * get_vim_var_str (VV_OPTION_TYPE )!= NUL ) { 2098return ; 2099 } 2100 2101char buf_type [7 ]; 2102typval_T oldval_tv = opt_to_tv (oldval , false); 2103typval_T oldval_g_tv = opt_to_tv (oldval_g , false); 2104typval_T oldval_l_tv = opt_to_tv (oldval_l , false); 2105typval_T newval_tv = opt_to_tv (newval , false); 2106 2107set_vim_var_tv (VV_OPTION_OLD ,& oldval_tv ); 2108set_vim_var_tv (VV_OPTION_NEW ,& newval_tv ); 2109size_t typelen = vim_snprintf_safelen (buf_type ,sizeof (buf_type ),"%s" , 2110 (opt_flags & OPT_LOCAL ) ?"local" :"global" ); 2111set_vim_var_string (VV_OPTION_TYPE ,buf_type , (ptrdiff_t )typelen ); 2112if (opt_flags & OPT_LOCAL ) { 2113set_vim_var_string (VV_OPTION_COMMAND ,S_LEN ("setlocal" )); 2114set_vim_var_tv (VV_OPTION_OLDLOCAL ,& oldval_tv ); 2115 } 2116if (opt_flags & OPT_GLOBAL ) { 2117set_vim_var_string (VV_OPTION_COMMAND ,S_LEN ("setglobal" )); 2118set_vim_var_tv (VV_OPTION_OLDGLOBAL ,& oldval_tv ); 2119 } 2120if ((opt_flags & (OPT_LOCAL |OPT_GLOBAL ))== 0 ) { 2121set_vim_var_string (VV_OPTION_COMMAND ,S_LEN ("set" )); 2122set_vim_var_tv (VV_OPTION_OLDLOCAL ,& oldval_l_tv ); 2123set_vim_var_tv (VV_OPTION_OLDGLOBAL ,& oldval_g_tv ); 2124 } 2125if (opt_flags & OPT_MODELINE ) { 2126set_vim_var_string (VV_OPTION_COMMAND ,S_LEN ("modeline" )); 2127set_vim_var_tv (VV_OPTION_OLDLOCAL ,& oldval_tv ); 2128 } 2129apply_autocmds (EVENT_OPTIONSET ,options [opt_idx ].fullname ,NULL , false,NULL ); 2130reset_v_option_vars (); 2131 2132tv_clear (& oldval_tv ); 2133tv_clear (& oldval_g_tv ); 2134tv_clear (& oldval_l_tv ); 2135tv_clear (& newval_tv ); 2136} 2137 2138/// For 'modified', the event is deferred. 2139static void apply_optionset_autocmd (OptIndex opt_idx ,int opt_flags ,Object oldval ,Object oldval_g , 2140Object oldval_l ,Object newval ) 2141{ 2142if (starting ) { 2143return ; 2144 } 2145if (opt_idx == kOptModified ) { 2146aucmd_defer_modified (curbuf ,newval .data .boolean ); 2147return ; 2148 } 2149apply_optionset_autocmd_now (opt_idx ,opt_flags ,oldval ,oldval_g ,oldval_l ,newval ); 2150} 2151 2152/// Process the updated 'arabic' option value. 2153static const char * did_set_arabic (optset_T * args ) 2154{ 2155win_T * win = args -> os_win ; 2156const char * errmsg = NULL ; 2157 2158if (win -> w_p_arab ) { 2159// 'arabic' is set, handle various sub-settings. 2160if (!p_tbidi ) { 2161// set rightleft mode 2162if (!win -> w_p_rl ) { 2163win -> w_p_rl = true; 2164changed_window_setting (win ); 2165 } 2166 2167// Enable Arabic shaping (major part of what Arabic requires) 2168if (!p_arshape ) { 2169p_arshape = true; 2170redraw_all_later (UPD_NOT_VALID ); 2171 } 2172 } 2173 2174// Arabic requires a utf-8 encoding, inform the user if it's not 2175// set. 2176if (strcmp (p_enc ,"utf-8" )!= 0 ) { 2177static char * w_arabic = N_ ("W17: Arabic requires UTF-8, do ':set encoding=utf-8'" ); 2178 2179msg_source (HLF_W ); 2180msg (_ (w_arabic ),HLF_W ); 2181set_vim_var_string (VV_WARNINGMSG ,_ (w_arabic ),-1 ); 2182 } 2183 2184// set 'delcombine' 2185p_deco = true; 2186 2187// Force-set the necessary keymap for arabic. 2188errmsg = set_option_value (kOptKeymap ,STATIC_CSTR_AS_OBJ ("arabic" ),OPT_LOCAL , true, 2189args -> os_errbuf ); 2190 }else { 2191// 'arabic' is reset, handle various sub-settings. 2192if (!p_tbidi ) { 2193// reset rightleft mode 2194if (win -> w_p_rl ) { 2195win -> w_p_rl = false; 2196changed_window_setting (win ); 2197 } 2198 2199// 'arabicshape' isn't reset, it is a global option and 2200// another window may still need it "on". 2201 } 2202 2203// 'delcombine' isn't reset, it is a global option and another 2204// window may still want it "on". 2205 2206// Revert to the default keymap 2207win -> w_buffer -> b_p_iminsert = B_IMODE_NONE ; 2208win -> w_buffer -> b_p_imsearch = B_IMODE_USE_INSERT ; 2209 } 2210 2211return errmsg ; 2212} 2213 2214/// Process the updated 'autochdir' option value. 2215static const char * did_set_autochdir (optset_T * args FUNC_ATTR_UNUSED ) 2216{ 2217// Change directories when the 'acd' option is set now. 2218do_autochdir (); 2219return NULL ; 2220} 2221 2222/// Process the updated 'binary' option value. 2223static const char * did_set_binary (optset_T * args ) 2224{ 2225// when 'bin' is set also set some other options 2226set_options_bin ((int )args -> os_oldval .data .boolean ,args -> os_buf -> b_p_bin ,args -> os_flags ); 2227redraw_titles (); 2228 2229return NULL ; 2230} 2231 2232/// Process the updated 'buflisted' option value. 2233static const char * did_set_buflisted (optset_T * args ) 2234{ 2235buf_T * buf = args -> os_buf ; 2236 2237// when 'buflisted' changes, trigger autocommands 2238if (args -> os_oldval .data .boolean != buf -> b_p_bl ) { 2239apply_autocmds (buf -> b_p_bl ?EVENT_BUFADD :EVENT_BUFDELETE , 2240NULL ,NULL , true,buf ); 2241 } 2242return NULL ; 2243} 2244 2245/// Process the new 'cmdheight' option value. 2246static const char * did_set_cmdheight (optset_T * args ) 2247{ 2248OptInt old_value = args -> os_oldval .data .integer ; 2249 2250if (p_ch > Rows - min_rows (curtab )+ 1 ) { 2251p_ch = Rows - min_rows (curtab )+ 1 ; 2252 } 2253 2254// if p_ch changed value, change the command line height 2255// Only compute the new window layout when startup has been 2256// completed. Otherwise the frame sizes may be wrong. 2257if ((p_ch != old_value 2258|| tabline_height ()+ global_stl_height ()+ topframe -> fr_height != Rows - p_ch ) 2259&& full_screen ) { 2260command_height (); 2261 } 2262 2263return NULL ; 2264} 2265 2266/// Process the updated 'diff' option value. 2267static const char * did_set_diff (optset_T * args ) 2268{ 2269win_T * win = args -> os_win ; 2270// May add or remove the buffer from the list of diff buffers. 2271diff_buf_adjust (win ); 2272if (foldmethodIsDiff (win )) { 2273foldUpdateAll (win ); 2274 } 2275return NULL ; 2276} 2277 2278/// Process the updated 'endoffile' or 'endofline' or 'fixendofline' or 'bomb' 2279/// option value. 2280static const char * did_set_eof_eol_fixeol_bomb (optset_T * args FUNC_ATTR_UNUSED ) 2281{ 2282// redraw the window title and tab page text 2283redraw_titles (); 2284return NULL ; 2285} 2286 2287/// Process the updated 'equalalways' option value. 2288static const char * did_set_equalalways (optset_T * args ) 2289{ 2290if (p_ea && !args -> os_oldval .data .boolean ) { 2291win_equal (args -> os_win , false,0 ); 2292 } 2293 2294return NULL ; 2295} 2296 2297/// Process the new 'foldenable' option value. 2298static const char * did_set_foldenable (optset_T * args ) 2299{ 2300win_T * win = args -> os_win ; 2301if (args -> os_varp == & win -> w_p_fen && args -> os_oldval .data .boolean != win -> w_p_fen 2302&& foldmethodIsDiff (win )&& win -> w_p_scb ) { 2303// Adjust 'foldenable' in diff-synced windows without recursive setters. 2304FOR_ALL_WINDOWS_IN_TAB (wp ,curtab ) { 2305if (wp != win && foldmethodIsDiff (wp )&& wp -> w_p_scb ) { 2306wp -> w_p_fen = win -> w_p_fen ; 2307changed_window_setting (wp ); 2308 } 2309 } 2310 } 2311return NULL ; 2312} 2313 2314/// Process the new 'foldlevel' option value. 2315static const char * did_set_foldlevel (optset_T * args FUNC_ATTR_UNUSED ) 2316{ 2317newFoldLevel (); 2318return NULL ; 2319} 2320 2321/// Process the new 'foldminlines' option value. 2322static const char * did_set_foldminlines (optset_T * args ) 2323{ 2324foldUpdateAll (args -> os_win ); 2325return NULL ; 2326} 2327 2328/// Process the new 'foldnestmax' option value. 2329static const char * did_set_foldnestmax (optset_T * args ) 2330{ 2331win_T * win = args -> os_win ; 2332if (foldmethodIsSyntax (win )|| foldmethodIsIndent (win )) { 2333foldUpdateAll (win ); 2334 } 2335return NULL ; 2336} 2337 2338/// Multicursor: handle updates to 'follow' option. 2339static const char * did_set_follow (optset_T * args ) 2340{ 2341if (args -> os_buf == curbuf ) { 2342atom_follow_changed (); 2343 } 2344return NULL ; 2345} 2346 2347/// Process the new 'helpheight' option value. 2348static const char * did_set_helpheight (optset_T * args ) 2349{ 2350// Change window height NOW 2351if (!ONE_WINDOW ) { 2352if (curbuf -> b_help && curwin -> w_height < p_hh ) { 2353win_setheight ((int )p_hh ); 2354 } 2355 } 2356 2357return NULL ; 2358} 2359 2360/// Process the updated 'hlsearch' option value. 2361static const char * did_set_hlsearch (optset_T * args FUNC_ATTR_UNUSED ) 2362{ 2363// when 'hlsearch' is set or reset: reset Search.no_hlsearch 2364set_no_hlsearch (false); 2365return NULL ; 2366} 2367 2368/// Process the updated 'ignorecase' option value. 2369static const char * did_set_ignorecase (optset_T * args FUNC_ATTR_UNUSED ) 2370{ 2371// when 'ignorecase' is set or reset and 'hlsearch' is set, redraw 2372if (p_hls ) { 2373redraw_all_later (UPD_SOME_VALID ); 2374 } 2375return NULL ; 2376} 2377 2378/// Process the new 'iminset' option value. 2379static const char * did_set_iminsert (optset_T * args FUNC_ATTR_UNUSED ) 2380{ 2381showmode (); 2382// Show/unshow value of 'keymap' in status lines. 2383status_redraw_curbuf (); 2384 2385return NULL ; 2386} 2387 2388/// Process the updated 'langnoremap' option value. 2389static const char * did_set_langnoremap (optset_T * args FUNC_ATTR_UNUSED ) 2390{ 2391// 'langnoremap' -> !'langremap' 2392p_lrm = !p_lnr ; 2393return NULL ; 2394} 2395 2396/// Process the updated 'langremap' option value. 2397static const char * did_set_langremap (optset_T * args FUNC_ATTR_UNUSED ) 2398{ 2399// 'langremap' -> !'langnoremap' 2400p_lnr = !p_lrm ; 2401return NULL ; 2402} 2403 2404/// Process the new 'laststatus' option value. 2405static const char * did_set_laststatus (optset_T * args ) 2406{ 2407OptInt old_value = args -> os_oldval .data .integer ; 2408OptInt value = args -> os_newval .data .integer ; 2409 2410// When switching to global statusline, decrease topframe height 2411// Also clear the cmdline to remove the ruler if there is one 2412if (value == 3 && old_value != 3 ) { 2413frame_new_height (topframe ,topframe -> fr_height - STATUS_HEIGHT , false, false, false); 2414win_comp_pos (); 2415clear_cmdline = true; 2416 } 2417// When switching from global statusline, increase height of topframe by STATUS_HEIGHT 2418// in order to re-add the space that was previously taken by the global statusline 2419if (old_value == 3 && value != 3 ) { 2420frame_new_height (topframe ,topframe -> fr_height + STATUS_HEIGHT , false, false, false); 2421win_comp_pos (); 2422 } 2423 2424status_redraw_curbuf (); 2425last_status (false);// (re)set last window status line. 2426win_float_update_statusline (); 2427return NULL ; 2428} 2429 2430/// Process the updated 'lines' or 'columns' option value. 2431static const char * did_set_lines_or_columns (optset_T * args ) 2432{ 2433// If the screen (shell) height has been changed, assume it is the 2434// physical screenheight. 2435if (p_lines != Rows || p_columns != Columns ) { 2436// Changing the screen size is not allowed while updating the screen. 2437if (updating_screen ) { 2438Object oldval = INTEGER_OBJ (args -> os_oldval .data .integer ); 2439set_option_varp (args -> os_idx ,args -> os_varp ,oldval ); 2440 }else if (full_screen ) { 2441screen_resize ((int )p_columns , (int )p_lines ); 2442 }else { 2443// TODO(bfredl): is this branch ever needed? 2444// Postpone the resizing; check the size and cmdline position for 2445// messages. 2446Rows = (int )p_lines ; 2447Columns = (int )p_columns ; 2448check_screensize (); 2449int new_row = (int )(Rows - MAX (p_ch ,1 )); 2450if (cmdline_row > new_row && Rows > p_ch ) { 2451assert (p_ch >=0 && new_row <=INT_MAX ); 2452cmdline_row = new_row ; 2453 } 2454 } 2455if (p_window >=Rows || !option_was_set (kOptWindow )) { 2456p_window = Rows - 1 ; 2457 } 2458 } 2459 2460// Adjust 'scrolljump' if needed. 2461if (p_sj >=Rows && full_screen ) { 2462p_sj = Rows /2 ; 2463 } 2464 2465return NULL ; 2466} 2467 2468/// Process the updated 'lisp' option value. 2469static const char * did_set_lisp (optset_T * args ) 2470{ 2471// When 'lisp' option changes include/exclude '-' in keyword characters. 2472buf_init_isk_chartab (args -> os_buf );// ignore errors 2473return NULL ; 2474} 2475 2476/// Process the updated 'modifiable' option value. 2477static const char * did_set_modifiable (optset_T * args FUNC_ATTR_UNUSED ) 2478{ 2479// when 'modifiable' is changed, redraw the window title 2480redraw_titles (); 2481 2482return NULL ; 2483} 2484 2485/// Process the updated 'modified' option value. 2486static const char * did_set_modified (optset_T * args ) 2487{ 2488buf_T * buf = args -> os_buf ; 2489if (!args -> os_newval .data .boolean ) { 2490save_file_ff (buf );// Buffer is unchanged 2491 } 2492redraw_titles (); 2493buf -> b_modified_was_set = !!(int )args -> os_newval .data .boolean ; 2494return NULL ; 2495} 2496 2497/// Process the updated 'number' or 'relativenumber' option value. 2498static const char * did_set_number_relativenumber (optset_T * args ) 2499{ 2500win_T * win = args -> os_win ; 2501if (* win -> w_p_stc != NUL ) { 2502// When 'relativenumber'/'number' is changed and 'statuscolumn' is set, reset width. 2503win -> w_nrwidth_line_count = 0 ; 2504 } 2505check_signcolumn (NULL ,win ); 2506return NULL ; 2507} 2508 2509/// Process the new 'numberwidth' option value. 2510static const char * did_set_numberwidth (optset_T * args ) 2511{ 2512args -> os_win -> w_nrwidth_line_count = 0 ;// trigger a redraw 2513 2514return NULL ; 2515} 2516 2517/// Process the updated 'paste' option value. 2518static const char * did_set_paste (optset_T * args FUNC_ATTR_UNUSED ) 2519{ 2520static int old_p_paste = false; 2521static int save_sm = 0 ; 2522static int save_sta = 0 ; 2523static int save_ru = 0 ; 2524static int save_ri = 0 ; 2525 2526if (p_paste ) { 2527// Paste switched from off to on. 2528// Save the current values, so they can be restored later. 2529if (!old_p_paste ) { 2530// save options for each buffer 2531FOR_ALL_BUFFERS (buf ) { 2532buf -> b_p_tw_nopaste = buf -> b_p_tw ; 2533buf -> b_p_wm_nopaste = buf -> b_p_wm ; 2534buf -> b_p_sts_nopaste = buf -> b_p_sts ; 2535buf -> b_p_ai_nopaste = buf -> b_p_ai ; 2536buf -> b_p_et_nopaste = buf -> b_p_et ; 2537if (buf -> b_p_vsts_nopaste ) { 2538xfree (buf -> b_p_vsts_nopaste ); 2539 } 2540buf -> b_p_vsts_nopaste = buf -> b_p_vsts && buf -> b_p_vsts != empty_string_option 2541 ?xstrdup (buf -> b_p_vsts ) 2542 :NULL ; 2543 } 2544 2545// save global options 2546save_sm = p_sm ; 2547save_sta = p_sta ; 2548save_ru = p_ru ; 2549save_ri = p_ri ; 2550// save global values for local buffer options 2551p_ai_nopaste = p_ai ; 2552p_et_nopaste = p_et ; 2553p_sts_nopaste = p_sts ; 2554p_tw_nopaste = p_tw ; 2555p_wm_nopaste = p_wm ; 2556if (p_vsts_nopaste ) { 2557xfree (p_vsts_nopaste ); 2558 } 2559p_vsts_nopaste = p_vsts && p_vsts != empty_string_option ?xstrdup (p_vsts ) :NULL ; 2560 } 2561 2562// Always set the option values, also when 'paste' is set when it is 2563// already on. 2564// set options for each buffer 2565FOR_ALL_BUFFERS (buf ) { 2566buf -> b_p_tw = 0 ;// textwidth is 0 2567buf -> b_p_wm = 0 ;// wrapmargin is 0 2568buf -> b_p_sts = 0 ;// softtabstop is 0 2569buf -> b_p_ai = 0 ;// no auto-indent 2570buf -> b_p_et = 0 ;// no expandtab 2571if (buf -> b_p_vsts ) { 2572free_string_option (buf -> b_p_vsts ); 2573 } 2574buf -> b_p_vsts = empty_string_option ; 2575XFREE_CLEAR (buf -> b_p_vsts_array ); 2576 } 2577 2578// set global options 2579p_sm = 0 ;// no showmatch 2580p_sta = 0 ;// no smarttab 2581if (p_ru ) { 2582status_redraw_all ();// redraw to remove the ruler 2583 } 2584p_ru = 0 ;// no ruler 2585p_ri = 0 ;// no reverse insert 2586// set global values for local buffer options 2587p_tw = 0 ; 2588p_wm = 0 ; 2589p_sts = 0 ; 2590p_ai = 0 ; 2591p_et = 0 ; 2592if (p_vsts ) { 2593free_string_option (p_vsts ); 2594 } 2595p_vsts = empty_string_option ; 2596 }else if (old_p_paste ) { 2597// Paste switched from on to off: Restore saved values. 2598 2599// restore options for each buffer 2600FOR_ALL_BUFFERS (buf ) { 2601buf -> b_p_tw = buf -> b_p_tw_nopaste ; 2602buf -> b_p_wm = buf -> b_p_wm_nopaste ; 2603buf -> b_p_sts = buf -> b_p_sts_nopaste ; 2604buf -> b_p_ai = buf -> b_p_ai_nopaste ; 2605buf -> b_p_et = buf -> b_p_et_nopaste ; 2606if (buf -> b_p_vsts ) { 2607free_string_option (buf -> b_p_vsts ); 2608 } 2609buf -> b_p_vsts = buf -> b_p_vsts_nopaste ?xstrdup (buf -> b_p_vsts_nopaste ) :empty_string_option ; 2610xfree (buf -> b_p_vsts_array ); 2611if (buf -> b_p_vsts && buf -> b_p_vsts != empty_string_option ) { 2612tabstop_set (buf -> b_p_vsts ,& buf -> b_p_vsts_array ); 2613 }else { 2614buf -> b_p_vsts_array = NULL ; 2615 } 2616 } 2617 2618// restore global options 2619p_sm = save_sm ; 2620p_sta = save_sta ; 2621if (p_ru != save_ru ) { 2622status_redraw_all ();// redraw to draw the ruler 2623 } 2624p_ru = save_ru ; 2625p_ri = save_ri ; 2626// set global values for local buffer options 2627p_ai = p_ai_nopaste ; 2628p_et = p_et_nopaste ; 2629p_sts = p_sts_nopaste ; 2630p_tw = p_tw_nopaste ; 2631p_wm = p_wm_nopaste ; 2632if (p_vsts ) { 2633free_string_option (p_vsts ); 2634 } 2635p_vsts = p_vsts_nopaste ?xstrdup (p_vsts_nopaste ) :empty_string_option ; 2636 } 2637 2638old_p_paste = p_paste ; 2639 2640// Remember where the dependent options were reset 2641didset_options_sctx ((OPT_LOCAL |OPT_GLOBAL ),p_paste_dep_opts ); 2642 2643return NULL ; 2644} 2645 2646/// Validate the 'previewwindow' option. 2647static const char * validate_previewwindow (const optset_T * args ) 2648{ 2649if ((args -> os_flags & OPT_GLOBAL )|| !args -> os_newval .data .boolean ) { 2650return NULL ; 2651 } 2652win_T * win = args -> os_win ; 2653tabpage_T * tab = win == curwin ?curtab :win_find_tabpage (win ); 2654// There can be only one preview window in a tab. 2655FOR_ALL_WINDOWS_IN_TAB (wp ,tab ) { 2656if (wp != win && wp -> w_p_pvw ) { 2657return e_preview_window_already_exists ; 2658 } 2659 } 2660return NULL ; 2661} 2662 2663/// Process the new 'pumblend' option value. 2664static const char * did_set_pumblend (optset_T * args FUNC_ATTR_UNUSED ) 2665{ 2666hl_invalidate_blends (); 2667if (pum_drawn ()) { 2668pum_redraw (); 2669 } 2670 2671return NULL ; 2672} 2673 2674/// Process the updated 'readonly' option value. 2675static const char * did_set_readonly (optset_T * args ) 2676{ 2677buf_T * buf = args -> os_buf ; 2678 2679// when 'readonly' is reset globally, also reset readonlymode 2680if (!buf -> b_p_ro && (args -> os_flags & OPT_LOCAL )== 0 ) { 2681readonlymode = false; 2682 } 2683 2684// when 'readonly' is set may give W10 again 2685if (buf -> b_p_ro ) { 2686buf -> b_did_warn = false; 2687 } 2688 2689redraw_titles (); 2690 2691return NULL ; 2692} 2693 2694/// Process the new 'scrollback' option value. 2695static const char * did_set_scrollback (optset_T * args ) 2696{ 2697buf_T * buf = args -> os_buf ; 2698OptInt old_value = args -> os_oldval .data .integer ; 2699OptInt value = args -> os_newval .data .integer ; 2700 2701if (buf -> terminal && value < old_value ) { 2702// Force the scrollback to take immediate effect only when decreasing it. 2703on_scrollback_option_changed (buf -> terminal ); 2704 } 2705return NULL ; 2706} 2707 2708/// Process the updated 'scrollbind' option value. 2709static const char * did_set_scrollbind (optset_T * args ) 2710{ 2711win_T * win = args -> os_win ; 2712 2713// when 'scrollbind' is set: snapshot the current position to avoid a jump 2714// at the end of normal_cmd() 2715if (!win -> w_p_scb ) { 2716return NULL ; 2717 } 2718do_check_scrollbind (false); 2719win -> w_scbind_pos = get_vtopline (win ); 2720return NULL ; 2721} 2722 2723/// Process the new 'shiftwidth' or the 'tabstop' option value. 2724static const char * did_set_shiftwidth_tabstop (optset_T * args ) 2725{ 2726buf_T * buf = args -> os_buf ; 2727win_T * win = args -> os_win ; 2728OptInt * pp = (OptInt * )args -> os_varp ; 2729 2730if (foldmethodIsIndent (win )) { 2731foldUpdateAll (win ); 2732 } 2733// When 'shiftwidth' changes, or it's zero and 'tabstop' changes: 2734// parse 'cinoptions'. 2735if (pp == & buf -> b_p_sw || buf -> b_p_sw == 0 ) { 2736parse_cino (buf ); 2737 } 2738 2739return NULL ; 2740} 2741 2742/// Process the new 'showtabline' option value. 2743static const char * did_set_showtabline (optset_T * args FUNC_ATTR_UNUSED ) 2744{ 2745// (re)set tab page line 2746win_new_screen_rows ();// recompute window positions and heights 2747return NULL ; 2748} 2749 2750/// Process the updated 'smoothscroll' option value. 2751static const char * did_set_smoothscroll (optset_T * args FUNC_ATTR_UNUSED ) 2752{ 2753win_T * win = args -> os_win ; 2754if (!win -> w_p_sms ) { 2755win -> w_skipcol = 0 ; 2756 } 2757 2758return NULL ; 2759} 2760 2761/// Process the updated 'spell' option value. 2762static const char * did_set_spell (optset_T * args ) 2763{ 2764win_T * win = args -> os_win ; 2765if (win -> w_p_spell ) { 2766return parse_spelllang (win ); 2767 } 2768 2769return NULL ; 2770} 2771 2772/// Process the updated 'swapfile' option value. 2773static const char * did_set_swapfile (optset_T * args ) 2774{ 2775buf_T * buf = args -> os_buf ; 2776// when 'swf' is set, create swapfile, when reset remove swapfile 2777if (buf -> b_p_swf && p_uc ) { 2778ml_open_file (buf );// create the swap file 2779 }else { 2780// no need to reset buf->b_may_swap, ml_open_file() will check buf->b_p_swf 2781mf_close_file (buf , true);// remove the swap file 2782 } 2783return NULL ; 2784} 2785 2786/// Process the new 'textwidth' option value. 2787static const char * did_set_textwidth (optset_T * args FUNC_ATTR_UNUSED ) 2788{ 2789FOR_ALL_TAB_WINDOWS (tp ,wp ) { 2790check_colorcolumn (NULL ,wp ); 2791 } 2792 2793return NULL ; 2794} 2795 2796/// Process the updated 'title' or the 'icon' option value. 2797static const char * did_set_title_icon (optset_T * args FUNC_ATTR_UNUSED ) 2798{ 2799// when 'title' changed, may need to change the title; same for 'icon' 2800did_set_title (); 2801return NULL ; 2802} 2803 2804/// Process the new 'titlelen' option value. 2805static const char * did_set_titlelen (optset_T * args ) 2806{ 2807OptInt old_value = args -> os_oldval .data .integer ; 2808 2809// if 'titlelen' has changed, redraw the title 2810if (starting != NO_SCREEN && old_value != p_titlelen ) { 2811need_maketitle = true; 2812 } 2813 2814return NULL ; 2815} 2816 2817/// Process the updated 'undofile' option value. 2818static const char * did_set_undofile (optset_T * args ) 2819{ 2820buf_T * buf = args -> os_buf ; 2821 2822// Only take action when the option was set. 2823if (!buf -> b_p_udf && !p_udf ) { 2824return NULL ; 2825 } 2826 2827// When reset we do not delete the undo file, the option may be set again 2828// without making any changes in between. 2829uint8_t hash [UNDO_HASH_SIZE ]; 2830 2831FOR_ALL_BUFFERS (bp ) { 2832// When 'undofile' is set globally: for every buffer, otherwise 2833// only for the current buffer: Try to read in the undofile, 2834// if one exists, the buffer wasn't changed and the buffer was 2835// loaded 2836if ((buf == bp 2837|| (args -> os_flags & OPT_GLOBAL )|| args -> os_flags == 0 ) 2838&& !bufIsChanged (bp )&& bp -> b_ml .ml_mfp != NULL ) { 2839u_compute_hash (bp ,hash ); 2840u_read_undo (NULL ,hash ,bp -> b_fname ); 2841 } 2842 } 2843 2844return NULL ; 2845} 2846 2847/// Process the new global 'undolevels' option value. 2848const char * did_set_global_undolevels (OptInt value ,OptInt old_value ) 2849{ 2850// sync undo before 'undolevels' changes 2851// use the old value, otherwise u_sync() may not work properly 2852p_ul = old_value ; 2853u_sync (true); 2854p_ul = value ; 2855return NULL ; 2856} 2857 2858/// Process the new buffer local 'undolevels' option value. 2859const char * did_set_buflocal_undolevels (buf_T * buf ,OptInt value ,OptInt old_value ) 2860{ 2861// use the old value, otherwise u_sync() may not work properly 2862buf -> b_p_ul = old_value ; 2863u_sync (true); 2864buf -> b_p_ul = value ; 2865return NULL ; 2866} 2867 2868/// Process the new 'undolevels' option value. 2869static const char * did_set_undolevels (optset_T * args ) 2870{ 2871buf_T * buf = args -> os_buf ; 2872OptInt * pp = (OptInt * )args -> os_varp ; 2873 2874if (pp == & p_ul ) {// global 'undolevels' 2875did_set_global_undolevels (args -> os_newval .data .integer ,args -> os_oldval .data .integer ); 2876 }else if (pp == & buf -> b_p_ul ) {// buffer local 'undolevels' 2877did_set_buflocal_undolevels (buf ,args -> os_newval .data .integer ,args -> os_oldval .data .integer ); 2878 } 2879 2880return NULL ; 2881} 2882 2883/// Process the new 'updatecount' option value. 2884static const char * did_set_updatecount (optset_T * args ) 2885{ 2886OptInt old_value = args -> os_oldval .data .integer ; 2887 2888// when 'updatecount' changes from zero to non-zero, open swap files 2889if (p_uc && !old_value ) { 2890ml_open_files (); 2891 } 2892 2893return NULL ; 2894} 2895 2896/// Validate the 'wildchar' or 'wildcharm' option. 2897static const char * validate_wildchar (const optset_T * args ) 2898{ 2899OptInt c = args -> os_newval .data .integer ; 2900 2901// Don't allow key values that wouldn't work as wildchar. 2902if (c == Ctrl_C || c == '\n' || c == '\r' || c == K_KENTER ) { 2903return e_invarg ; 2904 } 2905 2906return NULL ; 2907} 2908 2909/// Process the new 'winblend' option value. 2910static const char * did_set_winblend (optset_T * args ) 2911{ 2912win_T * win = args -> os_win ; 2913OptInt old_value = args -> os_oldval .data .integer ; 2914OptInt value = args -> os_newval .data .integer ; 2915 2916if (value != old_value ) { 2917win -> w_p_winbl = MAX (MIN (win -> w_p_winbl ,100 ),0 ); 2918win -> w_hl_needs_update = true; 2919check_blending (win ); 2920 } 2921 2922return NULL ; 2923} 2924 2925/// Process the new 'window' option value. 2926static const char * did_set_window (optset_T * args FUNC_ATTR_UNUSED ) 2927{ 2928if (p_window < 1 ) { 2929p_window = Rows - 1 ; 2930 }else if (p_window >=Rows ) { 2931p_window = Rows - 1 ; 2932 } 2933return NULL ; 2934} 2935 2936/// Process the new 'winheight' value. 2937static const char * did_set_winheight (optset_T * args ) 2938{ 2939// Change window height NOW 2940if (!ONE_WINDOW ) { 2941if (curwin -> w_height < p_wh ) { 2942win_setheight ((int )p_wh ); 2943 } 2944 } 2945 2946return NULL ; 2947} 2948 2949/// Process the new 'winwidth' option value. 2950static const char * did_set_winwidth (optset_T * args ) 2951{ 2952if (!ONE_WINDOW && curwin -> w_width < p_wiw ) { 2953win_setwidth ((int )p_wiw ); 2954 } 2955return NULL ; 2956} 2957 2958/// Process the updated 'wrap' option value. 2959static const char * did_set_wrap (optset_T * args ) 2960{ 2961win_T * win = args -> os_win ; 2962// Set w_leftcol or w_skipcol to zero. 2963if (win -> w_p_wrap ) { 2964win -> w_leftcol = 0 ; 2965 }else { 2966win -> w_skipcol = 0 ; 2967 } 2968 2969return NULL ; 2970} 2971 2972/// Process the new 'chistory' or 'lhistory' option value. 'chistory' will 2973/// be used if args->os_varp is the same as p_chi, else 'lhistory'. 2974static const char * did_set_xhistory (optset_T * args ) 2975{ 2976bool is_p_chi = (OptInt * )args -> os_varp == & p_chi ; 2977OptInt * arg = is_p_chi ?& p_chi : (OptInt * )args -> os_varp ; 2978 2979if (is_p_chi ) { 2980qf_resize_stack ((int )(* arg )); 2981 }else { 2982ll_resize_stack (args -> os_win , (int )(* arg )); 2983 } 2984 2985return NULL ; 2986} 2987 2988// When 'syntax' is set, load the syntax of that name 2989static void do_syntax_autocmd (buf_T * buf ,bool value_changed ) 2990{ 2991static int syn_recursive = 0 ; 2992 2993syn_recursive ++ ; 2994buf -> b_flags |=BF_SYN_SET ; 2995// Only pass true for "force" when the value changed or not used 2996// recursively, to avoid endless recurrence. 2997apply_autocmds (EVENT_SYNTAX ,buf -> b_p_syn ,buf -> b_fname , 2998value_changed || syn_recursive == 1 ,buf ); 2999syn_recursive -- ; 3000} 3001 3002static void do_spelllang_source (win_T * win ) 3003{ 3004char fname [200 ]; 3005char * q = win -> w_s -> b_p_spl ; 3006 3007// Skip the first name if it is "cjk". 3008if (strncmp (q ,"cjk," ,4 )== 0 ) { 3009q += 4 ; 3010 } 3011 3012// Source the spell/LANG.{vim,lua} in 'runtimepath'. 3013// They could set 'spellcapcheck' depending on the language. 3014// Use the first name in 'spelllang' up to '_region' or 3015// '.encoding'. 3016char * p ; 3017for (p = q ;* p != NUL ;p ++ ) { 3018if (!ASCII_ISALNUM (* p )&& * p != '-' ) { 3019break ; 3020 } 3021 } 3022if (p > q ) { 3023vim_snprintf (fname ,sizeof (fname ),"spell/%.*s.*" , (int )(p - q ),q ); 3024source_runtime_vim_lua (fname ,DIP_ALL ); 3025 } 3026} 3027 3028/// Format an option error. Without a buffer, return a non-NULL empty message. 3029const char * opt_error (const CharBuf * errbuf ,const char * fmt , ...) 3030FUNC_ATTR_PRINTF (2 ,3 ) 3031{ 3032if (errbuf == NULL ) { 3033return "" ; 3034 } 3035va_list arglist ; 3036va_start (arglist ,fmt ); 3037vim_vsnprintf (errbuf -> data ,errbuf -> size ,_ (fmt ),arglist ); 3038va_end (arglist ); 3039return errbuf -> data ; 3040} 3041 3042/// Check the bounds of numeric options. 3043/// 3044/// @param opt_idx Index in options[] table. Must not be kOptInvalid. 3045/// @param[in,out] newval Pointer to new option value. Will be set to bound checked value. 3046/// @param win Target window. 3047/// @param[out] errbuf Buffer for error message, or NULL if not needed. 3048/// 3049/// @return Error message, if any. 3050static const char * check_num_option_bounds (OptIndex opt_idx ,OptInt * newval ,win_T * win , 3051const CharBuf * errbuf ) 3052FUNC_ATTR_NONNULL_ARG (3 ) 3053{ 3054const char * errmsg = NULL ; 3055 3056switch (opt_idx ) { 3057case kOptLines : 3058if (* newval < min_rows_for_all_tabpages ()&& full_screen ) { 3059errmsg = opt_error (errbuf ,N_ ("E593: Need at least %d lines" ),min_rows_for_all_tabpages ()); 3060* newval = min_rows_for_all_tabpages (); 3061 } 3062// True max size is defined by check_screensize(). 3063* newval = MIN (* newval ,INT_MAX ); 3064break ; 3065case kOptColumns : 3066if (* newval < MIN_COLUMNS && full_screen ) { 3067errmsg = opt_error (errbuf ,N_ ("E594: Need at least %d columns" ),MIN_COLUMNS ); 3068* newval = MIN_COLUMNS ; 3069 } 3070// True max size is defined by check_screensize(). 3071* newval = MIN (* newval ,INT_MAX ); 3072break ; 3073case kOptPumblend : 3074* newval = MAX (MIN (* newval ,100 ),0 ); 3075break ; 3076case kOptScrolljump : 3077if ((* newval < -100 || * newval >=Rows )&& full_screen ) { 3078errmsg = e_scroll ; 3079* newval = 1 ; 3080 } 3081break ; 3082case kOptScroll : 3083if ((* newval <=0 || (* newval > win -> w_view_height && win -> w_view_height > 0 )) 3084&& full_screen ) { 3085if (* newval != 0 ) { 3086errmsg = e_scroll ; 3087 } 3088* newval = win_default_scroll (win ); 3089 } 3090break ; 3091default : 3092break ; 3093 } 3094 3095return errmsg ; 3096} 3097 3098/// Validate and bound check option value. 3099/// 3100/// @param opt_idx Index in options[] table. Must not be kOptInvalid. 3101/// @param[in,out] newval Pointer to new option value. Will be set to bound checked value. 3102/// @param[out] errbuf Buffer for error message, or NULL if not needed. 3103/// 3104/// @return Error message, if any. 3105static const char * validate_num_option (OptIndex opt_idx ,OptInt * newval ,win_T * win , 3106const CharBuf * errbuf ) 3107{ 3108OptInt value = * newval ; 3109 3110// Many number options assume their value is in the signed int range. 3111if (value < INT_MIN || value > INT_MAX ) { 3112return e_invarg ; 3113 } 3114 3115// if you increase this, also increase SEARCH_STAT_BUF_LEN in search.c 3116enum {MAX_SEARCH_COUNT = 9999 , }; 3117 3118switch (opt_idx ) { 3119case kOptHelpheight : 3120case kOptTitlelen : 3121case kOptUpdatecount : 3122case kOptReport : 3123case kOptUpdatetime : 3124case kOptSidescroll : 3125case kOptFoldlevel : 3126case kOptShiftwidth : 3127case kOptTextwidth : 3128case kOptWritedelay : 3129case kOptTimeoutlen : 3130if (value < 0 ) { 3131return e_positive ; 3132 } 3133break ; 3134case kOptWinheight : 3135if (value < 1 ) { 3136return e_positive ; 3137 }else if (p_wmh > value ) { 3138return e_winheight ; 3139 } 3140break ; 3141case kOptWinminheight : 3142if (value < 0 ) { 3143return e_positive ; 3144 }else if (value > p_wh ) { 3145return e_winheight ; 3146 } 3147break ; 3148case kOptWinwidth : 3149if (value < 1 ) { 3150return e_positive ; 3151 }else if (p_wmw > value ) { 3152return e_winwidth ; 3153 } 3154break ; 3155case kOptWinminwidth : 3156if (value < 0 ) { 3157return e_positive ; 3158 }else if (value > p_wiw ) { 3159return e_winwidth ; 3160 } 3161break ; 3162case kOptMaxcombine : 3163* newval = MAX_MCO ; 3164break ; 3165case kOptCmdheight : 3166if (value < 0 ) { 3167return e_positive ; 3168 } 3169break ; 3170case kOptHistory : 3171if (value < 0 ) { 3172return e_positive ; 3173 }else if (value > 10000 ) { 3174return e_invarg ; 3175 } 3176break ; 3177case kOptPyxversion : 3178if (value == 0 ) { 3179* newval = 3 ; 3180 }else if (value != 3 ) { 3181return e_invarg ; 3182 } 3183break ; 3184case kOptRegexpengine : 3185if (value < 0 || value > 2 ) { 3186return e_invarg ; 3187 } 3188break ; 3189case kOptScrolloff : 3190if (value < 0 && full_screen ) { 3191return e_positive ; 3192 } 3193break ; 3194case kOptScrolloffpad : 3195// if (value < 0 && full_screen) { 3196if (value < 0 ) { 3197return e_invarg ; 3198 } 3199break ; 3200case kOptSidescrolloff : 3201if (value < 0 && full_screen ) { 3202return e_positive ; 3203 } 3204break ; 3205case kOptCmdwinheight : 3206if (value < 1 ) { 3207return e_positive ; 3208 } 3209break ; 3210case kOptConceallevel : 3211if (value < 0 ) { 3212return e_positive ; 3213 }else if (value > 3 ) { 3214return e_invarg ; 3215 } 3216break ; 3217case kOptNumberwidth : 3218if (value < 1 ) { 3219return e_positive ; 3220 }else if (value > MAX_NUMBERWIDTH ) { 3221return e_invarg ; 3222 } 3223break ; 3224case kOptIminsert : 3225if (value < 0 || value > B_IMODE_LAST ) { 3226return e_invarg ; 3227 } 3228break ; 3229case kOptImsearch : 3230if (value < -1 || value > B_IMODE_LAST ) { 3231return e_invarg ; 3232 } 3233break ; 3234case kOptChannel : 3235return e_invarg ; 3236case kOptScrollback : 3237if (value < -1 || value > SB_MAX ) { 3238return e_invarg ; 3239 } 3240break ; 3241case kOptTabstop : 3242if (value < 1 ) { 3243return e_positive ; 3244 }else if (value > TABSTOP_MAX ) { 3245return e_invarg ; 3246 } 3247break ; 3248case kOptChistory : 3249case kOptLhistory : 3250if (value < 1 ) { 3251return e_cannot_have_negative_or_zero_number_of_quickfix ; 3252 }else if (value > 100 ) { 3253return e_cannot_have_more_than_hundred_quickfix ; 3254 } 3255break ; 3256case kOptMaxsearchcount : 3257if (value <=0 ) { 3258return e_positive ; 3259 }else if (value > MAX_SEARCH_COUNT ) { 3260return e_invarg ; 3261 } 3262break ; 3263default : 3264break ; 3265 } 3266 3267return check_num_option_bounds (opt_idx ,newval ,win ,errbuf ); 3268} 3269 3270/// Called after an option changed: check if something needs to be redrawn. 3271void check_redraw_for (buf_T * buf ,win_T * win ,uint32_t flags ) 3272{ 3273// Careful: kOptFlagRedrAll is a combination of other redraw flags 3274bool all = (flags & kOptFlagRedrAll )== kOptFlagRedrAll ; 3275 3276if ((flags & kOptFlagRedrStat )|| all ) {// mark all status lines and window bars dirty 3277status_redraw_all (); 3278 } 3279 3280if ((flags & kOptFlagRedrTabl )|| all ) {// mark tablines dirty 3281redraw_tabline = true; 3282 } 3283 3284if ((flags & kOptFlagRedrBuf )|| (flags & kOptFlagRedrWin )|| all ) { 3285if (flags & kOptFlagHLOnly ) { 3286redraw_later (win ,UPD_NOT_VALID ); 3287 }else { 3288changed_window_setting (win ); 3289 } 3290 } 3291if (flags & kOptFlagRedrBuf ) { 3292redraw_buf_later (buf ,UPD_NOT_VALID ); 3293 } 3294if (all ) { 3295redraw_all_later (UPD_NOT_VALID ); 3296 } 3297} 3298 3299void check_redraw (uint32_t flags ) 3300{ 3301check_redraw_for (curbuf ,curwin ,flags ); 3302} 3303 3304bool is_tty_option (const char * name ) 3305FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT 3306{ 3307return find_tty_option_end (name )!= NULL ; 3308} 3309 3310/// Get value of TTY option. 3311/// 3312/// @param name Name of TTY option. 3313/// 3314/// @return [allocated] TTY option value. Returns NIL if option isn't a TTY option. 3315Object get_tty_option (const char * name ) 3316{ 3317char * value = NULL ; 3318 3319if (strequal (name ,"t_Co" )) { 3320if (t_colors <=1 ) { 3321value = xstrdup ("" ); 3322 }else { 3323value = xmalloc (NUMBUFLEN ); 3324snprintf (value ,NUMBUFLEN ,"%d" ,t_colors ); 3325 } 3326 }else if (strequal (name ,"term" )) { 3327value = p_term ?xstrdup (p_term ) :xstrdup ("nvim" ); 3328 }else if (strequal (name ,"ttytype" )) { 3329value = p_ttytype ?xstrdup (p_ttytype ) :xstrdup ("nvim" ); 3330 }else if (is_tty_option (name )) { 3331// XXX: All other t_* options were removed in 3baba1e7. 3332value = xstrdup ("" ); 3333 } 3334 3335return value == NULL ?NIL :CSTR_AS_OBJ (value ); 3336} 3337 3338bool set_tty_option (const char * name ,char * value ) 3339{ 3340if (strequal (name ,"term" )) { 3341if (p_term ) { 3342xfree (p_term ); 3343 } 3344p_term = value ; 3345return true; 3346 } 3347 3348if (strequal (name ,"ttytype" )) { 3349if (p_ttytype ) { 3350xfree (p_ttytype ); 3351 } 3352p_ttytype = value ; 3353return true; 3354 } 3355 3356return false; 3357} 3358 3359/// Find index for an option. Don't go beyond `len` length. 3360/// 3361/// @param[in] name Option name. 3362/// @param len Option name length. 3363/// 3364/// @return Option index or kOptInvalid if option was not found. 3365OptIndex find_option_len (const char * const name ,size_t len ) 3366FUNC_ATTR_NONNULL_ALL 3367{ 3368int index = find_option_hash (name ,len ); 3369return index >=0 ?option_hash_elems [index ].opt_idx :kOptInvalid ; 3370} 3371 3372/// Find index for an option. 3373/// 3374/// @param[in] name Option name. 3375/// 3376/// @return Option index or kOptInvalid if option was not found. 3377OptIndex find_option (const char * const name ) 3378FUNC_ATTR_NONNULL_ALL 3379{ 3380return find_option_len (name ,strlen (name )); 3381} 3382 3383/// True if `opt_idx` is a dict option (`schema.dict` in options.lua, e.g. 'diffopt'). Stored as its 3384/// canonical ":set" string; reified on-demand (`opt_keyset()`) for validation and applying. 3385bool is_dict_option (OptIndex opt_idx ) 3386{ 3387return opt_dict_schema (opt_idx )!= NULL ; 3388} 3389 3390/// Release an option value read from opt_from_varp() (and similar). 3391void optval_free_read (OptIndex opt_idx ,Object value ) 3392{ 3393if (optval_is_owned (opt_idx )) { 3394optval_free (value ); 3395 } 3396} 3397 3398/// Free an allocated option value. 3399void optval_free (Object o ) 3400{ 3401// Only strings and Lua callbacks own memory. 3402switch (o .type ) { 3403case kObjectTypeString : 3404if (o .data .string .data != empty_string_option ) { 3405api_free_string (o .data .string );// Don't free the shared empty-string-option sentinel 3406 } 3407return ; 3408case kObjectTypeLuaRef : 3409api_free_luaref (o .data .luaref ); 3410return ; 3411case kObjectTypeUnset : 3412case kObjectTypeNil : 3413case kObjectTypeBoolean : 3414case kObjectTypeInteger : 3415return ; 3416default : 3417abort ();// Should not happen. 3418 } 3419} 3420 3421/// Check if two option values are equal. 3422bool option_equal (Object o1 ,Object o2 ) 3423{ 3424if (o1 .type != o2 .type ) { 3425return false; 3426 } 3427 3428switch (o1 .type ) { 3429case kObjectTypeUnset : 3430case kObjectTypeNil : 3431return true; 3432case kObjectTypeBoolean : 3433return o1 .data .boolean == o2 .data .boolean ; 3434case kObjectTypeInteger : 3435return o1 .data .integer == o2 .data .integer ; 3436case kObjectTypeString : 3437return o1 .data .string .size == o2 .data .string .size 3438&& (o1 .data .string .data == o2 .data .string .data 3439|| strnequal (o1 .data .string .data ,o2 .data .string .data ,o1 .data .string .size )); 3440case kObjectTypeLuaRef : 3441return false;// Callbacks compare unequal: setting one always counts as a change. 3442default : 3443abort ();// Should not happen. 3444 } 3445} 3446 3447/// Convert a tri-state boolean option to Object. `kNone` (unset local value) maps to Unset. 3448Object opt_from_tristate (TriState t ) 3449{ 3450return t == kNone ?UNSET :BOOLEAN_OBJ (t == kTrue ); 3451} 3452 3453/// Map an option value Object to its declared option type. Unset maps to boolean, since only 3454/// global-local booleans have an unset value representation. 3455static ObjectType optval_type (Object o ) 3456{ 3457switch (o .type ) { 3458case kObjectTypeNil : 3459return kObjectTypeNil ; 3460case kObjectTypeUnset : 3461case kObjectTypeBoolean : 3462return kObjectTypeBoolean ; 3463case kObjectTypeInteger : 3464return kObjectTypeInteger ; 3465case kObjectTypeString : 3466return kObjectTypeString ; 3467case kObjectTypeLuaRef : 3468return kObjectTypeLuaRef ; 3469default : 3470abort ();// Should not happen. 3471 } 3472} 3473 3474/// True for a "callback option" (varp stores `Callback`): func option (e.g. 'operatorfunc') or expr 3475/// option (e.g. 'foldexpr'). 3476static bool is_callback_option (OptIndex opt_idx ) 3477{ 3478return (options [opt_idx ].flags & (kOptFlagFunc |kOptFlagExpr ))!= 0 ; 3479} 3480 3481/// Returns true if _reading_ the option value (opt_from_varp(), etc.) returns an owned Object 3482/// (release with optval_free_read()), or false if it borrows the stored value. 3483static bool optval_is_owned (OptIndex opt_idx ) 3484{ 3485return is_callback_option (opt_idx ); 3486} 3487 3488/// Ensures an option value read is "owned", i.e. the caller decides when to free it. 3489Object optval_own (OptIndex opt_idx ,Object value ) 3490{ 3491return optval_is_owned (opt_idx ) ?value :copy_object (value ,NULL ); 3492} 3493 3494/// Copies an option value for OptionSet/UI reporting. Lua function is reported as "<Lua N>". 3495static Object optval_snapshot (Object value ) 3496{ 3497if (value .type == kObjectTypeLuaRef ) { 3498return CSTR_AS_OBJ (nlua_funcref_str (value .data .luaref ,NULL , true)); 3499 } 3500return copy_object (value ,NULL ); 3501} 3502 3503/// Reads the option value at `varp` and returns a snapshot (see optval_snapshot()). 3504static Object optval_snapshot_varp (OptIndex opt_idx ,void * varp ) 3505{ 3506Object value = opt_from_varp (opt_idx ,varp ); 3507Object snapshot = optval_snapshot (value ); 3508optval_free_read (opt_idx ,value ); 3509return snapshot ; 3510} 3511 3512/// Converts a callback option's stored Callback to an optval Object. 3513/// Always OWNED (a copied name/expr string, or a new LuaRef): free with optval_free(). 3514/// 3515/// - Lua callback => `LuaRef` 3516/// - named funcref => name 3517/// - partial => name 3518/// - expr option => expression string 3519/// - unset callback => empty string 3520static Object opt_from_callback (Callback * cb ) 3521{ 3522switch (cb -> type ) { 3523case kCallbackLua : 3524return LUAREF_OBJ (api_new_luaref (cb -> data .luaref )); 3525case kCallbackExpr : 3526return CSTR_TO_OBJ (cb -> data .expr ); 3527case kCallbackFuncref : 3528return CSTR_TO_OBJ (cb -> data .funcref ); 3529case kCallbackPartial : { 3530// Serialize with bound args so the value round-trips losslessly, e.g. `function('F', [10])`. 3531typval_T tv ; 3532callback_put (cb ,& tv ); 3533char * str = encode_tv2string (& tv ,NULL ); 3534tv_clear (& tv ); 3535return CSTR_AS_OBJ (str ); 3536 } 3537case kCallbackNone : 3538break ; 3539 } 3540return STATIC_CSTR_TO_OBJ ("" ); 3541} 3542 3543/// Builds a callback option's Callback from an option value Object. Borrows `value` (copies its 3544/// string/ref; the caller retains ownership). 3545/// 3546/// - `LuaRef` ("func"/"expr" options) => Lua callback 3547/// - func option with `is_expr=false` => string parsed as a function name or lambda 3548/// - expr option with non-empty string => expression string (`<SID>`/`s:` resolves to `<SNR>`) 3549/// - other (empty string, `Unset`) => `CALLBACK_NONE` 3550static Callback opt_to_callback (Object value ,bool is_expr ) 3551{ 3552Callback cb = CALLBACK_NONE ; 3553switch (value .type ) { 3554case kObjectTypeLuaRef : 3555cb .type = kCallbackLua ; 3556cb .data .luaref = api_new_luaref (value .data .luaref ); 3557break ; 3558case kObjectTypeString : 3559if (!is_expr ) { 3560option_set_callback_func (value .data .string .data ,& cb ); 3561 }else if (value .data .string .size > 0 ) { 3562cb .type = kCallbackExpr ; 3563char * name = get_scriptlocal_funcname (value .data .string .data ); 3564cb .data .expr = name != NULL ?name :xstrdup (value .data .string .data ); 3565 } 3566break ; 3567default : 3568break ; 3569 } 3570return cb ; 3571} 3572 3573/// Creates Object from var pointer. Release with optval_free_read(), or promote with optval_own(). 3574/// 3575/// @param opt_idx Option index in options[] table. 3576/// @param[out] varp Pointer to option variable. 3577/// 3578/// @return Option value stored in varp. 3579Object opt_from_varp (OptIndex opt_idx ,void * varp ) 3580FUNC_ATTR_NONNULL_ARG (2 ) 3581{ 3582// Special case: 'modified' is b_changed, but we also want to consider it set when 'ff' or 'fenc' 3583// changed. 3584if ((int * )varp == & curbuf -> b_changed ) { 3585return BOOLEAN_OBJ (curbufIsChanged ()); 3586 } 3587 3588// Callback options (e.g. 'operatorfunc', 'foldexpr') store a Callback, not a scalar. 3589if (is_callback_option (opt_idx )) { 3590return opt_from_callback ((Callback * )varp ); 3591 } 3592 3593switch (options [opt_idx ].type ) { 3594case kObjectTypeBoolean : 3595// Boolean options are tri-states; kNone (an unset local value) maps to Unset. 3596return opt_from_tristate (TRISTATE_FROM_INT (* (int * )varp )); 3597case kObjectTypeInteger : 3598return INTEGER_OBJ (* (OptInt * )varp ); 3599case kObjectTypeString : 3600return STRING_OBJ (cstr_as_string (* (char ** )varp )); 3601default : 3602abort ();// Should not happen. 3603 } 3604} 3605 3606/// Stores an option value at its "varp", freeing the previously-stored value. `value` is copied 3607/// in (caller retains ownership). 3608static void set_option_varp (OptIndex opt_idx ,void * varp ,Object value ) 3609FUNC_ATTR_NONNULL_ARG (2 ) 3610{ 3611// Callback options (e.g. 'operatorfunc', 'foldexpr') store a Callback, not a scalar. 3612if (is_callback_option (opt_idx )) { 3613Callback * cb = (Callback * )varp ; 3614callback_free (cb ); 3615* cb = opt_to_callback (value ,options [opt_idx ].flags & kOptFlagExpr ); 3616return ; 3617 } 3618 3619switch (value .type ) { 3620case kObjectTypeUnset : 3621// Unset the local value of a global-local option: store its unset sentinel. 3622assert (option_is_global_local (opt_idx )); 3623if (option_has_type (opt_idx ,kObjectTypeBoolean )) { 3624* (int * )varp = kNone ; 3625 }else if (option_has_type (opt_idx ,kObjectTypeString )) { 3626free_string_option (* (char ** )varp ); 3627* (char ** )varp = empty_string_option ; 3628 }else if (opt_idx == kOptUndolevels ) { 3629* (OptInt * )varp = NO_LOCAL_UNDOLEVEL ; 3630 }else { 3631assert (opt_idx == kOptScrolloff || opt_idx == kOptScrolloffpad 3632|| opt_idx == kOptSidescrolloff ); 3633* (OptInt * )varp = -1 ; 3634 } 3635return ; 3636case kObjectTypeBoolean : 3637assert (option_has_type (opt_idx ,kObjectTypeBoolean )); 3638* (int * )varp = value .data .boolean ; 3639return ; 3640case kObjectTypeInteger : 3641assert (option_has_type (opt_idx ,kObjectTypeInteger )); 3642* (OptInt * )varp = value .data .integer ; 3643return ; 3644case kObjectTypeString : 3645assert (option_has_type (opt_idx ,kObjectTypeString )); 3646free_string_option (* (char ** )varp ); 3647* (char ** )varp = copy_option_val (value .data .string .data ); 3648return ; 3649default : 3650abort (); 3651 } 3652} 3653 3654/// Gets the string form of an option value. Caller must free the result. 3655/// 3656/// @param quote Wrap a String value in double-quotes (error-message style). 3657static char * optval_to_cstr (Object o ,bool quote ) 3658{ 3659switch (o .type ) { 3660case kObjectTypeUnset : 3661case kObjectTypeNil : 3662return xstrdup ("" ); 3663case kObjectTypeBoolean : 3664return xstrdup (o .data .boolean ?"true" :"false" ); 3665case kObjectTypeInteger : { 3666char * buf = xmalloc (NUMBUFLEN ); 3667snprintf (buf ,NUMBUFLEN ,"%" PRId64 ,o .data .integer ); 3668return buf ; 3669 } 3670case kObjectTypeString : { 3671if (!quote ) { 3672return xmemdupz (o .data .string .data ,o .data .string .size ); 3673 } 3674char * buf = xmalloc (o .data .string .size + 3 ); 3675snprintf (buf ,o .data .string .size + 3 ,"\"%s\"" ,o .data .string .data ); 3676return buf ; 3677 } 3678case kObjectTypeLuaRef : 3679return nlua_funcref_str (o .data .luaref ,NULL , false);// show_ref=false: ref changes every time. 3680default : 3681abort ();// Should not happen. 3682 } 3683} 3684 3685/// Converts an option value to its structured form. 3686/// 3687/// @return Object allocated in `arena` (scalar values are returned unchanged). 3688Object optval_to_obj (OptIndex opt_idx ,Object value ,Arena * arena ) 3689{ 3690if (value .type == kObjectTypeLuaRef ) { 3691// Callback option: return an independent ref so it outlives the source value. 3692return LUAREF_OBJ (api_new_luaref (value .data .luaref )); 3693 } 3694if (value .type != kObjectTypeString ) { 3695return value ;// boolean/number/nil/unset scalar; already an Object. 3696 } 3697 3698const uint32_t flags = options [opt_idx ].flags ; 3699const OptSchemaItem * schema = options [opt_idx ].schema ; 3700 3701// A dict option (`schema != NULL`) parses here like any comma "key:value" map: its stored value 3702// is already the canonical ":set" string. 3703char * str = value .data .string .data != NULL ?value .data .string .data :"" ; 3704 3705Object rv ; 3706// Plain string option: no list/map structure. 3707if (!(flags & (kOptFlagComma |kOptFlagFlagList ))) { 3708rv = STRING_OBJ (CSTR_TO_ARENA_STR (arena ,str )); 3709 }else if ((flags & kOptFlagFlagList )&& !(flags & kOptFlagComma )) { 3710// Single-char flag list, e.g. 'shortmess': each character is a flag. 3711size_t n = strlen (str ); 3712Dict d = arena_dict (arena ,n ); 3713for (size_t i = 0 ;i < n ;i ++ ) { 3714PUT_C (d ,arena_memdupz (arena ,& str [i ],1 ),BOOLEAN_OBJ (true)); 3715 } 3716rv = DICT_OBJ (d ); 3717 }else { 3718// Comma-separated list/map/set. Upper-bound the item count for arena sizing. 3719size_t nparts = 1 ; 3720for (char * p = str ;* p != NUL ;p ++ ) { 3721nparts += (* p == ',' ); 3722 } 3723const bool as_map = (flags & kOptFlagColon )|| (flags & kOptFlagFlagList )|| schema != NULL ; 3724Dict d = as_map ?arena_dict (arena ,nparts ) : (Dict )ARRAY_DICT_INIT ; 3725Array a = as_map ? (Array )ARRAY_DICT_INIT :arena_array (arena ,nparts ); 3726char * item = xmalloc (strlen (str )+ 1 ); 3727for (char * p = str ;* p != NUL ;) { 3728copy_option_part (& p ,item ,strlen (str )+ 1 ,"," ); 3729if (* item == NUL ) { 3730continue ;// skip empty parts, e.g. "a,,b" 3731 } 3732if (!as_map ) { 3733// Note: the raw string preserves the ",," literal-comma convention (e.g. 'isfname'); the 3734// structured view splits on every comma and does not reconstruct literal commas. 3735ADD_C (a ,STRING_OBJ (CSTR_TO_ARENA_STR (arena ,item ))); 3736continue ; 3737 } 3738char * colon = strchr (item ,':' ); 3739char * val = NULL ; 3740if (colon != NULL ) { 3741* colon = NUL ; 3742val = colon + 1 ; 3743 } 3744String key = CSTR_TO_ARENA_STR (arena ,item ); 3745Object v ; 3746if (flags & kOptFlagFlagList ) { 3747v = BOOLEAN_OBJ (true);// comma flag list ('whichwrap'): each item is a flag 3748 }else if (val == NULL ) { 3749v = BOOLEAN_OBJ (true);// bare flag in a typed/colon map 3750 }else { 3751// A key's value stays a string, even for a num/enum key: option sub-value types are not a 3752// stable contract (Vim options are "stringly typed"), so we expose structure, not types. 3753v = STRING_OBJ (CSTR_TO_ARENA_STR (arena ,val )); 3754 } 3755PUT_C (d ,key .data ,v ); 3756 } 3757xfree (item ); 3758rv = as_map ?DICT_OBJ (d ) :ARRAY_OBJ (a ); 3759 } 3760 3761return rv ; 3762} 3763 3764/// Converts a structured option (non-scalar Object) to the internal scalar (:set-style) form. 3765/// 3766/// Example: 'listchars' `{ eol = "~" }` => "eol:~". 3767/// 3768/// @param op The :set operation; "key:value" removals are normalized to match by key. 3769/// @return Object (owned; free with optval_free). 3770Object optval_from_obj (OptIndex opt_idx ,Object o ,set_op_T op ,bool * error ) 3771{ 3772if (o .type == kObjectTypeNil ) { 3773return NIL ; 3774 } 3775 3776const uint32_t flags = options [opt_idx ].flags ; 3777const bool is_list = flags & (kOptFlagComma |kOptFlagFlagList ); 3778// "key:value" list, e.g. 'listchars', or a dict option, e.g. 'breakindentopt' (which accepts 3779// a Dict even without kOptFlagColon, mirroring `as_map` in optval_to_obj()). 3780const bool is_map = (flags & kOptFlagColon )|| is_dict_option (opt_idx ); 3781const bool is_flaglist = flags & kOptFlagFlagList ;// single-char flag list, e.g. 'shortmess'. 3782const bool is_comma = flags & kOptFlagComma ; 3783const bool allow_dup = !(flags & kOptFlagNoDup ); 3784 3785// Validate the value type. Special cases: 'wildchar'/'wildcharm'. 3786bool type_ok ; 3787switch (o .type ) { 3788case kObjectTypeBoolean : 3789type_ok = option_has_type (opt_idx ,kObjectTypeBoolean ); 3790break ; 3791case kObjectTypeInteger : 3792type_ok = option_has_type (opt_idx ,kObjectTypeInteger ); 3793break ; 3794case kObjectTypeString : 3795type_ok = option_has_type (opt_idx ,kObjectTypeString ) 3796|| opt_idx == kOptWildchar || opt_idx == kOptWildcharm ; 3797break ; 3798case kObjectTypeArray : 3799type_ok = is_list ; 3800break ; 3801case kObjectTypeDict : 3802type_ok = is_map || is_flaglist ; 3803break ; 3804case kObjectTypeLuaRef : 3805type_ok = is_callback_option (opt_idx );// A callback option accepts a funcref. 3806break ; 3807default : 3808type_ok = false; 3809 } 3810if (!type_ok ) { 3811* error = true; 3812return NIL ; 3813 } 3814 3815switch (o .type ) { 3816case kObjectTypeBoolean : 3817case kObjectTypeInteger : 3818return o ;// Scalar; already type-checked above. 3819case kObjectTypeLuaRef : 3820return LUAREF_OBJ (api_new_luaref (o .data .luaref ));// Funcref; stored as a Callback. 3821default : 3822break ;// String/Array/Dict are serialized below. 3823 } 3824 3825char * str = NULL ; 3826if (o .type == kObjectTypeString ) { 3827str = xstrdup (o .data .string .data ); 3828 }else if (o .type == kObjectTypeArray ) { 3829// List style: join items with comma, dropping duplicates unless the option allows them. 3830garray_T ga ; 3831ga_init (& ga ,sizeof (char * ),4 ); 3832for (size_t ai = 0 ;ai < o .data .array .size ;ai ++ ) { 3833Object item = o .data .array .items [ai ]; 3834if (item .type != kObjectTypeString ) { 3835* error = true; 3836GA_DEEP_CLEAR_PTR (& ga ); 3837return NIL ; 3838 } 3839bool dup = false; 3840for (int j = 0 ; !allow_dup && j < ga .ga_len ;j ++ ) { 3841if (strequal (((char ** )ga .ga_data )[j ],item .data .string .data )) { 3842dup = true; 3843break ; 3844 } 3845 } 3846if (!dup ) { 3847GA_APPEND (char * ,& ga ,xstrdup (item .data .string .data )); 3848 } 3849 } 3850// A bare flag list is concatenated with no separator, as in the Dict branch below. 3851str = ga_concat_strings (& ga , (is_flaglist && !is_comma ) ?"" :"," ); 3852GA_DEEP_CLEAR_PTR (& ga ); 3853 }else {// kObjectTypeDict 3854garray_T ga ; 3855Dict dict = o .data .dict ; 3856ga_init (& ga ,sizeof (char * ),4 ); 3857for (size_t di = 0 ;di < dict .size ;di ++ ) { 3858String k = dict .items [di ].key ; 3859Object v = dict .items [di ].value ; 3860if (is_flaglist ) { 3861// Flag set: include the key when its value is truthy; the value itself is dropped. 3862if (!(v .type == kObjectTypeNil || (v .type == kObjectTypeBoolean && !v .data .boolean ))) { 3863GA_APPEND (char * ,& ga ,xstrdup (k .data )); 3864 } 3865 }else if (v .type == kObjectTypeString ) { 3866char * kv = concat_str (k .data ,":" ); 3867GA_APPEND (char * ,& ga ,concat_str (kv ,v .data .string .data )); 3868xfree (kv ); 3869 }else if (v .type == kObjectTypeInteger ) { 3870// Typed map value, e.g. 'diffopt' `{ context = 4 }` -> "context:4". 3871char buf [NUMBUFLEN ]; 3872snprintf (buf ,sizeof (buf ),":%" PRId64 , (int64_t )v .data .integer ); 3873char * kv = concat_str (k .data ,buf ); 3874GA_APPEND (char * ,& ga ,kv ); 3875 }else if (v .type == kObjectTypeBoolean || v .type == kObjectTypeNil ) { 3876// Bare flag in a typed map, e.g. 'diffopt' `{ internal = true }` -> "internal". 3877if (v .type == kObjectTypeBoolean && v .data .boolean ) { 3878GA_APPEND (char * ,& ga ,xstrdup (k .data )); 3879 } 3880 }else { 3881* error = true; 3882GA_DEEP_CLEAR_PTR (& ga ); 3883return NIL ; 3884 } 3885 } 3886// Sort maps and comma-flag lists for a deterministic result (Dict order is unstable); a bare 3887// flag list is concatenated in-order with no separator. 3888if (ga .ga_len > 0 && (is_map || is_comma )) { 3889sort_strings (ga .ga_data ,ga .ga_len ); 3890 } 3891str = ga_concat_strings (& ga , (is_flaglist && !is_comma ) ?"" :"," ); 3892GA_DEEP_CLEAR_PTR (& ga ); 3893 } 3894 3895// `:set-=` on a "key:value" list matches by "key:"; a bare key needs the trailing colon appended. 3896// See stropt_handle_keymatch. (Lua: `vim.opt.listchars = vim.opt.listchars - 'space'`.) 3897if (op == OP_REMOVING && is_map && strchr (str ,':' )== NULL ) { 3898char * with_colon = concat_str (str ,":" ); 3899xfree (str ); 3900str = with_colon ; 3901 } 3902 3903return CSTR_AS_OBJ (str ); 3904} 3905 3906/// Check if option is hidden. 3907/// 3908/// @param opt_idx Option index in options[] table. 3909/// 3910/// @return True if option is hidden, false otherwise. Returns false if option name is invalid. 3911bool is_option_hidden (OptIndex opt_idx ) 3912{ 3913// Hidden options are always immutable and point to their default value 3914return opt_idx != kOptInvalid && options [opt_idx ].immutable 3915&& options [opt_idx ].var == & options [opt_idx ].def_val .data ; 3916} 3917 3918/// Check if option supports a specific type. 3919bool option_has_type (OptIndex opt_idx ,ObjectType type ) 3920{ 3921return opt_idx != kOptInvalid && options [opt_idx ].type == type ; 3922} 3923 3924/// Check if option supports a specific scope. 3925bool option_has_scope (OptIndex opt_idx ,OptScope scope ) 3926{ 3927// Ensure that scope flags variable can hold all scopes. 3928STATIC_ASSERT (kOptScopeSize <=sizeof (OptScopeFlags )* 8 , 3929"Option scope_flags cannot fit all option scopes" ); 3930// Ensure that the scope is valid before accessing scope_flags. 3931assert (scope >=kOptScopeGlobal && scope < kOptScopeSize ); 3932// Bitshift 1 by the value of scope to get the scope's corresponding flag, and check if it's set 3933// in the scope_flags bit field. 3934return get_option (opt_idx )-> scope_flags & (1 <<scope ); 3935} 3936 3937/// Check if option is global-local (has global AND buffer/window scope). 3938/// Tab scope is independent and does not make an option "global-local". 3939static inline bool option_is_global_local (OptIndex opt_idx ) 3940{ 3941if (opt_idx == kOptInvalid ) { 3942return false; 3943 } 3944const OptScopeFlags bw = (1 <<kOptScopeBuf ) | (1 <<kOptScopeWin ); 3945return (options [opt_idx ].scope_flags & bw )!= 0 3946&& option_has_scope (opt_idx ,kOptScopeGlobal ); 3947} 3948 3949/// Check if option only supports global scope (ignoring tab scope, which is independent). 3950static inline bool option_is_global_only (OptIndex opt_idx ) 3951{ 3952if (opt_idx == kOptInvalid ) { 3953return false; 3954 } 3955const OptScopeFlags bw = (1 <<kOptScopeBuf ) | (1 <<kOptScopeWin ); 3956return (options [opt_idx ].scope_flags & bw )== 0 3957&& option_has_scope (opt_idx ,kOptScopeGlobal ); 3958} 3959 3960/// Check if option only supports window scope (ignoring tab scope, which is independent). 3961static inline bool option_is_window_local (OptIndex opt_idx ) 3962{ 3963if (opt_idx == kOptInvalid ) { 3964return false; 3965 } 3966const OptScopeFlags exclude = (1 <<kOptScopeGlobal ) | (1 <<kOptScopeBuf ); 3967return (options [opt_idx ].scope_flags & exclude )== 0 3968&& option_has_scope (opt_idx ,kOptScopeWin ); 3969} 3970 3971/// Get option index for scope. 3972ssize_t option_scope_idx (OptIndex opt_idx ,OptScope scope ) 3973{ 3974return options [opt_idx ].scope_idx [scope ]; 3975} 3976 3977/// Get option flags. 3978/// 3979/// @param opt_idx Option index in options[] table. 3980/// 3981/// @return Option flags. Returns 0 for invalid option name. 3982uint32_t get_option_flags (OptIndex opt_idx ) 3983{ 3984return opt_idx == kOptInvalid ?0 :options [opt_idx ].flags ; 3985} 3986 3987/// Gets the value for an option. 3988/// 3989/// @param opt_idx Option index in options[] table. 3990/// @param opt_flags Option flags (can be OPT_LOCAL, OPT_GLOBAL or a combination). 3991/// 3992/// @return [allocated] Option value. Returns NIL for invalid option index. 3993Object get_option_value (OptIndex opt_idx ,int opt_flags ) 3994{ 3995if (opt_idx == kOptInvalid ) {// option not in the options[] table. 3996return NIL ; 3997 } 3998 3999vimoption_T * opt = & options [opt_idx ]; 4000return optval_own (opt_idx ,opt_from_varp (opt_idx ,get_varp_scope (opt ,opt_flags ))); 4001} 4002 4003/// Return information for option at 'opt_idx' 4004vimoption_T * get_option (OptIndex opt_idx ) 4005{ 4006assert (opt_idx != kOptInvalid ); 4007return & options [opt_idx ]; 4008} 4009 4010/// True if `value` unsets the local value of global-local option: kObjectTypeUnset, or the 4011/// option-specific (legacy) sentinel stored by set_option_varp(). Always false for 4012/// a non-global-local option. 4013static bool optval_is_unset_local (OptIndex opt_idx ,Object value ) 4014{ 4015if (!option_is_global_local (opt_idx )) { 4016return false; 4017 } 4018if (value .type == kObjectTypeUnset ) { 4019return true; 4020 } 4021// String (including callback) global-local options use an empty string for the unset value. 4022if (option_has_type (opt_idx ,kObjectTypeString )) { 4023return value .type == kObjectTypeString && value .data .string .size == 0 ; 4024 } 4025if (option_has_type (opt_idx ,kObjectTypeBoolean )|| value .type != kObjectTypeInteger ) { 4026return false;// Unset local boolean (kNone) reads as kObjectTypeUnset, handled above. 4027 } 4028switch (opt_idx ) {// Integer global-local options and their unset sentinels. 4029case kOptScrolloff : 4030case kOptScrolloffpad : 4031case kOptSidescrolloff : 4032return value .data .integer == -1 ; 4033case kOptUndolevels : 4034return value .data .integer == NO_LOCAL_UNDOLEVEL ; 4035default : 4036abort (); 4037 } 4038} 4039 4040/// Check if local value of global-local option is unset for current buffer / window. 4041/// Always returns false for options that aren't global-local. 4042static bool is_option_local_value_unset (OptIndex opt_idx ) 4043{ 4044if (!option_is_global_local (opt_idx )) { 4045return false; 4046 } 4047vimoption_T * opt = get_option (opt_idx ); 4048Object local_value = opt_from_varp (opt_idx ,get_varp_scope (opt ,OPT_LOCAL )); 4049bool is_unset = optval_is_unset_local (opt_idx ,local_value ); 4050optval_free_read (opt_idx ,local_value ); 4051return is_unset ; 4052} 4053 4054/// Handle side-effects of setting an option. 4055/// 4056/// @param opt_idx Index in options[] table. Must not be kOptInvalid. 4057/// @param[in] varp Option variable pointer, cannot be NULL. 4058/// @param old_value Old option value. 4059/// @param opt_flags Option flags (can be OPT_LOCAL, OPT_GLOBAL or a combination). 4060/// @param set_sid Script ID. Special values: 4061/// 0: Use current script ID. 4062/// SID_NONE: Don't set script ID. 4063/// @param direct Don't process side-effects. 4064/// @param value_replaced Value was replaced completely. 4065/// @param value_untrusted Value comes from a restricted context or retains untrusted content. 4066/// @param[out] errbuf Buffer for error message. 4067/// 4068/// @return NULL on success, an untranslated error message on error. 4069static const char * did_set_option (OptIndex opt_idx ,void * varp ,Object old_value ,Object new_value , 4070int opt_flags ,scid_T set_sid ,const bool direct , 4071const bool value_replaced ,const bool value_untrusted , 4072const CharBuf * errbuf ) 4073{ 4074vimoption_T * opt = & options [opt_idx ]; 4075const char * errmsg = NULL ; 4076bool value_changed = false; 4077bool value_checked = false; 4078 4079optset_T did_set_cb_args = { 4080 .os_varp = varp , 4081 .os_idx = opt_idx , 4082 .os_flags = opt_flags , 4083 .os_oldval = old_value , 4084 .os_newval = new_value , 4085 .os_value_checked = false, 4086 .os_value_changed = false, 4087 .os_errbuf = errbuf , 4088 .os_buf = curbuf , 4089 .os_win = curwin , 4090 }; 4091 4092if (direct ) { 4093// Don't do any extra processing if setting directly. 4094 } 4095// Disallow changing some options from secure mode. 4096else if ((secure || sandbox != 0 )&& (opt -> flags & kOptFlagSecure )) { 4097errmsg = e_secure ; 4098 } 4099// Check for a "normal" directory or file name in some string options. 4100else if (new_value .type == kObjectTypeString 4101&& check_illegal_path_names (* (char ** )varp ,opt -> flags )) { 4102errmsg = e_invarg ; 4103 }else if (opt -> opt_did_set_cb != NULL ) { 4104// Invoke the option specific callback function to validate and apply the new value. 4105errmsg = opt -> opt_did_set_cb (& did_set_cb_args ); 4106// The 'filetype' and 'syntax' option callback functions may change the os_value_changed field. 4107value_changed = did_set_cb_args .os_value_changed ; 4108// The 'keymap', 'filetype' and 'syntax' option callback functions may change the 4109// os_value_checked field. 4110value_checked = did_set_cb_args .os_value_checked ; 4111// The 'isident', 'iskeyword', 'isprint' and 'isfname' options may change the character table. 4112 } 4113 4114// If option is hidden or if an error is detected, restore the previous value and don't do any 4115// further processing. 4116if (errmsg != NULL ) { 4117set_option_varp (opt_idx ,varp ,old_value ); 4118optval_free (old_value ); 4119// When resetting some values, need to act on it. 4120 4121return errmsg ; 4122 } 4123 4124// Re-assign the new value as its value may get freed or modified by the option callback. 4125new_value = optval_own (opt_idx ,opt_from_varp (opt_idx ,varp )); 4126 4127if (set_sid != SID_NONE ) { 4128sctx_T script_ctx = set_sid == 0 ?current_sctx : (sctx_T ){ .sc_sid = set_sid }; 4129// Remember where the option was set. 4130set_option_sctx (opt_idx ,opt_flags ,script_ctx ); 4131 } 4132 4133optval_free (old_value ); 4134 4135const bool scope_both = (opt_flags & (OPT_LOCAL |OPT_GLOBAL ))== 0 ; 4136 4137if (scope_both ) { 4138if (option_is_global_local (opt_idx )) { 4139// Global option with local value set to use global value. 4140// Free the local value and clear it. 4141set_option_varp (opt_idx ,get_varp_scope (opt ,OPT_LOCAL ),UNSET ); 4142 }else { 4143// May set global value for a buffer/window-local option. Skip when varp already is the 4144// global (a purely-global option): re-storing there is redundant, and for a callback option 4145// it would free the callback and then fail to re-parse an anonymous lambda's `<lambda>N`. 4146void * varp_global = get_varp_scope (opt ,OPT_GLOBAL ); 4147if (varp_global != varp ) { 4148set_option_varp (opt_idx ,varp_global ,new_value ); 4149 } 4150 } 4151 } 4152 4153optval_free (new_value );// Owned via optval_own() above. 4154 4155// Don't do anything else if setting the option directly. 4156if (direct ) { 4157return errmsg ; 4158 } 4159 4160// Trigger the autocommand only after setting the flags. 4161if (varp == & curbuf -> b_p_syn ) { 4162do_syntax_autocmd (curbuf ,value_changed ); 4163 }else if (varp == & curbuf -> b_p_ft ) { 4164// 'filetype' is set, trigger the FileType autocommand 4165// Skip this when called from a modeline 4166// Force autocmd when the filetype was changed 4167if (!(opt_flags & OPT_MODELINE )|| value_changed ) { 4168do_filetype_autocmd (curbuf ,value_changed ); 4169 } 4170 }else if (varp == & curwin -> w_s -> b_p_spl ) { 4171do_spelllang_source (curwin ); 4172 } 4173 4174// In case 'ruler' or 'showcmd' or 'columns' or 'ls' changed. 4175comp_col (); 4176 4177if (varp == & p_mouse ) { 4178setmouse ();// in case 'mouse' changed 4179 }else if ((varp == & p_flp || varp == & (curbuf -> b_p_flp ))&& curwin -> w_briopt_list ) { 4180// Changing Formatlistpattern when briopt includes the list setting: 4181// redraw 4182redraw_all_later (UPD_NOT_VALID ); 4183 }else if (varp == & p_wbr || varp == & (curwin -> w_p_wbr )) { 4184// add / remove window bars for 'winbar' 4185if (varp == & p_wbr ) { 4186set_winbar_all (true); 4187 }else { 4188set_winbar (true); 4189 } 4190 } 4191 4192if (curwin -> w_curswant != MAXCOL 4193&& (opt -> flags & (kOptFlagCurswant |kOptFlagRedrAll ))!= 0 4194&& (opt -> flags & kOptFlagHLOnly )== 0 ) { 4195curwin -> w_set_curswant = true; 4196 } 4197 4198check_redraw (opt -> flags ); 4199 4200if (errmsg == NULL ) { 4201opt -> flags |=kOptFlagWasSet ; 4202 4203uint32_t * flagsp = insecure_flag (curwin ,opt_idx ,opt_flags ); 4204uint32_t * flagsp_local = scope_both ?insecure_flag (curwin ,opt_idx ,OPT_LOCAL ) :NULL ; 4205// Persist trust separately from the temporary secure mode used for side effects. 4206// Only a complete, trusted replacement can clear an existing untrusted flag. 4207if (!value_checked && value_untrusted ) { 4208* flagsp |=kOptFlagInsecure ; 4209if (flagsp_local != NULL ) { 4210* flagsp_local |=kOptFlagInsecure ; 4211 } 4212 }else if (value_replaced ) { 4213* flagsp &= ~(unsigned )kOptFlagInsecure ; 4214if (flagsp_local != NULL ) { 4215* flagsp_local &= ~(unsigned )kOptFlagInsecure ; 4216 } 4217 } 4218 } 4219 4220return errmsg ; 4221} 4222 4223/// Validates an option value (internal scalar/:set-style form) without applying side effects. 4224/// Some option-specific checks still live in did_set callbacks and are not covered here. 4225/// 4226/// @param opt_idx Index in options[] table. Must not be kOptInvalid. 4227/// @param newval[in,out] New option value. Might be modified. 4228/// @param buf Target buffer. 4229/// @param win Target window, used for defaults and window-dependent bounds. 4230const char * validate_option_value (const OptIndex opt_idx ,Object * newval ,int opt_flags ,buf_T * buf , 4231win_T * win ,const CharBuf * errbuf ) 4232{ 4233const char * errmsg = NULL ; 4234vimoption_T * opt = & options [opt_idx ]; 4235 4236// Always allow unsetting local value of global-local option. 4237if ((opt_flags & OPT_LOCAL )&& optval_is_unset_local (opt_idx ,* newval )) { 4238return NULL ; 4239 } 4240 4241if (newval -> type == kObjectTypeNil ) { 4242// Don't try to unset local value if scope is global. 4243// TODO(famiu): Change this to forbid changing all non-local scopes when the API scope bug is 4244// fixed. 4245if (opt_flags == OPT_GLOBAL ) { 4246errmsg = _ ("Cannot unset global option value" ); 4247 }else { 4248// Unset the local value of a global-local option; for other options, an unset local value 4249// means the global value. 4250void * varp = get_varp_scope_from (opt ,OPT_GLOBAL ,buf ,win ); 4251* newval = option_is_global_local (opt_idx ) ?UNSET :optval_own (opt_idx , 4252opt_from_varp (opt_idx ,varp )); 4253 } 4254 }else if (newval -> type == kObjectTypeLuaRef ) { 4255// A callback option accepts a funcref; scalar validation doesn't apply. 4256assert (is_callback_option (opt_idx )); 4257 }else if (!option_has_type (opt_idx ,optval_type (* newval ))) { 4258char * rep = optval_to_cstr (* newval , true); 4259const char * type_str = optval_type_name (opt -> type ); 4260errmsg = opt_error (errbuf ,N_ ("Invalid value for option '%s': expected %s, got %s %s" ), 4261opt -> fullname ,type_str ,optval_type_name (optval_type (* newval )),rep ); 4262xfree (rep ); 4263 }else if (newval -> type == kObjectTypeInteger ) { 4264// Validate and bound check num option values. 4265errmsg = validate_num_option (opt_idx ,& newval -> data .integer ,win ,errbuf ); 4266 } 4267if (errmsg != NULL ) { 4268return errmsg ; 4269 } 4270 4271// Disallow changing immutable options. 4272if (opt -> immutable ) { 4273Object oldval = opt_from_varp (opt_idx ,get_varp_scope_from (opt ,opt_flags ,buf ,win )); 4274bool unchanged = option_equal (oldval ,* newval ); 4275optval_free_read (opt_idx ,oldval ); 4276if (!unchanged ) { 4277return e_unsupportedoption ; 4278 } 4279 } 4280if (newval -> type == kObjectTypeString && opt -> schema != NULL ) { 4281errmsg = opt_strings_check (newval -> data .string .data ,opt -> schema ,errbuf ); 4282if (errmsg != NULL ) { 4283return errmsg ; 4284 } 4285 } 4286if (newval -> type != kObjectTypeUnset && opt -> opt_validate_cb != NULL ) { 4287const bool scope_both = !(opt_flags & (OPT_LOCAL |OPT_GLOBAL )); 4288// Match set_option(): setting both scopes of a global-local option resets its local value. 4289void * varp = scope_both && option_is_global_local (opt_idx ) 4290 ?opt -> var :get_varp_scope_from (opt ,opt_flags ,buf ,win ); 4291const optset_T args = { 4292 .os_varp = varp , 4293 .os_idx = opt_idx , 4294 .os_flags = opt_flags , 4295 .os_oldval = opt_from_varp (opt_idx ,varp ), 4296 .os_newval = * newval , 4297 .os_value_checked = false, 4298 .os_value_changed = false, 4299 .os_restore_chartab = false, 4300 .os_errbuf = errbuf , 4301 .os_buf = buf , 4302 .os_win = win , 4303 }; 4304errmsg = opt -> opt_validate_cb (& args ); 4305optval_free_read (opt_idx ,args .os_oldval ); 4306return errmsg ; 4307 } 4308return NULL ; 4309} 4310 4311/// Set the value of an option using an Object. 4312/// 4313/// @param opt_idx Index in options[] table. Must not be kOptInvalid. 4314/// @param value New option value. Might get freed. 4315/// @param opt_flags Option flags (can be OPT_LOCAL, OPT_GLOBAL or a combination). 4316/// @param set_sid Script ID. Special values: 4317/// 0: Use current script ID. 4318/// SID_NONE: Don't set script ID. 4319/// @param direct Don't process side-effects. 4320/// @param value_replaced Value was replaced completely. 4321/// @param[out] errbuf Buffer for error message. 4322/// 4323/// @return NULL on success, an untranslated error message on error. 4324static const char * set_option (const OptIndex opt_idx ,Object value ,int opt_flags ,scid_T set_sid , 4325const bool direct ,const bool value_replaced ,const CharBuf * errbuf ) 4326{ 4327assert (opt_idx != kOptInvalid ); 4328 4329const char * errmsg = NULL ; 4330 4331// Every set path for a dict option (":set", the API, Vimscript, a merge) funnels through here as a 4332// ":set" string. 4333if (!direct ) { 4334// Callback parsing can execute Vimscript, so reject restricted assignments first. 4335if ((secure || sandbox != 0 )&& (options [opt_idx ].flags & kOptFlagSecure )) { 4336optval_free (value ); 4337return e_secure ; 4338 } 4339 4340errmsg = validate_option_value (opt_idx ,& value ,opt_flags ,curbuf ,curwin ,errbuf ); 4341 4342if (errmsg == NULL && value .type == kObjectTypeString 4343&& (options [opt_idx ].flags & kOptFlagFunc )&& value .data .string .size > 0 ) { 4344// Callback option: the string must parse to a valid function reference or lambda. 4345// Parsing can evaluate Vimscript, so keep it off the dry-run path. Check before storing 4346// so an invalid value leaves the old callback intact. 4347Callback cb = CALLBACK_NONE ; 4348if (option_set_callback_func (value .data .string .data ,& cb )== FAIL ) { 4349errmsg = e_invarg ; 4350 } 4351callback_free (& cb ); 4352 } 4353 }else if (value .type == kObjectTypeString && is_dict_option (opt_idx )) { 4354// Internal direct setters also require valid dict schemas. 4355errmsg = opt_strings_check (value .data .string .data ,opt_dict_schema (opt_idx )-> schema ,errbuf ); 4356 } 4357 4358if (errmsg != NULL ) { 4359optval_free (value ); 4360return errmsg ; 4361 } 4362 4363#ifdef BACKSLASH_IN_FILENAME 4364// Ensure "/" slashes in various options. 4365uint32_t flags = options [opt_idx ].flags ; 4366if (value .type == kObjectTypeString 4367&& (flags & kOptFlagExpand ) 4368&& opt_idx != kOptEqualprg 4369&& opt_idx != kOptFormatprg 4370&& opt_idx != kOptGrepprg 4371&& opt_idx != kOptKeywordprg 4372&& opt_idx != kOptMakeprg 4373&& opt_idx != kOptShell ) { 4374bool allow_comma = flags & kOptFlagComma ; 4375bool allow_space = (opt_idx == kOptCdpath || opt_idx == kOptPath || opt_idx == kOptTags ); 4376for (char * p = value .data .string .data ;* p ;p ++ ) { 4377if (* p != '\\' 4378|| (p [1 ]== ',' && allow_comma ) 4379|| (p [1 ]== ' ' && allow_space )) { 4380continue ; 4381 } 4382* p = '/' ; 4383 } 4384 } 4385#endif 4386 4387vimoption_T * opt = & options [opt_idx ]; 4388const bool scope_local = opt_flags & OPT_LOCAL ; 4389const bool scope_global = opt_flags & OPT_GLOBAL ; 4390const bool scope_both = !scope_local && !scope_global ; 4391// Whether local value of global-local option is unset. 4392// NOTE: When this is true, it also implies that the option is global-local. 4393const bool is_opt_local_unset = is_option_local_value_unset (opt_idx ); 4394 4395// When using ":set opt=val" for a global option with a local value the local value will be reset, 4396// use the global value in that case. 4397void * varp 4398= scope_both && option_is_global_local (opt_idx ) ?opt -> var :get_varp_scope (opt ,opt_flags ); 4399void * varp_local = get_varp_scope (opt ,OPT_LOCAL ); 4400void * varp_global = get_varp_scope (opt ,OPT_GLOBAL ); 4401 4402// All values on the set path are owned. 4403Object old_value = optval_own (opt_idx ,opt_from_varp (opt_idx ,varp )); 4404 4405// Snapshots for OptionSet/UI reporting, taken before the store since it changes varp (and 4406// autocommands may even close the buffer). Skipped when not reporting (direct set). 4407Object saved_used_value = NIL ; 4408Object saved_old_global_value = NIL ; 4409Object saved_old_local_value = NIL ; 4410Object saved_new_value = NIL ; 4411if (!direct ) { 4412saved_old_global_value = optval_snapshot_varp (opt_idx ,varp_global ); 4413// If local value of global-local option is unset, use global value as local value. 4414saved_old_local_value = is_opt_local_unset 4415 ?copy_object (saved_old_global_value ,NULL ) 4416 :optval_snapshot_varp (opt_idx ,varp_local ); 4417// Value that's actually being used: for local scope of a global-local option, the global 4418// value if the local value is unset; in every other case, the same as old_value. Used instead 4419// of old_value when triggering the OptionSet autocommand. 4420saved_used_value = (scope_local && is_opt_local_unset ) 4421 ?optval_snapshot_varp (opt_idx ,get_varp (opt )) 4422 :optval_snapshot (old_value ); 4423 } 4424 4425const int secure_saved = secure ; 4426 4427// Use secure mode for sandbox, modeline, and secure-mode assignments, and for partial 4428// changes to insecure values. Full replacements inherit only the current context's 4429// restrictions. Keep value trust separate from temporary secure mode; did_set_option() 4430// accounts for callback safety checks when updating the stored trust flag. 4431const bool value_untrusted = secure || sandbox != 0 || (opt_flags & OPT_MODELINE ) 4432|| (!value_replaced && was_set_insecurely (curwin ,opt_idx , 4433opt_flags )); 4434if (!secure && value_untrusted ) { 4435secure = 1 ; 4436 } 4437 4438// Store the new value (copied) at varp. 4439set_option_varp (opt_idx ,varp ,value ); 4440if (value .type == kObjectTypeUnset ) { 4441// Re-read the "unset" sentinel ("", -1, …; see optval_is_unset_local()), so did_set callbacks 4442// and OptionSet reporting get that concrete sentinel, not the global value. 4443value = optval_own (opt_idx ,opt_from_varp (opt_idx ,varp )); 4444 } 4445if (!direct ) { 4446// New value (and varp) may become invalid if the buffer is closed by autocommands. 4447saved_new_value = optval_snapshot (value ); 4448 } 4449// Process any side effects. 4450errmsg = did_set_option (opt_idx ,varp ,old_value ,value ,opt_flags ,set_sid ,direct , 4451value_replaced ,value_untrusted ,errbuf ); 4452 4453secure = secure_saved ; 4454 4455if (errmsg == NULL && !direct ) { 4456if (!starting ) { 4457apply_optionset_autocmd (opt_idx ,opt_flags ,saved_used_value ,saved_old_global_value , 4458saved_old_local_value ,saved_new_value ); 4459 } 4460if (opt -> flags & kOptFlagUIOption ) { 4461ui_call_option_set (cstr_as_string (opt -> fullname ),saved_new_value ); 4462 } 4463 } 4464 4465// Free copied values as they are not needed anymore 4466optval_free (saved_used_value ); 4467optval_free (saved_old_local_value ); 4468optval_free (saved_old_global_value ); 4469optval_free (saved_new_value ); 4470 4471// `old_value` is freed by did_set_option(). 4472optval_free (value ); 4473 4474return errmsg ; 4475} 4476 4477/// Set option value directly, without processing any side effects. 4478/// 4479/// @param opt_idx Option index in options[] table. 4480/// @param value Option value. 4481/// @param opt_flags Option flags (can be OPT_LOCAL, OPT_GLOBAL or a combination). 4482/// @param set_sid Script ID. Special values: 4483/// 0: Use current script ID. 4484/// SID_NONE: Don't set script ID. 4485void set_option_direct (OptIndex opt_idx ,Object value ,int opt_flags ,scid_T set_sid ) 4486{ 4487if (is_option_hidden (opt_idx )) { 4488return ; 4489 } 4490 4491const char * errmsg = set_option (opt_idx ,copy_object (value ,NULL ),opt_flags ,set_sid , true, true, 4492NULL ); 4493assert (errmsg == NULL ); 4494 (void )errmsg ;// ignore unused warning 4495} 4496 4497/// Set option value directly for buffer / window, without processing any side effects. 4498/// 4499/// @param opt_idx Option index in options[] table. 4500/// @param value Option value. 4501/// @param opt_flags Option flags (can be OPT_LOCAL, OPT_GLOBAL or a combination). 4502/// @param set_sid Script ID. Special values: 4503/// 0: Use current script ID. 4504/// SID_NONE: Don't set script ID. 4505/// @param scope Option scope. See OptScope in option.h. 4506/// @param[in] from Target buffer/window. 4507void set_option_direct_for (OptIndex opt_idx ,Object value ,int opt_flags ,scid_T set_sid , 4508OptScope scope ,void * const from ) 4509{ 4510buf_T * save_curbuf = curbuf ; 4511win_T * save_curwin = curwin ; 4512 4513// Don't use switch_option_context(), as that calls ctx_switch(), which may have unintended 4514// side-effects when setting an option directly. Just change the values of curbuf and curwin if 4515// needed, no need to properly switch the window / buffer. 4516switch (scope ) { 4517case kOptScopeGlobal : 4518break ; 4519case kOptScopeWin : 4520curwin = (win_T * )from ; 4521curbuf = curwin -> w_buffer ; 4522break ; 4523case kOptScopeBuf : 4524curbuf = (buf_T * )from ; 4525break ; 4526case kOptScopeTab : 4527// No context to switch; tab-scoped direct-set isn't used. Caller should route through 4528// set_option_value_for() instead. 4529abort (); 4530 } 4531 4532set_option_direct (opt_idx ,value ,opt_flags ,set_sid ); 4533 4534curwin = save_curwin ; 4535curbuf = save_curbuf ; 4536} 4537 4538/// Sets the value of an (non-tty) option. 4539/// 4540/// @param opt_idx Index in options[] table. Must not be kOptInvalid. 4541/// @param[in] value Option value. If NIL, the option value is cleared. 4542/// @param[in] opt_flags Flags: OPT_LOCAL, OPT_GLOBAL, or 0 (both). 4543/// @param value_replaced Value was replaced completely. 4544/// @param[out] errbuf Buffer for error message, or NULL if not needed. 4545/// 4546/// @return NULL on success, an error message (possibly in errbuf) on error. 4547const char * set_option_value (const OptIndex opt_idx ,const Object value ,int opt_flags , 4548const bool value_replaced ,const CharBuf * errbuf ) 4549{ 4550assert (opt_idx != kOptInvalid ); 4551 4552uint32_t flags = options [opt_idx ].flags ; 4553 4554// Disallow changing some options in the sandbox 4555if (sandbox > 0 && (flags & kOptFlagSecure )) { 4556return _ (e_sandbox ); 4557 } 4558 4559return set_option (opt_idx ,copy_object (value ,NULL ),opt_flags ,0 , false,value_replaced ,errbuf ); 4560} 4561 4562/// Unset the local value of a global-local option. 4563/// 4564/// @param opt_idx Index in options[] table. Must not be kOptInvalid. 4565/// 4566/// @return NULL on success, an untranslated error message on error. 4567static inline const char * unset_option_local_value (const OptIndex opt_idx ) 4568{ 4569assert (option_is_global_local (opt_idx )); 4570return set_option_value (opt_idx ,UNSET ,OPT_LOCAL , true,NULL ); 4571} 4572 4573/// Call set_option_value() and when an error is returned, report it. 4574/// 4575/// @param opt_idx Option index in options[] table. 4576/// @param value Option value. If NIL, the option value is cleared. 4577/// @param opt_flags Option flags (can be OPT_LOCAL, OPT_GLOBAL or a combination). 4578void set_option_value_give_err (const OptIndex opt_idx ,Object value ,int opt_flags ) 4579{ 4580const CharBuf errbuf = { (char [IOSIZE ]){0 },IOSIZE }; 4581const char * errmsg = set_option_value (opt_idx ,value ,opt_flags , true,& errbuf ); 4582 4583if (errmsg != NULL ) { 4584emsg (_ (errmsg )); 4585 } 4586} 4587 4588/// Switch current context to get/set option value for the target window/buffer/tabpage. 4589/// 4590/// Tab-scope switch is GET-only (SET requires side-effects, see set_option_value_for()). 4591/// 4592/// @param[out] ctx Switched-from context, restored by restore_option_context(): 4593/// - kOptScopeWin/kOptScopeBuf: CtxSwitch 4594/// - kOptScopeTab: tabpage_T * (saved curtab) 4595/// - kOptScopeGlobal: unused 4596/// @param scope Option scope. See OptScope in option.h. 4597/// @param[in] from Target win_T/buf_T/tabpage_T. 4598/// @param[out] err Error message, if any. 4599/// 4600/// @return true if context was switched, false otherwise. 4601static bool switch_option_context (void * const ctx ,OptScope scope ,void * const from ,Error * err ) 4602{ 4603switch (scope ) { 4604case kOptScopeGlobal : 4605return false; 4606case kOptScopeWin : { 4607win_T * const win = (win_T * )from ; 4608 4609if (win == curwin ) { 4610return false; 4611 } 4612 4613// kCtxNoDisplay (no kCtxNoEvents): switch without redraw, but let autocommands fire. 4614if (!ctx_switch ((CtxSwitch * )ctx ,win ,win_find_tabpage (win ),NULL ,kCtxNoDisplay )) { 4615ctx_restore ((CtxSwitch * )ctx ); 4616if (!ERROR_SET (err )) { 4617api_set_error (err ,kErrorTypeException ,"Problem while switching windows" ); 4618 } 4619return false; 4620 } 4621return true; 4622 } 4623case kOptScopeBuf : { 4624buf_T * const buf = (buf_T * )from ; 4625 4626if (buf == curbuf ) { 4627return false; 4628 } 4629ctx_switch ((CtxSwitch * )ctx ,NULL ,NULL ,buf ,0 ); 4630return true; 4631 } 4632case kOptScopeTab : { 4633// GET-only: swap curtab so get_option_value() reads the target tab's stored value (p_ch). 4634// SET on a non-current tab cannot use this path, see comment in set_option_value_for(). 4635tabpage_T * const tab = (tabpage_T * )from ; 4636tabpage_T ** const saved_curtab = (tabpage_T ** )ctx ; 4637 4638if (tab == curtab ) { 4639return false; 4640 } 4641* saved_curtab = curtab ; 4642unuse_tabpage (curtab ); 4643use_tabpage (tab ); 4644return true; 4645 } 4646 } 4647UNREACHABLE ; 4648} 4649 4650/// Restore context after getting/setting option for window/buffer. See switch_option_context() for 4651/// params. 4652static void restore_option_context (void * const ctx ,OptScope scope ) 4653{ 4654switch (scope ) { 4655case kOptScopeGlobal : 4656break ; 4657case kOptScopeWin : 4658case kOptScopeBuf : 4659ctx_restore ((CtxSwitch * )ctx ); 4660break ; 4661case kOptScopeTab : { 4662tabpage_T * const saved_curtab = * (tabpage_T ** )ctx ; 4663unuse_tabpage (curtab ); 4664use_tabpage (saved_curtab ); 4665break ; 4666 } 4667 } 4668} 4669 4670/// Get option value for buffer / window. 4671/// 4672/// @param opt_idx Option index in options[] table. 4673/// @param[out] flagsp Set to the option flags (see OptFlags) (if not NULL). 4674/// @param[in] scope Option scope (can be OPT_LOCAL, OPT_GLOBAL or a combination). 4675/// @param[out] hidden Whether option is hidden. 4676/// @param scope Option scope. See OptScope in option.h. 4677/// @param[in] from Target buffer/window. 4678/// @param[out] err Error message, if any. 4679/// 4680/// @return Option value as an owned Object (free with api_free_object). Nil if the option has no 4681/// value in the requested scope (e.g. an unset global-local value). 4682Object get_option_value_for (OptIndex opt_idx ,int opt_flags ,const OptScope scope ,void * const from , 4683Error * err ) 4684{ 4685CtxSwitch cs = {0 }; 4686tabpage_T * swtab = NULL ; 4687void * ctx = scope == kOptScopeTab ? (void * )& swtab : (void * )& cs ; 4688 4689bool switched = switch_option_context (ctx ,scope ,from ,err ); 4690if (ERROR_SET (err )) { 4691return NIL ; 4692 } 4693 4694Object retv = get_option_value (opt_idx ,opt_flags ); 4695 4696if (switched ) { 4697restore_option_context (ctx ,scope ); 4698 } 4699 4700// Move ownership of any string from `retv` into the Object; `retv` itself is not freed. 4701return retv ; 4702} 4703 4704/// Set option value for buffer / window. 4705/// 4706/// @param opt_idx Option index in options[] table. Must not be kOptInvalid. 4707/// @param[in] value Option value. 4708/// @param[in] opt_flags Flags: OPT_LOCAL, OPT_GLOBAL, or 0 (both). 4709/// @param scope Option scope. See OptScope in option.h. 4710/// @param[in] from Target buffer/window. 4711/// @param value_replaced Value was replaced completely, not appended/prepended/removed. 4712/// @param[out] err Error message, if any. 4713void set_option_value_for (OptIndex opt_idx ,Object value ,const int opt_flags ,const OptScope scope , 4714void * const from ,const bool value_replaced ,Error * err ) 4715{ 4716// Special case: Tab scope (for NON-CURRENT tab) can't go through the normal "set" path: 4717// did_set_cmdheight() mutates globals not managed by use_tabpage()/unuse_tabpage(), which would 4718// leak across switch_option_context(). 4719// 4720// Workaround: set `tp_ch_used` directly; the cmdline will resize when the tab is switched-to. 4721if (scope == kOptScopeTab && (tabpage_T * )from != curtab ) { 4722tabpage_T * const tab = (tabpage_T * )from ; 4723assert (opt_idx == kOptCmdheight ); 4724if (value .type != kObjectTypeInteger ) { 4725api_set_error (err ,kErrorTypeValidation ,"'cmdheight' requires a Number" ); 4726return ; 4727 } 4728tab -> tp_ch_used = value .data .integer ; 4729return ; 4730 } 4731 4732CtxSwitch cs = {0 }; 4733tabpage_T * swtab = NULL ; 4734void * ctx = scope == kOptScopeTab ? (void * )& swtab : (void * )& cs ; 4735 4736bool switched = switch_option_context (ctx ,scope ,from ,err ); 4737if (ERROR_SET (err )) { 4738return ; 4739 } 4740 4741const CharBuf errbuf = { (char [IOSIZE ]){0 },IOSIZE }; 4742const char * const errmsg = set_option_value (opt_idx ,value ,opt_flags ,value_replaced ,& errbuf ); 4743if (errmsg ) { 4744api_set_error (err ,kErrorTypeException ,"%s" ,errmsg ); 4745 } 4746 4747if (switched ) { 4748restore_option_context (ctx ,scope ); 4749 } 4750} 4751 4752/// if 'all' == false: show changed options 4753/// if 'all' == true: show all normal options 4754/// 4755/// @param opt_flags Option flags (can be OPT_LOCAL, OPT_GLOBAL or a combination). 4756static void showoptions (bool all ,int opt_flags ) 4757{ 4758#define INC 20 4759#define GAP 3 4760 4761vimoption_T ** items = xmalloc (sizeof (vimoption_T * )* OPTION_COUNT ); 4762 4763msg_ext_set_kind ("list_cmd" ); 4764// Highlight title 4765if (opt_flags & OPT_GLOBAL ) { 4766msg_puts_title (_ ("\n--- Global option values ---" )); 4767 }else if (opt_flags & OPT_LOCAL ) { 4768msg_puts_title (_ ("\n--- Local option values ---" )); 4769 }else { 4770msg_puts_title (_ ("\n--- Options ---" )); 4771 } 4772 4773// Do the loop two times: 4774// 1. display the short items 4775// 2. display the long items (only strings and numbers) 4776// When "opt_flags" has OPT_ONECOLUMN do everything in run 2. 4777for (int run = 1 ;run <=2 && !got_int ;run ++ ) { 4778// collect the items in items[] 4779int item_count = 0 ; 4780vimoption_T * opt ; 4781for (OptIndex opt_idx = 0 ;opt_idx < kOptCount ;opt_idx ++ ) { 4782opt = & options [opt_idx ]; 4783// apply :filter /pat/ 4784if (message_filtered (opt -> fullname )) { 4785continue ; 4786 } 4787 4788void * varp = NULL ; 4789if ((opt_flags & (OPT_LOCAL |OPT_GLOBAL ))!= 0 ) { 4790if (!option_is_global_only (opt_idx )) { 4791varp = get_varp_scope (opt ,opt_flags ); 4792 } 4793 }else { 4794varp = get_varp (opt ); 4795 } 4796if (varp != NULL && (all || !optval_default (opt_idx ,varp ))) { 4797int len ; 4798if (opt_flags & OPT_ONECOLUMN ) { 4799len = Columns ; 4800 }else if (option_has_type (opt_idx ,kObjectTypeBoolean )) { 4801len = 1 ;// a toggle option fits always 4802 }else { 4803optval_fmt (opt_idx ,opt_flags ); 4804len = (int )strlen (opt -> fullname )+ vim_strsize (NameBuff )+ 1 ; 4805 } 4806if ((len <=INC - GAP && run == 1 ) 4807|| (len > INC - GAP && run == 2 )) { 4808items [item_count ++ ]= opt ; 4809 } 4810 } 4811 } 4812 4813int rows ; 4814 4815// display the items 4816if (run == 1 ) { 4817assert (Columns <=INT_MAX - GAP 4818&& Columns + GAP >=INT_MIN + 3 4819&& (Columns + GAP - 3 ) /INC >=INT_MIN 4820&& (Columns + GAP - 3 ) /INC <=INT_MAX ); 4821int cols = (Columns + GAP - 3 ) /INC ; 4822if (cols == 0 ) { 4823cols = 1 ; 4824 } 4825rows = (item_count + cols - 1 ) /cols ; 4826 }else {// run == 2 4827rows = item_count ; 4828 } 4829for (int row = 0 ;row < rows && !got_int ;row ++ ) { 4830msg_putchar ('\n' );// go to next line 4831if (got_int ) {// 'q' typed in more 4832break ; 4833 } 4834int col = 0 ; 4835for (int i = row ;i < item_count ;i += rows ) { 4836msg_advance (col );// make columns 4837showoneopt (items [i ],opt_flags ); 4838col += INC ; 4839 } 4840os_breakcheck (); 4841 } 4842 } 4843xfree (items ); 4844} 4845 4846/// Return true if option "p" has its default value. 4847static int optval_default (OptIndex opt_idx ,void * varp ) 4848{ 4849vimoption_T * opt = & options [opt_idx ]; 4850 4851// Hidden options always use their default value. 4852if (is_option_hidden (opt_idx )) { 4853return true; 4854 } 4855 4856Object current_val = opt_from_varp (opt_idx ,varp ); 4857Object default_val = opt -> def_val ; 4858 4859bool is_default = option_equal (current_val ,default_val ); 4860optval_free_read (opt_idx ,current_val ); 4861return is_default ; 4862} 4863 4864/// Send update to UIs with values of UI relevant options 4865void ui_refresh_options (void ) 4866{ 4867for (OptIndex opt_idx = 0 ;opt_idx < kOptCount ;opt_idx ++ ) { 4868uint32_t flags = options [opt_idx ].flags ; 4869if (!(flags & kOptFlagUIOption )) { 4870continue ; 4871 } 4872String name = cstr_as_string (options [opt_idx ].fullname ); 4873Object value = opt_from_varp (opt_idx ,options [opt_idx ].var ); 4874ui_call_option_set (name ,value ); 4875 } 4876if (p_mouse != NULL ) { 4877setmouse (); 4878 } 4879} 4880 4881/// showoneopt: show the value of one option 4882/// must not be called with a hidden option! 4883/// 4884/// @param opt_flags Option flags (can be OPT_LOCAL, OPT_GLOBAL or a combination). 4885static void showoneopt (vimoption_T * opt ,int opt_flags ) 4886{ 4887int save_silent = silent_mode ; 4888 4889silent_mode = false; 4890info_message = true;// use stdout, not stderr 4891 4892OptIndex opt_idx = get_opt_idx (opt ); 4893void * varp = get_varp_scope (opt ,opt_flags ); 4894 4895// for 'modified' we also need to check if 'ff' or 'fenc' changed. 4896if (option_has_type (opt_idx ,kObjectTypeBoolean ) 4897&& ((int * )varp == & curbuf -> b_changed ? !curbufIsChanged () : !* (int * )varp )) { 4898msg_puts ("no" ); 4899 }else if (option_has_type (opt_idx ,kObjectTypeBoolean )&& * (int * )varp < 0 ) { 4900msg_puts ("--" ); 4901 }else { 4902msg_puts (" " ); 4903 } 4904msg_puts (opt -> fullname ); 4905if (!(option_has_type (opt_idx ,kObjectTypeBoolean ))) { 4906msg_putchar ('=' ); 4907// put value string in NameBuff 4908optval_fmt (opt_idx ,opt_flags ); 4909if (* NameBuff != NUL ) { 4910msg_outtrans (NameBuff ,0 , false); 4911 } 4912 } 4913 4914silent_mode = save_silent ; 4915info_message = false; 4916} 4917 4918/// Write modified options as ":set" commands to a file. 4919/// 4920/// There are three values for "opt_flags": 4921/// OPT_GLOBAL: Write global option values and fresh values of 4922/// buffer-local options (used for start of a session 4923/// file). 4924/// OPT_GLOBAL + OPT_LOCAL: Idem, add fresh values of window-local options for 4925/// curwin (used for a vimrc file). 4926/// OPT_LOCAL: Write buffer-local option values for curbuf, fresh 4927/// and local values for window-local options of 4928/// curwin. Local values are also written when at the 4929/// default value, because a modeline or autocommand 4930/// may have set them when doing ":edit file" and the 4931/// user has set them back at the default or fresh 4932/// value. 4933/// When "local_only" is true, don't write fresh 4934/// values, only local values (for ":mkview"). 4935/// (fresh value = value used for a new buffer or window for a local option). 4936/// 4937/// Return FAIL on error, OK otherwise. 4938int makeset (FILE * fd ,int opt_flags ,int local_only ) 4939{ 4940// Some options are never written: 4941// - Options that don't have a default (terminal name, columns, lines). 4942// - Terminal options. 4943// - Hidden options. 4944// 4945// Do the loop over "options[]" twice: once for options with the 4946// kOptFlagPriMkrc flag and once without. 4947for (int pri = 1 ;pri >=0 ;pri -- ) { 4948vimoption_T * opt ; 4949for (OptIndex opt_idx = 0 ;opt_idx < kOptCount ;opt_idx ++ ) { 4950opt = & options [opt_idx ]; 4951 4952if (!(opt -> flags & kOptFlagNoMkrc ) 4953&& ((pri == 1 )== ((opt -> flags & kOptFlagPriMkrc )!= 0 ))) { 4954// skip global option when only doing locals 4955if (option_is_global_only (opt_idx )&& !(opt_flags & OPT_GLOBAL )) { 4956continue ; 4957 } 4958 4959// Do not store options like 'bufhidden' and 'syntax' in a vimrc 4960// file, they are always buffer-specific. 4961if ((opt_flags & OPT_GLOBAL )&& (opt -> flags & kOptFlagNoGlob )) { 4962continue ; 4963 } 4964 4965void * varp = get_varp_scope (opt ,opt_flags );// currently used value 4966// Hidden options are never written. 4967if (!varp ) { 4968continue ; 4969 } 4970// Global values are only written when not at the default value. 4971if ((opt_flags & OPT_GLOBAL )&& optval_default (opt_idx ,varp )) { 4972continue ; 4973 } 4974 4975if ((opt_flags & OPT_SKIPRTP ) 4976&& (opt -> var == & p_rtp || opt -> var == & p_pp )) { 4977continue ; 4978 } 4979 4980int round = 2 ; 4981void * varp_local = NULL ;// fresh value 4982if (option_is_window_local (opt_idx )) { 4983// skip window-local option when only doing globals 4984if (!(opt_flags & OPT_LOCAL )) { 4985continue ; 4986 } 4987// When fresh value of window-local option is not at the 4988// default, need to write it too. 4989if (!(opt_flags & OPT_GLOBAL )&& !local_only ) { 4990void * varp_fresh = get_varp_scope (opt ,OPT_GLOBAL );// local value 4991if (!optval_default (opt_idx ,varp_fresh )) { 4992round = 1 ; 4993varp_local = varp ; 4994varp = varp_fresh ; 4995 } 4996 } 4997 } 4998 4999// Round 1: fresh value for window-local options. 5000// Round 2: other values 5001for (;round <=2 ;varp = varp_local ,round ++ ) { 5002char * cmd ; 5003if (round == 1 || (opt_flags & OPT_GLOBAL )) { 5004cmd = "set" ; 5005 }else { 5006cmd = "setlocal" ; 5007 } 5008 5009bool do_endif = false; 5010// Don't set 'syntax' and 'filetype' again if the value is already right, avoids reloading 5011// the syntax file. 5012if (opt_idx == kOptSyntax || opt_idx == kOptFiletype ) { 5013if (fprintf (fd ,"if &%s != '%s'" ,opt -> fullname , 5014* (char ** )varp )< 0 5015|| put_eol (fd )< 0 ) { 5016return FAIL ; 5017 } 5018do_endif = true; 5019 } 5020if (put_set (fd ,cmd ,opt_idx ,varp )== FAIL ) { 5021return FAIL ; 5022 } 5023if (do_endif ) { 5024if (put_line (fd ,"endif" )== FAIL ) { 5025return FAIL ; 5026 } 5027 } 5028 } 5029 } 5030 } 5031 } 5032return OK ; 5033} 5034 5035/// Generate set commands for the local fold options only. Used when 5036/// 'sessionoptions' or 'viewoptions' contains "folds" but not "options". 5037int makefoldset (FILE * fd ) 5038{ 5039if (put_set (fd ,"setlocal" ,kOptFoldmethod ,& curwin -> w_p_fdm )== FAIL 5040|| put_set (fd ,"setlocal" ,kOptFoldexpr ,& curwin -> w_p_fde )== FAIL 5041|| put_set (fd ,"setlocal" ,kOptFoldmarker ,& curwin -> w_p_fmr )== FAIL 5042|| put_set (fd ,"setlocal" ,kOptFoldignore ,& curwin -> w_p_fdi )== FAIL 5043|| put_set (fd ,"setlocal" ,kOptFoldlevel ,& curwin -> w_p_fdl )== FAIL 5044|| put_set (fd ,"setlocal" ,kOptFoldminlines ,& curwin -> w_p_fml )== FAIL 5045|| put_set (fd ,"setlocal" ,kOptFoldnestmax ,& curwin -> w_p_fdn )== FAIL 5046|| put_set (fd ,"setlocal" ,kOptFoldenable ,& curwin -> w_p_fen )== FAIL ) { 5047return FAIL ; 5048 } 5049 5050return OK ; 5051} 5052 5053/// Print the ":set" command to set a single option to file. 5054/// 5055/// @param fd File descriptor. 5056/// @param cmd Command name. 5057/// @param opt_idx Option index in options[] table. 5058/// @param varp Pointer to option variable. 5059/// 5060/// @return FAIL on error, OK otherwise. 5061static int put_set_value (FILE * fd ,char * cmd ,OptIndex opt_idx ,void * varp ,Object value ) 5062{ 5063vimoption_T * opt = & options [opt_idx ]; 5064char * name = opt -> fullname ; 5065uint64_t flags = opt -> flags ; 5066 5067if (varp != opt -> var && optval_is_unset_local (opt_idx ,value )) { 5068// Processing unset local value of global-local option. Do nothing. 5069return OK ; 5070 } 5071 5072switch (value .type ) { 5073case kObjectTypeBoolean : { 5074bool value_bool = value .data .boolean ; 5075 5076if (fprintf (fd ,"%s %s%s" ,cmd ,value_bool ?"" :"no" ,name )< 0 ) { 5077return FAIL ; 5078 } 5079break ; 5080 } 5081case kObjectTypeInteger : { 5082if (fprintf (fd ,"%s %s=" ,cmd ,name )< 0 ) { 5083return FAIL ; 5084 } 5085 5086OptInt value_num = value .data .integer ; 5087 5088OptInt wc ; 5089if (wc_use_keyname (varp ,& wc )) { 5090// print 'wildchar' and 'wildcharm' as a key name 5091if (fputs (get_special_key_name ((int )wc ,0 ),fd )< 0 ) { 5092return FAIL ; 5093 } 5094 }else if (fprintf (fd ,"%" PRId64 ,value_num )< 0 ) { 5095return FAIL ; 5096 } 5097break ; 5098 } 5099case kObjectTypeString : { 5100if (fprintf (fd ,"%s %s=" ,cmd ,name )< 0 ) { 5101return FAIL ; 5102 } 5103 5104const char * value_str = value .data .string .data ; 5105char * buf = NULL ; 5106char * part = NULL ; 5107 5108if (value_str != NULL ) { 5109if ((flags & kOptFlagExpand )!= 0 ) { 5110size_t size = (size_t )strlen (value_str )+ 1 ; 5111 5112// replace home directory in the whole option value into "buf" 5113buf = xmalloc (size ); 5114home_replace (NULL ,value_str ,buf ,size , false); 5115 5116// If the option value is longer than MAXPATHL, we need to append 5117// each comma separated part of the option separately, so that it 5118// can be expanded when read back. 5119if (size >=MAXPATHL && (flags & kOptFlagComma )!= 0 5120&& vim_strchr (value_str ,',' )!= NULL ) { 5121part = xmalloc (size ); 5122 5123// write line break to clear the option, e.g. ':set rtp=' 5124if (put_eol (fd )== FAIL ) { 5125 gotofail ; 5126 } 5127char * p = buf ; 5128while (* p != NUL ) { 5129// for each comma separated option part, append value to 5130// the option, :set rtp+=value 5131if (fprintf (fd ,"%s %s+=" ,cmd ,name )< 0 ) { 5132 gotofail ; 5133 } 5134copy_option_part (& p ,part ,size ,"," ); 5135if (put_escstr (fd ,part ,2 )== FAIL || put_eol (fd )== FAIL ) { 5136 gotofail ; 5137 } 5138 } 5139xfree (buf ); 5140xfree (part ); 5141return OK ; 5142 } 5143if (put_escstr (fd ,buf ,2 )== FAIL ) { 5144xfree (buf ); 5145return FAIL ; 5146 } 5147xfree (buf ); 5148 }else if (put_escstr (fd ,value_str ,2 )== FAIL ) { 5149return FAIL ; 5150 } 5151 } 5152break ; 5153fail : 5154xfree (buf ); 5155xfree (part ); 5156return FAIL ; 5157 } 5158default : 5159abort (); 5160 } 5161 5162if (put_eol (fd )< 0 ) { 5163return FAIL ; 5164 } 5165return OK ; 5166} 5167 5168/// Print the ":set" command for one option to a file, then release the read value. 5169static int put_set (FILE * fd ,char * cmd ,OptIndex opt_idx ,void * varp ) 5170{ 5171Object value = opt_from_varp (opt_idx ,varp ); 5172// Skip func-option set to a Lua function (omit from :mksession/etc.). 5173int ret = value .type == kObjectTypeLuaRef ?OK :put_set_value (fd ,cmd ,opt_idx ,varp ,value ); 5174optval_free_read (opt_idx ,value ); 5175return ret ; 5176} 5177 5178void * get_varp_scope_from (vimoption_T * p ,int opt_flags ,buf_T * buf ,win_T * win ) 5179{ 5180OptIndex opt_idx = get_opt_idx (p ); 5181 5182if ((opt_flags & OPT_GLOBAL )&& !option_is_global_only (opt_idx )) { 5183if (option_is_window_local (opt_idx )) { 5184return GLOBAL_WO (get_varp_from (p ,buf ,win )); 5185 } 5186return p -> var ; 5187 } 5188 5189if ((opt_flags & OPT_LOCAL )&& option_is_global_local (opt_idx )) { 5190switch (opt_idx ) { 5191case kOptFormatprg : 5192return & (buf -> b_p_fp ); 5193case kOptFsync : 5194return & (buf -> b_p_fs ); 5195case kOptFindfunc : 5196return & (buf -> b_p_ffu ); 5197case kOptErrorformat : 5198return & (buf -> b_p_efm ); 5199case kOptGrepformat : 5200return & (buf -> b_p_gefm ); 5201case kOptGrepprg : 5202return & (buf -> b_p_gp ); 5203case kOptMakeprg : 5204return & (buf -> b_p_mp ); 5205case kOptEqualprg : 5206return & (buf -> b_p_ep ); 5207case kOptKeywordprg : 5208return & (buf -> b_p_kp ); 5209case kOptPath : 5210return & (buf -> b_p_path ); 5211case kOptAutocomplete : 5212return & (buf -> b_p_ac ); 5213case kOptAutoread : 5214return & (buf -> b_p_ar ); 5215case kOptTags : 5216return & (buf -> b_p_tags ); 5217case kOptTagcase : 5218return & (buf -> b_p_tc ); 5219case kOptSidescrolloff : 5220return & (win -> w_p_siso ); 5221case kOptScrolloff : 5222return & (win -> w_p_so ); 5223case kOptScrolloffpad : 5224return & (win -> w_p_sop ); 5225case kOptDefine : 5226return & (buf -> b_p_def ); 5227case kOptInclude : 5228return & (buf -> b_p_inc ); 5229case kOptCompleteopt : 5230return & (buf -> b_p_cot ); 5231case kOptDictionary : 5232return & (buf -> b_p_dict ); 5233case kOptDiffanchors : 5234return & (buf -> b_p_dia ); 5235case kOptThesaurus : 5236return & (buf -> b_p_tsr ); 5237case kOptThesaurusfunc : 5238return & (buf -> b_p_tsrfu ); 5239case kOptTagfunc : 5240return & (buf -> b_p_tfu ); 5241case kOptShowbreak : 5242return & (win -> w_p_sbr ); 5243case kOptStatusline : 5244return & (win -> w_p_stl ); 5245case kOptWinbar : 5246return & (win -> w_p_wbr ); 5247case kOptUndolevels : 5248return & (buf -> b_p_ul ); 5249case kOptLispwords : 5250return & (buf -> b_p_lw ); 5251case kOptBackupcopy : 5252return & (buf -> b_p_bkc ); 5253case kOptMakeencoding : 5254return & (buf -> b_p_menc ); 5255case kOptFillchars : 5256return & (win -> w_p_fcs ); 5257case kOptListchars : 5258return & (win -> w_p_lcs ); 5259case kOptVirtualedit : 5260return & (win -> w_p_ve ); 5261default : 5262abort (); 5263 } 5264 } 5265return get_varp_from (p ,buf ,win ); 5266} 5267 5268/// Get pointer to option variable, depending on local or global scope. 5269/// 5270/// @param opt_flags Option flags (can be OPT_LOCAL, OPT_GLOBAL or a combination). 5271void * get_varp_scope (vimoption_T * p ,int opt_flags ) 5272{ 5273return get_varp_scope_from (p ,opt_flags ,curbuf ,curwin ); 5274} 5275 5276/// Get pointer to option variable at 'opt_idx', depending on local or global 5277/// scope. 5278void * get_option_varp_scope_from (OptIndex opt_idx ,int opt_flags ,buf_T * buf ,win_T * win ) 5279{ 5280return get_varp_scope_from (& (options [opt_idx ]),opt_flags ,buf ,win ); 5281} 5282 5283void * get_varp_from (vimoption_T * p ,buf_T * buf ,win_T * win ) 5284{ 5285OptIndex opt_idx = get_opt_idx (p ); 5286 5287// Hidden options and global-only options always use the same var pointer 5288if (is_option_hidden (opt_idx )|| option_is_global_only (opt_idx )) { 5289return p -> var ; 5290 } 5291 5292switch (opt_idx ) { 5293// global option with local value: use local value if it's been set 5294case kOptEqualprg : 5295return * buf -> b_p_ep != NUL ?& buf -> b_p_ep :p -> var ; 5296case kOptKeywordprg : 5297return * buf -> b_p_kp != NUL ?& buf -> b_p_kp :p -> var ; 5298case kOptPath : 5299return * buf -> b_p_path != NUL ?& (buf -> b_p_path ) :p -> var ; 5300case kOptAutocomplete : 5301return buf -> b_p_ac >=0 ?& (buf -> b_p_ac ) :p -> var ; 5302case kOptAutoread : 5303return buf -> b_p_ar >=0 ?& (buf -> b_p_ar ) :p -> var ; 5304case kOptTags : 5305return * buf -> b_p_tags != NUL ?& (buf -> b_p_tags ) :p -> var ; 5306case kOptTagcase : 5307return * buf -> b_p_tc != NUL ?& (buf -> b_p_tc ) :p -> var ; 5308case kOptSidescrolloff : 5309return win -> w_p_siso >=0 ?& (win -> w_p_siso ) :p -> var ; 5310case kOptScrolloff : 5311return win -> w_p_so >=0 ?& (win -> w_p_so ) :p -> var ; 5312case kOptScrolloffpad : 5313return win -> w_p_sop >=0 ?& (win -> w_p_sop ) :p -> var ; 5314case kOptBackupcopy : 5315return * buf -> b_p_bkc != NUL ?& (buf -> b_p_bkc ) :p -> var ; 5316case kOptDefine : 5317return * buf -> b_p_def != NUL ?& (buf -> b_p_def ) :p -> var ; 5318case kOptInclude : 5319return * buf -> b_p_inc != NUL ?& (buf -> b_p_inc ) :p -> var ; 5320case kOptCompleteopt : 5321return * buf -> b_p_cot != NUL ?& (buf -> b_p_cot ) :p -> var ; 5322case kOptDictionary : 5323return * buf -> b_p_dict != NUL ?& (buf -> b_p_dict ) :p -> var ; 5324case kOptDiffanchors : 5325return * buf -> b_p_dia != NUL ?& (buf -> b_p_dia ) :p -> var ; 5326case kOptThesaurus : 5327return * buf -> b_p_tsr != NUL ?& (buf -> b_p_tsr ) :p -> var ; 5328case kOptThesaurusfunc : 5329return buf -> b_p_tsrfu .type != kCallbackNone ?& (buf -> b_p_tsrfu ) :p -> var ; 5330case kOptFormatprg : 5331return * buf -> b_p_fp != NUL ?& (buf -> b_p_fp ) :p -> var ; 5332case kOptFsync : 5333return buf -> b_p_fs >=0 ?& (buf -> b_p_fs ) :p -> var ; 5334case kOptFindfunc : 5335return buf -> b_p_ffu .type != kCallbackNone ?& (buf -> b_p_ffu ) :p -> var ; 5336case kOptErrorformat : 5337return * buf -> b_p_efm != NUL ?& (buf -> b_p_efm ) :p -> var ; 5338case kOptGrepformat : 5339return * buf -> b_p_gefm != NUL ?& (buf -> b_p_gefm ) :p -> var ; 5340case kOptGrepprg : 5341return * buf -> b_p_gp != NUL ?& (buf -> b_p_gp ) :p -> var ; 5342case kOptMakeprg : 5343return * buf -> b_p_mp != NUL ?& (buf -> b_p_mp ) :p -> var ; 5344case kOptShowbreak : 5345return * win -> w_p_sbr != NUL ?& (win -> w_p_sbr ) :p -> var ; 5346case kOptStatusline : 5347return * win -> w_p_stl != NUL ?& (win -> w_p_stl ) :p -> var ; 5348case kOptWinbar : 5349return * win -> w_p_wbr != NUL ?& (win -> w_p_wbr ) :p -> var ; 5350case kOptUndolevels : 5351return buf -> b_p_ul != NO_LOCAL_UNDOLEVEL ?& (buf -> b_p_ul ) :p -> var ; 5352case kOptLispwords : 5353return * buf -> b_p_lw != NUL ?& (buf -> b_p_lw ) :p -> var ; 5354case kOptMakeencoding : 5355return * buf -> b_p_menc != NUL ?& (buf -> b_p_menc ) :p -> var ; 5356case kOptFillchars : 5357return * win -> w_p_fcs != NUL ?& (win -> w_p_fcs ) :p -> var ; 5358case kOptListchars : 5359return * win -> w_p_lcs != NUL ?& (win -> w_p_lcs ) :p -> var ; 5360case kOptVirtualedit : 5361return * win -> w_p_ve != NUL ?& win -> w_p_ve :p -> var ; 5362 5363case kOptArabic : 5364return & (win -> w_p_arab ); 5365case kOptList : 5366return & (win -> w_p_list ); 5367case kOptSpell : 5368return & (win -> w_p_spell ); 5369case kOptCursorcolumn : 5370return & (win -> w_p_cuc ); 5371case kOptCursorline : 5372return & (win -> w_p_cul ); 5373case kOptCursorlineopt : 5374return & (win -> w_p_culopt ); 5375case kOptColorcolumn : 5376return & (win -> w_p_cc ); 5377case kOptDiff : 5378return & (win -> w_p_diff ); 5379case kOptEventignorewin : 5380return & (win -> w_p_eiw ); 5381case kOptFoldcolumn : 5382return & (win -> w_p_fdc ); 5383case kOptFoldenable : 5384return & (win -> w_p_fen ); 5385case kOptFoldignore : 5386return & (win -> w_p_fdi ); 5387case kOptFoldlevel : 5388return & (win -> w_p_fdl ); 5389case kOptFoldmethod : 5390return & (win -> w_p_fdm ); 5391case kOptFoldminlines : 5392return & (win -> w_p_fml ); 5393case kOptFoldnestmax : 5394return & (win -> w_p_fdn ); 5395case kOptFoldexpr : 5396return & (win -> w_p_fde ); 5397case kOptFoldtext : 5398return & (win -> w_p_fdt ); 5399case kOptFoldmarker : 5400return & (win -> w_p_fmr ); 5401case kOptNumber : 5402return & (win -> w_p_nu ); 5403case kOptRelativenumber : 5404return & (win -> w_p_rnu ); 5405case kOptNumberwidth : 5406return & (win -> w_p_nuw ); 5407case kOptWinfixbuf : 5408return & (win -> w_p_wfb ); 5409case kOptWinfixheight : 5410return & (win -> w_p_wfh ); 5411case kOptWinfixwidth : 5412return & (win -> w_p_wfw ); 5413case kOptWinpinned : 5414return & (win -> w_p_wp ); 5415case kOptPreviewwindow : 5416return & (win -> w_p_pvw ); 5417case kOptLhistory : 5418return & (win -> w_p_lhi ); 5419case kOptRightleft : 5420return & (win -> w_p_rl ); 5421case kOptRightleftcmd : 5422return & (win -> w_p_rlc ); 5423case kOptScroll : 5424return & (win -> w_p_scr ); 5425case kOptSmoothscroll : 5426return & (win -> w_p_sms ); 5427case kOptWrap : 5428return & (win -> w_p_wrap ); 5429case kOptLinebreak : 5430return & (win -> w_p_lbr ); 5431case kOptBreakindent : 5432return & (win -> w_p_bri ); 5433case kOptBreakindentopt : 5434return & (win -> w_p_briopt ); 5435case kOptScrollbind : 5436return & (win -> w_p_scb ); 5437case kOptCursorbind : 5438return & (win -> w_p_crb ); 5439case kOptConcealcursor : 5440return & (win -> w_p_cocu ); 5441case kOptConceallevel : 5442return & (win -> w_p_cole ); 5443 5444case kOptAutoindent : 5445return & (buf -> b_p_ai ); 5446case kOptBinary : 5447return & (buf -> b_p_bin ); 5448case kOptBomb : 5449return & (buf -> b_p_bomb ); 5450case kOptBufhidden : 5451return & (buf -> b_p_bh ); 5452case kOptBuftype : 5453return & (buf -> b_p_bt ); 5454case kOptBuflisted : 5455return & (buf -> b_p_bl ); 5456case kOptBusy : 5457return & (buf -> b_p_busy ); 5458case kOptChannel : 5459return & (buf -> b_p_channel ); 5460case kOptCopyindent : 5461return & (buf -> b_p_ci ); 5462case kOptCindent : 5463return & (buf -> b_p_cin ); 5464case kOptCinkeys : 5465return & (buf -> b_p_cink ); 5466case kOptCinoptions : 5467return & (buf -> b_p_cino ); 5468case kOptCinscopedecls : 5469return & (buf -> b_p_cinsd ); 5470case kOptCinwords : 5471return & (buf -> b_p_cinw ); 5472case kOptComments : 5473return & (buf -> b_p_com ); 5474case kOptCommentstring : 5475return & (buf -> b_p_cms ); 5476case kOptComplete : 5477return & (buf -> b_p_cpt ); 5478#ifdef BACKSLASH_IN_FILENAME 5479case kOptCompleteslash : 5480return & (buf -> b_p_csl ); 5481#endif 5482case kOptCompletefunc : 5483return & (buf -> b_p_cfu ); 5484case kOptOmnifunc : 5485return & (buf -> b_p_ofu ); 5486case kOptEndoffile : 5487return & (buf -> b_p_eof ); 5488case kOptEndofline : 5489return & (buf -> b_p_eol ); 5490case kOptFixendofline : 5491return & (buf -> b_p_fixeol ); 5492case kOptExpandtab : 5493return & (buf -> b_p_et ); 5494case kOptFileencoding : 5495return & (buf -> b_p_fenc ); 5496case kOptFileformat : 5497return & (buf -> b_p_ff ); 5498case kOptFiletype : 5499return & (buf -> b_p_ft ); 5500case kOptFollow : 5501return & (buf -> b_p_follow ); 5502case kOptFormatoptions : 5503return & (buf -> b_p_fo ); 5504case kOptFormatlistpat : 5505return & (buf -> b_p_flp ); 5506case kOptIminsert : 5507return & (buf -> b_p_iminsert ); 5508case kOptImsearch : 5509return & (buf -> b_p_imsearch ); 5510case kOptInfercase : 5511return & (buf -> b_p_inf ); 5512case kOptIskeyword : 5513return & (buf -> b_p_isk ); 5514case kOptIncludeexpr : 5515return & (buf -> b_p_inex ); 5516case kOptIndentexpr : 5517return & (buf -> b_p_inde ); 5518case kOptIndentkeys : 5519return & (buf -> b_p_indk ); 5520case kOptFormatexpr : 5521return & (buf -> b_p_fex ); 5522case kOptLisp : 5523return & (buf -> b_p_lisp ); 5524case kOptLispoptions : 5525return & (buf -> b_p_lop ); 5526case kOptModeline : 5527return & (buf -> b_p_ml ); 5528case kOptMatchpairs : 5529return & (buf -> b_p_mps ); 5530case kOptModifiable : 5531return & (buf -> b_p_ma ); 5532case kOptModified : 5533return & (buf -> b_changed ); 5534case kOptNrformats : 5535return & (buf -> b_p_nf ); 5536case kOptPreserveindent : 5537return & (buf -> b_p_pi ); 5538case kOptQuoteescape : 5539return & (buf -> b_p_qe ); 5540case kOptReadonly : 5541return & (buf -> b_p_ro ); 5542case kOptScrollback : 5543return & (buf -> b_p_scbk ); 5544case kOptSmartindent : 5545return & (buf -> b_p_si ); 5546case kOptSofttabstop : 5547return & (buf -> b_p_sts ); 5548case kOptSuffixesadd : 5549return & (buf -> b_p_sua ); 5550case kOptSwapfile : 5551return & (buf -> b_p_swf ); 5552case kOptSynmaxcol : 5553return & (buf -> b_p_smc ); 5554case kOptSyntax : 5555return & (buf -> b_p_syn ); 5556case kOptSpellcapcheck : 5557return & (win -> w_s -> b_p_spc ); 5558case kOptSpellfile : 5559return & (win -> w_s -> b_p_spf ); 5560case kOptSpelllang : 5561return & (win -> w_s -> b_p_spl ); 5562case kOptSpelloptions : 5563return & (win -> w_s -> b_p_spo ); 5564case kOptShiftwidth : 5565return & (buf -> b_p_sw ); 5566case kOptTagfunc : 5567return & (buf -> b_p_tfu ); 5568case kOptTabstop : 5569return & (buf -> b_p_ts ); 5570case kOptTextwidth : 5571return & (buf -> b_p_tw ); 5572case kOptUndofile : 5573return & (buf -> b_p_udf ); 5574case kOptWrapmargin : 5575return & (buf -> b_p_wm ); 5576case kOptVarsofttabstop : 5577return & (buf -> b_p_vsts ); 5578case kOptVartabstop : 5579return & (buf -> b_p_vts ); 5580case kOptKeymap : 5581return & (buf -> b_p_keymap ); 5582case kOptSigncolumn : 5583return & (win -> w_p_scl ); 5584case kOptWinhighlight : 5585return & (win -> w_p_winhl ); 5586case kOptWinblend : 5587return & (win -> w_p_winbl ); 5588case kOptStatuscolumn : 5589return & (win -> w_p_stc ); 5590default : 5591iemsg (_ ("E356: get_varp ERROR" )); 5592 } 5593// always return a valid pointer to avoid a crash! 5594return & (buf -> b_p_wm ); 5595} 5596 5597/// Get option index from option pointer 5598static inline OptIndex get_opt_idx (vimoption_T * opt ) 5599FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE 5600{ 5601return (OptIndex )(opt - options ); 5602} 5603 5604/// Get pointer to option variable. 5605static inline void * get_varp (vimoption_T * p ) 5606{ 5607return get_varp_from (p ,curbuf ,curwin ); 5608} 5609 5610/// Get the value of 'equalprg', either the buffer-local one or the global one. 5611char * get_equalprg (void ) 5612{ 5613if (* curbuf -> b_p_ep == NUL ) { 5614return p_ep ; 5615 } 5616return curbuf -> b_p_ep ; 5617} 5618 5619/// Get the value of 'findfunc', either the buffer-local one or the global one. 5620/// Returns the effective 'findfunc' callback: the buffer-local one if set, else the global one. 5621Callback * get_findfunc (void ) 5622{ 5623return curbuf -> b_p_ffu .type != kCallbackNone ?& curbuf -> b_p_ffu :& p_ffu ; 5624} 5625 5626/// Copy options from one window to another. 5627/// Used when splitting a window. 5628void win_copy_options (win_T * wp_from ,win_T * wp_to ) 5629{ 5630copy_winopt (& wp_from -> w_onebuf_opt ,& wp_to -> w_onebuf_opt ); 5631copy_winopt (& wp_from -> w_allbuf_opt ,& wp_to -> w_allbuf_opt ); 5632didset_window_options (wp_to , true); 5633} 5634 5635static char * copy_option_val (const char * val ) 5636{ 5637if (val == empty_string_option ) { 5638return empty_string_option ;// no need to allocate memory 5639 } 5640return xstrdup (val ); 5641} 5642 5643/// Copy the options from one winopt_T to another. 5644/// Doesn't free the old option values in "to", use clear_winopt() for that. 5645/// The 'scroll' option is not copied, because it depends on the window height. 5646/// The 'previewwindow' option is reset, there can be only one preview window. 5647void copy_winopt (winopt_T * from ,winopt_T * to ) 5648{ 5649to -> wo_arab = from -> wo_arab ; 5650to -> wo_list = from -> wo_list ; 5651to -> wo_lcs = copy_option_val (from -> wo_lcs ); 5652to -> wo_fcs = copy_option_val (from -> wo_fcs ); 5653to -> wo_nu = from -> wo_nu ; 5654to -> wo_rnu = from -> wo_rnu ; 5655to -> wo_ve = copy_option_val (from -> wo_ve ); 5656to -> wo_ve_flags = from -> wo_ve_flags ; 5657to -> wo_nuw = from -> wo_nuw ; 5658to -> wo_rl = from -> wo_rl ; 5659to -> wo_rlc = copy_option_val (from -> wo_rlc ); 5660to -> wo_sbr = copy_option_val (from -> wo_sbr ); 5661to -> wo_stl = copy_option_val (from -> wo_stl ); 5662to -> wo_wbr = copy_option_val (from -> wo_wbr ); 5663to -> wo_wrap = from -> wo_wrap ; 5664to -> wo_wrap_save = from -> wo_wrap_save ; 5665to -> wo_lbr = from -> wo_lbr ; 5666to -> wo_bri = from -> wo_bri ; 5667to -> wo_briopt = copy_option_val (from -> wo_briopt ); 5668to -> wo_scb = from -> wo_scb ; 5669to -> wo_scb_save = from -> wo_scb_save ; 5670to -> wo_sms = from -> wo_sms ; 5671to -> wo_crb = from -> wo_crb ; 5672to -> wo_crb_save = from -> wo_crb_save ; 5673to -> wo_siso = from -> wo_siso ; 5674to -> wo_so = from -> wo_so ; 5675to -> wo_sop = from -> wo_sop ; 5676to -> wo_spell = from -> wo_spell ; 5677to -> wo_cuc = from -> wo_cuc ; 5678to -> wo_cul = from -> wo_cul ; 5679to -> wo_culopt = copy_option_val (from -> wo_culopt ); 5680to -> wo_cc = copy_option_val (from -> wo_cc ); 5681to -> wo_diff = from -> wo_diff ; 5682to -> wo_diff_saved = from -> wo_diff_saved ; 5683to -> wo_eiw = copy_option_val (from -> wo_eiw ); 5684to -> wo_cocu = copy_option_val (from -> wo_cocu ); 5685to -> wo_cole = from -> wo_cole ; 5686to -> wo_fdc = copy_option_val (from -> wo_fdc ); 5687to -> wo_fdc_save = from -> wo_diff_saved ?xstrdup (from -> wo_fdc_save ) :empty_string_option ; 5688to -> wo_fen = from -> wo_fen ; 5689to -> wo_fen_save = from -> wo_fen_save ; 5690to -> wo_fdi = copy_option_val (from -> wo_fdi ); 5691to -> wo_fml = from -> wo_fml ; 5692to -> wo_fdl = from -> wo_fdl ; 5693to -> wo_fdl_save = from -> wo_fdl_save ; 5694to -> wo_fdm = copy_option_val (from -> wo_fdm ); 5695to -> wo_fdm_save = from -> wo_diff_saved ?xstrdup (from -> wo_fdm_save ) :empty_string_option ; 5696to -> wo_fdn = from -> wo_fdn ; 5697callback_copy (& to -> wo_fde ,& from -> wo_fde ); 5698callback_copy (& to -> wo_fdt ,& from -> wo_fdt ); 5699to -> wo_fmr = copy_option_val (from -> wo_fmr ); 5700to -> wo_scl = copy_option_val (from -> wo_scl ); 5701to -> wo_lhi = from -> wo_lhi ; 5702to -> wo_winhl = copy_option_val (from -> wo_winhl ); 5703to -> wo_winbl = from -> wo_winbl ; 5704to -> wo_stc = copy_option_val (from -> wo_stc ); 5705 5706to -> wo_wrap_flags = from -> wo_wrap_flags ; 5707to -> wo_stl_flags = from -> wo_stl_flags ; 5708to -> wo_wbr_flags = from -> wo_wbr_flags ; 5709to -> wo_fde_flags = from -> wo_fde_flags ; 5710to -> wo_fdt_flags = from -> wo_fdt_flags ; 5711 5712// Copy the script context so that we know were the value was last set. 5713memmove (to -> wo_script_ctx ,from -> wo_script_ctx ,sizeof (to -> wo_script_ctx )); 5714check_winopt (to );// don't want NULL pointers 5715} 5716 5717/// Check string options in a window for a NULL value. 5718static void check_win_options (win_T * win ) 5719{ 5720check_winopt (& win -> w_onebuf_opt ); 5721check_winopt (& win -> w_allbuf_opt ); 5722} 5723 5724/// Check for NULL pointers in a winopt_T and replace them with empty_string_option. 5725static void check_winopt (winopt_T * wop ) 5726{ 5727check_string_option (& wop -> wo_fdc ); 5728check_string_option (& wop -> wo_fdc_save ); 5729check_string_option (& wop -> wo_fdi ); 5730check_string_option (& wop -> wo_fdm ); 5731check_string_option (& wop -> wo_fdm_save ); 5732check_string_option (& wop -> wo_fmr ); 5733check_string_option (& wop -> wo_eiw ); 5734check_string_option (& wop -> wo_scl ); 5735check_string_option (& wop -> wo_rlc ); 5736check_string_option (& wop -> wo_sbr ); 5737check_string_option (& wop -> wo_stl ); 5738check_string_option (& wop -> wo_culopt ); 5739check_string_option (& wop -> wo_cc ); 5740check_string_option (& wop -> wo_cocu ); 5741check_string_option (& wop -> wo_briopt ); 5742check_string_option (& wop -> wo_winhl ); 5743check_string_option (& wop -> wo_lcs ); 5744check_string_option (& wop -> wo_fcs ); 5745check_string_option (& wop -> wo_ve ); 5746check_string_option (& wop -> wo_wbr ); 5747check_string_option (& wop -> wo_stc ); 5748} 5749 5750/// Free the allocated memory inside a winopt_T. 5751void clear_winopt (winopt_T * wop ) 5752{ 5753clear_string_option (& wop -> wo_fdc ); 5754clear_string_option (& wop -> wo_fdc_save ); 5755clear_string_option (& wop -> wo_fdi ); 5756clear_string_option (& wop -> wo_fdm ); 5757clear_string_option (& wop -> wo_fdm_save ); 5758callback_free (& wop -> wo_fde ); 5759callback_free (& wop -> wo_fdt ); 5760clear_string_option (& wop -> wo_fmr ); 5761clear_string_option (& wop -> wo_eiw ); 5762clear_string_option (& wop -> wo_scl ); 5763clear_string_option (& wop -> wo_rlc ); 5764clear_string_option (& wop -> wo_sbr ); 5765clear_string_option (& wop -> wo_stl ); 5766clear_string_option (& wop -> wo_culopt ); 5767clear_string_option (& wop -> wo_cc ); 5768clear_string_option (& wop -> wo_cocu ); 5769clear_string_option (& wop -> wo_briopt ); 5770clear_string_option (& wop -> wo_winhl ); 5771clear_string_option (& wop -> wo_lcs ); 5772clear_string_option (& wop -> wo_fcs ); 5773clear_string_option (& wop -> wo_ve ); 5774clear_string_option (& wop -> wo_wbr ); 5775clear_string_option (& wop -> wo_stc ); 5776} 5777 5778void didset_window_options (win_T * wp ,bool valid_cursor ) 5779{ 5780// Set w_leftcol or w_skipcol to zero. 5781if (wp -> w_p_wrap ) { 5782wp -> w_leftcol = 0 ; 5783 }else { 5784wp -> w_skipcol = 0 ; 5785 } 5786check_colorcolumn (NULL ,wp ); 5787briopt_check (wp ); 5788fill_culopt_flags (NULL ,wp ); 5789set_chars_option (wp ,wp -> w_p_fcs ,kFillchars , true,NULL ); 5790set_chars_option (wp ,wp -> w_p_lcs ,kListchars , true,NULL ); 5791parse_winhl_opt (NULL ,wp );// sets w_hl_needs_update also for w_p_winbl 5792check_blending (wp ); 5793set_winbar_win (wp , false,valid_cursor ); 5794check_signcolumn (NULL ,wp ); 5795wp -> w_grid_alloc .blending = wp -> w_p_winbl > 0 ; 5796} 5797 5798#define COPY_OPT_SCTX (buf ,bv ) buf->b_p_script_ctx[bv] = options[buf_opt_idx[bv]].script_ctx 5799#define COPY_OPT_INSECURE (flagsfield ,bv ) \ 5800 (flagsfield) = (options[buf_opt_idx[bv]].flags & kOptFlagInsecure) 5801 5802/// Copy global option values to local options for one buffer. 5803/// Used when creating a new buffer and sometimes when entering a buffer. 5804/// flags: 5805/// BCO_ENTER We will enter the buffer "buf". 5806/// BCO_ALWAYS Always copy the options, but only set b_p_initialized when 5807/// appropriate. 5808/// BCO_NOHELP Don't copy the values to a help buffer. 5809void buf_copy_options (buf_T * buf ,int flags ) 5810{ 5811bool should_copy = true; 5812char * save_p_isk = NULL ;// init for GCC 5813bool did_isk = false; 5814 5815// Skip this when the option defaults have not been set yet. Happens when 5816// main() allocates the first buffer. 5817if (p_cpo != NULL ) { 5818// 5819// Always copy when entering and 'cpo' contains 'S'. 5820// Don't copy when already initialized. 5821// Don't copy when 'cpo' contains 's' and not entering. 5822// 'S' BCO_ENTER initialized 's' should_copy 5823// yes yes X X true 5824// yes no yes X false 5825// no X yes X false 5826// X no no yes false 5827// X no no no true 5828// no yes no X true 5829/// 5830if ((vim_strchr (p_cpo ,kCpoBufoptglob )== NULL || !(flags & BCO_ENTER )) 5831&& (buf -> b_p_initialized 5832|| (!(flags & BCO_ENTER ) 5833&& vim_strchr (p_cpo ,kCpoBufopt )!= NULL ))) { 5834should_copy = false; 5835 } 5836 5837if (should_copy || (flags & BCO_ALWAYS )) { 5838CLEAR_FIELD (buf -> b_p_script_ctx ); 5839// Don't copy the options specific to a help buffer when 5840// BCO_NOHELP is given or the options were initialized already 5841// (jumping back to a help file with CTRL-T or CTRL-O) 5842bool dont_do_help = ((flags & BCO_NOHELP )&& buf -> b_help )|| buf -> b_p_initialized ; 5843if (dont_do_help ) {// don't free b_p_isk 5844save_p_isk = buf -> b_p_isk ; 5845buf -> b_p_isk = NULL ; 5846 } 5847// Always free the allocated strings. If not already initialized, 5848// reset 'readonly' and copy 'fileformat'. 5849if (!buf -> b_p_initialized ) { 5850free_buf_options (buf , true); 5851buf -> b_p_ro = false;// don't copy readonly 5852buf -> b_p_fenc = xstrdup (p_fenc ); 5853switch (* p_ffs ) { 5854case 'm' : 5855buf -> b_p_ff = xstrdup ("mac" ); 5856break ; 5857case 'd' : 5858buf -> b_p_ff = xstrdup ("dos" ); 5859break ; 5860case 'u' : 5861buf -> b_p_ff = xstrdup ("unix" ); 5862break ; 5863default : 5864buf -> b_p_ff = xstrdup (p_ff ); 5865break ; 5866 } 5867buf -> b_p_bh = empty_string_option ; 5868buf -> b_p_bt = empty_string_option ; 5869 }else { 5870free_buf_options (buf , false); 5871 } 5872 5873buf -> b_p_ai = p_ai ; 5874COPY_OPT_SCTX (buf ,kBufOptAutoindent ); 5875buf -> b_p_ai_nopaste = p_ai_nopaste ; 5876buf -> b_p_sw = p_sw ; 5877COPY_OPT_SCTX (buf ,kBufOptShiftwidth ); 5878buf -> b_p_scbk = p_scbk ; 5879COPY_OPT_SCTX (buf ,kBufOptScrollback ); 5880buf -> b_p_tw = p_tw ; 5881COPY_OPT_SCTX (buf ,kBufOptTextwidth ); 5882buf -> b_p_tw_nopaste = p_tw_nopaste ; 5883buf -> b_p_tw_nobin = p_tw_nobin ; 5884buf -> b_p_wm = p_wm ; 5885COPY_OPT_SCTX (buf ,kBufOptWrapmargin ); 5886buf -> b_p_wm_nopaste = p_wm_nopaste ; 5887buf -> b_p_wm_nobin = p_wm_nobin ; 5888buf -> b_p_bin = p_bin ; 5889COPY_OPT_SCTX (buf ,kBufOptBinary ); 5890buf -> b_p_bomb = p_bomb ; 5891COPY_OPT_SCTX (buf ,kBufOptBomb ); 5892buf -> b_p_et = p_et ; 5893COPY_OPT_SCTX (buf ,kBufOptExpandtab ); 5894buf -> b_p_fixeol = p_fixeol ; 5895COPY_OPT_SCTX (buf ,kBufOptFixendofline ); 5896buf -> b_p_follow = p_follow ; 5897COPY_OPT_SCTX (buf ,kBufOptFollow ); 5898buf -> b_p_et_nobin = p_et_nobin ; 5899buf -> b_p_et_nopaste = p_et_nopaste ; 5900buf -> b_p_ml = p_ml ; 5901COPY_OPT_SCTX (buf ,kBufOptModeline ); 5902buf -> b_p_ml_nobin = p_ml_nobin ; 5903buf -> b_p_inf = p_inf ; 5904COPY_OPT_SCTX (buf ,kBufOptInfercase ); 5905if (cmdmod .cmod_flags & CMOD_NOSWAPFILE ) { 5906buf -> b_p_swf = false; 5907 }else { 5908buf -> b_p_swf = p_swf ; 5909COPY_OPT_SCTX (buf ,kBufOptSwapfile ); 5910 } 5911buf -> b_p_cpt = xstrdup (p_cpt ); 5912COPY_OPT_SCTX (buf ,kBufOptComplete ); 5913COPY_OPT_INSECURE (buf -> b_p_cpt_flags ,kBufOptComplete ); 5914set_buflocal_cpt_callbacks (buf ); 5915#ifdef BACKSLASH_IN_FILENAME 5916buf -> b_p_csl = xstrdup (p_csl ); 5917COPY_OPT_SCTX (buf ,kBufOptCompleteslash ); 5918#endif 5919callback_copy (& buf -> b_p_cfu ,& p_cfu ); 5920COPY_OPT_SCTX (buf ,kBufOptCompletefunc ); 5921callback_copy (& buf -> b_p_ofu ,& p_ofu ); 5922COPY_OPT_SCTX (buf ,kBufOptOmnifunc ); 5923callback_copy (& buf -> b_p_tfu ,& p_tfu ); 5924COPY_OPT_SCTX (buf ,kBufOptTagfunc ); 5925buf -> b_p_sts = p_sts ; 5926COPY_OPT_SCTX (buf ,kBufOptSofttabstop ); 5927buf -> b_p_sts_nopaste = p_sts_nopaste ; 5928buf -> b_p_vsts = xstrdup (p_vsts ); 5929COPY_OPT_SCTX (buf ,kBufOptVarsofttabstop ); 5930if (p_vsts && p_vsts != empty_string_option ) { 5931tabstop_set (p_vsts ,& buf -> b_p_vsts_array ); 5932 }else { 5933buf -> b_p_vsts_array = NULL ; 5934 } 5935buf -> b_p_vsts_nopaste = p_vsts_nopaste ?xstrdup (p_vsts_nopaste ) :NULL ; 5936buf -> b_p_com = xstrdup (p_com ); 5937COPY_OPT_SCTX (buf ,kBufOptComments ); 5938buf -> b_p_cms = xstrdup (p_cms ); 5939COPY_OPT_SCTX (buf ,kBufOptCommentstring ); 5940buf -> b_p_fo = xstrdup (p_fo ); 5941COPY_OPT_SCTX (buf ,kBufOptFormatoptions ); 5942buf -> b_p_flp = xstrdup (p_flp ); 5943COPY_OPT_SCTX (buf ,kBufOptFormatlistpat ); 5944buf -> b_p_nf = xstrdup (p_nf ); 5945COPY_OPT_SCTX (buf ,kBufOptNrformats ); 5946buf -> b_p_mps = xstrdup (p_mps ); 5947COPY_OPT_SCTX (buf ,kBufOptMatchpairs ); 5948buf -> b_p_si = p_si ; 5949COPY_OPT_SCTX (buf ,kBufOptSmartindent ); 5950buf -> b_p_channel = 0 ; 5951buf -> b_p_ci = p_ci ; 5952 5953COPY_OPT_SCTX (buf ,kBufOptCopyindent ); 5954buf -> b_p_cin = p_cin ; 5955COPY_OPT_SCTX (buf ,kBufOptCindent ); 5956buf -> b_p_cink = xstrdup (p_cink ); 5957COPY_OPT_SCTX (buf ,kBufOptCinkeys ); 5958buf -> b_p_cino = xstrdup (p_cino ); 5959COPY_OPT_SCTX (buf ,kBufOptCinoptions ); 5960buf -> b_p_cinsd = xstrdup (p_cinsd ); 5961COPY_OPT_SCTX (buf ,kBufOptCinscopedecls ); 5962buf -> b_p_lop = xstrdup (p_lop ); 5963COPY_OPT_SCTX (buf ,kBufOptLispoptions ); 5964 5965// Don't copy 'filetype', it must be detected 5966buf -> b_p_ft = empty_string_option ; 5967buf -> b_p_pi = p_pi ; 5968COPY_OPT_SCTX (buf ,kBufOptPreserveindent ); 5969buf -> b_p_cinw = xstrdup (p_cinw ); 5970COPY_OPT_SCTX (buf ,kBufOptCinwords ); 5971buf -> b_p_lisp = p_lisp ; 5972COPY_OPT_SCTX (buf ,kBufOptLisp ); 5973// Don't copy 'syntax', it must be set 5974buf -> b_p_syn = empty_string_option ; 5975buf -> b_p_smc = p_smc ; 5976COPY_OPT_SCTX (buf ,kBufOptSynmaxcol ); 5977buf -> b_s .b_syn_isk = empty_string_option ; 5978buf -> b_s .b_p_spc = xstrdup (p_spc ); 5979COPY_OPT_SCTX (buf ,kBufOptSpellcapcheck ); 5980compile_cap_prog (& buf -> b_s ); 5981buf -> b_s .b_p_spf = xstrdup (p_spf ); 5982COPY_OPT_SCTX (buf ,kBufOptSpellfile ); 5983buf -> b_s .b_p_spl = xstrdup (p_spl ); 5984COPY_OPT_SCTX (buf ,kBufOptSpelllang ); 5985buf -> b_s .b_p_spo = xstrdup (p_spo ); 5986COPY_OPT_SCTX (buf ,kBufOptSpelloptions ); 5987buf -> b_s .b_p_spo_flags = spo_flags ; 5988callback_copy (& buf -> b_p_inde ,& p_inde ); 5989COPY_OPT_SCTX (buf ,kBufOptIndentexpr ); 5990COPY_OPT_INSECURE (buf -> b_p_inde_flags ,kBufOptIndentexpr ); 5991buf -> b_p_indk = xstrdup (p_indk ); 5992COPY_OPT_SCTX (buf ,kBufOptIndentkeys ); 5993buf -> b_p_fp = empty_string_option ; 5994callback_copy (& buf -> b_p_fex ,& p_fex ); 5995COPY_OPT_SCTX (buf ,kBufOptFormatexpr ); 5996COPY_OPT_INSECURE (buf -> b_p_fex_flags ,kBufOptFormatexpr ); 5997buf -> b_p_sua = xstrdup (p_sua ); 5998COPY_OPT_SCTX (buf ,kBufOptSuffixesadd ); 5999buf -> b_p_keymap = xstrdup (p_keymap ); 6000COPY_OPT_SCTX (buf ,kBufOptKeymap ); 6001buf -> b_kmap_state |=KEYMAP_INIT ; 6002// This isn't really an option, but copying the langmap and IME 6003// state from the current buffer is better than resetting it. 6004buf -> b_p_iminsert = p_iminsert ; 6005COPY_OPT_SCTX (buf ,kBufOptIminsert ); 6006buf -> b_p_imsearch = p_imsearch ; 6007COPY_OPT_SCTX (buf ,kBufOptImsearch ); 6008 6009// options that are normally global but also have a local value 6010// are not copied, start using the global value 6011buf -> b_p_ac = -1 ; 6012buf -> b_p_ar = -1 ; 6013buf -> b_p_fs = -1 ; 6014buf -> b_p_ul = NO_LOCAL_UNDOLEVEL ; 6015buf -> b_p_bkc = empty_string_option ; 6016buf -> b_bkc_flags = 0 ; 6017buf -> b_p_gefm = empty_string_option ; 6018buf -> b_p_gp = empty_string_option ; 6019buf -> b_p_mp = empty_string_option ; 6020buf -> b_p_efm = empty_string_option ; 6021buf -> b_p_ep = empty_string_option ; 6022buf -> b_p_ffu = CALLBACK_NONE ; 6023buf -> b_p_kp = empty_string_option ; 6024buf -> b_p_path = empty_string_option ; 6025buf -> b_p_tags = empty_string_option ; 6026buf -> b_p_tc = empty_string_option ; 6027buf -> b_tc_flags = 0 ; 6028buf -> b_p_def = empty_string_option ; 6029buf -> b_p_inc = empty_string_option ; 6030callback_copy (& buf -> b_p_inex ,& p_inex ); 6031COPY_OPT_SCTX (buf ,kBufOptIncludeexpr ); 6032COPY_OPT_INSECURE (buf -> b_p_inex_flags ,kBufOptIncludeexpr ); 6033buf -> b_p_cot = empty_string_option ; 6034buf -> b_cot_flags = 0 ; 6035buf -> b_p_dict = empty_string_option ; 6036buf -> b_p_dia = empty_string_option ; 6037buf -> b_p_tsr = empty_string_option ; 6038buf -> b_p_tsrfu = CALLBACK_NONE ; 6039buf -> b_p_qe = xstrdup (p_qe ); 6040COPY_OPT_SCTX (buf ,kBufOptQuoteescape ); 6041buf -> b_p_udf = p_udf ; 6042COPY_OPT_SCTX (buf ,kBufOptUndofile ); 6043buf -> b_p_lw = empty_string_option ; 6044buf -> b_p_menc = empty_string_option ; 6045 6046// Don't copy the options set by ex_help(), use the saved values, 6047// when going from a help buffer to a non-help buffer. 6048// Don't touch these at all when BCO_NOHELP is used and going from 6049// or to a help buffer. 6050if (dont_do_help ) { 6051buf -> b_p_isk = save_p_isk ; 6052if (p_vts && * p_vts != NUL && !buf -> b_p_vts_array ) { 6053tabstop_set (p_vts ,& buf -> b_p_vts_array ); 6054 }else { 6055buf -> b_p_vts_array = NULL ; 6056 } 6057 }else { 6058buf -> b_p_isk = xstrdup (p_isk ); 6059COPY_OPT_SCTX (buf ,kBufOptIskeyword ); 6060did_isk = true; 6061buf -> b_p_ts = p_ts ; 6062COPY_OPT_SCTX (buf ,kBufOptTabstop ); 6063buf -> b_p_vts = xstrdup (p_vts ); 6064COPY_OPT_SCTX (buf ,kBufOptVartabstop ); 6065if (p_vts && * p_vts != NUL && !buf -> b_p_vts_array ) { 6066tabstop_set (p_vts ,& buf -> b_p_vts_array ); 6067 }else { 6068buf -> b_p_vts_array = NULL ; 6069 } 6070buf -> b_help = false; 6071if (buf -> b_p_bt [0 ]== 'h' ) { 6072clear_string_option (& buf -> b_p_bt ); 6073 } 6074buf -> b_p_ma = p_ma ; 6075COPY_OPT_SCTX (buf ,kBufOptModifiable ); 6076 } 6077 } 6078 6079// When the options should be copied (ignoring BCO_ALWAYS), set the 6080// flag that indicates that the options have been initialized. 6081if (should_copy ) { 6082buf -> b_p_initialized = true; 6083 } 6084 } 6085 6086check_buf_options (buf );// make sure we don't have NULLs 6087if (did_isk ) { 6088buf_init_isk_chartab (buf ); 6089 } 6090} 6091 6092/// Reset the 'modifiable' option and its default value. 6093void reset_modifiable (void ) 6094{ 6095curbuf -> b_p_ma = false; 6096p_ma = false; 6097change_option_default (kOptModifiable ,BOOLEAN_OBJ (false)); 6098} 6099 6100/// Set the global value for 'iminsert' to the local value. 6101void set_iminsert_global (buf_T * buf ) 6102{ 6103p_iminsert = buf -> b_p_iminsert ; 6104} 6105 6106/// Set the global value for 'imsearch' to the local value. 6107void set_imsearch_global (buf_T * buf ) 6108{ 6109p_imsearch = buf -> b_p_imsearch ; 6110} 6111 6112static OptIndex expand_option_idx = kOptInvalid ; 6113static int expand_option_start_col = 0 ; 6114static char expand_option_name [5 ]= {'t' ,'_' ,NUL ,NUL ,NUL }; 6115static int expand_option_flags = 0 ; 6116static bool expand_option_append = false; 6117 6118/// @param opt_flags Option flags (can be OPT_LOCAL, OPT_GLOBAL or a combination). 6119void set_context_in_set_cmd (expand_T * xp ,char * arg ,int opt_flags ) 6120{ 6121expand_option_flags = opt_flags ; 6122 6123xp -> xp_context = EXPAND_SETTINGS ; 6124if (* arg == NUL ) { 6125xp -> xp_pattern = arg ; 6126return ; 6127 } 6128char * const argend = arg + strlen (arg ); 6129char * p = argend - 1 ; 6130if (* p == ' ' && * (p - 1 )!= '\\' ) { 6131xp -> xp_pattern = p + 1 ; 6132return ; 6133 } 6134while (p > arg ) { 6135char * s = p ; 6136// count number of backslashes before ' ' or ',' 6137if (* p == ' ' || * p == ',' ) { 6138while (s > arg && * (s - 1 )== '\\' ) { 6139s -- ; 6140 } 6141 } 6142// break at a space with an even number of backslashes 6143if (* p == ' ' && ((p - s )& 1 )== 0 ) { 6144p ++ ; 6145break ; 6146 } 6147p -- ; 6148 } 6149if (strncmp (p ,"no" ,2 )== 0 ) { 6150xp -> xp_context = EXPAND_BOOL_SETTINGS ; 6151xp -> xp_prefix = XP_PREFIX_NO ; 6152p += 2 ; 6153 }else if (strncmp (p ,"inv" ,3 )== 0 ) { 6154xp -> xp_context = EXPAND_BOOL_SETTINGS ; 6155xp -> xp_prefix = XP_PREFIX_INV ; 6156p += 3 ; 6157 } 6158xp -> xp_pattern = p ; 6159arg = p ; 6160 6161char nextchar ; 6162uint32_t flags = 0 ; 6163OptIndex opt_idx = 0 ; 6164bool is_term_option = false; 6165 6166if (* arg == '<' ) { 6167while (* p != '>' ) { 6168if (* p ++ == NUL ) {// expand terminal option name 6169return ; 6170 } 6171 } 6172int key = get_special_key_code (arg + 1 ); 6173if (key == 0 ) {// unknown name 6174xp -> xp_context = EXPAND_NOTHING ; 6175return ; 6176 } 6177nextchar = *++ p ; 6178is_term_option = true; 6179expand_option_name [2 ]= (char )(uint8_t )KEY2TERMCAP0 (key ); 6180expand_option_name [3 ]= (char )(uint8_t )KEY2TERMCAP1 (key ); 6181 }else { 6182if (p [0 ]== 't' && p [1 ]== '_' ) { 6183p += 2 ; 6184if (* p != NUL ) { 6185p ++ ; 6186 } 6187if (* p == NUL ) { 6188return ;// expand option name 6189 } 6190nextchar = *++ p ; 6191is_term_option = true; 6192expand_option_name [2 ]= p [-2 ]; 6193expand_option_name [3 ]= p [-1 ]; 6194 }else { 6195// Allow * wildcard. 6196while (ASCII_ISALNUM (* p )|| * p == '_' || * p == '*' ) { 6197p ++ ; 6198 } 6199if (* p == NUL ) { 6200return ; 6201 } 6202nextchar = * p ; 6203opt_idx = find_option_len (arg , (size_t )(p - arg )); 6204if (opt_idx == kOptInvalid || is_option_hidden (opt_idx )) { 6205xp -> xp_context = EXPAND_NOTHING ; 6206return ; 6207 } 6208flags = options [opt_idx ].flags ; 6209if (option_has_type (opt_idx ,kObjectTypeBoolean )) { 6210xp -> xp_context = EXPAND_NOTHING ; 6211return ; 6212 } 6213 } 6214 } 6215// handle "-=" and "+=" 6216expand_option_append = false; 6217bool expand_option_subtract = false; 6218if ((nextchar == '-' || nextchar == '+' || nextchar == '^' )&& p [1 ]== '=' ) { 6219if (nextchar == '-' ) { 6220expand_option_subtract = true; 6221 } 6222if (nextchar == '+' || nextchar == '^' ) { 6223expand_option_append = true; 6224 } 6225p ++ ; 6226nextchar = '=' ; 6227 } 6228if ((nextchar != '=' && nextchar != ':' ) 6229|| xp -> xp_context == EXPAND_BOOL_SETTINGS ) { 6230xp -> xp_context = EXPAND_UNSUCCESSFUL ; 6231return ; 6232 } 6233 6234// Below are for handling expanding a specific option's value after the '=' or ':' 6235 6236if (is_term_option ) { 6237expand_option_idx = kOptInvalid ; 6238 }else { 6239expand_option_idx = opt_idx ; 6240 } 6241 6242xp -> xp_pattern = p + 1 ; 6243expand_option_start_col = (int )(p + 1 - xp -> xp_line ); 6244 6245// Certain options currently have special case handling to reuse the 6246// expansion logic with other commands. 6247if (options [opt_idx ].var == & p_syn ) { 6248xp -> xp_context = EXPAND_OWNSYNTAX ; 6249return ; 6250 } 6251if (options [opt_idx ].var == & p_ft ) { 6252xp -> xp_context = EXPAND_FILETYPE ; 6253return ; 6254 } 6255if (options [opt_idx ].var == & p_keymap ) { 6256xp -> xp_context = EXPAND_KEYMAP ; 6257return ; 6258 } 6259 6260// Now pick. If the option has a custom expander, use that. Otherwise, just 6261// fill with the existing option value. 6262if (expand_option_subtract ) { 6263xp -> xp_context = EXPAND_SETTING_SUBTRACT ; 6264return ; 6265 }else if (expand_option_idx != kOptInvalid && options [expand_option_idx ].opt_expand_cb != NULL ) { 6266xp -> xp_context = EXPAND_STRING_SETTING ; 6267 }else if (* xp -> xp_pattern == NUL ) { 6268xp -> xp_context = EXPAND_OLD_SETTING ; 6269return ; 6270 }else { 6271xp -> xp_context = EXPAND_NOTHING ; 6272 } 6273 6274if (is_term_option || option_has_type (opt_idx ,kObjectTypeInteger )) { 6275return ; 6276 } 6277 6278// Only string options below 6279 6280// Options that have kOptFlagExpand are considered to all use file/dir expansion. 6281if (flags & kOptFlagExpand ) { 6282p = options [opt_idx ].var ; 6283if (p == (char * )& p_bdir 6284|| p == (char * )& p_dir 6285|| p == (char * )& p_path 6286|| p == (char * )& p_pp 6287|| p == (char * )& p_rtp 6288|| p == (char * )& p_cdpath 6289|| p == (char * )& p_vdir ) { 6290xp -> xp_context = EXPAND_DIRECTORIES ; 6291if (p == (char * )& p_path || p == (char * )& p_cdpath ) { 6292xp -> xp_backslash = XP_BS_THREE ; 6293 }else { 6294xp -> xp_backslash = XP_BS_ONE ; 6295 } 6296 }else { 6297xp -> xp_context = EXPAND_FILES ; 6298// for 'tags' need three backslashes for a space 6299if (p == (char * )& p_tags ) { 6300xp -> xp_backslash = XP_BS_THREE ; 6301 }else { 6302xp -> xp_backslash = XP_BS_ONE ; 6303 } 6304 } 6305if (flags & kOptFlagComma ) { 6306xp -> xp_backslash |=XP_BS_COMMA ; 6307 } 6308 } 6309 6310// For an option that is a list of file names, or comma/colon-separated 6311// values, split it by the delimiter and find the start of the current 6312// pattern, while accounting for backslash-escaped space/commas/colons. 6313// Triple-backslashed escaped file names (e.g. 'path') can also be 6314// delimited by space. 6315if ((flags & kOptFlagExpand )|| (flags & kOptFlagComma )|| (flags & kOptFlagColon )) { 6316for (p = argend - 1 ;p > xp -> xp_pattern ;p -- ) { 6317// count number of backslashes before ' ' or ',' 6318if (* p == ' ' || * p == ',' || (* p == ':' && (flags & kOptFlagColon ))) { 6319char * s = p ; 6320while (s > xp -> xp_pattern && * (s - 1 )== '\\' ) { 6321s -- ; 6322 } 6323if ((* p == ' ' && ((xp -> xp_backslash & XP_BS_THREE )&& (p - s )< 3 )) 6324#ifdef BACKSLASH_IN_FILENAME 6325|| (* p == ',' && (flags & kOptFlagComma )&& (p - s )< 1 ) 6326#else 6327|| (* p == ',' && (flags & kOptFlagComma )&& (p - s )< 2 ) 6328#endif 6329|| (* p == ':' && (flags & kOptFlagColon ))) { 6330xp -> xp_pattern = p + 1 ; 6331break ; 6332 } 6333 } 6334 } 6335 } 6336 6337// An option that is a list of single-character flags should always start 6338// at the end as we don't complete words. 6339if (flags & kOptFlagFlagList ) { 6340xp -> xp_pattern = argend ; 6341 } 6342 6343// Some options can either be using file/dir expansions, or custom value 6344// expansion depending on what the user typed. Unfortunately we have to 6345// manually handle it here to make sure we have the correct xp_context set. 6346// for 'spellsuggest' start at "file:" 6347if (options [opt_idx ].var == & p_sps ) { 6348if (strncmp (xp -> xp_pattern ,"file:" ,5 )== 0 ) { 6349xp -> xp_pattern += 5 ; 6350return ; 6351 }else if (options [expand_option_idx ].opt_expand_cb != NULL ) { 6352xp -> xp_context = EXPAND_STRING_SETTING ; 6353 } 6354 } 6355} 6356 6357/// Returns true if "str" either matches "regmatch" or fuzzy matches "pat". 6358/// 6359/// If "test_only" is true and "fuzzy" is false and if "str" matches the regular 6360/// expression "regmatch", then returns true. Otherwise returns false. 6361/// 6362/// If "test_only" is false and "fuzzy" is false and if "str" matches the 6363/// regular expression "regmatch", then stores the match in matches[idx] and 6364/// returns true. 6365/// 6366/// If "test_only" is true and "fuzzy" is true and if "str" fuzzy matches 6367/// "fuzzystr", then returns true. Otherwise returns false. 6368/// 6369/// If "test_only" is false and "fuzzy" is true and if "str" fuzzy matches 6370/// "fuzzystr", then stores the match details in fuzmatch[idx] and returns true. 6371static bool match_str (char * const str ,regmatch_T * const regmatch ,char ** const matches , 6372const int idx ,const bool test_only ,const bool fuzzy , 6373const char * const fuzzystr ,fuzmatch_str_T * const fuzmatch ) 6374{ 6375if (!fuzzy ) { 6376if (vim_regexec (regmatch ,str ,0 )) { 6377if (!test_only ) { 6378matches [idx ]= xstrdup (str ); 6379 } 6380return true; 6381 } 6382 }else { 6383const int score = fuzzy_match_str (str ,fuzzystr ); 6384if (score != FUZZY_SCORE_NONE ) { 6385if (!test_only ) { 6386fuzmatch [idx ].idx = idx ; 6387fuzmatch [idx ].str = xstrdup (str ); 6388fuzmatch [idx ].score = score ; 6389 } 6390return true; 6391 } 6392 } 6393return false; 6394} 6395 6396int ExpandSettings (expand_T * xp ,regmatch_T * regmatch ,char * fuzzystr ,int * numMatches , 6397char *** matches ,const bool can_fuzzy ) 6398{ 6399int num_normal = 0 ;// Nr of matching non-term-code settings 6400int count = 0 ; 6401static char * (names [])= {"all" }; 6402int ic = regmatch -> rm_ic ;// remember the ignore-case flag 6403 6404fuzmatch_str_T * fuzmatch = NULL ; 6405const bool fuzzy = can_fuzzy && cmdline_fuzzy_complete (fuzzystr ); 6406 6407// do this loop twice: 6408// loop == 0: count the number of matching options 6409// loop == 1: copy the matching options into allocated memory 6410for (int loop = 0 ;loop <=1 ;loop ++ ) { 6411regmatch -> rm_ic = ic ; 6412if (xp -> xp_context != EXPAND_BOOL_SETTINGS ) { 6413for (int match = 0 ;match < (int )ARRAY_SIZE (names ); 6414match ++ ) { 6415if (match_str (names [match ],regmatch ,* matches , 6416count , (loop == 0 ),fuzzy ,fuzzystr ,fuzmatch )) { 6417if (loop == 0 ) { 6418num_normal ++ ; 6419 }else { 6420count ++ ; 6421 } 6422 } 6423 } 6424 } 6425char * str ; 6426for (OptIndex opt_idx = 0 ;opt_idx < kOptCount ;opt_idx ++ ) { 6427str = options [opt_idx ].fullname ; 6428if (is_option_hidden (opt_idx )) { 6429continue ; 6430 } 6431if (xp -> xp_context == EXPAND_BOOL_SETTINGS 6432&& !(option_has_type (opt_idx ,kObjectTypeBoolean ))) { 6433continue ; 6434 } 6435 6436if (match_str (str ,regmatch ,* matches ,count , (loop == 0 ), 6437fuzzy ,fuzzystr ,fuzmatch )) { 6438if (loop == 0 ) { 6439num_normal ++ ; 6440 }else { 6441count ++ ; 6442 } 6443 }else if (!fuzzy && options [opt_idx ].shortname != NULL 6444&& vim_regexec (regmatch ,options [opt_idx ].shortname ,0 )) { 6445// Compare against the abbreviated option name (for regular 6446// expression match). Fuzzy matching (previous if) already 6447// matches against both the expanded and abbreviated names. 6448if (loop == 0 ) { 6449num_normal ++ ; 6450 }else { 6451 (* matches )[count ++ ]= xstrdup (str ); 6452 } 6453 } 6454 } 6455 6456if (loop == 0 ) { 6457if (num_normal > 0 ) { 6458* numMatches = num_normal ; 6459 }else { 6460return OK ; 6461 } 6462if (!fuzzy ) { 6463* matches = xmalloc ((size_t )(* numMatches )* sizeof (char * )); 6464 }else { 6465fuzmatch = xmalloc ((size_t )(* numMatches )* sizeof (fuzmatch_str_T )); 6466 } 6467 } 6468 } 6469 6470if (fuzzy ) { 6471fuzzymatches_to_strmatches (fuzmatch ,matches ,count , false); 6472 } 6473 6474return OK ; 6475} 6476 6477/// Escape an option value that can be used on the command-line with :set. 6478/// Caller needs to free the returned string, unless NULL is returned. 6479char * escape_option_str_cmdline (char * var ) 6480{ 6481// A backslash is required before some characters. This is the reverse of 6482// what happens in do_set(). 6483char * buf = vim_strsave_escaped (var ,escape_chars ); 6484 6485#ifdef BACKSLASH_IN_FILENAME 6486// For MS-Windows et al. we don't double backslashes at the start and 6487// before a file name character. 6488// The reverse is found at stropt_copy_value(). 6489for (var = buf ;* var != NUL ;MB_PTR_ADV (var )) { 6490if (var [0 ]== '\\' && var [1 ]== '\\' 6491&& expand_option_idx != kOptInvalid 6492&& (options [expand_option_idx ].flags & kOptFlagExpand ) 6493&& vim_isfilec ((uint8_t )var [2 ]) 6494&& (var [2 ]!= '\\' || (var == buf && var [4 ]!= '\\' ))) { 6495STRMOVE (var ,var + 1 ); 6496 } 6497 } 6498#endif 6499return buf ; 6500} 6501 6502/// Expansion handler for :set= when we just want to fill in with the existing value. 6503int ExpandOldSetting (int * numMatches ,char *** matches ) 6504{ 6505char * var = NULL ; 6506 6507* numMatches = 0 ; 6508* matches = NULL ; 6509 6510// For a terminal key code expand_option_idx is kOptInvalid. 6511if (expand_option_idx == kOptInvalid ) { 6512expand_option_idx = find_option (expand_option_name ); 6513 } 6514 6515if (expand_option_idx != kOptInvalid ) { 6516Object o = opt_from_varp (expand_option_idx , 6517get_varp_scope (& options [expand_option_idx ],expand_option_flags )); 6518bool is_luafn = o .type == kObjectTypeLuaRef ; 6519optval_free_read (expand_option_idx ,o ); 6520if (is_luafn ) { 6521// Special case: ":set x=<tab>" cannot meaningfully complete a Lua function. 6522return OK ; 6523 } 6524// Put string of option value in NameBuff. 6525optval_fmt (expand_option_idx ,expand_option_flags ); 6526var = NameBuff ; 6527 }else { 6528var = "" ; 6529 } 6530 6531char * buf = escape_option_str_cmdline (var ); 6532 6533* matches = xmalloc (sizeof (char * )); 6534 (* matches )[0 ]= buf ; 6535* numMatches = 1 ; 6536return OK ; 6537} 6538 6539/// Expansion handler for :set=/:set+= when the option has a custom expansion handler. 6540int ExpandStringSetting (expand_T * xp ,regmatch_T * regmatch ,int * numMatches ,char *** matches ) 6541{ 6542if (expand_option_idx == kOptInvalid || options [expand_option_idx ].opt_expand_cb == NULL ) { 6543// Not supposed to reach this. This function is only for options with 6544// custom expansion callbacks. 6545return FAIL ; 6546 } 6547 6548optexpand_T args = { 6549 .oe_varp = get_varp_scope (& options [expand_option_idx ],expand_option_flags ), 6550 .oe_idx = expand_option_idx , 6551 .oe_append = expand_option_append , 6552 .oe_regmatch = regmatch , 6553 .oe_xp = xp , 6554 .oe_set_arg = xp -> xp_line + expand_option_start_col , 6555 }; 6556args .oe_include_orig_val = !expand_option_append && (* args .oe_set_arg == NUL ); 6557 6558// Retrieve the existing value, but escape it as a reverse of setting it. 6559// We technically only need to do this when oe_append or 6560// oe_include_orig_val is true. 6561optval_fmt (expand_option_idx ,expand_option_flags ); 6562char * var = NameBuff ; 6563char * buf = escape_option_str_cmdline (var ); 6564args .oe_opt_value = buf ; 6565 6566int num_ret = options [expand_option_idx ].opt_expand_cb (& args ,numMatches ,matches ); 6567 6568xfree (buf ); 6569return num_ret ; 6570} 6571 6572/// Expansion handler for :set-= 6573int ExpandSettingSubtract (expand_T * xp ,regmatch_T * regmatch ,int * numMatches ,char *** matches ) 6574{ 6575if (expand_option_idx == kOptInvalid ) { 6576// term option 6577return ExpandOldSetting (numMatches ,matches ); 6578 } 6579 6580char * option_val = * (char ** )get_option_varp_scope_from (expand_option_idx , 6581expand_option_flags , 6582curbuf ,curwin ); 6583 6584uint32_t option_flags = options [expand_option_idx ].flags ; 6585 6586if (option_has_type (expand_option_idx ,kObjectTypeInteger )) { 6587return ExpandOldSetting (numMatches ,matches ); 6588 }else if (option_flags & kOptFlagComma ) { 6589// Split the option by comma, then present each option to the user if 6590// it matches the pattern. 6591// This condition needs to go first, because 'whichwrap' has both 6592// kOptFlagComma and kOptFlagFlagList. 6593 6594if (* option_val == NUL ) { 6595return FAIL ; 6596 } 6597 6598// Make a copy as we need to inject null characters destructively. 6599char * option_copy = xstrdup (option_val ); 6600char * next_val = option_copy ; 6601 6602garray_T ga ; 6603ga_init (& ga ,sizeof (char * ),10 ); 6604 6605do { 6606char * item = next_val ; 6607char * comma = vim_strchr (next_val ,',' ); 6608while (comma != NULL && comma != next_val && * (comma - 1 )== '\\' ) { 6609// "\," is interpreted as a literal comma rather than option 6610// separator when reading options in copy_option_part(). Skip 6611// it. 6612comma = vim_strchr (comma + 1 ,',' ); 6613 } 6614if (comma != NULL ) { 6615* comma = NUL ;// null-terminate this value, required by later functions 6616next_val = comma + 1 ; 6617 }else { 6618next_val = NULL ; 6619 } 6620 6621if (* item == NUL ) { 6622// empty value, don't add to list 6623continue ; 6624 } 6625 6626if (!vim_regexec (regmatch ,item ,0 )) { 6627continue ; 6628 } 6629 6630char * buf = escape_option_str_cmdline (item ); 6631GA_APPEND (char * ,& ga ,buf ); 6632 }while (next_val != NULL ); 6633 6634xfree (option_copy ); 6635 6636* matches = ga .ga_data ; 6637* numMatches = ga .ga_len ; 6638return OK ; 6639 }else if (option_flags & kOptFlagFlagList ) { 6640// Only present the flags that are set on the option as the other flags 6641// are not meaningful to do set-= on. 6642 6643if (* xp -> xp_pattern != NUL ) { 6644// Don't suggest anything if cmdline is non-empty. Vim's set-= 6645// behavior requires consecutive strings and it's usually 6646// unintuitive to users if they try to subtract multiple flags at 6647// once. 6648return FAIL ; 6649 } 6650 6651size_t num_flags = strlen (option_val ); 6652if (num_flags == 0 ) { 6653return FAIL ; 6654 } 6655 6656* matches = xmalloc (sizeof (char * )* (num_flags + 1 )); 6657 6658int count = 0 ; 6659 6660 (* matches )[count ++ ]= xmemdupz (option_val ,num_flags ); 6661 6662if (num_flags > 1 ) { 6663// If more than one flags, split the flags up and expose each 6664// character as individual choice. 6665for (char * flag = option_val ;* flag != NUL ;flag ++ ) { 6666 (* matches )[count ++ ]= xmemdupz (flag ,1 ); 6667 } 6668 } 6669 6670* numMatches = count ; 6671return OK ; 6672 } 6673 6674return ExpandOldSetting (numMatches ,matches ); 6675} 6676 6677/// Writes an option value into `NameBuff` in ":set" display form ('wildchar' as a key name, 6678/// kOptFlagExpand paths with "~"). Must not be called with a hidden or boolean option! 6679/// 6680/// @param opt_flags Option flags (can be OPT_LOCAL, OPT_GLOBAL or a combination). 6681static void optval_fmt (OptIndex opt_idx ,int opt_flags ) 6682{ 6683vimoption_T * opt = & options [opt_idx ]; 6684void * varp = get_varp_scope (opt ,opt_flags ); 6685assert (varp != NULL ); 6686 6687// Display-only forms, not value renderings: 'wildchar'/'wildcharm' shown as a key name, and 6688// kOptFlagExpand (path) options with "~" abbreviation. 6689OptInt wc = 0 ; 6690if (wc_use_keyname (varp ,& wc )) { 6691xstrlcpy (NameBuff ,get_special_key_name ((int )wc ,0 ),MAXPATHL ); 6692return ; 6693 } 6694if (wc != 0 ) { 6695xstrlcpy (NameBuff ,transchar ((int )wc ),MAXPATHL ); 6696return ; 6697 } 6698if ((opt -> flags & kOptFlagExpand )&& !is_callback_option (opt_idx ) 6699&& option_has_type (opt_idx ,kObjectTypeString )) { 6700home_replace (NULL ,* (char ** )varp ,NameBuff ,MAXPATHL , false); 6701return ; 6702 } 6703 6704Object o = opt_from_varp (opt_idx ,varp ); 6705char * s = optval_to_cstr (o , false); 6706xstrlcpy (NameBuff ,s ,MAXPATHL ); 6707xfree (s ); 6708optval_free_read (opt_idx ,o ); 6709} 6710 6711/// Return true if "varp" points to 'wildchar' or 'wildcharm' and it can be 6712/// printed as a keyname. 6713/// "*wcp" is set to the value of the option if it's 'wildchar' or 'wildcharm'. 6714static int wc_use_keyname (const void * varp ,OptInt * wcp ) 6715{ 6716if (((OptInt * )varp == & p_wc )|| ((OptInt * )varp == & p_wcm )) { 6717* wcp = * (OptInt * )varp ; 6718if (IS_SPECIAL (* wcp )|| find_special_key_in_table ((int )(* wcp )) >=0 ) { 6719return true; 6720 } 6721 } 6722return false; 6723} 6724 6725/// @returns true if "x" is present in 'shortmess' option, or 6726/// 'shortmess' contains 'a' and "x" is present in SHM_ALL_ABBREVIATIONS. 6727bool shortmess (int x ) 6728{ 6729return (p_shm != NULL 6730&& (vim_strchr (p_shm ,x )!= NULL 6731|| (vim_strchr (p_shm ,'a' )!= NULL 6732&& vim_strchr (SHM_ALL_ABBREVIATIONS ,x )!= NULL ))); 6733} 6734 6735/// vimrc_found() - Called when a vimrc or "VIMINIT" has been found. 6736/// 6737/// Set the values for options that didn't get set yet to the defaults. 6738/// When "fname" is not NULL, use it to set $"envname" when it wasn't set yet. 6739void vimrc_found (char * fname ,char * envname ) 6740{ 6741if (fname != NULL && envname != NULL ) { 6742char * p = vim_getenv (envname ); 6743if (p == NULL ) { 6744// Set $MYVIMRC to the first vimrc file found. 6745p = FullName_save (fname , false); 6746if (p != NULL ) { 6747os_setenv (envname ,p ,1 ); 6748xfree (p ); 6749 } 6750 }else { 6751xfree (p ); 6752 } 6753 } 6754} 6755 6756/// Check whether global option has been set. 6757/// 6758/// @param[in] name Option name. 6759/// 6760/// @return True if option was set. 6761bool option_was_set (OptIndex opt_idx ) 6762{ 6763assert (opt_idx != kOptInvalid ); 6764return options [opt_idx ].flags & kOptFlagWasSet ; 6765} 6766 6767/// Reset the flag indicating option "name" was set. 6768/// 6769/// @param[in] name Option name. 6770void reset_option_was_set (OptIndex opt_idx ) 6771{ 6772assert (opt_idx != kOptInvalid ); 6773options [opt_idx ].flags &= ~(unsigned )kOptFlagWasSet ; 6774} 6775 6776/// fill_culopt_flags() -- called when 'culopt' changes value 6777int fill_culopt_flags (char * val ,win_T * wp ) 6778{ 6779char * p ; 6780uint8_t culopt_flags_new = 0 ; 6781 6782if (val == NULL ) { 6783p = wp -> w_p_culopt ; 6784 }else { 6785p = val ; 6786 } 6787while (* p != NUL ) { 6788// Note: Keep this in sync with opt_culopt_values. 6789if (strncmp (p ,"line" ,4 )== 0 ) { 6790p += 4 ; 6791culopt_flags_new |=kOptCuloptFlagLine ; 6792 }else if (strncmp (p ,"both" ,4 )== 0 ) { 6793p += 4 ; 6794culopt_flags_new |=kOptCuloptFlagLine |kOptCuloptFlagNumber ; 6795 }else if (strncmp (p ,"number" ,6 )== 0 ) { 6796p += 6 ; 6797culopt_flags_new |=kOptCuloptFlagNumber ; 6798 }else if (strncmp (p ,"screenline" ,10 )== 0 ) { 6799p += 10 ; 6800culopt_flags_new |=kOptCuloptFlagScreenline ; 6801 } 6802 6803if (* p != ',' && * p != NUL ) { 6804return FAIL ; 6805 } 6806if (* p == ',' ) { 6807p ++ ; 6808 } 6809 } 6810 6811// Can't have both "line" and "screenline". 6812if ((culopt_flags_new & kOptCuloptFlagLine )&& (culopt_flags_new & kOptCuloptFlagScreenline )) { 6813return FAIL ; 6814 } 6815wp -> w_p_culopt_flags = culopt_flags_new ; 6816 6817return OK ; 6818} 6819 6820/// Set the callback function value for an option that accepts a function name, 6821/// lambda, et al. (e.g. 'operatorfunc', 'tagfunc', etc.) 6822/// @return OK if the option is successfully set to a function, otherwise FAIL 6823int option_set_callback_func (char * optval ,Callback * optcb ) 6824{ 6825if (optval == NULL || * optval == NUL ) { 6826callback_free (optcb ); 6827return OK ; 6828 } 6829 6830typval_T * tv ; 6831if (* optval == '{' 6832|| (strncmp (optval ,"function(" ,9 )== 0 ) 6833|| (strncmp (optval ,"funcref(" ,8 )== 0 )) { 6834// Lambda expression or a funcref 6835tv = eval_expr (optval ,NULL ); 6836if (tv == NULL ) { 6837return FAIL ; 6838 } 6839 }else { 6840// treat everything else as a function name string 6841tv = xcalloc (1 ,sizeof (* tv )); 6842tv -> v_type = VAR_STRING ; 6843tv -> vval .v_string = xstrdup (optval ); 6844 } 6845 6846Callback cb ; 6847if (!callback_from_typval (& cb ,tv )|| cb .type == kCallbackNone ) { 6848tv_free (tv ); 6849return FAIL ; 6850 } 6851 6852callback_free (optcb ); 6853* optcb = cb ; 6854tv_free (tv ); 6855return OK ; 6856} 6857 6858static void didset_options_sctx (int opt_flags ,int * buf ) 6859{ 6860for (int i = 0 ;;i ++ ) { 6861if (buf [i ]== kOptInvalid ) { 6862break ; 6863 } 6864 6865set_option_sctx (buf [i ],opt_flags ,current_sctx ); 6866 } 6867} 6868 6869/// Check if backspacing over something is allowed. 6870/// @param what BS_INDENT, BS_EOL, BS_START, or BS_NOSTOP 6871bool can_bs (int what ) 6872{ 6873if (what == BS_START && bt_prompt (curbuf )) { 6874return false; 6875 } 6876 6877// Multicursor replays may join lines only if the primary's own span did. 6878if (what == BS_EOL && !mc_ins_replay_can_join ()) { 6879return false; 6880 } 6881 6882// support for number values was removed but we keep '2' since it is used in 6883// legacy tests 6884if (* p_bs == '2' ) { 6885return what != BS_NOSTOP ; 6886 } 6887 6888return vim_strchr (p_bs ,what )!= NULL ; 6889} 6890 6891/// Get the local or global value of 'backupcopy' flags. 6892/// 6893/// @param buf The buffer. 6894unsigned get_bkc_flags (buf_T * buf ) 6895{ 6896return buf -> b_bkc_flags ?buf -> b_bkc_flags :bkc_flags ; 6897} 6898 6899/// Get the local or global value of 'formatlistpat'. 6900/// 6901/// @param buf The buffer. 6902char * get_flp_value (buf_T * buf ) 6903{ 6904if (buf -> b_p_flp == NULL || * buf -> b_p_flp == NUL ) { 6905return p_flp ; 6906 } 6907return buf -> b_p_flp ; 6908} 6909 6910/// Get the local or global value of 'virtualedit' flags. 6911unsigned get_ve_flags (win_T * wp ) 6912{ 6913return (wp -> w_ve_flags ?wp -> w_ve_flags :ve_flags ) 6914& ~(unsigned )(kOptVeFlagNone |kOptVeFlagNoneU ); 6915} 6916 6917/// Get the local or global value of 'showbreak'. 6918/// 6919/// @param win If not NULL, the window to get the local option from; global 6920/// otherwise. 6921char * get_showbreak_value (win_T * const win ) 6922FUNC_ATTR_WARN_UNUSED_RESULT 6923{ 6924if (win -> w_p_sbr == NULL || * win -> w_p_sbr == NUL ) { 6925return p_sbr ; 6926 } 6927if (strcmp (win -> w_p_sbr ,"NONE" )== 0 ) { 6928return empty_string_option ; 6929 } 6930return win -> w_p_sbr ; 6931} 6932 6933/// Return the current end-of-line type: EOL_DOS, EOL_UNIX or EOL_MAC. 6934int get_fileformat (const buf_T * buf ) 6935FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL 6936{ 6937int c = (unsigned char )(* buf -> b_p_ff ); 6938 6939if (buf -> b_p_bin || c == 'u' ) { 6940return EOL_UNIX ; 6941 } 6942if (c == 'm' ) { 6943return EOL_MAC ; 6944 } 6945return EOL_DOS ; 6946} 6947 6948/// Like get_fileformat(), but override 'fileformat' with "p" for "++opt=val" 6949/// argument. 6950/// 6951/// @param eap can be NULL! 6952int get_fileformat_force (const buf_T * buf ,const exarg_T * eap ) 6953FUNC_ATTR_NONNULL_ARG (1 ) 6954{ 6955int c ; 6956 6957if (eap != NULL && eap -> force_ff != 0 ) { 6958c = eap -> force_ff ; 6959 }else { 6960if ((eap != NULL && eap -> force_bin != 0 ) 6961 ? (eap -> force_bin == FORCE_BIN ) :buf -> b_p_bin ) { 6962return EOL_UNIX ; 6963 } 6964c = (unsigned char )(* buf -> b_p_ff ); 6965 } 6966if (c == 'u' ) { 6967return EOL_UNIX ; 6968 } 6969if (c == 'm' ) { 6970return EOL_MAC ; 6971 } 6972return EOL_DOS ; 6973} 6974 6975/// Return the default fileformat from 'fileformats'. 6976int default_fileformat (void ) 6977{ 6978switch (* p_ffs ) { 6979case 'm' : 6980return EOL_MAC ; 6981case 'd' : 6982return EOL_DOS ; 6983 } 6984return EOL_UNIX ; 6985} 6986 6987/// Set the current end-of-line type to EOL_UNIX, EOL_MAC, or EOL_DOS. 6988/// 6989/// Sets 'fileformat'. 6990/// 6991/// @param eol_style End-of-line style. 6992/// @param opt_flags Option flags (can be OPT_LOCAL, OPT_GLOBAL or a combination). 6993void set_fileformat (int eol_style ,int opt_flags ) 6994{ 6995char * p = NULL ; 6996 6997switch (eol_style ) { 6998case EOL_UNIX : 6999p = "unix" ; 7000break ; 7001case EOL_MAC : 7002p = "mac" ; 7003break ; 7004case EOL_DOS : 7005p = "dos" ; 7006break ; 7007 } 7008 7009// p is NULL if "eol_style" is EOL_UNKNOWN. 7010if (p != NULL ) { 7011set_option_direct (kOptFileformat ,CSTR_AS_OBJ (p ),opt_flags ,0 ); 7012 } 7013 7014// This may cause the buffer to become (un)modified. 7015redraw_buf_status_later (curbuf ); 7016redraw_tabline = true; 7017need_maketitle = true;// Set window title later. 7018} 7019 7020/// Skip to next part of an option argument: skip space and comma 7021char * skip_to_option_part (const char * p ) 7022{ 7023if (* p == ',' ) { 7024p ++ ; 7025 } 7026while (* p == ' ' ) { 7027p ++ ; 7028 } 7029return (char * )p ; 7030} 7031 7032/// Isolate one part of a string option separated by `sep_chars`. 7033/// 7034/// @param[in,out] option advanced to the next part 7035/// @param[in,out] buf copy of the isolated part 7036/// @param[in] maxlen length of `buf` 7037/// @param[in] sep_chars chars that separate the option parts 7038/// 7039/// @return length of `*option` 7040size_t copy_option_part (char ** option ,char * buf ,size_t maxlen ,char * sep_chars ) 7041{ 7042size_t len = 0 ; 7043char * p = * option ; 7044 7045// skip '.' at start of option part, for 'suffixes' 7046if (* p == '.' ) { 7047buf [len ++ ]= * p ++ ; 7048 } 7049while (* p != NUL && vim_strchr (sep_chars , (uint8_t )(* p ))== NULL ) { 7050// Skip backslash before a separator character and space. 7051if (p [0 ]== '\\' && vim_strchr (sep_chars , (uint8_t )p [1 ])!= NULL ) { 7052p ++ ; 7053 } 7054if (len < maxlen - 1 ) { 7055buf [len ++ ]= * p ; 7056 } 7057p ++ ; 7058 } 7059buf [len ]= NUL ; 7060 7061if (* p != NUL && * p != ',' ) {// skip non-standard separator 7062p ++ ; 7063 } 7064p = skip_to_option_part (p );// p points to next file name 7065 7066* option = p ; 7067return len ; 7068} 7069 7070/// Iterates comma-separated parts of option, splitting each part at its first ':' into key/value. 7071/// The returned pointers are slices into the original string: for simple "key:value" list options 7072/// like 'winhighlight' and 'previewpopup', but not 'listchars'/'fillchars' whose values need 7073/// decoding. 7074/// 7075/// Slices are paired lengths; copy with xmemcpyz() if you need a NUL-terminated string. 7076/// 7077/// A part with no ':' yields `*val == NULL`, i.e. a bare flag such as 'diffopt' "filler". An empty 7078/// part (from "a,,b" or a leading ',') yields "*keylen == 0" with "*val == NULL"; the caller 7079/// decides if that is an error (strict key:value options, but not 'diffopt'). 7080/// 7081/// Drive it with a loop, advancing `*p` each step: 7082/// 7083/// const char *key, *val; 7084/// size_t keylen, vallen; 7085/// for (const char *p = value; option_next_keyval(&p, &key, &keylen, &val, &vallen);) { 7086/// ... 7087/// } 7088/// 7089/// @param[in,out] p Cursor into the option string; advanced past the part. 7090/// @param[out] key Start of the key slice. 7091/// @param[out] keylen Length of the key slice. 7092/// @param[out] val Start of the value slice, or NULL if the part had no ':'. 7093/// @param[out] vallen Length of the value slice (0 when "*val" is NULL). 7094/// 7095/// @return true if a part was returned, false at the end of the string. 7096bool option_next_keyval (const char ** p ,const char ** key ,size_t * keylen ,const char ** val , 7097size_t * vallen ) 7098FUNC_ATTR_NONNULL_ALL 7099{ 7100const char * s = * p ; 7101if (* s == NUL ) { 7102return false; 7103 } 7104 7105const char * comma = vim_strchr (s ,',' ); 7106const char * end = comma != NULL ?comma :s + strlen (s ); 7107const char * colon = vim_strchr (s ,':' ); 7108 7109* key = s ; 7110if (colon != NULL && colon < end ) { 7111* keylen = (size_t )(colon - s ); 7112* val = colon + 1 ; 7113* vallen = (size_t )(end - (colon + 1 )); 7114 }else { 7115* keylen = (size_t )(end - s ); 7116* val = NULL ; 7117* vallen = 0 ; 7118 } 7119 7120* p = comma != NULL ?comma + 1 :end ; 7121return true; 7122} 7123 7124/// Compare a (non-NUL-terminated) slice from option_next_keyval() against a name. 7125/// 7126/// @param slice Start of the slice; may be NULL (e.g. a bare flag's value). 7127/// @param slicelen Length of the slice. 7128/// @param name NUL-terminated name to match. 7129/// 7130/// @return true if "slice[0..slicelen)" equals "name". 7131bool option_slice_eq (const char * slice ,size_t slicelen ,const char * name ) 7132FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT 7133{ 7134return slice != NULL && strlen (name )== slicelen && strncmp (slice ,name ,slicelen )== 0 ; 7135} 7136 7137/// Return true when 'shell' has "csh" in the tail. 7138int csh_like_shell (void ) 7139{ 7140return strstr (path_tail (p_sh ),"csh" )!= NULL ; 7141} 7142 7143/// Return true when 'shell' has "fish" in the tail. 7144bool fish_like_shell (void ) 7145{ 7146return strstr (path_tail (p_sh ),"fish" )!= NULL ; 7147} 7148 7149/// Get window or buffer local options 7150dict_T * get_winbuf_options (const int bufopt ) 7151FUNC_ATTR_WARN_UNUSED_RESULT 7152{ 7153dict_T * const d = tv_dict_alloc (); 7154 7155for (OptIndex opt_idx = 0 ;opt_idx < kOptCount ;opt_idx ++ ) { 7156vimoption_T * opt = & options [opt_idx ]; 7157 7158if ((bufopt && (option_has_scope (opt_idx ,kOptScopeBuf ))) 7159|| (!bufopt && (option_has_scope (opt_idx ,kOptScopeWin )))) { 7160void * varp = get_varp (opt ); 7161 7162if (varp != NULL ) { 7163Object ov = opt_from_varp (opt_idx ,varp ); 7164typval_T opt_tv = opt_to_tv (ov , true); 7165tv_dict_add_tv (d ,opt -> fullname ,strlen (opt -> fullname ),& opt_tv ); 7166tv_clear (& opt_tv ); 7167optval_free_read (opt_idx ,ov ); 7168 } 7169 } 7170 } 7171 7172return d ; 7173} 7174 7175/// Return the effective 'scrolloff' value for the current window, using the 7176/// global value when appropriate. 7177int64_t get_scrolloff_value (win_T * wp ) 7178{ 7179// Disallow scrolloff in terminal-mode. #11915 7180// Still allow 'scrolloff' for non-terminal buffers. #34447 7181if ((State & MODE_TERMINAL )&& wp -> w_buffer -> terminal ) { 7182return 0 ; 7183 } 7184return wp -> w_p_so < 0 ?p_so :wp -> w_p_so ; 7185} 7186 7187/// Return the effective 'scrolloffpad' value for the current window, using the 7188/// global value when appropriate. 7189int64_t get_scrolloffpad_value (win_T * wp ) 7190{ 7191return wp -> w_p_sop == -1 ?p_sop :wp -> w_p_sop ; 7192} 7193 7194/// Return the effective 'sidescrolloff' value for the current window, using the 7195/// global value when appropriate. 7196int64_t get_sidescrolloff_value (win_T * wp ) 7197{ 7198return wp -> w_p_siso < 0 ?p_siso :wp -> w_p_siso ; 7199} 7200 7201/// Metadata Dict for option `name`; errors if `name` is unknown. 7202Dict get_option_info (String name ,int opt_flags ,buf_T * buf ,win_T * win ,Arena * arena ,Error * err ) 7203{ 7204OptIndex opt_idx = find_option_len (name .data ,name .size ); 7205VALIDATE_S (opt_idx != kOptInvalid ,"option (not found)" ,name .data , { 7206return (Dict )ARRAY_DICT_INIT ; 7207 }); 7208 7209return option_info_dict (& options [opt_idx ],opt_flags ,buf ,win ,arena ); 7210} 7211 7212/// Metadata Dict for every option, keyed by full name. 7213Dict get_all_options_info (Arena * arena ) 7214{ 7215Dict retval = arena_dict (arena ,kOptCount ); 7216for (OptIndex opt_idx = 0 ;opt_idx < kOptCount ;opt_idx ++ ) { 7217Dict opt_dict = option_info_dict (& options [opt_idx ],OPT_GLOBAL ,curbuf ,curwin ,arena ); 7218PUT_C (retval ,options [opt_idx ].fullname ,DICT_OBJ (opt_dict )); 7219 } 7220return retval ; 7221} 7222 7223/// Gets option metadata, in the shape of `DictAs(get_option_info)`. 7224static Dict option_info_dict (vimoption_T * opt ,int opt_flags ,buf_T * buf ,win_T * win ,Arena * arena ) 7225{ 7226OptIndex opt_idx = get_opt_idx (opt ); 7227Dict dict = arena_dict (arena ,13 ); 7228 7229PUT_C (dict ,"name" ,CSTR_AS_OBJ (opt -> fullname )); 7230PUT_C (dict ,"shortname" ,CSTR_AS_OBJ (opt -> shortname )); 7231 7232const char * scope ; 7233if (option_has_scope (opt_idx ,kOptScopeBuf )) { 7234scope = "buf" ; 7235 }else if (option_has_scope (opt_idx ,kOptScopeWin )) { 7236scope = "win" ; 7237 }else if (option_has_scope (opt_idx ,kOptScopeTab )) { 7238scope = "tab" ; 7239 }else { 7240scope = "global" ; 7241 } 7242 7243PUT_C (dict ,"scope" ,CSTR_AS_OBJ (scope )); 7244 7245// welcome to the jungle 7246PUT_C (dict ,"global_local" ,BOOLEAN_OBJ (option_is_global_local (opt_idx ))); 7247PUT_C (dict ,"commalist" ,BOOLEAN_OBJ (opt -> flags & kOptFlagComma )); 7248PUT_C (dict ,"flaglist" ,BOOLEAN_OBJ (opt -> flags & kOptFlagFlagList )); 7249 7250PUT_C (dict ,"was_set" ,BOOLEAN_OBJ (opt -> flags & kOptFlagWasSet )); 7251 7252sctx_T script_ctx = { .sc_sid = 0 }; 7253if (opt_flags == OPT_GLOBAL ) { 7254script_ctx = opt -> script_ctx ; 7255 }else { 7256// Scope is either OPT_LOCAL or a fallback mode was requested. 7257if (option_has_scope (opt_idx ,kOptScopeBuf )) { 7258script_ctx = buf -> b_p_script_ctx [opt -> scope_idx [kOptScopeBuf ]]; 7259 } 7260if (option_has_scope (opt_idx ,kOptScopeWin )) { 7261script_ctx = win -> w_p_script_ctx [opt -> scope_idx [kOptScopeWin ]]; 7262 } 7263if (opt_flags != OPT_LOCAL && script_ctx .sc_sid == 0 ) { 7264script_ctx = opt -> script_ctx ; 7265 } 7266 } 7267 7268PUT_C (dict ,"last_set_sid" ,INTEGER_OBJ (script_ctx .sc_sid )); 7269PUT_C (dict ,"last_set_linenr" ,INTEGER_OBJ (script_ctx .sc_lnum )); 7270PUT_C (dict ,"last_set_chan" ,INTEGER_OBJ ((int64_t )script_ctx .sc_chan )); 7271 7272PUT_C (dict ,"type" ,CSTR_AS_OBJ (optval_type_name (options [get_opt_idx (opt )].type ))); 7273PUT_C (dict ,"default" ,opt -> def_val ); 7274PUT_C (dict ,"allows_duplicates" ,BOOLEAN_OBJ (!(opt -> flags & kOptFlagNoDup ))); 7275 7276return dict ; 7277}