aboutsummaryrefslogtreecommitdiff
path: root/src/nvim/api/options.c
blob: 09ca61654d0bd0774635f8ed5deb9300eb185fb2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
#include <assert.h>
#include <stdbool.h>
#include <string.h>

#include "nvim/api/keysets_defs.h"
#include "nvim/api/options.h"
#include "nvim/api/private/defs.h"
#include "nvim/api/private/dispatch.h"
#include "nvim/api/private/helpers.h"
#include "nvim/api/private/validate.h"
#include "nvim/autocmd.h"
#include "nvim/autocmd_defs.h"
#include "nvim/buffer.h"
#include "nvim/buffer_defs.h"
#include "nvim/context.h"
#include "nvim/globals.h"
#include "nvim/lua/executor.h"
#include "nvim/memline.h"
#include "nvim/memory.h"
#include "nvim/memory_defs.h"
#include "nvim/option.h"
#include "nvim/option_defs.h"
#include "nvim/option_vars.h"
#include "nvim/strings.h"
#include "nvim/types_defs.h"
#include "nvim/vim_defs.h"
#include "nvim/window.h"

#include "api/options.c.generated.h"

static int validate_option_value_args(Dict(option) *opts, char *name, bool allow_tab,
                                      OptIndex *opt_idxp, int *opt_flags, OptScope *scope,
                                      void **from, char **filetype, set_op_T *operation,
                                      bool *dry_run, Error *err)
{
#define HAS_KEY_X(d, v) HAS_KEY(d, option, v)
  // Validate incompatible argument combinations first, then resolve handles and scope.
  VALIDATE_CON(!HAS_KEY_X(opts, filetype)
               || (!HAS_KEY_X(opts, scope) && !HAS_KEY_X(opts, buf)
                   && !HAS_KEY_X(opts, win) && !HAS_KEY_X(opts, tab)),
               "filetype", "'scope', 'buf', 'win' or 'tab'", {
    return FAIL;
  });

  VALIDATE_CON(!HAS_KEY_X(opts, tab) || allow_tab, "tab", "this function", {
    return FAIL;
  });

  VALIDATE_CON(!HAS_KEY_X(opts, tab)
               || (!HAS_KEY_X(opts, win) && !HAS_KEY_X(opts, buf)
                   && !HAS_KEY_X(opts, filetype) && !HAS_KEY_X(opts, scope)),
               "tab", "'win', 'buf', 'filetype' or 'scope'", {
    return FAIL;
  });

  VALIDATE_CON(!(HAS_KEY_X(opts, win) && HAS_KEY_X(opts, buf)), "buf", "win", {
    return FAIL;
  });

  if (HAS_KEY_X(opts, scope)) {
    if (!strcmp(opts->scope.data, "local")) {
      *opt_flags = OPT_LOCAL;
    } else if (!strcmp(opts->scope.data, "global")) {
      *opt_flags = OPT_GLOBAL;
    } else {
      VALIDATE_EXP(false, "scope", "'local' or 'global'", NULL, {
        return FAIL;
      });
    }
  }

  *scope = kOptScopeGlobal;

  if (filetype != NULL && HAS_KEY_X(opts, filetype)) {
    *filetype = opts->filetype.data;
  }

  if (HAS_KEY_X(opts, win)) {
    *scope = kOptScopeWin;
    *from = find_window_by_handle(opts->win, err);
    if (ERROR_SET(err)) {
      return FAIL;
    }
  }

  if (HAS_KEY_X(opts, buf)) {
    VALIDATE_CON(!(HAS_KEY_X(opts, scope) && *opt_flags == OPT_GLOBAL), "buf", "global scope", {
      return FAIL;
    });
    *opt_flags = OPT_LOCAL;
    *scope = kOptScopeBuf;
    *from = find_buffer_by_handle(opts->buf, err);
    if (ERROR_SET(err)) {
      return FAIL;
    }
  }

  if (HAS_KEY_X(opts, tab)) {
    *scope = kOptScopeTab;
    *from = find_tab_by_handle(opts->tab, err);
    if (ERROR_SET(err)) {
      return FAIL;
    }
  }

  *opt_idxp = find_option(name);
  if (*opt_idxp == kOptInvalid) {
    // unknown option
    api_set_error(err, kErrorTypeValidation, "Unknown option '%s'", name);
    return FAIL;
  }

  if (operation != NULL && HAS_KEY_X(opts, operation)) {
    if (strequal(opts->operation.data, "set")) {
      *operation = OP_NONE;
    } else if (strequal(opts->operation.data, "append")) {
      *operation = OP_ADDING;
    } else if (strequal(opts->operation.data, "prepend")) {
      *operation = OP_PREPENDING;
    } else if (strequal(opts->operation.data, "remove")) {
      *operation = OP_REMOVING;
    } else {
      VALIDATE_EXP(false, "operation", "'set', 'append', 'prepend', or 'remove'", NULL, {
        return FAIL;
      });
    }

    VALIDATE_CON(*operation == OP_NONE || option_has_type(*opt_idxp, kObjectTypeString)
                 || option_has_type(*opt_idxp, kObjectTypeInteger),
                 opts->operation.data,
                 "boolean options", {
      return FAIL;
    });
  }

  if (dry_run != NULL && HAS_KEY_X(opts, dry_run)) {
    *dry_run = opts->dry_run;
  }

  // Reject keys whose scope the option doesn't support.
  VALIDATE_CON(!HAS_KEY_X(opts, tab) || option_has_scope(*opt_idxp, kOptScopeTab),
               "tab", name, { return FAIL; });

  // If 'buf' or 'win' is passed, make sure the option supports it.
  if (*scope == kOptScopeBuf || *scope == kOptScopeWin) {
    if (!option_has_scope(*opt_idxp, *scope)) {
      char *tgt = *scope == kOptScopeBuf ? "buf" : "win";
      char *global = option_has_scope(*opt_idxp, kOptScopeGlobal) ? "global " : "";
      char *req = option_has_scope(*opt_idxp, kOptScopeBuf)
                  ? "buffer-local "
                  : (option_has_scope(*opt_idxp, kOptScopeWin) ? "window-local " : "");

      api_set_error(err, kErrorTypeValidation, "'%s' cannot be passed for %s%soption '%s'",
                    tgt, global, req, name);
      return FAIL;
    }
  }

  return ERROR_SET(err) ? FAIL : OK;
#undef HAS_KEY_X
}

/// Create a dummy buffer and run the FileType autocmd on it.
static buf_T *do_ft_buf(const char *filetype, CtxSwitch *aco, Error *err)
  FUNC_ATTR_NONNULL_ARG(2, 3)
{
  if (filetype == NULL) {
    return NULL;
  }

  // Allocate a buffer without putting it in the buffer list.
  buf_T *ftbuf = buflist_new(NULL, NULL, 1, BLN_DUMMY);
  if (ftbuf == NULL) {
    api_set_error(err, kErrorTypeException, "Could not create internal buffer");
    return NULL;
  }

  // Open a memline for use by autocommands.
  if (ml_open(ftbuf) == FAIL) {
    api_set_error(err, kErrorTypeException, "Could not load internal buffer");
    return ftbuf;
  }

  bufref_T bufref;
  set_bufref(&bufref, ftbuf);

  // Set curwin/curbuf to buf and save a few things.
  ctx_switch(aco, NULL, NULL, ftbuf, 0);

  set_option_direct(kOptBufhidden, STATIC_CSTR_AS_OBJ("hide"), OPT_LOCAL, SID_NONE);
  set_option_direct(kOptBuftype, STATIC_CSTR_AS_OBJ("nofile"), OPT_LOCAL, SID_NONE);
  assert(ftbuf->b_ml.ml_mfp->mf_fd < 0);  // ml_open() should not have opened swapfile already
  ftbuf->b_p_swf = false;
  ftbuf->b_p_ml = false;
  ftbuf->b_p_ft = xstrdup(filetype);

  if (!has_event(EVENT_FILETYPE)) {
    return ftbuf;  // Nothing more to do.
  }

  bool did_au_ft = false;
  TRY_WRAP(err, {
    did_au_ft = do_filetype_autocmd(ftbuf, true);
  });

  if (!bufref_valid(&bufref)) {
    if (!ERROR_SET(err)) {
      api_set_error(err, kErrorTypeException, "Internal buffer was deleted");
    }
    return NULL;
  }

  if (!did_au_ft && !ERROR_SET(err)) {
    api_set_error(err, kErrorTypeException, "Could not execute FileType autocommands");
  }
  return ftbuf;
}

static void wipe_ft_buf(buf_T *buf)
  FUNC_ATTR_NONNULL_ALL
{
  block_autocmds();

  bufref_T bufref;
  set_bufref(&bufref, buf);

  close_windows(buf, false);
  // Autocommands are blocked, but 'bufhidden' may have wiped it already.
  // Also can't wipe if the buffer is somehow still in a window or current.
  if (bufref_valid(&bufref) && buf != curbuf && buf->b_nwindows == 0) {
    wipe_buffer(buf, false);
  }
  if (bufref_valid(&bufref)) {
    buf->b_flags &= ~BF_DUMMY;  // Couldn't wipe; keep it instead.
  }

  unblock_autocmds();
}

/// Gets the value of an option. The behavior of this function matches that of
/// |:set|: the local value of an option is returned if it exists; otherwise,
/// the global value is returned. Local values always correspond to the current
/// buffer or window, unless "buf" or "win" is set in {opts}.
///
/// @param name      Option name
/// @param opts      Optional parameters
///                  - buf: Buffer number. Used for getting buffer local options.
///                         Implies {scope} is "local".
///                  - filetype: |filetype|. Used to get the default option for a
///                    specific filetype. Cannot be used with any other option.
///                    Note: this will trigger |ftplugin| and all |FileType|
///                    autocommands for the corresponding filetype.
///                  - scope: One of "global" or "local". Analogous to
///                  |:setglobal| and |:setlocal|, respectively.
///                  - tab: |tab-ID| for tab-local options. Currently only
///                    supports "cmdheight". Tabpage `0` means the current tabpage.
///                  - win: |window-ID|. Used for getting window local options.
/// @param[out] err  Error details, if any
/// @return          Option value
Object nvim_get_option_value(String name, Dict(option) *opts, Error *err)
  FUNC_API_SINCE(9) FUNC_API_RET_ALLOC
{
  OptIndex opt_idx = 0;
  int opt_flags = 0;
  OptScope scope = kOptScopeGlobal;
  void *from = NULL;
  char *filetype = NULL;

  if (!validate_option_value_args(opts, name.data, true, &opt_idx, &opt_flags, &scope, &from,
                                  &filetype, NULL, NULL, err)) {
    return (Object)OBJECT_INIT;
  }

  CtxSwitch aco = { 0 };

  buf_T *ftbuf = do_ft_buf(filetype, &aco, err);
  if (ERROR_SET(err)) {
    // Restore curwin/curbuf and a few other things.
    ctx_restore(&aco);
    if (ftbuf != NULL) {
      wipe_ft_buf(ftbuf);
    }
    return (Object)OBJECT_INIT;
  }

  if (ftbuf != NULL) {
    assert(!from);
    from = ftbuf;
  }

  Object value = get_option_value_for(opt_idx, opt_flags, scope, from, err);

  // Restore curwin/curbuf and a few other things.
  ctx_restore(&aco);
  if (ftbuf != NULL) {
    wipe_ft_buf(ftbuf);
  }

  if (ERROR_SET(err)) {
    api_free_object(value);
    return (Object)OBJECT_INIT;
  }

  return value;
}

/// Sets the value of an option. The behavior of this function matches that of
/// |:set|: for global-local options, both the global and local value are set
/// unless otherwise specified with {scope}.
///
/// Note that `win` and `buf` cannot be used together.
///
/// @param name      Option name
/// @param value     New option value. May be structured for dict/list options, e.g. 'formatoptions'
///                  accepts `{ 'c', 'r' }`, 'listchars' accepts `{ eol = '~' }`.
/// @param opts      Optional parameters
///                  - buf: Buffer number. Used for setting buffer local option.
///                  - dry_run: (`boolean?`, default: false) If true, validates the
///                    option value without setting it.
///                  - operation: (`string?`, default: "set") One of "set", "append", "prepend", or
///                    "remove". Corresponds to |:set=|, |:set+=|, |:set^=|, and |:set-=|.
///                    With "remove", each item in a structured `value` is removed regardless of
///                    order/adjacency.
///                  - scope: One of "global" or "local". Analogous to
///                  |:setglobal| and |:setlocal|, respectively.
///                  - tab: |tab-ID| for tab-local options (currently only 'cmdheight'). Tabpage 0
///                    means the current tabpage. If a non-current tab is given, the value will take
///                    effect when it is switched-to.
///                  - win: |window-ID|. Used for setting window local option.
/// @param[out] err  Error details, if any
/// @return          Option value
Object nvim_set_option_value(uint64_t channel_id, String name, Object value, Dict(option) *opts,
                             Arena *arena, Error *err)
  FUNC_API_SINCE(9)
{
  OptIndex opt_idx = 0;
  int opt_flags = 0;
  OptScope scope = kOptScopeGlobal;
  set_op_T operation = OP_NONE;
  void *to = NULL;
  bool dry_run = false;
  if (!validate_option_value_args(opts, name.data, true, &opt_idx, &opt_flags, &scope, &to, NULL,
                                  &operation, &dry_run, err)) {
    return NIL;
  }

  // If:
  // - window id is provided
  // - scope is not provided
  // - option is global or local to window (global-local)
  //
  // Then force scope to local since we don't want to change the global option
  if (scope == kOptScopeWin && opt_flags == 0) {
    if (option_has_scope(opt_idx, kOptScopeGlobal)) {
      opt_flags = OPT_LOCAL;
    }
  }

  Object merged_val = NIL;
  const char *errmsg = NULL;
  vimoption_T *option = get_option