robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
16.6 KiB499 linesraw
1#include <assert.h>
2#include <stdbool.h>
3#include <string.h>
4
5#include "nvim/api/keysets_defs.h"
6#include "nvim/api/options.h"
7#include "nvim/api/private/defs.h"
8#include "nvim/api/private/dispatch.h"
9#include "nvim/api/private/helpers.h"
10#include "nvim/api/private/validate.h"
11#include "nvim/autocmd.h"
12#include "nvim/autocmd_defs.h"
13#include "nvim/buffer.h"
14#include "nvim/buffer_defs.h"
15#include "nvim/context.h"
16#include "nvim/globals.h"
17#include "nvim/lua/executor.h"
18#include "nvim/memline.h"
19#include "nvim/memory.h"
20#include "nvim/memory_defs.h"
21#include "nvim/option.h"
22#include "nvim/option_defs.h"
23#include "nvim/option_vars.h"
24#include "nvim/strings.h"
25#include "nvim/types_defs.h"
26#include "nvim/vim_defs.h"
27#include "nvim/window.h"
28
29#include "api/options.c.generated.h"
30
31static int validate_option_value_args(Dict(option) *opts, char *name, bool allow_tab,
32                                      OptIndex *opt_idxp, int *opt_flags, OptScope *scope,
33                                      void **from, char **filetype, set_op_T *operation,
34                                      bool *dry_run, Error *err)
35{
36#define HAS_KEY_X(d, v) HAS_KEY(d, option, v)
37  // Validate incompatible argument combinations first, then resolve handles and scope.
38  VALIDATE_CON(!HAS_KEY_X(opts, filetype)
39               || (!HAS_KEY_X(opts, scope) && !HAS_KEY_X(opts, buf)
40                   && !HAS_KEY_X(opts, win) && !HAS_KEY_X(opts, tab)),
41               "filetype", "'scope', 'buf', 'win' or 'tab'", {
42    return FAIL;
43  });
44
45  VALIDATE_CON(!HAS_KEY_X(opts, tab) || allow_tab, "tab", "this function", {
46    return FAIL;
47  });
48
49  VALIDATE_CON(!HAS_KEY_X(opts, tab)
50               || (!HAS_KEY_X(opts, win) && !HAS_KEY_X(opts, buf)
51                   && !HAS_KEY_X(opts, filetype) && !HAS_KEY_X(opts, scope)),
52               "tab", "'win', 'buf', 'filetype' or 'scope'", {
53    return FAIL;
54  });
55
56  VALIDATE_CON(!(HAS_KEY_X(opts, win) && HAS_KEY_X(opts, buf)), "buf", "win", {
57    return FAIL;
58  });
59
60  if (HAS_KEY_X(opts, scope)) {
61    if (!strcmp(opts->scope.data, "local")) {
62      *opt_flags = OPT_LOCAL;
63    } else if (!strcmp(opts->scope.data, "global")) {
64      *opt_flags = OPT_GLOBAL;
65    } else {
66      VALIDATE_EXP(false, "scope", "'local' or 'global'", NULL, {
67        return FAIL;
68      });
69    }
70  }
71
72  *scope = kOptScopeGlobal;
73
74  if (filetype != NULL && HAS_KEY_X(opts, filetype)) {
75    *filetype = opts->filetype.data;
76  }
77
78  if (HAS_KEY_X(opts, win)) {
79    *scope = kOptScopeWin;
80    *from = find_window_by_handle(opts->win, err);
81    if (ERROR_SET(err)) {
82      return FAIL;
83    }
84  }
85
86  if (HAS_KEY_X(opts, buf)) {
87    VALIDATE_CON(!(HAS_KEY_X(opts, scope) && *opt_flags == OPT_GLOBAL), "buf", "global scope", {
88      return FAIL;
89    });
90    *opt_flags = OPT_LOCAL;
91    *scope = kOptScopeBuf;
92    *from = find_buffer_by_handle(opts->buf, err);
93    if (ERROR_SET(err)) {
94      return FAIL;
95    }
96  }
97
98  if (HAS_KEY_X(opts, tab)) {
99    *scope = kOptScopeTab;
100    *from = find_tab_by_handle(opts->tab, err);
101    if (ERROR_SET(err)) {
102      return FAIL;
103    }
104  }
105
106  *opt_idxp = find_option(name);
107  if (*opt_idxp == kOptInvalid) {
108    // unknown option
109    api_set_error(err, kErrorTypeValidation, "Unknown option '%s'", name);
110    return FAIL;
111  }
112
113  if (operation != NULL && HAS_KEY_X(opts, operation)) {
114    if (strequal(opts->operation.data, "set")) {
115      *operation = OP_NONE;
116    } else if (strequal(opts->operation.data, "append")) {
117      *operation = OP_ADDING;
118    } else if (strequal(opts->operation.data, "prepend")) {
119      *operation = OP_PREPENDING;
120    } else if (strequal(opts->operation.data, "remove")) {
121      *operation = OP_REMOVING;
122    } else {
123      VALIDATE_EXP(false, "operation", "'set', 'append', 'prepend', or 'remove'", NULL, {
124        return FAIL;
125      });
126    }
127
128    VALIDATE_CON(*operation == OP_NONE || option_has_type(*opt_idxp, kObjectTypeString)
129                 || option_has_type(*opt_idxp, kObjectTypeInteger),
130                 opts->operation.data,
131                 "boolean options", {
132      return FAIL;
133    });
134  }
135
136  if (dry_run != NULL && HAS_KEY_X(opts, dry_run)) {
137    *dry_run = opts->dry_run;
138  }
139
140  // Reject keys whose scope the option doesn't support.
141  VALIDATE_CON(!HAS_KEY_X(opts, tab) || option_has_scope(*opt_idxp, kOptScopeTab),
142               "tab", name, { return FAIL; });
143
144  // If 'buf' or 'win' is passed, make sure the option supports it.
145  if (*scope == kOptScopeBuf || *scope == kOptScopeWin) {
146    if (!option_has_scope(*opt_idxp, *scope)) {
147      char *tgt = *scope == kOptScopeBuf ? "buf" : "win";
148      char *global = option_has_scope(*opt_idxp, kOptScopeGlobal) ? "global " : "";
149      char *req = option_has_scope(*opt_idxp, kOptScopeBuf)
150                  ? "buffer-local "
151                  : (option_has_scope(*opt_idxp, kOptScopeWin) ? "window-local " : "");
152
153      api_set_error(err, kErrorTypeValidation, "'%s' cannot be passed for %s%soption '%s'",
154                    tgt, global, req, name);
155      return FAIL;
156    }
157  }
158
159  return ERROR_SET(err) ? FAIL : OK;
160#undef HAS_KEY_X
161}
162
163/// Create a dummy buffer and run the FileType autocmd on it.
164static buf_T *do_ft_buf(const char *filetype, CtxSwitch *aco, Error *err)
165  FUNC_ATTR_NONNULL_ARG(2, 3)
166{
167  if (filetype == NULL) {
168    return NULL;
169  }
170
171  // Allocate a buffer without putting it in the buffer list.
172  buf_T *ftbuf = buflist_new(NULL, NULL, 1, BLN_DUMMY);
173  if (ftbuf == NULL) {
174    api_set_error(err, kErrorTypeException, "Could not create internal buffer");
175    return NULL;
176  }
177
178  // Open a memline for use by autocommands.
179  if (ml_open(ftbuf) == FAIL) {
180    api_set_error(err, kErrorTypeException, "Could not load internal buffer");
181    return ftbuf;
182  }
183
184  bufref_T bufref;
185  set_bufref(&bufref, ftbuf);
186
187  // Set curwin/curbuf to buf and save a few things.
188  ctx_switch(aco, NULL, NULL, ftbuf, 0);
189
190  set_option_direct(kOptBufhidden, STATIC_CSTR_AS_OBJ("hide"), OPT_LOCAL, SID_NONE);
191  set_option_direct(kOptBuftype, STATIC_CSTR_AS_OBJ("nofile"), OPT_LOCAL, SID_NONE);
192  assert(ftbuf->b_ml.ml_mfp->mf_fd < 0);  // ml_open() should not have opened swapfile already
193  ftbuf->b_p_swf = false;
194  ftbuf->b_p_ml = false;
195  ftbuf->b_p_ft = xstrdup(filetype);
196
197  if (!has_event(EVENT_FILETYPE)) {
198    return ftbuf;  // Nothing more to do.
199  }
200
201  bool did_au_ft = false;
202  TRY_WRAP(err, {
203    did_au_ft = do_filetype_autocmd(ftbuf, true);
204  });
205
206  if (!bufref_valid(&bufref)) {
207    if (!ERROR_SET(err)) {
208      api_set_error(err, kErrorTypeException, "Internal buffer was deleted");
209    }
210    return NULL;
211  }
212
213  if (!did_au_ft && !ERROR_SET(err)) {
214    api_set_error(err, kErrorTypeException, "Could not execute FileType autocommands");
215  }
216  return ftbuf;
217}
218
219static void wipe_ft_buf(buf_T *buf)
220  FUNC_ATTR_NONNULL_ALL
221{
222  block_autocmds();
223
224  bufref_T bufref;
225  set_bufref(&bufref, buf);
226
227  close_windows(buf, false);
228  // Autocommands are blocked, but 'bufhidden' may have wiped it already.
229  // Also can't wipe if the buffer is somehow still in a window or current.
230  if (bufref_valid(&bufref) && buf != curbuf && buf->b_nwindows == 0) {
231    wipe_buffer(buf, false);
232  }
233  if (bufref_valid(&bufref)) {
234    buf->b_flags &= ~BF_DUMMY;  // Couldn't wipe; keep it instead.
235  }
236
237  unblock_autocmds();
238}
239
240/// Gets the value of an option. The behavior of this function matches that of
241/// |:set|: the local value of an option is returned if it exists; otherwise,
242/// the global value is returned. Local values always correspond to the current
243/// buffer or window, unless "buf" or "win" is set in {opts}.
244///
245/// @param name      Option name
246/// @param opts      Optional parameters
247///                  - buf: Buffer number. Used for getting buffer local options.
248///                         Implies {scope} is "local".
249///                  - filetype: |filetype|. Used to get the default option for a
250///                    specific filetype. Cannot be used with any other option.
251///                    Note: this will trigger |ftplugin| and all |FileType|
252///                    autocommands for the corresponding filetype.
253///                  - scope: One of "global" or "local". Analogous to
254///                  |:setglobal| and |:setlocal|, respectively.
255///                  - tab: |tab-ID| for tab-local options. Currently only
256///                    supports "cmdheight". Tabpage `0` means the current tabpage.
257///                  - win: |window-ID|. Used for getting window local options.
258/// @param[out] err  Error details, if any
259/// @return          Option value
260Object nvim_get_option_value(String name, Dict(option) *opts, Error *err)
261  FUNC_API_SINCE(9) FUNC_API_RET_ALLOC
262{
263  OptIndex opt_idx = 0;
264  int opt_flags = 0;
265  OptScope scope = kOptScopeGlobal;
266  void *from = NULL;
267  char *filetype = NULL;
268
269  if (!validate_option_value_args(opts, name.data, true, &opt_idx, &opt_flags, &scope, &from,
270                                  &filetype, NULL, NULL, err)) {
271    return (Object)OBJECT_INIT;
272  }
273
274  CtxSwitch aco = { 0 };
275
276  buf_T *ftbuf = do_ft_buf(filetype, &aco, err);
277  if (ERROR_SET(err)) {
278    // Restore curwin/curbuf and a few other things.
279    ctx_restore(&aco);
280    if (ftbuf != NULL) {
281      wipe_ft_buf(ftbuf);
282    }
283    return (Object)OBJECT_INIT;
284  }
285
286  if (ftbuf != NULL) {
287    assert(!from);
288    from = ftbuf;
289  }
290
291  Object value = get_option_value_for(opt_idx, opt_flags, scope, from, err);
292
293  // Restore curwin/curbuf and a few other things.
294  ctx_restore(&aco);
295  if (ftbuf != NULL) {
296    wipe_ft_buf(ftbuf);
297  }
298
299  if (ERROR_SET(err)) {
300    api_free_object(value);
301    return (Object)OBJECT_INIT;
302  }
303
304  return value;
305}
306
307/// Sets the value of an option. The behavior of this function matches that of
308/// |:set|: for global-local options, both the global and local value are set
309/// unless otherwise specified with {scope}.
310///
311/// Note the options {win} and {buf} cannot be used together.
312///
313/// @param name      Option name
314/// @param value     New option value
315/// @param opts      Optional parameters
316///                  - buf: Buffer number. Used for setting buffer local option.
317///                  - dry_run: (`boolean?`, default: false) If true, validates the
318///                    option value without setting it.
319///                  - operation: One of "set", "append", "prepend", or "remove".
320///                    Corresponds to |:set=|, |:set+=|, |:set^=|, and |:set-=|.
321///                    Default is "set".
322///                  - scope: One of "global" or "local". Analogous to
323///                  |:setglobal| and |:setlocal|, respectively.
324///                  - tab: |tab-ID| for tab-local options (currently only 'cmdheight'). Tabpage 0
325///                    means the current tabpage. If a non-current tab is given, the value will take
326///                    effect when it is switched-to.
327///                  - win: |window-ID|. Used for setting window local option.
328/// @param[out] err  Error details, if any
329/// @return          Option value
330Object nvim_set_option_value(uint64_t channel_id, String name, Object value, Dict(option) *opts,
331                             Arena *arena, Error *err)
332  FUNC_API_SINCE(9)
333{
334  OptIndex opt_idx = 0;
335  int opt_flags = 0;
336  OptScope scope = kOptScopeGlobal;
337  set_op_T operation = OP_NONE;
338  void *to = NULL;
339  bool dry_run = false;
340  if (!validate_option_value_args(opts, name.data, true, &opt_idx, &opt_flags, &scope, &to, NULL,
341                                  &operation, &dry_run, err)) {
342    return NIL;
343  }
344
345  // If:
346  // - window id is provided
347  // - scope is not provided
348  // - option is global or local to window (global-local)
349  //
350  // Then force scope to local since we don't want to change the global option
351  if (scope == kOptScopeWin && opt_flags == 0) {
352    if (option_has_scope(opt_idx, kOptScopeGlobal)) {
353      opt_flags = OPT_LOCAL;
354    }
355  }
356
357  // Convert the incoming value into an Object.
358  bool error = false;
359  Object optval_right = optval_from_obj(opt_idx, value, operation, &error);
360
361  VALIDATE_EXP(!error, name.data, "a valid type", api_typename(value.type), {
362    return NIL;
363  });
364
365  Object merged_val = NIL;
366  const char *errmsg = NULL;
367  vimoption_T *option = get_option(opt_idx);
368
369  // Need to use varp specific to buf/win to ensure that merges are handled
370  // correctly when the supplied buf/win are different than curbuf/curwin.
371  buf_T *buf = scope == kOptScopeBuf ? to : curbuf;
372  win_T *win = scope == kOptScopeWin ? to : curwin;
373  void *varp = get_varp_from(option, buf, win);
374  char *argp = NULL;
375
376  switch (optval_right.type) {
377  case kObjectTypeUnset:
378  case kObjectTypeNil:
379    break;
380  case kObjectTypeString: {
381    char *optval_escaped = escape_option_str_cmdline(optval_right.data.string.data);
382    // We need a leading equal sign because get_option_newval is used for
383    // cmdline stuff and expects an =
384    argp = arena_printf(arena, "=%s", optval_escaped).data;
385    XFREE_CLEAR(optval_escaped);
386    break;
387  }
388  case kObjectTypeInteger:
389    argp = arena_printf(arena, "=%" PRId64, optval_right.data.integer).data;
390    break;
391  case kObjectTypeBoolean:
392    merged_val = optval_right;
393    break;
394  case kObjectTypeLuaRef:
395    // Callback option: no ":set"-style merge; take an independent ref for the set below.
396    merged_val = copy_object(optval_right, NULL);
397    break;
398  default:
399    abort();
400  }
401
402  optval_free(optval_right);
403
404  if (optval_right.type == kObjectTypeInteger || optval_right.type == kObjectTypeString) {
405    Object oldval = optval_own(opt_idx, opt_from_varp(opt_idx, varp));
406    merged_val = get_option_newval(opt_idx, opt_flags, PREFIX_NONE, &argp, 0, operation,
407                                   varp, &oldval, &errmsg);
408    optval_free(oldval);
409    VALIDATE(errmsg == NULL, "%s", errmsg, {
410      return NIL;
411    });
412  }
413
414  if (dry_run) {
415    const CharBuf errbuf = { (char[IOSIZE]){ 0 }, IOSIZE };
416    errmsg = validate_option_value(opt_idx, &merged_val, opt_flags, buf, win, &errbuf);
417    if (errmsg != NULL) {
418      api_set_error(err, kErrorTypeException, "%s", errmsg);
419      optval_free(merged_val);
420      return NIL;
421    }
422  } else {
423    WITH_SCRIPT_CONTEXT(channel_id, {
424      set_option_value_for(opt_idx, merged_val, opt_flags, scope, to, operation == OP_NONE, err);
425    });
426  }
427
428  // Return the value in its structured (list/map/set) form.
429  Object rv = optval_to_obj(opt_idx, merged_val, arena);
430  optval_free(merged_val);
431  return rv;
432}
433
434/// Gets the option information for all options.
435///
436/// The dict has the full option names as keys and option metadata dicts as detailed at
437/// |nvim_get_option_info2()|.
438///
439/// @see |nvim_get_commands()|
440///
441/// @return dict of all options
442Dict nvim_get_all_options_info(Arena *arena, Error *err)
443  FUNC_API_SINCE(7)
444{
445  return get_all_options_info(arena);
446}
447
448/// Gets the option information for one option from arbitrary buffer or window
449///
450/// Resulting dict has keys:
451/// - name: Name of the option (like 'filetype')
452/// - shortname: Shortened name of the option (like 'ft')
453/// - type: type of option ("string", "number" or "boolean")
454/// - default: The default value for the option
455/// - was_set: Whether the option was set.
456///
457/// - last_set_sid: Last set script id (if any)
458/// - last_set_linenr: line number where option was set
459/// - last_set_chan: Channel where option was set (0 for local)
460///
461/// - scope: one of "global", "win", "buf", or "tab"
462/// - global_local: whether win or buf option has a global value
463///
464/// - commalist: List of comma separated values
465/// - flaglist: List of single char flags
466///
467/// When {scope} is not provided, the last set information applies to the local
468/// value in the current buffer or window if it is available, otherwise the
469/// global value information is returned. This behavior can be disabled by
470/// explicitly specifying {scope} in the {opts} table.
471///
472/// @param name      Option name
473/// @param opts      Optional parameters
474///                  - buf: Buffer number. Used for getting buffer local options.
475///                         Implies {scope} is "local".
476///                  - scope: One of "global" or "local". Analogous to
477///                  |:setglobal| and |:setlocal|, respectively.
478///                  - win: |window-ID|. Used for getting window local options.
479/// @param[out] err Error details, if any
480/// @return         Option Information
481DictAs(get_option_info) nvim_get_option_info2(String name, Dict(option) *opts, Arena *arena,
482                                              Error *err)
483  FUNC_API_SINCE(11)
484{
485  OptIndex opt_idx = 0;
486  int opt_flags = 0;
487  OptScope scope = kOptScopeGlobal;
488  void *from = NULL;
489  // TODO(justinmk): support tab-local option.
490  if (!validate_option_value_args(opts, name.data, false, &opt_idx, &opt_flags, &scope, &from, NULL,
491                                  NULL, NULL, err)) {
492    return (Dict)ARRAY_DICT_INIT;
493  }
494
495  buf_T *buf = (scope == kOptScopeBuf) ? (buf_T *)from : curbuf;
496  win_T *win = (scope == kOptScopeWin) ? (win_T *)from : curwin;
497
498  return get_option_info(name, opt_flags, buf, win, arena, err);
499}