robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
76.4 KiB2645 linesraw
1#include <assert.h>
2#include <stdbool.h>
3#include <stdint.h>
4#include <stdlib.h>
5#include <string.h>
6
7#include "nvim/api/private/defs.h"
8#include "nvim/api/win_config.h"
9#include "nvim/ascii_defs.h"
10#include "nvim/autocmd.h"
11#include "nvim/buffer_defs.h"
12#include "nvim/charset.h"
13#include "nvim/cmdexpand.h"
14#include "nvim/cmdexpand_defs.h"
15#include "nvim/cursor.h"
16#include "nvim/cursor_shape.h"
17#include "nvim/decoration.h"
18#include "nvim/diff.h"
19#include "nvim/digraph.h"
20#include "nvim/drawscreen.h"
21#include "nvim/errors.h"
22#include "nvim/eval/userfunc.h"
23#include "nvim/eval/vars.h"
24#include "nvim/ex_getln.h"
25#include "nvim/fold.h"
26#include "nvim/garray.h"
27#include "nvim/gettext_defs.h"
28#include "nvim/globals.h"
29#include "nvim/grid.h"
30#include "nvim/highlight_group.h"
31#include "nvim/indent.h"
32#include "nvim/indent_c.h"
33#include "nvim/insexpand.h"
34#include "nvim/macros_defs.h"
35#include "nvim/mark.h"
36#include "nvim/mbyte.h"
37#include "nvim/memline.h"
38#include "nvim/memory.h"
39#include "nvim/message.h"
40#include "nvim/move.h"
41#include "nvim/option.h"
42#include "nvim/option_defs.h"
43#include "nvim/option_vars.h"
44#include "nvim/optionstr.h"
45#include "nvim/os/os.h"
46#include "nvim/pos_defs.h"
47#include "nvim/regexp.h"
48#include "nvim/regexp_defs.h"
49#include "nvim/spell.h"
50#include "nvim/spellfile.h"
51#include "nvim/spellsuggest.h"
52#include "nvim/strings.h"
53#include "nvim/tag.h"
54#include "nvim/terminal.h"
55#include "nvim/types_defs.h"
56#include "nvim/ui.h"
57#include "nvim/vim_defs.h"
58#include "nvim/window.h"
59#include "nvim/winfloat.h"
60
61typedef enum {
62  kTopLevel,
63  kItemGroup,
64  kHighlightScope,
65} StlScopeType;
66
67#include "options_keysets.generated.h"
68#include "optionstr.c.generated.h"
69
70static const char e_illegal_character_after_chr[]
71  = N_("E535: Illegal character after <%c>");
72static const char e_comma_required[]
73  = N_("E536: Comma required");
74static const char e_unclosed_expression_sequence[]
75  = N_("E540: Unclosed expression sequence");
76static const char e_unbalanced_groups[]
77  = N_("E542: Unbalanced groups");
78static const char e_backupext_and_patchmode_are_equal[]
79  = N_("E589: 'backupext' and 'patchmode' are equal");
80static const char e_showbreak_contains_unprintable_or_wide_character[]
81  = N_("E595: 'showbreak' contains unprintable or wide character");
82static const char e_wrong_number_of_characters_for_field_str[]
83  = N_("E1511: Wrong number of characters for field \"%s\"");
84static const char e_wrong_character_width_for_field_str[]
85  = N_("E1512: Wrong character width for field \"%s\"");
86
87/// All possible flags for 'shm'.
88/// the literal chars before 0 are removed flags. these are safely ignored
89static char SHM_ALL[] = { kShmRo, kShmMod, kShmLines,
90                          kShmWri, kShmAbbreviations, kShmWrite, kShmTrunc, kShmTruncall,
91                          kShmOver, kShmOverall, kShmSearch, kShmAttention, kShmIntro,
92                          kShmCompletionmenu, kShmCompletionscan, kShmRecording, kShmFileinfo,
93                          kShmSearchcount, kShmUndo, 'n', 'f', 'x', 'i', 0, };
94
95/// After setting various option values: recompute variables that depend on
96/// option values.
97void didset_string_options(void)
98{
99  check_str_opt(kOptCasemap, NULL, NULL);
100  check_str_opt(kOptBackupcopy, NULL, NULL);
101  check_str_opt(kOptBelloff, NULL, NULL);
102  check_str_opt(kOptCompleteopt, NULL, NULL);
103  check_str_opt(kOptSessionoptions, NULL, NULL);
104  check_str_opt(kOptViewoptions, NULL, NULL);
105  check_str_opt(kOptFoldopen, NULL, NULL);
106  check_str_opt(kOptDisplay, NULL, NULL);
107  check_str_opt(kOptJumpoptions, NULL, NULL);
108  check_str_opt(kOptRedrawdebug, NULL, NULL);
109  check_str_opt(kOptTagcase, NULL, NULL);
110  check_str_opt(kOptTermpastefilter, NULL, NULL);
111  check_str_opt(kOptVirtualedit, NULL, NULL);
112  check_str_opt(kOptSwitchbuf, NULL, NULL);
113  check_str_opt(kOptTabclose, NULL, NULL);
114  check_str_opt(kOptWildoptions, NULL, NULL);
115  check_str_opt(kOptClipboard, NULL, NULL);
116}
117
118static const char *illegal_char(const CharBuf *errbuf, int c)
119{
120  if (errbuf == NULL) {
121    return "";
122  }
123  return opt_error(errbuf, N_("E539: Illegal character <%s>"), transchar(c));
124}
125
126/// Check string options in a buffer for NULL value.
127void check_buf_options(buf_T *buf)
128{
129  check_string_option(&buf->b_p_bh);
130  check_string_option(&buf->b_p_bt);
131  check_string_option(&buf->b_p_fenc);
132  check_string_option(&buf->b_p_ff);
133  check_string_option(&buf->b_p_def);
134  check_string_option(&buf->b_p_inc);
135  check_string_option(&buf->b_p_indk);
136  check_string_option(&buf->b_p_fp);
137  check_string_option(&buf->b_p_kp);
138  check_string_option(&buf->b_p_mps);
139  check_string_option(&buf->b_p_fo);
140  check_string_option(&buf->b_p_flp);
141  check_string_option(&buf->b_p_isk);
142  check_string_option(&buf->b_p_com);
143  check_string_option(&buf->b_p_cms);
144  check_string_option(&buf->b_p_nf);
145  check_string_option(&buf->b_p_qe);
146  check_string_option(&buf->b_p_syn);
147  check_string_option(&buf->b_s.b_syn_isk);
148  check_string_option(&buf->b_s.b_p_spc);
149  check_string_option(&buf->b_s.b_p_spf);
150  check_string_option(&buf->b_s.b_p_spl);
151  check_string_option(&buf->b_s.b_p_spo);
152  check_string_option(&buf->b_p_sua);
153  check_string_option(&buf->b_p_cink);
154  check_string_option(&buf->b_p_cino);
155  parse_cino(buf);
156  check_string_option(&buf->b_p_lop);
157  check_string_option(&buf->b_p_ft);
158  check_string_option(&buf->b_p_cinw);
159  check_string_option(&buf->b_p_cinsd);
160  check_string_option(&buf->b_p_cot);
161  check_string_option(&buf->b_p_cpt);
162  check_string_option(&buf->b_p_keymap);
163  check_string_option(&buf->b_p_gefm);
164  check_string_option(&buf->b_p_gp);
165  check_string_option(&buf->b_p_mp);
166  check_string_option(&buf->b_p_efm);
167  check_string_option(&buf->b_p_ep);
168  check_string_option(&buf->b_p_path);
169  check_string_option(&buf->b_p_tags);
170  check_string_option(&buf->b_p_tc);
171  check_string_option(&buf->b_p_dict);
172  check_string_option(&buf->b_p_dia);
173  check_string_option(&buf->b_p_tsr);
174  check_string_option(&buf->b_p_lw);
175  check_string_option(&buf->b_p_bkc);
176  check_string_option(&buf->b_p_menc);
177  check_string_option(&buf->b_p_vsts);
178  check_string_option(&buf->b_p_vts);
179}
180
181/// Free the string allocated for an option.
182/// Checks for the string being empty_string_option. This may happen if we're out of memory,
183/// xstrdup() returned NULL, which was replaced by empty_string_option by check_options().
184void free_string_option(char *p)
185{
186  if (p != empty_string_option) {
187    xfree(p);
188  }
189}
190
191void clear_string_option(char **pp)
192{
193  if (*pp != empty_string_option) {
194    xfree(*pp);
195  }
196  *pp = empty_string_option;
197}
198
199void check_string_option(char **pp)
200{
201  if (*pp == NULL) {
202    *pp = empty_string_option;
203  }
204}
205
206/// Return true if "val" is a valid 'filetype' name.
207/// Also used for 'syntax' and 'keymap'.
208static bool valid_filetype(const char *val)
209  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
210{
211  return valid_name(val, ".-_");
212}
213
214/// Handle setting 'signcolumn' for value 'val'. Store minimum and maximum width.
215///
216/// @param wcl  when NULL: use "wp->w_p_scl"
217/// @param wp   when NULL: only parse "scl"
218///
219/// @return OK when the value is valid, FAIL otherwise
220int check_signcolumn(char *scl, win_T *wp)
221{
222  char *val = empty_string_option;
223  if (scl != NULL) {
224    val = scl;
225  } else if (wp != NULL) {
226    val = wp->w_p_scl;
227  }
228
229  if (*val == NUL) {
230    return FAIL;
231  }
232
233  if (opt_strings_flags(val, opt_scl_values, NULL, false, NULL) == NULL) {
234    if (wp == NULL) {
235      return OK;
236    }
237    if (!strncmp(val, "no", 2)) {  // no
238      wp->w_minscwidth = wp->w_maxscwidth = SCL_NO;
239    } else if (!strncmp(val, "nu", 2) && (wp->w_p_nu || wp->w_p_rnu)) {  // number
240      wp->w_minscwidth = wp->w_maxscwidth = SCL_NUM;
241    } else if (!strncmp(val, "yes:", 4)) {  // yes:<NUM>
242      wp->w_minscwidth = wp->w_maxscwidth = val[4] - '0';
243    } else if (*val == 'y') {  // yes
244      wp->w_minscwidth = wp->w_maxscwidth = 1;
245    } else if (!strncmp(val, "auto:", 5)) {  // auto:<NUM>
246      wp->w_minscwidth = 0;
247      wp->w_maxscwidth = val[5] - '0';
248    } else {  // auto
249      wp->w_minscwidth = 0;
250      wp->w_maxscwidth = 1;
251    }
252  } else {
253    if (strncmp(val, "auto:", 5) != 0
254        || strlen(val) != 8
255        || !ascii_isdigit(val[5])
256        || val[6] != '-'
257        || !ascii_isdigit(val[7])) {
258      return FAIL;
259    }
260    // auto:<NUM>-<NUM>
261    int min = val[5] - '0';
262    int max = val[7] - '0';
263    if (min < 1 || max < 2 || min > 8 || min >= max) {
264      return FAIL;
265    }
266    if (wp == NULL) {
267      return OK;
268    }
269    wp->w_minscwidth = min;
270    wp->w_maxscwidth = max;
271  }
272
273  int scwidth = wp->w_minscwidth <= 0 ? 0 : MIN(wp->w_maxscwidth, wp->w_scwidth);
274  wp->w_scwidth = MAX(wp->w_minscwidth, scwidth);
275  return OK;
276}
277
278/// Check validity of string with the 'statusline' format until the end of the current scope.
279///
280/// @param errbuf  Buffer for error message, or NULL when only checking validity.
281/// @param scope_type  Type of current scope.
282/// @return An untranslated error message or NULL.
283static const char *check_stl_str_adv_scope(char **s, const CharBuf *errbuf, StlScopeType scope_type)
284{
285  while (**s) {
286    // Check for valid keys after % sequences
287    while (**s && **s != '%') {
288      (*s)++;
289    }
290    if (!**s) {
291      break;
292    }
293    (*s)++;
294    if (**s == '%' || **s == STL_TRUNCMARK || **s == STL_SEPARATE) {
295      (*s)++;
296      continue;
297    }
298    if (**s == ')') {
299      (*s)++;
300      return scope_type == kItemGroup ? NULL : e_unbalanced_groups;
301    }
302    if (**s == STL_HIGHLIGHT) {
303      (*s)++;
304      if (**s == '(') {
305        (*s)++;
306        const char *err = check_stl_str_adv_scope(s, errbuf, kHighlightScope);
307        if (err == NULL) {
308          continue;
309        } else {
310          return err;
311        }
312      } else if (**s == ')') {
313        (*s)++;
314        return scope_type == kHighlightScope ? NULL : e_unbalanced_groups;
315      }
316      while (**s && **s != STL_HIGHLIGHT) {
317        (*s)++;
318      }
319      if (**s) {
320        (*s)++;
321      }
322      continue;
323    }
324    if (**s == '-') {
325      (*s)++;
326    }
327    while (ascii_isdigit(**s)) {
328      (*s)++;
329    }
330    if (**s == STL_USER_HL) {
331      continue;
332    }
333    if (**s == '.') {
334      (*s)++;
335      while (**s && ascii_isdigit(**s)) {
336        (*s)++;
337      }
338    }
339    if (**s == '(') {
340      (*s)++;
341      const char *err = check_stl_str_adv_scope(s, errbuf, kItemGroup);
342      if (err == NULL) {
343        continue;
344      } else {
345        return err;
346      }
347    }
348    if (vim_strchr(STL_ALL, (uint8_t)(**s)) == NULL) {
349      return illegal_char(errbuf, (uint8_t)(**s));
350    }
351    if (**s == '{') {
352      bool reevaluate = (*(++*s) == '%');
353
354      if (reevaluate && *(++*s) == '}') {
355        // "}" is not allowed immediately after "%{%"
356        return illegal_char(errbuf, '}');
357      }
358      while ((**s != '}' || (reevaluate && (*s)[-1] != '%')) && **s) {
359        (*s)++;
360      }
361      if (**s != '}') {
362        return e_unclosed_expression_sequence;
363      }
364    }
365  }
366  return scope_type == kTopLevel ? NULL : e_unbalanced_groups;
367}
368
369/// Check validity of options with the 'statusline' format.
370///
371/// @param errbuf  Buffer for error message, or NULL when only checking validity.
372/// @return An untranslated error message or NULL.
373const char *check_stl_option(char *s, const CharBuf *errbuf)
374{
375  return check_stl_str_adv_scope(&s, errbuf, kTopLevel);
376}
377
378/// Check for a "normal" directory or file name in some options.  Disallow a
379/// path separator (slash and/or backslash), wildcards and characters that are
380/// often illegal in a file name. Be more permissive if "secure" is off.
381bool check_illegal_path_names(char *val, uint32_t flags)
382{
383  return (((flags & kOptFlagNFname)
384           && strpbrk(val, (secure ? "/\\*?[|;&<>\r\n" : "/\\*?[<>\r\n")) != NULL)
385          || ((flags & kOptFlagNDname)
386              && strpbrk(val, "*?[|;&<>\r\n") != NULL));
387}
388
389static const char **opt_values(OptIndex idx, size_t *values_len)
390{
391  OptIndex idx1 = idx == kOptViewoptions ? kOptSessionoptions
392                                         : idx == kOptFileformats ? kOptFileformat
393                                                                  : idx;
394
395  vimoption_T *opt = get_option(idx1);
396  if (values_len != NULL) {
397    *values_len = opt->values_len;
398  }
399  return opt->values;
400}
401
402static const char *check_str_opt(OptIndex idx, char **varp, const CharBuf *errbuf)
403{
404  vimoption_T *opt = get_option(idx);
405  if (varp == NULL) {
406    varp = opt->var;
407  }
408  bool list = opt->flags & (kOptFlagComma | kOptFlagOneComma);
409  const char **values = opt_values(idx, NULL);
410  return opt_strings_flags(*varp, values, opt->flags_var, list, errbuf);
411}
412
413int expand_set_str_generic(optexpand_T *args, int *numMatches, char ***matches)
414{
415  size_t values_len;
416  const char **values = opt_values(args->oe_idx, &values_len);
417  return expand_set_opt_string(args, values, values_len, numMatches, matches);
418}
419
420/// An option that accepts a list of flags is changed.
421/// e.g. 'viewoptions', 'switchbuf', 'casemap', etc.
422const char *did_set_str_generic(optset_T *args)
423{
424  return check_str_opt(args->os_idx, args->os_varp, args->os_errbuf);
425}
426
427/// Validate named string values without updating derived flags.
428const char *validate_str_generic(const optset_T *args)
429{
430  vimoption_T *opt = get_option(args->os_idx);
431  char *value = args->os_newval.data.string.data;
432  return opt_strings_flags(value, opt_values(args->os_idx, NULL), NULL,
433                           opt->flags & kOptFlagComma, args->os_errbuf);
434}
435
436/// Validate a list of character flags against "flags".
437static const char *check_option_listflag(char *val, char *flags, const CharBuf *errbuf)
438{
439  for (char *s = val; *s; s++) {
440    if (vim_strchr(flags, (uint8_t)(*s)) == NULL) {
441      return illegal_char(errbuf, (uint8_t)(*s));
442    }
443  }
444
445  return NULL;
446}
447
448/// Expand an option that accepts a list of string values.
449static int expand_set_opt_string(optexpand_T *args, const char **values, size_t numValues,
450                                 int *numMatches, char ***matches)
451{
452  regmatch_T *regmatch = args->oe_regmatch;
453  bool include_orig_val = args->oe_include_orig_val;
454  char *option_val = args->oe_opt_value;
455
456  // Assume numValues is small since they are fixed enums, so just allocate
457  // upfront instead of needing two passes to calculate output size.
458  *matches = xmalloc(sizeof(char *) * (numValues + 1));
459
460  int count = 0;
461
462  if (include_orig_val && *option_val != NUL) {
463    (*matches)[count++] = xstrdup(option_val);
464  }
465
466  for (const char **val = values; *val != NULL; val++) {
467    if (**val == NUL) {
468      continue;  // Ignore empty
469    } else if (include_orig_val && *option_val != NUL) {
470      if (strcmp(*val, option_val) == 0) {
471        continue;
472      }
473    }
474    if (vim_regexec(regmatch, *val, 0)) {
475      (*matches)[count++] = xstrdup(*val);
476    }
477  }
478  if (count == 0) {
479    XFREE_CLEAR(*matches);
480    return FAIL;
481  }
482  *numMatches = count;
483  return OK;
484}
485
486static char *set_opt_callback_orig_option = NULL;
487static char *((*set_opt_callback_func)(expand_T *, int));
488
489/// Callback used by expand_set_opt_generic to also include the original value.
490static char *expand_set_opt_callback(expand_T *xp, int idx)
491{
492  if (idx == 0) {
493    if (set_opt_callback_orig_option != NULL) {
494      return set_opt_callback_orig_option;
495    } else {
496      return "";  // empty strings are ignored
497    }
498  }
499  return set_opt_callback_func(xp, idx - 1);
500}
501
502/// Expand an option with a callback that iterates through a list of possible names.
503static int expand_set_opt_generic(optexpand_T *args, CompleteListItemGetter func, int *numMatches,
504                                  char ***matches)
505{
506  set_opt_callback_orig_option = args->oe_include_orig_val ? args->oe_opt_value : NULL;
507  set_opt_callback_func = func;
508
509  // not using fuzzy as currently EXPAND_STRING_SETTING doesn't use it
510  ExpandGeneric("", args->oe_xp, args->oe_regmatch, matches, numMatches,
511                expand_set_opt_callback, false);
512
513  set_opt_callback_orig_option = NULL;
514  set_opt_callback_func = NULL;
515  return OK;
516}
517
518/// Expand an option which is a list of flags.
519static int expand_set_opt_listflag(optexpand_T *args, char *flags, int *numMatches, char ***matches)
520{
521  char *option_val = args->oe_opt_value;
522  char *cmdline_val = args->oe_set_arg;
523  bool append = args->oe_append;
524  bool include_orig_val = args->oe_include_orig_val && (*option_val != NUL);
525
526  size_t num_flags = strlen(flags);
527
528  // Assume we only have small number of flags, so just allocate max size.
529  *matches = xmalloc(sizeof(char *) * (num_flags + 1));
530
531  int count = 0;
532
533  if (include_orig_val) {
534    (*matches)[count++] = xstrdup(option_val);
535  }
536
537  for (char *flag = flags; *flag != NUL; flag++) {
538    if (append && vim_strchr(option_val, *flag) != NULL) {
539      continue;
540    }
541
542    if (vim_strchr(cmdline_val, *flag) == NULL) {
543      if (include_orig_val && option_val[1] == NUL && *flag == option_val[0]) {
544        // This value is already used as the first choice as it's the
545        // existing flag. Just skip it to avoid duplicate.
546        continue;
547      }
548      (*matches)[count++] = xmemdupz(flag, 1);
549    }
550  }
551
552  if (count == 0) {
553    XFREE_CLEAR(*matches);
554    return FAIL;
555  }
556  *numMatches = count;
557  return OK;
558}
559
560static bool completing_value_for_subopt(optexpand_T *args, const char *name_suffix)
561{
562  const char *colon = args->oe_xp->xp_pattern - 1;
563  const size_t len = strlen(name_suffix);
564
565  return colon - args->oe_set_arg >= (int)len
566         && strncmp(colon - len, name_suffix, len) == 0;
567}
568
569/// The 'ambiwidth' option is changed.
570const char *did_set_ambiwidth(optset_T *args FUNC_ATTR_UNUSED)
571{
572  return check_chars_options();
573}
574
575/// The 'emoji' option is changed.
576const char *did_set_emoji(optset_T *args)
577{
578  const char *errmsg = check_str_opt(kOptAmbiwidth, NULL, args->os_errbuf);
579  if (errmsg != NULL) {
580    return errmsg;
581  }
582  return check_chars_options();
583}
584
585/// The 'background' option is changed.
586const char *did_set_background(optset_T *args)
587{
588  if (args->os_oldval.data.string.data[0] == *p_bg) {
589    // Value was not changed
590    return NULL;
591  }
592
593  int dark = (*p_bg == 'd');
594
595  init_highlight(false, false);
596
597  if (dark != (*p_bg == 'd') && get_var_value("g:colors_name") != NULL) {
598    // The color scheme must have set 'background' back to another
599    // value, that's not what we want here.  Disable the color
600    // scheme and set the colors again.
601    do_unlet(S_LEN("g:colors_name"), true);
602    free_string_option(p_bg);
603    p_bg = xstrdup((dark ? "dark" : "light"));
604    check_string_option(&p_bg);
605    init_highlight(false, false);
606  }
607
608  // Notify all terminal buffers that the background color changed so they can
609  // send a theme update notification
610  FOR_ALL_BUFFERS(buf) {
611    if (buf->terminal) {
612      terminal_notify_theme(buf->terminal, dark);
613    }
614  }
615
616  return NULL;
617}
618
619/// Validate the 'backspace' option.
620const char *validate_backspace(const optset_T *args)
621{
622  char *value = args->os_newval.data.string.data;
623  // Preserve the legacy numeric spelling accepted by :set.
624  if (ascii_isdigit(*value)) {
625    return *value == '2' ? NULL : e_invarg;
626  }
627  return validate_str_generic(args);
628}
629
630const char *validate_backupcopy(const optset_T *args)
631{
632  unsigned flags;
633  const char *errmsg = opt_strings_flags(args->os_newval.data.string.data, opt_bkc_values, &flags,
634                                         true, args->os_errbuf);
635  if (errmsg != NULL) {
636    return errmsg;
637  }
638  // Must have exactly one of "auto", "yes" and "no".
639  return ((flags & kOptBkcFlagAuto) != 0) + ((flags & kOptBkcFlagYes) != 0)
640         + ((flags & kOptBkcFlagNo) != 0) == 1 ? NULL : e_invarg;
641}
642
643/// The 'backupcopy' option is changed.
644const char *did_set_backupcopy(optset_T *args)
645{
646  buf_T *buf = args->os_buf;
647  int opt_flags = args->os_flags;
648  char *bkc = p_bkc;
649  unsigned *flags = &bkc_flags;
650
651  if (opt_flags & OPT_LOCAL) {
652    bkc = buf->b_p_bkc;
653    flags = &buf->b_bkc_flags;
654  } else if (!(opt_flags & OPT_GLOBAL)) {
655    // When using :set, clear the local flags.
656    buf->b_bkc_flags = 0;
657  }
658
659  if ((opt_flags & OPT_LOCAL) && *bkc == NUL) {
660    // make the local value empty: use the global value
661    *flags = 0;
662  } else {
663    const char *errmsg = opt_strings_flags(bkc, opt_bkc_values, flags, true, args->os_errbuf);
664    if (errmsg != NULL) {
665      return errmsg;
666    }
667  }
668
669  return NULL;
670}
671
672/// Validate the 'backupext' or 'patchmode' option.
673const char *validate_backupext_or_patchmode(const optset_T *args)
674{
675  char *bex = args->os_idx == kOptBackupext ? args->os_newval.data.string.data : p_bex;
676  char *pm = args->os_idx == kOptPatchmode ? args->os_newval.data.string.data : p_pm;
677  if (strcmp(*bex == '.' ? bex + 1 : bex, *pm == '.' ? pm + 1 : pm) == 0) {
678    return e_backupext_and_patchmode_are_equal;
679  }
680
681  return NULL;
682}
683
684/// The 'breakat' option is changed.
685const char *did_set_breakat(optset_T *args FUNC_ATTR_UNUSED)
686{
687  for (int i = 0; i < 256; i++) {
688    breakat_flags[i] = false;
689  }
690
691  if (p_breakat != NULL) {
692    for (char *p = p_breakat; *p; p++) {
693      breakat_flags[(uint8_t)(*p)] = true;
694    }
695  }
696
697  return NULL;
698}
699
700/// The 'breakindentopt' option is changed.
701const char *did_set_breakindentopt(optset_T *args)
702{
703  win_T *win = args->os_win;
704  // Apply it to the window, or to nothing if setting the global value.
705  bool is_local = args->os_varp == (void *)&win->w_p_briopt;
706  briopt_check(is_local ? win : NULL);
707
708  // list setting requires a redraw
709  if (is_local && win->w_briopt_list) {
710    redraw_all_later(UPD_NOT_VALID);
711  }
712
713  return NULL;
714}
715
716/// Validate the 'buftype' option.
717const char *validate_buftype(const optset_T *args)
718{
719  buf_T *buf = args->os_buf;
720  const char *errmsg = validate_str_generic(args);
721  if (errmsg != NULL) {
722    return errmsg;
723  }
724  // The global value does not change the target buffer's type.
725  if (!(args->os_flags & OPT_GLOBAL)
726      && (buf->terminal != NULL) != (args->os_newval.data.string.data[0] == 't')) {
727    return e_invarg;
728  }
729  return NULL;
730}
731
732/// The 'buftype' option is changed.
733const char *did_set_buftype(optset_T *args)
734{
735  buf_T *buf = args->os_buf;
736  win_T *win = args->os_win;
737  // buftype=prompt:
738  if (buf->b_p_bt[0] == 'p') {
739    // Set default value for 'comments'
740    set_option_direct(kOptComments, STATIC_CSTR_AS_OBJ(""), OPT_LOCAL, SID_NONE);
741    // set the prompt start position to lastline.
742    pos_T next_prompt = { .lnum = buf->b_ml.ml_line_count, .col = buf->b_prompt_start.mark.col,
743                          .coladd = 0 };
744    RESET_FMARK(&buf->b_prompt_start, next_prompt, 0, ((fmarkv_T)INIT_FMARKV));
745  }
746  if (win->w_status_height || global_stl_height()) {
747    win->w_redr_status = true;
748    redraw_later(win, UPD_VALID);
749  }
750  buf->b_help = (buf->b_p_bt[0] == 'h');
751  redraw_titles();
752  return NULL;
753}
754
755const char *validate_chars_option(const optset_T *args)
756{
757  return set_chars_option(args->os_win, args->os_newval.data.string.data,
758                          args->os_idx == kOptListchars ? kListchars : kFillchars,
759                          false, args->os_errbuf);
760}
761
762/// The global 'listchars' or 'fillchars' option is changed.
763static const char *did_set_global_chars_option(win_T *win, char *val, CharsOption what,
764                                               int opt_flags, const CharBuf *errbuf)
765{
766  const char *errmsg = NULL;
767  char **local_ptr = (what == kListchars) ? &win->w_p_lcs : &win->w_p_fcs;
768
769  // only apply the global value to "win" when it does not have a
770  // local value
771  errmsg = set_chars_option(win, val, what,
772                            **local_ptr == NUL || !(opt_flags & OPT_GLOBAL), errbuf);
773  if (errmsg != NULL) {
774    return errmsg;
775  }
776
777  // If the current window is set to use the global
778  // 'listchars'/'fillchars' value, clear the window-local value.
779  if (!(opt_flags & OPT_GLOBAL)) {
780    clear_string_option(local_ptr);
781  }
782
783  FOR_ALL_TAB_WINDOWS(tp, wp) {
784    // If the current window has a local value need to apply it
785    // again, it was changed when setting the global value.
786    // If no error was returned above, we don't expect an error
787    // here, so ignore the return value.
788    char *opt = (what == kListchars) ? wp->w_p_lcs : wp->w_p_fcs;
789    if (*opt == NUL) {
790      set_chars_option(wp, opt, what, true, errbuf);
791    }
792  }
793
794  redraw_all_later(UPD_NOT_VALID);
795
796  return NULL;
797}
798
799/// The 'fillchars' option or the 'listchars' option is changed.
800const char *did_set_chars_option(optset_T *args)
801{
802  win_T *win = args->os_win;
803  char **varp = (char **)args->os_varp;
804  const char *errmsg = NULL;
805
806  if (varp == &p_lcs) {      // global 'listchars'
807    errmsg = did_set_global_chars_option(win, *varp, kListchars, args->os_flags, args->os_errbuf);
808  } else if (varp == &p_fcs) {  // global 'fillchars'
809    errmsg = did_set_global_chars_option(win, *varp, kFillchars, args->os_flags, args->os_errbuf);
810  } else if (varp == &win->w_p_lcs) {  // local 'listchars'
811    errmsg = set_chars_option(win, *varp, kListchars, true, args->os_errbuf);
812  } else if (varp == &win->w_p_fcs) {  // local 'fillchars'
813    errmsg = set_chars_option(win, *varp, kFillchars, true, args->os_errbuf);
814  }
815
816  return errmsg;
817}
818
819/// Expand 'fillchars' or 'listchars' option value.
820int expand_set_chars_option(optexpand_T *args, int *numMatches, char ***matches)
821{
822  char **varp = (char **)args->oe_varp;
823  bool is_lcs = (varp == &p_lcs || varp == &curwin->w_p_lcs);
824  return expand_set_opt_generic(args,
825                                is_lcs ? get_listchars_name : get_fillchars_name,
826                                numMatches,
827                                matches);
828}
829
830/// The 'cinoptions' option is changed.
831const char *did_set_cinoptions(optset_T *args)
832{
833  buf_T *buf = args->os_buf;
834  // TODO(vim): recognize errors
835  parse_cino(buf);
836
837  return NULL;
838}
839
840const char *validate_colorcolumn(const optset_T *args)
841{
842  return check_colorcolumn(args->os_newval.data.string.data, NULL);
843}
844
845/// The 'colorcolumn' option is changed.
846const char *did_set_colorcolumn(optset_T *args)
847{
848  win_T *win = args->os_win;
849  char **varp = (char **)args->os_varp;
850  return check_colorcolumn(*varp, varp == &win->w_p_cc ? win : NULL);
851}
852
853/// Validate the 'comments' option.
854const char *validate_comments(const optset_T *args)
855{
856  const char *errmsg = NULL;
857  for (char *s = args->os_newval.data.string.data; *s;) {
858    while (*s && *s != ':') {
859      if (vim_strchr(COM_ALL, (uint8_t)(*s)) == NULL
860          && !ascii_isdigit(*s) && *s != '-') {
861        errmsg = illegal_char(args->os_errbuf, (uint8_t)(*s));
862        break;
863      }
864      s++;
865    }
866    if (*s++ == NUL) {
867      errmsg = N_("E524: Missing colon");
868    } else if (*s == ',' || *s == NUL) {
869      errmsg = N_("E525: Zero length string");
870    }
871    if (errmsg != NULL) {
872      break;
873    }
874    while (*s && *s != ',') {
875      if (*s == '\\' && s[1] != NUL) {
876        s++;
877      }
878      s++;
879    }
880    s = skip_to_option_part(s);
881  }
882  return errmsg;
883}
884
885/// Validate the 'commentstring' option.
886const char *validate_commentstring(const optset_T *args)
887{
888  char *value = args->os_newval.data.string.data;
889  return *value == NUL || strstr(value, "%s") != NULL
890         ? NULL : N_("E537: 'commentstring' must be empty or contain %s");
891}
892
893/// Validate the 'complete' option.
894const char *validate_complete(const optset_T *args)
895{
896  char buffer[LSIZE];
897  uint8_t char_before = NUL;
898
899  for (char *p = args->os_newval.data.string.data; *p;) {
900    memset(buffer, 0, LSIZE);
901    char *buf_ptr = buffer;
902    int escape = 0;
903
904    // Extract substring while handling escaped commas
905    while (*p && (*p != ',' || escape) && buf_ptr < (buffer + LSIZE - 1)) {
906      if (*p == '\\' && *(p + 1) == ',') {
907        escape = 1;  // Mark escape mode
908        p++;         // Skip '\'
909      } else {
910        escape = 0;
911        *buf_ptr++ = *p;
912      }
913      p++;
914    }
915    *buf_ptr = NUL;
916
917    if (vim_strchr(".wbuksid]tUfFo", (uint8_t)(*buffer)) == NULL) {
918      return illegal_char(args->os_errbuf, (uint8_t)(*buffer));
919    }
920
921    if (vim_strchr("ksF", (uint8_t)(*buffer)) == NULL && *(buffer + 1) != NUL
922        && *(buffer + 1) != '^') {
923      char_before = (uint8_t)(*buffer);
924    } else {
925      char *t;
926      // Test for a number after '^'
927      if ((t = vim_strchr(buffer, '^')) != NULL) {
928        *t++ = NUL;
929        if (!*t) {
930          char_before = '^';
931        } else {
932          for (; *t; t++) {
933            if (!ascii_isdigit(*t)) {
934              char_before = '^';
935              break;
936            }
937          }
938        }
939      }
940    }
941    if (char_before != NUL) {
942      return opt_error(args->os_errbuf, e_illegal_character_after_chr, char_before);
943    }
944    // Skip comma and spaces
945    while (*p == ',' || *p == ' ') {
946      p++;
947    }
948  }
949
950  return NULL;
951}
952
953/// The 'complete' option is changed.
954const char *did_set_complete(optset_T *args)
955{
956  if (set_cpt_callbacks(args) != OK) {
957    return opt_error(args->os_errbuf, e_illegal_character_after_chr, 'F');
958  }
959  return NULL;
960}
961
962/// The 'completeitemalign' option is changed.
963const char *did_set_completeitemalign(optset_T *args)
964{
965  char *p = p_cia;
966  unsigned new_cia_flags = 0;
967  bool seen[3] = { false, false, false };
968  int count = 0;
969  char buf[10];
970  while (*p) {
971    copy_option_part(&p, buf, sizeof(buf), ",");
972    if (count >= 3) {
973      return e_invarg;
974    }
975    if (strequal(buf, "abbr")) {
976      if (seen[CPT_ABBR]) {
977        return e_invarg;
978      }
979      new_cia_flags = new_cia_flags * 10 + CPT_ABBR;
980      seen[CPT_ABBR] = true;
981      count++;
982    } else if (strequal(buf, "kind")) {
983      if (seen[CPT_KIND]) {
984        return e_invarg;
985      }
986      new_cia_flags = new_cia_flags * 10 + CPT_KIND;
987      seen[CPT_KIND] = true;
988      count++;
989    } else if (strequal(buf, "menu")) {
990      if (seen[CPT_MENU]) {
991        return e_invarg;
992      }
993      new_cia_flags = new_cia_flags * 10 + CPT_MENU;
994      seen[CPT_MENU] = true;
995      count++;
996    } else {
997      return e_invarg;
998    }
999  }
1000  if (new_cia_flags == 0 || count != 3) {
1001    return e_invarg;
1002  }
1003  cia_flags = new_cia_flags;
1004  return NULL;
1005}
1006
1007/// The 'completeopt' option is changed.
1008const char *did_set_completeopt(optset_T *args FUNC_ATTR_UNUSED)
1009{
1010  buf_T *buf = args->os_buf;
1011  char *cot = p_cot;
1012  unsigned *flags = &cot_flags;
1013
1014  if (args->os_flags & OPT_LOCAL) {
1015    cot = buf->b_p_cot;
1016    flags = &buf->b_cot_flags;
1017  } else if (!(args->os_flags & OPT_GLOBAL)) {
1018    // When using :set, clear the local flags.
1019    buf->b_cot_flags = 0;
1020  }
1021
1022  return opt_strings_flags(cot, opt_cot_values, flags, true, args->os_errbuf);
1023}
1024
1025#ifdef BACKSLASH_IN_FILENAME
1026/// The 'completeslash' option is changed.
1027const char *did_set_completeslash(optset_T *args)
1028{
1029  buf_T *buf = args->os_buf;
1030  const char *errmsg = opt_strings_flags(p_csl, opt_csl_values, NULL, false, args->os_errbuf);
1031  if (errmsg != NULL) {
1032    return errmsg;
1033  }
1034  return opt_strings_flags(buf->b_p_csl, opt_csl_values, NULL, false, args->os_errbuf);
1035}
1036#endif
1037
1038/// Validate the 'concealcursor' option.
1039const char *validate_concealcursor(const optset_T *args)
1040{
1041  return check_option_listflag(args->os_newval.data.string.data, COCU_ALL, args->os_errbuf);
1042}
1043
1044int expand_set_concealcursor(optexpand_T *args, int *numMatches, char ***matches)
1045{
1046  return expand_set_opt_listflag(args, COCU_ALL, numMatches, matches);
1047}
1048
1049/// Validate the 'cpoptions' option.
1050const char *validate_cpoptions(const optset_T *args)
1051{
1052  return check_option_listflag(args->os_newval.data.string.data, CPO_VI, args->os_errbuf);
1053}
1054
1055int expand_set_cpoptions(optexpand_T *args, int *numMatches, char ***matches)
1056{
1057  return expand_set_opt_listflag(args, CPO_VI, numMatches, matches);
1058}
1059
1060/// The 'cursorlineopt' option is changed.
1061const char *did_set_cursorlineopt(optset_T *args)
1062{
1063  win_T *win = args->os_win;
1064  char **varp = (char **)args->os_varp;
1065
1066  // This could be changed to use opt_strings_flags() instead.
1067  if (**varp == NUL || fill_culopt_flags(*varp, win) != OK) {
1068    return e_invarg;
1069  }
1070
1071  return NULL;
1072}
1073
1074/// The 'diffanchors' option is changed.
1075const char *did_set_diffanchors(optset_T *args)
1076{
1077  if (diffanchors_changed(args->os_flags & OPT_LOCAL) == FAIL) {
1078    return e_invarg;
1079  }
1080
1081  return NULL;
1082}
1083
1084/// The 'diffopt' option is changed.
1085const char *did_set_diffopt(optset_T *args FUNC_ATTR_UNUSED)
1086{
1087  return diffopt_changed() == FAIL ? e_invarg : NULL;
1088}
1089
1090int expand_set_diffopt(optexpand_T *args, int *numMatches, char ***matches)
1091{
1092  expand_T *xp = args->oe_xp;
1093
1094  if (xp->xp_pattern > args->oe_set_arg && *(xp->xp_pattern - 1) == ':') {
1095    if (completing_value_for_subopt(args, "algorithm")) {
1096      return expand_set_opt_string(args,
1097                                   opt_dip_algorithm_values,
1098                                   ARRAY_SIZE(opt_dip_algorithm_values) - 1,
1099                                   numMatches,
1100                                   matches);
1101    }
1102    if (completing_value_for_subopt(args, "inline")) {
1103      return expand_set_opt_string(args,
1104                                   opt_dip_inline_values,
1105                                   ARRAY_SIZE(opt_dip_inline_values) - 1,
1106                                   numMatches,
1107                                   matches);
1108    }
1109    return FAIL;
1110  }
1111
1112  return expand_set_str_generic(args, numMatches, matches);
1113}
1114
1115/// The 'display' option is changed.
1116const char *did_set_display(optset_T *args)
1117{
1118  const char *errmsg = did_set_str_generic(args);
1119  if (errmsg != NULL) {
1120    return errmsg;
1121  }
1122  dy_escape_width = ((dy_flags & kOptDyFlagUhex) ? 4 : 2);
1123  msg_grid_validate();
1124  return NULL;
1125}
1126
1127/// One of the 'encoding', 'fileencoding' or 'makeencoding'
1128/// options is changed.
1129const char *did_set_encoding(optset_T *args)
1130{
1131  buf_T *buf = args->os_buf;
1132  char **varp = (char **)args->os_varp;
1133  int opt_flags = args->os_flags;
1134  // Get the global option to compare with, otherwise we would have to check
1135  // two values for all local options.
1136  char **gvarp = (char **)get_option_varp_scope_from(args->os_idx, OPT_GLOBAL, buf, NULL);
1137
1138  if (gvarp == &p_fenc) {
1139    if (!MODIFIABLE(buf) && opt_flags != OPT_GLOBAL) {
1140      return e_modifiable;
1141    }
1142
1143    if (vim_strchr(*varp, ',') != NULL) {
1144      // No comma allowed in 'fileencoding'; catches confusing it
1145      // with 'fileencodings'.
1146      return e_invarg;
1147    }
1148
1149    // May show a "+" in the title now.
1150    redraw_titles();
1151    // Add 'fileencoding' to the swap file.
1152    ml_setflags(buf);
1153  }
1154
1155  // canonize the value, so that strcmp() can be used on it
1156  char *p = enc_canonize(*varp);
1157  xfree(*varp);
1158  *varp = p;
1159  if (varp == &p_enc) {
1160    // only encoding=utf-8 allowed
1161    if (strcmp(p_enc, "utf-8") != 0) {
1162      return e_unsupportedoption;
1163    }
1164    spell_reload();
1165  }
1166  return NULL;
1167}
1168
1169int expand_set_encoding(optexpand_T *args, int *numMatches, char ***matches)
1170{
1171  return expand_set_opt_generic(args, get_encoding_name, numMatches, matches);
1172}
1173
1174/// Validate the 'eventignore'/'eventignorewin' option.
1175const char *validate_eventignore(const optset_T *args)
1176{
1177  if (check_ei(args->os_newval.data.string.data, args->os_idx == kOptEventignorewin) == FAIL) {
1178    return e_invarg;
1179  }
1180  return NULL;
1181}
1182
1183static bool expand_eiw = false;
1184
1185static char *get_eventignore_name(expand_T *xp, int idx)
1186{
1187  bool subtract = *xp->xp_pattern == '-';
1188  // 'eventignore(win)' allows special keyword "all" in addition to
1189  // all event names.
1190  if (!subtract && idx == 0) {
1191    return "all";
1192  }
1193
1194  char *name = get_event_name_no_group(xp, idx - 1 + subtract, expand_eiw);
1195  if (name == NULL) {
1196    return NULL;
1197  }
1198
1199  snprintf(IObuff, IOSIZE, "%s%s", subtract ? "-" : "", name);
1200  return IObuff;
1201}
1202
1203int expand_set_eventignore(optexpand_T *args, int *numMatches, char ***matches)
1204{
1205  expand_eiw = args->oe_varp != (char *)&p_ei;
1206  return expand_set_opt_generic(args, get_eventignore_name, numMatches, matches);
1207}
1208
1209const char *validate_fileformat(const optset_T *args)
1210{
1211  buf_T *buf = args->os_buf;
1212  if (!(args->os_flags & OPT_GLOBAL) && !MODIFIABLE(buf)) {
1213    return e_modifiable;
1214  }
1215  return validate_str_generic(args);
1216}
1217
1218/// The 'fileformat' option is changed.
1219const char *did_set_fileformat(optset_T *args)
1220{
1221  buf_T *buf = args->os_buf;
1222  const char *oldval = args->os_oldval.data.string.data;
1223
1224  redraw_titles();
1225  // update flag in swap file
1226  ml_setflags(buf);
1227  // Redraw needed when switching to/from "mac": a CR in the text
1228  // will be displayed differently.
1229  if (get_fileformat(buf) == EOL_MAC || *oldval == 'm') {
1230    redraw_buf_later(buf, UPD_NOT_VALID);
1231  }
1232  return NULL;
1233}
1234
1235/// Function given to ExpandGeneric() to obtain the possible arguments of the
1236/// fileformat options.
1237char *get_fileformat_name(expand_T *xp FUNC_ATTR_UNUSED, int idx)
1238{
1239  if (idx >= (int)ARRAY_SIZE(opt_ff_values)) {
1240    return NULL;
1241  }
1242
1243  return (char *)opt_ff_values[idx];
1244}
1245
1246/// Validate the 'filetype', 'syntax' or 'keymap' option.
1247const char *validate_filetype(const optset_T *args)
1248{
1249  return valid_filetype(args->os_newval.data.string.data) ? NULL : e_invarg;
1250}
1251
1252/// The 'filetype' or the 'syntax' option is changed.
1253const char *did_set_filetype_or_syntax(optset_T *args)
1254{
1255  char **varp = (char **)args->os_varp;
1256
1257  args->os_value_changed = strcmp(args->os_oldval.data.string.data, *varp) != 0;
1258
1259  // Since we check the value, there is no need to set kOptFlagInsecure,
1260  // even when the value comes from a modeline.
1261  args->os_value_checked = true;
1262
1263  return NULL;
1264}
1265
1266/// The 'foldexpr' option is changed.
1267const char *did_set_foldexpr(optset_T *args)
1268{
1269  win_T *win = args->os_win;
1270  if (foldmethodIsExpr(win)) {
1271    foldUpdateAll(win);
1272  }
1273  return NULL;
1274}
1275
1276/// The 'foldignore' option is changed.
1277const char *did_set_foldignore(optset_T *args)
1278{
1279  win_T *win = args->os_win;
1280  if (foldmethodIsIndent(win)) {
1281    foldUpdateAll(win);
1282  }
1283  return NULL;
1284}
1285
1286/// Validate the 'foldmarker' option.
1287const char *validate_foldmarker(const optset_T *args)
1288{
1289  char *value = args->os_newval.data.string.data;
1290  const char *p = vim_strchr(value, ',');
1291  if (p == NULL) {
1292    return e_comma_required;
1293  }
1294  return p == value || p[1] == NUL ? e_invarg : NULL;
1295}
1296
1297/// The 'foldmarker' option is changed.
1298const char *did_set_foldmarker(optset_T *args)
1299{
1300  win_T *win = args->os_win;
1301  if (foldmethodIsMarker(win)) {
1302    foldUpdateAll(win);
1303  }
1304
1305  return NULL;
1306}
1307
1308/// The 'foldmethod' option is changed.
1309const char *did_set_foldmethod(optset_T *args)
1310{
1311  win_T *win = args->os_win;
1312  foldUpdateAll(win);
1313  if (foldmethodIsDiff(win)) {
1314    newFoldLevel();
1315  }
1316  return NULL;
1317}
1318
1319/// Validate the 'formatoptions' option.
1320const char *validate_formatoptions(const optset_T *args)
1321{
1322  return check_option_listflag(args->os_newval.data.string.data, FO_ALL, args->os_errbuf);
1323}
1324
1325int expand_set_formatoptions(optexpand_T *args, int *numMatches, char ***matches)
1326{
1327  return expand_set_opt_listflag(args, FO_ALL, numMatches, matches);
1328}
1329
1330/// The 'guicursor' option is changed.
1331const char *did_set_guicursor(optset_T *args FUNC_ATTR_UNUSED)
1332{
1333  const char *errmsg = parse_shape_opt(SHAPE_CURSOR);
1334  if (errmsg != NULL) {
1335    return errmsg;
1336  }
1337  if (Visual.active) {
1338    // In Visual mode cursor may be drawn differently.
1339    redrawWinline(curwin, curwin->w_cursor.lnum);
1340  }
1341  return NULL;
1342}
1343
1344/// The 'helpfile' option is changed.
1345const char *did_set_helpfile(optset_T *args FUNC_ATTR_UNUSED)
1346{
1347  // May compute new values for $VIM and $VIMRUNTIME
1348  if (didset_vim) {
1349    vim_unsetenv_ext("VIM");
1350  }
1351  if (didset_vimruntime) {
1352    vim_unsetenv_ext("VIMRUNTIME");
1353  }
1354  return NULL;
1355}
1356
1357/// Validate the 'helplang' option.
1358const char *validate_helplang(const optset_T *args)
1359{
1360  // Check for "", "ab", "ab,cd", etc.
1361  for (char *s = args->os_newval.data.string.data; *s != NUL; s += 3) {
1362    if (s[1] == NUL || ((s[2] != ',' || s[3] == NUL) && s[2] != NUL)) {
1363      return e_invarg;
1364    }
1365    if (s[2] == NUL) {
1366      break;
1367    }
1368  }
1369  return NULL;
1370}
1371
1372/// Validate the 'highlight' option.
1373const char *validate_highlight(const optset_T *args)
1374{
1375  if (strcmp(args->os_newval.data.string.data, HIGHLIGHT_INIT) != 0) {
1376    return e_unsupportedoption;
1377  }
1378  return NULL;
1379}
1380
1381/// The 'iconstring' option is changed.
1382const char *did_set_iconstring(optset_T *args)
1383{
1384  return did_set_titleiconstring(args, STL_IN_ICON);
1385}
1386
1387/// The 'inccommand' option is changed.
1388const char *did_set_inccommand(optset_T *args FUNC_ATTR_UNUSED)
1389{
1390  if (cmdpreview) {
1391    return e_invarg;
1392  }
1393  return NULL;
1394}
1395
1396/// Validate the 'isident', 'iskeyword' or 'isfname' option.
1397const char *validate_isopt(const optset_T *args)
1398{
1399  return check_isopt(args->os_newval.data.string.data) == FAIL ? e_invarg : NULL;
1400}
1401
1402/// The 'iskeyword' option is changed.
1403const char *did_set_iskeyword(optset_T *args)
1404{
1405  char **varp = (char **)args->os_varp;
1406
1407  // The global value only affects new buffers.
1408  if (varp != &p_isk) {
1409    buf_T *buf = args->os_buf;
1410    if (buf_init_isk_chartab(buf) == FAIL) {
1411      return e_invarg;    // error in value
1412    }
1413  }
1414
1415  return NULL;
1416}
1417
1418/// The 'isident' or the 'iskeyword' or the 'isprint' or the 'isfname' option is
1419/// changed.
1420const char *did_set_isopt(optset_T *args)
1421{
1422  int res = FAIL;
1423  if (args->os_varp == &p_isf) {
1424    res = init_isf_chartab();
1425  } else {
1426    res = init_isi_chartab();
1427  }
1428
1429  return res == FAIL ? e_invarg : NULL;
1430}
1431
1432/// The 'keymap' option has changed.
1433const char *did_set_keymap(optset_T *args)
1434{
1435  buf_T *buf = args->os_buf;
1436  int opt_flags = args->os_flags;
1437
1438  int secure_save = secure;
1439
1440  // Reset the secure flag, since the value of 'keymap' has
1441  // been checked to be safe.
1442  secure = 0;
1443
1444  // load or unload key mapping tables
1445  const char *errmsg = keymap_init();
1446
1447  secure = secure_save;
1448
1449  // Since we check the value, there is no need to set kOptFlagInsecure,
1450  // even when the value comes from a modeline.
1451  args->os_value_checked = true;
1452
1453  if (errmsg == NULL) {
1454    if (*buf->b_p_keymap != NUL) {
1455      // Installed a new keymap, switch on using it.
1456      buf->b_p_iminsert = B_IMODE_LMAP;
1457      if (buf->b_p_imsearch != B_IMODE_USE_INSERT) {
1458        buf->b_p_imsearch = B_IMODE_LMAP;
1459      }
1460    } else {
1461      // Cleared the keymap, may reset 'iminsert' and 'imsearch'.
1462      if (buf->b_p_iminsert == B_IMODE_LMAP) {
1463        buf->b_p_iminsert = B_IMODE_NONE;
1464      }
1465      if (buf->b_p_imsearch == B_IMODE_LMAP) {
1466        buf->b_p_imsearch = B_IMODE_USE_INSERT;
1467      }
1468    }
1469    if ((opt_flags & OPT_LOCAL) == 0) {
1470      set_iminsert_global(buf);
1471      set_imsearch_global(buf);
1472    }
1473    status_redraw_buf(buf);
1474  }
1475
1476  return errmsg;
1477}
1478
1479/// The 'keymodel' option is changed.
1480const char *did_set_keymodel(optset_T *args FUNC_ATTR_UNUSED)
1481{
1482  km_stopsel = (vim_strchr(p_km, 'o') != NULL);
1483  km_startsel = (vim_strchr(p_km, 'a') != NULL);
1484  return NULL;
1485}
1486
1487/// Validate the 'lispoptions' option.
1488const char *validate_lispoptions(const optset_T *args)
1489{
1490  char *value = args->os_newval.data.string.data;
1491  return *value == NUL || strcmp(value, "expr:0") == 0 || strcmp(value, "expr:1") == 0
1492         ? NULL : e_invarg;
1493}
1494
1495/// Validate the 'matchpairs' option.
1496const char *validate_matchpairs(const optset_T *args)
1497{
1498  for (char *p = args->os_newval.data.string.data; *p != NUL; p++) {
1499    int x2 = -1;
1500    int x3 = -1;
1501
1502    p += utfc_ptr2len(p);
1503    if (*p != NUL) {
1504      x2 = (unsigned char)(*p++);
1505    }
1506    if (*p != NUL) {
1507      x3 = utf_ptr2char(p);
1508      p += utfc_ptr2len(p);
1509    }
1510    if (x2 != ':' || x3 == -1 || (*p != NUL && *p != ',')) {
1511      return e_invarg;
1512    }
1513    if (*p == NUL) {
1514      break;
1515    }
1516  }
1517  return NULL;
1518}
1519
1520/// Process the updated 'messagesopt' option value.
1521const char *did_set_messagesopt(optset_T *args FUNC_ATTR_UNUSED)
1522{
1523  if (messagesopt_changed() == FAIL) {
1524    return e_invarg;
1525  }
1526  return NULL;
1527}
1528
1529/// Validate the 'mkspellmem' option.
1530const char *validate_mkspellmem(const optset_T *args)
1531{
1532  return spell_check_msm(args->os_newval.data.string.data, false) == OK ? NULL : e_invarg;
1533}
1534
1535/// Validate the 'mouse' option.
1536const char *validate_mouse(const optset_T *args)
1537{
1538  return check_option_listflag(args->os_newval.data.string.data, MOUSE_ALL, args->os_errbuf);
1539}
1540
1541int expand_set_mouse(optexpand_T *args, int *numMatches, char ***matches)
1542{
1543  return expand_set_opt_listflag(args, MOUSE_ALL, numMatches, matches);
1544}
1545
1546/// Validate the 'mousescroll' option.
1547/// @return error message, NULL if it's OK.
1548const char *validate_mousescroll(const optset_T *args)
1549{
1550  OptKeyDict_mousescroll *v = opt_keyset(args->os_newval.data.string.data, kOptMousescroll, NULL);
1551  // At least one direction is required, even if its count is zero.
1552  return HAS_KEY(v, mousescroll, hor) || HAS_KEY(v, mousescroll, ver) ? NULL : e_invarg;
1553}
1554
1555/// Handle setting 'mousescroll'.
1556const char *did_set_mousescroll(optset_T *args FUNC_ATTR_UNUSED)
1557{
1558  OptKeyDict_mousescroll *v = opt_keyset(p_mousescroll, kOptMousescroll, NULL);
1559  p_mousescroll_hor = HAS_KEY(v, mousescroll, hor) ? (int)v->hor : MOUSESCROLL_HOR_DFLT;
1560  p_mousescroll_vert = HAS_KEY(v, mousescroll, ver) ? (int)v->ver : MOUSESCROLL_VERT_DFLT;
1561  return NULL;
1562}
1563
1564/// The 'rulerformat' option is changed.
1565const char *did_set_rulerformat(optset_T *args)
1566{
1567  return did_set_statustabline_rulerformat(args, true, false);
1568}
1569
1570/// The 'selection' option is changed.
1571const char *did_set_selection(optset_T *args FUNC_ATTR_UNUSED)
1572{
1573  if (Visual.active) {
1574    // Visual selection may be drawn differently.
1575    redraw_curbuf_later(UPD_INVERTED);
1576  }
1577  return NULL;
1578}
1579
1580/// Validate the 'sessionoptions' option.
1581const char *validate_sessionoptions(const optset_T *args)
1582{
1583  unsigned flags;
1584  const char *errmsg = opt_strings_flags(args->os_newval.data.string.data, opt_ssop_values, &flags,
1585                                         true, args->os_errbuf);
1586  if (errmsg != NULL) {
1587    return errmsg;
1588  }
1589  // Don't allow both "sesdir" and "curdir".
1590  return (flags & kOptSsopFlagCurdir) && (flags & kOptSsopFlagSesdir) ? e_invarg : NULL;
1591}
1592
1593/// Validate the 'shada' option.
1594const char *validate_shada(const optset_T *args)
1595{
1596  const CharBuf *errbuf = args->os_errbuf;
1597  char *value = args->os_newval.data.string.data;
1598  char *marks = NULL;
1599
1600  for (char *s = value; *s;) {
1601    // Keep the first ' parameter, matching get_shada_parameter().
1602    if (*s == '\'' && marks == NULL) {
1603      marks = s + 1;
1604    }
1605    // Check it's a valid character
1606    if (vim_strchr("!\"%'/:<@cfhnrs", (uint8_t)(*s)) == NULL) {
1607      return illegal_char(errbuf, (uint8_t)(*s));
1608    }
1609    if (*s == 'n') {          // name is always last one
1610      break;
1611    } else if (*s == 'r') {  // skip until next ','
1612      while (*++s && *s != ',') {}
1613    } else if (*s == '%') {
1614      // optional number
1615      while (ascii_isdigit(*++s)) {}
1616    } else if (*s == '!' || *s == 'h' || *s == 'c') {
1617      s++;                    // no extra chars
1618    } else {                    // must have a number
1619      while (ascii_isdigit(*++s)) {}
1620
1621      if (!ascii_isdigit(*(s - 1))) {
1622        if (errbuf != NULL) {
1623          return opt_error(errbuf, N_("E526: Missing number after <%s>"),
1624                           transchar_byte((uint8_t)(*(s - 1))));
1625        } else {
1626          return "";
1627        }
1628      }
1629    }
1630    if (*s == ',') {
1631      s++;
1632    } else if (*s) {
1633      if (errbuf != NULL) {
1634        return N_("E527: Missing comma");
1635      } else {
1636        return "";
1637      }
1638    }
1639  }
1640  if (*value && (marks == NULL || atoi(marks) < 0)) {
1641    return N_("E528: Must specify a ' value");
1642  }
1643  return NULL;
1644}
1645
1646/// Validate 'shellpipe'/'shellredir' option.
1647const char *validate_shellpipe_redir(const optset_T *args)
1648{
1649  bool seen = false;
1650
1651  for (char *p = args->os_newval.data.string.data; *p != NUL; p++) {
1652    if (*p != '%') {
1653      continue;
1654    }
1655    if (p[1] == NUL) {
1656      return e_invalid_format_string_single_percent_s;
1657    }
1658    if (p[1] == '%') {
1659      p++;    // skip second %
1660      continue;
1661    }
1662
1663    if (p[1] == 's') {
1664      if (seen) {
1665        return e_invalid_format_string_single_percent_s;
1666      }
1667      seen = true;
1668      p++;    // consume 's'
1669      continue;
1670    }
1671    return e_invalid_format_string_single_percent_s;
1672  }
1673  return NULL;
1674}
1675
1676int expand_set_shortmess(optexpand_T *args, int *numMatches, char ***matches)
1677{
1678  return expand_set_opt_listflag(args, SHM_ALL, numMatches, matches);
1679}
1680
1681/// Validate the 'shortmess' option.
1682const char *validate_shortmess(const optset_T *args)
1683{
1684  return check_option_listflag(args->os_newval.data.string.data, SHM_ALL, args->os_errbuf);
1685}
1686
1687/// Validate the 'showbreak' option.
1688const char *validate_showbreak(const optset_T *args)
1689{
1690  for (char *s = args->os_newval.data.string.data; *s;) {
1691    if (ptr2cells(s) != 1) {
1692      return e_showbreak_contains_unprintable_or_wide_character;
1693    }
1694    MB_PTR_ADV(s);
1695  }
1696  return NULL;
1697}
1698
1699/// The 'showcmdloc' option is changed.
1700const char *did_set_showcmdloc(optset_T *args FUNC_ATTR_UNUSED)
1701{
1702  comp_col();
1703  return NULL;
1704}
1705
1706const char *validate_signcolumn(const optset_T *args)
1707{
1708  return check_signcolumn(args->os_newval.data.string.data, NULL) == OK ? NULL : e_invarg;
1709}
1710
1711/// The 'signcolumn' option is changed.
1712const char *did_set_signcolumn(optset_T *args)
1713{
1714  win_T *win = args->os_win;
1715  char **varp = (char **)args->os_varp;
1716  const char *oldval = args->os_oldval.data.string.data;
1717  if (check_signcolumn(*varp, varp == &win->w_p_scl ? win : NULL) != OK) {
1718    return e_invarg;
1719  }
1720  // When changing the 'signcolumn' to or from 'number', recompute the
1721  // width of the number column if 'number' or 'relativenumber' is set.
1722  if ((*oldval == 'n' && *(oldval + 1) == 'u') || win->w_minscwidth == SCL_NUM) {
1723    win->w_nrwidth_line_count = 0;
1724  }
1725  return NULL;
1726}
1727
1728/// The 'spellcapcheck' option is changed.
1729const char *did_set_spellcapcheck(optset_T *args)
1730{
1731  win_T *win = args->os_win;
1732  // When 'spellcapcheck' is set compile the regexp program.
1733  return compile_cap_prog(win->w_s);
1734}
1735
1736/// Validate the 'spellfile' option.
1737const char *validate_spellfile(const optset_T *args)
1738{
1739  return valid_spellfile(args->os_newval.data.string.data) ? NULL : e_invarg;
1740}
1741
1742/// The 'spellfile' option is changed.
1743const char *did_set_spellfile(optset_T *args FUNC_ATTR_UNUSED)
1744{
1745  // When there is a window for this buffer in which 'spell'
1746  // is set load the wordlists.
1747  return did_set_spell_option();
1748}
1749
1750/// Validate the 'spelllang' option.
1751const char *validate_spelllang(const optset_T *args)
1752{
1753  return valid_spelllang(args->os_newval.data.string.data) ? NULL : e_invarg;
1754}
1755
1756/// The 'spelllang' option is changed.
1757const char *did_set_spelllang(optset_T *args FUNC_ATTR_UNUSED)
1758{
1759  // When there is a window for this buffer in which 'spell'
1760  // is set load the wordlists.
1761  return did_set_spell_option();
1762}
1763
1764/// The 'spelloptions' option is changed.
1765const char *did_set_spelloptions(optset_T *args)
1766{
1767  win_T *win = args->os_win;
1768  int opt_flags = args->os_flags;
1769  const char *val = args->os_newval.data.string.data;
1770
1771  if (!(opt_flags & OPT_LOCAL)) {
1772    const char *errmsg = opt_strings_flags(val, opt_spo_values, &spo_flags, true, args->os_errbuf);
1773    if (errmsg != NULL) {
1774      return errmsg;
1775    }
1776  }
1777  if (!(opt_flags & OPT_GLOBAL)) {
1778    const char *errmsg = opt_strings_flags(val, opt_spo_values, &win->w_s->b_p_spo_flags, true,
1779                                           args->os_errbuf);
1780    if (errmsg != NULL) {
1781      return errmsg;
1782    }
1783  }
1784  return NULL;
1785}
1786
1787/// The 'spellsuggest' option is changed.
1788const char *did_set_spellsuggest(optset_T *args FUNC_ATTR_UNUSED)
1789{
1790  if (spell_check_sps() != OK) {
1791    return e_invarg;
1792  }
1793  return NULL;
1794}
1795
1796const char *did_set_splitkeep(optset_T *args FUNC_ATTR_UNUSED)
1797{
1798  FOR_ALL_TAB_WINDOWS(tp, wp) {
1799    wp->w_prev_height = wp->w_height;
1800    wp->w_prev_winrow = wp->w_winrow;
1801  }
1802  return NULL;
1803}
1804
1805const char *validate_statustabline_rulerformat(const optset_T *args)
1806{
1807  char *value = args->os_newval.data.string.data;
1808  // Check 'statusline', 'rulerformat', 'winbar', 'tabline' or 'statuscolumn' only if it
1809  // doesn't start with "%!": those expressions are evaluated when drawing.
1810  return value[0] == '%' && value[1] == '!' ? NULL : check_stl_option(value, args->os_errbuf);
1811}
1812
1813/// The 'statuscolumn' option is changed.
1814const char *did_set_statuscolumn(optset_T *args)
1815{
1816  return did_set_statustabline_rulerformat(args, false, true);
1817}
1818
1819/// The 'statusline' option is changed.
1820const char *did_set_statusline(optset_T *args)
1821{
1822  return did_set_statustabline_rulerformat(args, false, false);
1823}
1824
1825/// The 'statusline', 'winbar', 'tabline', 'rulerformat' or 'statuscolumn' option is changed.
1826///
1827/// @param rulerformat  true if the 'rulerformat' option is changed
1828/// @param statuscolumn  true if the 'statuscolumn' option is changed
1829static const char *did_set_statustabline_rulerformat(optset_T *args, bool rulerformat,
1830                                                     bool statuscolumn)
1831{
1832  win_T *win = args->os_win;
1833  char **varp = (char **)args->os_varp;
1834  if (rulerformat) {       // reset ru_wid first
1835    ru_wid = 0;
1836  } else if (statuscolumn) {
1837    // reset 'statuscolumn' width
1838    win->w_nrwidth_line_count = 0;
1839  }
1840  char *s = *varp;
1841  bool is_stl = args->os_idx == kOptStatusline;
1842
1843  // reset global statusline/rulerformat option to default when it is being set to an empty string
1844  if ((is_stl || rulerformat)
1845      && ((args->os_flags & OPT_GLOBAL) || !(args->os_flags & OPT_LOCAL))
1846      && s[0] == NUL) {
1847    xfree(*varp);
1848    Object def = get_option_default(args->os_idx, args->os_flags);
1849    *varp = xstrdup(def.data.string.data);
1850    optval_free_read(args->os_idx, def);
1851    s = *varp;
1852  }
1853
1854  // handle floating window statusline changes
1855  if (is_stl && win && win->w_floating) {
1856    win_config_float(win, win->w_config);
1857  }
1858
1859  if (rulerformat && !ui_has(kUIMessages) && *s == '%') {
1860    // set ru_wid if 'ruf' starts with "%99("
1861    if (*++s == '-') {        // ignore a '-'
1862      s++;
1863    }
1864    int wid = getdigits_int(&s, true, 0);
1865    if (wid && *s == '(') {
1866      ru_wid = wid;
1867    }
1868  }
1869  if (rulerformat) {
1870    comp_col();
1871  }
1872  return NULL;
1873}
1874
1875/// The 'tabline' option is changed.
1876const char *did_set_tabline(optset_T *args)
1877{
1878  return did_set_statustabline_rulerformat(args, false, false);
1879}
1880
1881/// The 'tagcase' option is changed.
1882const char *did_set_tagcase(optset_T *args)
1883{
1884  buf_T *buf = args->os_buf;
1885  int opt_flags = args->os_flags;
1886
1887  unsigned *flags;
1888  char *p;
1889
1890  if (opt_flags & OPT_LOCAL) {
1891    p = buf->b_p_tc;
1892    flags = &buf->b_tc_flags;
1893  } else {
1894    p = p_tc;
1895    flags = &tc_flags;
1896  }
1897
1898  if ((opt_flags & OPT_LOCAL) && *p == NUL) {
1899    // make the local value empty: use the global value
1900    *flags = 0;
1901  } else {
1902    const char *errmsg = opt_strings_flags(p, opt_tc_values, flags, false, args->os_errbuf);
1903    if (errmsg != NULL) {
1904      return errmsg;
1905    }
1906  }
1907  return NULL;
1908}
1909
1910/// The 'titlestring' or the 'iconstring' option is changed.
1911static const char *did_set_titleiconstring(optset_T *args, int flagval)
1912{
1913  char **varp = (char **)args->os_varp;
1914
1915  // NULL => statusline syntax
1916  if (vim_strchr(*varp, '%') && check_stl_option(*varp, NULL) == NULL) {
1917    stl_syntax |= flagval;
1918  } else {
1919    stl_syntax &= ~flagval;
1920  }
1921  did_set_title();
1922
1923  return NULL;
1924}
1925
1926/// The 'titlestring' option is changed.
1927const char *did_set_titlestring(optset_T *args)
1928{
1929  return did_set_titleiconstring(args, STL_IN_TITLE);
1930}
1931
1932/// The 'varsofttabstop' option is changed.
1933const char *did_set_varsofttabstop(optset_T *args)
1934{
1935  buf_T *buf = args->os_buf;
1936  char **varp = (char **)args->os_varp;
1937
1938  if (!(*varp)[0] || ((*varp)[0] == '0' && !(*varp)[1])) {
1939    XFREE_CLEAR(buf->b_p_vsts_array);
1940    return NULL;
1941  }
1942
1943  for (char *cp = *varp; *cp; cp++) {
1944    if (ascii_isdigit(*cp)) {
1945      continue;
1946    }
1947    if (*cp == ',' && cp > *varp && *(cp - 1) != ',') {
1948      continue;
1949    }
1950    return e_invarg;
1951  }
1952
1953  colnr_T *oldarray = buf->b_p_vsts_array;
1954  if (tabstop_set(*varp, &(buf->b_p_vsts_array))) {
1955    xfree(oldarray);
1956  } else {
1957    return e_invarg;
1958  }
1959  return NULL;
1960}
1961
1962/// The 'varstabstop' option is changed.
1963const char *did_set_vartabstop(optset_T *args)
1964{
1965  buf_T *buf = args->os_buf;
1966  win_T *win = args->os_win;
1967  char **varp = (char **)args->os_varp;
1968
1969  if (!(*varp)[0] || ((*varp)[0] == '0' && !(*varp)[1])) {
1970    XFREE_CLEAR(buf->b_p_vts_array);
1971    return NULL;
1972  }
1973
1974  for (char *cp = *varp; *cp; cp++) {
1975    if (ascii_isdigit(*cp)) {
1976      continue;
1977    }
1978    if (*cp == ',' && cp > *varp && *(cp - 1) != ',') {
1979      continue;
1980    }
1981    return e_invarg;
1982  }
1983
1984  colnr_T *oldarray = buf->b_p_vts_array;
1985  if (tabstop_set(*varp, &(buf->b_p_vts_array))) {
1986    xfree(oldarray);
1987    if (foldmethodIsIndent(win)) {
1988      foldUpdateAll(win);
1989    }
1990  } else {
1991    return e_invarg;
1992  }
1993  return NULL;
1994}
1995
1996/// The 'verbosefile' option is changed.
1997const char *did_set_verbosefile(optset_T *args)
1998{
1999  verbose_stop();
2000  if (*p_vfile != NUL && verbose_open() == FAIL) {
2001    return (char *)e_invarg;
2002  }
2003  return NULL;
2004}
2005
2006/// The 'virtualedit' option is changed.
2007const char *did_set_virtualedit(optset_T *args)
2008{
2009  win_T *win = args->os_win;
2010
2011  char *ve = p_ve;
2012  unsigned *flags = &ve_flags;
2013
2014  if (args->os_flags & OPT_LOCAL) {
2015    ve = win->w_p_ve;
2016    flags = &win->w_ve_flags;
2017  }
2018
2019  if ((args->os_flags & OPT_LOCAL) && *ve == NUL) {
2020    // make the local value empty: use the global value
2021    *flags = 0;
2022  } else {
2023    const char *errmsg = opt_strings_flags(ve, opt_ve_values, flags, true, args->os_errbuf);
2024    if (errmsg != NULL) {
2025      return errmsg;
2026    } else if (strcmp(ve, args->os_oldval.data.string.data) != 0) {
2027      // Recompute cursor position in case the new 've' setting
2028      // changes something.
2029      validate_virtcol(win);
2030      coladvance(win, win->w_virtcol);
2031    }
2032  }
2033  return NULL;
2034}
2035
2036/// Validate the 'whichwrap' option.
2037const char *validate_whichwrap(const optset_T *args)
2038{
2039  // Add ',' to the list flags because 'whichwrap' is a flag
2040  // list that is comma-separated.
2041  return check_option_listflag(args->os_newval.data.string.data, WW_ALL ",", args->os_errbuf);
2042}
2043
2044int expand_set_whichwrap(optexpand_T *args, int *numMatches, char ***matches)
2045{
2046  return expand_set_opt_listflag(args, WW_ALL, numMatches, matches);
2047}
2048
2049/// The 'wildmode' option is changed.
2050const char *did_set_wildmode(optset_T *args FUNC_ATTR_UNUSED)
2051{
2052  if (check_opt_wim() == FAIL) {
2053    return e_invarg;
2054  }
2055  return NULL;
2056}
2057
2058/// The 'winbar' option is changed.
2059const char *did_set_winbar(optset_T *args)
2060{
2061  return did_set_statustabline_rulerformat(args, false, false);
2062}
2063
2064/// Validate the 'winborder' or 'pumborder' option.
2065const char *validate_border(const optset_T *args)
2066{
2067  WinConfig fconfig = WIN_CONFIG_INIT;
2068  Error err = ERROR_INIT;
2069  bool ok = parse_winborder(&fconfig, args->os_newval.data.string.data, &err);
2070  api_clear_error(&err);
2071  return ok ? NULL : e_invarg;
2072}
2073
2074/// The 'winhighlight' option is changed.
2075const char *did_set_winhighlight(optset_T *args)
2076{
2077  win_T *win = args->os_win;
2078  char **varp = (char **)args->os_varp;
2079  if (!parse_winhl_opt(*varp, varp == &win->w_p_winhl ? win : NULL)) {
2080    return e_invarg;
2081  }
2082  return NULL;
2083}
2084
2085int expand_set_winhighlight(optexpand_T *args, int *numMatches, char ***matches)
2086{
2087  return expand_set_opt_generic(args, get_highlight_name, numMatches, matches);
2088}
2089
2090/// Format an error naming an item (at most 63 bytes) and listing its valid values.
2091/// Returns `errbuf->data`, or the generic `e_invarg` when no buffer is available.
2092static const char *opt_values_err(const CharBuf *errbuf, const char *fmt, const char *item,
2093                                  size_t itemlen, const char **values)
2094{
2095  if (errbuf == NULL) {
2096    return e_invarg;
2097  }
2098  char itembuf[64];
2099  xmemcpyz(itembuf, item, MIN(itemlen, sizeof(itembuf) - 1));
2100  int n = vim_snprintf(errbuf->data, errbuf->size, _(fmt), itembuf);
2101  for (int j = 0; values[j] != NULL && n > 0 && (size_t)n < errbuf->size; j++) {
2102    n += vim_snprintf(errbuf->data + n, errbuf->size - (size_t)n, "%s%s", j == 0 ? " " : ", ",
2103                      values[j]);
2104  }
2105  return errbuf->data;
2106}
2107
2108/// Handle an option that can be a range of string values.
2109/// Set a flag in "*flagp" for each string present.
2110///
2111/// @param val      new value
2112/// @param values   array of valid string values
2113/// @param list     when true: accept a list of values
2114/// @param errbuf   buffer for the error message (may be NULL, then a generic error is returned)
2115///
2116/// @return  NULL for a correct value, otherwise an error message. Empty is always OK.
2117static const char *opt_strings_flags(const char *val, const char **values, unsigned *flagp,
2118                                     bool list, const CharBuf *errbuf)
2119{
2120  unsigned new_flags = 0;
2121
2122  // If not list and val is empty, then force one iteration of the while loop
2123  bool iter_one = (*val == NUL) && !list;
2124
2125  while (*val || iter_one) {
2126    for (unsigned i = 0;; i++) {
2127      if (values[i] == NULL) {          // val not found in values[]
2128        return opt_values_err(errbuf, N_("E474: Invalid value '%s', expected one of:"),
2129                              val, strcspn(val, ","), values);
2130      }
2131
2132      size_t len = strlen(values[i]);
2133      if (strncmp(values[i], val, len) == 0
2134          && ((list && val[len] == ',') || val[len] == NUL)) {
2135        val += len + (val[len] == ',');
2136        assert(i < sizeof(new_flags) * 8);
2137        new_flags |= (1U << i);
2138        break;                  // check next item in val list
2139      }
2140    }
2141    if (iter_one) {
2142      break;
2143    }
2144  }
2145  if (flagp != NULL) {
2146    *flagp = new_flags;
2147  }
2148
2149  return NULL;
2150}
2151
2152/// Format a schema-validation error naming the offending key. Returns `errbuf->data`, or the generic
2153/// `e_invarg` when no buffer is available.
2154static const char *opt_schema_err(const CharBuf *errbuf, const char *fmt, const char *key,
2155                                  size_t keylen)
2156{
2157  if (errbuf == NULL) {
2158    return e_invarg;
2159  }
2160  char keybuf[64];
2161  xmemcpyz(keybuf, key, MIN(keylen, sizeof(keybuf) - 1));
2162  return opt_error(errbuf, fmt, keybuf);
2163}
2164
2165/// Validates a dict option against its schema (options.lua). On failure, writes a msg to `errbuf`.
2166///
2167/// @param val     The option value.
2168/// @param schema  NULL-terminated schema array (opt_<name>_schema).
2169/// @param errbuf  Error message (may be NULL, then a generic error is returned).
2170///
2171/// @return  NULL when valid, otherwise an (untranslated) error message.
2172const char *opt_strings_check(const char *val, const OptSchemaItem *schema, const CharBuf *errbuf)
2173  FUNC_ATTR_NONNULL_ARG(1, 2)
2174{
2175  const char *key, *v;
2176  size_t keylen, vlen;
2177  for (const char *p = val; option_next_keyval(&p, &key, &keylen, &v, &vlen);) {
2178    if (keylen == 0 && v == NULL) {
2179      continue;  // tolerate empty parts, e.g. "a,,b"
2180    }
2181    const OptSchemaItem *it = schema;
2182    while (it->name != NULL && !option_slice_eq(key, keylen, it->name)) {
2183      it++;
2184    }
2185    if (it->name == NULL) {
2186      return opt_schema_err(errbuf, N_("E474: Unknown item '%s'"), key, keylen);
2187    }
2188    switch (it->kind) {
2189    case kOptSchemaFlag:
2190      if (v != NULL) {
2191        return opt_schema_err(errbuf, N_("E474: '%s' does not take a value"), key, keylen);
2192      }
2193      break;
2194    case kOptSchemaNum:
2195    case kOptSchemaSNum: {
2196      // snum allows a leading '-'; both require at least one digit and nothing else.
2197      size_t i = (v != NULL && it->kind == kOptSchemaSNum && *v == '-') ? 1 : 0;
2198      bool ok = v != NULL && vlen > i;
2199      for (; ok && i < vlen; i++) {
2200        ok = ascii_isdigit((uint8_t)v[i]);
2201      }
2202      if (!ok) {
2203        return opt_schema_err(errbuf, N_("E474: '%s' requires a number"), key, keylen);
2204      }
2205      // The value must fit the `int` it is parsed into (opt_fill() uses getdigits_int()).
2206      char *end = (char *)v;
2207      intmax_t n;
2208      if (!try_getdigits(&end, &n) || n < INT_MIN || n > INT_MAX) {
2209        return opt_schema_err(errbuf, N_("E474: '%s' number is out of range"), key, keylen);
2210      }
2211      break;
2212    }
2213    case kOptSchemaEnum: {
2214      const char **ev = it->enum_values;
2215      while (v != NULL && *ev != NULL && !option_slice_eq(v, vlen, *ev)) {
2216        ev++;
2217      }
2218      if (v != NULL && *ev != NULL) {
2219        break;  // matched an enum value
2220      }
2221      return opt_values_err(errbuf, N_("E474: '%s' must be one of:"), key, keylen, it->enum_values);
2222    }
2223    case kOptSchemaStr:
2224      if (v == NULL) {
2225        return opt_schema_err(errbuf, N_("E474: '%s' requires a value"), key, keylen);
2226      }
2227      if (vlen >= 256) {  // This limit must match `keyset_str_max` (gen_options.lua).
2228        return opt_schema_err(errbuf, N_("E474: '%s' value is too long"), key, keylen);
2229      }
2230      break;
2231    }
2232  }
2233  return NULL;
2234}
2235
2236/// Parses a validated dict option into `out`. String-ish values live in fixed `char[]` fields (not
2237/// allocated), so the keyset owns nothing and needs no free.
2238///
2239/// @param value Option value in ":set"-string form.
2240/// @param get_field Perfect-hash fn.
2241/// @param out Caller-provided keyset storage (`OptKeyDict_…`).
2242void opt_fill(const char *value, FieldHashfn get_field, void *out)
2243  FUNC_ATTR_NONNULL_ALL
2244{
2245  const char *key, *v;
2246  size_t keylen, vlen;
2247  for (const char *p = value; option_next_keyval(&p, &key, &keylen, &v, &vlen);) {
2248    const KeySetLink *f = get_field(key, keylen);
2249    if (f == NULL) {
2250      continue;  // unknown key can't occur after validation
2251    }
2252    void *field = (char *)out + f->ptr_off;
2253    switch (f->type) {
2254    case kObjectTypeBoolean:
2255      *(Boolean *)field = true;  // a flag: present means true
2256      break;
2257    case kObjectTypeInteger: {
2258      char *end = (char *)v;
2259      *(Integer *)field = getdigits_int(&end, false, 0);
2260      break;
2261    }
2262    case kObjectTypeString:
2263      // A repeated key is "last wins" (overwritten). opt_strings_check() bounds the size.
2264      memcpy(field, v, vlen);
2265      ((char *)field)[vlen] = NUL;
2266      break;
2267    default:
2268      break;
2269    }
2270    ((OptKeySet *)out)->is_set_ |= (1ULL << (unsigned)f->opt_index);
2271  }
2272}
2273
2274/// Reify a dict-option value to a keyset (`OptKeyDict_…`). String values live in fixed char[]
2275/// fields (not allocated), so the keyset owns nothing and needs no free.
2276///
2277/// @param value   Option value in ":set"-string form.
2278/// @param opt_idx Option idx.
2279/// @param keyset  Caller-provided storage, or NULL to use shared static storage.
2280///                Shared storage is overwritten by the next call using NULL.
2281///                Cleared first; a NULL or empty value yields an all-unset keyset.
2282/// @return The keyset (for convenient assignment).
2283void *opt_keyset(const char *value, OptIndex opt_idx, void *keyset)
2284{
2285  static OptKeyDict shared;
2286  if (keyset == NULL) {
2287    keyset = &shared;
2288  }
2289  const OptDictSchema *si = opt_dict_schema(opt_idx);
2290  memset(keyset, 0, si->size);
2291  if (value != NULL) {
2292    opt_fill(value, si->get_field, keyset);
2293  }
2294  return keyset;
2295}
2296
2297/// @return  OK if "p" is a valid fileformat name, FAIL otherwise.
2298int check_ff_value(char *p)
2299{
2300  return opt_strings_flags(p, opt_ff_values, NULL, false, NULL) == NULL ? OK : FAIL;
2301}
2302
2303static const char e_conflicts_with_value_of_listchars[]
2304  = N_("E834: Conflicts with value of 'listchars'");
2305static const char e_conflicts_with_value_of_fillchars[]
2306  = N_("E835: Conflicts with value of 'fillchars'");
2307
2308/// Calls mb_cptr2char_adv(p) and returns the character.
2309/// If "p" starts with "\x", "\u" or "\U" the hex or unicode value is used.
2310/// Returns 0 for invalid hex or invalid UTF-8 byte.
2311static schar_T get_encoded_char_adv(const char **p)
2312{
2313  const char *s = *p;
2314
2315  if (s[0] == '\\' && (s[1] == 'x' || s[1] == 'u' || s[1] == 'U')) {
2316    int64_t num = 0;
2317    for (int bytes = s[1] == 'x' ? 1 : s[1] == 'u' ? 2 : 4; bytes > 0; bytes--) {
2318      *p += 2;
2319      int n = hexhex2nr(*p);
2320      if (n < 0) {
2321        return 0;
2322      }
2323      num = num * 256 + n;
2324    }
2325    *p += 2;
2326    return (char2cells((int)num) > 1) ? 0 : schar_from_char((int)num);
2327  }
2328
2329  int clen = utfc_ptr2len(s);
2330  int firstc;
2331  schar_T c = utfc_ptr2schar(s, &firstc);
2332  *p += clen;
2333  // Invalid UTF-8 byte or doublewidth not allowed
2334  return ((clen == 1 && firstc > 127) || char2cells(firstc) > 1) ? 0 : c;
2335}
2336
2337struct chars_tab {
2338  schar_T *cp;           ///< char value
2339  String name;           ///< char id
2340  const char *def;       ///< default value
2341  const char *fallback;  ///< default value when "def" isn't single-width
2342};
2343
2344#define CHARSTAB_ENTRY(cp, name, def, fallback) \
2345  { (cp), STATIC_CSTR_STRING_INIT(name), def, fallback }
2346
2347static fcs_chars_T fcs_chars;
2348static lcs_chars_T lcs_chars;
2349
2350// Generated from options.lua:
2351// - 'fillchars' => fcs_tab[]
2352// - 'listchars' => lcs_tab[]
2353#include "options_chartab.generated.h"
2354
2355#undef CHARSTAB_ENTRY
2356
2357/// Handle setting 'listchars' or 'fillchars'.
2358/// Assume monocell characters
2359///
2360/// @param value      points to either the global or the window-local value.
2361/// @param what       kListchars or kFillchars
2362/// @param apply      if false, validate the supplied value without resolving the local default
2363///                   or changing derived state.
2364/// @param errbuf     buffer for error message, can be NULL if it won't be used.
2365///
2366/// @return error message, NULL if it's OK.
2367const char *set_chars_option(win_T *wp, const char *value, CharsOption what, bool apply,
2368                             const CharBuf *errbuf)
2369{
2370  const char *last_multispace = NULL;   // Last occurrence of "multispace:"
2371  const char *last_lmultispace = NULL;  // Last occurrence of "leadmultispace:"
2372  int multispace_len = 0;           // Length of lcs-multispace string
2373  int lead_multispace_len = 0;      // Length of lcs-leadmultispace string
2374
2375  const struct chars_tab *tab;
2376  int entries;
2377  if (what == kListchars) {
2378    tab = lcs_tab;
2379    entries = ARRAY_SIZE(lcs_tab);
2380    if (apply && wp->w_p_lcs[0] == NUL) {
2381      value = p_lcs;  // local value is empty, use the global value
2382    }
2383  } else {
2384    tab = fcs_tab;
2385    entries = ARRAY_SIZE(fcs_tab);
2386    if (apply && wp->w_p_fcs[0] == NUL) {
2387      value = p_fcs;  // local value is empty, use the global value
2388    }
2389  }
2390
2391  // first round: check for valid value, second round: assign values
2392  for (int round = 0; round <= (apply ? 1 : 0); round++) {
2393    bool has_tab = false, has_leadtab = false;
2394
2395    if (round > 0) {
2396      // After checking that the value is valid: set defaults
2397      for (int i = 0; i < entries; i++) {
2398        if (tab[i].cp != NULL) {
2399          // XXX: Characters taking 2 columns is forbidden (TUI limitation?).
2400          // Set old defaults in this case.
2401          *(tab[i].cp) = schar_from_str((tab[i].def && ptr2cells(tab[i].def) == 1)
2402                                        ? tab[i].def : tab[i].fallback);
2403        }
2404      }
2405
2406      if (what == kListchars) {
2407        lcs_chars.tab1 = NUL;
2408        lcs_chars.tab3 = NUL;
2409        lcs_chars.leadtab1 = NUL;
2410        lcs_chars.leadtab3 = NUL;
2411
2412        if (multispace_len > 0) {
2413          lcs_chars.multispace = xmalloc(((size_t)multispace_len + 1) * sizeof(schar_T));
2414          lcs_chars.multispace[multispace_len] = NUL;
2415        } else {
2416          lcs_chars.multispace = NULL;
2417        }
2418
2419        if (lead_multispace_len > 0) {
2420          lcs_chars.leadmultispace = xmalloc(((size_t)lead_multispace_len + 1) * sizeof(schar_T));
2421          lcs_chars.leadmultispace[lead_multispace_len] = NUL;
2422        } else {
2423          lcs_chars.leadmultispace = NULL;
2424        }
2425      }
2426    }
2427
2428    const char *p = value;
2429    while (*p) {
2430      int i;
2431      for (i = 0; i < entries; i++) {
2432        if (!(strncmp(p, tab[i].name.data,
2433                      tab[i].name.size) == 0 && p[tab[i].name.size] == ':')) {
2434          continue;
2435        }
2436
2437        const char *s = p + tab[i].name.size + 1;
2438
2439        if (what == kListchars && strcmp(tab[i].name.data, "multispace") == 0) {
2440          if (round == 0) {
2441            // Get length of lcs-multispace string in the first round
2442            last_multispace = p;
2443            multispace_len = 0;
2444            while (*s != NUL && *s != ',') {
2445              schar_T c1 = get_encoded_char_adv(&s);
2446              if (c1 == 0) {
2447                return opt_error(errbuf, e_wrong_character_width_for_field_str, tab[i].name.data);
2448              }
2449              multispace_len++;
2450            }
2451            if (multispace_len == 0) {
2452              // lcs-multispace cannot be an empty string
2453              return opt_error(errbuf, e_wrong_number_of_characters_for_field_str,
2454                               tab[i].name.data);
2455            }
2456          } else {
2457            int multispace_pos = 0;
2458            while (*s != NUL && *s != ',') {
2459              schar_T c1 = get_encoded_char_adv(&s);
2460              if (p == last_multispace) {
2461                lcs_chars.multispace[multispace_pos++] = c1;
2462              }
2463            }
2464          }
2465          p = s;
2466          break;
2467        }
2468
2469        if (what == kListchars && strcmp(tab[i].name.data, "leadmultispace") == 0) {
2470          if (round == 0) {
2471            // Get length of lcs-leadmultispace string in first round
2472            last_lmultispace = p;
2473            lead_multispace_len = 0;
2474            while (*s != NUL && *s != ',') {
2475              schar_T c1 = get_encoded_char_adv(&s);
2476              if (c1 == 0) {
2477                return opt_error(errbuf, e_wrong_character_width_for_field_str, tab[i].name.data);
2478              }
2479              lead_multispace_len++;
2480            }
2481            if (lead_multispace_len == 0) {
2482              // lcs-leadmultispace cannot be an empty string
2483              return opt_error(errbuf, e_wrong_number_of_characters_for_field_str,
2484                               tab[i].name.data);
2485            }
2486          } else {
2487            int multispace_pos = 0;
2488            while (*s != NUL && *s != ',') {
2489              schar_T c1 = get_encoded_char_adv(&s);
2490              if (p == last_lmultispace) {
2491                lcs_chars.leadmultispace[multispace_pos++] = c1;
2492              }
2493            }
2494          }
2495          p = s;
2496          break;
2497        }
2498
2499        if (*s == NUL) {
2500          return opt_error(errbuf, e_wrong_number_of_characters_for_field_str, tab[i].name.data);
2501        }
2502        schar_T c1 = get_encoded_char_adv(&s);
2503        if (c1 == 0) {
2504          return opt_error(errbuf, e_wrong_character_width_for_field_str, tab[i].name.data);
2505        }
2506        schar_T c2 = 0;
2507        schar_T c3 = 0;
2508        if (tab[i].cp == &lcs_chars.tab2 || tab[i].cp == &lcs_chars.leadtab2) {
2509          if (*s == NUL) {
2510            return opt_error(errbuf, e_wrong_number_of_characters_for_field_str, tab[i].name.data);
2511          }
2512          c2 = get_encoded_char_adv(&s);
2513          if (c2 == 0) {
2514            return opt_error(errbuf, e_wrong_character_width_for_field_str, tab[i].name.data);
2515          }
2516          if (!(*s == ',' || *s == NUL)) {
2517            c3 = get_encoded_char_adv(&s);
2518            if (c3 == 0) {
2519              return opt_error(errbuf, e_wrong_character_width_for_field_str, tab[i].name.data);
2520            }
2521          }
2522          if (tab[i].cp == &lcs_chars.tab2) {
2523            has_tab = true;
2524          } else {  // tab[i].cp == &lcs_chars.leadtab2
2525            has_leadtab = true;
2526          }
2527        }
2528
2529        if (*s == ',' || *s == NUL) {
2530          if (round > 0) {
2531            if (tab[i].cp == &lcs_chars.tab2) {
2532              lcs_chars.tab1 = c1;
2533              lcs_chars.tab2 = c2;
2534              lcs_chars.tab3 = c3;
2535            } else if (tab[i].cp == &lcs_chars.leadtab2) {
2536              lcs_chars.leadtab1 = c1;
2537              lcs_chars.leadtab2 = c2;
2538              lcs_chars.leadtab3 = c3;
2539            } else if (tab[i].cp != NULL) {
2540              *(tab[i].cp) = c1;
2541            }
2542          }
2543          p = s;
2544          break;
2545        } else {
2546          return opt_error(errbuf, e_wrong_number_of_characters_for_field_str, tab[i].name.data);
2547        }
2548      }
2549
2550      if (i == entries) {
2551        return e_invarg;
2552      }
2553
2554      if (*p == ',') {
2555        p++;
2556      }
2557    }
2558
2559    if (what == kListchars && has_leadtab && !has_tab) {
2560      return e_leadtab_requires_tab;
2561    }
2562  }
2563
2564  if (apply) {
2565    if (what == kListchars) {
2566      xfree(wp->w_p_lcs_chars.multispace);
2567      xfree(wp->w_p_lcs_chars.leadmultispace);
2568      wp->w_p_lcs_chars = lcs_chars;
2569    } else {
2570      wp->w_p_fcs_chars = fcs_chars;
2571    }
2572  }
2573
2574  return NULL;          // no error
2575}
2576
2577/// Function given to ExpandGeneric() to obtain possible arguments of the
2578/// 'fillchars' option.
2579char *get_fillchars_name(expand_T *xp FUNC_ATTR_UNUSED, int idx)
2580{
2581  if (idx < 0 || idx >= (int)ARRAY_SIZE(fcs_tab)) {
2582    return NULL;
2583  }
2584
2585  return fcs_tab[idx].name.data;
2586}
2587
2588/// Function given to ExpandGeneric() to obtain possible arguments of the
2589/// 'listchars' option.
2590char *get_listchars_name(expand_T *xp FUNC_ATTR_UNUSED, int idx)
2591{
2592  if (idx < 0 || idx >= (int)ARRAY_SIZE(lcs_tab)) {
2593    return NULL;
2594  }
2595
2596  return lcs_tab[idx].name.data;
2597}
2598
2599/// Check all global and local values of 'listchars' and 'fillchars'.
2600/// May set different defaults in case character widths change.
2601///
2602/// @return  an untranslated error message if any of them is invalid, NULL otherwise.
2603const char *check_chars_options(void)
2604{
2605  if (set_chars_option(curwin, p_lcs, kListchars, false, NULL) != NULL) {
2606    return e_conflicts_with_value_of_listchars;
2607  }
2608  if (set_chars_option(curwin, p_fcs, kFillchars, false, NULL) != NULL) {
2609    return e_conflicts_with_value_of_fillchars;
2610  }
2611  FOR_ALL_TAB_WINDOWS(tp, wp) {
2612    if (set_chars_option(wp, wp->w_p_lcs, kListchars, true, NULL) != NULL) {
2613      return e_conflicts_with_value_of_listchars;
2614    }
2615    if (set_chars_option(wp, wp->w_p_fcs, kFillchars, true, NULL) != NULL) {
2616      return e_conflicts_with_value_of_fillchars;
2617    }
2618  }
2619  return NULL;
2620}
2621
2622const char *validate_previewpopup(const optset_T *args)
2623{
2624  WinConfig fconfig = WIN_CONFIG_INIT;
2625  if (!win_previewpopup_config(args->os_newval.data.string.data, &fconfig)) {
2626    return e_invarg;
2627  }
2628  return NULL;
2629}
2630
2631int expand_set_popupoption(optexpand_T *args, int *numMatches, char ***matches)
2632{
2633  expand_T *xp = args->oe_xp;
2634
2635  if (xp->xp_pattern > args->oe_set_arg && *(xp->xp_pattern - 1) == ':') {
2636    if (completing_value_for_subopt(args, "border")) {
2637      return expand_set_opt_string(args, opt_pvp_border_values,
2638                                   ARRAY_SIZE(opt_pvp_border_values) - 1, numMatches, matches);
2639    }
2640    return FAIL;  // "height:"/"width:" = number, nothing to complete.
2641  }
2642
2643  return expand_set_opt_string(args, opt_pvp_values, ARRAY_SIZE(opt_pvp_values) - 1,
2644                               numMatches, matches);
2645}