robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
204.8 KiB7615 linesraw
1#include <assert.h>
2#include <float.h>
3#include <inttypes.h>
4#include <limits.h>
5#include <math.h>
6#include <signal.h>
7#include <stdarg.h>
8#include <stddef.h>
9#include <stdio.h>
10#include <stdlib.h>
11#include <string.h>
12#include <time.h>
13#include <uv.h>
14
15#include "auto/config.h"
16#include "klib/kvec.h"
17#include "mpack/mpack_core.h"
18#include "mpack/object.h"
19#include "nvim/api/private/converter.h"
20#include "nvim/api/private/defs.h"
21#include "nvim/api/private/dispatch.h"
22#include "nvim/api/private/helpers.h"
23#include "nvim/api/vim.h"
24#include "nvim/ascii_defs.h"
25#include "nvim/assert_defs.h"
26#include "nvim/autocmd.h"
27#include "nvim/autocmd_defs.h"
28#include "nvim/buffer.h"
29#include "nvim/buffer_defs.h"
30#include "nvim/channel.h"
31#include "nvim/channel_defs.h"
32#include "nvim/charset.h"
33#include "nvim/cmdexpand.h"
34#include "nvim/cmdexpand_defs.h"
35#include "nvim/context.h"
36#include "nvim/cursor.h"
37#include "nvim/dialog.h"
38#include "nvim/errors.h"
39#include "nvim/eval/buffer.h"
40#include "nvim/eval/decode.h"
41#include "nvim/eval/encode.h"
42#include "nvim/eval/executor.h"
43#include "nvim/eval/funcs.h"
44#include "nvim/eval/typval.h"
45#include "nvim/eval/typval_defs.h"
46#include "nvim/eval/userfunc.h"
47#include "nvim/eval/vars.h"
48#include "nvim/eval/window.h"
49#include "nvim/event/defs.h"
50#include "nvim/event/loop.h"
51#include "nvim/event/multiqueue.h"
52#include "nvim/event/proc.h"
53#include "nvim/event/time.h"
54#include "nvim/ex_cmds.h"
55#include "nvim/ex_cmds_defs.h"
56#include "nvim/ex_docmd.h"
57#include "nvim/ex_eval.h"
58#include "nvim/ex_getln.h"
59#include "nvim/garray.h"
60#include "nvim/garray_defs.h"
61#include "nvim/gettext_defs.h"
62#include "nvim/globals.h"
63#include "nvim/grid.h"
64#include "nvim/grid_defs.h"
65#include "nvim/highlight_defs.h"
66#include "nvim/highlight_group.h"
67#include "nvim/indent.h"
68#include "nvim/indent_c.h"
69#include "nvim/input.h"
70#include "nvim/input_defs.h"
71#include "nvim/insert.h"
72#include "nvim/insexpand.h"
73#include "nvim/keycodes.h"
74#include "nvim/lua/executor.h"
75#include "nvim/macros_defs.h"
76#include "nvim/main.h"
77#include "nvim/mark.h"
78#include "nvim/mark_defs.h"
79#include "nvim/math.h"
80#include "nvim/mbyte.h"
81#include "nvim/mbyte_defs.h"
82#include "nvim/memline.h"
83#include "nvim/memory.h"
84#include "nvim/memory_defs.h"
85#include "nvim/menu.h"
86#include "nvim/menu_defs.h"
87#include "nvim/message.h"
88#include "nvim/move.h"
89#include "nvim/msgpack_rpc/channel.h"
90#include "nvim/msgpack_rpc/channel_defs.h"
91#include "nvim/msgpack_rpc/packer.h"
92#include "nvim/msgpack_rpc/packer_defs.h"
93#include "nvim/msgpack_rpc/server.h"
94#include "nvim/normal.h"
95#include "nvim/normal_defs.h"
96#include "nvim/ops.h"
97#include "nvim/option.h"
98#include "nvim/option_defs.h"
99#include "nvim/option_vars.h"
100#include "nvim/optionstr.h"
101#include "nvim/os/dl.h"
102#include "nvim/os/fs.h"
103#include "nvim/os/os.h"
104#include "nvim/os/os_defs.h"
105#include "nvim/os/pty_proc.h"
106#include "nvim/os/shell.h"
107#include "nvim/os/stdpaths_defs.h"
108#include "nvim/os/time.h"
109#include "nvim/path.h"
110#include "nvim/plines.h"
111#include "nvim/popupmenu.h"
112#include "nvim/pos_defs.h"
113#include "nvim/profile.h"
114#include "nvim/regexp.h"
115#include "nvim/regexp_defs.h"
116#include "nvim/register.h"
117#include "nvim/runtime.h"
118#include "nvim/runtime_defs.h"
119#include "nvim/search.h"
120#include "nvim/sha256.h"
121#include "nvim/spell.h"
122#include "nvim/spellsuggest.h"
123#include "nvim/state.h"
124#include "nvim/state_defs.h"
125#include "nvim/strings.h"
126#include "nvim/syntax.h"
127#include "nvim/tag.h"
128#include "nvim/terminal.h"
129#include "nvim/types_defs.h"
130#include "nvim/ui.h"
131#include "nvim/ui_compositor.h"
132#include "nvim/version.h"
133#include "nvim/vim_defs.h"
134#include "nvim/window.h"
135
136/// Describe data to return from find_some_match()
137typedef enum {
138  kSomeMatch,  ///< Data for match().
139  kSomeMatchEnd,  ///< Data for matchend().
140  kSomeMatchList,  ///< Data for matchlist().
141  kSomeMatchStr,  ///< Data for matchstr().
142  kSomeMatchStrPos,  ///< Data for matchstrpos().
143} SomeMatchType;
144
145#include "eval/funcs.c.generated.h"
146
147#ifdef _MSC_VER
148// This prevents MSVC from replacing the functions with intrinsics,
149// and causing errors when trying to get their addresses in funcs.generated.h
150# pragma function(ceil)
151# pragma function(floor)
152#endif
153
154PRAGMA_DIAG_PUSH_IGNORE_MISSING_PROTOTYPES
155PRAGMA_DIAG_PUSH_IGNORE_IMPLICIT_FALLTHROUGH
156#include "funcs.generated.h"
157
158PRAGMA_DIAG_POP
159PRAGMA_DIAG_POP
160
161static const char e_invalid_submatch_number_nr[]
162  = N_("E935: Invalid submatch number: %d");
163static const char e_string_list_or_blob_required[]
164  = N_("E1098: String, List or Blob required");
165static const char e_missing_function_argument[]
166  = N_("E1132: Missing function argument");
167
168/// Dummy va_list for passing to vim_snprintf
169///
170/// Used because:
171/// - passing a NULL pointer doesn't work when va_list isn't a pointer
172/// - locally in the function results in a "used before set" warning
173/// - using va_start() to initialize it gives "function with fixed args" error
174static va_list dummy_ap;
175
176/// Function given to ExpandGeneric() to obtain the list of internal
177/// or user defined function names.
178char *get_function_name(expand_T *xp, int idx)
179{
180  static int intidx = -1;
181
182  if (idx == 0) {
183    intidx = -1;
184  }
185  if (intidx < 0) {
186    char *name = get_user_func_name(xp, idx);
187    if (name != NULL) {
188      if (*name != NUL && *name != '<'
189          && strncmp("g:", xp->xp_pattern, 2) == 0) {
190        return cat_prefix_varname('g', name);
191      }
192      return name;
193    }
194  }
195
196  const char *const key = functions[++intidx].name;
197  if (!key) {
198    return NULL;
199  }
200  const size_t key_len = strlen(key);
201  memcpy(IObuff, key, key_len);
202  IObuff[key_len] = '(';
203  if (functions[intidx].max_argc == 0) {
204    IObuff[key_len + 1] = ')';
205    IObuff[key_len + 2] = NUL;
206  } else {
207    IObuff[key_len + 1] = NUL;
208  }
209  return IObuff;
210}
211
212/// Function given to ExpandGeneric() to obtain the list of internal or
213/// user defined variable or function names.
214char *get_expr_name(expand_T *xp, int idx)
215{
216  static int intidx = -1;
217
218  if (idx == 0) {
219    intidx = -1;
220  }
221  if (intidx < 0) {
222    char *name = get_function_name(xp, idx);
223    if (name != NULL) {
224      return name;
225    }
226  }
227  return get_user_var_name(xp, ++intidx);
228}
229
230/// Gets a builtin (aka "vimfn", "eval") function from the generated hash table.
231///
232/// @param[in]  name  Name of the function.
233///
234/// @return  pointer to the function definition or NULL if not found.
235const EvalFuncDef *find_internal_func(const char *const name)
236  FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE FUNC_ATTR_NONNULL_ALL
237{
238  size_t len = strlen(name);
239  int index = find_internal_func_hash(name, len);
240  return index >= 0 ? &functions[index] : NULL;
241}
242
243/// Gets the Lua name of a Lua-implemented "vimfn" function, or NULL if not found.
244const char *find_internal_func_lua(const char *const name)
245  FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE FUNC_ATTR_NONNULL_ALL
246{
247  const EvalFuncDef *const fdef = find_internal_func(name);
248  if (fdef && fdef->func == &lua_wrapper) {
249    return fdef->data.func_lua;
250  }
251  return NULL;
252}
253
254/// Check the argument count to use for internal function "fdef".
255/// @return  -1 for failure, 0 if no method base accepted, 1 if method base is
256/// first argument, 2 if method base is second argument, etc.
257int check_internal_func(const EvalFuncDef *const fdef, const int argcount)
258  FUNC_ATTR_NONNULL_ALL
259{
260  int res;
261
262  if (argcount < fdef->min_argc) {
263    res = FCERR_TOOFEW;
264  } else if (argcount > fdef->max_argc) {
265    res = FCERR_TOOMANY;
266  } else {
267    return fdef->base_arg;
268  }
269
270  const char *const name = fdef->name;
271  if (res == FCERR_TOOMANY) {
272    semsg(_(e_toomanyarg), name);
273  } else {
274    semsg(_(e_toofewarg), name);
275  }
276  return -1;
277}
278
279int call_internal_func(const char *const fname, const int argcount, typval_T *const argvars,
280                       typval_T *const rettv)
281  FUNC_ATTR_NONNULL_ALL
282{
283  const EvalFuncDef *const fdef = find_internal_func(fname);
284  if (fdef == NULL) {
285    return FCERR_UNKNOWN;
286  } else if (argcount < fdef->min_argc) {
287    return FCERR_TOOFEW;
288  } else if (argcount > fdef->max_argc) {
289    return FCERR_TOOMANY;
290  }
291  argvars[argcount].v_type = VAR_UNKNOWN;
292  fdef->func(argvars, rettv, fdef->data);
293  return FCERR_NONE;
294}
295
296/// Invoke a method for base->method().
297int call_internal_method(const char *const fname, const int argcount, typval_T *const argvars,
298                         typval_T *const rettv, typval_T *const basetv)
299  FUNC_ATTR_NONNULL_ALL
300{
301  const EvalFuncDef *const fdef = find_internal_func(fname);
302  if (fdef == NULL) {
303    return FCERR_UNKNOWN;
304  } else if (fdef->base_arg == BASE_NONE) {
305    return FCERR_NOTMETHOD;
306  } else if (argcount + 1 < fdef->min_argc) {
307    return FCERR_TOOFEW;
308  } else if (argcount + 1 > fdef->max_argc) {
309    return FCERR_TOOMANY;
310  }
311
312  typval_T argv[MAX_FUNC_ARGS + 1];
313  const ptrdiff_t base_index = fdef->base_arg == BASE_LAST ? argcount : fdef->base_arg - 1;
314  if (argcount < base_index) {
315    return FCERR_TOOFEW;
316  }
317  memcpy(argv, argvars, (size_t)base_index * sizeof(typval_T));
318  argv[base_index] = *basetv;
319  memcpy(argv + base_index + 1, argvars + base_index,
320         (size_t)(argcount - base_index) * sizeof(typval_T));
321  argv[argcount + 1].v_type = VAR_UNKNOWN;
322
323  fdef->func(argv, rettv, fdef->data);
324  return FCERR_NONE;
325}
326
327/// @return  true for a non-zero Number and a non-empty String.
328static bool non_zero_arg(typval_T *argvars)
329{
330  return ((argvars[0].v_type == VAR_NUMBER
331           && argvars[0].vval.v_number != 0)
332          || (argvars[0].v_type == VAR_BOOL
333              && argvars[0].vval.v_bool == kBoolVarTrue)
334          || (argvars[0].v_type == VAR_STRING
335              && argvars[0].vval.v_string != NULL
336              && *argvars[0].vval.v_string != NUL));
337}
338
339/// Apply a floating point C function on a typval with one float_T (`func_float` in eval.lua).
340///
341/// Some versions of glibc on i386 have an optimization that makes it harder to
342/// call math functions indirectly from inside an inlined function, causing
343/// compile-time errors. Avoid `inline` in that case. #3072
344static void float_op_wrapper(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
345{
346  float_T f;
347
348  rettv->v_type = VAR_FLOAT;
349  if (tv_get_float_chk(argvars, &f)) {
350    rettv->vval.v_float = fptr.func_float(f);
351  } else {
352    rettv->vval.v_float = 0.0;
353  }
354}
355
356/// Invokes an API (nvim_) function from Vimscript.
357///
358/// Converts `argvars` to API Objects, calls the API handler, and converts the result back.
359/// Used by `gen_eval.lua` for `eval=true` API functions.
360static void api_wrapper(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
361{
362  if (check_secure()) {
363    return;
364  }
365
366  MsgpackRpcRequestHandler handler = *fptr.func_api;
367
368  MAXSIZE_TEMP_ARRAY(args, MAX_FUNC_ARGS);
369  Arena arena = ARENA_EMPTY;
370
371  for (typval_T *tv = argvars; tv->v_type != VAR_UNKNOWN; tv++) {
372    ADD_C(args, vim_to_object(tv, &arena, false));
373  }
374
375  Error err = ERROR_INIT;
376  Object result = handler.fn(VIML_INTERNAL_CALL, args, &arena, &err);
377
378  if (ERROR_SET(&err)) {
379    semsg_multiline("emsg", e_api_error, err.msg);
380    goto end;
381  }
382
383  object_to_vim_take_luaref(&result, rettv, true, &err);
384
385end:
386  if (handler.ret_alloc) {
387    api_free_object(result);
388  }
389  arena_mem_free(arena_finish(&arena));
390  api_clear_error(&err);
391}
392
393/// Invokes a Lua-implemented vimfn/"f_xx" function from Vimscript (`func_lua` in eval.lua).
394///
395/// - Converts argvars to API Objects, calls the Lua function, converts the result back.
396/// - NOT used when called from Lua; `nlua_call()` calls the function directly.
397static void lua_wrapper(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
398{
399  MAXSIZE_TEMP_ARRAY(args, MAX_FUNC_ARGS);
400  Arena arena = ARENA_EMPTY;
401
402  for (typval_T *tv = argvars; tv->v_type != VAR_UNKNOWN; tv++) {
403    ADD_C(args, vim_to_object(tv, &arena, false));
404  }
405
406  char buf[256];
407  snprintf(buf, sizeof(buf), "return require('vim._core.vimfn').%s(...)", fptr.func_lua);
408
409  Error err = ERROR_INIT;
410  Object result = nlua_exec(cstr_as_string(buf), NULL, args, kRetObject, &arena, &err);
411
412  if (ERROR_SET(&err)) {
413    semsg_multiline("emsg", e_api_error, err.msg);
414    goto end;
415  }
416
417  object_to_vim_take_luaref(&result, rettv, true, &err);
418
419end:
420  arena_mem_free(arena_finish(&arena));
421  api_clear_error(&err);
422}
423
424/// "abs(expr)" function
425static void f_abs(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
426{
427  if (argvars[0].v_type == VAR_FLOAT) {
428    float_op_wrapper(argvars, rettv, (EvalFuncData){ .func_float = &fabs });
429  } else {
430    bool error = false;
431
432    varnumber_T n = tv_get_number_chk(&argvars[0], &error);
433    if (error) {
434      rettv->vval.v_number = -1;
435    } else if (n > 0) {
436      rettv->vval.v_number = n;
437    } else {
438      rettv->vval.v_number = -n;
439    }
440  }
441}
442
443/// "and(expr, expr)" function
444static void f_and(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
445{
446  rettv->vval.v_number = tv_get_number_chk(&argvars[0], NULL)
447                         & tv_get_number_chk(&argvars[1], NULL);
448}
449
450/// "api_info()" function
451static void f_api_info(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
452{
453  object_to_vim(api_metadata(), rettv, NULL);
454}
455
456/// "atan2()" function
457static void f_atan2(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
458{
459  float_T fx;
460  float_T fy;
461
462  rettv->v_type = VAR_FLOAT;
463  if (tv_get_float_chk(argvars, &fx) && tv_get_float_chk(&argvars[1], &fy)) {
464    rettv->vval.v_float = atan2(fx, fy);
465  } else {
466    rettv->vval.v_float = 0.0;
467  }
468}
469
470/// Get buffer by number or pattern.
471buf_T *tv_get_buf(typval_T *tv, int curtab_only)
472{
473  if (tv->v_type == VAR_NUMBER) {
474    return buflist_findnr((int)tv->vval.v_number);
475  }
476  if (tv->v_type != VAR_STRING) {
477    return NULL;
478  }
479
480  char *name = tv->vval.v_string;
481
482  if (name == NULL || *name == NUL) {
483    return curbuf;
484  }
485  if (name[0] == '$' && name[1] == NUL) {
486    return lastbuf;
487  }
488
489  // Ignore 'magic' and 'cpoptions' here to make scripts portable
490  int save_magic = p_magic;
491  p_magic = true;
492  char *save_cpo = p_cpo;
493  p_cpo = empty_string_option;
494
495  buf_T *buf = buflist_findnr(buflist_findpat(name, name + strlen(name),
496                                              true, false, curtab_only));
497
498  p_magic = save_magic;
499  p_cpo = save_cpo;
500
501  // If not found, try expanding the name, like done for bufexists().
502  if (buf == NULL) {
503    buf = find_buffer(tv);
504  }
505
506  return buf;
507}
508
509/// Like tv_get_buf() but give an error message if the type is wrong.
510buf_T *tv_get_buf_from_arg(typval_T *const tv) FUNC_ATTR_NONNULL_ALL
511{
512  if (!tv_check_str_or_nr(tv)) {
513    return NULL;
514  }
515  emsg_off++;
516  buf_T *const buf = tv_get_buf(tv, false);
517  emsg_off--;
518  return buf;
519}
520
521/// Get the buffer from "arg" and give an error and return NULL if it is not
522/// valid.
523buf_T *get_buf_arg(typval_T *arg)
524{
525  emsg_off++;
526  buf_T *buf = tv_get_buf(arg, false);
527  emsg_off--;
528  if (buf == NULL) {
529    semsg(_("E158: Invalid buffer name: %s"), tv_get_string(arg));
530  }
531  return buf;
532}
533
534/// "byte2line(byte)" function
535static void f_byte2line(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
536{
537  int boff = (int)tv_get_number(&argvars[0]) - 1;
538  if (boff < 0) {
539    rettv->vval.v_number = -1;
540  } else {
541    rettv->vval.v_number = (varnumber_T)ml_find_line_or_offset(curbuf, 0,
542                                                               &boff, false);
543  }
544}
545
546/// "call(func, arglist [, dict])" function
547static void f_call(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
548{
549  if (tv_check_for_list_arg(argvars, 1) == FAIL) {
550    return;
551  }
552  if (argvars[1].vval.v_list == NULL) {
553    return;
554  }
555
556  bool owned = false;
557  char *func;
558  partial_T *partial = NULL;
559  if (argvars[0].v_type == VAR_FUNC) {
560    func = argvars[0].vval.v_string;
561  } else if (argvars[0].v_type == VAR_PARTIAL) {
562    partial = argvars[0].vval.v_partial;
563    func = partial_name(partial);
564  } else if (nlua_is_table_from_lua(&argvars[0])) {
565    // TODO(tjdevries): UnifiedCallback
566    func = nlua_register_table_as_callable(&argvars[0]);
567    owned = true;
568  } else {
569    func = (char *)tv_get_string(&argvars[0]);
570  }
571
572  if (func == NULL || *func == NUL) {
573    return;         // type error, empty name or null function
574  }
575  char *tofree = NULL;
576  if (argvars[0].v_type == VAR_STRING) {
577    char *p = func;
578    tofree = trans_function_name(&p, false, TFN_INT|TFN_QUIET, NULL, NULL);
579    if (tofree == NULL) {
580      emsg_funcname(e_unknown_function_str, func);
581      return;
582    }
583    func = tofree;
584  }
585
586  dict_T *selfdict = NULL;
587  if (argvars[2].v_type != VAR_UNKNOWN) {
588    if (tv_check_for_dict_arg(argvars, 2) == FAIL) {
589      goto done;
590    }
591    selfdict = argvars[2].vval.v_dict;
592  }
593
594  func_call(func, &argvars[1], partial, selfdict, rettv);
595
596done:
597  if (owned) {
598    func_unref(func);
599  }
600  xfree(tofree);
601}
602
603/// "changenr()" function
604static void f_changenr(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
605{
606  rettv->vval.v_number = curbuf->b_u_seq_cur;
607}
608
609/// "chanclose(id[, stream])" function
610static void f_chanclose(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
611{
612  rettv->v_type = VAR_NUMBER;
613  rettv->vval.v_number = 0;
614
615  if (check_secure()) {
616    return;
617  }
618
619  if (argvars[0].v_type != VAR_NUMBER || (argvars[1].v_type != VAR_STRING
620                                          && argvars[1].v_type != VAR_UNKNOWN)) {
621    emsg(_(e_invarg));
622    return;
623  }
624
625  ChannelPart part = kChannelPartAll;
626  if (argvars[1].v_type == VAR_STRING) {
627    const char *stream = tv_get_string(&argvars[1]);
628    if (!strcmp(stream, "stdin")) {
629      part = kChannelPartStdin;
630    } else if (!strcmp(stream, "stdout")) {
631      part = kChannelPartStdout;
632    } else if (!strcmp(stream, "stderr")) {
633      part = kChannelPartStderr;
634    } else if (!strcmp(stream, "rpc")) {
635      part = kChannelPartRpc;
636    } else {
637      semsg(_("Invalid channel stream \"%s\""), stream);
638      return;
639    }
640  }
641  const char *error;
642  rettv->vval.v_number = channel_close((uint64_t)argvars[0].vval.v_number, part, &error);
643  if (!rettv->vval.v_number) {
644    emsg(error);
645  }
646}
647
648/// "chansend(id, data)" function
649static void f_chansend(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
650{
651  rettv->v_type = VAR_NUMBER;
652  rettv->vval.v_number = 0;
653
654  if (check_secure()) {
655    return;
656  }
657
658  if (argvars[0].v_type != VAR_NUMBER || argvars[1].v_type == VAR_UNKNOWN) {
659    // First argument is the channel id and second is the data to write
660    emsg(_(e_invarg));
661    return;
662  }
663
664  ptrdiff_t input_len = 0;
665  char *input = NULL;
666  uint64_t id = (uint64_t)argvars[0].vval.v_number;
667#ifdef UNIX
668  bool crlf = false;
669#else
670  Channel *chan = find_channel(id);
671  bool crlf = (chan != NULL && chan->term) ? true : false;
672#endif
673
674  if (argvars[1].v_type == VAR_BLOB) {
675    const blob_T *const b = argvars[1].vval.v_blob;
676    input_len = tv_blob_len(b);
677    if (input_len > 0) {
678      input = xmemdup(b->bv_ga.ga_data, (size_t)input_len);
679    }
680  } else {
681    input = save_tv_as_string(&argvars[1], &input_len, false, crlf);
682  }
683
684  if (!input) {
685    // Either the error has been handled by save_tv_as_string(),
686    // or there is no input to send.
687    return;
688  }
689  const char *error = NULL;
690  rettv->vval.v_number = (varnumber_T)channel_send(id, input, (size_t)input_len, true, &error);
691  if (error) {
692    emsg(error);
693  }
694}
695
696/// "char2nr(string)" function
697static void f_char2nr(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
698{
699  if (argvars[1].v_type != VAR_UNKNOWN) {
700    if (!tv_check_num(&argvars[1])) {
701      return;
702    }
703  }
704
705  rettv->vval.v_number = utf_ptr2char(tv_get_string(&argvars[0]));
706}
707
708/// Get the current cursor column and store it in 'rettv'.
709///
710/// @return  the character index of the column if 'charcol' is true,
711///          otherwise the byte index of the column.
712static void get_col(typval_T *argvars, typval_T *rettv, bool charcol)
713{
714  if (tv_check_for_string_or_list_arg(argvars, 0) == FAIL
715      || tv_check_for_opt_number_arg(argvars, 1) == FAIL) {
716    return;
717  }
718
719  win_T *wp = curwin;
720
721  if (argvars[1].v_type != VAR_UNKNOWN) {
722    // use the window specified in the second argument
723    tabpage_T *tp;
724    wp = win_id2wp_tp((int)tv_get_number(&argvars[1]), &tp);
725    if (wp == NULL || tp == NULL) {
726      return;
727    }
728    check_cursor(wp);
729  }
730
731  buf_T *bp = wp->w_buffer;
732  colnr_T col = 0;
733  int fnum = bp->b_fnum;
734  pos_T *fp = var2fpos(&argvars[0], false, &fnum, charcol, wp);
735  if (fp != NULL && fnum == bp->b_fnum) {
736    if (fp->col == MAXCOL) {
737      // '> can be MAXCOL, get the length of the line then
738      if (fp->lnum <= bp->b_ml.ml_line_count) {
739        col = ml_get_buf_len(bp, fp->lnum) + 1;
740      } else {
741        col = MAXCOL;
742      }
743    } else {
744      col = fp->col + 1;
745      // col(".") when the cursor is on the NUL at the end of the line
746      // because of "coladd" can be seen as an extra column.
747      if (virtual_active(wp) && fp == &wp->w_cursor) {
748        char *p = ml_get_buf(bp, wp->w_cursor.lnum) + wp->w_cursor.col;
749        if (wp->w_cursor.coladd >=
750            (colnr_T)win_chartabsize(wp, p,
751                                     wp->w_virtcol - wp->w_cursor.coladd)) {
752          int l;
753          if (*p != NUL && p[(l = utfc_ptr2len(p))] == NUL) {
754            col += l;
755          }
756        }
757      }
758    }
759  }
760  rettv->vval.v_number = col;
761}
762
763/// "charcol()" function
764static void f_charcol(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
765{
766  get_col(argvars, rettv, true);
767}
768
769win_T *get_optional_window(typval_T *argvars, int idx)
770{
771  if (argvars[idx].v_type == VAR_UNKNOWN) {
772    return curwin;
773  }
774
775  win_T *win = find_win_by_nr_or_id(&argvars[idx]);
776  if (win == NULL) {
777    emsg(_(e_invalwindow));
778    return NULL;
779  }
780  return win;
781}
782
783/// "col(string)" function
784static void f_col(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
785{
786  get_col(argvars, rettv, false);
787}
788
789/// "confirm(message, buttons[, default [, type]])" function
790static void f_confirm(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
791{
792  char buf[NUMBUFLEN];
793  char buf2[NUMBUFLEN];
794  const char *buttons = NULL;
795  int def = 1;
796  int type = VIM_GENERIC;
797  bool error = false;
798
799  const char *message = tv_get_string_chk(&argvars[0]);
800  if (message == NULL) {
801    error = true;
802  }
803  if (argvars[1].v_type != VAR_UNKNOWN) {
804    buttons = tv_get_string_buf_chk(&argvars[1], buf);
805    if (buttons == NULL) {
806      error = true;
807    }
808    if (argvars[2].v_type != VAR_UNKNOWN) {
809      def = (int)tv_get_number_chk(&argvars[2], &error);
810      if (argvars[3].v_type != VAR_UNKNOWN) {
811        const char *typestr = tv_get_string_buf_chk(&argvars[3], buf2);
812        if (typestr == NULL) {
813          error = true;
814        } else {
815          switch (TOUPPER_ASC(*typestr)) {
816          case 'E':
817            type = VIM_ERROR; break;
818          case 'Q':
819            type = VIM_QUESTION; break;
820          case 'I':
821            type = VIM_INFO; break;
822          case 'W':
823            type = VIM_WARNING; break;
824          case 'G':
825            type = VIM_GENERIC; break;
826          }
827        }
828      }
829    }
830  }
831
832  if (buttons == NULL || *buttons == NUL) {
833    buttons = _("&Ok");
834  }
835
836  if (!error) {
837    rettv->vval.v_number = do_dialog(type, NULL, message, buttons, def, NULL, false);
838  }
839}
840
841/// "copy()" function
842static void f_copy(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
843{
844  var_item_copy(NULL, &argvars[0], rettv, false, 0);
845}
846
847/// Set the cursor position.
848/// If "charcol" is true, then use the column number as a character offset.
849/// Otherwise use the column number as a byte offset.
850static void set_cursorpos(typval_T *argvars, typval_T *rettv, bool charcol)
851{
852  linenr_T lnum;
853  colnr_T col;
854  colnr_T coladd = 0;
855  bool set_curswant = true;
856
857  rettv->vval.v_number = -1;
858  if (argvars[0].v_type == VAR_LIST) {
859    pos_T pos;
860    colnr_T curswant = -1;
861
862    if (list2fpos(argvars, &pos, NULL, &curswant, charcol) == FAIL) {
863      emsg(_(e_invarg));
864      return;
865    }
866
867    lnum = pos.lnum;
868    col = pos.col;
869    coladd = pos.coladd;
870    if (curswant >= 0) {
871      curwin->w_curswant = curswant - 1;
872      set_curswant = false;
873    }
874  } else if ((argvars[0].v_type == VAR_NUMBER || argvars[0].v_type == VAR_STRING)
875             && (argvars[1].v_type == VAR_NUMBER || argvars[1].v_type == VAR_STRING)) {
876    lnum = tv_get_lnum(argvars);
877    if (lnum < 0) {
878      semsg(_(e_invarg2), tv_get_string(&argvars[0]));
879    } else if (lnum == 0) {
880      lnum = curwin->w_cursor.lnum;
881    }
882    col = (colnr_T)tv_get_number_chk(&argvars[1], NULL);
883    if (charcol) {
884      col = buf_charidx_to_byteidx(curbuf, lnum, (int)col) + 1;
885    }
886    if (argvars[2].v_type != VAR_UNKNOWN) {
887      coladd = (colnr_T)tv_get_number_chk(&argvars[2], NULL);
888    }
889  } else {
890    emsg(_(e_invarg));
891    return;
892  }
893  if (lnum < 0 || col < 0 || coladd < 0) {
894    return;  // type error; errmsg already given
895  }
896  if (lnum > 0) {
897    curwin->w_cursor.lnum = lnum;
898  }
899  if (col != MAXCOL && --col < 0) {
900    col = 0;
901  }
902  curwin->w_cursor.col = col;
903  curwin->w_cursor.coladd = coladd;
904
905  // Make sure the cursor is in a valid position.
906  check_cursor(curwin);
907  // Correct cursor for multi-byte character.
908  mb_adjust_cursor();
909
910  curwin->w_set_curswant = set_curswant;
911  rettv->vval.v_number = 0;
912}
913
914/// "cursor(lnum, col)" function, or
915/// "cursor(list)"
916///
917/// Moves the cursor to the specified line and column.
918///
919/// @return  0 when the position could be set, -1 otherwise.
920static void f_cursor(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
921{
922  set_cursorpos(argvars, rettv, false);
923}
924
925/// "debugbreak()" function
926static void f_debugbreak(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
927{
928  rettv->vval.v_number = FAIL;
929  int pid = (int)tv_get_number(&argvars[0]);
930  if (pid == 0) {
931    emsg(_(e_invarg));
932    return;
933  }
934
935#ifdef MSWIN
936  HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, 0, pid);
937  if (hProcess == NULL) {
938    return;
939  }
940
941  DebugBreakProcess(hProcess);
942  CloseHandle(hProcess);
943  rettv->vval.v_number = OK;
944#else
945  uv_kill(pid, SIGINT);
946#endif
947}
948
949/// "deepcopy()" function
950static void f_deepcopy(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
951{
952  if (tv_check_for_opt_bool_arg(argvars, 1) == FAIL) {
953    return;
954  }
955
956  varnumber_T noref = 0;
957  if (argvars[1].v_type != VAR_UNKNOWN) {
958    noref = tv_get_bool_chk(&argvars[1], NULL);
959  }
960
961  var_item_copy(NULL, &argvars[0], rettv, true, (noref == 0 ? get_copyID() : 0));
962}
963
964/// dictwatcheradd(dict, key, funcref) function
965static void f_dictwatcheradd(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
966{
967  if (check_secure()) {
968    return;
969  }
970
971  if (argvars[0].v_type != VAR_DICT) {
972    semsg(_(e_invarg2), "dict");
973    return;
974  } else if (argvars[0].vval.v_dict == NULL) {
975    const char *const arg_errmsg = _("dictwatcheradd() argument");
976    const size_t arg_errmsg_len = strlen(arg_errmsg);
977    semsg(_(e_cannot_change_readonly_variable_str), (int)arg_errmsg_len, arg_errmsg);
978    return;
979  }
980
981  if (argvars[1].v_type != VAR_STRING && argvars[1].v_type != VAR_NUMBER) {
982    semsg(_(e_invarg2), "key");
983    return;
984  }
985
986  const char *const key_pattern = tv_get_string_chk(argvars + 1);
987  if (key_pattern == NULL) {
988    return;
989  }
990  const size_t key_pattern_len = strlen(key_pattern);
991
992  Callback callback;
993  if (!callback_from_typval(&callback, &argvars[2])) {
994    semsg(_(e_invarg2), "funcref");
995    return;
996  }
997
998  tv_dict_watcher_add(argvars[0].vval.v_dict, key_pattern, key_pattern_len,
999                      callback);
1000}
1001
1002/// dictwatcherdel(dict, key, funcref) function
1003static void f_dictwatcherdel(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1004{
1005  if (check_secure()) {
1006    return;
1007  }
1008
1009  if (argvars[0].v_type != VAR_DICT) {
1010    semsg(_(e_invarg2), "dict");
1011    return;
1012  }
1013
1014  if (argvars[2].v_type != VAR_FUNC && argvars[2].v_type != VAR_STRING) {
1015    semsg(_(e_invarg2), "funcref");
1016    return;
1017  }
1018
1019  const char *const key_pattern = tv_get_string_chk(argvars + 1);
1020  if (key_pattern == NULL) {
1021    return;
1022  }
1023
1024  Callback callback;
1025  if (!callback_from_typval(&callback, &argvars[2])) {
1026    return;
1027  }
1028
1029  if (!tv_dict_watcher_remove(argvars[0].vval.v_dict, key_pattern,
1030                              strlen(key_pattern), callback)) {
1031    emsg("Couldn't find a watcher matching key and callback");
1032  }
1033
1034  callback_free(&callback);
1035}
1036
1037/// "did_filetype()" function
1038static void f_did_filetype(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1039{
1040  rettv->vval.v_number = curbuf->b_did_filetype;
1041}
1042
1043/// "empty({expr})" function
1044static void f_empty(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1045{
1046  bool n = true;
1047
1048  switch (argvars[0].v_type) {
1049  case VAR_STRING:
1050  case VAR_FUNC:
1051    n = argvars[0].vval.v_string == NULL
1052        || *argvars[0].vval.v_string == NUL;
1053    break;
1054  case VAR_PARTIAL:
1055    n = argvars[0].vval.v_partial == NULL;
1056    break;
1057  case VAR_NUMBER:
1058    n = argvars[0].vval.v_number == 0;
1059    break;
1060  case VAR_FLOAT:
1061    n = argvars[0].vval.v_float == 0.0;
1062    break;
1063  case VAR_LIST:
1064    n = (tv_list_len(argvars[0].vval.v_list) == 0);
1065    break;
1066  case VAR_DICT:
1067    n = (tv_dict_len(argvars[0].vval.v_dict) == 0);
1068    break;
1069  case VAR_BOOL:
1070    switch (argvars[0].vval.v_bool) {
1071    case kBoolVarTrue:
1072      n = false;
1073      break;
1074    case kBoolVarFalse:
1075      n = true;
1076      break;
1077    }
1078    break;
1079  case VAR_SPECIAL:
1080    n = argvars[0].vval.v_special == kSpecialVarNull;
1081    break;
1082  case VAR_BLOB:
1083    n = (tv_blob_len(argvars[0].vval.v_blob) == 0);
1084    break;
1085  case VAR_UNKNOWN:
1086    internal_error("f_empty(UNKNOWN)");
1087    break;
1088  }
1089
1090  rettv->vval.v_number = n;
1091}
1092
1093/// "escape({string}, {chars})" function
1094static void f_escape(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1095{
1096  char buf[NUMBUFLEN];
1097
1098  rettv->vval.v_string = vim_strsave_escaped(tv_get_string(&argvars[0]),
1099                                             tv_get_string_buf(&argvars[1], buf));
1100  rettv->v_type = VAR_STRING;
1101}
1102
1103/// "getenv()" function
1104static void f_getenv(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1105{
1106  char *p = vim_getenv(tv_get_string(&argvars[0]));
1107
1108  if (p == NULL) {
1109    rettv->v_type = VAR_SPECIAL;
1110    rettv->vval.v_special = kSpecialVarNull;
1111    return;
1112  }
1113  rettv->vval.v_string = p;
1114  rettv->v_type = VAR_STRING;
1115}
1116
1117/// "eval()" function
1118static void f_eval(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1119{
1120  const char *s = tv_get_string_chk(&argvars[0]);
1121  if (s != NULL) {
1122    s = skipwhite(s);
1123  }
1124
1125  const char *const expr_start = s;
1126  if (s == NULL || eval1((char **)&s, rettv, &EVALARG_EVALUATE) == FAIL) {
1127    if (expr_start != NULL && !aborting()) {
1128      semsg(_(e_invexpr2), expr_start);
1129    }
1130    need_clr_eos = false;
1131    rettv->v_type = VAR_NUMBER;
1132    rettv->vval.v_number = 0;
1133  } else if (*s != NUL) {
1134    semsg(_(e_trailing_arg), s);
1135  }
1136}
1137
1138/// "eventhandler()" function
1139static void f_eventhandler(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1140{
1141  rettv->vval.v_number = vgetc_busy;
1142}
1143
1144typedef struct {
1145  const list_T *const l;
1146  const listitem_T *li;
1147} GetListLineCookie;
1148
1149char *get_list_line(int c, void *cookie, int indent, bool do_concat)
1150{
1151  GetListLineCookie *const p = (GetListLineCookie *)cookie;
1152
1153  const listitem_T *const item = p->li;
1154  if (item == NULL) {
1155    return NULL;
1156  }
1157  char buf[NUMBUFLEN];
1158  const char *const s = tv_get_string_buf_chk(TV_LIST_ITEM_TV(item), buf);
1159  p->li = TV_LIST_ITEM_NEXT(p->l, item);
1160  return s == NULL ? NULL : xstrdup(s);
1161}
1162
1163void execute_common(typval_T *argvars, typval_T *rettv, int arg_off)
1164{
1165  const int save_msg_silent = msg_silent;
1166  const int save_emsg_silent = emsg_silent;
1167  const bool save_emsg_noredir = emsg_noredir;
1168  const bool save_redir_off = redir_off;
1169  garray_T *const save_capture_ga = capture_ga;
1170  const int save_msg_col = msg_col;
1171  bool echo_output = false;
1172
1173  if (check_secure()) {
1174    return;
1175  }
1176
1177  if (argvars[arg_off + 1].v_type != VAR_UNKNOWN) {
1178    char buf[NUMBUFLEN];
1179    const char *const s = tv_get_string_buf_chk(&argvars[arg_off + 1], buf);
1180
1181    if (s == NULL) {
1182      return;
1183    }
1184    if (*s == NUL) {
1185      echo_output = true;
1186    }
1187    if (strncmp(s, "silent", 6) == 0) {
1188      msg_silent++;
1189    }
1190    if (strcmp(s, "silent!") == 0) {
1191      emsg_silent = true;
1192      emsg_noredir = true;
1193    }
1194  } else {
1195    msg_silent++;
1196  }
1197
1198  garray_T capture_local;
1199  ga_init(&capture_local, (int)sizeof(char), 80);
1200  capture_ga = &capture_local;
1201  redir_off = false;
1202  if (!echo_output) {
1203    msg_col = 0;  // prevent leading spaces
1204  }
1205
1206  if (argvars[arg_off].v_type != VAR_LIST) {
1207    do_cmdline_cmd(tv_get_string(&argvars[arg_off]));
1208  } else if (argvars[arg_off].vval.v_list != NULL) {
1209    list_T *const list = argvars[arg_off].vval.v_list;
1210    tv_list_ref(list);
1211    GetListLineCookie cookie = {
1212      .l = list,
1213      .li = tv_list_first(list),
1214    };
1215    do_cmdline(NULL, get_list_line, (void *)&cookie,
1216               DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT|DOCMD_KEYTYPED);
1217    tv_list_unref(list);
1218  }
1219  msg_silent = save_msg_silent;
1220  emsg_silent = save_emsg_silent;
1221  emsg_noredir = save_emsg_noredir;
1222  redir_off = save_redir_off;
1223  // "silent reg" or "silent echo x" leaves msg_col somewhere in the line.
1224  if (echo_output) {
1225    // When not working silently: put it in column zero.  A following
1226    // "echon" will overwrite the message, unavoidably.
1227    msg_col = 0;
1228  } else {
1229    // When working silently: Put it back where it was, since nothing
1230    // should have been written.
1231    msg_col = save_msg_col;
1232  }
1233
1234  ga_append(capture_ga, NUL);
1235  rettv->v_type = VAR_STRING;
1236  rettv->vval.v_string = capture_ga->ga_data;
1237
1238  capture_ga = save_capture_ga;
1239}
1240
1241/// "execute(command)" function
1242static void f_execute(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1243{
1244  execute_common(argvars, rettv, 0);
1245}
1246
1247/// "exists()" function
1248static void f_exists(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1249{
1250  int n = false;
1251
1252  const char *p = tv_get_string(&argvars[0]);
1253  if (*p == '$') {  // Environment variable.
1254    // First try "normal" environment variables (fast).
1255    if (os_env_exists(p + 1, false)) {
1256      n = true;
1257    } else {
1258      // Try expanding things like $VIM and ${HOME}.
1259      char *const exp = expand_env_save((char *)p);
1260      if (exp != NULL && *exp != '$') {
1261        n = true;
1262      }
1263      xfree(exp);
1264    }
1265  } else if (*p == '&' || *p == '+') {  // Option.
1266    n = (eval_option(&p, NULL, true) == OK);
1267    if (*skipwhite(p) != NUL) {
1268      n = false;  // Trailing garbage.
1269    }
1270  } else if (*p == '*') {  // Internal or user defined function.
1271    n = strnequal(p, "*v:lua.", 7) ? nlua_func_exists(p + 7) : function_exists(p + 1, false);
1272  } else if (*p == ':') {
1273    n = cmd_exists(p + 1);
1274  } else if (*p == '#') {
1275    if (p[1] == '#') {
1276      n = autocmd_supported(p + 2);
1277    } else {
1278      n = au_exists(p + 1);
1279    }
1280  } else {  // Internal variable.
1281    n = var_exists(p);
1282  }
1283
1284  rettv->vval.v_number = n;
1285}
1286
1287/// "expand()" function
1288static void f_expand(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1289{
1290  int options = WILD_SILENT|WILD_USE_NL|WILD_LIST_NOTFOUND|WILD_USE_SHELLSLASH;
1291  bool error = false;
1292
1293  rettv->v_type = VAR_STRING;
1294  if (argvars[1].v_type != VAR_UNKNOWN
1295      && argvars[2].v_type != VAR_UNKNOWN
1296      && tv_get_bool_chk(&argvars[2], &error)
1297      && !error) {
1298    tv_list_set_ret(rettv, NULL);
1299  }
1300
1301  const char *s = tv_get_string(&argvars[0]);
1302  if (*s == '%' || *s == '#' || *s == '<') {
1303    if (p_verbose == 0) {
1304      emsg_off++;
1305    }
1306    size_t len;
1307    const char *errormsg = NULL;
1308    char *result = eval_vars((char *)s, s, &len, NULL, &errormsg, NULL, false);
1309    if (p_verbose == 0) {
1310      emsg_off--;
1311    } else if (errormsg != NULL) {
1312      emsg(errormsg);
1313    }
1314    if (rettv->v_type == VAR_LIST) {
1315      tv_list_alloc_ret(rettv, (result != NULL));
1316      if (result != NULL) {
1317        tv_list_append_string(rettv->vval.v_list, result, -1);
1318      }
1319      XFREE_CLEAR(result);
1320    } else {
1321      rettv->vval.v_string = result;
1322    }
1323  } else {
1324    // When the optional second argument is non-zero, don't remove matches
1325    // for 'wildignore' and don't put matches for 'suffixes' at the end.
1326    if (argvars[1].v_type != VAR_UNKNOWN
1327        && tv_get_bool_chk(&argvars[1], &error)) {
1328      options |= WILD_KEEP_ALL;
1329    }
1330    if (!error) {
1331      expand_T xpc;
1332      ExpandInit(&xpc);
1333      xpc.xp_context = EXPAND_FILES;
1334      if (p_wic) {
1335        options += WILD_ICASE;
1336      }
1337      if (rettv->v_type == VAR_STRING) {
1338        rettv->vval.v_string = ExpandOne(&xpc, (char *)s, NULL, options, WILD_ALL);
1339      } else {
1340        ExpandOne(&xpc, (char *)s, NULL, options, WILD_ALL_KEEP);
1341        tv_list_alloc_ret(rettv, xpc.xp_numfiles);
1342        for (int i = 0; i < xpc.xp_numfiles; i++) {
1343          tv_list_append_string(rettv->vval.v_list, xpc.xp_files[i], -1);
1344        }
1345        ExpandCleanup(&xpc);
1346      }
1347    } else {
1348      rettv->vval.v_string = NULL;
1349    }
1350  }
1351}
1352
1353/// "menu_get(path [, modes])" function
1354static void f_menu_get(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1355{
1356  tv_list_alloc_ret(rettv, kListLenMayKnow);
1357  int modes = MENU_ALL_MODES;
1358  if (argvars[1].v_type == VAR_STRING) {
1359    const char *const strmodes = tv_get_string(&argvars[1]);
1360    modes = get_menu_cmd_modes(strmodes, false, NULL, NULL);
1361  }
1362  menu_get((char *)tv_get_string(&argvars[0]), modes, rettv->vval.v_list);
1363}
1364
1365/// "expandcmd()" function
1366/// Expand all the special characters in a command string.
1367static void f_expandcmd(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1368{
1369  const char *errormsg = NULL;
1370  bool emsgoff = true;
1371
1372  if (argvars[1].v_type == VAR_DICT
1373      && tv_dict_get_bool(argvars[1].vval.v_dict, "errmsg", kBoolVarFalse)) {
1374    emsgoff = false;
1375  }
1376
1377  rettv->v_type = VAR_STRING;
1378  char *cmdstr = xstrdup(tv_get_string(&argvars[0]));
1379
1380  exarg_T eap = {
1381    .cmd = cmdstr,
1382    .arg = cmdstr,
1383    .usefilter = false,
1384    .nextcmd = NULL,
1385    .cmdidx = CMD_USER,
1386  };
1387  eap.argt |= EX_NOSPC;
1388
1389  if (emsgoff) {
1390    emsg_off++;
1391  }
1392  if (expand_filename(&eap, &cmdstr, &errormsg) == FAIL) {
1393    if (!emsgoff && errormsg != NULL && *errormsg != NUL) {
1394      emsg(errormsg);
1395    }
1396  }
1397  if (emsgoff) {
1398    emsg_off--;
1399  }
1400
1401  rettv->vval.v_string = cmdstr;
1402}
1403
1404/// "flatten()" and "flattennew()" functions
1405static void flatten_common(typval_T *argvars, typval_T *rettv, bool make_copy)
1406{
1407  bool error = false;
1408
1409  if (argvars[0].v_type != VAR_LIST) {
1410    semsg(_(e_listarg), "flatten()");
1411    return;
1412  }
1413
1414  int maxdepth;
1415  if (argvars[1].v_type == VAR_UNKNOWN) {
1416    maxdepth = 999999;
1417  } else {
1418    maxdepth = (int)tv_get_number_chk(&argvars[1], &error);
1419    if (error) {
1420      return;
1421    }
1422    if (maxdepth < 0) {
1423      emsg(_("E900: maxdepth must be non-negative number"));
1424      return;
1425    }
1426  }
1427
1428  list_T *list = argvars[0].vval.v_list;
1429  rettv->v_type = VAR_LIST;
1430  rettv->vval.v_list = list;
1431  if (list == NULL) {
1432    return;
1433  }
1434
1435  if (make_copy) {
1436    list = tv_list_copy(NULL, list, false, get_copyID());
1437    rettv->vval.v_list = list;
1438    if (list == NULL) {
1439      return;
1440    }
1441  } else {
1442    if (value_check_lock(tv_list_locked(list), N_("flatten() argument"), TV_TRANSLATE)) {
1443      return;
1444    }
1445    tv_list_ref(list);
1446  }
1447
1448  tv_list_flatten(list, NULL, tv_list_len(list), maxdepth);
1449}
1450
1451/// "flatten(list[, {maxdepth}])" function
1452static void f_flatten(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1453{
1454  flatten_common(argvars, rettv, false);
1455}
1456
1457/// "flattennew(list[, {maxdepth}])" function
1458static void f_flattennew(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1459{
1460  flatten_common(argvars, rettv, true);
1461}
1462
1463/// "feedkeys()" function
1464static void f_feedkeys(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1465{
1466  // This is not allowed in the sandbox.  If the commands would still be
1467  // executed in the sandbox it would be OK, but it probably happens later,
1468  // when "sandbox" is no longer set.
1469  if (check_secure()) {
1470    return;
1471  }
1472
1473  const char *const keys = tv_get_string(&argvars[0]);
1474  char nbuf[NUMBUFLEN];
1475  const char *flags = NULL;
1476  if (argvars[1].v_type != VAR_UNKNOWN) {
1477    flags = tv_get_string_buf(&argvars[1], nbuf);
1478  }
1479
1480  nvim_feedkeys(cstr_as_string(keys),
1481                cstr_as_string(flags), true);
1482}
1483
1484/// "float2nr({float})" function
1485static void f_float2nr(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1486{
1487  float_T f;
1488
1489  if (!tv_get_float_chk(argvars, &f)) {
1490    return;
1491  }
1492
1493  if (f <= (float_T)(-VARNUMBER_MAX) + DBL_EPSILON) {
1494    rettv->vval.v_number = -VARNUMBER_MAX;
1495  } else if (f >= (float_T)VARNUMBER_MAX - DBL_EPSILON) {
1496    rettv->vval.v_number = VARNUMBER_MAX;
1497  } else {
1498    rettv->vval.v_number = (varnumber_T)f;
1499  }
1500}
1501
1502/// "fmod()" function
1503static void f_fmod(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1504{
1505  float_T fx;
1506  float_T fy;
1507
1508  rettv->v_type = VAR_FLOAT;
1509  if (tv_get_float_chk(argvars, &fx) && tv_get_float_chk(&argvars[1], &fy)) {
1510    rettv->vval.v_float = fmod(fx, fy);
1511  } else {
1512    rettv->vval.v_float = 0.0;
1513  }
1514}
1515
1516/// "fnameescape({string})" function
1517static void f_fnameescape(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1518{
1519  rettv->vval.v_string = vim_strsave_fnameescape(tv_get_string(&argvars[0]), VSE_NONE);
1520  rettv->v_type = VAR_STRING;
1521}
1522
1523/// "foreground()" function
1524static void f_foreground(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1525{
1526}
1527
1528/// "function()" function
1529/// "funcref()" function
1530static void common_function(typval_T *argvars, typval_T *rettv, bool is_funcref)
1531{
1532  char *s;
1533  char *name;
1534  bool use_string = false;
1535  partial_T *arg_pt = NULL;
1536  char *trans_name = NULL;
1537
1538  if (argvars[0].v_type == VAR_FUNC) {
1539    // function(MyFunc, [arg], dict)
1540    s = argvars[0].vval.v_string;
1541  } else if (argvars[0].v_type == VAR_PARTIAL
1542             && argvars[0].vval.v_partial != NULL) {
1543    // function(dict.MyFunc, [arg])
1544    arg_pt = argvars[0].vval.v_partial;
1545    s = partial_name(arg_pt);
1546    // TODO(bfredl): do the entire nlua_is_table_from_lua dance
1547  } else {
1548    // function('MyFunc', [arg], dict)
1549    s = (char *)tv_get_string(&argvars[0]);
1550    use_string = true;
1551  }
1552
1553  if ((use_string && vim_strchr(s, AUTOLOAD_CHAR) == NULL) || is_funcref) {
1554    name = s;
1555    trans_name = save_function_name(&name, false,
1556                                    TFN_INT | TFN_QUIET | TFN_NO_AUTOLOAD | TFN_NO_DEREF, NULL);
1557    if (*name != NUL) {
1558      s = NULL;
1559    }
1560  }
1561  if (s == NULL || *s == NUL || (use_string && ascii_isdigit(*s))
1562      || (is_funcref && trans_name == NULL)) {
1563    semsg(_(e_invarg2), (use_string ? tv_get_string(&argvars[0]) : s));
1564    // Don't check an autoload name for existence here.
1565  } else if (trans_name != NULL
1566             && (is_funcref
1567                 ? find_func(trans_name) == NULL
1568                 : !translated_function_exists(trans_name))) {
1569    semsg(_("E700: Unknown function: %s"), s);
1570  } else {
1571    int dict_idx = 0;
1572    int arg_idx = 0;
1573    list_T *list = NULL;
1574    if (strncmp(s, "s:", 2) == 0 || strncmp(s, "<SID>", 5) == 0) {
1575      // Expand s: and <SID> into <SNR>nr_, so that the function can
1576      // also be called from another script. Using trans_function_name()
1577      // would also work, but some plugins depend on the name being
1578      // printable text.
1579      name = get_scriptlocal_funcname(s);
1580    } else {
1581      name = xstrdup(s);
1582    }
1583
1584    if (argvars[1].v_type != VAR_UNKNOWN) {
1585      if (argvars[2].v_type != VAR_UNKNOWN) {
1586        // function(name, [args], dict)
1587        arg_idx = 1;
1588        dict_idx = 2;
1589      } else if (argvars[1].v_type == VAR_DICT) {
1590        // function(name, dict)
1591        dict_idx = 1;
1592      } else {
1593        // function(name, [args])
1594        arg_idx = 1;
1595      }
1596      if (dict_idx > 0) {
1597        if (tv_check_for_dict_arg(argvars, dict_idx) == FAIL) {
1598          xfree(name);
1599          goto theend;
1600        }
1601        if (argvars[dict_idx].vval.v_dict == NULL) {
1602          dict_idx = 0;
1603        }
1604      }
1605      if (arg_idx > 0) {
1606        if (argvars[arg_idx].v_type != VAR_LIST) {
1607          emsg(_("E923: Second argument of function() must be "
1608                 "a list or a dict"));
1609          xfree(name);
1610          goto theend;
1611        }
1612        list = argvars[arg_idx].vval.v_list;
1613        if (tv_list_len(list) == 0) {
1614          arg_idx = 0;
1615        } else if (tv_list_len(list) > MAX_FUNC_ARGS) {
1616          emsg_funcname(e_toomanyarg, s);
1617          xfree(name);
1618          goto theend;
1619        }
1620      }
1621    }
1622    if (dict_idx > 0 || arg_idx > 0 || arg_pt != NULL || is_funcref) {
1623      partial_T *const pt = xcalloc(1, sizeof(*pt));
1624
1625      // result is a VAR_PARTIAL
1626      if (arg_idx > 0 || (arg_pt != NULL && arg_pt->pt_argc > 0)) {
1627        const int arg_len = (arg_pt == NULL ? 0 : arg_pt->pt_argc);
1628        const int lv_len = tv_list_len(list);
1629
1630        pt->pt_argc = arg_len + lv_len;
1631        pt->pt_argv = xmalloc(sizeof(pt->pt_argv[0]) * (size_t)pt->pt_argc);
1632        int i = 0;
1633        for (; i < arg_len; i++) {
1634          tv_copy(&arg_pt->pt_argv[i], &pt->pt_argv[i]);
1635        }
1636        if (lv_len > 0) {
1637          TV_LIST_ITER(list, li, {
1638            tv_copy(TV_LIST_ITEM_TV(li), &pt->pt_argv[i++]);
1639          });
1640        }
1641      }
1642
1643      // For "function(dict.func, [], dict)" and "func" is a partial
1644      // use "dict". That is backwards compatible.
1645      if (dict_idx > 0) {
1646        // The dict is bound explicitly, pt_auto is false
1647        pt->pt_dict = argvars[dict_idx].vval.v_dict;
1648        (pt->pt_dict->dv_refcount)++;
1649      } else if (arg_pt != NULL) {
1650        // If the dict was bound automatically the result is also
1651        // bound automatically.
1652        pt->pt_dict = arg_pt->pt_dict;
1653        pt->pt_auto = arg_pt->pt_auto;
1654        if (pt->pt_dict != NULL) {
1655          (pt->pt_dict->dv_refcount)++;
1656        }
1657      }
1658
1659      pt->pt_refcount = 1;
1660      if (arg_pt != NULL && arg_pt->pt_func != NULL) {
1661        pt->pt_func = arg_pt->pt_func;
1662        func_ptr_ref(pt->pt_func);
1663        xfree(name);
1664      } else if (is_funcref) {
1665        pt->pt_func = find_func(trans_name);
1666        func_ptr_ref(pt->pt_func);
1667        xfree(name);
1668      } else {
1669        pt->pt_name = name;
1670        func_ref(name);
1671      }
1672
1673      rettv->v_type = VAR_PARTIAL;
1674      rettv->vval.v_partial = pt;
1675    } else {
1676      // result is a VAR_FUNC
1677      rettv->v_type = VAR_FUNC;
1678      rettv->vval.v_string = name;
1679      func_ref(name);
1680    }
1681  }
1682theend:
1683  xfree(trans_name);
1684}
1685
1686static void f_funcref(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1687{
1688  common_function(argvars, rettv, true);
1689}
1690
1691static void f_function(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1692{
1693  common_function(argvars, rettv, false);
1694}
1695
1696/// "garbagecollect()" function
1697static void f_garbagecollect(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1698{
1699  // This is postponed until we are back at the toplevel, because we may be
1700  // using Lists and Dicts internally.  E.g.: ":echo [garbagecollect()]".
1701  want_garbage_collect = true;
1702
1703  if (argvars[0].v_type != VAR_UNKNOWN && tv_get_bool(&argvars[0]) == 1) {
1704    garbage_collect_at_exit = true;
1705  }
1706}
1707
1708/// "get()" function
1709static void f_get(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1710{
1711  typval_T *tv = NULL;
1712  bool what_is_dict = false;
1713
1714  if (argvars[0].v_type == VAR_BLOB) {
1715    bool error = false;
1716    int idx = (int)tv_get_number_chk(&argvars[1], &error);
1717
1718    if (!error) {
1719      rettv->v_type = VAR_NUMBER;
1720      if (idx < 0) {
1721        idx = tv_blob_len(argvars[0].vval.v_blob) + idx;
1722      }
1723      if (idx < 0 || idx >= tv_blob_len(argvars[0].vval.v_blob)) {
1724        rettv->vval.v_number = -1;
1725      } else {
1726        rettv->vval.v_number = tv_blob_get(argvars[0].vval.v_blob, idx);
1727        tv = rettv;
1728      }
1729    }
1730  } else if (argvars[0].v_type == VAR_LIST) {
1731    list_T *l = argvars[0].vval.v_list;
1732    if (l != NULL) {
1733      bool error = false;
1734
1735      listitem_T *li = tv_list_find(l, (int)tv_get_number_chk(&argvars[1], &error));
1736      if (!error && li != NULL) {
1737        tv = TV_LIST_ITEM_TV(li);
1738      }
1739    }
1740  } else if (argvars[0].v_type == VAR_DICT) {
1741    dict_T *d = argvars[0].vval.v_dict;
1742    if (d != NULL) {
1743      dictitem_T *di = tv_dict_find(d, tv_get_string(&argvars[1]), -1);
1744      if (di != NULL) {
1745        tv = &di->di_tv;
1746      }
1747    }
1748  } else if (tv_is_func(argvars[0])) {
1749    partial_T *pt;
1750    partial_T fref_pt;
1751
1752    if (argvars[0].v_type == VAR_PARTIAL) {
1753      pt = argvars[0].vval.v_partial;
1754    } else {
1755      CLEAR_FIELD(fref_pt);
1756      fref_pt.pt_name = argvars[0].vval.v_string;
1757      pt = &fref_pt;
1758    }
1759
1760    if (pt != NULL) {
1761      const char *const what = tv_get_string(&argvars[1]);
1762
1763      if (strcmp(what, "func") == 0 || strcmp(what, "name") == 0) {
1764        const char *name = partial_name(pt);
1765        rettv->v_type = (*what == 'f' ? VAR_FUNC : VAR_STRING);
1766        assert(name != NULL);
1767        if (rettv->v_type == VAR_FUNC) {
1768          func_ref((char *)name);
1769        }
1770        if (*what == 'n' && pt->pt_name == NULL && pt->pt_func != NULL) {
1771          // use <SNR> instead of the byte code
1772          name = printable_func_name(pt->pt_func);
1773        }
1774        rettv->vval.v_string = xstrdup(name);
1775      } else if (strcmp(what, "dict") == 0) {
1776        what_is_dict = true;
1777        if (pt->pt_dict != NULL) {
1778          tv_dict_set_ret(rettv, pt->pt_dict);
1779        }
1780      } else if (strcmp(what, "args") == 0) {
1781        rettv->v_type = VAR_LIST;
1782        tv_list_alloc_ret(rettv, pt->pt_argc);
1783        for (int i = 0; i < pt->pt_argc; i++) {
1784          tv_list_append_tv(rettv->vval.v_list, &pt->pt_argv[i]);
1785        }
1786      } else if (strcmp(what, "arity") == 0) {
1787        int required = 0;
1788        int optional = 0;
1789        bool varargs = false;
1790        const char *name = partial_name(pt);
1791
1792        get_func_arity(name, &required, &optional, &varargs);
1793
1794        rettv->v_type = VAR_DICT;
1795        tv_dict_alloc_ret(rettv);
1796        dict_T *dict = rettv->vval.v_dict;
1797
1798        // Take into account the arguments of the partial, if any.
1799        // Note that it is possible to supply more arguments than the function
1800        // accepts.
1801        if (pt->pt_argc >= required + optional) {
1802          required = optional = 0;
1803        } else if (pt->pt_argc > required) {
1804          optional -= pt->pt_argc - required;
1805          required = 0;
1806        } else {
1807          required -= pt->pt_argc;
1808        }
1809
1810        tv_dict_add_nr(dict, S_LEN("required"), required);
1811        tv_dict_add_nr(dict, S_LEN("optional"), optional);
1812        tv_dict_add_bool(dict, S_LEN("varargs"), varargs);
1813      } else {
1814        semsg(_(e_invarg2), what);
1815      }
1816
1817      // When {what} == "dict" and pt->pt_dict == NULL, evaluate the
1818      // third argument
1819      if (!what_is_dict) {
1820        return;
1821      }
1822    }
1823  } else {
1824    semsg(_(e_listdictblobarg), "get()");
1825  }
1826
1827  if (tv == NULL) {
1828    if (argvars[2].v_type != VAR_UNKNOWN) {
1829      tv_copy(&argvars[2], rettv);
1830    }
1831  } else {
1832    tv_copy(tv, rettv);
1833  }
1834}
1835
1836/// "getchangelist()" function
1837static void f_getchangelist(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1838{
1839  tv_list_alloc_ret(rettv, 2);
1840
1841  const buf_T *buf;
1842  if (argvars[0].v_type == VAR_UNKNOWN) {
1843    buf = curbuf;
1844  } else {
1845    vim_ignored = (int)tv_get_number(&argvars[0]);  // issue errmsg if type error
1846    emsg_off++;
1847    buf = tv_get_buf(&argvars[0], false);
1848    emsg_off--;
1849  }
1850  if (buf == NULL) {
1851    return;
1852  }
1853
1854  list_T *const l = tv_list_alloc(buf->b_changelistlen);
1855  tv_list_append_list(rettv->vval.v_list, l);
1856  // The current window change list index tracks only the position for the
1857  // current buffer. For other buffers use the stored index for the current
1858  // window, or, if that's not available, the change list length.
1859  int changelistindex;
1860  if (buf == curwin->w_buffer) {
1861    changelistindex = curwin->w_changelistidx;
1862  } else {
1863    changelistindex = buf->b_changelistlen;
1864
1865    for (size_t i = 0; i < kv_size(buf->b_wininfo); i++) {
1866      WinInfo *wip = kv_A(buf->b_wininfo, i);
1867      if (wip->wi_win == curwin) {
1868        changelistindex = wip->wi_changelistidx;
1869        break;
1870      }
1871    }
1872  }
1873  tv_list_append_number(rettv->vval.v_list, (varnumber_T)changelistindex);
1874
1875  for (int i = 0; i < buf->b_changelistlen; i++) {
1876    if (buf->b_changelist[i].mark.lnum == 0) {
1877      continue;
1878    }
1879    dict_T *const d = tv_dict_alloc();
1880    tv_list_append_dict(l, d);
1881    tv_dict_add_nr(d, S_LEN("lnum"), buf->b_changelist[i].mark.lnum);
1882    tv_dict_add_nr(d, S_LEN("col"), buf->b_changelist[i].mark.col);
1883    tv_dict_add_nr(d, S_LEN("coladd"), buf->b_changelist[i].mark.coladd);
1884  }
1885}
1886
1887static void getpos_both(typval_T *argvars, typval_T *rettv, bool getcurpos, bool charcol)
1888{
1889  pos_T *fp = NULL;
1890  pos_T pos;
1891  win_T *wp = curwin;
1892  int fnum = -1;
1893
1894  if (getcurpos) {
1895    if (argvars[0].v_type != VAR_UNKNOWN) {
1896      wp = find_win_by_nr_or_id(&argvars[0]);
1897      if (wp != NULL) {
1898        fp = &wp->w_cursor;
1899      }
1900    } else {
1901      fp = &curwin->w_cursor;
1902    }
1903    if (fp != NULL && charcol) {
1904      pos = *fp;
1905      pos.col = buf_byteidx_to_charidx(wp->w_buffer, pos.lnum, pos.col);
1906      fp = &pos;
1907    }
1908  } else {
1909    fp = var2fpos(&argvars[0], true, &fnum, charcol, curwin);
1910  }
1911
1912  list_T *const l = tv_list_alloc_ret(rettv, 4 + getcurpos);
1913  tv_list_append_number(l, (fnum != -1) ? (varnumber_T)fnum : (varnumber_T)0);
1914  tv_list_append_number(l, ((fp != NULL) ? (varnumber_T)fp->lnum : (varnumber_T)0));
1915  tv_list_append_number(l, ((fp != NULL)
1916                            ? (varnumber_T)(fp->col == MAXCOL ? MAXCOL : fp->col + 1)
1917                            : (varnumber_T)0));
1918  tv_list_append_number(l, (fp != NULL) ? (varnumber_T)fp->coladd : (varnumber_T)0);
1919  if (getcurpos) {
1920    const bool save_set_curswant = curwin->w_set_curswant;
1921    const colnr_T save_curswant = curwin->w_curswant;
1922    const colnr_T save_virtcol = curwin->w_virtcol;
1923
1924    if (wp == curwin) {
1925      update_curswant();
1926    }
1927    tv_list_append_number(l, (wp == NULL) ? 0 : ((wp->w_curswant == MAXCOL)
1928                                                 ? (varnumber_T)MAXCOL
1929                                                 : (varnumber_T)wp->w_curswant + 1));
1930
1931    // Do not change "curswant", as it is unexpected that a get
1932    // function has a side effect.
1933    if (wp == curwin && save_set_curswant) {
1934      curwin->w_set_curswant = save_set_curswant;
1935      curwin->w_curswant = save_curswant;
1936      curwin->w_virtcol = save_virtcol;
1937      curwin->w_valid &= ~VALID_VIRTCOL;
1938    }
1939  }
1940}
1941
1942/// "getcharpos()" function
1943static void f_getcharpos(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1944{
1945  getpos_both(argvars, rettv, false, true);
1946}
1947
1948/// "getcharsearch()" function
1949static void f_getcharsearch(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1950{
1951  tv_dict_alloc_ret(rettv);
1952
1953  dict_T *dict = rettv->vval.v_dict;
1954
1955  tv_dict_add_str(dict, S_LEN("char"), last_csearch());
1956  tv_dict_add_nr(dict, S_LEN("forward"), last_csearch_forward());
1957  tv_dict_add_nr(dict, S_LEN("until"), last_csearch_until());
1958}
1959
1960/// "getfontname()" function
1961static void f_getfontname(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1962{
1963  rettv->v_type = VAR_STRING;
1964  rettv->vval.v_string = NULL;
1965}
1966
1967/// "getjumplist()" function
1968static void f_getjumplist(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1969{
1970  tv_list_alloc_ret(rettv, kListLenMayKnow);
1971  win_T *const wp = find_tabwin(&argvars[0], &argvars[1]);
1972  if (wp == NULL) {
1973    return;
1974  }
1975
1976  cleanup_jumplist(wp, true);
1977
1978  list_T *const l = tv_list_alloc(wp->w_jumplistlen);
1979  tv_list_append_list(rettv->vval.v_list, l);
1980  tv_list_append_number(rettv->vval.v_list, wp->w_jumplistidx);
1981
1982  for (int i = 0; i < wp->w_jumplistlen; i++) {
1983    if (wp->w_jumplist[i].fmark.mark.lnum == 0) {
1984      continue;
1985    }
1986    dict_T *const d = tv_dict_alloc();
1987    tv_list_append_dict(l, d);
1988    tv_dict_add_nr(d, S_LEN("lnum"), wp->w_jumplist[i].fmark.mark.lnum);
1989    tv_dict_add_nr(d, S_LEN("col"), wp->w_jumplist[i].fmark.mark.col);
1990    tv_dict_add_nr(d, S_LEN("coladd"), wp->w_jumplist[i].fmark.mark.coladd);
1991    tv_dict_add_nr(d, S_LEN("bufnr"), wp->w_jumplist[i].fmark.fnum);
1992    if (wp->w_jumplist[i].fname != NULL) {
1993      tv_dict_add_str(d, S_LEN("filename"), wp->w_jumplist[i].fname);
1994    }
1995  }
1996}
1997
1998/// "getmarklist()" function
1999static void f_getmarklist(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
2000{
2001  tv_list_alloc_ret(rettv, kListLenMayKnow);
2002
2003  if (argvars[0].v_type == VAR_UNKNOWN) {
2004    get_global_marks(rettv->vval.v_list);
2005    return;
2006  }
2007
2008  buf_T *buf = tv_get_buf(&argvars[0], false);
2009  if (buf == NULL) {
2010    return;
2011  }
2012
2013  get_buf_local_marks(buf, rettv->vval.v_list);
2014}
2015
2016/// "getpid()" function
2017static void f_getpid(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
2018{
2019  rettv->vval.v_number = os_get_pid();
2020}
2021
2022/// "getcurpos(string)" function
2023static void f_getcurpos(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
2024{
2025  getpos_both(argvars, rettv, true, false);
2026}
2027
2028static void f_getcursorcharpos(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
2029{
2030  getpos_both(argvars, rettv, true, true);
2031}
2032
2033/// "getpos(string)" function
2034static void f_getpos(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
2035{
2036  getpos_both(argvars, rettv, false, false);
2037}
2038
2039/// Convert from block_def to string
2040static String block_def2str(struct block_def *bd)
2041{
2042  size_t size = (size_t)bd->startspaces + (size_t)bd->endspaces + (size_t)bd->textlen;
2043  String ret = { .data = xmalloc(size + 1) };
2044
2045  memset(ret.data, ' ', (size_t)bd->startspaces);
2046  ret.size += (size_t)bd->startspaces;
2047  memmove(ret.data + ret.size, bd->textstart, (size_t)bd->textlen);
2048  ret.size += (size_t)bd->textlen;
2049  memset(ret.data + ret.size, ' ', (size_t)bd->endspaces);
2050  ret.size += (size_t)bd->endspaces;
2051  ret.data[ret.size] = NUL;
2052
2053  return ret;
2054}
2055
2056static int getregionpos(typval_T *argvars, typval_T *rettv, pos_T *p1, pos_T *p2,
2057                        bool *const inclusive, MotionType *region_type, oparg_T *oap)
2058  FUNC_ATTR_NONNULL_ALL
2059{
2060  tv_list_alloc_ret(rettv, kListLenMayKnow);
2061
2062  if (tv_check_for_list_arg(argvars, 0) == FAIL
2063      || tv_check_for_list_arg(argvars, 1) == FAIL
2064      || tv_check_for_opt_dict_arg(argvars, 2) == FAIL) {
2065    return FAIL;
2066  }
2067
2068  int fnum1 = -1;
2069  int fnum2 = -1;
2070  if (list2fpos(&argvars[0], p1, &fnum1, NULL, false) != OK
2071      || list2fpos(&argvars[1], p2, &fnum2, NULL, false) != OK
2072      || fnum1 != fnum2) {
2073    return FAIL;
2074  }
2075
2076  bool is_select_exclusive;
2077  char *type;
2078  char default_type[] = "v";
2079  if (argvars[2].v_type == VAR_DICT) {
2080    is_select_exclusive = tv_dict_get_bool(argvars[2].vval.v_dict, "exclusive",
2081                                           *p_sel == 'e');
2082    type = tv_dict_get_string(argvars[2].vval.v_dict, "type", false);
2083    if (type == NULL) {
2084      type = default_type;
2085    }
2086  } else {
2087    is_select_exclusive = *p_sel == 'e';
2088    type = default_type;
2089  }
2090
2091  int block_width = 0;
2092  if (type[0] == 'v' && type[1] == NUL) {
2093    *region_type = kMTCharWise;
2094  } else if (type[0] == 'V' && type[1] == NUL) {
2095    *region_type = kMTLineWise;
2096  } else if (type[0] == Ctrl_V) {
2097    char *p = type + 1;
2098    if (*p != NUL && ((block_width = getdigits_int(&p, false, 0)) <= 0 || *p != NUL)) {
2099      semsg(_(e_invargNval), "type", type);
2100      return FAIL;
2101    }
2102    *region_type = kMTBlockWise;
2103  } else {
2104    semsg(_(e_invargNval), "type", type);
2105    return FAIL;
2106  }
2107
2108  buf_T *findbuf = fnum1 != 0 ? buflist_findnr(fnum1) : curbuf;
2109  if (findbuf == NULL || findbuf->b_ml.ml_mfp == NULL) {
2110    emsg(_(e_buffer_is_not_loaded));
2111    return FAIL;
2112  }
2113
2114  if (p1->lnum < 1 || p1->lnum > findbuf->b_ml.ml_line_count) {
2115    semsg(_(e_invalid_line_number_nr), p1->lnum);
2116    return FAIL;
2117  }
2118  if (p1->col == MAXCOL) {
2119    p1->col = ml_get_buf_len(findbuf, p1->lnum) + 1;
2120  } else if (p1->col < 1 || p1->col > ml_get_buf_len(findbuf, p1->lnum) + 1) {
2121    semsg(_(e_invalid_column_number_nr), p1->col);
2122    return FAIL;
2123  }
2124
2125  if (p2->lnum < 1 || p2->lnum > findbuf->b_ml.ml_line_count) {
2126    semsg(_(e_invalid_line_number_nr), p2->lnum);
2127    return FAIL;
2128  }
2129  if (p2->col == MAXCOL) {
2130    p2->col = ml_get_buf_len(findbuf, p2->lnum) + 1;
2131  } else if (p2->col < 1 || p2->col > ml_get_buf_len(findbuf, p2->lnum) + 1) {
2132    semsg(_(e_invalid_column_number_nr), p2->col);
2133    return FAIL;
2134  }
2135
2136  curbuf = findbuf;
2137  curwin->w_buffer = curbuf;
2138  virtual_op = virtual_active(curwin);
2139
2140  // NOTE: Adjustment is needed.
2141  p1->col--;
2142  p2->col--;
2143
2144  getregionpos_prep(p1, p2, *region_type, is_select_exclusive, block_width, inclusive, oap);
2145  return OK;
2146}
2147
2148/// "getregion()" function
2149static void f_getregion(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
2150{
2151  buf_T *const save_curbuf = curbuf;
2152  const TriState save_virtual = virtual_op;
2153
2154  pos_T p1, p2;
2155  bool inclusive = true;
2156  MotionType region_type = kMTUnknown;
2157  oparg_T oa;
2158
2159  if (getregionpos(argvars, rettv, &p1, &p2, &inclusive, &region_type, &oa) == FAIL) {
2160    return;
2161  }
2162
2163  for (linenr_T lnum = p1.lnum; lnum <= p2.lnum; lnum++) {
2164    String akt = STRING_INIT;
2165
2166    if (region_type == kMTBlockWise) {
2167      struct block_def bd;
2168      block_prep(&oa, &bd, lnum, false);
2169      akt = block_def2str(&bd);
2170    } else if (region_type == kMTLineWise || (p1.lnum < lnum && lnum < p2.lnum)) {
2171      akt = cbuf_to_string(ml_get(lnum), (size_t)ml_get_len(lnum));
2172    } else {
2173      struct block_def bd;
2174      charwise_block_prep(p1, p2, &bd, lnum, inclusive);
2175      akt = block_def2str(&bd);
2176    }
2177
2178    assert(akt.data != NULL);
2179    tv_list_append_allocated_string(rettv->vval.v_list, akt.data);
2180  }
2181
2182  // getregionpos() may change curbuf and virtual_op
2183  curbuf = save_curbuf;
2184  curwin->w_buffer = curbuf;
2185  virtual_op = save_virtual;
2186}
2187
2188static void add_regionpos_range(typval_T *rettv, pos_T p1, pos_T p2)
2189{
2190  list_T *l1 = tv_list_alloc(2);
2191  tv_list_append_list(rettv->vval.v_list, l1);
2192
2193  list_T *l2 = tv_list_alloc(4);
2194  tv_list_append_list(l1, l2);
2195
2196  list_T *l3 = tv_list_alloc(4);
2197  tv_list_append_list(l1, l3);
2198
2199  tv_list_append_number(l2, curbuf->b_fnum);
2200  tv_list_append_number(l2, p1.lnum);
2201  tv_list_append_number(l2, p1.col);
2202  tv_list_append_number(l2, p1.coladd);
2203
2204  tv_list_append_number(l3, curbuf->b_fnum);
2205  tv_list_append_number(l3, p2.lnum);
2206  tv_list_append_number(l3, p2.col);
2207  tv_list_append_number(l3, p2.coladd);
2208}
2209
2210/// "getregionpos()" function
2211static void f_getregionpos(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
2212{
2213  buf_T *const save_curbuf = curbuf;
2214  const TriState save_virtual = virtual_op;
2215
2216  pos_T p1, p2;
2217  bool inclusive = true;
2218  MotionType region_type = kMTUnknown;
2219  bool allow_eol = false;
2220  bool bounds_only = false;
2221  oparg_T oa;
2222
2223  if (getregionpos(argvars, rettv, &p1, &p2, &inclusive, &region_type, &oa) == FAIL) {
2224    return;
2225  }
2226
2227  if (argvars[2].v_type == VAR_DICT) {
2228    allow_eol = tv_dict_get_bool(argvars[2].vval.v_dict, "eol", false);
2229    bounds_only = tv_dict_get_bool(argvars[2].vval.v_dict, "bounds", false);
2230  }
2231
2232  if (bounds_only) {
2233    // Only the outer bounds of the region are wanted, so the lines in
2234    // between do not have to be visited.
2235    pos_T start_pos, end_pos;
2236
2237    getregionpos_line(p1.lnum, p1, p2, inclusive, region_type, &oa,
2238                      allow_eol, &start_pos, &end_pos);
2239    if (p2.lnum != p1.lnum) {
2240      pos_T unused;
2241
2242      getregionpos_line(p2.lnum, p1, p2, inclusive, region_type, &oa,
2243                        allow_eol, &unused, &end_pos);
2244    }
2245    add_regionpos_range(rettv, start_pos, end_pos);
2246  } else {
2247    for (linenr_T lnum = p1.lnum; lnum <= p2.lnum; lnum++) {
2248      pos_T ret_p1, ret_p2;
2249
2250      getregionpos_line(lnum, p1, p2, inclusive, region_type, &oa,
2251                        allow_eol, &ret_p1, &ret_p2);
2252      add_regionpos_range(rettv, ret_p1, ret_p2);
2253    }
2254  }
2255
2256  // getregionpos() may change curbuf and virtual_op
2257  curbuf = save_curbuf;
2258  curwin->w_buffer = curbuf;
2259  virtual_op = save_virtual;
2260}
2261
2262/// Common between getreg(), getreginfo() and getregtype(): get the register
2263/// name from the first argument.
2264/// Returns zero on error.
2265static int getreg_get_regname(typval_T *argvars)
2266{
2267  const char *strregname;
2268
2269  if (argvars[0].v_type != VAR_UNKNOWN) {
2270    strregname = tv_get_string_chk(&argvars[0]);
2271    if (strregname == NULL) {  // type error; errmsg already given
2272      return 0;
2273    }
2274  } else {
2275    // Default to v:register
2276    strregname = get_vim_var_str(VV_REG);
2277  }
2278
2279  return *strregname == 0 ? '"' : (uint8_t)(*strregname);
2280}
2281
2282/// "getreg()" function
2283static void f_getreg(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
2284{
2285  int arg2 = false;
2286  bool return_list = false;
2287
2288  int regname = getreg_get_regname(argvars);
2289  if (regname == 0) {
2290    return;
2291  }
2292
2293  if (argvars[0].v_type != VAR_UNKNOWN && argvars[1].v_type != VAR_UNKNOWN) {
2294    bool error = false;
2295    arg2 = (int)tv_get_bool_chk(&argvars[1], &error);
2296    if (!error && argvars[2].v_type != VAR_UNKNOWN) {
2297      return_list = (bool)tv_get_bool_chk(&argvars[2], &error);
2298    }
2299    if (error) {
2300      return;
2301    }
2302  }
2303
2304  if (return_list) {
2305    rettv->v_type = VAR_LIST;
2306    rettv->vval.v_list =
2307      get_reg_contents(regname, (arg2 ? kGRegExprSrc : 0) | kGRegList);
2308    if (rettv->vval.v_list == NULL) {
2309      rettv->vval.v_list = tv_list_alloc(0);
2310    }
2311    tv_list_ref(rettv->vval.v_list);
2312  } else {
2313    rettv->v_type = VAR_STRING;
2314    rettv->vval.v_string = get_reg_contents(regname, arg2 ? kGRegExprSrc : 0);
2315  }
2316}
2317
2318/// "getregtype()" function
2319static void f_getregtype(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
2320{
2321  // on error return an empty string
2322  rettv->v_type = VAR_STRING;
2323  rettv->vval.v_string = NULL;
2324
2325  int regname = getreg_get_regname(argvars);
2326  if (regname == 0) {
2327    return;
2328  }
2329
2330  colnr_T reglen = 0;
2331  char buf[NUMBUFLEN + 2];
2332  MotionType reg_type = get_reg_type(regname, &reglen);
2333  format_reg_type(reg_type, reglen, buf, ARRAY_SIZE(buf));
2334
2335  rettv->vval.v_string = xstrdup(buf);
2336}
2337
2338/// "gettagstack()" function
2339static void f_gettagstack(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
2340{
2341  win_T *wp = curwin;                  // default is current window
2342
2343  tv_dict_alloc_ret(rettv);
2344
2345  if (argvars[0].v_type != VAR_UNKNOWN) {
2346    wp = find_win_by_nr_or_id(&argvars[0]);
2347    if (wp == NULL) {
2348      return;
2349    }
2350  }
2351
2352  get_tagstack(wp, rettv->vval.v_dict);
2353}
2354
2355/// Dummy timer callback. Used by f_wait().
2356static void dummy_timer_due_cb(TimeWatcher *tw, void *data)
2357{
2358  // If the main loop is closing, the condition won't be checked again.
2359  // Close the timer to avoid leaking resources.
2360  if (main_loop.closing) {
2361    time_watcher_stop(tw);
2362    time_watcher_close(tw, dummy_timer_close_cb);
2363  }
2364}
2365
2366/// Dummy timer close callback. Used by f_wait().
2367static void dummy_timer_close_cb(TimeWatcher *tw, void *data)
2368{
2369  xfree(tw);
2370}
2371
2372/// "wait(timeout, condition[, interval])" function
2373static void f_wait(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
2374{
2375  rettv->v_type = VAR_NUMBER;
2376  rettv->vval.v_number = -1;
2377
2378  if (argvars[0].v_type != VAR_NUMBER) {
2379    semsg(_(e_invargval), "1");
2380    return;
2381  }
2382  if ((argvars[2].v_type != VAR_NUMBER && argvars[2].v_type != VAR_UNKNOWN)
2383      || (argvars[2].v_type == VAR_NUMBER && argvars[2].vval.v_number <= 0)) {
2384    semsg(_(e_invargval), "3");
2385    return;
2386  }
2387
2388  int timeout = (int)argvars[0].vval.v_number;
2389  typval_T expr = argvars[1];
2390  int interval = argvars[2].v_type == VAR_NUMBER
2391                 ? (int)argvars[2].vval.v_number
2392                 : 200;  // Default.
2393  TimeWatcher *tw = xmalloc(sizeof(TimeWatcher));
2394
2395  // Start dummy timer.
2396  time_watcher_init(&main_loop, tw, NULL);
2397  // Don't schedule the due callback, as that'll lead to two different types of events
2398  // on each interval, causing the condition to be checked twice.
2399  tw->events = NULL;
2400  time_watcher_start(tw, dummy_timer_due_cb, (uint64_t)interval, (uint64_t)interval);
2401
2402  typval_T argv = TV_INITIAL_VALUE;
2403  typval_T exprval = TV_INITIAL_VALUE;
2404  bool error = false;
2405  const int called_emsg_before = called_emsg;
2406
2407  // Flush screen updates before blocking.
2408  ui_flush();
2409
2410  LOOP_PROCESS_EVENTS_UNTIL(&main_loop, main_loop.events, timeout,
2411                            eval_expr_typval(&expr, false, &argv, 0, &exprval) != OK
2412                            || tv_get_number_chk(&exprval, &error)
2413                            || called_emsg > called_emsg_before || error || got_int);
2414
2415  if (called_emsg > called_emsg_before || error) {
2416    rettv->vval.v_number = -3;
2417  } else if (got_int) {
2418    got_int = false;
2419    vgetc();
2420    rettv->vval.v_number = -2;
2421  } else if (tv_get_number_chk(&exprval, &error)) {
2422    rettv->vval.v_number = 0;
2423  }
2424
2425  // Stop dummy timer
2426  time_watcher_stop(tw);
2427  time_watcher_close(tw, dummy_timer_close_cb);
2428}
2429
2430/// "gettext()" function
2431static void f_gettext(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
2432{
2433  if (tv_check_for_nonempty_string_arg(argvars, 0) == FAIL) {
2434    return;
2435  }
2436
2437  rettv->v_type = VAR_STRING;
2438  rettv->vval.v_string = xstrdup(_(argvars[0].vval.v_string));
2439}
2440
2441/// "has()" function
2442static void f_has(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
2443{
2444  static const char *const has_list[] = {
2445#ifdef __ANDROID__
2446    "android",
2447#endif
2448#if defined(BSD) && !defined(__APPLE__) && !defined(__GNU__)
2449    "bsd",
2450#endif
2451#ifdef __GNU__
2452    "hurd",
2453#endif
2454#ifdef __linux__
2455    "linux",
2456#endif
2457#ifdef SUN_SYSTEM
2458    "sun",
2459#endif
2460#ifdef __TERMUX__
2461    "termux",
2462#endif
2463#ifdef UNIX
2464    "unix",
2465#endif
2466#ifdef MSWIN
2467    "win32",
2468#endif
2469#ifdef _WIN64
2470    "win64",
2471#endif
2472#ifndef CASE_INSENSITIVE_FILENAME
2473    "fname_case",
2474#endif
2475#ifdef HAVE_ACL
2476    "acl",
2477#endif
2478    "autochdir",
2479    "arabic",
2480    "autocmd",
2481    "browsefilter",
2482    "byte_offset",
2483    "cindent",
2484    "cmdline_compl",
2485    "cmdline_hist",
2486    "cmdwin",
2487    "comments",
2488    "conceal",
2489    "cursorbind",
2490    "cursorshape",
2491    "dialog_con",
2492    "diff",
2493    "digraphs",
2494    "eval",         // always present, of course!
2495    "ex_extra",
2496    "extra_search",
2497    "file_in_path",
2498    "filterpipe",
2499    "find_in_path",
2500    "float",
2501    "folding",
2502#ifdef UNIX
2503    "fork",
2504#endif
2505    "gettext",
2506    "iconv",
2507    "insert_expand",
2508    "jumplist",
2509    "keymap",
2510    "lambda",
2511    "langmap",
2512    "libcall",
2513    "linebreak",
2514    "lispindent",
2515    "listcmds",
2516    "localmap",
2517#ifdef __APPLE__
2518    "mac",
2519    "macunix",
2520    "osx",
2521    "osxdarwin",
2522#endif
2523    "menu",
2524    "mksession",
2525    "modify_fname",
2526    "mouse",
2527    "multi_byte",
2528    "multi_lang",
2529    "nanotime",
2530    "num64",
2531    "packages",
2532    "path_extra",
2533    "persistent_undo",
2534    "profile",
2535    "reltime",
2536    "quickfix",
2537    "rightleft",
2538    "scrollbind",
2539    "showcmd",
2540    "cmdline_info",
2541    "shada",
2542    "signs",
2543    "smartindent",
2544    "startuptime",
2545    "statusline",
2546    "spell",
2547    "syntax",
2548#ifndef UNIX
2549    "system",
2550#endif
2551    "tablineat",
2552    "tag_binary",
2553    "termguicolors",
2554#ifdef HAVE_UNIBILIUM
2555    "terminfo",
2556#endif
2557    "termresponse",
2558    "textobjects",
2559    "timers",
2560    "title",
2561    "user-commands",        // was accidentally included in 5.4
2562    "user_commands",
2563    "vartabs",
2564    "vertsplit",
2565    "vimscript-1",
2566    "virtualedit",
2567    "visual",
2568    "visualextra",
2569    "vreplace",
2570    "wildignore",
2571    "wildmenu",
2572    "windows",
2573    "winaltkeys",
2574    "writebackup",
2575#ifdef HAVE_XATTR
2576    "xattr",
2577#endif
2578    "nvim",
2579  };
2580
2581  bool x = false;
2582  bool n = false;
2583  const char *const name = tv_get_string(&argvars[0]);
2584
2585  // Fast-path: check features not in has_list[] first to avoid the full
2586  // linear scan for very common queries like has('patch-...').
2587  if (STRNICMP(name, "patch", 5) == 0) {
2588    x = true;
2589    if (name[5] == '-'
2590        && strlen(name) >= 11
2591        && (name[6] >= '1' && name[6] <= '9')) {
2592      char *end;
2593
2594      // This works for patch-8.1.2, patch-9.0.3, patch-10.0.4, etc.
2595      // Not for patch-9.10.5.
2596      int major = (int)strtoul(name + 6, &end, 10);
2597      if (*end == '.' && ascii_isdigit(end[1])
2598          && end[2] == '.' && ascii_isdigit(end[3])) {
2599        int minor = atoi(end + 1);
2600
2601        // Expect "patch-9.9.01234".
2602        n = has_vim_patch(atoi(end + 3), major * 100 + minor);
2603      }
2604    } else if (ascii_isdigit(name[5])) {
2605      n = has_vim_patch(atoi(name + 5), 0);
2606    }
2607  } else if (STRNICMP(name, "nvim-", 5) == 0) {
2608    x = true;
2609    // Expect "nvim-x.y.z"
2610    n = has_nvim_version(name + 5);
2611  } else if (STRICMP(name, "vim_starting") == 0) {
2612    x = true;
2613    n = (starting != 0);
2614  } else if (STRICMP(name, "ttyin") == 0) {
2615    x = true;
2616    n = stdin_isatty;
2617  } else if (STRICMP(name, "ttyout") == 0) {
2618    x = true;
2619    n = stdout_isatty;
2620  } else if (STRICMP(name, "multi_byte_encoding") == 0) {
2621    x = true;
2622    n = true;
2623  } else if (STRICMP(name, "gui_running") == 0) {
2624    x = true;
2625    n = ui_gui_attached();
2626  } else if (STRICMP(name, "syntax_items") == 0) {
2627    x = true;
2628    n = syntax_present(curwin);
2629  } else if (STRICMP(name, "wsl") == 0) {
2630    x = true;
2631    n = has_wsl();
2632  }
2633
2634  // Look up in has_list[] only if not already handled above.
2635  if (!x) {
2636    for (size_t i = 0; i < ARRAY_SIZE(has_list); i++) {
2637      if (STRICMP(name, has_list[i]) == 0) {
2638        x = true;
2639        n = true;
2640        break;
2641      }
2642    }
2643  }
2644
2645  if (!x) {
2646    // XXX: eval_has_provider() may shell out :(
2647    const int save_shell_error = (int)get_vim_var_nr(VV_SHELL_ERROR);
2648
2649    if (STRICMP(name, "clipboard_working") == 0) {
2650      n = eval_has_provider("clipboard", true);
2651#ifdef UNIX
2652    } else if (STRICMP(name, "unnamedplus") == 0) {
2653      n = eval_has_provider("clipboard", true);
2654#endif
2655    } else if (STRICMP(name, "pythonx") == 0) {
2656      n = eval_has_provider("python3", true);
2657    } else if (eval_has_provider(name, true)) {
2658      n = true;
2659    }
2660
2661    set_vim_var_nr(VV_SHELL_ERROR, save_shell_error);
2662  }
2663
2664  rettv->vval.v_number = n;
2665}
2666
2667static bool has_wsl(void)
2668{
2669  static TriState has_wsl = kNone;
2670  if (has_wsl == kNone) {
2671    Error err = ERROR_INIT;
2672    Object o = NLUA_EXEC_STATIC("return vim.uv.os_uname()['release']:lower()"
2673                                ":match('microsoft')",
2674                                (Array)ARRAY_DICT_INIT, kRetNilBool, NULL, &err);
2675    assert(!ERROR_SET(&err));
2676    has_wsl = LUARET_TRUTHY(o) ? kTrue : kFalse;
2677  }
2678  return has_wsl == kTrue;
2679}
2680
2681/// "highlightID(name)" function
2682static void f_hlID(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
2683{
2684  rettv->vval.v_number = syn_name2id(tv_get_string(&argvars[0]));
2685}
2686
2687/// "highlight_exists()" function
2688static void f_hlexists(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
2689{
2690  rettv->vval.v_number = highlight_exists(tv_get_string(&argvars[0]));
2691}
2692
2693/// "index()" function
2694static void f_index(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
2695{
2696  int idx = 0;
2697  bool ic = false;
2698
2699  rettv->vval.v_number = -1;
2700  if (argvars[0].v_type == VAR_BLOB) {
2701    bool error = false;
2702    int start = 0;
2703
2704    if (argvars[2].v_type != VAR_UNKNOWN) {
2705      start = (int)tv_get_number_chk(&argvars[2], &error);
2706      if (error) {
2707        return;
2708      }
2709    }
2710    blob_T *const b = argvars[0].vval.v_blob;
2711    if (b == NULL) {
2712      return;
2713    }
2714    if (start < 0) {
2715      start = tv_blob_len(b) + start;
2716      if (start < 0) {
2717        start = 0;
2718      }
2719    }
2720    for (idx = start; idx < tv_blob_len(b); idx++) {
2721      typval_T tv;
2722      tv.v_type = VAR_NUMBER;
2723      tv.vval.v_number = tv_blob_get(b, idx);
2724      if (tv_equal(&tv, &argvars[1], ic)) {
2725        rettv->vval.v_number = idx;
2726        return;
2727      }
2728    }
2729    return;
2730  } else if (argvars[0].v_type != VAR_LIST) {
2731    emsg(_(e_listblobreq));
2732    return;
2733  }
2734
2735  list_T *const l = argvars[0].vval.v_list;
2736  if (l == NULL) {
2737    return;
2738  }
2739
2740  listitem_T *item = tv_list_first(l);
2741  if (argvars[2].v_type != VAR_UNKNOWN) {
2742    bool error = false;
2743
2744    // Start at specified item.
2745    idx = tv_list_uidx(l, (int)tv_get_number_chk(&argvars[2], &error));
2746    if (error || idx == -1) {
2747      item = NULL;
2748    } else {
2749      item = tv_list_find(l, idx);
2750      assert(item != NULL);
2751    }
2752    if (argvars[3].v_type != VAR_UNKNOWN) {
2753      ic = !!tv_get_bool_chk(&argvars[3], &error);
2754      if (error) {
2755        item = NULL;
2756      }
2757    }
2758  }
2759
2760  for (; item != NULL; item = TV_LIST_ITEM_NEXT(l, item), idx++) {
2761    if (tv_equal(TV_LIST_ITEM_TV(item), &argvars[1], ic)) {
2762      rettv->vval.v_number = idx;
2763      break;
2764    }
2765  }
2766}
2767
2768/// Evaluate "expr" with the v:key and v:val arguments and return the result.
2769/// The expression is expected to return a boolean value.  The caller should set
2770/// the VV_KEY and VV_VAL vim variables before calling this function.
2771static varnumber_T indexof_eval_expr(typval_T *expr)
2772{
2773  typval_T argv[3];
2774  argv[0] = *get_vim_var_tv(VV_KEY);
2775  argv[1] = *get_vim_var_tv(VV_VAL);
2776  typval_T newtv;
2777  newtv.v_type = VAR_UNKNOWN;
2778
2779  if (eval_expr_typval(expr, false, argv, 2, &newtv) == FAIL) {
2780    return false;
2781  }
2782
2783  bool error = false;
2784  varnumber_T found = tv_get_bool_chk(&newtv, &error);
2785  tv_clear(&newtv);
2786
2787  return error ? false : found;
2788}
2789
2790/// Evaluate "expr" for each byte in the Blob "b" starting with the byte at
2791/// "startidx" and return the index of the byte where "expr" is TRUE.  Returns
2792/// -1 if "expr" doesn't evaluate to TRUE for any of the bytes.
2793static varnumber_T indexof_blob(blob_T *b, varnumber_T startidx, typval_T *expr)
2794{
2795  if (b == NULL) {
2796    return -1;
2797  }
2798
2799  if (startidx < 0) {
2800    // negative index: index from the last byte
2801    startidx = tv_blob_len(b) + startidx;
2802    if (startidx < 0) {
2803      startidx = 0;
2804    }
2805  }
2806
2807  set_vim_var_type(VV_KEY, VAR_NUMBER);
2808  set_vim_var_type(VV_VAL, VAR_NUMBER);
2809
2810  const int called_emsg_start = called_emsg;
2811  for (varnumber_T idx = startidx; idx < tv_blob_len(b); idx++) {
2812    set_vim_var_nr(VV_KEY, idx);
2813    set_vim_var_nr(VV_VAL, tv_blob_get(b, (int)idx));
2814
2815    if (indexof_eval_expr(expr)) {
2816      return idx;
2817    }
2818
2819    if (called_emsg != called_emsg_start) {
2820      return -1;
2821    }
2822  }
2823
2824  return -1;
2825}
2826
2827/// Evaluate "expr" for each item in the List "l" starting with the item at
2828/// "startidx" and return the index of the item where "expr" is TRUE.  Returns
2829/// -1 if "expr" doesn't evaluate to TRUE for any of the items.
2830static varnumber_T indexof_list(list_T *l, varnumber_T startidx, typval_T *expr)
2831{
2832  if (l == NULL) {
2833    return -1;
2834  }
2835
2836  listitem_T *item;
2837  varnumber_T idx = 0;
2838  if (startidx == 0) {
2839    item = tv_list_first(l);
2840  } else {
2841    // Start at specified item.
2842    idx = tv_list_uidx(l, (int)startidx);
2843    if (idx == -1) {
2844      item = NULL;
2845    } else {
2846      item = tv_list_find(l, (int)idx);
2847      assert(item != NULL);
2848    }
2849  }
2850
2851  set_vim_var_type(VV_KEY, VAR_NUMBER);
2852
2853  const int called_emsg_start = called_emsg;
2854  for (; item != NULL; item = TV_LIST_ITEM_NEXT(l, item), idx++) {
2855    set_vim_var_nr(VV_KEY, idx);
2856    tv_copy(TV_LIST_ITEM_TV(item), get_vim_var_tv(VV_VAL));
2857
2858    bool found = indexof_eval_expr(expr);
2859    tv_clear(get_vim_var_tv(VV_VAL));
2860
2861    if (found) {
2862      return idx;
2863    }
2864
2865    if (called_emsg != called_emsg_start) {
2866      return -1;
2867    }
2868  }
2869
2870  return -1;
2871}
2872
2873/// "indexof()" function
2874static void f_indexof(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
2875{
2876  rettv->vval.v_number = -1;
2877
2878  if (tv_check_for_list_or_blob_arg(argvars, 0) == FAIL
2879      || tv_check_for_string_or_func_arg(argvars, 1) == FAIL
2880      || tv_check_for_opt_dict_arg(argvars, 2) == FAIL) {
2881    return;
2882  }
2883
2884  if ((argvars[1].v_type == VAR_STRING
2885       && (argvars[1].vval.v_string == NULL || *argvars[1].vval.v_string == NUL))
2886      || (argvars[1].v_type == VAR_FUNC && argvars[1].vval.v_partial == NULL)) {
2887    return;
2888  }
2889
2890  varnumber_T startidx = 0;
2891  if (argvars[2].v_type == VAR_DICT) {
2892    startidx = tv_dict_get_number_def(argvars[2].vval.v_dict, "startidx", 0);
2893  }
2894
2895  typval_T save_val;
2896  typval_T save_key;
2897  prepare_vimvar(VV_VAL, &save_val);
2898  prepare_vimvar(VV_KEY, &save_key);
2899
2900  // We reset "did_emsg" to be able to detect whether an error occurred
2901  // during evaluation of the expression.
2902  const int save_did_emsg = did_emsg;
2903  did_emsg = false;
2904
2905  if (argvars[0].v_type == VAR_BLOB) {
2906    rettv->vval.v_number = indexof_blob(argvars[0].vval.v_blob, startidx, &argvars[1]);
2907  } else {
2908    rettv->vval.v_number = indexof_list(argvars[0].vval.v_list, startidx, &argvars[1]);
2909  }
2910
2911  restore_vimvar(VV_KEY, &save_key);
2912  restore_vimvar(VV_VAL, &save_val);
2913  did_emsg |= save_did_emsg;
2914}
2915
2916static bool inputsecret_flag = false;
2917
2918/// "input()" function
2919///     Also handles inputsecret() when inputsecret is set.
2920static void f_input(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
2921{
2922  get_user_input(argvars, rettv, false, inputsecret_flag);
2923}
2924
2925/// "inputdialog()" function
2926static void f_inputdialog(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
2927{
2928  get_user_input(argvars, rettv, true, inputsecret_flag);
2929}
2930
2931/// "inputlist()" function
2932static void f_inputlist(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
2933{
2934  if (argvars[0].v_type != VAR_LIST) {
2935    semsg(_(e_listarg), "inputlist()");
2936    return;
2937  }
2938
2939  msg_ext_set_kind("confirm");
2940  msg_start();
2941  msg_row = Rows - 1;   // for when 'cmdheight' > 1
2942  lines_left = Rows;    // avoid more prompt
2943  msg_scroll = true;
2944  msg_clr_eos();
2945
2946  list_T *l = argvars[0].vval.v_list;
2947  TV_LIST_ITER_CONST(l, li, {
2948    msg_puts(tv_get_string(TV_LIST_ITEM_TV(li)));
2949    if (!ui_has(kUIMessages) || TV_LIST_ITEM_NEXT(l, li) != NULL) {
2950      msg_putchar('\n');
2951    }
2952  });
2953
2954  // Ask for choice.
2955  bool mouse_used = false;
2956  int selected = prompt_for_input(NULL, 0, false, &mouse_used);
2957  if (mouse_used) {
2958    selected = tv_list_len(l) - (cmdline_row - mouse_row);
2959  }
2960
2961  rettv->vval.v_number = selected;
2962}
2963
2964static garray_T ga_userinput = { 0, 0, sizeof(tasave_T), 4, NULL };
2965
2966/// "inputrestore()" function
2967static void f_inputrestore(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
2968{
2969  if (!GA_EMPTY(&ga_userinput)) {
2970    ga_userinput.ga_len--;
2971    restore_typeahead((tasave_T *)(ga_userinput.ga_data)
2972                      + ga_userinput.ga_len);
2973    // default return is zero == OK
2974  } else if (p_verbose > 1) {
2975    verb_msg(_("called inputrestore() more often than inputsave()"));
2976    rettv->vval.v_number = 1;  // Failed
2977  }
2978}
2979
2980/// "inputsave()" function
2981static void f_inputsave(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
2982{
2983  // Add an entry to the stack of typeahead storage.
2984  tasave_T *p = GA_APPEND_VIA_PTR(tasave_T, &ga_userinput);
2985  save_typeahead(p);
2986}
2987
2988/// "inputsecret()" function
2989static void f_inputsecret(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
2990{
2991  cmdline_star++;
2992  inputsecret_flag = true;
2993  f_input(argvars, rettv, fptr);
2994  cmdline_star--;
2995  inputsecret_flag = false;
2996}
2997
2998/// "interrupt()" function
2999static void f_interrupt(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
3000{
3001  got_int = true;
3002}
3003
3004/// "invert(expr)" function
3005static void f_invert(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
3006{
3007  rettv->vval.v_number = ~tv_get_number_chk(&argvars[0], NULL);
3008}
3009
3010/// "islocked()" function
3011static void f_islocked(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
3012{
3013  lval_T lv;
3014
3015  rettv->vval.v_number = -1;
3016  const char *const end = get_lval((char *)tv_get_string(&argvars[0]),
3017                                   NULL,
3018                                   &lv, false, false,
3019                                   GLV_NO_AUTOLOAD|GLV_READ_ONLY,
3020                                   FNE_CHECK_START);
3021  if (end != NULL && lv.ll_name != NULL) {
3022    if (*end != NUL) {
3023      semsg(_(lv.ll_name_len == 0 ? e_invarg2 : e_trailing_arg), end);
3024    } else {
3025      if (lv.ll_tv == NULL) {
3026        dictitem_T *di = find_var(lv.ll_name, lv.ll_name_len, NULL, true);
3027        if (di != NULL) {
3028          // Consider a variable locked when:
3029          // 1. the variable itself is locked
3030          // 2. the value of the variable is locked.
3031          // 3. the List or Dict value is locked.
3032          rettv->vval.v_number = ((di->di_flags & DI_FLAGS_LOCK)
3033                                  || tv_islocked(&di->di_tv));
3034        }
3035      } else if (lv.ll_range) {
3036        emsg(_("E786: Range not allowed"));
3037      } else if (lv.ll_newkey != NULL) {
3038        semsg(_(e_dictkey), lv.ll_newkey);
3039      } else if (lv.ll_list != NULL) {
3040        // List item.
3041        rettv->vval.v_number = tv_islocked(TV_LIST_ITEM_TV(lv.ll_li));
3042      } else {
3043        // Dictionary item.
3044        rettv->vval.v_number = tv_islocked(&lv.ll_di->di_tv);
3045      }
3046    }
3047  }
3048
3049  clear_lval(&lv);
3050}
3051
3052/// "isinf()" function
3053static void f_isinf(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
3054{
3055  if (argvars[0].v_type == VAR_FLOAT
3056      && xisinf(argvars[0].vval.v_float)) {
3057    rettv->vval.v_number = argvars[0].vval.v_float > 0.0 ? 1 : -1;
3058  }
3059}
3060
3061/// "isnan()" function
3062static void f_isnan(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
3063{
3064  rettv->vval.v_number = argvars[0].v_type == VAR_FLOAT
3065                         && xisnan(argvars[0].vval.v_float);
3066}
3067
3068/// "id()" function
3069static void f_id(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
3070  FUNC_ATTR_NONNULL_ALL
3071{
3072  const int len = vim_vsnprintf_typval(NULL, 0, "%p", dummy_ap, argvars);
3073  rettv->v_type = VAR_STRING;
3074  rettv->vval.v_string = xmalloc((size_t)len + 1);
3075  vim_vsnprintf_typval(rettv->vval.v_string, (size_t)len + 1, "%p", dummy_ap, argvars);
3076}
3077
3078/// "jobpid(id)" function
3079static void f_jobpid(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
3080{
3081  rettv->v_type = VAR_NUMBER;
3082  rettv->vval.v_number = 0;
3083
3084  if (check_secure()) {
3085    return;
3086  }
3087
3088  if (argvars[0].v_type != VAR_NUMBER) {
3089    emsg(_(e_invarg));
3090    return;
3091  }
3092
3093  Channel *data = find_job((uint64_t)argvars[0].vval.v_number, true);
3094  if (!data) {
3095    return;
3096  }
3097
3098  Proc *proc = &data->stream.proc;
3099  rettv->vval.v_number = proc->pid;
3100}
3101
3102/// "jobresize(job, width, height)" function
3103static void f_jobresize(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
3104{
3105  rettv->v_type = VAR_NUMBER;
3106  rettv->vval.v_number = 0;
3107
3108  if (check_secure()) {
3109    return;
3110  }
3111
3112  if (argvars[0].v_type != VAR_NUMBER || argvars[1].v_type != VAR_NUMBER
3113      || argvars[2].v_type != VAR_NUMBER) {
3114    // job id, width, height
3115    emsg(_(e_invarg));
3116    return;
3117  }
3118
3119  Channel *data = find_job((uint64_t)argvars[0].vval.v_number, true);
3120  if (!data) {
3121    return;
3122  }
3123
3124  if (data->stream.proc.type != kProcTypePty) {
3125    emsg(_(e_channotpty));
3126    return;
3127  }
3128
3129  pty_proc_resize(&data->stream.pty, (uint16_t)argvars[1].vval.v_number,
3130                  (uint16_t)argvars[2].vval.v_number);
3131  rettv->vval.v_number = 1;
3132}
3133
3134static const char *pty_ignored_env_vars[] = {
3135#ifndef MSWIN
3136  "COLUMNS",
3137  "LINES",
3138  "TERMCAP",
3139  "COLORFGBG",
3140#endif
3141  "COLORTERM",
3142  // Nvim-owned env vars. #6764
3143  "VIM",
3144  "VIMRUNTIME",
3145  NULL
3146};
3147
3148/// According to comments in src/win/process.c of libuv, Windows has a few
3149/// "essential" environment variables.
3150static const char *required_env_vars[] = {
3151#ifdef MSWIN
3152  "HOMEDRIVE",
3153  "HOMEPATH",
3154  "LOGONSERVER",
3155  "PATH",
3156  "SYSTEMDRIVE",
3157  "SYSTEMROOT",
3158  "TEMP",
3159  "USERDOMAIN",
3160  "USERNAME",
3161  "USERPROFILE",
3162  "WINDIR",
3163#endif
3164  NULL
3165};
3166
3167/// Builds an environment dict for a child process (job).
3168///
3169/// @param set_nvim_addr  Set the $NVIM env var.
3170dict_T *create_environment(const dictitem_T *job_env, const bool clear_env, const bool pty,
3171                           const bool set_nvim_addr, const char * const pty_term_name)
3172{
3173  dict_T *env = tv_dict_alloc();
3174
3175  if (!clear_env) {
3176    uv_env_item_t *envitems;
3177    int envcount;
3178    if (uv_os_environ(&envitems, &envcount) == 0) {
3179      for (int i = 0; i < envcount; i++) {
3180        const char *name = envitems[i].name;
3181        size_t namelen = strlen(name);
3182#ifdef MSWIN
3183        // Force uppercase keys on Windows (for dedup, below). #39443
3184        if (namelen < MAXPATHL / MB_MAXBYTES) {
3185          namelen = mb_strup_buf(name, NameBuff);
3186          name = NameBuff;
3187        }
3188#endif
3189        tv_dict_add_str(env, name, namelen, envitems[i].value);
3190      }
3191      uv_os_free_environ(envitems, envcount);
3192    }
3193
3194    if (pty) {
3195      // These env vars shouldn't propagate to the child process. #6764
3196      // Remove them here, then the user may decide to explicitly set them below.
3197      for (size_t i = 0;
3198           i < ARRAY_SIZE(pty_ignored_env_vars) && pty_ignored_env_vars[i];
3199           i++) {
3200        dictitem_T *dv = tv_dict_find(env, pty_ignored_env_vars[i], -1);
3201        if (dv) {
3202          tv_dict_item_remove(env, dv);
3203        }
3204      }
3205      // Set COLORTERM to "truecolor" if termguicolors is set
3206      if (p_tgc) {
3207        tv_dict_add_str(env, S_LEN("COLORTERM"), "truecolor");
3208      }
3209    }
3210  }
3211
3212  // For a pty, we need a sane $TERM set.  We can't rely on nvim's environment,
3213  // because the child process is going to be communicating with nvim, not the
3214  // parent terminal.  Set a sane default, but let the user override it in the
3215  // job's environment if they want.
3216  if (pty) {
3217    dictitem_T *dv = tv_dict_find(env, S_LEN("TERM"));
3218    if (dv) {
3219      tv_dict_item_remove(env, dv);
3220    }
3221    tv_dict_add_str(env, S_LEN("TERM"), pty_term_name);
3222  }
3223
3224  // Set $NVIM (in the child process) to v:servername. #3118
3225  if (set_nvim_addr) {
3226    char *nvim_addr = get_vim_var_str(VV_SEND_SERVER);
3227    if (nvim_addr[0] != NUL) {
3228      dictitem_T *dv = tv_dict_find(env, S_LEN("NVIM"));
3229      if (dv) {
3230        tv_dict_item_remove(env, dv);
3231      }
3232      tv_dict_add_str(env, S_LEN("NVIM"), nvim_addr);
3233    }
3234  }
3235
3236  if (job_env) {
3237#ifdef MSWIN
3238    TV_DICT_ITER(job_env->di_tv.vval.v_dict, var, {
3239      // Force uppercase keys on Windows (dedup).
3240      const char *name = var->di_key;
3241      size_t namelen = strlen(name);
3242      if (namelen < MAXPATHL / MB_MAXBYTES) {
3243        namelen = mb_strup_buf(name, NameBuff);
3244        name = NameBuff;
3245      }
3246      dictitem_T *dv = tv_dict_find(env, name, (ptrdiff_t)namelen);
3247      if (dv) {
3248        tv_dict_item_remove(env, dv);
3249      }
3250      tv_dict_add_str(env, name, namelen, tv_get_string(&var->di_tv));
3251    });
3252#else
3253    tv_dict_extend(env, job_env->di_tv.vval.v_dict, "force");
3254#endif
3255  }
3256
3257  if (pty) {
3258    // Now that the custom environment is configured, we need to ensure certain
3259    // environment variables are present.
3260    for (size_t i = 0;
3261         i < ARRAY_SIZE(required_env_vars) && required_env_vars[i];
3262         i++) {
3263      size_t len = strlen(required_env_vars[i]);
3264      dictitem_T *dv = tv_dict_find(env, required_env_vars[i], (ptrdiff_t)len);
3265      if (!dv) {
3266        char *env_var = os_getenv(required_env_vars[i]);
3267        if (env_var) {
3268          tv_dict_add_allocated_str(env, required_env_vars[i], len, env_var);
3269        }
3270      }
3271    }
3272  }
3273
3274  return env;
3275}
3276
3277/// "jobstart()" function
3278void f_jobstart(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
3279{
3280  rettv->v_type = VAR_NUMBER;
3281  rettv->vval.v_number = 0;
3282
3283  if (check_secure()) {
3284    return;
3285  }
3286
3287  const char *cmd;
3288  bool executable = true;
3289  char **argv = tv_to_argv(&argvars[0], &cmd, &executable);
3290  if (!argv) {
3291    rettv->vval.v_number = executable ? 0 : -1;
3292    return;  // Did error message in tv_to_argv.
3293  }
3294
3295  if (argvars[1].v_type != VAR_DICT && argvars[1].v_type != VAR_UNKNOWN) {
3296    // Wrong argument types
3297    semsg(_(e_invarg2), "expected dictionary");
3298    shell_free_argv(argv);
3299    return;
3300  }
3301
3302  dict_T *job_opts = NULL;
3303  bool detach = false;
3304  bool rpc = false;
3305  bool pty = false;
3306  bool term = false;
3307  bool clear_env = false;
3308  bool overlapped = false;
3309  ChannelStdinMode stdin_mode = kChannelStdinPipe;
3310  CallbackReader on_stdout = CALLBACK_READER_INIT;
3311  CallbackReader on_stderr = CALLBACK_READER_INIT;
3312  Callback on_exit = CALLBACK_NONE;
3313  char *cwd = NULL;
3314  dictitem_T *job_env = NULL;
3315  if (argvars[1].v_type == VAR_DICT) {
3316    job_opts = argvars[1].vval.v_dict;
3317
3318    detach = tv_dict_get_number(job_opts, "detach") != 0;
3319    rpc = tv_dict_get_number(job_opts, "rpc") != 0;
3320    term = tv_dict_get_number(job_opts, "term") != 0;
3321    pty = term || tv_dict_get_number(job_opts, "pty") != 0;
3322    clear_env = tv_dict_get_number(job_opts, "clear_env") != 0;
3323    overlapped = tv_dict_get_number(job_opts, "overlapped") != 0;
3324
3325    char *s = tv_dict_get_string(job_opts, "stdin", false);
3326    if (s) {
3327      if (!strncmp(s, "null", NUMBUFLEN)) {
3328        stdin_mode = kChannelStdinNull;
3329      } else if (!strncmp(s, "pipe", NUMBUFLEN)) {
3330        // Nothing to do, default value
3331      } else {
3332        semsg(_(e_invargNval), "stdin", s);
3333      }
3334    }
3335
3336    dictitem_T *const job_term = tv_dict_find(job_opts, S_LEN("term"));
3337    if (job_term && VAR_BOOL != job_term->di_tv.v_type) {
3338      // Restrict "term" field to boolean, in case we want to allow buffer numbers in the future.
3339      semsg(_(e_invarg2), "'term' must be Boolean");
3340      shell_free_argv(argv);
3341      return;
3342    }
3343
3344    if (pty && rpc) {
3345      semsg(_(e_invarg2), "job cannot have both 'pty' and 'rpc' options set");
3346      shell_free_argv(argv);
3347      return;
3348    }
3349
3350#ifdef MSWIN
3351    if (pty && overlapped) {
3352      semsg(_(e_invarg2),
3353            "job cannot have both 'pty' and 'overlapped' options set");
3354      shell_free_argv(argv);
3355      return;
3356    }
3357#endif
3358
3359    char *new_cwd = tv_dict_get_string(job_opts, "cwd", false);
3360    if (new_cwd && *new_cwd != NUL) {
3361      cwd = new_cwd;
3362      // The new cwd must be a directory.
3363      if (!os_isdir(cwd)) {
3364        semsg(_(e_invarg2), "expected valid directory");
3365        shell_free_argv(argv);
3366        return;
3367      }
3368    }
3369
3370    job_env = tv_dict_find(job_opts, S_LEN("env"));
3371    if (job_env && job_env->di_tv.v_type != VAR_DICT) {
3372      semsg(_(e_invarg2), "env");
3373      shell_free_argv(argv);
3374      return;
3375    }
3376
3377    if (!common_job_callbacks(job_opts, &on_stdout, &on_stderr, &on_exit)) {
3378      shell_free_argv(argv);
3379      return;
3380    }
3381  }
3382
3383  uint16_t width = (uint16_t)tv_dict_get_number(job_opts, "width");
3384  uint16_t height = (uint16_t)tv_dict_get_number(job_opts, "height");
3385  char *term_name = NULL;
3386
3387  if (term) {
3388    if (text_locked()) {
3389      text_locked_msg();
3390      shell_free_argv(argv);
3391      return;
3392    }
3393    if (curbuf->b_changed) {
3394      emsg(_("jobstart(...,{term=true}) requires unmodified buffer"));
3395      shell_free_argv(argv);
3396      return;
3397    }
3398    if (curbuf->terminal) {
3399      if (terminal_running(curbuf->terminal)) {
3400        semsg(_("Terminal already connected to buffer %d"), curbuf->handle);
3401        shell_free_argv(argv);
3402        return;
3403      }
3404      buf_close_terminal(curbuf);
3405    }
3406    assert(!rpc);
3407    term_name = "xterm-256color";
3408    cwd = cwd ? cwd : ".";
3409    overlapped = false;
3410    detach = false;
3411    stdin_mode = kChannelStdinPipe;
3412    width = width ? width : (uint16_t)MAX(0, curwin->w_view_width - win_col_off(curwin));
3413    height = height ? height : (uint16_t)curwin->w_view_height;
3414  }
3415
3416  if (pty) {
3417    // Deprecated TERM field is from before `env` option existed.
3418    term_name = term_name ? term_name : tv_dict_get_string(job_opts, "TERM", false);
3419    term_name = term_name ? term_name : "ansi";
3420  }
3421
3422  dict_T *env = create_environment(job_env, clear_env, pty, true, term_name);
3423  Channel *chan = channel_job_start(argv, NULL, on_stdout, on_stderr, on_exit, pty,
3424                                    rpc, overlapped, detach, stdin_mode, cwd,
3425                                    width, height, env, &rettv->vval.v_number);
3426  if (!chan) {
3427    return;
3428  } else if (!term) {
3429    channel_create_event(chan, NULL);
3430  } else {
3431    if (rettv->vval.v_number <= 0) {
3432      return;
3433    }
3434
3435    const int pid = chan->stream.pty.proc.pid;
3436    buf_T *const buf = curbuf;
3437
3438    // Unset 'swapfile' to ensure no swapfile is created.
3439    buf->b_p_swf = false;
3440    // If the buffer isn't loaded, open a memfile here to avoid spurious autocommands
3441    // from open_buffer() when updating the terminal buffer later.
3442    if (buf->b_ml.ml_mfp == NULL && ml_open(buf) == FAIL) {
3443      // Internal error in ml_open(): stop the job.
3444      proc_stop(&chan->stream.proc);
3445      channel_decref(chan);
3446      return;
3447    }
3448
3449    channel_incref(chan);
3450    channel_terminal_alloc(buf, chan);
3451
3452    apply_autocmds(EVENT_BUFFILEPRE, NULL, NULL, false, buf);
3453
3454    if (chan->term == NULL || terminal_buf(chan->term) == 0) {
3455      goto term_done;  // Terminal may be destroyed during autocommands.
3456    }
3457
3458    // "./…" => "/home/foo/…"
3459    vim_FullName(cwd, NameBuff, sizeof(NameBuff), false);
3460    // "/home/foo/…" => "~/…"
3461    size_t len = home_replace(NULL, NameBuff, IObuff, sizeof(IObuff), true);
3462    // Trim slash.
3463    if (len != 1 && (IObuff[len - 1] == '\\' || IObuff[len - 1] == '/')) {
3464      IObuff[len - 1] = NUL;
3465    }
3466
3467    if (len == 1 && IObuff[0] == '/') {
3468      // Avoid ambiguity in the URI when CWD is root directory.
3469      IObuff[1] = '.';
3470      IObuff[2] = NUL;
3471    }
3472
3473    // Terminal URI: "term://$CWD//$PID:$CMD"
3474    snprintf(NameBuff, sizeof(NameBuff), "term://%s//%d:%s", IObuff, pid, cmd);
3475
3476    setfname(buf, NameBuff, NULL, true);
3477    apply_autocmds(EVENT_BUFFILEPOST, NULL, NULL, false, buf);
3478
3479    if (chan->term == NULL || terminal_buf(chan->term) == 0) {
3480      goto term_done;  // Terminal may be destroyed during autocommands.
3481    }
3482
3483    Error err = ERROR_INIT;
3484    buf->b_locked++;
3485    // Set (deprecated) buffer-local vars (prefer 'channel' buffer-local option).
3486    dict_set_var(buf->b_vars, cstr_as_string("terminal_job_id"),
3487                 INTEGER_OBJ((Integer)chan->id), false, false, NULL, &err);
3488    api_clear_error(&err);
3489    dict_set_var(buf->b_vars, cstr_as_string("terminal_job_pid"),
3490                 INTEGER_OBJ(pid), false, false, NULL, &err);
3491    api_clear_error(&err);
3492    buf->b_locked--;
3493
3494    if (chan->term == NULL || terminal_buf(chan->term) == 0) {
3495      goto term_done;  // Terminal may be destroyed in dict watchers.
3496    }
3497
3498    terminal_open(&chan->term, buf);
3499term_done:
3500    channel_create_event(chan, NULL);
3501    channel_decref(chan);
3502  }
3503}
3504
3505/// "jobstop()" function
3506void f_jobstop(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
3507{
3508  rettv->v_type = VAR_NUMBER;
3509  rettv->vval.v_number = 0;
3510
3511  if (check_secure()) {
3512    return;
3513  }
3514
3515  if (argvars[0].v_type != VAR_NUMBER) {
3516    // Only argument is the job id
3517    emsg(_(e_invarg));
3518    return;
3519  }
3520
3521  Channel *data = find_job((uint64_t)argvars[0].vval.v_number, false);
3522  if (!data) {
3523    return;
3524  }
3525
3526  const char *error = NULL;
3527  if (data->is_rpc) {
3528    // Ignore return code, but show error later.
3529    channel_close(data->id, kChannelPartRpc, &error);
3530  }
3531  proc_stop(&data->stream.proc);
3532  rettv->vval.v_number = 1;
3533  if (error) {
3534    emsg(error);
3535  }
3536}
3537
3538/// "jobwait(ids[, timeout])" function
3539static void f_jobwait(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
3540{
3541  rettv->v_type = VAR_NUMBER;
3542  rettv->vval.v_number = 0;
3543
3544  if (check_secure()) {
3545    return;
3546  }
3547  if (argvars[0].v_type != VAR_LIST || (argvars[1].v_type != VAR_NUMBER
3548                                        && argvars[1].v_type != VAR_UNKNOWN)) {
3549    emsg(_(e_invarg));
3550    return;
3551  }
3552
3553  list_T *args = argvars[0].vval.v_list;
3554  Channel **jobs = xcalloc((size_t)tv_list_len(args), sizeof(*jobs));
3555  MultiQueue *waiting_jobs = multiqueue_new(loop_on_put, &main_loop);
3556
3557  // Validate, prepare jobs for waiting.
3558  int i = 0;
3559  TV_LIST_ITER_CONST(args, arg, {
3560    Channel *chan = NULL;
3561    if (TV_LIST_ITEM_TV(arg)->v_type != VAR_NUMBER
3562        || !(chan = find_channel((uint64_t)TV_LIST_ITEM_TV(arg)->vval.v_number))
3563        || chan->streamtype != kChannelStreamProc) {
3564      jobs[i] = NULL;  // Invalid job.
3565    } else if (proc_is_stopped(&chan->stream.proc)) {
3566      // Job is stopped but not fully destroyed.
3567      // Ensure all callbacks on its event queue are executed. #15402
3568      proc_wait(&chan->stream.proc, -1, NULL);
3569      jobs[i] = NULL;  // Invalid job.
3570    } else {
3571      jobs[i] = chan;
3572      channel_incref(chan);
3573      if (chan->stream.proc.status < 0) {
3574        // Flush any events in the job's queue before temporarily replacing it.
3575        multiqueue_process_events(chan->events);
3576        multiqueue_replace_parent(chan->events, waiting_jobs);
3577      }
3578    }
3579    i++;
3580  });
3581
3582  int remaining = -1;
3583  uint64_t before = 0;
3584  if (argvars[1].v_type == VAR_NUMBER && argvars[1].vval.v_number >= 0) {
3585    remaining = (int)argvars[1].vval.v_number;
3586    before = os_hrtime();
3587  }
3588
3589  // Only mark the UI as busy when jobwait() blocks
3590  const bool busy = remaining != 0;
3591  if (busy) {
3592    ui_busy_start();
3593    ui_flush();
3594  }
3595
3596  for (i = 0; i < tv_list_len(args); i++) {
3597    if (remaining == 0) {
3598      break;  // Timeout.
3599    }
3600    if (jobs[i] == NULL) {
3601      continue;  // Invalid job, will assign status=-3 below.
3602    }
3603    int status = proc_wait(&jobs[i]->stream.proc, remaining,
3604                           waiting_jobs);
3605    if (status < 0) {
3606      break;  // Interrupted (CTRL-C) or timeout, skip remaining jobs.
3607    }
3608    if (remaining > 0) {
3609      uint64_t now = os_hrtime();
3610      remaining = MIN(0, remaining - (int)((now - before) / 1000000));
3611      before = now;
3612    }
3613  }
3614
3615  list_T *const rv = tv_list_alloc(tv_list_len(args));
3616
3617  // For each job:
3618  //  * Restore its parent queue if the job is still alive.
3619  //  * Append its status to the output list, or:
3620  //       -3 for "invalid job id"
3621  //       -2 for "interrupted" (user hit CTRL-C)
3622  //       -1 for jobs that were skipped or timed out
3623  for (i = 0; i < tv_list_len(args); i++) {
3624    if (jobs[i] == NULL) {
3625      tv_list_append_number(rv, -3);
3626      continue;
3627    }
3628    multiqueue_process_events(jobs[i]->events);
3629    multiqueue_replace_parent(jobs[i]->events, main_loop.events);
3630
3631    tv_list_append_number(rv, jobs[i]->stream.proc.status);
3632    channel_decref(jobs[i]);
3633  }
3634
3635  multiqueue_free(waiting_jobs);
3636  xfree(jobs);
3637  if (busy) {
3638    ui_busy_stop();
3639  }
3640  tv_list_ref(rv);
3641  rettv->v_type = VAR_LIST;
3642  rettv->vval.v_list = rv;
3643}
3644
3645/// json_decode() function
3646static void f_json_decode(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
3647{
3648  char numbuf[NUMBUFLEN];
3649  const char *s = NULL;
3650  char *tofree = NULL;
3651  size_t len;
3652  if (argvars[0].v_type == VAR_LIST) {
3653    if (!encode_vim_list_to_buf(argvars[0].vval.v_list, &len, &tofree)) {
3654      emsg(_("E474: Failed to convert list to string"));
3655      return;
3656    }
3657    s = tofree;
3658    if (s == NULL) {
3659      assert(len == 0);
3660      s = "";
3661    }
3662  } else {
3663    s = tv_get_string_buf_chk(&argvars[0], numbuf);
3664    if (s) {
3665      len = strlen(s);
3666    } else {
3667      return;
3668    }
3669  }
3670  if (json_decode_string(s, len, rettv) == FAIL) {
3671    semsg(_("E474: Failed to parse %.*s"), (int)len, s);
3672    rettv->v_type = VAR_NUMBER;
3673    rettv->vval.v_number = 0;
3674  }
3675  assert(rettv->v_type != VAR_UNKNOWN);
3676  xfree(tofree);
3677}
3678
3679/// json_encode() function
3680static void f_json_encode(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
3681{
3682  rettv->v_type = VAR_STRING;
3683  rettv->vval.v_string = encode_tv2json(&argvars[0], NULL);
3684}
3685
3686/// "keytrans()" function
3687static void f_keytrans(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
3688{
3689  rettv->v_type = VAR_STRING;
3690  if (tv_check_for_string_arg(argvars, 0) == FAIL
3691      || argvars[0].vval.v_string == NULL) {
3692    return;
3693  }
3694  // Need to escape K_SPECIAL for mb_unescape().
3695  char *escaped = vim_strsave_escape_ks(argvars[0].vval.v_string);
3696  rettv->vval.v_string = str2special_save(escaped, true, true);
3697  xfree(escaped);
3698}
3699
3700/// "len()" function
3701static void f_len(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
3702{
3703  switch (argvars[0].v_type) {
3704  case VAR_STRING:
3705  case VAR_NUMBER:
3706    rettv->vval.v_number = (varnumber_T)strlen(tv_get_string(&argvars[0]));
3707    break;
3708  case VAR_BLOB:
3709    rettv->vval.v_number = tv_blob_len(argvars[0].vval.v_blob);
3710    break;
3711  case VAR_LIST:
3712    rettv->vval.v_number = tv_list_len(argvars[0].vval.v_list);
3713    break;
3714  case VAR_DICT:
3715    rettv->vval.v_number = tv_dict_len(argvars[0].vval.v_dict);
3716    break;
3717  case VAR_UNKNOWN:
3718  case VAR_BOOL:
3719  case VAR_SPECIAL:
3720  case VAR_FLOAT:
3721  case VAR_PARTIAL:
3722  case VAR_FUNC:
3723    emsg(_("E701: Invalid type for len()"));
3724    break;
3725  }
3726}
3727
3728static void libcall_common(typval_T *argvars, typval_T *rettv, int out_type)
3729{
3730  rettv->v_type = (VarType)out_type;
3731  if (out_type != VAR_NUMBER) {
3732    rettv->vval.v_string = NULL;
3733  }
3734
3735  if (check_secure()) {
3736    return;
3737  }
3738
3739  // The first two args (libname and funcname) must be strings
3740  if (argvars[0].v_type != VAR_STRING || argvars[1].v_type != VAR_STRING) {
3741    return;
3742  }
3743
3744  const char *libname = argvars[0].vval.v_string;
3745  const char *funcname = argvars[1].vval.v_string;
3746
3747  VarType in_type = argvars[2].v_type;
3748
3749  // input variables
3750  char *str_in = (in_type == VAR_STRING) ? argvars[2].vval.v_string : NULL;
3751  int int_in = (int)argvars[2].vval.v_number;
3752
3753  // output variables
3754  char **str_out = (out_type == VAR_STRING) ? &rettv->vval.v_string : NULL;
3755  int int_out = 0;
3756
3757  bool success = os_libcall(libname, funcname,
3758                            str_in, int_in,
3759                            str_out, &int_out);
3760
3761  if (!success) {
3762    semsg(_(e_libcall), funcname);
3763    return;
3764  }
3765
3766  if (out_type == VAR_NUMBER) {
3767    rettv->vval.v_number = (varnumber_T)int_out;
3768  }
3769}
3770
3771/// "libcall()" function
3772static void f_libcall(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
3773{
3774  libcall_common(argvars, rettv, VAR_STRING);
3775}
3776
3777/// "libcallnr()" function
3778static void f_libcallnr(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
3779{
3780  libcall_common(argvars, rettv, VAR_NUMBER);
3781}
3782
3783/// "line(string, [winid])" function
3784static void f_line(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
3785{
3786  linenr_T lnum = 0;
3787  pos_T *fp = NULL;
3788  int fnum;
3789
3790  if (argvars[1].v_type != VAR_UNKNOWN) {
3791    // use window specified in the second argument
3792    int id = (int)tv_get_number(&argvars[1]);
3793    tabpage_T *tp;
3794    win_T *wp = win_id2wp_tp(id, &tp);
3795    if (wp != NULL && tp != NULL) {
3796      // With 'splitkeep' != cursor and in diff mode, prevent that the
3797      // window scrolls and keep the topline.
3798      if (*p_spk != 'c' || (wp->w_p_diff && curwin->w_p_diff)) {
3799        skip_update_topline = true;
3800      }
3801      check_cursor(wp);
3802      fp = var2fpos(&argvars[0], true, &fnum, false, wp);
3803      skip_update_topline = false;
3804    }
3805  } else {
3806    // use current window
3807    fp = var2fpos(&argvars[0], true, &fnum, false, curwin);
3808  }
3809
3810  if (fp != NULL) {
3811    lnum = fp->lnum;
3812  }
3813  rettv->vval.v_number = lnum;
3814}
3815
3816/// "line2byte(lnum)" function
3817static void f_line2byte(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
3818{
3819  const linenr_T lnum = tv_get_lnum(argvars);
3820  if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1) {
3821    rettv->vval.v_number = -1;
3822  } else {
3823    rettv->vval.v_number = ml_find_line_or_offset(curbuf, lnum, NULL, false);
3824  }
3825  if (rettv->vval.v_number >= 0) {
3826    rettv->vval.v_number++;
3827  }
3828}
3829
3830/// "localtime()" function
3831static void f_localtime(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
3832{
3833  rettv->vval.v_number = (varnumber_T)time(NULL);
3834}
3835
3836/// luaeval() function implementation
3837static void f_luaeval(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
3838  FUNC_ATTR_NONNULL_ALL
3839{
3840  const char *const str = tv_get_string_chk(&argvars[0]);
3841  if (str == NULL) {
3842    return;
3843  }
3844
3845  nlua_call_luaeval(cstr_as_string(str), &argvars[1], rettv);
3846}
3847
3848static void find_some_match(typval_T *const argvars, typval_T *const rettv,
3849                            const SomeMatchType type)
3850{
3851  char *str = NULL;
3852  int64_t len = 0;
3853  char *expr = NULL;
3854  regmatch_T regmatch;
3855  int64_t start = 0;
3856  int64_t nth = 1;
3857  colnr_T startcol = 0;
3858  bool match = false;
3859  list_T *l = NULL;
3860  int idx = 0;
3861  char *tofree = NULL;
3862
3863  // Make 'cpoptions' empty, the 'l' flag should not be used here.
3864  char *save_cpo = p_cpo;
3865  p_cpo = empty_string_option;
3866
3867  rettv->vval.v_number = -1;
3868  switch (type) {
3869  // matchlist(): return empty list when there are no matches.
3870  case kSomeMatchList:
3871    tv_list_alloc_ret(rettv, kListLenMayKnow);
3872    break;
3873  // matchstrpos(): return ["", -1, -1, -1]
3874  case kSomeMatchStrPos:
3875    tv_list_alloc_ret(rettv, 4);
3876    tv_list_append_string(rettv->vval.v_list, "", 0);
3877    tv_list_append_number(rettv->vval.v_list, -1);
3878    tv_list_append_number(rettv->vval.v_list, -1);
3879    tv_list_append_number(rettv->vval.v_list, -1);
3880    break;
3881  case kSomeMatchStr:
3882    rettv->v_type = VAR_STRING;
3883    rettv->vval.v_string = NULL;
3884    break;
3885  case kSomeMatch:
3886  case kSomeMatchEnd:
3887    // Do nothing: zero is default.
3888    break;
3889  }
3890
3891  listitem_T *li = NULL;
3892  if (argvars[0].v_type == VAR_LIST) {
3893    if ((l = argvars[0].vval.v_list) == NULL) {
3894      goto theend;
3895    }
3896    li = tv_list_first(l);
3897  } else {
3898    expr = str = (char *)tv_get_string(&argvars[0]);
3899    len = (int64_t)strlen(str);
3900  }
3901
3902  char patbuf[NUMBUFLEN];
3903  const char *const pat = tv_get_string_buf_chk(&argvars[1], patbuf);
3904  if (pat == NULL) {
3905    goto theend;
3906  }
3907
3908  if (argvars[2].v_type != VAR_UNKNOWN) {
3909    bool error = false;
3910
3911    start = tv_get_number_chk(&argvars[2], &error);
3912    if (error) {
3913      goto theend;
3914    }
3915    if (l != NULL) {
3916      idx = tv_list_uidx(l, (int)start);
3917      if (idx == -1) {
3918        goto theend;
3919      }
3920      li = tv_list_find(l, idx);
3921    } else {
3922      if (start < 0) {
3923        start = 0;
3924      }
3925      if (start > len) {
3926        goto theend;
3927      }
3928      // When "count" argument is there ignore matches before "start",
3929      // otherwise skip part of the string.  Differs when pattern is "^"
3930      // or "\<".
3931      if (argvars[3].v_type != VAR_UNKNOWN) {
3932        startcol = (colnr_T)start;
3933      } else {
3934        str += start;
3935        len -= start;
3936      }
3937    }
3938
3939    if (argvars[3].v_type != VAR_UNKNOWN) {
3940      nth = tv_get_number_chk(&argvars[3], &error);
3941    }
3942    if (error) {
3943      goto theend;
3944    }
3945  }
3946
3947  regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
3948  if (regmatch.regprog != NULL) {
3949    regmatch.rm_ic = p_ic;
3950
3951    while (true) {
3952      if (l != NULL) {
3953        if (li == NULL) {
3954          match = false;
3955          break;
3956        }
3957        xfree(tofree);
3958        tofree = expr = str = encode_tv2echo(TV_LIST_ITEM_TV(li), NULL);
3959        if (str == NULL) {
3960          break;
3961        }
3962      }
3963
3964      match = vim_regexec_nl(&regmatch, str, startcol);
3965
3966      if (match && --nth <= 0) {
3967        break;
3968      }
3969      if (l == NULL && !match) {
3970        break;
3971      }
3972
3973      // Advance to just after the match.
3974      if (l != NULL) {
3975        li = TV_LIST_ITEM_NEXT(l, li);
3976        idx++;
3977      } else {
3978        startcol = (colnr_T)(regmatch.startp[0]
3979                             + utfc_ptr2len(regmatch.startp[0]) - str);
3980        if (startcol > (colnr_T)len || str + startcol <= regmatch.startp[0]) {
3981          match = false;
3982          break;
3983        }
3984      }
3985    }
3986
3987    if (match) {
3988      switch (type) {
3989      case kSomeMatchStrPos: {
3990        list_T *const ret_l = rettv->vval.v_list;
3991        listitem_T *li1 = tv_list_first(ret_l);
3992        listitem_T *li2 = TV_LIST_ITEM_NEXT(ret_l, li1);
3993        listitem_T *li3 = TV_LIST_ITEM_NEXT(ret_l, li2);
3994        listitem_T *li4 = TV_LIST_ITEM_NEXT(ret_l, li3);
3995        xfree(TV_LIST_ITEM_TV(li1)->vval.v_string);
3996
3997        const size_t rd = (size_t)(regmatch.endp[0] - regmatch.startp[0]);
3998        TV_LIST_ITEM_TV(li1)->vval.v_string = xmemdupz(regmatch.startp[0], rd);
3999        TV_LIST_ITEM_TV(li3)->vval.v_number = (varnumber_T)(regmatch.startp[0] - expr);
4000        TV_LIST_ITEM_TV(li4)->vval.v_number = (varnumber_T)(regmatch.endp[0] - expr);
4001        if (l != NULL) {
4002          TV_LIST_ITEM_TV(li2)->vval.v_number = (varnumber_T)idx;
4003        }
4004        break;
4005      }
4006      case kSomeMatchList:
4007        // Return list with matched string and submatches.
4008        for (int i = 0; i < NSUBEXP; i++) {
4009          if (regmatch.endp[i] == NULL) {
4010            tv_list_append_string(rettv->vval.v_list, NULL, 0);
4011          } else {
4012            tv_list_append_string(rettv->vval.v_list, regmatch.startp[i],
4013                                  (regmatch.endp[i] - regmatch.startp[i]));
4014          }
4015        }
4016        break;
4017      case kSomeMatchStr:
4018        // Return matched string.
4019        if (l != NULL) {
4020          tv_copy(TV_LIST_ITEM_TV(li), rettv);
4021        } else {
4022          rettv->vval.v_string = xmemdupz(regmatch.startp[0],
4023                                          (size_t)(regmatch.endp[0] -
4024                                                   regmatch.startp[0]));
4025        }
4026        break;
4027      case kSomeMatch:
4028      case kSomeMatchEnd:
4029        if (l != NULL) {
4030          rettv->vval.v_number = idx;
4031        } else {
4032          if (type == kSomeMatch) {
4033            rettv->vval.v_number = (varnumber_T)(regmatch.startp[0] - str);
4034          } else {
4035            rettv->vval.v_number = (varnumber_T)(regmatch.endp[0] - str);
4036          }
4037          rettv->vval.v_number += (varnumber_T)(str - expr);
4038        }
4039        break;
4040      }
4041    }
4042    vim_regfree(regmatch.regprog);
4043  }
4044
4045theend:
4046  if (type == kSomeMatchStrPos && l == NULL && rettv->vval.v_list != NULL) {
4047    // matchstrpos() without a list: drop the second item
4048    list_T *const ret_l = rettv->vval.v_list;
4049    tv_list_item_remove(ret_l, TV_LIST_ITEM_NEXT(ret_l, tv_list_first(ret_l)));
4050  }
4051
4052  xfree(tofree);
4053  p_cpo = save_cpo;
4054}
4055
4056/// Return all the matches in string "str" for pattern "rmp".
4057/// The matches are returned in the List "mlist".
4058/// If "submatches" is true, then submatch information is also returned.
4059/// "matchbuf" is true when called for matchbufline().
4060static void get_matches_in_str(const char *str, regmatch_T *rmp, list_T *mlist, int idx,
4061                               bool submatches, bool matchbuf)
4062{
4063  size_t len = strlen(str);
4064  int match = 0;
4065  colnr_T startidx = 0;
4066
4067  while (true) {
4068    match = vim_regexec_nl(rmp, str, startidx);
4069    if (!match) {
4070      break;
4071    }
4072
4073    dict_T *d = tv_dict_alloc();
4074    tv_list_append_dict(mlist, d);
4075
4076    if (matchbuf) {
4077      tv_dict_add_nr(d, S_LEN("lnum"), idx);
4078    } else {
4079      tv_dict_add_nr(d, S_LEN("idx"), idx);
4080    }
4081
4082    tv_dict_add_nr(d, S_LEN("byteidx"),
4083                   (colnr_T)(rmp->startp[0] - str));
4084
4085    tv_dict_add_str_len(d, S_LEN("text"), rmp->startp[0],
4086                        (int)(rmp->endp[0] - rmp->startp[0]));
4087
4088    if (submatches) {
4089      list_T *sml = tv_list_alloc(NSUBEXP - 1);
4090
4091      tv_dict_add_list(d, S_LEN("submatches"), sml);
4092
4093      // return a list with the submatches
4094      for (int i = 1; i < NSUBEXP; i++) {
4095        if (rmp->endp[i] == NULL) {
4096          tv_list_append_string(sml, "", 0);
4097        } else {
4098          tv_list_append_string(sml, rmp->startp[i], rmp->endp[i] - rmp->startp[i]);
4099        }
4100      }
4101    }
4102    startidx = (colnr_T)(rmp->endp[0] - str);
4103    if (startidx >= (colnr_T)len || str + startidx <= rmp->startp[0]) {
4104      break;
4105    }
4106  }
4107}
4108
4109/// "matchbufline()" function
4110static void f_matchbufline(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
4111{
4112  rettv->vval.v_number = -1;
4113  tv_list_alloc_ret(rettv, kListLenUnknown);
4114  list_T *retlist = rettv->vval.v_list;
4115
4116  if (tv_check_for_buffer_arg(argvars, 0) == FAIL
4117      || tv_check_for_string_arg(argvars, 1) == FAIL
4118      || tv_check_for_lnum_arg(argvars, 2) == FAIL
4119      || tv_check_for_lnum_arg(argvars, 3) == FAIL
4120      || tv_check_for_opt_dict_arg(argvars, 4) == FAIL) {
4121    return;
4122  }
4123
4124  const int prev_did_emsg = did_emsg;
4125  buf_T *buf = tv_get_buf(&argvars[0], false);
4126  if (buf == NULL) {
4127    if (did_emsg == prev_did_emsg) {
4128      semsg(_(e_invalid_buffer_name_str), tv_get_string(&argvars[0]));
4129    }
4130    return;
4131  }
4132  if (buf->b_ml.ml_mfp == NULL) {
4133    emsg(_(e_buffer_is_not_loaded));
4134    return;
4135  }
4136
4137  char patbuf[NUMBUFLEN];
4138  const char *pat = tv_get_string_buf(&argvars[1], patbuf);
4139
4140  const int did_emsg_before = did_emsg;
4141  linenr_T slnum = tv_get_lnum_buf(&argvars[2], buf);
4142  if (did_emsg > did_emsg_before) {
4143    return;
4144  }
4145  if (slnum < 1) {
4146    semsg(_(e_invargval), "lnum");
4147    return;
4148  }
4149
4150  linenr_T elnum = tv_get_lnum_buf(&argvars[3], buf);
4151  if (did_emsg > did_emsg_before) {
4152    return;
4153  }
4154  if (elnum < 1 || elnum < slnum) {
4155    semsg(_(e_invargval), "end_lnum");
4156    return;
4157  }
4158
4159  if (elnum > buf->b_ml.ml_line_count) {
4160    elnum = buf->b_ml.ml_line_count;
4161  }
4162
4163  bool submatches = false;
4164  if (argvars[4].v_type != VAR_UNKNOWN) {
4165    dict_T *d = argvars[4].vval.v_dict;
4166    if (d != NULL) {
4167      dictitem_T *di = tv_dict_find(d, S_LEN("submatches"));
4168      if (di != NULL) {
4169        if (di->di_tv.v_type != VAR_BOOL) {
4170          semsg(_(e_invargval), "submatches");
4171          return;
4172        }
4173        submatches = tv_get_bool(&di->di_tv);
4174      }
4175    }
4176  }
4177
4178  // Make 'cpoptions' empty, the 'l' flag should not be used here.
4179  char *const save_cpo = p_cpo;
4180  p_cpo = empty_string_option;
4181
4182  regmatch_T regmatch;
4183  regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
4184  if (regmatch.regprog == NULL) {
4185    goto theend;
4186  }
4187  regmatch.rm_ic = p_ic;
4188
4189  while (slnum <= elnum) {
4190    const char *str = ml_get_buf(buf, slnum);
4191    get_matches_in_str(str, &regmatch, retlist, slnum, submatches, true);
4192    slnum++;
4193  }
4194
4195  vim_regfree(regmatch.regprog);
4196
4197theend:
4198  p_cpo = save_cpo;
4199}
4200
4201/// "match()" function
4202static void f_match(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
4203{
4204  find_some_match(argvars, rettv, kSomeMatch);
4205}
4206
4207/// "matchend()" function
4208static void f_matchend(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
4209{
4210  find_some_match(argvars, rettv, kSomeMatchEnd);
4211}
4212
4213/// "matchlist()" function
4214static void f_matchlist(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
4215{
4216  find_some_match(argvars, rettv, kSomeMatchList);
4217}
4218
4219/// "matchstr()" function
4220static void f_matchstr(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
4221{
4222  find_some_match(argvars, rettv, kSomeMatchStr);
4223}
4224
4225/// "matchstrlist()" function
4226static void f_matchstrlist(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
4227{
4228  rettv->vval.v_number = -1;
4229  tv_list_alloc_ret(rettv, kListLenUnknown);
4230  list_T *retlist = rettv->vval.v_list;
4231
4232  if (tv_check_for_list_arg(argvars, 0) == FAIL
4233      || tv_check_for_string_arg(argvars, 1) == FAIL
4234      || tv_check_for_opt_dict_arg(argvars, 2) == FAIL) {
4235    return;
4236  }
4237
4238  list_T *l = NULL;
4239  if ((l = argvars[0].vval.v_list) == NULL) {
4240    return;
4241  }
4242
4243  char patbuf[NUMBUFLEN];
4244  const char *pat = tv_get_string_buf_chk(&argvars[1], patbuf);
4245  if (pat == NULL) {
4246    return;
4247  }
4248
4249  // Make 'cpoptions' empty, the 'l' flag should not be used here.
4250  char *const save_cpo = p_cpo;
4251  p_cpo = empty_string_option;
4252
4253  regmatch_T regmatch;
4254  regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
4255  if (regmatch.regprog == NULL) {
4256    goto theend;
4257  }
4258  regmatch.rm_ic = p_ic;
4259
4260  bool submatches = false;
4261  if (argvars[2].v_type != VAR_UNKNOWN) {
4262    dict_T *d = argvars[2].vval.v_dict;
4263    if (d != NULL) {
4264      dictitem_T *di = tv_dict_find(d, S_LEN("submatches"));
4265      if (di != NULL) {
4266        if (di->di_tv.v_type != VAR_BOOL) {
4267          semsg(_(e_invargval), "submatches");
4268          goto cleanup;
4269        }
4270        submatches = tv_get_bool(&di->di_tv);
4271      }
4272    }
4273  }
4274
4275  int idx = 0;
4276  TV_LIST_ITER_CONST(l, li, {
4277    const typval_T *const li_tv = TV_LIST_ITEM_TV(li);
4278    if (li_tv->v_type == VAR_STRING && li_tv->vval.v_string != NULL) {
4279      const char *str = li_tv->vval.v_string;
4280      get_matches_in_str(str, &regmatch, retlist, idx, submatches, false);
4281    }
4282    idx++;
4283  });
4284
4285cleanup:
4286  vim_regfree(regmatch.regprog);
4287
4288theend:
4289  p_cpo = save_cpo;
4290}
4291
4292/// "matchstrpos()" function
4293static void f_matchstrpos(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
4294{
4295  find_some_match(argvars, rettv, kSomeMatchStrPos);
4296}
4297
4298/// Get maximal/minimal number value in a list or dictionary
4299///
4300/// @param[in]  tv  List or dictionary to work with. If it contains something
4301///                 that is not an integer number (or cannot be coerced to
4302///                 it) error is given.
4303/// @param[out]  rettv  Location where result will be saved. Only assigns
4304///                     vval.v_number, type is not touched. Returns zero for
4305///                     empty lists/dictionaries.
4306/// @param[in]  domax  Determines whether maximal or minimal value is desired.
4307static void max_min(const typval_T *const tv, typval_T *const rettv, const bool domax)
4308  FUNC_ATTR_NONNULL_ALL
4309{
4310  bool error = false;
4311
4312  rettv->vval.v_number = 0;
4313  varnumber_T n = (domax ? VARNUMBER_MIN : VARNUMBER_MAX);
4314  if (tv->v_type == VAR_LIST) {
4315    if (tv_list_len(tv->vval.v_list) == 0) {
4316      return;
4317    }
4318    TV_LIST_ITER_CONST(tv->vval.v_list, li, {
4319      const varnumber_T i = tv_get_number_chk(TV_LIST_ITEM_TV(li), &error);
4320      if (error) {
4321        return;  // type error; errmsg already given
4322      }
4323      if (domax ? i > n : i < n) {
4324        n = i;
4325      }
4326    });
4327  } else if (tv->v_type == VAR_DICT) {
4328    if (tv_dict_len(tv->vval.v_dict) == 0) {
4329      return;
4330    }
4331    TV_DICT_ITER(tv->vval.v_dict, di, {
4332      const varnumber_T i = tv_get_number_chk(&di->di_tv, &error);
4333      if (error) {
4334        return;  // type error; errmsg already given
4335      }
4336      if (domax ? i > n : i < n) {
4337        n = i;
4338      }
4339    });
4340  } else {
4341    semsg(_(e_listdictarg), domax ? "max()" : "min()");
4342    return;
4343  }
4344
4345  rettv->vval.v_number = n;
4346}
4347
4348/// "max()" function
4349static void f_max(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
4350{
4351  max_min(argvars, rettv, true);
4352}
4353
4354/// "min()" function
4355static void f_min(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
4356{
4357  max_min(argvars, rettv, false);
4358}
4359
4360/// "mode()" function
4361static void f_mode(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
4362{
4363  char buf[MODE_MAX_LENGTH];
4364
4365  get_mode(buf);
4366
4367  // Clear out the minor mode when the argument is not a non-zero number or
4368  // non-empty string.
4369  if (!non_zero_arg(&argvars[0])) {
4370    buf[1] = NUL;
4371  }
4372
4373  rettv->vval.v_string = xstrdup(buf);
4374  rettv->v_type = VAR_STRING;
4375}
4376
4377static void may_add_state_char(garray_T *gap, const char *include, uint8_t c)
4378{
4379  if (include == NULL || vim_strchr(include, c) != NULL) {
4380    ga_append(gap, c);
4381  }
4382}
4383
4384/// "state()" function
4385static void f_state(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
4386{
4387  garray_T ga;
4388  ga_init(&ga, 1, 20);
4389  const char *include = NULL;
4390
4391  if (argvars[0].v_type != VAR_UNKNOWN) {
4392    include = tv_get_string(&argvars[0]);
4393  }
4394
4395  if (!(stuff_empty() && typebuf.tb_len == 0 && !using_script())) {
4396    may_add_state_char(&ga, include, 'm');
4397  }
4398  if (op_pending()) {
4399    may_add_state_char(&ga, include, 'o');
4400  }
4401  if (autocmd_busy) {
4402    may_add_state_char(&ga, include, 'x');
4403  }
4404  if (ins_compl_active()) {
4405    may_add_state_char(&ga, include, 'a');
4406  }
4407  if (!get_was_safe_state()) {
4408    may_add_state_char(&ga, include, 'S');
4409  }
4410  for (int i = 0; i < get_callback_depth() && i < 3; i++) {
4411    may_add_state_char(&ga, include, 'c');
4412  }
4413  if (msg_scrolled > 0) {
4414    may_add_state_char(&ga, include, 's');
4415  }
4416
4417  rettv->v_type = VAR_STRING;
4418  rettv->vval.v_string = ga.ga_data;
4419}
4420
4421/// "msgpackdump()" function
4422static void f_msgpackdump(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
4423  FUNC_ATTR_NONNULL_ALL
4424{
4425  if (argvars[0].v_type != VAR_LIST) {
4426    semsg(_(e_listarg), "msgpackdump()");
4427    return;
4428  }
4429  list_T *const list = argvars[0].vval.v_list;
4430  PackerBuffer packer = packer_string_buffer();
4431  const char *const msg = _("msgpackdump() argument, index %i");
4432  // Assume that translation will not take more then 4 times more space
4433  char msgbuf[sizeof("msgpackdump() argument, index ") * 4 + NUMBUFLEN];
4434  int idx = 0;
4435  TV_LIST_ITER(list, li, {
4436    vim_snprintf(msgbuf, sizeof(msgbuf), msg, idx);
4437    idx++;
4438    if (encode_vim_to_msgpack(&packer, TV_LIST_ITEM_TV(li), msgbuf) == FAIL) {
4439      break;
4440    }
4441  });
4442  String data = packer_take_string(&packer);
4443  if (argvars[1].v_type != VAR_UNKNOWN && strequal(tv_get_string(&argvars[1]), "B")) {
4444    blob_T *b = tv_blob_alloc_ret(rettv);
4445    b->bv_ga.ga_data = data.data;
4446    b->bv_ga.ga_len = (int)data.size;
4447    b->bv_ga.ga_maxlen = (int)(packer.endptr - packer.startptr);
4448  } else {
4449    encode_list_write(tv_list_alloc_ret(rettv, kListLenMayKnow), data.data, data.size);
4450    api_free_string(data);
4451  }
4452}
4453
4454static void emsg_mpack_error(int status)
4455{
4456  switch (status) {
4457  case MPACK_ERROR:
4458    semsg(_(e_invarg2), "Failed to parse msgpack string");
4459    break;
4460
4461  case MPACK_EOF:
4462    semsg(_(e_invarg2), "Incomplete msgpack string");
4463    break;
4464
4465  case MPACK_NOMEM:
4466    semsg(_(e_invarg2), "object was too deep to unpack");
4467    break;
4468
4469  default:
4470    break;
4471  }
4472}
4473
4474static void msgpackparse_unpack_list(const list_T *const list, list_T *const ret_list)
4475  FUNC_ATTR_NONNULL_ARG(2)
4476{
4477  if (tv_list_len(list) == 0) {
4478    return;
4479  }
4480  if (TV_LIST_ITEM_TV(tv_list_first(list))->v_type != VAR_STRING) {
4481    semsg(_(e_invarg2), "List item is not a string");
4482    return;
4483  }
4484  ListReaderState lrstate = encode_init_lrstate(list);
4485  char *buf = alloc_block();
4486  size_t buf_size = 0;
4487
4488  typval_T cur_item = { .v_type = VAR_UNKNOWN };
4489  mpack_parser_t parser;
4490  mpack_parser_init(&parser, 0);
4491  parser.data.p = &cur_item;
4492
4493  int status = MPACK_OK;
4494  while (true) {
4495    size_t read_bytes;
4496    const int rlret = encode_read_from_list(&lrstate, buf + buf_size, ARENA_BLOCK_SIZE - buf_size,
4497                                            &read_bytes);
4498    if (rlret == FAIL) {
4499      semsg(_(e_invarg2), "List item is not a string");
4500      goto end;
4501    }
4502    buf_size += read_bytes;
4503
4504    const char *ptr = buf;
4505    while (buf_size) {
4506      status = mpack_parse_typval(&parser, &ptr, &buf_size);
4507      if (status == MPACK_OK) {
4508        tv_list_append_owned_tv(ret_list, cur_item);
4509        cur_item.v_type = VAR_UNKNOWN;
4510      } else {
4511        break;
4512      }
4513    }
4514
4515    if (rlret == OK) {
4516      break;
4517    }
4518
4519    if (status == MPACK_EOF) {
4520      // move remaining data to front of buffer
4521      if (buf_size && ptr > buf) {
4522        memmove(buf, ptr, buf_size);
4523      }
4524    } else if (status != MPACK_OK) {
4525      break;
4526    }
4527  }
4528
4529  if (status != MPACK_OK) {
4530    typval_parser_error_free(&parser);
4531    emsg_mpack_error(status);
4532  }
4533
4534end:
4535  free_block(buf);
4536}
4537
4538static void msgpackparse_unpack_blob(const blob_T *const blob, list_T *const ret_list)
4539  FUNC_ATTR_NONNULL_ARG(2)
4540{
4541  const int len = tv_blob_len(blob);
4542  if (len == 0) {
4543    return;
4544  }
4545
4546  const char *data = blob->bv_ga.ga_data;
4547  size_t remaining = (size_t)len;
4548  while (remaining) {
4549    typval_T tv;
4550    int status = unpack_typval(&data, &remaining, &tv);
4551    if (status != MPACK_OK) {
4552      emsg_mpack_error(status);
4553      return;
4554    }
4555
4556    tv_list_append_owned_tv(ret_list, tv);
4557  }
4558}
4559
4560/// "msgpackparse" function
4561static void f_msgpackparse(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
4562  FUNC_ATTR_NONNULL_ALL
4563{
4564  if (argvars[0].v_type != VAR_LIST && argvars[0].v_type != VAR_BLOB) {
4565    semsg(_(e_listblobarg), "msgpackparse()");
4566    return;
4567  }
4568  list_T *const ret_list = tv_list_alloc_ret(rettv, kListLenMayKnow);
4569  if (argvars[0].v_type == VAR_LIST) {
4570    msgpackparse_unpack_list(argvars[0].vval.v_list, ret_list);
4571  } else {
4572    msgpackparse_unpack_blob(argvars[0].vval.v_blob, ret_list);
4573  }
4574}
4575
4576/// "nextnonblank()" function
4577static void f_nextnonblank(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
4578{
4579  linenr_T lnum;
4580
4581  for (lnum = tv_get_lnum(argvars);; lnum++) {
4582    if (lnum < 0 || lnum > curbuf->b_ml.ml_line_count) {
4583      lnum = 0;
4584      break;
4585    }
4586    if (*skipwhite(ml_get(lnum)) != NUL) {
4587      break;
4588    }
4589  }
4590  rettv->vval.v_number = lnum;
4591}
4592
4593/// "nr2char()" function
4594static void f_nr2char(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
4595{
4596  if (argvars[1].v_type != VAR_UNKNOWN) {
4597    if (!tv_check_num(&argvars[1])) {
4598      return;
4599    }
4600  }
4601
4602  bool error = false;
4603  const varnumber_T num = tv_get_number_chk(&argvars[0], &error);
4604  if (error) {
4605    return;
4606  }
4607  if (num < 0) {
4608    emsg(_("E5070: Character number must not be less than zero"));
4609    return;
4610  }
4611  if (num > INT_MAX) {
4612    semsg(_("E5071: Character number must not be greater than INT_MAX (%i)"),
4613          INT_MAX);
4614    return;
4615  }
4616
4617  char buf[MB_MAXCHAR];
4618  const int len = utf_char2bytes((int)num, buf);
4619
4620  rettv->v_type = VAR_STRING;
4621  rettv->vval.v_string = xmemdupz(buf, (size_t)len);
4622}
4623
4624/// "or(expr, expr)" function
4625static void f_or(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
4626{
4627  rettv->vval.v_number = tv_get_number_chk(&argvars[0], NULL)
4628                         | tv_get_number_chk(&argvars[1], NULL);
4629}
4630
4631/// "pow()" function
4632static void f_pow(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
4633{
4634  float_T fx;
4635  float_T fy;
4636
4637  rettv->v_type = VAR_FLOAT;
4638  if (tv_get_float_chk(argvars, &fx) && tv_get_float_chk(&argvars[1], &fy)) {
4639    rettv->vval.v_float = pow(fx, fy);
4640  } else {
4641    rettv->vval.v_float = 0.0;
4642  }
4643}
4644
4645/// "prevnonblank()" function
4646static void f_prevnonblank(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
4647{
4648  linenr_T lnum = tv_get_lnum(argvars);
4649  if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count) {
4650    lnum = 0;
4651  } else {
4652    while (lnum >= 1 && *skipwhite(ml_get(lnum)) == NUL) {
4653      lnum--;
4654    }
4655  }
4656  rettv->vval.v_number = lnum;
4657}
4658
4659/// "printf()" function
4660static void f_printf(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
4661{
4662  rettv->v_type = VAR_STRING;
4663  rettv->vval.v_string = NULL;
4664  {
4665    int saved_did_emsg = did_emsg;
4666
4667    // Get the required length, allocate the buffer and do it for real.
4668    did_emsg = false;
4669    char buf[NUMBUFLEN];
4670    const char *fmt = tv_get_string_buf(&argvars[0], buf);
4671    int len = vim_vsnprintf_typval(NULL, 0, fmt, dummy_ap, argvars + 1);
4672    if (!did_emsg) {
4673      char *s = xmalloc((size_t)len + 1);
4674      rettv->vval.v_string = s;
4675      vim_vsnprintf_typval(s, (size_t)len + 1, fmt, dummy_ap, argvars + 1);
4676    }
4677    did_emsg |= saved_did_emsg;
4678  }
4679}
4680
4681/// "pum_getpos()" function
4682static void f_pum_getpos(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
4683{
4684  tv_dict_alloc_ret(rettv);
4685  pum_set_event_info(rettv->vval.v_dict);
4686}
4687
4688/// "pumvisible()" function
4689static void f_pumvisible(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
4690{
4691  if (pum_visible()) {
4692    rettv->vval.v_number = 1;
4693  }
4694}
4695
4696/// "py3eval()" and "pyxeval()" functions (always python3)
4697static void f_py3eval(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
4698{
4699  script_host_eval("python3", argvars, rettv);
4700}
4701
4702static void init_srand(uint32_t *const x)
4703  FUNC_ATTR_NONNULL_ALL
4704{
4705  union {
4706    uint32_t number;
4707    uint8_t bytes[sizeof(uint32_t)];
4708  } buf;
4709
4710  if (uv_random(NULL, NULL, buf.bytes, sizeof(buf.bytes), 0, NULL) == 0) {
4711    *x = buf.number;
4712    return;
4713  }
4714
4715  // The system's random number generator doesn't work,
4716  // fall back to os_hrtime() XOR with process ID
4717  *x = (uint32_t)os_hrtime();
4718  *x ^= (uint32_t)os_get_pid();
4719}
4720
4721static inline uint32_t splitmix32(uint32_t *const x)
4722  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_ALWAYS_INLINE
4723{
4724  uint32_t z = (*x += 0x9e3779b9);
4725  z = (z ^ (z >> 16)) * 0x85ebca6b;
4726  z = (z ^ (z >> 13)) * 0xc2b2ae35;
4727  return z ^ (z >> 16);
4728}
4729
4730static inline uint32_t shuffle_xoshiro128starstar(uint32_t *const x, uint32_t *const y,
4731                                                  uint32_t *const z, uint32_t *const w)
4732  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_ALWAYS_INLINE
4733{
4734#define ROTL(x, k) (((x) << (k)) | ((x) >> (32 - (k))))
4735  const uint32_t result = ROTL(*y * 5, 7) * 9;
4736  const uint32_t t = *y << 9;
4737  *z ^= *x;
4738  *w ^= *y;
4739  *y ^= *z;
4740  *x ^= *w;
4741  *z ^= t;
4742  *w = ROTL(*w, 11);
4743#undef ROTL
4744  return result;
4745}
4746
4747/// "rand()" function
4748static void f_rand(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
4749{
4750  uint32_t result;
4751
4752  if (argvars[0].v_type == VAR_UNKNOWN) {
4753    static uint32_t gx, gy, gz, gw;
4754    static bool initialized = false;
4755
4756    // When no argument is given use the global seed list.
4757    if (!initialized) {
4758      // Initialize the global seed list.
4759      uint32_t x = 0;
4760      init_srand(&x);
4761
4762      gx = splitmix32(&x);
4763      gy = splitmix32(&x);
4764      gz = splitmix32(&x);
4765      gw = splitmix32(&x);
4766      initialized = true;
4767    }
4768
4769    result = shuffle_xoshiro128starstar(&gx, &gy, &gz, &gw);
4770  } else if (argvars[0].v_type == VAR_LIST) {
4771    list_T *const l = argvars[0].vval.v_list;
4772    if (tv_list_len(l) != 4) {
4773      goto theend;
4774    }
4775
4776    typval_T *const tvx = TV_LIST_ITEM_TV(tv_list_find(l, 0));
4777    typval_T *const tvy = TV_LIST_ITEM_TV(tv_list_find(l, 1));
4778    typval_T *const tvz = TV_LIST_ITEM_TV(tv_list_find(l, 2));
4779    typval_T *const tvw = TV_LIST_ITEM_TV(tv_list_find(l, 3));
4780    if (tvx->v_type != VAR_NUMBER) {
4781      goto theend;
4782    }
4783    if (tvy->v_type != VAR_NUMBER) {
4784      goto theend;
4785    }
4786    if (tvz->v_type != VAR_NUMBER) {
4787      goto theend;
4788    }
4789    if (tvw->v_type != VAR_NUMBER) {
4790      goto theend;
4791    }
4792    uint32_t x = (uint32_t)tvx->vval.v_number;
4793    uint32_t y = (uint32_t)tvy->vval.v_number;
4794    uint32_t z = (uint32_t)tvz->vval.v_number;
4795    uint32_t w = (uint32_t)tvw->vval.v_number;
4796
4797    result = shuffle_xoshiro128starstar(&x, &y, &z, &w);
4798
4799    tvx->vval.v_number = (varnumber_T)x;
4800    tvy->vval.v_number = (varnumber_T)y;
4801    tvz->vval.v_number = (varnumber_T)z;
4802    tvw->vval.v_number = (varnumber_T)w;
4803  } else {
4804    goto theend;
4805  }
4806
4807  rettv->v_type = VAR_NUMBER;
4808  rettv->vval.v_number = (varnumber_T)result;
4809  return;
4810
4811theend:
4812  semsg(_(e_invarg2), tv_get_string(&argvars[0]));
4813  rettv->v_type = VAR_NUMBER;
4814  rettv->vval.v_number = -1;
4815}
4816
4817/// "srand()" function
4818static void f_srand(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
4819{
4820  uint32_t x = 0;
4821
4822  tv_list_alloc_ret(rettv, 4);
4823  if (argvars[0].v_type == VAR_UNKNOWN) {
4824    init_srand(&x);
4825  } else {
4826    bool error = false;
4827    x = (uint32_t)tv_get_number_chk(&argvars[0], &error);
4828    if (error) {
4829      return;
4830    }
4831  }
4832
4833  tv_list_append_number(rettv->vval.v_list, (varnumber_T)splitmix32(&x));
4834  tv_list_append_number(rettv->vval.v_list, (varnumber_T)splitmix32(&x));
4835  tv_list_append_number(rettv->vval.v_list, (varnumber_T)splitmix32(&x));
4836  tv_list_append_number(rettv->vval.v_list, (varnumber_T)splitmix32(&x));
4837}
4838
4839/// "perleval()" function
4840static void f_perleval(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
4841{
4842  script_host_eval("perl", argvars, rettv);
4843}
4844
4845/// "rubyeval()" function
4846static void f_rubyeval(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
4847{
4848  script_host_eval("ruby", argvars, rettv);
4849}
4850
4851/// "range()" function
4852static void f_range(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
4853{
4854  varnumber_T end;
4855  varnumber_T stride = 1;
4856  bool error = false;
4857
4858  varnumber_T start = tv_get_number_chk(&argvars[0], &error);
4859  if (argvars[1].v_type == VAR_UNKNOWN) {
4860    end = start - 1;
4861    start = 0;
4862  } else {
4863    end = tv_get_number_chk(&argvars[1], &error);
4864    if (argvars[2].v_type != VAR_UNKNOWN) {
4865      stride = tv_get_number_chk(&argvars[2], &error);
4866    }
4867  }
4868
4869  if (error) {
4870    return;  // Type error; errmsg already given.
4871  }
4872  if (stride == 0) {
4873    emsg(_("E726: Stride is zero"));
4874    return;
4875  }
4876  if (stride > 0 ? end + 1 < start : end - 1 > start) {
4877    emsg(_("E727: Start past end"));
4878    return;
4879  }
4880
4881  tv_list_alloc_ret(rettv, (end - start) / stride);
4882  for (varnumber_T i = start; stride > 0 ? i <= end : i >= end; i += stride) {
4883    tv_list_append_number(rettv->vval.v_list, i);
4884  }
4885}
4886
4887/// "getreginfo()" function
4888static void f_getreginfo(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
4889{
4890  int regname = getreg_get_regname(argvars);
4891  if (regname == 0) {
4892    return;
4893  }
4894
4895  if (regname == '@') {
4896    regname = '"';
4897  }
4898
4899  tv_dict_alloc_ret(rettv);
4900  dict_T *const dict = rettv->vval.v_dict;
4901
4902  list_T *const list = get_reg_contents(regname, kGRegExprSrc | kGRegList);
4903  if (list == NULL) {
4904    return;
4905  }
4906  tv_dict_add_list(dict, S_LEN("regcontents"), list);
4907
4908  char buf[NUMBUFLEN + 2];
4909  size_t buflen;
4910  colnr_T reglen = 0;
4911  switch (get_reg_type(regname, &reglen)) {
4912  case kMTLineWise:
4913    buf[0] = 'V';
4914    buf[1] = NUL;
4915    buflen = 1;
4916    break;
4917  case kMTCharWise:
4918    buf[0] = 'v';
4919    buf[1] = NUL;
4920    buflen = 1;
4921    break;
4922  case kMTBlockWise:
4923    buflen = vim_snprintf_safelen(buf, sizeof(buf), "%c%d", Ctrl_V, reglen + 1);
4924    break;
4925  case kMTUnknown:
4926    abort();
4927  }
4928  tv_dict_add_str_len(dict, S_LEN("regtype"), buf, (int)buflen);
4929
4930  buf[0] = (char)get_register_name(get_unname_register());
4931  buf[1] = NUL;
4932  buflen = buf[0] == NUL ? 0 : 1;
4933  if (regname == '"') {
4934    tv_dict_add_str_len(dict, S_LEN("points_to"), buf, (int)buflen);
4935  } else {
4936    tv_dict_add_bool(dict, S_LEN("isunnamed"),
4937                     regname == buf[0] ? kBoolVarTrue : kBoolVarFalse);
4938  }
4939}
4940
4941static void return_register(int regname, typval_T *rettv)
4942{
4943  char buf[2] = { (char)regname, NUL };
4944
4945  rettv->v_type = VAR_STRING;
4946  rettv->vval.v_string = xmemdupz(buf, buf[0] == NUL ? 0 : 1);
4947}
4948
4949/// "reg_executing()" function
4950static void f_reg_executing(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
4951{
4952  return_register(reg_executing, rettv);
4953}
4954
4955/// "reg_recording()" function
4956static void f_reg_recording(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
4957{
4958  return_register(reg_recording, rettv);
4959}
4960
4961static void f_reg_recorded(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
4962{
4963  return_register(reg_recorded, rettv);
4964}
4965
4966/// list2proftime - convert a List to proftime_T
4967///
4968/// @param arg The input list, must be of type VAR_LIST and have
4969///            exactly 2 items
4970/// @param[out] tm The proftime_T representation of `arg`
4971/// @return OK In case of success, FAIL in case of error
4972static int list2proftime(typval_T *arg, proftime_T *tm) FUNC_ATTR_NONNULL_ALL
4973{
4974  if (arg->v_type != VAR_LIST || tv_list_len(arg->vval.v_list) != 2) {
4975    return FAIL;
4976  }
4977
4978  bool error = false;
4979  varnumber_T n1 = tv_list_find_nr(arg->vval.v_list, 0, &error);
4980  varnumber_T n2 = tv_list_find_nr(arg->vval.v_list, 1, &error);
4981  if (error) {
4982    return FAIL;
4983  }
4984
4985  // in f_reltime() we split up the 64-bit proftime_T into two 32-bit
4986  // values, now we combine them again.
4987  union {
4988    struct { int32_t low, high; } split;
4989    proftime_T prof;
4990  } u = { .split.high = (int32_t)n1, .split.low = (int32_t)n2 };
4991
4992  *tm = u.prof;
4993
4994  return OK;
4995}
4996
4997/// f_reltime - return an item that represents a time value
4998///
4999/// @param[out] rettv Without an argument it returns the current time. With
5000///             one argument it returns the time passed since the argument.
5001///             With two arguments it returns the time passed between
5002///             the two arguments.
5003static void f_reltime(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
5004{
5005  proftime_T res;
5006  proftime_T start;
5007
5008  if (argvars[0].v_type == VAR_UNKNOWN) {
5009    // no arguments: get current time.
5010    res = profile_start();
5011  } else if (argvars[1].v_type == VAR_UNKNOWN) {
5012    if (list2proftime(&argvars[0], &res) == FAIL) {
5013      return;
5014    }
5015    res = profile_end(res);
5016  } else {
5017    // two arguments: compute the difference.
5018    if (list2proftime(&argvars[0], &start) == FAIL
5019        || list2proftime(&argvars[1], &res) == FAIL) {
5020      return;
5021    }
5022    res = profile_sub(res, start);
5023  }
5024
5025  // we have to store the 64-bit proftime_T inside of a list of int's
5026  // (varnumber_T is defined as int). For all our supported platforms, int's
5027  // are at least 32-bits wide. So we'll use two 32-bit values to store it.
5028  union {
5029    struct { int32_t low, high; } split;
5030    proftime_T prof;
5031  } u = { .prof = res };
5032
5033  // statically assert that the union type conv will provide the correct
5034  // results, if varnumber_T or proftime_T change, the union cast will need
5035  // to be revised.
5036  STATIC_ASSERT(sizeof(u.prof) == sizeof(u) && sizeof(u.split) == sizeof(u),
5037                "type punning will produce incorrect results on this platform");
5038
5039  tv_list_alloc_ret(rettv, 2);
5040  tv_list_append_number(rettv->vval.v_list, u.split.high);
5041  tv_list_append_number(rettv->vval.v_list, u.split.low);
5042}
5043
5044/// "reltimestr()" function
5045static void f_reltimestr(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
5046  FUNC_ATTR_NONNULL_ALL
5047{
5048  proftime_T tm;
5049
5050  rettv->v_type = VAR_STRING;
5051  rettv->vval.v_string = NULL;
5052  if (list2proftime(&argvars[0], &tm) == OK) {
5053    rettv->vval.v_string = xstrdup(profile_msg(tm));
5054  }
5055}
5056
5057/// Repeat the list "l" "n" times and set "rettv" to the new list.
5058static void repeat_list(list_T *l, varnumber_T n, typval_T *rettv)
5059{
5060  const int slen = tv_list_len(l);
5061
5062  tv_list_alloc_ret(rettv, (n > 0) * n * slen);
5063  if (l == NULL || n <= 0 || slen == 0) {
5064    return;
5065  }
5066
5067  if (check_repeat_count(slen, n) == FAIL) {
5068    return;
5069  }
5070
5071  while (n-- > 0) {
5072    tv_list_extend(rettv->vval.v_list, l, NULL);
5073  }
5074}
5075
5076/// Repeat the blob "b" "n" times and set "rettv" to the new blob.
5077static void repeat_blob(typval_T *blob_tv, varnumber_T n, typval_T *rettv)
5078{
5079  blob_T *const blob = blob_tv->vval.v_blob;
5080
5081  tv_blob_alloc_ret(rettv);
5082  if (blob == NULL || n <= 0) {
5083    return;
5084  }
5085
5086  const int slen = blob->bv_ga.ga_len;
5087  if (slen <= 0) {
5088    return;
5089  }
5090  if (check_repeat_count(slen, n) == FAIL) {
5091    return;
5092  }
5093  const int len = slen * (int)n;
5094
5095  ga_grow(&rettv->vval.v_blob->bv_ga, len);
5096
5097  rettv->vval.v_blob->bv_ga.ga_len = len;
5098
5099  int i;
5100  for (i = 0; i < slen; i++) {
5101    if (tv_blob_get(blob, i) != 0) {
5102      break;
5103    }
5104  }
5105
5106  if (i == slen) {
5107    // No need to copy since all bytes are already zero
5108    return;
5109  }
5110
5111  for (i = 0; i < (int)n; i++) {
5112    tv_blob_set_range(rettv->vval.v_blob, i * slen, (i + 1) * slen - 1, blob_tv);
5113  }
5114}
5115
5116/// Repeat the string "str" "n" times and set "rettv" to the new string.
5117static void repeat_string(typval_T *str_tv, varnumber_T n, typval_T *rettv)
5118{
5119  rettv->v_type = VAR_STRING;
5120  rettv->vval.v_string = NULL;
5121  if (n <= 0) {
5122    return;
5123  }
5124
5125  const char *const p = tv_get_string(str_tv);
5126
5127  const size_t slen = strlen(p);
5128  if (slen == 0 || n <= 0) {
5129    return;
5130  }
5131  if (check_repeat_count((varnumber_T)slen, n) == FAIL) {
5132    return;
5133  }
5134  const size_t len = slen * (size_t)n;
5135
5136  char *const r = xmallocz(len);
5137
5138  memmove(r, p, slen);
5139  size_t done = slen;
5140  while (done < len) {
5141    size_t copy_len = done;
5142    if (copy_len > len - done) {
5143      copy_len = len - done;
5144    }
5145    memmove(r + done, r, copy_len);
5146    done += copy_len;
5147  }
5148
5149  rettv->vval.v_string = r;
5150}
5151
5152/// "repeat()" function
5153static void f_repeat(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
5154{
5155  varnumber_T n = tv_get_number(&argvars[1]);
5156  if (argvars[0].v_type == VAR_LIST) {
5157    repeat_list(argvars[0].vval.v_list, n, rettv);
5158  } else if (argvars[0].v_type == VAR_BLOB) {
5159    repeat_blob(&argvars[0], n, rettv);
5160  } else {
5161    repeat_string(&argvars[0], n, rettv);
5162  }
5163}
5164
5165/// Implementation of reduce() for list "argvars[0]", using the function "expr"
5166/// starting with the optional initial value argvars[2] and return the result in
5167/// "rettv".
5168static void reduce_list(typval_T *argvars, typval_T *expr, typval_T *rettv)
5169{
5170  list_T *const l = argvars[0].vval.v_list;
5171  const int called_emsg_start = called_emsg;
5172
5173  typval_T initial;
5174  const listitem_T *li = NULL;
5175  if (argvars[2].v_type == VAR_UNKNOWN) {
5176    if (tv_list_len(l) == 0) {
5177      semsg(_(e_reduce_of_an_empty_str_with_no_initial_value), "List");
5178      return;
5179    }
5180    const listitem_T *const first = tv_list_first(l);
5181    initial = *TV_LIST_ITEM_TV(first);
5182    li = TV_LIST_ITEM_NEXT(l, first);
5183  } else {
5184    initial = argvars[2];
5185    li = tv_list_first(l);
5186  }
5187
5188  tv_copy(&initial, rettv);
5189
5190  if (l == NULL) {
5191    return;
5192  }
5193
5194  const VarLockStatus prev_locked = tv_list_locked(l);
5195
5196  tv_list_set_lock(l, VAR_FIXED);  // disallow the list changing here
5197  for (; li != NULL; li = TV_LIST_ITEM_NEXT(l, li)) {
5198    typval_T argv[3];
5199    argv[0] = *rettv;
5200    argv[1] = *TV_LIST_ITEM_TV(li);
5201    rettv->v_type = VAR_UNKNOWN;
5202
5203    const int r = eval_expr_typval(expr, true, argv, 2, rettv);
5204
5205    tv_clear(&argv[0]);
5206    if (r == FAIL || called_emsg != called_emsg_start) {
5207      break;
5208    }
5209  }
5210  tv_list_set_lock(l, prev_locked);
5211}
5212
5213/// Implementation of reduce() for String "argvars[0]" using the function "expr"
5214/// starting with the optional initial value "argvars[2]" and return the result
5215/// in "rettv".
5216static void reduce_string(typval_T *argvars, typval_T *expr, typval_T *rettv)
5217{
5218  const char *p = tv_get_string(&argvars[0]);
5219  int len;
5220  const int called_emsg_start = called_emsg;
5221
5222  if (argvars[2].v_type == VAR_UNKNOWN) {
5223    if (*p == NUL) {
5224      semsg(_(e_reduce_of_an_empty_str_with_no_initial_value), "String");
5225      return;
5226    }
5227    len = utfc_ptr2len(p);
5228    *rettv = (typval_T){
5229      .v_type = VAR_STRING,
5230      .v_lock = VAR_UNLOCKED,
5231      .vval.v_string = xmemdupz(p, (size_t)len),
5232    };
5233    p += len;
5234  } else if (tv_check_for_string_arg(argvars, 2) == FAIL) {
5235    return;
5236  } else {
5237    tv_copy(&argvars[2], rettv);
5238  }
5239
5240  for (; *p != NUL; p += len) {
5241    typval_T argv[3];
5242    argv[0] = *rettv;
5243    rettv->v_type = VAR_UNKNOWN;
5244    len = utfc_ptr2len(p);
5245    argv[1] = (typval_T){
5246      .v_type = VAR_STRING,
5247      .v_lock = VAR_UNLOCKED,
5248      .vval.v_string = xmemdupz(p, (size_t)len),
5249    };
5250
5251    const int r = eval_expr_typval(expr, true, argv, 2, rettv);
5252
5253    tv_clear(&argv[0]);
5254    tv_clear(&argv[1]);
5255    if (r == FAIL || called_emsg != called_emsg_start) {
5256      break;
5257    }
5258  }
5259}
5260
5261/// Implementation of reduce() for Blob "argvars[0]" using the function "expr"
5262/// starting with the optional initial value "argvars[2]" and return the result
5263/// in "rettv".
5264static void reduce_blob(typval_T *argvars, typval_T *expr, typval_T *rettv)
5265{
5266  const blob_T *const b = argvars[0].vval.v_blob;
5267  const int called_emsg_start = called_emsg;
5268
5269  typval_T initial;
5270  int i;
5271  if (argvars[2].v_type == VAR_UNKNOWN) {
5272    if (tv_blob_len(b) == 0) {
5273      semsg(_(e_reduce_of_an_empty_str_with_no_initial_value), "Blob");
5274      return;
5275    }
5276    initial = (typval_T){
5277      .v_type = VAR_NUMBER,
5278      .v_lock = VAR_UNLOCKED,
5279      .vval.v_number = tv_blob_get(b, 0),
5280    };
5281    i = 1;
5282  } else if (tv_check_for_number_arg(argvars, 2) == FAIL) {
5283    return;
5284  } else {
5285    initial = argvars[2];
5286    i = 0;
5287  }
5288
5289  tv_copy(&initial, rettv);
5290  for (; i < tv_blob_len(b); i++) {
5291    typval_T argv[3];
5292    argv[0] = *rettv;
5293    argv[1] = (typval_T){
5294      .v_type = VAR_NUMBER,
5295      .v_lock = VAR_UNLOCKED,
5296      .vval.v_number = tv_blob_get(b, i),
5297    };
5298
5299    const int r = eval_expr_typval(expr, true, argv, 2, rettv);
5300
5301    if (r == FAIL || called_emsg != called_emsg_start) {
5302      return;
5303    }
5304  }
5305}
5306
5307/// "reduce(list, { accumulator, element -> value } [, initial])" function
5308/// "reduce(blob, { accumulator, element -> value } [, initial])" function
5309/// "reduce(string, { accumulator, element -> value } [, initial])" function
5310static void f_reduce(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
5311{
5312  if (argvars[0].v_type != VAR_STRING
5313      && argvars[0].v_type != VAR_LIST
5314      && argvars[0].v_type != VAR_BLOB) {
5315    emsg(_(e_string_list_or_blob_required));
5316    return;
5317  }
5318
5319  const char *func_name;
5320  if (argvars[1].v_type == VAR_FUNC) {
5321    func_name = argvars[1].vval.v_string;
5322  } else if (argvars[1].v_type == VAR_PARTIAL) {
5323    func_name = partial_name(argvars[1].vval.v_partial);
5324  } else {
5325    func_name = tv_get_string(&argvars[1]);
5326  }
5327  if (func_name == NULL || *func_name == NUL) {
5328    emsg(_(e_missing_function_argument));
5329    return;
5330  }
5331
5332  if (argvars[0].v_type == VAR_LIST) {
5333    reduce_list(argvars, &argvars[1], rettv);
5334  } else if (argvars[0].v_type == VAR_STRING) {
5335    reduce_string(argvars, &argvars[1], rettv);
5336  } else {
5337    reduce_blob(argvars, &argvars[1], rettv);
5338  }
5339}
5340
5341#define SP_NOMOVE       0x01        ///< don't move cursor
5342#define SP_REPEAT       0x02        ///< repeat to find outer pair
5343#define SP_RETCOUNT     0x04        ///< return matchcount
5344#define SP_SETPCMARK    0x08        ///< set previous context mark
5345#define SP_START        0x10        ///< accept match at start position
5346#define SP_SUBPAT       0x20        ///< return nr of matching sub-pattern
5347#define SP_END          0x40        ///< leave cursor at end of match
5348#define SP_COLUMN       0x80        ///< start at cursor column
5349
5350/// Get flags for a search function.
5351/// Possibly sets "p_ws".
5352///
5353/// @return  BACKWARD, FORWARD or zero (for an error).
5354static int get_search_arg(typval_T *varp, int *flagsp)
5355{
5356  int dir = FORWARD;
5357
5358  if (varp->v_type == VAR_UNKNOWN) {
5359    return FORWARD;
5360  }
5361
5362  char nbuf[NUMBUFLEN];
5363  const char *flags = tv_get_string_buf_chk(varp, nbuf);
5364  if (flags == NULL) {
5365    return 0;  // Type error; errmsg already given.
5366  }
5367  int mask;
5368  while (*flags != NUL) {
5369    switch (*flags) {
5370    case 'b':
5371      dir = BACKWARD; break;
5372    case 'w':
5373      p_ws = true; break;
5374    case 'W':
5375      p_ws = false; break;
5376    default:
5377      mask = 0;
5378      if (flagsp != NULL) {
5379        switch (*flags) {
5380        case 'c':
5381          mask = SP_START; break;
5382        case 'e':
5383          mask = SP_END; break;
5384        case 'm':
5385          mask = SP_RETCOUNT; break;
5386        case 'n':
5387          mask = SP_NOMOVE; break;
5388        case 'p':
5389          mask = SP_SUBPAT; break;
5390        case 'r':
5391          mask = SP_REPEAT; break;
5392        case 's':
5393          mask = SP_SETPCMARK; break;
5394        case 'z':
5395          mask = SP_COLUMN; break;
5396        }
5397      }
5398      if (mask == 0) {
5399        semsg(_(e_invarg2), flags);
5400        dir = 0;
5401      } else {
5402        *flagsp |= mask;
5403      }
5404    }
5405    if (dir == 0) {
5406      break;
5407    }
5408    flags++;
5409  }
5410  return dir;
5411}
5412
5413/// Shared by search() and searchpos() functions.
5414static int search_cmn(typval_T *argvars, pos_T *match_pos, int *flagsp)
5415{
5416  bool save_p_ws = p_ws;
5417  int retval = 0;               // default: FAIL
5418  linenr_T lnum_stop = 0;
5419  int64_t time_limit = 0;
5420  int options = SEARCH_KEEP;
5421  bool use_skip = false;
5422
5423  const char *const pat = tv_get_string(&argvars[0]);
5424  int dir = get_search_arg(&argvars[1], flagsp);  // May set p_ws.
5425  if (dir == 0) {
5426    goto theend;
5427  }
5428  int flags = *flagsp;
5429  if (flags & SP_START) {
5430    options |= SEARCH_START;
5431  }
5432  if (flags & SP_END) {
5433    options |= SEARCH_END;
5434  }
5435  if (flags & SP_COLUMN) {
5436    options |= SEARCH_COL;
5437  }
5438
5439  // Optional arguments: line number to stop searching, timeout and skip.
5440  if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN) {
5441    lnum_stop = (linenr_T)tv_get_number_chk(&argvars[2], NULL);
5442    if (lnum_stop < 0) {
5443      goto theend;
5444    }
5445    if (argvars[3].v_type != VAR_UNKNOWN) {
5446      time_limit = tv_get_number_chk(&argvars[3], NULL);
5447      if (time_limit < 0) {
5448        goto theend;
5449      }
5450      use_skip = eval_expr_valid_arg(&argvars[4]);
5451    }
5452  }
5453
5454  // Set the time limit, if there is one.
5455  proftime_T tm = profile_setlimit(time_limit);
5456
5457  // This function does not accept SP_REPEAT and SP_RETCOUNT flags.
5458  // Check to make sure only those flags are set.
5459  // Also, Only the SP_NOMOVE or the SP_SETPCMARK flag can be set. Both
5460  // flags cannot be set. Check for that condition also.
5461  if (((flags & (SP_REPEAT | SP_RETCOUNT)) != 0)
5462      || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK))) {
5463    semsg(_(e_invarg2), tv_get_string(&argvars[1]));
5464    goto theend;
5465  }
5466
5467  pos_T save_cursor;
5468  pos_T pos = save_cursor = curwin->w_cursor;
5469  pos_T firstpos = { 0 };
5470  searchit_arg_T sia = {
5471    .sa_stop_lnum = lnum_stop,
5472    .sa_tm = &tm,
5473  };
5474
5475  const size_t patlen = strlen(pat);
5476  int subpatnum;
5477
5478  // Repeat until {skip} returns false.
5479  while (true) {
5480    subpatnum = searchit(curwin, curbuf, &pos, NULL, dir, (char *)pat, patlen, 1,
5481                         options, RE_SEARCH, p_magic, &sia);
5482    // finding the first match again means there is no match where {skip}
5483    // evaluates to zero.
5484    if (firstpos.lnum != 0 && equalpos(pos, firstpos)) {
5485      subpatnum = FAIL;
5486    }
5487
5488    if (subpatnum == FAIL || !use_skip) {
5489      // didn't find it or no skip argument
5490      break;
5491    }
5492    if (firstpos.lnum == 0) {
5493      firstpos = pos;
5494    }
5495
5496    // If the skip expression matches, ignore this match.
5497    {
5498      const pos_T save_pos = curwin->w_cursor;
5499
5500      curwin->w_cursor = pos;
5501      bool err = false;
5502      const bool do_skip = eval_expr_to_bool(&argvars[4], &err);
5503      curwin->w_cursor = save_pos;
5504      if (err) {
5505        // Evaluating {skip} caused an error, break here.
5506        subpatnum = FAIL;
5507        break;
5508      }
5509      if (!do_skip) {
5510        break;
5511      }
5512    }
5513
5514    // clear the start flag to avoid getting stuck here
5515    options &= ~SEARCH_START;
5516  }
5517
5518  if (subpatnum != FAIL) {
5519    if (flags & SP_SUBPAT) {
5520      retval = subpatnum;
5521    } else {
5522      retval = pos.lnum;
5523    }
5524    if (flags & SP_SETPCMARK) {
5525      setpcmark();
5526    }
5527    curwin->w_cursor = pos;
5528    if (match_pos != NULL) {
5529      // Store the match cursor position
5530      match_pos->lnum = pos.lnum;
5531      match_pos->col = pos.col + 1;
5532    }
5533    // "/$" will put the cursor after the end of the line, may need to
5534    // correct that here
5535    check_cursor(curwin);
5536  }
5537
5538  // If 'n' flag is used: restore cursor position.
5539  if (flags & SP_NOMOVE) {
5540    curwin->w_cursor = save_cursor;
5541  } else {
5542    curwin->w_set_curswant = true;
5543  }
5544theend:
5545  p_ws = save_p_ws;
5546
5547  return retval;
5548}
5549
5550/// "rpcnotify()" function
5551static void f_rpcnotify(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
5552{
5553  rettv->v_type = VAR_NUMBER;
5554  rettv->vval.v_number = 0;
5555
5556  if (check_secure()) {
5557    return;
5558  }
5559
5560  if (argvars[0].v_type != VAR_NUMBER || argvars[0].vval.v_number < 0) {
5561    semsg(_(e_invarg2), "Channel id must be a positive integer");
5562    return;
5563  }
5564
5565  if (argvars[1].v_type != VAR_STRING) {
5566    semsg(_(e_invarg2), "Event type must be a string");
5567    return;
5568  }
5569
5570  MAXSIZE_TEMP_ARRAY(args, MAX_FUNC_ARGS);
5571  Arena arena = ARENA_EMPTY;
5572
5573  for (typval_T *tv = argvars + 2; tv->v_type != VAR_UNKNOWN; tv++) {
5574    ADD_C(args, vim_to_object(tv, &arena, true));
5575  }
5576
5577  bool ok = rpc_send_event((uint64_t)argvars[0].vval.v_number,
5578                           tv_get_string(&argvars[1]), args);
5579
5580  arena_mem_free(arena_finish(&arena));
5581
5582  if (!ok) {
5583    semsg(_(e_invarg2), "Channel doesn't exist");
5584    return;
5585  }
5586  rettv->vval.v_number = 1;
5587}
5588
5589/// "rpcrequest()" function
5590static void f_rpcrequest(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
5591{
5592  rettv->v_type = VAR_NUMBER;
5593  rettv->vval.v_number = 0;
5594  const int l_provider_call_nesting = provider_call_nesting;
5595
5596  if (check_secure()) {
5597    return;
5598  }
5599
5600  if (argvars[0].v_type != VAR_NUMBER || argvars[0].vval.v_number <= 0) {
5601    semsg(_(e_invarg2), "Channel id must be a positive integer");
5602    return;
5603  }
5604
5605  if (argvars[1].v_type != VAR_STRING) {
5606    semsg(_(e_invarg2), "Method name must be a string");
5607    return;
5608  }
5609
5610  MAXSIZE_TEMP_ARRAY(args, MAX_FUNC_ARGS);
5611  Arena arena = ARENA_EMPTY;
5612
5613  for (typval_T *tv = argvars + 2; tv->v_type != VAR_UNKNOWN; tv++) {
5614    ADD_C(args, vim_to_object(tv, &arena, true));
5615  }
5616
5617  sctx_T save_current_sctx;
5618  char *save_autocmd_fname, *save_autocmd_match;
5619  bool save_autocmd_fname_full;
5620  int save_autocmd_bufnr;
5621  funccal_entry_T funccal_entry;
5622
5623  if (l_provider_call_nesting) {
5624    // If this is called from a provider function, restore the scope
5625    // information of the caller.
5626    save_current_sctx = current_sctx;
5627    save_autocmd_fname = autocmd_fname;
5628    save_autocmd_match = autocmd_match;
5629    save_autocmd_fname_full = autocmd_fname_full;
5630    save_autocmd_bufnr = autocmd_bufnr;
5631    save_funccal(&funccal_entry);
5632
5633    current_sctx = provider_caller_scope.script_ctx;
5634    ga_grow(&exestack, 1);
5635    ((estack_T *)exestack.ga_data)[exestack.ga_len++] = provider_caller_scope.es_entry;
5636    autocmd_fname = provider_caller_scope.autocmd_fname;
5637    autocmd_match = provider_caller_scope.autocmd_match;
5638    autocmd_fname_full = provider_caller_scope.autocmd_fname_full;
5639    autocmd_bufnr = provider_caller_scope.autocmd_bufnr;
5640    set_current_funccal((funccall_T *)(provider_caller_scope.funccalp));
5641  }
5642
5643  Error err = ERROR_INIT;
5644
5645  uint64_t chan_id = (uint64_t)argvars[0].vval.v_number;
5646  const char *method = tv_get_string(&argvars[1]);
5647
5648  ArenaMem res_mem = NULL;
5649  Object result = rpc_send_call(chan_id, method, args, &res_mem, &err);
5650  arena_mem_free(arena_finish(&arena));
5651
5652  if (l_provider_call_nesting) {
5653    current_sctx = save_current_sctx;
5654    exestack.ga_len--;
5655    autocmd_fname = save_autocmd_fname;
5656    autocmd_match = save_autocmd_match;
5657    autocmd_fname_full = save_autocmd_fname_full;
5658    autocmd_bufnr = save_autocmd_bufnr;
5659    restore_funccal();
5660  }
5661
5662  if (ERROR_SET(&err)) {
5663    const char *name = NULL;
5664    Channel *chan = find_channel(chan_id);
5665    if (chan) {
5666      name = get_client_info(chan, "name");
5667    }
5668    if (name) {
5669      semsg_multiline("rpc_error", "Invoking '%s' on channel %" PRIu64 " (%s):\n%s",
5670                      method, chan_id, name, err.msg);
5671    } else {
5672      semsg_multiline("rpc_error", "Invoking '%s' on channel %" PRIu64 ":\n%s",
5673                      method, chan_id, err.msg);
5674    }
5675
5676    goto end;
5677  }
5678
5679  object_to_vim(result, rettv, &err);
5680
5681end:
5682  arena_mem_free(res_mem);
5683  api_clear_error(&err);
5684}
5685
5686static void screenchar_adjust(ScreenGrid **grid, int *row, int *col)
5687{
5688  // TODO(bfredl): this is a hack for legacy tests which use screenchar()
5689  // to check printed messages on the screen (but not floats etc
5690  // as these are not legacy features). If the compositor is refactored to
5691  // have its own buffer, this should just read from it instead.
5692  msg_scroll_flush();
5693
5694  *grid = ui_comp_get_grid_at_coord(*row, *col);
5695
5696  // Make `row` and `col` relative to the grid
5697  *row -= (*grid)->comp_row;
5698  *col -= (*grid)->comp_col;
5699}
5700
5701/// "screenattr()" function
5702static void f_screenattr(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
5703{
5704  int row = (int)tv_get_number_chk(&argvars[0], NULL) - 1;
5705  int col = (int)tv_get_number_chk(&argvars[1], NULL) - 1;
5706
5707  ScreenGrid *grid;
5708  screenchar_adjust(&grid, &row, &col);
5709
5710  int c;
5711  if (row < 0 || row >= grid->rows || col < 0 || col >= grid->cols) {
5712    c = -1;
5713  } else {
5714    c = grid->attrs[grid->line_offset[row] + (size_t)col];
5715  }
5716  rettv->vval.v_number = c;
5717}
5718
5719/// "screenchar()" function
5720static void f_screenchar(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
5721{
5722  int row = (int)tv_get_number_chk(&argvars[0], NULL) - 1;
5723  int col = (int)tv_get_number_chk(&argvars[1], NULL) - 1;
5724
5725  ScreenGrid *grid;
5726  screenchar_adjust(&grid, &row, &col);
5727
5728  rettv->vval.v_number = (row < 0 || row >= grid->rows || col < 0 || col >= grid->cols)
5729                         ? -1 : schar_get_first_codepoint(grid_getchar(grid, row, col, NULL));
5730}
5731
5732/// "screenchars()" function
5733static void f_screenchars(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
5734{
5735  int row = (int)tv_get_number_chk(&argvars[0], NULL) - 1;
5736  int col = (int)tv_get_number_chk(&argvars[1], NULL) - 1;
5737
5738  ScreenGrid *grid;
5739  screenchar_adjust(&grid, &row, &col);
5740
5741  tv_list_alloc_ret(rettv, kListLenMayKnow);
5742  if (row < 0 || row >= grid->rows || col < 0 || col >= grid->cols) {
5743    return;
5744  }
5745
5746  char buf[MAX_SCHAR_SIZE + 1];
5747  schar_get(buf, grid_getchar(grid, row, col, NULL));
5748
5749  // schar values are already processed chars which are always NUL-terminated.
5750  // A single [0] is expected when char is NUL.
5751  size_t i = 0;
5752  do {
5753    int c = utf_ptr2char(buf + i);
5754    tv_list_append_number(rettv->vval.v_list, c);
5755    i += (size_t)utf_ptr2len(buf + i);
5756  } while (buf[i] != NUL);
5757}
5758
5759/// "screencol()" function
5760///
5761/// First column is 1 to be consistent with virtcol().
5762static void f_screencol(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
5763{
5764  rettv->vval.v_number = ui_current_col() + 1;
5765}
5766
5767/// "screenrow()" function
5768static void f_screenrow(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
5769{
5770  rettv->vval.v_number = ui_current_row() + 1;
5771}
5772
5773/// "screenstring()" function
5774static void f_screenstring(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
5775{
5776  rettv->vval.v_string = NULL;
5777  rettv->v_type = VAR_STRING;
5778
5779  ScreenGrid *grid;
5780  int row = (int)tv_get_number_chk(&argvars[0], NULL) - 1;
5781  int col = (int)tv_get_number_chk(&argvars[1], NULL) - 1;
5782
5783  screenchar_adjust(&grid, &row, &col);
5784
5785  if (row < 0 || row >= grid->rows || col < 0 || col >= grid->cols) {
5786    return;
5787  }
5788
5789  char buf[MAX_SCHAR_SIZE + 1];
5790  schar_get(buf, grid_getchar(grid, row, col, NULL));
5791  rettv->vval.v_string = xstrdup(buf);
5792}
5793
5794/// "search()" function
5795static void f_search(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
5796{
5797  int flags = 0;
5798
5799  rettv->vval.v_number = search_cmn(argvars, NULL, &flags);
5800}
5801
5802/// "searchdecl()" function
5803static void f_searchdecl(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
5804{
5805  int locally = 1;
5806  int thisblock = 0;
5807  bool error = false;
5808
5809  rettv->vval.v_number = 1;     // default: FAIL
5810
5811  const char *const name = tv_get_string_chk(&argvars[0]);
5812  if (argvars[1].v_type != VAR_UNKNOWN) {
5813    locally = !tv_get_bool_chk(&argvars[1], &error);
5814    if (!error && argvars[2].v_type != VAR_UNKNOWN) {
5815      thisblock = (int)tv_get_bool_chk(&argvars[2], &error);
5816    }
5817  }
5818  if (!error && name != NULL) {
5819    rettv->vval.v_number = find_decl((char *)name, strlen(name), locally,
5820                                     thisblock, SEARCH_KEEP) == FAIL;
5821  }
5822}
5823
5824/// Used by searchpair() and searchpairpos()
5825static int searchpair_cmn(typval_T *argvars, pos_T *match_pos)
5826{
5827  bool save_p_ws = p_ws;
5828  int flags = 0;
5829  int retval = 0;  // default: FAIL
5830  linenr_T lnum_stop = 0;
5831  int64_t time_limit = 0;
5832
5833  // Get the three pattern arguments: start, middle, end. Will result in an
5834  // error if not a valid argument.
5835  char nbuf1[NUMBUFLEN];
5836  char nbuf2[NUMBUFLEN];
5837  const char *spat = tv_get_string_chk(&argvars[0]);
5838  const char *mpat = tv_get_string_buf_chk(&argvars[1], nbuf1);
5839  const char *epat = tv_get_string_buf_chk(&argvars[2], nbuf2);
5840  if (spat == NULL || mpat == NULL || epat == NULL) {
5841    goto theend;  // Type error.
5842  }
5843
5844  // Handle the optional fourth argument: flags.
5845  int dir = get_search_arg(&argvars[3], &flags);   // may set p_ws.
5846  if (dir == 0) {
5847    goto theend;
5848  }
5849
5850  // Don't accept SP_END or SP_SUBPAT.
5851  // Only one of the SP_NOMOVE or SP_SETPCMARK flags can be set.
5852  if ((flags & (SP_END | SP_SUBPAT)) != 0
5853      || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK))) {
5854    semsg(_(e_invarg2), tv_get_string(&argvars[3]));
5855    goto theend;
5856  }
5857
5858  // Using 'r' implies 'W', otherwise it doesn't work.
5859  if (flags & SP_REPEAT) {
5860    p_ws = false;
5861  }
5862
5863  // Optional fifth argument: skip expression.
5864  const typval_T *skip;
5865  if (argvars[3].v_type == VAR_UNKNOWN
5866      || argvars[4].v_type == VAR_UNKNOWN) {
5867    skip = NULL;
5868  } else {
5869    // Type is checked later.
5870    skip = &argvars[4];
5871
5872    if (argvars[5].v_type != VAR_UNKNOWN) {
5873      lnum_stop = (linenr_T)tv_get_number_chk(&argvars[5], NULL);
5874      if (lnum_stop < 0) {
5875        semsg(_(e_invarg2), tv_get_string(&argvars[5]));
5876        goto theend;
5877      }
5878      if (argvars[6].v_type != VAR_UNKNOWN) {
5879        time_limit = tv_get_number_chk(&argvars[6], NULL);
5880        if (time_limit < 0) {
5881          semsg(_(e_invarg2), tv_get_string(&argvars[6]));
5882          goto theend;
5883        }
5884      }
5885    }
5886  }
5887
5888  retval = do_searchpair(spat, mpat, epat, dir, skip,
5889                         flags, match_pos, lnum_stop, time_limit);
5890
5891theend:
5892  p_ws = save_p_ws;
5893
5894  return retval;
5895}
5896
5897/// "searchpair()" function
5898static void f_searchpair(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
5899{
5900  rettv->vval.v_number = searchpair_cmn(argvars, NULL);
5901}
5902
5903/// "searchpairpos()" function
5904static void f_searchpairpos(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
5905{
5906  pos_T match_pos;
5907  int lnum = 0;
5908  int col = 0;
5909
5910  tv_list_alloc_ret(rettv, 2);
5911
5912  if (searchpair_cmn(argvars, &match_pos) > 0) {
5913    lnum = match_pos.lnum;
5914    col = match_pos.col;
5915  }
5916
5917  tv_list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
5918  tv_list_append_number(rettv->vval.v_list, (varnumber_T)col);
5919}
5920
5921/// Search for a start/middle/end thing.
5922/// Used by searchpair(), see its documentation for the details.
5923///
5924/// @param spat  start pattern
5925/// @param mpat  middle pattern
5926/// @param epat  end pattern
5927/// @param dir  BACKWARD or FORWARD
5928/// @param skip  skip expression
5929/// @param flags  SP_SETPCMARK and other SP_ values
5930/// @param lnum_stop  stop at this line if not zero
5931/// @param time_limit  stop after this many msec
5932///
5933/// @returns  0 or -1 for no match,
5934int do_searchpair(const char *spat, const char *mpat, const char *epat, int dir,
5935                  const typval_T *skip, int flags, pos_T *match_pos, linenr_T lnum_stop,
5936                  int64_t time_limit)
5937  FUNC_ATTR_NONNULL_ARG(1, 2, 3)
5938{
5939  int retval = 0;
5940  int nest = 1;
5941  bool use_skip = false;
5942  int options = SEARCH_KEEP;
5943
5944  // Make 'cpoptions' empty, the 'l' flag should not be used here.
5945  char *save_cpo = p_cpo;
5946  p_cpo = empty_string_option;
5947
5948  // Set the time limit, if there is one.
5949  proftime_T tm = profile_setlimit(time_limit);
5950
5951  // Make two search patterns: start/end (pat2, for in nested pairs) and
5952  // start/middle/end (pat3, for the top pair).
5953  const size_t spatlen = strlen(spat);
5954  const size_t epatlen = strlen(epat);
5955  const size_t pat2size = spatlen + epatlen + 17;
5956  char *pat2 = xmalloc(pat2size);
5957  const size_t pat3size = spatlen + strlen(mpat) + epatlen + 25;
5958  char *pat3 = xmalloc(pat3size);
5959  int pat2len = snprintf(pat2, pat2size, "\\m\\(%s\\m\\)\\|\\(%s\\m\\)", spat, epat);
5960  int pat3len;
5961  if (*mpat == NUL) {
5962    STRCPY(pat3, pat2);
5963    pat3len = pat2len;
5964  } else {
5965    pat3len = snprintf(pat3, pat3size,
5966                       "\\m\\(%s\\m\\)\\|\\(%s\\m\\)\\|\\(%s\\m\\)", spat, epat, mpat);
5967  }
5968  if (flags & SP_START) {
5969    options |= SEARCH_START;
5970  }
5971
5972  if (skip != NULL) {
5973    use_skip = eval_expr_valid_arg(skip);
5974  }
5975
5976  pos_T save_cursor = curwin->w_cursor;
5977  pos_T pos = curwin->w_cursor;
5978  pos_T firstpos;
5979  clearpos(&firstpos);
5980  pos_T foundpos;
5981  clearpos(&foundpos);
5982  char *pat = pat3;
5983  assert(pat3len >= 0);
5984  size_t patlen = (size_t)pat3len;
5985  while (true) {
5986    searchit_arg_T sia = {
5987      .sa_stop_lnum = lnum_stop,
5988      .sa_tm = &tm,
5989    };
5990
5991    int n = searchit(curwin, curbuf, &pos, NULL, dir, pat, patlen, 1,
5992                     options, RE_SEARCH, true, &sia);
5993    if (n == FAIL || (firstpos.lnum != 0 && equalpos(pos, firstpos))) {
5994      // didn't find it or found the first match again: FAIL
5995      break;
5996    }
5997
5998    if (firstpos.lnum == 0) {
5999      firstpos = pos;
6000    }
6001    if (equalpos(pos, foundpos)) {
6002      // Found the same position again.  Can happen with a pattern that
6003      // has "\zs" at the end and searching backwards.  Advance one
6004      // character and try again.
6005      if (dir == BACKWARD) {
6006        decl(&pos);
6007      } else {
6008        incl(&pos);
6009      }
6010    }
6011    foundpos = pos;
6012
6013    // clear the start flag to avoid getting stuck here
6014    options &= ~SEARCH_START;
6015
6016    // If the skip pattern matches, ignore this match.
6017    if (use_skip) {
6018      pos_T save_pos = curwin->w_cursor;
6019      curwin->w_cursor = pos;
6020      bool err = false;
6021      const bool r = eval_expr_to_bool(skip, &err);
6022      curwin->w_cursor = save_pos;
6023      if (err) {
6024        // Evaluating {skip} caused an error, break here.
6025        curwin->w_cursor = save_cursor;
6026        retval = -1;
6027        break;
6028      }
6029      if (r) {
6030        continue;
6031      }
6032    }
6033
6034    if ((dir == BACKWARD && n == 3) || (dir == FORWARD && n == 2)) {
6035      // Found end when searching backwards or start when searching
6036      // forward: nested pair.
6037      nest++;
6038      pat = pat2;               // nested, don't search for middle
6039    } else {
6040      // Found end when searching forward or start when searching
6041      // backward: end of (nested) pair; or found middle in outer pair.
6042      if (--nest == 1) {
6043        pat = pat3;             // outer level, search for middle
6044      }
6045    }
6046
6047    if (nest == 0) {
6048      // Found the match: return matchcount or line number.
6049      if (flags & SP_RETCOUNT) {
6050        retval++;
6051      } else {
6052        retval = pos.lnum;
6053      }
6054      if (flags & SP_SETPCMARK) {
6055        setpcmark();
6056      }
6057      curwin->w_cursor = pos;
6058      if (!(flags & SP_REPEAT)) {
6059        break;
6060      }
6061      nest = 1;             // search for next unmatched
6062    }
6063  }
6064
6065  if (match_pos != NULL) {
6066    // Store the match cursor position
6067    match_pos->lnum = curwin->w_cursor.lnum;
6068    match_pos->col = curwin->w_cursor.col + 1;
6069  }
6070
6071  // If 'n' flag is used or search failed: restore cursor position.
6072  if ((flags & SP_NOMOVE) || retval == 0) {
6073    curwin->w_cursor = save_cursor;
6074  }
6075
6076  xfree(pat2);
6077  xfree(pat3);
6078  if (p_cpo == empty_string_option) {
6079    p_cpo = save_cpo;
6080  } else {
6081    // Darn, evaluating the {skip} expression changed the value.
6082    // If it's still empty it was changed and restored, need to restore in
6083    // the complicated way.
6084    if (*p_cpo == NUL) {
6085      set_option_value_give_err(kOptCpoptions, CSTR_AS_OBJ(save_cpo), 0);
6086    }
6087    free_string_option(save_cpo);
6088  }
6089
6090  return retval;
6091}
6092
6093/// "searchpos()" function
6094static void f_searchpos(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
6095{
6096  pos_T match_pos;
6097  int flags = 0;
6098
6099  const int n = search_cmn(argvars, &match_pos, &flags);
6100
6101  tv_list_alloc_ret(rettv, 2 + (!!(flags & SP_SUBPAT)));
6102
6103  const int lnum = (n > 0 ? match_pos.lnum : 0);
6104  const int col = (n > 0 ? match_pos.col : 0);
6105
6106  tv_list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
6107  tv_list_append_number(rettv->vval.v_list, (varnumber_T)col);
6108  if (flags & SP_SUBPAT) {
6109    tv_list_append_number(rettv->vval.v_list, (varnumber_T)n);
6110  }
6111}
6112
6113/// "serverlist()" function
6114static void f_serverlist(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
6115{
6116  size_t n;
6117  char **addrs = server_address_list(&n);
6118
6119  // Get the (internal) address list as a typval to pass to Lua.
6120  typval_T addrs_tv;
6121  tv_list_alloc_ret(&addrs_tv, (ptrdiff_t)n);
6122  for (size_t i = 0; i < n; i++) {
6123    tv_list_append_allocated_string(addrs_tv.vval.v_list, addrs[i]);
6124  }
6125  xfree(addrs);
6126
6127  // Lua handles options (e.g. {peer=true}), peer discovery, and returns combined list.
6128  typval_T opts = argvars[0].v_type != VAR_UNKNOWN ? argvars[0] : (typval_T){ .v_type = VAR_SPECIAL,
6129                                                                              .vval.v_special =
6130                                                                                kSpecialVarNull };
6131  typval_T lua_args[] = { opts, addrs_tv, { .v_type = VAR_UNKNOWN } };
6132  nlua_call_typval("vim._core.server", "serverlist", lua_args, rettv);
6133  tv_clear(&addrs_tv);
6134}
6135
6136/// "serverstart()" function
6137static void f_serverstart(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
6138{
6139  rettv->v_type = VAR_STRING;
6140  rettv->vval.v_string = NULL;  // Address of the new server
6141
6142  if (check_secure()) {
6143    return;
6144  }
6145
6146  char *address;
6147  // If the user supplied an address, use it, otherwise use a temp.
6148  if (argvars[0].v_type != VAR_UNKNOWN) {
6149    if (argvars[0].v_type != VAR_STRING) {
6150      emsg(_(e_invarg));
6151      return;
6152    }
6153    address = TO_SLASH_SAVE(tv_get_string(argvars));
6154  } else {
6155    address = server_address_new(NULL);
6156  }
6157
6158  int result = server_start(address);
6159  xfree(address);
6160
6161  if (result != 0) {
6162    semsg("Failed to start server: %s",
6163          result > 0 ? "Unknown system error" : uv_strerror(result));
6164    return;
6165  }
6166
6167  // Since it's possible server_start adjusted the given {address} (e.g.,
6168  // "localhost:" will now have a port), return the final value to the user.
6169  size_t n;
6170  char **addrs = server_address_list(&n);
6171  rettv->vval.v_string = addrs[n - 1];
6172
6173  n--;
6174  for (size_t i = 0; i < n; i++) {
6175    xfree(addrs[i]);
6176  }
6177  xfree(addrs);
6178}
6179
6180/// "serverstop()" function
6181static void f_serverstop(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
6182{
6183  if (check_secure()) {
6184    return;
6185  }
6186
6187  if (argvars[0].v_type != VAR_STRING) {
6188    emsg(_(e_invarg));
6189    return;
6190  }
6191
6192  rettv->v_type = VAR_NUMBER;
6193  rettv->vval.v_number = 0;
6194  if (argvars[0].vval.v_string) {
6195    bool rv = server_stop(argvars[0].vval.v_string, false);
6196    rettv->vval.v_number = (rv ? 1 : 0);
6197  }
6198}
6199
6200/// Set the cursor or mark position.
6201/// If "charpos" is true, then use the column number as a character offset.
6202/// Otherwise use the column number as a byte offset.
6203static void set_position(typval_T *argvars, typval_T *rettv, bool charpos)
6204{
6205  colnr_T curswant = -1;
6206
6207  rettv->vval.v_number = -1;
6208  const char *const name = tv_get_string_chk(argvars);
6209  if (name == NULL) {
6210    return;
6211  }
6212
6213  pos_T pos;
6214  int fnum;
6215  if (list2fpos(&argvars[1], &pos, &fnum, &curswant, charpos) != OK) {
6216    return;
6217  }
6218
6219  if (pos.col != MAXCOL && --pos.col < 0) {
6220    pos.col = 0;
6221  }
6222  if (name[0] == '.' && name[1] == NUL) {
6223    // set cursor; "fnum" is ignored
6224    curwin->w_cursor = pos;
6225    if (curswant >= 0) {
6226      curwin->w_curswant = curswant - 1;
6227      curwin->w_set_curswant = false;
6228    }
6229    check_cursor(curwin);
6230    rettv->vval.v_number = 0;
6231  } else if (name[0] == '\'' && name[1] != NUL && name[2] == NUL) {
6232    // set mark
6233    if (setmark_pos((uint8_t)name[1], &pos, fnum, NULL) == OK) {
6234      rettv->vval.v_number = 0;
6235    }
6236  } else {
6237    emsg(_(e_invarg));
6238  }
6239}
6240
6241/// "setcharpos()" function
6242static void f_setcharpos(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
6243{
6244  set_position(argvars, rettv, true);
6245}
6246
6247static void f_setcharsearch(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
6248{
6249  if (tv_check_for_dict_arg(argvars, 0) == FAIL) {
6250    return;
6251  }
6252
6253  dict_T *d = argvars[0].vval.v_dict;
6254  if (d == NULL) {
6255    return;
6256  }
6257
6258  char *const csearch = tv_dict_get_string(d, "char", false);
6259  if (csearch != NULL) {
6260    int c = utf_ptr2char(csearch);
6261    set_last_csearch(c, csearch, utfc_ptr2len(csearch));
6262  }
6263
6264  dictitem_T *di = tv_dict_find(d, S_LEN("forward"));
6265  if (di != NULL) {
6266    set_csearch_direction(tv_get_number(&di->di_tv) ? FORWARD : BACKWARD);
6267  }
6268
6269  di = tv_dict_find(d, S_LEN("until"));
6270  if (di != NULL) {
6271    set_csearch_until(!!tv_get_number(&di->di_tv));
6272  }
6273}
6274
6275/// "setcursorcharpos" function
6276static void f_setcursorcharpos(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
6277{
6278  set_cursorpos(argvars, rettv, true);
6279}
6280
6281/// "setenv()" function
6282static void f_setenv(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
6283{
6284  char namebuf[NUMBUFLEN];
6285  char valbuf[NUMBUFLEN];
6286  const char *name = tv_get_string_buf(&argvars[0], namebuf);
6287
6288  // setting an environment variable may be dangerous, e.g. you could
6289  // setenv GCONV_PATH=/tmp and then have iconv() unexpectedly call
6290  // a shell command using some shared library:
6291  if (check_secure()) {
6292    return;
6293  }
6294
6295  if (argvars[1].v_type == VAR_SPECIAL
6296      && argvars[1].vval.v_special == kSpecialVarNull) {
6297    vim_unsetenv_ext(name);
6298  } else {
6299    vim_setenv_ext(name, tv_get_string_buf(&argvars[1], valbuf));
6300  }
6301}
6302
6303/// "setfperm({fname}, {mode})" function
6304static void f_setfperm(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
6305{
6306  rettv->vval.v_number = 0;
6307
6308  const char *const fname = tv_get_string_chk(&argvars[0]);
6309  if (fname == NULL) {
6310    return;
6311  }
6312
6313  char modebuf[NUMBUFLEN];
6314  const char *const mode_str = tv_get_string_buf_chk(&argvars[1], modebuf);
6315  if (mode_str == NULL) {
6316    return;
6317  }
6318  if (strlen(mode_str) != 9) {
6319    semsg(_(e_invarg2), mode_str);
6320    return;
6321  }
6322
6323  int mask = 1;
6324  int mode = 0;
6325  for (int i = 8; i >= 0; i--) {
6326    if (mode_str[i] != '-') {
6327      mode |= mask;
6328    }
6329    mask = mask << 1;
6330  }
6331  rettv->vval.v_number = os_setperm(fname, mode) == OK;
6332}
6333
6334/// "setpos()" function
6335static void f_setpos(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
6336{
6337  set_position(argvars, rettv, false);
6338}
6339
6340/// Translate a register type string to the yank type and block length
6341static int get_yank_type(char **const pp, MotionType *const yank_type, int *const block_len)
6342  FUNC_ATTR_NONNULL_ALL
6343{
6344  char *stropt = *pp;
6345  switch (*stropt) {
6346  case 'v':
6347  case 'c':  // character-wise selection
6348    *yank_type = kMTCharWise;
6349    break;
6350  case 'V':
6351  case 'l':  // line-wise selection
6352    *yank_type = kMTLineWise;
6353    break;
6354  case 'b':
6355  case Ctrl_V:  // block-wise selection
6356    *yank_type = kMTBlockWise;
6357    if (ascii_isdigit(stropt[1])) {
6358      stropt++;
6359      *block_len = getdigits_int(&stropt, false, 0) - 1;
6360      stropt--;
6361    }
6362    break;
6363  default:
6364    return FAIL;
6365  }
6366  *pp = stropt;
6367  return OK;
6368}
6369
6370/// "setreg()" function
6371static void f_setreg(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
6372{
6373  bool append = false;
6374
6375  int block_len = -1;
6376  MotionType yank_type = kMTUnknown;
6377
6378  rettv->vval.v_number = 1;  // FAIL is default.
6379
6380  const char *const strregname = tv_get_string_chk(argvars);
6381  if (strregname == NULL) {
6382    return;  // Type error; errmsg already given.
6383  }
6384  char regname = *strregname;
6385  if (regname == 0 || regname == '@') {
6386    regname = '"';
6387  }
6388
6389  const typval_T *regcontents = NULL;
6390  char pointreg = 0;
6391  if (argvars[1].v_type == VAR_DICT) {
6392    dict_T *const d = argvars[1].vval.v_dict;
6393
6394    if (tv_dict_len(d) == 0) {
6395      // Empty dict, clear the register (like setreg(0, []))
6396      char *lstval[2] = { NULL, NULL };
6397      write_reg_contents_lst(regname, lstval, false, kMTUnknown, -1);
6398      return;
6399    }
6400
6401    dictitem_T *const di = tv_dict_find(d, "regcontents", -1);
6402    if (di != NULL) {
6403      regcontents = &di->di_tv;
6404    }
6405
6406    const char *stropt = tv_dict_get_string(d, "regtype", false);
6407    if (stropt != NULL) {
6408      const int ret = get_yank_type((char **)&stropt, &yank_type, &block_len);
6409
6410      if (ret == FAIL || *(++stropt) != NUL) {
6411        semsg(_(e_invargval), "value");
6412        return;
6413      }
6414    }
6415
6416    if (regname == '"') {
6417      stropt = tv_dict_get_string(d, "points_to", false);
6418      if (stropt != NULL) {
6419        pointreg = *stropt;
6420        regname = pointreg;
6421      }
6422    } else if (tv_dict_get_bool(d, "isunnamed", -1) > 0) {
6423      pointreg = regname;
6424    }
6425  } else {
6426    regcontents = &argvars[1];
6427  }
6428
6429  bool set_unnamed = false;
6430  if (argvars[2].v_type != VAR_UNKNOWN) {
6431    if (yank_type != kMTUnknown) {
6432      semsg(_(e_toomanyarg), "setreg");
6433      return;
6434    }
6435
6436    const char *stropt = tv_get_string_chk(&argvars[2]);
6437    if (stropt == NULL) {
6438      return;  // Type error.
6439    }
6440    for (; *stropt != NUL; stropt++) {
6441      switch (*stropt) {
6442      case 'a':
6443      case 'A':    // append
6444        append = true;
6445        break;
6446      case 'u':
6447      case '"':    // unnamed register
6448        set_unnamed = true;
6449        break;
6450      default:
6451        get_yank_type((char **)&stropt, &yank_type, &block_len);
6452      }
6453    }
6454  }
6455
6456  if (regcontents != NULL && regcontents->v_type == VAR_LIST) {
6457    list_T *const ll = regcontents->vval.v_list;
6458    // If the list is NULL handle like an empty list.
6459    const int len = tv_list_len(ll);
6460
6461    // First half: use for pointers to result lines; second half: use for
6462    // pointers to allocated copies.
6463    char **lstval = xmalloc(sizeof(char *) * (((size_t)len + 1) * 2));
6464    const char **curval = (const char **)lstval;
6465    char **allocval = lstval + len + 2;
6466    char **curallocval = allocval;
6467
6468    TV_LIST_ITER_CONST(ll, li, {
6469      char buf[NUMBUFLEN];
6470      *curval = tv_get_string_buf_chk(TV_LIST_ITEM_TV(li), buf);
6471      if (*curval == NULL) {
6472        goto free_lstval;
6473      }
6474      if (*curval == buf) {
6475        // Need to make a copy,
6476        // next tv_get_string_buf_chk() will overwrite the string.
6477        *curallocval = xstrdup(*curval);
6478        *curval = *curallocval;
6479        curallocval++;
6480      }
6481      curval++;
6482    });
6483    *curval++ = NULL;
6484
6485    write_reg_contents_lst(regname, lstval, append, yank_type, (colnr_T)block_len);
6486
6487free_lstval:
6488    while (curallocval > allocval) {
6489      xfree(*--curallocval);
6490    }
6491    xfree(lstval);
6492  } else if (regcontents != NULL) {
6493    const char *const strval = tv_get_string_chk(regcontents);
6494    if (strval == NULL) {
6495      return;
6496    }
6497    write_reg_contents_ex(regname, strval, (ssize_t)strlen(strval),
6498                          append, yank_type, (colnr_T)block_len);
6499  }
6500  if (pointreg != 0) {
6501    get_yank_register(pointreg, YREG_YANK);
6502  }
6503  rettv->vval.v_number = 0;
6504
6505  if (set_unnamed) {
6506    // Discard the result. We already handle the error case.
6507    op_reg_set_previous(regname);
6508  }
6509}
6510
6511/// "settagstack()" function
6512static void f_settagstack(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
6513{
6514  static const char *e_invact2 = N_("E962: Invalid action: '%s'");
6515  char action = 'r';
6516
6517  rettv->vval.v_number = -1;
6518
6519  // first argument: window number or id
6520  win_T *wp = find_win_by_nr_or_id(&argvars[0]);
6521  if (wp == NULL) {
6522    return;
6523  }
6524
6525  // second argument: dict with items to set in the tag stack
6526  if (tv_check_for_dict_arg(argvars, 1) == FAIL) {
6527    return;
6528  }
6529  dict_T *d = argvars[1].vval.v_dict;
6530  if (d == NULL) {
6531    return;
6532  }
6533
6534  // third argument: action - 'a' for append and 'r' for replace.
6535  // default is to replace the stack.
6536  if (argvars[2].v_type == VAR_UNKNOWN) {
6537    // action = 'r';
6538  } else if (tv_check_for_string_arg(argvars, 2) == FAIL) {
6539    return;
6540  } else {
6541    const char *actstr;
6542    actstr = tv_get_string_chk(&argvars[2]);
6543    if (actstr == NULL) {
6544      return;
6545    }
6546    if ((*actstr == 'r' || *actstr == 'a' || *actstr == 't')
6547        && actstr[1] == NUL) {
6548      action = *actstr;
6549    } else {
6550      semsg(_(e_invact2), actstr);
6551      return;
6552    }
6553  }
6554
6555  if (set_tagstack(wp, d, action) == OK) {
6556    rettv->vval.v_number = 0;
6557  }
6558}
6559
6560/// "sha256({expr})" function
6561static void f_sha256(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
6562{
6563  rettv->v_type = VAR_STRING;
6564  rettv->vval.v_string = NULL;
6565
6566  if (argvars[0].v_type == VAR_BLOB) {
6567    blob_T *blob = argvars[0].vval.v_blob;
6568    const uint8_t *p = blob != NULL ? (uint8_t *)blob->bv_ga.ga_data : (uint8_t *)"";
6569    int len = blob != NULL ? blob->bv_ga.ga_len : 0;
6570    rettv->vval.v_string = xstrdup(sha256_bytes(p, (size_t)len, NULL, 0));
6571  } else {
6572    const char *p = tv_get_string(&argvars[0]);
6573    const char *hash = sha256_bytes((const uint8_t *)p, strlen(p), NULL, 0);
6574    rettv->vval.v_string = xstrdup(hash);
6575  }
6576}
6577
6578/// "shellescape({string})" function
6579static void f_shellescape(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
6580{
6581  const bool do_special = non_zero_arg(&argvars[1]);
6582
6583  rettv->vval.v_string =
6584    vim_strsave_shellescape(tv_get_string(&argvars[0]), do_special, do_special);
6585  rettv->v_type = VAR_STRING;
6586}
6587
6588/// shiftwidth() function
6589static void f_shiftwidth(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
6590{
6591  rettv->vval.v_number = 0;
6592
6593  if (argvars[0].v_type != VAR_UNKNOWN) {
6594    colnr_T col = (colnr_T)tv_get_number_chk(argvars, NULL);
6595    if (col < 0) {
6596      return;  // type error; errmsg already given
6597    }
6598    rettv->vval.v_number = get_sw_value_col(curbuf, col, false);
6599    return;
6600  }
6601  rettv->vval.v_number = get_sw_value(curbuf);
6602}
6603
6604/// "sockconnect()" function
6605static void f_sockconnect(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
6606{
6607  if (argvars[0].v_type != VAR_STRING || argvars[1].v_type != VAR_STRING) {
6608    emsg(_(e_invarg));
6609    return;
6610  }
6611  if (argvars[2].v_type != VAR_DICT && argvars[2].v_type != VAR_UNKNOWN) {
6612    // Wrong argument types
6613    semsg(_(e_invarg2), "expected dictionary");
6614    return;
6615  }
6616
6617  const char *mode = tv_get_string(&argvars[0]);
6618  const char *address = TO_SLASH_SAVE(tv_get_string(&argvars[1]));
6619
6620  bool tcp;
6621  if (strcmp(mode, "tcp") == 0) {
6622    tcp = true;
6623  } else if (strcmp(mode, "pipe") == 0) {
6624    tcp = false;
6625  } else {
6626    semsg(_(e_invarg2), "invalid mode");
6627    goto cleanup;
6628  }
6629
6630  bool rpc = false;
6631  CallbackReader on_data = CALLBACK_READER_INIT;
6632  if (argvars[2].v_type == VAR_DICT) {
6633    dict_T *opts = argvars[2].vval.v_dict;
6634    rpc = tv_dict_get_number(opts, "rpc") != 0;
6635
6636    if (!tv_dict_get_callback(opts, S_LEN("on_data"), &on_data.cb)) {
6637      goto cleanup;
6638    }
6639    on_data.buffered = tv_dict_get_number(opts, "data_buffered");
6640    if (on_data.buffered && on_data.cb.type == kCallbackNone) {
6641      on_data.self = opts;
6642    }
6643  }
6644
6645  const char *error = NULL;
6646  uint64_t id = channel_connect(tcp, address, rpc, on_data, 50, &error);
6647
6648  if (error) {
6649    semsg(_("connection failed: %s"), error);
6650  }
6651
6652  rettv->vval.v_number = (varnumber_T)id;
6653  rettv->v_type = VAR_NUMBER;
6654cleanup:
6655  XFREE_CLEAR(address);
6656}
6657
6658/// "stdioopen()" function
6659static void f_stdioopen(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
6660{
6661  if (argvars[0].v_type != VAR_DICT) {
6662    emsg(_(e_invarg));
6663    return;
6664  }
6665
6666  CallbackReader on_stdin = CALLBACK_READER_INIT;
6667  dict_T *opts = argvars[0].vval.v_dict;
6668  bool rpc = tv_dict_get_number(opts, "rpc") != 0;
6669
6670  if (!tv_dict_get_callback(opts, S_LEN("on_stdin"), &on_stdin.cb)) {
6671    return;
6672  }
6673  if (!tv_dict_get_callback(opts, S_LEN("on_print"), &on_print)) {
6674    return;
6675  }
6676
6677  on_stdin.buffered = tv_dict_get_number(opts, "stdin_buffered");
6678  if (on_stdin.buffered && on_stdin.cb.type == kCallbackNone) {
6679    on_stdin.self = opts;
6680  }
6681
6682  const char *error;
6683  uint64_t id = channel_from_stdio(rpc, on_stdin, &error);
6684  if (!id) {
6685    semsg(e_stdiochan2, error);
6686  }
6687
6688  rettv->vval.v_number = (varnumber_T)id;
6689  rettv->v_type = VAR_NUMBER;
6690}
6691
6692/// "reltimefloat()" function
6693static void f_reltimefloat(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
6694  FUNC_ATTR_NONNULL_ALL
6695{
6696  proftime_T tm;
6697
6698  rettv->v_type = VAR_FLOAT;
6699  rettv->vval.v_float = 0;
6700  if (list2proftime(&argvars[0], &tm) == OK) {
6701    rettv->vval.v_float = (float_T)profile_signed(tm) / NS_PER_SEC;
6702  }
6703}
6704
6705/// "soundfold({word})" function
6706static void f_soundfold(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
6707{
6708  rettv->v_type = VAR_STRING;
6709  const char *const s = tv_get_string(&argvars[0]);
6710  rettv->vval.v_string = eval_soundfold(s);
6711}
6712
6713/// "spellbadword()" function
6714static void f_spellbadword(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
6715{
6716  const int wo_spell_save = curwin->w_p_spell;
6717
6718  if (!curwin->w_p_spell) {
6719    parse_spelllang(curwin);
6720    curwin->w_p_spell = true;
6721  }
6722
6723  if (*curwin->w_s->b_p_spl == NUL) {
6724    emsg(_(e_no_spell));
6725    curwin->w_p_spell = wo_spell_save;
6726    return;
6727  }
6728
6729  const char *word = "";
6730  hlf_T attr = HLF_COUNT;
6731  size_t len = 0;
6732  if (argvars[0].v_type == VAR_UNKNOWN) {
6733    // Find the start and length of the badly spelled word.
6734    len = spell_move_to(curwin, FORWARD, SMT_ALL, true, &attr);
6735    if (len != 0) {
6736      word = get_cursor_pos_ptr();
6737      curwin->w_set_curswant = true;
6738    }
6739  } else if (*curbuf->b_s.b_p_spl != NUL) {
6740    const char *str = tv_get_string_chk(&argvars[0]);
6741    int capcol = -1;
6742
6743    if (str != NULL) {
6744      // Check the argument for spelling.
6745      while (*str != NUL) {
6746        len = spell_check(curwin, (char *)str, &attr, &capcol, false);
6747        if (attr != HLF_COUNT) {
6748          word = str;
6749          break;
6750        }
6751        str += len;
6752        capcol -= (int)len;
6753        len = 0;
6754      }
6755    }
6756  }
6757  curwin->w_p_spell = wo_spell_save;
6758
6759  assert(len <= INT_MAX);
6760  tv_list_alloc_ret(rettv, 2);
6761  tv_list_append_string(rettv->vval.v_list, word, (ssize_t)len);
6762  switch (attr) {
6763  case HLF_SPB:
6764    tv_list_append_string(rettv->vval.v_list, S_LEN("bad")); break;
6765  case HLF_SPR:
6766    tv_list_append_string(rettv->vval.v_list, S_LEN("rare")); break;
6767  case HLF_SPL:
6768    tv_list_append_string(rettv->vval.v_list, S_LEN("local")); break;
6769  case HLF_SPC:
6770    tv_list_append_string(rettv->vval.v_list, S_LEN("caps")); break;
6771  default:
6772    tv_list_append_string(rettv->vval.v_list, NULL, -1); break;
6773  }
6774}
6775
6776/// "spellsuggest()" function
6777static void f_spellsuggest(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
6778{
6779  garray_T ga = GA_EMPTY_INIT_VALUE;
6780  const int wo_spell_save = curwin->w_p_spell;
6781
6782  if (!curwin->w_p_spell) {
6783    parse_spelllang(curwin);
6784    curwin->w_p_spell = true;
6785  }
6786
6787  if (*curwin->w_s->b_p_spl == NUL) {
6788    emsg(_(e_no_spell));
6789    curwin->w_p_spell = wo_spell_save;
6790    return;
6791  }
6792
6793  int maxcount;
6794  bool need_capital = false;
6795  const char *const str = tv_get_string(&argvars[0]);
6796  if (argvars[1].v_type != VAR_UNKNOWN) {
6797    bool typeerr = false;
6798    maxcount = (int)tv_get_number_chk(&argvars[1], &typeerr);
6799    if (maxcount <= 0) {
6800      goto f_spellsuggest_return;
6801    }
6802    if (argvars[2].v_type != VAR_UNKNOWN) {
6803      need_capital = tv_get_bool_chk(&argvars[2], &typeerr);
6804      if (typeerr) {
6805        goto f_spellsuggest_return;
6806      }
6807    }
6808  } else {
6809    maxcount = 25;
6810  }
6811
6812  spell_suggest_list(&ga, (char *)str, maxcount, need_capital, false);
6813
6814f_spellsuggest_return:
6815  tv_list_alloc_ret(rettv, (ptrdiff_t)ga.ga_len);
6816  for (int i = 0; i < ga.ga_len; i++) {
6817    char *const p = ((char **)ga.ga_data)[i];
6818    tv_list_append_allocated_string(rettv->vval.v_list, p);
6819  }
6820  ga_clear(&ga);
6821  curwin->w_p_spell = wo_spell_save;
6822}
6823
6824static void f_split(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
6825{
6826  colnr_T col = 0;
6827  bool keepempty = false;
6828  bool typeerr = false;
6829
6830  // Make 'cpoptions' empty, the 'l' flag should not be used here.
6831  char *save_cpo = p_cpo;
6832  p_cpo = empty_string_option;
6833
6834  const char *str = tv_get_string(&argvars[0]);
6835  const char *pat = NULL;
6836  char patbuf[NUMBUFLEN];
6837  if (argvars[1].v_type != VAR_UNKNOWN) {
6838    pat = tv_get_string_buf_chk(&argvars[1], patbuf);
6839    if (pat == NULL) {
6840      typeerr = true;
6841    }
6842    if (argvars[2].v_type != VAR_UNKNOWN) {
6843      keepempty = (bool)tv_get_bool_chk(&argvars[2], &typeerr);
6844    }
6845  }
6846  if (pat == NULL || *pat == NUL) {
6847    pat = "[\\x01- ]\\+";
6848  }
6849
6850  tv_list_alloc_ret(rettv, kListLenMayKnow);
6851
6852  if (typeerr) {
6853    goto theend;
6854  }
6855
6856  regmatch_T regmatch = {
6857    .regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING),
6858    .startp = { NULL },
6859    .endp = { NULL },
6860    .rm_ic = false,
6861  };
6862  if (regmatch.regprog != NULL) {
6863    while (*str != NUL || keepempty) {
6864      bool match;
6865      if (*str == NUL) {
6866        match = false;  // Empty item at the end.
6867      } else {
6868        match = vim_regexec_nl(&regmatch, str, col);
6869      }
6870      const char *end;
6871      if (match) {
6872        end = regmatch.startp[0];
6873      } else {
6874        end = str + strlen(str);
6875      }
6876      if (keepempty || end > str || (tv_list_len(rettv->vval.v_list) > 0
6877                                     && *str != NUL
6878                                     && match
6879                                     && end < regmatch.endp[0])) {
6880        tv_list_append_string(rettv->vval.v_list, str, end - str);
6881      }
6882      if (!match) {
6883        break;
6884      }
6885      // Advance to just after the match.
6886      if (regmatch.endp[0] > str) {
6887        col = 0;
6888      } else {
6889        // Don't get stuck at the same match.
6890        col = utfc_ptr2len(regmatch.endp[0]);
6891      }
6892      str = regmatch.endp[0];
6893    }
6894
6895    vim_regfree(regmatch.regprog);
6896  }
6897
6898theend:
6899  p_cpo = save_cpo;
6900}
6901
6902/// "stdpath()" helper for list results
6903static void get_xdg_var_list(const XDGVarType xdg, typval_T *rettv)
6904  FUNC_ATTR_NONNULL_ALL
6905{
6906  list_T *const list = tv_list_alloc(kListLenShouldKnow);
6907  rettv->v_type = VAR_LIST;
6908  rettv->vval.v_list = list;
6909  tv_list_ref(list);
6910
6911  char *dirs;
6912  if (xdg == kXDGConfigHome) {
6913    dirs = stdpaths_user_conf();
6914  } else {
6915    dirs = stdpaths_get_xdg_var(xdg);
6916  }
6917  if (dirs == NULL) {
6918    return;
6919  }
6920  const void *iter = NULL;
6921  const char *appname = get_appname(false);
6922  do {
6923    size_t dir_len;
6924    const char *dir;
6925    iter = vim_env_iter(ENV_SEPCHAR, dirs, iter, &dir, &dir_len);
6926    if (dir != NULL && dir_len > 0) {
6927      char *dir_with_nvim = xmemdupz(dir, dir_len);
6928      dir_with_nvim = concat_fnames_realloc(dir_with_nvim, appname, true);
6929      tv_list_append_allocated_string(list, dir_with_nvim);
6930    }
6931  } while (iter != NULL);
6932  xfree(dirs);
6933}
6934
6935/// "stdpath(type)" function
6936static void f_stdpath(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
6937{
6938  rettv->v_type = VAR_STRING;
6939  rettv->vval.v_string = NULL;
6940
6941  const char *const p = tv_get_string_chk(&argvars[0]);
6942  if (p == NULL) {
6943    return;  // Type error; errmsg already given.
6944  }
6945
6946  if (strequal(p, "config")) {
6947    rettv->vval.v_string = get_xdg_home(kXDGConfigHome);
6948  } else if (strequal(p, "data")) {
6949    rettv->vval.v_string = get_xdg_home(kXDGDataHome);
6950  } else if (strequal(p, "cache")) {
6951    rettv->vval.v_string = get_xdg_home(kXDGCacheHome);
6952  } else if (strequal(p, "state")) {
6953    rettv->vval.v_string = get_xdg_home(kXDGStateHome);
6954  } else if (strequal(p, "log")) {
6955    rettv->vval.v_string = concat_fnames_realloc(get_xdg_home(kXDGStateHome), "logs", true);
6956  } else if (strequal(p, "run")) {
6957    rettv->vval.v_string = stdpaths_get_xdg_var(kXDGRuntimeDir);
6958  } else if (strequal(p, "config_dirs")) {
6959    get_xdg_var_list(kXDGConfigDirs, rettv);
6960  } else if (strequal(p, "data_dirs")) {
6961    get_xdg_var_list(kXDGDataDirs, rettv);
6962  } else {
6963    semsg(_("E6100: \"%s\" is not a valid stdpath"), p);
6964  }
6965}
6966
6967/// "str2float()" function
6968static void f_str2float(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
6969{
6970  char *p = skipwhite(tv_get_string(&argvars[0]));
6971  bool isneg = (*p == '-');
6972
6973  if (*p == '+' || *p == '-') {
6974    p = skipwhite(p + 1);
6975  }
6976  string2float(p, &rettv->vval.v_float);
6977  if (isneg) {
6978    rettv->vval.v_float *= -1;
6979  }
6980  rettv->v_type = VAR_FLOAT;
6981}
6982
6983/// "strftime({format}[, {time}])" function
6984static void f_strftime(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
6985{
6986  time_t seconds;
6987
6988  rettv->v_type = VAR_STRING;
6989
6990  char *p = (char *)tv_get_string(&argvars[0]);
6991  if (argvars[1].v_type == VAR_UNKNOWN) {
6992    seconds = time(NULL);
6993  } else {
6994    seconds = (time_t)tv_get_number(&argvars[1]);
6995  }
6996
6997  struct tm curtime;
6998  struct tm *curtime_ptr = os_localtime_r(&seconds, &curtime);
6999  // MSVC returns NULL for an invalid value of seconds.
7000  if (curtime_ptr == NULL) {
7001    rettv->vval.v_string = xstrdup(_("(Invalid)"));
7002    return;
7003  }
7004
7005  vimconv_T conv;
7006
7007  conv.vc_type = CONV_NONE;
7008  char *enc = enc_locale();
7009  convert_setup(&conv, p_enc, enc);
7010  if (conv.vc_type != CONV_NONE) {
7011    p = string_convert(&conv, p, NULL);
7012  }
7013  char result_buf[256];
7014  if (p == NULL || strftime(result_buf, sizeof(result_buf), p, curtime_ptr) == 0) {
7015    result_buf[0] = NUL;
7016  }
7017
7018  if (conv.vc_type != CONV_NONE) {
7019    xfree(p);
7020  }
7021  convert_setup(&conv, enc, p_enc);
7022  if (conv.vc_type != CONV_NONE) {
7023    rettv->vval.v_string = string_convert(&conv, result_buf, NULL);
7024  } else {
7025    rettv->vval.v_string = xstrdup(result_buf);
7026  }
7027
7028  // Release conversion descriptors.
7029  convert_setup(&conv, NULL, NULL);
7030  xfree(enc);
7031}
7032
7033/// "strptime({format}, {timestring})" function
7034static void f_strptime(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
7035{
7036  char fmt_buf[NUMBUFLEN];
7037  char str_buf[NUMBUFLEN];
7038
7039  struct tm tmval = {
7040    .tm_isdst = -1,
7041  };
7042  char *fmt = (char *)tv_get_string_buf(&argvars[0], fmt_buf);
7043  char *str = (char *)tv_get_string_buf(&argvars[1], str_buf);
7044
7045  vimconv_T conv = {
7046    .vc_type = CONV_NONE,
7047  };
7048  char *enc = enc_locale();
7049  convert_setup(&conv, p_enc, enc);
7050  if (conv.vc_type != CONV_NONE) {
7051    fmt = string_convert(&conv, fmt, NULL);
7052  }
7053  if (fmt == NULL
7054      || os_strptime(str, fmt, &tmval) == NULL
7055      || (rettv->vval.v_number = mktime(&tmval)) == -1) {
7056    rettv->vval.v_number = 0;
7057  }
7058  if (conv.vc_type != CONV_NONE) {
7059    xfree(fmt);
7060  }
7061  convert_setup(&conv, NULL, NULL);
7062  xfree(enc);
7063}
7064
7065/// "submatch()" function
7066static void f_submatch(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
7067{
7068  bool error = false;
7069  int no = (int)tv_get_number_chk(&argvars[0], &error);
7070  if (error) {
7071    return;
7072  }
7073
7074  if (no < 0 || no >= NSUBEXP) {
7075    semsg(_(e_invalid_submatch_number_nr), no);
7076    return;
7077  }
7078  int retList = 0;
7079
7080  if (argvars[1].v_type != VAR_UNKNOWN) {
7081    retList = (int)tv_get_bool_chk(&argvars[1], &error);
7082    if (error) {
7083      return;
7084    }
7085  }
7086
7087  if (retList == 0) {
7088    rettv->v_type = VAR_STRING;
7089    rettv->vval.v_string = reg_submatch(no);
7090  } else {
7091    rettv->v_type = VAR_LIST;
7092    rettv->vval.v_list = reg_submatch_list(no);
7093  }
7094}
7095
7096/// "substitute()" function
7097static void f_substitute(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
7098{
7099  char patbuf[NUMBUFLEN];
7100  char subbuf[NUMBUFLEN];
7101  char flagsbuf[NUMBUFLEN];
7102
7103  const char *const str = tv_get_string_chk(&argvars[0]);
7104  const char *const pat = tv_get_string_buf_chk(&argvars[1], patbuf);
7105  const char *sub = NULL;
7106  const char *const flg = tv_get_string_buf_chk(&argvars[3], flagsbuf);
7107
7108  typval_T *expr = NULL;
7109  if (tv_is_func(argvars[2])) {
7110    expr = &argvars[2];
7111  } else {
7112    sub = tv_get_string_buf_chk(&argvars[2], subbuf);
7113  }
7114
7115  rettv->v_type = VAR_STRING;
7116  if (str == NULL || pat == NULL || (sub == NULL && expr == NULL)
7117      || flg == NULL) {
7118    rettv->vval.v_string = NULL;
7119  } else {
7120    rettv->vval.v_string = do_string_sub((char *)str, strlen(str), (char *)pat,
7121                                         (char *)sub, expr, (char *)flg, NULL);
7122  }
7123}
7124
7125/// "swapfilelist()" function
7126static void f_swapfilelist(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
7127{
7128  tv_list_alloc_ret(rettv, kListLenUnknown);
7129  recover_names(NULL, false, rettv->vval.v_list);
7130}
7131
7132/// "swapinfo(swap_filename)" function
7133static void f_swapinfo(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
7134{
7135  tv_dict_alloc_ret(rettv);
7136  swapfile_dict(tv_get_string(argvars), rettv->vval.v_dict);
7137}
7138
7139/// "swapname(expr)" function
7140static void f_swapname(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
7141{
7142  rettv->v_type = VAR_STRING;
7143  buf_T *buf = tv_get_buf(&argvars[0], false);
7144  if (buf == NULL
7145      || buf->b_ml.ml_mfp == NULL
7146      || buf->b_ml.ml_mfp->mf_fname == NULL) {
7147    rettv->vval.v_string = NULL;
7148  } else {
7149    rettv->vval.v_string = xstrdup(buf->b_ml.ml_mfp->mf_fname);
7150  }
7151}
7152
7153/// "synID(lnum, col, trans)" function
7154static void f_synID(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
7155{
7156  // -1 on type error (both)
7157  const linenr_T lnum = tv_get_lnum(argvars);
7158  const colnr_T col = (colnr_T)tv_get_number(&argvars[1]) - 1;
7159
7160  bool transerr = false;
7161  const int trans = (int)tv_get_bool_chk(&argvars[2], &transerr);
7162
7163  int id = 0;
7164  if (!transerr && lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
7165      && col >= 0 && col < ml_get_len(lnum)) {
7166    id = syn_get_id(curwin, lnum, col, trans, NULL, false);
7167  }
7168
7169  rettv->vval.v_number = id;
7170}
7171
7172/// "synIDattr(id, what [, mode])" function
7173static void f_synIDattr(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
7174{
7175  const int id = (int)tv_get_number(&argvars[0]);
7176  const char *const what = tv_get_string(&argvars[1]);
7177  int modec;
7178  if (argvars[2].v_type != VAR_UNKNOWN) {
7179    char modebuf[NUMBUFLEN];
7180    const char *const mode = tv_get_string_buf(&argvars[2], modebuf);
7181    modec = TOLOWER_ASC(mode[0]);
7182    if (modec != 'c' && modec != 'g') {
7183      modec = 0;  // Replace invalid with current.
7184    }
7185  } else if (ui_rgb_attached()) {
7186    modec = 'g';
7187  } else {
7188    modec = 'c';
7189  }
7190
7191  const char *p = NULL;
7192  switch (TOLOWER_ASC(what[0])) {
7193  case 'b':
7194    if (TOLOWER_ASC(what[1]) == 'g') {  // bg[#]
7195      p = highlight_color(id, what, modec);
7196    } else if (TOLOWER_ASC(what[1]) == 'l') {  // blink
7197      p = highlight_has_attr(id, HL_BLINK, modec);
7198    } else {  // bold
7199      p = highlight_has_attr(id, HL_BOLD, modec);
7200    }
7201    break;
7202  case 'c':    // conceal
7203    p = highlight_has_attr(id, HL_CONCEALED, modec);
7204    break;
7205  case 'd':    // dim
7206    p = highlight_has_attr(id, HL_DIM, modec);
7207    break;
7208  case 'o':    // overline
7209    p = highlight_has_attr(id, HL_OVERLINE, modec);
7210    break;
7211  case 'f':    // fg[#] or font
7212    p = highlight_color(id, what, modec);
7213    break;
7214  case 'i':
7215    if (TOLOWER_ASC(what[1]) == 'n') {  // inverse
7216      p = highlight_has_attr(id, HL_INVERSE, modec);
7217    } else {  // italic
7218      p = highlight_has_attr(id, HL_ITALIC, modec);
7219    }
7220    break;
7221  case 'n':
7222    if (TOLOWER_ASC(what[1]) == 'o') {  // nocombine
7223      p = highlight_has_attr(id, HL_NOCOMBINE, modec);
7224    } else {  // name
7225      p = get_highlight_name_ext(NULL, id - 1, false);
7226    }
7227    break;
7228  case 'r':    // reverse
7229    p = highlight_has_attr(id, HL_INVERSE, modec);
7230    break;
7231  case 's':
7232    if (TOLOWER_ASC(what[1]) == 'p') {  // sp[#]
7233      p = highlight_color(id, what, modec);
7234    } else if (TOLOWER_ASC(what[1]) == 't'
7235               && TOLOWER_ASC(what[2]) == 'r') {  // strikethrough
7236      p = highlight_has_attr(id, HL_STRIKETHROUGH, modec);
7237    } else {  // standout
7238      p = highlight_has_attr(id, HL_STANDOUT, modec);
7239    }
7240    break;
7241  case 'u':
7242    if (strlen(what) >= 9) {
7243      if (TOLOWER_ASC(what[5]) == 'l') {
7244        // underline
7245        p = highlight_has_attr(id, HL_UNDERLINE, modec);
7246      } else if (TOLOWER_ASC(what[5]) != 'd') {
7247        // undercurl
7248        p = highlight_has_attr(id, HL_UNDERCURL, modec);
7249      } else if (TOLOWER_ASC(what[6]) != 'o') {
7250        // underdashed
7251        p = highlight_has_attr(id, HL_UNDERDASHED, modec);
7252      } else if (TOLOWER_ASC(what[7]) == 'u') {
7253        // underdouble
7254        p = highlight_has_attr(id, HL_UNDERDOUBLE, modec);
7255      } else {
7256        // underdotted
7257        p = highlight_has_attr(id, HL_UNDERDOTTED, modec);
7258      }
7259    } else {
7260      // ul
7261      p = highlight_color(id, what, modec);
7262    }
7263    break;
7264  }
7265
7266  rettv->v_type = VAR_STRING;
7267  rettv->vval.v_string = p == NULL ? NULL : xstrdup(p);
7268}
7269
7270/// "synIDtrans(id)" function
7271static void f_synIDtrans(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
7272{
7273  int id = (int)tv_get_number(&argvars[0]);
7274
7275  if (id > 0) {
7276    id = syn_get_final_id(id);
7277  } else {
7278    id = 0;
7279  }
7280
7281  rettv->vval.v_number = id;
7282}
7283
7284/// "synconcealed(lnum, col)" function
7285static void f_synconcealed(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
7286{
7287  int syntax_flags = 0;
7288  int matchid = 0;
7289  char str[NUMBUFLEN];
7290
7291  tv_list_set_ret(rettv, NULL);
7292
7293  // -1 on type error (both)
7294  const linenr_T lnum = tv_get_lnum(argvars);
7295  const colnr_T col = (colnr_T)tv_get_number(&argvars[1]) - 1;
7296
7297  CLEAR_FIELD(str);
7298
7299  if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
7300      && col >= 0 && col <= ml_get_len(lnum) && curwin->w_p_cole > 0) {
7301    syn_get_id(curwin, lnum, col, false, NULL, false);
7302    syntax_flags = get_syntax_info(&matchid);
7303
7304    // get the conceal character
7305    if ((syntax_flags & HL_CONCEAL) && curwin->w_p_cole < 3) {
7306      schar_T cchar = schar_from_char(syn_get_sub_char());
7307      if (cchar == NUL && curwin->w_p_cole == 1) {
7308        cchar = (curwin->w_p_lcs_chars.conceal == NUL)
7309                ? schar_from_ascii(' ') : curwin->w_p_lcs_chars.conceal;
7310      }
7311      if (cchar != NUL) {
7312        schar_get(str, cchar);
7313      }
7314    }
7315  }
7316
7317  tv_list_alloc_ret(rettv, 3);
7318  tv_list_append_number(rettv->vval.v_list, (syntax_flags & HL_CONCEAL) != 0);
7319  // -1 to auto-determine strlen
7320  tv_list_append_string(rettv->vval.v_list, str, -1);
7321  tv_list_append_number(rettv->vval.v_list, matchid);
7322}
7323
7324/// "synstack(lnum, col)" function
7325static void f_synstack(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
7326{
7327  tv_list_set_ret(rettv, NULL);
7328
7329  // -1 on type error (both)
7330  const linenr_T lnum = tv_get_lnum(argvars);
7331  const colnr_T col = (colnr_T)tv_get_number(&argvars[1]) - 1;
7332
7333  if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
7334      && col >= 0 && col <= ml_get_len(lnum)) {
7335    tv_list_alloc_ret(rettv, kListLenMayKnow);
7336    syn_get_id(curwin, lnum, col, false, NULL, true);
7337
7338    int id;
7339    int i = 0;
7340    while ((id = syn_get_stack_item(i++)) >= 0) {
7341      tv_list_append_number(rettv->vval.v_list, id);
7342    }
7343  }
7344}
7345
7346/// "tabpagebuflist()" function
7347static void f_tabpagebuflist(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
7348{
7349  win_T *wp = NULL;
7350
7351  if (argvars[0].v_type == VAR_UNKNOWN) {
7352    wp = firstwin;
7353  } else {
7354    tabpage_T *const tp = find_tabpage((int)tv_get_number(&argvars[0]));
7355    if (tp != NULL) {
7356      wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
7357    }
7358  }
7359  if (wp != NULL) {
7360    tv_list_alloc_ret(rettv, kListLenMayKnow);
7361    while (wp != NULL) {
7362      tv_list_append_number(rettv->vval.v_list, wp->w_buffer->b_fnum);
7363      wp = wp->w_next;
7364    }
7365  }
7366}
7367
7368/// "tagfiles()" function
7369static void f_tagfiles(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
7370{
7371  tv_list_alloc_ret(rettv, kListLenUnknown);
7372  char *fname = xmalloc(MAXPATHL);
7373
7374  bool first = true;
7375  tagname_T tn;
7376  while (get_tagfname(&tn, first, fname) == OK) {
7377    tv_list_append_string(rettv->vval.v_list, fname, -1);
7378    first = false;
7379  }
7380
7381  tagname_free(&tn);
7382  xfree(fname);
7383}
7384
7385/// "taglist()" function
7386static void f_taglist(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
7387{
7388  const char *const tag_pattern = tv_get_string(&argvars[0]);
7389
7390  rettv->vval.v_number = false;
7391  if (*tag_pattern == NUL) {
7392    return;
7393  }
7394
7395  const char *fname = NULL;
7396  if (argvars[1].v_type != VAR_UNKNOWN) {
7397    fname = tv_get_string(&argvars[1]);
7398  }
7399  get_tags(tv_list_alloc_ret(rettv, kListLenUnknown),
7400           (char *)tag_pattern, (char *)fname);
7401}
7402
7403/// "timer_info([timer])" function
7404static void f_timer_info(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
7405{
7406  tv_list_alloc_ret(rettv, kListLenUnknown);
7407
7408  if (tv_check_for_opt_number_arg(argvars, 0) == FAIL) {
7409    return;
7410  }
7411
7412  if (argvars[0].v_type != VAR_UNKNOWN) {
7413    timer_T *timer = find_timer_by_nr(tv_get_number(&argvars[0]));
7414    if (timer != NULL && (!timer->stopped || timer->refcount > 1)) {
7415      add_timer_info(rettv, timer);
7416    }
7417  } else {
7418    add_timer_info_all(rettv);
7419  }
7420}
7421
7422/// "timer_pause(timer, paused)" function
7423static void f_timer_pause(typval_T *argvars, typval_T *unused, EvalFuncData fptr)
7424{
7425  if (argvars[0].v_type != VAR_NUMBER) {
7426    emsg(_(e_number_exp));
7427    return;
7428  }
7429
7430  bool paused = (bool)tv_get_bool(&argvars[1]);
7431  timer_T *timer = find_timer_by_nr(tv_get_number(&argvars[0]));
7432  if (timer != NULL) {
7433    if (!timer->paused && paused) {
7434      time_watcher_stop(&timer->tw);
7435    } else if (timer->paused && !paused) {
7436      time_watcher_start(&timer->tw, timer_due_cb, (uint64_t)timer->timeout,
7437                         (uint64_t)timer->timeout);
7438    }
7439    timer->paused = paused;
7440  }
7441}
7442
7443/// "timer_start(timeout, callback, opts)" function
7444static void f_timer_start(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
7445{
7446  int repeat = 1;
7447
7448  rettv->vval.v_number = -1;
7449  if (check_secure()) {
7450    return;
7451  }
7452
7453  if (argvars[2].v_type != VAR_UNKNOWN) {
7454    if (tv_check_for_nonnull_dict_arg(argvars, 2) == FAIL) {
7455      return;
7456    }
7457    dict_T *dict = argvars[2].vval.v_dict;
7458    dictitem_T *const di = tv_dict_find(dict, S_LEN("repeat"));
7459    if (di != NULL) {
7460      repeat = (int)tv_get_number(&di->di_tv);
7461      if (repeat == 0) {
7462        repeat = 1;
7463      }
7464    }
7465  }
7466
7467  Callback callback;
7468  if (!callback_from_typval(&callback, &argvars[1])) {
7469    return;
7470  }
7471  rettv->vval.v_number = (varnumber_T)timer_start(tv_get_number(&argvars[0]), repeat, &callback);
7472}
7473
7474/// "timer_stop(timerid)" function
7475static void f_timer_stop(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
7476{
7477  if (tv_check_for_number_arg(argvars, 0) == FAIL) {
7478    return;
7479  }
7480
7481  timer_T *timer = find_timer_by_nr(tv_get_number(&argvars[0]));
7482  if (timer == NULL) {
7483    return;
7484  }
7485
7486  timer_stop(timer);
7487}
7488
7489static void f_timer_stopall(typval_T *argvars, typval_T *unused, EvalFuncData fptr)
7490{
7491  timer_stop_all();
7492}
7493
7494/// "type(expr)" function
7495static void f_type(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
7496{
7497  int n = -1;
7498
7499  switch (argvars[0].v_type) {
7500  case VAR_NUMBER:
7501    n = VAR_TYPE_NUMBER; break;
7502  case VAR_STRING:
7503    n = VAR_TYPE_STRING; break;
7504  case VAR_PARTIAL:
7505  case VAR_FUNC:
7506    n = VAR_TYPE_FUNC; break;
7507  case VAR_LIST:
7508    n = VAR_TYPE_LIST; break;
7509  case VAR_DICT:
7510    n = VAR_TYPE_DICT; break;
7511  case VAR_FLOAT:
7512    n = VAR_TYPE_FLOAT; break;
7513  case VAR_BOOL:
7514    n = VAR_TYPE_BOOL; break;
7515  case VAR_SPECIAL:
7516    n = VAR_TYPE_SPECIAL; break;
7517  case VAR_BLOB:
7518    n = VAR_TYPE_BLOB; break;
7519  case VAR_UNKNOWN:
7520    internal_error("f_type(UNKNOWN)");
7521    break;
7522  }
7523  rettv->vval.v_number = n;
7524}
7525
7526/// "virtcol({expr}, [, {list} [, {winid}]])" function
7527static void f_virtcol(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
7528{
7529  colnr_T vcol_start = 0;
7530  colnr_T vcol_end = 0;
7531  win_T *wp = curwin;
7532
7533  if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN) {
7534    // use the window specified in the third argument
7535    tabpage_T *tp;
7536    wp = win_id2wp_tp((int)tv_get_number(&argvars[2]), &tp);
7537    if (wp == NULL || tp == NULL) {
7538      goto theend;
7539    }
7540    check_cursor(wp);
7541  }
7542
7543  buf_T *bp = wp->w_buffer;
7544  int fnum = bp->b_fnum;
7545  pos_T *fp = var2fpos(&argvars[0], false, &fnum, false, wp);
7546  if (fp != NULL && fp->lnum <= bp->b_ml.ml_line_count
7547      && fnum == bp->b_fnum) {
7548    // Limit the column to a valid value, getvvcol() doesn't check.
7549    if (fp->col < 0) {
7550      fp->col = 0;
7551    } else {
7552      const colnr_T len = ml_get_buf_len(bp, fp->lnum);
7553      if (fp->col > len) {
7554        fp->col = len;
7555      }
7556    }
7557    getvvcol(wp, fp, &vcol_start, NULL, &vcol_end, 0);
7558    vcol_start++;
7559    vcol_end++;
7560  }
7561
7562theend:
7563  if (argvars[1].v_type != VAR_UNKNOWN && tv_get_bool(&argvars[1])) {
7564    tv_list_alloc_ret(rettv, 2);
7565    tv_list_append_number(rettv->vval.v_list, vcol_start);
7566    tv_list_append_number(rettv->vval.v_list, vcol_end);
7567  } else {
7568    rettv->vval.v_number = vcol_end;
7569  }
7570}
7571
7572/// "visualmode()" function
7573static void f_visualmode(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
7574{
7575  char str[2];
7576
7577  rettv->v_type = VAR_STRING;
7578  str[0] = (char)curbuf->b_visual_mode_eval;
7579  str[1] = NUL;
7580  rettv->vval.v_string = xstrdup(str);
7581
7582  // A non-zero number or non-empty string argument: reset mode.
7583  if (non_zero_arg(&argvars[0])) {
7584    curbuf->b_visual_mode_eval = NUL;
7585  }
7586}
7587
7588/// "wildmenumode()" function
7589static void f_wildmenumode(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
7590{
7591  if (wild_menu_showing || ((State & MODE_CMDLINE) && cmdline_pum_active())) {
7592    rettv->vval.v_number = 1;
7593  }
7594}
7595
7596/// "windowsversion()" function
7597static void f_windowsversion(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
7598{
7599  rettv->v_type = VAR_STRING;
7600  rettv->vval.v_string = xstrdup(windowsVersion);
7601}
7602
7603/// "wordcount()" function
7604static void f_wordcount(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
7605{
7606  tv_dict_alloc_ret(rettv);
7607  cursor_pos_info(rettv->vval.v_dict);
7608}
7609
7610/// "xor(expr, expr)" function
7611static void f_xor(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
7612{
7613  rettv->vval.v_number = tv_get_number_chk(&argvars[0], NULL)
7614                         ^ tv_get_number_chk(&argvars[1], NULL);
7615}