diff options
Diffstat (limited to 'src/nvim/option.c')
-rw-r--r-- | src/nvim/option.c | 1901 |
1 files changed, 999 insertions, 902 deletions
diff --git a/src/nvim/option.c b/src/nvim/option.c index 96d6d8e01e..d5df8385f8 100644 --- a/src/nvim/option.c +++ b/src/nvim/option.c @@ -1,8 +1,7 @@ // User-settable options. Checklist for adding a new option: // - Put it in options.lua -// - For a global option: Add a variable for it in option_defs.h. +// - For a global option: Add a variable for it in option_vars.h. // - For a buffer or window local option: -// - Add a BV_XX or WV_XX entry to option_defs.h // - Add a variable to the window or buffer struct in buffer_defs.h. // - For a window option, add some code to copy_winopt(). // - For a window string option, add code to check_winopt() @@ -12,7 +11,7 @@ // - For a buffer string option, add code to check_buf_options(). // - If it's a numeric option, add any necessary bounds checks to check_num_option_bounds(). // - If it's a list of flags, add some code in do_set(), search for WW_ALL. -// - Add documentation! doc/options.txt, and any other related places. +// - Add documentation! "desc" in options.lua, and any other related places. // - Add an entry in runtime/optwin.vim. #define IN_OPTION_C @@ -31,29 +30,35 @@ #include "nvim/api/private/helpers.h" #include "nvim/api/private/validate.h" #include "nvim/ascii_defs.h" +#include "nvim/assert_defs.h" #include "nvim/autocmd.h" +#include "nvim/autocmd_defs.h" #include "nvim/buffer.h" +#include "nvim/buffer_defs.h" #include "nvim/change.h" #include "nvim/charset.h" #include "nvim/cmdexpand.h" #include "nvim/cmdexpand_defs.h" #include "nvim/cursor_shape.h" +#include "nvim/decoration_defs.h" #include "nvim/decoration_provider.h" #include "nvim/diff.h" #include "nvim/drawscreen.h" #include "nvim/eval.h" #include "nvim/eval/typval.h" #include "nvim/eval/vars.h" +#include "nvim/eval/window.h" #include "nvim/ex_cmds_defs.h" #include "nvim/ex_docmd.h" #include "nvim/ex_getln.h" #include "nvim/ex_session.h" #include "nvim/fold.h" -#include "nvim/func_attr.h" #include "nvim/garray.h" -#include "nvim/gettext.h" +#include "nvim/garray_defs.h" +#include "nvim/gettext_defs.h" #include "nvim/globals.h" #include "nvim/highlight.h" +#include "nvim/highlight_defs.h" #include "nvim/highlight_group.h" #include "nvim/indent.h" #include "nvim/indent_c.h" @@ -63,6 +68,7 @@ #include "nvim/lua/executor.h" #include "nvim/macros_defs.h" #include "nvim/mapping.h" +#include "nvim/math.h" #include "nvim/mbyte.h" #include "nvim/memfile.h" #include "nvim/memline.h" @@ -79,13 +85,14 @@ #include "nvim/os/input.h" #include "nvim/os/lang.h" #include "nvim/os/os.h" +#include "nvim/os/os_defs.h" #include "nvim/path.h" #include "nvim/popupmenu.h" #include "nvim/pos_defs.h" #include "nvim/regexp.h" +#include "nvim/regexp_defs.h" #include "nvim/runtime.h" #include "nvim/search.h" -#include "nvim/sign_defs.h" #include "nvim/spell.h" #include "nvim/spellfile.h" #include "nvim/spellsuggest.h" @@ -95,7 +102,9 @@ #include "nvim/terminal.h" #include "nvim/types_defs.h" #include "nvim/ui.h" +#include "nvim/ui_defs.h" #include "nvim/undo.h" +#include "nvim/undo_defs.h" #include "nvim/vim_defs.h" #include "nvim/window.h" @@ -109,8 +118,6 @@ static const char e_not_allowed_in_modeline[] = N_("E520: Not allowed in a modeline"); static const char e_not_allowed_in_modeline_when_modelineexpr_is_off[] = N_("E992: Not allowed in a modeline when 'modelineexpr' is off"); -static const char e_key_code_not_set[] - = N_("E846: Key code not set"); static const char e_number_required_after_equal[] = N_("E521: Number required after ="); static const char e_preview_window_already_exists[] @@ -146,30 +153,28 @@ typedef enum { # include "option.c.generated.h" #endif -// options[] is initialized here. -// The order of the options MUST be alphabetic for ":set all" and findoption(). -// All option names MUST start with a lowercase letter (for findoption()). -// Exception: "t_" options are at the end. +// options[] is initialized in options.generated.h. // The options with a NULL variable are 'hidden': a set command for them is // ignored and they are not printed. #ifdef INCLUDE_GENERATED_DECLARATIONS # include "options.generated.h" +# include "options_map.generated.h" #endif -static char *(p_bin_dep_opts[]) = { - "textwidth", "wrapmargin", "modeline", "expandtab", NULL +static int p_bin_dep_opts[] = { + kOptTextwidth, kOptWrapmargin, kOptModeline, kOptExpandtab, kOptInvalid }; -static char *(p_paste_dep_opts[]) = { - "autoindent", "expandtab", "ruler", "showmatch", "smarttab", - "softtabstop", "textwidth", "wrapmargin", "revins", "varsofttabstop", NULL + +static int p_paste_dep_opts[] = { + kOptAutoindent, kOptExpandtab, kOptRuler, kOptShowmatch, kOptSmarttab, kOptSofttabstop, + kOptTextwidth, kOptWrapmargin, kOptRevins, kOptVarsofttabstop, kOptInvalid }; void set_init_tablocal(void) { // susy baka: cmdheight calls itself OPT_GLOBAL but is really tablocal! - int ch_idx = findoption("cmdheight"); - p_ch = (OptInt)(intptr_t)options[ch_idx].def_val; + p_ch = options[kOptCmdheight].def_val.number; } /// Initialize the 'shell' option to a default value. @@ -183,9 +188,9 @@ static void set_init_default_shell(void) const size_t len = strlen(shell) + 3; // two quotes and a trailing NUL char *const cmd = xmalloc(len); snprintf(cmd, len, "\"%s\"", shell); - set_string_default("sh", cmd, true); + set_string_default(kOptShell, cmd, true); } else { - set_string_default("sh", (char *)shell, false); + set_string_default(kOptShell, (char *)shell, false); } } } @@ -200,7 +205,7 @@ static void set_init_default_backupskip(void) static char *(names[3]) = { "TMPDIR", "TEMP", "TMP" }; #endif garray_T ga; - int opt_idx = findoption("backupskip"); + OptIndex opt_idx = kOptBackupskip; ga_init(&ga, 1, 100); for (size_t n = 0; n < ARRAY_SIZE(names); n++) { @@ -214,7 +219,7 @@ static void set_init_default_backupskip(void) p = "/tmp"; # endif mustfree = false; - } else // NOLINT(readability/braces) + } else #endif { p = vim_getenv(names[n]); @@ -244,7 +249,7 @@ static void set_init_default_backupskip(void) } } if (ga.ga_data != NULL) { - set_string_default("bsk", ga.ga_data, true); + set_string_default(kOptBackupskip, ga.ga_data, true); } } @@ -270,13 +275,8 @@ static void set_init_default_cdpath(void) } } buf[j] = NUL; - int opt_idx = findoption("cdpath"); - if (opt_idx >= 0) { - options[opt_idx].def_val = buf; - options[opt_idx].flags |= P_DEF_ALLOCED; - } else { - xfree(buf); // cannot happen - } + options[kOptCdpath].def_val.string = buf; + options[kOptCdpath].flags |= P_DEF_ALLOCED; xfree(cdpath); } @@ -289,7 +289,7 @@ static void set_init_default_cdpath(void) /// default. static void set_init_expand_env(void) { - for (int opt_idx = 0; options[opt_idx].fullname; opt_idx++) { + for (OptIndex opt_idx = 0; opt_idx < kOptIndexCount; opt_idx++) { vimoption_T *opt = &options[opt_idx]; if (opt->flags & P_NO_DEF_EXP) { continue; @@ -304,9 +304,9 @@ static void set_init_expand_env(void) p = xstrdup(p); *(char **)opt->var = p; if (opt->flags & P_DEF_ALLOCED) { - xfree(opt->def_val); + xfree(opt->def_val.string); } - opt->def_val = p; + opt->def_val.string = p; opt->flags |= P_DEF_ALLOCED; } } @@ -347,20 +347,20 @@ void set_init_1(bool clean_arg) backupdir = xrealloc(backupdir, backupdir_len + 3); memmove(backupdir + 2, backupdir, backupdir_len + 1); memmove(backupdir, ".,", 2); - set_string_default("backupdir", backupdir, true); - set_string_default("viewdir", stdpaths_user_state_subpath("view", 2, true), + set_string_default(kOptBackupdir, backupdir, true); + set_string_default(kOptViewdir, stdpaths_user_state_subpath("view", 2, true), true); - set_string_default("directory", stdpaths_user_state_subpath("swap", 2, true), + set_string_default(kOptDirectory, stdpaths_user_state_subpath("swap", 2, true), true); - set_string_default("undodir", stdpaths_user_state_subpath("undo", 2, true), + set_string_default(kOptUndodir, stdpaths_user_state_subpath("undo", 2, true), true); // Set default for &runtimepath. All necessary expansions are performed in // this function. char *rtp = runtimepath_default(clean_arg); if (rtp) { - set_string_default("runtimepath", rtp, true); + set_string_default(kOptRuntimepath, rtp, true); // Make a copy of 'rtp' for 'packpath' - set_string_default("packpath", rtp, false); + set_string_default(kOptPackpath, rtp, false); rtp = NULL; // ownership taken } @@ -375,9 +375,6 @@ void set_init_1(bool clean_arg) check_win_options(curwin); check_options(); - // Set all options to their default value - set_options_default(OPT_FREE); - // set 'laststatus' last_status(false); @@ -399,7 +396,7 @@ void set_init_1(bool clean_arg) // NOTE: mlterm's author is being asked to 'set' a variable // instead of an environment variable due to inheritance. if (os_env_exists("MLTERM")) { - set_option_value_give_err("tbidi", BOOLEAN_OPTVAL(true), 0); + set_option_value_give_err(kOptTermbidi, BOOLEAN_OPTVAL(true), 0); } didset_options2(); @@ -420,33 +417,35 @@ void set_init_1(bool clean_arg) /// Set an option to its default value. /// This does not take care of side effects! /// -/// @param opt_flags OPT_FREE, OPT_LOCAL and/or OPT_GLOBAL -static void set_option_default(const int opt_idx, int opt_flags) +/// @param opt_flags OPT_FREE, OPT_LOCAL and/or OPT_GLOBAL. +/// +/// TODO(famiu): Refactor this when def_val uses OptVal. +static void set_option_default(const OptIndex opt_idx, int opt_flags) { - int both = (opt_flags & (OPT_LOCAL | OPT_GLOBAL)) == 0; + bool both = (opt_flags & (OPT_LOCAL | OPT_GLOBAL)) == 0; // pointer to variable for current option vimoption_T *opt = &options[opt_idx]; void *varp = get_varp_scope(opt, both ? OPT_LOCAL : opt_flags); uint32_t flags = opt->flags; if (varp != NULL) { // skip hidden option, nothing to do for it - if (flags & P_STRING) { - // Use set_string_option_direct() for local options to handle - // freeing and allocating the value. + if (option_has_type(opt_idx, kOptValTypeString)) { + // Use set_string_option_direct() for local options to handle freeing and allocating the + // value. if (opt->indir != PV_NONE) { - set_string_option_direct(NULL, opt_idx, opt->def_val, opt_flags, 0); + set_string_option_direct(opt_idx, opt->def_val.string, opt_flags, 0); } else { - if ((opt_flags & OPT_FREE) && (flags & P_ALLOCED)) { + if (flags & P_ALLOCED) { free_string_option(*(char **)(varp)); } - *(char **)varp = opt->def_val; + *(char **)varp = opt->def_val.string; opt->flags &= ~P_ALLOCED; } - } else if (flags & P_NUM) { + } else if (option_has_type(opt_idx, kOptValTypeNumber)) { if (opt->indir == PV_SCROLL) { win_comp_scroll(curwin); } else { - OptInt def_val = (OptInt)(intptr_t)opt->def_val; + OptInt def_val = opt->def_val.number; if ((OptInt *)varp == &curwin->w_p_so || (OptInt *)varp == &curwin->w_p_siso) { // 'scrolloff' and 'sidescrolloff' local values have a @@ -460,8 +459,8 @@ static void set_option_default(const int opt_idx, int opt_flags) *(OptInt *)get_varp_scope(opt, OPT_GLOBAL) = def_val; } } - } else { // P_BOOL - *(int *)varp = (int)(intptr_t)opt->def_val; + } else { // boolean + *(int *)varp = opt->def_val.boolean; #ifdef UNIX // 'modeline' defaults to off for root if (opt->indir == PV_ML && getuid() == ROOT_UID) { @@ -480,17 +479,17 @@ static void set_option_default(const int opt_idx, int opt_flags) *flagsp = *flagsp & ~P_INSECURE; } - set_option_sctx_idx(opt_idx, opt_flags, current_sctx); + set_option_sctx(opt_idx, opt_flags, current_sctx); } /// Set all options (except terminal options) to their default value. /// -/// @param opt_flags OPT_FREE, OPT_LOCAL and/or OPT_GLOBAL +/// @param opt_flags Option flags. static void set_options_default(int opt_flags) { - for (int i = 0; options[i].fullname; i++) { - if (!(options[i].flags & P_NODEFAULT)) { - set_option_default(i, opt_flags); + for (OptIndex opt_idx = 0; opt_idx < kOptIndexCount; opt_idx++) { + if (!(options[opt_idx].flags & P_NODEFAULT)) { + set_option_default(opt_idx, opt_flags); } } @@ -505,22 +504,23 @@ static void set_options_default(int opt_flags) /// Set the Vi-default value of a string option. /// Used for 'sh', 'backupskip' and 'term'. /// -/// @param name The name of the option -/// @param val The value of the option -/// @param allocated If true, do not copy default as it was already allocated. -static void set_string_default(const char *name, char *val, bool allocated) +/// @param opt_idx Option index in options[] table. +/// @param val The value of the option. +/// @param allocated If true, do not copy default as it was already allocated. +static void set_string_default(OptIndex opt_idx, char *val, bool allocated) FUNC_ATTR_NONNULL_ALL { - int opt_idx = findoption(name); - if (opt_idx >= 0) { - vimoption_T *opt = &options[opt_idx]; - if (opt->flags & P_DEF_ALLOCED) { - xfree(opt->def_val); - } + if (opt_idx == kOptInvalid) { + return; + } - opt->def_val = allocated ? val : xstrdup(val); - opt->flags |= P_DEF_ALLOCED; + vimoption_T *opt = &options[opt_idx]; + if (opt->flags & P_DEF_ALLOCED) { + xfree(opt->def_val.string); } + + opt->def_val.string = allocated ? val : xstrdup(val); + opt->flags |= P_DEF_ALLOCED; } /// For an option value that contains comma separated items, find "newval" in @@ -556,11 +556,10 @@ static char *find_dup_item(char *origval, const char *newval, uint32_t flags) /// Set the Vi-default value of a number option. /// Used for 'lines' and 'columns'. -void set_number_default(char *name, OptInt val) +void set_number_default(OptIndex opt_idx, OptInt val) { - int opt_idx = findoption(name); - if (opt_idx >= 0) { - options[opt_idx].def_val = (void *)(intptr_t)val; + if (opt_idx != kOptInvalid) { + options[opt_idx].def_val.number = val; } } @@ -568,22 +567,25 @@ void set_number_default(char *name, OptInt val) /// Free all options. void free_all_options(void) { - for (int i = 0; options[i].fullname; i++) { - if (options[i].indir == PV_NONE) { + for (OptIndex opt_idx = 0; opt_idx < kOptIndexCount; opt_idx++) { + if (options[opt_idx].indir == PV_NONE) { // global option: free value and default value. - if ((options[i].flags & P_ALLOCED) && options[i].var != NULL) { - optval_free(optval_from_varp(i, options[i].var)); + if ((options[opt_idx].flags & P_ALLOCED) && options[opt_idx].var != NULL) { + optval_free(optval_from_varp(opt_idx, options[opt_idx].var)); } - if (options[i].flags & P_DEF_ALLOCED) { - optval_free(optval_from_varp(i, &options[i].def_val)); + if (options[opt_idx].flags & P_DEF_ALLOCED) { + optval_free(optval_from_varp(opt_idx, &options[opt_idx].def_val)); } - } else if (options[i].var != VAR_WIN) { + } else if (options[opt_idx].var != VAR_WIN) { // buffer-local option: free global value - optval_free(optval_from_varp(i, options[i].var)); + optval_free(optval_from_varp(opt_idx, options[opt_idx].var)); } } free_operatorfunc_option(); free_tagfunc_option(); + XFREE_CLEAR(fenc_default); + XFREE_CLEAR(p_term); + XFREE_CLEAR(p_ttytype); } #endif @@ -595,18 +597,17 @@ void set_init_2(bool headless) // 'scroll' defaults to half the window height. The stored default is zero, // which results in the actual value computed from the window height. - int idx = findoption("scroll"); - if (idx >= 0 && !(options[idx].flags & P_WAS_SET)) { - set_option_default(idx, OPT_LOCAL); + if (!(options[kOptScroll].flags & P_WAS_SET)) { + set_option_default(kOptScroll, OPT_LOCAL); } comp_col(); // 'window' is only for backwards compatibility with Vi. // Default is Rows - 1. - if (!option_was_set("window")) { + if (!option_was_set(kOptWindow)) { p_window = Rows - 1; } - set_number_default("window", Rows - 1); + set_number_default(kOptWindow, Rows - 1); } /// Initialize the options, part three: After reading the .vimrc @@ -617,14 +618,8 @@ void set_init_3(void) // Set 'shellpipe' and 'shellredir', depending on the 'shell' option. // This is done after other initializations, where 'shell' might have been // set, but only if they have not been set before. - int idx_srr = findoption("srr"); - int do_srr = (idx_srr < 0) - ? false - : !(options[idx_srr].flags & P_WAS_SET); - int idx_sp = findoption("sp"); - int do_sp = (idx_sp < 0) - ? false - : !(options[idx_sp].flags & P_WAS_SET); + bool do_srr = !(options[kOptShellredir].flags & P_WAS_SET); + bool do_sp = !(options[kOptShellpipe].flags & P_WAS_SET); size_t len = 0; char *p = (char *)invocation_path_tail(p_sh, &len); @@ -639,11 +634,11 @@ void set_init_3(void) || path_fnamecmp(p, "tcsh") == 0) { if (do_sp) { p_sp = "|& tee"; - options[idx_sp].def_val = p_sp; + options[kOptShellpipe].def_val.string = p_sp; } if (do_srr) { p_srr = ">&"; - options[idx_srr].def_val = p_srr; + options[kOptShellredir].def_val.string = p_srr; } } else if (path_fnamecmp(p, "sh") == 0 || path_fnamecmp(p, "ksh") == 0 @@ -658,18 +653,18 @@ void set_init_3(void) // Always use POSIX shell style redirection if we reach this if (do_sp) { p_sp = "2>&1| tee"; - options[idx_sp].def_val = p_sp; + options[kOptShellpipe].def_val.string = p_sp; } if (do_srr) { p_srr = ">%s 2>&1"; - options[idx_srr].def_val = p_srr; + options[kOptShellredir].def_val.string = p_srr; } } xfree(p); } if (buf_is_empty(curbuf)) { - int idx_ffs = findoption_len(S_LEN("ffs")); + int idx_ffs = find_option("ffs"); // Apply the first entry of 'fileformats' to the initial buffer. if (idx_ffs >= 0 && (options[idx_ffs].flags & P_WAS_SET)) { @@ -692,12 +687,11 @@ void set_helplang_default(const char *lang) if (lang_len < 2) { // safety check return; } - int idx = findoption("hlg"); - if (idx < 0 || (options[idx].flags & P_WAS_SET)) { + if (options[kOptHelplang].flags & P_WAS_SET) { return; } - if (options[idx].flags & P_ALLOCED) { + if (options[kOptHelplang].flags & P_ALLOCED) { free_string_option(p_hlg); } p_hlg = xmemdupz(lang, lang_len); @@ -711,7 +705,7 @@ void set_helplang_default(const char *lang) p_hlg[1] = 'n'; } p_hlg[2] = NUL; - options[idx].flags |= P_ALLOCED; + options[kOptHelplang].flags |= P_ALLOCED; } /// 'title' and 'icon' only default to true if they have not been set or reset @@ -724,15 +718,13 @@ void set_title_defaults(void) // If GUI is (going to be) used, we can always set the window title and // icon name. Saves a bit of time, because the X11 display server does // not need to be contacted. - int idx1 = findoption("title"); - if (idx1 >= 0 && !(options[idx1].flags & P_WAS_SET)) { - options[idx1].def_val = 0; - p_title = 0; + if (!(options[kOptTitle].flags & P_WAS_SET)) { + options[kOptTitle].def_val.boolean = false; + p_title = false; } - idx1 = findoption("icon"); - if (idx1 >= 0 && !(options[idx1].flags & P_WAS_SET)) { - options[idx1].def_val = 0; - p_icon = 0; + if (!(options[kOptIcon].flags & P_WAS_SET)) { + options[kOptIcon].def_val.boolean = false; + p_icon = false; } } @@ -748,13 +740,13 @@ void ex_set(exarg_T *eap) if (eap->forceit) { flags |= OPT_ONECOLUMN; } - (void)do_set(eap->arg, flags); + do_set(eap->arg, flags); } /// Get the default value for a string option. -static char *stropt_get_default_val(int opt_idx, uint64_t flags) +static char *stropt_get_default_val(OptIndex opt_idx, uint64_t flags) { - char *newval = options[opt_idx].def_val; + char *newval = options[opt_idx].def_val.string; // expand environment variables and ~ since the default value was // already expanded, only required when an environment variable was set // later @@ -773,8 +765,7 @@ static char *stropt_get_default_val(int opt_idx, uint64_t flags) } /// Copy the new string value into allocated memory for the option. -/// Can't use set_string_option_direct(), because we need to remove the -/// backslashes. +/// Can't use set_string_option_direct(), because we need to remove the backslashes. static char *stropt_copy_value(char *origval, char **argp, set_op_T op, uint32_t flags FUNC_ATTR_UNUSED) { @@ -822,7 +813,7 @@ static char *stropt_copy_value(char *origval, char **argp, set_op_T op, } /// Expand environment variables and ~ in string option value 'newval'. -static char *stropt_expand_envvar(int opt_idx, char *origval, char *newval, set_op_T op) +static char *stropt_expand_envvar(OptIndex opt_idx, char *origval, char *newval, set_op_T op) { char *s = option_expand(opt_idx, newval); if (s == NULL) { @@ -922,8 +913,8 @@ static void stropt_remove_dupflags(char *newval, uint32_t flags) /// set {opt}< /// set {opt}={val} /// set {opt}:{val} -static char *stropt_get_newval(int nextchar, int opt_idx, char **argp, void *varp, char *origval, - set_op_T *op_arg, uint32_t flags) +static char *stropt_get_newval(int nextchar, OptIndex opt_idx, char **argp, void *varp, + char *origval, set_op_T *op_arg, uint32_t flags) { char *arg = *argp; set_op_T op = *op_arg; @@ -1024,81 +1015,23 @@ static set_prefix_T get_option_prefix(char **argp) return PREFIX_NONE; } -/// @param[in] arg Pointer to start option name -/// @param[out] opt_idxp Option index in options[] table. -/// @param[out] keyp -/// @param[out] len Length of option name -/// @return FAIL if an error is detected, OK otherwise -static int parse_option_name(char *arg, int *keyp, int *lenp, int *opt_idxp) -{ - // find end of name - int key = 0; - int len; - int opt_idx; - - if (*arg == '<') { - opt_idx = -1; - // look out for <t_>;> - if (arg[1] == 't' && arg[2] == '_' && arg[3] && arg[4]) { - len = 5; - } else { - len = 1; - while (arg[len] != NUL && arg[len] != '>') { - len++; - } - } - if (arg[len] != '>') { - return FAIL; - } - if (arg[1] == 't' && arg[2] == '_') { // could be term code - opt_idx = findoption_len(arg + 1, (size_t)(len - 1)); - } - len++; - if (opt_idx == -1) { - key = find_key_option(arg + 1, true); - } - } else { - // The two characters after "t_" may not be alphanumeric. - if (arg[0] == 't' && arg[1] == '_' && arg[2] && arg[3]) { - len = 4; - } else { - len = 0; - while (ASCII_ISALNUM(arg[len]) || arg[len] == '_') { - len++; - } - } - opt_idx = findoption_len(arg, (size_t)len); - if (opt_idx == -1) { - key = find_key_option(arg, false); - } - } - - *keyp = key; - *lenp = len; - *opt_idxp = opt_idx; - - return OK; -} - -static int validate_opt_idx(win_T *win, int opt_idx, int opt_flags, uint32_t flags, +static int validate_opt_idx(win_T *win, OptIndex opt_idx, int opt_flags, uint32_t flags, set_prefix_T prefix, const char **errmsg) { // Only bools can have a prefix of 'inv' or 'no' - if (!(flags & P_BOOL) && prefix != PREFIX_NONE) { + if (!option_has_type(opt_idx, kOptValTypeBoolean) && prefix != PREFIX_NONE) { *errmsg = e_invarg; return FAIL; } // Skip all options that are not window-local (used when showing // an already loaded buffer in a window). - if ((opt_flags & OPT_WINONLY) - && (opt_idx < 0 || options[opt_idx].var != VAR_WIN)) { + if ((opt_flags & OPT_WINONLY) && (opt_idx == kOptInvalid || options[opt_idx].var != VAR_WIN)) { return FAIL; } // Skip all options that are window-local (used for :vimgrep). - if ((opt_flags & OPT_NOWIN) && opt_idx >= 0 - && options[opt_idx].var == VAR_WIN) { + if ((opt_flags & OPT_NOWIN) && opt_idx != kOptInvalid && options[opt_idx].var == VAR_WIN) { return FAIL; } @@ -1116,7 +1049,7 @@ static int validate_opt_idx(win_T *win, int opt_idx, int opt_flags, uint32_t fla // 'foldmethod' becomes "marker" instead of "diff" and that // "wrap" gets set. if (win->w_p_diff - && opt_idx >= 0 // shut up coverity warning + && opt_idx != kOptInvalid // shut up coverity warning && (options[opt_idx].indir == PV_FDM || options[opt_idx].indir == PV_WRAP)) { return FAIL; @@ -1132,8 +1065,79 @@ static int validate_opt_idx(win_T *win, int opt_idx, int opt_flags, uint32_t fla return OK; } +/// Skip over the name of a TTY option or keycode option. +/// +/// @param[in] arg Start of TTY or keycode option name. +/// +/// @return NULL when option isn't a TTY or keycode option. Otherwise pointer to the char after the +/// option name. +static const char *find_tty_option_end(const char *arg) +{ + if (strequal(arg, "term")) { + return arg + sizeof("term") - 1; + } else if (strequal(arg, "ttytype")) { + return arg + sizeof("ttytype") - 1; + } + + const char *p = arg; + bool delimit = false; // whether to delimit < + + if (arg[0] == '<') { + // look out for <t_>;> + delimit = true; + p++; + } + if (p[0] == 't' && p[1] == '_' && p[2] && p[3]) { + p += 4; + } else if (delimit) { + // Search for delimiting >. + while (*p != NUL && *p != '>') { + p++; + } + } + // Return NULL when delimiting > is not found. + if (delimit) { + if (*p != '>') { + return NULL; + } + p++; + } + + return arg == p ? NULL : p; +} + +/// Skip over the name of an option. +/// +/// @param[in] arg Start of option name. +/// @param[out] opt_idxp Set to option index in options[] table. +/// +/// @return NULL when no option name found. Otherwise pointer to the char after the option name. +const char *find_option_end(const char *arg, OptIndex *opt_idxp) +{ + const char *p; + + // Handle TTY and keycode options separately. + if ((p = find_tty_option_end(arg)) != NULL) { + *opt_idxp = kOptInvalid; + return p; + } else { + p = arg; + } + + if (!ASCII_ISALPHA(*p)) { + *opt_idxp = kOptInvalid; + return NULL; + } + while (ASCII_ISALPHA(*p)) { + p++; + } + + *opt_idxp = find_option_len(arg, (size_t)(p - arg)); + return p; +} + /// Get new option value from argp. Allocated OptVal must be freed by caller. -static OptVal get_option_newval(int opt_idx, int opt_flags, set_prefix_T prefix, char **argp, +static OptVal get_option_newval(OptIndex opt_idx, int opt_flags, set_prefix_T prefix, char **argp, int nextchar, set_op_T op, uint32_t flags, void *varp, char *errbuf, const size_t errbuflen, const char **errmsg) FUNC_ATTR_WARN_UNUSED_RESULT @@ -1169,7 +1173,7 @@ static OptVal get_option_newval(int opt_idx, int opt_flags, set_prefix_T prefix, break; } } else if (nextchar == '&') { - newval_bool = TRISTATE_FROM_INT((int)(intptr_t)options[opt_idx].def_val); + newval_bool = TRISTATE_FROM_INT(options[opt_idx].def_val.boolean); } else if (nextchar == '<') { // For 'autoread', kNone means to use global value. if ((int *)varp == &curbuf->b_p_ar && opt_flags == OPT_LOCAL) { @@ -1203,7 +1207,7 @@ static OptVal get_option_newval(int opt_idx, int opt_flags, set_prefix_T prefix, // other error arg++; if (nextchar == '&') { - newval_num = (OptInt)(intptr_t)options[opt_idx].def_val; + newval_num = options[opt_idx].def_val.number; } else if (nextchar == '<') { if ((OptInt *)varp == &curbuf->b_p_ul && opt_flags == OPT_LOCAL) { // for 'undolevels' NO_LOCAL_UNDOLEVEL means using the global newval_num @@ -1271,61 +1275,56 @@ static void do_one_set_option(int opt_flags, char **argp, bool *did_show, char * char *arg = *argp; // find end of name - int key = 0; - int len; - int opt_idx; - if (parse_option_name(arg, &key, &len, &opt_idx) == FAIL) { - *errmsg = e_invarg; + OptIndex opt_idx; + const char *const option_end = find_option_end(arg, &opt_idx); + + if (opt_idx != kOptInvalid) { + assert(option_end >= arg); + } else if (is_tty_option(arg)) { // Silently ignore TTY options. + return; + } else { // Invalid option name, skip. + *errmsg = e_unknown_option; return; } - // remember character after option name - int afterchar = (uint8_t)arg[len]; + // Remember character after option name. + uint8_t afterchar = (uint8_t)(*option_end); + char *p = (char *)option_end; - // skip white space, allow ":set ai ?" - while (ascii_iswhite(arg[len])) { - len++; + // Skip white space, allow ":set ai ?". + while (ascii_iswhite(*p)) { + p++; } - set_op_T op = get_op(arg + len); + set_op_T op = get_op(p); if (op != OP_NONE) { - len++; - } - - uint8_t nextchar = (uint8_t)arg[len]; // next non-white char after option name - - if (opt_idx == -1 && key == 0) { // found a mismatch: skip - *errmsg = e_unknown_option; - return; + p++; } - uint32_t flags; // flags for current option + uint8_t nextchar = (uint8_t)(*p); // next non-white char after option name + uint32_t flags = 0; // flags for current option void *varp = NULL; // pointer to variable for current option - if (opt_idx >= 0) { - if (options[opt_idx].var == NULL) { // hidden option: skip - // Only give an error message when requesting the value of - // a hidden option, ignore setting it. - if (vim_strchr("=:!&<", nextchar) == NULL - && (!(options[opt_idx].flags & P_BOOL) - || nextchar == '?')) { - *errmsg = e_unsupportedoption; - } - return; + if (options[opt_idx].var == NULL) { // hidden option: skip + // Only give an error message when requesting the value of + // a hidden option, ignore setting it. + if (vim_strchr("=:!&<", nextchar) == NULL + && (!option_has_type(opt_idx, kOptValTypeBoolean) || nextchar == '?')) { + *errmsg = e_unsupportedoption; } - - flags = options[opt_idx].flags; - varp = get_varp_scope(&(options[opt_idx]), opt_flags); - } else { - flags = P_STRING; + return; } + flags = options[opt_idx].flags; + varp = get_varp_scope(&(options[opt_idx]), opt_flags); + if (validate_opt_idx(curwin, opt_idx, opt_flags, flags, prefix, errmsg) == FAIL) { return; } if (vim_strchr("?=:!&<", nextchar) != NULL) { - *argp += len; + *argp = p; + if (nextchar == '&' && (*argp)[1] == 'v' && (*argp)[2] == 'i') { if ((*argp)[3] == 'm') { // "opt&vim": set to Vim default *argp += 3; @@ -1340,14 +1339,10 @@ static void do_one_set_option(int opt_flags, char **argp, bool *did_show, char * } } - // - // allow '=' and ':' as MS-DOS command.com allows only one - // '=' character per "set" command line. grrr. (jw) - // + // Allow '=' and ':' as MS-DOS command.com allows only one '=' character per "set" command line. if (nextchar == '?' - || (prefix == PREFIX_NONE - && vim_strchr("=:&<", nextchar) == NULL - && !(flags & P_BOOL))) { + || (prefix == PREFIX_NONE && vim_strchr("=:&<", nextchar) == NULL + && !option_has_type(opt_idx, kOptValTypeBoolean))) { // print value if (*did_show) { msg_putchar('\n'); // cursor below last one @@ -1355,29 +1350,26 @@ static void do_one_set_option(int opt_flags, char **argp, bool *did_show, char * gotocmdline(true); // cursor at status line *did_show = true; // remember that we did a line } - if (opt_idx >= 0) { - showoneopt(&options[opt_idx], opt_flags); - if (p_verbose > 0) { - // Mention where the option was last set. - if (varp == options[opt_idx].var) { - option_last_set_msg(options[opt_idx].last_set); - } else if ((int)options[opt_idx].indir & PV_WIN) { - option_last_set_msg(curwin->w_p_script_ctx[(int)options[opt_idx].indir & PV_MASK]); - } else if ((int)options[opt_idx].indir & PV_BUF) { - option_last_set_msg(curbuf->b_p_script_ctx[(int)options[opt_idx].indir & PV_MASK]); - } + showoneopt(&options[opt_idx], opt_flags); + + if (p_verbose > 0) { + // Mention where the option was last set. + if (varp == options[opt_idx].var) { + option_last_set_msg(options[opt_idx].last_set); + } else if ((int)options[opt_idx].indir & PV_WIN) { + option_last_set_msg(curwin->w_p_script_ctx[(int)options[opt_idx].indir & PV_MASK]); + } else if ((int)options[opt_idx].indir & PV_BUF) { + option_last_set_msg(curbuf->b_p_script_ctx[(int)options[opt_idx].indir & PV_MASK]); } - } else { - *errmsg = e_key_code_not_set; - return; } + if (nextchar != '?' && nextchar != NUL && !ascii_iswhite(afterchar)) { *errmsg = e_trailing; } return; } - if (flags & P_BOOL) { + if (option_has_type(opt_idx, kOptValTypeBoolean)) { if (vim_strchr("=:", nextchar) != NULL) { *errmsg = e_invarg; return; @@ -1441,7 +1433,7 @@ int do_set(char *arg, int opt_flags) if (*arg == '&') { arg++; // Only for :set command set global value of local options. - set_options_default(OPT_FREE | opt_flags); + set_options_default(opt_flags); didset_options(); didset_options2(); ui_refresh_options(); @@ -1453,7 +1445,7 @@ int do_set(char *arg, int opt_flags) } else { char *startarg = arg; // remember for error message const char *errmsg = NULL; - char errbuf[80]; + char errbuf[ERR_BUFLEN]; do_one_set_option(opt_flags, &arg, &did_show, errbuf, sizeof(errbuf), &errmsg); @@ -1497,21 +1489,45 @@ int do_set(char *arg, int opt_flags) if (silent_mode && did_show) { // After displaying option values in silent mode. silent_mode = false; - info_message = true; // use os_msg(), not os_errmsg() + info_message = true; // use stdout, not stderr msg_putchar('\n'); silent_mode = true; - info_message = false; // use os_msg(), not os_errmsg() + info_message = false; // use stdout, not stderr } return OK; } +// Translate a string like "t_xx", "<t_xx>" or "<S-Tab>" to a key number. +// When "has_lt" is true there is a '<' before "*arg_arg". +// Returns 0 when the key is not recognized. +static int find_key_len(const char *arg_arg, size_t len, bool has_lt) +{ + int key = 0; + const char *arg = arg_arg; + + // Don't use get_special_key_code() for t_xx, we don't want it to call + // add_termcap_entry(). + if (len >= 4 && arg[0] == 't' && arg[1] == '_') { + key = TERMCAP2KEY((uint8_t)arg[2], (uint8_t)arg[3]); + } else if (has_lt) { + arg--; // put arg at the '<' + int modifiers = 0; + key = find_special_key(&arg, len + 1, &modifiers, FSK_KEYCODE | FSK_KEEP_X_KEY | FSK_SIMPLIFY, + NULL); + if (modifiers) { // can't handle modifiers here + key = 0; + } + } + return key; +} + /// Convert a key name or string into a key value. /// Used for 'wildchar' and 'cedit' options. int string_to_key(char *arg) { if (*arg == '<') { - return find_key_option(arg + 1, true); + return find_key_len(arg + 1, strlen(arg), true); } if (*arg == '^') { return CTRL_CHR((uint8_t)arg[1]); @@ -1623,7 +1639,7 @@ char *find_shada_parameter(int type) /// These string options cannot be indirect! /// If "val" is NULL expand the current value of the option. /// Return pointer to NameBuff, or NULL when not expanded. -static char *option_expand(int opt_idx, char *val) +static char *option_expand(OptIndex opt_idx, char *val) { // if option doesn't need expansion nothing to do if (!(options[opt_idx].flags & P_EXPAND) || options[opt_idx].var == NULL) { @@ -1660,18 +1676,18 @@ static char *option_expand(int opt_idx, char *val) static void didset_options(void) { // initialize the table for 'iskeyword' et.al. - (void)init_chartab(); + init_chartab(); didset_string_options(); - (void)spell_check_msm(); - (void)spell_check_sps(); - (void)compile_cap_prog(curwin->w_s); - (void)did_set_spell_option(true); + spell_check_msm(); + spell_check_sps(); + compile_cap_prog(curwin->w_s); + did_set_spell_option(true); // set cedit_key - (void)did_set_cedit(NULL); + did_set_cedit(NULL); // initialize the table for 'breakat'. - (void)did_set_breakat(NULL); + did_set_breakat(NULL); didset_window_options(curwin, true); } @@ -1682,49 +1698,49 @@ static void didset_options2(void) highlight_changed(); // Parse default for 'fillchars'. - (void)set_fillchars_option(curwin, curwin->w_p_fcs, true); + set_chars_option(curwin, curwin->w_p_fcs, kFillchars, true, NULL, 0); // Parse default for 'listchars'. - (void)set_listchars_option(curwin, curwin->w_p_lcs, true); + set_chars_option(curwin, curwin->w_p_lcs, kListchars, true, NULL, 0); // Parse default for 'wildmode'. check_opt_wim(); xfree(curbuf->b_p_vsts_array); - (void)tabstop_set(curbuf->b_p_vsts, &curbuf->b_p_vsts_array); + tabstop_set(curbuf->b_p_vsts, &curbuf->b_p_vsts_array); xfree(curbuf->b_p_vts_array); - (void)tabstop_set(curbuf->b_p_vts, &curbuf->b_p_vts_array); + tabstop_set(curbuf->b_p_vts, &curbuf->b_p_vts_array); } /// Check for string options that are NULL (normally only termcap options). void check_options(void) { - for (int opt_idx = 0; options[opt_idx].fullname != NULL; opt_idx++) { - if ((options[opt_idx].flags & P_STRING) && options[opt_idx].var != NULL) { + for (OptIndex opt_idx = 0; opt_idx < kOptIndexCount; opt_idx++) { + if ((option_has_type(opt_idx, kOptValTypeString)) && options[opt_idx].var != NULL) { check_string_option((char **)get_varp(&(options[opt_idx]))); } } } -/// Return true when option "opt" was set from a modeline or in secure mode. -/// Return false when it wasn't. -/// Return -1 for an unknown option. -int was_set_insecurely(win_T *const wp, char *opt, int opt_flags) +/// Check if option was set insecurely. +/// +/// @param wp Window. +/// @param opt_idx Option index in options[] table. +/// @param opt_flags Option flags. +/// +/// @return True if option was set from a modeline or in secure mode, false if it wasn't. +int was_set_insecurely(win_T *const wp, OptIndex opt_idx, int opt_flags) { - int idx = findoption(opt); + assert(opt_idx != kOptInvalid); - if (idx >= 0) { - uint32_t *flagp = insecure_flag(wp, idx, opt_flags); - return (*flagp & P_INSECURE) != 0; - } - internal_error("was_set_insecurely()"); - return -1; + uint32_t *flagp = insecure_flag(wp, opt_idx, opt_flags); + return (*flagp & P_INSECURE) != 0; } /// Get a pointer to the flags used for the P_INSECURE flag of option /// "opt_idx". For some local options a local flags field is used. /// NOTE: Caller must make sure that "wp" is set to the window from which /// the option is used. -uint32_t *insecure_flag(win_T *const wp, int opt_idx, int opt_flags) +uint32_t *insecure_flag(win_T *const wp, OptIndex opt_idx, int opt_flags) { if (opt_flags & OPT_LOCAL) { assert(wp != NULL); @@ -1774,7 +1790,7 @@ bool valid_name(const char *val, const char *allowed) void check_blending(win_T *wp) { wp->w_grid_alloc.blending = - wp->w_p_winbl > 0 || (wp->w_floating && wp->w_float_config.shadow); + wp->w_p_winbl > 0 || (wp->w_floating && wp->w_config.shadow); } /// Handle setting `winhighlight' in window "wp" @@ -1827,23 +1843,18 @@ bool parse_winhl_opt(win_T *wp) return true; } -/// Get the script context of global option "name". -sctx_T *get_option_sctx(const char *const name) +/// Get the script context of global option at index opt_idx. +sctx_T *get_option_sctx(OptIndex opt_idx) { - int idx = findoption(name); - - if (idx >= 0) { - return &options[idx].last_set.script_ctx; - } - siemsg("no such option: %s", name); - return NULL; + assert(opt_idx != kOptInvalid); + return &options[opt_idx].last_set.script_ctx; } /// Set the script_ctx for an option, taking care of setting the buffer- or /// window-local value. -void set_option_sctx_idx(int opt_idx, int opt_flags, sctx_T script_ctx) +void set_option_sctx(OptIndex opt_idx, int opt_flags, sctx_T script_ctx) { - int both = (opt_flags & (OPT_LOCAL | OPT_GLOBAL)) == 0; + bool both = (opt_flags & (OPT_LOCAL | OPT_GLOBAL)) == 0; int indir = (int)options[opt_idx].indir; nlua_set_sctx(&script_ctx); LastSet last_set = { @@ -1875,7 +1886,7 @@ void set_option_sctx_idx(int opt_idx, int opt_flags, sctx_T script_ctx) } /// Apply the OptionSet autocommand. -static void apply_optionset_autocmd(int opt_idx, int opt_flags, OptVal oldval, OptVal oldval_g, +static void apply_optionset_autocmd(OptIndex opt_idx, int opt_flags, OptVal oldval, OptVal oldval_g, OptVal oldval_l, OptVal newval, const char *errmsg) { // Don't do this while starting up, failure or recursively. @@ -1884,10 +1895,10 @@ static void apply_optionset_autocmd(int opt_idx, int opt_flags, OptVal oldval, O } char buf_type[7]; - typval_T oldval_tv = optval_as_tv(oldval); - typval_T oldval_g_tv = optval_as_tv(oldval_g); - typval_T oldval_l_tv = optval_as_tv(oldval_l); - typval_T newval_tv = optval_as_tv(newval); + typval_T oldval_tv = optval_as_tv(oldval, false); + typval_T oldval_g_tv = optval_as_tv(oldval_g, false); + typval_T oldval_l_tv = optval_as_tv(oldval_l, false); + typval_T newval_tv = optval_as_tv(newval, false); vim_snprintf(buf_type, sizeof(buf_type), "%s", (opt_flags & OPT_LOCAL) ? "local" : "global"); set_vim_var_tv(VV_OPTION_NEW, &newval_tv); @@ -1950,7 +1961,7 @@ static const char *did_set_arabic(optset_T *args) p_deco = true; // Force-set the necessary keymap for arabic. - errmsg = set_option_value("keymap", STATIC_CSTR_AS_OPTVAL("arabic"), OPT_LOCAL); + errmsg = set_option_value(kOptKeymap, STATIC_CSTR_AS_OPTVAL("arabic"), OPT_LOCAL); } else { // 'arabic' is reset, handle various sub-settings. if (!p_tbidi) { @@ -1995,22 +2006,6 @@ static const char *did_set_binary(optset_T *args) return NULL; } -/// Called when the 'breakat' option changes value. -static const char *did_set_breakat(optset_T *args FUNC_ATTR_UNUSED) -{ - for (int i = 0; i < 256; i++) { - breakat_flags[i] = false; - } - - if (p_breakat != NULL) { - for (char *p = p_breakat; *p; p++) { - breakat_flags[(uint8_t)(*p)] = true; - } - } - - return NULL; -} - /// Process the updated 'buflisted' option value. static const char *did_set_buflisted(optset_T *args) { @@ -2174,26 +2169,64 @@ static const char *did_set_laststatus(optset_T *args) // Also clear the cmdline to remove the ruler if there is one if (value == 3 && old_value != 3) { frame_new_height(topframe, topframe->fr_height - STATUS_HEIGHT, false, false); - (void)win_comp_pos(); + win_comp_pos(); clear_cmdline = true; } // When switching from global statusline, increase height of topframe by STATUS_HEIGHT // in order to to re-add the space that was previously taken by the global statusline if (old_value == 3 && value != 3) { frame_new_height(topframe, topframe->fr_height + STATUS_HEIGHT, false, false); - (void)win_comp_pos(); + win_comp_pos(); } last_status(false); // (re)set last window status line. return NULL; } +/// Process the updated 'lines' or 'columns' option value. +static const char *did_set_lines_or_columns(optset_T *args) +{ + // If the screen (shell) height has been changed, assume it is the + // physical screenheight. + if (p_lines != Rows || p_columns != Columns) { + // Changing the screen size is not allowed while updating the screen. + if (updating_screen) { + OptVal oldval = (OptVal){ .type = kOptValTypeNumber, .data = args->os_oldval }; + set_option_varp(args->os_idx, args->os_varp, oldval, false); + } else if (full_screen) { + screen_resize((int)p_columns, (int)p_lines); + } else { + // TODO(bfredl): is this branch ever needed? + // Postpone the resizing; check the size and cmdline position for + // messages. + Rows = (int)p_lines; + Columns = (int)p_columns; + check_screensize(); + int new_row = (int)(Rows - MAX(p_ch, 1)); + if (cmdline_row > new_row && Rows > p_ch) { + assert(p_ch >= 0 && new_row <= INT_MAX); + cmdline_row = new_row; + } + } + if (p_window >= Rows || !option_was_set(kOptWindow)) { + p_window = Rows - 1; + } + } + + // Adjust 'scrolljump' if needed. + if (p_sj >= Rows && full_screen) { + p_sj = Rows / 2; + } + + return NULL; +} + /// Process the updated 'lisp' option value. static const char *did_set_lisp(optset_T *args) { buf_T *buf = (buf_T *)args->os_buf; // When 'lisp' option changes include/exclude '-' in keyword characters. - (void)buf_init_chartab(buf, false); // ignore errors + buf_init_chartab(buf, false); // ignore errors return NULL; } @@ -2334,7 +2367,7 @@ static const char *did_set_paste(optset_T *args FUNC_ATTR_UNUSED) buf->b_p_vsts = buf->b_p_vsts_nopaste ? xstrdup(buf->b_p_vsts_nopaste) : empty_string_option; xfree(buf->b_p_vsts_array); if (buf->b_p_vsts && buf->b_p_vsts != empty_string_option) { - (void)tabstop_set(buf->b_p_vsts, &buf->b_p_vsts_array); + tabstop_set(buf->b_p_vsts, &buf->b_p_vsts_array); } else { buf->b_p_vsts_array = NULL; } @@ -2391,7 +2424,6 @@ static const char *did_set_previewwindow(optset_T *args) /// Process the new 'pumblend' option value. static const char *did_set_pumblend(optset_T *args FUNC_ATTR_UNUSED) { - p_pb = MAX(MIN(p_pb, 100), 0); hl_invalidate_blends(); pum_grid.blending = (p_pb > 0); if (pum_drawn()) { @@ -2762,231 +2794,224 @@ static void do_spelllang_source(win_T *win) } /// Check the bounds of numeric options. -static const char *check_num_option_bounds(OptInt *pp, OptInt old_value, char *errbuf, - size_t errbuflen, const char *errmsg) +/// +/// @param opt_idx Index in options[] table. Must not be kOptInvalid. +/// @param[in] varp Pointer to option variable. +/// @param[in,out] newval Pointer to new option value. Will be set to bound checked value. +/// @param[out] errbuf Buffer for error message. Cannot be NULL. +/// @param errbuflen Length of error buffer. +/// +/// @return Error message, if any. +static const char *check_num_option_bounds(OptIndex opt_idx, void *varp, OptInt *newval, + char *errbuf, size_t errbuflen) + FUNC_ATTR_NONNULL_ARG(4) { - int old_Rows = Rows; // remember old Rows - // Check the (new) bounds for Rows and Columns here. - if (p_lines < min_rows() && full_screen) { - if (errbuf != NULL) { + const char *errmsg = NULL; + + switch (opt_idx) { + case kOptLines: + if (*newval < min_rows() && full_screen) { vim_snprintf(errbuf, errbuflen, _("E593: Need at least %d lines"), min_rows()); errmsg = errbuf; + *newval = min_rows(); } - p_lines = min_rows(); - } - if (p_columns < MIN_COLUMNS && full_screen) { - if (errbuf != NULL) { + // True max size is defined by check_screensize(). + *newval = MIN(*newval, INT_MAX); + break; + case kOptColumns: + if (*newval < MIN_COLUMNS && full_screen) { vim_snprintf(errbuf, errbuflen, _("E594: Need at least %d columns"), MIN_COLUMNS); errmsg = errbuf; + *newval = MIN_COLUMNS; } - p_columns = MIN_COLUMNS; - } - - // True max size is defined by check_screensize() - p_lines = MIN(p_lines, INT_MAX); - p_columns = MIN(p_columns, INT_MAX); - - // If the screen (shell) height has been changed, assume it is the - // physical screenheight. - if (p_lines != Rows || p_columns != Columns) { - // Changing the screen size is not allowed while updating the screen. - if (updating_screen) { - *pp = old_value; - } else if (full_screen) { - screen_resize((int)p_columns, (int)p_lines); - } else { - // TODO(bfredl): is this branch ever needed? - // Postpone the resizing; check the size and cmdline position for - // messages. - Rows = (int)p_lines; - Columns = (int)p_columns; - check_screensize(); - int new_row = (int)(Rows - MAX(p_ch, 1)); - if (cmdline_row > new_row && Rows > p_ch) { - assert(p_ch >= 0 && new_row <= INT_MAX); - cmdline_row = new_row; - } - } - if (p_window >= Rows || !option_was_set("window")) { - p_window = Rows - 1; + // True max size is defined by check_screensize(). + *newval = MIN(*newval, INT_MAX); + break; + case kOptPumblend: + *newval = MAX(MIN(*newval, 100), 0); + break; + case kOptScrolljump: + if ((*newval < -100 || *newval >= Rows) && full_screen) { + errmsg = e_scroll; + *newval = 1; } - } - - if ((curwin->w_p_scr <= 0 || (curwin->w_p_scr > curwin->w_height && curwin->w_height > 0)) - && full_screen) { - if (pp == &(curwin->w_p_scr)) { - if (curwin->w_p_scr != 0) { + break; + case kOptScroll: + if (varp == &(curwin->w_p_scr) + && (*newval <= 0 + || (*newval > curwin->w_height_inner && curwin->w_height_inner > 0)) + && full_screen) { + if (*newval != 0) { errmsg = e_scroll; } - win_comp_scroll(curwin); - } else if (curwin->w_p_scr <= 0) { - // If 'scroll' became invalid because of a side effect silently adjust it. - curwin->w_p_scr = 1; - } else { // curwin->w_p_scr > curwin->w_height - curwin->w_p_scr = curwin->w_height; - } - } - if ((p_sj < -100 || p_sj >= Rows) && full_screen) { - if (Rows != old_Rows) { // Rows changed, just adjust p_sj - p_sj = Rows / 2; - } else { - errmsg = e_scroll; - p_sj = 1; + *newval = win_default_scroll(curwin); } + break; + default: + break; } return errmsg; } -/// Options that need some validation. -static const char *validate_num_option(const OptInt *pp, OptInt *valuep) +/// Validate and bound check option value. +/// +/// @param opt_idx Index in options[] table. Must not be kOptInvalid. +/// @param[in] varp Pointer to option variable. +/// @param[in,out] newval Pointer to new option value. Will be set to bound checked value. +/// @param[out] errbuf Buffer for error message. Cannot be NULL. +/// @param errbuflen Length of error buffer. +/// +/// @return Error message, if any. +static const char *validate_num_option(OptIndex opt_idx, void *varp, OptInt *newval, char *errbuf, + size_t errbuflen) { - OptInt value = *valuep; + OptInt value = *newval; // Many number options assume their value is in the signed int range. if (value < INT_MIN || value > INT_MAX) { return e_invarg; } - if (pp == &p_wh) { + if (varp == &p_wh) { if (value < 1) { return e_positive; } else if (p_wmh > value) { return e_winheight; } - } else if (pp == &p_hh) { + } else if (varp == &p_hh) { if (value < 0) { return e_positive; } - } else if (pp == &p_wmh) { + } else if (varp == &p_wmh) { if (value < 0) { return e_positive; } else if (value > p_wh) { return e_winheight; } - } else if (pp == &p_wiw) { + } else if (varp == &p_wiw) { if (value < 1) { return e_positive; } else if (p_wmw > value) { return e_winwidth; } - } else if (pp == &p_wmw) { + } else if (varp == &p_wmw) { if (value < 0) { return e_positive; } else if (value > p_wiw) { return e_winwidth; } - } else if (pp == &p_mco) { - *valuep = MAX_MCO; - } else if (pp == &p_titlelen) { + } else if (varp == &p_mco) { + *newval = MAX_MCO; + } else if (varp == &p_titlelen) { if (value < 0) { return e_positive; } - } else if (pp == &p_uc) { + } else if (varp == &p_uc) { if (value < 0) { return e_positive; } - } else if (pp == &p_ch) { + } else if (varp == &p_ch) { if (value < 0) { return e_positive; } else { p_ch_was_zero = value == 0; } - } else if (pp == &p_tm) { + } else if (varp == &p_tm) { if (value < 0) { return e_positive; } - } else if (pp == &p_hi) { + } else if (varp == &p_hi) { if (value < 0) { return e_positive; } else if (value > 10000) { return e_invarg; } - } else if (pp == &p_pyx) { + } else if (varp == &p_pyx) { if (value == 0) { - *valuep = 3; + *newval = 3; } else if (value != 3) { return e_invarg; } - } else if (pp == &p_re) { + } else if (varp == &p_re) { if (value < 0 || value > 2) { return e_invarg; } - } else if (pp == &p_report) { + } else if (varp == &p_report) { if (value < 0) { return e_positive; } - } else if (pp == &p_so) { + } else if (varp == &p_so) { if (value < 0 && full_screen) { return e_positive; } - } else if (pp == &p_siso) { + } else if (varp == &p_siso) { if (value < 0 && full_screen) { return e_positive; } - } else if (pp == &p_cwh) { + } else if (varp == &p_cwh) { if (value < 1) { return e_positive; } - } else if (pp == &p_ut) { + } else if (varp == &p_ut) { if (value < 0) { return e_positive; } - } else if (pp == &p_ss) { + } else if (varp == &p_ss) { if (value < 0) { return e_positive; } - } else if (pp == &curwin->w_p_fdl || pp == &curwin->w_allbuf_opt.wo_fdl) { + } else if (varp == &curwin->w_p_fdl || varp == &curwin->w_allbuf_opt.wo_fdl) { if (value < 0) { return e_positive; } - } else if (pp == &curwin->w_p_cole || pp == &curwin->w_allbuf_opt.wo_cole) { + } else if (varp == &curwin->w_p_cole || varp == &curwin->w_allbuf_opt.wo_cole) { if (value < 0) { return e_positive; } else if (value > 3) { return e_invarg; } - } else if (pp == &curwin->w_p_nuw || pp == &curwin->w_allbuf_opt.wo_nuw) { + } else if (varp == &curwin->w_p_nuw || varp == &curwin->w_allbuf_opt.wo_nuw) { if (value < 1) { return e_positive; } else if (value > MAX_NUMBERWIDTH) { return e_invarg; } - } else if (pp == &curbuf->b_p_iminsert || pp == &p_iminsert) { + } else if (varp == &curbuf->b_p_iminsert || varp == &p_iminsert) { if (value < 0 || value > B_IMODE_LAST) { return e_invarg; } - } else if (pp == &curbuf->b_p_imsearch || pp == &p_imsearch) { + } else if (varp == &curbuf->b_p_imsearch || varp == &p_imsearch) { if (value < -1 || value > B_IMODE_LAST) { return e_invarg; } - } else if (pp == &curbuf->b_p_channel || pp == &p_channel) { + } else if (varp == &curbuf->b_p_channel || varp == &p_channel) { return e_invarg; - } else if (pp == &curbuf->b_p_scbk || pp == &p_scbk) { + } else if (varp == &curbuf->b_p_scbk || varp == &p_scbk) { if (value < -1 || value > SB_MAX) { return e_invarg; } - } else if (pp == &curbuf->b_p_sw || pp == &p_sw) { + } else if (varp == &curbuf->b_p_sw || varp == &p_sw) { if (value < 0) { return e_positive; } - } else if (pp == &curbuf->b_p_ts || pp == &p_ts) { + } else if (varp == &curbuf->b_p_ts || varp == &p_ts) { if (value < 1) { return e_positive; } else if (value > TABSTOP_MAX) { return e_invarg; } - } else if (pp == &curbuf->b_p_tw || pp == &p_tw) { + } else if (varp == &curbuf->b_p_tw || varp == &p_tw) { if (value < 0) { return e_positive; } - } else if (pp == &p_wd) { + } else if (varp == &p_wd) { if (value < 0) { return e_positive; } } - return NULL; + return check_num_option_bounds(opt_idx, varp, newval, errbuf, errbuflen); } /// Called after an option changed: check if something needs to be redrawn. @@ -3004,14 +3029,15 @@ void check_redraw_for(buf_T *buf, win_T *win, uint32_t flags) } if ((flags & P_RBUF) || (flags & P_RWIN) || all) { - changed_window_setting_win(win); + if (flags & P_HLONLY) { + redraw_later(win, UPD_NOT_VALID); + } else { + changed_window_setting_win(win); + } } if (flags & P_RBUF) { redraw_buf_later(buf, UPD_NOT_VALID); } - if (flags & P_RWINONLY) { - redraw_later(win, UPD_NOT_VALID); - } if (all) { redraw_all_later(UPD_NOT_VALID); } @@ -3022,126 +3048,40 @@ void check_redraw(uint32_t flags) check_redraw_for(curbuf, curwin, flags); } -/// Find index for named option -/// -/// @param[in] arg Option to find index for. -/// @param[in] len Length of the option. -/// -/// @return Index of the option or -1 if option was not found. -int findoption_len(const char *const arg, const size_t len) -{ - const char *s; - static int quick_tab[27] = { 0, 0 }; // quick access table - - // For first call: Initialize the quick-access table. - // It contains the index for the first option that starts with a certain - // letter. There are 26 letters, plus the first "t_" option. - if (quick_tab[1] == 0) { - const char *p = options[0].fullname; - for (uint16_t i = 1; (s = options[i].fullname) != NULL; i++) { - if (s[0] != p[0]) { - if (s[0] == 't' && s[1] == '_') { - quick_tab[26] = i; - } else { - quick_tab[CHAR_ORD_LOW(s[0])] = i; - } - } - p = s; - } - } - - // Check for name starting with an illegal character. - if (len == 0 || arg[0] < 'a' || arg[0] > 'z') { - return -1; - } - - int opt_idx; - const bool is_term_opt = (len > 2 && arg[0] == 't' && arg[1] == '_'); - if (is_term_opt) { - opt_idx = quick_tab[26]; - } else { - opt_idx = quick_tab[CHAR_ORD_LOW(arg[0])]; - } - // Match full name - for (; (s = options[opt_idx].fullname) != NULL; opt_idx++) { - if (strncmp(arg, s, len) == 0 && s[len] == NUL) { - break; - } - } - if (s == NULL && !is_term_opt) { - opt_idx = quick_tab[CHAR_ORD_LOW(arg[0])]; - // Match short name - for (; options[opt_idx].fullname != NULL; opt_idx++) { - s = options[opt_idx].shortname; - if (s != NULL && strncmp(arg, s, len) == 0 && s[len] == NUL) { - break; - } - s = NULL; - } - } - if (s == NULL) { - opt_idx = -1; - } else { - // Nvim: handle option aliases. - if (strncmp(options[opt_idx].fullname, "viminfo", 7) == 0) { - if (strlen(options[opt_idx].fullname) == 7) { - return findoption_len("shada", 5); - } - assert(strcmp(options[opt_idx].fullname, "viminfofile") == 0); - return findoption_len("shadafile", 9); - } - } - return opt_idx; -} - bool is_tty_option(const char *name) FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT { - return (name[0] == 't' && name[1] == '_') - || strequal(name, "term") - || strequal(name, "ttytype"); + return find_tty_option_end(name) != NULL; } #define TCO_BUFFER_SIZE 8 -/// @param name TUI-related option -/// @param[out,allocated] value option string value -bool get_tty_option(const char *name, char **value) -{ - if (strequal(name, "t_Co")) { - if (value) { - if (t_colors <= 1) { - *value = xstrdup(""); - } else { - *value = xmalloc(TCO_BUFFER_SIZE); - snprintf(*value, TCO_BUFFER_SIZE, "%d", t_colors); - } - } - return true; - } - - if (strequal(name, "term")) { - if (value) { - *value = p_term ? xstrdup(p_term) : xstrdup("nvim"); - } - return true; - } - if (strequal(name, "ttytype")) { - if (value) { - *value = p_ttytype ? xstrdup(p_ttytype) : xstrdup("nvim"); - } - return true; - } +/// Get value of TTY option. +/// +/// @param name Name of TTY option. +/// +/// @return [allocated] TTY option value. Returns NIL_OPTVAL if option isn't a TTY option. +OptVal get_tty_option(const char *name) +{ + char *value = NULL; - if (is_tty_option(name)) { - if (value) { - // XXX: All other t_* options were removed in 3baba1e7. - *value = xstrdup(""); + if (strequal(name, "t_Co")) { + if (t_colors <= 1) { + value = xstrdup(""); + } else { + value = xmalloc(TCO_BUFFER_SIZE); + snprintf(value, TCO_BUFFER_SIZE, "%d", t_colors); } - return true; + } else if (strequal(name, "term")) { + value = p_term ? xstrdup(p_term) : xstrdup("nvim"); + } else if (strequal(name, "ttytype")) { + value = p_ttytype ? xstrdup(p_ttytype) : xstrdup("nvim"); + } else if (is_tty_option(name)) { + // XXX: All other t_* options were removed in 3baba1e7. + value = xstrdup(""); } - return false; + return value == NULL ? NIL_OPTVAL : CSTR_AS_OPTVAL(value); } bool set_tty_option(const char *name, char *value) @@ -3165,15 +3105,28 @@ bool set_tty_option(const char *name, char *value) return false; } -/// Find index for an option +/// Find index for an option. Don't go beyond `len` length. +/// +/// @param[in] name Option name. +/// @param len Option name length. +/// +/// @return Option index or kOptInvalid if option was not found. +OptIndex find_option_len(const char *const name, size_t len) + FUNC_ATTR_NONNULL_ALL +{ + int index = find_option_hash(name, len); + return index >= 0 ? option_hash_elems[index].opt_idx : kOptInvalid; +} + +/// Find index for an option. /// -/// @param[in] arg Option name. +/// @param[in] name Option name. /// -/// @return Option index or -1 if option was not found. -int findoption(const char *const arg) +/// @return Option index or kOptInvalid if option was not found. +OptIndex find_option(const char *const name) FUNC_ATTR_NONNULL_ALL { - return findoption_len(arg, strlen(arg)); + return find_option_len(name, strlen(name)); } /// Free an allocated OptVal. @@ -3223,27 +3176,7 @@ bool optval_equal(OptVal o1, OptVal o2) return o1.data.number == o2.data.number; case kOptValTypeString: return o1.data.string.size == o2.data.string.size - && strequal(o1.data.string.data, o2.data.string.data); - } - UNREACHABLE; -} - -/// Match type of OptVal with the type of the target option. Returns true if the types match and -/// false otherwise. -static bool optval_match_type(OptVal o, int opt_idx) -{ - assert(opt_idx >= 0); - uint32_t flags = options[opt_idx].flags; - - switch (o.type) { - case kOptValTypeNil: - return false; - case kOptValTypeBoolean: - return flags & P_BOOL; - case kOptValTypeNumber: - return flags & P_NUM; - case kOptValTypeString: - return flags & P_STRING; + && strnequal(o1.data.string.data, o2.data.string.data, o1.data.string.size); } UNREACHABLE; } @@ -3252,7 +3185,9 @@ static bool optval_match_type(OptVal o, int opt_idx) /// /// @param opt_idx Option index in options[] table. /// @param[out] varp Pointer to option variable. -OptVal optval_from_varp(int opt_idx, void *varp) +/// +/// @return Option value stored in varp. +OptVal optval_from_varp(OptIndex opt_idx, void *varp) { // Special case: 'modified' is b_changed, but we also want to consider it set when 'ff' or 'fenc' // changed. @@ -3260,19 +3195,17 @@ OptVal optval_from_varp(int opt_idx, void *varp) return BOOLEAN_OPTVAL(curbufIsChanged()); } - uint32_t flags = options[opt_idx].flags; - - OptValType type = kOptValTypeNil; - if (flags & P_BOOL) { - type = kOptValTypeBoolean; - } else if (flags & P_NUM) { - type = kOptValTypeNumber; - } else if (flags & P_STRING) { - type = kOptValTypeString; - } else { - abort(); + if (option_is_multitype(opt_idx)) { + // Multitype options are stored as OptVal. + return varp == NULL ? NIL_OPTVAL : *(OptVal *)varp; } + // If the option only supports a single type, it means that the index of the option's type flag + // corresponds to the value of the type enum. So get the index of the type flag using xctz() and + // use that as the option's type. + OptValType type = xctz(options[opt_idx].type_flags); + assert(type > kOptValTypeNil && type < kOptValTypeSize); + switch (type) { case kOptValTypeNil: return NIL_OPTVAL; @@ -3286,16 +3219,16 @@ OptVal optval_from_varp(int opt_idx, void *varp) UNREACHABLE; } -/// Set option var pointer value from Optval. +/// Set option var pointer value from OptVal. /// /// @param opt_idx Option index in options[] table. /// @param[out] varp Pointer to option variable. /// @param[in] value New option value. /// @param free_oldval Free old value. -static void set_option_varp(int opt_idx, void *varp, OptVal value, bool free_oldval) +static void set_option_varp(OptIndex opt_idx, void *varp, OptVal value, bool free_oldval) FUNC_ATTR_NONNULL_ARG(2) { - assert(optval_match_type(value, opt_idx)); + assert(option_has_type(opt_idx, value.type)); if (free_oldval) { optval_free(optval_from_varp(opt_idx, varp)); @@ -3303,7 +3236,7 @@ static void set_option_varp(int opt_idx, void *varp, OptVal value, bool free_old switch (value.type) { case kOptValTypeNil: - return; + abort(); case kOptValTypeBoolean: *(int *)varp = value.data.boolean; return; @@ -3388,13 +3321,13 @@ OptVal object_as_optval(Object o, bool *error) /// @param[in] varp Pointer to option variable. /// /// @return [allocated] Option value equal to the unset value for the option. -static OptVal optval_unset_local(int opt_idx, void *varp) +static OptVal optval_unset_local(OptIndex opt_idx, void *varp) { vimoption_T *opt = &options[opt_idx]; // For global-local options, use the unset value of the local value. if (opt->indir & PV_BOTH) { // String global-local options always use an empty string for the unset value. - if (opt->flags & P_STRING) { + if (option_has_type(opt_idx, kOptValTypeString)) { return STATIC_CSTR_TO_OPTVAL(""); } @@ -3410,43 +3343,29 @@ static OptVal optval_unset_local(int opt_idx, void *varp) } } // For options that aren't global-local, just set the local value to the global value. - return get_option_value(opt->fullname, NULL, OPT_GLOBAL, NULL); + return get_option_value(opt_idx, OPT_GLOBAL); } /// Get an allocated string containing a list of valid types for an option. /// For options with a singular type, it returns the name of the type. For options with multiple /// possible types, it returns a slash separated list of types. For example, if an option can be a /// number, boolean or string, the function returns "Number/Boolean/String" -static char *option_get_valid_types(int opt_idx) +static char *option_get_valid_types(OptIndex opt_idx) { - uint32_t flags = options[opt_idx].flags; - uint32_t type_count = 0; - StringBuilder str = KV_INITIAL_VALUE; kv_resize(str, 32); -#define OPTION_ADD_TYPE(typename) \ - do { \ - if (type_count == 0) { \ - kv_concat(str, typename); \ - } else { \ - kv_printf(str, "/%s", typename); \ - } \ - type_count++; \ - } while (0); - - if (flags & P_NUM) { - OPTION_ADD_TYPE("Number"); - } - if (flags & P_BOOL) { - OPTION_ADD_TYPE("Boolean"); - } - if (flags & P_STRING) { - OPTION_ADD_TYPE("String"); - } + // Iterate through every valid option value type and check if the option supports that type + for (OptValType type = 0; type < kOptValTypeSize; type++) { + if (option_has_type(opt_idx, type)) { + const char *typename = optval_type_get_name(type); - if (type_count == 0) { - abort(); + if (str.size == 0) { + kv_concat(str, typename); + } else { + kv_printf(str, "/%s", typename); + } + } } // Ensure that the string is NUL-terminated. @@ -3456,52 +3375,48 @@ static char *option_get_valid_types(int opt_idx) #undef OPTION_ADD_TYPE } -/// Gets the value for an option. +/// Check if option is hidden. /// -/// @param[in] name Option name. -/// @param[out] flagsp Set to the option flags (P_xxxx) (if not NULL). -/// @param[in] scope Option scope (can be OPT_LOCAL, OPT_GLOBAL or a combination). -/// @param[out] hidden Whether option is hidden. +/// @param opt_idx Option index in options[] table. /// -/// @return [allocated] Option value. Returns NIL_OPTVAL for invalid options. -OptVal get_option_value(const char *name, uint32_t *flagsp, int scope, bool *hidden) +/// @return True if option is hidden, false otherwise. Returns false if option name is invalid. +bool is_option_hidden(OptIndex opt_idx) { - // Make sure that hidden and flagsp are never returned uninitialized - if (hidden != NULL) { - *hidden = false; - } - if (flagsp != NULL) { - *flagsp = 0; - } + return opt_idx == kOptInvalid ? false : get_varp(&options[opt_idx]) == NULL; +} - char *str; - if (get_tty_option(name, &str)) { - return CSTR_AS_OPTVAL(str); - } +/// Get option flags. +/// +/// @param opt_idx Option index in options[] table. +/// +/// @return Option flags. Returns 0 for invalid option name. +uint32_t get_option_flags(OptIndex opt_idx) +{ + return opt_idx == kOptInvalid ? 0 : options[opt_idx].flags; +} - int opt_idx = findoption(name); - if (opt_idx < 0) { // option not in the table +/// Gets the value for an option. +/// +/// @param opt_idx Option index in options[] table. +/// @param[in] scope Option scope (can be OPT_LOCAL, OPT_GLOBAL or a combination). +/// +/// @return [allocated] Option value. Returns NIL_OPTVAL for invalid option index. +OptVal get_option_value(OptIndex opt_idx, int scope) +{ + if (opt_idx == kOptInvalid) { // option not in the options[] table. return NIL_OPTVAL; } vimoption_T *opt = &options[opt_idx]; void *varp = get_varp_scope(opt, scope); - if (hidden != NULL) { - *hidden = varp == NULL; - } - - if (flagsp != NULL) { - // Return the P_xxxx option flags. - *flagsp = opt->flags; - } - return optval_copy(optval_from_varp(opt_idx, varp)); } /// Return information for option at 'opt_idx' -vimoption_T *get_option(int opt_idx) +vimoption_T *get_option(OptIndex opt_idx) { + assert(opt_idx != kOptInvalid); return &options[opt_idx]; } @@ -3527,7 +3442,7 @@ static bool is_option_local_value_unset(vimoption_T *opt, buf_T *buf, win_T *win /// Handle side-effects of setting an option. /// -/// @param opt_idx Index in options[] table. Must be >= 0. +/// @param opt_idx Index in options[] table. Must not be kOptInvalid. /// @param[in] varp Option variable pointer, cannot be NULL. /// @param old_value Old option value. /// @param new_value New option value. @@ -3538,9 +3453,10 @@ static bool is_option_local_value_unset(vimoption_T *opt, buf_T *buf, win_T *win /// @param errbuflen Length of error buffer. /// /// @return NULL on success, an untranslated error message on error. -static const char *did_set_option(int opt_idx, void *varp, OptVal old_value, OptVal new_value, +static const char *did_set_option(OptIndex opt_idx, void *varp, OptVal old_value, OptVal new_value, int opt_flags, bool *value_checked, bool value_replaced, - char *errbuf, size_t errbuflen) + char *errbuf, // NOLINT(readability-non-const-parameter) + size_t errbuflen) { vimoption_T *opt = &options[opt_idx]; const char *errmsg = NULL; @@ -3593,7 +3509,7 @@ static const char *did_set_option(int opt_idx, void *varp, OptVal old_value, Opt set_option_varp(opt_idx, varp, old_value, true); // When resetting some values, need to act on it. if (restore_chartab) { - (void)buf_init_chartab(curbuf, true); + buf_init_chartab(curbuf, true); } // Unset new_value as it is no longer valid. @@ -3605,7 +3521,7 @@ static const char *did_set_option(int opt_idx, void *varp, OptVal old_value, Opt new_value = optval_from_varp(opt_idx, varp); // Remember where the option was set. - set_option_sctx_idx(opt_idx, opt_flags, current_sctx); + set_option_sctx(opt_idx, opt_flags, current_sctx); // Free options that are in allocated memory. // Use "free_oldval", because recursiveness may change the flags (esp. init_highlight()). if (free_oldval) { @@ -3613,14 +3529,6 @@ static const char *did_set_option(int opt_idx, void *varp, OptVal old_value, Opt } opt->flags |= P_ALLOCED; - // Check the bound for num options. - if (new_value.type == kOptValTypeNumber) { - errmsg = check_num_option_bounds((OptInt *)varp, old_value.data.number, errbuf, errbuflen, - errmsg); - // Re-assign new_value because the new value was modified by the bound check. - new_value = optval_from_varp(opt_idx, varp); - } - if ((opt_flags & (OPT_LOCAL | OPT_GLOBAL)) == 0 && (opt->indir & PV_BOTH)) { // Global option with local value set to use global value. // Free the local value and clear it. @@ -3647,7 +3555,7 @@ static const char *did_set_option(int opt_idx, void *varp, OptVal old_value, Opt do_spelllang_source(curwin); } - // In case 'columns' or 'ls' changed. + // In case 'ruler' or 'showcmd' or 'columns' or 'ls' changed. comp_col(); if (varp == &p_mouse) { @@ -3661,7 +3569,8 @@ static const char *did_set_option(int opt_idx, void *varp, OptVal old_value, Opt set_winbar(true); } - if (curwin->w_curswant != MAXCOL && (opt->flags & (P_CURSWANT | P_RALL)) != 0) { + if (curwin->w_curswant != MAXCOL + && (opt->flags & (P_CURSWANT | P_RALL)) != 0 && (opt->flags & P_HLONLY) == 0) { curwin->w_set_curswant = true; } @@ -3685,7 +3594,7 @@ static const char *did_set_option(int opt_idx, void *varp, OptVal old_value, Opt /// Set the value of an option using an OptVal. /// -/// @param opt_idx Index in options[] table. Must be >= 0. +/// @param opt_idx Index in options[] table. Must not be kOptInvalid. /// @param[in] varp Option variable pointer, cannot be NULL. /// @param value New option value. Might get freed. /// @param opt_flags Option flags. @@ -3694,23 +3603,16 @@ static const char *did_set_option(int opt_idx, void *varp, OptVal old_value, Opt /// @param errbuflen Length of error buffer. /// /// @return NULL on success, an untranslated error message on error. -static const char *set_option(const int opt_idx, void *varp, OptVal value, int opt_flags, +static const char *set_option(const OptIndex opt_idx, void *varp, OptVal value, int opt_flags, const bool value_replaced, char *errbuf, size_t errbuflen) { - assert(opt_idx >= 0 && varp != NULL); + assert(opt_idx != kOptInvalid && varp != NULL); const char *errmsg = NULL; bool value_checked = false; vimoption_T *opt = &options[opt_idx]; - static const char *optval_type_names[] = { - [kOptValTypeNil] = "Nil", - [kOptValTypeBoolean] = "Boolean", - [kOptValTypeNumber] = "Number", - [kOptValTypeString] = "String" - }; - if (value.type == kOptValTypeNil) { // Don't try to unset local value if scope is global. // TODO(famiu): Change this to forbid changing all non-local scopes when the API scope bug is @@ -3721,11 +3623,11 @@ static const char *set_option(const int opt_idx, void *varp, OptVal value, int o optval_free(value); value = optval_unset_local(opt_idx, varp); } - } else if (!optval_match_type(value, opt_idx)) { + } else if (!option_has_type(opt_idx, value.type)) { char *rep = optval_to_cstr(value); char *valid_types = option_get_valid_types(opt_idx); snprintf(errbuf, IOSIZE, _("Invalid value for option '%s': expected %s, got %s %s"), - opt->fullname, valid_types, optval_type_names[value.type], rep); + opt->fullname, valid_types, optval_type_get_name(value.type), rep); xfree(rep); xfree(valid_types); errmsg = errbuf; @@ -3767,9 +3669,7 @@ static const char *set_option(const int opt_idx, void *varp, OptVal value, int o OptVal used_old_value = oldval_is_global ? optval_from_varp(opt_idx, get_varp(opt)) : old_value; if (value.type == kOptValTypeNumber) { - errmsg = validate_num_option((OptInt *)varp, &value.data.number); - - // Don't change the value and return early if validation failed. + errmsg = validate_num_option(opt_idx, varp, &value.data.number, errbuf, errbuflen); if (errmsg != NULL) { goto err; } @@ -3825,29 +3725,20 @@ err: return errmsg; } -/// Set the value of an option +/// Set the value of an option. /// -/// @param[in] name Option name. +/// @param opt_idx Index in options[] table. Must not be kOptInvalid. /// @param[in] value Option value. If NIL_OPTVAL, the option value is cleared. /// @param[in] opt_flags Flags: OPT_LOCAL, OPT_GLOBAL, or 0 (both). /// /// @return NULL on success, an untranslated error message on error. -const char *set_option_value(const char *const name, const OptVal value, int opt_flags) - FUNC_ATTR_NONNULL_ARG(1) +const char *set_option_value(const OptIndex opt_idx, const OptVal value, int opt_flags) { - static char errbuf[IOSIZE]; - - if (is_tty_option(name)) { - return NULL; // Fail silently; many old vimrcs set t_xx options. - } - - int opt_idx = findoption(name); - if (opt_idx < 0) { - snprintf(errbuf, IOSIZE, _(e_unknown_option2), name); - return errbuf; - } + assert(opt_idx != kOptInvalid); + static char errbuf[IOSIZE]; uint32_t flags = options[opt_idx].flags; + // Disallow changing some options in the sandbox if (sandbox > 0 && (flags & P_SECURE)) { return _(e_sandbox); @@ -3859,58 +3750,283 @@ const char *set_option_value(const char *const name, const OptVal value, int opt return NULL; } - const char *errmsg = NULL; + return set_option(opt_idx, varp, optval_copy(value), opt_flags, true, errbuf, sizeof(errbuf)); +} - errmsg = set_option(opt_idx, varp, optval_copy(value), opt_flags, true, errbuf, sizeof(errbuf)); +/// Set the value of an option. Supports TTY options, unlike set_option_value(). +/// +/// @param name Option name. Used for error messages and for setting TTY options. +/// @param opt_idx Option indx in options[] table. If kOptInvalid, `name` is used to +/// check if the option is a TTY option, and an error is shown if it's not. +/// If the option is a TTY option, the function fails silently. +/// @param value Option value. If NIL_OPTVAL, the option value is cleared. +/// @param[in] opt_flags Flags: OPT_LOCAL, OPT_GLOBAL, or 0 (both). +/// +/// @return NULL on success, an untranslated error message on error. +const char *set_option_value_handle_tty(const char *name, OptIndex opt_idx, const OptVal value, + int opt_flags) + FUNC_ATTR_NONNULL_ARG(1) +{ + static char errbuf[IOSIZE]; - return errmsg; + if (opt_idx == kOptInvalid) { + if (is_tty_option(name)) { + return NULL; // Fail silently; many old vimrcs set t_xx options. + } + + snprintf(errbuf, sizeof(errbuf), _(e_unknown_option2), name); + return errbuf; + } + + return set_option_value(opt_idx, value, opt_flags); } -/// Call set_option_value() and when an error is returned report it. +/// Call set_option_value() and when an error is returned, report it. /// -/// @param opt_flags OPT_LOCAL or 0 (both) -void set_option_value_give_err(const char *name, OptVal value, int opt_flags) +/// @param opt_idx Option index in options[] table. +/// @param value Option value. If NIL_OPTVAL, the option value is cleared. +/// @param opt_flags OPT_LOCAL or 0 (both) +void set_option_value_give_err(const OptIndex opt_idx, OptVal value, int opt_flags) { - const char *errmsg = set_option_value(name, value, opt_flags); + const char *errmsg = set_option_value(opt_idx, value, opt_flags); if (errmsg != NULL) { emsg(_(errmsg)); } } -bool is_option_allocated(const char *name) +/// Switch current context to get/set option value for window/buffer. +/// +/// @param[out] ctx Current context. switchwin_T for window and aco_save_T for buffer. +/// @param req_scope Requested option scope. See OptReqScope in option.h. +/// @param[in] from Target buffer/window. +/// @param[out] err Error message, if any. +/// +/// @return true if context was switched, false otherwise. +static bool switch_option_context(void *const ctx, OptReqScope req_scope, void *const from, + Error *err) { - int idx = findoption(name); - return idx >= 0 && (options[idx].flags & P_ALLOCED); + switch (req_scope) { + case kOptReqWin: { + win_T *const win = (win_T *)from; + switchwin_T *const switchwin = (switchwin_T *)ctx; + + if (win == curwin) { + return false; + } + + if (switch_win_noblock(switchwin, win, win_find_tabpage(win), true) + == FAIL) { + restore_win_noblock(switchwin, true); + + if (try_end(err)) { + return false; + } + api_set_error(err, kErrorTypeException, "Problem while switching windows"); + return false; + } + return true; + } + case kOptReqBuf: { + buf_T *const buf = (buf_T *)from; + aco_save_T *const aco = (aco_save_T *)ctx; + + if (buf == curbuf) { + return false; + } + aucmd_prepbuf(aco, buf); + return true; + } + case kOptReqGlobal: + return false; + } + UNREACHABLE; } -// Translate a string like "t_xx", "<t_xx>" or "<S-Tab>" to a key number. -// When "has_lt" is true there is a '<' before "*arg_arg". -// Returns 0 when the key is not recognized. -int find_key_option_len(const char *arg_arg, size_t len, bool has_lt) +/// Restore context after getting/setting option for window/buffer. See switch_option_context() for +/// params. +static void restore_option_context(void *const ctx, OptReqScope req_scope) { - int key = 0; - const char *arg = arg_arg; + switch (req_scope) { + case kOptReqWin: + restore_win_noblock((switchwin_T *)ctx, true); + break; + case kOptReqBuf: + aucmd_restbuf((aco_save_T *)ctx); + break; + case kOptReqGlobal: + break; + } +} - // Don't use get_special_key_code() for t_xx, we don't want it to call - // add_termcap_entry(). - if (len >= 4 && arg[0] == 't' && arg[1] == '_') { - key = TERMCAP2KEY((uint8_t)arg[2], (uint8_t)arg[3]); - } else if (has_lt) { - arg--; // put arg at the '<' - int modifiers = 0; - key = find_special_key(&arg, len + 1, &modifiers, - FSK_KEYCODE | FSK_KEEP_X_KEY | FSK_SIMPLIFY, NULL); - if (modifiers) { // can't handle modifiers here - key = 0; - } +/// Get attributes for an option. +/// +/// @param opt_idx Option index in options[] table. +/// +/// @return Option attributes. +/// 0 for hidden or unknown option. +/// See SOPT_* in option_defs.h for other flags. +int get_option_attrs(OptIndex opt_idx) +{ + if (opt_idx == kOptInvalid) { + return 0; } - return key; + + vimoption_T *opt = get_option(opt_idx); + + // Hidden option + if (opt->var == NULL) { + return 0; + } + + int attrs = 0; + + if (opt->indir == PV_NONE || (opt->indir & PV_BOTH)) { + attrs |= SOPT_GLOBAL; + } + if (opt->indir & PV_WIN) { + attrs |= SOPT_WIN; + } else if (opt->indir & PV_BUF) { + attrs |= SOPT_BUF; + } + + return attrs; +} + +/// Check if option has a value in the requested scope. +/// +/// @param opt_idx Option index in options[] table. +/// @param req_scope Requested option scope. See OptReqScope in option.h. +/// +/// @return true if option has a value in the requested scope, false otherwise. +static bool option_has_scope(OptIndex opt_idx, OptReqScope req_scope) +{ + if (opt_idx == kOptInvalid) { + return false; + } + + vimoption_T *opt = get_option(opt_idx); + + // Hidden option. + if (opt->var == NULL) { + return false; + } + // TTY option. + if (is_tty_option(opt->fullname)) { + return req_scope == kOptReqGlobal; + } + + switch (req_scope) { + case kOptReqGlobal: + return opt->var != VAR_WIN; + case kOptReqBuf: + return opt->indir & PV_BUF; + case kOptReqWin: + return opt->indir & PV_WIN; + } + UNREACHABLE; +} + +/// Get the option value in the requested scope. +/// +/// @param opt_idx Option index in options[] table. +/// @param req_scope Requested option scope. See OptReqScope in option.h. +/// @param[in] from Pointer to buffer or window for local option value. +/// @param[out] err Error message, if any. +/// +/// @return Option value in the requested scope. Returns a Nil option value if option is not found, +/// hidden or if it isn't present in the requested scope. (i.e. has no global, window-local or +/// buffer-local value depending on opt_scope). +OptVal get_option_value_strict(OptIndex opt_idx, OptReqScope req_scope, void *from, Error *err) +{ + if (opt_idx == kOptInvalid || !option_has_scope(opt_idx, req_scope)) { + return NIL_OPTVAL; + } + + vimoption_T *opt = get_option(opt_idx); + switchwin_T switchwin; + aco_save_T aco; + void *ctx = req_scope == kOptReqWin ? (void *)&switchwin + : (req_scope == kOptReqBuf ? (void *)&aco : NULL); + bool switched = switch_option_context(ctx, req_scope, from, err); + if (ERROR_SET(err)) { + return NIL_OPTVAL; + } + + char *varp = get_varp_scope(opt, req_scope == kOptReqGlobal ? OPT_GLOBAL : OPT_LOCAL); + OptVal retv = optval_from_varp(opt_idx, varp); + + if (switched) { + restore_option_context(ctx, req_scope); + } + + return retv; +} + +/// Get option value for buffer / window. +/// +/// @param opt_idx Option index in options[] table. +/// @param[out] flagsp Set to the option flags (P_xxxx) (if not NULL). +/// @param[in] scope Option scope (can be OPT_LOCAL, OPT_GLOBAL or a combination). +/// @param[out] hidden Whether option is hidden. +/// @param req_scope Requested option scope. See OptReqScope in option.h. +/// @param[in] from Target buffer/window. +/// @param[out] err Error message, if any. +/// +/// @return Option value. Must be freed by caller. +OptVal get_option_value_for(OptIndex opt_idx, int scope, const OptReqScope req_scope, + void *const from, Error *err) +{ + switchwin_T switchwin; + aco_save_T aco; + void *ctx = req_scope == kOptReqWin ? (void *)&switchwin + : (req_scope == kOptReqBuf ? (void *)&aco : NULL); + + bool switched = switch_option_context(ctx, req_scope, from, err); + if (ERROR_SET(err)) { + return NIL_OPTVAL; + } + + OptVal retv = get_option_value(opt_idx, scope); + + if (switched) { + restore_option_context(ctx, req_scope); + } + + return retv; } -static int find_key_option(const char *arg, bool has_lt) +/// Set option value for buffer / window. +/// +/// @param name Option name. +/// @param opt_idx Option index in options[] table. +/// @param[in] value Option value. +/// @param[in] opt_flags Flags: OPT_LOCAL, OPT_GLOBAL, or 0 (both). +/// @param req_scope Requested option scope. See OptReqScope in option.h. +/// @param[in] from Target buffer/window. +/// @param[out] err Error message, if any. +void set_option_value_for(const char *name, OptIndex opt_idx, OptVal value, const int opt_flags, + const OptReqScope req_scope, void *const from, Error *err) + FUNC_ATTR_NONNULL_ARG(1) { - return find_key_option_len(arg, strlen(arg), has_lt); + switchwin_T switchwin; + aco_save_T aco; + void *ctx = req_scope == kOptReqWin ? (void *)&switchwin + : (req_scope == kOptReqBuf ? (void *)&aco : NULL); + + bool switched = switch_option_context(ctx, req_scope, from, err); + if (ERROR_SET(err)) { + return; + } + + const char *const errmsg = set_option_value_handle_tty(name, opt_idx, value, opt_flags); + if (errmsg) { + api_set_error(err, kErrorTypeException, "%s", errmsg); + } + + if (switched) { + restore_option_context(ctx, req_scope); + } } /// if 'all' == false: show changed options @@ -3940,33 +4056,35 @@ static void showoptions(bool all, int opt_flags) for (int run = 1; run <= 2 && !got_int; run++) { // collect the items in items[] int item_count = 0; - for (vimoption_T *p = &options[0]; p->fullname != NULL; p++) { + vimoption_T *opt; + for (OptIndex opt_idx = 0; opt_idx < kOptIndexCount; opt_idx++) { + opt = &options[opt_idx]; // apply :filter /pat/ - if (message_filtered(p->fullname)) { + if (message_filtered(opt->fullname)) { continue; } void *varp = NULL; if ((opt_flags & (OPT_LOCAL | OPT_GLOBAL)) != 0) { - if (p->indir != PV_NONE) { - varp = get_varp_scope(p, opt_flags); + if (opt->indir != PV_NONE) { + varp = get_varp_scope(opt, opt_flags); } } else { - varp = get_varp(p); + varp = get_varp(opt); } - if (varp != NULL && (all || !optval_default(p, varp))) { + if (varp != NULL && (all || !optval_default(opt_idx, varp))) { int len; if (opt_flags & OPT_ONECOLUMN) { len = Columns; - } else if (p->flags & P_BOOL) { + } else if (option_has_type(opt_idx, kOptValTypeBoolean)) { len = 1; // a toggle option fits always } else { - option_value2string(p, opt_flags); - len = (int)strlen(p->fullname) + vim_strsize(NameBuff) + 1; + option_value2string(opt, opt_flags); + len = (int)strlen(opt->fullname) + vim_strsize(NameBuff) + 1; } if ((len <= INC - GAP && run == 1) || (len > INC - GAP && run == 2)) { - items[item_count++] = p; + items[item_count++] = opt; } } } @@ -4005,40 +4123,31 @@ static void showoptions(bool all, int opt_flags) } /// Return true if option "p" has its default value. -static int optval_default(vimoption_T *p, const void *varp) +static int optval_default(OptIndex opt_idx, void *varp) { - if (varp == NULL) { - return true; // hidden option is always at default - } - if (p->flags & P_NUM) { - return *(OptInt *)varp == (OptInt)(intptr_t)p->def_val; - } - if (p->flags & P_BOOL) { - return *(int *)varp == (int)(intptr_t)p->def_val; + vimoption_T *opt = &options[opt_idx]; + + // Hidden or immutable options always use their default value. + if (varp == NULL || opt->immutable) { + return true; } - // P_STRING - return strcmp(*(char **)varp, p->def_val) == 0; + + OptVal current_val = optval_from_varp(opt_idx, varp); + OptVal default_val = optval_from_varp(opt_idx, &opt->def_val); + + return optval_equal(current_val, default_val); } /// Send update to UIs with values of UI relevant options void ui_refresh_options(void) { - for (int opt_idx = 0; options[opt_idx].fullname; opt_idx++) { + for (OptIndex opt_idx = 0; opt_idx < kOptIndexCount; opt_idx++) { uint32_t flags = options[opt_idx].flags; if (!(flags & P_UI_OPTION)) { continue; } String name = cstr_as_string(options[opt_idx].fullname); - void *varp = options[opt_idx].var; - Object value = OBJECT_INIT; - if (flags & P_BOOL) { - value = BOOLEAN_OBJ(*(int *)varp); - } else if (flags & P_NUM) { - value = INTEGER_OBJ(*(OptInt *)varp); - } else if (flags & P_STRING) { - // cstr_as_string handles NULL string - value = CSTR_AS_OBJ(*(char **)varp); - } + Object value = optval_as_object(optval_from_varp(opt_idx, options[opt_idx].var)); ui_call_option_set(name, value); } if (p_mouse != NULL) { @@ -4050,29 +4159,30 @@ void ui_refresh_options(void) /// must not be called with a hidden option! /// /// @param opt_flags OPT_LOCAL or OPT_GLOBAL -static void showoneopt(vimoption_T *p, int opt_flags) +static void showoneopt(vimoption_T *opt, int opt_flags) { int save_silent = silent_mode; silent_mode = false; - info_message = true; // use os_msg(), not os_errmsg() + info_message = true; // use stdout, not stderr - void *varp = get_varp_scope(p, opt_flags); + OptIndex opt_idx = get_opt_idx(opt); + void *varp = get_varp_scope(opt, opt_flags); // for 'modified' we also need to check if 'ff' or 'fenc' changed. - if ((p->flags & P_BOOL) && ((int *)varp == &curbuf->b_changed - ? !curbufIsChanged() : !*(int *)varp)) { + if (option_has_type(opt_idx, kOptValTypeBoolean) + && ((int *)varp == &curbuf->b_changed ? !curbufIsChanged() : !*(int *)varp)) { msg_puts("no"); - } else if ((p->flags & P_BOOL) && *(int *)varp < 0) { + } else if (option_has_type(opt_idx, kOptValTypeBoolean) && *(int *)varp < 0) { msg_puts("--"); } else { msg_puts(" "); } - msg_puts(p->fullname); - if (!(p->flags & P_BOOL)) { + msg_puts(opt->fullname); + if (!(option_has_type(opt_idx, kOptValTypeBoolean))) { msg_putchar('='); // put value string in NameBuff - option_value2string(p, opt_flags); + option_value2string(opt, opt_flags); msg_outtrans(NameBuff, 0); } @@ -4110,39 +4220,42 @@ int makeset(FILE *fd, int opt_flags, int local_only) // Do the loop over "options[]" twice: once for options with the // P_PRI_MKRC flag and once without. for (int pri = 1; pri >= 0; pri--) { - for (vimoption_T *p = &options[0]; p->fullname; p++) { - if (!(p->flags & P_NO_MKRC) - && ((pri == 1) == ((p->flags & P_PRI_MKRC) != 0))) { + vimoption_T *opt; + for (OptIndex opt_idx = 0; opt_idx < kOptIndexCount; opt_idx++) { + opt = &options[opt_idx]; + + if (!(opt->flags & P_NO_MKRC) + && ((pri == 1) == ((opt->flags & P_PRI_MKRC) != 0))) { // skip global option when only doing locals - if (p->indir == PV_NONE && !(opt_flags & OPT_GLOBAL)) { + if (opt->indir == PV_NONE && !(opt_flags & OPT_GLOBAL)) { continue; } // Do not store options like 'bufhidden' and 'syntax' in a vimrc // file, they are always buffer-specific. - if ((opt_flags & OPT_GLOBAL) && (p->flags & P_NOGLOB)) { + if ((opt_flags & OPT_GLOBAL) && (opt->flags & P_NOGLOB)) { continue; } - void *varp = get_varp_scope(p, opt_flags); // currently used value + void *varp = get_varp_scope(opt, opt_flags); // currently used value // Hidden options are never written. if (!varp) { continue; } // Global values are only written when not at the default value. - if ((opt_flags & OPT_GLOBAL) && optval_default(p, varp)) { + if ((opt_flags & OPT_GLOBAL) && optval_default(opt_idx, varp)) { continue; } if ((opt_flags & OPT_SKIPRTP) - && (p->var == &p_rtp || p->var == &p_pp)) { + && (opt->var == &p_rtp || opt->var == &p_pp)) { continue; } int round = 2; void *varp_local = NULL; // fresh value - if (p->indir != PV_NONE) { - if (p->var == VAR_WIN) { + if (opt->indir != PV_NONE) { + if (opt->var == VAR_WIN) { // skip window-local option when only doing globals if (!(opt_flags & OPT_LOCAL)) { continue; @@ -4150,8 +4263,8 @@ int makeset(FILE *fd, int opt_flags, int local_only) // When fresh value of window-local option is not at the // default, need to write it too. if (!(opt_flags & OPT_GLOBAL) && !local_only) { - void *varp_fresh = get_varp_scope(p, OPT_GLOBAL); // local value - if (!optval_default(p, varp_fresh)) { + void *varp_fresh = get_varp_scope(opt, OPT_GLOBAL); // local value + if (!optval_default(opt_idx, varp_fresh)) { round = 1; varp_local = varp; varp = varp_fresh; @@ -4170,28 +4283,28 @@ int makeset(FILE *fd, int opt_flags, int local_only) cmd = "setlocal"; } - if (p->flags & P_BOOL) { - if (put_setbool(fd, cmd, p->fullname, *(int *)varp) == FAIL) { + if (option_has_type(opt_idx, kOptValTypeBoolean)) { + if (put_setbool(fd, cmd, opt->fullname, *(int *)varp) == FAIL) { return FAIL; } - } else if (p->flags & P_NUM) { - if (put_setnum(fd, cmd, p->fullname, (OptInt *)varp) == FAIL) { + } else if (option_has_type(opt_idx, kOptValTypeNumber)) { + if (put_setnum(fd, cmd, opt->fullname, (OptInt *)varp) == FAIL) { return FAIL; } - } else { // P_STRING - int do_endif = false; + } else { // string + bool do_endif = false; // Don't set 'syntax' and 'filetype' again if the value is // already right, avoids reloading the syntax file. - if (p->indir == PV_SYN || p->indir == PV_FT) { - if (fprintf(fd, "if &%s != '%s'", p->fullname, + if (opt->indir == PV_SYN || opt->indir == PV_FT) { + if (fprintf(fd, "if &%s != '%s'", opt->fullname, *(char **)(varp)) < 0 || put_eol(fd) < 0) { return FAIL; } do_endif = true; } - if (put_setstring(fd, cmd, p->fullname, (char **)varp, p->flags) == FAIL) { + if (put_setstring(fd, cmd, opt->fullname, (char **)varp, opt->flags) == FAIL) { return FAIL; } if (do_endif) { @@ -4260,7 +4373,7 @@ static int put_setstring(FILE *fd, char *cmd, char *name, char **valuep, uint64_ if (fprintf(fd, "%s %s+=", cmd, name) < 0) { goto fail; } - (void)copy_option_part(&p, part, size, ","); + copy_option_part(&p, part, size, ","); if (put_escstr(fd, part, 2) == FAIL || put_eol(fd) == FAIL) { goto fail; } @@ -4402,7 +4515,7 @@ void *get_varp_scope(vimoption_T *p, int scope) /// Get pointer to option variable at 'opt_idx', depending on local or global /// scope. -void *get_option_varp_scope_from(int opt_idx, int scope, buf_T *buf, win_T *win) +void *get_option_varp_scope_from(OptIndex opt_idx, int scope, buf_T *buf, win_T *win) { return get_varp_scope_from(&(options[opt_idx]), scope, buf, win); } @@ -4587,6 +4700,8 @@ void *get_varp_from(vimoption_T *p, buf_T *buf, win_T *win) return &(buf->b_p_cfu); case PV_OFU: return &(buf->b_p_ofu); + case PV_URF: + return &(buf->b_p_urf); case PV_EOF: return &(buf->b_p_eof); case PV_EOL: @@ -4696,6 +4811,13 @@ void *get_varp_from(vimoption_T *p, buf_T *buf, win_T *win) return &(buf->b_p_wm); } +/// Get option index from option pointer +static inline OptIndex get_opt_idx(vimoption_T *opt) + FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE +{ + return (OptIndex)(opt - options); +} + /// Get pointer to option variable. static inline void *get_varp(vimoption_T *p) { @@ -4859,8 +4981,8 @@ void didset_window_options(win_T *wp, bool valid_cursor) check_colorcolumn(wp); briopt_check(wp); fill_culopt_flags(NULL, wp); - set_fillchars_option(wp, wp->w_p_fcs, true); - set_listchars_option(wp, wp->w_p_lcs, true); + set_chars_option(wp, wp->w_p_fcs, kFillchars, true, NULL, 0); + set_chars_option(wp, wp->w_p_lcs, kListchars, true, NULL, 0); parse_winhl_opt(wp); // sets w_hl_needs_update also for w_p_winbl check_blending(wp); set_winbar_win(wp, false, valid_cursor); @@ -4869,19 +4991,19 @@ void didset_window_options(win_T *wp, bool valid_cursor) } /// Index into the options table for a buffer-local option enum. -static int buf_opt_idx[BV_COUNT]; +static OptIndex buf_opt_idx[BV_COUNT]; #define COPY_OPT_SCTX(buf, bv) buf->b_p_script_ctx[bv] = options[buf_opt_idx[bv]].last_set /// Initialize buf_opt_idx[] if not done already. static void init_buf_opt_idx(void) { - static int did_init_buf_opt_idx = false; + static bool did_init_buf_opt_idx = false; if (did_init_buf_opt_idx) { return; } did_init_buf_opt_idx = true; - for (int i = 0; options[i].fullname != NULL; i++) { + for (OptIndex i = 0; i < kOptIndexCount; i++) { if (options[i].indir & PV_BUF) { buf_opt_idx[options[i].indir & PV_MASK] = i; } @@ -4897,9 +5019,9 @@ static void init_buf_opt_idx(void) /// BCO_NOHELP Don't copy the values to a help buffer. void buf_copy_options(buf_T *buf, int flags) { - int should_copy = true; + bool should_copy = true; char *save_p_isk = NULL; // init for GCC - int did_isk = false; + bool did_isk = false; // Skip this when the option defaults have not been set yet. Happens when // main() allocates the first buffer. @@ -5007,6 +5129,8 @@ void buf_copy_options(buf_T *buf, int flags) set_buflocal_cfu_callback(buf); buf->b_p_ofu = xstrdup(p_ofu); COPY_OPT_SCTX(buf, BV_OFU); + buf->b_p_urf = xstrdup(p_urf); + COPY_OPT_SCTX(buf, BV_URF); set_buflocal_ofu_callback(buf); buf->b_p_tfu = xstrdup(p_tfu); COPY_OPT_SCTX(buf, BV_TFU); @@ -5017,7 +5141,7 @@ void buf_copy_options(buf_T *buf, int flags) buf->b_p_vsts = xstrdup(p_vsts); COPY_OPT_SCTX(buf, BV_VSTS); if (p_vsts && p_vsts != empty_string_option) { - (void)tabstop_set(p_vsts, &buf->b_p_vsts_array); + tabstop_set(p_vsts, &buf->b_p_vsts_array); } else { buf->b_p_vsts_array = NULL; } @@ -5066,7 +5190,7 @@ void buf_copy_options(buf_T *buf, int flags) buf->b_s.b_syn_isk = empty_string_option; buf->b_s.b_p_spc = xstrdup(p_spc); COPY_OPT_SCTX(buf, BV_SPC); - (void)compile_cap_prog(&buf->b_s); + compile_cap_prog(&buf->b_s); buf->b_s.b_p_spf = xstrdup(p_spf); COPY_OPT_SCTX(buf, BV_SPF); buf->b_s.b_p_spl = xstrdup(p_spl); @@ -5128,7 +5252,7 @@ void buf_copy_options(buf_T *buf, int flags) if (dont_do_help) { buf->b_p_isk = save_p_isk; if (p_vts && p_vts != empty_string_option && !buf->b_p_vts_array) { - (void)tabstop_set(p_vts, &buf->b_p_vts_array); + tabstop_set(p_vts, &buf->b_p_vts_array); } else { buf->b_p_vts_array = NULL; } @@ -5141,7 +5265,7 @@ void buf_copy_options(buf_T *buf, int flags) buf->b_p_vts = xstrdup(p_vts); COPY_OPT_SCTX(buf, BV_VTS); if (p_vts && p_vts != empty_string_option && !buf->b_p_vts_array) { - (void)tabstop_set(p_vts, &buf->b_p_vts_array); + tabstop_set(p_vts, &buf->b_p_vts_array); } else { buf->b_p_vts_array = NULL; } @@ -5163,21 +5287,16 @@ void buf_copy_options(buf_T *buf, int flags) check_buf_options(buf); // make sure we don't have NULLs if (did_isk) { - (void)buf_init_chartab(buf, false); + buf_init_chartab(buf, false); } } /// Reset the 'modifiable' option and its default value. void reset_modifiable(void) { - int opt_idx; - curbuf->b_p_ma = false; p_ma = false; - opt_idx = findoption("ma"); - if (opt_idx >= 0) { - options[opt_idx].def_val = false; - } + options[kOptModifiable].def_val.boolean = false; } /// Set the global value for 'iminsert' to the local value. @@ -5192,7 +5311,7 @@ void set_imsearch_global(buf_T *buf) p_imsearch = buf->b_p_imsearch; } -static int expand_option_idx = -1; +static OptIndex expand_option_idx = kOptInvalid; static int expand_option_start_col = 0; static char expand_option_name[5] = { 't', '_', NUL, NUL, NUL }; static int expand_option_flags = 0; @@ -5242,8 +5361,8 @@ void set_context_in_set_cmd(expand_T *xp, char *arg, int opt_flags) char nextchar; uint32_t flags = 0; - int opt_idx = 0; - int is_term_option = false; + OptIndex opt_idx = 0; + bool is_term_option = false; if (*arg == '<') { while (*p != '>') { @@ -5282,13 +5401,13 @@ void set_context_in_set_cmd(expand_T *xp, char *arg, int opt_flags) return; } nextchar = *p; - opt_idx = findoption_len(arg, (size_t)(p - arg)); - if (opt_idx == -1 || options[opt_idx].var == NULL) { + opt_idx = find_option_len(arg, (size_t)(p - arg)); + if (opt_idx == kOptInvalid || options[opt_idx].var == NULL) { xp->xp_context = EXPAND_NOTHING; return; } flags = options[opt_idx].flags; - if (flags & P_BOOL) { + if (option_has_type(opt_idx, kOptValTypeBoolean)) { xp->xp_context = EXPAND_NOTHING; return; } @@ -5316,7 +5435,7 @@ void set_context_in_set_cmd(expand_T *xp, char *arg, int opt_flags) // Below are for handling expanding a specific option's value after the '=' or ':' if (is_term_option) { - expand_option_idx = -1; + expand_option_idx = kOptInvalid; } else { expand_option_idx = opt_idx; } @@ -5334,14 +5453,17 @@ void set_context_in_set_cmd(expand_T *xp, char *arg, int opt_flags) xp->xp_context = EXPAND_FILETYPE; return; } + if (options[opt_idx].var == &p_keymap) { + xp->xp_context = EXPAND_KEYMAP; + return; + } // Now pick. If the option has a custom expander, use that. Otherwise, just // fill with the existing option value. if (expand_option_subtract) { xp->xp_context = EXPAND_SETTING_SUBTRACT; return; - } else if (expand_option_idx >= 0 - && options[expand_option_idx].opt_expand_cb != NULL) { + } else if (expand_option_idx != kOptInvalid && options[expand_option_idx].opt_expand_cb != NULL) { xp->xp_context = EXPAND_STRING_SETTING; } else if (*xp->xp_pattern == NUL) { xp->xp_context = EXPAND_OLD_SETTING; @@ -5350,7 +5472,7 @@ void set_context_in_set_cmd(expand_T *xp, char *arg, int opt_flags) xp->xp_context = EXPAND_NOTHING; } - if (is_term_option || (flags & P_NUM)) { + if (is_term_option || option_has_type(opt_idx, kOptValTypeNumber)) { return; } @@ -5502,13 +5624,13 @@ int ExpandSettings(expand_T *xp, regmatch_T *regmatch, char *fuzzystr, int *numM } } char *str; - for (size_t opt_idx = 0; (str = options[opt_idx].fullname) != NULL; - opt_idx++) { + for (OptIndex opt_idx = 0; opt_idx < kOptIndexCount; opt_idx++) { + str = options[opt_idx].fullname; if (options[opt_idx].var == NULL) { continue; } if (xp->xp_context == EXPAND_BOOL_SETTINGS - && !(options[opt_idx].flags & P_BOOL)) { + && !(option_has_type(opt_idx, kOptValTypeBoolean))) { continue; } @@ -5567,7 +5689,7 @@ static char *escape_option_str_cmdline(char *var) // The reverse is found at stropt_copy_value(). for (var = buf; *var != NUL; MB_PTR_ADV(var)) { if (var[0] == '\\' && var[1] == '\\' - && expand_option_idx >= 0 + && expand_option_idx != kOptInvalid && (options[expand_option_idx].flags & P_EXPAND) && vim_isfilec((uint8_t)var[2]) && (var[2] != '\\' || (var == buf && var[4] != '\\'))) { @@ -5586,12 +5708,12 @@ int ExpandOldSetting(int *numMatches, char ***matches) *numMatches = 0; *matches = xmalloc(sizeof(char *)); - // For a terminal key code expand_option_idx is < 0. - if (expand_option_idx < 0) { - expand_option_idx = findoption(expand_option_name); + // For a terminal key code expand_option_idx is kOptInvalid. + if (expand_option_idx == kOptInvalid) { + expand_option_idx = find_option(expand_option_name); } - if (expand_option_idx >= 0) { + if (expand_option_idx != kOptInvalid) { // Put string of option value in NameBuff. option_value2string(&options[expand_option_idx], expand_option_flags); var = NameBuff; @@ -5609,8 +5731,7 @@ int ExpandOldSetting(int *numMatches, char ***matches) /// Expansion handler for :set=/:set+= when the option has a custom expansion handler. int ExpandStringSetting(expand_T *xp, regmatch_T *regmatch, int *numMatches, char ***matches) { - if (expand_option_idx < 0 - || options[expand_option_idx].opt_expand_cb == NULL) { + if (expand_option_idx == kOptInvalid || options[expand_option_idx].opt_expand_cb == NULL) { // Not supposed to reach this. This function is only for options with // custom expansion callbacks. return FAIL; @@ -5642,7 +5763,7 @@ int ExpandStringSetting(expand_T *xp, regmatch_T *regmatch, int *numMatches, cha /// Expansion handler for :set-= int ExpandSettingSubtract(expand_T *xp, regmatch_T *regmatch, int *numMatches, char ***matches) { - if (expand_option_idx < 0) { + if (expand_option_idx == kOptInvalid) { // term option return ExpandOldSetting(numMatches, matches); } @@ -5653,7 +5774,7 @@ int ExpandSettingSubtract(expand_T *xp, regmatch_T *regmatch, int *numMatches, c uint32_t option_flags = options[expand_option_idx].flags; - if (option_flags & P_NUM) { + if (option_has_type(expand_option_idx, kOptValTypeNumber)) { return ExpandOldSetting(numMatches, matches); } else if (option_flags & P_COMMA) { // Split the option by comma, then present each option to the user if @@ -5748,11 +5869,13 @@ int ExpandSettingSubtract(expand_T *xp, regmatch_T *regmatch, int *numMatches, c /// NameBuff[]. Must not be called with a hidden option! /// /// @param opt_flags OPT_GLOBAL and/or OPT_LOCAL -static void option_value2string(vimoption_T *opp, int scope) +/// +/// TODO(famiu): Replace this with optval_to_cstr() if possible. +static void option_value2string(vimoption_T *opt, int scope) { - void *varp = get_varp_scope(opp, scope); + void *varp = get_varp_scope(opt, scope); - if (opp->flags & P_NUM) { + if (option_has_type(get_opt_idx(opt), kOptValTypeNumber)) { OptInt wc = 0; if (wc_use_keyname(varp, &wc)) { @@ -5765,11 +5888,11 @@ static void option_value2string(vimoption_T *opp, int scope) "%" PRId64, (int64_t)(*(OptInt *)varp)); } - } else { // P_STRING + } else { // string varp = *(char **)(varp); if (varp == NULL) { // Just in case. NameBuff[0] = NUL; - } else if (opp->flags & P_EXPAND) { + } else if (opt->flags & P_EXPAND) { home_replace(NULL, varp, NameBuff, MAXPATHL, false); } else { xstrlcpy(NameBuff, varp, MAXPATHL); @@ -5822,35 +5945,24 @@ void vimrc_found(char *fname, char *envname) } } -/// Check whether global option has been set +/// Check whether global option has been set. /// /// @param[in] name Option name. /// -/// @return True if it was set. -bool option_was_set(const char *name) +/// @return True if option was set. +bool option_was_set(OptIndex opt_idx) { - int idx; - - idx = findoption(name); - if (idx < 0) { // Unknown option. - return false; - } else if (options[idx].flags & P_WAS_SET) { - return true; - } - return false; + assert(opt_idx != kOptInvalid); + return options[opt_idx].flags & P_WAS_SET; } /// Reset the flag indicating option "name" was set. /// /// @param[in] name Option name. -void reset_option_was_set(const char *name) +void reset_option_was_set(OptIndex opt_idx) { - const int idx = findoption(name); - if (idx < 0) { - return; - } - - options[idx].flags &= ~P_WAS_SET; + assert(opt_idx != kOptInvalid); + options[opt_idx].flags &= ~P_WAS_SET; } /// fill_culopt_flags() -- called when 'culopt' changes value @@ -5949,17 +6061,14 @@ int option_set_callback_func(char *optval, Callback *optcb) return OK; } -static void didset_options_sctx(int opt_flags, char **buf) +static void didset_options_sctx(int opt_flags, int *buf) { for (int i = 0;; i++) { - if (buf[i] == NULL) { + if (buf[i] == kOptInvalid) { break; } - int idx = findoption(buf[i]); - if (idx >= 0) { - set_option_sctx_idx(idx, opt_flags, current_sctx); - } + set_option_sctx(buf[i], opt_flags, current_sctx); } } @@ -6099,7 +6208,7 @@ void set_fileformat(int eol_style, int opt_flags) // p is NULL if "eol_style" is EOL_UNKNOWN. if (p != NULL) { - set_string_option_direct("ff", -1, p, OPT_FREE | opt_flags, 0); + set_string_option_direct(kOptFileformat, p, opt_flags, 0); } // This may cause the buffer to become (un)modified. @@ -6170,43 +6279,22 @@ bool fish_like_shell(void) return strstr(path_tail(p_sh), "fish") != NULL; } -/// Return the number of requested sign columns, based on current -/// buffer signs and on user configuration. -int win_signcol_count(win_T *wp) -{ - if (wp->w_minscwidth <= SCL_NO) { - return 0; - } - - int needed_signcols = buf_signcols(wp->w_buffer, wp->w_maxscwidth); - int ret = MAX(wp->w_minscwidth, MIN(wp->w_maxscwidth, needed_signcols)); - assert(ret <= SIGN_SHOW_MAX); - return ret; -} - /// Get window or buffer local options dict_T *get_winbuf_options(const int bufopt) FUNC_ATTR_WARN_UNUSED_RESULT { dict_T *const d = tv_dict_alloc(); - for (int opt_idx = 0; options[opt_idx].fullname; opt_idx++) { - struct vimoption *opt = &options[opt_idx]; + for (OptIndex opt_idx = 0; opt_idx < kOptIndexCount; opt_idx++) { + vimoption_T *opt = &options[opt_idx]; if ((bufopt && (opt->indir & PV_BUF)) || (!bufopt && (opt->indir & PV_WIN))) { void *varp = get_varp(opt); if (varp != NULL) { - if (opt->flags & P_STRING) { - tv_dict_add_str(d, opt->fullname, strlen(opt->fullname), - *(const char **)varp); - } else if (opt->flags & P_NUM) { - tv_dict_add_nr(d, opt->fullname, strlen(opt->fullname), - *(OptInt *)varp); - } else { - tv_dict_add_nr(d, opt->fullname, strlen(opt->fullname), *(int *)varp); - } + typval_T opt_tv = optval_as_tv(optval_from_varp(opt_idx, varp), true); + tv_dict_add_tv(d, opt->fullname, strlen(opt->fullname), &opt_tv); } } } @@ -6232,32 +6320,33 @@ int get_sidescrolloff_value(win_T *wp) return (int)(wp->w_p_siso < 0 ? p_siso : wp->w_p_siso); } -Dictionary get_vimoption(String name, int scope, buf_T *buf, win_T *win, Error *err) +Dictionary get_vimoption(String name, int scope, buf_T *buf, win_T *win, Arena *arena, Error *err) { - int opt_idx = findoption_len(name.data, name.size); - VALIDATE_S(opt_idx >= 0, "option (not found)", name.data, { + OptIndex opt_idx = find_option_len(name.data, name.size); + VALIDATE_S(opt_idx != kOptInvalid, "option (not found)", name.data, { return (Dictionary)ARRAY_DICT_INIT; }); - return vimoption2dict(&options[opt_idx], scope, buf, win); + return vimoption2dict(&options[opt_idx], scope, buf, win, arena); } -Dictionary get_all_vimoptions(void) +Dictionary get_all_vimoptions(Arena *arena) { - Dictionary retval = ARRAY_DICT_INIT; - for (size_t i = 0; options[i].fullname != NULL; i++) { - Dictionary opt_dict = vimoption2dict(&options[i], OPT_GLOBAL, curbuf, curwin); - PUT(retval, options[i].fullname, DICTIONARY_OBJ(opt_dict)); + Dictionary retval = arena_dict(arena, kOptIndexCount); + for (OptIndex opt_idx = 0; opt_idx < kOptIndexCount; opt_idx++) { + Dictionary opt_dict = vimoption2dict(&options[opt_idx], OPT_GLOBAL, curbuf, curwin, arena); + PUT_C(retval, options[opt_idx].fullname, DICTIONARY_OBJ(opt_dict)); } return retval; } -static Dictionary vimoption2dict(vimoption_T *opt, int req_scope, buf_T *buf, win_T *win) +static Dictionary vimoption2dict(vimoption_T *opt, int req_scope, buf_T *buf, win_T *win, + Arena *arena) { - Dictionary dict = ARRAY_DICT_INIT; + Dictionary dict = arena_dict(arena, 13); - PUT(dict, "name", CSTR_TO_OBJ(opt->fullname)); - PUT(dict, "shortname", CSTR_TO_OBJ(opt->shortname)); + PUT_C(dict, "name", CSTR_AS_OBJ(opt->fullname)); + PUT_C(dict, "shortname", CSTR_AS_OBJ(opt->shortname)); const char *scope; if (opt->indir & PV_BUF) { @@ -6268,14 +6357,14 @@ static Dictionary vimoption2dict(vimoption_T *opt, int req_scope, buf_T *buf, wi scope = "global"; } - PUT(dict, "scope", CSTR_TO_OBJ(scope)); + PUT_C(dict, "scope", CSTR_AS_OBJ(scope)); // welcome to the jungle - PUT(dict, "global_local", BOOLEAN_OBJ(opt->indir & PV_BOTH)); - PUT(dict, "commalist", BOOLEAN_OBJ(opt->flags & P_COMMA)); - PUT(dict, "flaglist", BOOLEAN_OBJ(opt->flags & P_FLAGLIST)); + PUT_C(dict, "global_local", BOOLEAN_OBJ(opt->indir & PV_BOTH)); + PUT_C(dict, "commalist", BOOLEAN_OBJ(opt->flags & P_COMMA)); + PUT_C(dict, "flaglist", BOOLEAN_OBJ(opt->flags & P_FLAGLIST)); - PUT(dict, "was_set", BOOLEAN_OBJ(opt->flags & P_WAS_SET)); + PUT_C(dict, "was_set", BOOLEAN_OBJ(opt->flags & P_WAS_SET)); LastSet last_set = { .channel_id = 0 }; if (req_scope == OPT_GLOBAL) { @@ -6293,29 +6382,37 @@ static Dictionary vimoption2dict(vimoption_T *opt, int req_scope, buf_T *buf, wi } } - PUT(dict, "last_set_sid", INTEGER_OBJ(last_set.script_ctx.sc_sid)); - PUT(dict, "last_set_linenr", INTEGER_OBJ(last_set.script_ctx.sc_lnum)); - PUT(dict, "last_set_chan", INTEGER_OBJ((int64_t)last_set.channel_id)); + PUT_C(dict, "last_set_sid", INTEGER_OBJ(last_set.script_ctx.sc_sid)); + PUT_C(dict, "last_set_linenr", INTEGER_OBJ(last_set.script_ctx.sc_lnum)); + PUT_C(dict, "last_set_chan", INTEGER_OBJ((int64_t)last_set.channel_id)); - const char *type; - Object def; // TODO(bfredl): do you even nocp? - char *def_val = opt->def_val; - if (opt->flags & P_STRING) { - type = "string"; - def = CSTR_TO_OBJ(def_val ? def_val : ""); - } else if (opt->flags & P_NUM) { - type = "number"; - def = INTEGER_OBJ((Integer)(intptr_t)def_val); - } else if (opt->flags & P_BOOL) { - type = "boolean"; - def = BOOLEAN_OBJ((intptr_t)def_val); - } else { - type = ""; def = NIL; - } - PUT(dict, "type", CSTR_TO_OBJ(type)); - PUT(dict, "default", def); - PUT(dict, "allows_duplicates", BOOLEAN_OBJ(!(opt->flags & P_NODUP))); + OptVal def = optval_from_varp(get_opt_idx(opt), &opt->def_val); + + PUT_C(dict, "type", CSTR_AS_OBJ(optval_type_get_name(def.type))); + PUT_C(dict, "default", optval_as_object(def)); + PUT_C(dict, "allows_duplicates", BOOLEAN_OBJ(!(opt->flags & P_NODUP))); return dict; } + +/// Check if option is multitype (supports multiple types). +static bool option_is_multitype(OptIndex opt_idx) +{ + const OptTypeFlags type_flags = get_option(opt_idx)->type_flags; + assert(type_flags != 0); + return !is_power_of_two(type_flags); +} + +/// Check if option supports a specific type. +bool option_has_type(OptIndex opt_idx, OptValType type) +{ + // Ensure that type flags variable can hold all types. + STATIC_ASSERT(kOptValTypeSize <= sizeof(OptTypeFlags) * 8, + "Option type_flags cannot fit all option types"); + // Ensure that the type is valid before accessing type_flags. + assert(type > kOptValTypeNil && type < kOptValTypeSize); + // Bitshift 1 by the value of type to get the type's corresponding flag, and check if it's set in + // the type_flags bit field. + return get_option(opt_idx)->type_flags & (1 << type); +} |