robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

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