1 | // This is an open source non-commercial project. Dear PVS-Studio, please check |
2 | // it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com |
3 | |
4 | /* |
5 | * eval.c: Expression evaluation. |
6 | */ |
7 | |
8 | #include <assert.h> |
9 | #include <float.h> |
10 | #include <inttypes.h> |
11 | #include <stdarg.h> |
12 | #include <string.h> |
13 | #include <stdlib.h> |
14 | #include <stdbool.h> |
15 | #include <math.h> |
16 | #include <limits.h> |
17 | #include <msgpack.h> |
18 | |
19 | #include "nvim/assert.h" |
20 | #include "nvim/vim.h" |
21 | #include "nvim/ascii.h" |
22 | #ifdef HAVE_LOCALE_H |
23 | # include <locale.h> |
24 | #endif |
25 | #include "nvim/eval.h" |
26 | #include "nvim/buffer.h" |
27 | #include "nvim/change.h" |
28 | #include "nvim/channel.h" |
29 | #include "nvim/charset.h" |
30 | #include "nvim/context.h" |
31 | #include "nvim/cursor.h" |
32 | #include "nvim/diff.h" |
33 | #include "nvim/edit.h" |
34 | #include "nvim/ex_cmds.h" |
35 | #include "nvim/ex_cmds2.h" |
36 | #include "nvim/ex_docmd.h" |
37 | #include "nvim/ex_eval.h" |
38 | #include "nvim/ex_getln.h" |
39 | #include "nvim/fileio.h" |
40 | #include "nvim/os/fileio.h" |
41 | #include "nvim/func_attr.h" |
42 | #include "nvim/fold.h" |
43 | #include "nvim/getchar.h" |
44 | #include "nvim/hashtab.h" |
45 | #include "nvim/iconv.h" |
46 | #include "nvim/if_cscope.h" |
47 | #include "nvim/indent_c.h" |
48 | #include "nvim/indent.h" |
49 | #include "nvim/mark.h" |
50 | #include "nvim/math.h" |
51 | #include "nvim/mbyte.h" |
52 | #include "nvim/memline.h" |
53 | #include "nvim/memory.h" |
54 | #include "nvim/menu.h" |
55 | #include "nvim/message.h" |
56 | #include "nvim/misc1.h" |
57 | #include "nvim/keymap.h" |
58 | #include "nvim/map.h" |
59 | #include "nvim/file_search.h" |
60 | #include "nvim/garray.h" |
61 | #include "nvim/move.h" |
62 | #include "nvim/normal.h" |
63 | #include "nvim/ops.h" |
64 | #include "nvim/option.h" |
65 | #include "nvim/os_unix.h" |
66 | #include "nvim/path.h" |
67 | #include "nvim/popupmnu.h" |
68 | #include "nvim/profile.h" |
69 | #include "nvim/quickfix.h" |
70 | #include "nvim/regexp.h" |
71 | #include "nvim/screen.h" |
72 | #include "nvim/search.h" |
73 | #include "nvim/sha256.h" |
74 | #include "nvim/sign.h" |
75 | #include "nvim/spell.h" |
76 | #include "nvim/state.h" |
77 | #include "nvim/strings.h" |
78 | #include "nvim/syntax.h" |
79 | #include "nvim/tag.h" |
80 | #include "nvim/ui.h" |
81 | #include "nvim/main.h" |
82 | #include "nvim/mouse.h" |
83 | #include "nvim/terminal.h" |
84 | #include "nvim/undo.h" |
85 | #include "nvim/version.h" |
86 | #include "nvim/window.h" |
87 | #include "nvim/eval/encode.h" |
88 | #include "nvim/eval/decode.h" |
89 | #include "nvim/os/os.h" |
90 | #include "nvim/event/libuv_process.h" |
91 | #include "nvim/os/pty_process.h" |
92 | #include "nvim/event/rstream.h" |
93 | #include "nvim/event/wstream.h" |
94 | #include "nvim/event/time.h" |
95 | #include "nvim/os/time.h" |
96 | #include "nvim/msgpack_rpc/channel.h" |
97 | #include "nvim/msgpack_rpc/server.h" |
98 | #include "nvim/msgpack_rpc/helpers.h" |
99 | #include "nvim/api/private/helpers.h" |
100 | #include "nvim/api/vim.h" |
101 | #include "nvim/os/dl.h" |
102 | #include "nvim/os/input.h" |
103 | #include "nvim/event/loop.h" |
104 | #include "nvim/lib/kvec.h" |
105 | #include "nvim/lib/khash.h" |
106 | #include "nvim/lib/queue.h" |
107 | #include "nvim/lua/executor.h" |
108 | #include "nvim/eval/typval.h" |
109 | #include "nvim/eval/executor.h" |
110 | #include "nvim/eval/gc.h" |
111 | #include "nvim/macros.h" |
112 | |
113 | // TODO(ZyX-I): Remove DICT_MAXNEST, make users be non-recursive instead |
114 | |
115 | #define DICT_MAXNEST 100 /* maximum nesting of lists and dicts */ |
116 | |
117 | // Character used as separator in autoload function/variable names. |
118 | #define AUTOLOAD_CHAR '#' |
119 | |
120 | /* |
121 | * Structure returned by get_lval() and used by set_var_lval(). |
122 | * For a plain name: |
123 | * "name" points to the variable name. |
124 | * "exp_name" is NULL. |
125 | * "tv" is NULL |
126 | * For a magic braces name: |
127 | * "name" points to the expanded variable name. |
128 | * "exp_name" is non-NULL, to be freed later. |
129 | * "tv" is NULL |
130 | * For an index in a list: |
131 | * "name" points to the (expanded) variable name. |
132 | * "exp_name" NULL or non-NULL, to be freed later. |
133 | * "tv" points to the (first) list item value |
134 | * "li" points to the (first) list item |
135 | * "range", "n1", "n2" and "empty2" indicate what items are used. |
136 | * For an existing Dict item: |
137 | * "name" points to the (expanded) variable name. |
138 | * "exp_name" NULL or non-NULL, to be freed later. |
139 | * "tv" points to the dict item value |
140 | * "newkey" is NULL |
141 | * For a non-existing Dict item: |
142 | * "name" points to the (expanded) variable name. |
143 | * "exp_name" NULL or non-NULL, to be freed later. |
144 | * "tv" points to the Dictionary typval_T |
145 | * "newkey" is the key for the new item. |
146 | */ |
147 | typedef struct lval_S { |
148 | const char *ll_name; ///< Start of variable name (can be NULL). |
149 | size_t ll_name_len; ///< Length of the .ll_name. |
150 | char *ll_exp_name; ///< NULL or expanded name in allocated memory. |
151 | typval_T *ll_tv; ///< Typeval of item being used. If "newkey" |
152 | ///< isn't NULL it's the Dict to which to add the item. |
153 | listitem_T *ll_li; ///< The list item or NULL. |
154 | list_T *ll_list; ///< The list or NULL. |
155 | int ll_range; ///< TRUE when a [i:j] range was used. |
156 | long ll_n1; ///< First index for list. |
157 | long ll_n2; ///< Second index for list range. |
158 | int ll_empty2; ///< Second index is empty: [i:]. |
159 | dict_T *ll_dict; ///< The Dictionary or NULL. |
160 | dictitem_T *ll_di; ///< The dictitem or NULL. |
161 | char_u *ll_newkey; ///< New key for Dict in allocated memory or NULL. |
162 | } lval_T; |
163 | |
164 | |
165 | static char *e_letunexp = N_("E18: Unexpected characters in :let" ); |
166 | static char *e_missbrac = N_("E111: Missing ']'" ); |
167 | static char *e_listarg = N_("E686: Argument of %s must be a List" ); |
168 | static char *e_listdictarg = N_( |
169 | "E712: Argument of %s must be a List or Dictionary" ); |
170 | static char *e_listreq = N_("E714: List required" ); |
171 | static char *e_dictreq = N_("E715: Dictionary required" ); |
172 | static char *e_stringreq = N_("E928: String required" ); |
173 | static char *e_toomanyarg = N_("E118: Too many arguments for function: %s" ); |
174 | static char *e_dictkey = N_("E716: Key not present in Dictionary: %s" ); |
175 | static char *e_funcexts = N_( |
176 | "E122: Function %s already exists, add ! to replace it" ); |
177 | static char *e_funcdict = N_("E717: Dictionary entry already exists" ); |
178 | static char *e_funcref = N_("E718: Funcref required" ); |
179 | static char *e_dictrange = N_("E719: Cannot use [:] with a Dictionary" ); |
180 | static char *e_nofunc = N_("E130: Unknown function: %s" ); |
181 | static char *e_illvar = N_("E461: Illegal variable name: %s" ); |
182 | static char *e_cannot_mod = N_("E995: Cannot modify existing variable" ); |
183 | static const char *e_readonlyvar = N_( |
184 | "E46: Cannot change read-only variable \"%.*s\"" ); |
185 | |
186 | // TODO(ZyX-I): move to eval/executor |
187 | static char *e_letwrong = N_("E734: Wrong variable type for %s=" ); |
188 | |
189 | static char_u * const namespace_char = (char_u *)"abglstvw" ; |
190 | |
191 | /// Variable used for g: |
192 | static ScopeDictDictItem globvars_var; |
193 | |
194 | /// g: value |
195 | #define globvarht globvardict.dv_hashtab |
196 | |
197 | /* |
198 | * Old Vim variables such as "v:version" are also available without the "v:". |
199 | * Also in functions. We need a special hashtable for them. |
200 | */ |
201 | static hashtab_T compat_hashtab; |
202 | |
203 | hashtab_T func_hashtab; |
204 | |
205 | // Used for checking if local variables or arguments used in a lambda. |
206 | static int *eval_lavars_used = NULL; |
207 | |
208 | /* |
209 | * Array to hold the hashtab with variables local to each sourced script. |
210 | * Each item holds a variable (nameless) that points to the dict_T. |
211 | */ |
212 | typedef struct { |
213 | ScopeDictDictItem sv_var; |
214 | dict_T sv_dict; |
215 | } scriptvar_T; |
216 | |
217 | static garray_T ga_scripts = {0, 0, sizeof(scriptvar_T *), 4, NULL}; |
218 | #define SCRIPT_SV(id) (((scriptvar_T **)ga_scripts.ga_data)[(id) - 1]) |
219 | #define SCRIPT_VARS(id) (SCRIPT_SV(id)->sv_dict.dv_hashtab) |
220 | |
221 | static int echo_attr = 0; /* attributes used for ":echo" */ |
222 | |
223 | /// Describe data to return from find_some_match() |
224 | typedef enum { |
225 | kSomeMatch, ///< Data for match(). |
226 | kSomeMatchEnd, ///< Data for matchend(). |
227 | kSomeMatchList, ///< Data for matchlist(). |
228 | kSomeMatchStr, ///< Data for matchstr(). |
229 | kSomeMatchStrPos, ///< Data for matchstrpos(). |
230 | } SomeMatchType; |
231 | |
232 | /// trans_function_name() flags |
233 | typedef enum { |
234 | TFN_INT = 1, ///< May use internal function name |
235 | TFN_QUIET = 2, ///< Do not emit error messages. |
236 | TFN_NO_AUTOLOAD = 4, ///< Do not use script autoloading. |
237 | TFN_NO_DEREF = 8, ///< Do not dereference a Funcref. |
238 | TFN_READ_ONLY = 16, ///< Will not change the variable. |
239 | } TransFunctionNameFlags; |
240 | |
241 | /// get_lval() flags |
242 | typedef enum { |
243 | GLV_QUIET = TFN_QUIET, ///< Do not emit error messages. |
244 | GLV_NO_AUTOLOAD = TFN_NO_AUTOLOAD, ///< Do not use script autoloading. |
245 | GLV_READ_ONLY = TFN_READ_ONLY, ///< Indicates that caller will not change |
246 | ///< the value (prevents error message). |
247 | } GetLvalFlags; |
248 | |
249 | // flags used in uf_flags |
250 | #define FC_ABORT 0x01 // abort function on error |
251 | #define FC_RANGE 0x02 // function accepts range |
252 | #define FC_DICT 0x04 // Dict function, uses "self" |
253 | #define FC_CLOSURE 0x08 // closure, uses outer scope variables |
254 | #define FC_DELETED 0x10 // :delfunction used while uf_refcount > 0 |
255 | #define FC_REMOVED 0x20 // function redefined while uf_refcount > 0 |
256 | #define FC_SANDBOX 0x40 // function defined in the sandbox |
257 | |
258 | // The names of packages that once were loaded are remembered. |
259 | static garray_T ga_loaded = { 0, 0, sizeof(char_u *), 4, NULL }; |
260 | |
261 | #define FUNCARG(fp, j) ((char_u **)(fp->uf_args.ga_data))[j] |
262 | #define FUNCLINE(fp, j) ((char_u **)(fp->uf_lines.ga_data))[j] |
263 | |
264 | /// Short variable name length |
265 | #define VAR_SHORT_LEN 20 |
266 | /// Number of fixed variables used for arguments |
267 | #define FIXVAR_CNT 12 |
268 | |
269 | struct funccall_S { |
270 | ufunc_T *func; ///< Function being called. |
271 | int linenr; ///< Next line to be executed. |
272 | int returned; ///< ":return" used. |
273 | /// Fixed variables for arguments. |
274 | TV_DICTITEM_STRUCT(VAR_SHORT_LEN + 1) fixvar[FIXVAR_CNT]; |
275 | dict_T l_vars; ///< l: local function variables. |
276 | ScopeDictDictItem l_vars_var; ///< Variable for l: scope. |
277 | dict_T l_avars; ///< a: argument variables. |
278 | ScopeDictDictItem l_avars_var; ///< Variable for a: scope. |
279 | list_T l_varlist; ///< List for a:000. |
280 | listitem_T l_listitems[MAX_FUNC_ARGS]; ///< List items for a:000. |
281 | typval_T *rettv; ///< Return value. |
282 | linenr_T breakpoint; ///< Next line with breakpoint or zero. |
283 | int dbg_tick; ///< Debug_tick when breakpoint was set. |
284 | int level; ///< Top nesting level of executed function. |
285 | proftime_T prof_child; ///< Time spent in a child. |
286 | funccall_T *caller; ///< Calling function or NULL. |
287 | int fc_refcount; ///< Number of user functions that reference this funccall. |
288 | int fc_copyID; ///< CopyID used for garbage collection. |
289 | garray_T fc_funcs; ///< List of ufunc_T* which keep a reference to "func". |
290 | }; |
291 | |
292 | ///< Structure used by trans_function_name() |
293 | typedef struct { |
294 | dict_T *fd_dict; ///< Dictionary used. |
295 | char_u *fd_newkey; ///< New key in "dict" in allocated memory. |
296 | dictitem_T *fd_di; ///< Dictionary item used. |
297 | } funcdict_T; |
298 | |
299 | /* |
300 | * Info used by a ":for" loop. |
301 | */ |
302 | typedef struct { |
303 | int fi_semicolon; /* TRUE if ending in '; var]' */ |
304 | int fi_varcount; /* nr of variables in the list */ |
305 | listwatch_T fi_lw; /* keep an eye on the item used. */ |
306 | list_T *fi_list; /* list being used */ |
307 | } forinfo_T; |
308 | |
309 | /* values for vv_flags: */ |
310 | #define VV_COMPAT 1 /* compatible, also used without "v:" */ |
311 | #define VV_RO 2 /* read-only */ |
312 | #define VV_RO_SBX 4 /* read-only in the sandbox */ |
313 | |
314 | #define VV(idx, name, type, flags) \ |
315 | [idx] = { \ |
316 | .vv_name = name, \ |
317 | .vv_di = { \ |
318 | .di_tv = { .v_type = type }, \ |
319 | .di_flags = 0, \ |
320 | .di_key = { 0 }, \ |
321 | }, \ |
322 | .vv_flags = flags, \ |
323 | } |
324 | |
325 | // Array to hold the value of v: variables. |
326 | // The value is in a dictitem, so that it can also be used in the v: scope. |
327 | // The reason to use this table anyway is for very quick access to the |
328 | // variables with the VV_ defines. |
329 | static struct vimvar { |
330 | char *vv_name; ///< Name of the variable, without v:. |
331 | TV_DICTITEM_STRUCT(17) vv_di; ///< Value and name for key (max 16 chars). |
332 | char vv_flags; ///< Flags: #VV_COMPAT, #VV_RO, #VV_RO_SBX. |
333 | } vimvars[] = |
334 | { |
335 | // VV_ tails differing from upcased string literals: |
336 | // VV_CC_FROM "charconvert_from" |
337 | // VV_CC_TO "charconvert_to" |
338 | // VV_SEND_SERVER "servername" |
339 | // VV_REG "register" |
340 | // VV_OP "operator" |
341 | VV(VV_COUNT, "count" , VAR_NUMBER, VV_RO), |
342 | VV(VV_COUNT1, "count1" , VAR_NUMBER, VV_RO), |
343 | VV(VV_PREVCOUNT, "prevcount" , VAR_NUMBER, VV_RO), |
344 | VV(VV_ERRMSG, "errmsg" , VAR_STRING, 0), |
345 | VV(VV_WARNINGMSG, "warningmsg" , VAR_STRING, 0), |
346 | VV(VV_STATUSMSG, "statusmsg" , VAR_STRING, 0), |
347 | VV(VV_SHELL_ERROR, "shell_error" , VAR_NUMBER, VV_RO), |
348 | VV(VV_THIS_SESSION, "this_session" , VAR_STRING, 0), |
349 | VV(VV_VERSION, "version" , VAR_NUMBER, VV_COMPAT+VV_RO), |
350 | VV(VV_LNUM, "lnum" , VAR_NUMBER, VV_RO_SBX), |
351 | VV(VV_TERMRESPONSE, "termresponse" , VAR_STRING, VV_RO), |
352 | VV(VV_FNAME, "fname" , VAR_STRING, VV_RO), |
353 | VV(VV_LANG, "lang" , VAR_STRING, VV_RO), |
354 | VV(VV_LC_TIME, "lc_time" , VAR_STRING, VV_RO), |
355 | VV(VV_CTYPE, "ctype" , VAR_STRING, VV_RO), |
356 | VV(VV_CC_FROM, "charconvert_from" , VAR_STRING, VV_RO), |
357 | VV(VV_CC_TO, "charconvert_to" , VAR_STRING, VV_RO), |
358 | VV(VV_FNAME_IN, "fname_in" , VAR_STRING, VV_RO), |
359 | VV(VV_FNAME_OUT, "fname_out" , VAR_STRING, VV_RO), |
360 | VV(VV_FNAME_NEW, "fname_new" , VAR_STRING, VV_RO), |
361 | VV(VV_FNAME_DIFF, "fname_diff" , VAR_STRING, VV_RO), |
362 | VV(VV_CMDARG, "cmdarg" , VAR_STRING, VV_RO), |
363 | VV(VV_FOLDSTART, "foldstart" , VAR_NUMBER, VV_RO_SBX), |
364 | VV(VV_FOLDEND, "foldend" , VAR_NUMBER, VV_RO_SBX), |
365 | VV(VV_FOLDDASHES, "folddashes" , VAR_STRING, VV_RO_SBX), |
366 | VV(VV_FOLDLEVEL, "foldlevel" , VAR_NUMBER, VV_RO_SBX), |
367 | VV(VV_PROGNAME, "progname" , VAR_STRING, VV_RO), |
368 | VV(VV_SEND_SERVER, "servername" , VAR_STRING, VV_RO), |
369 | VV(VV_DYING, "dying" , VAR_NUMBER, VV_RO), |
370 | VV(VV_EXCEPTION, "exception" , VAR_STRING, VV_RO), |
371 | VV(VV_THROWPOINT, "throwpoint" , VAR_STRING, VV_RO), |
372 | VV(VV_STDERR, "stderr" , VAR_NUMBER, VV_RO), |
373 | VV(VV_REG, "register" , VAR_STRING, VV_RO), |
374 | VV(VV_CMDBANG, "cmdbang" , VAR_NUMBER, VV_RO), |
375 | VV(VV_INSERTMODE, "insertmode" , VAR_STRING, VV_RO), |
376 | VV(VV_VAL, "val" , VAR_UNKNOWN, VV_RO), |
377 | VV(VV_KEY, "key" , VAR_UNKNOWN, VV_RO), |
378 | VV(VV_PROFILING, "profiling" , VAR_NUMBER, VV_RO), |
379 | VV(VV_FCS_REASON, "fcs_reason" , VAR_STRING, VV_RO), |
380 | VV(VV_FCS_CHOICE, "fcs_choice" , VAR_STRING, 0), |
381 | VV(VV_BEVAL_BUFNR, "beval_bufnr" , VAR_NUMBER, VV_RO), |
382 | VV(VV_BEVAL_WINNR, "beval_winnr" , VAR_NUMBER, VV_RO), |
383 | VV(VV_BEVAL_WINID, "beval_winid" , VAR_NUMBER, VV_RO), |
384 | VV(VV_BEVAL_LNUM, "beval_lnum" , VAR_NUMBER, VV_RO), |
385 | VV(VV_BEVAL_COL, "beval_col" , VAR_NUMBER, VV_RO), |
386 | VV(VV_BEVAL_TEXT, "beval_text" , VAR_STRING, VV_RO), |
387 | VV(VV_SCROLLSTART, "scrollstart" , VAR_STRING, 0), |
388 | VV(VV_SWAPNAME, "swapname" , VAR_STRING, VV_RO), |
389 | VV(VV_SWAPCHOICE, "swapchoice" , VAR_STRING, 0), |
390 | VV(VV_SWAPCOMMAND, "swapcommand" , VAR_STRING, VV_RO), |
391 | VV(VV_CHAR, "char" , VAR_STRING, 0), |
392 | VV(VV_MOUSE_WIN, "mouse_win" , VAR_NUMBER, 0), |
393 | VV(VV_MOUSE_WINID, "mouse_winid" , VAR_NUMBER, 0), |
394 | VV(VV_MOUSE_LNUM, "mouse_lnum" , VAR_NUMBER, 0), |
395 | VV(VV_MOUSE_COL, "mouse_col" , VAR_NUMBER, 0), |
396 | VV(VV_OP, "operator" , VAR_STRING, VV_RO), |
397 | VV(VV_SEARCHFORWARD, "searchforward" , VAR_NUMBER, 0), |
398 | VV(VV_HLSEARCH, "hlsearch" , VAR_NUMBER, 0), |
399 | VV(VV_OLDFILES, "oldfiles" , VAR_LIST, 0), |
400 | VV(VV_WINDOWID, "windowid" , VAR_NUMBER, VV_RO_SBX), |
401 | VV(VV_PROGPATH, "progpath" , VAR_STRING, VV_RO), |
402 | VV(VV_COMPLETED_ITEM, "completed_item" , VAR_DICT, VV_RO), |
403 | VV(VV_OPTION_NEW, "option_new" , VAR_STRING, VV_RO), |
404 | VV(VV_OPTION_OLD, "option_old" , VAR_STRING, VV_RO), |
405 | VV(VV_OPTION_TYPE, "option_type" , VAR_STRING, VV_RO), |
406 | VV(VV_ERRORS, "errors" , VAR_LIST, 0), |
407 | VV(VV_MSGPACK_TYPES, "msgpack_types" , VAR_DICT, VV_RO), |
408 | VV(VV_EVENT, "event" , VAR_DICT, VV_RO), |
409 | VV(VV_FALSE, "false" , VAR_SPECIAL, VV_RO), |
410 | VV(VV_TRUE, "true" , VAR_SPECIAL, VV_RO), |
411 | VV(VV_NULL, "null" , VAR_SPECIAL, VV_RO), |
412 | VV(VV__NULL_LIST, "_null_list" , VAR_LIST, VV_RO), |
413 | VV(VV__NULL_DICT, "_null_dict" , VAR_DICT, VV_RO), |
414 | VV(VV_VIM_DID_ENTER, "vim_did_enter" , VAR_NUMBER, VV_RO), |
415 | VV(VV_TESTING, "testing" , VAR_NUMBER, 0), |
416 | VV(VV_TYPE_NUMBER, "t_number" , VAR_NUMBER, VV_RO), |
417 | VV(VV_TYPE_STRING, "t_string" , VAR_NUMBER, VV_RO), |
418 | VV(VV_TYPE_FUNC, "t_func" , VAR_NUMBER, VV_RO), |
419 | VV(VV_TYPE_LIST, "t_list" , VAR_NUMBER, VV_RO), |
420 | VV(VV_TYPE_DICT, "t_dict" , VAR_NUMBER, VV_RO), |
421 | VV(VV_TYPE_FLOAT, "t_float" , VAR_NUMBER, VV_RO), |
422 | VV(VV_TYPE_BOOL, "t_bool" , VAR_NUMBER, VV_RO), |
423 | VV(VV_ECHOSPACE, "echospace" , VAR_NUMBER, VV_RO), |
424 | VV(VV_EXITING, "exiting" , VAR_NUMBER, VV_RO), |
425 | }; |
426 | #undef VV |
427 | |
428 | /* shorthand */ |
429 | #define vv_type vv_di.di_tv.v_type |
430 | #define vv_nr vv_di.di_tv.vval.v_number |
431 | #define vv_special vv_di.di_tv.vval.v_special |
432 | #define vv_float vv_di.di_tv.vval.v_float |
433 | #define vv_str vv_di.di_tv.vval.v_string |
434 | #define vv_list vv_di.di_tv.vval.v_list |
435 | #define vv_dict vv_di.di_tv.vval.v_dict |
436 | #define vv_tv vv_di.di_tv |
437 | |
438 | /// Variable used for v: |
439 | static ScopeDictDictItem vimvars_var; |
440 | |
441 | /// v: hashtab |
442 | #define vimvarht vimvardict.dv_hashtab |
443 | |
444 | typedef struct { |
445 | TimeWatcher tw; |
446 | int timer_id; |
447 | int repeat_count; |
448 | int refcount; |
449 | int emsg_count; ///< Errors in a repeating timer. |
450 | long timeout; |
451 | bool stopped; |
452 | bool paused; |
453 | Callback callback; |
454 | } timer_T; |
455 | |
456 | typedef void (*FunPtr)(void); |
457 | |
458 | /// Prototype of C function that implements VimL function |
459 | typedef void (*VimLFunc)(typval_T *args, typval_T *rvar, FunPtr data); |
460 | |
461 | /// Structure holding VimL function definition |
462 | typedef struct fst { |
463 | char *name; ///< Name of the function. |
464 | uint8_t min_argc; ///< Minimal number of arguments. |
465 | uint8_t max_argc; ///< Maximal number of arguments. |
466 | VimLFunc func; ///< Function implementation. |
467 | FunPtr data; ///< Userdata for function implementation. |
468 | } VimLFuncDef; |
469 | |
470 | KHASH_MAP_INIT_STR(functions, VimLFuncDef) |
471 | |
472 | /// Type of assert_* check being performed |
473 | typedef enum |
474 | { |
475 | ASSERT_EQUAL, |
476 | ASSERT_NOTEQUAL, |
477 | ASSERT_MATCH, |
478 | ASSERT_NOTMATCH, |
479 | ASSERT_INRANGE, |
480 | ASSERT_OTHER, |
481 | } assert_type_T; |
482 | |
483 | /// Type for dict_list function |
484 | typedef enum { |
485 | kDictListKeys, ///< List dictionary keys. |
486 | kDictListValues, ///< List dictionary values. |
487 | kDictListItems, ///< List dictionary contents: [keys, values]. |
488 | } DictListType; |
489 | |
490 | #ifdef INCLUDE_GENERATED_DECLARATIONS |
491 | # include "eval.c.generated.h" |
492 | #endif |
493 | |
494 | #define FNE_INCL_BR 1 /* find_name_end(): include [] in name */ |
495 | #define FNE_CHECK_START 2 /* find_name_end(): check name starts with |
496 | valid character */ |
497 | |
498 | static uint64_t last_timer_id = 1; |
499 | static PMap(uint64_t) *timers = NULL; |
500 | |
501 | /// Dummy va_list for passing to vim_snprintf |
502 | /// |
503 | /// Used because: |
504 | /// - passing a NULL pointer doesn't work when va_list isn't a pointer |
505 | /// - locally in the function results in a "used before set" warning |
506 | /// - using va_start() to initialize it gives "function with fixed args" error |
507 | static va_list dummy_ap; |
508 | |
509 | static const char *const msgpack_type_names[] = { |
510 | [kMPNil] = "nil" , |
511 | [kMPBoolean] = "boolean" , |
512 | [kMPInteger] = "integer" , |
513 | [kMPFloat] = "float" , |
514 | [kMPString] = "string" , |
515 | [kMPBinary] = "binary" , |
516 | [kMPArray] = "array" , |
517 | [kMPMap] = "map" , |
518 | [kMPExt] = "ext" , |
519 | }; |
520 | const list_T *eval_msgpack_type_lists[] = { |
521 | [kMPNil] = NULL, |
522 | [kMPBoolean] = NULL, |
523 | [kMPInteger] = NULL, |
524 | [kMPFloat] = NULL, |
525 | [kMPString] = NULL, |
526 | [kMPBinary] = NULL, |
527 | [kMPArray] = NULL, |
528 | [kMPMap] = NULL, |
529 | [kMPExt] = NULL, |
530 | }; |
531 | |
532 | // Return "n1" divided by "n2", taking care of dividing by zero. |
533 | varnumber_T num_divide(varnumber_T n1, varnumber_T n2) |
534 | FUNC_ATTR_CONST FUNC_ATTR_WARN_UNUSED_RESULT |
535 | { |
536 | varnumber_T result; |
537 | |
538 | if (n2 == 0) { // give an error message? |
539 | if (n1 == 0) { |
540 | result = VARNUMBER_MIN; // similar to NaN |
541 | } else if (n1 < 0) { |
542 | result = -VARNUMBER_MAX; |
543 | } else { |
544 | result = VARNUMBER_MAX; |
545 | } |
546 | } else { |
547 | result = n1 / n2; |
548 | } |
549 | |
550 | return result; |
551 | } |
552 | |
553 | // Return "n1" modulus "n2", taking care of dividing by zero. |
554 | varnumber_T num_modulus(varnumber_T n1, varnumber_T n2) |
555 | FUNC_ATTR_CONST FUNC_ATTR_WARN_UNUSED_RESULT |
556 | { |
557 | // Give an error when n2 is 0? |
558 | return (n2 == 0) ? 0 : (n1 % n2); |
559 | } |
560 | |
561 | /* |
562 | * Initialize the global and v: variables. |
563 | */ |
564 | void eval_init(void) |
565 | { |
566 | vimvars[VV_VERSION].vv_nr = VIM_VERSION_100; |
567 | |
568 | timers = pmap_new(uint64_t)(); |
569 | struct vimvar *p; |
570 | |
571 | init_var_dict(&globvardict, &globvars_var, VAR_DEF_SCOPE); |
572 | init_var_dict(&vimvardict, &vimvars_var, VAR_SCOPE); |
573 | vimvardict.dv_lock = VAR_FIXED; |
574 | hash_init(&compat_hashtab); |
575 | hash_init(&func_hashtab); |
576 | |
577 | for (size_t i = 0; i < ARRAY_SIZE(vimvars); i++) { |
578 | p = &vimvars[i]; |
579 | assert(STRLEN(p->vv_name) <= 16); |
580 | STRCPY(p->vv_di.di_key, p->vv_name); |
581 | if (p->vv_flags & VV_RO) |
582 | p->vv_di.di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; |
583 | else if (p->vv_flags & VV_RO_SBX) |
584 | p->vv_di.di_flags = DI_FLAGS_RO_SBX | DI_FLAGS_FIX; |
585 | else |
586 | p->vv_di.di_flags = DI_FLAGS_FIX; |
587 | |
588 | /* add to v: scope dict, unless the value is not always available */ |
589 | if (p->vv_type != VAR_UNKNOWN) |
590 | hash_add(&vimvarht, p->vv_di.di_key); |
591 | if (p->vv_flags & VV_COMPAT) |
592 | /* add to compat scope dict */ |
593 | hash_add(&compat_hashtab, p->vv_di.di_key); |
594 | } |
595 | vimvars[VV_VERSION].vv_nr = VIM_VERSION_100; |
596 | |
597 | dict_T *const msgpack_types_dict = tv_dict_alloc(); |
598 | for (size_t i = 0; i < ARRAY_SIZE(msgpack_type_names); i++) { |
599 | list_T *const type_list = tv_list_alloc(0); |
600 | tv_list_set_lock(type_list, VAR_FIXED); |
601 | tv_list_ref(type_list); |
602 | dictitem_T *const di = tv_dict_item_alloc(msgpack_type_names[i]); |
603 | di->di_flags |= DI_FLAGS_RO|DI_FLAGS_FIX; |
604 | di->di_tv = (typval_T) { |
605 | .v_type = VAR_LIST, |
606 | .vval = { .v_list = type_list, }, |
607 | }; |
608 | eval_msgpack_type_lists[i] = type_list; |
609 | if (tv_dict_add(msgpack_types_dict, di) == FAIL) { |
610 | // There must not be duplicate items in this dictionary by definition. |
611 | assert(false); |
612 | } |
613 | } |
614 | msgpack_types_dict->dv_lock = VAR_FIXED; |
615 | |
616 | set_vim_var_dict(VV_MSGPACK_TYPES, msgpack_types_dict); |
617 | set_vim_var_dict(VV_COMPLETED_ITEM, tv_dict_alloc()); |
618 | |
619 | dict_T *v_event = tv_dict_alloc(); |
620 | v_event->dv_lock = VAR_FIXED; |
621 | set_vim_var_dict(VV_EVENT, v_event); |
622 | set_vim_var_list(VV_ERRORS, tv_list_alloc(kListLenUnknown)); |
623 | set_vim_var_nr(VV_STDERR, CHAN_STDERR); |
624 | set_vim_var_nr(VV_SEARCHFORWARD, 1L); |
625 | set_vim_var_nr(VV_HLSEARCH, 1L); |
626 | set_vim_var_nr(VV_COUNT1, 1); |
627 | set_vim_var_nr(VV_TYPE_NUMBER, VAR_TYPE_NUMBER); |
628 | set_vim_var_nr(VV_TYPE_STRING, VAR_TYPE_STRING); |
629 | set_vim_var_nr(VV_TYPE_FUNC, VAR_TYPE_FUNC); |
630 | set_vim_var_nr(VV_TYPE_LIST, VAR_TYPE_LIST); |
631 | set_vim_var_nr(VV_TYPE_DICT, VAR_TYPE_DICT); |
632 | set_vim_var_nr(VV_TYPE_FLOAT, VAR_TYPE_FLOAT); |
633 | set_vim_var_nr(VV_TYPE_BOOL, VAR_TYPE_BOOL); |
634 | |
635 | set_vim_var_special(VV_FALSE, kSpecialVarFalse); |
636 | set_vim_var_special(VV_TRUE, kSpecialVarTrue); |
637 | set_vim_var_special(VV_NULL, kSpecialVarNull); |
638 | set_vim_var_special(VV_EXITING, kSpecialVarNull); |
639 | |
640 | set_vim_var_nr(VV_ECHOSPACE, sc_col - 1); |
641 | |
642 | set_reg_var(0); // default for v:register is not 0 but '"' |
643 | } |
644 | |
645 | #if defined(EXITFREE) |
646 | void eval_clear(void) |
647 | { |
648 | struct vimvar *p; |
649 | |
650 | for (size_t i = 0; i < ARRAY_SIZE(vimvars); i++) { |
651 | p = &vimvars[i]; |
652 | if (p->vv_di.di_tv.v_type == VAR_STRING) { |
653 | XFREE_CLEAR(p->vv_str); |
654 | } else if (p->vv_di.di_tv.v_type == VAR_LIST) { |
655 | tv_list_unref(p->vv_list); |
656 | p->vv_list = NULL; |
657 | } |
658 | } |
659 | hash_clear(&vimvarht); |
660 | hash_init(&vimvarht); /* garbage_collect() will access it */ |
661 | hash_clear(&compat_hashtab); |
662 | |
663 | free_scriptnames(); |
664 | free_locales(); |
665 | |
666 | /* global variables */ |
667 | vars_clear(&globvarht); |
668 | |
669 | /* autoloaded script names */ |
670 | ga_clear_strings(&ga_loaded); |
671 | |
672 | /* Script-local variables. First clear all the variables and in a second |
673 | * loop free the scriptvar_T, because a variable in one script might hold |
674 | * a reference to the whole scope of another script. */ |
675 | for (int i = 1; i <= ga_scripts.ga_len; ++i) |
676 | vars_clear(&SCRIPT_VARS(i)); |
677 | for (int i = 1; i <= ga_scripts.ga_len; ++i) |
678 | xfree(SCRIPT_SV(i)); |
679 | ga_clear(&ga_scripts); |
680 | |
681 | // unreferenced lists and dicts |
682 | (void)garbage_collect(false); |
683 | |
684 | // functions |
685 | free_all_functions(); |
686 | } |
687 | |
688 | #endif |
689 | |
690 | /* |
691 | * Return the name of the executed function. |
692 | */ |
693 | char_u *func_name(void *cookie) |
694 | { |
695 | return ((funccall_T *)cookie)->func->uf_name; |
696 | } |
697 | |
698 | /* |
699 | * Return the address holding the next breakpoint line for a funccall cookie. |
700 | */ |
701 | linenr_T *func_breakpoint(void *cookie) |
702 | { |
703 | return &((funccall_T *)cookie)->breakpoint; |
704 | } |
705 | |
706 | /* |
707 | * Return the address holding the debug tick for a funccall cookie. |
708 | */ |
709 | int *func_dbg_tick(void *cookie) |
710 | { |
711 | return &((funccall_T *)cookie)->dbg_tick; |
712 | } |
713 | |
714 | /* |
715 | * Return the nesting level for a funccall cookie. |
716 | */ |
717 | int func_level(void *cookie) |
718 | { |
719 | return ((funccall_T *)cookie)->level; |
720 | } |
721 | |
722 | /* pointer to funccal for currently active function */ |
723 | funccall_T *current_funccal = NULL; |
724 | |
725 | // Pointer to list of previously used funccal, still around because some |
726 | // item in it is still being used. |
727 | funccall_T *previous_funccal = NULL; |
728 | |
729 | /* |
730 | * Return TRUE when a function was ended by a ":return" command. |
731 | */ |
732 | int current_func_returned(void) |
733 | { |
734 | return current_funccal->returned; |
735 | } |
736 | |
737 | /* |
738 | * Set an internal variable to a string value. Creates the variable if it does |
739 | * not already exist. |
740 | */ |
741 | void set_internal_string_var(char_u *name, char_u *value) |
742 | { |
743 | const typval_T tv = { |
744 | .v_type = VAR_STRING, |
745 | .vval.v_string = value, |
746 | }; |
747 | |
748 | set_var((const char *)name, STRLEN(name), (typval_T *)&tv, true); |
749 | } |
750 | |
751 | static lval_T *redir_lval = NULL; |
752 | static garray_T redir_ga; // Only valid when redir_lval is not NULL. |
753 | static char_u *redir_endp = NULL; |
754 | static char_u *redir_varname = NULL; |
755 | |
756 | /* |
757 | * Start recording command output to a variable |
758 | * Returns OK if successfully completed the setup. FAIL otherwise. |
759 | */ |
760 | int |
761 | var_redir_start( |
762 | char_u *name, |
763 | int append /* append to an existing variable */ |
764 | ) |
765 | { |
766 | int save_emsg; |
767 | int err; |
768 | typval_T tv; |
769 | |
770 | /* Catch a bad name early. */ |
771 | if (!eval_isnamec1(*name)) { |
772 | EMSG(_(e_invarg)); |
773 | return FAIL; |
774 | } |
775 | |
776 | /* Make a copy of the name, it is used in redir_lval until redir ends. */ |
777 | redir_varname = vim_strsave(name); |
778 | |
779 | redir_lval = xcalloc(1, sizeof(lval_T)); |
780 | |
781 | /* The output is stored in growarray "redir_ga" until redirection ends. */ |
782 | ga_init(&redir_ga, (int)sizeof(char), 500); |
783 | |
784 | // Parse the variable name (can be a dict or list entry). |
785 | redir_endp = (char_u *)get_lval(redir_varname, NULL, redir_lval, false, false, |
786 | 0, FNE_CHECK_START); |
787 | if (redir_endp == NULL || redir_lval->ll_name == NULL |
788 | || *redir_endp != NUL) { |
789 | clear_lval(redir_lval); |
790 | if (redir_endp != NULL && *redir_endp != NUL) |
791 | /* Trailing characters are present after the variable name */ |
792 | EMSG(_(e_trailing)); |
793 | else |
794 | EMSG(_(e_invarg)); |
795 | redir_endp = NULL; /* don't store a value, only cleanup */ |
796 | var_redir_stop(); |
797 | return FAIL; |
798 | } |
799 | |
800 | /* check if we can write to the variable: set it to or append an empty |
801 | * string */ |
802 | save_emsg = did_emsg; |
803 | did_emsg = FALSE; |
804 | tv.v_type = VAR_STRING; |
805 | tv.vval.v_string = (char_u *)"" ; |
806 | if (append) { |
807 | set_var_lval(redir_lval, redir_endp, &tv, true, false, (char_u *)"." ); |
808 | } else { |
809 | set_var_lval(redir_lval, redir_endp, &tv, true, false, (char_u *)"=" ); |
810 | } |
811 | clear_lval(redir_lval); |
812 | err = did_emsg; |
813 | did_emsg |= save_emsg; |
814 | if (err) { |
815 | redir_endp = NULL; /* don't store a value, only cleanup */ |
816 | var_redir_stop(); |
817 | return FAIL; |
818 | } |
819 | |
820 | return OK; |
821 | } |
822 | |
823 | /* |
824 | * Append "value[value_len]" to the variable set by var_redir_start(). |
825 | * The actual appending is postponed until redirection ends, because the value |
826 | * appended may in fact be the string we write to, changing it may cause freed |
827 | * memory to be used: |
828 | * :redir => foo |
829 | * :let foo |
830 | * :redir END |
831 | */ |
832 | void var_redir_str(char_u *value, int value_len) |
833 | { |
834 | int len; |
835 | |
836 | if (redir_lval == NULL) |
837 | return; |
838 | |
839 | if (value_len == -1) |
840 | len = (int)STRLEN(value); /* Append the entire string */ |
841 | else |
842 | len = value_len; /* Append only "value_len" characters */ |
843 | |
844 | ga_grow(&redir_ga, len); |
845 | memmove((char *)redir_ga.ga_data + redir_ga.ga_len, value, len); |
846 | redir_ga.ga_len += len; |
847 | } |
848 | |
849 | /* |
850 | * Stop redirecting command output to a variable. |
851 | * Frees the allocated memory. |
852 | */ |
853 | void var_redir_stop(void) |
854 | { |
855 | typval_T tv; |
856 | |
857 | if (redir_lval != NULL) { |
858 | /* If there was no error: assign the text to the variable. */ |
859 | if (redir_endp != NULL) { |
860 | ga_append(&redir_ga, NUL); /* Append the trailing NUL. */ |
861 | tv.v_type = VAR_STRING; |
862 | tv.vval.v_string = redir_ga.ga_data; |
863 | // Call get_lval() again, if it's inside a Dict or List it may |
864 | // have changed. |
865 | redir_endp = (char_u *)get_lval(redir_varname, NULL, redir_lval, |
866 | false, false, 0, FNE_CHECK_START); |
867 | if (redir_endp != NULL && redir_lval->ll_name != NULL) { |
868 | set_var_lval(redir_lval, redir_endp, &tv, false, false, (char_u *)"." ); |
869 | } |
870 | clear_lval(redir_lval); |
871 | } |
872 | |
873 | // free the collected output |
874 | XFREE_CLEAR(redir_ga.ga_data); |
875 | |
876 | XFREE_CLEAR(redir_lval); |
877 | } |
878 | XFREE_CLEAR(redir_varname); |
879 | } |
880 | |
881 | int eval_charconvert(const char *const enc_from, const char *const enc_to, |
882 | const char *const fname_from, const char *const fname_to) |
883 | { |
884 | bool err = false; |
885 | |
886 | set_vim_var_string(VV_CC_FROM, enc_from, -1); |
887 | set_vim_var_string(VV_CC_TO, enc_to, -1); |
888 | set_vim_var_string(VV_FNAME_IN, fname_from, -1); |
889 | set_vim_var_string(VV_FNAME_OUT, fname_to, -1); |
890 | if (eval_to_bool(p_ccv, &err, NULL, false)) { |
891 | err = true; |
892 | } |
893 | set_vim_var_string(VV_CC_FROM, NULL, -1); |
894 | set_vim_var_string(VV_CC_TO, NULL, -1); |
895 | set_vim_var_string(VV_FNAME_IN, NULL, -1); |
896 | set_vim_var_string(VV_FNAME_OUT, NULL, -1); |
897 | |
898 | if (err) { |
899 | return FAIL; |
900 | } |
901 | return OK; |
902 | } |
903 | |
904 | int eval_printexpr(const char *const fname, const char *const args) |
905 | { |
906 | bool err = false; |
907 | |
908 | set_vim_var_string(VV_FNAME_IN, fname, -1); |
909 | set_vim_var_string(VV_CMDARG, args, -1); |
910 | if (eval_to_bool(p_pexpr, &err, NULL, false)) { |
911 | err = true; |
912 | } |
913 | set_vim_var_string(VV_FNAME_IN, NULL, -1); |
914 | set_vim_var_string(VV_CMDARG, NULL, -1); |
915 | |
916 | if (err) { |
917 | os_remove(fname); |
918 | return FAIL; |
919 | } |
920 | return OK; |
921 | } |
922 | |
923 | void eval_diff(const char *const origfile, const char *const newfile, |
924 | const char *const outfile) |
925 | { |
926 | bool err = false; |
927 | |
928 | set_vim_var_string(VV_FNAME_IN, origfile, -1); |
929 | set_vim_var_string(VV_FNAME_NEW, newfile, -1); |
930 | set_vim_var_string(VV_FNAME_OUT, outfile, -1); |
931 | (void)eval_to_bool(p_dex, &err, NULL, FALSE); |
932 | set_vim_var_string(VV_FNAME_IN, NULL, -1); |
933 | set_vim_var_string(VV_FNAME_NEW, NULL, -1); |
934 | set_vim_var_string(VV_FNAME_OUT, NULL, -1); |
935 | } |
936 | |
937 | void eval_patch(const char *const origfile, const char *const difffile, |
938 | const char *const outfile) |
939 | { |
940 | bool err = false; |
941 | |
942 | set_vim_var_string(VV_FNAME_IN, origfile, -1); |
943 | set_vim_var_string(VV_FNAME_DIFF, difffile, -1); |
944 | set_vim_var_string(VV_FNAME_OUT, outfile, -1); |
945 | (void)eval_to_bool(p_pex, &err, NULL, FALSE); |
946 | set_vim_var_string(VV_FNAME_IN, NULL, -1); |
947 | set_vim_var_string(VV_FNAME_DIFF, NULL, -1); |
948 | set_vim_var_string(VV_FNAME_OUT, NULL, -1); |
949 | } |
950 | |
951 | /* |
952 | * Top level evaluation function, returning a boolean. |
953 | * Sets "error" to TRUE if there was an error. |
954 | * Return TRUE or FALSE. |
955 | */ |
956 | int |
957 | eval_to_bool( |
958 | char_u *arg, |
959 | bool *error, |
960 | char_u **nextcmd, |
961 | int skip /* only parse, don't execute */ |
962 | ) |
963 | { |
964 | typval_T tv; |
965 | bool retval = false; |
966 | |
967 | if (skip) { |
968 | emsg_skip++; |
969 | } |
970 | if (eval0(arg, &tv, nextcmd, !skip) == FAIL) { |
971 | *error = true; |
972 | } else { |
973 | *error = false; |
974 | if (!skip) { |
975 | retval = (tv_get_number_chk(&tv, error) != 0); |
976 | tv_clear(&tv); |
977 | } |
978 | } |
979 | if (skip) { |
980 | emsg_skip--; |
981 | } |
982 | |
983 | return retval; |
984 | } |
985 | |
986 | // Call eval1() and give an error message if not done at a lower level. |
987 | static int eval1_emsg(char_u **arg, typval_T *rettv, bool evaluate) |
988 | FUNC_ATTR_NONNULL_ARG(1, 2) |
989 | { |
990 | const char_u *const start = *arg; |
991 | const int did_emsg_before = did_emsg; |
992 | const int called_emsg_before = called_emsg; |
993 | |
994 | const int ret = eval1(arg, rettv, evaluate); |
995 | if (ret == FAIL) { |
996 | // Report the invalid expression unless the expression evaluation has |
997 | // been cancelled due to an aborting error, an interrupt, or an |
998 | // exception, or we already gave a more specific error. |
999 | // Also check called_emsg for when using assert_fails(). |
1000 | if (!aborting() |
1001 | && did_emsg == did_emsg_before |
1002 | && called_emsg == called_emsg_before) { |
1003 | emsgf(_(e_invexpr2), start); |
1004 | } |
1005 | } |
1006 | return ret; |
1007 | } |
1008 | |
1009 | static int eval_expr_typval(const typval_T *expr, typval_T *argv, |
1010 | int argc, typval_T *rettv) |
1011 | FUNC_ATTR_NONNULL_ARG(1, 2, 4) |
1012 | { |
1013 | int dummy; |
1014 | |
1015 | if (expr->v_type == VAR_FUNC) { |
1016 | const char_u *const s = expr->vval.v_string; |
1017 | if (s == NULL || *s == NUL) { |
1018 | return FAIL; |
1019 | } |
1020 | if (call_func(s, (int)STRLEN(s), rettv, argc, argv, NULL, |
1021 | 0L, 0L, &dummy, true, NULL, NULL) == FAIL) { |
1022 | return FAIL; |
1023 | } |
1024 | } else if (expr->v_type == VAR_PARTIAL) { |
1025 | partial_T *const partial = expr->vval.v_partial; |
1026 | const char_u *const s = partial_name(partial); |
1027 | if (s == NULL || *s == NUL) { |
1028 | return FAIL; |
1029 | } |
1030 | if (call_func(s, (int)STRLEN(s), rettv, argc, argv, NULL, |
1031 | 0L, 0L, &dummy, true, partial, NULL) == FAIL) { |
1032 | return FAIL; |
1033 | } |
1034 | } else { |
1035 | char buf[NUMBUFLEN]; |
1036 | char_u *s = (char_u *)tv_get_string_buf_chk(expr, buf); |
1037 | if (s == NULL) { |
1038 | return FAIL; |
1039 | } |
1040 | s = skipwhite(s); |
1041 | if (eval1_emsg(&s, rettv, true) == FAIL) { |
1042 | return FAIL; |
1043 | } |
1044 | if (*s != NUL) { // check for trailing chars after expr |
1045 | tv_clear(rettv); |
1046 | emsgf(_(e_invexpr2), s); |
1047 | return FAIL; |
1048 | } |
1049 | } |
1050 | return OK; |
1051 | } |
1052 | |
1053 | /// Like eval_to_bool() but using a typval_T instead of a string. |
1054 | /// Works for string, funcref and partial. |
1055 | static bool eval_expr_to_bool(const typval_T *expr, bool *error) |
1056 | FUNC_ATTR_NONNULL_ARG(1, 2) |
1057 | { |
1058 | typval_T argv, rettv; |
1059 | |
1060 | if (eval_expr_typval(expr, &argv, 0, &rettv) == FAIL) { |
1061 | *error = true; |
1062 | return false; |
1063 | } |
1064 | const bool res = (tv_get_number_chk(&rettv, error) != 0); |
1065 | tv_clear(&rettv); |
1066 | return res; |
1067 | } |
1068 | |
1069 | /// Top level evaluation function, returning a string |
1070 | /// |
1071 | /// @param[in] arg String to evaluate. |
1072 | /// @param nextcmd Pointer to the start of the next Ex command. |
1073 | /// @param[in] skip If true, only do parsing to nextcmd without reporting |
1074 | /// errors or actually evaluating anything. |
1075 | /// |
1076 | /// @return [allocated] string result of evaluation or NULL in case of error or |
1077 | /// when skipping. |
1078 | char *eval_to_string_skip(const char *arg, const char **nextcmd, |
1079 | const bool skip) |
1080 | FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_ARG(1) FUNC_ATTR_WARN_UNUSED_RESULT |
1081 | { |
1082 | typval_T tv; |
1083 | char *retval; |
1084 | |
1085 | if (skip) { |
1086 | emsg_skip++; |
1087 | } |
1088 | if (eval0((char_u *)arg, &tv, (char_u **)nextcmd, !skip) == FAIL || skip) { |
1089 | retval = NULL; |
1090 | } else { |
1091 | retval = xstrdup(tv_get_string(&tv)); |
1092 | tv_clear(&tv); |
1093 | } |
1094 | if (skip) { |
1095 | emsg_skip--; |
1096 | } |
1097 | |
1098 | return retval; |
1099 | } |
1100 | |
1101 | /* |
1102 | * Skip over an expression at "*pp". |
1103 | * Return FAIL for an error, OK otherwise. |
1104 | */ |
1105 | int skip_expr(char_u **pp) |
1106 | { |
1107 | typval_T rettv; |
1108 | |
1109 | *pp = skipwhite(*pp); |
1110 | return eval1(pp, &rettv, FALSE); |
1111 | } |
1112 | |
1113 | /* |
1114 | * Top level evaluation function, returning a string. |
1115 | * When "convert" is TRUE convert a List into a sequence of lines and convert |
1116 | * a Float to a String. |
1117 | * Return pointer to allocated memory, or NULL for failure. |
1118 | */ |
1119 | char_u *eval_to_string(char_u *arg, char_u **nextcmd, int convert) |
1120 | { |
1121 | typval_T tv; |
1122 | char *retval; |
1123 | garray_T ga; |
1124 | |
1125 | if (eval0(arg, &tv, nextcmd, true) == FAIL) { |
1126 | retval = NULL; |
1127 | } else { |
1128 | if (convert && tv.v_type == VAR_LIST) { |
1129 | ga_init(&ga, (int)sizeof(char), 80); |
1130 | if (tv.vval.v_list != NULL) { |
1131 | tv_list_join(&ga, tv.vval.v_list, "\n" ); |
1132 | if (tv_list_len(tv.vval.v_list) > 0) { |
1133 | ga_append(&ga, NL); |
1134 | } |
1135 | } |
1136 | ga_append(&ga, NUL); |
1137 | retval = (char *)ga.ga_data; |
1138 | } else if (convert && tv.v_type == VAR_FLOAT) { |
1139 | char numbuf[NUMBUFLEN]; |
1140 | vim_snprintf(numbuf, NUMBUFLEN, "%g" , tv.vval.v_float); |
1141 | retval = xstrdup(numbuf); |
1142 | } else { |
1143 | retval = xstrdup(tv_get_string(&tv)); |
1144 | } |
1145 | tv_clear(&tv); |
1146 | } |
1147 | |
1148 | return (char_u *)retval; |
1149 | } |
1150 | |
1151 | /* |
1152 | * Call eval_to_string() without using current local variables and using |
1153 | * textlock. When "use_sandbox" is TRUE use the sandbox. |
1154 | */ |
1155 | char_u *eval_to_string_safe(char_u *arg, char_u **nextcmd, int use_sandbox) |
1156 | { |
1157 | char_u *retval; |
1158 | void *save_funccalp; |
1159 | |
1160 | save_funccalp = save_funccal(); |
1161 | if (use_sandbox) |
1162 | ++sandbox; |
1163 | ++textlock; |
1164 | retval = eval_to_string(arg, nextcmd, FALSE); |
1165 | if (use_sandbox) |
1166 | --sandbox; |
1167 | --textlock; |
1168 | restore_funccal(save_funccalp); |
1169 | return retval; |
1170 | } |
1171 | |
1172 | /* |
1173 | * Top level evaluation function, returning a number. |
1174 | * Evaluates "expr" silently. |
1175 | * Returns -1 for an error. |
1176 | */ |
1177 | varnumber_T eval_to_number(char_u *expr) |
1178 | { |
1179 | typval_T rettv; |
1180 | varnumber_T retval; |
1181 | char_u *p = skipwhite(expr); |
1182 | |
1183 | ++emsg_off; |
1184 | |
1185 | if (eval1(&p, &rettv, true) == FAIL) { |
1186 | retval = -1; |
1187 | } else { |
1188 | retval = tv_get_number_chk(&rettv, NULL); |
1189 | tv_clear(&rettv); |
1190 | } |
1191 | --emsg_off; |
1192 | |
1193 | return retval; |
1194 | } |
1195 | |
1196 | |
1197 | /* |
1198 | * Prepare v: variable "idx" to be used. |
1199 | * Save the current typeval in "save_tv". |
1200 | * When not used yet add the variable to the v: hashtable. |
1201 | */ |
1202 | static void prepare_vimvar(int idx, typval_T *save_tv) |
1203 | { |
1204 | *save_tv = vimvars[idx].vv_tv; |
1205 | if (vimvars[idx].vv_type == VAR_UNKNOWN) |
1206 | hash_add(&vimvarht, vimvars[idx].vv_di.di_key); |
1207 | } |
1208 | |
1209 | /* |
1210 | * Restore v: variable "idx" to typeval "save_tv". |
1211 | * When no longer defined, remove the variable from the v: hashtable. |
1212 | */ |
1213 | static void restore_vimvar(int idx, typval_T *save_tv) |
1214 | { |
1215 | hashitem_T *hi; |
1216 | |
1217 | vimvars[idx].vv_tv = *save_tv; |
1218 | if (vimvars[idx].vv_type == VAR_UNKNOWN) { |
1219 | hi = hash_find(&vimvarht, vimvars[idx].vv_di.di_key); |
1220 | if (HASHITEM_EMPTY(hi)) { |
1221 | internal_error("restore_vimvar()" ); |
1222 | } else { |
1223 | hash_remove(&vimvarht, hi); |
1224 | } |
1225 | } |
1226 | } |
1227 | |
1228 | /// If there is a window for "curbuf", make it the current window. |
1229 | static void find_win_for_curbuf(void) |
1230 | { |
1231 | for (wininfo_T *wip = curbuf->b_wininfo; wip != NULL; wip = wip->wi_next) { |
1232 | if (wip->wi_win != NULL) { |
1233 | curwin = wip->wi_win; |
1234 | break; |
1235 | } |
1236 | } |
1237 | } |
1238 | |
1239 | /* |
1240 | * Evaluate an expression to a list with suggestions. |
1241 | * For the "expr:" part of 'spellsuggest'. |
1242 | * Returns NULL when there is an error. |
1243 | */ |
1244 | list_T *eval_spell_expr(char_u *badword, char_u *expr) |
1245 | { |
1246 | typval_T save_val; |
1247 | typval_T rettv; |
1248 | list_T *list = NULL; |
1249 | char_u *p = skipwhite(expr); |
1250 | |
1251 | // Set "v:val" to the bad word. |
1252 | prepare_vimvar(VV_VAL, &save_val); |
1253 | vimvars[VV_VAL].vv_type = VAR_STRING; |
1254 | vimvars[VV_VAL].vv_str = badword; |
1255 | if (p_verbose == 0) |
1256 | ++emsg_off; |
1257 | |
1258 | if (eval1(&p, &rettv, true) == OK) { |
1259 | if (rettv.v_type != VAR_LIST) { |
1260 | tv_clear(&rettv); |
1261 | } else { |
1262 | list = rettv.vval.v_list; |
1263 | } |
1264 | } |
1265 | |
1266 | if (p_verbose == 0) |
1267 | --emsg_off; |
1268 | restore_vimvar(VV_VAL, &save_val); |
1269 | |
1270 | return list; |
1271 | } |
1272 | |
1273 | /// Get spell word from an entry from spellsuggest=expr: |
1274 | /// |
1275 | /// Entry in question is supposed to be a list (to be checked by the caller) |
1276 | /// with two items: a word and a score represented as an unsigned number |
1277 | /// (whether it actually is unsigned is not checked). |
1278 | /// |
1279 | /// Used to get the good word and score from the eval_spell_expr() result. |
1280 | /// |
1281 | /// @param[in] list List to get values from. |
1282 | /// @param[out] ret_word Suggested word. Not initialized if return value is |
1283 | /// -1. |
1284 | /// |
1285 | /// @return -1 in case of error, score otherwise. |
1286 | int get_spellword(list_T *const list, const char **ret_word) |
1287 | { |
1288 | if (tv_list_len(list) != 2) { |
1289 | EMSG(_("E5700: Expression from 'spellsuggest' must yield lists with " |
1290 | "exactly two values" )); |
1291 | return -1; |
1292 | } |
1293 | *ret_word = tv_list_find_str(list, 0); |
1294 | if (*ret_word == NULL) { |
1295 | return -1; |
1296 | } |
1297 | return tv_list_find_nr(list, -1, NULL); |
1298 | } |
1299 | |
1300 | |
1301 | // Call some vim script function and return the result in "*rettv". |
1302 | // Uses argv[0] to argv[argc-1] for the function arguments. argv[argc] |
1303 | // should have type VAR_UNKNOWN. |
1304 | // |
1305 | // Return OK or FAIL. |
1306 | int call_vim_function( |
1307 | const char_u *func, |
1308 | int argc, |
1309 | typval_T *argv, |
1310 | typval_T *rettv |
1311 | ) |
1312 | FUNC_ATTR_NONNULL_ALL |
1313 | { |
1314 | int doesrange; |
1315 | int ret; |
1316 | |
1317 | rettv->v_type = VAR_UNKNOWN; // tv_clear() uses this. |
1318 | ret = call_func(func, (int)STRLEN(func), rettv, argc, argv, NULL, |
1319 | curwin->w_cursor.lnum, curwin->w_cursor.lnum, |
1320 | &doesrange, true, NULL, NULL); |
1321 | |
1322 | if (ret == FAIL) { |
1323 | tv_clear(rettv); |
1324 | } |
1325 | |
1326 | return ret; |
1327 | } |
1328 | /// Call Vim script function and return the result as a number |
1329 | /// |
1330 | /// @param[in] func Function name. |
1331 | /// @param[in] argc Number of arguments. |
1332 | /// @param[in] argv Array with typval_T arguments. |
1333 | /// |
1334 | /// @return -1 when calling function fails, result of function otherwise. |
1335 | varnumber_T call_func_retnr(const char_u *func, int argc, |
1336 | typval_T *argv) |
1337 | FUNC_ATTR_NONNULL_ALL |
1338 | { |
1339 | typval_T rettv; |
1340 | varnumber_T retval; |
1341 | |
1342 | if (call_vim_function(func, argc, argv, &rettv) == FAIL) { |
1343 | return -1; |
1344 | } |
1345 | retval = tv_get_number_chk(&rettv, NULL); |
1346 | tv_clear(&rettv); |
1347 | return retval; |
1348 | } |
1349 | /// Call Vim script function and return the result as a string |
1350 | /// |
1351 | /// @param[in] func Function name. |
1352 | /// @param[in] argc Number of arguments. |
1353 | /// @param[in] argv Array with typval_T arguments. |
1354 | /// |
1355 | /// @return [allocated] NULL when calling function fails, allocated string |
1356 | /// otherwise. |
1357 | char *call_func_retstr(const char *const func, int argc, |
1358 | typval_T *argv) |
1359 | FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_MALLOC |
1360 | { |
1361 | typval_T rettv; |
1362 | // All arguments are passed as strings, no conversion to number. |
1363 | if (call_vim_function((const char_u *)func, argc, argv, &rettv) |
1364 | == FAIL) { |
1365 | return NULL; |
1366 | } |
1367 | |
1368 | char *const retval = xstrdup(tv_get_string(&rettv)); |
1369 | tv_clear(&rettv); |
1370 | return retval; |
1371 | } |
1372 | /// Call Vim script function and return the result as a List |
1373 | /// |
1374 | /// @param[in] func Function name. |
1375 | /// @param[in] argc Number of arguments. |
1376 | /// @param[in] argv Array with typval_T arguments. |
1377 | /// |
1378 | /// @return [allocated] NULL when calling function fails or return tv is not a |
1379 | /// List, allocated List otherwise. |
1380 | void *call_func_retlist(const char_u *func, int argc, typval_T *argv) |
1381 | FUNC_ATTR_NONNULL_ALL |
1382 | { |
1383 | typval_T rettv; |
1384 | |
1385 | // All arguments are passed as strings, no conversion to number. |
1386 | if (call_vim_function(func, argc, argv, &rettv) == FAIL) { |
1387 | return NULL; |
1388 | } |
1389 | |
1390 | if (rettv.v_type != VAR_LIST) { |
1391 | tv_clear(&rettv); |
1392 | return NULL; |
1393 | } |
1394 | |
1395 | return rettv.vval.v_list; |
1396 | } |
1397 | |
1398 | /* |
1399 | * Save the current function call pointer, and set it to NULL. |
1400 | * Used when executing autocommands and for ":source". |
1401 | */ |
1402 | void *save_funccal(void) |
1403 | { |
1404 | funccall_T *fc = current_funccal; |
1405 | |
1406 | current_funccal = NULL; |
1407 | return (void *)fc; |
1408 | } |
1409 | |
1410 | void restore_funccal(void *vfc) |
1411 | { |
1412 | funccall_T *fc = (funccall_T *)vfc; |
1413 | |
1414 | current_funccal = fc; |
1415 | } |
1416 | |
1417 | /* |
1418 | * Prepare profiling for entering a child or something else that is not |
1419 | * counted for the script/function itself. |
1420 | * Should always be called in pair with prof_child_exit(). |
1421 | */ |
1422 | void prof_child_enter(proftime_T *tm /* place to store waittime */ |
1423 | ) |
1424 | { |
1425 | funccall_T *fc = current_funccal; |
1426 | |
1427 | if (fc != NULL && fc->func->uf_profiling) { |
1428 | fc->prof_child = profile_start(); |
1429 | } |
1430 | |
1431 | script_prof_save(tm); |
1432 | } |
1433 | |
1434 | /* |
1435 | * Take care of time spent in a child. |
1436 | * Should always be called after prof_child_enter(). |
1437 | */ |
1438 | void prof_child_exit(proftime_T *tm /* where waittime was stored */ |
1439 | ) |
1440 | { |
1441 | funccall_T *fc = current_funccal; |
1442 | |
1443 | if (fc != NULL && fc->func->uf_profiling) { |
1444 | fc->prof_child = profile_end(fc->prof_child); |
1445 | // don't count waiting time |
1446 | fc->prof_child = profile_sub_wait(*tm, fc->prof_child); |
1447 | fc->func->uf_tm_children = |
1448 | profile_add(fc->func->uf_tm_children, fc->prof_child); |
1449 | fc->func->uf_tml_children = |
1450 | profile_add(fc->func->uf_tml_children, fc->prof_child); |
1451 | } |
1452 | script_prof_restore(tm); |
1453 | } |
1454 | |
1455 | |
1456 | /* |
1457 | * Evaluate 'foldexpr'. Returns the foldlevel, and any character preceding |
1458 | * it in "*cp". Doesn't give error messages. |
1459 | */ |
1460 | int eval_foldexpr(char_u *arg, int *cp) |
1461 | { |
1462 | typval_T tv; |
1463 | varnumber_T retval; |
1464 | char_u *s; |
1465 | int use_sandbox = was_set_insecurely((char_u *)"foldexpr" , |
1466 | OPT_LOCAL); |
1467 | |
1468 | ++emsg_off; |
1469 | if (use_sandbox) |
1470 | ++sandbox; |
1471 | ++textlock; |
1472 | *cp = NUL; |
1473 | if (eval0(arg, &tv, NULL, TRUE) == FAIL) |
1474 | retval = 0; |
1475 | else { |
1476 | /* If the result is a number, just return the number. */ |
1477 | if (tv.v_type == VAR_NUMBER) |
1478 | retval = tv.vval.v_number; |
1479 | else if (tv.v_type != VAR_STRING || tv.vval.v_string == NULL) |
1480 | retval = 0; |
1481 | else { |
1482 | /* If the result is a string, check if there is a non-digit before |
1483 | * the number. */ |
1484 | s = tv.vval.v_string; |
1485 | if (!ascii_isdigit(*s) && *s != '-') |
1486 | *cp = *s++; |
1487 | retval = atol((char *)s); |
1488 | } |
1489 | tv_clear(&tv); |
1490 | } |
1491 | --emsg_off; |
1492 | if (use_sandbox) |
1493 | --sandbox; |
1494 | --textlock; |
1495 | |
1496 | return (int)retval; |
1497 | } |
1498 | |
1499 | // ":cons[t] var = expr1" define constant |
1500 | // ":cons[t] [name1, name2, ...] = expr1" define constants unpacking list |
1501 | // ":cons[t] [name, ..., ; lastname] = expr" define constants unpacking list |
1502 | void ex_const(exarg_T *eap) |
1503 | { |
1504 | ex_let_const(eap, true); |
1505 | } |
1506 | |
1507 | // ":let" list all variable values |
1508 | // ":let var1 var2" list variable values |
1509 | // ":let var = expr" assignment command. |
1510 | // ":let var += expr" assignment command. |
1511 | // ":let var -= expr" assignment command. |
1512 | // ":let var *= expr" assignment command. |
1513 | // ":let var /= expr" assignment command. |
1514 | // ":let var %= expr" assignment command. |
1515 | // ":let var .= expr" assignment command. |
1516 | // ":let var ..= expr" assignment command. |
1517 | // ":let [var1, var2] = expr" unpack list. |
1518 | // ":let [name, ..., ; lastname] = expr" unpack list. |
1519 | void ex_let(exarg_T *eap) |
1520 | { |
1521 | ex_let_const(eap, false); |
1522 | } |
1523 | |
1524 | static void ex_let_const(exarg_T *eap, const bool is_const) |
1525 | { |
1526 | char_u *arg = eap->arg; |
1527 | char_u *expr = NULL; |
1528 | typval_T rettv; |
1529 | int i; |
1530 | int var_count = 0; |
1531 | int semicolon = 0; |
1532 | char_u op[2]; |
1533 | char_u *argend; |
1534 | int first = TRUE; |
1535 | |
1536 | argend = (char_u *)skip_var_list(arg, &var_count, &semicolon); |
1537 | if (argend == NULL) { |
1538 | return; |
1539 | } |
1540 | if (argend > arg && argend[-1] == '.') { // For var.='str'. |
1541 | argend--; |
1542 | } |
1543 | expr = skipwhite(argend); |
1544 | if (*expr != '=' && !((vim_strchr((char_u *)"+-*/%." , *expr) != NULL |
1545 | && expr[1] == '=') || STRNCMP(expr, "..=" , 3) == 0)) { |
1546 | // ":let" without "=": list variables |
1547 | if (*arg == '[') { |
1548 | EMSG(_(e_invarg)); |
1549 | } else if (!ends_excmd(*arg)) { |
1550 | // ":let var1 var2" |
1551 | arg = (char_u *)list_arg_vars(eap, (const char *)arg, &first); |
1552 | } else if (!eap->skip) { |
1553 | // ":let" |
1554 | list_glob_vars(&first); |
1555 | list_buf_vars(&first); |
1556 | list_win_vars(&first); |
1557 | list_tab_vars(&first); |
1558 | list_script_vars(&first); |
1559 | list_func_vars(&first); |
1560 | list_vim_vars(&first); |
1561 | } |
1562 | eap->nextcmd = check_nextcmd(arg); |
1563 | } else { |
1564 | op[0] = '='; |
1565 | op[1] = NUL; |
1566 | if (*expr != '=') { |
1567 | if (vim_strchr((char_u *)"+-*/%." , *expr) != NULL) { |
1568 | op[0] = *expr; // +=, -=, *=, /=, %= or .= |
1569 | if (expr[0] == '.' && expr[1] == '.') { // ..= |
1570 | expr++; |
1571 | } |
1572 | } |
1573 | expr = skipwhite(expr + 2); |
1574 | } else { |
1575 | expr = skipwhite(expr + 1); |
1576 | } |
1577 | |
1578 | if (eap->skip) |
1579 | ++emsg_skip; |
1580 | i = eval0(expr, &rettv, &eap->nextcmd, !eap->skip); |
1581 | if (eap->skip) { |
1582 | if (i != FAIL) { |
1583 | tv_clear(&rettv); |
1584 | } |
1585 | emsg_skip--; |
1586 | } else if (i != FAIL) { |
1587 | (void)ex_let_vars(eap->arg, &rettv, false, semicolon, var_count, |
1588 | is_const, op); |
1589 | tv_clear(&rettv); |
1590 | } |
1591 | } |
1592 | } |
1593 | |
1594 | /* |
1595 | * Assign the typevalue "tv" to the variable or variables at "arg_start". |
1596 | * Handles both "var" with any type and "[var, var; var]" with a list type. |
1597 | * When "nextchars" is not NULL it points to a string with characters that |
1598 | * must appear after the variable(s). Use "+", "-" or "." for add, subtract |
1599 | * or concatenate. |
1600 | * Returns OK or FAIL; |
1601 | */ |
1602 | static int |
1603 | ex_let_vars( |
1604 | char_u *arg_start, |
1605 | typval_T *tv, |
1606 | int copy, // copy values from "tv", don't move |
1607 | int semicolon, // from skip_var_list() |
1608 | int var_count, // from skip_var_list() |
1609 | int is_const, // lock variables for :const |
1610 | char_u *nextchars |
1611 | ) |
1612 | { |
1613 | char_u *arg = arg_start; |
1614 | typval_T ltv; |
1615 | |
1616 | if (*arg != '[') { |
1617 | /* |
1618 | * ":let var = expr" or ":for var in list" |
1619 | */ |
1620 | if (ex_let_one(arg, tv, copy, is_const, nextchars, nextchars) == NULL) { |
1621 | return FAIL; |
1622 | } |
1623 | return OK; |
1624 | } |
1625 | |
1626 | // ":let [v1, v2] = list" or ":for [v1, v2] in listlist" |
1627 | if (tv->v_type != VAR_LIST) { |
1628 | EMSG(_(e_listreq)); |
1629 | return FAIL; |
1630 | } |
1631 | list_T *const l = tv->vval.v_list; |
1632 | |
1633 | const int len = tv_list_len(l); |
1634 | if (semicolon == 0 && var_count < len) { |
1635 | EMSG(_("E687: Less targets than List items" )); |
1636 | return FAIL; |
1637 | } |
1638 | if (var_count - semicolon > len) { |
1639 | EMSG(_("E688: More targets than List items" )); |
1640 | return FAIL; |
1641 | } |
1642 | // List l may actually be NULL, but it should fail with E688 or even earlier |
1643 | // if you try to do ":let [] = v:_null_list". |
1644 | assert(l != NULL); |
1645 | |
1646 | listitem_T *item = tv_list_first(l); |
1647 | size_t rest_len = tv_list_len(l); |
1648 | while (*arg != ']') { |
1649 | arg = skipwhite(arg + 1); |
1650 | arg = ex_let_one(arg, TV_LIST_ITEM_TV(item), true, is_const, |
1651 | (const char_u *)",;]" , nextchars); |
1652 | if (arg == NULL) { |
1653 | return FAIL; |
1654 | } |
1655 | rest_len--; |
1656 | |
1657 | item = TV_LIST_ITEM_NEXT(l, item); |
1658 | arg = skipwhite(arg); |
1659 | if (*arg == ';') { |
1660 | /* Put the rest of the list (may be empty) in the var after ';'. |
1661 | * Create a new list for this. */ |
1662 | list_T *const rest_list = tv_list_alloc(rest_len); |
1663 | while (item != NULL) { |
1664 | tv_list_append_tv(rest_list, TV_LIST_ITEM_TV(item)); |
1665 | item = TV_LIST_ITEM_NEXT(l, item); |
1666 | } |
1667 | |
1668 | ltv.v_type = VAR_LIST; |
1669 | ltv.v_lock = VAR_UNLOCKED; |
1670 | ltv.vval.v_list = rest_list; |
1671 | tv_list_ref(rest_list); |
1672 | |
1673 | arg = ex_let_one(skipwhite(arg + 1), <v, false, is_const, |
1674 | (char_u *)"]" , nextchars); |
1675 | tv_clear(<v); |
1676 | if (arg == NULL) { |
1677 | return FAIL; |
1678 | } |
1679 | break; |
1680 | } else if (*arg != ',' && *arg != ']') { |
1681 | internal_error("ex_let_vars()" ); |
1682 | return FAIL; |
1683 | } |
1684 | } |
1685 | |
1686 | return OK; |
1687 | } |
1688 | |
1689 | /* |
1690 | * Skip over assignable variable "var" or list of variables "[var, var]". |
1691 | * Used for ":let varvar = expr" and ":for varvar in expr". |
1692 | * For "[var, var]" increment "*var_count" for each variable. |
1693 | * for "[var, var; var]" set "semicolon". |
1694 | * Return NULL for an error. |
1695 | */ |
1696 | static const char_u *skip_var_list(const char_u *arg, int *var_count, |
1697 | int *semicolon) |
1698 | { |
1699 | const char_u *p; |
1700 | const char_u *s; |
1701 | |
1702 | if (*arg == '[') { |
1703 | /* "[var, var]": find the matching ']'. */ |
1704 | p = arg; |
1705 | for (;; ) { |
1706 | p = skipwhite(p + 1); /* skip whites after '[', ';' or ',' */ |
1707 | s = skip_var_one(p); |
1708 | if (s == p) { |
1709 | EMSG2(_(e_invarg2), p); |
1710 | return NULL; |
1711 | } |
1712 | ++*var_count; |
1713 | |
1714 | p = skipwhite(s); |
1715 | if (*p == ']') |
1716 | break; |
1717 | else if (*p == ';') { |
1718 | if (*semicolon == 1) { |
1719 | EMSG(_("Double ; in list of variables" )); |
1720 | return NULL; |
1721 | } |
1722 | *semicolon = 1; |
1723 | } else if (*p != ',') { |
1724 | EMSG2(_(e_invarg2), p); |
1725 | return NULL; |
1726 | } |
1727 | } |
1728 | return p + 1; |
1729 | } else |
1730 | return skip_var_one(arg); |
1731 | } |
1732 | |
1733 | /* |
1734 | * Skip one (assignable) variable name, including @r, $VAR, &option, d.key, |
1735 | * l[idx]. |
1736 | */ |
1737 | static const char_u *skip_var_one(const char_u *arg) |
1738 | { |
1739 | if (*arg == '@' && arg[1] != NUL) |
1740 | return arg + 2; |
1741 | return find_name_end(*arg == '$' || *arg == '&' ? arg + 1 : arg, |
1742 | NULL, NULL, FNE_INCL_BR | FNE_CHECK_START); |
1743 | } |
1744 | |
1745 | /* |
1746 | * List variables for hashtab "ht" with prefix "prefix". |
1747 | * If "empty" is TRUE also list NULL strings as empty strings. |
1748 | */ |
1749 | static void list_hashtable_vars(hashtab_T *ht, const char *prefix, int empty, |
1750 | int *first) |
1751 | { |
1752 | hashitem_T *hi; |
1753 | dictitem_T *di; |
1754 | int todo; |
1755 | |
1756 | todo = (int)ht->ht_used; |
1757 | for (hi = ht->ht_array; todo > 0 && !got_int; ++hi) { |
1758 | if (!HASHITEM_EMPTY(hi)) { |
1759 | todo--; |
1760 | di = TV_DICT_HI2DI(hi); |
1761 | char buf[IOSIZE]; |
1762 | |
1763 | // apply :filter /pat/ to variable name |
1764 | xstrlcpy(buf, prefix, IOSIZE - 1); |
1765 | xstrlcat(buf, (char *)di->di_key, IOSIZE); |
1766 | if (message_filtered((char_u *)buf)) { |
1767 | continue; |
1768 | } |
1769 | |
1770 | if (empty || di->di_tv.v_type != VAR_STRING |
1771 | || di->di_tv.vval.v_string != NULL) { |
1772 | list_one_var(di, prefix, first); |
1773 | } |
1774 | } |
1775 | } |
1776 | } |
1777 | |
1778 | /* |
1779 | * List global variables. |
1780 | */ |
1781 | static void list_glob_vars(int *first) |
1782 | { |
1783 | list_hashtable_vars(&globvarht, "" , true, first); |
1784 | } |
1785 | |
1786 | /* |
1787 | * List buffer variables. |
1788 | */ |
1789 | static void list_buf_vars(int *first) |
1790 | { |
1791 | list_hashtable_vars(&curbuf->b_vars->dv_hashtab, "b:" , true, first); |
1792 | } |
1793 | |
1794 | /* |
1795 | * List window variables. |
1796 | */ |
1797 | static void list_win_vars(int *first) |
1798 | { |
1799 | list_hashtable_vars(&curwin->w_vars->dv_hashtab, "w:" , true, first); |
1800 | } |
1801 | |
1802 | /* |
1803 | * List tab page variables. |
1804 | */ |
1805 | static void list_tab_vars(int *first) |
1806 | { |
1807 | list_hashtable_vars(&curtab->tp_vars->dv_hashtab, "t:" , true, first); |
1808 | } |
1809 | |
1810 | /* |
1811 | * List Vim variables. |
1812 | */ |
1813 | static void list_vim_vars(int *first) |
1814 | { |
1815 | list_hashtable_vars(&vimvarht, "v:" , false, first); |
1816 | } |
1817 | |
1818 | // List script-local variables, if there is a script. |
1819 | static void list_script_vars(int *first) |
1820 | { |
1821 | if (current_sctx.sc_sid > 0 && current_sctx.sc_sid <= ga_scripts.ga_len) { |
1822 | list_hashtable_vars(&SCRIPT_VARS(current_sctx.sc_sid), "s:" , false, first); |
1823 | } |
1824 | } |
1825 | |
1826 | /* |
1827 | * List function variables, if there is a function. |
1828 | */ |
1829 | static void list_func_vars(int *first) |
1830 | { |
1831 | if (current_funccal != NULL) { |
1832 | list_hashtable_vars(¤t_funccal->l_vars.dv_hashtab, "l:" , false, |
1833 | first); |
1834 | } |
1835 | } |
1836 | |
1837 | /* |
1838 | * List variables in "arg". |
1839 | */ |
1840 | static const char *list_arg_vars(exarg_T *eap, const char *arg, int *first) |
1841 | { |
1842 | int error = FALSE; |
1843 | int len; |
1844 | const char *name; |
1845 | const char *name_start; |
1846 | typval_T tv; |
1847 | |
1848 | while (!ends_excmd(*arg) && !got_int) { |
1849 | if (error || eap->skip) { |
1850 | arg = (const char *)find_name_end((char_u *)arg, NULL, NULL, |
1851 | FNE_INCL_BR | FNE_CHECK_START); |
1852 | if (!ascii_iswhite(*arg) && !ends_excmd(*arg)) { |
1853 | emsg_severe = TRUE; |
1854 | EMSG(_(e_trailing)); |
1855 | break; |
1856 | } |
1857 | } else { |
1858 | // get_name_len() takes care of expanding curly braces |
1859 | name_start = name = arg; |
1860 | char *tofree; |
1861 | len = get_name_len(&arg, &tofree, true, true); |
1862 | if (len <= 0) { |
1863 | /* This is mainly to keep test 49 working: when expanding |
1864 | * curly braces fails overrule the exception error message. */ |
1865 | if (len < 0 && !aborting()) { |
1866 | emsg_severe = TRUE; |
1867 | EMSG2(_(e_invarg2), arg); |
1868 | break; |
1869 | } |
1870 | error = TRUE; |
1871 | } else { |
1872 | if (tofree != NULL) { |
1873 | name = tofree; |
1874 | } |
1875 | if (get_var_tv((const char *)name, len, &tv, NULL, true, false) |
1876 | == FAIL) { |
1877 | error = true; |
1878 | } else { |
1879 | // handle d.key, l[idx], f(expr) |
1880 | const char *const arg_subsc = arg; |
1881 | if (handle_subscript(&arg, &tv, true, true) == FAIL) { |
1882 | error = true; |
1883 | } else { |
1884 | if (arg == arg_subsc && len == 2 && name[1] == ':') { |
1885 | switch (*name) { |
1886 | case 'g': list_glob_vars(first); break; |
1887 | case 'b': list_buf_vars(first); break; |
1888 | case 'w': list_win_vars(first); break; |
1889 | case 't': list_tab_vars(first); break; |
1890 | case 'v': list_vim_vars(first); break; |
1891 | case 's': list_script_vars(first); break; |
1892 | case 'l': list_func_vars(first); break; |
1893 | default: |
1894 | EMSG2(_("E738: Can't list variables for %s" ), name); |
1895 | } |
1896 | } else { |
1897 | char *const s = encode_tv2echo(&tv, NULL); |
1898 | const char *const used_name = (arg == arg_subsc |
1899 | ? name |
1900 | : name_start); |
1901 | const ptrdiff_t name_size = (used_name == tofree |
1902 | ? (ptrdiff_t)strlen(used_name) |
1903 | : (arg - used_name)); |
1904 | list_one_var_a("" , used_name, name_size, |
1905 | tv.v_type, s == NULL ? "" : s, first); |
1906 | xfree(s); |
1907 | } |
1908 | tv_clear(&tv); |
1909 | } |
1910 | } |
1911 | } |
1912 | |
1913 | xfree(tofree); |
1914 | } |
1915 | |
1916 | arg = (const char *)skipwhite((const char_u *)arg); |
1917 | } |
1918 | |
1919 | return arg; |
1920 | } |
1921 | |
1922 | // TODO(ZyX-I): move to eval/ex_cmds |
1923 | |
1924 | /// Set one item of `:let var = expr` or `:let [v1, v2] = list` to its value |
1925 | /// |
1926 | /// @param[in] arg Start of the variable name. |
1927 | /// @param[in] tv Value to assign to the variable. |
1928 | /// @param[in] copy If true, copy value from `tv`. |
1929 | /// @param[in] endchars Valid characters after variable name or NULL. |
1930 | /// @param[in] op Operation performed: *op is `+`, `-`, `.` for `+=`, etc. |
1931 | /// NULL for `=`. |
1932 | /// |
1933 | /// @return a pointer to the char just after the var name or NULL in case of |
1934 | /// error. |
1935 | static char_u *ex_let_one(char_u *arg, typval_T *const tv, |
1936 | const bool copy, const bool is_const, |
1937 | const char_u *const endchars, const char_u *const op) |
1938 | FUNC_ATTR_NONNULL_ARG(1, 2) FUNC_ATTR_WARN_UNUSED_RESULT |
1939 | { |
1940 | char_u *arg_end = NULL; |
1941 | int len; |
1942 | int opt_flags; |
1943 | char_u *tofree = NULL; |
1944 | |
1945 | /* |
1946 | * ":let $VAR = expr": Set environment variable. |
1947 | */ |
1948 | if (*arg == '$') { |
1949 | if (is_const) { |
1950 | EMSG(_("E996: Cannot lock an environment variable" )); |
1951 | return NULL; |
1952 | } |
1953 | // Find the end of the name. |
1954 | arg++; |
1955 | char *name = (char *)arg; |
1956 | len = get_env_len((const char_u **)&arg); |
1957 | if (len == 0) { |
1958 | EMSG2(_(e_invarg2), name - 1); |
1959 | } else { |
1960 | if (op != NULL && vim_strchr((char_u *)"+-*/%" , *op) != NULL) { |
1961 | EMSG2(_(e_letwrong), op); |
1962 | } else if (endchars != NULL |
1963 | && vim_strchr(endchars, *skipwhite(arg)) == NULL) { |
1964 | EMSG(_(e_letunexp)); |
1965 | } else if (!check_secure()) { |
1966 | const char c1 = name[len]; |
1967 | name[len] = NUL; |
1968 | const char *p = tv_get_string_chk(tv); |
1969 | if (p != NULL && op != NULL && *op == '.') { |
1970 | char *s = vim_getenv(name); |
1971 | |
1972 | if (s != NULL) { |
1973 | tofree = concat_str((const char_u *)s, (const char_u *)p); |
1974 | p = (const char *)tofree; |
1975 | xfree(s); |
1976 | } |
1977 | } |
1978 | if (p != NULL) { |
1979 | os_setenv(name, p, 1); |
1980 | if (STRICMP(name, "HOME" ) == 0) { |
1981 | init_homedir(); |
1982 | } else if (didset_vim && STRICMP(name, "VIM" ) == 0) { |
1983 | didset_vim = false; |
1984 | } else if (didset_vimruntime |
1985 | && STRICMP(name, "VIMRUNTIME" ) == 0) { |
1986 | didset_vimruntime = false; |
1987 | } |
1988 | arg_end = arg; |
1989 | } |
1990 | name[len] = c1; |
1991 | xfree(tofree); |
1992 | } |
1993 | } |
1994 | // ":let &option = expr": Set option value. |
1995 | // ":let &l:option = expr": Set local option value. |
1996 | // ":let &g:option = expr": Set global option value. |
1997 | } else if (*arg == '&') { |
1998 | if (is_const) { |
1999 | EMSG(_("E996: Cannot lock an option" )); |
2000 | return NULL; |
2001 | } |
2002 | // Find the end of the name. |
2003 | char *const p = (char *)find_option_end((const char **)&arg, &opt_flags); |
2004 | if (p == NULL |
2005 | || (endchars != NULL |
2006 | && vim_strchr(endchars, *skipwhite((const char_u *)p)) == NULL)) { |
2007 | EMSG(_(e_letunexp)); |
2008 | } else { |
2009 | int opt_type; |
2010 | long numval; |
2011 | char *stringval = NULL; |
2012 | |
2013 | const char c1 = *p; |
2014 | *p = NUL; |
2015 | |
2016 | varnumber_T n = tv_get_number(tv); |
2017 | const char *s = tv_get_string_chk(tv); // != NULL if number or string. |
2018 | if (s != NULL && op != NULL && *op != '=') { |
2019 | opt_type = get_option_value(arg, &numval, (char_u **)&stringval, |
2020 | opt_flags); |
2021 | if ((opt_type == 1 && *op == '.') |
2022 | || (opt_type == 0 && *op != '.')) { |
2023 | EMSG2(_(e_letwrong), op); |
2024 | s = NULL; // don't set the value |
2025 | } else { |
2026 | if (opt_type == 1) { // number |
2027 | switch (*op) { |
2028 | case '+': n = numval + n; break; |
2029 | case '-': n = numval - n; break; |
2030 | case '*': n = numval * n; break; |
2031 | case '/': n = num_divide(numval, n); break; |
2032 | case '%': n = num_modulus(numval, n); break; |
2033 | } |
2034 | } else if (opt_type == 0 && stringval != NULL) { // string |
2035 | char *const oldstringval = stringval; |
2036 | stringval = (char *)concat_str((const char_u *)stringval, |
2037 | (const char_u *)s); |
2038 | xfree(oldstringval); |
2039 | s = stringval; |
2040 | } |
2041 | } |
2042 | } |
2043 | if (s != NULL) { |
2044 | set_option_value((const char *)arg, n, s, opt_flags); |
2045 | arg_end = (char_u *)p; |
2046 | } |
2047 | *p = c1; |
2048 | xfree(stringval); |
2049 | } |
2050 | // ":let @r = expr": Set register contents. |
2051 | } else if (*arg == '@') { |
2052 | if (is_const) { |
2053 | EMSG(_("E996: Cannot lock a register" )); |
2054 | return NULL; |
2055 | } |
2056 | arg++; |
2057 | if (op != NULL && vim_strchr((char_u *)"+-*/%" , *op) != NULL) { |
2058 | emsgf(_(e_letwrong), op); |
2059 | } else if (endchars != NULL |
2060 | && vim_strchr(endchars, *skipwhite(arg + 1)) == NULL) { |
2061 | EMSG(_(e_letunexp)); |
2062 | } else { |
2063 | char_u *s; |
2064 | |
2065 | char_u *ptofree = NULL; |
2066 | const char *p = tv_get_string_chk(tv); |
2067 | if (p != NULL && op != NULL && *op == '.') { |
2068 | s = get_reg_contents(*arg == '@' ? '"' : *arg, kGRegExprSrc); |
2069 | if (s != NULL) { |
2070 | ptofree = concat_str(s, (const char_u *)p); |
2071 | p = (const char *)ptofree; |
2072 | xfree(s); |
2073 | } |
2074 | } |
2075 | if (p != NULL) { |
2076 | write_reg_contents(*arg == '@' ? '"' : *arg, |
2077 | (const char_u *)p, STRLEN(p), false); |
2078 | arg_end = arg + 1; |
2079 | } |
2080 | xfree(ptofree); |
2081 | } |
2082 | } |
2083 | /* |
2084 | * ":let var = expr": Set internal variable. |
2085 | * ":let {expr} = expr": Idem, name made with curly braces |
2086 | */ |
2087 | else if (eval_isnamec1(*arg) || *arg == '{') { |
2088 | lval_T lv; |
2089 | |
2090 | char_u *const p = get_lval(arg, tv, &lv, false, false, 0, FNE_CHECK_START); |
2091 | if (p != NULL && lv.ll_name != NULL) { |
2092 | if (endchars != NULL && vim_strchr(endchars, *skipwhite(p)) == NULL) { |
2093 | EMSG(_(e_letunexp)); |
2094 | } else { |
2095 | set_var_lval(&lv, p, tv, copy, is_const, op); |
2096 | arg_end = p; |
2097 | } |
2098 | } |
2099 | clear_lval(&lv); |
2100 | } else |
2101 | EMSG2(_(e_invarg2), arg); |
2102 | |
2103 | return arg_end; |
2104 | } |
2105 | |
2106 | // TODO(ZyX-I): move to eval/executor |
2107 | |
2108 | /// Get an lvalue |
2109 | /// |
2110 | /// Lvalue may be |
2111 | /// - variable: "name", "na{me}" |
2112 | /// - dictionary item: "dict.key", "dict['key']" |
2113 | /// - list item: "list[expr]" |
2114 | /// - list slice: "list[expr:expr]" |
2115 | /// |
2116 | /// Indexing only works if trying to use it with an existing List or Dictionary. |
2117 | /// |
2118 | /// @param[in] name Name to parse. |
2119 | /// @param rettv Pointer to the value to be assigned or NULL. |
2120 | /// @param[out] lp Lvalue definition. When evaluation errors occur `->ll_name` |
2121 | /// is NULL. |
2122 | /// @param[in] unlet True if using `:unlet`. This results in slightly |
2123 | /// different behaviour when something is wrong; must end in |
2124 | /// space or cmd separator. |
2125 | /// @param[in] skip True when skipping. |
2126 | /// @param[in] flags @see GetLvalFlags. |
2127 | /// @param[in] fne_flags Flags for find_name_end(). |
2128 | /// |
2129 | /// @return A pointer to just after the name, including indexes. Returns NULL |
2130 | /// for a parsing error, but it is still needed to free items in lp. |
2131 | static char_u *get_lval(char_u *const name, typval_T *const rettv, |
2132 | lval_T *const lp, const bool unlet, const bool skip, |
2133 | const int flags, const int fne_flags) |
2134 | FUNC_ATTR_NONNULL_ARG(1, 3) |
2135 | { |
2136 | dictitem_T *v; |
2137 | typval_T var1; |
2138 | typval_T var2; |
2139 | int empty1 = FALSE; |
2140 | listitem_T *ni; |
2141 | hashtab_T *ht; |
2142 | int quiet = flags & GLV_QUIET; |
2143 | |
2144 | /* Clear everything in "lp". */ |
2145 | memset(lp, 0, sizeof(lval_T)); |
2146 | |
2147 | if (skip) { |
2148 | // When skipping just find the end of the name. |
2149 | lp->ll_name = (const char *)name; |
2150 | return (char_u *)find_name_end((const char_u *)name, NULL, NULL, |
2151 | FNE_INCL_BR | fne_flags); |
2152 | } |
2153 | |
2154 | // Find the end of the name. |
2155 | char_u *expr_start; |
2156 | char_u *expr_end; |
2157 | char_u *p = (char_u *)find_name_end(name, |
2158 | (const char_u **)&expr_start, |
2159 | (const char_u **)&expr_end, |
2160 | fne_flags); |
2161 | if (expr_start != NULL) { |
2162 | /* Don't expand the name when we already know there is an error. */ |
2163 | if (unlet && !ascii_iswhite(*p) && !ends_excmd(*p) |
2164 | && *p != '[' && *p != '.') { |
2165 | EMSG(_(e_trailing)); |
2166 | return NULL; |
2167 | } |
2168 | |
2169 | lp->ll_exp_name = (char *)make_expanded_name(name, expr_start, expr_end, |
2170 | (char_u *)p); |
2171 | lp->ll_name = lp->ll_exp_name; |
2172 | if (lp->ll_exp_name == NULL) { |
2173 | /* Report an invalid expression in braces, unless the |
2174 | * expression evaluation has been cancelled due to an |
2175 | * aborting error, an interrupt, or an exception. */ |
2176 | if (!aborting() && !quiet) { |
2177 | emsg_severe = TRUE; |
2178 | EMSG2(_(e_invarg2), name); |
2179 | return NULL; |
2180 | } |
2181 | lp->ll_name_len = 0; |
2182 | } else { |
2183 | lp->ll_name_len = strlen(lp->ll_name); |
2184 | } |
2185 | } else { |
2186 | lp->ll_name = (const char *)name; |
2187 | lp->ll_name_len = (size_t)((const char *)p - lp->ll_name); |
2188 | } |
2189 | |
2190 | // Without [idx] or .key we are done. |
2191 | if ((*p != '[' && *p != '.') || lp->ll_name == NULL) { |
2192 | return p; |
2193 | } |
2194 | |
2195 | // Only pass &ht when we would write to the variable, it prevents autoload |
2196 | // as well. |
2197 | v = find_var(lp->ll_name, lp->ll_name_len, |
2198 | (flags & GLV_READ_ONLY) ? NULL : &ht, |
2199 | flags & GLV_NO_AUTOLOAD); |
2200 | if (v == NULL && !quiet) { |
2201 | emsgf(_("E121: Undefined variable: %.*s" ), |
2202 | (int)lp->ll_name_len, lp->ll_name); |
2203 | } |
2204 | if (v == NULL) { |
2205 | return NULL; |
2206 | } |
2207 | |
2208 | /* |
2209 | * Loop until no more [idx] or .key is following. |
2210 | */ |
2211 | lp->ll_tv = &v->di_tv; |
2212 | var1.v_type = VAR_UNKNOWN; |
2213 | var2.v_type = VAR_UNKNOWN; |
2214 | while (*p == '[' || (*p == '.' && lp->ll_tv->v_type == VAR_DICT)) { |
2215 | if (!(lp->ll_tv->v_type == VAR_LIST && lp->ll_tv->vval.v_list != NULL) |
2216 | && !(lp->ll_tv->v_type == VAR_DICT |
2217 | && lp->ll_tv->vval.v_dict != NULL)) { |
2218 | if (!quiet) |
2219 | EMSG(_("E689: Can only index a List or Dictionary" )); |
2220 | return NULL; |
2221 | } |
2222 | if (lp->ll_range) { |
2223 | if (!quiet) |
2224 | EMSG(_("E708: [:] must come last" )); |
2225 | return NULL; |
2226 | } |
2227 | |
2228 | int len = -1; |
2229 | char_u *key = NULL; |
2230 | if (*p == '.') { |
2231 | key = p + 1; |
2232 | for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; len++) { |
2233 | } |
2234 | if (len == 0) { |
2235 | if (!quiet) { |
2236 | EMSG(_("E713: Cannot use empty key after ." )); |
2237 | } |
2238 | return NULL; |
2239 | } |
2240 | p = key + len; |
2241 | } else { |
2242 | /* Get the index [expr] or the first index [expr: ]. */ |
2243 | p = skipwhite(p + 1); |
2244 | if (*p == ':') { |
2245 | empty1 = true; |
2246 | } else { |
2247 | empty1 = false; |
2248 | if (eval1(&p, &var1, true) == FAIL) { // Recursive! |
2249 | return NULL; |
2250 | } |
2251 | if (!tv_check_str(&var1)) { |
2252 | // Not a number or string. |
2253 | tv_clear(&var1); |
2254 | return NULL; |
2255 | } |
2256 | } |
2257 | |
2258 | /* Optionally get the second index [ :expr]. */ |
2259 | if (*p == ':') { |
2260 | if (lp->ll_tv->v_type == VAR_DICT) { |
2261 | if (!quiet) { |
2262 | EMSG(_(e_dictrange)); |
2263 | } |
2264 | tv_clear(&var1); |
2265 | return NULL; |
2266 | } |
2267 | if (rettv != NULL && (rettv->v_type != VAR_LIST |
2268 | || rettv->vval.v_list == NULL)) { |
2269 | if (!quiet) { |
2270 | EMSG(_("E709: [:] requires a List value" )); |
2271 | } |
2272 | tv_clear(&var1); |
2273 | return NULL; |
2274 | } |
2275 | p = skipwhite(p + 1); |
2276 | if (*p == ']') { |
2277 | lp->ll_empty2 = true; |
2278 | } else { |
2279 | lp->ll_empty2 = false; |
2280 | if (eval1(&p, &var2, true) == FAIL) { // Recursive! |
2281 | tv_clear(&var1); |
2282 | return NULL; |
2283 | } |
2284 | if (!tv_check_str(&var2)) { |
2285 | // Not a number or string. |
2286 | tv_clear(&var1); |
2287 | tv_clear(&var2); |
2288 | return NULL; |
2289 | } |
2290 | } |
2291 | lp->ll_range = TRUE; |
2292 | } else |
2293 | lp->ll_range = FALSE; |
2294 | |
2295 | if (*p != ']') { |
2296 | if (!quiet) { |
2297 | EMSG(_(e_missbrac)); |
2298 | } |
2299 | tv_clear(&var1); |
2300 | tv_clear(&var2); |
2301 | return NULL; |
2302 | } |
2303 | |
2304 | /* Skip to past ']'. */ |
2305 | ++p; |
2306 | } |
2307 | |
2308 | if (lp->ll_tv->v_type == VAR_DICT) { |
2309 | if (len == -1) { |
2310 | // "[key]": get key from "var1" |
2311 | key = (char_u *)tv_get_string(&var1); // is number or string |
2312 | } |
2313 | lp->ll_list = NULL; |
2314 | lp->ll_dict = lp->ll_tv->vval.v_dict; |
2315 | lp->ll_di = tv_dict_find(lp->ll_dict, (const char *)key, len); |
2316 | |
2317 | /* When assigning to a scope dictionary check that a function and |
2318 | * variable name is valid (only variable name unless it is l: or |
2319 | * g: dictionary). Disallow overwriting a builtin function. */ |
2320 | if (rettv != NULL && lp->ll_dict->dv_scope != 0) { |
2321 | int prevval; |
2322 | int wrong; |
2323 | |
2324 | if (len != -1) { |
2325 | prevval = key[len]; |
2326 | key[len] = NUL; |
2327 | } else { |
2328 | prevval = 0; // Avoid compiler warning. |
2329 | } |
2330 | wrong = ((lp->ll_dict->dv_scope == VAR_DEF_SCOPE |
2331 | && tv_is_func(*rettv) |
2332 | && !var_check_func_name((const char *)key, lp->ll_di == NULL)) |
2333 | || !valid_varname((const char *)key)); |
2334 | if (len != -1) { |
2335 | key[len] = prevval; |
2336 | } |
2337 | if (wrong) { |
2338 | return NULL; |
2339 | } |
2340 | } |
2341 | |
2342 | if (lp->ll_di == NULL) { |
2343 | // Can't add "v:" or "a:" variable. |
2344 | if (lp->ll_dict == &vimvardict |
2345 | || &lp->ll_dict->dv_hashtab == get_funccal_args_ht()) { |
2346 | EMSG2(_(e_illvar), name); |
2347 | tv_clear(&var1); |
2348 | return NULL; |
2349 | } |
2350 | |
2351 | // Key does not exist in dict: may need to add it. |
2352 | if (*p == '[' || *p == '.' || unlet) { |
2353 | if (!quiet) { |
2354 | emsgf(_(e_dictkey), key); |
2355 | } |
2356 | tv_clear(&var1); |
2357 | return NULL; |
2358 | } |
2359 | if (len == -1) { |
2360 | lp->ll_newkey = vim_strsave(key); |
2361 | } else { |
2362 | lp->ll_newkey = vim_strnsave(key, len); |
2363 | } |
2364 | tv_clear(&var1); |
2365 | break; |
2366 | // existing variable, need to check if it can be changed |
2367 | } else if (!(flags & GLV_READ_ONLY) && var_check_ro(lp->ll_di->di_flags, |
2368 | (const char *)name, |
2369 | (size_t)(p - name))) { |
2370 | tv_clear(&var1); |
2371 | return NULL; |
2372 | } |
2373 | |
2374 | tv_clear(&var1); |
2375 | lp->ll_tv = &lp->ll_di->di_tv; |
2376 | } else { |
2377 | // Get the number and item for the only or first index of the List. |
2378 | if (empty1) { |
2379 | lp->ll_n1 = 0; |
2380 | } else { |
2381 | // Is number or string. |
2382 | lp->ll_n1 = (long)tv_get_number(&var1); |
2383 | } |
2384 | tv_clear(&var1); |
2385 | |
2386 | lp->ll_dict = NULL; |
2387 | lp->ll_list = lp->ll_tv->vval.v_list; |
2388 | lp->ll_li = tv_list_find(lp->ll_list, lp->ll_n1); |
2389 | if (lp->ll_li == NULL) { |
2390 | if (lp->ll_n1 < 0) { |
2391 | lp->ll_n1 = 0; |
2392 | lp->ll_li = tv_list_find(lp->ll_list, lp->ll_n1); |
2393 | } |
2394 | } |
2395 | if (lp->ll_li == NULL) { |
2396 | tv_clear(&var2); |
2397 | if (!quiet) { |
2398 | EMSGN(_(e_listidx), lp->ll_n1); |
2399 | } |
2400 | return NULL; |
2401 | } |
2402 | |
2403 | /* |
2404 | * May need to find the item or absolute index for the second |
2405 | * index of a range. |
2406 | * When no index given: "lp->ll_empty2" is TRUE. |
2407 | * Otherwise "lp->ll_n2" is set to the second index. |
2408 | */ |
2409 | if (lp->ll_range && !lp->ll_empty2) { |
2410 | lp->ll_n2 = (long)tv_get_number(&var2); // Is number or string. |
2411 | tv_clear(&var2); |
2412 | if (lp->ll_n2 < 0) { |
2413 | ni = tv_list_find(lp->ll_list, lp->ll_n2); |
2414 | if (ni == NULL) { |
2415 | if (!quiet) |
2416 | EMSGN(_(e_listidx), lp->ll_n2); |
2417 | return NULL; |
2418 | } |
2419 | lp->ll_n2 = tv_list_idx_of_item(lp->ll_list, ni); |
2420 | } |
2421 | |
2422 | // Check that lp->ll_n2 isn't before lp->ll_n1. |
2423 | if (lp->ll_n1 < 0) { |
2424 | lp->ll_n1 = tv_list_idx_of_item(lp->ll_list, lp->ll_li); |
2425 | } |
2426 | if (lp->ll_n2 < lp->ll_n1) { |
2427 | if (!quiet) { |
2428 | EMSGN(_(e_listidx), lp->ll_n2); |
2429 | } |
2430 | return NULL; |
2431 | } |
2432 | } |
2433 | |
2434 | lp->ll_tv = TV_LIST_ITEM_TV(lp->ll_li); |
2435 | } |
2436 | } |
2437 | |
2438 | tv_clear(&var1); |
2439 | return p; |
2440 | } |
2441 | |
2442 | // TODO(ZyX-I): move to eval/executor |
2443 | |
2444 | /* |
2445 | * Clear lval "lp" that was filled by get_lval(). |
2446 | */ |
2447 | static void clear_lval(lval_T *lp) |
2448 | { |
2449 | xfree(lp->ll_exp_name); |
2450 | xfree(lp->ll_newkey); |
2451 | } |
2452 | |
2453 | // TODO(ZyX-I): move to eval/executor |
2454 | |
2455 | /* |
2456 | * Set a variable that was parsed by get_lval() to "rettv". |
2457 | * "endp" points to just after the parsed name. |
2458 | * "op" is NULL, "+" for "+=", "-" for "-=", "*" for "*=", "/" for "/=", |
2459 | * "%" for "%=", "." for ".=" or "=" for "=". |
2460 | */ |
2461 | static void set_var_lval(lval_T *lp, char_u *endp, typval_T *rettv, |
2462 | int copy, const bool is_const, const char_u *op) |
2463 | { |
2464 | int cc; |
2465 | listitem_T *ri; |
2466 | dictitem_T *di; |
2467 | |
2468 | if (lp->ll_tv == NULL) { |
2469 | cc = *endp; |
2470 | *endp = NUL; |
2471 | if (op != NULL && *op != '=') { |
2472 | typval_T tv; |
2473 | |
2474 | if (is_const) { |
2475 | EMSG(_(e_cannot_mod)); |
2476 | *endp = cc; |
2477 | return; |
2478 | } |
2479 | |
2480 | // handle +=, -=, *=, /=, %= and .= |
2481 | di = NULL; |
2482 | if (get_var_tv((const char *)lp->ll_name, (int)STRLEN(lp->ll_name), |
2483 | &tv, &di, true, false) == OK) { |
2484 | if ((di == NULL |
2485 | || (!var_check_ro(di->di_flags, (const char *)lp->ll_name, |
2486 | TV_CSTRING) |
2487 | && !tv_check_lock(di->di_tv.v_lock, (const char *)lp->ll_name, |
2488 | TV_CSTRING))) |
2489 | && eexe_mod_op(&tv, rettv, (const char *)op) == OK) { |
2490 | set_var(lp->ll_name, lp->ll_name_len, &tv, false); |
2491 | } |
2492 | tv_clear(&tv); |
2493 | } |
2494 | } else { |
2495 | set_var_const(lp->ll_name, lp->ll_name_len, rettv, copy, is_const); |
2496 | } |
2497 | *endp = cc; |
2498 | } else if (tv_check_lock(lp->ll_newkey == NULL |
2499 | ? lp->ll_tv->v_lock |
2500 | : lp->ll_tv->vval.v_dict->dv_lock, |
2501 | (const char *)lp->ll_name, TV_CSTRING)) { |
2502 | } else if (lp->ll_range) { |
2503 | listitem_T *ll_li = lp->ll_li; |
2504 | int ll_n1 = lp->ll_n1; |
2505 | |
2506 | if (is_const) { |
2507 | EMSG(_("E996: Cannot lock a range" )); |
2508 | return; |
2509 | } |
2510 | |
2511 | // Check whether any of the list items is locked |
2512 | for (ri = tv_list_first(rettv->vval.v_list); |
2513 | ri != NULL && ll_li != NULL; ) { |
2514 | if (tv_check_lock(TV_LIST_ITEM_TV(ll_li)->v_lock, |
2515 | (const char *)lp->ll_name, |
2516 | TV_CSTRING)) { |
2517 | return; |
2518 | } |
2519 | ri = TV_LIST_ITEM_NEXT(rettv->vval.v_list, ri); |
2520 | if (ri == NULL || (!lp->ll_empty2 && lp->ll_n2 == ll_n1)) { |
2521 | break; |
2522 | } |
2523 | ll_li = TV_LIST_ITEM_NEXT(lp->ll_list, ll_li); |
2524 | ll_n1++; |
2525 | } |
2526 | |
2527 | /* |
2528 | * Assign the List values to the list items. |
2529 | */ |
2530 | for (ri = tv_list_first(rettv->vval.v_list); ri != NULL; ) { |
2531 | if (op != NULL && *op != '=') { |
2532 | eexe_mod_op(TV_LIST_ITEM_TV(lp->ll_li), TV_LIST_ITEM_TV(ri), |
2533 | (const char *)op); |
2534 | } else { |
2535 | tv_clear(TV_LIST_ITEM_TV(lp->ll_li)); |
2536 | tv_copy(TV_LIST_ITEM_TV(ri), TV_LIST_ITEM_TV(lp->ll_li)); |
2537 | } |
2538 | ri = TV_LIST_ITEM_NEXT(rettv->vval.v_list, ri); |
2539 | if (ri == NULL || (!lp->ll_empty2 && lp->ll_n2 == lp->ll_n1)) { |
2540 | break; |
2541 | } |
2542 | assert(lp->ll_li != NULL); |
2543 | if (TV_LIST_ITEM_NEXT(lp->ll_list, lp->ll_li) == NULL) { |
2544 | // Need to add an empty item. |
2545 | tv_list_append_number(lp->ll_list, 0); |
2546 | // ll_li may have become invalid after append, don’t use it. |
2547 | lp->ll_li = tv_list_last(lp->ll_list); // Valid again. |
2548 | } else { |
2549 | lp->ll_li = TV_LIST_ITEM_NEXT(lp->ll_list, lp->ll_li); |
2550 | } |
2551 | lp->ll_n1++; |
2552 | } |
2553 | if (ri != NULL) { |
2554 | EMSG(_("E710: List value has more items than target" )); |
2555 | } else if (lp->ll_empty2 |
2556 | ? (lp->ll_li != NULL |
2557 | && TV_LIST_ITEM_NEXT(lp->ll_list, lp->ll_li) != NULL) |
2558 | : lp->ll_n1 != lp->ll_n2) { |
2559 | EMSG(_("E711: List value has not enough items" )); |
2560 | } |
2561 | } else { |
2562 | typval_T oldtv = TV_INITIAL_VALUE; |
2563 | dict_T *dict = lp->ll_dict; |
2564 | bool watched = tv_dict_is_watched(dict); |
2565 | |
2566 | if (is_const) { |
2567 | EMSG(_("E996: Cannot lock a list or dict" )); |
2568 | return; |
2569 | } |
2570 | |
2571 | // Assign to a List or Dictionary item. |
2572 | if (lp->ll_newkey != NULL) { |
2573 | if (op != NULL && *op != '=') { |
2574 | EMSG2(_(e_letwrong), op); |
2575 | return; |
2576 | } |
2577 | |
2578 | // Need to add an item to the Dictionary. |
2579 | di = tv_dict_item_alloc((const char *)lp->ll_newkey); |
2580 | if (tv_dict_add(lp->ll_tv->vval.v_dict, di) == FAIL) { |
2581 | xfree(di); |
2582 | return; |
2583 | } |
2584 | lp->ll_tv = &di->di_tv; |
2585 | } else { |
2586 | if (watched) { |
2587 | tv_copy(lp->ll_tv, &oldtv); |
2588 | } |
2589 | |
2590 | if (op != NULL && *op != '=') { |
2591 | eexe_mod_op(lp->ll_tv, rettv, (const char *)op); |
2592 | goto notify; |
2593 | } else { |
2594 | tv_clear(lp->ll_tv); |
2595 | } |
2596 | } |
2597 | |
2598 | // Assign the value to the variable or list item. |
2599 | if (copy) { |
2600 | tv_copy(rettv, lp->ll_tv); |
2601 | } else { |
2602 | *lp->ll_tv = *rettv; |
2603 | lp->ll_tv->v_lock = 0; |
2604 | tv_init(rettv); |
2605 | } |
2606 | |
2607 | notify: |
2608 | if (watched) { |
2609 | if (oldtv.v_type == VAR_UNKNOWN) { |
2610 | assert(lp->ll_newkey != NULL); |
2611 | tv_dict_watcher_notify(dict, (char *)lp->ll_newkey, lp->ll_tv, NULL); |
2612 | } else { |
2613 | dictitem_T *di_ = lp->ll_di; |
2614 | assert(di_->di_key != NULL); |
2615 | tv_dict_watcher_notify(dict, (char *)di_->di_key, lp->ll_tv, &oldtv); |
2616 | tv_clear(&oldtv); |
2617 | } |
2618 | } |
2619 | } |
2620 | } |
2621 | |
2622 | // TODO(ZyX-I): move to eval/ex_cmds |
2623 | |
2624 | /* |
2625 | * Evaluate the expression used in a ":for var in expr" command. |
2626 | * "arg" points to "var". |
2627 | * Set "*errp" to TRUE for an error, FALSE otherwise; |
2628 | * Return a pointer that holds the info. Null when there is an error. |
2629 | */ |
2630 | void *eval_for_line(const char_u *arg, bool *errp, char_u **nextcmdp, int skip) |
2631 | { |
2632 | forinfo_T *fi = xcalloc(1, sizeof(forinfo_T)); |
2633 | const char_u *expr; |
2634 | typval_T tv; |
2635 | list_T *l; |
2636 | |
2637 | *errp = true; // Default: there is an error. |
2638 | |
2639 | expr = skip_var_list(arg, &fi->fi_varcount, &fi->fi_semicolon); |
2640 | if (expr == NULL) |
2641 | return fi; |
2642 | |
2643 | expr = skipwhite(expr); |
2644 | if (expr[0] != 'i' || expr[1] != 'n' || !ascii_iswhite(expr[2])) { |
2645 | EMSG(_("E690: Missing \"in\" after :for" )); |
2646 | return fi; |
2647 | } |
2648 | |
2649 | if (skip) |
2650 | ++emsg_skip; |
2651 | if (eval0(skipwhite(expr + 2), &tv, nextcmdp, !skip) == OK) { |
2652 | *errp = false; |
2653 | if (!skip) { |
2654 | l = tv.vval.v_list; |
2655 | if (tv.v_type != VAR_LIST) { |
2656 | EMSG(_(e_listreq)); |
2657 | tv_clear(&tv); |
2658 | } else if (l == NULL) { |
2659 | // a null list is like an empty list: do nothing |
2660 | tv_clear(&tv); |
2661 | } else { |
2662 | /* No need to increment the refcount, it's already set for the |
2663 | * list being used in "tv". */ |
2664 | fi->fi_list = l; |
2665 | tv_list_watch_add(l, &fi->fi_lw); |
2666 | fi->fi_lw.lw_item = tv_list_first(l); |
2667 | } |
2668 | } |
2669 | } |
2670 | if (skip) |
2671 | --emsg_skip; |
2672 | |
2673 | return fi; |
2674 | } |
2675 | |
2676 | // TODO(ZyX-I): move to eval/ex_cmds |
2677 | |
2678 | /* |
2679 | * Use the first item in a ":for" list. Advance to the next. |
2680 | * Assign the values to the variable (list). "arg" points to the first one. |
2681 | * Return TRUE when a valid item was found, FALSE when at end of list or |
2682 | * something wrong. |
2683 | */ |
2684 | bool next_for_item(void *fi_void, char_u *arg) |
2685 | { |
2686 | forinfo_T *fi = (forinfo_T *)fi_void; |
2687 | |
2688 | listitem_T *item = fi->fi_lw.lw_item; |
2689 | if (item == NULL) { |
2690 | return false; |
2691 | } else { |
2692 | fi->fi_lw.lw_item = TV_LIST_ITEM_NEXT(fi->fi_list, item); |
2693 | return (ex_let_vars(arg, TV_LIST_ITEM_TV(item), true, |
2694 | fi->fi_semicolon, fi->fi_varcount, false, NULL) == OK); |
2695 | } |
2696 | } |
2697 | |
2698 | // TODO(ZyX-I): move to eval/ex_cmds |
2699 | |
2700 | /* |
2701 | * Free the structure used to store info used by ":for". |
2702 | */ |
2703 | void free_for_info(void *fi_void) |
2704 | { |
2705 | forinfo_T *fi = (forinfo_T *)fi_void; |
2706 | |
2707 | if (fi != NULL && fi->fi_list != NULL) { |
2708 | tv_list_watch_remove(fi->fi_list, &fi->fi_lw); |
2709 | tv_list_unref(fi->fi_list); |
2710 | } |
2711 | xfree(fi); |
2712 | } |
2713 | |
2714 | |
2715 | void set_context_for_expression(expand_T *xp, char_u *arg, cmdidx_T cmdidx) |
2716 | { |
2717 | int got_eq = FALSE; |
2718 | int c; |
2719 | char_u *p; |
2720 | |
2721 | if (cmdidx == CMD_let) { |
2722 | xp->xp_context = EXPAND_USER_VARS; |
2723 | if (vim_strpbrk(arg, (char_u *)"\"'+-*/%.=!?~|&$([<>,#" ) == NULL) { |
2724 | /* ":let var1 var2 ...": find last space. */ |
2725 | for (p = arg + STRLEN(arg); p >= arg; ) { |
2726 | xp->xp_pattern = p; |
2727 | MB_PTR_BACK(arg, p); |
2728 | if (ascii_iswhite(*p)) { |
2729 | break; |
2730 | } |
2731 | } |
2732 | return; |
2733 | } |
2734 | } else |
2735 | xp->xp_context = cmdidx == CMD_call ? EXPAND_FUNCTIONS |
2736 | : EXPAND_EXPRESSION; |
2737 | while ((xp->xp_pattern = vim_strpbrk(arg, |
2738 | (char_u *)"\"'+-*/%.=!?~|&$([<>,#" )) != NULL) { |
2739 | c = *xp->xp_pattern; |
2740 | if (c == '&') { |
2741 | c = xp->xp_pattern[1]; |
2742 | if (c == '&') { |
2743 | ++xp->xp_pattern; |
2744 | xp->xp_context = cmdidx != CMD_let || got_eq |
2745 | ? EXPAND_EXPRESSION : EXPAND_NOTHING; |
2746 | } else if (c != ' ') { |
2747 | xp->xp_context = EXPAND_SETTINGS; |
2748 | if ((c == 'l' || c == 'g') && xp->xp_pattern[2] == ':') |
2749 | xp->xp_pattern += 2; |
2750 | |
2751 | } |
2752 | } else if (c == '$') { |
2753 | /* environment variable */ |
2754 | xp->xp_context = EXPAND_ENV_VARS; |
2755 | } else if (c == '=') { |
2756 | got_eq = TRUE; |
2757 | xp->xp_context = EXPAND_EXPRESSION; |
2758 | } else if (c == '#' |
2759 | && xp->xp_context == EXPAND_EXPRESSION) { |
2760 | // Autoload function/variable contains '#' |
2761 | break; |
2762 | } else if ((c == '<' || c == '#') |
2763 | && xp->xp_context == EXPAND_FUNCTIONS |
2764 | && vim_strchr(xp->xp_pattern, '(') == NULL) { |
2765 | /* Function name can start with "<SNR>" and contain '#'. */ |
2766 | break; |
2767 | } else if (cmdidx != CMD_let || got_eq) { |
2768 | if (c == '"') { /* string */ |
2769 | while ((c = *++xp->xp_pattern) != NUL && c != '"') |
2770 | if (c == '\\' && xp->xp_pattern[1] != NUL) |
2771 | ++xp->xp_pattern; |
2772 | xp->xp_context = EXPAND_NOTHING; |
2773 | } else if (c == '\'') { /* literal string */ |
2774 | /* Trick: '' is like stopping and starting a literal string. */ |
2775 | while ((c = *++xp->xp_pattern) != NUL && c != '\'') |
2776 | /* skip */; |
2777 | xp->xp_context = EXPAND_NOTHING; |
2778 | } else if (c == '|') { |
2779 | if (xp->xp_pattern[1] == '|') { |
2780 | ++xp->xp_pattern; |
2781 | xp->xp_context = EXPAND_EXPRESSION; |
2782 | } else |
2783 | xp->xp_context = EXPAND_COMMANDS; |
2784 | } else |
2785 | xp->xp_context = EXPAND_EXPRESSION; |
2786 | } else |
2787 | /* Doesn't look like something valid, expand as an expression |
2788 | * anyway. */ |
2789 | xp->xp_context = EXPAND_EXPRESSION; |
2790 | arg = xp->xp_pattern; |
2791 | if (*arg != NUL) |
2792 | while ((c = *++arg) != NUL && (c == ' ' || c == '\t')) |
2793 | /* skip */; |
2794 | } |
2795 | xp->xp_pattern = arg; |
2796 | } |
2797 | |
2798 | // TODO(ZyX-I): move to eval/ex_cmds |
2799 | |
2800 | /* |
2801 | * ":1,25call func(arg1, arg2)" function call. |
2802 | */ |
2803 | void ex_call(exarg_T *eap) |
2804 | { |
2805 | char_u *arg = eap->arg; |
2806 | char_u *startarg; |
2807 | char_u *name; |
2808 | char_u *tofree; |
2809 | int len; |
2810 | typval_T rettv; |
2811 | linenr_T lnum; |
2812 | int doesrange; |
2813 | bool failed = false; |
2814 | funcdict_T fudi; |
2815 | partial_T *partial = NULL; |
2816 | |
2817 | if (eap->skip) { |
2818 | // trans_function_name() doesn't work well when skipping, use eval0() |
2819 | // instead to skip to any following command, e.g. for: |
2820 | // :if 0 | call dict.foo().bar() | endif. |
2821 | emsg_skip++; |
2822 | if (eval0(eap->arg, &rettv, &eap->nextcmd, false) != FAIL) { |
2823 | tv_clear(&rettv); |
2824 | } |
2825 | emsg_skip--; |
2826 | return; |
2827 | } |
2828 | |
2829 | tofree = trans_function_name(&arg, false, TFN_INT, &fudi, &partial); |
2830 | if (fudi.fd_newkey != NULL) { |
2831 | // Still need to give an error message for missing key. |
2832 | EMSG2(_(e_dictkey), fudi.fd_newkey); |
2833 | xfree(fudi.fd_newkey); |
2834 | } |
2835 | if (tofree == NULL) { |
2836 | return; |
2837 | } |
2838 | |
2839 | // Increase refcount on dictionary, it could get deleted when evaluating |
2840 | // the arguments. |
2841 | if (fudi.fd_dict != NULL) { |
2842 | fudi.fd_dict->dv_refcount++; |
2843 | } |
2844 | |
2845 | // If it is the name of a variable of type VAR_FUNC or VAR_PARTIAL use its |
2846 | // contents. For VAR_PARTIAL get its partial, unless we already have one |
2847 | // from trans_function_name(). |
2848 | len = (int)STRLEN(tofree); |
2849 | name = deref_func_name((const char *)tofree, &len, |
2850 | partial != NULL ? NULL : &partial, false); |
2851 | |
2852 | // Skip white space to allow ":call func ()". Not good, but required for |
2853 | // backward compatibility. |
2854 | startarg = skipwhite(arg); |
2855 | rettv.v_type = VAR_UNKNOWN; // tv_clear() uses this. |
2856 | |
2857 | if (*startarg != '(') { |
2858 | EMSG2(_("E107: Missing parentheses: %s" ), eap->arg); |
2859 | goto end; |
2860 | } |
2861 | |
2862 | lnum = eap->line1; |
2863 | for (; lnum <= eap->line2; lnum++) { |
2864 | if (eap->addr_count > 0) { // -V560 |
2865 | if (lnum > curbuf->b_ml.ml_line_count) { |
2866 | // If the function deleted lines or switched to another buffer |
2867 | // the line number may become invalid. |
2868 | EMSG(_(e_invrange)); |
2869 | break; |
2870 | } |
2871 | curwin->w_cursor.lnum = lnum; |
2872 | curwin->w_cursor.col = 0; |
2873 | curwin->w_cursor.coladd = 0; |
2874 | } |
2875 | arg = startarg; |
2876 | if (get_func_tv(name, (int)STRLEN(name), &rettv, &arg, |
2877 | eap->line1, eap->line2, &doesrange, |
2878 | true, partial, fudi.fd_dict) == FAIL) { |
2879 | failed = true; |
2880 | break; |
2881 | } |
2882 | |
2883 | // Handle a function returning a Funcref, Dictionary or List. |
2884 | if (handle_subscript((const char **)&arg, &rettv, true, true) |
2885 | == FAIL) { |
2886 | failed = true; |
2887 | break; |
2888 | } |
2889 | |
2890 | tv_clear(&rettv); |
2891 | if (doesrange) { |
2892 | break; |
2893 | } |
2894 | |
2895 | // Stop when immediately aborting on error, or when an interrupt |
2896 | // occurred or an exception was thrown but not caught. |
2897 | // get_func_tv() returned OK, so that the check for trailing |
2898 | // characters below is executed. |
2899 | if (aborting()) { |
2900 | break; |
2901 | } |
2902 | } |
2903 | |
2904 | if (!failed) { |
2905 | // Check for trailing illegal characters and a following command. |
2906 | if (!ends_excmd(*arg)) { |
2907 | emsg_severe = TRUE; |
2908 | EMSG(_(e_trailing)); |
2909 | } else { |
2910 | eap->nextcmd = check_nextcmd(arg); |
2911 | } |
2912 | } |
2913 | |
2914 | end: |
2915 | tv_dict_unref(fudi.fd_dict); |
2916 | xfree(tofree); |
2917 | } |
2918 | |
2919 | // TODO(ZyX-I): move to eval/ex_cmds |
2920 | |
2921 | /* |
2922 | * ":unlet[!] var1 ... " command. |
2923 | */ |
2924 | void ex_unlet(exarg_T *eap) |
2925 | { |
2926 | ex_unletlock(eap, eap->arg, 0); |
2927 | } |
2928 | |
2929 | // TODO(ZyX-I): move to eval/ex_cmds |
2930 | |
2931 | /* |
2932 | * ":lockvar" and ":unlockvar" commands |
2933 | */ |
2934 | void ex_lockvar(exarg_T *eap) |
2935 | { |
2936 | char_u *arg = eap->arg; |
2937 | int deep = 2; |
2938 | |
2939 | if (eap->forceit) { |
2940 | deep = -1; |
2941 | } else if (ascii_isdigit(*arg)) { |
2942 | deep = getdigits_int(&arg, false, -1); |
2943 | arg = skipwhite(arg); |
2944 | } |
2945 | |
2946 | ex_unletlock(eap, arg, deep); |
2947 | } |
2948 | |
2949 | // TODO(ZyX-I): move to eval/ex_cmds |
2950 | |
2951 | /* |
2952 | * ":unlet", ":lockvar" and ":unlockvar" are quite similar. |
2953 | */ |
2954 | static void ex_unletlock(exarg_T *eap, char_u *argstart, int deep) |
2955 | { |
2956 | char_u *arg = argstart; |
2957 | bool error = false; |
2958 | lval_T lv; |
2959 | |
2960 | do { |
2961 | if (*arg == '$') { |
2962 | const char *name = (char *)++arg; |
2963 | |
2964 | if (get_env_len((const char_u **)&arg) == 0) { |
2965 | EMSG2(_(e_invarg2), name - 1); |
2966 | return; |
2967 | } |
2968 | os_unsetenv(name); |
2969 | arg = skipwhite(arg); |
2970 | continue; |
2971 | } |
2972 | |
2973 | // Parse the name and find the end. |
2974 | char_u *const name_end = (char_u *)get_lval(arg, NULL, &lv, true, |
2975 | eap->skip || error, |
2976 | 0, FNE_CHECK_START); |
2977 | if (lv.ll_name == NULL) { |
2978 | error = true; // error, but continue parsing. |
2979 | } |
2980 | if (name_end == NULL || (!ascii_iswhite(*name_end) |
2981 | && !ends_excmd(*name_end))) { |
2982 | if (name_end != NULL) { |
2983 | emsg_severe = TRUE; |
2984 | EMSG(_(e_trailing)); |
2985 | } |
2986 | if (!(eap->skip || error)) |
2987 | clear_lval(&lv); |
2988 | break; |
2989 | } |
2990 | |
2991 | if (!error && !eap->skip) { |
2992 | if (eap->cmdidx == CMD_unlet) { |
2993 | if (do_unlet_var(&lv, name_end, eap->forceit) == FAIL) |
2994 | error = TRUE; |
2995 | } else { |
2996 | if (do_lock_var(&lv, name_end, deep, |
2997 | eap->cmdidx == CMD_lockvar) == FAIL) { |
2998 | error = true; |
2999 | } |
3000 | } |
3001 | } |
3002 | |
3003 | if (!eap->skip) |
3004 | clear_lval(&lv); |
3005 | |
3006 | arg = skipwhite(name_end); |
3007 | } while (!ends_excmd(*arg)); |
3008 | |
3009 | eap->nextcmd = check_nextcmd(arg); |
3010 | } |
3011 | |
3012 | // TODO(ZyX-I): move to eval/ex_cmds |
3013 | |
3014 | static int do_unlet_var(lval_T *const lp, char_u *const name_end, int forceit) |
3015 | { |
3016 | int ret = OK; |
3017 | int cc; |
3018 | |
3019 | if (lp->ll_tv == NULL) { |
3020 | cc = *name_end; |
3021 | *name_end = NUL; |
3022 | |
3023 | // Normal name or expanded name. |
3024 | if (do_unlet(lp->ll_name, lp->ll_name_len, forceit) == FAIL) { |
3025 | ret = FAIL; |
3026 | } |
3027 | *name_end = cc; |
3028 | } else if ((lp->ll_list != NULL |
3029 | // ll_list is not NULL when lvalue is not in a list, NULL lists |
3030 | // yield E689. |
3031 | && tv_check_lock(tv_list_locked(lp->ll_list), |
3032 | (const char *)lp->ll_name, |
3033 | lp->ll_name_len)) |
3034 | || (lp->ll_dict != NULL |
3035 | && tv_check_lock(lp->ll_dict->dv_lock, |
3036 | (const char *)lp->ll_name, |
3037 | lp->ll_name_len))) { |
3038 | return FAIL; |
3039 | } else if (lp->ll_range) { |
3040 | assert(lp->ll_list != NULL); |
3041 | // Delete a range of List items. |
3042 | listitem_T *const first_li = lp->ll_li; |
3043 | listitem_T *last_li = first_li; |
3044 | for (;;) { |
3045 | listitem_T *const li = TV_LIST_ITEM_NEXT(lp->ll_list, lp->ll_li); |
3046 | if (tv_check_lock(TV_LIST_ITEM_TV(lp->ll_li)->v_lock, |
3047 | (const char *)lp->ll_name, |
3048 | lp->ll_name_len)) { |
3049 | return false; |
3050 | } |
3051 | lp->ll_li = li; |
3052 | lp->ll_n1++; |
3053 | if (lp->ll_li == NULL || (!lp->ll_empty2 && lp->ll_n2 < lp->ll_n1)) { |
3054 | break; |
3055 | } else { |
3056 | last_li = lp->ll_li; |
3057 | } |
3058 | } |
3059 | tv_list_remove_items(lp->ll_list, first_li, last_li); |
3060 | } else { |
3061 | if (lp->ll_list != NULL) { |
3062 | // unlet a List item. |
3063 | tv_list_item_remove(lp->ll_list, lp->ll_li); |
3064 | } else { |
3065 | // unlet a Dictionary item. |
3066 | dict_T *d = lp->ll_dict; |
3067 | assert(d != NULL); |
3068 | dictitem_T *di = lp->ll_di; |
3069 | bool watched = tv_dict_is_watched(d); |
3070 | char *key = NULL; |
3071 | typval_T oldtv; |
3072 | |
3073 | if (watched) { |
3074 | tv_copy(&di->di_tv, &oldtv); |
3075 | // need to save key because dictitem_remove will free it |
3076 | key = xstrdup((char *)di->di_key); |
3077 | } |
3078 | |
3079 | tv_dict_item_remove(d, di); |
3080 | |
3081 | if (watched) { |
3082 | tv_dict_watcher_notify(d, key, NULL, &oldtv); |
3083 | tv_clear(&oldtv); |
3084 | xfree(key); |
3085 | } |
3086 | } |
3087 | } |
3088 | |
3089 | return ret; |
3090 | } |
3091 | |
3092 | // TODO(ZyX-I): move to eval/ex_cmds |
3093 | |
3094 | /// unlet a variable |
3095 | /// |
3096 | /// @param[in] name Variable name to unlet. |
3097 | /// @param[in] name_len Variable name length. |
3098 | /// @param[in] fonceit If true, do not complain if variable doesn’t exist. |
3099 | /// |
3100 | /// @return OK if it existed, FAIL otherwise. |
3101 | int do_unlet(const char *const name, const size_t name_len, const int forceit) |
3102 | FUNC_ATTR_NONNULL_ALL |
3103 | { |
3104 | const char *varname; |
3105 | dict_T *dict; |
3106 | hashtab_T *ht = find_var_ht_dict(name, name_len, &varname, &dict); |
3107 | |
3108 | if (ht != NULL && *varname != NUL) { |
3109 | dict_T *d; |
3110 | if (ht == &globvarht) { |
3111 | d = &globvardict; |
3112 | } else if (current_funccal != NULL |
3113 | && ht == ¤t_funccal->l_vars.dv_hashtab) { |
3114 | d = ¤t_funccal->l_vars; |
3115 | } else if (ht == &compat_hashtab) { |
3116 | d = &vimvardict; |
3117 | } else { |
3118 | dictitem_T *const di = find_var_in_ht(ht, *name, "" , 0, false); |
3119 | d = di->di_tv.vval.v_dict; |
3120 | } |
3121 | if (d == NULL) { |
3122 | internal_error("do_unlet()" ); |
3123 | return FAIL; |
3124 | } |
3125 | hashitem_T *hi = hash_find(ht, (const char_u *)varname); |
3126 | if (HASHITEM_EMPTY(hi)) { |
3127 | hi = find_hi_in_scoped_ht((const char *)name, &ht); |
3128 | } |
3129 | if (hi != NULL && !HASHITEM_EMPTY(hi)) { |
3130 | dictitem_T *const di = TV_DICT_HI2DI(hi); |
3131 | if (var_check_fixed(di->di_flags, (const char *)name, TV_CSTRING) |
3132 | || var_check_ro(di->di_flags, (const char *)name, TV_CSTRING) |
3133 | || tv_check_lock(d->dv_lock, (const char *)name, TV_CSTRING)) { |
3134 | return FAIL; |
3135 | } |
3136 | |
3137 | if (tv_check_lock(d->dv_lock, (const char *)name, TV_CSTRING)) { |
3138 | return FAIL; |
3139 | } |
3140 | |
3141 | typval_T oldtv; |
3142 | bool watched = tv_dict_is_watched(dict); |
3143 | |
3144 | if (watched) { |
3145 | tv_copy(&di->di_tv, &oldtv); |
3146 | } |
3147 | |
3148 | delete_var(ht, hi); |
3149 | |
3150 | if (watched) { |
3151 | tv_dict_watcher_notify(dict, varname, NULL, &oldtv); |
3152 | tv_clear(&oldtv); |
3153 | } |
3154 | return OK; |
3155 | } |
3156 | } |
3157 | if (forceit) |
3158 | return OK; |
3159 | EMSG2(_("E108: No such variable: \"%s\"" ), name); |
3160 | return FAIL; |
3161 | } |
3162 | |
3163 | // TODO(ZyX-I): move to eval/ex_cmds |
3164 | |
3165 | /* |
3166 | * Lock or unlock variable indicated by "lp". |
3167 | * "deep" is the levels to go (-1 for unlimited); |
3168 | * "lock" is TRUE for ":lockvar", FALSE for ":unlockvar". |
3169 | */ |
3170 | static int do_lock_var(lval_T *lp, char_u *const name_end, const int deep, |
3171 | const bool lock) |
3172 | { |
3173 | int ret = OK; |
3174 | |
3175 | if (deep == 0) { // Nothing to do. |
3176 | return OK; |
3177 | } |
3178 | |
3179 | if (lp->ll_tv == NULL) { |
3180 | // Normal name or expanded name. |
3181 | dictitem_T *const di = find_var( |
3182 | (const char *)lp->ll_name, lp->ll_name_len, NULL, |
3183 | true); |
3184 | if (di == NULL) { |
3185 | ret = FAIL; |
3186 | } else if ((di->di_flags & DI_FLAGS_FIX) |
3187 | && di->di_tv.v_type != VAR_DICT |
3188 | && di->di_tv.v_type != VAR_LIST) { |
3189 | // For historical reasons this error is not given for Lists and |
3190 | // Dictionaries. E.g. b: dictionary may be locked/unlocked. |
3191 | emsgf(_("E940: Cannot lock or unlock variable %s" ), lp->ll_name); |
3192 | } else { |
3193 | if (lock) { |
3194 | di->di_flags |= DI_FLAGS_LOCK; |
3195 | } else { |
3196 | di->di_flags &= ~DI_FLAGS_LOCK; |
3197 | } |
3198 | tv_item_lock(&di->di_tv, deep, lock); |
3199 | } |
3200 | } else if (lp->ll_range) { |
3201 | listitem_T *li = lp->ll_li; |
3202 | |
3203 | /* (un)lock a range of List items. */ |
3204 | while (li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1)) { |
3205 | tv_item_lock(TV_LIST_ITEM_TV(li), deep, lock); |
3206 | li = TV_LIST_ITEM_NEXT(lp->ll_list, li); |
3207 | lp->ll_n1++; |
3208 | } |
3209 | } else if (lp->ll_list != NULL) { |
3210 | // (un)lock a List item. |
3211 | tv_item_lock(TV_LIST_ITEM_TV(lp->ll_li), deep, lock); |
3212 | } else { |
3213 | // (un)lock a Dictionary item. |
3214 | tv_item_lock(&lp->ll_di->di_tv, deep, lock); |
3215 | } |
3216 | |
3217 | return ret; |
3218 | } |
3219 | |
3220 | /* |
3221 | * Delete all "menutrans_" variables. |
3222 | */ |
3223 | void (void) |
3224 | { |
3225 | hash_lock(&globvarht); |
3226 | HASHTAB_ITER(&globvarht, hi, { |
3227 | if (STRNCMP(hi->hi_key, "menutrans_" , 10) == 0) { |
3228 | delete_var(&globvarht, hi); |
3229 | } |
3230 | }); |
3231 | hash_unlock(&globvarht); |
3232 | } |
3233 | |
3234 | /* |
3235 | * Local string buffer for the next two functions to store a variable name |
3236 | * with its prefix. Allocated in cat_prefix_varname(), freed later in |
3237 | * get_user_var_name(). |
3238 | */ |
3239 | |
3240 | |
3241 | static char_u *varnamebuf = NULL; |
3242 | static size_t varnamebuflen = 0; |
3243 | |
3244 | /* |
3245 | * Function to concatenate a prefix and a variable name. |
3246 | */ |
3247 | static char_u *cat_prefix_varname(int prefix, char_u *name) |
3248 | { |
3249 | size_t len = STRLEN(name) + 3; |
3250 | |
3251 | if (len > varnamebuflen) { |
3252 | xfree(varnamebuf); |
3253 | len += 10; /* some additional space */ |
3254 | varnamebuf = xmalloc(len); |
3255 | varnamebuflen = len; |
3256 | } |
3257 | *varnamebuf = prefix; |
3258 | varnamebuf[1] = ':'; |
3259 | STRCPY(varnamebuf + 2, name); |
3260 | return varnamebuf; |
3261 | } |
3262 | |
3263 | /* |
3264 | * Function given to ExpandGeneric() to obtain the list of user defined |
3265 | * (global/buffer/window/built-in) variable names. |
3266 | */ |
3267 | char_u *get_user_var_name(expand_T *xp, int idx) |
3268 | { |
3269 | static size_t gdone; |
3270 | static size_t bdone; |
3271 | static size_t wdone; |
3272 | static size_t tdone; |
3273 | static size_t vidx; |
3274 | static hashitem_T *hi; |
3275 | hashtab_T *ht; |
3276 | |
3277 | if (idx == 0) { |
3278 | gdone = bdone = wdone = vidx = 0; |
3279 | tdone = 0; |
3280 | } |
3281 | |
3282 | /* Global variables */ |
3283 | if (gdone < globvarht.ht_used) { |
3284 | if (gdone++ == 0) |
3285 | hi = globvarht.ht_array; |
3286 | else |
3287 | ++hi; |
3288 | while (HASHITEM_EMPTY(hi)) |
3289 | ++hi; |
3290 | if (STRNCMP("g:" , xp->xp_pattern, 2) == 0) |
3291 | return cat_prefix_varname('g', hi->hi_key); |
3292 | return hi->hi_key; |
3293 | } |
3294 | |
3295 | /* b: variables */ |
3296 | ht = &curbuf->b_vars->dv_hashtab; |
3297 | if (bdone < ht->ht_used) { |
3298 | if (bdone++ == 0) |
3299 | hi = ht->ht_array; |
3300 | else |
3301 | ++hi; |
3302 | while (HASHITEM_EMPTY(hi)) |
3303 | ++hi; |
3304 | return cat_prefix_varname('b', hi->hi_key); |
3305 | } |
3306 | |
3307 | /* w: variables */ |
3308 | ht = &curwin->w_vars->dv_hashtab; |
3309 | if (wdone < ht->ht_used) { |
3310 | if (wdone++ == 0) |
3311 | hi = ht->ht_array; |
3312 | else |
3313 | ++hi; |
3314 | while (HASHITEM_EMPTY(hi)) |
3315 | ++hi; |
3316 | return cat_prefix_varname('w', hi->hi_key); |
3317 | } |
3318 | |
3319 | /* t: variables */ |
3320 | ht = &curtab->tp_vars->dv_hashtab; |
3321 | if (tdone < ht->ht_used) { |
3322 | if (tdone++ == 0) |
3323 | hi = ht->ht_array; |
3324 | else |
3325 | ++hi; |
3326 | while (HASHITEM_EMPTY(hi)) |
3327 | ++hi; |
3328 | return cat_prefix_varname('t', hi->hi_key); |
3329 | } |
3330 | |
3331 | // v: variables |
3332 | if (vidx < ARRAY_SIZE(vimvars)) { |
3333 | return cat_prefix_varname('v', (char_u *)vimvars[vidx++].vv_name); |
3334 | } |
3335 | |
3336 | XFREE_CLEAR(varnamebuf); |
3337 | varnamebuflen = 0; |
3338 | return NULL; |
3339 | } |
3340 | |
3341 | // TODO(ZyX-I): move to eval/expressions |
3342 | |
3343 | /// Return TRUE if "pat" matches "text". |
3344 | /// Does not use 'cpo' and always uses 'magic'. |
3345 | static int pattern_match(char_u *pat, char_u *text, int ic) |
3346 | { |
3347 | int matches = 0; |
3348 | regmatch_T regmatch; |
3349 | |
3350 | // avoid 'l' flag in 'cpoptions' |
3351 | char_u *save_cpo = p_cpo; |
3352 | p_cpo = (char_u *)"" ; |
3353 | regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING); |
3354 | if (regmatch.regprog != NULL) { |
3355 | regmatch.rm_ic = ic; |
3356 | matches = vim_regexec_nl(®match, text, (colnr_T)0); |
3357 | vim_regfree(regmatch.regprog); |
3358 | } |
3359 | p_cpo = save_cpo; |
3360 | return matches; |
3361 | } |
3362 | |
3363 | /* |
3364 | * types for expressions. |
3365 | */ |
3366 | typedef enum { |
3367 | TYPE_UNKNOWN = 0, |
3368 | TYPE_EQUAL, // == |
3369 | TYPE_NEQUAL, // != |
3370 | TYPE_GREATER, // > |
3371 | TYPE_GEQUAL, // >= |
3372 | TYPE_SMALLER, // < |
3373 | TYPE_SEQUAL, // <= |
3374 | TYPE_MATCH, // =~ |
3375 | TYPE_NOMATCH, // !~ |
3376 | } exptype_T; |
3377 | |
3378 | // TODO(ZyX-I): move to eval/expressions |
3379 | |
3380 | /* |
3381 | * The "evaluate" argument: When FALSE, the argument is only parsed but not |
3382 | * executed. The function may return OK, but the rettv will be of type |
3383 | * VAR_UNKNOWN. The function still returns FAIL for a syntax error. |
3384 | */ |
3385 | |
3386 | /* |
3387 | * Handle zero level expression. |
3388 | * This calls eval1() and handles error message and nextcmd. |
3389 | * Put the result in "rettv" when returning OK and "evaluate" is TRUE. |
3390 | * Note: "rettv.v_lock" is not set. |
3391 | * Return OK or FAIL. |
3392 | */ |
3393 | int eval0(char_u *arg, typval_T *rettv, char_u **nextcmd, int evaluate) |
3394 | { |
3395 | int ret; |
3396 | char_u *p; |
3397 | |
3398 | p = skipwhite(arg); |
3399 | ret = eval1(&p, rettv, evaluate); |
3400 | if (ret == FAIL || !ends_excmd(*p)) { |
3401 | if (ret != FAIL) { |
3402 | tv_clear(rettv); |
3403 | } |
3404 | // Report the invalid expression unless the expression evaluation has |
3405 | // been cancelled due to an aborting error, an interrupt, or an |
3406 | // exception. |
3407 | if (!aborting()) { |
3408 | emsgf(_(e_invexpr2), arg); |
3409 | } |
3410 | ret = FAIL; |
3411 | } |
3412 | if (nextcmd != NULL) |
3413 | *nextcmd = check_nextcmd(p); |
3414 | |
3415 | return ret; |
3416 | } |
3417 | |
3418 | // TODO(ZyX-I): move to eval/expressions |
3419 | |
3420 | /* |
3421 | * Handle top level expression: |
3422 | * expr2 ? expr1 : expr1 |
3423 | * |
3424 | * "arg" must point to the first non-white of the expression. |
3425 | * "arg" is advanced to the next non-white after the recognized expression. |
3426 | * |
3427 | * Note: "rettv.v_lock" is not set. |
3428 | * |
3429 | * Return OK or FAIL. |
3430 | */ |
3431 | static int eval1(char_u **arg, typval_T *rettv, int evaluate) |
3432 | { |
3433 | int result; |
3434 | typval_T var2; |
3435 | |
3436 | /* |
3437 | * Get the first variable. |
3438 | */ |
3439 | if (eval2(arg, rettv, evaluate) == FAIL) |
3440 | return FAIL; |
3441 | |
3442 | if ((*arg)[0] == '?') { |
3443 | result = FALSE; |
3444 | if (evaluate) { |
3445 | bool error = false; |
3446 | |
3447 | if (tv_get_number_chk(rettv, &error) != 0) { |
3448 | result = true; |
3449 | } |
3450 | tv_clear(rettv); |
3451 | if (error) { |
3452 | return FAIL; |
3453 | } |
3454 | } |
3455 | |
3456 | /* |
3457 | * Get the second variable. |
3458 | */ |
3459 | *arg = skipwhite(*arg + 1); |
3460 | if (eval1(arg, rettv, evaluate && result) == FAIL) /* recursive! */ |
3461 | return FAIL; |
3462 | |
3463 | /* |
3464 | * Check for the ":". |
3465 | */ |
3466 | if ((*arg)[0] != ':') { |
3467 | EMSG(_("E109: Missing ':' after '?'" )); |
3468 | if (evaluate && result) { |
3469 | tv_clear(rettv); |
3470 | } |
3471 | return FAIL; |
3472 | } |
3473 | |
3474 | /* |
3475 | * Get the third variable. |
3476 | */ |
3477 | *arg = skipwhite(*arg + 1); |
3478 | if (eval1(arg, &var2, evaluate && !result) == FAIL) { // Recursive! |
3479 | if (evaluate && result) { |
3480 | tv_clear(rettv); |
3481 | } |
3482 | return FAIL; |
3483 | } |
3484 | if (evaluate && !result) |
3485 | *rettv = var2; |
3486 | } |
3487 | |
3488 | return OK; |
3489 | } |
3490 | |
3491 | // TODO(ZyX-I): move to eval/expressions |
3492 | |
3493 | /* |
3494 | * Handle first level expression: |
3495 | * expr2 || expr2 || expr2 logical OR |
3496 | * |
3497 | * "arg" must point to the first non-white of the expression. |
3498 | * "arg" is advanced to the next non-white after the recognized expression. |
3499 | * |
3500 | * Return OK or FAIL. |
3501 | */ |
3502 | static int eval2(char_u **arg, typval_T *rettv, int evaluate) |
3503 | { |
3504 | typval_T var2; |
3505 | long result; |
3506 | int first; |
3507 | bool error = false; |
3508 | |
3509 | /* |
3510 | * Get the first variable. |
3511 | */ |
3512 | if (eval3(arg, rettv, evaluate) == FAIL) |
3513 | return FAIL; |
3514 | |
3515 | /* |
3516 | * Repeat until there is no following "||". |
3517 | */ |
3518 | first = TRUE; |
3519 | result = FALSE; |
3520 | while ((*arg)[0] == '|' && (*arg)[1] == '|') { |
3521 | if (evaluate && first) { |
3522 | if (tv_get_number_chk(rettv, &error) != 0) { |
3523 | result = true; |
3524 | } |
3525 | tv_clear(rettv); |
3526 | if (error) { |
3527 | return FAIL; |
3528 | } |
3529 | first = false; |
3530 | } |
3531 | |
3532 | /* |
3533 | * Get the second variable. |
3534 | */ |
3535 | *arg = skipwhite(*arg + 2); |
3536 | if (eval3(arg, &var2, evaluate && !result) == FAIL) |
3537 | return FAIL; |
3538 | |
3539 | /* |
3540 | * Compute the result. |
3541 | */ |
3542 | if (evaluate && !result) { |
3543 | if (tv_get_number_chk(&var2, &error) != 0) { |
3544 | result = true; |
3545 | } |
3546 | tv_clear(&var2); |
3547 | if (error) { |
3548 | return FAIL; |
3549 | } |
3550 | } |
3551 | if (evaluate) { |
3552 | rettv->v_type = VAR_NUMBER; |
3553 | rettv->vval.v_number = result; |
3554 | } |
3555 | } |
3556 | |
3557 | return OK; |
3558 | } |
3559 | |
3560 | // TODO(ZyX-I): move to eval/expressions |
3561 | |
3562 | /* |
3563 | * Handle second level expression: |
3564 | * expr3 && expr3 && expr3 logical AND |
3565 | * |
3566 | * "arg" must point to the first non-white of the expression. |
3567 | * "arg" is advanced to the next non-white after the recognized expression. |
3568 | * |
3569 | * Return OK or FAIL. |
3570 | */ |
3571 | static int eval3(char_u **arg, typval_T *rettv, int evaluate) |
3572 | { |
3573 | typval_T var2; |
3574 | long result; |
3575 | int first; |
3576 | bool error = false; |
3577 | |
3578 | /* |
3579 | * Get the first variable. |
3580 | */ |
3581 | if (eval4(arg, rettv, evaluate) == FAIL) |
3582 | return FAIL; |
3583 | |
3584 | /* |
3585 | * Repeat until there is no following "&&". |
3586 | */ |
3587 | first = TRUE; |
3588 | result = TRUE; |
3589 | while ((*arg)[0] == '&' && (*arg)[1] == '&') { |
3590 | if (evaluate && first) { |
3591 | if (tv_get_number_chk(rettv, &error) == 0) { |
3592 | result = false; |
3593 | } |
3594 | tv_clear(rettv); |
3595 | if (error) { |
3596 | return FAIL; |
3597 | } |
3598 | first = false; |
3599 | } |
3600 | |
3601 | /* |
3602 | * Get the second variable. |
3603 | */ |
3604 | *arg = skipwhite(*arg + 2); |
3605 | if (eval4(arg, &var2, evaluate && result) == FAIL) |
3606 | return FAIL; |
3607 | |
3608 | /* |
3609 | * Compute the result. |
3610 | */ |
3611 | if (evaluate && result) { |
3612 | if (tv_get_number_chk(&var2, &error) == 0) { |
3613 | result = false; |
3614 | } |
3615 | tv_clear(&var2); |
3616 | if (error) { |
3617 | return FAIL; |
3618 | } |
3619 | } |
3620 | if (evaluate) { |
3621 | rettv->v_type = VAR_NUMBER; |
3622 | rettv->vval.v_number = result; |
3623 | } |
3624 | } |
3625 | |
3626 | return OK; |
3627 | } |
3628 | |
3629 | // TODO(ZyX-I): move to eval/expressions |
3630 | |
3631 | /* |
3632 | * Handle third level expression: |
3633 | * var1 == var2 |
3634 | * var1 =~ var2 |
3635 | * var1 != var2 |
3636 | * var1 !~ var2 |
3637 | * var1 > var2 |
3638 | * var1 >= var2 |
3639 | * var1 < var2 |
3640 | * var1 <= var2 |
3641 | * var1 is var2 |
3642 | * var1 isnot var2 |
3643 | * |
3644 | * "arg" must point to the first non-white of the expression. |
3645 | * "arg" is advanced to the next non-white after the recognized expression. |
3646 | * |
3647 | * Return OK or FAIL. |
3648 | */ |
3649 | static int eval4(char_u **arg, typval_T *rettv, int evaluate) |
3650 | { |
3651 | typval_T var2; |
3652 | char_u *p; |
3653 | int i; |
3654 | exptype_T type = TYPE_UNKNOWN; |
3655 | int type_is = FALSE; /* TRUE for "is" and "isnot" */ |
3656 | int len = 2; |
3657 | varnumber_T n1, n2; |
3658 | int ic; |
3659 | |
3660 | /* |
3661 | * Get the first variable. |
3662 | */ |
3663 | if (eval5(arg, rettv, evaluate) == FAIL) |
3664 | return FAIL; |
3665 | |
3666 | p = *arg; |
3667 | switch (p[0]) { |
3668 | case '=': if (p[1] == '=') |
3669 | type = TYPE_EQUAL; |
3670 | else if (p[1] == '~') |
3671 | type = TYPE_MATCH; |
3672 | break; |
3673 | case '!': if (p[1] == '=') |
3674 | type = TYPE_NEQUAL; |
3675 | else if (p[1] == '~') |
3676 | type = TYPE_NOMATCH; |
3677 | break; |
3678 | case '>': if (p[1] != '=') { |
3679 | type = TYPE_GREATER; |
3680 | len = 1; |
3681 | } else |
3682 | type = TYPE_GEQUAL; |
3683 | break; |
3684 | case '<': if (p[1] != '=') { |
3685 | type = TYPE_SMALLER; |
3686 | len = 1; |
3687 | } else |
3688 | type = TYPE_SEQUAL; |
3689 | break; |
3690 | case 'i': if (p[1] == 's') { |
3691 | if (p[2] == 'n' && p[3] == 'o' && p[4] == 't') { |
3692 | len = 5; |
3693 | } |
3694 | if (!isalnum(p[len]) && p[len] != '_') { |
3695 | type = len == 2 ? TYPE_EQUAL : TYPE_NEQUAL; |
3696 | type_is = TRUE; |
3697 | } |
3698 | } |
3699 | break; |
3700 | } |
3701 | |
3702 | /* |
3703 | * If there is a comparative operator, use it. |
3704 | */ |
3705 | if (type != TYPE_UNKNOWN) { |
3706 | /* extra question mark appended: ignore case */ |
3707 | if (p[len] == '?') { |
3708 | ic = TRUE; |
3709 | ++len; |
3710 | } |
3711 | /* extra '#' appended: match case */ |
3712 | else if (p[len] == '#') { |
3713 | ic = FALSE; |
3714 | ++len; |
3715 | } |
3716 | /* nothing appended: use 'ignorecase' */ |
3717 | else |
3718 | ic = p_ic; |
3719 | |
3720 | /* |
3721 | * Get the second variable. |
3722 | */ |
3723 | *arg = skipwhite(p + len); |
3724 | if (eval5(arg, &var2, evaluate) == FAIL) { |
3725 | tv_clear(rettv); |
3726 | return FAIL; |
3727 | } |
3728 | |
3729 | if (evaluate) { |
3730 | if (type_is && rettv->v_type != var2.v_type) { |
3731 | /* For "is" a different type always means FALSE, for "notis" |
3732 | * it means TRUE. */ |
3733 | n1 = (type == TYPE_NEQUAL); |
3734 | } else if (rettv->v_type == VAR_LIST || var2.v_type == VAR_LIST) { |
3735 | if (type_is) { |
3736 | n1 = (rettv->v_type == var2.v_type |
3737 | && rettv->vval.v_list == var2.vval.v_list); |
3738 | if (type == TYPE_NEQUAL) |
3739 | n1 = !n1; |
3740 | } else if (rettv->v_type != var2.v_type |
3741 | || (type != TYPE_EQUAL && type != TYPE_NEQUAL)) { |
3742 | if (rettv->v_type != var2.v_type) { |
3743 | EMSG(_("E691: Can only compare List with List" )); |
3744 | } else { |
3745 | EMSG(_("E692: Invalid operation for List" )); |
3746 | } |
3747 | tv_clear(rettv); |
3748 | tv_clear(&var2); |
3749 | return FAIL; |
3750 | } else { |
3751 | // Compare two Lists for being equal or unequal. |
3752 | n1 = tv_list_equal(rettv->vval.v_list, var2.vval.v_list, ic, false); |
3753 | if (type == TYPE_NEQUAL) { |
3754 | n1 = !n1; |
3755 | } |
3756 | } |
3757 | } else if (rettv->v_type == VAR_DICT || var2.v_type == VAR_DICT) { |
3758 | if (type_is) { |
3759 | n1 = (rettv->v_type == var2.v_type |
3760 | && rettv->vval.v_dict == var2.vval.v_dict); |
3761 | if (type == TYPE_NEQUAL) |
3762 | n1 = !n1; |
3763 | } else if (rettv->v_type != var2.v_type |
3764 | || (type != TYPE_EQUAL && type != TYPE_NEQUAL)) { |
3765 | if (rettv->v_type != var2.v_type) |
3766 | EMSG(_("E735: Can only compare Dictionary with Dictionary" )); |
3767 | else |
3768 | EMSG(_("E736: Invalid operation for Dictionary" )); |
3769 | tv_clear(rettv); |
3770 | tv_clear(&var2); |
3771 | return FAIL; |
3772 | } else { |
3773 | // Compare two Dictionaries for being equal or unequal. |
3774 | n1 = tv_dict_equal(rettv->vval.v_dict, var2.vval.v_dict, |
3775 | ic, false); |
3776 | if (type == TYPE_NEQUAL) { |
3777 | n1 = !n1; |
3778 | } |
3779 | } |
3780 | } else if (tv_is_func(*rettv) || tv_is_func(var2)) { |
3781 | if (type != TYPE_EQUAL && type != TYPE_NEQUAL) { |
3782 | EMSG(_("E694: Invalid operation for Funcrefs" )); |
3783 | tv_clear(rettv); |
3784 | tv_clear(&var2); |
3785 | return FAIL; |
3786 | } |
3787 | if ((rettv->v_type == VAR_PARTIAL |
3788 | && rettv->vval.v_partial == NULL) |
3789 | || (var2.v_type == VAR_PARTIAL |
3790 | && var2.vval.v_partial == NULL)) { |
3791 | // when a partial is NULL assume not equal |
3792 | n1 = false; |
3793 | } else if (type_is) { |
3794 | if (rettv->v_type == VAR_FUNC && var2.v_type == VAR_FUNC) { |
3795 | // strings are considered the same if their value is |
3796 | // the same |
3797 | n1 = tv_equal(rettv, &var2, ic, false); |
3798 | } else if (rettv->v_type == VAR_PARTIAL |
3799 | && var2.v_type == VAR_PARTIAL) { |
3800 | n1 = (rettv->vval.v_partial == var2.vval.v_partial); |
3801 | } else { |
3802 | n1 = false; |
3803 | } |
3804 | } else { |
3805 | n1 = tv_equal(rettv, &var2, ic, false); |
3806 | } |
3807 | if (type == TYPE_NEQUAL) { |
3808 | n1 = !n1; |
3809 | } |
3810 | } |
3811 | /* |
3812 | * If one of the two variables is a float, compare as a float. |
3813 | * When using "=~" or "!~", always compare as string. |
3814 | */ |
3815 | else if ((rettv->v_type == VAR_FLOAT || var2.v_type == VAR_FLOAT) |
3816 | && type != TYPE_MATCH && type != TYPE_NOMATCH) { |
3817 | float_T f1, f2; |
3818 | |
3819 | if (rettv->v_type == VAR_FLOAT) { |
3820 | f1 = rettv->vval.v_float; |
3821 | } else { |
3822 | f1 = tv_get_number(rettv); |
3823 | } |
3824 | if (var2.v_type == VAR_FLOAT) { |
3825 | f2 = var2.vval.v_float; |
3826 | } else { |
3827 | f2 = tv_get_number(&var2); |
3828 | } |
3829 | n1 = false; |
3830 | switch (type) { |
3831 | case TYPE_EQUAL: n1 = (f1 == f2); break; |
3832 | case TYPE_NEQUAL: n1 = (f1 != f2); break; |
3833 | case TYPE_GREATER: n1 = (f1 > f2); break; |
3834 | case TYPE_GEQUAL: n1 = (f1 >= f2); break; |
3835 | case TYPE_SMALLER: n1 = (f1 < f2); break; |
3836 | case TYPE_SEQUAL: n1 = (f1 <= f2); break; |
3837 | case TYPE_UNKNOWN: |
3838 | case TYPE_MATCH: |
3839 | case TYPE_NOMATCH: break; |
3840 | } |
3841 | } |
3842 | /* |
3843 | * If one of the two variables is a number, compare as a number. |
3844 | * When using "=~" or "!~", always compare as string. |
3845 | */ |
3846 | else if ((rettv->v_type == VAR_NUMBER || var2.v_type == VAR_NUMBER) |
3847 | && type != TYPE_MATCH && type != TYPE_NOMATCH) { |
3848 | n1 = tv_get_number(rettv); |
3849 | n2 = tv_get_number(&var2); |
3850 | switch (type) { |
3851 | case TYPE_EQUAL: n1 = (n1 == n2); break; |
3852 | case TYPE_NEQUAL: n1 = (n1 != n2); break; |
3853 | case TYPE_GREATER: n1 = (n1 > n2); break; |
3854 | case TYPE_GEQUAL: n1 = (n1 >= n2); break; |
3855 | case TYPE_SMALLER: n1 = (n1 < n2); break; |
3856 | case TYPE_SEQUAL: n1 = (n1 <= n2); break; |
3857 | case TYPE_UNKNOWN: |
3858 | case TYPE_MATCH: |
3859 | case TYPE_NOMATCH: break; |
3860 | } |
3861 | } else { |
3862 | char buf1[NUMBUFLEN]; |
3863 | char buf2[NUMBUFLEN]; |
3864 | const char *const s1 = tv_get_string_buf(rettv, buf1); |
3865 | const char *const s2 = tv_get_string_buf(&var2, buf2); |
3866 | if (type != TYPE_MATCH && type != TYPE_NOMATCH) { |
3867 | i = mb_strcmp_ic((bool)ic, s1, s2); |
3868 | } else { |
3869 | i = 0; |
3870 | } |
3871 | n1 = false; |
3872 | switch (type) { |
3873 | case TYPE_EQUAL: n1 = (i == 0); break; |
3874 | case TYPE_NEQUAL: n1 = (i != 0); break; |
3875 | case TYPE_GREATER: n1 = (i > 0); break; |
3876 | case TYPE_GEQUAL: n1 = (i >= 0); break; |
3877 | case TYPE_SMALLER: n1 = (i < 0); break; |
3878 | case TYPE_SEQUAL: n1 = (i <= 0); break; |
3879 | |
3880 | case TYPE_MATCH: |
3881 | case TYPE_NOMATCH: { |
3882 | n1 = pattern_match((char_u *)s2, (char_u *)s1, ic); |
3883 | if (type == TYPE_NOMATCH) { |
3884 | n1 = !n1; |
3885 | } |
3886 | break; |
3887 | } |
3888 | case TYPE_UNKNOWN: break; // Avoid gcc warning. |
3889 | } |
3890 | } |
3891 | tv_clear(rettv); |
3892 | tv_clear(&var2); |
3893 | rettv->v_type = VAR_NUMBER; |
3894 | rettv->vval.v_number = n1; |
3895 | } |
3896 | } |
3897 | |
3898 | return OK; |
3899 | } |
3900 | |
3901 | // TODO(ZyX-I): move to eval/expressions |
3902 | |
3903 | /* |
3904 | * Handle fourth level expression: |
3905 | * + number addition |
3906 | * - number subtraction |
3907 | * . string concatenation |
3908 | * .. string concatenation |
3909 | * |
3910 | * "arg" must point to the first non-white of the expression. |
3911 | * "arg" is advanced to the next non-white after the recognized expression. |
3912 | * |
3913 | * Return OK or FAIL. |
3914 | */ |
3915 | static int eval5(char_u **arg, typval_T *rettv, int evaluate) |
3916 | { |
3917 | typval_T var2; |
3918 | typval_T var3; |
3919 | int op; |
3920 | varnumber_T n1, n2; |
3921 | float_T f1 = 0, f2 = 0; |
3922 | char_u *p; |
3923 | |
3924 | /* |
3925 | * Get the first variable. |
3926 | */ |
3927 | if (eval6(arg, rettv, evaluate, FALSE) == FAIL) |
3928 | return FAIL; |
3929 | |
3930 | /* |
3931 | * Repeat computing, until no '+', '-' or '.' is following. |
3932 | */ |
3933 | for (;; ) { |
3934 | op = **arg; |
3935 | if (op != '+' && op != '-' && op != '.') |
3936 | break; |
3937 | |
3938 | if ((op != '+' || rettv->v_type != VAR_LIST) |
3939 | && (op == '.' || rettv->v_type != VAR_FLOAT)) { |
3940 | // For "list + ...", an illegal use of the first operand as |
3941 | // a number cannot be determined before evaluating the 2nd |
3942 | // operand: if this is also a list, all is ok. |
3943 | // For "something . ...", "something - ..." or "non-list + ...", |
3944 | // we know that the first operand needs to be a string or number |
3945 | // without evaluating the 2nd operand. So check before to avoid |
3946 | // side effects after an error. |
3947 | if (evaluate && !tv_check_str(rettv)) { |
3948 | tv_clear(rettv); |
3949 | return FAIL; |
3950 | } |
3951 | } |
3952 | |
3953 | /* |
3954 | * Get the second variable. |
3955 | */ |
3956 | if (op == '.' && *(*arg + 1) == '.') { // ..string concatenation |
3957 | (*arg)++; |
3958 | } |
3959 | *arg = skipwhite(*arg + 1); |
3960 | if (eval6(arg, &var2, evaluate, op == '.') == FAIL) { |
3961 | tv_clear(rettv); |
3962 | return FAIL; |
3963 | } |
3964 | |
3965 | if (evaluate) { |
3966 | /* |
3967 | * Compute the result. |
3968 | */ |
3969 | if (op == '.') { |
3970 | char buf1[NUMBUFLEN]; |
3971 | char buf2[NUMBUFLEN]; |
3972 | // s1 already checked |
3973 | const char *const s1 = tv_get_string_buf(rettv, buf1); |
3974 | const char *const s2 = tv_get_string_buf_chk(&var2, buf2); |
3975 | if (s2 == NULL) { // Type error? |
3976 | tv_clear(rettv); |
3977 | tv_clear(&var2); |
3978 | return FAIL; |
3979 | } |
3980 | p = concat_str((const char_u *)s1, (const char_u *)s2); |
3981 | tv_clear(rettv); |
3982 | rettv->v_type = VAR_STRING; |
3983 | rettv->vval.v_string = p; |
3984 | } else if (op == '+' && rettv->v_type == VAR_LIST |
3985 | && var2.v_type == VAR_LIST) { |
3986 | // Concatenate Lists. |
3987 | if (tv_list_concat(rettv->vval.v_list, var2.vval.v_list, &var3) |
3988 | == FAIL) { |
3989 | tv_clear(rettv); |
3990 | tv_clear(&var2); |
3991 | return FAIL; |
3992 | } |
3993 | tv_clear(rettv); |
3994 | *rettv = var3; |
3995 | } else { |
3996 | bool error = false; |
3997 | |
3998 | if (rettv->v_type == VAR_FLOAT) { |
3999 | f1 = rettv->vval.v_float; |
4000 | n1 = 0; |
4001 | } else { |
4002 | n1 = tv_get_number_chk(rettv, &error); |
4003 | if (error) { |
4004 | /* This can only happen for "list + non-list". For |
4005 | * "non-list + ..." or "something - ...", we returned |
4006 | * before evaluating the 2nd operand. */ |
4007 | tv_clear(rettv); |
4008 | return FAIL; |
4009 | } |
4010 | if (var2.v_type == VAR_FLOAT) |
4011 | f1 = n1; |
4012 | } |
4013 | if (var2.v_type == VAR_FLOAT) { |
4014 | f2 = var2.vval.v_float; |
4015 | n2 = 0; |
4016 | } else { |
4017 | n2 = tv_get_number_chk(&var2, &error); |
4018 | if (error) { |
4019 | tv_clear(rettv); |
4020 | tv_clear(&var2); |
4021 | return FAIL; |
4022 | } |
4023 | if (rettv->v_type == VAR_FLOAT) |
4024 | f2 = n2; |
4025 | } |
4026 | tv_clear(rettv); |
4027 | |
4028 | /* If there is a float on either side the result is a float. */ |
4029 | if (rettv->v_type == VAR_FLOAT || var2.v_type == VAR_FLOAT) { |
4030 | if (op == '+') |
4031 | f1 = f1 + f2; |
4032 | else |
4033 | f1 = f1 - f2; |
4034 | rettv->v_type = VAR_FLOAT; |
4035 | rettv->vval.v_float = f1; |
4036 | } else { |
4037 | if (op == '+') |
4038 | n1 = n1 + n2; |
4039 | else |
4040 | n1 = n1 - n2; |
4041 | rettv->v_type = VAR_NUMBER; |
4042 | rettv->vval.v_number = n1; |
4043 | } |
4044 | } |
4045 | tv_clear(&var2); |
4046 | } |
4047 | } |
4048 | return OK; |
4049 | } |
4050 | |
4051 | // TODO(ZyX-I): move to eval/expressions |
4052 | |
4053 | /// Handle fifth level expression: |
4054 | /// - * number multiplication |
4055 | /// - / number division |
4056 | /// - % number modulo |
4057 | /// |
4058 | /// @param[in,out] arg Points to the first non-whitespace character of the |
4059 | /// expression. Is advanced to the next non-whitespace |
4060 | /// character after the recognized expression. |
4061 | /// @param[out] rettv Location where result is saved. |
4062 | /// @param[in] evaluate If not true, rettv is not populated. |
4063 | /// @param[in] want_string True if "." is string_concatenation, otherwise |
4064 | /// float |
4065 | /// @return OK or FAIL. |
4066 | static int eval6(char_u **arg, typval_T *rettv, int evaluate, int want_string) |
4067 | FUNC_ATTR_NO_SANITIZE_UNDEFINED |
4068 | { |
4069 | typval_T var2; |
4070 | int op; |
4071 | varnumber_T n1, n2; |
4072 | bool use_float = false; |
4073 | float_T f1 = 0, f2 = 0; |
4074 | bool error = false; |
4075 | |
4076 | /* |
4077 | * Get the first variable. |
4078 | */ |
4079 | if (eval7(arg, rettv, evaluate, want_string) == FAIL) |
4080 | return FAIL; |
4081 | |
4082 | /* |
4083 | * Repeat computing, until no '*', '/' or '%' is following. |
4084 | */ |
4085 | for (;; ) { |
4086 | op = **arg; |
4087 | if (op != '*' && op != '/' && op != '%') |
4088 | break; |
4089 | |
4090 | if (evaluate) { |
4091 | if (rettv->v_type == VAR_FLOAT) { |
4092 | f1 = rettv->vval.v_float; |
4093 | use_float = true; |
4094 | n1 = 0; |
4095 | } else { |
4096 | n1 = tv_get_number_chk(rettv, &error); |
4097 | } |
4098 | tv_clear(rettv); |
4099 | if (error) { |
4100 | return FAIL; |
4101 | } |
4102 | } else { |
4103 | n1 = 0; |
4104 | } |
4105 | |
4106 | /* |
4107 | * Get the second variable. |
4108 | */ |
4109 | *arg = skipwhite(*arg + 1); |
4110 | if (eval7(arg, &var2, evaluate, FALSE) == FAIL) |
4111 | return FAIL; |
4112 | |
4113 | if (evaluate) { |
4114 | if (var2.v_type == VAR_FLOAT) { |
4115 | if (!use_float) { |
4116 | f1 = n1; |
4117 | use_float = true; |
4118 | } |
4119 | f2 = var2.vval.v_float; |
4120 | n2 = 0; |
4121 | } else { |
4122 | n2 = tv_get_number_chk(&var2, &error); |
4123 | tv_clear(&var2); |
4124 | if (error) { |
4125 | return FAIL; |
4126 | } |
4127 | if (use_float) { |
4128 | f2 = n2; |
4129 | } |
4130 | } |
4131 | |
4132 | /* |
4133 | * Compute the result. |
4134 | * When either side is a float the result is a float. |
4135 | */ |
4136 | if (use_float) { |
4137 | if (op == '*') { |
4138 | f1 = f1 * f2; |
4139 | } else if (op == '/') { |
4140 | // Division by zero triggers error from AddressSanitizer |
4141 | f1 = (f2 == 0 |
4142 | ? ( |
4143 | #ifdef NAN |
4144 | f1 == 0 |
4145 | ? NAN |
4146 | : |
4147 | #endif |
4148 | (f1 > 0 |
4149 | ? INFINITY |
4150 | : -INFINITY) |
4151 | ) |
4152 | : f1 / f2); |
4153 | } else { |
4154 | EMSG(_("E804: Cannot use '%' with Float" )); |
4155 | return FAIL; |
4156 | } |
4157 | rettv->v_type = VAR_FLOAT; |
4158 | rettv->vval.v_float = f1; |
4159 | } else { |
4160 | if (op == '*') { |
4161 | n1 = n1 * n2; |
4162 | } else if (op == '/') { |
4163 | n1 = num_divide(n1, n2); |
4164 | } else { |
4165 | n1 = num_modulus(n1, n2); |
4166 | } |
4167 | rettv->v_type = VAR_NUMBER; |
4168 | rettv->vval.v_number = n1; |
4169 | } |
4170 | } |
4171 | } |
4172 | |
4173 | return OK; |
4174 | } |
4175 | |
4176 | // TODO(ZyX-I): move to eval/expressions |
4177 | |
4178 | // Handle sixth level expression: |
4179 | // number number constant |
4180 | // "string" string constant |
4181 | // 'string' literal string constant |
4182 | // &option-name option value |
4183 | // @r register contents |
4184 | // identifier variable value |
4185 | // function() function call |
4186 | // $VAR environment variable |
4187 | // (expression) nested expression |
4188 | // [expr, expr] List |
4189 | // {key: val, key: val} Dictionary |
4190 | // |
4191 | // Also handle: |
4192 | // ! in front logical NOT |
4193 | // - in front unary minus |
4194 | // + in front unary plus (ignored) |
4195 | // trailing [] subscript in String or List |
4196 | // trailing .name entry in Dictionary |
4197 | // |
4198 | // "arg" must point to the first non-white of the expression. |
4199 | // "arg" is advanced to the next non-white after the recognized expression. |
4200 | // |
4201 | // Return OK or FAIL. |
4202 | static int eval7( |
4203 | char_u **arg, |
4204 | typval_T *rettv, |
4205 | int evaluate, |
4206 | int want_string // after "." operator |
4207 | ) |
4208 | { |
4209 | varnumber_T n; |
4210 | int len; |
4211 | char_u *s; |
4212 | char_u *start_leader, *end_leader; |
4213 | int ret = OK; |
4214 | char_u *alias; |
4215 | |
4216 | // Initialise variable so that tv_clear() can't mistake this for a |
4217 | // string and free a string that isn't there. |
4218 | rettv->v_type = VAR_UNKNOWN; |
4219 | |
4220 | // Skip '!', '-' and '+' characters. They are handled later. |
4221 | start_leader = *arg; |
4222 | while (**arg == '!' || **arg == '-' || **arg == '+') { |
4223 | *arg = skipwhite(*arg + 1); |
4224 | } |
4225 | end_leader = *arg; |
4226 | |
4227 | switch (**arg) { |
4228 | // Number constant. |
4229 | case '0': |
4230 | case '1': |
4231 | case '2': |
4232 | case '3': |
4233 | case '4': |
4234 | case '5': |
4235 | case '6': |
4236 | case '7': |
4237 | case '8': |
4238 | case '9': |
4239 | { |
4240 | char_u *p = skipdigits(*arg + 1); |
4241 | int get_float = false; |
4242 | |
4243 | // We accept a float when the format matches |
4244 | // "[0-9]\+\.[0-9]\+\([eE][+-]\?[0-9]\+\)\?". This is very |
4245 | // strict to avoid backwards compatibility problems. |
4246 | // Don't look for a float after the "." operator, so that |
4247 | // ":let vers = 1.2.3" doesn't fail. |
4248 | if (!want_string && p[0] == '.' && ascii_isdigit(p[1])) { |
4249 | get_float = true; |
4250 | p = skipdigits(p + 2); |
4251 | if (*p == 'e' || *p == 'E') { |
4252 | ++p; |
4253 | if (*p == '-' || *p == '+') { |
4254 | ++p; |
4255 | } |
4256 | if (!ascii_isdigit(*p)) { |
4257 | get_float = false; |
4258 | } else { |
4259 | p = skipdigits(p + 1); |
4260 | } |
4261 | } |
4262 | if (ASCII_ISALPHA(*p) || *p == '.') { |
4263 | get_float = false; |
4264 | } |
4265 | } |
4266 | if (get_float) { |
4267 | float_T f; |
4268 | |
4269 | *arg += string2float((char *) *arg, &f); |
4270 | if (evaluate) { |
4271 | rettv->v_type = VAR_FLOAT; |
4272 | rettv->vval.v_float = f; |
4273 | } |
4274 | } else { |
4275 | vim_str2nr(*arg, NULL, &len, STR2NR_ALL, &n, NULL, 0); |
4276 | *arg += len; |
4277 | if (evaluate) { |
4278 | rettv->v_type = VAR_NUMBER; |
4279 | rettv->vval.v_number = n; |
4280 | } |
4281 | } |
4282 | break; |
4283 | } |
4284 | |
4285 | // String constant: "string". |
4286 | case '"': ret = get_string_tv(arg, rettv, evaluate); |
4287 | break; |
4288 | |
4289 | // Literal string constant: 'str''ing'. |
4290 | case '\'': ret = get_lit_string_tv(arg, rettv, evaluate); |
4291 | break; |
4292 | |
4293 | // List: [expr, expr] |
4294 | case '[': ret = get_list_tv(arg, rettv, evaluate); |
4295 | break; |
4296 | |
4297 | // Lambda: {arg, arg -> expr} |
4298 | // Dictionary: {key: val, key: val} |
4299 | case '{': ret = get_lambda_tv(arg, rettv, evaluate); |
4300 | if (ret == NOTDONE) { |
4301 | ret = dict_get_tv(arg, rettv, evaluate); |
4302 | } |
4303 | break; |
4304 | |
4305 | // Option value: &name |
4306 | case '&': { |
4307 | ret = get_option_tv((const char **)arg, rettv, evaluate); |
4308 | break; |
4309 | } |
4310 | // Environment variable: $VAR. |
4311 | case '$': ret = get_env_tv(arg, rettv, evaluate); |
4312 | break; |
4313 | |
4314 | // Register contents: @r. |
4315 | case '@': ++*arg; |
4316 | if (evaluate) { |
4317 | rettv->v_type = VAR_STRING; |
4318 | rettv->vval.v_string = get_reg_contents(**arg, kGRegExprSrc); |
4319 | } |
4320 | if (**arg != NUL) { |
4321 | ++*arg; |
4322 | } |
4323 | break; |
4324 | |
4325 | // nested expression: (expression). |
4326 | case '(': *arg = skipwhite(*arg + 1); |
4327 | ret = eval1(arg, rettv, evaluate); // recursive! |
4328 | if (**arg == ')') { |
4329 | ++*arg; |
4330 | } else if (ret == OK) { |
4331 | EMSG(_("E110: Missing ')'" )); |
4332 | tv_clear(rettv); |
4333 | ret = FAIL; |
4334 | } |
4335 | break; |
4336 | |
4337 | default: ret = NOTDONE; |
4338 | break; |
4339 | } |
4340 | |
4341 | if (ret == NOTDONE) { |
4342 | // Must be a variable or function name. |
4343 | // Can also be a curly-braces kind of name: {expr}. |
4344 | s = *arg; |
4345 | len = get_name_len((const char **)arg, (char **)&alias, evaluate, true); |
4346 | if (alias != NULL) { |
4347 | s = alias; |
4348 | } |
4349 | |
4350 | if (len <= 0) { |
4351 | ret = FAIL; |
4352 | } else { |
4353 | if (**arg == '(') { // recursive! |
4354 | partial_T *partial; |
4355 | |
4356 | if (!evaluate) { |
4357 | check_vars((const char *)s, len); |
4358 | } |
4359 | |
4360 | // If "s" is the name of a variable of type VAR_FUNC |
4361 | // use its contents. |
4362 | s = deref_func_name((const char *)s, &len, &partial, !evaluate); |
4363 | |
4364 | // Need to make a copy, in case evaluating the arguments makes |
4365 | // the name invalid. |
4366 | s = xmemdupz(s, len); |
4367 | |
4368 | // Invoke the function. |
4369 | ret = get_func_tv(s, len, rettv, arg, |
4370 | curwin->w_cursor.lnum, curwin->w_cursor.lnum, |
4371 | &len, evaluate, partial, NULL); |
4372 | |
4373 | xfree(s); |
4374 | |
4375 | // If evaluate is false rettv->v_type was not set in |
4376 | // get_func_tv, but it's needed in handle_subscript() to parse |
4377 | // what follows. So set it here. |
4378 | if (rettv->v_type == VAR_UNKNOWN && !evaluate && **arg == '(') { |
4379 | rettv->vval.v_string = (char_u *)tv_empty_string; |
4380 | rettv->v_type = VAR_FUNC; |
4381 | } |
4382 | |
4383 | // Stop the expression evaluation when immediately |
4384 | // aborting on error, or when an interrupt occurred or |
4385 | // an exception was thrown but not caught. |
4386 | if (evaluate && aborting()) { |
4387 | if (ret == OK) { |
4388 | tv_clear(rettv); |
4389 | } |
4390 | ret = FAIL; |
4391 | } |
4392 | } else if (evaluate) { |
4393 | ret = get_var_tv((const char *)s, len, rettv, NULL, true, false); |
4394 | } else { |
4395 | check_vars((const char *)s, len); |
4396 | ret = OK; |
4397 | } |
4398 | } |
4399 | xfree(alias); |
4400 | } |
4401 | |
4402 | *arg = skipwhite(*arg); |
4403 | |
4404 | // Handle following '[', '(' and '.' for expr[expr], expr.name, |
4405 | // expr(expr). |
4406 | if (ret == OK) { |
4407 | ret = handle_subscript((const char **)arg, rettv, evaluate, true); |
4408 | } |
4409 | |
4410 | // Apply logical NOT and unary '-', from right to left, ignore '+'. |
4411 | if (ret == OK && evaluate && end_leader > start_leader) { |
4412 | bool error = false; |
4413 | varnumber_T val = 0; |
4414 | float_T f = 0.0; |
4415 | |
4416 | if (rettv->v_type == VAR_FLOAT) { |
4417 | f = rettv->vval.v_float; |
4418 | } else { |
4419 | val = tv_get_number_chk(rettv, &error); |
4420 | } |
4421 | if (error) { |
4422 | tv_clear(rettv); |
4423 | ret = FAIL; |
4424 | } else { |
4425 | while (end_leader > start_leader) { |
4426 | --end_leader; |
4427 | if (*end_leader == '!') { |
4428 | if (rettv->v_type == VAR_FLOAT) { |
4429 | f = !f; |
4430 | } else { |
4431 | val = !val; |
4432 | } |
4433 | } else if (*end_leader == '-') { |
4434 | if (rettv->v_type == VAR_FLOAT) { |
4435 | f = -f; |
4436 | } else { |
4437 | val = -val; |
4438 | } |
4439 | } |
4440 | } |
4441 | if (rettv->v_type == VAR_FLOAT) { |
4442 | tv_clear(rettv); |
4443 | rettv->vval.v_float = f; |
4444 | } else { |
4445 | tv_clear(rettv); |
4446 | rettv->v_type = VAR_NUMBER; |
4447 | rettv->vval.v_number = val; |
4448 | } |
4449 | } |
4450 | } |
4451 | |
4452 | return ret; |
4453 | } |
4454 | |
4455 | // TODO(ZyX-I): move to eval/expressions |
4456 | |
4457 | /* |
4458 | * Evaluate an "[expr]" or "[expr:expr]" index. Also "dict.key". |
4459 | * "*arg" points to the '[' or '.'. |
4460 | * Returns FAIL or OK. "*arg" is advanced to after the ']'. |
4461 | */ |
4462 | static int |
4463 | eval_index( |
4464 | char_u **arg, |
4465 | typval_T *rettv, |
4466 | int evaluate, |
4467 | int verbose /* give error messages */ |
4468 | ) |
4469 | { |
4470 | bool empty1 = false; |
4471 | bool empty2 = false; |
4472 | long n1, n2 = 0; |
4473 | ptrdiff_t len = -1; |
4474 | int range = false; |
4475 | char_u *key = NULL; |
4476 | |
4477 | switch (rettv->v_type) { |
4478 | case VAR_FUNC: |
4479 | case VAR_PARTIAL: { |
4480 | if (verbose) { |
4481 | EMSG(_("E695: Cannot index a Funcref" )); |
4482 | } |
4483 | return FAIL; |
4484 | } |
4485 | case VAR_FLOAT: { |
4486 | if (verbose) { |
4487 | EMSG(_(e_float_as_string)); |
4488 | } |
4489 | return FAIL; |
4490 | } |
4491 | case VAR_SPECIAL: { |
4492 | if (verbose) { |
4493 | EMSG(_("E909: Cannot index a special variable" )); |
4494 | } |
4495 | return FAIL; |
4496 | } |
4497 | case VAR_UNKNOWN: { |
4498 | if (evaluate) { |
4499 | return FAIL; |
4500 | } |
4501 | FALLTHROUGH; |
4502 | } |
4503 | case VAR_STRING: |
4504 | case VAR_NUMBER: |
4505 | case VAR_LIST: |
4506 | case VAR_DICT: { |
4507 | break; |
4508 | } |
4509 | } |
4510 | |
4511 | typval_T var1 = TV_INITIAL_VALUE; |
4512 | typval_T var2 = TV_INITIAL_VALUE; |
4513 | if (**arg == '.') { |
4514 | /* |
4515 | * dict.name |
4516 | */ |
4517 | key = *arg + 1; |
4518 | for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len) |
4519 | ; |
4520 | if (len == 0) |
4521 | return FAIL; |
4522 | *arg = skipwhite(key + len); |
4523 | } else { |
4524 | /* |
4525 | * something[idx] |
4526 | * |
4527 | * Get the (first) variable from inside the []. |
4528 | */ |
4529 | *arg = skipwhite(*arg + 1); |
4530 | if (**arg == ':') { |
4531 | empty1 = true; |
4532 | } else if (eval1(arg, &var1, evaluate) == FAIL) { // Recursive! |
4533 | return FAIL; |
4534 | } else if (evaluate && !tv_check_str(&var1)) { |
4535 | // Not a number or string. |
4536 | tv_clear(&var1); |
4537 | return FAIL; |
4538 | } |
4539 | |
4540 | /* |
4541 | * Get the second variable from inside the [:]. |
4542 | */ |
4543 | if (**arg == ':') { |
4544 | range = TRUE; |
4545 | *arg = skipwhite(*arg + 1); |
4546 | if (**arg == ']') { |
4547 | empty2 = true; |
4548 | } else if (eval1(arg, &var2, evaluate) == FAIL) { // Recursive! |
4549 | if (!empty1) { |
4550 | tv_clear(&var1); |
4551 | } |
4552 | return FAIL; |
4553 | } else if (evaluate && !tv_check_str(&var2)) { |
4554 | // Not a number or string. |
4555 | if (!empty1) { |
4556 | tv_clear(&var1); |
4557 | } |
4558 | tv_clear(&var2); |
4559 | return FAIL; |
4560 | } |
4561 | } |
4562 | |
4563 | /* Check for the ']'. */ |
4564 | if (**arg != ']') { |
4565 | if (verbose) { |
4566 | EMSG(_(e_missbrac)); |
4567 | } |
4568 | tv_clear(&var1); |
4569 | if (range) { |
4570 | tv_clear(&var2); |
4571 | } |
4572 | return FAIL; |
4573 | } |
4574 | *arg = skipwhite(*arg + 1); /* skip the ']' */ |
4575 | } |
4576 | |
4577 | if (evaluate) { |
4578 | n1 = 0; |
4579 | if (!empty1 && rettv->v_type != VAR_DICT) { |
4580 | n1 = tv_get_number(&var1); |
4581 | tv_clear(&var1); |
4582 | } |
4583 | if (range) { |
4584 | if (empty2) { |
4585 | n2 = -1; |
4586 | } else { |
4587 | n2 = tv_get_number(&var2); |
4588 | tv_clear(&var2); |
4589 | } |
4590 | } |
4591 | |
4592 | switch (rettv->v_type) { |
4593 | case VAR_NUMBER: |
4594 | case VAR_STRING: { |
4595 | const char *const s = tv_get_string(rettv); |
4596 | char *v; |
4597 | len = (ptrdiff_t)strlen(s); |
4598 | if (range) { |
4599 | // The resulting variable is a substring. If the indexes |
4600 | // are out of range the result is empty. |
4601 | if (n1 < 0) { |
4602 | n1 = len + n1; |
4603 | if (n1 < 0) { |
4604 | n1 = 0; |
4605 | } |
4606 | } |
4607 | if (n2 < 0) { |
4608 | n2 = len + n2; |
4609 | } else if (n2 >= len) { |
4610 | n2 = len; |
4611 | } |
4612 | if (n1 >= len || n2 < 0 || n1 > n2) { |
4613 | v = NULL; |
4614 | } else { |
4615 | v = xmemdupz(s + n1, (size_t)(n2 - n1 + 1)); |
4616 | } |
4617 | } else { |
4618 | // The resulting variable is a string of a single |
4619 | // character. If the index is too big or negative the |
4620 | // result is empty. |
4621 | if (n1 >= len || n1 < 0) { |
4622 | v = NULL; |
4623 | } else { |
4624 | v = xmemdupz(s + n1, 1); |
4625 | } |
4626 | } |
4627 | tv_clear(rettv); |
4628 | rettv->v_type = VAR_STRING; |
4629 | rettv->vval.v_string = (char_u *)v; |
4630 | break; |
4631 | } |
4632 | case VAR_LIST: { |
4633 | len = tv_list_len(rettv->vval.v_list); |
4634 | if (n1 < 0) { |
4635 | n1 = len + n1; |
4636 | } |
4637 | if (!empty1 && (n1 < 0 || n1 >= len)) { |
4638 | // For a range we allow invalid values and return an empty |
4639 | // list. A list index out of range is an error. |
4640 | if (!range) { |
4641 | if (verbose) { |
4642 | EMSGN(_(e_listidx), n1); |
4643 | } |
4644 | return FAIL; |
4645 | } |
4646 | n1 = len; |
4647 | } |
4648 | if (range) { |
4649 | list_T *l; |
4650 | listitem_T *item; |
4651 | |
4652 | if (n2 < 0) { |
4653 | n2 = len + n2; |
4654 | } else if (n2 >= len) { |
4655 | n2 = len - 1; |
4656 | } |
4657 | if (!empty2 && (n2 < 0 || n2 + 1 < n1)) { |
4658 | n2 = -1; |
4659 | } |
4660 | l = tv_list_alloc(n2 - n1 + 1); |
4661 | item = tv_list_find(rettv->vval.v_list, n1); |
4662 | while (n1++ <= n2) { |
4663 | tv_list_append_tv(l, TV_LIST_ITEM_TV(item)); |
4664 | item = TV_LIST_ITEM_NEXT(rettv->vval.v_list, item); |
4665 | } |
4666 | tv_clear(rettv); |
4667 | tv_list_set_ret(rettv, l); |
4668 | } else { |
4669 | tv_copy(TV_LIST_ITEM_TV(tv_list_find(rettv->vval.v_list, n1)), &var1); |
4670 | tv_clear(rettv); |
4671 | *rettv = var1; |
4672 | } |
4673 | break; |
4674 | } |
4675 | case VAR_DICT: { |
4676 | if (range) { |
4677 | if (verbose) { |
4678 | EMSG(_(e_dictrange)); |
4679 | } |
4680 | if (len == -1) { |
4681 | tv_clear(&var1); |
4682 | } |
4683 | return FAIL; |
4684 | } |
4685 | |
4686 | if (len == -1) { |
4687 | key = (char_u *)tv_get_string_chk(&var1); |
4688 | if (key == NULL) { |
4689 | tv_clear(&var1); |
4690 | return FAIL; |
4691 | } |
4692 | } |
4693 | |
4694 | dictitem_T *const item = tv_dict_find(rettv->vval.v_dict, |
4695 | (const char *)key, len); |
4696 | |
4697 | if (item == NULL && verbose) { |
4698 | emsgf(_(e_dictkey), key); |
4699 | } |
4700 | if (len == -1) { |
4701 | tv_clear(&var1); |
4702 | } |
4703 | if (item == NULL) { |
4704 | return FAIL; |
4705 | } |
4706 | |
4707 | tv_copy(&item->di_tv, &var1); |
4708 | tv_clear(rettv); |
4709 | *rettv = var1; |
4710 | break; |
4711 | } |
4712 | case VAR_SPECIAL: |
4713 | case VAR_FUNC: |
4714 | case VAR_FLOAT: |
4715 | case VAR_PARTIAL: |
4716 | case VAR_UNKNOWN: { |
4717 | break; // Not evaluating, skipping over subscript |
4718 | } |
4719 | } |
4720 | } |
4721 | |
4722 | return OK; |
4723 | } |
4724 | |
4725 | // TODO(ZyX-I): move to eval/executor |
4726 | |
4727 | /// Get an option value |
4728 | /// |
4729 | /// @param[in,out] arg Points to the '&' or '+' before the option name. Is |
4730 | /// advanced to the character after the option name. |
4731 | /// @param[out] rettv Location where result is saved. |
4732 | /// @param[in] evaluate If not true, rettv is not populated. |
4733 | /// |
4734 | /// @return OK or FAIL. |
4735 | static int get_option_tv(const char **const arg, typval_T *const rettv, |
4736 | const bool evaluate) |
4737 | FUNC_ATTR_NONNULL_ARG(1) |
4738 | { |
4739 | long numval; |
4740 | char_u *stringval; |
4741 | int opt_type; |
4742 | int c; |
4743 | bool working = (**arg == '+'); // has("+option") |
4744 | int ret = OK; |
4745 | int opt_flags; |
4746 | |
4747 | // Isolate the option name and find its value. |
4748 | char *option_end = (char *)find_option_end(arg, &opt_flags); |
4749 | if (option_end == NULL) { |
4750 | if (rettv != NULL) { |
4751 | EMSG2(_("E112: Option name missing: %s" ), *arg); |
4752 | } |
4753 | return FAIL; |
4754 | } |
4755 | |
4756 | if (!evaluate) { |
4757 | *arg = option_end; |
4758 | return OK; |
4759 | } |
4760 | |
4761 | c = *option_end; |
4762 | *option_end = NUL; |
4763 | opt_type = get_option_value((char_u *)(*arg), &numval, |
4764 | rettv == NULL ? NULL : &stringval, opt_flags); |
4765 | |
4766 | if (opt_type == -3) { /* invalid name */ |
4767 | if (rettv != NULL) |
4768 | EMSG2(_("E113: Unknown option: %s" ), *arg); |
4769 | ret = FAIL; |
4770 | } else if (rettv != NULL) { |
4771 | if (opt_type == -2) { /* hidden string option */ |
4772 | rettv->v_type = VAR_STRING; |
4773 | rettv->vval.v_string = NULL; |
4774 | } else if (opt_type == -1) { /* hidden number option */ |
4775 | rettv->v_type = VAR_NUMBER; |
4776 | rettv->vval.v_number = 0; |
4777 | } else if (opt_type == 1) { /* number option */ |
4778 | rettv->v_type = VAR_NUMBER; |
4779 | rettv->vval.v_number = numval; |
4780 | } else { /* string option */ |
4781 | rettv->v_type = VAR_STRING; |
4782 | rettv->vval.v_string = stringval; |
4783 | } |
4784 | } else if (working && (opt_type == -2 || opt_type == -1)) |
4785 | ret = FAIL; |
4786 | |
4787 | *option_end = c; /* put back for error messages */ |
4788 | *arg = option_end; |
4789 | |
4790 | return ret; |
4791 | } |
4792 | |
4793 | /* |
4794 | * Allocate a variable for a string constant. |
4795 | * Return OK or FAIL. |
4796 | */ |
4797 | static int get_string_tv(char_u **arg, typval_T *rettv, int evaluate) |
4798 | { |
4799 | char_u *p; |
4800 | char_u *name; |
4801 | unsigned int = 0; |
4802 | |
4803 | /* |
4804 | * Find the end of the string, skipping backslashed characters. |
4805 | */ |
4806 | for (p = *arg + 1; *p != NUL && *p != '"'; MB_PTR_ADV(p)) { |
4807 | if (*p == '\\' && p[1] != NUL) { |
4808 | ++p; |
4809 | /* A "\<x>" form occupies at least 4 characters, and produces up |
4810 | * to 6 characters: reserve space for 2 extra */ |
4811 | if (*p == '<') |
4812 | extra += 2; |
4813 | } |
4814 | } |
4815 | |
4816 | if (*p != '"') { |
4817 | EMSG2(_("E114: Missing quote: %s" ), *arg); |
4818 | return FAIL; |
4819 | } |
4820 | |
4821 | /* If only parsing, set *arg and return here */ |
4822 | if (!evaluate) { |
4823 | *arg = p + 1; |
4824 | return OK; |
4825 | } |
4826 | |
4827 | /* |
4828 | * Copy the string into allocated memory, handling backslashed |
4829 | * characters. |
4830 | */ |
4831 | name = xmalloc(p - *arg + extra); |
4832 | rettv->v_type = VAR_STRING; |
4833 | rettv->vval.v_string = name; |
4834 | |
4835 | for (p = *arg + 1; *p != NUL && *p != '"'; ) { |
4836 | if (*p == '\\') { |
4837 | switch (*++p) { |
4838 | case 'b': *name++ = BS; ++p; break; |
4839 | case 'e': *name++ = ESC; ++p; break; |
4840 | case 'f': *name++ = FF; ++p; break; |
4841 | case 'n': *name++ = NL; ++p; break; |
4842 | case 'r': *name++ = CAR; ++p; break; |
4843 | case 't': *name++ = TAB; ++p; break; |
4844 | |
4845 | case 'X': /* hex: "\x1", "\x12" */ |
4846 | case 'x': |
4847 | case 'u': /* Unicode: "\u0023" */ |
4848 | case 'U': |
4849 | if (ascii_isxdigit(p[1])) { |
4850 | int n, nr; |
4851 | int c = toupper(*p); |
4852 | |
4853 | if (c == 'X') { |
4854 | n = 2; |
4855 | } else if (*p == 'u') { |
4856 | n = 4; |
4857 | } else { |
4858 | n = 8; |
4859 | } |
4860 | nr = 0; |
4861 | while (--n >= 0 && ascii_isxdigit(p[1])) { |
4862 | ++p; |
4863 | nr = (nr << 4) + hex2nr(*p); |
4864 | } |
4865 | ++p; |
4866 | /* For "\u" store the number according to |
4867 | * 'encoding'. */ |
4868 | if (c != 'X') { |
4869 | name += utf_char2bytes(nr, name); |
4870 | } else { |
4871 | *name++ = nr; |
4872 | } |
4873 | } |
4874 | break; |
4875 | |
4876 | /* octal: "\1", "\12", "\123" */ |
4877 | case '0': |
4878 | case '1': |
4879 | case '2': |
4880 | case '3': |
4881 | case '4': |
4882 | case '5': |
4883 | case '6': |
4884 | case '7': *name = *p++ - '0'; |
4885 | if (*p >= '0' && *p <= '7') { |
4886 | *name = (*name << 3) + *p++ - '0'; |
4887 | if (*p >= '0' && *p <= '7') |
4888 | *name = (*name << 3) + *p++ - '0'; |
4889 | } |
4890 | ++name; |
4891 | break; |
4892 | |
4893 | // Special key, e.g.: "\<C-W>" |
4894 | case '<': |
4895 | extra = trans_special((const char_u **)&p, STRLEN(p), name, true, true); |
4896 | if (extra != 0) { |
4897 | name += extra; |
4898 | break; |
4899 | } |
4900 | FALLTHROUGH; |
4901 | |
4902 | default: MB_COPY_CHAR(p, name); |
4903 | break; |
4904 | } |
4905 | } else |
4906 | MB_COPY_CHAR(p, name); |
4907 | |
4908 | } |
4909 | *name = NUL; |
4910 | if (*p != NUL) { // just in case |
4911 | p++; |
4912 | } |
4913 | *arg = p; |
4914 | |
4915 | return OK; |
4916 | } |
4917 | |
4918 | /* |
4919 | * Allocate a variable for a 'str''ing' constant. |
4920 | * Return OK or FAIL. |
4921 | */ |
4922 | static int get_lit_string_tv(char_u **arg, typval_T *rettv, int evaluate) |
4923 | { |
4924 | char_u *p; |
4925 | char_u *str; |
4926 | int reduce = 0; |
4927 | |
4928 | /* |
4929 | * Find the end of the string, skipping ''. |
4930 | */ |
4931 | for (p = *arg + 1; *p != NUL; MB_PTR_ADV(p)) { |
4932 | if (*p == '\'') { |
4933 | if (p[1] != '\'') |
4934 | break; |
4935 | ++reduce; |
4936 | ++p; |
4937 | } |
4938 | } |
4939 | |
4940 | if (*p != '\'') { |
4941 | EMSG2(_("E115: Missing quote: %s" ), *arg); |
4942 | return FAIL; |
4943 | } |
4944 | |
4945 | /* If only parsing return after setting "*arg" */ |
4946 | if (!evaluate) { |
4947 | *arg = p + 1; |
4948 | return OK; |
4949 | } |
4950 | |
4951 | /* |
4952 | * Copy the string into allocated memory, handling '' to ' reduction. |
4953 | */ |
4954 | str = xmalloc((p - *arg) - reduce); |
4955 | rettv->v_type = VAR_STRING; |
4956 | rettv->vval.v_string = str; |
4957 | |
4958 | for (p = *arg + 1; *p != NUL; ) { |
4959 | if (*p == '\'') { |
4960 | if (p[1] != '\'') |
4961 | break; |
4962 | ++p; |
4963 | } |
4964 | MB_COPY_CHAR(p, str); |
4965 | } |
4966 | *str = NUL; |
4967 | *arg = p + 1; |
4968 | |
4969 | return OK; |
4970 | } |
4971 | |
4972 | /// @return the function name of the partial. |
4973 | char_u *partial_name(partial_T *pt) |
4974 | { |
4975 | if (pt->pt_name != NULL) { |
4976 | return pt->pt_name; |
4977 | } |
4978 | return pt->pt_func->uf_name; |
4979 | } |
4980 | |
4981 | // TODO(ZyX-I): Move to eval/typval.h |
4982 | |
4983 | static void partial_free(partial_T *pt) |
4984 | { |
4985 | for (int i = 0; i < pt->pt_argc; i++) { |
4986 | tv_clear(&pt->pt_argv[i]); |
4987 | } |
4988 | xfree(pt->pt_argv); |
4989 | tv_dict_unref(pt->pt_dict); |
4990 | if (pt->pt_name != NULL) { |
4991 | func_unref(pt->pt_name); |
4992 | xfree(pt->pt_name); |
4993 | } else { |
4994 | func_ptr_unref(pt->pt_func); |
4995 | } |
4996 | xfree(pt); |
4997 | } |
4998 | |
4999 | // TODO(ZyX-I): Move to eval/typval.h |
5000 | |
5001 | /// Unreference a closure: decrement the reference count and free it when it |
5002 | /// becomes zero. |
5003 | void partial_unref(partial_T *pt) |
5004 | { |
5005 | if (pt != NULL && --pt->pt_refcount <= 0) { |
5006 | partial_free(pt); |
5007 | } |
5008 | } |
5009 | |
5010 | /// Allocate a variable for a List and fill it from "*arg". |
5011 | /// Return OK or FAIL. |
5012 | static int get_list_tv(char_u **arg, typval_T *rettv, int evaluate) |
5013 | { |
5014 | list_T *l = NULL; |
5015 | |
5016 | if (evaluate) { |
5017 | l = tv_list_alloc(kListLenShouldKnow); |
5018 | } |
5019 | |
5020 | *arg = skipwhite(*arg + 1); |
5021 | while (**arg != ']' && **arg != NUL) { |
5022 | typval_T tv; |
5023 | if (eval1(arg, &tv, evaluate) == FAIL) { // Recursive! |
5024 | goto failret; |
5025 | } |
5026 | if (evaluate) { |
5027 | tv.v_lock = VAR_UNLOCKED; |
5028 | tv_list_append_owned_tv(l, tv); |
5029 | } |
5030 | |
5031 | if (**arg == ']') { |
5032 | break; |
5033 | } |
5034 | if (**arg != ',') { |
5035 | emsgf(_("E696: Missing comma in List: %s" ), *arg); |
5036 | goto failret; |
5037 | } |
5038 | *arg = skipwhite(*arg + 1); |
5039 | } |
5040 | |
5041 | if (**arg != ']') { |
5042 | emsgf(_("E697: Missing end of List ']': %s" ), *arg); |
5043 | failret: |
5044 | if (evaluate) { |
5045 | tv_list_free(l); |
5046 | } |
5047 | return FAIL; |
5048 | } |
5049 | |
5050 | *arg = skipwhite(*arg + 1); |
5051 | if (evaluate) { |
5052 | tv_list_set_ret(rettv, l); |
5053 | } |
5054 | |
5055 | return OK; |
5056 | } |
5057 | |
5058 | bool func_equal( |
5059 | typval_T *tv1, |
5060 | typval_T *tv2, |
5061 | bool ic // ignore case |
5062 | ) { |
5063 | char_u *s1, *s2; |
5064 | dict_T *d1, *d2; |
5065 | int a1, a2; |
5066 | |
5067 | // empty and NULL function name considered the same |
5068 | s1 = tv1->v_type == VAR_FUNC ? tv1->vval.v_string |
5069 | : partial_name(tv1->vval.v_partial); |
5070 | if (s1 != NULL && *s1 == NUL) { |
5071 | s1 = NULL; |
5072 | } |
5073 | s2 = tv2->v_type == VAR_FUNC ? tv2->vval.v_string |
5074 | : partial_name(tv2->vval.v_partial); |
5075 | if (s2 != NULL && *s2 == NUL) { |
5076 | s2 = NULL; |
5077 | } |
5078 | if (s1 == NULL || s2 == NULL) { |
5079 | if (s1 != s2) { |
5080 | return false; |
5081 | } |
5082 | } else if (STRCMP(s1, s2) != 0) { |
5083 | return false; |
5084 | } |
5085 | |
5086 | // empty dict and NULL dict is different |
5087 | d1 = tv1->v_type == VAR_FUNC ? NULL : tv1->vval.v_partial->pt_dict; |
5088 | d2 = tv2->v_type == VAR_FUNC ? NULL : tv2->vval.v_partial->pt_dict; |
5089 | if (d1 == NULL || d2 == NULL) { |
5090 | if (d1 != d2) { |
5091 | return false; |
5092 | } |
5093 | } else if (!tv_dict_equal(d1, d2, ic, true)) { |
5094 | return false; |
5095 | } |
5096 | |
5097 | // empty list and no list considered the same |
5098 | a1 = tv1->v_type == VAR_FUNC ? 0 : tv1->vval.v_partial->pt_argc; |
5099 | a2 = tv2->v_type == VAR_FUNC ? 0 : tv2->vval.v_partial->pt_argc; |
5100 | if (a1 != a2) { |
5101 | return false; |
5102 | } |
5103 | for (int i = 0; i < a1; i++) { |
5104 | if (!tv_equal(tv1->vval.v_partial->pt_argv + i, |
5105 | tv2->vval.v_partial->pt_argv + i, ic, true)) { |
5106 | return false; |
5107 | } |
5108 | } |
5109 | return true; |
5110 | } |
5111 | |
5112 | /// Get next (unique) copy ID |
5113 | /// |
5114 | /// Used for traversing nested structures e.g. when serializing them or garbage |
5115 | /// collecting. |
5116 | int get_copyID(void) |
5117 | FUNC_ATTR_WARN_UNUSED_RESULT |
5118 | { |
5119 | // CopyID for recursively traversing lists and dicts |
5120 | // |
5121 | // This value is needed to avoid endless recursiveness. Last bit is used for |
5122 | // previous_funccal and normally ignored when comparing. |
5123 | static int current_copyID = 0; |
5124 | current_copyID += COPYID_INC; |
5125 | return current_copyID; |
5126 | } |
5127 | |
5128 | // Used by get_func_tv() |
5129 | static garray_T funcargs = GA_EMPTY_INIT_VALUE; |
5130 | |
5131 | /* |
5132 | * Garbage collection for lists and dictionaries. |
5133 | * |
5134 | * We use reference counts to be able to free most items right away when they |
5135 | * are no longer used. But for composite items it's possible that it becomes |
5136 | * unused while the reference count is > 0: When there is a recursive |
5137 | * reference. Example: |
5138 | * :let l = [1, 2, 3] |
5139 | * :let d = {9: l} |
5140 | * :let l[1] = d |
5141 | * |
5142 | * Since this is quite unusual we handle this with garbage collection: every |
5143 | * once in a while find out which lists and dicts are not referenced from any |
5144 | * variable. |
5145 | * |
5146 | * Here is a good reference text about garbage collection (refers to Python |
5147 | * but it applies to all reference-counting mechanisms): |
5148 | * http://python.ca/nas/python/gc/ |
5149 | */ |
5150 | |
5151 | /// Do garbage collection for lists and dicts. |
5152 | /// |
5153 | /// @param testing true if called from test_garbagecollect_now(). |
5154 | /// @returns true if some memory was freed. |
5155 | bool garbage_collect(bool testing) |
5156 | { |
5157 | bool abort = false; |
5158 | #define ABORTING(func) abort = abort || func |
5159 | |
5160 | if (!testing) { |
5161 | // Only do this once. |
5162 | want_garbage_collect = false; |
5163 | may_garbage_collect = false; |
5164 | garbage_collect_at_exit = false; |
5165 | } |
5166 | |
5167 | // We advance by two (COPYID_INC) because we add one for items referenced |
5168 | // through previous_funccal. |
5169 | const int copyID = get_copyID(); |
5170 | |
5171 | // 1. Go through all accessible variables and mark all lists and dicts |
5172 | // with copyID. |
5173 | |
5174 | // Don't free variables in the previous_funccal list unless they are only |
5175 | // referenced through previous_funccal. This must be first, because if |
5176 | // the item is referenced elsewhere the funccal must not be freed. |
5177 | for (funccall_T *fc = previous_funccal; fc != NULL; fc = fc->caller) { |
5178 | fc->fc_copyID = copyID + 1; |
5179 | ABORTING(set_ref_in_ht)(&fc->l_vars.dv_hashtab, copyID + 1, NULL); |
5180 | ABORTING(set_ref_in_ht)(&fc->l_avars.dv_hashtab, copyID + 1, NULL); |
5181 | } |
5182 | |
5183 | // script-local variables |
5184 | for (int i = 1; i <= ga_scripts.ga_len; ++i) { |
5185 | ABORTING(set_ref_in_ht)(&SCRIPT_VARS(i), copyID, NULL); |
5186 | } |
5187 | |
5188 | FOR_ALL_BUFFERS(buf) { |
5189 | // buffer-local variables |
5190 | ABORTING(set_ref_in_item)(&buf->b_bufvar.di_tv, copyID, NULL, NULL); |
5191 | // buffer marks (ShaDa additional data) |
5192 | ABORTING(set_ref_in_fmark)(buf->b_last_cursor, copyID); |
5193 | ABORTING(set_ref_in_fmark)(buf->b_last_insert, copyID); |
5194 | ABORTING(set_ref_in_fmark)(buf->b_last_change, copyID); |
5195 | for (size_t i = 0; i < NMARKS; i++) { |
5196 | ABORTING(set_ref_in_fmark)(buf->b_namedm[i], copyID); |
5197 | } |
5198 | // buffer change list (ShaDa additional data) |
5199 | for (int i = 0; i < buf->b_changelistlen; i++) { |
5200 | ABORTING(set_ref_in_fmark)(buf->b_changelist[i], copyID); |
5201 | } |
5202 | // buffer ShaDa additional data |
5203 | ABORTING(set_ref_dict)(buf->additional_data, copyID); |
5204 | } |
5205 | |
5206 | FOR_ALL_TAB_WINDOWS(tp, wp) { |
5207 | // window-local variables |
5208 | ABORTING(set_ref_in_item)(&wp->w_winvar.di_tv, copyID, NULL, NULL); |
5209 | // window jump list (ShaDa additional data) |
5210 | for (int i = 0; i < wp->w_jumplistlen; i++) { |
5211 | ABORTING(set_ref_in_fmark)(wp->w_jumplist[i].fmark, copyID); |
5212 | } |
5213 | } |
5214 | if (aucmd_win != NULL) { |
5215 | ABORTING(set_ref_in_item)(&aucmd_win->w_winvar.di_tv, copyID, NULL, NULL); |
5216 | } |
5217 | |
5218 | // registers (ShaDa additional data) |
5219 | { |
5220 | const void *reg_iter = NULL; |
5221 | do { |
5222 | yankreg_T reg; |
5223 | char name = NUL; |
5224 | bool is_unnamed = false; |
5225 | reg_iter = op_global_reg_iter(reg_iter, &name, ®, &is_unnamed); |
5226 | if (name != NUL) { |
5227 | ABORTING(set_ref_dict)(reg.additional_data, copyID); |
5228 | } |
5229 | } while (reg_iter != NULL); |
5230 | } |
5231 | |
5232 | // global marks (ShaDa additional data) |
5233 | { |
5234 | const void *mark_iter = NULL; |
5235 | do { |
5236 | xfmark_T fm; |
5237 | char name = NUL; |
5238 | mark_iter = mark_global_iter(mark_iter, &name, &fm); |
5239 | if (name != NUL) { |
5240 | ABORTING(set_ref_dict)(fm.fmark.additional_data, copyID); |
5241 | } |
5242 | } while (mark_iter != NULL); |
5243 | } |
5244 | |
5245 | // tabpage-local variables |
5246 | FOR_ALL_TABS(tp) { |
5247 | ABORTING(set_ref_in_item)(&tp->tp_winvar.di_tv, copyID, NULL, NULL); |
5248 | } |
5249 | |
5250 | // global variables |
5251 | ABORTING(set_ref_in_ht)(&globvarht, copyID, NULL); |
5252 | |
5253 | // function-local variables |
5254 | for (funccall_T *fc = current_funccal; fc != NULL; fc = fc->caller) { |
5255 | fc->fc_copyID = copyID; |
5256 | ABORTING(set_ref_in_ht)(&fc->l_vars.dv_hashtab, copyID, NULL); |
5257 | ABORTING(set_ref_in_ht)(&fc->l_avars.dv_hashtab, copyID, NULL); |
5258 | } |
5259 | |
5260 | // named functions (matters for closures) |
5261 | ABORTING(set_ref_in_functions(copyID)); |
5262 | |
5263 | // Channels |
5264 | { |
5265 | Channel *data; |
5266 | map_foreach_value(channels, data, { |
5267 | set_ref_in_callback_reader(&data->on_data, copyID, NULL, NULL); |
5268 | set_ref_in_callback_reader(&data->on_stderr, copyID, NULL, NULL); |
5269 | set_ref_in_callback(&data->on_exit, copyID, NULL, NULL); |
5270 | }) |
5271 | } |
5272 | |
5273 | // Timers |
5274 | { |
5275 | timer_T *timer; |
5276 | map_foreach_value(timers, timer, { |
5277 | set_ref_in_callback(&timer->callback, copyID, NULL, NULL); |
5278 | }) |
5279 | } |
5280 | |
5281 | // function call arguments, if v:testing is set. |
5282 | for (int i = 0; i < funcargs.ga_len; i++) { |
5283 | ABORTING(set_ref_in_item)(((typval_T **)funcargs.ga_data)[i], |
5284 | copyID, NULL, NULL); |
5285 | } |
5286 | |
5287 | // v: vars |
5288 | ABORTING(set_ref_in_ht)(&vimvarht, copyID, NULL); |
5289 | |
5290 | // history items (ShaDa additional elements) |
5291 | if (p_hi) { |
5292 | for (uint8_t i = 0; i < HIST_COUNT; i++) { |
5293 | const void *iter = NULL; |
5294 | do { |
5295 | histentry_T hist; |
5296 | iter = hist_iter(iter, i, false, &hist); |
5297 | if (hist.hisstr != NULL) { |
5298 | ABORTING(set_ref_list)(hist.additional_elements, copyID); |
5299 | } |
5300 | } while (iter != NULL); |
5301 | } |
5302 | } |
5303 | |
5304 | // previously used search/substitute patterns (ShaDa additional data) |
5305 | { |
5306 | SearchPattern pat; |
5307 | get_search_pattern(&pat); |
5308 | ABORTING(set_ref_dict)(pat.additional_data, copyID); |
5309 | get_substitute_pattern(&pat); |
5310 | ABORTING(set_ref_dict)(pat.additional_data, copyID); |
5311 | } |
5312 | |
5313 | // previously used replacement string |
5314 | { |
5315 | SubReplacementString sub; |
5316 | sub_get_replacement(&sub); |
5317 | ABORTING(set_ref_list)(sub.additional_elements, copyID); |
5318 | } |
5319 | |
5320 | ABORTING(set_ref_in_quickfix)(copyID); |
5321 | |
5322 | bool did_free = false; |
5323 | if (!abort) { |
5324 | // 2. Free lists and dictionaries that are not referenced. |
5325 | did_free = free_unref_items(copyID); |
5326 | |
5327 | // 3. Check if any funccal can be freed now. |
5328 | bool did_free_funccal = false; |
5329 | for (funccall_T **pfc = &previous_funccal; *pfc != NULL;) { |
5330 | if (can_free_funccal(*pfc, copyID)) { |
5331 | funccall_T *fc = *pfc; |
5332 | *pfc = fc->caller; |
5333 | free_funccal(fc, true); |
5334 | did_free = true; |
5335 | did_free_funccal = true; |
5336 | } else { |
5337 | pfc = &(*pfc)->caller; |
5338 | } |
5339 | } |
5340 | if (did_free_funccal) { |
5341 | // When a funccal was freed some more items might be garbage |
5342 | // collected, so run again. |
5343 | (void)garbage_collect(testing); |
5344 | } |
5345 | } else if (p_verbose > 0) { |
5346 | verb_msg(_( |
5347 | "Not enough memory to set references, garbage collection aborted!" )); |
5348 | } |
5349 | #undef ABORTING |
5350 | return did_free; |
5351 | } |
5352 | |
5353 | /// Free lists and dictionaries that are no longer referenced. |
5354 | /// |
5355 | /// @note This function may only be called from garbage_collect(). |
5356 | /// |
5357 | /// @param copyID Free lists/dictionaries that don't have this ID. |
5358 | /// @return true, if something was freed. |
5359 | static int free_unref_items(int copyID) |
5360 | { |
5361 | bool did_free = false; |
5362 | |
5363 | // Let all "free" functions know that we are here. This means no |
5364 | // dictionaries, lists, or jobs are to be freed, because we will |
5365 | // do that here. |
5366 | tv_in_free_unref_items = true; |
5367 | |
5368 | // PASS 1: free the contents of the items. We don't free the items |
5369 | // themselves yet, so that it is possible to decrement refcount counters. |
5370 | |
5371 | // Go through the list of dicts and free items without the copyID. |
5372 | // Don't free dicts that are referenced internally. |
5373 | for (dict_T *dd = gc_first_dict; dd != NULL; dd = dd->dv_used_next) { |
5374 | if ((dd->dv_copyID & COPYID_MASK) != (copyID & COPYID_MASK)) { |
5375 | // Free the Dictionary and ordinary items it contains, but don't |
5376 | // recurse into Lists and Dictionaries, they will be in the list |
5377 | // of dicts or list of lists. |
5378 | tv_dict_free_contents(dd); |
5379 | did_free = true; |
5380 | } |
5381 | } |
5382 | |
5383 | // Go through the list of lists and free items without the copyID. |
5384 | // But don't free a list that has a watcher (used in a for loop), these |
5385 | // are not referenced anywhere. |
5386 | for (list_T *ll = gc_first_list; ll != NULL; ll = ll->lv_used_next) { |
5387 | if ((tv_list_copyid(ll) & COPYID_MASK) != (copyID & COPYID_MASK) |
5388 | && !tv_list_has_watchers(ll)) { |
5389 | // Free the List and ordinary items it contains, but don't recurse |
5390 | // into Lists and Dictionaries, they will be in the list of dicts |
5391 | // or list of lists. |
5392 | tv_list_free_contents(ll); |
5393 | did_free = true; |
5394 | } |
5395 | } |
5396 | |
5397 | // PASS 2: free the items themselves. |
5398 | dict_T *dd_next; |
5399 | for (dict_T *dd = gc_first_dict; dd != NULL; dd = dd_next) { |
5400 | dd_next = dd->dv_used_next; |
5401 | if ((dd->dv_copyID & COPYID_MASK) != (copyID & COPYID_MASK)) { |
5402 | tv_dict_free_dict(dd); |
5403 | } |
5404 | } |
5405 | |
5406 | list_T *ll_next; |
5407 | for (list_T *ll = gc_first_list; ll != NULL; ll = ll_next) { |
5408 | ll_next = ll->lv_used_next; |
5409 | if ((ll->lv_copyID & COPYID_MASK) != (copyID & COPYID_MASK) |
5410 | && !tv_list_has_watchers(ll)) { |
5411 | // Free the List and ordinary items it contains, but don't recurse |
5412 | // into Lists and Dictionaries, they will be in the list of dicts |
5413 | // or list of lists. |
5414 | tv_list_free_list(ll); |
5415 | } |
5416 | } |
5417 | tv_in_free_unref_items = false; |
5418 | return did_free; |
5419 | } |
5420 | |
5421 | /// Mark all lists and dicts referenced through hashtab "ht" with "copyID". |
5422 | /// |
5423 | /// @param ht Hashtab content will be marked. |
5424 | /// @param copyID New mark for lists and dicts. |
5425 | /// @param list_stack Used to add lists to be marked. Can be NULL. |
5426 | /// |
5427 | /// @returns true if setting references failed somehow. |
5428 | bool set_ref_in_ht(hashtab_T *ht, int copyID, list_stack_T **list_stack) |
5429 | FUNC_ATTR_WARN_UNUSED_RESULT |
5430 | { |
5431 | bool abort = false; |
5432 | ht_stack_T *ht_stack = NULL; |
5433 | |
5434 | hashtab_T *cur_ht = ht; |
5435 | for (;;) { |
5436 | if (!abort) { |
5437 | // Mark each item in the hashtab. If the item contains a hashtab |
5438 | // it is added to ht_stack, if it contains a list it is added to |
5439 | // list_stack. |
5440 | HASHTAB_ITER(cur_ht, hi, { |
5441 | abort = abort || set_ref_in_item( |
5442 | &TV_DICT_HI2DI(hi)->di_tv, copyID, &ht_stack, list_stack); |
5443 | }); |
5444 | } |
5445 | |
5446 | if (ht_stack == NULL) { |
5447 | break; |
5448 | } |
5449 | |
5450 | // take an item from the stack |
5451 | cur_ht = ht_stack->ht; |
5452 | ht_stack_T *tempitem = ht_stack; |
5453 | ht_stack = ht_stack->prev; |
5454 | xfree(tempitem); |
5455 | } |
5456 | |
5457 | return abort; |
5458 | } |
5459 | |
5460 | /// Mark all lists and dicts referenced through list "l" with "copyID". |
5461 | /// |
5462 | /// @param l List content will be marked. |
5463 | /// @param copyID New mark for lists and dicts. |
5464 | /// @param ht_stack Used to add hashtabs to be marked. Can be NULL. |
5465 | /// |
5466 | /// @returns true if setting references failed somehow. |
5467 | bool set_ref_in_list(list_T *l, int copyID, ht_stack_T **ht_stack) |
5468 | FUNC_ATTR_WARN_UNUSED_RESULT |
5469 | { |
5470 | bool abort = false; |
5471 | list_stack_T *list_stack = NULL; |
5472 | |
5473 | list_T *cur_l = l; |
5474 | for (;;) { |
5475 | // Mark each item in the list. If the item contains a hashtab |
5476 | // it is added to ht_stack, if it contains a list it is added to |
5477 | // list_stack. |
5478 | TV_LIST_ITER(cur_l, li, { |
5479 | if (abort) { |
5480 | break; |
5481 | } |
5482 | abort = set_ref_in_item(TV_LIST_ITEM_TV(li), copyID, ht_stack, |
5483 | &list_stack); |
5484 | }); |
5485 | |
5486 | if (list_stack == NULL) { |
5487 | break; |
5488 | } |
5489 | |
5490 | // take an item from the stack |
5491 | cur_l = list_stack->list; |
5492 | list_stack_T *tempitem = list_stack; |
5493 | list_stack = list_stack->prev; |
5494 | xfree(tempitem); |
5495 | } |
5496 | |
5497 | return abort; |
5498 | } |
5499 | |
5500 | /// Mark all lists and dicts referenced through typval "tv" with "copyID". |
5501 | /// |
5502 | /// @param tv Typval content will be marked. |
5503 | /// @param copyID New mark for lists and dicts. |
5504 | /// @param ht_stack Used to add hashtabs to be marked. Can be NULL. |
5505 | /// @param list_stack Used to add lists to be marked. Can be NULL. |
5506 | /// |
5507 | /// @returns true if setting references failed somehow. |
5508 | bool set_ref_in_item(typval_T *tv, int copyID, ht_stack_T **ht_stack, |
5509 | list_stack_T **list_stack) |
5510 | FUNC_ATTR_WARN_UNUSED_RESULT |
5511 | { |
5512 | bool abort = false; |
5513 | |
5514 | switch (tv->v_type) { |
5515 | case VAR_DICT: { |
5516 | dict_T *dd = tv->vval.v_dict; |
5517 | if (dd != NULL && dd->dv_copyID != copyID) { |
5518 | // Didn't see this dict yet. |
5519 | dd->dv_copyID = copyID; |
5520 | if (ht_stack == NULL) { |
5521 | abort = set_ref_in_ht(&dd->dv_hashtab, copyID, list_stack); |
5522 | } else { |
5523 | ht_stack_T *newitem = try_malloc(sizeof(ht_stack_T)); |
5524 | if (newitem == NULL) { |
5525 | abort = true; |
5526 | } else { |
5527 | newitem->ht = &dd->dv_hashtab; |
5528 | newitem->prev = *ht_stack; |
5529 | *ht_stack = newitem; |
5530 | } |
5531 | } |
5532 | |
5533 | QUEUE *w = NULL; |
5534 | DictWatcher *watcher = NULL; |
5535 | QUEUE_FOREACH(w, &dd->watchers) { |
5536 | watcher = tv_dict_watcher_node_data(w); |
5537 | set_ref_in_callback(&watcher->callback, copyID, ht_stack, list_stack); |
5538 | } |
5539 | } |
5540 | break; |
5541 | } |
5542 | |
5543 | case VAR_LIST: { |
5544 | list_T *ll = tv->vval.v_list; |
5545 | if (ll != NULL && ll->lv_copyID != copyID) { |
5546 | // Didn't see this list yet. |
5547 | ll->lv_copyID = copyID; |
5548 | if (list_stack == NULL) { |
5549 | abort = set_ref_in_list(ll, copyID, ht_stack); |
5550 | } else { |
5551 | list_stack_T *newitem = try_malloc(sizeof(list_stack_T)); |
5552 | if (newitem == NULL) { |
5553 | abort = true; |
5554 | } else { |
5555 | newitem->list = ll; |
5556 | newitem->prev = *list_stack; |
5557 | *list_stack = newitem; |
5558 | } |
5559 | } |
5560 | } |
5561 | break; |
5562 | } |
5563 | |
5564 | case VAR_PARTIAL: { |
5565 | partial_T *pt = tv->vval.v_partial; |
5566 | |
5567 | // A partial does not have a copyID, because it cannot contain itself. |
5568 | if (pt != NULL) { |
5569 | abort = set_ref_in_func(pt->pt_name, pt->pt_func, copyID); |
5570 | if (pt->pt_dict != NULL) { |
5571 | typval_T dtv; |
5572 | |
5573 | dtv.v_type = VAR_DICT; |
5574 | dtv.vval.v_dict = pt->pt_dict; |
5575 | abort = abort || set_ref_in_item(&dtv, copyID, ht_stack, list_stack); |
5576 | } |
5577 | |
5578 | for (int i = 0; i < pt->pt_argc; i++) { |
5579 | abort = abort || set_ref_in_item(&pt->pt_argv[i], copyID, |
5580 | ht_stack, list_stack); |
5581 | } |
5582 | } |
5583 | break; |
5584 | } |
5585 | case VAR_FUNC: |
5586 | abort = set_ref_in_func(tv->vval.v_string, NULL, copyID); |
5587 | break; |
5588 | case VAR_UNKNOWN: |
5589 | case VAR_SPECIAL: |
5590 | case VAR_FLOAT: |
5591 | case VAR_NUMBER: |
5592 | case VAR_STRING: { |
5593 | break; |
5594 | } |
5595 | } |
5596 | return abort; |
5597 | } |
5598 | |
5599 | /// Set "copyID" in all functions available by name. |
5600 | bool set_ref_in_functions(int copyID) |
5601 | { |
5602 | int todo; |
5603 | hashitem_T *hi = NULL; |
5604 | bool abort = false; |
5605 | ufunc_T *fp; |
5606 | |
5607 | todo = (int)func_hashtab.ht_used; |
5608 | for (hi = func_hashtab.ht_array; todo > 0 && !got_int; hi++) { |
5609 | if (!HASHITEM_EMPTY(hi)) { |
5610 | todo--; |
5611 | fp = HI2UF(hi); |
5612 | if (!func_name_refcount(fp->uf_name)) { |
5613 | abort = abort || set_ref_in_func(NULL, fp, copyID); |
5614 | } |
5615 | } |
5616 | } |
5617 | return abort; |
5618 | } |
5619 | |
5620 | |
5621 | |
5622 | /// Mark all lists and dicts referenced in given mark |
5623 | /// |
5624 | /// @returns true if setting references failed somehow. |
5625 | static inline bool set_ref_in_fmark(fmark_T fm, int copyID) |
5626 | FUNC_ATTR_WARN_UNUSED_RESULT |
5627 | { |
5628 | if (fm.additional_data != NULL |
5629 | && fm.additional_data->dv_copyID != copyID) { |
5630 | fm.additional_data->dv_copyID = copyID; |
5631 | return set_ref_in_ht(&fm.additional_data->dv_hashtab, copyID, NULL); |
5632 | } |
5633 | return false; |
5634 | } |
5635 | |
5636 | /// Mark all lists and dicts referenced in given list and the list itself |
5637 | /// |
5638 | /// @returns true if setting references failed somehow. |
5639 | static inline bool set_ref_list(list_T *list, int copyID) |
5640 | FUNC_ATTR_WARN_UNUSED_RESULT |
5641 | { |
5642 | if (list != NULL) { |
5643 | typval_T tv = (typval_T) { |
5644 | .v_type = VAR_LIST, |
5645 | .vval = { .v_list = list } |
5646 | }; |
5647 | return set_ref_in_item(&tv, copyID, NULL, NULL); |
5648 | } |
5649 | return false; |
5650 | } |
5651 | |
5652 | /// Mark all lists and dicts referenced in given dict and the dict itself |
5653 | /// |
5654 | /// @returns true if setting references failed somehow. |
5655 | static inline bool set_ref_dict(dict_T *dict, int copyID) |
5656 | FUNC_ATTR_WARN_UNUSED_RESULT |
5657 | { |
5658 | if (dict != NULL) { |
5659 | typval_T tv = (typval_T) { |
5660 | .v_type = VAR_DICT, |
5661 | .vval = { .v_dict = dict } |
5662 | }; |
5663 | return set_ref_in_item(&tv, copyID, NULL, NULL); |
5664 | } |
5665 | return false; |
5666 | } |
5667 | |
5668 | static bool set_ref_in_funccal(funccall_T *fc, int copyID) |
5669 | { |
5670 | bool abort = false; |
5671 | |
5672 | if (fc->fc_copyID != copyID) { |
5673 | fc->fc_copyID = copyID; |
5674 | abort = abort || set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID, NULL); |
5675 | abort = abort || set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID, NULL); |
5676 | abort = abort || set_ref_in_func(NULL, fc->func, copyID); |
5677 | } |
5678 | return abort; |
5679 | } |
5680 | |
5681 | /* |
5682 | * Allocate a variable for a Dictionary and fill it from "*arg". |
5683 | * Return OK or FAIL. Returns NOTDONE for {expr}. |
5684 | */ |
5685 | static int dict_get_tv(char_u **arg, typval_T *rettv, int evaluate) |
5686 | { |
5687 | dict_T *d = NULL; |
5688 | typval_T tvkey; |
5689 | typval_T tv; |
5690 | char_u *key = NULL; |
5691 | dictitem_T *item; |
5692 | char_u *start = skipwhite(*arg + 1); |
5693 | char buf[NUMBUFLEN]; |
5694 | |
5695 | /* |
5696 | * First check if it's not a curly-braces thing: {expr}. |
5697 | * Must do this without evaluating, otherwise a function may be called |
5698 | * twice. Unfortunately this means we need to call eval1() twice for the |
5699 | * first item. |
5700 | * But {} is an empty Dictionary. |
5701 | */ |
5702 | if (*start != '}') { |
5703 | if (eval1(&start, &tv, FALSE) == FAIL) /* recursive! */ |
5704 | return FAIL; |
5705 | if (*start == '}') |
5706 | return NOTDONE; |
5707 | } |
5708 | |
5709 | if (evaluate) { |
5710 | d = tv_dict_alloc(); |
5711 | } |
5712 | tvkey.v_type = VAR_UNKNOWN; |
5713 | tv.v_type = VAR_UNKNOWN; |
5714 | |
5715 | *arg = skipwhite(*arg + 1); |
5716 | while (**arg != '}' && **arg != NUL) { |
5717 | if (eval1(arg, &tvkey, evaluate) == FAIL) /* recursive! */ |
5718 | goto failret; |
5719 | if (**arg != ':') { |
5720 | EMSG2(_("E720: Missing colon in Dictionary: %s" ), *arg); |
5721 | tv_clear(&tvkey); |
5722 | goto failret; |
5723 | } |
5724 | if (evaluate) { |
5725 | key = (char_u *)tv_get_string_buf_chk(&tvkey, buf); |
5726 | if (key == NULL) { |
5727 | // "key" is NULL when tv_get_string_buf_chk() gave an errmsg |
5728 | tv_clear(&tvkey); |
5729 | goto failret; |
5730 | } |
5731 | } |
5732 | |
5733 | *arg = skipwhite(*arg + 1); |
5734 | if (eval1(arg, &tv, evaluate) == FAIL) { // Recursive! |
5735 | if (evaluate) { |
5736 | tv_clear(&tvkey); |
5737 | } |
5738 | goto failret; |
5739 | } |
5740 | if (evaluate) { |
5741 | item = tv_dict_find(d, (const char *)key, -1); |
5742 | if (item != NULL) { |
5743 | EMSG2(_("E721: Duplicate key in Dictionary: \"%s\"" ), key); |
5744 | tv_clear(&tvkey); |
5745 | tv_clear(&tv); |
5746 | goto failret; |
5747 | } |
5748 | item = tv_dict_item_alloc((const char *)key); |
5749 | tv_clear(&tvkey); |
5750 | item->di_tv = tv; |
5751 | item->di_tv.v_lock = 0; |
5752 | if (tv_dict_add(d, item) == FAIL) { |
5753 | tv_dict_item_free(item); |
5754 | } |
5755 | } |
5756 | |
5757 | if (**arg == '}') |
5758 | break; |
5759 | if (**arg != ',') { |
5760 | EMSG2(_("E722: Missing comma in Dictionary: %s" ), *arg); |
5761 | goto failret; |
5762 | } |
5763 | *arg = skipwhite(*arg + 1); |
5764 | } |
5765 | |
5766 | if (**arg != '}') { |
5767 | EMSG2(_("E723: Missing end of Dictionary '}': %s" ), *arg); |
5768 | failret: |
5769 | if (evaluate) { |
5770 | tv_dict_free(d); |
5771 | } |
5772 | return FAIL; |
5773 | } |
5774 | |
5775 | *arg = skipwhite(*arg + 1); |
5776 | if (evaluate) { |
5777 | tv_dict_set_ret(rettv, d); |
5778 | } |
5779 | |
5780 | return OK; |
5781 | } |
5782 | |
5783 | /// Get function arguments. |
5784 | static int get_function_args(char_u **argp, char_u endchar, garray_T *newargs, |
5785 | int *varargs, bool skip) |
5786 | { |
5787 | bool mustend = false; |
5788 | char_u *arg = *argp; |
5789 | char_u *p = arg; |
5790 | int c; |
5791 | int i; |
5792 | |
5793 | if (newargs != NULL) { |
5794 | ga_init(newargs, (int)sizeof(char_u *), 3); |
5795 | } |
5796 | |
5797 | if (varargs != NULL) { |
5798 | *varargs = false; |
5799 | } |
5800 | |
5801 | // Isolate the arguments: "arg1, arg2, ...)" |
5802 | while (*p != endchar) { |
5803 | if (p[0] == '.' && p[1] == '.' && p[2] == '.') { |
5804 | if (varargs != NULL) { |
5805 | *varargs = true; |
5806 | } |
5807 | p += 3; |
5808 | mustend = true; |
5809 | } else { |
5810 | arg = p; |
5811 | while (ASCII_ISALNUM(*p) || *p == '_') { |
5812 | p++; |
5813 | } |
5814 | if (arg == p || isdigit(*arg) |
5815 | || (p - arg == 9 && STRNCMP(arg, "firstline" , 9) == 0) |
5816 | || (p - arg == 8 && STRNCMP(arg, "lastline" , 8) == 0)) { |
5817 | if (!skip) { |
5818 | EMSG2(_("E125: Illegal argument: %s" ), arg); |
5819 | } |
5820 | break; |
5821 | } |
5822 | if (newargs != NULL) { |
5823 | ga_grow(newargs, 1); |
5824 | c = *p; |
5825 | *p = NUL; |
5826 | arg = vim_strsave(arg); |
5827 | |
5828 | // Check for duplicate argument name. |
5829 | for (i = 0; i < newargs->ga_len; i++) { |
5830 | if (STRCMP(((char_u **)(newargs->ga_data))[i], arg) == 0) { |
5831 | EMSG2(_("E853: Duplicate argument name: %s" ), arg); |
5832 | xfree(arg); |
5833 | goto err_ret; |
5834 | } |
5835 | } |
5836 | ((char_u **)(newargs->ga_data))[newargs->ga_len] = arg; |
5837 | newargs->ga_len++; |
5838 | |
5839 | *p = c; |
5840 | } |
5841 | if (*p == ',') { |
5842 | p++; |
5843 | } else { |
5844 | mustend = true; |
5845 | } |
5846 | } |
5847 | p = skipwhite(p); |
5848 | if (mustend && *p != endchar) { |
5849 | if (!skip) { |
5850 | EMSG2(_(e_invarg2), *argp); |
5851 | } |
5852 | break; |
5853 | } |
5854 | } |
5855 | if (*p != endchar) { |
5856 | goto err_ret; |
5857 | } |
5858 | p++; // skip "endchar" |
5859 | |
5860 | *argp = p; |
5861 | return OK; |
5862 | |
5863 | err_ret: |
5864 | if (newargs != NULL) { |
5865 | ga_clear_strings(newargs); |
5866 | } |
5867 | return FAIL; |
5868 | } |
5869 | |
5870 | /// Register function "fp" as using "current_funccal" as its scope. |
5871 | static void register_closure(ufunc_T *fp) |
5872 | { |
5873 | if (fp->uf_scoped == current_funccal) { |
5874 | // no change |
5875 | return; |
5876 | } |
5877 | funccal_unref(fp->uf_scoped, fp, false); |
5878 | fp->uf_scoped = current_funccal; |
5879 | current_funccal->fc_refcount++; |
5880 | ga_grow(¤t_funccal->fc_funcs, 1); |
5881 | ((ufunc_T **)current_funccal->fc_funcs.ga_data) |
5882 | [current_funccal->fc_funcs.ga_len++] = fp; |
5883 | } |
5884 | |
5885 | /// Parse a lambda expression and get a Funcref from "*arg". |
5886 | /// |
5887 | /// @return OK or FAIL. Returns NOTDONE for dict or {expr}. |
5888 | static int get_lambda_tv(char_u **arg, typval_T *rettv, bool evaluate) |
5889 | { |
5890 | garray_T newargs = GA_EMPTY_INIT_VALUE; |
5891 | garray_T *pnewargs; |
5892 | ufunc_T *fp = NULL; |
5893 | int varargs; |
5894 | int ret; |
5895 | char_u *start = skipwhite(*arg + 1); |
5896 | char_u *s, *e; |
5897 | static int lambda_no = 0; |
5898 | int *old_eval_lavars = eval_lavars_used; |
5899 | int eval_lavars = false; |
5900 | |
5901 | // First, check if this is a lambda expression. "->" must exists. |
5902 | ret = get_function_args(&start, '-', NULL, NULL, true); |
5903 | if (ret == FAIL || *start != '>') { |
5904 | return NOTDONE; |
5905 | } |
5906 | |
5907 | // Parse the arguments again. |
5908 | if (evaluate) { |
5909 | pnewargs = &newargs; |
5910 | } else { |
5911 | pnewargs = NULL; |
5912 | } |
5913 | *arg = skipwhite(*arg + 1); |
5914 | ret = get_function_args(arg, '-', pnewargs, &varargs, false); |
5915 | if (ret == FAIL || **arg != '>') { |
5916 | goto errret; |
5917 | } |
5918 | |
5919 | // Set up a flag for checking local variables and arguments. |
5920 | if (evaluate) { |
5921 | eval_lavars_used = &eval_lavars; |
5922 | } |
5923 | |
5924 | // Get the start and the end of the expression. |
5925 | *arg = skipwhite(*arg + 1); |
5926 | s = *arg; |
5927 | ret = skip_expr(arg); |
5928 | if (ret == FAIL) { |
5929 | goto errret; |
5930 | } |
5931 | e = *arg; |
5932 | *arg = skipwhite(*arg); |
5933 | if (**arg != '}') { |
5934 | goto errret; |
5935 | } |
5936 | (*arg)++; |
5937 | |
5938 | if (evaluate) { |
5939 | int len, flags = 0; |
5940 | char_u *p; |
5941 | char_u name[20]; |
5942 | partial_T *pt; |
5943 | garray_T newlines; |
5944 | |
5945 | lambda_no++; |
5946 | snprintf((char *)name, sizeof(name), "<lambda>%d" , lambda_no); |
5947 | |
5948 | fp = xcalloc(1, offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); |
5949 | pt = xcalloc(1, sizeof(partial_T)); |
5950 | |
5951 | ga_init(&newlines, (int)sizeof(char_u *), 1); |
5952 | ga_grow(&newlines, 1); |
5953 | |
5954 | // Add "return " before the expression. |
5955 | len = 7 + e - s + 1; |
5956 | p = (char_u *)xmalloc(len); |
5957 | ((char_u **)(newlines.ga_data))[newlines.ga_len++] = p; |
5958 | STRCPY(p, "return " ); |
5959 | STRLCPY(p + 7, s, e - s + 1); |
5960 | |
5961 | fp->uf_refcount = 1; |
5962 | STRCPY(fp->uf_name, name); |
5963 | hash_add(&func_hashtab, UF2HIKEY(fp)); |
5964 | fp->uf_args = newargs; |
5965 | fp->uf_lines = newlines; |
5966 | if (current_funccal != NULL && eval_lavars) { |
5967 | flags |= FC_CLOSURE; |
5968 | register_closure(fp); |
5969 | } else { |
5970 | fp->uf_scoped = NULL; |
5971 | } |
5972 | |
5973 | if (prof_def_func()) { |
5974 | func_do_profile(fp); |
5975 | } |
5976 | if (sandbox) { |
5977 | flags |= FC_SANDBOX; |
5978 | } |
5979 | fp->uf_varargs = true; |
5980 | fp->uf_flags = flags; |
5981 | fp->uf_calls = 0; |
5982 | fp->uf_script_ctx = current_sctx; |
5983 | fp->uf_script_ctx.sc_lnum += sourcing_lnum - newlines.ga_len; |
5984 | |
5985 | pt->pt_func = fp; |
5986 | pt->pt_refcount = 1; |
5987 | rettv->vval.v_partial = pt; |
5988 | rettv->v_type = VAR_PARTIAL; |
5989 | } |
5990 | |
5991 | eval_lavars_used = old_eval_lavars; |
5992 | return OK; |
5993 | |
5994 | errret: |
5995 | ga_clear_strings(&newargs); |
5996 | xfree(fp); |
5997 | eval_lavars_used = old_eval_lavars; |
5998 | return FAIL; |
5999 | } |
6000 | |
6001 | /// Convert the string to a floating point number |
6002 | /// |
6003 | /// This uses strtod(). setlocale(LC_NUMERIC, "C") has been used earlier to |
6004 | /// make sure this always uses a decimal point. |
6005 | /// |
6006 | /// @param[in] text String to convert. |
6007 | /// @param[out] ret_value Location where conversion result is saved. |
6008 | /// |
6009 | /// @return Length of the text that was consumed. |
6010 | size_t string2float(const char *const text, float_T *const ret_value) |
6011 | FUNC_ATTR_NONNULL_ALL |
6012 | { |
6013 | char *s = NULL; |
6014 | |
6015 | // MS-Windows does not deal with "inf" and "nan" properly |
6016 | if (STRNICMP(text, "inf" , 3) == 0) { |
6017 | *ret_value = INFINITY; |
6018 | return 3; |
6019 | } |
6020 | if (STRNICMP(text, "-inf" , 3) == 0) { |
6021 | *ret_value = -INFINITY; |
6022 | return 4; |
6023 | } |
6024 | if (STRNICMP(text, "nan" , 3) == 0) { |
6025 | *ret_value = NAN; |
6026 | return 3; |
6027 | } |
6028 | *ret_value = strtod(text, &s); |
6029 | return (size_t) (s - text); |
6030 | } |
6031 | |
6032 | /// Get the value of an environment variable. |
6033 | /// |
6034 | /// If the environment variable was not set, silently assume it is empty. |
6035 | /// |
6036 | /// @param arg Points to the '$'. It is advanced to after the name. |
6037 | /// @return FAIL if the name is invalid. |
6038 | /// |
6039 | static int get_env_tv(char_u **arg, typval_T *rettv, int evaluate) |
6040 | { |
6041 | char_u *name; |
6042 | char_u *string = NULL; |
6043 | int len; |
6044 | int cc; |
6045 | |
6046 | ++*arg; |
6047 | name = *arg; |
6048 | len = get_env_len((const char_u **)arg); |
6049 | |
6050 | if (evaluate) { |
6051 | if (len == 0) { |
6052 | return FAIL; // Invalid empty name. |
6053 | } |
6054 | cc = name[len]; |
6055 | name[len] = NUL; |
6056 | // First try vim_getenv(), fast for normal environment vars. |
6057 | string = (char_u *)vim_getenv((char *)name); |
6058 | if (string == NULL || *string == NUL) { |
6059 | xfree(string); |
6060 | |
6061 | // Next try expanding things like $VIM and ${HOME}. |
6062 | string = expand_env_save(name - 1); |
6063 | if (string != NULL && *string == '$') { |
6064 | XFREE_CLEAR(string); |
6065 | } |
6066 | } |
6067 | name[len] = cc; |
6068 | rettv->v_type = VAR_STRING; |
6069 | rettv->vval.v_string = string; |
6070 | } |
6071 | |
6072 | return OK; |
6073 | } |
6074 | |
6075 | #ifdef INCLUDE_GENERATED_DECLARATIONS |
6076 | |
6077 | #ifdef _MSC_VER |
6078 | // This prevents MSVC from replacing the functions with intrinsics, |
6079 | // and causing errors when trying to get their addresses in funcs.generated.h |
6080 | #pragma function (ceil) |
6081 | #pragma function (floor) |
6082 | #endif |
6083 | |
6084 | PRAGMA_DIAG_PUSH_IGNORE_MISSING_PROTOTYPES |
6085 | # include "funcs.generated.h" |
6086 | PRAGMA_DIAG_POP |
6087 | #endif |
6088 | |
6089 | /* |
6090 | * Function given to ExpandGeneric() to obtain the list of internal |
6091 | * or user defined function names. |
6092 | */ |
6093 | char_u *get_function_name(expand_T *xp, int idx) |
6094 | { |
6095 | static int intidx = -1; |
6096 | char_u *name; |
6097 | |
6098 | if (idx == 0) |
6099 | intidx = -1; |
6100 | if (intidx < 0) { |
6101 | name = get_user_func_name(xp, idx); |
6102 | if (name != NULL) |
6103 | return name; |
6104 | } |
6105 | while ( (size_t)++intidx < ARRAY_SIZE(functions) |
6106 | && functions[intidx].name[0] == '\0') { |
6107 | } |
6108 | |
6109 | if ((size_t)intidx >= ARRAY_SIZE(functions)) { |
6110 | return NULL; |
6111 | } |
6112 | |
6113 | const char *const key = functions[intidx].name; |
6114 | const size_t key_len = strlen(key); |
6115 | memcpy(IObuff, key, key_len); |
6116 | IObuff[key_len] = '('; |
6117 | if (functions[intidx].max_argc == 0) { |
6118 | IObuff[key_len + 1] = ')'; |
6119 | IObuff[key_len + 2] = NUL; |
6120 | } else { |
6121 | IObuff[key_len + 1] = NUL; |
6122 | } |
6123 | return IObuff; |
6124 | } |
6125 | |
6126 | /* |
6127 | * Function given to ExpandGeneric() to obtain the list of internal or |
6128 | * user defined variable or function names. |
6129 | */ |
6130 | char_u *get_expr_name(expand_T *xp, int idx) |
6131 | { |
6132 | static int intidx = -1; |
6133 | char_u *name; |
6134 | |
6135 | if (idx == 0) |
6136 | intidx = -1; |
6137 | if (intidx < 0) { |
6138 | name = get_function_name(xp, idx); |
6139 | if (name != NULL) |
6140 | return name; |
6141 | } |
6142 | return get_user_var_name(xp, ++intidx); |
6143 | } |
6144 | |
6145 | /// Find internal function in hash functions |
6146 | /// |
6147 | /// @param[in] name Name of the function. |
6148 | /// |
6149 | /// Returns pointer to the function definition or NULL if not found. |
6150 | static const VimLFuncDef *find_internal_func(const char *const name) |
6151 | FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE FUNC_ATTR_NONNULL_ALL |
6152 | { |
6153 | size_t len = strlen(name); |
6154 | return find_internal_func_gperf(name, len); |
6155 | } |
6156 | |
6157 | /// Return name of the function corresponding to `name` |
6158 | /// |
6159 | /// If `name` points to variable that is either a function or partial then |
6160 | /// corresponding function name is returned. Otherwise it returns `name` itself. |
6161 | /// |
6162 | /// @param[in] name Function name to check. |
6163 | /// @param[in,out] lenp Location where length of the returned name is stored. |
6164 | /// Must be set to the length of the `name` argument. |
6165 | /// @param[out] partialp Location where partial will be stored if found |
6166 | /// function appears to be a partial. May be NULL if this |
6167 | /// is not needed. |
6168 | /// @param[in] no_autoload If true, do not source autoload scripts if function |
6169 | /// was not found. |
6170 | /// |
6171 | /// @return name of the function. |
6172 | static char_u *deref_func_name(const char *name, int *lenp, |
6173 | partial_T **const partialp, bool no_autoload) |
6174 | FUNC_ATTR_NONNULL_ARG(1, 2) |
6175 | { |
6176 | if (partialp != NULL) { |
6177 | *partialp = NULL; |
6178 | } |
6179 | |
6180 | dictitem_T *const v = find_var(name, (size_t)(*lenp), NULL, no_autoload); |
6181 | if (v != NULL && v->di_tv.v_type == VAR_FUNC) { |
6182 | if (v->di_tv.vval.v_string == NULL) { // just in case |
6183 | *lenp = 0; |
6184 | return (char_u *)"" ; |
6185 | } |
6186 | *lenp = (int)STRLEN(v->di_tv.vval.v_string); |
6187 | return v->di_tv.vval.v_string; |
6188 | } |
6189 | |
6190 | if (v != NULL && v->di_tv.v_type == VAR_PARTIAL) { |
6191 | partial_T *const pt = v->di_tv.vval.v_partial; |
6192 | |
6193 | if (pt == NULL) { // just in case |
6194 | *lenp = 0; |
6195 | return (char_u *)"" ; |
6196 | } |
6197 | if (partialp != NULL) { |
6198 | *partialp = pt; |
6199 | } |
6200 | char_u *s = partial_name(pt); |
6201 | *lenp = (int)STRLEN(s); |
6202 | return s; |
6203 | } |
6204 | |
6205 | return (char_u *)name; |
6206 | } |
6207 | |
6208 | /* |
6209 | * Allocate a variable for the result of a function. |
6210 | * Return OK or FAIL. |
6211 | */ |
6212 | static int |
6213 | get_func_tv( |
6214 | char_u *name, // name of the function |
6215 | int len, // length of "name" |
6216 | typval_T *rettv, |
6217 | char_u **arg, // argument, pointing to the '(' |
6218 | linenr_T firstline, // first line of range |
6219 | linenr_T lastline, // last line of range |
6220 | int *doesrange, // return: function handled range |
6221 | int evaluate, |
6222 | partial_T *partial, // for extra arguments |
6223 | dict_T *selfdict // Dictionary for "self" |
6224 | ) |
6225 | { |
6226 | char_u *argp; |
6227 | int ret = OK; |
6228 | typval_T argvars[MAX_FUNC_ARGS + 1]; /* vars for arguments */ |
6229 | int argcount = 0; /* number of arguments found */ |
6230 | |
6231 | /* |
6232 | * Get the arguments. |
6233 | */ |
6234 | argp = *arg; |
6235 | while (argcount < MAX_FUNC_ARGS - (partial == NULL ? 0 : partial->pt_argc)) { |
6236 | argp = skipwhite(argp + 1); // skip the '(' or ',' |
6237 | if (*argp == ')' || *argp == ',' || *argp == NUL) { |
6238 | break; |
6239 | } |
6240 | if (eval1(&argp, &argvars[argcount], evaluate) == FAIL) { |
6241 | ret = FAIL; |
6242 | break; |
6243 | } |
6244 | ++argcount; |
6245 | if (*argp != ',') |
6246 | break; |
6247 | } |
6248 | if (*argp == ')') |
6249 | ++argp; |
6250 | else |
6251 | ret = FAIL; |
6252 | |
6253 | if (ret == OK) { |
6254 | int i = 0; |
6255 | |
6256 | if (get_vim_var_nr(VV_TESTING)) { |
6257 | // Prepare for calling garbagecollect_for_testing(), need to know |
6258 | // what variables are used on the call stack. |
6259 | if (funcargs.ga_itemsize == 0) { |
6260 | ga_init(&funcargs, (int)sizeof(typval_T *), 50); |
6261 | } |
6262 | for (i = 0; i < argcount; i++) { |
6263 | ga_grow(&funcargs, 1); |
6264 | ((typval_T **)funcargs.ga_data)[funcargs.ga_len++] = &argvars[i]; |
6265 | } |
6266 | } |
6267 | ret = call_func(name, len, rettv, argcount, argvars, NULL, |
6268 | firstline, lastline, doesrange, evaluate, |
6269 | partial, selfdict); |
6270 | |
6271 | funcargs.ga_len -= i; |
6272 | } else if (!aborting()) { |
6273 | if (argcount == MAX_FUNC_ARGS) { |
6274 | emsg_funcname(N_("E740: Too many arguments for function %s" ), name); |
6275 | } else { |
6276 | emsg_funcname(N_("E116: Invalid arguments for function %s" ), name); |
6277 | } |
6278 | } |
6279 | |
6280 | while (--argcount >= 0) { |
6281 | tv_clear(&argvars[argcount]); |
6282 | } |
6283 | |
6284 | *arg = skipwhite(argp); |
6285 | return ret; |
6286 | } |
6287 | |
6288 | typedef enum { |
6289 | ERROR_UNKNOWN = 0, |
6290 | ERROR_TOOMANY, |
6291 | ERROR_TOOFEW, |
6292 | ERROR_SCRIPT, |
6293 | ERROR_DICT, |
6294 | ERROR_NONE, |
6295 | ERROR_OTHER, |
6296 | ERROR_BOTH, |
6297 | ERROR_DELETED, |
6298 | } FnameTransError; |
6299 | |
6300 | #define FLEN_FIXED 40 |
6301 | |
6302 | /// In a script transform script-local names into actually used names |
6303 | /// |
6304 | /// Transforms "<SID>" and "s:" prefixes to `K_SNR {N}` (e.g. K_SNR "123") and |
6305 | /// "<SNR>" prefix to `K_SNR`. Uses `fname_buf` buffer that is supposed to have |
6306 | /// #FLEN_FIXED + 1 length when it fits, otherwise it allocates memory. |
6307 | /// |
6308 | /// @param[in] name Name to transform. |
6309 | /// @param fname_buf Buffer to save resulting function name to, if it fits. |
6310 | /// Must have at least #FLEN_FIXED + 1 length. |
6311 | /// @param[out] tofree Location where pointer to an allocated memory is saved |
6312 | /// in case result does not fit into fname_buf. |
6313 | /// @param[out] error Location where error type is saved, @see |
6314 | /// FnameTransError. |
6315 | /// |
6316 | /// @return transformed name: either `fname_buf` or a pointer to an allocated |
6317 | /// memory. |
6318 | static char_u *fname_trans_sid(const char_u *const name, |
6319 | char_u *const fname_buf, |
6320 | char_u **const tofree, int *const error) |
6321 | FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT |
6322 | { |
6323 | char_u *fname; |
6324 | const int llen = eval_fname_script((const char *)name); |
6325 | if (llen > 0) { |
6326 | fname_buf[0] = K_SPECIAL; |
6327 | fname_buf[1] = KS_EXTRA; |
6328 | fname_buf[2] = (int)KE_SNR; |
6329 | int i = 3; |
6330 | if (eval_fname_sid((const char *)name)) { // "<SID>" or "s:" |
6331 | if (current_sctx.sc_sid <= 0) { |
6332 | *error = ERROR_SCRIPT; |
6333 | } else { |
6334 | snprintf((char *)fname_buf + 3, FLEN_FIXED + 1, "%" PRId64 "_" , |
6335 | (int64_t)current_sctx.sc_sid); |
6336 | i = (int)STRLEN(fname_buf); |
6337 | } |
6338 | } |
6339 | if (i + STRLEN(name + llen) < FLEN_FIXED) { |
6340 | STRCPY(fname_buf + i, name + llen); |
6341 | fname = fname_buf; |
6342 | } else { |
6343 | fname = xmalloc(i + STRLEN(name + llen) + 1); |
6344 | *tofree = fname; |
6345 | memmove(fname, fname_buf, (size_t)i); |
6346 | STRCPY(fname + i, name + llen); |
6347 | } |
6348 | } else { |
6349 | fname = (char_u *)name; |
6350 | } |
6351 | |
6352 | return fname; |
6353 | } |
6354 | |
6355 | /// Mark all lists and dicts referenced through function "name" with "copyID". |
6356 | /// "list_stack" is used to add lists to be marked. Can be NULL. |
6357 | /// "ht_stack" is used to add hashtabs to be marked. Can be NULL. |
6358 | /// |
6359 | /// @return true if setting references failed somehow. |
6360 | bool set_ref_in_func(char_u *name, ufunc_T *fp_in, int copyID) |
6361 | { |
6362 | ufunc_T *fp = fp_in; |
6363 | funccall_T *fc; |
6364 | int error = ERROR_NONE; |
6365 | char_u fname_buf[FLEN_FIXED + 1]; |
6366 | char_u *tofree = NULL; |
6367 | char_u *fname; |
6368 | bool abort = false; |
6369 | if (name == NULL && fp_in == NULL) { |
6370 | return false; |
6371 | } |
6372 | |
6373 | if (fp_in == NULL) { |
6374 | fname = fname_trans_sid(name, fname_buf, &tofree, &error); |
6375 | fp = find_func(fname); |
6376 | } |
6377 | if (fp != NULL) { |
6378 | for (fc = fp->uf_scoped; fc != NULL; fc = fc->func->uf_scoped) { |
6379 | abort = abort || set_ref_in_funccal(fc, copyID); |
6380 | } |
6381 | } |
6382 | xfree(tofree); |
6383 | return abort; |
6384 | } |
6385 | |
6386 | /// Call a function with its resolved parameters |
6387 | /// |
6388 | /// "argv_func", when not NULL, can be used to fill in arguments only when the |
6389 | /// invoked function uses them. It is called like this: |
6390 | /// new_argcount = argv_func(current_argcount, argv, called_func_argcount) |
6391 | /// |
6392 | /// @return FAIL if function cannot be called, else OK (even if an error |
6393 | /// occurred while executing the function! Set `msg_list` to capture |
6394 | /// the error, see do_cmdline()). |
6395 | int |
6396 | call_func( |
6397 | const char_u *funcname, // name of the function |
6398 | int len, // length of "name" |
6399 | typval_T *rettv, // [out] value goes here |
6400 | int argcount_in, // number of "argvars" |
6401 | typval_T *argvars_in, // vars for arguments, must have "argcount" |
6402 | // PLUS ONE elements! |
6403 | ArgvFunc argv_func, // function to fill in argvars |
6404 | linenr_T firstline, // first line of range |
6405 | linenr_T lastline, // last line of range |
6406 | int *doesrange, // [out] function handled range |
6407 | bool evaluate, |
6408 | partial_T *partial, // optional, can be NULL |
6409 | dict_T *selfdict_in // Dictionary for "self" |
6410 | ) |
6411 | FUNC_ATTR_NONNULL_ARG(1, 3, 5, 9) |
6412 | { |
6413 | int ret = FAIL; |
6414 | int error = ERROR_NONE; |
6415 | ufunc_T *fp; |
6416 | char_u fname_buf[FLEN_FIXED + 1]; |
6417 | char_u *tofree = NULL; |
6418 | char_u *fname; |
6419 | char_u *name; |
6420 | int argcount = argcount_in; |
6421 | typval_T *argvars = argvars_in; |
6422 | dict_T *selfdict = selfdict_in; |
6423 | typval_T argv[MAX_FUNC_ARGS + 1]; // used when "partial" is not NULL |
6424 | int argv_clear = 0; |
6425 | |
6426 | // Initialize rettv so that it is safe for caller to invoke clear_tv(rettv) |
6427 | // even when call_func() returns FAIL. |
6428 | rettv->v_type = VAR_UNKNOWN; |
6429 | |
6430 | // Make a copy of the name, if it comes from a funcref variable it could |
6431 | // be changed or deleted in the called function. |
6432 | name = vim_strnsave(funcname, len); |
6433 | |
6434 | fname = fname_trans_sid(name, fname_buf, &tofree, &error); |
6435 | |
6436 | *doesrange = false; |
6437 | |
6438 | if (partial != NULL) { |
6439 | // When the function has a partial with a dict and there is a dict |
6440 | // argument, use the dict argument. That is backwards compatible. |
6441 | // When the dict was bound explicitly use the one from the partial. |
6442 | if (partial->pt_dict != NULL |
6443 | && (selfdict_in == NULL || !partial->pt_auto)) { |
6444 | selfdict = partial->pt_dict; |
6445 | } |
6446 | if (error == ERROR_NONE && partial->pt_argc > 0) { |
6447 | for (argv_clear = 0; argv_clear < partial->pt_argc; argv_clear++) { |
6448 | tv_copy(&partial->pt_argv[argv_clear], &argv[argv_clear]); |
6449 | } |
6450 | for (int i = 0; i < argcount_in; i++) { |
6451 | argv[i + argv_clear] = argvars_in[i]; |
6452 | } |
6453 | argvars = argv; |
6454 | argcount = partial->pt_argc + argcount_in; |
6455 | } |
6456 | } |
6457 | |
6458 | if (error == ERROR_NONE && evaluate) { |
6459 | char_u *rfname = fname; |
6460 | |
6461 | /* Ignore "g:" before a function name. */ |
6462 | if (fname[0] == 'g' && fname[1] == ':') { |
6463 | rfname = fname + 2; |
6464 | } |
6465 | |
6466 | rettv->v_type = VAR_NUMBER; /* default rettv is number zero */ |
6467 | rettv->vval.v_number = 0; |
6468 | error = ERROR_UNKNOWN; |
6469 | |
6470 | if (!builtin_function((const char *)rfname, -1)) { |
6471 | // User defined function. |
6472 | if (partial != NULL && partial->pt_func != NULL) { |
6473 | fp = partial->pt_func; |
6474 | } else { |
6475 | fp = find_func(rfname); |
6476 | } |
6477 | |
6478 | // Trigger FuncUndefined event, may load the function. |
6479 | if (fp == NULL |
6480 | && apply_autocmds(EVENT_FUNCUNDEFINED, rfname, rfname, TRUE, NULL) |
6481 | && !aborting()) { |
6482 | /* executed an autocommand, search for the function again */ |
6483 | fp = find_func(rfname); |
6484 | } |
6485 | // Try loading a package. |
6486 | if (fp == NULL && script_autoload((const char *)rfname, STRLEN(rfname), |
6487 | true) && !aborting()) { |
6488 | // Loaded a package, search for the function again. |
6489 | fp = find_func(rfname); |
6490 | } |
6491 | |
6492 | if (fp != NULL && (fp->uf_flags & FC_DELETED)) { |
6493 | error = ERROR_DELETED; |
6494 | } else if (fp != NULL) { |
6495 | if (argv_func != NULL) { |
6496 | argcount = argv_func(argcount, argvars, fp->uf_args.ga_len); |
6497 | } |
6498 | if (fp->uf_flags & FC_RANGE) { |
6499 | *doesrange = true; |
6500 | } |
6501 | if (argcount < fp->uf_args.ga_len) { |
6502 | error = ERROR_TOOFEW; |
6503 | } else if (!fp->uf_varargs && argcount > fp->uf_args.ga_len) { |
6504 | error = ERROR_TOOMANY; |
6505 | } else if ((fp->uf_flags & FC_DICT) && selfdict == NULL) { |
6506 | error = ERROR_DICT; |
6507 | } else { |
6508 | // Call the user function. |
6509 | call_user_func(fp, argcount, argvars, rettv, firstline, lastline, |
6510 | (fp->uf_flags & FC_DICT) ? selfdict : NULL); |
6511 | error = ERROR_NONE; |
6512 | } |
6513 | } |
6514 | } else { |
6515 | // Find the function name in the table, call its implementation. |
6516 | const VimLFuncDef *const fdef = find_internal_func((const char *)fname); |
6517 | if (fdef != NULL) { |
6518 | if (argcount < fdef->min_argc) { |
6519 | error = ERROR_TOOFEW; |
6520 | } else if (argcount > fdef->max_argc) { |
6521 | error = ERROR_TOOMANY; |
6522 | } else { |
6523 | argvars[argcount].v_type = VAR_UNKNOWN; |
6524 | fdef->func(argvars, rettv, fdef->data); |
6525 | error = ERROR_NONE; |
6526 | } |
6527 | } |
6528 | } |
6529 | /* |
6530 | * The function call (or "FuncUndefined" autocommand sequence) might |
6531 | * have been aborted by an error, an interrupt, or an explicitly thrown |
6532 | * exception that has not been caught so far. This situation can be |
6533 | * tested for by calling aborting(). For an error in an internal |
6534 | * function or for the "E132" error in call_user_func(), however, the |
6535 | * throw point at which the "force_abort" flag (temporarily reset by |
6536 | * emsg()) is normally updated has not been reached yet. We need to |
6537 | * update that flag first to make aborting() reliable. |
6538 | */ |
6539 | update_force_abort(); |
6540 | } |
6541 | if (error == ERROR_NONE) |
6542 | ret = OK; |
6543 | |
6544 | /* |
6545 | * Report an error unless the argument evaluation or function call has been |
6546 | * cancelled due to an aborting error, an interrupt, or an exception. |
6547 | */ |
6548 | if (!aborting()) { |
6549 | switch (error) { |
6550 | case ERROR_UNKNOWN: |
6551 | emsg_funcname(N_("E117: Unknown function: %s" ), name); |
6552 | break; |
6553 | case ERROR_DELETED: |
6554 | emsg_funcname(N_("E933: Function was deleted: %s" ), name); |
6555 | break; |
6556 | case ERROR_TOOMANY: |
6557 | emsg_funcname(e_toomanyarg, name); |
6558 | break; |
6559 | case ERROR_TOOFEW: |
6560 | emsg_funcname(N_("E119: Not enough arguments for function: %s" ), |
6561 | name); |
6562 | break; |
6563 | case ERROR_SCRIPT: |
6564 | emsg_funcname(N_("E120: Using <SID> not in a script context: %s" ), |
6565 | name); |
6566 | break; |
6567 | case ERROR_DICT: |
6568 | emsg_funcname(N_("E725: Calling dict function without Dictionary: %s" ), |
6569 | name); |
6570 | break; |
6571 | } |
6572 | } |
6573 | |
6574 | while (argv_clear > 0) { |
6575 | tv_clear(&argv[--argv_clear]); |
6576 | } |
6577 | xfree(tofree); |
6578 | xfree(name); |
6579 | |
6580 | return ret; |
6581 | } |
6582 | |
6583 | /// Give an error message with a function name. Handle <SNR> things. |
6584 | /// |
6585 | /// @param ermsg must be passed without translation (use N_() instead of _()). |
6586 | /// @param name function name |
6587 | static void emsg_funcname(char *ermsg, char_u *name) |
6588 | { |
6589 | char_u *p; |
6590 | |
6591 | if (*name == K_SPECIAL) { |
6592 | p = concat_str((char_u *)"<SNR>" , name + 3); |
6593 | } else { |
6594 | p = name; |
6595 | } |
6596 | |
6597 | EMSG2(_(ermsg), p); |
6598 | |
6599 | if (p != name) { |
6600 | xfree(p); |
6601 | } |
6602 | } |
6603 | |
6604 | /* |
6605 | * Return TRUE for a non-zero Number and a non-empty String. |
6606 | */ |
6607 | static int non_zero_arg(typval_T *argvars) |
6608 | { |
6609 | return ((argvars[0].v_type == VAR_NUMBER |
6610 | && argvars[0].vval.v_number != 0) |
6611 | || (argvars[0].v_type == VAR_SPECIAL |
6612 | && argvars[0].vval.v_special == kSpecialVarTrue) |
6613 | || (argvars[0].v_type == VAR_STRING |
6614 | && argvars[0].vval.v_string != NULL |
6615 | && *argvars[0].vval.v_string != NUL)); |
6616 | } |
6617 | |
6618 | /********************************************* |
6619 | * Implementation of the built-in functions |
6620 | */ |
6621 | |
6622 | |
6623 | // Apply a floating point C function on a typval with one float_T. |
6624 | // |
6625 | // Some versions of glibc on i386 have an optimization that makes it harder to |
6626 | // call math functions indirectly from inside an inlined function, causing |
6627 | // compile-time errors. Avoid `inline` in that case. #3072 |
6628 | static void float_op_wrapper(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
6629 | { |
6630 | float_T f; |
6631 | float_T (*function)(float_T) = (float_T (*)(float_T))fptr; |
6632 | |
6633 | rettv->v_type = VAR_FLOAT; |
6634 | if (tv_get_float_chk(argvars, &f)) { |
6635 | rettv->vval.v_float = function(f); |
6636 | } else { |
6637 | rettv->vval.v_float = 0.0; |
6638 | } |
6639 | } |
6640 | |
6641 | static void api_wrapper(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
6642 | { |
6643 | if (check_restricted() || check_secure()) { |
6644 | return; |
6645 | } |
6646 | |
6647 | ApiDispatchWrapper fn = (ApiDispatchWrapper)fptr; |
6648 | |
6649 | Array args = ARRAY_DICT_INIT; |
6650 | |
6651 | for (typval_T *tv = argvars; tv->v_type != VAR_UNKNOWN; tv++) { |
6652 | ADD(args, vim_to_object(tv)); |
6653 | } |
6654 | |
6655 | Error err = ERROR_INIT; |
6656 | Object result = fn(VIML_INTERNAL_CALL, args, &err); |
6657 | |
6658 | if (ERROR_SET(&err)) { |
6659 | emsgf_multiline((const char *)e_api_error, err.msg); |
6660 | goto end; |
6661 | } |
6662 | |
6663 | if (!object_to_vim(result, rettv, &err)) { |
6664 | EMSG2(_("Error converting the call result: %s" ), err.msg); |
6665 | } |
6666 | |
6667 | end: |
6668 | api_free_array(args); |
6669 | api_free_object(result); |
6670 | api_clear_error(&err); |
6671 | } |
6672 | |
6673 | /* |
6674 | * "abs(expr)" function |
6675 | */ |
6676 | static void f_abs(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
6677 | { |
6678 | if (argvars[0].v_type == VAR_FLOAT) { |
6679 | float_op_wrapper(argvars, rettv, (FunPtr)&fabs); |
6680 | } else { |
6681 | varnumber_T n; |
6682 | bool error = false; |
6683 | |
6684 | n = tv_get_number_chk(&argvars[0], &error); |
6685 | if (error) { |
6686 | rettv->vval.v_number = -1; |
6687 | } else if (n > 0) { |
6688 | rettv->vval.v_number = n; |
6689 | } else { |
6690 | rettv->vval.v_number = -n; |
6691 | } |
6692 | } |
6693 | } |
6694 | |
6695 | /* |
6696 | * "add(list, item)" function |
6697 | */ |
6698 | static void f_add(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
6699 | { |
6700 | rettv->vval.v_number = 1; // Default: failed. |
6701 | if (argvars[0].v_type == VAR_LIST) { |
6702 | list_T *const l = argvars[0].vval.v_list; |
6703 | if (!tv_check_lock(tv_list_locked(l), N_("add() argument" ), TV_TRANSLATE)) { |
6704 | tv_list_append_tv(l, &argvars[1]); |
6705 | tv_copy(&argvars[0], rettv); |
6706 | } |
6707 | } else { |
6708 | EMSG(_(e_listreq)); |
6709 | } |
6710 | } |
6711 | |
6712 | /* |
6713 | * "and(expr, expr)" function |
6714 | */ |
6715 | static void f_and(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
6716 | { |
6717 | rettv->vval.v_number = tv_get_number_chk(&argvars[0], NULL) |
6718 | & tv_get_number_chk(&argvars[1], NULL); |
6719 | } |
6720 | |
6721 | |
6722 | /// "api_info()" function |
6723 | static void f_api_info(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
6724 | { |
6725 | Dictionary metadata = api_metadata(); |
6726 | (void)object_to_vim(DICTIONARY_OBJ(metadata), rettv, NULL); |
6727 | api_free_dictionary(metadata); |
6728 | } |
6729 | |
6730 | // "append(lnum, string/list)" function |
6731 | static void f_append(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
6732 | { |
6733 | const linenr_T lnum = tv_get_lnum(&argvars[0]); |
6734 | |
6735 | set_buffer_lines(curbuf, lnum, true, &argvars[1], rettv); |
6736 | } |
6737 | |
6738 | // "appendbufline(buf, lnum, string/list)" function |
6739 | static void f_appendbufline(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
6740 | { |
6741 | buf_T *const buf = tv_get_buf(&argvars[0], false); |
6742 | if (buf == NULL) { |
6743 | rettv->vval.v_number = 1; // FAIL |
6744 | } else { |
6745 | const linenr_T lnum = tv_get_lnum_buf(&argvars[1], buf); |
6746 | set_buffer_lines(buf, lnum, true, &argvars[2], rettv); |
6747 | } |
6748 | } |
6749 | |
6750 | static void f_argc(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
6751 | { |
6752 | if (argvars[0].v_type == VAR_UNKNOWN) { |
6753 | // use the current window |
6754 | rettv->vval.v_number = ARGCOUNT; |
6755 | } else if (argvars[0].v_type == VAR_NUMBER |
6756 | && tv_get_number(&argvars[0]) == -1) { |
6757 | // use the global argument list |
6758 | rettv->vval.v_number = GARGCOUNT; |
6759 | } else { |
6760 | // use the argument list of the specified window |
6761 | win_T *wp = find_win_by_nr_or_id(&argvars[0]); |
6762 | if (wp != NULL) { |
6763 | rettv->vval.v_number = WARGCOUNT(wp); |
6764 | } else { |
6765 | rettv->vval.v_number = -1; |
6766 | } |
6767 | } |
6768 | } |
6769 | |
6770 | /* |
6771 | * "argidx()" function |
6772 | */ |
6773 | static void f_argidx(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
6774 | { |
6775 | rettv->vval.v_number = curwin->w_arg_idx; |
6776 | } |
6777 | |
6778 | /// "arglistid" function |
6779 | static void f_arglistid(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
6780 | { |
6781 | rettv->vval.v_number = -1; |
6782 | win_T *wp = find_tabwin(&argvars[0], &argvars[1]); |
6783 | if (wp != NULL) { |
6784 | rettv->vval.v_number = wp->w_alist->id; |
6785 | } |
6786 | } |
6787 | |
6788 | /// Get the argument list for a given window |
6789 | static void get_arglist_as_rettv(aentry_T *arglist, int argcount, |
6790 | typval_T *rettv) |
6791 | { |
6792 | tv_list_alloc_ret(rettv, argcount); |
6793 | if (arglist != NULL) { |
6794 | for (int idx = 0; idx < argcount; idx++) { |
6795 | tv_list_append_string(rettv->vval.v_list, |
6796 | (const char *)alist_name(&arglist[idx]), -1); |
6797 | } |
6798 | } |
6799 | } |
6800 | |
6801 | /* |
6802 | * "argv(nr)" function |
6803 | */ |
6804 | static void f_argv(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
6805 | { |
6806 | aentry_T *arglist = NULL; |
6807 | int argcount = -1; |
6808 | |
6809 | if (argvars[0].v_type != VAR_UNKNOWN) { |
6810 | if (argvars[1].v_type == VAR_UNKNOWN) { |
6811 | arglist = ARGLIST; |
6812 | argcount = ARGCOUNT; |
6813 | } else if (argvars[1].v_type == VAR_NUMBER |
6814 | && tv_get_number(&argvars[1]) == -1) { |
6815 | arglist = GARGLIST; |
6816 | argcount = GARGCOUNT; |
6817 | } else { |
6818 | win_T *wp = find_win_by_nr_or_id(&argvars[1]); |
6819 | if (wp != NULL) { |
6820 | // Use the argument list of the specified window |
6821 | arglist = WARGLIST(wp); |
6822 | argcount = WARGCOUNT(wp); |
6823 | } |
6824 | } |
6825 | rettv->v_type = VAR_STRING; |
6826 | rettv->vval.v_string = NULL; |
6827 | int idx = tv_get_number_chk(&argvars[0], NULL); |
6828 | if (arglist != NULL && idx >= 0 && idx < argcount) { |
6829 | rettv->vval.v_string = (char_u *)xstrdup( |
6830 | (const char *)alist_name(&arglist[idx])); |
6831 | } else if (idx == -1) { |
6832 | get_arglist_as_rettv(arglist, argcount, rettv); |
6833 | } |
6834 | } else { |
6835 | get_arglist_as_rettv(ARGLIST, ARGCOUNT, rettv); |
6836 | } |
6837 | } |
6838 | |
6839 | // Prepare "gap" for an assert error and add the sourcing position. |
6840 | static void prepare_assert_error(garray_T *gap) |
6841 | { |
6842 | char buf[NUMBUFLEN]; |
6843 | |
6844 | ga_init(gap, 1, 100); |
6845 | if (sourcing_name != NULL) { |
6846 | ga_concat(gap, sourcing_name); |
6847 | if (sourcing_lnum > 0) { |
6848 | ga_concat(gap, (char_u *)" " ); |
6849 | } |
6850 | } |
6851 | if (sourcing_lnum > 0) { |
6852 | vim_snprintf(buf, ARRAY_SIZE(buf), "line %" PRId64, (int64_t)sourcing_lnum); |
6853 | ga_concat(gap, (char_u *)buf); |
6854 | } |
6855 | if (sourcing_name != NULL || sourcing_lnum > 0) { |
6856 | ga_concat(gap, (char_u *)": " ); |
6857 | } |
6858 | } |
6859 | |
6860 | // Append "str" to "gap", escaping unprintable characters. |
6861 | // Changes NL to \n, CR to \r, etc. |
6862 | static void ga_concat_esc(garray_T *gap, char_u *str) |
6863 | { |
6864 | char_u *p; |
6865 | char_u buf[NUMBUFLEN]; |
6866 | |
6867 | if (str == NULL) { |
6868 | ga_concat(gap, (char_u *)"NULL" ); |
6869 | return; |
6870 | } |
6871 | |
6872 | for (p = str; *p != NUL; p++) { |
6873 | switch (*p) { |
6874 | case BS: ga_concat(gap, (char_u *)"\\b" ); break; |
6875 | case ESC: ga_concat(gap, (char_u *)"\\e" ); break; |
6876 | case FF: ga_concat(gap, (char_u *)"\\f" ); break; |
6877 | case NL: ga_concat(gap, (char_u *)"\\n" ); break; |
6878 | case TAB: ga_concat(gap, (char_u *)"\\t" ); break; |
6879 | case CAR: ga_concat(gap, (char_u *)"\\r" ); break; |
6880 | case '\\': ga_concat(gap, (char_u *)"\\\\" ); break; |
6881 | default: |
6882 | if (*p < ' ') { |
6883 | vim_snprintf((char *)buf, NUMBUFLEN, "\\x%02x" , *p); |
6884 | ga_concat(gap, buf); |
6885 | } else { |
6886 | ga_append(gap, *p); |
6887 | } |
6888 | break; |
6889 | } |
6890 | } |
6891 | } |
6892 | |
6893 | // Fill "gap" with information about an assert error. |
6894 | static void fill_assert_error(garray_T *gap, typval_T *opt_msg_tv, |
6895 | char_u *exp_str, typval_T *exp_tv, |
6896 | typval_T *got_tv, assert_type_T atype) |
6897 | { |
6898 | char_u *tofree; |
6899 | |
6900 | if (opt_msg_tv->v_type != VAR_UNKNOWN) { |
6901 | tofree = (char_u *)encode_tv2echo(opt_msg_tv, NULL); |
6902 | ga_concat(gap, tofree); |
6903 | xfree(tofree); |
6904 | ga_concat(gap, (char_u *)": " ); |
6905 | } |
6906 | |
6907 | if (atype == ASSERT_MATCH || atype == ASSERT_NOTMATCH) { |
6908 | ga_concat(gap, (char_u *)"Pattern " ); |
6909 | } else if (atype == ASSERT_NOTEQUAL) { |
6910 | ga_concat(gap, (char_u *)"Expected not equal to " ); |
6911 | } else { |
6912 | ga_concat(gap, (char_u *)"Expected " ); |
6913 | } |
6914 | |
6915 | if (exp_str == NULL) { |
6916 | tofree = (char_u *)encode_tv2string(exp_tv, NULL); |
6917 | ga_concat_esc(gap, tofree); |
6918 | xfree(tofree); |
6919 | } else { |
6920 | ga_concat_esc(gap, exp_str); |
6921 | } |
6922 | |
6923 | if (atype != ASSERT_NOTEQUAL) { |
6924 | if (atype == ASSERT_MATCH) { |
6925 | ga_concat(gap, (char_u *)" does not match " ); |
6926 | } else if (atype == ASSERT_NOTMATCH) { |
6927 | ga_concat(gap, (char_u *)" does match " ); |
6928 | } else { |
6929 | ga_concat(gap, (char_u *)" but got " ); |
6930 | } |
6931 | tofree = (char_u *)encode_tv2string(got_tv, NULL); |
6932 | ga_concat_esc(gap, tofree); |
6933 | xfree(tofree); |
6934 | } |
6935 | } |
6936 | |
6937 | // Add an assert error to v:errors. |
6938 | static void assert_error(garray_T *gap) |
6939 | { |
6940 | struct vimvar *vp = &vimvars[VV_ERRORS]; |
6941 | |
6942 | if (vp->vv_type != VAR_LIST || vimvars[VV_ERRORS].vv_list == NULL) { |
6943 | // Make sure v:errors is a list. |
6944 | set_vim_var_list(VV_ERRORS, tv_list_alloc(1)); |
6945 | } |
6946 | tv_list_append_string(vimvars[VV_ERRORS].vv_list, |
6947 | (const char *)gap->ga_data, (ptrdiff_t)gap->ga_len); |
6948 | } |
6949 | |
6950 | static void assert_equal_common(typval_T *argvars, assert_type_T atype) |
6951 | { |
6952 | garray_T ga; |
6953 | |
6954 | if (tv_equal(&argvars[0], &argvars[1], false, false) |
6955 | != (atype == ASSERT_EQUAL)) { |
6956 | prepare_assert_error(&ga); |
6957 | fill_assert_error(&ga, &argvars[2], NULL, |
6958 | &argvars[0], &argvars[1], atype); |
6959 | assert_error(&ga); |
6960 | ga_clear(&ga); |
6961 | } |
6962 | } |
6963 | |
6964 | static void f_assert_beeps(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
6965 | { |
6966 | const char *const cmd = tv_get_string_chk(&argvars[0]); |
6967 | garray_T ga; |
6968 | |
6969 | called_vim_beep = false; |
6970 | suppress_errthrow = true; |
6971 | emsg_silent = false; |
6972 | do_cmdline_cmd(cmd); |
6973 | if (!called_vim_beep) { |
6974 | prepare_assert_error(&ga); |
6975 | ga_concat(&ga, (const char_u *)"command did not beep: " ); |
6976 | ga_concat(&ga, (const char_u *)cmd); |
6977 | assert_error(&ga); |
6978 | ga_clear(&ga); |
6979 | } |
6980 | |
6981 | suppress_errthrow = false; |
6982 | emsg_on_display = false; |
6983 | } |
6984 | |
6985 | // "assert_equal(expected, actual[, msg])" function |
6986 | static void f_assert_equal(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
6987 | { |
6988 | assert_equal_common(argvars, ASSERT_EQUAL); |
6989 | } |
6990 | |
6991 | // "assert_notequal(expected, actual[, msg])" function |
6992 | static void f_assert_notequal(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
6993 | { |
6994 | assert_equal_common(argvars, ASSERT_NOTEQUAL); |
6995 | } |
6996 | |
6997 | /// "assert_report(msg) |
6998 | static void f_assert_report(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
6999 | { |
7000 | garray_T ga; |
7001 | |
7002 | prepare_assert_error(&ga); |
7003 | ga_concat(&ga, (const char_u *)tv_get_string(&argvars[0])); |
7004 | assert_error(&ga); |
7005 | ga_clear(&ga); |
7006 | } |
7007 | |
7008 | /// "assert_exception(string[, msg])" function |
7009 | static void f_assert_exception(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
7010 | { |
7011 | garray_T ga; |
7012 | |
7013 | const char *const error = tv_get_string_chk(&argvars[0]); |
7014 | if (vimvars[VV_EXCEPTION].vv_str == NULL) { |
7015 | prepare_assert_error(&ga); |
7016 | ga_concat(&ga, (char_u *)"v:exception is not set" ); |
7017 | assert_error(&ga); |
7018 | ga_clear(&ga); |
7019 | } else if (error != NULL |
7020 | && strstr((char *)vimvars[VV_EXCEPTION].vv_str, error) == NULL) { |
7021 | prepare_assert_error(&ga); |
7022 | fill_assert_error(&ga, &argvars[1], NULL, &argvars[0], |
7023 | &vimvars[VV_EXCEPTION].vv_tv, ASSERT_OTHER); |
7024 | assert_error(&ga); |
7025 | ga_clear(&ga); |
7026 | } |
7027 | } |
7028 | |
7029 | /// "assert_fails(cmd [, error])" function |
7030 | static void f_assert_fails(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
7031 | { |
7032 | const char *const cmd = tv_get_string_chk(&argvars[0]); |
7033 | garray_T ga; |
7034 | int save_trylevel = trylevel; |
7035 | |
7036 | // trylevel must be zero for a ":throw" command to be considered failed |
7037 | trylevel = 0; |
7038 | called_emsg = false; |
7039 | suppress_errthrow = true; |
7040 | emsg_silent = true; |
7041 | |
7042 | do_cmdline_cmd(cmd); |
7043 | if (!called_emsg) { |
7044 | prepare_assert_error(&ga); |
7045 | ga_concat(&ga, (const char_u *)"command did not fail: " ); |
7046 | ga_concat(&ga, (const char_u *)cmd); |
7047 | assert_error(&ga); |
7048 | ga_clear(&ga); |
7049 | } else if (argvars[1].v_type != VAR_UNKNOWN) { |
7050 | char buf[NUMBUFLEN]; |
7051 | const char *const error = tv_get_string_buf_chk(&argvars[1], buf); |
7052 | |
7053 | if (error == NULL |
7054 | || strstr((char *)vimvars[VV_ERRMSG].vv_str, error) == NULL) { |
7055 | prepare_assert_error(&ga); |
7056 | fill_assert_error(&ga, &argvars[2], NULL, &argvars[1], |
7057 | &vimvars[VV_ERRMSG].vv_tv, ASSERT_OTHER); |
7058 | assert_error(&ga); |
7059 | ga_clear(&ga); |
7060 | } |
7061 | } |
7062 | |
7063 | trylevel = save_trylevel; |
7064 | called_emsg = false; |
7065 | suppress_errthrow = false; |
7066 | emsg_silent = false; |
7067 | emsg_on_display = false; |
7068 | set_vim_var_string(VV_ERRMSG, NULL, 0); |
7069 | } |
7070 | |
7071 | void assert_inrange(typval_T *argvars) |
7072 | { |
7073 | bool error = false; |
7074 | const varnumber_T lower = tv_get_number_chk(&argvars[0], &error); |
7075 | const varnumber_T upper = tv_get_number_chk(&argvars[1], &error); |
7076 | const varnumber_T actual = tv_get_number_chk(&argvars[2], &error); |
7077 | |
7078 | if (error) { |
7079 | return; |
7080 | } |
7081 | if (actual < lower || actual > upper) { |
7082 | garray_T ga; |
7083 | prepare_assert_error(&ga); |
7084 | |
7085 | char msg[55]; |
7086 | vim_snprintf(msg, sizeof(msg), |
7087 | "range %" PRIdVARNUMBER " - %" PRIdVARNUMBER "," , |
7088 | lower, upper); |
7089 | fill_assert_error(&ga, &argvars[3], (char_u *)msg, NULL, &argvars[2], |
7090 | ASSERT_INRANGE); |
7091 | assert_error(&ga); |
7092 | ga_clear(&ga); |
7093 | } |
7094 | } |
7095 | |
7096 | // Common for assert_true() and assert_false(). |
7097 | static void assert_bool(typval_T *argvars, bool is_true) |
7098 | { |
7099 | bool error = false; |
7100 | garray_T ga; |
7101 | |
7102 | if ((argvars[0].v_type != VAR_NUMBER |
7103 | || (tv_get_number_chk(&argvars[0], &error) == 0) == is_true |
7104 | || error) |
7105 | && (argvars[0].v_type != VAR_SPECIAL |
7106 | || (argvars[0].vval.v_special |
7107 | != (SpecialVarValue) (is_true |
7108 | ? kSpecialVarTrue |
7109 | : kSpecialVarFalse)))) { |
7110 | prepare_assert_error(&ga); |
7111 | fill_assert_error(&ga, &argvars[1], |
7112 | (char_u *)(is_true ? "True" : "False" ), |
7113 | NULL, &argvars[0], ASSERT_OTHER); |
7114 | assert_error(&ga); |
7115 | ga_clear(&ga); |
7116 | } |
7117 | } |
7118 | |
7119 | // "assert_false(actual[, msg])" function |
7120 | static void f_assert_false(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
7121 | { |
7122 | assert_bool(argvars, false); |
7123 | } |
7124 | |
7125 | static void assert_match_common(typval_T *argvars, assert_type_T atype) |
7126 | { |
7127 | char buf1[NUMBUFLEN]; |
7128 | char buf2[NUMBUFLEN]; |
7129 | const char *const pat = tv_get_string_buf_chk(&argvars[0], buf1); |
7130 | const char *const text = tv_get_string_buf_chk(&argvars[1], buf2); |
7131 | |
7132 | if (pat == NULL || text == NULL) { |
7133 | EMSG(_(e_invarg)); |
7134 | } else if (pattern_match((char_u *)pat, (char_u *)text, false) |
7135 | != (atype == ASSERT_MATCH)) { |
7136 | garray_T ga; |
7137 | prepare_assert_error(&ga); |
7138 | fill_assert_error(&ga, &argvars[2], NULL, &argvars[0], &argvars[1], atype); |
7139 | assert_error(&ga); |
7140 | ga_clear(&ga); |
7141 | } |
7142 | } |
7143 | |
7144 | /// "assert_inrange(lower, upper[, msg])" function |
7145 | static void f_assert_inrange(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
7146 | { |
7147 | assert_inrange(argvars); |
7148 | } |
7149 | |
7150 | /// "assert_match(pattern, actual[, msg])" function |
7151 | static void f_assert_match(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
7152 | { |
7153 | assert_match_common(argvars, ASSERT_MATCH); |
7154 | } |
7155 | |
7156 | /// "assert_notmatch(pattern, actual[, msg])" function |
7157 | static void f_assert_notmatch(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
7158 | { |
7159 | assert_match_common(argvars, ASSERT_NOTMATCH); |
7160 | } |
7161 | |
7162 | // "assert_true(actual[, msg])" function |
7163 | static void f_assert_true(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
7164 | { |
7165 | assert_bool(argvars, true); |
7166 | } |
7167 | |
7168 | /* |
7169 | * "atan2()" function |
7170 | */ |
7171 | static void f_atan2(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
7172 | { |
7173 | float_T fx; |
7174 | float_T fy; |
7175 | |
7176 | rettv->v_type = VAR_FLOAT; |
7177 | if (tv_get_float_chk(argvars, &fx) && tv_get_float_chk(&argvars[1], &fy)) { |
7178 | rettv->vval.v_float = atan2(fx, fy); |
7179 | } else { |
7180 | rettv->vval.v_float = 0.0; |
7181 | } |
7182 | } |
7183 | |
7184 | /* |
7185 | * "browse(save, title, initdir, default)" function |
7186 | */ |
7187 | static void f_browse(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
7188 | { |
7189 | rettv->vval.v_string = NULL; |
7190 | rettv->v_type = VAR_STRING; |
7191 | } |
7192 | |
7193 | /* |
7194 | * "browsedir(title, initdir)" function |
7195 | */ |
7196 | static void f_browsedir(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
7197 | { |
7198 | f_browse(argvars, rettv, NULL); |
7199 | } |
7200 | |
7201 | |
7202 | /* |
7203 | * Find a buffer by number or exact name. |
7204 | */ |
7205 | static buf_T *find_buffer(typval_T *avar) |
7206 | { |
7207 | buf_T *buf = NULL; |
7208 | |
7209 | if (avar->v_type == VAR_NUMBER) |
7210 | buf = buflist_findnr((int)avar->vval.v_number); |
7211 | else if (avar->v_type == VAR_STRING && avar->vval.v_string != NULL) { |
7212 | buf = buflist_findname_exp(avar->vval.v_string); |
7213 | if (buf == NULL) { |
7214 | /* No full path name match, try a match with a URL or a "nofile" |
7215 | * buffer, these don't use the full path. */ |
7216 | FOR_ALL_BUFFERS(bp) { |
7217 | if (bp->b_fname != NULL |
7218 | && (path_with_url((char *)bp->b_fname) |
7219 | || bt_nofile(bp) |
7220 | ) |
7221 | && STRCMP(bp->b_fname, avar->vval.v_string) == 0) { |
7222 | buf = bp; |
7223 | break; |
7224 | } |
7225 | } |
7226 | } |
7227 | } |
7228 | return buf; |
7229 | } |
7230 | |
7231 | // "bufadd(expr)" function |
7232 | static void f_bufadd(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
7233 | { |
7234 | char_u *name = (char_u *)tv_get_string(&argvars[0]); |
7235 | |
7236 | rettv->vval.v_number = buflist_add(*name == NUL ? NULL : name, 0); |
7237 | } |
7238 | |
7239 | /* |
7240 | * "bufexists(expr)" function |
7241 | */ |
7242 | static void f_bufexists(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
7243 | { |
7244 | rettv->vval.v_number = (find_buffer(&argvars[0]) != NULL); |
7245 | } |
7246 | |
7247 | /* |
7248 | * "buflisted(expr)" function |
7249 | */ |
7250 | static void f_buflisted(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
7251 | { |
7252 | buf_T *buf; |
7253 | |
7254 | buf = find_buffer(&argvars[0]); |
7255 | rettv->vval.v_number = (buf != NULL && buf->b_p_bl); |
7256 | } |
7257 | |
7258 | // "bufload(expr)" function |
7259 | static void f_bufload(typval_T *argvars, typval_T *unused, FunPtr fptr) |
7260 | { |
7261 | buf_T *buf = get_buf_arg(&argvars[0]); |
7262 | |
7263 | if (buf != NULL && buf->b_ml.ml_mfp == NULL) { |
7264 | aco_save_T aco; |
7265 | |
7266 | aucmd_prepbuf(&aco, buf); |
7267 | swap_exists_action = SEA_NONE; |
7268 | open_buffer(false, NULL, 0); |
7269 | aucmd_restbuf(&aco); |
7270 | } |
7271 | } |
7272 | |
7273 | /* |
7274 | * "bufloaded(expr)" function |
7275 | */ |
7276 | static void f_bufloaded(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
7277 | { |
7278 | buf_T *buf; |
7279 | |
7280 | buf = find_buffer(&argvars[0]); |
7281 | rettv->vval.v_number = (buf != NULL && buf->b_ml.ml_mfp != NULL); |
7282 | } |
7283 | |
7284 | |
7285 | /* |
7286 | * Get buffer by number or pattern. |
7287 | */ |
7288 | static buf_T *tv_get_buf(typval_T *tv, int curtab_only) |
7289 | { |
7290 | char_u *name = tv->vval.v_string; |
7291 | int save_magic; |
7292 | char_u *save_cpo; |
7293 | buf_T *buf; |
7294 | |
7295 | if (tv->v_type == VAR_NUMBER) |
7296 | return buflist_findnr((int)tv->vval.v_number); |
7297 | if (tv->v_type != VAR_STRING) |
7298 | return NULL; |
7299 | if (name == NULL || *name == NUL) |
7300 | return curbuf; |
7301 | if (name[0] == '$' && name[1] == NUL) |
7302 | return lastbuf; |
7303 | |
7304 | // Ignore 'magic' and 'cpoptions' here to make scripts portable |
7305 | save_magic = p_magic; |
7306 | p_magic = TRUE; |
7307 | save_cpo = p_cpo; |
7308 | p_cpo = (char_u *)"" ; |
7309 | |
7310 | buf = buflist_findnr(buflist_findpat(name, name + STRLEN(name), |
7311 | TRUE, FALSE, curtab_only)); |
7312 | |
7313 | p_magic = save_magic; |
7314 | p_cpo = save_cpo; |
7315 | |
7316 | // If not found, try expanding the name, like done for bufexists(). |
7317 | if (buf == NULL) { |
7318 | buf = find_buffer(tv); |
7319 | } |
7320 | |
7321 | return buf; |
7322 | } |
7323 | |
7324 | /// Get the buffer from "arg" and give an error and return NULL if it is not |
7325 | /// valid. |
7326 | static buf_T * get_buf_arg(typval_T *arg) |
7327 | { |
7328 | buf_T *buf; |
7329 | |
7330 | emsg_off++; |
7331 | buf = tv_get_buf(arg, false); |
7332 | emsg_off--; |
7333 | if (buf == NULL) { |
7334 | EMSG2(_("E158: Invalid buffer name: %s" ), tv_get_string(arg)); |
7335 | } |
7336 | return buf; |
7337 | } |
7338 | |
7339 | /* |
7340 | * "bufname(expr)" function |
7341 | */ |
7342 | static void f_bufname(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
7343 | { |
7344 | const buf_T *buf; |
7345 | rettv->v_type = VAR_STRING; |
7346 | rettv->vval.v_string = NULL; |
7347 | if (argvars[0].v_type == VAR_UNKNOWN) { |
7348 | buf = curbuf; |
7349 | } else { |
7350 | if (!tv_check_str_or_nr(&argvars[0])) { |
7351 | return; |
7352 | } |
7353 | emsg_off++; |
7354 | buf = tv_get_buf(&argvars[0], false); |
7355 | emsg_off--; |
7356 | } |
7357 | if (buf != NULL && buf->b_fname != NULL) { |
7358 | rettv->vval.v_string = (char_u *)xstrdup((char *)buf->b_fname); |
7359 | } |
7360 | } |
7361 | |
7362 | /* |
7363 | * "bufnr(expr)" function |
7364 | */ |
7365 | static void f_bufnr(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
7366 | { |
7367 | const buf_T *buf; |
7368 | bool error = false; |
7369 | |
7370 | rettv->vval.v_number = -1; |
7371 | |
7372 | if (argvars[0].v_type == VAR_UNKNOWN) { |
7373 | buf = curbuf; |
7374 | } else { |
7375 | if (!tv_check_str_or_nr(&argvars[0])) { |
7376 | return; |
7377 | } |
7378 | emsg_off++; |
7379 | buf = tv_get_buf(&argvars[0], false); |
7380 | emsg_off--; |
7381 | } |
7382 | |
7383 | // If the buffer isn't found and the second argument is not zero create a |
7384 | // new buffer. |
7385 | const char *name; |
7386 | if (buf == NULL |
7387 | && argvars[1].v_type != VAR_UNKNOWN |
7388 | && tv_get_number_chk(&argvars[1], &error) != 0 |
7389 | && !error |
7390 | && (name = tv_get_string_chk(&argvars[0])) != NULL) { |
7391 | buf = buflist_new((char_u *)name, NULL, 1, 0); |
7392 | } |
7393 | |
7394 | if (buf != NULL) { |
7395 | rettv->vval.v_number = buf->b_fnum; |
7396 | } |
7397 | } |
7398 | |
7399 | static void buf_win_common(typval_T *argvars, typval_T *rettv, bool get_nr) |
7400 | { |
7401 | if (!tv_check_str_or_nr(&argvars[0])) { |
7402 | rettv->vval.v_number = -1; |
7403 | return; |
7404 | } |
7405 | |
7406 | emsg_off++; |
7407 | buf_T *buf = tv_get_buf(&argvars[0], true); |
7408 | if (buf == NULL) { // no need to search if buffer was not found |
7409 | rettv->vval.v_number = -1; |
7410 | goto end; |
7411 | } |
7412 | |
7413 | int winnr = 0; |
7414 | int winid; |
7415 | bool found_buf = false; |
7416 | FOR_ALL_WINDOWS_IN_TAB(wp, curtab) { |
7417 | winnr++; |
7418 | if (wp->w_buffer == buf) { |
7419 | found_buf = true; |
7420 | winid = wp->handle; |
7421 | break; |
7422 | } |
7423 | } |
7424 | rettv->vval.v_number = (found_buf ? (get_nr ? winnr : winid) : -1); |
7425 | end: |
7426 | emsg_off--; |
7427 | } |
7428 | |
7429 | /// "bufwinid(nr)" function |
7430 | static void f_bufwinid(typval_T *argvars, typval_T *rettv, FunPtr fptr) { |
7431 | buf_win_common(argvars, rettv, false); |
7432 | } |
7433 | |
7434 | /// "bufwinnr(nr)" function |
7435 | static void f_bufwinnr(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
7436 | { |
7437 | buf_win_common(argvars, rettv, true); |
7438 | } |
7439 | |
7440 | /* |
7441 | * "byte2line(byte)" function |
7442 | */ |
7443 | static void f_byte2line(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
7444 | { |
7445 | long boff = tv_get_number(&argvars[0]) - 1; |
7446 | if (boff < 0) { |
7447 | rettv->vval.v_number = -1; |
7448 | } else { |
7449 | rettv->vval.v_number = (varnumber_T)ml_find_line_or_offset(curbuf, 0, |
7450 | &boff, false); |
7451 | } |
7452 | } |
7453 | |
7454 | static void byteidx(typval_T *argvars, typval_T *rettv, int comp) |
7455 | { |
7456 | const char *const str = tv_get_string_chk(&argvars[0]); |
7457 | varnumber_T idx = tv_get_number_chk(&argvars[1], NULL); |
7458 | rettv->vval.v_number = -1; |
7459 | if (str == NULL || idx < 0) { |
7460 | return; |
7461 | } |
7462 | |
7463 | const char *t = str; |
7464 | for (; idx > 0; idx--) { |
7465 | if (*t == NUL) { // EOL reached. |
7466 | return; |
7467 | } |
7468 | if (enc_utf8 && comp) { |
7469 | t += utf_ptr2len((const char_u *)t); |
7470 | } else { |
7471 | t += (*mb_ptr2len)((const char_u *)t); |
7472 | } |
7473 | } |
7474 | rettv->vval.v_number = (varnumber_T)(t - str); |
7475 | } |
7476 | |
7477 | /* |
7478 | * "byteidx()" function |
7479 | */ |
7480 | static void f_byteidx(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
7481 | { |
7482 | byteidx(argvars, rettv, FALSE); |
7483 | } |
7484 | |
7485 | /* |
7486 | * "byteidxcomp()" function |
7487 | */ |
7488 | static void f_byteidxcomp(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
7489 | { |
7490 | byteidx(argvars, rettv, TRUE); |
7491 | } |
7492 | |
7493 | int func_call(char_u *name, typval_T *args, partial_T *partial, |
7494 | dict_T *selfdict, typval_T *rettv) |
7495 | { |
7496 | typval_T argv[MAX_FUNC_ARGS + 1]; |
7497 | int argc = 0; |
7498 | int dummy; |
7499 | int r = 0; |
7500 | |
7501 | TV_LIST_ITER(args->vval.v_list, item, { |
7502 | if (argc == MAX_FUNC_ARGS - (partial == NULL ? 0 : partial->pt_argc)) { |
7503 | EMSG(_("E699: Too many arguments" )); |
7504 | goto func_call_skip_call; |
7505 | } |
7506 | // Make a copy of each argument. This is needed to be able to set |
7507 | // v_lock to VAR_FIXED in the copy without changing the original list. |
7508 | tv_copy(TV_LIST_ITEM_TV(item), &argv[argc++]); |
7509 | }); |
7510 | |
7511 | r = call_func(name, (int)STRLEN(name), rettv, argc, argv, NULL, |
7512 | curwin->w_cursor.lnum, curwin->w_cursor.lnum, |
7513 | &dummy, true, partial, selfdict); |
7514 | |
7515 | func_call_skip_call: |
7516 | // Free the arguments. |
7517 | while (argc > 0) { |
7518 | tv_clear(&argv[--argc]); |
7519 | } |
7520 | |
7521 | return r; |
7522 | } |
7523 | |
7524 | /// "call(func, arglist [, dict])" function |
7525 | static void f_call(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
7526 | { |
7527 | if (argvars[1].v_type != VAR_LIST) { |
7528 | EMSG(_(e_listreq)); |
7529 | return; |
7530 | } |
7531 | if (argvars[1].vval.v_list == NULL) { |
7532 | return; |
7533 | } |
7534 | |
7535 | char_u *func; |
7536 | partial_T *partial = NULL; |
7537 | dict_T *selfdict = NULL; |
7538 | if (argvars[0].v_type == VAR_FUNC) { |
7539 | func = argvars[0].vval.v_string; |
7540 | } else if (argvars[0].v_type == VAR_PARTIAL) { |
7541 | partial = argvars[0].vval.v_partial; |
7542 | func = partial_name(partial); |
7543 | } else { |
7544 | func = (char_u *)tv_get_string(&argvars[0]); |
7545 | } |
7546 | if (*func == NUL) { |
7547 | return; // type error or empty name |
7548 | } |
7549 | |
7550 | if (argvars[2].v_type != VAR_UNKNOWN) { |
7551 | if (argvars[2].v_type != VAR_DICT) { |
7552 | EMSG(_(e_dictreq)); |
7553 | return; |
7554 | } |
7555 | selfdict = argvars[2].vval.v_dict; |
7556 | } |
7557 | |
7558 | func_call(func, &argvars[1], partial, selfdict, rettv); |
7559 | } |
7560 | |
7561 | /* |
7562 | * "changenr()" function |
7563 | */ |
7564 | static void f_changenr(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
7565 | { |
7566 | rettv->vval.v_number = curbuf->b_u_seq_cur; |
7567 | } |
7568 | |
7569 | // "chanclose(id[, stream])" function |
7570 | static void f_chanclose(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
7571 | { |
7572 | rettv->v_type = VAR_NUMBER; |
7573 | rettv->vval.v_number = 0; |
7574 | |
7575 | if (check_restricted() || check_secure()) { |
7576 | return; |
7577 | } |
7578 | |
7579 | if (argvars[0].v_type != VAR_NUMBER || (argvars[1].v_type != VAR_STRING |
7580 | && argvars[1].v_type != VAR_UNKNOWN)) { |
7581 | EMSG(_(e_invarg)); |
7582 | return; |
7583 | } |
7584 | |
7585 | ChannelPart part = kChannelPartAll; |
7586 | if (argvars[1].v_type == VAR_STRING) { |
7587 | char *stream = (char *)argvars[1].vval.v_string; |
7588 | if (!strcmp(stream, "stdin" )) { |
7589 | part = kChannelPartStdin; |
7590 | } else if (!strcmp(stream, "stdout" )) { |
7591 | part = kChannelPartStdout; |
7592 | } else if (!strcmp(stream, "stderr" )) { |
7593 | part = kChannelPartStderr; |
7594 | } else if (!strcmp(stream, "rpc" )) { |
7595 | part = kChannelPartRpc; |
7596 | } else { |
7597 | EMSG2(_("Invalid channel stream \"%s\"" ), stream); |
7598 | return; |
7599 | } |
7600 | } |
7601 | const char *error; |
7602 | rettv->vval.v_number = channel_close(argvars[0].vval.v_number, part, &error); |
7603 | if (!rettv->vval.v_number) { |
7604 | EMSG(error); |
7605 | } |
7606 | } |
7607 | |
7608 | // "chansend(id, data)" function |
7609 | static void f_chansend(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
7610 | { |
7611 | rettv->v_type = VAR_NUMBER; |
7612 | rettv->vval.v_number = 0; |
7613 | |
7614 | if (check_restricted() || check_secure()) { |
7615 | return; |
7616 | } |
7617 | |
7618 | if (argvars[0].v_type != VAR_NUMBER || argvars[1].v_type == VAR_UNKNOWN) { |
7619 | // First argument is the channel id and second is the data to write |
7620 | EMSG(_(e_invarg)); |
7621 | return; |
7622 | } |
7623 | |
7624 | ptrdiff_t input_len = 0; |
7625 | char *input = save_tv_as_string(&argvars[1], &input_len, false); |
7626 | if (!input) { |
7627 | // Either the error has been handled by save_tv_as_string(), |
7628 | // or there is no input to send. |
7629 | return; |
7630 | } |
7631 | uint64_t id = argvars[0].vval.v_number; |
7632 | const char *error = NULL; |
7633 | rettv->vval.v_number = channel_send(id, input, input_len, &error); |
7634 | if (error) { |
7635 | EMSG(error); |
7636 | } |
7637 | } |
7638 | |
7639 | /* |
7640 | * "char2nr(string)" function |
7641 | */ |
7642 | static void f_char2nr(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
7643 | { |
7644 | if (argvars[1].v_type != VAR_UNKNOWN) { |
7645 | if (!tv_check_num(&argvars[1])) { |
7646 | return; |
7647 | } |
7648 | } |
7649 | |
7650 | rettv->vval.v_number = utf_ptr2char( |
7651 | (const char_u *)tv_get_string(&argvars[0])); |
7652 | } |
7653 | |
7654 | /* |
7655 | * "cindent(lnum)" function |
7656 | */ |
7657 | static void f_cindent(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
7658 | { |
7659 | pos_T pos; |
7660 | linenr_T lnum; |
7661 | |
7662 | pos = curwin->w_cursor; |
7663 | lnum = tv_get_lnum(argvars); |
7664 | if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count) { |
7665 | curwin->w_cursor.lnum = lnum; |
7666 | rettv->vval.v_number = get_c_indent(); |
7667 | curwin->w_cursor = pos; |
7668 | } else |
7669 | rettv->vval.v_number = -1; |
7670 | } |
7671 | |
7672 | /* |
7673 | * "clearmatches()" function |
7674 | */ |
7675 | static void f_clearmatches(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
7676 | { |
7677 | clear_matches(curwin); |
7678 | } |
7679 | |
7680 | /* |
7681 | * "col(string)" function |
7682 | */ |
7683 | static void f_col(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
7684 | { |
7685 | colnr_T col = 0; |
7686 | pos_T *fp; |
7687 | int fnum = curbuf->b_fnum; |
7688 | |
7689 | fp = var2fpos(&argvars[0], FALSE, &fnum); |
7690 | if (fp != NULL && fnum == curbuf->b_fnum) { |
7691 | if (fp->col == MAXCOL) { |
7692 | /* '> can be MAXCOL, get the length of the line then */ |
7693 | if (fp->lnum <= curbuf->b_ml.ml_line_count) |
7694 | col = (colnr_T)STRLEN(ml_get(fp->lnum)) + 1; |
7695 | else |
7696 | col = MAXCOL; |
7697 | } else { |
7698 | col = fp->col + 1; |
7699 | /* col(".") when the cursor is on the NUL at the end of the line |
7700 | * because of "coladd" can be seen as an extra column. */ |
7701 | if (virtual_active() && fp == &curwin->w_cursor) { |
7702 | char_u *p = get_cursor_pos_ptr(); |
7703 | |
7704 | if (curwin->w_cursor.coladd >= (colnr_T)chartabsize(p, |
7705 | curwin->w_virtcol - curwin->w_cursor.coladd)) { |
7706 | int l; |
7707 | |
7708 | if (*p != NUL && p[(l = (*mb_ptr2len)(p))] == NUL) |
7709 | col += l; |
7710 | } |
7711 | } |
7712 | } |
7713 | } |
7714 | rettv->vval.v_number = col; |
7715 | } |
7716 | |
7717 | /* |
7718 | * "complete()" function |
7719 | */ |
7720 | static void f_complete(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
7721 | { |
7722 | if ((State & INSERT) == 0) { |
7723 | EMSG(_("E785: complete() can only be used in Insert mode" )); |
7724 | return; |
7725 | } |
7726 | |
7727 | /* Check for undo allowed here, because if something was already inserted |
7728 | * the line was already saved for undo and this check isn't done. */ |
7729 | if (!undo_allowed()) |
7730 | return; |
7731 | |
7732 | if (argvars[1].v_type != VAR_LIST) { |
7733 | EMSG(_(e_invarg)); |
7734 | return; |
7735 | } |
7736 | |
7737 | const colnr_T startcol = tv_get_number_chk(&argvars[0], NULL); |
7738 | if (startcol <= 0) { |
7739 | return; |
7740 | } |
7741 | |
7742 | set_completion(startcol - 1, argvars[1].vval.v_list); |
7743 | } |
7744 | |
7745 | /* |
7746 | * "complete_add()" function |
7747 | */ |
7748 | static void f_complete_add(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
7749 | { |
7750 | rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0); |
7751 | } |
7752 | |
7753 | /* |
7754 | * "complete_check()" function |
7755 | */ |
7756 | static void f_complete_check(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
7757 | { |
7758 | int saved = RedrawingDisabled; |
7759 | |
7760 | RedrawingDisabled = 0; |
7761 | ins_compl_check_keys(0, true); |
7762 | rettv->vval.v_number = compl_interrupted; |
7763 | RedrawingDisabled = saved; |
7764 | } |
7765 | |
7766 | // "complete_info()" function |
7767 | static void f_complete_info(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
7768 | { |
7769 | tv_dict_alloc_ret(rettv); |
7770 | |
7771 | list_T *what_list = NULL; |
7772 | |
7773 | if (argvars[0].v_type != VAR_UNKNOWN) { |
7774 | if (argvars[0].v_type != VAR_LIST) { |
7775 | EMSG(_(e_listreq)); |
7776 | return; |
7777 | } |
7778 | what_list = argvars[0].vval.v_list; |
7779 | } |
7780 | get_complete_info(what_list, rettv->vval.v_dict); |
7781 | } |
7782 | |
7783 | /* |
7784 | * "confirm(message, buttons[, default [, type]])" function |
7785 | */ |
7786 | static void f_confirm(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
7787 | { |
7788 | char buf[NUMBUFLEN]; |
7789 | char buf2[NUMBUFLEN]; |
7790 | const char *message; |
7791 | const char *buttons = NULL; |
7792 | int def = 1; |
7793 | int type = VIM_GENERIC; |
7794 | const char *typestr; |
7795 | bool error = false; |
7796 | |
7797 | message = tv_get_string_chk(&argvars[0]); |
7798 | if (message == NULL) { |
7799 | error = true; |
7800 | } |
7801 | if (argvars[1].v_type != VAR_UNKNOWN) { |
7802 | buttons = tv_get_string_buf_chk(&argvars[1], buf); |
7803 | if (buttons == NULL) { |
7804 | error = true; |
7805 | } |
7806 | if (argvars[2].v_type != VAR_UNKNOWN) { |
7807 | def = tv_get_number_chk(&argvars[2], &error); |
7808 | if (argvars[3].v_type != VAR_UNKNOWN) { |
7809 | typestr = tv_get_string_buf_chk(&argvars[3], buf2); |
7810 | if (typestr == NULL) { |
7811 | error = true; |
7812 | } else { |
7813 | switch (TOUPPER_ASC(*typestr)) { |
7814 | case 'E': type = VIM_ERROR; break; |
7815 | case 'Q': type = VIM_QUESTION; break; |
7816 | case 'I': type = VIM_INFO; break; |
7817 | case 'W': type = VIM_WARNING; break; |
7818 | case 'G': type = VIM_GENERIC; break; |
7819 | } |
7820 | } |
7821 | } |
7822 | } |
7823 | } |
7824 | |
7825 | if (buttons == NULL || *buttons == NUL) { |
7826 | buttons = _("&Ok" ); |
7827 | } |
7828 | |
7829 | if (!error) { |
7830 | rettv->vval.v_number = do_dialog( |
7831 | type, NULL, (char_u *)message, (char_u *)buttons, def, NULL, false); |
7832 | } |
7833 | } |
7834 | |
7835 | /* |
7836 | * "copy()" function |
7837 | */ |
7838 | static void f_copy(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
7839 | { |
7840 | var_item_copy(NULL, &argvars[0], rettv, false, 0); |
7841 | } |
7842 | |
7843 | /* |
7844 | * "count()" function |
7845 | */ |
7846 | static void f_count(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
7847 | { |
7848 | long n = 0; |
7849 | int ic = 0; |
7850 | bool error = false; |
7851 | |
7852 | if (argvars[2].v_type != VAR_UNKNOWN) { |
7853 | ic = tv_get_number_chk(&argvars[2], &error); |
7854 | } |
7855 | |
7856 | if (argvars[0].v_type == VAR_STRING) { |
7857 | const char_u *expr = (char_u *)tv_get_string_chk(&argvars[1]); |
7858 | const char_u *p = argvars[0].vval.v_string; |
7859 | |
7860 | if (!error && expr != NULL && *expr != NUL && p != NULL) { |
7861 | if (ic) { |
7862 | const size_t len = STRLEN(expr); |
7863 | |
7864 | while (*p != NUL) { |
7865 | if (mb_strnicmp(p, expr, len) == 0) { |
7866 | n++; |
7867 | p += len; |
7868 | } else { |
7869 | MB_PTR_ADV(p); |
7870 | } |
7871 | } |
7872 | } else { |
7873 | char_u *next; |
7874 | while ((next = (char_u *)strstr((char *)p, (char *)expr)) != NULL) { |
7875 | n++; |
7876 | p = next + STRLEN(expr); |
7877 | } |
7878 | } |
7879 | } |
7880 | } else if (argvars[0].v_type == VAR_LIST) { |
7881 | listitem_T *li; |
7882 | list_T *l; |
7883 | long idx; |
7884 | |
7885 | if ((l = argvars[0].vval.v_list) != NULL) { |
7886 | li = tv_list_first(l); |
7887 | if (argvars[2].v_type != VAR_UNKNOWN) { |
7888 | if (argvars[3].v_type != VAR_UNKNOWN) { |
7889 | idx = tv_get_number_chk(&argvars[3], &error); |
7890 | if (!error) { |
7891 | li = tv_list_find(l, idx); |
7892 | if (li == NULL) { |
7893 | EMSGN(_(e_listidx), idx); |
7894 | } |
7895 | } |
7896 | } |
7897 | if (error) |
7898 | li = NULL; |
7899 | } |
7900 | |
7901 | for (; li != NULL; li = TV_LIST_ITEM_NEXT(l, li)) { |
7902 | if (tv_equal(TV_LIST_ITEM_TV(li), &argvars[1], ic, false)) { |
7903 | n++; |
7904 | } |
7905 | } |
7906 | } |
7907 | } else if (argvars[0].v_type == VAR_DICT) { |
7908 | int todo; |
7909 | dict_T *d; |
7910 | hashitem_T *hi; |
7911 | |
7912 | if ((d = argvars[0].vval.v_dict) != NULL) { |
7913 | if (argvars[2].v_type != VAR_UNKNOWN) { |
7914 | if (argvars[3].v_type != VAR_UNKNOWN) { |
7915 | EMSG(_(e_invarg)); |
7916 | } |
7917 | } |
7918 | |
7919 | todo = error ? 0 : (int)d->dv_hashtab.ht_used; |
7920 | for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi) { |
7921 | if (!HASHITEM_EMPTY(hi)) { |
7922 | todo--; |
7923 | if (tv_equal(&TV_DICT_HI2DI(hi)->di_tv, &argvars[1], ic, false)) { |
7924 | n++; |
7925 | } |
7926 | } |
7927 | } |
7928 | } |
7929 | } else { |
7930 | EMSG2(_(e_listdictarg), "count()" ); |
7931 | } |
7932 | rettv->vval.v_number = n; |
7933 | } |
7934 | |
7935 | /* |
7936 | * "cscope_connection([{num} , {dbpath} [, {prepend}]])" function |
7937 | * |
7938 | * Checks the existence of a cscope connection. |
7939 | */ |
7940 | static void f_cscope_connection(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
7941 | { |
7942 | int num = 0; |
7943 | const char *dbpath = NULL; |
7944 | const char *prepend = NULL; |
7945 | char buf[NUMBUFLEN]; |
7946 | |
7947 | if (argvars[0].v_type != VAR_UNKNOWN |
7948 | && argvars[1].v_type != VAR_UNKNOWN) { |
7949 | num = (int)tv_get_number(&argvars[0]); |
7950 | dbpath = tv_get_string(&argvars[1]); |
7951 | if (argvars[2].v_type != VAR_UNKNOWN) { |
7952 | prepend = tv_get_string_buf(&argvars[2], buf); |
7953 | } |
7954 | } |
7955 | |
7956 | rettv->vval.v_number = cs_connection(num, (char_u *)dbpath, |
7957 | (char_u *)prepend); |
7958 | } |
7959 | |
7960 | /// "ctxget([{index}])" function |
7961 | static void f_ctxget(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
7962 | { |
7963 | size_t index = 0; |
7964 | if (argvars[0].v_type == VAR_NUMBER) { |
7965 | index = argvars[0].vval.v_number; |
7966 | } else if (argvars[0].v_type != VAR_UNKNOWN) { |
7967 | EMSG2(_(e_invarg2), "expected nothing or a Number as an argument" ); |
7968 | return; |
7969 | } |
7970 | |
7971 | Context *ctx = ctx_get(index); |
7972 | if (ctx == NULL) { |
7973 | EMSG3(_(e_invargNval), "index" , "out of bounds" ); |
7974 | return; |
7975 | } |
7976 | |
7977 | Dictionary ctx_dict = ctx_to_dict(ctx); |
7978 | Error err = ERROR_INIT; |
7979 | object_to_vim(DICTIONARY_OBJ(ctx_dict), rettv, &err); |
7980 | api_free_dictionary(ctx_dict); |
7981 | api_clear_error(&err); |
7982 | } |
7983 | |
7984 | /// "ctxpop()" function |
7985 | static void f_ctxpop(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
7986 | { |
7987 | if (!ctx_restore(NULL, kCtxAll)) { |
7988 | EMSG(_("Context stack is empty" )); |
7989 | } |
7990 | } |
7991 | |
7992 | /// "ctxpush([{types}])" function |
7993 | static void f_ctxpush(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
7994 | { |
7995 | int types = kCtxAll; |
7996 | if (argvars[0].v_type == VAR_LIST) { |
7997 | types = 0; |
7998 | TV_LIST_ITER(argvars[0].vval.v_list, li, { |
7999 | typval_T *tv_li = TV_LIST_ITEM_TV(li); |
8000 | if (tv_li->v_type == VAR_STRING) { |
8001 | if (strequal((char *)tv_li->vval.v_string, "regs" )) { |
8002 | types |= kCtxRegs; |
8003 | } else if (strequal((char *)tv_li->vval.v_string, "jumps" )) { |
8004 | types |= kCtxJumps; |
8005 | } else if (strequal((char *)tv_li->vval.v_string, "buflist" )) { |
8006 | types |= kCtxBuflist; |
8007 | } else if (strequal((char *)tv_li->vval.v_string, "gvars" )) { |
8008 | types |= kCtxGVars; |
8009 | } else if (strequal((char *)tv_li->vval.v_string, "sfuncs" )) { |
8010 | types |= kCtxSFuncs; |
8011 | } else if (strequal((char *)tv_li->vval.v_string, "funcs" )) { |
8012 | types |= kCtxFuncs; |
8013 | } |
8014 | } |
8015 | }); |
8016 | } else if (argvars[0].v_type != VAR_UNKNOWN) { |
8017 | EMSG2(_(e_invarg2), "expected nothing or a List as an argument" ); |
8018 | return; |
8019 | } |
8020 | ctx_save(NULL, types); |
8021 | } |
8022 | |
8023 | /// "ctxset({context}[, {index}])" function |
8024 | static void f_ctxset(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
8025 | { |
8026 | if (argvars[0].v_type != VAR_DICT) { |
8027 | EMSG2(_(e_invarg2), "expected dictionary as first argument" ); |
8028 | return; |
8029 | } |
8030 | |
8031 | size_t index = 0; |
8032 | if (argvars[1].v_type == VAR_NUMBER) { |
8033 | index = argvars[1].vval.v_number; |
8034 | } else if (argvars[1].v_type != VAR_UNKNOWN) { |
8035 | EMSG2(_(e_invarg2), "expected nothing or a Number as second argument" ); |
8036 | return; |
8037 | } |
8038 | |
8039 | Context *ctx = ctx_get(index); |
8040 | if (ctx == NULL) { |
8041 | EMSG3(_(e_invargNval), "index" , "out of bounds" ); |
8042 | return; |
8043 | } |
8044 | |
8045 | int save_did_emsg = did_emsg; |
8046 | did_emsg = false; |
8047 | |
8048 | Dictionary dict = vim_to_object(&argvars[0]).data.dictionary; |
8049 | Context tmp = CONTEXT_INIT; |
8050 | ctx_from_dict(dict, &tmp); |
8051 | |
8052 | if (did_emsg) { |
8053 | ctx_free(&tmp); |
8054 | } else { |
8055 | ctx_free(ctx); |
8056 | *ctx = tmp; |
8057 | } |
8058 | |
8059 | api_free_dictionary(dict); |
8060 | did_emsg = save_did_emsg; |
8061 | } |
8062 | |
8063 | /// "ctxsize()" function |
8064 | static void f_ctxsize(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
8065 | { |
8066 | rettv->v_type = VAR_NUMBER; |
8067 | rettv->vval.v_number = ctx_size(); |
8068 | } |
8069 | |
8070 | /// "cursor(lnum, col)" function, or |
8071 | /// "cursor(list)" |
8072 | /// |
8073 | /// Moves the cursor to the specified line and column. |
8074 | /// |
8075 | /// @returns 0 when the position could be set, -1 otherwise. |
8076 | static void f_cursor(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
8077 | { |
8078 | long line, col; |
8079 | long coladd = 0; |
8080 | bool set_curswant = true; |
8081 | |
8082 | rettv->vval.v_number = -1; |
8083 | if (argvars[1].v_type == VAR_UNKNOWN) { |
8084 | pos_T pos; |
8085 | colnr_T curswant = -1; |
8086 | |
8087 | if (list2fpos(argvars, &pos, NULL, &curswant) == FAIL) { |
8088 | EMSG(_(e_invarg)); |
8089 | return; |
8090 | } |
8091 | |
8092 | line = pos.lnum; |
8093 | col = pos.col; |
8094 | coladd = pos.coladd; |
8095 | if (curswant >= 0) { |
8096 | curwin->w_curswant = curswant - 1; |
8097 | set_curswant = false; |
8098 | } |
8099 | } else { |
8100 | line = tv_get_lnum(argvars); |
8101 | col = (long)tv_get_number_chk(&argvars[1], NULL); |
8102 | if (argvars[2].v_type != VAR_UNKNOWN) { |
8103 | coladd = (long)tv_get_number_chk(&argvars[2], NULL); |
8104 | } |
8105 | } |
8106 | if (line < 0 || col < 0 |
8107 | || coladd < 0) { |
8108 | return; // type error; errmsg already given |
8109 | } |
8110 | if (line > 0) { |
8111 | curwin->w_cursor.lnum = line; |
8112 | } |
8113 | if (col > 0) { |
8114 | curwin->w_cursor.col = col - 1; |
8115 | } |
8116 | curwin->w_cursor.coladd = coladd; |
8117 | |
8118 | // Make sure the cursor is in a valid position. |
8119 | check_cursor(); |
8120 | // Correct cursor for multi-byte character. |
8121 | if (has_mbyte) { |
8122 | mb_adjust_cursor(); |
8123 | } |
8124 | |
8125 | curwin->w_set_curswant = set_curswant; |
8126 | rettv->vval.v_number = 0; |
8127 | } |
8128 | |
8129 | /* |
8130 | * "deepcopy()" function |
8131 | */ |
8132 | static void f_deepcopy(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
8133 | { |
8134 | int noref = 0; |
8135 | |
8136 | if (argvars[1].v_type != VAR_UNKNOWN) { |
8137 | noref = tv_get_number_chk(&argvars[1], NULL); |
8138 | } |
8139 | if (noref < 0 || noref > 1) { |
8140 | EMSG(_(e_invarg)); |
8141 | } else { |
8142 | var_item_copy(NULL, &argvars[0], rettv, true, (noref == 0 |
8143 | ? get_copyID() |
8144 | : 0)); |
8145 | } |
8146 | } |
8147 | |
8148 | // "delete()" function |
8149 | static void f_delete(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
8150 | { |
8151 | rettv->vval.v_number = -1; |
8152 | if (check_restricted() || check_secure()) { |
8153 | return; |
8154 | } |
8155 | |
8156 | const char *const name = tv_get_string(&argvars[0]); |
8157 | if (*name == NUL) { |
8158 | EMSG(_(e_invarg)); |
8159 | return; |
8160 | } |
8161 | |
8162 | char nbuf[NUMBUFLEN]; |
8163 | const char *flags; |
8164 | if (argvars[1].v_type != VAR_UNKNOWN) { |
8165 | flags = tv_get_string_buf(&argvars[1], nbuf); |
8166 | } else { |
8167 | flags = "" ; |
8168 | } |
8169 | |
8170 | if (*flags == NUL) { |
8171 | // delete a file |
8172 | rettv->vval.v_number = os_remove(name) == 0 ? 0 : -1; |
8173 | } else if (strcmp(flags, "d" ) == 0) { |
8174 | // delete an empty directory |
8175 | rettv->vval.v_number = os_rmdir(name) == 0 ? 0 : -1; |
8176 | } else if (strcmp(flags, "rf" ) == 0) { |
8177 | // delete a directory recursively |
8178 | rettv->vval.v_number = delete_recursive(name); |
8179 | } else { |
8180 | emsgf(_(e_invexpr2), flags); |
8181 | } |
8182 | } |
8183 | |
8184 | // dictwatcheradd(dict, key, funcref) function |
8185 | static void f_dictwatcheradd(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
8186 | { |
8187 | if (check_restricted() || check_secure()) { |
8188 | return; |
8189 | } |
8190 | |
8191 | if (argvars[0].v_type != VAR_DICT) { |
8192 | emsgf(_(e_invarg2), "dict" ); |
8193 | return; |
8194 | } else if (argvars[0].vval.v_dict == NULL) { |
8195 | const char *const arg_errmsg = _("dictwatcheradd() argument" ); |
8196 | const size_t arg_errmsg_len = strlen(arg_errmsg); |
8197 | emsgf(_(e_readonlyvar), (int)arg_errmsg_len, arg_errmsg); |
8198 | return; |
8199 | } |
8200 | |
8201 | if (argvars[1].v_type != VAR_STRING && argvars[1].v_type != VAR_NUMBER) { |
8202 | emsgf(_(e_invarg2), "key" ); |
8203 | return; |
8204 | } |
8205 | |
8206 | const char *const key_pattern = tv_get_string_chk(argvars + 1); |
8207 | if (key_pattern == NULL) { |
8208 | return; |
8209 | } |
8210 | const size_t key_pattern_len = strlen(key_pattern); |
8211 | |
8212 | Callback callback; |
8213 | if (!callback_from_typval(&callback, &argvars[2])) { |
8214 | emsgf(_(e_invarg2), "funcref" ); |
8215 | return; |
8216 | } |
8217 | |
8218 | tv_dict_watcher_add(argvars[0].vval.v_dict, key_pattern, key_pattern_len, |
8219 | callback); |
8220 | } |
8221 | |
8222 | // dictwatcherdel(dict, key, funcref) function |
8223 | static void f_dictwatcherdel(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
8224 | { |
8225 | if (check_restricted() || check_secure()) { |
8226 | return; |
8227 | } |
8228 | |
8229 | if (argvars[0].v_type != VAR_DICT) { |
8230 | emsgf(_(e_invarg2), "dict" ); |
8231 | return; |
8232 | } |
8233 | |
8234 | if (argvars[2].v_type != VAR_FUNC && argvars[2].v_type != VAR_STRING) { |
8235 | emsgf(_(e_invarg2), "funcref" ); |
8236 | return; |
8237 | } |
8238 | |
8239 | const char *const key_pattern = tv_get_string_chk(argvars + 1); |
8240 | if (key_pattern == NULL) { |
8241 | return; |
8242 | } |
8243 | |
8244 | Callback callback; |
8245 | if (!callback_from_typval(&callback, &argvars[2])) { |
8246 | return; |
8247 | } |
8248 | |
8249 | if (!tv_dict_watcher_remove(argvars[0].vval.v_dict, key_pattern, |
8250 | strlen(key_pattern), callback)) { |
8251 | EMSG("Couldn't find a watcher matching key and callback" ); |
8252 | } |
8253 | |
8254 | callback_free(&callback); |
8255 | } |
8256 | |
8257 | /// "deletebufline()" function |
8258 | static void f_deletebufline(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
8259 | { |
8260 | linenr_T last; |
8261 | buf_T *curbuf_save = NULL; |
8262 | win_T *curwin_save = NULL; |
8263 | |
8264 | buf_T *const buf = tv_get_buf(&argvars[0], false); |
8265 | if (buf == NULL) { |
8266 | rettv->vval.v_number = 1; // FAIL |
8267 | return; |
8268 | } |
8269 | const bool is_curbuf = buf == curbuf; |
8270 | |
8271 | const linenr_T first = tv_get_lnum_buf(&argvars[1], buf); |
8272 | if (argvars[2].v_type != VAR_UNKNOWN) { |
8273 | last = tv_get_lnum_buf(&argvars[2], buf); |
8274 | } else { |
8275 | last = first; |
8276 | } |
8277 | |
8278 | if (buf->b_ml.ml_mfp == NULL || first < 1 |
8279 | || first > buf->b_ml.ml_line_count || last < first) { |
8280 | rettv->vval.v_number = 1; // FAIL |
8281 | return; |
8282 | } |
8283 | |
8284 | if (!is_curbuf) { |
8285 | curbuf_save = curbuf; |
8286 | curwin_save = curwin; |
8287 | curbuf = buf; |
8288 | find_win_for_curbuf(); |
8289 | } |
8290 | if (last > curbuf->b_ml.ml_line_count) { |
8291 | last = curbuf->b_ml.ml_line_count; |
8292 | } |
8293 | const long count = last - first + 1; |
8294 | |
8295 | // When coming here from Insert mode, sync undo, so that this can be |
8296 | // undone separately from what was previously inserted. |
8297 | if (u_sync_once == 2) { |
8298 | u_sync_once = 1; // notify that u_sync() was called |
8299 | u_sync(true); |
8300 | } |
8301 | |
8302 | if (u_save(first - 1, last + 1) == FAIL) { |
8303 | rettv->vval.v_number = 1; // FAIL |
8304 | return; |
8305 | } |
8306 | |
8307 | for (linenr_T lnum = first; lnum <= last; lnum++) { |
8308 | ml_delete(first, true); |
8309 | } |
8310 | |
8311 | FOR_ALL_TAB_WINDOWS(tp, wp) { |
8312 | if (wp->w_buffer == buf) { |
8313 | if (wp->w_cursor.lnum > last) { |
8314 | wp->w_cursor.lnum -= count; |
8315 | } else if (wp->w_cursor.lnum> first) { |
8316 | wp->w_cursor.lnum = first; |
8317 | } |
8318 | if (wp->w_cursor.lnum > wp->w_buffer->b_ml.ml_line_count) { |
8319 | wp->w_cursor.lnum = wp->w_buffer->b_ml.ml_line_count; |
8320 | } |
8321 | } |
8322 | } |
8323 | check_cursor_col(); |
8324 | deleted_lines_mark(first, count); |
8325 | |
8326 | if (!is_curbuf) { |
8327 | curbuf = curbuf_save; |
8328 | curwin = curwin_save; |
8329 | } |
8330 | } |
8331 | |
8332 | /* |
8333 | * "did_filetype()" function |
8334 | */ |
8335 | static void f_did_filetype(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
8336 | { |
8337 | rettv->vval.v_number = did_filetype; |
8338 | } |
8339 | |
8340 | /* |
8341 | * "diff_filler()" function |
8342 | */ |
8343 | static void f_diff_filler(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
8344 | { |
8345 | rettv->vval.v_number = diff_check_fill(curwin, tv_get_lnum(argvars)); |
8346 | } |
8347 | |
8348 | /* |
8349 | * "diff_hlID()" function |
8350 | */ |
8351 | static void f_diff_hlID(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
8352 | { |
8353 | linenr_T lnum = tv_get_lnum(argvars); |
8354 | static linenr_T prev_lnum = 0; |
8355 | static int changedtick = 0; |
8356 | static int fnum = 0; |
8357 | static int change_start = 0; |
8358 | static int change_end = 0; |
8359 | static hlf_T hlID = (hlf_T)0; |
8360 | int filler_lines; |
8361 | int col; |
8362 | |
8363 | if (lnum < 0) /* ignore type error in {lnum} arg */ |
8364 | lnum = 0; |
8365 | if (lnum != prev_lnum |
8366 | || changedtick != buf_get_changedtick(curbuf) |
8367 | || fnum != curbuf->b_fnum) { |
8368 | /* New line, buffer, change: need to get the values. */ |
8369 | filler_lines = diff_check(curwin, lnum); |
8370 | if (filler_lines < 0) { |
8371 | if (filler_lines == -1) { |
8372 | change_start = MAXCOL; |
8373 | change_end = -1; |
8374 | if (diff_find_change(curwin, lnum, &change_start, &change_end)) |
8375 | hlID = HLF_ADD; /* added line */ |
8376 | else |
8377 | hlID = HLF_CHD; /* changed line */ |
8378 | } else |
8379 | hlID = HLF_ADD; /* added line */ |
8380 | } else |
8381 | hlID = (hlf_T)0; |
8382 | prev_lnum = lnum; |
8383 | changedtick = buf_get_changedtick(curbuf); |
8384 | fnum = curbuf->b_fnum; |
8385 | } |
8386 | |
8387 | if (hlID == HLF_CHD || hlID == HLF_TXD) { |
8388 | col = tv_get_number(&argvars[1]) - 1; // Ignore type error in {col}. |
8389 | if (col >= change_start && col <= change_end) { |
8390 | hlID = HLF_TXD; // Changed text. |
8391 | } else { |
8392 | hlID = HLF_CHD; // Changed line. |
8393 | } |
8394 | } |
8395 | rettv->vval.v_number = hlID == (hlf_T)0 ? 0 : (int)(hlID + 1); |
8396 | } |
8397 | |
8398 | /* |
8399 | * "empty({expr})" function |
8400 | */ |
8401 | static void f_empty(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
8402 | { |
8403 | bool n = true; |
8404 | |
8405 | switch (argvars[0].v_type) { |
8406 | case VAR_STRING: |
8407 | case VAR_FUNC: { |
8408 | n = argvars[0].vval.v_string == NULL |
8409 | || *argvars[0].vval.v_string == NUL; |
8410 | break; |
8411 | } |
8412 | case VAR_PARTIAL: { |
8413 | n = false; |
8414 | break; |
8415 | } |
8416 | case VAR_NUMBER: { |
8417 | n = argvars[0].vval.v_number == 0; |
8418 | break; |
8419 | } |
8420 | case VAR_FLOAT: { |
8421 | n = argvars[0].vval.v_float == 0.0; |
8422 | break; |
8423 | } |
8424 | case VAR_LIST: { |
8425 | n = (tv_list_len(argvars[0].vval.v_list) == 0); |
8426 | break; |
8427 | } |
8428 | case VAR_DICT: { |
8429 | n = (tv_dict_len(argvars[0].vval.v_dict) == 0); |
8430 | break; |
8431 | } |
8432 | case VAR_SPECIAL: { |
8433 | // Using switch to get warning if SpecialVarValue receives more values. |
8434 | switch (argvars[0].vval.v_special) { |
8435 | case kSpecialVarTrue: { |
8436 | n = false; |
8437 | break; |
8438 | } |
8439 | case kSpecialVarFalse: |
8440 | case kSpecialVarNull: { |
8441 | n = true; |
8442 | break; |
8443 | } |
8444 | } |
8445 | break; |
8446 | } |
8447 | case VAR_UNKNOWN: { |
8448 | internal_error("f_empty(UNKNOWN)" ); |
8449 | break; |
8450 | } |
8451 | } |
8452 | |
8453 | rettv->vval.v_number = n; |
8454 | } |
8455 | |
8456 | /// "environ()" function |
8457 | static void f_environ(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
8458 | { |
8459 | tv_dict_alloc_ret(rettv); |
8460 | |
8461 | for (int i = 0; ; i++) { |
8462 | // TODO(justinmk): use os_copyfullenv from #7202 ? |
8463 | char *envname = os_getenvname_at_index((size_t)i); |
8464 | if (envname == NULL) { |
8465 | break; |
8466 | } |
8467 | const char *value = os_getenv(envname); |
8468 | tv_dict_add_str(rettv->vval.v_dict, |
8469 | (char *)envname, STRLEN((char *)envname), |
8470 | value == NULL ? "" : value); |
8471 | xfree(envname); |
8472 | } |
8473 | } |
8474 | |
8475 | /* |
8476 | * "escape({string}, {chars})" function |
8477 | */ |
8478 | static void f_escape(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
8479 | { |
8480 | char buf[NUMBUFLEN]; |
8481 | |
8482 | rettv->vval.v_string = vim_strsave_escaped( |
8483 | (const char_u *)tv_get_string(&argvars[0]), |
8484 | (const char_u *)tv_get_string_buf(&argvars[1], buf)); |
8485 | rettv->v_type = VAR_STRING; |
8486 | } |
8487 | |
8488 | /// "getenv()" function |
8489 | static void f_getenv(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
8490 | { |
8491 | char_u *p = (char_u *)vim_getenv(tv_get_string(&argvars[0])); |
8492 | |
8493 | if (p == NULL) { |
8494 | rettv->v_type = VAR_SPECIAL; |
8495 | rettv->vval.v_number = kSpecialVarNull; |
8496 | return; |
8497 | } |
8498 | rettv->vval.v_string = p; |
8499 | rettv->v_type = VAR_STRING; |
8500 | } |
8501 | |
8502 | /* |
8503 | * "eval()" function |
8504 | */ |
8505 | static void f_eval(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
8506 | { |
8507 | const char *s = tv_get_string_chk(&argvars[0]); |
8508 | if (s != NULL) { |
8509 | s = (const char *)skipwhite((const char_u *)s); |
8510 | } |
8511 | |
8512 | const char *const expr_start = s; |
8513 | if (s == NULL || eval1((char_u **)&s, rettv, true) == FAIL) { |
8514 | if (expr_start != NULL && !aborting()) { |
8515 | EMSG2(_(e_invexpr2), expr_start); |
8516 | } |
8517 | need_clr_eos = FALSE; |
8518 | rettv->v_type = VAR_NUMBER; |
8519 | rettv->vval.v_number = 0; |
8520 | } else if (*s != NUL) { |
8521 | EMSG(_(e_trailing)); |
8522 | } |
8523 | } |
8524 | |
8525 | /* |
8526 | * "eventhandler()" function |
8527 | */ |
8528 | static void f_eventhandler(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
8529 | { |
8530 | rettv->vval.v_number = vgetc_busy; |
8531 | } |
8532 | |
8533 | /* |
8534 | * "executable()" function |
8535 | */ |
8536 | static void f_executable(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
8537 | { |
8538 | const char *name = tv_get_string(&argvars[0]); |
8539 | |
8540 | // Check in $PATH and also check directly if there is a directory name |
8541 | rettv->vval.v_number = os_can_exe(name, NULL, true); |
8542 | } |
8543 | |
8544 | typedef struct { |
8545 | const list_T *const l; |
8546 | const listitem_T *li; |
8547 | } GetListLineCookie; |
8548 | |
8549 | static char_u *get_list_line(int c, void *cookie, int indent) |
8550 | { |
8551 | GetListLineCookie *const p = (GetListLineCookie *)cookie; |
8552 | |
8553 | const listitem_T *const item = p->li; |
8554 | if (item == NULL) { |
8555 | return NULL; |
8556 | } |
8557 | char buf[NUMBUFLEN]; |
8558 | const char *const s = tv_get_string_buf_chk(TV_LIST_ITEM_TV(item), buf); |
8559 | p->li = TV_LIST_ITEM_NEXT(p->l, item); |
8560 | return (char_u *)(s == NULL ? NULL : xstrdup(s)); |
8561 | } |
8562 | |
8563 | // "execute(command)" function |
8564 | static void f_execute(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
8565 | { |
8566 | const int save_msg_silent = msg_silent; |
8567 | const int save_emsg_silent = emsg_silent; |
8568 | const bool save_emsg_noredir = emsg_noredir; |
8569 | const bool save_redir_off = redir_off; |
8570 | garray_T *const save_capture_ga = capture_ga; |
8571 | const int save_msg_col = msg_col; |
8572 | bool echo_output = false; |
8573 | |
8574 | if (check_secure()) { |
8575 | return; |
8576 | } |
8577 | |
8578 | if (argvars[1].v_type != VAR_UNKNOWN) { |
8579 | char buf[NUMBUFLEN]; |
8580 | const char *const s = tv_get_string_buf_chk(&argvars[1], buf); |
8581 | |
8582 | if (s == NULL) { |
8583 | return; |
8584 | } |
8585 | if (*s == NUL) { |
8586 | echo_output = true; |
8587 | } |
8588 | if (strncmp(s, "silent" , 6) == 0) { |
8589 | msg_silent++; |
8590 | } |
8591 | if (strcmp(s, "silent!" ) == 0) { |
8592 | emsg_silent = true; |
8593 | emsg_noredir = true; |
8594 | } |
8595 | } else { |
8596 | msg_silent++; |
8597 | } |
8598 | |
8599 | garray_T capture_local; |
8600 | ga_init(&capture_local, (int)sizeof(char), 80); |
8601 | capture_ga = &capture_local; |
8602 | redir_off = false; |
8603 | if (!echo_output) { |
8604 | msg_col = 0; // prevent leading spaces |
8605 | } |
8606 | |
8607 | if (argvars[0].v_type != VAR_LIST) { |
8608 | do_cmdline_cmd(tv_get_string(&argvars[0])); |
8609 | } else if (argvars[0].vval.v_list != NULL) { |
8610 | list_T *const list = argvars[0].vval.v_list; |
8611 | tv_list_ref(list); |
8612 | GetListLineCookie cookie = { |
8613 | .l = list, |
8614 | .li = tv_list_first(list), |
8615 | }; |
8616 | do_cmdline(NULL, get_list_line, (void *)&cookie, |
8617 | DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT|DOCMD_KEYTYPED); |
8618 | tv_list_unref(list); |
8619 | } |
8620 | msg_silent = save_msg_silent; |
8621 | emsg_silent = save_emsg_silent; |
8622 | emsg_noredir = save_emsg_noredir; |
8623 | redir_off = save_redir_off; |
8624 | // "silent reg" or "silent echo x" leaves msg_col somewhere in the line. |
8625 | if (echo_output) { |
8626 | // When not working silently: put it in column zero. A following |
8627 | // "echon" will overwrite the message, unavoidably. |
8628 | msg_col = 0; |
8629 | } else { |
8630 | // When working silently: Put it back where it was, since nothing |
8631 | // should have been written. |
8632 | msg_col = save_msg_col; |
8633 | } |
8634 | |
8635 | ga_append(capture_ga, NUL); |
8636 | rettv->v_type = VAR_STRING; |
8637 | rettv->vval.v_string = capture_ga->ga_data; |
8638 | |
8639 | capture_ga = save_capture_ga; |
8640 | } |
8641 | |
8642 | /// "exepath()" function |
8643 | static void f_exepath(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
8644 | { |
8645 | const char *arg = tv_get_string(&argvars[0]); |
8646 | char *path = NULL; |
8647 | |
8648 | (void)os_can_exe(arg, &path, true); |
8649 | |
8650 | rettv->v_type = VAR_STRING; |
8651 | rettv->vval.v_string = (char_u *)path; |
8652 | } |
8653 | |
8654 | /// Find a window: When using a Window ID in any tab page, when using a number |
8655 | /// in the current tab page. |
8656 | win_T * find_win_by_nr_or_id(typval_T *vp) |
8657 | { |
8658 | int nr = (int)tv_get_number_chk(vp, NULL); |
8659 | |
8660 | if (nr >= LOWEST_WIN_ID) { |
8661 | return win_id2wp(vp); |
8662 | } |
8663 | |
8664 | return find_win_by_nr(vp, NULL); |
8665 | } |
8666 | |
8667 | /* |
8668 | * "exists()" function |
8669 | */ |
8670 | static void f_exists(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
8671 | { |
8672 | int n = false; |
8673 | int len = 0; |
8674 | |
8675 | const char *p = tv_get_string(&argvars[0]); |
8676 | if (*p == '$') { // Environment variable. |
8677 | // First try "normal" environment variables (fast). |
8678 | if (os_env_exists(p + 1)) { |
8679 | n = true; |
8680 | } else { |
8681 | // Try expanding things like $VIM and ${HOME}. |
8682 | char_u *const exp = expand_env_save((char_u *)p); |
8683 | if (exp != NULL && *exp != '$') { |
8684 | n = true; |
8685 | } |
8686 | xfree(exp); |
8687 | } |
8688 | } else if (*p == '&' || *p == '+') { // Option. |
8689 | n = (get_option_tv(&p, NULL, true) == OK); |
8690 | if (*skipwhite((const char_u *)p) != NUL) { |
8691 | n = false; // Trailing garbage. |
8692 | } |
8693 | } else if (*p == '*') { // Internal or user defined function. |
8694 | n = function_exists(p + 1, false); |
8695 | } else if (*p == ':') { |
8696 | n = cmd_exists(p + 1); |
8697 | } else if (*p == '#') { |
8698 | if (p[1] == '#') { |
8699 | n = autocmd_supported(p + 2); |
8700 | } else { |
8701 | n = au_exists(p + 1); |
8702 | } |
8703 | } else { // Internal variable. |
8704 | typval_T tv; |
8705 | |
8706 | // get_name_len() takes care of expanding curly braces |
8707 | const char *name = p; |
8708 | char *tofree; |
8709 | len = get_name_len((const char **)&p, &tofree, true, false); |
8710 | if (len > 0) { |
8711 | if (tofree != NULL) { |
8712 | name = tofree; |
8713 | } |
8714 | n = (get_var_tv(name, len, &tv, NULL, false, true) == OK); |
8715 | if (n) { |
8716 | // Handle d.key, l[idx], f(expr). |
8717 | n = (handle_subscript(&p, &tv, true, false) == OK); |
8718 | if (n) { |
8719 | tv_clear(&tv); |
8720 | } |
8721 | } |
8722 | } |
8723 | if (*p != NUL) |
8724 | n = FALSE; |
8725 | |
8726 | xfree(tofree); |
8727 | } |
8728 | |
8729 | rettv->vval.v_number = n; |
8730 | } |
8731 | |
8732 | /* |
8733 | * "expand()" function |
8734 | */ |
8735 | static void f_expand(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
8736 | { |
8737 | size_t len; |
8738 | char_u *errormsg; |
8739 | int options = WILD_SILENT|WILD_USE_NL|WILD_LIST_NOTFOUND; |
8740 | expand_T xpc; |
8741 | bool error = false; |
8742 | char_u *result; |
8743 | |
8744 | rettv->v_type = VAR_STRING; |
8745 | if (argvars[1].v_type != VAR_UNKNOWN |
8746 | && argvars[2].v_type != VAR_UNKNOWN |
8747 | && tv_get_number_chk(&argvars[2], &error) |
8748 | && !error) { |
8749 | tv_list_set_ret(rettv, NULL); |
8750 | } |
8751 | |
8752 | const char *s = tv_get_string(&argvars[0]); |
8753 | if (*s == '%' || *s == '#' || *s == '<') { |
8754 | emsg_off++; |
8755 | result = eval_vars((char_u *)s, (char_u *)s, &len, NULL, &errormsg, NULL); |
8756 | emsg_off--; |
8757 | if (rettv->v_type == VAR_LIST) { |
8758 | tv_list_alloc_ret(rettv, (result != NULL)); |
8759 | if (result != NULL) { |
8760 | tv_list_append_string(rettv->vval.v_list, (const char *)result, -1); |
8761 | } |
8762 | } else |
8763 | rettv->vval.v_string = result; |
8764 | } else { |
8765 | /* When the optional second argument is non-zero, don't remove matches |
8766 | * for 'wildignore' and don't put matches for 'suffixes' at the end. */ |
8767 | if (argvars[1].v_type != VAR_UNKNOWN |
8768 | && tv_get_number_chk(&argvars[1], &error)) { |
8769 | options |= WILD_KEEP_ALL; |
8770 | } |
8771 | if (!error) { |
8772 | ExpandInit(&xpc); |
8773 | xpc.xp_context = EXPAND_FILES; |
8774 | if (p_wic) { |
8775 | options += WILD_ICASE; |
8776 | } |
8777 | if (rettv->v_type == VAR_STRING) { |
8778 | rettv->vval.v_string = ExpandOne(&xpc, (char_u *)s, NULL, options, |
8779 | WILD_ALL); |
8780 | } else { |
8781 | ExpandOne(&xpc, (char_u *)s, NULL, options, WILD_ALL_KEEP); |
8782 | tv_list_alloc_ret(rettv, xpc.xp_numfiles); |
8783 | for (int i = 0; i < xpc.xp_numfiles; i++) { |
8784 | tv_list_append_string(rettv->vval.v_list, |
8785 | (const char *)xpc.xp_files[i], -1); |
8786 | } |
8787 | ExpandCleanup(&xpc); |
8788 | } |
8789 | } else { |
8790 | rettv->vval.v_string = NULL; |
8791 | } |
8792 | } |
8793 | } |
8794 | |
8795 | |
8796 | /// "menu_get(path [, modes])" function |
8797 | static void (typval_T *argvars, typval_T *rettv, FunPtr fptr) |
8798 | { |
8799 | tv_list_alloc_ret(rettv, kListLenMayKnow); |
8800 | int modes = MENU_ALL_MODES; |
8801 | if (argvars[1].v_type == VAR_STRING) { |
8802 | const char_u *const strmodes = (char_u *)tv_get_string(&argvars[1]); |
8803 | modes = get_menu_cmd_modes(strmodes, false, NULL, NULL); |
8804 | } |
8805 | menu_get((char_u *)tv_get_string(&argvars[0]), modes, rettv->vval.v_list); |
8806 | } |
8807 | |
8808 | /* |
8809 | * "extend(list, list [, idx])" function |
8810 | * "extend(dict, dict [, action])" function |
8811 | */ |
8812 | static void f_extend(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
8813 | { |
8814 | const char *const arg_errmsg = N_("extend() argument" ); |
8815 | |
8816 | if (argvars[0].v_type == VAR_LIST && argvars[1].v_type == VAR_LIST) { |
8817 | long before; |
8818 | bool error = false; |
8819 | |
8820 | list_T *const l1 = argvars[0].vval.v_list; |
8821 | list_T *const l2 = argvars[1].vval.v_list; |
8822 | if (!tv_check_lock(tv_list_locked(l1), arg_errmsg, TV_TRANSLATE)) { |
8823 | listitem_T *item; |
8824 | if (argvars[2].v_type != VAR_UNKNOWN) { |
8825 | before = (long)tv_get_number_chk(&argvars[2], &error); |
8826 | if (error) { |
8827 | return; // Type error; errmsg already given. |
8828 | } |
8829 | |
8830 | if (before == tv_list_len(l1)) { |
8831 | item = NULL; |
8832 | } else { |
8833 | item = tv_list_find(l1, before); |
8834 | if (item == NULL) { |
8835 | EMSGN(_(e_listidx), before); |
8836 | return; |
8837 | } |
8838 | } |
8839 | } else { |
8840 | item = NULL; |
8841 | } |
8842 | tv_list_extend(l1, l2, item); |
8843 | |
8844 | tv_copy(&argvars[0], rettv); |
8845 | } |
8846 | } else if (argvars[0].v_type == VAR_DICT && argvars[1].v_type == |
8847 | VAR_DICT) { |
8848 | dict_T *const d1 = argvars[0].vval.v_dict; |
8849 | dict_T *const d2 = argvars[1].vval.v_dict; |
8850 | if (d1 == NULL) { |
8851 | const bool locked = tv_check_lock(VAR_FIXED, arg_errmsg, TV_TRANSLATE); |
8852 | (void)locked; |
8853 | assert(locked == true); |
8854 | } else if (d2 == NULL) { |
8855 | // Do nothing |
8856 | tv_copy(&argvars[0], rettv); |
8857 | } else if (!tv_check_lock(d1->dv_lock, arg_errmsg, TV_TRANSLATE)) { |
8858 | const char *action = "force" ; |
8859 | // Check the third argument. |
8860 | if (argvars[2].v_type != VAR_UNKNOWN) { |
8861 | const char *const av[] = { "keep" , "force" , "error" }; |
8862 | |
8863 | action = tv_get_string_chk(&argvars[2]); |
8864 | if (action == NULL) { |
8865 | return; // Type error; error message already given. |
8866 | } |
8867 | size_t i; |
8868 | for (i = 0; i < ARRAY_SIZE(av); i++) { |
8869 | if (strcmp(action, av[i]) == 0) { |
8870 | break; |
8871 | } |
8872 | } |
8873 | if (i == 3) { |
8874 | EMSG2(_(e_invarg2), action); |
8875 | return; |
8876 | } |
8877 | } |
8878 | |
8879 | tv_dict_extend(d1, d2, action); |
8880 | |
8881 | tv_copy(&argvars[0], rettv); |
8882 | } |
8883 | } else { |
8884 | EMSG2(_(e_listdictarg), "extend()" ); |
8885 | } |
8886 | } |
8887 | |
8888 | /* |
8889 | * "feedkeys()" function |
8890 | */ |
8891 | static void f_feedkeys(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
8892 | { |
8893 | // This is not allowed in the sandbox. If the commands would still be |
8894 | // executed in the sandbox it would be OK, but it probably happens later, |
8895 | // when "sandbox" is no longer set. |
8896 | if (check_secure()) { |
8897 | return; |
8898 | } |
8899 | |
8900 | const char *const keys = tv_get_string(&argvars[0]); |
8901 | char nbuf[NUMBUFLEN]; |
8902 | const char *flags = NULL; |
8903 | if (argvars[1].v_type != VAR_UNKNOWN) { |
8904 | flags = tv_get_string_buf(&argvars[1], nbuf); |
8905 | } |
8906 | |
8907 | nvim_feedkeys(cstr_as_string((char *)keys), |
8908 | cstr_as_string((char *)flags), true); |
8909 | } |
8910 | |
8911 | /// "filereadable()" function |
8912 | static void f_filereadable(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
8913 | { |
8914 | const char *const p = tv_get_string(&argvars[0]); |
8915 | rettv->vval.v_number = |
8916 | (*p && !os_isdir((const char_u *)p) && os_file_is_readable(p)); |
8917 | } |
8918 | |
8919 | /* |
8920 | * Return 0 for not writable, 1 for writable file, 2 for a dir which we have |
8921 | * rights to write into. |
8922 | */ |
8923 | static void f_filewritable(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
8924 | { |
8925 | const char *filename = tv_get_string(&argvars[0]); |
8926 | rettv->vval.v_number = os_file_is_writable(filename); |
8927 | } |
8928 | |
8929 | |
8930 | static void findfilendir(typval_T *argvars, typval_T *rettv, int find_what) |
8931 | { |
8932 | char_u *fresult = NULL; |
8933 | char_u *path = *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path; |
8934 | int count = 1; |
8935 | bool first = true; |
8936 | bool error = false; |
8937 | |
8938 | rettv->vval.v_string = NULL; |
8939 | rettv->v_type = VAR_STRING; |
8940 | |
8941 | const char *fname = tv_get_string(&argvars[0]); |
8942 | |
8943 | char pathbuf[NUMBUFLEN]; |
8944 | if (argvars[1].v_type != VAR_UNKNOWN) { |
8945 | const char *p = tv_get_string_buf_chk(&argvars[1], pathbuf); |
8946 | if (p == NULL) { |
8947 | error = true; |
8948 | } else { |
8949 | if (*p != NUL) { |
8950 | path = (char_u *)p; |
8951 | } |
8952 | |
8953 | if (argvars[2].v_type != VAR_UNKNOWN) { |
8954 | count = tv_get_number_chk(&argvars[2], &error); |
8955 | } |
8956 | } |
8957 | } |
8958 | |
8959 | if (count < 0) { |
8960 | tv_list_alloc_ret(rettv, kListLenUnknown); |
8961 | } |
8962 | |
8963 | if (*fname != NUL && !error) { |
8964 | do { |
8965 | if (rettv->v_type == VAR_STRING || rettv->v_type == VAR_LIST) |
8966 | xfree(fresult); |
8967 | fresult = find_file_in_path_option(first ? (char_u *)fname : NULL, |
8968 | first ? strlen(fname) : 0, |
8969 | 0, first, path, |
8970 | find_what, curbuf->b_ffname, |
8971 | (find_what == FINDFILE_DIR |
8972 | ? (char_u *)"" |
8973 | : curbuf->b_p_sua)); |
8974 | first = false; |
8975 | |
8976 | if (fresult != NULL && rettv->v_type == VAR_LIST) { |
8977 | tv_list_append_string(rettv->vval.v_list, (const char *)fresult, -1); |
8978 | } |
8979 | } while ((rettv->v_type == VAR_LIST || --count > 0) && fresult != NULL); |
8980 | } |
8981 | |
8982 | if (rettv->v_type == VAR_STRING) |
8983 | rettv->vval.v_string = fresult; |
8984 | } |
8985 | |
8986 | |
8987 | /* |
8988 | * Implementation of map() and filter(). |
8989 | */ |
8990 | static void filter_map(typval_T *argvars, typval_T *rettv, int map) |
8991 | { |
8992 | typval_T *expr; |
8993 | list_T *l = NULL; |
8994 | dictitem_T *di; |
8995 | hashtab_T *ht; |
8996 | hashitem_T *hi; |
8997 | dict_T *d = NULL; |
8998 | typval_T save_val; |
8999 | typval_T save_key; |
9000 | int rem = false; |
9001 | int todo; |
9002 | char_u *ermsg = (char_u *)(map ? "map()" : "filter()" ); |
9003 | const char *const arg_errmsg = (map |
9004 | ? N_("map() argument" ) |
9005 | : N_("filter() argument" )); |
9006 | int save_did_emsg; |
9007 | int idx = 0; |
9008 | |
9009 | if (argvars[0].v_type == VAR_LIST) { |
9010 | tv_copy(&argvars[0], rettv); |
9011 | if ((l = argvars[0].vval.v_list) == NULL |
9012 | || (!map && tv_check_lock(tv_list_locked(l), arg_errmsg, |
9013 | TV_TRANSLATE))) { |
9014 | return; |
9015 | } |
9016 | } else if (argvars[0].v_type == VAR_DICT) { |
9017 | tv_copy(&argvars[0], rettv); |
9018 | if ((d = argvars[0].vval.v_dict) == NULL |
9019 | || (!map && tv_check_lock(d->dv_lock, arg_errmsg, TV_TRANSLATE))) { |
9020 | return; |
9021 | } |
9022 | } else { |
9023 | EMSG2(_(e_listdictarg), ermsg); |
9024 | return; |
9025 | } |
9026 | |
9027 | expr = &argvars[1]; |
9028 | // On type errors, the preceding call has already displayed an error |
9029 | // message. Avoid a misleading error message for an empty string that |
9030 | // was not passed as argument. |
9031 | if (expr->v_type != VAR_UNKNOWN) { |
9032 | prepare_vimvar(VV_VAL, &save_val); |
9033 | |
9034 | // We reset "did_emsg" to be able to detect whether an error |
9035 | // occurred during evaluation of the expression. |
9036 | save_did_emsg = did_emsg; |
9037 | did_emsg = FALSE; |
9038 | |
9039 | prepare_vimvar(VV_KEY, &save_key); |
9040 | if (argvars[0].v_type == VAR_DICT) { |
9041 | vimvars[VV_KEY].vv_type = VAR_STRING; |
9042 | |
9043 | ht = &d->dv_hashtab; |
9044 | hash_lock(ht); |
9045 | todo = (int)ht->ht_used; |
9046 | for (hi = ht->ht_array; todo > 0; ++hi) { |
9047 | if (!HASHITEM_EMPTY(hi)) { |
9048 | --todo; |
9049 | |
9050 | di = TV_DICT_HI2DI(hi); |
9051 | if (map |
9052 | && (tv_check_lock(di->di_tv.v_lock, arg_errmsg, TV_TRANSLATE) |
9053 | || var_check_ro(di->di_flags, arg_errmsg, TV_TRANSLATE))) { |
9054 | break; |
9055 | } |
9056 | |
9057 | vimvars[VV_KEY].vv_str = vim_strsave(di->di_key); |
9058 | int r = filter_map_one(&di->di_tv, expr, map, &rem); |
9059 | tv_clear(&vimvars[VV_KEY].vv_tv); |
9060 | if (r == FAIL || did_emsg) { |
9061 | break; |
9062 | } |
9063 | if (!map && rem) { |
9064 | if (var_check_fixed(di->di_flags, arg_errmsg, TV_TRANSLATE) |
9065 | || var_check_ro(di->di_flags, arg_errmsg, TV_TRANSLATE)) { |
9066 | break; |
9067 | } |
9068 | tv_dict_item_remove(d, di); |
9069 | } |
9070 | } |
9071 | } |
9072 | hash_unlock(ht); |
9073 | } else { |
9074 | assert(argvars[0].v_type == VAR_LIST); |
9075 | vimvars[VV_KEY].vv_type = VAR_NUMBER; |
9076 | |
9077 | for (listitem_T *li = tv_list_first(l); li != NULL;) { |
9078 | if (map |
9079 | && tv_check_lock(TV_LIST_ITEM_TV(li)->v_lock, arg_errmsg, |
9080 | TV_TRANSLATE)) { |
9081 | break; |
9082 | } |
9083 | vimvars[VV_KEY].vv_nr = idx; |
9084 | if (filter_map_one(TV_LIST_ITEM_TV(li), expr, map, &rem) == FAIL |
9085 | || did_emsg) { |
9086 | break; |
9087 | } |
9088 | if (!map && rem) { |
9089 | li = tv_list_item_remove(l, li); |
9090 | } else { |
9091 | li = TV_LIST_ITEM_NEXT(l, li); |
9092 | } |
9093 | idx++; |
9094 | } |
9095 | } |
9096 | |
9097 | restore_vimvar(VV_KEY, &save_key); |
9098 | restore_vimvar(VV_VAL, &save_val); |
9099 | |
9100 | did_emsg |= save_did_emsg; |
9101 | } |
9102 | } |
9103 | |
9104 | static int filter_map_one(typval_T *tv, typval_T *expr, int map, int *remp) |
9105 | FUNC_ATTR_NONNULL_ARG(1, 2) |
9106 | { |
9107 | typval_T rettv; |
9108 | typval_T argv[3]; |
9109 | int retval = FAIL; |
9110 | |
9111 | tv_copy(tv, &vimvars[VV_VAL].vv_tv); |
9112 | argv[0] = vimvars[VV_KEY].vv_tv; |
9113 | argv[1] = vimvars[VV_VAL].vv_tv; |
9114 | if (eval_expr_typval(expr, argv, 2, &rettv) == FAIL) { |
9115 | goto theend; |
9116 | } |
9117 | if (map) { |
9118 | // map(): replace the list item value. |
9119 | tv_clear(tv); |
9120 | rettv.v_lock = 0; |
9121 | *tv = rettv; |
9122 | } else { |
9123 | bool error = false; |
9124 | |
9125 | // filter(): when expr is zero remove the item |
9126 | *remp = (tv_get_number_chk(&rettv, &error) == 0); |
9127 | tv_clear(&rettv); |
9128 | // On type error, nothing has been removed; return FAIL to stop the |
9129 | // loop. The error message was given by tv_get_number_chk(). |
9130 | if (error) { |
9131 | goto theend; |
9132 | } |
9133 | } |
9134 | retval = OK; |
9135 | theend: |
9136 | tv_clear(&vimvars[VV_VAL].vv_tv); |
9137 | return retval; |
9138 | } |
9139 | |
9140 | /* |
9141 | * "filter()" function |
9142 | */ |
9143 | static void f_filter(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
9144 | { |
9145 | filter_map(argvars, rettv, FALSE); |
9146 | } |
9147 | |
9148 | /* |
9149 | * "finddir({fname}[, {path}[, {count}]])" function |
9150 | */ |
9151 | static void f_finddir(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
9152 | { |
9153 | findfilendir(argvars, rettv, FINDFILE_DIR); |
9154 | } |
9155 | |
9156 | /* |
9157 | * "findfile({fname}[, {path}[, {count}]])" function |
9158 | */ |
9159 | static void f_findfile(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
9160 | { |
9161 | findfilendir(argvars, rettv, FINDFILE_FILE); |
9162 | } |
9163 | |
9164 | /* |
9165 | * "float2nr({float})" function |
9166 | */ |
9167 | static void f_float2nr(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
9168 | { |
9169 | float_T f; |
9170 | |
9171 | if (tv_get_float_chk(argvars, &f)) { |
9172 | if (f <= -VARNUMBER_MAX + DBL_EPSILON) { |
9173 | rettv->vval.v_number = -VARNUMBER_MAX; |
9174 | } else if (f >= VARNUMBER_MAX - DBL_EPSILON) { |
9175 | rettv->vval.v_number = VARNUMBER_MAX; |
9176 | } else { |
9177 | rettv->vval.v_number = (varnumber_T)f; |
9178 | } |
9179 | } |
9180 | } |
9181 | |
9182 | /* |
9183 | * "fmod()" function |
9184 | */ |
9185 | static void f_fmod(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
9186 | { |
9187 | float_T fx; |
9188 | float_T fy; |
9189 | |
9190 | rettv->v_type = VAR_FLOAT; |
9191 | if (tv_get_float_chk(argvars, &fx) && tv_get_float_chk(&argvars[1], &fy)) { |
9192 | rettv->vval.v_float = fmod(fx, fy); |
9193 | } else { |
9194 | rettv->vval.v_float = 0.0; |
9195 | } |
9196 | } |
9197 | |
9198 | /* |
9199 | * "fnameescape({string})" function |
9200 | */ |
9201 | static void f_fnameescape(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
9202 | { |
9203 | rettv->vval.v_string = (char_u *)vim_strsave_fnameescape( |
9204 | tv_get_string(&argvars[0]), false); |
9205 | rettv->v_type = VAR_STRING; |
9206 | } |
9207 | |
9208 | /* |
9209 | * "fnamemodify({fname}, {mods})" function |
9210 | */ |
9211 | static void f_fnamemodify(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
9212 | { |
9213 | char_u *fbuf = NULL; |
9214 | size_t len; |
9215 | char buf[NUMBUFLEN]; |
9216 | const char *fname = tv_get_string_chk(&argvars[0]); |
9217 | const char *const mods = tv_get_string_buf_chk(&argvars[1], buf); |
9218 | if (fname == NULL || mods == NULL) { |
9219 | fname = NULL; |
9220 | } else { |
9221 | len = strlen(fname); |
9222 | size_t usedlen = 0; |
9223 | (void)modify_fname((char_u *)mods, false, &usedlen, |
9224 | (char_u **)&fname, &fbuf, &len); |
9225 | } |
9226 | |
9227 | rettv->v_type = VAR_STRING; |
9228 | if (fname == NULL) { |
9229 | rettv->vval.v_string = NULL; |
9230 | } else { |
9231 | rettv->vval.v_string = (char_u *)xmemdupz(fname, len); |
9232 | } |
9233 | xfree(fbuf); |
9234 | } |
9235 | |
9236 | |
9237 | /* |
9238 | * "foldclosed()" function |
9239 | */ |
9240 | static void foldclosed_both(typval_T *argvars, typval_T *rettv, int end) |
9241 | { |
9242 | const linenr_T lnum = tv_get_lnum(argvars); |
9243 | if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count) { |
9244 | linenr_T first; |
9245 | linenr_T last; |
9246 | if (hasFoldingWin(curwin, lnum, &first, &last, false, NULL)) { |
9247 | if (end) { |
9248 | rettv->vval.v_number = (varnumber_T)last; |
9249 | } else { |
9250 | rettv->vval.v_number = (varnumber_T)first; |
9251 | } |
9252 | return; |
9253 | } |
9254 | } |
9255 | rettv->vval.v_number = -1; |
9256 | } |
9257 | |
9258 | /* |
9259 | * "foldclosed()" function |
9260 | */ |
9261 | static void f_foldclosed(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
9262 | { |
9263 | foldclosed_both(argvars, rettv, FALSE); |
9264 | } |
9265 | |
9266 | /* |
9267 | * "foldclosedend()" function |
9268 | */ |
9269 | static void f_foldclosedend(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
9270 | { |
9271 | foldclosed_both(argvars, rettv, TRUE); |
9272 | } |
9273 | |
9274 | /* |
9275 | * "foldlevel()" function |
9276 | */ |
9277 | static void f_foldlevel(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
9278 | { |
9279 | const linenr_T lnum = tv_get_lnum(argvars); |
9280 | if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count) { |
9281 | rettv->vval.v_number = foldLevel(lnum); |
9282 | } |
9283 | } |
9284 | |
9285 | /* |
9286 | * "foldtext()" function |
9287 | */ |
9288 | static void f_foldtext(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
9289 | { |
9290 | linenr_T foldstart; |
9291 | linenr_T foldend; |
9292 | char_u *dashes; |
9293 | linenr_T lnum; |
9294 | char_u *s; |
9295 | char_u *r; |
9296 | int len; |
9297 | char *txt; |
9298 | |
9299 | rettv->v_type = VAR_STRING; |
9300 | rettv->vval.v_string = NULL; |
9301 | |
9302 | foldstart = (linenr_T)get_vim_var_nr(VV_FOLDSTART); |
9303 | foldend = (linenr_T)get_vim_var_nr(VV_FOLDEND); |
9304 | dashes = get_vim_var_str(VV_FOLDDASHES); |
9305 | if (foldstart > 0 && foldend <= curbuf->b_ml.ml_line_count) { |
9306 | // Find first non-empty line in the fold. |
9307 | for (lnum = foldstart; lnum < foldend; lnum++) { |
9308 | if (!linewhite(lnum)) { |
9309 | break; |
9310 | } |
9311 | } |
9312 | |
9313 | /* Find interesting text in this line. */ |
9314 | s = skipwhite(ml_get(lnum)); |
9315 | /* skip C comment-start */ |
9316 | if (s[0] == '/' && (s[1] == '*' || s[1] == '/')) { |
9317 | s = skipwhite(s + 2); |
9318 | if (*skipwhite(s) == NUL && lnum + 1 < foldend) { |
9319 | s = skipwhite(ml_get(lnum + 1)); |
9320 | if (*s == '*') |
9321 | s = skipwhite(s + 1); |
9322 | } |
9323 | } |
9324 | unsigned long count = (unsigned long)(foldend - foldstart + 1); |
9325 | txt = NGETTEXT("+-%s%3ld line: " , "+-%s%3ld lines: " , count); |
9326 | r = xmalloc(STRLEN(txt) |
9327 | + STRLEN(dashes) // for %s |
9328 | + 20 // for %3ld |
9329 | + STRLEN(s)); // concatenated |
9330 | sprintf((char *)r, txt, dashes, count); |
9331 | len = (int)STRLEN(r); |
9332 | STRCAT(r, s); |
9333 | /* remove 'foldmarker' and 'commentstring' */ |
9334 | foldtext_cleanup(r + len); |
9335 | rettv->vval.v_string = r; |
9336 | } |
9337 | } |
9338 | |
9339 | /* |
9340 | * "foldtextresult(lnum)" function |
9341 | */ |
9342 | static void f_foldtextresult(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
9343 | { |
9344 | char_u *text; |
9345 | char_u buf[FOLD_TEXT_LEN]; |
9346 | foldinfo_T foldinfo; |
9347 | int fold_count; |
9348 | static bool entered = false; |
9349 | |
9350 | rettv->v_type = VAR_STRING; |
9351 | rettv->vval.v_string = NULL; |
9352 | if (entered) { |
9353 | return; // reject recursive use |
9354 | } |
9355 | entered = true; |
9356 | linenr_T lnum = tv_get_lnum(argvars); |
9357 | // Treat illegal types and illegal string values for {lnum} the same. |
9358 | if (lnum < 0) { |
9359 | lnum = 0; |
9360 | } |
9361 | fold_count = foldedCount(curwin, lnum, &foldinfo); |
9362 | if (fold_count > 0) { |
9363 | text = get_foldtext(curwin, lnum, lnum + fold_count - 1, &foldinfo, buf); |
9364 | if (text == buf) { |
9365 | text = vim_strsave(text); |
9366 | } |
9367 | rettv->vval.v_string = text; |
9368 | } |
9369 | |
9370 | entered = false; |
9371 | } |
9372 | |
9373 | /* |
9374 | * "foreground()" function |
9375 | */ |
9376 | static void f_foreground(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
9377 | { |
9378 | } |
9379 | |
9380 | static void common_function(typval_T *argvars, typval_T *rettv, |
9381 | bool is_funcref, FunPtr fptr) |
9382 | { |
9383 | char_u *s; |
9384 | char_u *name; |
9385 | bool use_string = false; |
9386 | partial_T *arg_pt = NULL; |
9387 | char_u *trans_name = NULL; |
9388 | |
9389 | if (argvars[0].v_type == VAR_FUNC) { |
9390 | // function(MyFunc, [arg], dict) |
9391 | s = argvars[0].vval.v_string; |
9392 | } else if (argvars[0].v_type == VAR_PARTIAL |
9393 | && argvars[0].vval.v_partial != NULL) { |
9394 | // function(dict.MyFunc, [arg]) |
9395 | arg_pt = argvars[0].vval.v_partial; |
9396 | s = partial_name(arg_pt); |
9397 | } else { |
9398 | // function('MyFunc', [arg], dict) |
9399 | s = (char_u *)tv_get_string(&argvars[0]); |
9400 | use_string = true; |
9401 | } |
9402 | |
9403 | if ((use_string && vim_strchr(s, AUTOLOAD_CHAR) == NULL) || is_funcref) { |
9404 | name = s; |
9405 | trans_name = trans_function_name(&name, false, |
9406 | TFN_INT | TFN_QUIET | TFN_NO_AUTOLOAD |
9407 | | TFN_NO_DEREF, NULL, NULL); |
9408 | if (*name != NUL) { |
9409 | s = NULL; |
9410 | } |
9411 | } |
9412 | if (s == NULL || *s == NUL || (use_string && ascii_isdigit(*s)) |
9413 | || (is_funcref && trans_name == NULL)) { |
9414 | emsgf(_(e_invarg2), (use_string |
9415 | ? tv_get_string(&argvars[0]) |
9416 | : (const char *)s)); |
9417 | // Don't check an autoload name for existence here. |
9418 | } else if (trans_name != NULL |
9419 | && (is_funcref ? find_func(trans_name) == NULL |
9420 | : !translated_function_exists((const char *)trans_name))) { |
9421 | emsgf(_("E700: Unknown function: %s" ), s); |
9422 | } else { |
9423 | int dict_idx = 0; |
9424 | int arg_idx = 0; |
9425 | list_T *list = NULL; |
9426 | if (STRNCMP(s, "s:" , 2) == 0 || STRNCMP(s, "<SID>" , 5) == 0) { |
9427 | char sid_buf[25]; |
9428 | int off = *s == 's' ? 2 : 5; |
9429 | |
9430 | // Expand s: and <SID> into <SNR>nr_, so that the function can |
9431 | // also be called from another script. Using trans_function_name() |
9432 | // would also work, but some plugins depend on the name being |
9433 | // printable text. |
9434 | snprintf(sid_buf, sizeof(sid_buf), "<SNR>%" PRId64 "_" , |
9435 | (int64_t)current_sctx.sc_sid); |
9436 | name = xmalloc(STRLEN(sid_buf) + STRLEN(s + off) + 1); |
9437 | STRCPY(name, sid_buf); |
9438 | STRCAT(name, s + off); |
9439 | } else { |
9440 | name = vim_strsave(s); |
9441 | } |
9442 | |
9443 | if (argvars[1].v_type != VAR_UNKNOWN) { |
9444 | if (argvars[2].v_type != VAR_UNKNOWN) { |
9445 | // function(name, [args], dict) |
9446 | arg_idx = 1; |
9447 | dict_idx = 2; |
9448 | } else if (argvars[1].v_type == VAR_DICT) { |
9449 | // function(name, dict) |
9450 | dict_idx = 1; |
9451 | } else { |
9452 | // function(name, [args]) |
9453 | arg_idx = 1; |
9454 | } |
9455 | if (dict_idx > 0) { |
9456 | if (argvars[dict_idx].v_type != VAR_DICT) { |
9457 | EMSG(_("E922: expected a dict" )); |
9458 | xfree(name); |
9459 | goto theend; |
9460 | } |
9461 | if (argvars[dict_idx].vval.v_dict == NULL) { |
9462 | dict_idx = 0; |
9463 | } |
9464 | } |
9465 | if (arg_idx > 0) { |
9466 | if (argvars[arg_idx].v_type != VAR_LIST) { |
9467 | EMSG(_("E923: Second argument of function() must be " |
9468 | "a list or a dict" )); |
9469 | xfree(name); |
9470 | goto theend; |
9471 | } |
9472 | list = argvars[arg_idx].vval.v_list; |
9473 | if (tv_list_len(list) == 0) { |
9474 | arg_idx = 0; |
9475 | } |
9476 | } |
9477 | } |
9478 | if (dict_idx > 0 || arg_idx > 0 || arg_pt != NULL || is_funcref) { |
9479 | partial_T *const pt = xcalloc(1, sizeof(*pt)); |
9480 | |
9481 | // result is a VAR_PARTIAL |
9482 | if (arg_idx > 0 || (arg_pt != NULL && arg_pt->pt_argc > 0)) { |
9483 | const int arg_len = (arg_pt == NULL ? 0 : arg_pt->pt_argc); |
9484 | const int lv_len = tv_list_len(list); |
9485 | |
9486 | pt->pt_argc = arg_len + lv_len; |
9487 | pt->pt_argv = xmalloc(sizeof(pt->pt_argv[0]) * pt->pt_argc); |
9488 | int i = 0; |
9489 | for (; i < arg_len; i++) { |
9490 | tv_copy(&arg_pt->pt_argv[i], &pt->pt_argv[i]); |
9491 | } |
9492 | if (lv_len > 0) { |
9493 | TV_LIST_ITER(list, li, { |
9494 | tv_copy(TV_LIST_ITEM_TV(li), &pt->pt_argv[i++]); |
9495 | }); |
9496 | } |
9497 | } |
9498 | |
9499 | // For "function(dict.func, [], dict)" and "func" is a partial |
9500 | // use "dict". That is backwards compatible. |
9501 | if (dict_idx > 0) { |
9502 | // The dict is bound explicitly, pt_auto is false |
9503 | pt->pt_dict = argvars[dict_idx].vval.v_dict; |
9504 | (pt->pt_dict->dv_refcount)++; |
9505 | } else if (arg_pt != NULL) { |
9506 | // If the dict was bound automatically the result is also |
9507 | // bound automatically. |
9508 | pt->pt_dict = arg_pt->pt_dict; |
9509 | pt->pt_auto = arg_pt->pt_auto; |
9510 | if (pt->pt_dict != NULL) { |
9511 | (pt->pt_dict->dv_refcount)++; |
9512 | } |
9513 | } |
9514 | |
9515 | pt->pt_refcount = 1; |
9516 | if (arg_pt != NULL && arg_pt->pt_func != NULL) { |
9517 | pt->pt_func = arg_pt->pt_func; |
9518 | func_ptr_ref(pt->pt_func); |
9519 | xfree(name); |
9520 | } else if (is_funcref) { |
9521 | pt->pt_func = find_func(trans_name); |
9522 | func_ptr_ref(pt->pt_func); |
9523 | xfree(name); |
9524 | } else { |
9525 | pt->pt_name = name; |
9526 | func_ref(name); |
9527 | } |
9528 | |
9529 | rettv->v_type = VAR_PARTIAL; |
9530 | rettv->vval.v_partial = pt; |
9531 | } else { |
9532 | // result is a VAR_FUNC |
9533 | rettv->v_type = VAR_FUNC; |
9534 | rettv->vval.v_string = name; |
9535 | func_ref(name); |
9536 | } |
9537 | } |
9538 | theend: |
9539 | xfree(trans_name); |
9540 | } |
9541 | |
9542 | static void f_funcref(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
9543 | { |
9544 | common_function(argvars, rettv, true, fptr); |
9545 | } |
9546 | |
9547 | static void f_function(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
9548 | { |
9549 | common_function(argvars, rettv, false, fptr); |
9550 | } |
9551 | |
9552 | /// "garbagecollect()" function |
9553 | static void f_garbagecollect(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
9554 | { |
9555 | // This is postponed until we are back at the toplevel, because we may be |
9556 | // using Lists and Dicts internally. E.g.: ":echo [garbagecollect()]". |
9557 | want_garbage_collect = true; |
9558 | |
9559 | if (argvars[0].v_type != VAR_UNKNOWN && tv_get_number(&argvars[0]) == 1) { |
9560 | garbage_collect_at_exit = true; |
9561 | } |
9562 | } |
9563 | |
9564 | /* |
9565 | * "get()" function |
9566 | */ |
9567 | static void f_get(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
9568 | { |
9569 | listitem_T *li; |
9570 | list_T *l; |
9571 | dictitem_T *di; |
9572 | dict_T *d; |
9573 | typval_T *tv = NULL; |
9574 | bool what_is_dict = false; |
9575 | |
9576 | if (argvars[0].v_type == VAR_LIST) { |
9577 | if ((l = argvars[0].vval.v_list) != NULL) { |
9578 | bool error = false; |
9579 | |
9580 | li = tv_list_find(l, tv_get_number_chk(&argvars[1], &error)); |
9581 | if (!error && li != NULL) { |
9582 | tv = TV_LIST_ITEM_TV(li); |
9583 | } |
9584 | } |
9585 | } else if (argvars[0].v_type == VAR_DICT) { |
9586 | if ((d = argvars[0].vval.v_dict) != NULL) { |
9587 | di = tv_dict_find(d, tv_get_string(&argvars[1]), -1); |
9588 | if (di != NULL) { |
9589 | tv = &di->di_tv; |
9590 | } |
9591 | } |
9592 | } else if (tv_is_func(argvars[0])) { |
9593 | partial_T *pt; |
9594 | partial_T fref_pt; |
9595 | |
9596 | if (argvars[0].v_type == VAR_PARTIAL) { |
9597 | pt = argvars[0].vval.v_partial; |
9598 | } else { |
9599 | memset(&fref_pt, 0, sizeof(fref_pt)); |
9600 | fref_pt.pt_name = argvars[0].vval.v_string; |
9601 | pt = &fref_pt; |
9602 | } |
9603 | |
9604 | if (pt != NULL) { |
9605 | const char *const what = tv_get_string(&argvars[1]); |
9606 | |
9607 | if (strcmp(what, "func" ) == 0 || strcmp(what, "name" ) == 0) { |
9608 | rettv->v_type = (*what == 'f' ? VAR_FUNC : VAR_STRING); |
9609 | const char *const n = (const char *)partial_name(pt); |
9610 | assert(n != NULL); |
9611 | rettv->vval.v_string = (char_u *)xstrdup(n); |
9612 | if (rettv->v_type == VAR_FUNC) { |
9613 | func_ref(rettv->vval.v_string); |
9614 | } |
9615 | } else if (strcmp(what, "dict" ) == 0) { |
9616 | what_is_dict = true; |
9617 | if (pt->pt_dict != NULL) { |
9618 | tv_dict_set_ret(rettv, pt->pt_dict); |
9619 | } |
9620 | } else if (strcmp(what, "args" ) == 0) { |
9621 | rettv->v_type = VAR_LIST; |
9622 | if (tv_list_alloc_ret(rettv, pt->pt_argc) != NULL) { |
9623 | for (int i = 0; i < pt->pt_argc; i++) { |
9624 | tv_list_append_tv(rettv->vval.v_list, &pt->pt_argv[i]); |
9625 | } |
9626 | } |
9627 | } else { |
9628 | EMSG2(_(e_invarg2), what); |
9629 | } |
9630 | |
9631 | // When {what} == "dict" and pt->pt_dict == NULL, evaluate the |
9632 | // third argument |
9633 | if (!what_is_dict) { |
9634 | return; |
9635 | } |
9636 | } |
9637 | } else { |
9638 | EMSG2(_(e_listdictarg), "get()" ); |
9639 | } |
9640 | |
9641 | if (tv == NULL) { |
9642 | if (argvars[2].v_type != VAR_UNKNOWN) { |
9643 | tv_copy(&argvars[2], rettv); |
9644 | } |
9645 | } else { |
9646 | tv_copy(tv, rettv); |
9647 | } |
9648 | } |
9649 | |
9650 | /// Returns buffer options, variables and other attributes in a dictionary. |
9651 | static dict_T *get_buffer_info(buf_T *buf) |
9652 | { |
9653 | dict_T *const dict = tv_dict_alloc(); |
9654 | |
9655 | tv_dict_add_nr(dict, S_LEN("bufnr" ), buf->b_fnum); |
9656 | tv_dict_add_str(dict, S_LEN("name" ), |
9657 | buf->b_ffname != NULL ? (const char *)buf->b_ffname : "" ); |
9658 | tv_dict_add_nr(dict, S_LEN("lnum" ), |
9659 | buf == curbuf ? curwin->w_cursor.lnum : buflist_findlnum(buf)); |
9660 | tv_dict_add_nr(dict, S_LEN("loaded" ), buf->b_ml.ml_mfp != NULL); |
9661 | tv_dict_add_nr(dict, S_LEN("listed" ), buf->b_p_bl); |
9662 | tv_dict_add_nr(dict, S_LEN("changed" ), bufIsChanged(buf)); |
9663 | tv_dict_add_nr(dict, S_LEN("changedtick" ), buf_get_changedtick(buf)); |
9664 | tv_dict_add_nr(dict, S_LEN("hidden" ), |
9665 | buf->b_ml.ml_mfp != NULL && buf->b_nwindows == 0); |
9666 | |
9667 | // Get a reference to buffer variables |
9668 | tv_dict_add_dict(dict, S_LEN("variables" ), buf->b_vars); |
9669 | |
9670 | // List of windows displaying this buffer |
9671 | list_T *const windows = tv_list_alloc(kListLenMayKnow); |
9672 | FOR_ALL_TAB_WINDOWS(tp, wp) { |
9673 | if (wp->w_buffer == buf) { |
9674 | tv_list_append_number(windows, (varnumber_T)wp->handle); |
9675 | } |
9676 | } |
9677 | tv_dict_add_list(dict, S_LEN("windows" ), windows); |
9678 | |
9679 | if (buf->b_signlist != NULL) { |
9680 | // List of signs placed in this buffer |
9681 | tv_dict_add_list(dict, S_LEN("signs" ), get_buffer_signs(buf)); |
9682 | } |
9683 | |
9684 | return dict; |
9685 | } |
9686 | |
9687 | /// "getbufinfo()" function |
9688 | static void f_getbufinfo(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
9689 | { |
9690 | buf_T *argbuf = NULL; |
9691 | bool filtered = false; |
9692 | bool sel_buflisted = false; |
9693 | bool sel_bufloaded = false; |
9694 | bool sel_bufmodified = false; |
9695 | |
9696 | tv_list_alloc_ret(rettv, kListLenMayKnow); |
9697 | |
9698 | // List of all the buffers or selected buffers |
9699 | if (argvars[0].v_type == VAR_DICT) { |
9700 | dict_T *sel_d = argvars[0].vval.v_dict; |
9701 | |
9702 | if (sel_d != NULL) { |
9703 | dictitem_T *di; |
9704 | |
9705 | filtered = true; |
9706 | |
9707 | di = tv_dict_find(sel_d, S_LEN("buflisted" )); |
9708 | if (di != NULL && tv_get_number(&di->di_tv)) { |
9709 | sel_buflisted = true; |
9710 | } |
9711 | |
9712 | di = tv_dict_find(sel_d, S_LEN("bufloaded" )); |
9713 | if (di != NULL && tv_get_number(&di->di_tv)) { |
9714 | sel_bufloaded = true; |
9715 | } |
9716 | di = tv_dict_find(sel_d, S_LEN("bufmodified" )); |
9717 | if (di != NULL && tv_get_number(&di->di_tv)) { |
9718 | sel_bufmodified = true; |
9719 | } |
9720 | } |
9721 | } else if (argvars[0].v_type != VAR_UNKNOWN) { |
9722 | // Information about one buffer. Argument specifies the buffer |
9723 | if (tv_check_num(&argvars[0])) { // issue errmsg if type error |
9724 | emsg_off++; |
9725 | argbuf = tv_get_buf(&argvars[0], false); |
9726 | emsg_off--; |
9727 | if (argbuf == NULL) { |
9728 | return; |
9729 | } |
9730 | } |
9731 | } |
9732 | |
9733 | // Return information about all the buffers or a specified buffer |
9734 | FOR_ALL_BUFFERS(buf) { |
9735 | if (argbuf != NULL && argbuf != buf) { |
9736 | continue; |
9737 | } |
9738 | if (filtered && ((sel_bufloaded && buf->b_ml.ml_mfp == NULL) |
9739 | || (sel_buflisted && !buf->b_p_bl) |
9740 | || (sel_bufmodified && !buf->b_changed))) { |
9741 | continue; |
9742 | } |
9743 | |
9744 | dict_T *const d = get_buffer_info(buf); |
9745 | tv_list_append_dict(rettv->vval.v_list, d); |
9746 | if (argbuf != NULL) { |
9747 | return; |
9748 | } |
9749 | } |
9750 | } |
9751 | |
9752 | /* |
9753 | * Get line or list of lines from buffer "buf" into "rettv". |
9754 | * Return a range (from start to end) of lines in rettv from the specified |
9755 | * buffer. |
9756 | * If 'retlist' is TRUE, then the lines are returned as a Vim List. |
9757 | */ |
9758 | static void get_buffer_lines(buf_T *buf, linenr_T start, linenr_T end, int retlist, typval_T *rettv) |
9759 | { |
9760 | rettv->v_type = (retlist ? VAR_LIST : VAR_STRING); |
9761 | rettv->vval.v_string = NULL; |
9762 | |
9763 | if (buf == NULL || buf->b_ml.ml_mfp == NULL || start < 0 || end < start) { |
9764 | if (retlist) { |
9765 | tv_list_alloc_ret(rettv, 0); |
9766 | } |
9767 | return; |
9768 | } |
9769 | |
9770 | if (retlist) { |
9771 | if (start < 1) { |
9772 | start = 1; |
9773 | } |
9774 | if (end > buf->b_ml.ml_line_count) { |
9775 | end = buf->b_ml.ml_line_count; |
9776 | } |
9777 | tv_list_alloc_ret(rettv, end - start + 1); |
9778 | while (start <= end) { |
9779 | tv_list_append_string(rettv->vval.v_list, |
9780 | (const char *)ml_get_buf(buf, start++, false), -1); |
9781 | } |
9782 | } else { |
9783 | rettv->v_type = VAR_STRING; |
9784 | rettv->vval.v_string = ((start >= 1 && start <= buf->b_ml.ml_line_count) |
9785 | ? vim_strsave(ml_get_buf(buf, start, false)) |
9786 | : NULL); |
9787 | } |
9788 | } |
9789 | |
9790 | /// Get the line number from VimL object |
9791 | /// |
9792 | /// @note Unlike tv_get_lnum(), this one supports only "$" special string. |
9793 | /// |
9794 | /// @param[in] tv Object to get value from. Is expected to be a number or |
9795 | /// a special string "$". |
9796 | /// @param[in] buf Buffer to take last line number from in case tv is "$". May |
9797 | /// be NULL, in this case "$" results in zero return. |
9798 | /// |
9799 | /// @return Line number or 0 in case of error. |
9800 | static linenr_T tv_get_lnum_buf(const typval_T *const tv, |
9801 | const buf_T *const buf) |
9802 | FUNC_ATTR_NONNULL_ARG(1) FUNC_ATTR_WARN_UNUSED_RESULT |
9803 | { |
9804 | if (tv->v_type == VAR_STRING |
9805 | && tv->vval.v_string != NULL |
9806 | && tv->vval.v_string[0] == '$' |
9807 | && buf != NULL) { |
9808 | return buf->b_ml.ml_line_count; |
9809 | } |
9810 | return tv_get_number_chk(tv, NULL); |
9811 | } |
9812 | |
9813 | /* |
9814 | * "getbufline()" function |
9815 | */ |
9816 | static void f_getbufline(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
9817 | { |
9818 | buf_T *buf = NULL; |
9819 | |
9820 | if (tv_check_str_or_nr(&argvars[0])) { |
9821 | emsg_off++; |
9822 | buf = tv_get_buf(&argvars[0], false); |
9823 | emsg_off--; |
9824 | } |
9825 | |
9826 | const linenr_T lnum = tv_get_lnum_buf(&argvars[1], buf); |
9827 | const linenr_T end = (argvars[2].v_type == VAR_UNKNOWN |
9828 | ? lnum |
9829 | : tv_get_lnum_buf(&argvars[2], buf)); |
9830 | |
9831 | get_buffer_lines(buf, lnum, end, true, rettv); |
9832 | } |
9833 | |
9834 | /* |
9835 | * "getbufvar()" function |
9836 | */ |
9837 | static void f_getbufvar(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
9838 | { |
9839 | bool done = false; |
9840 | |
9841 | rettv->v_type = VAR_STRING; |
9842 | rettv->vval.v_string = NULL; |
9843 | |
9844 | if (!tv_check_str_or_nr(&argvars[0])) { |
9845 | goto f_getbufvar_end; |
9846 | } |
9847 | |
9848 | const char *varname = tv_get_string_chk(&argvars[1]); |
9849 | emsg_off++; |
9850 | buf_T *const buf = tv_get_buf(&argvars[0], false); |
9851 | |
9852 | if (buf != NULL && varname != NULL) { |
9853 | // set curbuf to be our buf, temporarily |
9854 | buf_T *const save_curbuf = curbuf; |
9855 | curbuf = buf; |
9856 | |
9857 | if (*varname == '&') { // buffer-local-option |
9858 | if (varname[1] == NUL) { |
9859 | // get all buffer-local options in a dict |
9860 | dict_T *opts = get_winbuf_options(true); |
9861 | |
9862 | if (opts != NULL) { |
9863 | tv_dict_set_ret(rettv, opts); |
9864 | done = true; |
9865 | } |
9866 | } else if (get_option_tv(&varname, rettv, true) == OK) { |
9867 | // buffer-local-option |
9868 | done = true; |
9869 | } |
9870 | } else { |
9871 | // Look up the variable. |
9872 | // Let getbufvar({nr}, "") return the "b:" dictionary. |
9873 | dictitem_T *const v = find_var_in_ht(&curbuf->b_vars->dv_hashtab, 'b', |
9874 | varname, strlen(varname), false); |
9875 | if (v != NULL) { |
9876 | tv_copy(&v->di_tv, rettv); |
9877 | done = true; |
9878 | } |
9879 | } |
9880 | |
9881 | // restore previous notion of curbuf |
9882 | curbuf = save_curbuf; |
9883 | } |
9884 | emsg_off--; |
9885 | |
9886 | f_getbufvar_end: |
9887 | if (!done && argvars[2].v_type != VAR_UNKNOWN) { |
9888 | // use the default value |
9889 | tv_copy(&argvars[2], rettv); |
9890 | } |
9891 | } |
9892 | |
9893 | // "getchangelist()" function |
9894 | static void f_getchangelist(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
9895 | { |
9896 | tv_list_alloc_ret(rettv, 2); |
9897 | vim_ignored = tv_get_number(&argvars[0]); // issue errmsg if type error |
9898 | emsg_off++; |
9899 | const buf_T *const buf = tv_get_buf(&argvars[0], false); |
9900 | emsg_off--; |
9901 | if (buf == NULL) { |
9902 | return; |
9903 | } |
9904 | |
9905 | list_T *const l = tv_list_alloc(buf->b_changelistlen); |
9906 | tv_list_append_list(rettv->vval.v_list, l); |
9907 | // The current window change list index tracks only the position in the |
9908 | // current buffer change list. For other buffers, use the change list |
9909 | // length as the current index. |
9910 | tv_list_append_number(rettv->vval.v_list, |
9911 | (buf == curwin->w_buffer) |
9912 | ? curwin->w_changelistidx |
9913 | : buf->b_changelistlen); |
9914 | |
9915 | for (int i = 0; i < buf->b_changelistlen; i++) { |
9916 | if (buf->b_changelist[i].mark.lnum == 0) { |
9917 | continue; |
9918 | } |
9919 | dict_T *const d = tv_dict_alloc(); |
9920 | tv_list_append_dict(l, d); |
9921 | tv_dict_add_nr(d, S_LEN("lnum" ), buf->b_changelist[i].mark.lnum); |
9922 | tv_dict_add_nr(d, S_LEN("col" ), buf->b_changelist[i].mark.col); |
9923 | tv_dict_add_nr(d, S_LEN("coladd" ), buf->b_changelist[i].mark.coladd); |
9924 | } |
9925 | } |
9926 | |
9927 | /* |
9928 | * "getchar()" function |
9929 | */ |
9930 | static void f_getchar(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
9931 | { |
9932 | varnumber_T n; |
9933 | bool error = false; |
9934 | |
9935 | no_mapping++; |
9936 | for (;; ) { |
9937 | // Position the cursor. Needed after a message that ends in a space, |
9938 | // or if event processing caused a redraw. |
9939 | ui_cursor_goto(msg_row, msg_col); |
9940 | |
9941 | if (argvars[0].v_type == VAR_UNKNOWN) { |
9942 | // getchar(): blocking wait. |
9943 | if (!(char_avail() || using_script() || input_available())) { |
9944 | (void)os_inchar(NULL, 0, -1, 0, main_loop.events); |
9945 | if (!multiqueue_empty(main_loop.events)) { |
9946 | multiqueue_process_events(main_loop.events); |
9947 | continue; |
9948 | } |
9949 | } |
9950 | n = safe_vgetc(); |
9951 | } else if (tv_get_number_chk(&argvars[0], &error) == 1) { |
9952 | // getchar(1): only check if char avail |
9953 | n = vpeekc_any(); |
9954 | } else if (error || vpeekc_any() == NUL) { |
9955 | // illegal argument or getchar(0) and no char avail: return zero |
9956 | n = 0; |
9957 | } else { |
9958 | // getchar(0) and char avail: return char |
9959 | n = safe_vgetc(); |
9960 | } |
9961 | |
9962 | if (n == K_IGNORE) { |
9963 | continue; |
9964 | } |
9965 | break; |
9966 | } |
9967 | no_mapping--; |
9968 | |
9969 | vimvars[VV_MOUSE_WIN].vv_nr = 0; |
9970 | vimvars[VV_MOUSE_WINID].vv_nr = 0; |
9971 | vimvars[VV_MOUSE_LNUM].vv_nr = 0; |
9972 | vimvars[VV_MOUSE_COL].vv_nr = 0; |
9973 | |
9974 | rettv->vval.v_number = n; |
9975 | if (IS_SPECIAL(n) || mod_mask != 0) { |
9976 | char_u temp[10]; /* modifier: 3, mbyte-char: 6, NUL: 1 */ |
9977 | int i = 0; |
9978 | |
9979 | /* Turn a special key into three bytes, plus modifier. */ |
9980 | if (mod_mask != 0) { |
9981 | temp[i++] = K_SPECIAL; |
9982 | temp[i++] = KS_MODIFIER; |
9983 | temp[i++] = mod_mask; |
9984 | } |
9985 | if (IS_SPECIAL(n)) { |
9986 | temp[i++] = K_SPECIAL; |
9987 | temp[i++] = K_SECOND(n); |
9988 | temp[i++] = K_THIRD(n); |
9989 | } else { |
9990 | i += utf_char2bytes(n, temp + i); |
9991 | } |
9992 | temp[i++] = NUL; |
9993 | rettv->v_type = VAR_STRING; |
9994 | rettv->vval.v_string = vim_strsave(temp); |
9995 | |
9996 | if (is_mouse_key(n)) { |
9997 | int row = mouse_row; |
9998 | int col = mouse_col; |
9999 | int grid = mouse_grid; |
10000 | win_T *win; |
10001 | linenr_T lnum; |
10002 | win_T *wp; |
10003 | int winnr = 1; |
10004 | |
10005 | if (row >= 0 && col >= 0) { |
10006 | /* Find the window at the mouse coordinates and compute the |
10007 | * text position. */ |
10008 | win = mouse_find_win(&grid, &row, &col); |
10009 | if (win == NULL) { |
10010 | return; |
10011 | } |
10012 | (void)mouse_comp_pos(win, &row, &col, &lnum); |
10013 | for (wp = firstwin; wp != win; wp = wp->w_next) |
10014 | ++winnr; |
10015 | vimvars[VV_MOUSE_WIN].vv_nr = winnr; |
10016 | vimvars[VV_MOUSE_WINID].vv_nr = wp->handle; |
10017 | vimvars[VV_MOUSE_LNUM].vv_nr = lnum; |
10018 | vimvars[VV_MOUSE_COL].vv_nr = col + 1; |
10019 | } |
10020 | } |
10021 | } |
10022 | } |
10023 | |
10024 | /* |
10025 | * "getcharmod()" function |
10026 | */ |
10027 | static void f_getcharmod(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
10028 | { |
10029 | rettv->vval.v_number = mod_mask; |
10030 | } |
10031 | |
10032 | /* |
10033 | * "getcharsearch()" function |
10034 | */ |
10035 | static void f_getcharsearch(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
10036 | { |
10037 | tv_dict_alloc_ret(rettv); |
10038 | |
10039 | dict_T *dict = rettv->vval.v_dict; |
10040 | |
10041 | tv_dict_add_str(dict, S_LEN("char" ), last_csearch()); |
10042 | tv_dict_add_nr(dict, S_LEN("forward" ), last_csearch_forward()); |
10043 | tv_dict_add_nr(dict, S_LEN("until" ), last_csearch_until()); |
10044 | } |
10045 | |
10046 | /* |
10047 | * "getcmdline()" function |
10048 | */ |
10049 | static void f_getcmdline(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
10050 | { |
10051 | rettv->v_type = VAR_STRING; |
10052 | rettv->vval.v_string = get_cmdline_str(); |
10053 | } |
10054 | |
10055 | /* |
10056 | * "getcmdpos()" function |
10057 | */ |
10058 | static void f_getcmdpos(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
10059 | { |
10060 | rettv->vval.v_number = get_cmdline_pos() + 1; |
10061 | } |
10062 | |
10063 | /* |
10064 | * "getcmdtype()" function |
10065 | */ |
10066 | static void f_getcmdtype(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
10067 | { |
10068 | rettv->v_type = VAR_STRING; |
10069 | rettv->vval.v_string = xmallocz(1); |
10070 | rettv->vval.v_string[0] = get_cmdline_type(); |
10071 | } |
10072 | |
10073 | /* |
10074 | * "getcmdwintype()" function |
10075 | */ |
10076 | static void f_getcmdwintype(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
10077 | { |
10078 | rettv->v_type = VAR_STRING; |
10079 | rettv->vval.v_string = NULL; |
10080 | rettv->vval.v_string = xmallocz(1); |
10081 | rettv->vval.v_string[0] = cmdwin_type; |
10082 | } |
10083 | |
10084 | // "getcompletion()" function |
10085 | static void f_getcompletion(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
10086 | { |
10087 | char_u *pat; |
10088 | expand_T xpc; |
10089 | bool filtered = false; |
10090 | int options = WILD_SILENT | WILD_USE_NL | WILD_ADD_SLASH |
10091 | | WILD_NO_BEEP; |
10092 | |
10093 | if (argvars[2].v_type != VAR_UNKNOWN) { |
10094 | filtered = (bool)tv_get_number_chk(&argvars[2], NULL); |
10095 | } |
10096 | |
10097 | if (p_wic) { |
10098 | options |= WILD_ICASE; |
10099 | } |
10100 | |
10101 | // For filtered results, 'wildignore' is used |
10102 | if (!filtered) { |
10103 | options |= WILD_KEEP_ALL; |
10104 | } |
10105 | |
10106 | if (argvars[0].v_type != VAR_STRING || argvars[1].v_type != VAR_STRING) { |
10107 | EMSG(_(e_invarg)); |
10108 | return; |
10109 | } |
10110 | |
10111 | if (strcmp(tv_get_string(&argvars[1]), "cmdline" ) == 0) { |
10112 | set_one_cmd_context(&xpc, tv_get_string(&argvars[0])); |
10113 | xpc.xp_pattern_len = STRLEN(xpc.xp_pattern); |
10114 | goto theend; |
10115 | } |
10116 | |
10117 | ExpandInit(&xpc); |
10118 | xpc.xp_pattern = (char_u *)tv_get_string(&argvars[0]); |
10119 | xpc.xp_pattern_len = STRLEN(xpc.xp_pattern); |
10120 | xpc.xp_context = cmdcomplete_str_to_type( |
10121 | (char_u *)tv_get_string(&argvars[1])); |
10122 | if (xpc.xp_context == EXPAND_NOTHING) { |
10123 | EMSG2(_(e_invarg2), argvars[1].vval.v_string); |
10124 | return; |
10125 | } |
10126 | |
10127 | if (xpc.xp_context == EXPAND_MENUS) { |
10128 | set_context_in_menu_cmd(&xpc, (char_u *)"menu" , xpc.xp_pattern, false); |
10129 | xpc.xp_pattern_len = STRLEN(xpc.xp_pattern); |
10130 | } |
10131 | |
10132 | if (xpc.xp_context == EXPAND_CSCOPE) { |
10133 | set_context_in_cscope_cmd(&xpc, (const char *)xpc.xp_pattern, CMD_cscope); |
10134 | xpc.xp_pattern_len = STRLEN(xpc.xp_pattern); |
10135 | } |
10136 | |
10137 | if (xpc.xp_context == EXPAND_SIGN) { |
10138 | set_context_in_sign_cmd(&xpc, xpc.xp_pattern); |
10139 | xpc.xp_pattern_len = STRLEN(xpc.xp_pattern); |
10140 | } |
10141 | |
10142 | theend: |
10143 | pat = addstar(xpc.xp_pattern, xpc.xp_pattern_len, xpc.xp_context); |
10144 | ExpandOne(&xpc, pat, NULL, options, WILD_ALL_KEEP); |
10145 | tv_list_alloc_ret(rettv, xpc.xp_numfiles); |
10146 | |
10147 | for (int i = 0; i < xpc.xp_numfiles; i++) { |
10148 | tv_list_append_string(rettv->vval.v_list, (const char *)xpc.xp_files[i], |
10149 | -1); |
10150 | } |
10151 | xfree(pat); |
10152 | ExpandCleanup(&xpc); |
10153 | } |
10154 | |
10155 | /// `getcwd([{win}[, {tab}]])` function |
10156 | /// |
10157 | /// Every scope not specified implies the currently selected scope object. |
10158 | /// |
10159 | /// @pre The arguments must be of type number. |
10160 | /// @pre There may not be more than two arguments. |
10161 | /// @pre An argument may not be -1 if preceding arguments are not all -1. |
10162 | /// |
10163 | /// @post The return value will be a string. |
10164 | static void f_getcwd(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
10165 | { |
10166 | // Possible scope of working directory to return. |
10167 | CdScope scope = kCdScopeInvalid; |
10168 | |
10169 | // Numbers of the scope objects (window, tab) we want the working directory |
10170 | // of. A `-1` means to skip this scope, a `0` means the current object. |
10171 | int scope_number[] = { |
10172 | [kCdScopeWindow] = 0, // Number of window to look at. |
10173 | [kCdScopeTab ] = 0, // Number of tab to look at. |
10174 | }; |
10175 | |
10176 | char_u *cwd = NULL; // Current working directory to print |
10177 | char_u *from = NULL; // The original string to copy |
10178 | |
10179 | tabpage_T *tp = curtab; // The tabpage to look at. |
10180 | win_T *win = curwin; // The window to look at. |
10181 | |
10182 | rettv->v_type = VAR_STRING; |
10183 | rettv->vval.v_string = NULL; |
10184 | |
10185 | // Pre-conditions and scope extraction together |
10186 | for (int i = MIN_CD_SCOPE; i < MAX_CD_SCOPE; i++) { |
10187 | // If there is no argument there are no more scopes after it, break out. |
10188 | if (argvars[i].v_type == VAR_UNKNOWN) { |
10189 | break; |
10190 | } |
10191 | if (argvars[i].v_type != VAR_NUMBER) { |
10192 | EMSG(_(e_invarg)); |
10193 | return; |
10194 | } |
10195 | scope_number[i] = argvars[i].vval.v_number; |
10196 | // It is an error for the scope number to be less than `-1`. |
10197 | if (scope_number[i] < -1) { |
10198 | EMSG(_(e_invarg)); |
10199 | return; |
10200 | } |
10201 | // Use the narrowest scope the user requested |
10202 | if (scope_number[i] >= 0 && scope == kCdScopeInvalid) { |
10203 | // The scope is the current iteration step. |
10204 | scope = i; |
10205 | } else if (scope_number[i] < 0) { |
10206 | scope = i + 1; |
10207 | } |
10208 | } |
10209 | |
10210 | // If the user didn't specify anything, default to window scope |
10211 | if (scope == kCdScopeInvalid) { |
10212 | scope = MIN_CD_SCOPE; |
10213 | } |
10214 | |
10215 | // Find the tabpage by number |
10216 | if (scope_number[kCdScopeTab] > 0) { |
10217 | tp = find_tabpage(scope_number[kCdScopeTab]); |
10218 | if (!tp) { |
10219 | EMSG(_("E5000: Cannot find tab number." )); |
10220 | return; |
10221 | } |
10222 | } |
10223 | |
10224 | // Find the window in `tp` by number, `NULL` if none. |
10225 | if (scope_number[kCdScopeWindow] >= 0) { |
10226 | if (scope_number[kCdScopeTab] < 0) { |
10227 | EMSG(_("E5001: Higher scope cannot be -1 if lower scope is >= 0." )); |
10228 | return; |
10229 | } |
10230 | |
10231 | if (scope_number[kCdScopeWindow] > 0) { |
10232 | win = find_win_by_nr(&argvars[0], tp); |
10233 | if (!win) { |
10234 | EMSG(_("E5002: Cannot find window number." )); |
10235 | return; |
10236 | } |
10237 | } |
10238 | } |
10239 | |
10240 | cwd = xmalloc(MAXPATHL); |
10241 | |
10242 | switch (scope) { |
10243 | case kCdScopeWindow: |
10244 | assert(win); |
10245 | from = win->w_localdir; |
10246 | if (from) { |
10247 | break; |
10248 | } |
10249 | FALLTHROUGH; |
10250 | case kCdScopeTab: |
10251 | assert(tp); |
10252 | from = tp->tp_localdir; |
10253 | if (from) { |
10254 | break; |
10255 | } |
10256 | FALLTHROUGH; |
10257 | case kCdScopeGlobal: |
10258 | if (globaldir) { // `globaldir` is not always set. |
10259 | from = globaldir; |
10260 | } else if (os_dirname(cwd, MAXPATHL) == FAIL) { // Get the OS CWD. |
10261 | from = (char_u *)"" ; // Return empty string on failure. |
10262 | } |
10263 | break; |
10264 | case kCdScopeInvalid: // We should never get here |
10265 | assert(false); |
10266 | } |
10267 | |
10268 | if (from) { |
10269 | xstrlcpy((char *)cwd, (char *)from, MAXPATHL); |
10270 | } |
10271 | |
10272 | rettv->vval.v_string = vim_strsave(cwd); |
10273 | #ifdef BACKSLASH_IN_FILENAME |
10274 | slash_adjust(rettv->vval.v_string); |
10275 | #endif |
10276 | |
10277 | xfree(cwd); |
10278 | } |
10279 | |
10280 | /* |
10281 | * "getfontname()" function |
10282 | */ |
10283 | static void f_getfontname(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
10284 | { |
10285 | rettv->v_type = VAR_STRING; |
10286 | rettv->vval.v_string = NULL; |
10287 | } |
10288 | |
10289 | /* |
10290 | * "getfperm({fname})" function |
10291 | */ |
10292 | static void f_getfperm(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
10293 | { |
10294 | char *perm = NULL; |
10295 | char_u flags[] = "rwx" ; |
10296 | |
10297 | const char *filename = tv_get_string(&argvars[0]); |
10298 | int32_t file_perm = os_getperm(filename); |
10299 | if (file_perm >= 0) { |
10300 | perm = xstrdup("---------" ); |
10301 | for (int i = 0; i < 9; i++) { |
10302 | if (file_perm & (1 << (8 - i))) { |
10303 | perm[i] = flags[i % 3]; |
10304 | } |
10305 | } |
10306 | } |
10307 | rettv->v_type = VAR_STRING; |
10308 | rettv->vval.v_string = (char_u *)perm; |
10309 | } |
10310 | |
10311 | /* |
10312 | * "getfsize({fname})" function |
10313 | */ |
10314 | static void f_getfsize(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
10315 | { |
10316 | const char *fname = tv_get_string(&argvars[0]); |
10317 | |
10318 | rettv->v_type = VAR_NUMBER; |
10319 | |
10320 | FileInfo file_info; |
10321 | if (os_fileinfo(fname, &file_info)) { |
10322 | uint64_t filesize = os_fileinfo_size(&file_info); |
10323 | if (os_isdir((const char_u *)fname)) { |
10324 | rettv->vval.v_number = 0; |
10325 | } else { |
10326 | rettv->vval.v_number = (varnumber_T)filesize; |
10327 | |
10328 | /* non-perfect check for overflow */ |
10329 | if ((uint64_t)rettv->vval.v_number != filesize) { |
10330 | rettv->vval.v_number = -2; |
10331 | } |
10332 | } |
10333 | } else { |
10334 | rettv->vval.v_number = -1; |
10335 | } |
10336 | } |
10337 | |
10338 | /* |
10339 | * "getftime({fname})" function |
10340 | */ |
10341 | static void f_getftime(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
10342 | { |
10343 | const char *fname = tv_get_string(&argvars[0]); |
10344 | |
10345 | FileInfo file_info; |
10346 | if (os_fileinfo(fname, &file_info)) { |
10347 | rettv->vval.v_number = (varnumber_T)file_info.stat.st_mtim.tv_sec; |
10348 | } else { |
10349 | rettv->vval.v_number = -1; |
10350 | } |
10351 | } |
10352 | |
10353 | /* |
10354 | * "getftype({fname})" function |
10355 | */ |
10356 | static void f_getftype(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
10357 | { |
10358 | char_u *type = NULL; |
10359 | char *t; |
10360 | |
10361 | const char *fname = tv_get_string(&argvars[0]); |
10362 | |
10363 | rettv->v_type = VAR_STRING; |
10364 | FileInfo file_info; |
10365 | if (os_fileinfo_link(fname, &file_info)) { |
10366 | uint64_t mode = file_info.stat.st_mode; |
10367 | #ifdef S_ISREG |
10368 | if (S_ISREG(mode)) |
10369 | t = "file" ; |
10370 | else if (S_ISDIR(mode)) |
10371 | t = "dir" ; |
10372 | # ifdef S_ISLNK |
10373 | else if (S_ISLNK(mode)) |
10374 | t = "link" ; |
10375 | # endif |
10376 | # ifdef S_ISBLK |
10377 | else if (S_ISBLK(mode)) |
10378 | t = "bdev" ; |
10379 | # endif |
10380 | # ifdef S_ISCHR |
10381 | else if (S_ISCHR(mode)) |
10382 | t = "cdev" ; |
10383 | # endif |
10384 | # ifdef S_ISFIFO |
10385 | else if (S_ISFIFO(mode)) |
10386 | t = "fifo" ; |
10387 | # endif |
10388 | # ifdef S_ISSOCK |
10389 | else if (S_ISSOCK(mode)) |
10390 | t = "socket" ; |
10391 | # endif |
10392 | else |
10393 | t = "other" ; |
10394 | #else |
10395 | # ifdef S_IFMT |
10396 | switch (mode & S_IFMT) { |
10397 | case S_IFREG: t = "file" ; break; |
10398 | case S_IFDIR: t = "dir" ; break; |
10399 | # ifdef S_IFLNK |
10400 | case S_IFLNK: t = "link" ; break; |
10401 | # endif |
10402 | # ifdef S_IFBLK |
10403 | case S_IFBLK: t = "bdev" ; break; |
10404 | # endif |
10405 | # ifdef S_IFCHR |
10406 | case S_IFCHR: t = "cdev" ; break; |
10407 | # endif |
10408 | # ifdef S_IFIFO |
10409 | case S_IFIFO: t = "fifo" ; break; |
10410 | # endif |
10411 | # ifdef S_IFSOCK |
10412 | case S_IFSOCK: t = "socket" ; break; |
10413 | # endif |
10414 | default: t = "other" ; |
10415 | } |
10416 | # else |
10417 | if (os_isdir((const char_u *)fname)) { |
10418 | t = "dir" ; |
10419 | } else { |
10420 | t = "file" ; |
10421 | } |
10422 | # endif |
10423 | #endif |
10424 | type = vim_strsave((char_u *)t); |
10425 | } |
10426 | rettv->vval.v_string = type; |
10427 | } |
10428 | |
10429 | // "getjumplist()" function |
10430 | static void f_getjumplist(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
10431 | { |
10432 | tv_list_alloc_ret(rettv, kListLenMayKnow); |
10433 | win_T *const wp = find_tabwin(&argvars[0], &argvars[1]); |
10434 | if (wp == NULL) { |
10435 | return; |
10436 | } |
10437 | |
10438 | cleanup_jumplist(wp, true); |
10439 | |
10440 | list_T *const l = tv_list_alloc(wp->w_jumplistlen); |
10441 | tv_list_append_list(rettv->vval.v_list, l); |
10442 | tv_list_append_number(rettv->vval.v_list, wp->w_jumplistidx); |
10443 | |
10444 | for (int i = 0; i < wp->w_jumplistlen; i++) { |
10445 | if (wp->w_jumplist[i].fmark.mark.lnum == 0) { |
10446 | continue; |
10447 | } |
10448 | dict_T *const d = tv_dict_alloc(); |
10449 | tv_list_append_dict(l, d); |
10450 | tv_dict_add_nr(d, S_LEN("lnum" ), wp->w_jumplist[i].fmark.mark.lnum); |
10451 | tv_dict_add_nr(d, S_LEN("col" ), wp->w_jumplist[i].fmark.mark.col); |
10452 | tv_dict_add_nr(d, S_LEN("coladd" ), wp->w_jumplist[i].fmark.mark.coladd); |
10453 | tv_dict_add_nr(d, S_LEN("bufnr" ), wp->w_jumplist[i].fmark.fnum); |
10454 | if (wp->w_jumplist[i].fname != NULL) { |
10455 | tv_dict_add_str(d, S_LEN("filename" ), (char *)wp->w_jumplist[i].fname); |
10456 | } |
10457 | } |
10458 | } |
10459 | |
10460 | /* |
10461 | * "getline(lnum, [end])" function |
10462 | */ |
10463 | static void f_getline(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
10464 | { |
10465 | linenr_T end; |
10466 | bool retlist; |
10467 | |
10468 | const linenr_T lnum = tv_get_lnum(argvars); |
10469 | if (argvars[1].v_type == VAR_UNKNOWN) { |
10470 | end = lnum; |
10471 | retlist = false; |
10472 | } else { |
10473 | end = tv_get_lnum(&argvars[1]); |
10474 | retlist = true; |
10475 | } |
10476 | |
10477 | get_buffer_lines(curbuf, lnum, end, retlist, rettv); |
10478 | } |
10479 | |
10480 | static void get_qf_loc_list(int is_qf, win_T *wp, typval_T *what_arg, |
10481 | typval_T *rettv) |
10482 | { |
10483 | if (what_arg->v_type == VAR_UNKNOWN) { |
10484 | tv_list_alloc_ret(rettv, kListLenMayKnow); |
10485 | if (is_qf || wp != NULL) { |
10486 | (void)get_errorlist(NULL, wp, -1, rettv->vval.v_list); |
10487 | } |
10488 | } else { |
10489 | tv_dict_alloc_ret(rettv); |
10490 | if (is_qf || wp != NULL) { |
10491 | if (what_arg->v_type == VAR_DICT) { |
10492 | dict_T *d = what_arg->vval.v_dict; |
10493 | |
10494 | if (d != NULL) { |
10495 | qf_get_properties(wp, d, rettv->vval.v_dict); |
10496 | } |
10497 | } else { |
10498 | EMSG(_(e_dictreq)); |
10499 | } |
10500 | } |
10501 | } |
10502 | } |
10503 | |
10504 | /// "getloclist()" function |
10505 | static void f_getloclist(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
10506 | { |
10507 | win_T *wp = find_win_by_nr_or_id(&argvars[0]); |
10508 | get_qf_loc_list(false, wp, &argvars[1], rettv); |
10509 | } |
10510 | |
10511 | /* |
10512 | * "getmatches()" function |
10513 | */ |
10514 | static void f_getmatches(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
10515 | { |
10516 | matchitem_T *cur = curwin->w_match_head; |
10517 | int i; |
10518 | |
10519 | tv_list_alloc_ret(rettv, kListLenMayKnow); |
10520 | while (cur != NULL) { |
10521 | dict_T *dict = tv_dict_alloc(); |
10522 | if (cur->match.regprog == NULL) { |
10523 | // match added with matchaddpos() |
10524 | for (i = 0; i < MAXPOSMATCH; i++) { |
10525 | llpos_T *llpos; |
10526 | char buf[30]; // use 30 to avoid compiler warning |
10527 | |
10528 | llpos = &cur->pos.pos[i]; |
10529 | if (llpos->lnum == 0) { |
10530 | break; |
10531 | } |
10532 | list_T *const l = tv_list_alloc(1 + (llpos->col > 0 ? 2 : 0)); |
10533 | tv_list_append_number(l, (varnumber_T)llpos->lnum); |
10534 | if (llpos->col > 0) { |
10535 | tv_list_append_number(l, (varnumber_T)llpos->col); |
10536 | tv_list_append_number(l, (varnumber_T)llpos->len); |
10537 | } |
10538 | int len = snprintf(buf, sizeof(buf), "pos%d" , i + 1); |
10539 | assert((size_t)len < sizeof(buf)); |
10540 | tv_dict_add_list(dict, buf, (size_t)len, l); |
10541 | } |
10542 | } else { |
10543 | tv_dict_add_str(dict, S_LEN("pattern" ), (const char *)cur->pattern); |
10544 | } |
10545 | tv_dict_add_str(dict, S_LEN("group" ), |
10546 | (const char *)syn_id2name(cur->hlg_id)); |
10547 | tv_dict_add_nr(dict, S_LEN("priority" ), (varnumber_T)cur->priority); |
10548 | tv_dict_add_nr(dict, S_LEN("id" ), (varnumber_T)cur->id); |
10549 | |
10550 | if (cur->conceal_char) { |
10551 | char buf[MB_MAXBYTES + 1]; |
10552 | |
10553 | buf[utf_char2bytes((int)cur->conceal_char, (char_u *)buf)] = NUL; |
10554 | tv_dict_add_str(dict, S_LEN("conceal" ), buf); |
10555 | } |
10556 | |
10557 | tv_list_append_dict(rettv->vval.v_list, dict); |
10558 | cur = cur->next; |
10559 | } |
10560 | } |
10561 | |
10562 | /* |
10563 | * "getpid()" function |
10564 | */ |
10565 | static void f_getpid(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
10566 | { |
10567 | rettv->vval.v_number = os_get_pid(); |
10568 | } |
10569 | |
10570 | static void getpos_both(typval_T *argvars, typval_T *rettv, bool getcurpos) |
10571 | { |
10572 | pos_T *fp; |
10573 | int fnum = -1; |
10574 | |
10575 | if (getcurpos) { |
10576 | fp = &curwin->w_cursor; |
10577 | } else { |
10578 | fp = var2fpos(&argvars[0], true, &fnum); |
10579 | } |
10580 | |
10581 | list_T *const l = tv_list_alloc_ret(rettv, 4 + (!!getcurpos)); |
10582 | tv_list_append_number(l, (fnum != -1) ? (varnumber_T)fnum : (varnumber_T)0); |
10583 | tv_list_append_number(l, ((fp != NULL) |
10584 | ? (varnumber_T)fp->lnum |
10585 | : (varnumber_T)0)); |
10586 | tv_list_append_number( |
10587 | l, ((fp != NULL) |
10588 | ? (varnumber_T)(fp->col == MAXCOL ? MAXCOL : fp->col + 1) |
10589 | : (varnumber_T)0)); |
10590 | tv_list_append_number( |
10591 | l, (fp != NULL) ? (varnumber_T)fp->coladd : (varnumber_T)0); |
10592 | if (getcurpos) { |
10593 | const int save_set_curswant = curwin->w_set_curswant; |
10594 | const colnr_T save_curswant = curwin->w_curswant; |
10595 | const colnr_T save_virtcol = curwin->w_virtcol; |
10596 | |
10597 | update_curswant(); |
10598 | tv_list_append_number(l, (curwin->w_curswant == MAXCOL |
10599 | ? (varnumber_T)MAXCOL |
10600 | : (varnumber_T)curwin->w_curswant + 1)); |
10601 | |
10602 | // Do not change "curswant", as it is unexpected that a get |
10603 | // function has a side effect. |
10604 | if (save_set_curswant) { |
10605 | curwin->w_set_curswant = save_set_curswant; |
10606 | curwin->w_curswant = save_curswant; |
10607 | curwin->w_virtcol = save_virtcol; |
10608 | curwin->w_valid &= ~VALID_VIRTCOL; |
10609 | } |
10610 | } |
10611 | } |
10612 | |
10613 | /* |
10614 | * "getcurpos(string)" function |
10615 | */ |
10616 | static void f_getcurpos(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
10617 | { |
10618 | getpos_both(argvars, rettv, true); |
10619 | } |
10620 | |
10621 | /* |
10622 | * "getpos(string)" function |
10623 | */ |
10624 | static void f_getpos(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
10625 | { |
10626 | getpos_both(argvars, rettv, false); |
10627 | } |
10628 | |
10629 | /// "getqflist()" functions |
10630 | static void f_getqflist(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
10631 | { |
10632 | get_qf_loc_list(true, NULL, &argvars[0], rettv); |
10633 | } |
10634 | |
10635 | /// "getreg()" function |
10636 | static void f_getreg(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
10637 | { |
10638 | const char *strregname; |
10639 | int arg2 = false; |
10640 | bool return_list = false; |
10641 | bool error = false; |
10642 | |
10643 | if (argvars[0].v_type != VAR_UNKNOWN) { |
10644 | strregname = tv_get_string_chk(&argvars[0]); |
10645 | error = strregname == NULL; |
10646 | if (argvars[1].v_type != VAR_UNKNOWN) { |
10647 | arg2 = tv_get_number_chk(&argvars[1], &error); |
10648 | if (!error && argvars[2].v_type != VAR_UNKNOWN) { |
10649 | return_list = tv_get_number_chk(&argvars[2], &error); |
10650 | } |
10651 | } |
10652 | } else { |
10653 | strregname = (const char *)vimvars[VV_REG].vv_str; |
10654 | } |
10655 | |
10656 | if (error) { |
10657 | return; |
10658 | } |
10659 | |
10660 | int regname = (uint8_t)(strregname == NULL ? '"' : *strregname); |
10661 | if (regname == 0) { |
10662 | regname = '"'; |
10663 | } |
10664 | |
10665 | if (return_list) { |
10666 | rettv->v_type = VAR_LIST; |
10667 | rettv->vval.v_list = |
10668 | get_reg_contents(regname, (arg2 ? kGRegExprSrc : 0) | kGRegList); |
10669 | if (rettv->vval.v_list == NULL) { |
10670 | rettv->vval.v_list = tv_list_alloc(0); |
10671 | } |
10672 | tv_list_ref(rettv->vval.v_list); |
10673 | } else { |
10674 | rettv->v_type = VAR_STRING; |
10675 | rettv->vval.v_string = get_reg_contents(regname, arg2 ? kGRegExprSrc : 0); |
10676 | } |
10677 | } |
10678 | |
10679 | /* |
10680 | * "getregtype()" function |
10681 | */ |
10682 | static void f_getregtype(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
10683 | { |
10684 | const char *strregname; |
10685 | |
10686 | if (argvars[0].v_type != VAR_UNKNOWN) { |
10687 | strregname = tv_get_string_chk(&argvars[0]); |
10688 | if (strregname == NULL) { // Type error; errmsg already given. |
10689 | rettv->v_type = VAR_STRING; |
10690 | rettv->vval.v_string = NULL; |
10691 | return; |
10692 | } |
10693 | } else { |
10694 | // Default to v:register. |
10695 | strregname = (const char *)vimvars[VV_REG].vv_str; |
10696 | } |
10697 | |
10698 | int regname = (uint8_t)(strregname == NULL ? '"' : *strregname); |
10699 | if (regname == 0) { |
10700 | regname = '"'; |
10701 | } |
10702 | |
10703 | colnr_T reglen = 0; |
10704 | char buf[NUMBUFLEN + 2]; |
10705 | MotionType reg_type = get_reg_type(regname, ®len); |
10706 | format_reg_type(reg_type, reglen, buf, ARRAY_SIZE(buf)); |
10707 | |
10708 | rettv->v_type = VAR_STRING; |
10709 | rettv->vval.v_string = (char_u *)xstrdup(buf); |
10710 | } |
10711 | |
10712 | /// Returns information (variables, options, etc.) about a tab page |
10713 | /// as a dictionary. |
10714 | static dict_T *get_tabpage_info(tabpage_T *tp, int tp_idx) |
10715 | { |
10716 | dict_T *const dict = tv_dict_alloc(); |
10717 | |
10718 | tv_dict_add_nr(dict, S_LEN("tabnr" ), tp_idx); |
10719 | |
10720 | list_T *const l = tv_list_alloc(kListLenMayKnow); |
10721 | FOR_ALL_WINDOWS_IN_TAB(wp, tp) { |
10722 | tv_list_append_number(l, (varnumber_T)wp->handle); |
10723 | } |
10724 | tv_dict_add_list(dict, S_LEN("windows" ), l); |
10725 | |
10726 | // Make a reference to tabpage variables |
10727 | tv_dict_add_dict(dict, S_LEN("variables" ), tp->tp_vars); |
10728 | |
10729 | return dict; |
10730 | } |
10731 | |
10732 | /// "gettabinfo()" function |
10733 | static void f_gettabinfo(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
10734 | { |
10735 | tabpage_T *tparg = NULL; |
10736 | |
10737 | tv_list_alloc_ret(rettv, (argvars[0].v_type == VAR_UNKNOWN |
10738 | ? 1 |
10739 | : kListLenMayKnow)); |
10740 | |
10741 | if (argvars[0].v_type != VAR_UNKNOWN) { |
10742 | // Information about one tab page |
10743 | tparg = find_tabpage((int)tv_get_number_chk(&argvars[0], NULL)); |
10744 | if (tparg == NULL) { |
10745 | return; |
10746 | } |
10747 | } |
10748 | |
10749 | // Get information about a specific tab page or all tab pages |
10750 | int tpnr = 0; |
10751 | FOR_ALL_TABS(tp) { |
10752 | tpnr++; |
10753 | if (tparg != NULL && tp != tparg) { |
10754 | continue; |
10755 | } |
10756 | dict_T *const d = get_tabpage_info(tp, tpnr); |
10757 | tv_list_append_dict(rettv->vval.v_list, d); |
10758 | if (tparg != NULL) { |
10759 | return; |
10760 | } |
10761 | } |
10762 | } |
10763 | |
10764 | /* |
10765 | * "gettabvar()" function |
10766 | */ |
10767 | static void f_gettabvar(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
10768 | { |
10769 | win_T *oldcurwin; |
10770 | tabpage_T *oldtabpage; |
10771 | bool done = false; |
10772 | |
10773 | rettv->v_type = VAR_STRING; |
10774 | rettv->vval.v_string = NULL; |
10775 | |
10776 | const char *const varname = tv_get_string_chk(&argvars[1]); |
10777 | tabpage_T *const tp = find_tabpage((int)tv_get_number_chk(&argvars[0], NULL)); |
10778 | if (tp != NULL && varname != NULL) { |
10779 | // Set tp to be our tabpage, temporarily. Also set the window to the |
10780 | // first window in the tabpage, otherwise the window is not valid. |
10781 | win_T *const window = tp == curtab || tp->tp_firstwin == NULL |
10782 | ? firstwin |
10783 | : tp->tp_firstwin; |
10784 | if (switch_win(&oldcurwin, &oldtabpage, window, tp, true) == OK) { |
10785 | // look up the variable |
10786 | // Let gettabvar({nr}, "") return the "t:" dictionary. |
10787 | const dictitem_T *const v = find_var_in_ht(&tp->tp_vars->dv_hashtab, 't', |
10788 | varname, strlen(varname), |
10789 | false); |
10790 | if (v != NULL) { |
10791 | tv_copy(&v->di_tv, rettv); |
10792 | done = true; |
10793 | } |
10794 | } |
10795 | |
10796 | // restore previous notion of curwin |
10797 | restore_win(oldcurwin, oldtabpage, true); |
10798 | } |
10799 | |
10800 | if (!done && argvars[2].v_type != VAR_UNKNOWN) { |
10801 | tv_copy(&argvars[2], rettv); |
10802 | } |
10803 | } |
10804 | |
10805 | /* |
10806 | * "gettabwinvar()" function |
10807 | */ |
10808 | static void f_gettabwinvar(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
10809 | { |
10810 | getwinvar(argvars, rettv, 1); |
10811 | } |
10812 | |
10813 | // "gettagstack()" function |
10814 | static void f_gettagstack(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
10815 | { |
10816 | win_T *wp = curwin; // default is current window |
10817 | |
10818 | tv_dict_alloc_ret(rettv); |
10819 | |
10820 | if (argvars[0].v_type != VAR_UNKNOWN) { |
10821 | wp = find_win_by_nr_or_id(&argvars[0]); |
10822 | if (wp == NULL) { |
10823 | return; |
10824 | } |
10825 | } |
10826 | |
10827 | get_tagstack(wp, rettv->vval.v_dict); |
10828 | } |
10829 | |
10830 | /// Returns information about a window as a dictionary. |
10831 | static dict_T *get_win_info(win_T *wp, int16_t tpnr, int16_t winnr) |
10832 | { |
10833 | dict_T *const dict = tv_dict_alloc(); |
10834 | |
10835 | tv_dict_add_nr(dict, S_LEN("tabnr" ), tpnr); |
10836 | tv_dict_add_nr(dict, S_LEN("winnr" ), winnr); |
10837 | tv_dict_add_nr(dict, S_LEN("winid" ), wp->handle); |
10838 | tv_dict_add_nr(dict, S_LEN("height" ), wp->w_height); |
10839 | tv_dict_add_nr(dict, S_LEN("winrow" ), wp->w_winrow + 1); |
10840 | tv_dict_add_nr(dict, S_LEN("topline" ), wp->w_topline); |
10841 | tv_dict_add_nr(dict, S_LEN("botline" ), wp->w_botline - 1); |
10842 | tv_dict_add_nr(dict, S_LEN("width" ), wp->w_width); |
10843 | tv_dict_add_nr(dict, S_LEN("bufnr" ), wp->w_buffer->b_fnum); |
10844 | tv_dict_add_nr(dict, S_LEN("wincol" ), wp->w_wincol + 1); |
10845 | |
10846 | tv_dict_add_nr(dict, S_LEN("terminal" ), bt_terminal(wp->w_buffer)); |
10847 | tv_dict_add_nr(dict, S_LEN("quickfix" ), bt_quickfix(wp->w_buffer)); |
10848 | tv_dict_add_nr(dict, S_LEN("loclist" ), |
10849 | (bt_quickfix(wp->w_buffer) && wp->w_llist_ref != NULL)); |
10850 | |
10851 | // Add a reference to window variables |
10852 | tv_dict_add_dict(dict, S_LEN("variables" ), wp->w_vars); |
10853 | |
10854 | return dict; |
10855 | } |
10856 | |
10857 | /// "getwininfo()" function |
10858 | static void f_getwininfo(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
10859 | { |
10860 | win_T *wparg = NULL; |
10861 | |
10862 | tv_list_alloc_ret(rettv, kListLenMayKnow); |
10863 | |
10864 | if (argvars[0].v_type != VAR_UNKNOWN) { |
10865 | wparg = win_id2wp(argvars); |
10866 | if (wparg == NULL) { |
10867 | return; |
10868 | } |
10869 | } |
10870 | |
10871 | // Collect information about either all the windows across all the tab |
10872 | // pages or one particular window. |
10873 | int16_t tabnr = 0; |
10874 | FOR_ALL_TABS(tp) { |
10875 | tabnr++; |
10876 | int16_t winnr = 0; |
10877 | FOR_ALL_WINDOWS_IN_TAB(wp, tp) { |
10878 | winnr++; |
10879 | if (wparg != NULL && wp != wparg) { |
10880 | continue; |
10881 | } |
10882 | dict_T *const d = get_win_info(wp, tabnr, winnr); |
10883 | tv_list_append_dict(rettv->vval.v_list, d); |
10884 | if (wparg != NULL) { |
10885 | // found information about a specific window |
10886 | return; |
10887 | } |
10888 | } |
10889 | } |
10890 | } |
10891 | |
10892 | // Dummy timer callback. Used by f_wait(). |
10893 | static void dummy_timer_due_cb(TimeWatcher *tw, void *data) |
10894 | { |
10895 | } |
10896 | |
10897 | // Dummy timer close callback. Used by f_wait(). |
10898 | static void dummy_timer_close_cb(TimeWatcher *tw, void *data) |
10899 | { |
10900 | xfree(tw); |
10901 | } |
10902 | |
10903 | /// "wait(timeout, condition[, interval])" function |
10904 | static void f_wait(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
10905 | { |
10906 | rettv->v_type = VAR_NUMBER; |
10907 | rettv->vval.v_number = -1; |
10908 | |
10909 | if (argvars[0].v_type != VAR_NUMBER) { |
10910 | EMSG2(_(e_invargval), "1" ); |
10911 | return; |
10912 | } |
10913 | if ((argvars[2].v_type != VAR_NUMBER && argvars[2].v_type != VAR_UNKNOWN) |
10914 | || (argvars[2].v_type == VAR_NUMBER && argvars[2].vval.v_number <= 0)) { |
10915 | EMSG2(_(e_invargval), "3" ); |
10916 | return; |
10917 | } |
10918 | |
10919 | int timeout = argvars[0].vval.v_number; |
10920 | typval_T expr = argvars[1]; |
10921 | int interval = argvars[2].v_type == VAR_NUMBER |
10922 | ? argvars[2].vval.v_number |
10923 | : 200; // Default. |
10924 | TimeWatcher *tw = xmalloc(sizeof(TimeWatcher)); |
10925 | |
10926 | // Start dummy timer. |
10927 | time_watcher_init(&main_loop, tw, NULL); |
10928 | tw->events = main_loop.events; |
10929 | tw->blockable = true; |
10930 | time_watcher_start(tw, dummy_timer_due_cb, interval, interval); |
10931 | |
10932 | typval_T argv = TV_INITIAL_VALUE; |
10933 | typval_T exprval = TV_INITIAL_VALUE; |
10934 | bool error = false; |
10935 | int save_called_emsg = called_emsg; |
10936 | called_emsg = false; |
10937 | |
10938 | LOOP_PROCESS_EVENTS_UNTIL(&main_loop, main_loop.events, timeout, |
10939 | eval_expr_typval(&expr, &argv, 0, &exprval) != OK |
10940 | || tv_get_number_chk(&exprval, &error) |
10941 | || called_emsg || error || got_int); |
10942 | |
10943 | if (called_emsg || error) { |
10944 | rettv->vval.v_number = -3; |
10945 | } else if (got_int) { |
10946 | got_int = false; |
10947 | vgetc(); |
10948 | rettv->vval.v_number = -2; |
10949 | } else if (tv_get_number_chk(&exprval, &error)) { |
10950 | rettv->vval.v_number = 0; |
10951 | } |
10952 | |
10953 | called_emsg = save_called_emsg; |
10954 | |
10955 | // Stop dummy timer |
10956 | time_watcher_stop(tw); |
10957 | time_watcher_close(tw, dummy_timer_close_cb); |
10958 | } |
10959 | |
10960 | // "win_screenpos()" function |
10961 | static void f_win_screenpos(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
10962 | { |
10963 | tv_list_alloc_ret(rettv, 2); |
10964 | const win_T *const wp = find_win_by_nr_or_id(&argvars[0]); |
10965 | tv_list_append_number(rettv->vval.v_list, wp == NULL ? 0 : wp->w_winrow + 1); |
10966 | tv_list_append_number(rettv->vval.v_list, wp == NULL ? 0 : wp->w_wincol + 1); |
10967 | } |
10968 | |
10969 | // "getwinpos({timeout})" function |
10970 | static void f_getwinpos(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
10971 | { |
10972 | tv_list_alloc_ret(rettv, 2); |
10973 | tv_list_append_number(rettv->vval.v_list, -1); |
10974 | tv_list_append_number(rettv->vval.v_list, -1); |
10975 | } |
10976 | |
10977 | /* |
10978 | * "getwinposx()" function |
10979 | */ |
10980 | static void f_getwinposx(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
10981 | { |
10982 | rettv->vval.v_number = -1; |
10983 | } |
10984 | |
10985 | /* |
10986 | * "getwinposy()" function |
10987 | */ |
10988 | static void f_getwinposy(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
10989 | { |
10990 | rettv->vval.v_number = -1; |
10991 | } |
10992 | |
10993 | /* |
10994 | * Find window specified by "vp" in tabpage "tp". |
10995 | */ |
10996 | static win_T * |
10997 | find_win_by_nr ( |
10998 | typval_T *vp, |
10999 | tabpage_T *tp /* NULL for current tab page */ |
11000 | ) |
11001 | { |
11002 | int nr = (int)tv_get_number_chk(vp, NULL); |
11003 | |
11004 | if (nr < 0) { |
11005 | return NULL; |
11006 | } |
11007 | |
11008 | if (nr == 0) { |
11009 | return curwin; |
11010 | } |
11011 | |
11012 | // This method accepts NULL as an alias for curtab. |
11013 | if (tp == NULL) { |
11014 | tp = curtab; |
11015 | } |
11016 | |
11017 | FOR_ALL_WINDOWS_IN_TAB(wp, tp) { |
11018 | if (nr >= LOWEST_WIN_ID) { |
11019 | if (wp->handle == nr) { |
11020 | return wp; |
11021 | } |
11022 | } else if (--nr <= 0) { |
11023 | return wp; |
11024 | } |
11025 | } |
11026 | return NULL; |
11027 | } |
11028 | |
11029 | /// Find window specified by "wvp" in tabpage "tvp". |
11030 | static win_T *find_tabwin(typval_T *wvp, typval_T *tvp) |
11031 | { |
11032 | win_T *wp = NULL; |
11033 | tabpage_T *tp = NULL; |
11034 | |
11035 | if (wvp->v_type != VAR_UNKNOWN) { |
11036 | if (tvp->v_type != VAR_UNKNOWN) { |
11037 | long n = tv_get_number(tvp); |
11038 | if (n >= 0) { |
11039 | tp = find_tabpage(n); |
11040 | } |
11041 | } else { |
11042 | tp = curtab; |
11043 | } |
11044 | |
11045 | if (tp != NULL) { |
11046 | wp = find_win_by_nr(wvp, tp); |
11047 | } |
11048 | } else { |
11049 | wp = curwin; |
11050 | } |
11051 | |
11052 | return wp; |
11053 | } |
11054 | |
11055 | /// "getwinvar()" function |
11056 | static void f_getwinvar(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
11057 | { |
11058 | getwinvar(argvars, rettv, 0); |
11059 | } |
11060 | |
11061 | /* |
11062 | * getwinvar() and gettabwinvar() |
11063 | */ |
11064 | static void |
11065 | getwinvar( |
11066 | typval_T *argvars, |
11067 | typval_T *rettv, |
11068 | int off /* 1 for gettabwinvar() */ |
11069 | ) |
11070 | { |
11071 | win_T *win, *oldcurwin; |
11072 | dictitem_T *v; |
11073 | tabpage_T *tp = NULL; |
11074 | tabpage_T *oldtabpage = NULL; |
11075 | bool done = false; |
11076 | |
11077 | if (off == 1) { |
11078 | tp = find_tabpage((int)tv_get_number_chk(&argvars[0], NULL)); |
11079 | } else { |
11080 | tp = curtab; |
11081 | } |
11082 | win = find_win_by_nr(&argvars[off], tp); |
11083 | const char *varname = tv_get_string_chk(&argvars[off + 1]); |
11084 | |
11085 | rettv->v_type = VAR_STRING; |
11086 | rettv->vval.v_string = NULL; |
11087 | |
11088 | emsg_off++; |
11089 | if (win != NULL && varname != NULL) { |
11090 | // Set curwin to be our win, temporarily. Also set the tabpage, |
11091 | // otherwise the window is not valid. Only do this when needed, |
11092 | // autocommands get blocked. |
11093 | bool need_switch_win = tp != curtab || win != curwin; |
11094 | if (!need_switch_win |
11095 | || switch_win(&oldcurwin, &oldtabpage, win, tp, true) == OK) { |
11096 | if (*varname == '&') { |
11097 | if (varname[1] == NUL) { |
11098 | // get all window-local options in a dict |
11099 | dict_T *opts = get_winbuf_options(false); |
11100 | |
11101 | if (opts != NULL) { |
11102 | tv_dict_set_ret(rettv, opts); |
11103 | done = true; |
11104 | } |
11105 | } else if (get_option_tv(&varname, rettv, 1) == OK) { |
11106 | // window-local-option |
11107 | done = true; |
11108 | } |
11109 | } else { |
11110 | // Look up the variable. |
11111 | // Let getwinvar({nr}, "") return the "w:" dictionary. |
11112 | v = find_var_in_ht(&win->w_vars->dv_hashtab, 'w', varname, |
11113 | strlen(varname), false); |
11114 | if (v != NULL) { |
11115 | tv_copy(&v->di_tv, rettv); |
11116 | done = true; |
11117 | } |
11118 | } |
11119 | } |
11120 | |
11121 | if (need_switch_win) { |
11122 | // restore previous notion of curwin |
11123 | restore_win(oldcurwin, oldtabpage, true); |
11124 | } |
11125 | } |
11126 | emsg_off--; |
11127 | |
11128 | if (!done && argvars[off + 2].v_type != VAR_UNKNOWN) { |
11129 | // use the default return value |
11130 | tv_copy(&argvars[off + 2], rettv); |
11131 | } |
11132 | } |
11133 | |
11134 | /* |
11135 | * "glob()" function |
11136 | */ |
11137 | static void f_glob(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
11138 | { |
11139 | int options = WILD_SILENT|WILD_USE_NL; |
11140 | expand_T xpc; |
11141 | bool error = false; |
11142 | |
11143 | /* When the optional second argument is non-zero, don't remove matches |
11144 | * for 'wildignore' and don't put matches for 'suffixes' at the end. */ |
11145 | rettv->v_type = VAR_STRING; |
11146 | if (argvars[1].v_type != VAR_UNKNOWN) { |
11147 | if (tv_get_number_chk(&argvars[1], &error)) { |
11148 | options |= WILD_KEEP_ALL; |
11149 | } |
11150 | if (argvars[2].v_type != VAR_UNKNOWN) { |
11151 | if (tv_get_number_chk(&argvars[2], &error)) { |
11152 | tv_list_set_ret(rettv, NULL); |
11153 | } |
11154 | if (argvars[3].v_type != VAR_UNKNOWN |
11155 | && tv_get_number_chk(&argvars[3], &error)) { |
11156 | options |= WILD_ALLLINKS; |
11157 | } |
11158 | } |
11159 | } |
11160 | if (!error) { |
11161 | ExpandInit(&xpc); |
11162 | xpc.xp_context = EXPAND_FILES; |
11163 | if (p_wic) |
11164 | options += WILD_ICASE; |
11165 | if (rettv->v_type == VAR_STRING) { |
11166 | rettv->vval.v_string = ExpandOne( |
11167 | &xpc, (char_u *)tv_get_string(&argvars[0]), NULL, options, WILD_ALL); |
11168 | } else { |
11169 | ExpandOne(&xpc, (char_u *)tv_get_string(&argvars[0]), NULL, options, |
11170 | WILD_ALL_KEEP); |
11171 | tv_list_alloc_ret(rettv, xpc.xp_numfiles); |
11172 | for (int i = 0; i < xpc.xp_numfiles; i++) { |
11173 | tv_list_append_string(rettv->vval.v_list, (const char *)xpc.xp_files[i], |
11174 | -1); |
11175 | } |
11176 | ExpandCleanup(&xpc); |
11177 | } |
11178 | } else |
11179 | rettv->vval.v_string = NULL; |
11180 | } |
11181 | |
11182 | /// "globpath()" function |
11183 | static void f_globpath(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
11184 | { |
11185 | int flags = 0; // Flags for globpath. |
11186 | bool error = false; |
11187 | |
11188 | // Return a string, or a list if the optional third argument is non-zero. |
11189 | rettv->v_type = VAR_STRING; |
11190 | |
11191 | if (argvars[2].v_type != VAR_UNKNOWN) { |
11192 | // When the optional second argument is non-zero, don't remove matches |
11193 | // for 'wildignore' and don't put matches for 'suffixes' at the end. |
11194 | if (tv_get_number_chk(&argvars[2], &error)) { |
11195 | flags |= WILD_KEEP_ALL; |
11196 | } |
11197 | |
11198 | if (argvars[3].v_type != VAR_UNKNOWN) { |
11199 | if (tv_get_number_chk(&argvars[3], &error)) { |
11200 | tv_list_set_ret(rettv, NULL); |
11201 | } |
11202 | if (argvars[4].v_type != VAR_UNKNOWN |
11203 | && tv_get_number_chk(&argvars[4], &error)) { |
11204 | flags |= WILD_ALLLINKS; |
11205 | } |
11206 | } |
11207 | } |
11208 | |
11209 | char buf1[NUMBUFLEN]; |
11210 | const char *const file = tv_get_string_buf_chk(&argvars[1], buf1); |
11211 | if (file != NULL && !error) { |
11212 | garray_T ga; |
11213 | ga_init(&ga, (int)sizeof(char_u *), 10); |
11214 | globpath((char_u *)tv_get_string(&argvars[0]), (char_u *)file, &ga, flags); |
11215 | |
11216 | if (rettv->v_type == VAR_STRING) { |
11217 | rettv->vval.v_string = ga_concat_strings_sep(&ga, "\n" ); |
11218 | } else { |
11219 | tv_list_alloc_ret(rettv, ga.ga_len); |
11220 | for (int i = 0; i < ga.ga_len; i++) { |
11221 | tv_list_append_string(rettv->vval.v_list, |
11222 | ((const char **)(ga.ga_data))[i], -1); |
11223 | } |
11224 | } |
11225 | |
11226 | ga_clear_strings(&ga); |
11227 | } else { |
11228 | rettv->vval.v_string = NULL; |
11229 | } |
11230 | } |
11231 | |
11232 | // "glob2regpat()" function |
11233 | static void f_glob2regpat(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
11234 | { |
11235 | const char *const pat = tv_get_string_chk(&argvars[0]); // NULL on type error |
11236 | |
11237 | rettv->v_type = VAR_STRING; |
11238 | rettv->vval.v_string = ((pat == NULL) |
11239 | ? NULL |
11240 | : file_pat_to_reg_pat((char_u *)pat, NULL, NULL, |
11241 | false)); |
11242 | } |
11243 | |
11244 | /// "has()" function |
11245 | static void f_has(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
11246 | { |
11247 | static const char *const has_list[] = { |
11248 | #ifdef UNIX |
11249 | "unix" , |
11250 | #endif |
11251 | #if defined(WIN32) |
11252 | "win32" , |
11253 | #endif |
11254 | #if defined(WIN64) || defined(_WIN64) |
11255 | "win64" , |
11256 | #endif |
11257 | "fname_case" , |
11258 | #ifdef HAVE_ACL |
11259 | "acl" , |
11260 | #endif |
11261 | "autochdir" , |
11262 | "arabic" , |
11263 | "autocmd" , |
11264 | "browsefilter" , |
11265 | "byte_offset" , |
11266 | "cindent" , |
11267 | "cmdline_compl" , |
11268 | "cmdline_hist" , |
11269 | "comments" , |
11270 | "conceal" , |
11271 | "cscope" , |
11272 | "cursorbind" , |
11273 | "cursorshape" , |
11274 | #ifdef DEBUG |
11275 | "debug" , |
11276 | #endif |
11277 | "dialog_con" , |
11278 | "diff" , |
11279 | "digraphs" , |
11280 | "eval" , /* always present, of course! */ |
11281 | "ex_extra" , |
11282 | "extra_search" , |
11283 | "file_in_path" , |
11284 | "filterpipe" , |
11285 | "find_in_path" , |
11286 | "float" , |
11287 | "folding" , |
11288 | #if defined(UNIX) |
11289 | "fork" , |
11290 | #endif |
11291 | "gettext" , |
11292 | #if defined(HAVE_ICONV) |
11293 | "iconv" , |
11294 | #endif |
11295 | "insert_expand" , |
11296 | "jumplist" , |
11297 | "keymap" , |
11298 | "lambda" , |
11299 | "langmap" , |
11300 | "libcall" , |
11301 | "linebreak" , |
11302 | "lispindent" , |
11303 | "listcmds" , |
11304 | "localmap" , |
11305 | #ifdef __APPLE__ |
11306 | "mac" , |
11307 | "macunix" , |
11308 | "osx" , |
11309 | "osxdarwin" , |
11310 | #endif |
11311 | "menu" , |
11312 | "mksession" , |
11313 | "modify_fname" , |
11314 | "mouse" , |
11315 | "multi_byte" , |
11316 | "multi_lang" , |
11317 | "num64" , |
11318 | "packages" , |
11319 | "path_extra" , |
11320 | "persistent_undo" , |
11321 | "postscript" , |
11322 | "printer" , |
11323 | "profile" , |
11324 | "pythonx" , |
11325 | "reltime" , |
11326 | "quickfix" , |
11327 | "rightleft" , |
11328 | "scrollbind" , |
11329 | "showcmd" , |
11330 | "cmdline_info" , |
11331 | "shada" , |
11332 | "signs" , |
11333 | "smartindent" , |
11334 | "startuptime" , |
11335 | "statusline" , |
11336 | "spell" , |
11337 | "syntax" , |
11338 | #if !defined(UNIX) |
11339 | "system" , // TODO(SplinterOfChaos): This IS defined for UNIX! |
11340 | #endif |
11341 | "tablineat" , |
11342 | "tag_binary" , |
11343 | "termguicolors" , |
11344 | "termresponse" , |
11345 | "textobjects" , |
11346 | "timers" , |
11347 | "title" , |
11348 | "user-commands" , /* was accidentally included in 5.4 */ |
11349 | "user_commands" , |
11350 | "vertsplit" , |
11351 | "virtualedit" , |
11352 | "visual" , |
11353 | "visualextra" , |
11354 | "vreplace" , |
11355 | "wildignore" , |
11356 | "wildmenu" , |
11357 | "windows" , |
11358 | "winaltkeys" , |
11359 | "writebackup" , |
11360 | #if defined(HAVE_WSL) |
11361 | "wsl" , |
11362 | #endif |
11363 | "nvim" , |
11364 | }; |
11365 | |
11366 | bool n = false; |
11367 | const char *const name = tv_get_string(&argvars[0]); |
11368 | for (size_t i = 0; i < ARRAY_SIZE(has_list); i++) { |
11369 | if (STRICMP(name, has_list[i]) == 0) { |
11370 | n = true; |
11371 | break; |
11372 | } |
11373 | } |
11374 | |
11375 | if (!n) { |
11376 | if (STRNICMP(name, "patch" , 5) == 0) { |
11377 | if (name[5] == '-' |
11378 | && strlen(name) >= 11 |
11379 | && ascii_isdigit(name[6]) |
11380 | && ascii_isdigit(name[8]) |
11381 | && ascii_isdigit(name[10])) { |
11382 | int major = atoi(name + 6); |
11383 | int minor = atoi(name + 8); |
11384 | |
11385 | // Expect "patch-9.9.01234". |
11386 | n = (major < VIM_VERSION_MAJOR |
11387 | || (major == VIM_VERSION_MAJOR |
11388 | && (minor < VIM_VERSION_MINOR |
11389 | || (minor == VIM_VERSION_MINOR |
11390 | && has_vim_patch(atoi(name + 10)))))); |
11391 | } else { |
11392 | n = has_vim_patch(atoi(name + 5)); |
11393 | } |
11394 | } else if (STRNICMP(name, "nvim-" , 5) == 0) { |
11395 | // Expect "nvim-x.y.z" |
11396 | n = has_nvim_version(name + 5); |
11397 | } else if (STRICMP(name, "vim_starting" ) == 0) { |
11398 | n = (starting != 0); |
11399 | } else if (STRICMP(name, "ttyin" ) == 0) { |
11400 | n = stdin_isatty; |
11401 | } else if (STRICMP(name, "ttyout" ) == 0) { |
11402 | n = stdout_isatty; |
11403 | } else if (STRICMP(name, "multi_byte_encoding" ) == 0) { |
11404 | n = has_mbyte != 0; |
11405 | } else if (STRICMP(name, "syntax_items" ) == 0) { |
11406 | n = syntax_present(curwin); |
11407 | #ifdef UNIX |
11408 | } else if (STRICMP(name, "unnamedplus" ) == 0) { |
11409 | n = eval_has_provider("clipboard" ); |
11410 | #endif |
11411 | } |
11412 | } |
11413 | |
11414 | if (!n && eval_has_provider(name)) { |
11415 | n = true; |
11416 | } |
11417 | |
11418 | rettv->vval.v_number = n; |
11419 | } |
11420 | |
11421 | /* |
11422 | * "has_key()" function |
11423 | */ |
11424 | static void f_has_key(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
11425 | { |
11426 | if (argvars[0].v_type != VAR_DICT) { |
11427 | EMSG(_(e_dictreq)); |
11428 | return; |
11429 | } |
11430 | if (argvars[0].vval.v_dict == NULL) |
11431 | return; |
11432 | |
11433 | rettv->vval.v_number = tv_dict_find(argvars[0].vval.v_dict, |
11434 | tv_get_string(&argvars[1]), |
11435 | -1) != NULL; |
11436 | } |
11437 | |
11438 | /// `haslocaldir([{win}[, {tab}]])` function |
11439 | /// |
11440 | /// Returns `1` if the scope object has a local directory, `0` otherwise. If a |
11441 | /// scope object is not specified the current one is implied. This function |
11442 | /// share a lot of code with `f_getcwd`. |
11443 | /// |
11444 | /// @pre The arguments must be of type number. |
11445 | /// @pre There may not be more than two arguments. |
11446 | /// @pre An argument may not be -1 if preceding arguments are not all -1. |
11447 | /// |
11448 | /// @post The return value will be either the number `1` or `0`. |
11449 | static void f_haslocaldir(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
11450 | { |
11451 | // Possible scope of working directory to return. |
11452 | CdScope scope = kCdScopeInvalid; |
11453 | |
11454 | // Numbers of the scope objects (window, tab) we want the working directory |
11455 | // of. A `-1` means to skip this scope, a `0` means the current object. |
11456 | int scope_number[] = { |
11457 | [kCdScopeWindow] = 0, // Number of window to look at. |
11458 | [kCdScopeTab ] = 0, // Number of tab to look at. |
11459 | }; |
11460 | |
11461 | tabpage_T *tp = curtab; // The tabpage to look at. |
11462 | win_T *win = curwin; // The window to look at. |
11463 | |
11464 | rettv->v_type = VAR_NUMBER; |
11465 | rettv->vval.v_number = 0; |
11466 | |
11467 | // Pre-conditions and scope extraction together |
11468 | for (int i = MIN_CD_SCOPE; i < MAX_CD_SCOPE; i++) { |
11469 | if (argvars[i].v_type == VAR_UNKNOWN) { |
11470 | break; |
11471 | } |
11472 | if (argvars[i].v_type != VAR_NUMBER) { |
11473 | EMSG(_(e_invarg)); |
11474 | return; |
11475 | } |
11476 | scope_number[i] = argvars[i].vval.v_number; |
11477 | if (scope_number[i] < -1) { |
11478 | EMSG(_(e_invarg)); |
11479 | return; |
11480 | } |
11481 | // Use the narrowest scope the user requested |
11482 | if (scope_number[i] >= 0 && scope == kCdScopeInvalid) { |
11483 | // The scope is the current iteration step. |
11484 | scope = i; |
11485 | } else if (scope_number[i] < 0) { |
11486 | scope = i + 1; |
11487 | } |
11488 | } |
11489 | |
11490 | // If the user didn't specify anything, default to window scope |
11491 | if (scope == kCdScopeInvalid) { |
11492 | scope = MIN_CD_SCOPE; |
11493 | } |
11494 | |
11495 | // Find the tabpage by number |
11496 | if (scope_number[kCdScopeTab] > 0) { |
11497 | tp = find_tabpage(scope_number[kCdScopeTab]); |
11498 | if (!tp) { |
11499 | EMSG(_("E5000: Cannot find tab number." )); |
11500 | return; |
11501 | } |
11502 | } |
11503 | |
11504 | // Find the window in `tp` by number, `NULL` if none. |
11505 | if (scope_number[kCdScopeWindow] >= 0) { |
11506 | if (scope_number[kCdScopeTab] < 0) { |
11507 | EMSG(_("E5001: Higher scope cannot be -1 if lower scope is >= 0." )); |
11508 | return; |
11509 | } |
11510 | |
11511 | if (scope_number[kCdScopeWindow] > 0) { |
11512 | win = find_win_by_nr(&argvars[0], tp); |
11513 | if (!win) { |
11514 | EMSG(_("E5002: Cannot find window number." )); |
11515 | return; |
11516 | } |
11517 | } |
11518 | } |
11519 | |
11520 | switch (scope) { |
11521 | case kCdScopeWindow: |
11522 | assert(win); |
11523 | rettv->vval.v_number = win->w_localdir ? 1 : 0; |
11524 | break; |
11525 | case kCdScopeTab: |
11526 | assert(tp); |
11527 | rettv->vval.v_number = tp->tp_localdir ? 1 : 0; |
11528 | break; |
11529 | case kCdScopeGlobal: |
11530 | // The global scope never has a local directory |
11531 | rettv->vval.v_number = 0; |
11532 | break; |
11533 | case kCdScopeInvalid: |
11534 | // We should never get here |
11535 | assert(false); |
11536 | } |
11537 | } |
11538 | |
11539 | /* |
11540 | * "hasmapto()" function |
11541 | */ |
11542 | static void f_hasmapto(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
11543 | { |
11544 | const char *mode; |
11545 | const char *const name = tv_get_string(&argvars[0]); |
11546 | bool abbr = false; |
11547 | char buf[NUMBUFLEN]; |
11548 | if (argvars[1].v_type == VAR_UNKNOWN) { |
11549 | mode = "nvo" ; |
11550 | } else { |
11551 | mode = tv_get_string_buf(&argvars[1], buf); |
11552 | if (argvars[2].v_type != VAR_UNKNOWN) { |
11553 | abbr = tv_get_number(&argvars[2]); |
11554 | } |
11555 | } |
11556 | |
11557 | if (map_to_exists(name, mode, abbr)) { |
11558 | rettv->vval.v_number = true; |
11559 | } else { |
11560 | rettv->vval.v_number = false; |
11561 | } |
11562 | } |
11563 | |
11564 | /* |
11565 | * "histadd()" function |
11566 | */ |
11567 | static void f_histadd(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
11568 | { |
11569 | HistoryType histype; |
11570 | |
11571 | rettv->vval.v_number = false; |
11572 | if (check_restricted() || check_secure()) { |
11573 | return; |
11574 | } |
11575 | const char *str = tv_get_string_chk(&argvars[0]); // NULL on type error |
11576 | histype = str != NULL ? get_histtype(str, strlen(str), false) : HIST_INVALID; |
11577 | if (histype != HIST_INVALID) { |
11578 | char buf[NUMBUFLEN]; |
11579 | str = tv_get_string_buf(&argvars[1], buf); |
11580 | if (*str != NUL) { |
11581 | init_history(); |
11582 | add_to_history(histype, (char_u *)str, false, NUL); |
11583 | rettv->vval.v_number = true; |
11584 | return; |
11585 | } |
11586 | } |
11587 | } |
11588 | |
11589 | /* |
11590 | * "histdel()" function |
11591 | */ |
11592 | static void f_histdel(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
11593 | { |
11594 | int n; |
11595 | const char *const str = tv_get_string_chk(&argvars[0]); // NULL on type error |
11596 | if (str == NULL) { |
11597 | n = 0; |
11598 | } else if (argvars[1].v_type == VAR_UNKNOWN) { |
11599 | // only one argument: clear entire history |
11600 | n = clr_history(get_histtype(str, strlen(str), false)); |
11601 | } else if (argvars[1].v_type == VAR_NUMBER) { |
11602 | // index given: remove that entry |
11603 | n = del_history_idx(get_histtype(str, strlen(str), false), |
11604 | (int)tv_get_number(&argvars[1])); |
11605 | } else { |
11606 | // string given: remove all matching entries |
11607 | char buf[NUMBUFLEN]; |
11608 | n = del_history_entry(get_histtype(str, strlen(str), false), |
11609 | (char_u *)tv_get_string_buf(&argvars[1], buf)); |
11610 | } |
11611 | rettv->vval.v_number = n; |
11612 | } |
11613 | |
11614 | /* |
11615 | * "histget()" function |
11616 | */ |
11617 | static void f_histget(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
11618 | { |
11619 | HistoryType type; |
11620 | int idx; |
11621 | |
11622 | const char *const str = tv_get_string_chk(&argvars[0]); // NULL on type error |
11623 | if (str == NULL) { |
11624 | rettv->vval.v_string = NULL; |
11625 | } else { |
11626 | type = get_histtype(str, strlen(str), false); |
11627 | if (argvars[1].v_type == VAR_UNKNOWN) { |
11628 | idx = get_history_idx(type); |
11629 | } else { |
11630 | idx = (int)tv_get_number_chk(&argvars[1], NULL); |
11631 | } |
11632 | // -1 on type error |
11633 | rettv->vval.v_string = vim_strsave(get_history_entry(type, idx)); |
11634 | } |
11635 | rettv->v_type = VAR_STRING; |
11636 | } |
11637 | |
11638 | /* |
11639 | * "histnr()" function |
11640 | */ |
11641 | static void f_histnr(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
11642 | { |
11643 | int i; |
11644 | |
11645 | const char *const history = tv_get_string_chk(&argvars[0]); |
11646 | |
11647 | i = history == NULL ? HIST_CMD - 1 : get_histtype(history, strlen(history), |
11648 | false); |
11649 | if (i != HIST_INVALID) { |
11650 | i = get_history_idx(i); |
11651 | } else { |
11652 | i = -1; |
11653 | } |
11654 | rettv->vval.v_number = i; |
11655 | } |
11656 | |
11657 | /* |
11658 | * "highlightID(name)" function |
11659 | */ |
11660 | static void f_hlID(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
11661 | { |
11662 | rettv->vval.v_number = syn_name2id( |
11663 | (const char_u *)tv_get_string(&argvars[0])); |
11664 | } |
11665 | |
11666 | /* |
11667 | * "highlight_exists()" function |
11668 | */ |
11669 | static void f_hlexists(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
11670 | { |
11671 | rettv->vval.v_number = highlight_exists( |
11672 | (const char_u *)tv_get_string(&argvars[0])); |
11673 | } |
11674 | |
11675 | /* |
11676 | * "hostname()" function |
11677 | */ |
11678 | static void f_hostname(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
11679 | { |
11680 | char hostname[256]; |
11681 | |
11682 | os_get_hostname(hostname, 256); |
11683 | rettv->v_type = VAR_STRING; |
11684 | rettv->vval.v_string = vim_strsave((char_u *)hostname); |
11685 | } |
11686 | |
11687 | /* |
11688 | * iconv() function |
11689 | */ |
11690 | static void f_iconv(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
11691 | { |
11692 | vimconv_T vimconv; |
11693 | |
11694 | rettv->v_type = VAR_STRING; |
11695 | rettv->vval.v_string = NULL; |
11696 | |
11697 | const char *const str = tv_get_string(&argvars[0]); |
11698 | char buf1[NUMBUFLEN]; |
11699 | char_u *const from = enc_canonize(enc_skip( |
11700 | (char_u *)tv_get_string_buf(&argvars[1], buf1))); |
11701 | char buf2[NUMBUFLEN]; |
11702 | char_u *const to = enc_canonize(enc_skip( |
11703 | (char_u *)tv_get_string_buf(&argvars[2], buf2))); |
11704 | vimconv.vc_type = CONV_NONE; |
11705 | convert_setup(&vimconv, from, to); |
11706 | |
11707 | // If the encodings are equal, no conversion needed. |
11708 | if (vimconv.vc_type == CONV_NONE) { |
11709 | rettv->vval.v_string = (char_u *)xstrdup(str); |
11710 | } else { |
11711 | rettv->vval.v_string = string_convert(&vimconv, (char_u *)str, NULL); |
11712 | } |
11713 | |
11714 | convert_setup(&vimconv, NULL, NULL); |
11715 | xfree(from); |
11716 | xfree(to); |
11717 | } |
11718 | |
11719 | /* |
11720 | * "indent()" function |
11721 | */ |
11722 | static void f_indent(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
11723 | { |
11724 | const linenr_T lnum = tv_get_lnum(argvars); |
11725 | if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count) { |
11726 | rettv->vval.v_number = get_indent_lnum(lnum); |
11727 | } else { |
11728 | rettv->vval.v_number = -1; |
11729 | } |
11730 | } |
11731 | |
11732 | /* |
11733 | * "index()" function |
11734 | */ |
11735 | static void f_index(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
11736 | { |
11737 | long idx = 0; |
11738 | bool ic = false; |
11739 | |
11740 | rettv->vval.v_number = -1; |
11741 | if (argvars[0].v_type != VAR_LIST) { |
11742 | EMSG(_(e_listreq)); |
11743 | return; |
11744 | } |
11745 | list_T *const l = argvars[0].vval.v_list; |
11746 | if (l != NULL) { |
11747 | listitem_T *item = tv_list_first(l); |
11748 | if (argvars[2].v_type != VAR_UNKNOWN) { |
11749 | bool error = false; |
11750 | |
11751 | // Start at specified item. |
11752 | idx = tv_list_uidx(l, tv_get_number_chk(&argvars[2], &error)); |
11753 | if (error || idx == -1) { |
11754 | item = NULL; |
11755 | } else { |
11756 | item = tv_list_find(l, idx); |
11757 | assert(item != NULL); |
11758 | } |
11759 | if (argvars[3].v_type != VAR_UNKNOWN) { |
11760 | ic = !!tv_get_number_chk(&argvars[3], &error); |
11761 | if (error) { |
11762 | item = NULL; |
11763 | } |
11764 | } |
11765 | } |
11766 | |
11767 | for (; item != NULL; item = TV_LIST_ITEM_NEXT(l, item), idx++) { |
11768 | if (tv_equal(TV_LIST_ITEM_TV(item), &argvars[1], ic, false)) { |
11769 | rettv->vval.v_number = idx; |
11770 | break; |
11771 | } |
11772 | } |
11773 | } |
11774 | } |
11775 | |
11776 | static int inputsecret_flag = 0; |
11777 | |
11778 | /* |
11779 | * This function is used by f_input() and f_inputdialog() functions. The third |
11780 | * argument to f_input() specifies the type of completion to use at the |
11781 | * prompt. The third argument to f_inputdialog() specifies the value to return |
11782 | * when the user cancels the prompt. |
11783 | */ |
11784 | void get_user_input(const typval_T *const argvars, |
11785 | typval_T *const rettv, const bool inputdialog) |
11786 | FUNC_ATTR_NONNULL_ALL |
11787 | { |
11788 | rettv->v_type = VAR_STRING; |
11789 | rettv->vval.v_string = NULL; |
11790 | |
11791 | const char *prompt = "" ; |
11792 | const char *defstr = "" ; |
11793 | const char *cancelreturn = NULL; |
11794 | const char *xp_name = NULL; |
11795 | Callback input_callback = { .type = kCallbackNone }; |
11796 | char prompt_buf[NUMBUFLEN]; |
11797 | char defstr_buf[NUMBUFLEN]; |
11798 | char cancelreturn_buf[NUMBUFLEN]; |
11799 | char xp_name_buf[NUMBUFLEN]; |
11800 | char def[1] = { 0 }; |
11801 | if (argvars[0].v_type == VAR_DICT) { |
11802 | if (argvars[1].v_type != VAR_UNKNOWN) { |
11803 | EMSG(_("E5050: {opts} must be the only argument" )); |
11804 | return; |
11805 | } |
11806 | dict_T *const dict = argvars[0].vval.v_dict; |
11807 | prompt = tv_dict_get_string_buf_chk(dict, S_LEN("prompt" ), prompt_buf, "" ); |
11808 | if (prompt == NULL) { |
11809 | return; |
11810 | } |
11811 | defstr = tv_dict_get_string_buf_chk(dict, S_LEN("default" ), defstr_buf, "" ); |
11812 | if (defstr == NULL) { |
11813 | return; |
11814 | } |
11815 | cancelreturn = tv_dict_get_string_buf_chk(dict, S_LEN("cancelreturn" ), |
11816 | cancelreturn_buf, def); |
11817 | if (cancelreturn == NULL) { // error |
11818 | return; |
11819 | } |
11820 | if (*cancelreturn == NUL) { |
11821 | cancelreturn = NULL; |
11822 | } |
11823 | xp_name = tv_dict_get_string_buf_chk(dict, S_LEN("completion" ), |
11824 | xp_name_buf, def); |
11825 | if (xp_name == NULL) { // error |
11826 | return; |
11827 | } |
11828 | if (xp_name == def) { // default to NULL |
11829 | xp_name = NULL; |
11830 | } |
11831 | if (!tv_dict_get_callback(dict, S_LEN("highlight" ), &input_callback)) { |
11832 | return; |
11833 | } |
11834 | } else { |
11835 | prompt = tv_get_string_buf_chk(&argvars[0], prompt_buf); |
11836 | if (prompt == NULL) { |
11837 | return; |
11838 | } |
11839 | if (argvars[1].v_type != VAR_UNKNOWN) { |
11840 | defstr = tv_get_string_buf_chk(&argvars[1], defstr_buf); |
11841 | if (defstr == NULL) { |
11842 | return; |
11843 | } |
11844 | if (argvars[2].v_type != VAR_UNKNOWN) { |
11845 | const char *const arg2 = tv_get_string_buf_chk(&argvars[2], |
11846 | cancelreturn_buf); |
11847 | if (arg2 == NULL) { |
11848 | return; |
11849 | } |
11850 | if (inputdialog) { |
11851 | cancelreturn = arg2; |
11852 | } else { |
11853 | xp_name = arg2; |
11854 | } |
11855 | } |
11856 | } |
11857 | } |
11858 | |
11859 | int xp_type = EXPAND_NOTHING; |
11860 | char *xp_arg = NULL; |
11861 | if (xp_name != NULL) { |
11862 | // input() with a third argument: completion |
11863 | const int xp_namelen = (int)strlen(xp_name); |
11864 | |
11865 | uint32_t argt; |
11866 | if (parse_compl_arg((char_u *)xp_name, xp_namelen, &xp_type, |
11867 | &argt, (char_u **)&xp_arg) == FAIL) { |
11868 | return; |
11869 | } |
11870 | } |
11871 | |
11872 | const bool cmd_silent_save = cmd_silent; |
11873 | |
11874 | cmd_silent = false; // Want to see the prompt. |
11875 | // Only the part of the message after the last NL is considered as |
11876 | // prompt for the command line, unlsess cmdline is externalized |
11877 | const char *p = prompt; |
11878 | if (!ui_has(kUICmdline)) { |
11879 | const char *lastnl = strrchr(prompt, '\n'); |
11880 | if (lastnl != NULL) { |
11881 | p = lastnl+1; |
11882 | msg_start(); |
11883 | msg_clr_eos(); |
11884 | msg_puts_attr_len(prompt, p - prompt, echo_attr); |
11885 | msg_didout = false; |
11886 | msg_starthere(); |
11887 | } |
11888 | } |
11889 | cmdline_row = msg_row; |
11890 | |
11891 | stuffReadbuffSpec(defstr); |
11892 | |
11893 | const int save_ex_normal_busy = ex_normal_busy; |
11894 | ex_normal_busy = 0; |
11895 | rettv->vval.v_string = |
11896 | (char_u *)getcmdline_prompt(inputsecret_flag ? NUL : '@', p, echo_attr, |
11897 | xp_type, xp_arg, input_callback); |
11898 | ex_normal_busy = save_ex_normal_busy; |
11899 | callback_free(&input_callback); |
11900 | |
11901 | if (rettv->vval.v_string == NULL && cancelreturn != NULL) { |
11902 | rettv->vval.v_string = (char_u *)xstrdup(cancelreturn); |
11903 | } |
11904 | |
11905 | xfree(xp_arg); |
11906 | |
11907 | // Since the user typed this, no need to wait for return. |
11908 | need_wait_return = false; |
11909 | msg_didout = false; |
11910 | cmd_silent = cmd_silent_save; |
11911 | } |
11912 | |
11913 | /* |
11914 | * "input()" function |
11915 | * Also handles inputsecret() when inputsecret is set. |
11916 | */ |
11917 | static void f_input(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
11918 | { |
11919 | get_user_input(argvars, rettv, FALSE); |
11920 | } |
11921 | |
11922 | /* |
11923 | * "inputdialog()" function |
11924 | */ |
11925 | static void f_inputdialog(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
11926 | { |
11927 | get_user_input(argvars, rettv, TRUE); |
11928 | } |
11929 | |
11930 | /* |
11931 | * "inputlist()" function |
11932 | */ |
11933 | static void f_inputlist(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
11934 | { |
11935 | int selected; |
11936 | int mouse_used; |
11937 | |
11938 | if (argvars[0].v_type != VAR_LIST) { |
11939 | EMSG2(_(e_listarg), "inputlist()" ); |
11940 | return; |
11941 | } |
11942 | |
11943 | msg_start(); |
11944 | msg_row = Rows - 1; /* for when 'cmdheight' > 1 */ |
11945 | lines_left = Rows; /* avoid more prompt */ |
11946 | msg_scroll = TRUE; |
11947 | msg_clr_eos(); |
11948 | |
11949 | TV_LIST_ITER_CONST(argvars[0].vval.v_list, li, { |
11950 | msg_puts(tv_get_string(TV_LIST_ITEM_TV(li))); |
11951 | msg_putchar('\n'); |
11952 | }); |
11953 | |
11954 | // Ask for choice. |
11955 | selected = prompt_for_number(&mouse_used); |
11956 | if (mouse_used) { |
11957 | selected -= lines_left; |
11958 | } |
11959 | |
11960 | rettv->vval.v_number = selected; |
11961 | } |
11962 | |
11963 | |
11964 | static garray_T ga_userinput = {0, 0, sizeof(tasave_T), 4, NULL}; |
11965 | |
11966 | /// "inputrestore()" function |
11967 | static void f_inputrestore(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
11968 | { |
11969 | if (!GA_EMPTY(&ga_userinput)) { |
11970 | ga_userinput.ga_len--; |
11971 | restore_typeahead((tasave_T *)(ga_userinput.ga_data) |
11972 | + ga_userinput.ga_len); |
11973 | // default return is zero == OK |
11974 | } else if (p_verbose > 1) { |
11975 | verb_msg(_("called inputrestore() more often than inputsave()" )); |
11976 | rettv->vval.v_number = 1; // Failed |
11977 | } |
11978 | } |
11979 | |
11980 | /// "inputsave()" function |
11981 | static void f_inputsave(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
11982 | { |
11983 | // Add an entry to the stack of typeahead storage. |
11984 | tasave_T *p = GA_APPEND_VIA_PTR(tasave_T, &ga_userinput); |
11985 | save_typeahead(p); |
11986 | } |
11987 | |
11988 | /// "inputsecret()" function |
11989 | static void f_inputsecret(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
11990 | { |
11991 | cmdline_star++; |
11992 | inputsecret_flag++; |
11993 | f_input(argvars, rettv, NULL); |
11994 | cmdline_star--; |
11995 | inputsecret_flag--; |
11996 | } |
11997 | |
11998 | /* |
11999 | * "insert()" function |
12000 | */ |
12001 | static void f_insert(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
12002 | { |
12003 | list_T *l; |
12004 | bool error = false; |
12005 | |
12006 | if (argvars[0].v_type != VAR_LIST) { |
12007 | EMSG2(_(e_listarg), "insert()" ); |
12008 | } else if (!tv_check_lock(tv_list_locked((l = argvars[0].vval.v_list)), |
12009 | N_("insert() argument" ), TV_TRANSLATE)) { |
12010 | long before = 0; |
12011 | if (argvars[2].v_type != VAR_UNKNOWN) { |
12012 | before = tv_get_number_chk(&argvars[2], &error); |
12013 | } |
12014 | if (error) { |
12015 | // type error; errmsg already given |
12016 | return; |
12017 | } |
12018 | |
12019 | listitem_T *item = NULL; |
12020 | if (before != tv_list_len(l)) { |
12021 | item = tv_list_find(l, before); |
12022 | if (item == NULL) { |
12023 | EMSGN(_(e_listidx), before); |
12024 | l = NULL; |
12025 | } |
12026 | } |
12027 | if (l != NULL) { |
12028 | tv_list_insert_tv(l, &argvars[1], item); |
12029 | tv_copy(&argvars[0], rettv); |
12030 | } |
12031 | } |
12032 | } |
12033 | |
12034 | /* |
12035 | * "invert(expr)" function |
12036 | */ |
12037 | static void f_invert(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
12038 | { |
12039 | rettv->vval.v_number = ~tv_get_number_chk(&argvars[0], NULL); |
12040 | } |
12041 | |
12042 | /* |
12043 | * "isdirectory()" function |
12044 | */ |
12045 | static void f_isdirectory(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
12046 | { |
12047 | rettv->vval.v_number = os_isdir((const char_u *)tv_get_string(&argvars[0])); |
12048 | } |
12049 | |
12050 | /* |
12051 | * "islocked()" function |
12052 | */ |
12053 | static void f_islocked(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
12054 | { |
12055 | lval_T lv; |
12056 | dictitem_T *di; |
12057 | |
12058 | rettv->vval.v_number = -1; |
12059 | const char_u *const end = get_lval((char_u *)tv_get_string(&argvars[0]), |
12060 | NULL, |
12061 | &lv, false, false, |
12062 | GLV_NO_AUTOLOAD|GLV_READ_ONLY, |
12063 | FNE_CHECK_START); |
12064 | if (end != NULL && lv.ll_name != NULL) { |
12065 | if (*end != NUL) { |
12066 | EMSG(_(e_trailing)); |
12067 | } else { |
12068 | if (lv.ll_tv == NULL) { |
12069 | di = find_var((const char *)lv.ll_name, lv.ll_name_len, NULL, true); |
12070 | if (di != NULL) { |
12071 | // Consider a variable locked when: |
12072 | // 1. the variable itself is locked |
12073 | // 2. the value of the variable is locked. |
12074 | // 3. the List or Dict value is locked. |
12075 | rettv->vval.v_number = ((di->di_flags & DI_FLAGS_LOCK) |
12076 | || tv_islocked(&di->di_tv)); |
12077 | } |
12078 | } else if (lv.ll_range) { |
12079 | EMSG(_("E786: Range not allowed" )); |
12080 | } else if (lv.ll_newkey != NULL) { |
12081 | EMSG2(_(e_dictkey), lv.ll_newkey); |
12082 | } else if (lv.ll_list != NULL) { |
12083 | // List item. |
12084 | rettv->vval.v_number = tv_islocked(TV_LIST_ITEM_TV(lv.ll_li)); |
12085 | } else { |
12086 | // Dictionary item. |
12087 | rettv->vval.v_number = tv_islocked(&lv.ll_di->di_tv); |
12088 | } |
12089 | } |
12090 | } |
12091 | |
12092 | clear_lval(&lv); |
12093 | } |
12094 | |
12095 | // "isinf()" function |
12096 | static void f_isinf(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
12097 | { |
12098 | if (argvars[0].v_type == VAR_FLOAT |
12099 | && xisinf(argvars[0].vval.v_float)) { |
12100 | rettv->vval.v_number = argvars[0].vval.v_float > 0.0 ? 1 : -1; |
12101 | } |
12102 | } |
12103 | |
12104 | // "isnan()" function |
12105 | static void f_isnan(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
12106 | { |
12107 | rettv->vval.v_number = argvars[0].v_type == VAR_FLOAT |
12108 | && xisnan(argvars[0].vval.v_float); |
12109 | } |
12110 | |
12111 | /// Turn a dictionary into a list |
12112 | /// |
12113 | /// @param[in] tv Dictionary to convert. Is checked for actually being |
12114 | /// a dictionary, will give an error if not. |
12115 | /// @param[out] rettv Location where result will be saved. |
12116 | /// @param[in] what What to save in rettv. |
12117 | static void dict_list(typval_T *const tv, typval_T *const rettv, |
12118 | const DictListType what) |
12119 | { |
12120 | if (tv->v_type != VAR_DICT) { |
12121 | EMSG(_(e_dictreq)); |
12122 | return; |
12123 | } |
12124 | if (tv->vval.v_dict == NULL) { |
12125 | return; |
12126 | } |
12127 | |
12128 | tv_list_alloc_ret(rettv, tv_dict_len(tv->vval.v_dict)); |
12129 | |
12130 | TV_DICT_ITER(tv->vval.v_dict, di, { |
12131 | typval_T tv_item = { .v_lock = VAR_UNLOCKED }; |
12132 | |
12133 | switch (what) { |
12134 | case kDictListKeys: { |
12135 | tv_item.v_type = VAR_STRING; |
12136 | tv_item.vval.v_string = vim_strsave(di->di_key); |
12137 | break; |
12138 | } |
12139 | case kDictListValues: { |
12140 | tv_copy(&di->di_tv, &tv_item); |
12141 | break; |
12142 | } |
12143 | case kDictListItems: { |
12144 | // items() |
12145 | list_T *const sub_l = tv_list_alloc(2); |
12146 | tv_item.v_type = VAR_LIST; |
12147 | tv_item.vval.v_list = sub_l; |
12148 | tv_list_ref(sub_l); |
12149 | |
12150 | tv_list_append_owned_tv(sub_l, (typval_T) { |
12151 | .v_type = VAR_STRING, |
12152 | .v_lock = VAR_UNLOCKED, |
12153 | .vval.v_string = (char_u *)xstrdup((const char *)di->di_key), |
12154 | }); |
12155 | |
12156 | tv_list_append_tv(sub_l, &di->di_tv); |
12157 | |
12158 | break; |
12159 | } |
12160 | } |
12161 | |
12162 | tv_list_append_owned_tv(rettv->vval.v_list, tv_item); |
12163 | }); |
12164 | } |
12165 | |
12166 | /// "id()" function |
12167 | static void f_id(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
12168 | FUNC_ATTR_NONNULL_ALL |
12169 | { |
12170 | const int len = vim_vsnprintf_typval(NULL, 0, "%p" , dummy_ap, argvars); |
12171 | rettv->v_type = VAR_STRING; |
12172 | rettv->vval.v_string = xmalloc(len + 1); |
12173 | vim_vsnprintf_typval((char *)rettv->vval.v_string, len + 1, "%p" , |
12174 | dummy_ap, argvars); |
12175 | } |
12176 | |
12177 | /* |
12178 | * "items(dict)" function |
12179 | */ |
12180 | static void f_items(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
12181 | { |
12182 | dict_list(argvars, rettv, 2); |
12183 | } |
12184 | |
12185 | // "jobpid(id)" function |
12186 | static void f_jobpid(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
12187 | { |
12188 | rettv->v_type = VAR_NUMBER; |
12189 | rettv->vval.v_number = 0; |
12190 | |
12191 | if (check_restricted() || check_secure()) { |
12192 | return; |
12193 | } |
12194 | |
12195 | if (argvars[0].v_type != VAR_NUMBER) { |
12196 | EMSG(_(e_invarg)); |
12197 | return; |
12198 | } |
12199 | |
12200 | Channel *data = find_job(argvars[0].vval.v_number, true); |
12201 | if (!data) { |
12202 | return; |
12203 | } |
12204 | |
12205 | Process *proc = (Process *)&data->stream.proc; |
12206 | rettv->vval.v_number = proc->pid; |
12207 | } |
12208 | |
12209 | // "jobresize(job, width, height)" function |
12210 | static void f_jobresize(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
12211 | { |
12212 | rettv->v_type = VAR_NUMBER; |
12213 | rettv->vval.v_number = 0; |
12214 | |
12215 | if (check_restricted() || check_secure()) { |
12216 | return; |
12217 | } |
12218 | |
12219 | if (argvars[0].v_type != VAR_NUMBER || argvars[1].v_type != VAR_NUMBER |
12220 | || argvars[2].v_type != VAR_NUMBER) { |
12221 | // job id, width, height |
12222 | EMSG(_(e_invarg)); |
12223 | return; |
12224 | } |
12225 | |
12226 | |
12227 | Channel *data = find_job(argvars[0].vval.v_number, true); |
12228 | if (!data) { |
12229 | return; |
12230 | } |
12231 | |
12232 | if (data->stream.proc.type != kProcessTypePty) { |
12233 | EMSG(_(e_channotpty)); |
12234 | return; |
12235 | } |
12236 | |
12237 | pty_process_resize(&data->stream.pty, argvars[1].vval.v_number, |
12238 | argvars[2].vval.v_number); |
12239 | rettv->vval.v_number = 1; |
12240 | } |
12241 | |
12242 | /// Builds a process argument vector from a VimL object (typval_T). |
12243 | /// |
12244 | /// @param[in] cmd_tv VimL object |
12245 | /// @param[out] cmd Returns the command or executable name. |
12246 | /// @param[out] executable Returns `false` if argv[0] is not executable. |
12247 | /// |
12248 | /// @returns Result of `shell_build_argv()` if `cmd_tv` is a String. |
12249 | /// Else, string values of `cmd_tv` copied to a (char **) list with |
12250 | /// argv[0] resolved to full path ($PATHEXT-resolved on Windows). |
12251 | static char **tv_to_argv(typval_T *cmd_tv, const char **cmd, bool *executable) |
12252 | { |
12253 | if (cmd_tv->v_type == VAR_STRING) { // String => "shell semantics". |
12254 | const char *cmd_str = tv_get_string(cmd_tv); |
12255 | if (cmd) { |
12256 | *cmd = cmd_str; |
12257 | } |
12258 | return shell_build_argv(cmd_str, NULL); |
12259 | } |
12260 | |
12261 | if (cmd_tv->v_type != VAR_LIST) { |
12262 | EMSG2(_(e_invarg2), "expected String or List" ); |
12263 | return NULL; |
12264 | } |
12265 | |
12266 | list_T *argl = cmd_tv->vval.v_list; |
12267 | int argc = tv_list_len(argl); |
12268 | if (!argc) { |
12269 | EMSG(_(e_invarg)); // List must have at least one item. |
12270 | return NULL; |
12271 | } |
12272 | |
12273 | const char *arg0 = tv_get_string_chk(TV_LIST_ITEM_TV(tv_list_first(argl))); |
12274 | char *exe_resolved = NULL; |
12275 | if (!arg0 || !os_can_exe(arg0, &exe_resolved, true)) { |
12276 | if (arg0 && executable) { |
12277 | *executable = false; |
12278 | } |
12279 | return NULL; |
12280 | } |
12281 | |
12282 | if (cmd) { |
12283 | *cmd = exe_resolved; |
12284 | } |
12285 | |
12286 | // Build the argument vector |
12287 | int i = 0; |
12288 | char **argv = xcalloc(argc + 1, sizeof(char *)); |
12289 | TV_LIST_ITER_CONST(argl, arg, { |
12290 | const char *a = tv_get_string_chk(TV_LIST_ITEM_TV(arg)); |
12291 | if (!a) { |
12292 | // Did emsg in tv_get_string_chk; just deallocate argv. |
12293 | shell_free_argv(argv); |
12294 | xfree(exe_resolved); |
12295 | return NULL; |
12296 | } |
12297 | argv[i++] = xstrdup(a); |
12298 | }); |
12299 | // Replace argv[0] with absolute path. The only reason for this is to make |
12300 | // $PATHEXT work on Windows with jobstart([…]). #9569 |
12301 | xfree(argv[0]); |
12302 | argv[0] = exe_resolved; |
12303 | |
12304 | return argv; |
12305 | } |
12306 | |
12307 | // "jobstart()" function |
12308 | static void f_jobstart(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
12309 | { |
12310 | rettv->v_type = VAR_NUMBER; |
12311 | rettv->vval.v_number = 0; |
12312 | |
12313 | if (check_restricted() || check_secure()) { |
12314 | return; |
12315 | } |
12316 | |
12317 | bool executable = true; |
12318 | char **argv = tv_to_argv(&argvars[0], NULL, &executable); |
12319 | if (!argv) { |
12320 | rettv->vval.v_number = executable ? 0 : -1; |
12321 | return; // Did error message in tv_to_argv. |
12322 | } |
12323 | |
12324 | if (argvars[1].v_type != VAR_DICT && argvars[1].v_type != VAR_UNKNOWN) { |
12325 | // Wrong argument types |
12326 | EMSG2(_(e_invarg2), "expected dictionary" ); |
12327 | shell_free_argv(argv); |
12328 | return; |
12329 | } |
12330 | |
12331 | |
12332 | dict_T *job_opts = NULL; |
12333 | bool detach = false; |
12334 | bool rpc = false; |
12335 | bool pty = false; |
12336 | CallbackReader on_stdout = CALLBACK_READER_INIT, |
12337 | on_stderr = CALLBACK_READER_INIT; |
12338 | Callback on_exit = CALLBACK_NONE; |
12339 | char *cwd = NULL; |
12340 | if (argvars[1].v_type == VAR_DICT) { |
12341 | job_opts = argvars[1].vval.v_dict; |
12342 | |
12343 | detach = tv_dict_get_number(job_opts, "detach" ) != 0; |
12344 | rpc = tv_dict_get_number(job_opts, "rpc" ) != 0; |
12345 | pty = tv_dict_get_number(job_opts, "pty" ) != 0; |
12346 | if (pty && rpc) { |
12347 | EMSG2(_(e_invarg2), "job cannot have both 'pty' and 'rpc' options set" ); |
12348 | shell_free_argv(argv); |
12349 | return; |
12350 | } |
12351 | |
12352 | char *new_cwd = tv_dict_get_string(job_opts, "cwd" , false); |
12353 | if (new_cwd && strlen(new_cwd) > 0) { |
12354 | cwd = new_cwd; |
12355 | // The new cwd must be a directory. |
12356 | if (!os_isdir_executable((const char *)cwd)) { |
12357 | EMSG2(_(e_invarg2), "expected valid directory" ); |
12358 | shell_free_argv(argv); |
12359 | return; |
12360 | } |
12361 | } |
12362 | |
12363 | if (!common_job_callbacks(job_opts, &on_stdout, &on_stderr, &on_exit)) { |
12364 | shell_free_argv(argv); |
12365 | return; |
12366 | } |
12367 | } |
12368 | |
12369 | uint16_t width = 0, height = 0; |
12370 | char *term_name = NULL; |
12371 | |
12372 | if (pty) { |
12373 | width = (uint16_t)tv_dict_get_number(job_opts, "width" ); |
12374 | height = (uint16_t)tv_dict_get_number(job_opts, "height" ); |
12375 | term_name = tv_dict_get_string(job_opts, "TERM" , true); |
12376 | } |
12377 | |
12378 | Channel *chan = channel_job_start(argv, on_stdout, on_stderr, on_exit, pty, |
12379 | rpc, detach, cwd, width, height, term_name, |
12380 | &rettv->vval.v_number); |
12381 | if (chan) { |
12382 | channel_create_event(chan, NULL); |
12383 | } |
12384 | } |
12385 | |
12386 | // "jobstop()" function |
12387 | static void f_jobstop(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
12388 | { |
12389 | rettv->v_type = VAR_NUMBER; |
12390 | rettv->vval.v_number = 0; |
12391 | |
12392 | if (check_restricted() || check_secure()) { |
12393 | return; |
12394 | } |
12395 | |
12396 | if (argvars[0].v_type != VAR_NUMBER) { |
12397 | // Only argument is the job id |
12398 | EMSG(_(e_invarg)); |
12399 | return; |
12400 | } |
12401 | |
12402 | Channel *data = find_job(argvars[0].vval.v_number, true); |
12403 | if (!data) { |
12404 | return; |
12405 | } |
12406 | |
12407 | const char *error = NULL; |
12408 | if (data->is_rpc) { |
12409 | // Ignore return code, but show error later. |
12410 | (void)channel_close(data->id, kChannelPartRpc, &error); |
12411 | } |
12412 | process_stop((Process *)&data->stream.proc); |
12413 | rettv->vval.v_number = 1; |
12414 | if (error) { |
12415 | EMSG(error); |
12416 | } |
12417 | } |
12418 | |
12419 | // "jobwait(ids[, timeout])" function |
12420 | static void f_jobwait(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
12421 | { |
12422 | rettv->v_type = VAR_NUMBER; |
12423 | rettv->vval.v_number = 0; |
12424 | |
12425 | if (check_restricted() || check_secure()) { |
12426 | return; |
12427 | } |
12428 | if (argvars[0].v_type != VAR_LIST || (argvars[1].v_type != VAR_NUMBER |
12429 | && argvars[1].v_type != VAR_UNKNOWN)) { |
12430 | EMSG(_(e_invarg)); |
12431 | return; |
12432 | } |
12433 | |
12434 | ui_busy_start(); |
12435 | list_T *args = argvars[0].vval.v_list; |
12436 | Channel **jobs = xcalloc(tv_list_len(args), sizeof(*jobs)); |
12437 | MultiQueue *waiting_jobs = multiqueue_new_parent(loop_on_put, &main_loop); |
12438 | |
12439 | // Validate, prepare jobs for waiting. |
12440 | int i = 0; |
12441 | TV_LIST_ITER_CONST(args, arg, { |
12442 | Channel *chan = NULL; |
12443 | if (TV_LIST_ITEM_TV(arg)->v_type != VAR_NUMBER |
12444 | || !(chan = find_job(TV_LIST_ITEM_TV(arg)->vval.v_number, false))) { |
12445 | jobs[i] = NULL; // Invalid job. |
12446 | } else { |
12447 | jobs[i] = chan; |
12448 | channel_incref(chan); |
12449 | if (chan->stream.proc.status < 0) { |
12450 | // Process any pending events on the job's queue before temporarily |
12451 | // replacing it. |
12452 | multiqueue_process_events(chan->events); |
12453 | multiqueue_replace_parent(chan->events, waiting_jobs); |
12454 | } |
12455 | } |
12456 | i++; |
12457 | }); |
12458 | |
12459 | int remaining = -1; |
12460 | uint64_t before = 0; |
12461 | if (argvars[1].v_type == VAR_NUMBER && argvars[1].vval.v_number >= 0) { |
12462 | remaining = argvars[1].vval.v_number; |
12463 | before = os_hrtime(); |
12464 | } |
12465 | |
12466 | for (i = 0; i < tv_list_len(args); i++) { |
12467 | if (remaining == 0) { |
12468 | break; // Timeout. |
12469 | } |
12470 | if (jobs[i] == NULL) { |
12471 | continue; // Invalid job, will assign status=-3 below. |
12472 | } |
12473 | int status = process_wait(&jobs[i]->stream.proc, remaining, |
12474 | waiting_jobs); |
12475 | if (status < 0) { |
12476 | break; // Interrupted (CTRL-C) or timeout, skip remaining jobs. |
12477 | } |
12478 | if (remaining > 0) { |
12479 | uint64_t now = os_hrtime(); |
12480 | remaining = MIN(0, remaining - (int)((now - before) / 1000000)); |
12481 | before = now; |
12482 | } |
12483 | } |
12484 | |
12485 | list_T *const rv = tv_list_alloc(tv_list_len(args)); |
12486 | |
12487 | // For each job: |
12488 | // * Restore its parent queue if the job is still alive. |
12489 | // * Append its status to the output list, or: |
12490 | // -3 for "invalid job id" |
12491 | // -2 for "interrupted" (user hit CTRL-C) |
12492 | // -1 for jobs that were skipped or timed out |
12493 | for (i = 0; i < tv_list_len(args); i++) { |
12494 | if (jobs[i] == NULL) { |
12495 | tv_list_append_number(rv, -3); |
12496 | continue; |
12497 | } |
12498 | multiqueue_process_events(jobs[i]->events); |
12499 | multiqueue_replace_parent(jobs[i]->events, main_loop.events); |
12500 | |
12501 | tv_list_append_number(rv, jobs[i]->stream.proc.status); |
12502 | channel_decref(jobs[i]); |
12503 | } |
12504 | |
12505 | multiqueue_free(waiting_jobs); |
12506 | xfree(jobs); |
12507 | ui_busy_stop(); |
12508 | tv_list_ref(rv); |
12509 | rettv->v_type = VAR_LIST; |
12510 | rettv->vval.v_list = rv; |
12511 | } |
12512 | |
12513 | /* |
12514 | * "join()" function |
12515 | */ |
12516 | static void f_join(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
12517 | { |
12518 | if (argvars[0].v_type != VAR_LIST) { |
12519 | EMSG(_(e_listreq)); |
12520 | return; |
12521 | } |
12522 | const char *const sep = (argvars[1].v_type == VAR_UNKNOWN |
12523 | ? " " |
12524 | : tv_get_string_chk(&argvars[1])); |
12525 | |
12526 | rettv->v_type = VAR_STRING; |
12527 | |
12528 | if (sep != NULL) { |
12529 | garray_T ga; |
12530 | ga_init(&ga, (int)sizeof(char), 80); |
12531 | tv_list_join(&ga, argvars[0].vval.v_list, sep); |
12532 | ga_append(&ga, NUL); |
12533 | rettv->vval.v_string = (char_u *)ga.ga_data; |
12534 | } else { |
12535 | rettv->vval.v_string = NULL; |
12536 | } |
12537 | } |
12538 | |
12539 | /// json_decode() function |
12540 | static void f_json_decode(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
12541 | { |
12542 | char numbuf[NUMBUFLEN]; |
12543 | const char *s = NULL; |
12544 | char *tofree = NULL; |
12545 | size_t len; |
12546 | if (argvars[0].v_type == VAR_LIST) { |
12547 | if (!encode_vim_list_to_buf(argvars[0].vval.v_list, &len, &tofree)) { |
12548 | EMSG(_("E474: Failed to convert list to string" )); |
12549 | return; |
12550 | } |
12551 | s = tofree; |
12552 | if (s == NULL) { |
12553 | assert(len == 0); |
12554 | s = "" ; |
12555 | } |
12556 | } else { |
12557 | s = tv_get_string_buf_chk(&argvars[0], numbuf); |
12558 | if (s) { |
12559 | len = strlen(s); |
12560 | } else { |
12561 | return; |
12562 | } |
12563 | } |
12564 | if (json_decode_string(s, len, rettv) == FAIL) { |
12565 | emsgf(_("E474: Failed to parse %.*s" ), (int)len, s); |
12566 | rettv->v_type = VAR_NUMBER; |
12567 | rettv->vval.v_number = 0; |
12568 | } |
12569 | assert(rettv->v_type != VAR_UNKNOWN); |
12570 | xfree(tofree); |
12571 | } |
12572 | |
12573 | /// json_encode() function |
12574 | static void f_json_encode(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
12575 | { |
12576 | rettv->v_type = VAR_STRING; |
12577 | rettv->vval.v_string = (char_u *) encode_tv2json(&argvars[0], NULL); |
12578 | } |
12579 | |
12580 | /* |
12581 | * "keys()" function |
12582 | */ |
12583 | static void f_keys(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
12584 | { |
12585 | dict_list(argvars, rettv, 0); |
12586 | } |
12587 | |
12588 | /* |
12589 | * "last_buffer_nr()" function. |
12590 | */ |
12591 | static void f_last_buffer_nr(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
12592 | { |
12593 | int n = 0; |
12594 | |
12595 | FOR_ALL_BUFFERS(buf) { |
12596 | if (n < buf->b_fnum) { |
12597 | n = buf->b_fnum; |
12598 | } |
12599 | } |
12600 | |
12601 | rettv->vval.v_number = n; |
12602 | } |
12603 | |
12604 | /* |
12605 | * "len()" function |
12606 | */ |
12607 | static void f_len(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
12608 | { |
12609 | switch (argvars[0].v_type) { |
12610 | case VAR_STRING: |
12611 | case VAR_NUMBER: { |
12612 | rettv->vval.v_number = (varnumber_T)strlen( |
12613 | tv_get_string(&argvars[0])); |
12614 | break; |
12615 | } |
12616 | case VAR_LIST: { |
12617 | rettv->vval.v_number = tv_list_len(argvars[0].vval.v_list); |
12618 | break; |
12619 | } |
12620 | case VAR_DICT: { |
12621 | rettv->vval.v_number = tv_dict_len(argvars[0].vval.v_dict); |
12622 | break; |
12623 | } |
12624 | case VAR_UNKNOWN: |
12625 | case VAR_SPECIAL: |
12626 | case VAR_FLOAT: |
12627 | case VAR_PARTIAL: |
12628 | case VAR_FUNC: { |
12629 | EMSG(_("E701: Invalid type for len()" )); |
12630 | break; |
12631 | } |
12632 | } |
12633 | } |
12634 | |
12635 | static void libcall_common(typval_T *argvars, typval_T *rettv, int out_type) |
12636 | { |
12637 | rettv->v_type = out_type; |
12638 | if (out_type != VAR_NUMBER) { |
12639 | rettv->vval.v_string = NULL; |
12640 | } |
12641 | |
12642 | if (check_restricted() || check_secure()) { |
12643 | return; |
12644 | } |
12645 | |
12646 | // The first two args (libname and funcname) must be strings |
12647 | if (argvars[0].v_type != VAR_STRING || argvars[1].v_type != VAR_STRING) { |
12648 | return; |
12649 | } |
12650 | |
12651 | const char *libname = (char *) argvars[0].vval.v_string; |
12652 | const char *funcname = (char *) argvars[1].vval.v_string; |
12653 | |
12654 | int in_type = argvars[2].v_type; |
12655 | |
12656 | // input variables |
12657 | char *str_in = (in_type == VAR_STRING) |
12658 | ? (char *) argvars[2].vval.v_string : NULL; |
12659 | int64_t int_in = argvars[2].vval.v_number; |
12660 | |
12661 | // output variables |
12662 | char **str_out = (out_type == VAR_STRING) |
12663 | ? (char **) &rettv->vval.v_string : NULL; |
12664 | int64_t int_out = 0; |
12665 | |
12666 | bool success = os_libcall(libname, funcname, |
12667 | str_in, int_in, |
12668 | str_out, &int_out); |
12669 | |
12670 | if (!success) { |
12671 | EMSG2(_(e_libcall), funcname); |
12672 | return; |
12673 | } |
12674 | |
12675 | if (out_type == VAR_NUMBER) { |
12676 | rettv->vval.v_number = (int) int_out; |
12677 | } |
12678 | } |
12679 | |
12680 | /* |
12681 | * "libcall()" function |
12682 | */ |
12683 | static void f_libcall(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
12684 | { |
12685 | libcall_common(argvars, rettv, VAR_STRING); |
12686 | } |
12687 | |
12688 | /* |
12689 | * "libcallnr()" function |
12690 | */ |
12691 | static void f_libcallnr(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
12692 | { |
12693 | libcall_common(argvars, rettv, VAR_NUMBER); |
12694 | } |
12695 | |
12696 | /* |
12697 | * "line(string)" function |
12698 | */ |
12699 | static void f_line(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
12700 | { |
12701 | linenr_T lnum = 0; |
12702 | pos_T *fp; |
12703 | int fnum; |
12704 | |
12705 | fp = var2fpos(&argvars[0], TRUE, &fnum); |
12706 | if (fp != NULL) |
12707 | lnum = fp->lnum; |
12708 | rettv->vval.v_number = lnum; |
12709 | } |
12710 | |
12711 | /* |
12712 | * "line2byte(lnum)" function |
12713 | */ |
12714 | static void f_line2byte(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
12715 | { |
12716 | const linenr_T lnum = tv_get_lnum(argvars); |
12717 | if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1) { |
12718 | rettv->vval.v_number = -1; |
12719 | } else { |
12720 | rettv->vval.v_number = ml_find_line_or_offset(curbuf, lnum, NULL, false); |
12721 | } |
12722 | if (rettv->vval.v_number >= 0) { |
12723 | rettv->vval.v_number++; |
12724 | } |
12725 | } |
12726 | |
12727 | /* |
12728 | * "lispindent(lnum)" function |
12729 | */ |
12730 | static void f_lispindent(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
12731 | { |
12732 | const pos_T pos = curwin->w_cursor; |
12733 | const linenr_T lnum = tv_get_lnum(argvars); |
12734 | if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count) { |
12735 | curwin->w_cursor.lnum = lnum; |
12736 | rettv->vval.v_number = get_lisp_indent(); |
12737 | curwin->w_cursor = pos; |
12738 | } else { |
12739 | rettv->vval.v_number = -1; |
12740 | } |
12741 | } |
12742 | |
12743 | /* |
12744 | * "localtime()" function |
12745 | */ |
12746 | static void f_localtime(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
12747 | { |
12748 | rettv->vval.v_number = (varnumber_T)time(NULL); |
12749 | } |
12750 | |
12751 | |
12752 | static void get_maparg(typval_T *argvars, typval_T *rettv, int exact) |
12753 | { |
12754 | char_u *keys_buf = NULL; |
12755 | char_u *rhs; |
12756 | int mode; |
12757 | int abbr = FALSE; |
12758 | int get_dict = FALSE; |
12759 | mapblock_T *mp; |
12760 | int buffer_local; |
12761 | |
12762 | // Return empty string for failure. |
12763 | rettv->v_type = VAR_STRING; |
12764 | rettv->vval.v_string = NULL; |
12765 | |
12766 | char_u *keys = (char_u *)tv_get_string(&argvars[0]); |
12767 | if (*keys == NUL) { |
12768 | return; |
12769 | } |
12770 | |
12771 | char buf[NUMBUFLEN]; |
12772 | const char *which; |
12773 | if (argvars[1].v_type != VAR_UNKNOWN) { |
12774 | which = tv_get_string_buf_chk(&argvars[1], buf); |
12775 | if (argvars[2].v_type != VAR_UNKNOWN) { |
12776 | abbr = tv_get_number(&argvars[2]); |
12777 | if (argvars[3].v_type != VAR_UNKNOWN) { |
12778 | get_dict = tv_get_number(&argvars[3]); |
12779 | } |
12780 | } |
12781 | } else { |
12782 | which = "" ; |
12783 | } |
12784 | if (which == NULL) { |
12785 | return; |
12786 | } |
12787 | |
12788 | mode = get_map_mode((char_u **)&which, 0); |
12789 | |
12790 | keys = replace_termcodes(keys, STRLEN(keys), &keys_buf, true, true, true, |
12791 | CPO_TO_CPO_FLAGS); |
12792 | rhs = check_map(keys, mode, exact, false, abbr, &mp, &buffer_local); |
12793 | xfree(keys_buf); |
12794 | |
12795 | if (!get_dict) { |
12796 | // Return a string. |
12797 | if (rhs != NULL) { |
12798 | if (*rhs == NUL) { |
12799 | rettv->vval.v_string = vim_strsave((char_u *)"<Nop>" ); |
12800 | } else { |
12801 | rettv->vval.v_string = (char_u *)str2special_save( |
12802 | (char *)rhs, false, false); |
12803 | } |
12804 | } |
12805 | |
12806 | } else { |
12807 | tv_dict_alloc_ret(rettv); |
12808 | if (rhs != NULL) { |
12809 | // Return a dictionary. |
12810 | mapblock_fill_dict(rettv->vval.v_dict, mp, buffer_local, true); |
12811 | } |
12812 | } |
12813 | } |
12814 | |
12815 | /// luaeval() function implementation |
12816 | static void f_luaeval(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
12817 | FUNC_ATTR_NONNULL_ALL |
12818 | { |
12819 | const char *const str = (const char *)tv_get_string_chk(&argvars[0]); |
12820 | if (str == NULL) { |
12821 | return; |
12822 | } |
12823 | |
12824 | executor_eval_lua(cstr_as_string((char *)str), &argvars[1], rettv); |
12825 | } |
12826 | |
12827 | /// Fill a dictionary with all applicable maparg() like dictionaries |
12828 | /// |
12829 | /// @param dict The dictionary to be filled |
12830 | /// @param mp The maphash that contains the mapping information |
12831 | /// @param buffer_value The "buffer" value |
12832 | /// @param compatible True for compatible with old maparg() dict |
12833 | void mapblock_fill_dict(dict_T *const dict, |
12834 | const mapblock_T *const mp, |
12835 | long buffer_value, |
12836 | bool compatible) |
12837 | FUNC_ATTR_NONNULL_ALL |
12838 | { |
12839 | char *const lhs = str2special_save((const char *)mp->m_keys, |
12840 | compatible, !compatible); |
12841 | char *const mapmode = map_mode_to_chars(mp->m_mode); |
12842 | varnumber_T noremap_value; |
12843 | |
12844 | if (compatible) { |
12845 | // Keep old compatible behavior |
12846 | // This is unable to determine whether a mapping is a <script> mapping |
12847 | noremap_value = !!mp->m_noremap; |
12848 | } else { |
12849 | // Distinguish between <script> mapping |
12850 | // If it's not a <script> mapping, check if it's a noremap |
12851 | noremap_value = mp->m_noremap == REMAP_SCRIPT ? 2 : !!mp->m_noremap; |
12852 | } |
12853 | |
12854 | if (compatible) { |
12855 | tv_dict_add_str(dict, S_LEN("rhs" ), (const char *)mp->m_orig_str); |
12856 | } else { |
12857 | tv_dict_add_allocated_str(dict, S_LEN("rhs" ), |
12858 | str2special_save((const char *)mp->m_str, false, |
12859 | true)); |
12860 | } |
12861 | tv_dict_add_allocated_str(dict, S_LEN("lhs" ), lhs); |
12862 | tv_dict_add_nr(dict, S_LEN("noremap" ), noremap_value); |
12863 | tv_dict_add_nr(dict, S_LEN("expr" ), mp->m_expr ? 1 : 0); |
12864 | tv_dict_add_nr(dict, S_LEN("silent" ), mp->m_silent ? 1 : 0); |
12865 | tv_dict_add_nr(dict, S_LEN("sid" ), (varnumber_T)mp->m_script_ctx.sc_sid); |
12866 | tv_dict_add_nr(dict, S_LEN("lnum" ), (varnumber_T)mp->m_script_ctx.sc_lnum); |
12867 | tv_dict_add_nr(dict, S_LEN("buffer" ), (varnumber_T)buffer_value); |
12868 | tv_dict_add_nr(dict, S_LEN("nowait" ), mp->m_nowait ? 1 : 0); |
12869 | tv_dict_add_allocated_str(dict, S_LEN("mode" ), mapmode); |
12870 | } |
12871 | |
12872 | /* |
12873 | * "map()" function |
12874 | */ |
12875 | static void f_map(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
12876 | { |
12877 | filter_map(argvars, rettv, TRUE); |
12878 | } |
12879 | |
12880 | /* |
12881 | * "maparg()" function |
12882 | */ |
12883 | static void f_maparg(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
12884 | { |
12885 | get_maparg(argvars, rettv, TRUE); |
12886 | } |
12887 | |
12888 | /* |
12889 | * "mapcheck()" function |
12890 | */ |
12891 | static void f_mapcheck(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
12892 | { |
12893 | get_maparg(argvars, rettv, FALSE); |
12894 | } |
12895 | |
12896 | |
12897 | static void find_some_match(typval_T *const argvars, typval_T *const rettv, |
12898 | const SomeMatchType type) |
12899 | { |
12900 | char_u *str = NULL; |
12901 | long len = 0; |
12902 | char_u *expr = NULL; |
12903 | regmatch_T regmatch; |
12904 | char_u *save_cpo; |
12905 | long start = 0; |
12906 | long nth = 1; |
12907 | colnr_T startcol = 0; |
12908 | bool match = false; |
12909 | list_T *l = NULL; |
12910 | listitem_T *li = NULL; |
12911 | long idx = 0; |
12912 | char_u *tofree = NULL; |
12913 | |
12914 | /* Make 'cpoptions' empty, the 'l' flag should not be used here. */ |
12915 | save_cpo = p_cpo; |
12916 | p_cpo = (char_u *)"" ; |
12917 | |
12918 | rettv->vval.v_number = -1; |
12919 | switch (type) { |
12920 | // matchlist(): return empty list when there are no matches. |
12921 | case kSomeMatchList: { |
12922 | tv_list_alloc_ret(rettv, kListLenMayKnow); |
12923 | break; |
12924 | } |
12925 | // matchstrpos(): return ["", -1, -1, -1] |
12926 | case kSomeMatchStrPos: { |
12927 | tv_list_alloc_ret(rettv, 4); |
12928 | tv_list_append_string(rettv->vval.v_list, "" , 0); |
12929 | tv_list_append_number(rettv->vval.v_list, -1); |
12930 | tv_list_append_number(rettv->vval.v_list, -1); |
12931 | tv_list_append_number(rettv->vval.v_list, -1); |
12932 | break; |
12933 | } |
12934 | case kSomeMatchStr: { |
12935 | rettv->v_type = VAR_STRING; |
12936 | rettv->vval.v_string = NULL; |
12937 | break; |
12938 | } |
12939 | case kSomeMatch: |
12940 | case kSomeMatchEnd: { |
12941 | // Do nothing: zero is default. |
12942 | break; |
12943 | } |
12944 | } |
12945 | |
12946 | if (argvars[0].v_type == VAR_LIST) { |
12947 | if ((l = argvars[0].vval.v_list) == NULL) { |
12948 | goto theend; |
12949 | } |
12950 | li = tv_list_first(l); |
12951 | } else { |
12952 | expr = str = (char_u *)tv_get_string(&argvars[0]); |
12953 | len = (long)STRLEN(str); |
12954 | } |
12955 | |
12956 | char patbuf[NUMBUFLEN]; |
12957 | const char *const pat = tv_get_string_buf_chk(&argvars[1], patbuf); |
12958 | if (pat == NULL) { |
12959 | goto theend; |
12960 | } |
12961 | |
12962 | if (argvars[2].v_type != VAR_UNKNOWN) { |
12963 | bool error = false; |
12964 | |
12965 | start = tv_get_number_chk(&argvars[2], &error); |
12966 | if (error) { |
12967 | goto theend; |
12968 | } |
12969 | if (l != NULL) { |
12970 | idx = tv_list_uidx(l, start); |
12971 | if (idx == -1) { |
12972 | goto theend; |
12973 | } |
12974 | li = tv_list_find(l, idx); |
12975 | } else { |
12976 | if (start < 0) |
12977 | start = 0; |
12978 | if (start > len) |
12979 | goto theend; |
12980 | /* When "count" argument is there ignore matches before "start", |
12981 | * otherwise skip part of the string. Differs when pattern is "^" |
12982 | * or "\<". */ |
12983 | if (argvars[3].v_type != VAR_UNKNOWN) |
12984 | startcol = start; |
12985 | else { |
12986 | str += start; |
12987 | len -= start; |
12988 | } |
12989 | } |
12990 | |
12991 | if (argvars[3].v_type != VAR_UNKNOWN) { |
12992 | nth = tv_get_number_chk(&argvars[3], &error); |
12993 | } |
12994 | if (error) { |
12995 | goto theend; |
12996 | } |
12997 | } |
12998 | |
12999 | regmatch.regprog = vim_regcomp((char_u *)pat, RE_MAGIC + RE_STRING); |
13000 | if (regmatch.regprog != NULL) { |
13001 | regmatch.rm_ic = p_ic; |
13002 | |
13003 | for (;; ) { |
13004 | if (l != NULL) { |
13005 | if (li == NULL) { |
13006 | match = false; |
13007 | break; |
13008 | } |
13009 | xfree(tofree); |
13010 | tofree = expr = str = (char_u *)encode_tv2echo(TV_LIST_ITEM_TV(li), |
13011 | NULL); |
13012 | if (str == NULL) { |
13013 | break; |
13014 | } |
13015 | } |
13016 | |
13017 | match = vim_regexec_nl(®match, str, (colnr_T)startcol); |
13018 | |
13019 | if (match && --nth <= 0) |
13020 | break; |
13021 | if (l == NULL && !match) |
13022 | break; |
13023 | |
13024 | /* Advance to just after the match. */ |
13025 | if (l != NULL) { |
13026 | li = TV_LIST_ITEM_NEXT(l, li); |
13027 | idx++; |
13028 | } else { |
13029 | startcol = (colnr_T)(regmatch.startp[0] |
13030 | + (*mb_ptr2len)(regmatch.startp[0]) - str); |
13031 | if (startcol > (colnr_T)len || str + startcol <= regmatch.startp[0]) { |
13032 | match = false; |
13033 | break; |
13034 | } |
13035 | } |
13036 | } |
13037 | |
13038 | if (match) { |
13039 | switch (type) { |
13040 | case kSomeMatchStrPos: { |
13041 | list_T *const ret_l = rettv->vval.v_list; |
13042 | listitem_T *li1 = tv_list_first(ret_l); |
13043 | listitem_T *li2 = TV_LIST_ITEM_NEXT(ret_l, li1); |
13044 | listitem_T *li3 = TV_LIST_ITEM_NEXT(ret_l, li2); |
13045 | listitem_T *li4 = TV_LIST_ITEM_NEXT(ret_l, li3); |
13046 | xfree(TV_LIST_ITEM_TV(li1)->vval.v_string); |
13047 | |
13048 | const size_t rd = (size_t)(regmatch.endp[0] - regmatch.startp[0]); |
13049 | TV_LIST_ITEM_TV(li1)->vval.v_string = xmemdupz( |
13050 | (const char *)regmatch.startp[0], rd); |
13051 | TV_LIST_ITEM_TV(li3)->vval.v_number = (varnumber_T)( |
13052 | regmatch.startp[0] - expr); |
13053 | TV_LIST_ITEM_TV(li4)->vval.v_number = (varnumber_T)( |
13054 | regmatch.endp[0] - expr); |
13055 | if (l != NULL) { |
13056 | TV_LIST_ITEM_TV(li2)->vval.v_number = (varnumber_T)idx; |
13057 | } |
13058 | break; |
13059 | } |
13060 | case kSomeMatchList: { |
13061 | // Return list with matched string and submatches. |
13062 | for (int i = 0; i < NSUBEXP; i++) { |
13063 | if (regmatch.endp[i] == NULL) { |
13064 | tv_list_append_string(rettv->vval.v_list, NULL, 0); |
13065 | } else { |
13066 | tv_list_append_string(rettv->vval.v_list, |
13067 | (const char *)regmatch.startp[i], |
13068 | (regmatch.endp[i] - regmatch.startp[i])); |
13069 | } |
13070 | } |
13071 | break; |
13072 | } |
13073 | case kSomeMatchStr: { |
13074 | // Return matched string. |
13075 | if (l != NULL) { |
13076 | tv_copy(TV_LIST_ITEM_TV(li), rettv); |
13077 | } else { |
13078 | rettv->vval.v_string = (char_u *)xmemdupz( |
13079 | (const char *)regmatch.startp[0], |
13080 | (size_t)(regmatch.endp[0] - regmatch.startp[0])); |
13081 | } |
13082 | break; |
13083 | } |
13084 | case kSomeMatch: |
13085 | case kSomeMatchEnd: { |
13086 | if (l != NULL) { |
13087 | rettv->vval.v_number = idx; |
13088 | } else { |
13089 | if (type == kSomeMatch) { |
13090 | rettv->vval.v_number = |
13091 | (varnumber_T)(regmatch.startp[0] - str); |
13092 | } else { |
13093 | rettv->vval.v_number = |
13094 | (varnumber_T)(regmatch.endp[0] - str); |
13095 | } |
13096 | rettv->vval.v_number += (varnumber_T)(str - expr); |
13097 | } |
13098 | break; |
13099 | } |
13100 | } |
13101 | } |
13102 | vim_regfree(regmatch.regprog); |
13103 | } |
13104 | |
13105 | theend: |
13106 | if (type == kSomeMatchStrPos && l == NULL && rettv->vval.v_list != NULL) { |
13107 | // matchstrpos() without a list: drop the second item |
13108 | list_T *const ret_l = rettv->vval.v_list; |
13109 | tv_list_item_remove(ret_l, TV_LIST_ITEM_NEXT(ret_l, tv_list_first(ret_l))); |
13110 | } |
13111 | |
13112 | xfree(tofree); |
13113 | p_cpo = save_cpo; |
13114 | } |
13115 | |
13116 | /* |
13117 | * "match()" function |
13118 | */ |
13119 | static void f_match(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
13120 | { |
13121 | find_some_match(argvars, rettv, kSomeMatch); |
13122 | } |
13123 | |
13124 | static int matchadd_dict_arg(typval_T *tv, const char **conceal_char, |
13125 | win_T **win) |
13126 | { |
13127 | dictitem_T *di; |
13128 | |
13129 | if (tv->v_type != VAR_DICT) { |
13130 | EMSG(_(e_dictreq)); |
13131 | return FAIL; |
13132 | } |
13133 | |
13134 | if ((di = tv_dict_find(tv->vval.v_dict, S_LEN("conceal" ))) != NULL) { |
13135 | *conceal_char = tv_get_string(&di->di_tv); |
13136 | } |
13137 | |
13138 | if ((di = tv_dict_find(tv->vval.v_dict, S_LEN("window" ))) != NULL) { |
13139 | *win = find_win_by_nr_or_id(&di->di_tv); |
13140 | if (*win == NULL) { |
13141 | EMSG(_("E957: Invalid window number" )); |
13142 | return FAIL; |
13143 | } |
13144 | } |
13145 | |
13146 | return OK; |
13147 | } |
13148 | |
13149 | /* |
13150 | * "matchadd()" function |
13151 | */ |
13152 | static void f_matchadd(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
13153 | { |
13154 | char grpbuf[NUMBUFLEN]; |
13155 | char patbuf[NUMBUFLEN]; |
13156 | const char *const grp = tv_get_string_buf_chk(&argvars[0], grpbuf); |
13157 | const char *const pat = tv_get_string_buf_chk(&argvars[1], patbuf); |
13158 | int prio = 10; |
13159 | int id = -1; |
13160 | bool error = false; |
13161 | const char *conceal_char = NULL; |
13162 | win_T *win = curwin; |
13163 | |
13164 | rettv->vval.v_number = -1; |
13165 | |
13166 | if (grp == NULL || pat == NULL) { |
13167 | return; |
13168 | } |
13169 | if (argvars[2].v_type != VAR_UNKNOWN) { |
13170 | prio = tv_get_number_chk(&argvars[2], &error); |
13171 | if (argvars[3].v_type != VAR_UNKNOWN) { |
13172 | id = tv_get_number_chk(&argvars[3], &error); |
13173 | if (argvars[4].v_type != VAR_UNKNOWN |
13174 | && matchadd_dict_arg(&argvars[4], &conceal_char, &win) == FAIL) { |
13175 | return; |
13176 | } |
13177 | } |
13178 | } |
13179 | if (error) { |
13180 | return; |
13181 | } |
13182 | if (id >= 1 && id <= 3) { |
13183 | EMSGN(_("E798: ID is reserved for \":match\": %" PRId64), id); |
13184 | return; |
13185 | } |
13186 | |
13187 | rettv->vval.v_number = match_add(win, grp, pat, prio, id, NULL, conceal_char); |
13188 | } |
13189 | |
13190 | static void f_matchaddpos(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
13191 | { |
13192 | rettv->vval.v_number = -1; |
13193 | |
13194 | char buf[NUMBUFLEN]; |
13195 | const char *const group = tv_get_string_buf_chk(&argvars[0], buf); |
13196 | if (group == NULL) { |
13197 | return; |
13198 | } |
13199 | |
13200 | if (argvars[1].v_type != VAR_LIST) { |
13201 | EMSG2(_(e_listarg), "matchaddpos()" ); |
13202 | return; |
13203 | } |
13204 | |
13205 | list_T *l; |
13206 | l = argvars[1].vval.v_list; |
13207 | if (l == NULL) { |
13208 | return; |
13209 | } |
13210 | |
13211 | bool error = false; |
13212 | int prio = 10; |
13213 | int id = -1; |
13214 | const char *conceal_char = NULL; |
13215 | win_T *win = curwin; |
13216 | |
13217 | if (argvars[2].v_type != VAR_UNKNOWN) { |
13218 | prio = tv_get_number_chk(&argvars[2], &error); |
13219 | if (argvars[3].v_type != VAR_UNKNOWN) { |
13220 | id = tv_get_number_chk(&argvars[3], &error); |
13221 | if (argvars[4].v_type != VAR_UNKNOWN |
13222 | && matchadd_dict_arg(&argvars[4], &conceal_char, &win) == FAIL) { |
13223 | return; |
13224 | } |
13225 | } |
13226 | } |
13227 | if (error == true) { |
13228 | return; |
13229 | } |
13230 | |
13231 | // id == 3 is ok because matchaddpos() is supposed to substitute :3match |
13232 | if (id == 1 || id == 2) { |
13233 | EMSGN(_("E798: ID is reserved for \"match\": %" PRId64), id); |
13234 | return; |
13235 | } |
13236 | |
13237 | rettv->vval.v_number = match_add(win, group, NULL, prio, id, l, conceal_char); |
13238 | } |
13239 | |
13240 | /* |
13241 | * "matcharg()" function |
13242 | */ |
13243 | static void f_matcharg(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
13244 | { |
13245 | const int id = tv_get_number(&argvars[0]); |
13246 | |
13247 | tv_list_alloc_ret(rettv, (id >= 1 && id <= 3 |
13248 | ? 2 |
13249 | : 0)); |
13250 | |
13251 | if (id >= 1 && id <= 3) { |
13252 | matchitem_T *const m = (matchitem_T *)get_match(curwin, id); |
13253 | |
13254 | if (m != NULL) { |
13255 | tv_list_append_string(rettv->vval.v_list, |
13256 | (const char *)syn_id2name(m->hlg_id), -1); |
13257 | tv_list_append_string(rettv->vval.v_list, (const char *)m->pattern, -1); |
13258 | } else { |
13259 | tv_list_append_string(rettv->vval.v_list, NULL, 0); |
13260 | tv_list_append_string(rettv->vval.v_list, NULL, 0); |
13261 | } |
13262 | } |
13263 | } |
13264 | |
13265 | /* |
13266 | * "matchdelete()" function |
13267 | */ |
13268 | static void f_matchdelete(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
13269 | { |
13270 | rettv->vval.v_number = match_delete(curwin, |
13271 | (int)tv_get_number(&argvars[0]), true); |
13272 | } |
13273 | |
13274 | /* |
13275 | * "matchend()" function |
13276 | */ |
13277 | static void f_matchend(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
13278 | { |
13279 | find_some_match(argvars, rettv, kSomeMatchEnd); |
13280 | } |
13281 | |
13282 | /* |
13283 | * "matchlist()" function |
13284 | */ |
13285 | static void f_matchlist(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
13286 | { |
13287 | find_some_match(argvars, rettv, kSomeMatchList); |
13288 | } |
13289 | |
13290 | /* |
13291 | * "matchstr()" function |
13292 | */ |
13293 | static void f_matchstr(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
13294 | { |
13295 | find_some_match(argvars, rettv, kSomeMatchStr); |
13296 | } |
13297 | |
13298 | /// "matchstrpos()" function |
13299 | static void f_matchstrpos(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
13300 | { |
13301 | find_some_match(argvars, rettv, kSomeMatchStrPos); |
13302 | } |
13303 | |
13304 | /// Get maximal/minimal number value in a list or dictionary |
13305 | /// |
13306 | /// @param[in] tv List or dictionary to work with. If it contains something |
13307 | /// that is not an integer number (or cannot be coerced to |
13308 | /// it) error is given. |
13309 | /// @param[out] rettv Location where result will be saved. Only assigns |
13310 | /// vval.v_number, type is not touched. Returns zero for |
13311 | /// empty lists/dictionaries. |
13312 | /// @param[in] domax Determines whether maximal or minimal value is desired. |
13313 | static void max_min(const typval_T *const tv, typval_T *const rettv, |
13314 | const bool domax) |
13315 | FUNC_ATTR_NONNULL_ALL |
13316 | { |
13317 | bool error = false; |
13318 | |
13319 | rettv->vval.v_number = 0; |
13320 | varnumber_T n = (domax ? VARNUMBER_MIN : VARNUMBER_MAX); |
13321 | if (tv->v_type == VAR_LIST) { |
13322 | if (tv_list_len(tv->vval.v_list) == 0) { |
13323 | return; |
13324 | } |
13325 | TV_LIST_ITER_CONST(tv->vval.v_list, li, { |
13326 | const varnumber_T i = tv_get_number_chk(TV_LIST_ITEM_TV(li), &error); |
13327 | if (error) { |
13328 | return; |
13329 | } |
13330 | if (domax ? i > n : i < n) { |
13331 | n = i; |
13332 | } |
13333 | }); |
13334 | } else if (tv->v_type == VAR_DICT) { |
13335 | if (tv_dict_len(tv->vval.v_dict) == 0) { |
13336 | return; |
13337 | } |
13338 | TV_DICT_ITER(tv->vval.v_dict, di, { |
13339 | const varnumber_T i = tv_get_number_chk(&di->di_tv, &error); |
13340 | if (error) { |
13341 | return; |
13342 | } |
13343 | if (domax ? i > n : i < n) { |
13344 | n = i; |
13345 | } |
13346 | }); |
13347 | } else { |
13348 | EMSG2(_(e_listdictarg), domax ? "max()" : "min()" ); |
13349 | return; |
13350 | } |
13351 | rettv->vval.v_number = n; |
13352 | } |
13353 | |
13354 | /* |
13355 | * "max()" function |
13356 | */ |
13357 | static void f_max(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
13358 | { |
13359 | max_min(argvars, rettv, TRUE); |
13360 | } |
13361 | |
13362 | /* |
13363 | * "min()" function |
13364 | */ |
13365 | static void f_min(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
13366 | { |
13367 | max_min(argvars, rettv, FALSE); |
13368 | } |
13369 | |
13370 | /* |
13371 | * "mkdir()" function |
13372 | */ |
13373 | static void f_mkdir(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
13374 | { |
13375 | int prot = 0755; // -V536 |
13376 | |
13377 | rettv->vval.v_number = FAIL; |
13378 | if (check_restricted() || check_secure()) |
13379 | return; |
13380 | |
13381 | char buf[NUMBUFLEN]; |
13382 | const char *const dir = tv_get_string_buf(&argvars[0], buf); |
13383 | if (*dir == NUL) { |
13384 | return; |
13385 | } |
13386 | |
13387 | if (*path_tail((char_u *)dir) == NUL) { |
13388 | // Remove trailing slashes. |
13389 | *path_tail_with_sep((char_u *)dir) = NUL; |
13390 | } |
13391 | |
13392 | if (argvars[1].v_type != VAR_UNKNOWN) { |
13393 | if (argvars[2].v_type != VAR_UNKNOWN) { |
13394 | prot = tv_get_number_chk(&argvars[2], NULL); |
13395 | if (prot == -1) { |
13396 | return; |
13397 | } |
13398 | } |
13399 | if (strcmp(tv_get_string(&argvars[1]), "p" ) == 0) { |
13400 | char *failed_dir; |
13401 | int ret = os_mkdir_recurse(dir, prot, &failed_dir); |
13402 | if (ret != 0) { |
13403 | EMSG3(_(e_mkdir), failed_dir, os_strerror(ret)); |
13404 | xfree(failed_dir); |
13405 | rettv->vval.v_number = FAIL; |
13406 | return; |
13407 | } else { |
13408 | rettv->vval.v_number = OK; |
13409 | return; |
13410 | } |
13411 | } |
13412 | } |
13413 | rettv->vval.v_number = vim_mkdir_emsg(dir, prot); |
13414 | } |
13415 | |
13416 | /// "mode()" function |
13417 | static void f_mode(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
13418 | { |
13419 | char *mode = get_mode(); |
13420 | |
13421 | // Clear out the minor mode when the argument is not a non-zero number or |
13422 | // non-empty string. |
13423 | if (!non_zero_arg(&argvars[0])) { |
13424 | mode[1] = NUL; |
13425 | } |
13426 | |
13427 | rettv->vval.v_string = (char_u *)mode; |
13428 | rettv->v_type = VAR_STRING; |
13429 | } |
13430 | |
13431 | /// "msgpackdump()" function |
13432 | static void f_msgpackdump(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
13433 | FUNC_ATTR_NONNULL_ALL |
13434 | { |
13435 | if (argvars[0].v_type != VAR_LIST) { |
13436 | EMSG2(_(e_listarg), "msgpackdump()" ); |
13437 | return; |
13438 | } |
13439 | list_T *const ret_list = tv_list_alloc_ret(rettv, kListLenMayKnow); |
13440 | list_T *const list = argvars[0].vval.v_list; |
13441 | msgpack_packer *lpacker = msgpack_packer_new(ret_list, &encode_list_write); |
13442 | const char *const msg = _("msgpackdump() argument, index %i" ); |
13443 | // Assume that translation will not take more then 4 times more space |
13444 | char msgbuf[sizeof("msgpackdump() argument, index " ) * 4 + NUMBUFLEN]; |
13445 | int idx = 0; |
13446 | TV_LIST_ITER(list, li, { |
13447 | vim_snprintf(msgbuf, sizeof(msgbuf), (char *)msg, idx); |
13448 | idx++; |
13449 | if (encode_vim_to_msgpack(lpacker, TV_LIST_ITEM_TV(li), msgbuf) == FAIL) { |
13450 | break; |
13451 | } |
13452 | }); |
13453 | msgpack_packer_free(lpacker); |
13454 | } |
13455 | |
13456 | /// "msgpackparse" function |
13457 | static void f_msgpackparse(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
13458 | FUNC_ATTR_NONNULL_ALL |
13459 | { |
13460 | if (argvars[0].v_type != VAR_LIST) { |
13461 | EMSG2(_(e_listarg), "msgpackparse()" ); |
13462 | return; |
13463 | } |
13464 | list_T *const ret_list = tv_list_alloc_ret(rettv, kListLenMayKnow); |
13465 | const list_T *const list = argvars[0].vval.v_list; |
13466 | if (tv_list_len(list) == 0) { |
13467 | return; |
13468 | } |
13469 | if (TV_LIST_ITEM_TV(tv_list_first(list))->v_type != VAR_STRING) { |
13470 | EMSG2(_(e_invarg2), "List item is not a string" ); |
13471 | return; |
13472 | } |
13473 | ListReaderState lrstate = encode_init_lrstate(list); |
13474 | msgpack_unpacker *const unpacker = msgpack_unpacker_new(IOSIZE); |
13475 | if (unpacker == NULL) { |
13476 | EMSG(_(e_outofmem)); |
13477 | return; |
13478 | } |
13479 | msgpack_unpacked unpacked; |
13480 | msgpack_unpacked_init(&unpacked); |
13481 | do { |
13482 | if (!msgpack_unpacker_reserve_buffer(unpacker, IOSIZE)) { |
13483 | EMSG(_(e_outofmem)); |
13484 | goto f_msgpackparse_exit; |
13485 | } |
13486 | size_t read_bytes; |
13487 | const int rlret = encode_read_from_list( |
13488 | &lrstate, msgpack_unpacker_buffer(unpacker), IOSIZE, &read_bytes); |
13489 | if (rlret == FAIL) { |
13490 | EMSG2(_(e_invarg2), "List item is not a string" ); |
13491 | goto f_msgpackparse_exit; |
13492 | } |
13493 | msgpack_unpacker_buffer_consumed(unpacker, read_bytes); |
13494 | if (read_bytes == 0) { |
13495 | break; |
13496 | } |
13497 | while (unpacker->off < unpacker->used) { |
13498 | const msgpack_unpack_return result = msgpack_unpacker_next(unpacker, |
13499 | &unpacked); |
13500 | if (result == MSGPACK_UNPACK_PARSE_ERROR) { |
13501 | EMSG2(_(e_invarg2), "Failed to parse msgpack string" ); |
13502 | goto f_msgpackparse_exit; |
13503 | } |
13504 | if (result == MSGPACK_UNPACK_NOMEM_ERROR) { |
13505 | EMSG(_(e_outofmem)); |
13506 | goto f_msgpackparse_exit; |
13507 | } |
13508 | if (result == MSGPACK_UNPACK_SUCCESS) { |
13509 | typval_T tv = { .v_type = VAR_UNKNOWN }; |
13510 | if (msgpack_to_vim(unpacked.data, &tv) == FAIL) { |
13511 | EMSG2(_(e_invarg2), "Failed to convert msgpack string" ); |
13512 | goto f_msgpackparse_exit; |
13513 | } |
13514 | tv_list_append_owned_tv(ret_list, tv); |
13515 | } |
13516 | if (result == MSGPACK_UNPACK_CONTINUE) { |
13517 | if (rlret == OK) { |
13518 | EMSG2(_(e_invarg2), "Incomplete msgpack string" ); |
13519 | } |
13520 | break; |
13521 | } |
13522 | } |
13523 | if (rlret == OK) { |
13524 | break; |
13525 | } |
13526 | } while (true); |
13527 | |
13528 | f_msgpackparse_exit: |
13529 | msgpack_unpacked_destroy(&unpacked); |
13530 | msgpack_unpacker_free(unpacker); |
13531 | return; |
13532 | } |
13533 | |
13534 | /* |
13535 | * "nextnonblank()" function |
13536 | */ |
13537 | static void f_nextnonblank(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
13538 | { |
13539 | linenr_T lnum; |
13540 | |
13541 | for (lnum = tv_get_lnum(argvars);; lnum++) { |
13542 | if (lnum < 0 || lnum > curbuf->b_ml.ml_line_count) { |
13543 | lnum = 0; |
13544 | break; |
13545 | } |
13546 | if (*skipwhite(ml_get(lnum)) != NUL) { |
13547 | break; |
13548 | } |
13549 | } |
13550 | rettv->vval.v_number = lnum; |
13551 | } |
13552 | |
13553 | /* |
13554 | * "nr2char()" function |
13555 | */ |
13556 | static void f_nr2char(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
13557 | { |
13558 | if (argvars[1].v_type != VAR_UNKNOWN) { |
13559 | if (!tv_check_num(&argvars[1])) { |
13560 | return; |
13561 | } |
13562 | } |
13563 | |
13564 | bool error = false; |
13565 | const varnumber_T num = tv_get_number_chk(&argvars[0], &error); |
13566 | if (error) { |
13567 | return; |
13568 | } |
13569 | if (num < 0) { |
13570 | EMSG(_("E5070: Character number must not be less than zero" )); |
13571 | return; |
13572 | } |
13573 | if (num > INT_MAX) { |
13574 | emsgf(_("E5071: Character number must not be greater than INT_MAX (%i)" ), |
13575 | INT_MAX); |
13576 | return; |
13577 | } |
13578 | |
13579 | char buf[MB_MAXBYTES]; |
13580 | const int len = utf_char2bytes((int)num, (char_u *)buf); |
13581 | |
13582 | rettv->v_type = VAR_STRING; |
13583 | rettv->vval.v_string = xmemdupz(buf, (size_t)len); |
13584 | } |
13585 | |
13586 | /* |
13587 | * "or(expr, expr)" function |
13588 | */ |
13589 | static void f_or(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
13590 | { |
13591 | rettv->vval.v_number = tv_get_number_chk(&argvars[0], NULL) |
13592 | | tv_get_number_chk(&argvars[1], NULL); |
13593 | } |
13594 | |
13595 | /* |
13596 | * "pathshorten()" function |
13597 | */ |
13598 | static void f_pathshorten(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
13599 | { |
13600 | rettv->v_type = VAR_STRING; |
13601 | const char *const s = tv_get_string_chk(&argvars[0]); |
13602 | if (!s) { |
13603 | return; |
13604 | } |
13605 | rettv->vval.v_string = shorten_dir((char_u *)xstrdup(s)); |
13606 | } |
13607 | |
13608 | /* |
13609 | * "pow()" function |
13610 | */ |
13611 | static void f_pow(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
13612 | { |
13613 | float_T fx; |
13614 | float_T fy; |
13615 | |
13616 | rettv->v_type = VAR_FLOAT; |
13617 | if (tv_get_float_chk(argvars, &fx) && tv_get_float_chk(&argvars[1], &fy)) { |
13618 | rettv->vval.v_float = pow(fx, fy); |
13619 | } else { |
13620 | rettv->vval.v_float = 0.0; |
13621 | } |
13622 | } |
13623 | |
13624 | /* |
13625 | * "prevnonblank()" function |
13626 | */ |
13627 | static void f_prevnonblank(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
13628 | { |
13629 | linenr_T lnum = tv_get_lnum(argvars); |
13630 | if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count) { |
13631 | lnum = 0; |
13632 | } else { |
13633 | while (lnum >= 1 && *skipwhite(ml_get(lnum)) == NUL) { |
13634 | lnum--; |
13635 | } |
13636 | } |
13637 | rettv->vval.v_number = lnum; |
13638 | } |
13639 | |
13640 | /* |
13641 | * "printf()" function |
13642 | */ |
13643 | static void f_printf(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
13644 | { |
13645 | rettv->v_type = VAR_STRING; |
13646 | rettv->vval.v_string = NULL; |
13647 | { |
13648 | int len; |
13649 | int saved_did_emsg = did_emsg; |
13650 | |
13651 | // Get the required length, allocate the buffer and do it for real. |
13652 | did_emsg = false; |
13653 | char buf[NUMBUFLEN]; |
13654 | const char *fmt = tv_get_string_buf(&argvars[0], buf); |
13655 | len = vim_vsnprintf_typval(NULL, 0, fmt, dummy_ap, argvars + 1); |
13656 | if (!did_emsg) { |
13657 | char *s = xmalloc(len + 1); |
13658 | rettv->vval.v_string = (char_u *)s; |
13659 | (void)vim_vsnprintf_typval(s, len + 1, fmt, dummy_ap, argvars + 1); |
13660 | } |
13661 | did_emsg |= saved_did_emsg; |
13662 | } |
13663 | } |
13664 | |
13665 | /* |
13666 | * "pumvisible()" function |
13667 | */ |
13668 | static void f_pumvisible(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
13669 | { |
13670 | if (pum_visible()) |
13671 | rettv->vval.v_number = 1; |
13672 | } |
13673 | |
13674 | /* |
13675 | * "pyeval()" function |
13676 | */ |
13677 | static void f_pyeval(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
13678 | { |
13679 | script_host_eval("python" , argvars, rettv); |
13680 | } |
13681 | |
13682 | /* |
13683 | * "py3eval()" function |
13684 | */ |
13685 | static void f_py3eval(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
13686 | { |
13687 | script_host_eval("python3" , argvars, rettv); |
13688 | } |
13689 | |
13690 | // "pyxeval()" function |
13691 | static void f_pyxeval(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
13692 | { |
13693 | init_pyxversion(); |
13694 | if (p_pyx == 2) { |
13695 | f_pyeval(argvars, rettv, NULL); |
13696 | } else { |
13697 | f_py3eval(argvars, rettv, NULL); |
13698 | } |
13699 | } |
13700 | |
13701 | /* |
13702 | * "range()" function |
13703 | */ |
13704 | static void f_range(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
13705 | { |
13706 | varnumber_T start; |
13707 | varnumber_T end; |
13708 | varnumber_T stride = 1; |
13709 | varnumber_T i; |
13710 | bool error = false; |
13711 | |
13712 | start = tv_get_number_chk(&argvars[0], &error); |
13713 | if (argvars[1].v_type == VAR_UNKNOWN) { |
13714 | end = start - 1; |
13715 | start = 0; |
13716 | } else { |
13717 | end = tv_get_number_chk(&argvars[1], &error); |
13718 | if (argvars[2].v_type != VAR_UNKNOWN) { |
13719 | stride = tv_get_number_chk(&argvars[2], &error); |
13720 | } |
13721 | } |
13722 | |
13723 | if (error) { |
13724 | return; // Type error; errmsg already given. |
13725 | } |
13726 | if (stride == 0) { |
13727 | EMSG(_("E726: Stride is zero" )); |
13728 | } else if (stride > 0 ? end + 1 < start : end - 1 > start) { |
13729 | EMSG(_("E727: Start past end" )); |
13730 | } else { |
13731 | tv_list_alloc_ret(rettv, (end - start) / stride); |
13732 | for (i = start; stride > 0 ? i <= end : i >= end; i += stride) { |
13733 | tv_list_append_number(rettv->vval.v_list, (varnumber_T)i); |
13734 | } |
13735 | } |
13736 | } |
13737 | |
13738 | /* |
13739 | * "readfile()" function |
13740 | */ |
13741 | static void f_readfile(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
13742 | { |
13743 | bool binary = false; |
13744 | FILE *fd; |
13745 | char_u buf[(IOSIZE/256)*256]; /* rounded to avoid odd + 1 */ |
13746 | int io_size = sizeof(buf); |
13747 | int readlen; /* size of last fread() */ |
13748 | char_u *prev = NULL; /* previously read bytes, if any */ |
13749 | long prevlen = 0; /* length of data in prev */ |
13750 | long prevsize = 0; /* size of prev buffer */ |
13751 | long maxline = MAXLNUM; |
13752 | |
13753 | if (argvars[1].v_type != VAR_UNKNOWN) { |
13754 | if (strcmp(tv_get_string(&argvars[1]), "b" ) == 0) { |
13755 | binary = true; |
13756 | } |
13757 | if (argvars[2].v_type != VAR_UNKNOWN) { |
13758 | maxline = tv_get_number(&argvars[2]); |
13759 | } |
13760 | } |
13761 | |
13762 | list_T *const l = tv_list_alloc_ret(rettv, kListLenUnknown); |
13763 | |
13764 | // Always open the file in binary mode, library functions have a mind of |
13765 | // their own about CR-LF conversion. |
13766 | const char *const fname = tv_get_string(&argvars[0]); |
13767 | if (*fname == NUL || (fd = os_fopen(fname, READBIN)) == NULL) { |
13768 | EMSG2(_(e_notopen), *fname == NUL ? _("<empty>" ) : fname); |
13769 | return; |
13770 | } |
13771 | |
13772 | while (maxline < 0 || tv_list_len(l) < maxline) { |
13773 | readlen = (int)fread(buf, 1, io_size, fd); |
13774 | |
13775 | // This for loop processes what was read, but is also entered at end |
13776 | // of file so that either: |
13777 | // - an incomplete line gets written |
13778 | // - a "binary" file gets an empty line at the end if it ends in a |
13779 | // newline. |
13780 | char_u *p; // Position in buf. |
13781 | char_u *start; // Start of current line. |
13782 | for (p = buf, start = buf; |
13783 | p < buf + readlen || (readlen <= 0 && (prevlen > 0 || binary)); |
13784 | p++) { |
13785 | if (*p == '\n' || readlen <= 0) { |
13786 | char_u *s = NULL; |
13787 | size_t len = p - start; |
13788 | |
13789 | /* Finished a line. Remove CRs before NL. */ |
13790 | if (readlen > 0 && !binary) { |
13791 | while (len > 0 && start[len - 1] == '\r') |
13792 | --len; |
13793 | /* removal may cross back to the "prev" string */ |
13794 | if (len == 0) |
13795 | while (prevlen > 0 && prev[prevlen - 1] == '\r') |
13796 | --prevlen; |
13797 | } |
13798 | if (prevlen == 0) { |
13799 | assert(len < INT_MAX); |
13800 | s = vim_strnsave(start, (int)len); |
13801 | } else { |
13802 | /* Change "prev" buffer to be the right size. This way |
13803 | * the bytes are only copied once, and very long lines are |
13804 | * allocated only once. */ |
13805 | s = xrealloc(prev, prevlen + len + 1); |
13806 | memcpy(s + prevlen, start, len); |
13807 | s[prevlen + len] = NUL; |
13808 | prev = NULL; /* the list will own the string */ |
13809 | prevlen = prevsize = 0; |
13810 | } |
13811 | |
13812 | tv_list_append_owned_tv(l, (typval_T) { |
13813 | .v_type = VAR_STRING, |
13814 | .v_lock = VAR_UNLOCKED, |
13815 | .vval.v_string = s, |
13816 | }); |
13817 | |
13818 | start = p + 1; // Step over newline. |
13819 | if (maxline < 0) { |
13820 | if (tv_list_len(l) > -maxline) { |
13821 | assert(tv_list_len(l) == 1 + (-maxline)); |
13822 | tv_list_item_remove(l, tv_list_first(l)); |
13823 | } |
13824 | } else if (tv_list_len(l) >= maxline) { |
13825 | assert(tv_list_len(l) == maxline); |
13826 | break; |
13827 | } |
13828 | if (readlen <= 0) { |
13829 | break; |
13830 | } |
13831 | } else if (*p == NUL) { |
13832 | *p = '\n'; |
13833 | // Check for utf8 "bom"; U+FEFF is encoded as EF BB BF. Do this |
13834 | // when finding the BF and check the previous two bytes. |
13835 | } else if (*p == 0xbf && !binary) { |
13836 | // Find the two bytes before the 0xbf. If p is at buf, or buf + 1, |
13837 | // these may be in the "prev" string. |
13838 | char_u back1 = p >= buf + 1 ? p[-1] |
13839 | : prevlen >= 1 ? prev[prevlen - 1] : NUL; |
13840 | char_u back2 = p >= buf + 2 ? p[-2] |
13841 | : p == buf + 1 && prevlen >= 1 ? prev[prevlen - 1] |
13842 | : prevlen >= 2 ? prev[prevlen - 2] : NUL; |
13843 | |
13844 | if (back2 == 0xef && back1 == 0xbb) { |
13845 | char_u *dest = p - 2; |
13846 | |
13847 | /* Usually a BOM is at the beginning of a file, and so at |
13848 | * the beginning of a line; then we can just step over it. |
13849 | */ |
13850 | if (start == dest) |
13851 | start = p + 1; |
13852 | else { |
13853 | /* have to shuffle buf to close gap */ |
13854 | int adjust_prevlen = 0; |
13855 | |
13856 | if (dest < buf) { // -V782 |
13857 | adjust_prevlen = (int)(buf - dest); // -V782 |
13858 | // adjust_prevlen must be 1 or 2. |
13859 | dest = buf; |
13860 | } |
13861 | if (readlen > p - buf + 1) |
13862 | memmove(dest, p + 1, readlen - (p - buf) - 1); |
13863 | readlen -= 3 - adjust_prevlen; |
13864 | prevlen -= adjust_prevlen; |
13865 | p = dest - 1; |
13866 | } |
13867 | } |
13868 | } |
13869 | } /* for */ |
13870 | |
13871 | if ((maxline >= 0 && tv_list_len(l) >= maxline) || readlen <= 0) { |
13872 | break; |
13873 | } |
13874 | if (start < p) { |
13875 | /* There's part of a line in buf, store it in "prev". */ |
13876 | if (p - start + prevlen >= prevsize) { |
13877 | |
13878 | /* A common use case is ordinary text files and "prev" gets a |
13879 | * fragment of a line, so the first allocation is made |
13880 | * small, to avoid repeatedly 'allocing' large and |
13881 | * 'reallocing' small. */ |
13882 | if (prevsize == 0) |
13883 | prevsize = (long)(p - start); |
13884 | else { |
13885 | long grow50pc = (prevsize * 3) / 2; |
13886 | long growmin = (long)((p - start) * 2 + prevlen); |
13887 | prevsize = grow50pc > growmin ? grow50pc : growmin; |
13888 | } |
13889 | prev = xrealloc(prev, prevsize); |
13890 | } |
13891 | /* Add the line part to end of "prev". */ |
13892 | memmove(prev + prevlen, start, p - start); |
13893 | prevlen += (long)(p - start); |
13894 | } |
13895 | } /* while */ |
13896 | |
13897 | xfree(prev); |
13898 | fclose(fd); |
13899 | } |
13900 | |
13901 | static void return_register(int regname, typval_T *rettv) |
13902 | { |
13903 | char_u buf[2] = { regname, 0 }; |
13904 | |
13905 | rettv->v_type = VAR_STRING; |
13906 | rettv->vval.v_string = vim_strsave(buf); |
13907 | } |
13908 | |
13909 | // "reg_executing()" function |
13910 | static void f_reg_executing(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
13911 | { |
13912 | return_register(reg_executing, rettv); |
13913 | } |
13914 | |
13915 | // "reg_recording()" function |
13916 | static void f_reg_recording(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
13917 | { |
13918 | return_register(reg_recording, rettv); |
13919 | } |
13920 | |
13921 | /// list2proftime - convert a List to proftime_T |
13922 | /// |
13923 | /// @param arg The input list, must be of type VAR_LIST and have |
13924 | /// exactly 2 items |
13925 | /// @param[out] tm The proftime_T representation of `arg` |
13926 | /// @return OK In case of success, FAIL in case of error |
13927 | static int list2proftime(typval_T *arg, proftime_T *tm) FUNC_ATTR_NONNULL_ALL |
13928 | { |
13929 | if (arg->v_type != VAR_LIST || tv_list_len(arg->vval.v_list) != 2) { |
13930 | return FAIL; |
13931 | } |
13932 | |
13933 | bool error = false; |
13934 | varnumber_T n1 = tv_list_find_nr(arg->vval.v_list, 0L, &error); |
13935 | varnumber_T n2 = tv_list_find_nr(arg->vval.v_list, 1L, &error); |
13936 | if (error) { |
13937 | return FAIL; |
13938 | } |
13939 | |
13940 | // in f_reltime() we split up the 64-bit proftime_T into two 32-bit |
13941 | // values, now we combine them again. |
13942 | union { |
13943 | struct { int32_t low, high; } split; |
13944 | proftime_T prof; |
13945 | } u = { .split.high = n1, .split.low = n2 }; |
13946 | |
13947 | *tm = u.prof; |
13948 | |
13949 | return OK; |
13950 | } |
13951 | |
13952 | /// f_reltime - return an item that represents a time value |
13953 | /// |
13954 | /// @param[out] rettv Without an argument it returns the current time. With |
13955 | /// one argument it returns the time passed since the argument. |
13956 | /// With two arguments it returns the time passed between |
13957 | /// the two arguments. |
13958 | static void f_reltime(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
13959 | { |
13960 | proftime_T res; |
13961 | proftime_T start; |
13962 | |
13963 | if (argvars[0].v_type == VAR_UNKNOWN) { |
13964 | // no arguments: get current time. |
13965 | res = profile_start(); |
13966 | } else if (argvars[1].v_type == VAR_UNKNOWN) { |
13967 | if (list2proftime(&argvars[0], &res) == FAIL) { |
13968 | return; |
13969 | } |
13970 | res = profile_end(res); |
13971 | } else { |
13972 | // two arguments: compute the difference. |
13973 | if (list2proftime(&argvars[0], &start) == FAIL |
13974 | || list2proftime(&argvars[1], &res) == FAIL) { |
13975 | return; |
13976 | } |
13977 | res = profile_sub(res, start); |
13978 | } |
13979 | |
13980 | // we have to store the 64-bit proftime_T inside of a list of int's |
13981 | // (varnumber_T is defined as int). For all our supported platforms, int's |
13982 | // are at least 32-bits wide. So we'll use two 32-bit values to store it. |
13983 | union { |
13984 | struct { int32_t low, high; } split; |
13985 | proftime_T prof; |
13986 | } u = { .prof = res }; |
13987 | |
13988 | // statically assert that the union type conv will provide the correct |
13989 | // results, if varnumber_T or proftime_T change, the union cast will need |
13990 | // to be revised. |
13991 | STATIC_ASSERT(sizeof(u.prof) == sizeof(u) && sizeof(u.split) == sizeof(u), |
13992 | "type punning will produce incorrect results on this platform" ); |
13993 | |
13994 | tv_list_alloc_ret(rettv, 2); |
13995 | tv_list_append_number(rettv->vval.v_list, u.split.high); |
13996 | tv_list_append_number(rettv->vval.v_list, u.split.low); |
13997 | } |
13998 | |
13999 | /// "reltimestr()" function |
14000 | static void f_reltimestr(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
14001 | FUNC_ATTR_NONNULL_ALL |
14002 | { |
14003 | proftime_T tm; |
14004 | |
14005 | rettv->v_type = VAR_STRING; |
14006 | rettv->vval.v_string = NULL; |
14007 | if (list2proftime(&argvars[0], &tm) == OK) { |
14008 | rettv->vval.v_string = (char_u *)xstrdup(profile_msg(tm)); |
14009 | } |
14010 | } |
14011 | |
14012 | /* |
14013 | * "remove()" function |
14014 | */ |
14015 | static void f_remove(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
14016 | { |
14017 | list_T *l; |
14018 | listitem_T *item, *item2; |
14019 | listitem_T *li; |
14020 | long idx; |
14021 | long end; |
14022 | dict_T *d; |
14023 | dictitem_T *di; |
14024 | const char *const arg_errmsg = N_("remove() argument" ); |
14025 | |
14026 | if (argvars[0].v_type == VAR_DICT) { |
14027 | if (argvars[2].v_type != VAR_UNKNOWN) { |
14028 | EMSG2(_(e_toomanyarg), "remove()" ); |
14029 | } else if ((d = argvars[0].vval.v_dict) != NULL |
14030 | && !tv_check_lock(d->dv_lock, arg_errmsg, TV_TRANSLATE)) { |
14031 | const char *key = tv_get_string_chk(&argvars[1]); |
14032 | if (key != NULL) { |
14033 | di = tv_dict_find(d, key, -1); |
14034 | if (di == NULL) { |
14035 | EMSG2(_(e_dictkey), key); |
14036 | } else if (!var_check_fixed(di->di_flags, arg_errmsg, TV_TRANSLATE) |
14037 | && !var_check_ro(di->di_flags, arg_errmsg, TV_TRANSLATE)) { |
14038 | *rettv = di->di_tv; |
14039 | di->di_tv = TV_INITIAL_VALUE; |
14040 | tv_dict_item_remove(d, di); |
14041 | if (tv_dict_is_watched(d)) { |
14042 | tv_dict_watcher_notify(d, key, NULL, rettv); |
14043 | } |
14044 | } |
14045 | } |
14046 | } |
14047 | } else if (argvars[0].v_type != VAR_LIST) { |
14048 | EMSG2(_(e_listdictarg), "remove()" ); |
14049 | } else if (!tv_check_lock(tv_list_locked((l = argvars[0].vval.v_list)), |
14050 | arg_errmsg, TV_TRANSLATE)) { |
14051 | bool error = false; |
14052 | |
14053 | idx = tv_get_number_chk(&argvars[1], &error); |
14054 | if (error) { |
14055 | // Type error: do nothing, errmsg already given. |
14056 | } else if ((item = tv_list_find(l, idx)) == NULL) { |
14057 | EMSGN(_(e_listidx), idx); |
14058 | } else { |
14059 | if (argvars[2].v_type == VAR_UNKNOWN) { |
14060 | // Remove one item, return its value. |
14061 | tv_list_drop_items(l, item, item); |
14062 | *rettv = *TV_LIST_ITEM_TV(item); |
14063 | xfree(item); |
14064 | } else { |
14065 | // Remove range of items, return list with values. |
14066 | end = tv_get_number_chk(&argvars[2], &error); |
14067 | if (error) { |
14068 | // Type error: do nothing. |
14069 | } else if ((item2 = tv_list_find(l, end)) == NULL) { |
14070 | EMSGN(_(e_listidx), end); |
14071 | } else { |
14072 | int cnt = 0; |
14073 | |
14074 | for (li = item; li != NULL; li = TV_LIST_ITEM_NEXT(l, li)) { |
14075 | cnt++; |
14076 | if (li == item2) { |
14077 | break; |
14078 | } |
14079 | } |
14080 | if (li == NULL) { // Didn't find "item2" after "item". |
14081 | EMSG(_(e_invrange)); |
14082 | } else { |
14083 | tv_list_move_items(l, item, item2, tv_list_alloc_ret(rettv, cnt), |
14084 | cnt); |
14085 | } |
14086 | } |
14087 | } |
14088 | } |
14089 | } |
14090 | } |
14091 | |
14092 | /* |
14093 | * "rename({from}, {to})" function |
14094 | */ |
14095 | static void f_rename(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
14096 | { |
14097 | if (check_restricted() || check_secure()) { |
14098 | rettv->vval.v_number = -1; |
14099 | } else { |
14100 | char buf[NUMBUFLEN]; |
14101 | rettv->vval.v_number = vim_rename( |
14102 | (const char_u *)tv_get_string(&argvars[0]), |
14103 | (const char_u *)tv_get_string_buf(&argvars[1], buf)); |
14104 | } |
14105 | } |
14106 | |
14107 | /* |
14108 | * "repeat()" function |
14109 | */ |
14110 | static void f_repeat(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
14111 | { |
14112 | varnumber_T n = tv_get_number(&argvars[1]); |
14113 | if (argvars[0].v_type == VAR_LIST) { |
14114 | tv_list_alloc_ret(rettv, (n > 0) * n * tv_list_len(argvars[0].vval.v_list)); |
14115 | while (n-- > 0) { |
14116 | tv_list_extend(rettv->vval.v_list, argvars[0].vval.v_list, NULL); |
14117 | } |
14118 | } else { |
14119 | rettv->v_type = VAR_STRING; |
14120 | rettv->vval.v_string = NULL; |
14121 | if (n <= 0) { |
14122 | return; |
14123 | } |
14124 | |
14125 | const char *const p = tv_get_string(&argvars[0]); |
14126 | |
14127 | const size_t slen = strlen(p); |
14128 | if (slen == 0) { |
14129 | return; |
14130 | } |
14131 | const size_t len = slen * n; |
14132 | // Detect overflow. |
14133 | if (len / n != slen) { |
14134 | return; |
14135 | } |
14136 | |
14137 | char *const r = xmallocz(len); |
14138 | for (varnumber_T i = 0; i < n; i++) { |
14139 | memmove(r + i * slen, p, slen); |
14140 | } |
14141 | |
14142 | rettv->vval.v_string = (char_u *)r; |
14143 | } |
14144 | } |
14145 | |
14146 | /* |
14147 | * "resolve()" function |
14148 | */ |
14149 | static void f_resolve(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
14150 | { |
14151 | rettv->v_type = VAR_STRING; |
14152 | const char *fname = tv_get_string(&argvars[0]); |
14153 | #ifdef WIN32 |
14154 | char *const v = os_resolve_shortcut(fname); |
14155 | rettv->vval.v_string = (char_u *)(v == NULL ? xstrdup(fname) : v); |
14156 | #else |
14157 | # ifdef HAVE_READLINK |
14158 | { |
14159 | bool is_relative_to_current = false; |
14160 | bool has_trailing_pathsep = false; |
14161 | int limit = 100; |
14162 | |
14163 | char *p = xstrdup(fname); |
14164 | |
14165 | if (p[0] == '.' && (vim_ispathsep(p[1]) |
14166 | || (p[1] == '.' && (vim_ispathsep(p[2]))))) { |
14167 | is_relative_to_current = true; |
14168 | } |
14169 | |
14170 | ptrdiff_t len = (ptrdiff_t)strlen(p); |
14171 | if (len > 0 && after_pathsep(p, p + len)) { |
14172 | has_trailing_pathsep = true; |
14173 | p[len - 1] = NUL; // The trailing slash breaks readlink(). |
14174 | } |
14175 | |
14176 | char *q = (char *)path_next_component(p); |
14177 | char *remain = NULL; |
14178 | if (*q != NUL) { |
14179 | // Separate the first path component in "p", and keep the |
14180 | // remainder (beginning with the path separator). |
14181 | remain = xstrdup(q - 1); |
14182 | q[-1] = NUL; |
14183 | } |
14184 | |
14185 | char *const buf = xmallocz(MAXPATHL); |
14186 | |
14187 | char *cpy; |
14188 | for (;; ) { |
14189 | for (;; ) { |
14190 | len = readlink(p, buf, MAXPATHL); |
14191 | if (len <= 0) { |
14192 | break; |
14193 | } |
14194 | buf[len] = NUL; |
14195 | |
14196 | if (limit-- == 0) { |
14197 | xfree(p); |
14198 | xfree(remain); |
14199 | EMSG(_("E655: Too many symbolic links (cycle?)" )); |
14200 | rettv->vval.v_string = NULL; |
14201 | xfree(buf); |
14202 | return; |
14203 | } |
14204 | |
14205 | // Ensure that the result will have a trailing path separator |
14206 | // if the argument has one. */ |
14207 | if (remain == NULL && has_trailing_pathsep) { |
14208 | add_pathsep(buf); |
14209 | } |
14210 | |
14211 | // Separate the first path component in the link value and |
14212 | // concatenate the remainders. */ |
14213 | q = (char *)path_next_component(vim_ispathsep(*buf) ? buf + 1 : buf); |
14214 | if (*q != NUL) { |
14215 | cpy = remain; |
14216 | remain = (remain |
14217 | ? (char *)concat_str((char_u *)q - 1, (char_u *)remain) |
14218 | : xstrdup(q - 1)); |
14219 | xfree(cpy); |
14220 | q[-1] = NUL; |
14221 | } |
14222 | |
14223 | q = (char *)path_tail((char_u *)p); |
14224 | if (q > p && *q == NUL) { |
14225 | // Ignore trailing path separator. |
14226 | q[-1] = NUL; |
14227 | q = (char *)path_tail((char_u *)p); |
14228 | } |
14229 | if (q > p && !path_is_absolute((const char_u *)buf)) { |
14230 | // Symlink is relative to directory of argument. Replace the |
14231 | // symlink with the resolved name in the same directory. |
14232 | const size_t p_len = strlen(p); |
14233 | const size_t buf_len = strlen(buf); |
14234 | p = xrealloc(p, p_len + buf_len + 1); |
14235 | memcpy(path_tail((char_u *)p), buf, buf_len + 1); |
14236 | } else { |
14237 | xfree(p); |
14238 | p = xstrdup(buf); |
14239 | } |
14240 | } |
14241 | |
14242 | if (remain == NULL) { |
14243 | break; |
14244 | } |
14245 | |
14246 | // Append the first path component of "remain" to "p". |
14247 | q = (char *)path_next_component(remain + 1); |
14248 | len = q - remain - (*q != NUL); |
14249 | const size_t p_len = strlen(p); |
14250 | cpy = xmallocz(p_len + len); |
14251 | memcpy(cpy, p, p_len + 1); |
14252 | xstrlcat(cpy + p_len, remain, len + 1); |
14253 | xfree(p); |
14254 | p = cpy; |
14255 | |
14256 | // Shorten "remain". |
14257 | if (*q != NUL) { |
14258 | STRMOVE(remain, q - 1); |
14259 | } else { |
14260 | XFREE_CLEAR(remain); |
14261 | } |
14262 | } |
14263 | |
14264 | // If the result is a relative path name, make it explicitly relative to |
14265 | // the current directory if and only if the argument had this form. |
14266 | if (!vim_ispathsep(*p)) { |
14267 | if (is_relative_to_current |
14268 | && *p != NUL |
14269 | && !(p[0] == '.' |
14270 | && (p[1] == NUL |
14271 | || vim_ispathsep(p[1]) |
14272 | || (p[1] == '.' |
14273 | && (p[2] == NUL |
14274 | || vim_ispathsep(p[2])))))) { |
14275 | // Prepend "./". |
14276 | cpy = (char *)concat_str((const char_u *)"./" , (const char_u *)p); |
14277 | xfree(p); |
14278 | p = cpy; |
14279 | } else if (!is_relative_to_current) { |
14280 | // Strip leading "./". |
14281 | q = p; |
14282 | while (q[0] == '.' && vim_ispathsep(q[1])) { |
14283 | q += 2; |
14284 | } |
14285 | if (q > p) { |
14286 | STRMOVE(p, p + 2); |
14287 | } |
14288 | } |
14289 | } |
14290 | |
14291 | // Ensure that the result will have no trailing path separator |
14292 | // if the argument had none. But keep "/" or "//". |
14293 | if (!has_trailing_pathsep) { |
14294 | q = p + strlen(p); |
14295 | if (after_pathsep(p, q)) { |
14296 | *path_tail_with_sep((char_u *)p) = NUL; |
14297 | } |
14298 | } |
14299 | |
14300 | rettv->vval.v_string = (char_u *)p; |
14301 | xfree(buf); |
14302 | } |
14303 | # else |
14304 | rettv->vval.v_string = (char_u *)xstrdup(p); |
14305 | # endif |
14306 | #endif |
14307 | |
14308 | simplify_filename(rettv->vval.v_string); |
14309 | } |
14310 | |
14311 | /* |
14312 | * "reverse({list})" function |
14313 | */ |
14314 | static void f_reverse(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
14315 | { |
14316 | list_T *l; |
14317 | if (argvars[0].v_type != VAR_LIST) { |
14318 | EMSG2(_(e_listarg), "reverse()" ); |
14319 | } else if (!tv_check_lock(tv_list_locked((l = argvars[0].vval.v_list)), |
14320 | N_("reverse() argument" ), TV_TRANSLATE)) { |
14321 | tv_list_reverse(l); |
14322 | tv_list_set_ret(rettv, l); |
14323 | } |
14324 | } |
14325 | |
14326 | #define SP_NOMOVE 0x01 ///< don't move cursor |
14327 | #define SP_REPEAT 0x02 ///< repeat to find outer pair |
14328 | #define SP_RETCOUNT 0x04 ///< return matchcount |
14329 | #define SP_SETPCMARK 0x08 ///< set previous context mark |
14330 | #define SP_START 0x10 ///< accept match at start position |
14331 | #define SP_SUBPAT 0x20 ///< return nr of matching sub-pattern |
14332 | #define SP_END 0x40 ///< leave cursor at end of match |
14333 | #define SP_COLUMN 0x80 ///< start at cursor column |
14334 | |
14335 | /* |
14336 | * Get flags for a search function. |
14337 | * Possibly sets "p_ws". |
14338 | * Returns BACKWARD, FORWARD or zero (for an error). |
14339 | */ |
14340 | static int get_search_arg(typval_T *varp, int *flagsp) |
14341 | { |
14342 | int dir = FORWARD; |
14343 | int mask; |
14344 | |
14345 | if (varp->v_type != VAR_UNKNOWN) { |
14346 | char nbuf[NUMBUFLEN]; |
14347 | const char *flags = tv_get_string_buf_chk(varp, nbuf); |
14348 | if (flags == NULL) { |
14349 | return 0; // Type error; errmsg already given. |
14350 | } |
14351 | while (*flags != NUL) { |
14352 | switch (*flags) { |
14353 | case 'b': dir = BACKWARD; break; |
14354 | case 'w': p_ws = true; break; |
14355 | case 'W': p_ws = false; break; |
14356 | default: { |
14357 | mask = 0; |
14358 | if (flagsp != NULL) { |
14359 | switch (*flags) { |
14360 | case 'c': mask = SP_START; break; |
14361 | case 'e': mask = SP_END; break; |
14362 | case 'm': mask = SP_RETCOUNT; break; |
14363 | case 'n': mask = SP_NOMOVE; break; |
14364 | case 'p': mask = SP_SUBPAT; break; |
14365 | case 'r': mask = SP_REPEAT; break; |
14366 | case 's': mask = SP_SETPCMARK; break; |
14367 | case 'z': mask = SP_COLUMN; break; |
14368 | } |
14369 | } |
14370 | if (mask == 0) { |
14371 | emsgf(_(e_invarg2), flags); |
14372 | dir = 0; |
14373 | } else { |
14374 | *flagsp |= mask; |
14375 | } |
14376 | } |
14377 | } |
14378 | if (dir == 0) { |
14379 | break; |
14380 | } |
14381 | flags++; |
14382 | } |
14383 | } |
14384 | return dir; |
14385 | } |
14386 | |
14387 | // Shared by search() and searchpos() functions. |
14388 | static int search_cmn(typval_T *argvars, pos_T *match_pos, int *flagsp) |
14389 | { |
14390 | int flags; |
14391 | pos_T pos; |
14392 | pos_T save_cursor; |
14393 | bool save_p_ws = p_ws; |
14394 | int dir; |
14395 | int retval = 0; /* default: FAIL */ |
14396 | long lnum_stop = 0; |
14397 | proftime_T tm; |
14398 | long time_limit = 0; |
14399 | int options = SEARCH_KEEP; |
14400 | int subpatnum; |
14401 | |
14402 | const char *const pat = tv_get_string(&argvars[0]); |
14403 | dir = get_search_arg(&argvars[1], flagsp); // May set p_ws. |
14404 | if (dir == 0) { |
14405 | goto theend; |
14406 | } |
14407 | flags = *flagsp; |
14408 | if (flags & SP_START) { |
14409 | options |= SEARCH_START; |
14410 | } |
14411 | if (flags & SP_END) { |
14412 | options |= SEARCH_END; |
14413 | } |
14414 | if (flags & SP_COLUMN) { |
14415 | options |= SEARCH_COL; |
14416 | } |
14417 | |
14418 | /* Optional arguments: line number to stop searching and timeout. */ |
14419 | if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN) { |
14420 | lnum_stop = tv_get_number_chk(&argvars[2], NULL); |
14421 | if (lnum_stop < 0) { |
14422 | goto theend; |
14423 | } |
14424 | if (argvars[3].v_type != VAR_UNKNOWN) { |
14425 | time_limit = tv_get_number_chk(&argvars[3], NULL); |
14426 | if (time_limit < 0) { |
14427 | goto theend; |
14428 | } |
14429 | } |
14430 | } |
14431 | |
14432 | /* Set the time limit, if there is one. */ |
14433 | tm = profile_setlimit(time_limit); |
14434 | |
14435 | /* |
14436 | * This function does not accept SP_REPEAT and SP_RETCOUNT flags. |
14437 | * Check to make sure only those flags are set. |
14438 | * Also, Only the SP_NOMOVE or the SP_SETPCMARK flag can be set. Both |
14439 | * flags cannot be set. Check for that condition also. |
14440 | */ |
14441 | if (((flags & (SP_REPEAT | SP_RETCOUNT)) != 0) |
14442 | || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK))) { |
14443 | EMSG2(_(e_invarg2), tv_get_string(&argvars[1])); |
14444 | goto theend; |
14445 | } |
14446 | |
14447 | pos = save_cursor = curwin->w_cursor; |
14448 | subpatnum = searchit(curwin, curbuf, &pos, NULL, dir, (char_u *)pat, 1, |
14449 | options, RE_SEARCH, (linenr_T)lnum_stop, &tm, NULL); |
14450 | if (subpatnum != FAIL) { |
14451 | if (flags & SP_SUBPAT) |
14452 | retval = subpatnum; |
14453 | else |
14454 | retval = pos.lnum; |
14455 | if (flags & SP_SETPCMARK) |
14456 | setpcmark(); |
14457 | curwin->w_cursor = pos; |
14458 | if (match_pos != NULL) { |
14459 | /* Store the match cursor position */ |
14460 | match_pos->lnum = pos.lnum; |
14461 | match_pos->col = pos.col + 1; |
14462 | } |
14463 | /* "/$" will put the cursor after the end of the line, may need to |
14464 | * correct that here */ |
14465 | check_cursor(); |
14466 | } |
14467 | |
14468 | /* If 'n' flag is used: restore cursor position. */ |
14469 | if (flags & SP_NOMOVE) |
14470 | curwin->w_cursor = save_cursor; |
14471 | else |
14472 | curwin->w_set_curswant = TRUE; |
14473 | theend: |
14474 | p_ws = save_p_ws; |
14475 | |
14476 | return retval; |
14477 | } |
14478 | |
14479 | // "rpcnotify()" function |
14480 | static void f_rpcnotify(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
14481 | { |
14482 | rettv->v_type = VAR_NUMBER; |
14483 | rettv->vval.v_number = 0; |
14484 | |
14485 | if (check_restricted() || check_secure()) { |
14486 | return; |
14487 | } |
14488 | |
14489 | if (argvars[0].v_type != VAR_NUMBER || argvars[0].vval.v_number < 0) { |
14490 | EMSG2(_(e_invarg2), "Channel id must be a positive integer" ); |
14491 | return; |
14492 | } |
14493 | |
14494 | if (argvars[1].v_type != VAR_STRING) { |
14495 | EMSG2(_(e_invarg2), "Event type must be a string" ); |
14496 | return; |
14497 | } |
14498 | |
14499 | Array args = ARRAY_DICT_INIT; |
14500 | |
14501 | for (typval_T *tv = argvars + 2; tv->v_type != VAR_UNKNOWN; tv++) { |
14502 | ADD(args, vim_to_object(tv)); |
14503 | } |
14504 | |
14505 | if (!rpc_send_event((uint64_t)argvars[0].vval.v_number, |
14506 | tv_get_string(&argvars[1]), args)) { |
14507 | EMSG2(_(e_invarg2), "Channel doesn't exist" ); |
14508 | return; |
14509 | } |
14510 | |
14511 | rettv->vval.v_number = 1; |
14512 | } |
14513 | |
14514 | // "rpcrequest()" function |
14515 | static void f_rpcrequest(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
14516 | { |
14517 | rettv->v_type = VAR_NUMBER; |
14518 | rettv->vval.v_number = 0; |
14519 | const int l_provider_call_nesting = provider_call_nesting; |
14520 | |
14521 | if (check_restricted() || check_secure()) { |
14522 | return; |
14523 | } |
14524 | |
14525 | if (argvars[0].v_type != VAR_NUMBER || argvars[0].vval.v_number <= 0) { |
14526 | EMSG2(_(e_invarg2), "Channel id must be a positive integer" ); |
14527 | return; |
14528 | } |
14529 | |
14530 | if (argvars[1].v_type != VAR_STRING) { |
14531 | EMSG2(_(e_invarg2), "Method name must be a string" ); |
14532 | return; |
14533 | } |
14534 | |
14535 | Array args = ARRAY_DICT_INIT; |
14536 | |
14537 | for (typval_T *tv = argvars + 2; tv->v_type != VAR_UNKNOWN; tv++) { |
14538 | ADD(args, vim_to_object(tv)); |
14539 | } |
14540 | |
14541 | sctx_T save_current_sctx; |
14542 | uint8_t *save_sourcing_name, *save_autocmd_fname, *save_autocmd_match; |
14543 | linenr_T save_sourcing_lnum; |
14544 | int save_autocmd_bufnr; |
14545 | void *save_funccalp; |
14546 | |
14547 | if (l_provider_call_nesting) { |
14548 | // If this is called from a provider function, restore the scope |
14549 | // information of the caller. |
14550 | save_current_sctx = current_sctx; |
14551 | save_sourcing_name = sourcing_name; |
14552 | save_sourcing_lnum = sourcing_lnum; |
14553 | save_autocmd_fname = autocmd_fname; |
14554 | save_autocmd_match = autocmd_match; |
14555 | save_autocmd_bufnr = autocmd_bufnr; |
14556 | save_funccalp = save_funccal(); |
14557 | |
14558 | current_sctx = provider_caller_scope.script_ctx; |
14559 | sourcing_name = provider_caller_scope.sourcing_name; |
14560 | sourcing_lnum = provider_caller_scope.sourcing_lnum; |
14561 | autocmd_fname = provider_caller_scope.autocmd_fname; |
14562 | autocmd_match = provider_caller_scope.autocmd_match; |
14563 | autocmd_bufnr = provider_caller_scope.autocmd_bufnr; |
14564 | restore_funccal(provider_caller_scope.funccalp); |
14565 | } |
14566 | |
14567 | |
14568 | Error err = ERROR_INIT; |
14569 | |
14570 | uint64_t chan_id = (uint64_t)argvars[0].vval.v_number; |
14571 | const char *method = tv_get_string(&argvars[1]); |
14572 | |
14573 | Object result = rpc_send_call(chan_id, method, args, &err); |
14574 | |
14575 | if (l_provider_call_nesting) { |
14576 | current_sctx = save_current_sctx; |
14577 | sourcing_name = save_sourcing_name; |
14578 | sourcing_lnum = save_sourcing_lnum; |
14579 | autocmd_fname = save_autocmd_fname; |
14580 | autocmd_match = save_autocmd_match; |
14581 | autocmd_bufnr = save_autocmd_bufnr; |
14582 | restore_funccal(save_funccalp); |
14583 | } |
14584 | |
14585 | if (ERROR_SET(&err)) { |
14586 | const char *name = NULL; |
14587 | Channel *chan = find_channel(chan_id); |
14588 | if (chan) { |
14589 | name = rpc_client_name(chan); |
14590 | } |
14591 | msg_ext_set_kind("rpc_error" ); |
14592 | if (name) { |
14593 | emsgf_multiline("Error invoking '%s' on channel %" PRIu64" (%s):\n%s" , |
14594 | method, chan_id, name, err.msg); |
14595 | } else { |
14596 | emsgf_multiline("Error invoking '%s' on channel %" PRIu64":\n%s" , |
14597 | method, chan_id, err.msg); |
14598 | } |
14599 | |
14600 | goto end; |
14601 | } |
14602 | |
14603 | if (!object_to_vim(result, rettv, &err)) { |
14604 | EMSG2(_("Error converting the call result: %s" ), err.msg); |
14605 | } |
14606 | |
14607 | end: |
14608 | api_free_object(result); |
14609 | api_clear_error(&err); |
14610 | } |
14611 | |
14612 | // "rpcstart()" function (DEPRECATED) |
14613 | static void f_rpcstart(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
14614 | { |
14615 | rettv->v_type = VAR_NUMBER; |
14616 | rettv->vval.v_number = 0; |
14617 | |
14618 | if (check_restricted() || check_secure()) { |
14619 | return; |
14620 | } |
14621 | |
14622 | if (argvars[0].v_type != VAR_STRING |
14623 | || (argvars[1].v_type != VAR_LIST && argvars[1].v_type != VAR_UNKNOWN)) { |
14624 | // Wrong argument types |
14625 | EMSG(_(e_invarg)); |
14626 | return; |
14627 | } |
14628 | |
14629 | list_T *args = NULL; |
14630 | int argsl = 0; |
14631 | if (argvars[1].v_type == VAR_LIST) { |
14632 | args = argvars[1].vval.v_list; |
14633 | argsl = tv_list_len(args); |
14634 | // Assert that all list items are strings |
14635 | int i = 0; |
14636 | TV_LIST_ITER_CONST(args, arg, { |
14637 | if (TV_LIST_ITEM_TV(arg)->v_type != VAR_STRING) { |
14638 | emsgf(_("E5010: List item %d of the second argument is not a string" ), |
14639 | i); |
14640 | return; |
14641 | } |
14642 | i++; |
14643 | }); |
14644 | } |
14645 | |
14646 | if (argvars[0].vval.v_string == NULL || argvars[0].vval.v_string[0] == NUL) { |
14647 | EMSG(_(e_api_spawn_failed)); |
14648 | return; |
14649 | } |
14650 | |
14651 | // Allocate extra memory for the argument vector and the NULL pointer |
14652 | int argvl = argsl + 2; |
14653 | char **argv = xmalloc(sizeof(char_u *) * argvl); |
14654 | |
14655 | // Copy program name |
14656 | argv[0] = xstrdup((char *)argvars[0].vval.v_string); |
14657 | |
14658 | int i = 1; |
14659 | // Copy arguments to the vector |
14660 | if (argsl > 0) { |
14661 | TV_LIST_ITER_CONST(args, arg, { |
14662 | argv[i++] = xstrdup(tv_get_string(TV_LIST_ITEM_TV(arg))); |
14663 | }); |
14664 | } |
14665 | |
14666 | // The last item of argv must be NULL |
14667 | argv[i] = NULL; |
14668 | |
14669 | Channel *chan = channel_job_start(argv, CALLBACK_READER_INIT, |
14670 | CALLBACK_READER_INIT, CALLBACK_NONE, |
14671 | false, true, false, NULL, 0, 0, NULL, |
14672 | &rettv->vval.v_number); |
14673 | if (chan) { |
14674 | channel_create_event(chan, NULL); |
14675 | } |
14676 | } |
14677 | |
14678 | // "rpcstop()" function |
14679 | static void f_rpcstop(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
14680 | { |
14681 | rettv->v_type = VAR_NUMBER; |
14682 | rettv->vval.v_number = 0; |
14683 | |
14684 | if (check_restricted() || check_secure()) { |
14685 | return; |
14686 | } |
14687 | |
14688 | if (argvars[0].v_type != VAR_NUMBER) { |
14689 | // Wrong argument types |
14690 | EMSG(_(e_invarg)); |
14691 | return; |
14692 | } |
14693 | |
14694 | // if called with a job, stop it, else closes the channel |
14695 | uint64_t id = argvars[0].vval.v_number; |
14696 | if (find_job(id, false)) { |
14697 | f_jobstop(argvars, rettv, NULL); |
14698 | } else { |
14699 | const char *error; |
14700 | rettv->vval.v_number = channel_close(argvars[0].vval.v_number, |
14701 | kChannelPartRpc, &error); |
14702 | if (!rettv->vval.v_number) { |
14703 | EMSG(error); |
14704 | } |
14705 | } |
14706 | } |
14707 | |
14708 | static void screenchar_adjust_grid(ScreenGrid **grid, int *row, int *col) |
14709 | { |
14710 | // TODO(bfredl): this is a hack for legacy tests which use screenchar() |
14711 | // to check printed messages on the screen (but not floats etc |
14712 | // as these are not legacy features). If the compositor is refactored to |
14713 | // have its own buffer, this should just read from it instead. |
14714 | msg_scroll_flush(); |
14715 | if (msg_grid.chars && msg_grid.comp_index > 0 && *row >= msg_grid.comp_row |
14716 | && *row < (msg_grid.Rows + msg_grid.comp_row) |
14717 | && *col < msg_grid.Columns) { |
14718 | *grid = &msg_grid; |
14719 | *row -= msg_grid.comp_row; |
14720 | } |
14721 | } |
14722 | |
14723 | /* |
14724 | * "screenattr()" function |
14725 | */ |
14726 | static void f_screenattr(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
14727 | { |
14728 | int c; |
14729 | |
14730 | int row = (int)tv_get_number_chk(&argvars[0], NULL) - 1; |
14731 | int col = (int)tv_get_number_chk(&argvars[1], NULL) - 1; |
14732 | if (row < 0 || row >= default_grid.Rows |
14733 | || col < 0 || col >= default_grid.Columns) { |
14734 | c = -1; |
14735 | } else { |
14736 | ScreenGrid *grid = &default_grid; |
14737 | screenchar_adjust_grid(&grid, &row, &col); |
14738 | c = grid->attrs[grid->line_offset[row] + col]; |
14739 | } |
14740 | rettv->vval.v_number = c; |
14741 | } |
14742 | |
14743 | /* |
14744 | * "screenchar()" function |
14745 | */ |
14746 | static void f_screenchar(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
14747 | { |
14748 | int c; |
14749 | |
14750 | int row = tv_get_number_chk(&argvars[0], NULL) - 1; |
14751 | int col = tv_get_number_chk(&argvars[1], NULL) - 1; |
14752 | if (row < 0 || row >= default_grid.Rows |
14753 | || col < 0 || col >= default_grid.Columns) { |
14754 | c = -1; |
14755 | } else { |
14756 | ScreenGrid *grid = &default_grid; |
14757 | screenchar_adjust_grid(&grid, &row, &col); |
14758 | c = utf_ptr2char(grid->chars[grid->line_offset[row] + col]); |
14759 | } |
14760 | rettv->vval.v_number = c; |
14761 | } |
14762 | |
14763 | /* |
14764 | * "screencol()" function |
14765 | * |
14766 | * First column is 1 to be consistent with virtcol(). |
14767 | */ |
14768 | static void f_screencol(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
14769 | { |
14770 | rettv->vval.v_number = ui_current_col() + 1; |
14771 | } |
14772 | |
14773 | /// "screenpos({winid}, {lnum}, {col})" function |
14774 | static void f_screenpos(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
14775 | { |
14776 | pos_T pos; |
14777 | int row = 0; |
14778 | int scol = 0, ccol = 0, ecol = 0; |
14779 | |
14780 | tv_dict_alloc_ret(rettv); |
14781 | dict_T *dict = rettv->vval.v_dict; |
14782 | |
14783 | win_T *wp = find_win_by_nr_or_id(&argvars[0]); |
14784 | if (wp == NULL) { |
14785 | return; |
14786 | } |
14787 | |
14788 | pos.lnum = tv_get_number(&argvars[1]); |
14789 | pos.col = tv_get_number(&argvars[2]) - 1; |
14790 | pos.coladd = 0; |
14791 | textpos2screenpos(wp, &pos, &row, &scol, &ccol, &ecol, false); |
14792 | |
14793 | tv_dict_add_nr(dict, S_LEN("row" ), row); |
14794 | tv_dict_add_nr(dict, S_LEN("col" ), scol); |
14795 | tv_dict_add_nr(dict, S_LEN("curscol" ), ccol); |
14796 | tv_dict_add_nr(dict, S_LEN("endcol" ), ecol); |
14797 | } |
14798 | |
14799 | /* |
14800 | * "screenrow()" function |
14801 | */ |
14802 | static void f_screenrow(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
14803 | { |
14804 | rettv->vval.v_number = ui_current_row() + 1; |
14805 | } |
14806 | |
14807 | /* |
14808 | * "search()" function |
14809 | */ |
14810 | static void f_search(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
14811 | { |
14812 | int flags = 0; |
14813 | |
14814 | rettv->vval.v_number = search_cmn(argvars, NULL, &flags); |
14815 | } |
14816 | |
14817 | /* |
14818 | * "searchdecl()" function |
14819 | */ |
14820 | static void f_searchdecl(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
14821 | { |
14822 | int locally = 1; |
14823 | int thisblock = 0; |
14824 | bool error = false; |
14825 | |
14826 | rettv->vval.v_number = 1; /* default: FAIL */ |
14827 | |
14828 | const char *const name = tv_get_string_chk(&argvars[0]); |
14829 | if (argvars[1].v_type != VAR_UNKNOWN) { |
14830 | locally = tv_get_number_chk(&argvars[1], &error) == 0; |
14831 | if (!error && argvars[2].v_type != VAR_UNKNOWN) { |
14832 | thisblock = tv_get_number_chk(&argvars[2], &error) != 0; |
14833 | } |
14834 | } |
14835 | if (!error && name != NULL) { |
14836 | rettv->vval.v_number = find_decl((char_u *)name, strlen(name), locally, |
14837 | thisblock, SEARCH_KEEP) == FAIL; |
14838 | } |
14839 | } |
14840 | |
14841 | /* |
14842 | * Used by searchpair() and searchpairpos() |
14843 | */ |
14844 | static int searchpair_cmn(typval_T *argvars, pos_T *match_pos) |
14845 | { |
14846 | bool save_p_ws = p_ws; |
14847 | int dir; |
14848 | int flags = 0; |
14849 | int retval = 0; // default: FAIL |
14850 | long lnum_stop = 0; |
14851 | long time_limit = 0; |
14852 | |
14853 | // Get the three pattern arguments: start, middle, end. Will result in an |
14854 | // error if not a valid argument. |
14855 | char nbuf1[NUMBUFLEN]; |
14856 | char nbuf2[NUMBUFLEN]; |
14857 | const char *spat = tv_get_string_chk(&argvars[0]); |
14858 | const char *mpat = tv_get_string_buf_chk(&argvars[1], nbuf1); |
14859 | const char *epat = tv_get_string_buf_chk(&argvars[2], nbuf2); |
14860 | if (spat == NULL || mpat == NULL || epat == NULL) { |
14861 | goto theend; // Type error. |
14862 | } |
14863 | |
14864 | // Handle the optional fourth argument: flags. |
14865 | dir = get_search_arg(&argvars[3], &flags); // may set p_ws. |
14866 | if (dir == 0) { |
14867 | goto theend; |
14868 | } |
14869 | |
14870 | // Don't accept SP_END or SP_SUBPAT. |
14871 | // Only one of the SP_NOMOVE or SP_SETPCMARK flags can be set. |
14872 | if ((flags & (SP_END | SP_SUBPAT)) != 0 |
14873 | || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK))) { |
14874 | EMSG2(_(e_invarg2), tv_get_string(&argvars[3])); |
14875 | goto theend; |
14876 | } |
14877 | |
14878 | // Using 'r' implies 'W', otherwise it doesn't work. |
14879 | if (flags & SP_REPEAT) { |
14880 | p_ws = false; |
14881 | } |
14882 | |
14883 | // Optional fifth argument: skip expression. |
14884 | const typval_T *skip; |
14885 | if (argvars[3].v_type == VAR_UNKNOWN |
14886 | || argvars[4].v_type == VAR_UNKNOWN) { |
14887 | skip = NULL; |
14888 | } else { |
14889 | skip = &argvars[4]; |
14890 | if (skip->v_type != VAR_FUNC |
14891 | && skip->v_type != VAR_PARTIAL |
14892 | && skip->v_type != VAR_STRING) { |
14893 | emsgf(_(e_invarg2), tv_get_string(&argvars[4])); |
14894 | goto theend; // Type error. |
14895 | } |
14896 | if (argvars[5].v_type != VAR_UNKNOWN) { |
14897 | lnum_stop = tv_get_number_chk(&argvars[5], NULL); |
14898 | if (lnum_stop < 0) { |
14899 | emsgf(_(e_invarg2), tv_get_string(&argvars[5])); |
14900 | goto theend; |
14901 | } |
14902 | if (argvars[6].v_type != VAR_UNKNOWN) { |
14903 | time_limit = tv_get_number_chk(&argvars[6], NULL); |
14904 | if (time_limit < 0) { |
14905 | emsgf(_(e_invarg2), tv_get_string(&argvars[6])); |
14906 | goto theend; |
14907 | } |
14908 | } |
14909 | } |
14910 | } |
14911 | |
14912 | retval = do_searchpair( |
14913 | (char_u *)spat, (char_u *)mpat, (char_u *)epat, dir, skip, |
14914 | flags, match_pos, lnum_stop, time_limit); |
14915 | |
14916 | theend: |
14917 | p_ws = save_p_ws; |
14918 | |
14919 | return retval; |
14920 | } |
14921 | |
14922 | /* |
14923 | * "searchpair()" function |
14924 | */ |
14925 | static void f_searchpair(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
14926 | { |
14927 | rettv->vval.v_number = searchpair_cmn(argvars, NULL); |
14928 | } |
14929 | |
14930 | /* |
14931 | * "searchpairpos()" function |
14932 | */ |
14933 | static void f_searchpairpos(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
14934 | { |
14935 | pos_T match_pos; |
14936 | int lnum = 0; |
14937 | int col = 0; |
14938 | |
14939 | tv_list_alloc_ret(rettv, 2); |
14940 | |
14941 | if (searchpair_cmn(argvars, &match_pos) > 0) { |
14942 | lnum = match_pos.lnum; |
14943 | col = match_pos.col; |
14944 | } |
14945 | |
14946 | tv_list_append_number(rettv->vval.v_list, (varnumber_T)lnum); |
14947 | tv_list_append_number(rettv->vval.v_list, (varnumber_T)col); |
14948 | } |
14949 | |
14950 | /* |
14951 | * Search for a start/middle/end thing. |
14952 | * Used by searchpair(), see its documentation for the details. |
14953 | * Returns 0 or -1 for no match, |
14954 | */ |
14955 | long |
14956 | do_searchpair( |
14957 | char_u *spat, // start pattern |
14958 | char_u *mpat, // middle pattern |
14959 | char_u *epat, // end pattern |
14960 | int dir, // BACKWARD or FORWARD |
14961 | const typval_T *skip, // skip expression |
14962 | int flags, // SP_SETPCMARK and other SP_ values |
14963 | pos_T *match_pos, |
14964 | linenr_T lnum_stop, // stop at this line if not zero |
14965 | long time_limit // stop after this many msec |
14966 | ) |
14967 | { |
14968 | char_u *save_cpo; |
14969 | char_u *pat, *pat2 = NULL, *pat3 = NULL; |
14970 | long retval = 0; |
14971 | pos_T pos; |
14972 | pos_T firstpos; |
14973 | pos_T foundpos; |
14974 | pos_T save_cursor; |
14975 | pos_T save_pos; |
14976 | int n; |
14977 | int nest = 1; |
14978 | bool use_skip = false; |
14979 | int options = SEARCH_KEEP; |
14980 | proftime_T tm; |
14981 | size_t pat2_len; |
14982 | size_t pat3_len; |
14983 | |
14984 | /* Make 'cpoptions' empty, the 'l' flag should not be used here. */ |
14985 | save_cpo = p_cpo; |
14986 | p_cpo = empty_option; |
14987 | |
14988 | /* Set the time limit, if there is one. */ |
14989 | tm = profile_setlimit(time_limit); |
14990 | |
14991 | // Make two search patterns: start/end (pat2, for in nested pairs) and |
14992 | // start/middle/end (pat3, for the top pair). |
14993 | pat2_len = STRLEN(spat) + STRLEN(epat) + 17; |
14994 | pat2 = xmalloc(pat2_len); |
14995 | pat3_len = STRLEN(spat) + STRLEN(mpat) + STRLEN(epat) + 25; |
14996 | pat3 = xmalloc(pat3_len); |
14997 | snprintf((char *)pat2, pat2_len, "\\m\\(%s\\m\\)\\|\\(%s\\m\\)" , spat, epat); |
14998 | if (*mpat == NUL) { |
14999 | STRCPY(pat3, pat2); |
15000 | } else { |
15001 | snprintf((char *)pat3, pat3_len, |
15002 | "\\m\\(%s\\m\\)\\|\\(%s\\m\\)\\|\\(%s\\m\\)" , spat, epat, mpat); |
15003 | } |
15004 | if (flags & SP_START) { |
15005 | options |= SEARCH_START; |
15006 | } |
15007 | |
15008 | if (skip != NULL) { |
15009 | // Empty string means to not use the skip expression. |
15010 | if (skip->v_type == VAR_STRING || skip->v_type == VAR_FUNC) { |
15011 | use_skip = skip->vval.v_string != NULL && *skip->vval.v_string != NUL; |
15012 | } |
15013 | } |
15014 | |
15015 | save_cursor = curwin->w_cursor; |
15016 | pos = curwin->w_cursor; |
15017 | clearpos(&firstpos); |
15018 | clearpos(&foundpos); |
15019 | pat = pat3; |
15020 | for (;; ) { |
15021 | n = searchit(curwin, curbuf, &pos, NULL, dir, pat, 1L, |
15022 | options, RE_SEARCH, lnum_stop, &tm, NULL); |
15023 | if (n == FAIL || (firstpos.lnum != 0 && equalpos(pos, firstpos))) { |
15024 | // didn't find it or found the first match again: FAIL |
15025 | break; |
15026 | } |
15027 | |
15028 | if (firstpos.lnum == 0) |
15029 | firstpos = pos; |
15030 | if (equalpos(pos, foundpos)) { |
15031 | /* Found the same position again. Can happen with a pattern that |
15032 | * has "\zs" at the end and searching backwards. Advance one |
15033 | * character and try again. */ |
15034 | if (dir == BACKWARD) |
15035 | decl(&pos); |
15036 | else |
15037 | incl(&pos); |
15038 | } |
15039 | foundpos = pos; |
15040 | |
15041 | /* clear the start flag to avoid getting stuck here */ |
15042 | options &= ~SEARCH_START; |
15043 | |
15044 | // If the skip pattern matches, ignore this match. |
15045 | if (use_skip) { |
15046 | save_pos = curwin->w_cursor; |
15047 | curwin->w_cursor = pos; |
15048 | bool err = false; |
15049 | const bool r = eval_expr_to_bool(skip, &err); |
15050 | curwin->w_cursor = save_pos; |
15051 | if (err) { |
15052 | /* Evaluating {skip} caused an error, break here. */ |
15053 | curwin->w_cursor = save_cursor; |
15054 | retval = -1; |
15055 | break; |
15056 | } |
15057 | if (r) |
15058 | continue; |
15059 | } |
15060 | |
15061 | if ((dir == BACKWARD && n == 3) || (dir == FORWARD && n == 2)) { |
15062 | /* Found end when searching backwards or start when searching |
15063 | * forward: nested pair. */ |
15064 | ++nest; |
15065 | pat = pat2; /* nested, don't search for middle */ |
15066 | } else { |
15067 | /* Found end when searching forward or start when searching |
15068 | * backward: end of (nested) pair; or found middle in outer pair. */ |
15069 | if (--nest == 1) |
15070 | pat = pat3; /* outer level, search for middle */ |
15071 | } |
15072 | |
15073 | if (nest == 0) { |
15074 | /* Found the match: return matchcount or line number. */ |
15075 | if (flags & SP_RETCOUNT) |
15076 | ++retval; |
15077 | else |
15078 | retval = pos.lnum; |
15079 | if (flags & SP_SETPCMARK) |
15080 | setpcmark(); |
15081 | curwin->w_cursor = pos; |
15082 | if (!(flags & SP_REPEAT)) |
15083 | break; |
15084 | nest = 1; /* search for next unmatched */ |
15085 | } |
15086 | } |
15087 | |
15088 | if (match_pos != NULL) { |
15089 | /* Store the match cursor position */ |
15090 | match_pos->lnum = curwin->w_cursor.lnum; |
15091 | match_pos->col = curwin->w_cursor.col + 1; |
15092 | } |
15093 | |
15094 | /* If 'n' flag is used or search failed: restore cursor position. */ |
15095 | if ((flags & SP_NOMOVE) || retval == 0) |
15096 | curwin->w_cursor = save_cursor; |
15097 | |
15098 | xfree(pat2); |
15099 | xfree(pat3); |
15100 | if (p_cpo == empty_option) |
15101 | p_cpo = save_cpo; |
15102 | else |
15103 | /* Darn, evaluating the {skip} expression changed the value. */ |
15104 | free_string_option(save_cpo); |
15105 | |
15106 | return retval; |
15107 | } |
15108 | |
15109 | /* |
15110 | * "searchpos()" function |
15111 | */ |
15112 | static void f_searchpos(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
15113 | { |
15114 | pos_T match_pos; |
15115 | int flags = 0; |
15116 | |
15117 | const int n = search_cmn(argvars, &match_pos, &flags); |
15118 | |
15119 | tv_list_alloc_ret(rettv, 2 + (!!(flags & SP_SUBPAT))); |
15120 | |
15121 | const int lnum = (n > 0 ? match_pos.lnum : 0); |
15122 | const int col = (n > 0 ? match_pos.col : 0); |
15123 | |
15124 | tv_list_append_number(rettv->vval.v_list, (varnumber_T)lnum); |
15125 | tv_list_append_number(rettv->vval.v_list, (varnumber_T)col); |
15126 | if (flags & SP_SUBPAT) { |
15127 | tv_list_append_number(rettv->vval.v_list, (varnumber_T)n); |
15128 | } |
15129 | } |
15130 | |
15131 | /// "serverlist()" function |
15132 | static void f_serverlist(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
15133 | { |
15134 | size_t n; |
15135 | char **addrs = server_address_list(&n); |
15136 | |
15137 | // Copy addrs into a linked list. |
15138 | list_T *const l = tv_list_alloc_ret(rettv, n); |
15139 | for (size_t i = 0; i < n; i++) { |
15140 | tv_list_append_allocated_string(l, addrs[i]); |
15141 | } |
15142 | xfree(addrs); |
15143 | } |
15144 | |
15145 | /// "serverstart()" function |
15146 | static void f_serverstart(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
15147 | { |
15148 | rettv->v_type = VAR_STRING; |
15149 | rettv->vval.v_string = NULL; // Address of the new server |
15150 | |
15151 | if (check_restricted() || check_secure()) { |
15152 | return; |
15153 | } |
15154 | |
15155 | char *address; |
15156 | // If the user supplied an address, use it, otherwise use a temp. |
15157 | if (argvars[0].v_type != VAR_UNKNOWN) { |
15158 | if (argvars[0].v_type != VAR_STRING) { |
15159 | EMSG(_(e_invarg)); |
15160 | return; |
15161 | } else { |
15162 | address = xstrdup(tv_get_string(argvars)); |
15163 | } |
15164 | } else { |
15165 | address = server_address_new(); |
15166 | } |
15167 | |
15168 | int result = server_start(address); |
15169 | xfree(address); |
15170 | |
15171 | if (result != 0) { |
15172 | EMSG2("Failed to start server: %s" , |
15173 | result > 0 ? "Unknown system error" : uv_strerror(result)); |
15174 | return; |
15175 | } |
15176 | |
15177 | // Since it's possible server_start adjusted the given {address} (e.g., |
15178 | // "localhost:" will now have a port), return the final value to the user. |
15179 | size_t n; |
15180 | char **addrs = server_address_list(&n); |
15181 | rettv->vval.v_string = (char_u *)addrs[n - 1]; |
15182 | |
15183 | n--; |
15184 | for (size_t i = 0; i < n; i++) { |
15185 | xfree(addrs[i]); |
15186 | } |
15187 | xfree(addrs); |
15188 | } |
15189 | |
15190 | /// "serverstop()" function |
15191 | static void f_serverstop(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
15192 | { |
15193 | if (check_restricted() || check_secure()) { |
15194 | return; |
15195 | } |
15196 | |
15197 | if (argvars[0].v_type != VAR_STRING) { |
15198 | EMSG(_(e_invarg)); |
15199 | return; |
15200 | } |
15201 | |
15202 | rettv->v_type = VAR_NUMBER; |
15203 | rettv->vval.v_number = 0; |
15204 | if (argvars[0].vval.v_string) { |
15205 | bool rv = server_stop((char *)argvars[0].vval.v_string); |
15206 | rettv->vval.v_number = (rv ? 1 : 0); |
15207 | } |
15208 | } |
15209 | |
15210 | /// Set line or list of lines in buffer "buf". |
15211 | static void set_buffer_lines(buf_T *buf, linenr_T lnum_arg, bool append, |
15212 | const typval_T *lines, typval_T *rettv) |
15213 | FUNC_ATTR_NONNULL_ARG(4, 5) |
15214 | { |
15215 | linenr_T lnum = lnum_arg + (append ? 1 : 0); |
15216 | const char *line = NULL; |
15217 | list_T *l = NULL; |
15218 | listitem_T *li = NULL; |
15219 | long added = 0; |
15220 | linenr_T append_lnum; |
15221 | buf_T *curbuf_save = NULL; |
15222 | win_T *curwin_save = NULL; |
15223 | const bool is_curbuf = buf == curbuf; |
15224 | |
15225 | // When using the current buffer ml_mfp will be set if needed. Useful when |
15226 | // setline() is used on startup. For other buffers the buffer must be |
15227 | // loaded. |
15228 | if (buf == NULL || (!is_curbuf && buf->b_ml.ml_mfp == NULL) || lnum < 1) { |
15229 | rettv->vval.v_number = 1; // FAIL |
15230 | return; |
15231 | } |
15232 | |
15233 | if (!is_curbuf) { |
15234 | curbuf_save = curbuf; |
15235 | curwin_save = curwin; |
15236 | curbuf = buf; |
15237 | find_win_for_curbuf(); |
15238 | } |
15239 | |
15240 | if (append) { |
15241 | // appendbufline() uses the line number below which we insert |
15242 | append_lnum = lnum - 1; |
15243 | } else { |
15244 | // setbufline() uses the line number above which we insert, we only |
15245 | // append if it's below the last line |
15246 | append_lnum = curbuf->b_ml.ml_line_count; |
15247 | } |
15248 | |
15249 | if (lines->v_type == VAR_LIST) { |
15250 | l = lines->vval.v_list; |
15251 | li = tv_list_first(l); |
15252 | } else { |
15253 | line = tv_get_string_chk(lines); |
15254 | } |
15255 | |
15256 | // Default result is zero == OK. |
15257 | for (;; ) { |
15258 | if (lines->v_type == VAR_LIST) { |
15259 | // List argument, get next string. |
15260 | if (li == NULL) { |
15261 | break; |
15262 | } |
15263 | line = tv_get_string_chk(TV_LIST_ITEM_TV(li)); |
15264 | li = TV_LIST_ITEM_NEXT(l, li); |
15265 | } |
15266 | |
15267 | rettv->vval.v_number = 1; // FAIL |
15268 | if (line == NULL || lnum > curbuf->b_ml.ml_line_count + 1) { |
15269 | break; |
15270 | } |
15271 | |
15272 | // When coming here from Insert mode, sync undo, so that this can be |
15273 | // undone separately from what was previously inserted. |
15274 | if (u_sync_once == 2) { |
15275 | u_sync_once = 1; // notify that u_sync() was called |
15276 | u_sync(true); |
15277 | } |
15278 | |
15279 | if (!append && lnum <= curbuf->b_ml.ml_line_count) { |
15280 | // Existing line, replace it. |
15281 | if (u_savesub(lnum) == OK |
15282 | && ml_replace(lnum, (char_u *)line, true) == OK) { |
15283 | changed_bytes(lnum, 0); |
15284 | if (is_curbuf && lnum == curwin->w_cursor.lnum) { |
15285 | check_cursor_col(); |
15286 | } |
15287 | rettv->vval.v_number = 0; // OK |
15288 | } |
15289 | } else if (added > 0 || u_save(lnum - 1, lnum) == OK) { |
15290 | // append the line. |
15291 | added++; |
15292 | if (ml_append(lnum - 1, (char_u *)line, 0, false) == OK) { |
15293 | rettv->vval.v_number = 0; // OK |
15294 | } |
15295 | } |
15296 | |
15297 | if (l == NULL) { // only one string argument |
15298 | break; |
15299 | } |
15300 | lnum++; |
15301 | } |
15302 | |
15303 | if (added > 0) { |
15304 | appended_lines_mark(append_lnum, added); |
15305 | |
15306 | // Only adjust the cursor for buffers other than the current, unless it |
15307 | // is the current window. For curbuf and other windows it has been done |
15308 | // in mark_adjust_internal(). |
15309 | FOR_ALL_TAB_WINDOWS(tp, wp) { |
15310 | if (wp->w_buffer == buf |
15311 | && (wp->w_buffer != curbuf || wp == curwin) |
15312 | && wp->w_cursor.lnum > append_lnum) { |
15313 | wp->w_cursor.lnum += added; |
15314 | } |
15315 | } |
15316 | check_cursor_col(); |
15317 | update_topline(); |
15318 | } |
15319 | |
15320 | if (!is_curbuf) { |
15321 | curbuf = curbuf_save; |
15322 | curwin = curwin_save; |
15323 | } |
15324 | } |
15325 | |
15326 | /// "setbufline()" function |
15327 | static void f_setbufline(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
15328 | { |
15329 | linenr_T lnum; |
15330 | buf_T *buf; |
15331 | |
15332 | buf = tv_get_buf(&argvars[0], false); |
15333 | if (buf == NULL) { |
15334 | rettv->vval.v_number = 1; // FAIL |
15335 | } else { |
15336 | lnum = tv_get_lnum_buf(&argvars[1], buf); |
15337 | set_buffer_lines(buf, lnum, false, &argvars[2], rettv); |
15338 | } |
15339 | } |
15340 | |
15341 | /* |
15342 | * "setbufvar()" function |
15343 | */ |
15344 | static void f_setbufvar(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
15345 | { |
15346 | if (check_restricted() |
15347 | || check_secure() |
15348 | || !tv_check_str_or_nr(&argvars[0])) { |
15349 | return; |
15350 | } |
15351 | const char *varname = tv_get_string_chk(&argvars[1]); |
15352 | buf_T *const buf = tv_get_buf(&argvars[0], false); |
15353 | typval_T *varp = &argvars[2]; |
15354 | |
15355 | if (buf != NULL && varname != NULL) { |
15356 | if (*varname == '&') { |
15357 | long numval; |
15358 | bool error = false; |
15359 | aco_save_T aco; |
15360 | |
15361 | // set curbuf to be our buf, temporarily |
15362 | aucmd_prepbuf(&aco, buf); |
15363 | |
15364 | varname++; |
15365 | numval = tv_get_number_chk(varp, &error); |
15366 | char nbuf[NUMBUFLEN]; |
15367 | const char *const strval = tv_get_string_buf_chk(varp, nbuf); |
15368 | if (!error && strval != NULL) { |
15369 | set_option_value(varname, numval, strval, OPT_LOCAL); |
15370 | } |
15371 | |
15372 | // reset notion of buffer |
15373 | aucmd_restbuf(&aco); |
15374 | } else { |
15375 | buf_T *save_curbuf = curbuf; |
15376 | |
15377 | const size_t varname_len = STRLEN(varname); |
15378 | char *const bufvarname = xmalloc(varname_len + 3); |
15379 | curbuf = buf; |
15380 | memcpy(bufvarname, "b:" , 2); |
15381 | memcpy(bufvarname + 2, varname, varname_len + 1); |
15382 | set_var(bufvarname, varname_len + 2, varp, true); |
15383 | xfree(bufvarname); |
15384 | curbuf = save_curbuf; |
15385 | } |
15386 | } |
15387 | } |
15388 | |
15389 | static void f_setcharsearch(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
15390 | { |
15391 | dict_T *d; |
15392 | dictitem_T *di; |
15393 | |
15394 | if (argvars[0].v_type != VAR_DICT) { |
15395 | EMSG(_(e_dictreq)); |
15396 | return; |
15397 | } |
15398 | |
15399 | if ((d = argvars[0].vval.v_dict) != NULL) { |
15400 | char_u *const csearch = (char_u *)tv_dict_get_string(d, "char" , false); |
15401 | if (csearch != NULL) { |
15402 | if (enc_utf8) { |
15403 | int pcc[MAX_MCO]; |
15404 | int c = utfc_ptr2char(csearch, pcc); |
15405 | set_last_csearch(c, csearch, utfc_ptr2len(csearch)); |
15406 | } |
15407 | else |
15408 | set_last_csearch(PTR2CHAR(csearch), |
15409 | csearch, MB_PTR2LEN(csearch)); |
15410 | } |
15411 | |
15412 | di = tv_dict_find(d, S_LEN("forward" )); |
15413 | if (di != NULL) { |
15414 | set_csearch_direction(tv_get_number(&di->di_tv) ? FORWARD : BACKWARD); |
15415 | } |
15416 | |
15417 | di = tv_dict_find(d, S_LEN("until" )); |
15418 | if (di != NULL) { |
15419 | set_csearch_until(!!tv_get_number(&di->di_tv)); |
15420 | } |
15421 | } |
15422 | } |
15423 | |
15424 | /* |
15425 | * "setcmdpos()" function |
15426 | */ |
15427 | static void f_setcmdpos(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
15428 | { |
15429 | const int pos = (int)tv_get_number(&argvars[0]) - 1; |
15430 | |
15431 | if (pos >= 0) { |
15432 | rettv->vval.v_number = set_cmdline_pos(pos); |
15433 | } |
15434 | } |
15435 | |
15436 | /// "setenv()" function |
15437 | static void f_setenv(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
15438 | { |
15439 | char namebuf[NUMBUFLEN]; |
15440 | char valbuf[NUMBUFLEN]; |
15441 | const char *name = tv_get_string_buf(&argvars[0], namebuf); |
15442 | |
15443 | if (argvars[1].v_type == VAR_SPECIAL |
15444 | && argvars[1].vval.v_number == kSpecialVarNull) { |
15445 | os_unsetenv(name); |
15446 | } else { |
15447 | os_setenv(name, tv_get_string_buf(&argvars[1], valbuf), 1); |
15448 | } |
15449 | } |
15450 | |
15451 | /// "setfperm({fname}, {mode})" function |
15452 | static void f_setfperm(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
15453 | { |
15454 | rettv->vval.v_number = 0; |
15455 | |
15456 | const char *const fname = tv_get_string_chk(&argvars[0]); |
15457 | if (fname == NULL) { |
15458 | return; |
15459 | } |
15460 | |
15461 | char modebuf[NUMBUFLEN]; |
15462 | const char *const mode_str = tv_get_string_buf_chk(&argvars[1], modebuf); |
15463 | if (mode_str == NULL) { |
15464 | return; |
15465 | } |
15466 | if (strlen(mode_str) != 9) { |
15467 | EMSG2(_(e_invarg2), mode_str); |
15468 | return; |
15469 | } |
15470 | |
15471 | int mask = 1; |
15472 | int mode = 0; |
15473 | for (int i = 8; i >= 0; i--) { |
15474 | if (mode_str[i] != '-') { |
15475 | mode |= mask; |
15476 | } |
15477 | mask = mask << 1; |
15478 | } |
15479 | rettv->vval.v_number = os_setperm(fname, mode) == OK; |
15480 | } |
15481 | |
15482 | /* |
15483 | * "setline()" function |
15484 | */ |
15485 | static void f_setline(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
15486 | { |
15487 | linenr_T lnum = tv_get_lnum(&argvars[0]); |
15488 | set_buffer_lines(curbuf, lnum, false, &argvars[1], rettv); |
15489 | } |
15490 | |
15491 | /// Create quickfix/location list from VimL values |
15492 | /// |
15493 | /// Used by `setqflist()` and `setloclist()` functions. Accepts invalid |
15494 | /// list_arg, action_arg and what_arg arguments in which case errors out, |
15495 | /// including VAR_UNKNOWN parameters. |
15496 | /// |
15497 | /// @param[in,out] wp Window to create location list for. May be NULL in |
15498 | /// which case quickfix list will be created. |
15499 | /// @param[in] list_arg Quickfix list contents. |
15500 | /// @param[in] action_arg Action to perform: append to an existing list, |
15501 | /// replace its content or create a new one. |
15502 | /// @param[in] title_arg New list title. Defaults to caller function name. |
15503 | /// @param[out] rettv Return value: 0 in case of success, -1 otherwise. |
15504 | static void set_qf_ll_list(win_T *wp, typval_T *args, typval_T *rettv) |
15505 | FUNC_ATTR_NONNULL_ARG(2, 3) |
15506 | { |
15507 | static char *e_invact = N_("E927: Invalid action: '%s'" ); |
15508 | const char *title = NULL; |
15509 | int action = ' '; |
15510 | static int recursive = 0; |
15511 | rettv->vval.v_number = -1; |
15512 | dict_T *d = NULL; |
15513 | |
15514 | typval_T *list_arg = &args[0]; |
15515 | if (list_arg->v_type != VAR_LIST) { |
15516 | EMSG(_(e_listreq)); |
15517 | return; |
15518 | } else if (recursive != 0) { |
15519 | EMSG(_(e_au_recursive)); |
15520 | return; |
15521 | } |
15522 | |
15523 | typval_T *action_arg = &args[1]; |
15524 | if (action_arg->v_type == VAR_UNKNOWN) { |
15525 | // Option argument was not given. |
15526 | goto skip_args; |
15527 | } else if (action_arg->v_type != VAR_STRING) { |
15528 | EMSG(_(e_stringreq)); |
15529 | return; |
15530 | } |
15531 | const char *const act = tv_get_string_chk(action_arg); |
15532 | if ((*act == 'a' || *act == 'r' || *act == ' ' || *act == 'f') |
15533 | && act[1] == NUL) { |
15534 | action = *act; |
15535 | } else { |
15536 | EMSG2(_(e_invact), act); |
15537 | return; |
15538 | } |
15539 | |
15540 | typval_T *title_arg = &args[2]; |
15541 | if (title_arg->v_type == VAR_UNKNOWN) { |
15542 | // Option argument was not given. |
15543 | goto skip_args; |
15544 | } else if (title_arg->v_type == VAR_STRING) { |
15545 | title = tv_get_string_chk(title_arg); |
15546 | if (!title) { |
15547 | // Type error. Error already printed by tv_get_string_chk(). |
15548 | return; |
15549 | } |
15550 | } else if (title_arg->v_type == VAR_DICT) { |
15551 | d = title_arg->vval.v_dict; |
15552 | } else { |
15553 | EMSG(_(e_dictreq)); |
15554 | return; |
15555 | } |
15556 | |
15557 | skip_args: |
15558 | if (!title) { |
15559 | title = (wp ? ":setloclist()" : ":setqflist()" ); |
15560 | } |
15561 | |
15562 | recursive++; |
15563 | list_T *const l = list_arg->vval.v_list; |
15564 | if (set_errorlist(wp, l, action, (char_u *)title, d) == OK) { |
15565 | rettv->vval.v_number = 0; |
15566 | } |
15567 | recursive--; |
15568 | } |
15569 | |
15570 | /* |
15571 | * "setloclist()" function |
15572 | */ |
15573 | static void f_setloclist(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
15574 | { |
15575 | win_T *win; |
15576 | |
15577 | rettv->vval.v_number = -1; |
15578 | |
15579 | win = find_win_by_nr_or_id(&argvars[0]); |
15580 | if (win != NULL) { |
15581 | set_qf_ll_list(win, &argvars[1], rettv); |
15582 | } |
15583 | } |
15584 | |
15585 | /* |
15586 | * "setmatches()" function |
15587 | */ |
15588 | static void f_setmatches(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
15589 | { |
15590 | dict_T *d; |
15591 | list_T *s = NULL; |
15592 | |
15593 | rettv->vval.v_number = -1; |
15594 | if (argvars[0].v_type != VAR_LIST) { |
15595 | EMSG(_(e_listreq)); |
15596 | return; |
15597 | } |
15598 | list_T *const l = argvars[0].vval.v_list; |
15599 | // To some extent make sure that we are dealing with a list from |
15600 | // "getmatches()". |
15601 | int li_idx = 0; |
15602 | TV_LIST_ITER_CONST(l, li, { |
15603 | if (TV_LIST_ITEM_TV(li)->v_type != VAR_DICT |
15604 | || (d = TV_LIST_ITEM_TV(li)->vval.v_dict) == NULL) { |
15605 | emsgf(_("E474: List item %d is either not a dictionary " |
15606 | "or an empty one" ), li_idx); |
15607 | return; |
15608 | } |
15609 | if (!(tv_dict_find(d, S_LEN("group" )) != NULL |
15610 | && (tv_dict_find(d, S_LEN("pattern" )) != NULL |
15611 | || tv_dict_find(d, S_LEN("pos1" )) != NULL) |
15612 | && tv_dict_find(d, S_LEN("priority" )) != NULL |
15613 | && tv_dict_find(d, S_LEN("id" )) != NULL)) { |
15614 | emsgf(_("E474: List item %d is missing one of the required keys" ), |
15615 | li_idx); |
15616 | return; |
15617 | } |
15618 | li_idx++; |
15619 | }); |
15620 | |
15621 | clear_matches(curwin); |
15622 | bool match_add_failed = false; |
15623 | TV_LIST_ITER_CONST(l, li, { |
15624 | int i = 0; |
15625 | |
15626 | d = TV_LIST_ITEM_TV(li)->vval.v_dict; |
15627 | dictitem_T *const di = tv_dict_find(d, S_LEN("pattern" )); |
15628 | if (di == NULL) { |
15629 | if (s == NULL) { |
15630 | s = tv_list_alloc(9); |
15631 | } |
15632 | |
15633 | // match from matchaddpos() |
15634 | for (i = 1; i < 9; i++) { |
15635 | char buf[30]; // use 30 to avoid compiler warning |
15636 | snprintf(buf, sizeof(buf), "pos%d" , i); |
15637 | dictitem_T *const pos_di = tv_dict_find(d, buf, -1); |
15638 | if (pos_di != NULL) { |
15639 | if (pos_di->di_tv.v_type != VAR_LIST) { |
15640 | return; |
15641 | } |
15642 | |
15643 | tv_list_append_tv(s, &pos_di->di_tv); |
15644 | tv_list_ref(s); |
15645 | } else { |
15646 | break; |
15647 | } |
15648 | } |
15649 | } |
15650 | |
15651 | // Note: there are three number buffers involved: |
15652 | // - group_buf below. |
15653 | // - numbuf in tv_dict_get_string(). |
15654 | // - mybuf in tv_get_string(). |
15655 | // |
15656 | // If you change this code make sure that buffers will not get |
15657 | // accidentally reused. |
15658 | char group_buf[NUMBUFLEN]; |
15659 | const char *const group = tv_dict_get_string_buf(d, "group" , group_buf); |
15660 | const int priority = (int)tv_dict_get_number(d, "priority" ); |
15661 | const int id = (int)tv_dict_get_number(d, "id" ); |
15662 | dictitem_T *const conceal_di = tv_dict_find(d, S_LEN("conceal" )); |
15663 | const char *const conceal = (conceal_di != NULL |
15664 | ? tv_get_string(&conceal_di->di_tv) |
15665 | : NULL); |
15666 | if (i == 0) { |
15667 | if (match_add(curwin, group, |
15668 | tv_dict_get_string(d, "pattern" , false), |
15669 | priority, id, NULL, conceal) != id) { |
15670 | match_add_failed = true; |
15671 | } |
15672 | } else { |
15673 | if (match_add(curwin, group, NULL, priority, id, s, conceal) != id) { |
15674 | match_add_failed = true; |
15675 | } |
15676 | tv_list_unref(s); |
15677 | s = NULL; |
15678 | } |
15679 | }); |
15680 | if (!match_add_failed) { |
15681 | rettv->vval.v_number = 0; |
15682 | } |
15683 | } |
15684 | |
15685 | /* |
15686 | * "setpos()" function |
15687 | */ |
15688 | static void f_setpos(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
15689 | { |
15690 | pos_T pos; |
15691 | int fnum; |
15692 | colnr_T curswant = -1; |
15693 | |
15694 | rettv->vval.v_number = -1; |
15695 | const char *const name = tv_get_string_chk(argvars); |
15696 | if (name != NULL) { |
15697 | if (list2fpos(&argvars[1], &pos, &fnum, &curswant) == OK) { |
15698 | if (--pos.col < 0) { |
15699 | pos.col = 0; |
15700 | } |
15701 | if (name[0] == '.' && name[1] == NUL) { |
15702 | // set cursor; "fnum" is ignored |
15703 | curwin->w_cursor = pos; |
15704 | if (curswant >= 0) { |
15705 | curwin->w_curswant = curswant - 1; |
15706 | curwin->w_set_curswant = false; |
15707 | } |
15708 | check_cursor(); |
15709 | rettv->vval.v_number = 0; |
15710 | } else if (name[0] == '\'' && name[1] != NUL && name[2] == NUL) { |
15711 | // set mark |
15712 | if (setmark_pos((uint8_t)name[1], &pos, fnum) == OK) { |
15713 | rettv->vval.v_number = 0; |
15714 | } |
15715 | } else { |
15716 | EMSG(_(e_invarg)); |
15717 | } |
15718 | } |
15719 | } |
15720 | } |
15721 | |
15722 | /* |
15723 | * "setqflist()" function |
15724 | */ |
15725 | static void f_setqflist(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
15726 | { |
15727 | set_qf_ll_list(NULL, argvars, rettv); |
15728 | } |
15729 | |
15730 | /* |
15731 | * "setreg()" function |
15732 | */ |
15733 | static void f_setreg(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
15734 | { |
15735 | int regname; |
15736 | bool append = false; |
15737 | MotionType yank_type; |
15738 | long block_len; |
15739 | |
15740 | block_len = -1; |
15741 | yank_type = kMTUnknown; |
15742 | |
15743 | rettv->vval.v_number = 1; // FAIL is default. |
15744 | |
15745 | const char *const strregname = tv_get_string_chk(argvars); |
15746 | if (strregname == NULL) { |
15747 | return; // Type error; errmsg already given. |
15748 | } |
15749 | regname = (uint8_t)(*strregname); |
15750 | if (regname == 0 || regname == '@') { |
15751 | regname = '"'; |
15752 | } |
15753 | |
15754 | bool set_unnamed = false; |
15755 | if (argvars[2].v_type != VAR_UNKNOWN) { |
15756 | const char *stropt = tv_get_string_chk(&argvars[2]); |
15757 | if (stropt == NULL) { |
15758 | return; // Type error. |
15759 | } |
15760 | for (; *stropt != NUL; stropt++) { |
15761 | switch (*stropt) { |
15762 | case 'a': case 'A': { // append |
15763 | append = true; |
15764 | break; |
15765 | } |
15766 | case 'v': case 'c': { // character-wise selection |
15767 | yank_type = kMTCharWise; |
15768 | break; |
15769 | } |
15770 | case 'V': case 'l': { // line-wise selection |
15771 | yank_type = kMTLineWise; |
15772 | break; |
15773 | } |
15774 | case 'b': case Ctrl_V: { // block-wise selection |
15775 | yank_type = kMTBlockWise; |
15776 | if (ascii_isdigit(stropt[1])) { |
15777 | stropt++; |
15778 | block_len = getdigits_long((char_u **)&stropt, true, 0) - 1; |
15779 | stropt--; |
15780 | } |
15781 | break; |
15782 | } |
15783 | case 'u': case '"': { // unnamed register |
15784 | set_unnamed = true; |
15785 | break; |
15786 | } |
15787 | } |
15788 | } |
15789 | } |
15790 | |
15791 | if (argvars[1].v_type == VAR_LIST) { |
15792 | list_T *ll = argvars[1].vval.v_list; |
15793 | // If the list is NULL handle like an empty list. |
15794 | const int len = tv_list_len(ll); |
15795 | |
15796 | // First half: use for pointers to result lines; second half: use for |
15797 | // pointers to allocated copies. |
15798 | char **lstval = xmalloc(sizeof(char *) * ((len + 1) * 2)); |
15799 | const char **curval = (const char **)lstval; |
15800 | char **allocval = lstval + len + 2; |
15801 | char **curallocval = allocval; |
15802 | |
15803 | TV_LIST_ITER_CONST(ll, li, { |
15804 | char buf[NUMBUFLEN]; |
15805 | *curval = tv_get_string_buf_chk(TV_LIST_ITEM_TV(li), buf); |
15806 | if (*curval == NULL) { |
15807 | goto free_lstval; |
15808 | } |
15809 | if (*curval == buf) { |
15810 | // Need to make a copy, |
15811 | // next tv_get_string_buf_chk() will overwrite the string. |
15812 | *curallocval = xstrdup(*curval); |
15813 | *curval = *curallocval; |
15814 | curallocval++; |
15815 | } |
15816 | curval++; |
15817 | }); |
15818 | *curval++ = NULL; |
15819 | |
15820 | write_reg_contents_lst(regname, (char_u **)lstval, append, yank_type, |
15821 | block_len); |
15822 | |
15823 | free_lstval: |
15824 | while (curallocval > allocval) { |
15825 | xfree(*--curallocval); |
15826 | } |
15827 | xfree(lstval); |
15828 | } else { |
15829 | const char *strval = tv_get_string_chk(&argvars[1]); |
15830 | if (strval == NULL) { |
15831 | return; |
15832 | } |
15833 | write_reg_contents_ex(regname, (const char_u *)strval, STRLEN(strval), |
15834 | append, yank_type, block_len); |
15835 | } |
15836 | rettv->vval.v_number = 0; |
15837 | |
15838 | if (set_unnamed) { |
15839 | // Discard the result. We already handle the error case. |
15840 | if (op_reg_set_previous(regname)) { } |
15841 | } |
15842 | } |
15843 | |
15844 | /* |
15845 | * "settabvar()" function |
15846 | */ |
15847 | static void f_settabvar(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
15848 | { |
15849 | rettv->vval.v_number = 0; |
15850 | |
15851 | if (check_restricted() || check_secure()) { |
15852 | return; |
15853 | } |
15854 | |
15855 | tabpage_T *const tp = find_tabpage((int)tv_get_number_chk(&argvars[0], NULL)); |
15856 | const char *const varname = tv_get_string_chk(&argvars[1]); |
15857 | typval_T *const varp = &argvars[2]; |
15858 | |
15859 | if (varname != NULL && tp != NULL) { |
15860 | tabpage_T *const save_curtab = curtab; |
15861 | goto_tabpage_tp(tp, false, false); |
15862 | |
15863 | const size_t varname_len = strlen(varname); |
15864 | char *const tabvarname = xmalloc(varname_len + 3); |
15865 | memcpy(tabvarname, "t:" , 2); |
15866 | memcpy(tabvarname + 2, varname, varname_len + 1); |
15867 | set_var(tabvarname, varname_len + 2, varp, true); |
15868 | xfree(tabvarname); |
15869 | |
15870 | // Restore current tabpage. |
15871 | if (valid_tabpage(save_curtab)) { |
15872 | goto_tabpage_tp(save_curtab, false, false); |
15873 | } |
15874 | } |
15875 | } |
15876 | |
15877 | /* |
15878 | * "settabwinvar()" function |
15879 | */ |
15880 | static void f_settabwinvar(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
15881 | { |
15882 | setwinvar(argvars, rettv, 1); |
15883 | } |
15884 | |
15885 | // "settagstack()" function |
15886 | static void f_settagstack(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
15887 | { |
15888 | static char *e_invact2 = N_("E962: Invalid action: '%s'" ); |
15889 | win_T *wp; |
15890 | dict_T *d; |
15891 | int action = 'r'; |
15892 | |
15893 | rettv->vval.v_number = -1; |
15894 | |
15895 | // first argument: window number or id |
15896 | wp = find_win_by_nr_or_id(&argvars[0]); |
15897 | if (wp == NULL) { |
15898 | return; |
15899 | } |
15900 | |
15901 | // second argument: dict with items to set in the tag stack |
15902 | if (argvars[1].v_type != VAR_DICT) { |
15903 | EMSG(_(e_dictreq)); |
15904 | return; |
15905 | } |
15906 | d = argvars[1].vval.v_dict; |
15907 | if (d == NULL) { |
15908 | return; |
15909 | } |
15910 | |
15911 | // third argument: action - 'a' for append and 'r' for replace. |
15912 | // default is to replace the stack. |
15913 | if (argvars[2].v_type == VAR_UNKNOWN) { |
15914 | action = 'r'; |
15915 | } else if (argvars[2].v_type == VAR_STRING) { |
15916 | const char *actstr; |
15917 | actstr = tv_get_string_chk(&argvars[2]); |
15918 | if (actstr == NULL) { |
15919 | return; |
15920 | } |
15921 | if ((*actstr == 'r' || *actstr == 'a') && actstr[1] == NUL) { |
15922 | action = *actstr; |
15923 | } else { |
15924 | EMSG2(_(e_invact2), actstr); |
15925 | return; |
15926 | } |
15927 | } else { |
15928 | EMSG(_(e_stringreq)); |
15929 | return; |
15930 | } |
15931 | |
15932 | if (set_tagstack(wp, d, action) == OK) { |
15933 | rettv->vval.v_number = 0; |
15934 | } else { |
15935 | EMSG(_(e_listreq)); |
15936 | } |
15937 | } |
15938 | |
15939 | /* |
15940 | * "setwinvar()" function |
15941 | */ |
15942 | static void f_setwinvar(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
15943 | { |
15944 | setwinvar(argvars, rettv, 0); |
15945 | } |
15946 | |
15947 | /* |
15948 | * "setwinvar()" and "settabwinvar()" functions |
15949 | */ |
15950 | |
15951 | static void setwinvar(typval_T *argvars, typval_T *rettv, int off) |
15952 | { |
15953 | if (check_secure()) { |
15954 | return; |
15955 | } |
15956 | |
15957 | tabpage_T *tp = NULL; |
15958 | if (off == 1) { |
15959 | tp = find_tabpage((int)tv_get_number_chk(&argvars[0], NULL)); |
15960 | } else { |
15961 | tp = curtab; |
15962 | } |
15963 | win_T *const win = find_win_by_nr(&argvars[off], tp); |
15964 | const char *varname = tv_get_string_chk(&argvars[off + 1]); |
15965 | typval_T *varp = &argvars[off + 2]; |
15966 | |
15967 | if (win != NULL && varname != NULL && varp != NULL) { |
15968 | win_T *save_curwin; |
15969 | tabpage_T *save_curtab; |
15970 | bool need_switch_win = tp != curtab || win != curwin; |
15971 | if (!need_switch_win |
15972 | || switch_win(&save_curwin, &save_curtab, win, tp, true) == OK) { |
15973 | if (*varname == '&') { |
15974 | long numval; |
15975 | bool error = false; |
15976 | |
15977 | varname++; |
15978 | numval = tv_get_number_chk(varp, &error); |
15979 | char nbuf[NUMBUFLEN]; |
15980 | const char *const strval = tv_get_string_buf_chk(varp, nbuf); |
15981 | if (!error && strval != NULL) { |
15982 | set_option_value(varname, numval, strval, OPT_LOCAL); |
15983 | } |
15984 | } else { |
15985 | const size_t varname_len = strlen(varname); |
15986 | char *const winvarname = xmalloc(varname_len + 3); |
15987 | memcpy(winvarname, "w:" , 2); |
15988 | memcpy(winvarname + 2, varname, varname_len + 1); |
15989 | set_var(winvarname, varname_len + 2, varp, true); |
15990 | xfree(winvarname); |
15991 | } |
15992 | } |
15993 | if (need_switch_win) { |
15994 | restore_win(save_curwin, save_curtab, true); |
15995 | } |
15996 | } |
15997 | } |
15998 | |
15999 | /// f_sha256 - sha256({string}) function |
16000 | static void f_sha256(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
16001 | { |
16002 | const char *p = tv_get_string(&argvars[0]); |
16003 | const char *hash = sha256_bytes((const uint8_t *)p, strlen(p) , NULL, 0); |
16004 | |
16005 | // make a copy of the hash (sha256_bytes returns a static buffer) |
16006 | rettv->vval.v_string = (char_u *)xstrdup(hash); |
16007 | rettv->v_type = VAR_STRING; |
16008 | } |
16009 | |
16010 | /* |
16011 | * "shellescape({string})" function |
16012 | */ |
16013 | static void f_shellescape(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
16014 | { |
16015 | const bool do_special = non_zero_arg(&argvars[1]); |
16016 | |
16017 | rettv->vval.v_string = vim_strsave_shellescape( |
16018 | (const char_u *)tv_get_string(&argvars[0]), do_special, do_special); |
16019 | rettv->v_type = VAR_STRING; |
16020 | } |
16021 | |
16022 | /* |
16023 | * shiftwidth() function |
16024 | */ |
16025 | static void f_shiftwidth(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
16026 | { |
16027 | rettv->vval.v_number = get_sw_value(curbuf); |
16028 | } |
16029 | |
16030 | /// "sign_define()" function |
16031 | static void f_sign_define(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
16032 | { |
16033 | const char *name; |
16034 | dict_T *dict; |
16035 | char *icon = NULL; |
16036 | char *linehl = NULL; |
16037 | char *text = NULL; |
16038 | char *texthl = NULL; |
16039 | char *numhl = NULL; |
16040 | |
16041 | rettv->vval.v_number = -1; |
16042 | |
16043 | name = tv_get_string_chk(&argvars[0]); |
16044 | if (name == NULL) { |
16045 | return; |
16046 | } |
16047 | |
16048 | if (argvars[1].v_type != VAR_UNKNOWN) { |
16049 | if (argvars[1].v_type != VAR_DICT) { |
16050 | EMSG(_(e_dictreq)); |
16051 | return; |
16052 | } |
16053 | |
16054 | // sign attributes |
16055 | dict = argvars[1].vval.v_dict; |
16056 | if (tv_dict_find(dict, "icon" , -1) != NULL) { |
16057 | icon = tv_dict_get_string(dict, "icon" , true); |
16058 | } |
16059 | if (tv_dict_find(dict, "linehl" , -1) != NULL) { |
16060 | linehl = tv_dict_get_string(dict, "linehl" , true); |
16061 | } |
16062 | if (tv_dict_find(dict, "text" , -1) != NULL) { |
16063 | text = tv_dict_get_string(dict, "text" , true); |
16064 | } |
16065 | if (tv_dict_find(dict, "texthl" , -1) != NULL) { |
16066 | texthl = tv_dict_get_string(dict, "texthl" , true); |
16067 | } |
16068 | if (tv_dict_find(dict, "numhl" , -1) != NULL) { |
16069 | numhl = tv_dict_get_string(dict, "numhl" , true); |
16070 | } |
16071 | } |
16072 | |
16073 | if (sign_define_by_name((char_u *)name, (char_u *)icon, (char_u *)linehl, |
16074 | (char_u *)text, (char_u *)texthl, (char_u *)numhl) |
16075 | == OK) { |
16076 | rettv->vval.v_number = 0; |
16077 | } |
16078 | |
16079 | xfree(icon); |
16080 | xfree(linehl); |
16081 | xfree(text); |
16082 | xfree(texthl); |
16083 | } |
16084 | |
16085 | /// "sign_getdefined()" function |
16086 | static void f_sign_getdefined(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
16087 | { |
16088 | const char *name = NULL; |
16089 | |
16090 | tv_list_alloc_ret(rettv, 0); |
16091 | |
16092 | if (argvars[0].v_type != VAR_UNKNOWN) { |
16093 | name = tv_get_string(&argvars[0]); |
16094 | } |
16095 | |
16096 | sign_getlist((const char_u *)name, rettv->vval.v_list); |
16097 | } |
16098 | |
16099 | /// "sign_getplaced()" function |
16100 | static void f_sign_getplaced(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
16101 | { |
16102 | buf_T *buf = NULL; |
16103 | dict_T *dict; |
16104 | dictitem_T *di; |
16105 | linenr_T lnum = 0; |
16106 | int sign_id = 0; |
16107 | const char *group = NULL; |
16108 | bool notanum = false; |
16109 | |
16110 | tv_list_alloc_ret(rettv, 0); |
16111 | |
16112 | if (argvars[0].v_type != VAR_UNKNOWN) { |
16113 | // get signs placed in the specified buffer |
16114 | buf = get_buf_arg(&argvars[0]); |
16115 | if (buf == NULL) { |
16116 | return; |
16117 | } |
16118 | |
16119 | if (argvars[1].v_type != VAR_UNKNOWN) { |
16120 | if (argvars[1].v_type != VAR_DICT |
16121 | || ((dict = argvars[1].vval.v_dict) == NULL)) { |
16122 | EMSG(_(e_dictreq)); |
16123 | return; |
16124 | } |
16125 | if ((di = tv_dict_find(dict, "lnum" , -1)) != NULL) { |
16126 | // get signs placed at this line |
16127 | lnum = (linenr_T)tv_get_number_chk(&di->di_tv, ¬anum); |
16128 | if (notanum) { |
16129 | return; |
16130 | } |
16131 | (void)lnum; |
16132 | lnum = tv_get_lnum(&di->di_tv); |
16133 | } |
16134 | if ((di = tv_dict_find(dict, "id" , -1)) != NULL) { |
16135 | // get sign placed with this identifier |
16136 | sign_id = (int)tv_get_number_chk(&di->di_tv, ¬anum); |
16137 | if (notanum) { |
16138 | return; |
16139 | } |
16140 | } |
16141 | if ((di = tv_dict_find(dict, "group" , -1)) != NULL) { |
16142 | group = tv_get_string_chk(&di->di_tv); |
16143 | if (group == NULL) { |
16144 | return; |
16145 | } |
16146 | if (*group == '\0') { // empty string means global group |
16147 | group = NULL; |
16148 | } |
16149 | } |
16150 | } |
16151 | } |
16152 | |
16153 | sign_get_placed(buf, lnum, sign_id, (const char_u *)group, |
16154 | rettv->vval.v_list); |
16155 | } |
16156 | |
16157 | /// "sign_jump()" function |
16158 | static void f_sign_jump(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
16159 | { |
16160 | int sign_id; |
16161 | char *sign_group = NULL; |
16162 | buf_T *buf; |
16163 | bool notanum = false; |
16164 | |
16165 | rettv->vval.v_number = -1; |
16166 | |
16167 | // Sign identifer |
16168 | sign_id = (int)tv_get_number_chk(&argvars[0], ¬anum); |
16169 | if (notanum) { |
16170 | return; |
16171 | } |
16172 | if (sign_id <= 0) { |
16173 | EMSG(_(e_invarg)); |
16174 | return; |
16175 | } |
16176 | |
16177 | // Sign group |
16178 | const char * sign_group_chk = tv_get_string_chk(&argvars[1]); |
16179 | if (sign_group_chk == NULL) { |
16180 | return; |
16181 | } |
16182 | if (sign_group_chk[0] == '\0') { |
16183 | sign_group = NULL; // global sign group |
16184 | } else { |
16185 | sign_group = xstrdup(sign_group_chk); |
16186 | } |
16187 | |
16188 | // Buffer to place the sign |
16189 | buf = get_buf_arg(&argvars[2]); |
16190 | if (buf == NULL) { |
16191 | goto cleanup; |
16192 | } |
16193 | |
16194 | rettv->vval.v_number = sign_jump(sign_id, (char_u *)sign_group, buf); |
16195 | |
16196 | cleanup: |
16197 | xfree(sign_group); |
16198 | } |
16199 | |
16200 | /// "sign_place()" function |
16201 | static void f_sign_place(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
16202 | { |
16203 | int sign_id; |
16204 | char_u *group = NULL; |
16205 | const char *sign_name; |
16206 | buf_T *buf; |
16207 | dict_T *dict; |
16208 | dictitem_T *di; |
16209 | linenr_T lnum = 0; |
16210 | int prio = SIGN_DEF_PRIO; |
16211 | bool notanum = false; |
16212 | |
16213 | rettv->vval.v_number = -1; |
16214 | |
16215 | // Sign identifer |
16216 | sign_id = (int)tv_get_number_chk(&argvars[0], ¬anum); |
16217 | if (notanum) { |
16218 | return; |
16219 | } |
16220 | if (sign_id < 0) { |
16221 | EMSG(_(e_invarg)); |
16222 | return; |
16223 | } |
16224 | |
16225 | // Sign group |
16226 | const char *group_chk = tv_get_string_chk(&argvars[1]); |
16227 | if (group_chk == NULL) { |
16228 | return; |
16229 | } |
16230 | if (group_chk[0] == '\0') { |
16231 | group = NULL; // global sign group |
16232 | } else { |
16233 | group = vim_strsave((const char_u *)group_chk); |
16234 | } |
16235 | |
16236 | // Sign name |
16237 | sign_name = tv_get_string_chk(&argvars[2]); |
16238 | if (sign_name == NULL) { |
16239 | goto cleanup; |
16240 | } |
16241 | |
16242 | // Buffer to place the sign |
16243 | buf = get_buf_arg(&argvars[3]); |
16244 | if (buf == NULL) { |
16245 | goto cleanup; |
16246 | } |
16247 | |
16248 | if (argvars[4].v_type != VAR_UNKNOWN) { |
16249 | if (argvars[4].v_type != VAR_DICT |
16250 | || ((dict = argvars[4].vval.v_dict) == NULL)) { |
16251 | EMSG(_(e_dictreq)); |
16252 | goto cleanup; |
16253 | } |
16254 | |
16255 | // Line number where the sign is to be placed |
16256 | if ((di = tv_dict_find(dict, "lnum" , -1)) != NULL) { |
16257 | lnum = (linenr_T)tv_get_number_chk(&di->di_tv, ¬anum); |
16258 | if (notanum) { |
16259 | goto cleanup; |
16260 | } |
16261 | (void)lnum; |
16262 | lnum = tv_get_lnum(&di->di_tv); |
16263 | } |
16264 | if ((di = tv_dict_find(dict, "priority" , -1)) != NULL) { |
16265 | // Sign priority |
16266 | prio = (int)tv_get_number_chk(&di->di_tv, ¬anum); |
16267 | if (notanum) { |
16268 | goto cleanup; |
16269 | } |
16270 | } |
16271 | } |
16272 | |
16273 | if (sign_place(&sign_id, group, (const char_u *)sign_name, buf, lnum, prio) |
16274 | == OK) { |
16275 | rettv->vval.v_number = sign_id; |
16276 | } |
16277 | |
16278 | cleanup: |
16279 | xfree(group); |
16280 | } |
16281 | |
16282 | /// "sign_undefine()" function |
16283 | static void f_sign_undefine(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
16284 | { |
16285 | const char *name; |
16286 | |
16287 | rettv->vval.v_number = -1; |
16288 | |
16289 | if (argvars[0].v_type == VAR_UNKNOWN) { |
16290 | // Free all the signs |
16291 | free_signs(); |
16292 | rettv->vval.v_number = 0; |
16293 | } else { |
16294 | // Free only the specified sign |
16295 | name = tv_get_string_chk(&argvars[0]); |
16296 | if (name == NULL) { |
16297 | return; |
16298 | } |
16299 | |
16300 | if (sign_undefine_by_name((const char_u *)name) == OK) { |
16301 | rettv->vval.v_number = 0; |
16302 | } |
16303 | } |
16304 | } |
16305 | |
16306 | /// "sign_unplace()" function |
16307 | static void f_sign_unplace(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
16308 | { |
16309 | dict_T *dict; |
16310 | dictitem_T *di; |
16311 | int sign_id = 0; |
16312 | buf_T *buf = NULL; |
16313 | char_u *group = NULL; |
16314 | |
16315 | rettv->vval.v_number = -1; |
16316 | |
16317 | if (argvars[0].v_type != VAR_STRING) { |
16318 | EMSG(_(e_invarg)); |
16319 | return; |
16320 | } |
16321 | |
16322 | const char *group_chk = tv_get_string(&argvars[0]); |
16323 | if (group_chk[0] == '\0') { |
16324 | group = NULL; // global sign group |
16325 | } else { |
16326 | group = vim_strsave((const char_u *)group_chk); |
16327 | } |
16328 | |
16329 | if (argvars[1].v_type != VAR_UNKNOWN) { |
16330 | if (argvars[1].v_type != VAR_DICT) { |
16331 | EMSG(_(e_dictreq)); |
16332 | goto cleanup; |
16333 | } |
16334 | dict = argvars[1].vval.v_dict; |
16335 | |
16336 | if ((di = tv_dict_find(dict, "buffer" , -1)) != NULL) { |
16337 | buf = get_buf_arg(&di->di_tv); |
16338 | if (buf == NULL) { |
16339 | goto cleanup; |
16340 | } |
16341 | } |
16342 | if (tv_dict_find(dict, "id" , -1) != NULL) { |
16343 | sign_id = tv_dict_get_number(dict, "id" ); |
16344 | } |
16345 | } |
16346 | |
16347 | if (buf == NULL) { |
16348 | // Delete the sign in all the buffers |
16349 | FOR_ALL_BUFFERS(cbuf) { |
16350 | if (sign_unplace(sign_id, group, cbuf, 0) == OK) { |
16351 | rettv->vval.v_number = 0; |
16352 | } |
16353 | } |
16354 | } else { |
16355 | if (sign_unplace(sign_id, group, buf, 0) == OK) { |
16356 | rettv->vval.v_number = 0; |
16357 | } |
16358 | } |
16359 | |
16360 | cleanup: |
16361 | xfree(group); |
16362 | } |
16363 | |
16364 | /* |
16365 | * "simplify()" function |
16366 | */ |
16367 | static void f_simplify(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
16368 | { |
16369 | const char *const p = tv_get_string(&argvars[0]); |
16370 | rettv->vval.v_string = (char_u *)xstrdup(p); |
16371 | simplify_filename(rettv->vval.v_string); // Simplify in place. |
16372 | rettv->v_type = VAR_STRING; |
16373 | } |
16374 | |
16375 | /// "sockconnect()" function |
16376 | static void f_sockconnect(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
16377 | { |
16378 | if (argvars[0].v_type != VAR_STRING || argvars[1].v_type != VAR_STRING) { |
16379 | EMSG(_(e_invarg)); |
16380 | return; |
16381 | } |
16382 | if (argvars[2].v_type != VAR_DICT && argvars[2].v_type != VAR_UNKNOWN) { |
16383 | // Wrong argument types |
16384 | EMSG2(_(e_invarg2), "expected dictionary" ); |
16385 | return; |
16386 | } |
16387 | |
16388 | const char *mode = tv_get_string(&argvars[0]); |
16389 | const char *address = tv_get_string(&argvars[1]); |
16390 | |
16391 | bool tcp; |
16392 | if (strcmp(mode, "tcp" ) == 0) { |
16393 | tcp = true; |
16394 | } else if (strcmp(mode, "pipe" ) == 0) { |
16395 | tcp = false; |
16396 | } else { |
16397 | EMSG2(_(e_invarg2), "invalid mode" ); |
16398 | return; |
16399 | } |
16400 | |
16401 | bool rpc = false; |
16402 | CallbackReader on_data = CALLBACK_READER_INIT; |
16403 | if (argvars[2].v_type == VAR_DICT) { |
16404 | dict_T *opts = argvars[2].vval.v_dict; |
16405 | rpc = tv_dict_get_number(opts, "rpc" ) != 0; |
16406 | |
16407 | if (!tv_dict_get_callback(opts, S_LEN("on_data" ), &on_data.cb)) { |
16408 | return; |
16409 | } |
16410 | on_data.buffered = tv_dict_get_number(opts, "data_buffered" ); |
16411 | if (on_data.buffered && on_data.cb.type == kCallbackNone) { |
16412 | on_data.self = opts; |
16413 | } |
16414 | } |
16415 | |
16416 | const char *error = NULL; |
16417 | uint64_t id = channel_connect(tcp, address, rpc, on_data, 50, &error); |
16418 | |
16419 | if (error) { |
16420 | EMSG2(_("connection failed: %s" ), error); |
16421 | } |
16422 | |
16423 | rettv->vval.v_number = (varnumber_T)id; |
16424 | rettv->v_type = VAR_NUMBER; |
16425 | } |
16426 | |
16427 | /// struct storing information about current sort |
16428 | typedef struct { |
16429 | int item_compare_ic; |
16430 | bool item_compare_numeric; |
16431 | bool item_compare_numbers; |
16432 | bool item_compare_float; |
16433 | const char *item_compare_func; |
16434 | partial_T *item_compare_partial; |
16435 | dict_T *item_compare_selfdict; |
16436 | bool item_compare_func_err; |
16437 | } sortinfo_T; |
16438 | static sortinfo_T *sortinfo = NULL; |
16439 | |
16440 | #define ITEM_COMPARE_FAIL 999 |
16441 | |
16442 | /* |
16443 | * Compare functions for f_sort() and f_uniq() below. |
16444 | */ |
16445 | static int item_compare(const void *s1, const void *s2, bool keep_zero) |
16446 | { |
16447 | ListSortItem *const si1 = (ListSortItem *)s1; |
16448 | ListSortItem *const si2 = (ListSortItem *)s2; |
16449 | |
16450 | typval_T *const tv1 = TV_LIST_ITEM_TV(si1->item); |
16451 | typval_T *const tv2 = TV_LIST_ITEM_TV(si2->item); |
16452 | |
16453 | int res; |
16454 | |
16455 | if (sortinfo->item_compare_numbers) { |
16456 | const varnumber_T v1 = tv_get_number(tv1); |
16457 | const varnumber_T v2 = tv_get_number(tv2); |
16458 | |
16459 | res = v1 == v2 ? 0 : v1 > v2 ? 1 : -1; |
16460 | goto item_compare_end; |
16461 | } |
16462 | |
16463 | if (sortinfo->item_compare_float) { |
16464 | const float_T v1 = tv_get_float(tv1); |
16465 | const float_T v2 = tv_get_float(tv2); |
16466 | |
16467 | res = v1 == v2 ? 0 : v1 > v2 ? 1 : -1; |
16468 | goto item_compare_end; |
16469 | } |
16470 | |
16471 | char *tofree1 = NULL; |
16472 | char *tofree2 = NULL; |
16473 | char *p1; |
16474 | char *p2; |
16475 | |
16476 | // encode_tv2string() puts quotes around a string and allocates memory. Don't |
16477 | // do that for string variables. Use a single quote when comparing with |
16478 | // a non-string to do what the docs promise. |
16479 | if (tv1->v_type == VAR_STRING) { |
16480 | if (tv2->v_type != VAR_STRING || sortinfo->item_compare_numeric) { |
16481 | p1 = "'" ; |
16482 | } else { |
16483 | p1 = (char *)tv1->vval.v_string; |
16484 | } |
16485 | } else { |
16486 | tofree1 = p1 = encode_tv2string(tv1, NULL); |
16487 | } |
16488 | if (tv2->v_type == VAR_STRING) { |
16489 | if (tv1->v_type != VAR_STRING || sortinfo->item_compare_numeric) { |
16490 | p2 = "'" ; |
16491 | } else { |
16492 | p2 = (char *)tv2->vval.v_string; |
16493 | } |
16494 | } else { |
16495 | tofree2 = p2 = encode_tv2string(tv2, NULL); |
16496 | } |
16497 | if (p1 == NULL) { |
16498 | p1 = "" ; |
16499 | } |
16500 | if (p2 == NULL) { |
16501 | p2 = "" ; |
16502 | } |
16503 | if (!sortinfo->item_compare_numeric) { |
16504 | if (sortinfo->item_compare_ic) { |
16505 | res = STRICMP(p1, p2); |
16506 | } else { |
16507 | res = STRCMP(p1, p2); |
16508 | } |
16509 | } else { |
16510 | double n1, n2; |
16511 | n1 = strtod(p1, &p1); |
16512 | n2 = strtod(p2, &p2); |
16513 | res = n1 == n2 ? 0 : n1 > n2 ? 1 : -1; |
16514 | } |
16515 | |
16516 | xfree(tofree1); |
16517 | xfree(tofree2); |
16518 | |
16519 | item_compare_end: |
16520 | // When the result would be zero, compare the item indexes. Makes the |
16521 | // sort stable. |
16522 | if (res == 0 && !keep_zero) { |
16523 | // WARNING: When using uniq si1 and si2 are actually listitem_T **, no |
16524 | // indexes are there. |
16525 | res = si1->idx > si2->idx ? 1 : -1; |
16526 | } |
16527 | return res; |
16528 | } |
16529 | |
16530 | static int item_compare_keeping_zero(const void *s1, const void *s2) |
16531 | { |
16532 | return item_compare(s1, s2, true); |
16533 | } |
16534 | |
16535 | static int item_compare_not_keeping_zero(const void *s1, const void *s2) |
16536 | { |
16537 | return item_compare(s1, s2, false); |
16538 | } |
16539 | |
16540 | static int item_compare2(const void *s1, const void *s2, bool keep_zero) |
16541 | { |
16542 | ListSortItem *si1, *si2; |
16543 | int res; |
16544 | typval_T rettv; |
16545 | typval_T argv[3]; |
16546 | int dummy; |
16547 | const char *func_name; |
16548 | partial_T *partial = sortinfo->item_compare_partial; |
16549 | |
16550 | // shortcut after failure in previous call; compare all items equal |
16551 | if (sortinfo->item_compare_func_err) { |
16552 | return 0; |
16553 | } |
16554 | |
16555 | si1 = (ListSortItem *)s1; |
16556 | si2 = (ListSortItem *)s2; |
16557 | |
16558 | if (partial == NULL) { |
16559 | func_name = sortinfo->item_compare_func; |
16560 | } else { |
16561 | func_name = (const char *)partial_name(partial); |
16562 | } |
16563 | |
16564 | // Copy the values. This is needed to be able to set v_lock to VAR_FIXED |
16565 | // in the copy without changing the original list items. |
16566 | tv_copy(TV_LIST_ITEM_TV(si1->item), &argv[0]); |
16567 | tv_copy(TV_LIST_ITEM_TV(si2->item), &argv[1]); |
16568 | |
16569 | rettv.v_type = VAR_UNKNOWN; // tv_clear() uses this |
16570 | res = call_func((const char_u *)func_name, |
16571 | (int)STRLEN(func_name), |
16572 | &rettv, 2, argv, NULL, 0L, 0L, &dummy, true, |
16573 | partial, sortinfo->item_compare_selfdict); |
16574 | tv_clear(&argv[0]); |
16575 | tv_clear(&argv[1]); |
16576 | |
16577 | if (res == FAIL) { |
16578 | res = ITEM_COMPARE_FAIL; |
16579 | } else { |
16580 | res = tv_get_number_chk(&rettv, &sortinfo->item_compare_func_err); |
16581 | } |
16582 | if (sortinfo->item_compare_func_err) { |
16583 | res = ITEM_COMPARE_FAIL; // return value has wrong type |
16584 | } |
16585 | tv_clear(&rettv); |
16586 | |
16587 | // When the result would be zero, compare the pointers themselves. Makes |
16588 | // the sort stable. |
16589 | if (res == 0 && !keep_zero) { |
16590 | // WARNING: When using uniq si1 and si2 are actually listitem_T **, no |
16591 | // indexes are there. |
16592 | res = si1->idx > si2->idx ? 1 : -1; |
16593 | } |
16594 | |
16595 | return res; |
16596 | } |
16597 | |
16598 | static int item_compare2_keeping_zero(const void *s1, const void *s2) |
16599 | { |
16600 | return item_compare2(s1, s2, true); |
16601 | } |
16602 | |
16603 | static int item_compare2_not_keeping_zero(const void *s1, const void *s2) |
16604 | { |
16605 | return item_compare2(s1, s2, false); |
16606 | } |
16607 | |
16608 | /* |
16609 | * "sort({list})" function |
16610 | */ |
16611 | static void do_sort_uniq(typval_T *argvars, typval_T *rettv, bool sort) |
16612 | { |
16613 | ListSortItem *ptrs; |
16614 | long len; |
16615 | long i; |
16616 | |
16617 | // Pointer to current info struct used in compare function. Save and restore |
16618 | // the current one for nested calls. |
16619 | sortinfo_T info; |
16620 | sortinfo_T *old_sortinfo = sortinfo; |
16621 | sortinfo = &info; |
16622 | |
16623 | const char *const arg_errmsg = (sort |
16624 | ? N_("sort() argument" ) |
16625 | : N_("uniq() argument" )); |
16626 | |
16627 | if (argvars[0].v_type != VAR_LIST) { |
16628 | EMSG2(_(e_listarg), sort ? "sort()" : "uniq()" ); |
16629 | } else { |
16630 | list_T *const l = argvars[0].vval.v_list; |
16631 | if (tv_check_lock(tv_list_locked(l), arg_errmsg, TV_TRANSLATE)) { |
16632 | goto theend; |
16633 | } |
16634 | tv_list_set_ret(rettv, l); |
16635 | |
16636 | len = tv_list_len(l); |
16637 | if (len <= 1) { |
16638 | goto theend; // short list sorts pretty quickly |
16639 | } |
16640 | |
16641 | info.item_compare_ic = false; |
16642 | info.item_compare_numeric = false; |
16643 | info.item_compare_numbers = false; |
16644 | info.item_compare_float = false; |
16645 | info.item_compare_func = NULL; |
16646 | info.item_compare_partial = NULL; |
16647 | info.item_compare_selfdict = NULL; |
16648 | |
16649 | if (argvars[1].v_type != VAR_UNKNOWN) { |
16650 | /* optional second argument: {func} */ |
16651 | if (argvars[1].v_type == VAR_FUNC) { |
16652 | info.item_compare_func = (const char *)argvars[1].vval.v_string; |
16653 | } else if (argvars[1].v_type == VAR_PARTIAL) { |
16654 | info.item_compare_partial = argvars[1].vval.v_partial; |
16655 | } else { |
16656 | bool error = false; |
16657 | |
16658 | i = tv_get_number_chk(&argvars[1], &error); |
16659 | if (error) { |
16660 | goto theend; // type error; errmsg already given |
16661 | } |
16662 | if (i == 1) { |
16663 | info.item_compare_ic = true; |
16664 | } else if (argvars[1].v_type != VAR_NUMBER) { |
16665 | info.item_compare_func = tv_get_string(&argvars[1]); |
16666 | } else if (i != 0) { |
16667 | EMSG(_(e_invarg)); |
16668 | goto theend; |
16669 | } |
16670 | if (info.item_compare_func != NULL) { |
16671 | if (*info.item_compare_func == NUL) { |
16672 | // empty string means default sort |
16673 | info.item_compare_func = NULL; |
16674 | } else if (strcmp(info.item_compare_func, "n" ) == 0) { |
16675 | info.item_compare_func = NULL; |
16676 | info.item_compare_numeric = true; |
16677 | } else if (strcmp(info.item_compare_func, "N" ) == 0) { |
16678 | info.item_compare_func = NULL; |
16679 | info.item_compare_numbers = true; |
16680 | } else if (strcmp(info.item_compare_func, "f" ) == 0) { |
16681 | info.item_compare_func = NULL; |
16682 | info.item_compare_float = true; |
16683 | } else if (strcmp(info.item_compare_func, "i" ) == 0) { |
16684 | info.item_compare_func = NULL; |
16685 | info.item_compare_ic = true; |
16686 | } |
16687 | } |
16688 | } |
16689 | |
16690 | if (argvars[2].v_type != VAR_UNKNOWN) { |
16691 | // optional third argument: {dict} |
16692 | if (argvars[2].v_type != VAR_DICT) { |
16693 | EMSG(_(e_dictreq)); |
16694 | goto theend; |
16695 | } |
16696 | info.item_compare_selfdict = argvars[2].vval.v_dict; |
16697 | } |
16698 | } |
16699 | |
16700 | // Make an array with each entry pointing to an item in the List. |
16701 | ptrs = xmalloc((size_t)(len * sizeof(ListSortItem))); |
16702 | |
16703 | if (sort) { |
16704 | info.item_compare_func_err = false; |
16705 | tv_list_item_sort(l, ptrs, |
16706 | ((info.item_compare_func == NULL |
16707 | && info.item_compare_partial == NULL) |
16708 | ? item_compare_not_keeping_zero |
16709 | : item_compare2_not_keeping_zero), |
16710 | &info.item_compare_func_err); |
16711 | if (info.item_compare_func_err) { |
16712 | EMSG(_("E702: Sort compare function failed" )); |
16713 | } |
16714 | } else { |
16715 | ListSorter item_compare_func_ptr; |
16716 | |
16717 | // f_uniq(): ptrs will be a stack of items to remove. |
16718 | info.item_compare_func_err = false; |
16719 | if (info.item_compare_func != NULL |
16720 | || info.item_compare_partial != NULL) { |
16721 | item_compare_func_ptr = item_compare2_keeping_zero; |
16722 | } else { |
16723 | item_compare_func_ptr = item_compare_keeping_zero; |
16724 | } |
16725 | |
16726 | int idx = 0; |
16727 | for (listitem_T *li = TV_LIST_ITEM_NEXT(l, tv_list_first(l)) |
16728 | ; li != NULL;) { |
16729 | listitem_T *const prev_li = TV_LIST_ITEM_PREV(l, li); |
16730 | if (item_compare_func_ptr(&prev_li, &li) == 0) { |
16731 | if (info.item_compare_func_err) { // -V547 |
16732 | EMSG(_("E882: Uniq compare function failed" )); |
16733 | break; |
16734 | } |
16735 | li = tv_list_item_remove(l, li); |
16736 | } else { |
16737 | idx++; |
16738 | li = TV_LIST_ITEM_NEXT(l, li); |
16739 | } |
16740 | } |
16741 | } |
16742 | |
16743 | xfree(ptrs); |
16744 | } |
16745 | |
16746 | theend: |
16747 | sortinfo = old_sortinfo; |
16748 | } |
16749 | |
16750 | /// "sort"({list})" function |
16751 | static void f_sort(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
16752 | { |
16753 | do_sort_uniq(argvars, rettv, true); |
16754 | } |
16755 | |
16756 | /// "stdioopen()" function |
16757 | static void f_stdioopen(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
16758 | { |
16759 | if (argvars[0].v_type != VAR_DICT) { |
16760 | EMSG(_(e_invarg)); |
16761 | return; |
16762 | } |
16763 | |
16764 | |
16765 | bool rpc = false; |
16766 | CallbackReader on_stdin = CALLBACK_READER_INIT; |
16767 | dict_T *opts = argvars[0].vval.v_dict; |
16768 | rpc = tv_dict_get_number(opts, "rpc" ) != 0; |
16769 | |
16770 | if (!tv_dict_get_callback(opts, S_LEN("on_stdin" ), &on_stdin.cb)) { |
16771 | return; |
16772 | } |
16773 | on_stdin.buffered = tv_dict_get_number(opts, "stdin_buffered" ); |
16774 | if (on_stdin.buffered && on_stdin.cb.type == kCallbackNone) { |
16775 | on_stdin.self = opts; |
16776 | } |
16777 | |
16778 | const char *error; |
16779 | uint64_t id = channel_from_stdio(rpc, on_stdin, &error); |
16780 | if (!id) { |
16781 | EMSG2(e_stdiochan2, error); |
16782 | } |
16783 | |
16784 | |
16785 | rettv->vval.v_number = (varnumber_T)id; |
16786 | rettv->v_type = VAR_NUMBER; |
16787 | } |
16788 | |
16789 | /// "uniq({list})" function |
16790 | static void f_uniq(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
16791 | { |
16792 | do_sort_uniq(argvars, rettv, false); |
16793 | } |
16794 | |
16795 | // "reltimefloat()" function |
16796 | static void f_reltimefloat(typval_T *argvars , typval_T *rettv, FunPtr fptr) |
16797 | FUNC_ATTR_NONNULL_ALL |
16798 | { |
16799 | proftime_T tm; |
16800 | |
16801 | rettv->v_type = VAR_FLOAT; |
16802 | rettv->vval.v_float = 0; |
16803 | if (list2proftime(&argvars[0], &tm) == OK) { |
16804 | rettv->vval.v_float = (float_T)profile_signed(tm) / 1000000000.0; |
16805 | } |
16806 | } |
16807 | |
16808 | /* |
16809 | * "soundfold({word})" function |
16810 | */ |
16811 | static void f_soundfold(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
16812 | { |
16813 | rettv->v_type = VAR_STRING; |
16814 | const char *const s = tv_get_string(&argvars[0]); |
16815 | rettv->vval.v_string = (char_u *)eval_soundfold(s); |
16816 | } |
16817 | |
16818 | /* |
16819 | * "spellbadword()" function |
16820 | */ |
16821 | static void f_spellbadword(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
16822 | { |
16823 | const char *word = "" ; |
16824 | hlf_T attr = HLF_COUNT; |
16825 | size_t len = 0; |
16826 | |
16827 | if (argvars[0].v_type == VAR_UNKNOWN) { |
16828 | // Find the start and length of the badly spelled word. |
16829 | len = spell_move_to(curwin, FORWARD, true, true, &attr); |
16830 | if (len != 0) { |
16831 | word = (char *)get_cursor_pos_ptr(); |
16832 | curwin->w_set_curswant = true; |
16833 | } |
16834 | } else if (curwin->w_p_spell && *curbuf->b_s.b_p_spl != NUL) { |
16835 | const char *str = tv_get_string_chk(&argvars[0]); |
16836 | int capcol = -1; |
16837 | |
16838 | if (str != NULL) { |
16839 | // Check the argument for spelling. |
16840 | while (*str != NUL) { |
16841 | len = spell_check(curwin, (char_u *)str, &attr, &capcol, false); |
16842 | if (attr != HLF_COUNT) { |
16843 | word = str; |
16844 | break; |
16845 | } |
16846 | str += len; |
16847 | capcol -= len; |
16848 | len = 0; |
16849 | } |
16850 | } |
16851 | } |
16852 | |
16853 | assert(len <= INT_MAX); |
16854 | tv_list_alloc_ret(rettv, 2); |
16855 | tv_list_append_string(rettv->vval.v_list, word, len); |
16856 | tv_list_append_string(rettv->vval.v_list, |
16857 | (attr == HLF_SPB ? "bad" |
16858 | : attr == HLF_SPR ? "rare" |
16859 | : attr == HLF_SPL ? "local" |
16860 | : attr == HLF_SPC ? "caps" |
16861 | : NULL), -1); |
16862 | } |
16863 | |
16864 | /* |
16865 | * "spellsuggest()" function |
16866 | */ |
16867 | static void f_spellsuggest(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
16868 | { |
16869 | bool typeerr = false; |
16870 | int maxcount; |
16871 | garray_T ga = GA_EMPTY_INIT_VALUE; |
16872 | bool need_capital = false; |
16873 | |
16874 | if (curwin->w_p_spell && *curwin->w_s->b_p_spl != NUL) { |
16875 | const char *const str = tv_get_string(&argvars[0]); |
16876 | if (argvars[1].v_type != VAR_UNKNOWN) { |
16877 | maxcount = tv_get_number_chk(&argvars[1], &typeerr); |
16878 | if (maxcount <= 0) { |
16879 | goto f_spellsuggest_return; |
16880 | } |
16881 | if (argvars[2].v_type != VAR_UNKNOWN) { |
16882 | need_capital = tv_get_number_chk(&argvars[2], &typeerr); |
16883 | if (typeerr) { |
16884 | goto f_spellsuggest_return; |
16885 | } |
16886 | } |
16887 | } else { |
16888 | maxcount = 25; |
16889 | } |
16890 | |
16891 | spell_suggest_list(&ga, (char_u *)str, maxcount, need_capital, false); |
16892 | } |
16893 | |
16894 | f_spellsuggest_return: |
16895 | tv_list_alloc_ret(rettv, (ptrdiff_t)ga.ga_len); |
16896 | for (int i = 0; i < ga.ga_len; i++) { |
16897 | char *const p = ((char **)ga.ga_data)[i]; |
16898 | tv_list_append_allocated_string(rettv->vval.v_list, p); |
16899 | } |
16900 | ga_clear(&ga); |
16901 | } |
16902 | |
16903 | static void f_split(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
16904 | { |
16905 | char_u *save_cpo; |
16906 | int match; |
16907 | colnr_T col = 0; |
16908 | bool keepempty = false; |
16909 | bool typeerr = false; |
16910 | |
16911 | /* Make 'cpoptions' empty, the 'l' flag should not be used here. */ |
16912 | save_cpo = p_cpo; |
16913 | p_cpo = (char_u *)"" ; |
16914 | |
16915 | const char *str = tv_get_string(&argvars[0]); |
16916 | const char *pat = NULL; |
16917 | char patbuf[NUMBUFLEN]; |
16918 | if (argvars[1].v_type != VAR_UNKNOWN) { |
16919 | pat = tv_get_string_buf_chk(&argvars[1], patbuf); |
16920 | if (pat == NULL) { |
16921 | typeerr = true; |
16922 | } |
16923 | if (argvars[2].v_type != VAR_UNKNOWN) { |
16924 | keepempty = (bool)tv_get_number_chk(&argvars[2], &typeerr); |
16925 | } |
16926 | } |
16927 | if (pat == NULL || *pat == NUL) { |
16928 | pat = "[\\x01- ]\\+" ; |
16929 | } |
16930 | |
16931 | tv_list_alloc_ret(rettv, kListLenMayKnow); |
16932 | |
16933 | if (typeerr) { |
16934 | return; |
16935 | } |
16936 | |
16937 | regmatch_T regmatch = { |
16938 | .regprog = vim_regcomp((char_u *)pat, RE_MAGIC + RE_STRING), |
16939 | .startp = { NULL }, |
16940 | .endp = { NULL }, |
16941 | .rm_ic = false, |
16942 | }; |
16943 | if (regmatch.regprog != NULL) { |
16944 | while (*str != NUL || keepempty) { |
16945 | if (*str == NUL) { |
16946 | match = false; // Empty item at the end. |
16947 | } else { |
16948 | match = vim_regexec_nl(®match, (char_u *)str, col); |
16949 | } |
16950 | const char *end; |
16951 | if (match) { |
16952 | end = (const char *)regmatch.startp[0]; |
16953 | } else { |
16954 | end = str + strlen(str); |
16955 | } |
16956 | if (keepempty || end > str || (tv_list_len(rettv->vval.v_list) > 0 |
16957 | && *str != NUL |
16958 | && match |
16959 | && end < (const char *)regmatch.endp[0])) { |
16960 | tv_list_append_string(rettv->vval.v_list, str, end - str); |
16961 | } |
16962 | if (!match) { |
16963 | break; |
16964 | } |
16965 | // Advance to just after the match. |
16966 | if (regmatch.endp[0] > (char_u *)str) { |
16967 | col = 0; |
16968 | } else { |
16969 | // Don't get stuck at the same match. |
16970 | col = (*mb_ptr2len)(regmatch.endp[0]); |
16971 | } |
16972 | str = (const char *)regmatch.endp[0]; |
16973 | } |
16974 | |
16975 | vim_regfree(regmatch.regprog); |
16976 | } |
16977 | |
16978 | p_cpo = save_cpo; |
16979 | } |
16980 | |
16981 | /// "stdpath()" helper for list results |
16982 | static void get_xdg_var_list(const XDGVarType xdg, typval_T *rettv) |
16983 | FUNC_ATTR_NONNULL_ALL |
16984 | { |
16985 | const void *iter = NULL; |
16986 | list_T *const list = tv_list_alloc(kListLenShouldKnow); |
16987 | rettv->v_type = VAR_LIST; |
16988 | rettv->vval.v_list = list; |
16989 | tv_list_ref(list); |
16990 | char *const dirs = stdpaths_get_xdg_var(xdg); |
16991 | if (dirs == NULL) { |
16992 | return; |
16993 | } |
16994 | do { |
16995 | size_t dir_len; |
16996 | const char *dir; |
16997 | iter = vim_env_iter(':', dirs, iter, &dir, &dir_len); |
16998 | if (dir != NULL && dir_len > 0) { |
16999 | char *dir_with_nvim = xmemdupz(dir, dir_len); |
17000 | dir_with_nvim = concat_fnames_realloc(dir_with_nvim, "nvim" , true); |
17001 | tv_list_append_string(list, dir_with_nvim, strlen(dir_with_nvim)); |
17002 | xfree(dir_with_nvim); |
17003 | } |
17004 | } while (iter != NULL); |
17005 | xfree(dirs); |
17006 | } |
17007 | |
17008 | /// "stdpath(type)" function |
17009 | static void f_stdpath(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
17010 | { |
17011 | rettv->v_type = VAR_STRING; |
17012 | rettv->vval.v_string = NULL; |
17013 | |
17014 | const char *const p = tv_get_string_chk(&argvars[0]); |
17015 | if (p == NULL) { |
17016 | return; // Type error; errmsg already given. |
17017 | } |
17018 | |
17019 | if (strequal(p, "config" )) { |
17020 | rettv->vval.v_string = (char_u *)get_xdg_home(kXDGConfigHome); |
17021 | } else if (strequal(p, "data" )) { |
17022 | rettv->vval.v_string = (char_u *)get_xdg_home(kXDGDataHome); |
17023 | } else if (strequal(p, "cache" )) { |
17024 | rettv->vval.v_string = (char_u *)get_xdg_home(kXDGCacheHome); |
17025 | } else if (strequal(p, "config_dirs" )) { |
17026 | get_xdg_var_list(kXDGConfigDirs, rettv); |
17027 | } else if (strequal(p, "data_dirs" )) { |
17028 | get_xdg_var_list(kXDGDataDirs, rettv); |
17029 | } else { |
17030 | EMSG2(_("E6100: \"%s\" is not a valid stdpath" ), p); |
17031 | } |
17032 | } |
17033 | |
17034 | /* |
17035 | * "str2float()" function |
17036 | */ |
17037 | static void f_str2float(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
17038 | { |
17039 | char_u *p = skipwhite((const char_u *)tv_get_string(&argvars[0])); |
17040 | bool isneg = (*p == '-'); |
17041 | |
17042 | if (*p == '+' || *p == '-') { |
17043 | p = skipwhite(p + 1); |
17044 | } |
17045 | (void)string2float((char *)p, &rettv->vval.v_float); |
17046 | if (isneg) { |
17047 | rettv->vval.v_float *= -1; |
17048 | } |
17049 | rettv->v_type = VAR_FLOAT; |
17050 | } |
17051 | |
17052 | // "str2nr()" function |
17053 | static void f_str2nr(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
17054 | { |
17055 | int base = 10; |
17056 | varnumber_T n; |
17057 | int what; |
17058 | |
17059 | if (argvars[1].v_type != VAR_UNKNOWN) { |
17060 | base = tv_get_number(&argvars[1]); |
17061 | if (base != 2 && base != 8 && base != 10 && base != 16) { |
17062 | EMSG(_(e_invarg)); |
17063 | return; |
17064 | } |
17065 | } |
17066 | |
17067 | char_u *p = skipwhite((const char_u *)tv_get_string(&argvars[0])); |
17068 | bool isneg = (*p == '-'); |
17069 | if (*p == '+' || *p == '-') { |
17070 | p = skipwhite(p + 1); |
17071 | } |
17072 | switch (base) { |
17073 | case 2: { |
17074 | what = STR2NR_BIN | STR2NR_FORCE; |
17075 | break; |
17076 | } |
17077 | case 8: { |
17078 | what = STR2NR_OCT | STR2NR_FORCE; |
17079 | break; |
17080 | } |
17081 | case 16: { |
17082 | what = STR2NR_HEX | STR2NR_FORCE; |
17083 | break; |
17084 | } |
17085 | default: { |
17086 | what = 0; |
17087 | } |
17088 | } |
17089 | vim_str2nr(p, NULL, NULL, what, &n, NULL, 0); |
17090 | if (isneg) { |
17091 | rettv->vval.v_number = -n; |
17092 | } else { |
17093 | rettv->vval.v_number = n; |
17094 | } |
17095 | } |
17096 | |
17097 | /* |
17098 | * "strftime({format}[, {time}])" function |
17099 | */ |
17100 | static void f_strftime(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
17101 | { |
17102 | time_t seconds; |
17103 | |
17104 | rettv->v_type = VAR_STRING; |
17105 | |
17106 | char *p = (char *)tv_get_string(&argvars[0]); |
17107 | if (argvars[1].v_type == VAR_UNKNOWN) { |
17108 | seconds = time(NULL); |
17109 | } else { |
17110 | seconds = (time_t)tv_get_number(&argvars[1]); |
17111 | } |
17112 | |
17113 | struct tm curtime; |
17114 | struct tm *curtime_ptr = os_localtime_r(&seconds, &curtime); |
17115 | /* MSVC returns NULL for an invalid value of seconds. */ |
17116 | if (curtime_ptr == NULL) |
17117 | rettv->vval.v_string = vim_strsave((char_u *)_("(Invalid)" )); |
17118 | else { |
17119 | vimconv_T conv; |
17120 | char_u *enc; |
17121 | |
17122 | conv.vc_type = CONV_NONE; |
17123 | enc = enc_locale(); |
17124 | convert_setup(&conv, p_enc, enc); |
17125 | if (conv.vc_type != CONV_NONE) { |
17126 | p = (char *)string_convert(&conv, (char_u *)p, NULL); |
17127 | } |
17128 | char result_buf[256]; |
17129 | if (p != NULL) { |
17130 | (void)strftime(result_buf, sizeof(result_buf), p, curtime_ptr); |
17131 | } else { |
17132 | result_buf[0] = NUL; |
17133 | } |
17134 | |
17135 | if (conv.vc_type != CONV_NONE) { |
17136 | xfree(p); |
17137 | } |
17138 | convert_setup(&conv, enc, p_enc); |
17139 | if (conv.vc_type != CONV_NONE) { |
17140 | rettv->vval.v_string = string_convert(&conv, (char_u *)result_buf, NULL); |
17141 | } else { |
17142 | rettv->vval.v_string = (char_u *)xstrdup(result_buf); |
17143 | } |
17144 | |
17145 | // Release conversion descriptors. |
17146 | convert_setup(&conv, NULL, NULL); |
17147 | xfree(enc); |
17148 | } |
17149 | } |
17150 | |
17151 | // "strgetchar()" function |
17152 | static void f_strgetchar(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
17153 | { |
17154 | rettv->vval.v_number = -1; |
17155 | |
17156 | const char *const str = tv_get_string_chk(&argvars[0]); |
17157 | if (str == NULL) { |
17158 | return; |
17159 | } |
17160 | bool error = false; |
17161 | varnumber_T charidx = tv_get_number_chk(&argvars[1], &error); |
17162 | if (error) { |
17163 | return; |
17164 | } |
17165 | |
17166 | const size_t len = STRLEN(str); |
17167 | size_t byteidx = 0; |
17168 | |
17169 | while (charidx >= 0 && byteidx < len) { |
17170 | if (charidx == 0) { |
17171 | rettv->vval.v_number = utf_ptr2char((const char_u *)str + byteidx); |
17172 | break; |
17173 | } |
17174 | charidx--; |
17175 | byteidx += MB_CPTR2LEN((const char_u *)str + byteidx); |
17176 | } |
17177 | } |
17178 | |
17179 | /* |
17180 | * "stridx()" function |
17181 | */ |
17182 | static void f_stridx(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
17183 | { |
17184 | rettv->vval.v_number = -1; |
17185 | |
17186 | char buf[NUMBUFLEN]; |
17187 | const char *const needle = tv_get_string_chk(&argvars[1]); |
17188 | const char *haystack = tv_get_string_buf_chk(&argvars[0], buf); |
17189 | const char *const haystack_start = haystack; |
17190 | if (needle == NULL || haystack == NULL) { |
17191 | return; // Type error; errmsg already given. |
17192 | } |
17193 | |
17194 | if (argvars[2].v_type != VAR_UNKNOWN) { |
17195 | bool error = false; |
17196 | |
17197 | const ptrdiff_t start_idx = (ptrdiff_t)tv_get_number_chk(&argvars[2], |
17198 | &error); |
17199 | if (error || start_idx >= (ptrdiff_t)strlen(haystack)) { |
17200 | return; |
17201 | } |
17202 | if (start_idx >= 0) { |
17203 | haystack += start_idx; |
17204 | } |
17205 | } |
17206 | |
17207 | const char *pos = strstr(haystack, needle); |
17208 | if (pos != NULL) { |
17209 | rettv->vval.v_number = (varnumber_T)(pos - haystack_start); |
17210 | } |
17211 | } |
17212 | |
17213 | /* |
17214 | * "string()" function |
17215 | */ |
17216 | static void f_string(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
17217 | { |
17218 | rettv->v_type = VAR_STRING; |
17219 | rettv->vval.v_string = (char_u *) encode_tv2string(&argvars[0], NULL); |
17220 | } |
17221 | |
17222 | /* |
17223 | * "strlen()" function |
17224 | */ |
17225 | static void f_strlen(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
17226 | { |
17227 | rettv->vval.v_number = (varnumber_T)strlen(tv_get_string(&argvars[0])); |
17228 | } |
17229 | |
17230 | /* |
17231 | * "strchars()" function |
17232 | */ |
17233 | static void f_strchars(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
17234 | { |
17235 | const char *s = tv_get_string(&argvars[0]); |
17236 | int skipcc = 0; |
17237 | varnumber_T len = 0; |
17238 | int (*func_mb_ptr2char_adv)(const char_u **pp); |
17239 | |
17240 | if (argvars[1].v_type != VAR_UNKNOWN) { |
17241 | skipcc = tv_get_number_chk(&argvars[1], NULL); |
17242 | } |
17243 | if (skipcc < 0 || skipcc > 1) { |
17244 | EMSG(_(e_invarg)); |
17245 | } else { |
17246 | func_mb_ptr2char_adv = skipcc ? mb_ptr2char_adv : mb_cptr2char_adv; |
17247 | while (*s != NUL) { |
17248 | func_mb_ptr2char_adv((const char_u **)&s); |
17249 | len++; |
17250 | } |
17251 | rettv->vval.v_number = len; |
17252 | } |
17253 | } |
17254 | |
17255 | /* |
17256 | * "strdisplaywidth()" function |
17257 | */ |
17258 | static void f_strdisplaywidth(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
17259 | { |
17260 | const char *const s = tv_get_string(&argvars[0]); |
17261 | int col = 0; |
17262 | |
17263 | if (argvars[1].v_type != VAR_UNKNOWN) { |
17264 | col = tv_get_number(&argvars[1]); |
17265 | } |
17266 | |
17267 | rettv->vval.v_number = (varnumber_T)(linetabsize_col(col, (char_u *)s) - col); |
17268 | } |
17269 | |
17270 | /* |
17271 | * "strwidth()" function |
17272 | */ |
17273 | static void f_strwidth(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
17274 | { |
17275 | const char *const s = tv_get_string(&argvars[0]); |
17276 | |
17277 | rettv->vval.v_number = (varnumber_T)mb_string2cells((const char_u *)s); |
17278 | } |
17279 | |
17280 | // "strcharpart()" function |
17281 | static void f_strcharpart(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
17282 | { |
17283 | const char *const p = tv_get_string(&argvars[0]); |
17284 | const size_t slen = STRLEN(p); |
17285 | |
17286 | int nbyte = 0; |
17287 | bool error = false; |
17288 | varnumber_T nchar = tv_get_number_chk(&argvars[1], &error); |
17289 | if (!error) { |
17290 | if (nchar > 0) { |
17291 | while (nchar > 0 && (size_t)nbyte < slen) { |
17292 | nbyte += MB_CPTR2LEN((const char_u *)p + nbyte); |
17293 | nchar--; |
17294 | } |
17295 | } else { |
17296 | nbyte = nchar; |
17297 | } |
17298 | } |
17299 | int len = 0; |
17300 | if (argvars[2].v_type != VAR_UNKNOWN) { |
17301 | int charlen = tv_get_number(&argvars[2]); |
17302 | while (charlen > 0 && nbyte + len < (int)slen) { |
17303 | int off = nbyte + len; |
17304 | |
17305 | if (off < 0) { |
17306 | len += 1; |
17307 | } else { |
17308 | len += (size_t)MB_CPTR2LEN((const char_u *)p + off); |
17309 | } |
17310 | charlen--; |
17311 | } |
17312 | } else { |
17313 | len = slen - nbyte; // default: all bytes that are available. |
17314 | } |
17315 | |
17316 | // Only return the overlap between the specified part and the actual |
17317 | // string. |
17318 | if (nbyte < 0) { |
17319 | len += nbyte; |
17320 | nbyte = 0; |
17321 | } else if ((size_t)nbyte > slen) { |
17322 | nbyte = slen; |
17323 | } |
17324 | if (len < 0) { |
17325 | len = 0; |
17326 | } else if (nbyte + len > (int)slen) { |
17327 | len = slen - nbyte; |
17328 | } |
17329 | |
17330 | rettv->v_type = VAR_STRING; |
17331 | rettv->vval.v_string = (char_u *)xstrndup(p + nbyte, (size_t)len); |
17332 | } |
17333 | |
17334 | /* |
17335 | * "strpart()" function |
17336 | */ |
17337 | static void f_strpart(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
17338 | { |
17339 | bool error = false; |
17340 | |
17341 | const char *const p = tv_get_string(&argvars[0]); |
17342 | const size_t slen = strlen(p); |
17343 | |
17344 | varnumber_T n = tv_get_number_chk(&argvars[1], &error); |
17345 | varnumber_T len; |
17346 | if (error) { |
17347 | len = 0; |
17348 | } else if (argvars[2].v_type != VAR_UNKNOWN) { |
17349 | len = tv_get_number(&argvars[2]); |
17350 | } else { |
17351 | len = slen - n; // Default len: all bytes that are available. |
17352 | } |
17353 | |
17354 | // Only return the overlap between the specified part and the actual |
17355 | // string. |
17356 | if (n < 0) { |
17357 | len += n; |
17358 | n = 0; |
17359 | } else if (n > (varnumber_T)slen) { |
17360 | n = slen; |
17361 | } |
17362 | if (len < 0) { |
17363 | len = 0; |
17364 | } else if (n + len > (varnumber_T)slen) { |
17365 | len = slen - n; |
17366 | } |
17367 | |
17368 | rettv->v_type = VAR_STRING; |
17369 | rettv->vval.v_string = (char_u *)xmemdupz(p + n, (size_t)len); |
17370 | } |
17371 | |
17372 | /* |
17373 | * "strridx()" function |
17374 | */ |
17375 | static void f_strridx(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
17376 | { |
17377 | char buf[NUMBUFLEN]; |
17378 | const char *const needle = tv_get_string_chk(&argvars[1]); |
17379 | const char *const haystack = tv_get_string_buf_chk(&argvars[0], buf); |
17380 | |
17381 | rettv->vval.v_number = -1; |
17382 | if (needle == NULL || haystack == NULL) { |
17383 | return; // Type error; errmsg already given. |
17384 | } |
17385 | |
17386 | const size_t haystack_len = STRLEN(haystack); |
17387 | ptrdiff_t end_idx; |
17388 | if (argvars[2].v_type != VAR_UNKNOWN) { |
17389 | // Third argument: upper limit for index. |
17390 | end_idx = (ptrdiff_t)tv_get_number_chk(&argvars[2], NULL); |
17391 | if (end_idx < 0) { |
17392 | return; // Can never find a match. |
17393 | } |
17394 | } else { |
17395 | end_idx = (ptrdiff_t)haystack_len; |
17396 | } |
17397 | |
17398 | const char *lastmatch = NULL; |
17399 | if (*needle == NUL) { |
17400 | // Empty string matches past the end. |
17401 | lastmatch = haystack + end_idx; |
17402 | } else { |
17403 | for (const char *rest = haystack; *rest != NUL; rest++) { |
17404 | rest = strstr(rest, needle); |
17405 | if (rest == NULL || rest > haystack + end_idx) { |
17406 | break; |
17407 | } |
17408 | lastmatch = rest; |
17409 | } |
17410 | } |
17411 | |
17412 | if (lastmatch == NULL) { |
17413 | rettv->vval.v_number = -1; |
17414 | } else { |
17415 | rettv->vval.v_number = (varnumber_T)(lastmatch - haystack); |
17416 | } |
17417 | } |
17418 | |
17419 | /* |
17420 | * "strtrans()" function |
17421 | */ |
17422 | static void f_strtrans(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
17423 | { |
17424 | rettv->v_type = VAR_STRING; |
17425 | rettv->vval.v_string = (char_u *)transstr(tv_get_string(&argvars[0])); |
17426 | } |
17427 | |
17428 | /* |
17429 | * "submatch()" function |
17430 | */ |
17431 | static void f_submatch(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
17432 | { |
17433 | bool error = false; |
17434 | int no = (int)tv_get_number_chk(&argvars[0], &error); |
17435 | if (error) { |
17436 | return; |
17437 | } |
17438 | |
17439 | if (no < 0 || no >= NSUBEXP) { |
17440 | emsgf(_("E935: invalid submatch number: %d" ), no); |
17441 | return; |
17442 | } |
17443 | int retList = 0; |
17444 | |
17445 | if (argvars[1].v_type != VAR_UNKNOWN) { |
17446 | retList = tv_get_number_chk(&argvars[1], &error); |
17447 | if (error) { |
17448 | return; |
17449 | } |
17450 | } |
17451 | |
17452 | if (retList == 0) { |
17453 | rettv->v_type = VAR_STRING; |
17454 | rettv->vval.v_string = reg_submatch(no); |
17455 | } else { |
17456 | rettv->v_type = VAR_LIST; |
17457 | rettv->vval.v_list = reg_submatch_list(no); |
17458 | } |
17459 | } |
17460 | |
17461 | /* |
17462 | * "substitute()" function |
17463 | */ |
17464 | static void f_substitute(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
17465 | { |
17466 | char patbuf[NUMBUFLEN]; |
17467 | char subbuf[NUMBUFLEN]; |
17468 | char flagsbuf[NUMBUFLEN]; |
17469 | |
17470 | const char *const str = tv_get_string_chk(&argvars[0]); |
17471 | const char *const pat = tv_get_string_buf_chk(&argvars[1], patbuf); |
17472 | const char *sub = NULL; |
17473 | const char *const flg = tv_get_string_buf_chk(&argvars[3], flagsbuf); |
17474 | |
17475 | typval_T *expr = NULL; |
17476 | if (tv_is_func(argvars[2])) { |
17477 | expr = &argvars[2]; |
17478 | } else { |
17479 | sub = tv_get_string_buf_chk(&argvars[2], subbuf); |
17480 | } |
17481 | |
17482 | rettv->v_type = VAR_STRING; |
17483 | if (str == NULL || pat == NULL || (sub == NULL && expr == NULL) |
17484 | || flg == NULL) { |
17485 | rettv->vval.v_string = NULL; |
17486 | } else { |
17487 | rettv->vval.v_string = do_string_sub((char_u *)str, (char_u *)pat, |
17488 | (char_u *)sub, expr, (char_u *)flg); |
17489 | } |
17490 | } |
17491 | |
17492 | /// "swapinfo(swap_filename)" function |
17493 | static void f_swapinfo(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
17494 | { |
17495 | tv_dict_alloc_ret(rettv); |
17496 | get_b0_dict(tv_get_string(argvars), rettv->vval.v_dict); |
17497 | } |
17498 | |
17499 | /// "swapname(expr)" function |
17500 | static void f_swapname(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
17501 | { |
17502 | rettv->v_type = VAR_STRING; |
17503 | buf_T *buf = tv_get_buf(&argvars[0], false); |
17504 | if (buf == NULL |
17505 | || buf->b_ml.ml_mfp == NULL |
17506 | || buf->b_ml.ml_mfp->mf_fname == NULL) { |
17507 | rettv->vval.v_string = NULL; |
17508 | } else { |
17509 | rettv->vval.v_string = vim_strsave(buf->b_ml.ml_mfp->mf_fname); |
17510 | } |
17511 | } |
17512 | |
17513 | /// "synID(lnum, col, trans)" function |
17514 | static void f_synID(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
17515 | { |
17516 | // -1 on type error (both) |
17517 | const linenr_T lnum = tv_get_lnum(argvars); |
17518 | const colnr_T col = (colnr_T)tv_get_number(&argvars[1]) - 1; |
17519 | |
17520 | bool transerr = false; |
17521 | const int trans = tv_get_number_chk(&argvars[2], &transerr); |
17522 | |
17523 | int id = 0; |
17524 | if (!transerr && lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count |
17525 | && col >= 0 && (size_t)col < STRLEN(ml_get(lnum))) { |
17526 | id = syn_get_id(curwin, lnum, col, trans, NULL, false); |
17527 | } |
17528 | |
17529 | rettv->vval.v_number = id; |
17530 | } |
17531 | |
17532 | /* |
17533 | * "synIDattr(id, what [, mode])" function |
17534 | */ |
17535 | static void f_synIDattr(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
17536 | { |
17537 | const int id = (int)tv_get_number(&argvars[0]); |
17538 | const char *const what = tv_get_string(&argvars[1]); |
17539 | int modec; |
17540 | if (argvars[2].v_type != VAR_UNKNOWN) { |
17541 | char modebuf[NUMBUFLEN]; |
17542 | const char *const mode = tv_get_string_buf(&argvars[2], modebuf); |
17543 | modec = TOLOWER_ASC(mode[0]); |
17544 | if (modec != 'c' && modec != 'g') { |
17545 | modec = 0; // Replace invalid with current. |
17546 | } |
17547 | } else if (ui_rgb_attached()) { |
17548 | modec = 'g'; |
17549 | } else { |
17550 | modec = 'c'; |
17551 | } |
17552 | |
17553 | |
17554 | const char *p = NULL; |
17555 | switch (TOLOWER_ASC(what[0])) { |
17556 | case 'b': { |
17557 | if (TOLOWER_ASC(what[1]) == 'g') { // bg[#] |
17558 | p = highlight_color(id, what, modec); |
17559 | } else { // bold |
17560 | p = highlight_has_attr(id, HL_BOLD, modec); |
17561 | } |
17562 | break; |
17563 | } |
17564 | case 'f': { // fg[#] or font |
17565 | p = highlight_color(id, what, modec); |
17566 | break; |
17567 | } |
17568 | case 'i': { |
17569 | if (TOLOWER_ASC(what[1]) == 'n') { // inverse |
17570 | p = highlight_has_attr(id, HL_INVERSE, modec); |
17571 | } else { // italic |
17572 | p = highlight_has_attr(id, HL_ITALIC, modec); |
17573 | } |
17574 | break; |
17575 | } |
17576 | case 'n': { // name |
17577 | p = get_highlight_name_ext(NULL, id - 1, false); |
17578 | break; |
17579 | } |
17580 | case 'r': { // reverse |
17581 | p = highlight_has_attr(id, HL_INVERSE, modec); |
17582 | break; |
17583 | } |
17584 | case 's': { |
17585 | if (TOLOWER_ASC(what[1]) == 'p') { // sp[#] |
17586 | p = highlight_color(id, what, modec); |
17587 | } else if (TOLOWER_ASC(what[1]) == 't' |
17588 | && TOLOWER_ASC(what[2]) == 'r') { // strikethrough |
17589 | p = highlight_has_attr(id, HL_STRIKETHROUGH, modec); |
17590 | } else { // standout |
17591 | p = highlight_has_attr(id, HL_STANDOUT, modec); |
17592 | } |
17593 | break; |
17594 | } |
17595 | case 'u': { |
17596 | if (STRLEN(what) <= 5 || TOLOWER_ASC(what[5]) != 'c') { // underline |
17597 | p = highlight_has_attr(id, HL_UNDERLINE, modec); |
17598 | } else { // undercurl |
17599 | p = highlight_has_attr(id, HL_UNDERCURL, modec); |
17600 | } |
17601 | break; |
17602 | } |
17603 | } |
17604 | |
17605 | rettv->v_type = VAR_STRING; |
17606 | rettv->vval.v_string = (char_u *)(p == NULL ? p : xstrdup(p)); |
17607 | } |
17608 | |
17609 | /* |
17610 | * "synIDtrans(id)" function |
17611 | */ |
17612 | static void f_synIDtrans(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
17613 | { |
17614 | int id = tv_get_number(&argvars[0]); |
17615 | |
17616 | if (id > 0) { |
17617 | id = syn_get_final_id(id); |
17618 | } else { |
17619 | id = 0; |
17620 | } |
17621 | |
17622 | rettv->vval.v_number = id; |
17623 | } |
17624 | |
17625 | /* |
17626 | * "synconcealed(lnum, col)" function |
17627 | */ |
17628 | static void f_synconcealed(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
17629 | { |
17630 | int syntax_flags = 0; |
17631 | int cchar; |
17632 | int matchid = 0; |
17633 | char_u str[NUMBUFLEN]; |
17634 | |
17635 | tv_list_set_ret(rettv, NULL); |
17636 | |
17637 | // -1 on type error (both) |
17638 | const linenr_T lnum = tv_get_lnum(argvars); |
17639 | const colnr_T col = (colnr_T)tv_get_number(&argvars[1]) - 1; |
17640 | |
17641 | memset(str, NUL, sizeof(str)); |
17642 | |
17643 | if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count && col >= 0 |
17644 | && (size_t)col <= STRLEN(ml_get(lnum)) && curwin->w_p_cole > 0) { |
17645 | (void)syn_get_id(curwin, lnum, col, false, NULL, false); |
17646 | syntax_flags = get_syntax_info(&matchid); |
17647 | |
17648 | // get the conceal character |
17649 | if ((syntax_flags & HL_CONCEAL) && curwin->w_p_cole < 3) { |
17650 | cchar = syn_get_sub_char(); |
17651 | if (cchar == NUL && curwin->w_p_cole == 1) { |
17652 | cchar = (curwin->w_p_lcs_chars.conceal == NUL) |
17653 | ? ' ' |
17654 | : curwin->w_p_lcs_chars.conceal; |
17655 | } |
17656 | if (cchar != NUL) { |
17657 | utf_char2bytes(cchar, str); |
17658 | } |
17659 | } |
17660 | } |
17661 | |
17662 | tv_list_alloc_ret(rettv, 3); |
17663 | tv_list_append_number(rettv->vval.v_list, (syntax_flags & HL_CONCEAL) != 0); |
17664 | // -1 to auto-determine strlen |
17665 | tv_list_append_string(rettv->vval.v_list, (const char *)str, -1); |
17666 | tv_list_append_number(rettv->vval.v_list, matchid); |
17667 | } |
17668 | |
17669 | /* |
17670 | * "synstack(lnum, col)" function |
17671 | */ |
17672 | static void f_synstack(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
17673 | { |
17674 | tv_list_set_ret(rettv, NULL); |
17675 | |
17676 | // -1 on type error (both) |
17677 | const linenr_T lnum = tv_get_lnum(argvars); |
17678 | const colnr_T col = (colnr_T)tv_get_number(&argvars[1]) - 1; |
17679 | |
17680 | if (lnum >= 1 |
17681 | && lnum <= curbuf->b_ml.ml_line_count |
17682 | && col >= 0 |
17683 | && (size_t)col <= STRLEN(ml_get(lnum))) { |
17684 | tv_list_alloc_ret(rettv, kListLenMayKnow); |
17685 | (void)syn_get_id(curwin, lnum, col, false, NULL, true); |
17686 | |
17687 | int id; |
17688 | int i = 0; |
17689 | while ((id = syn_get_stack_item(i++)) >= 0) { |
17690 | tv_list_append_number(rettv->vval.v_list, id); |
17691 | } |
17692 | } |
17693 | } |
17694 | |
17695 | static list_T *string_to_list(const char *str, size_t len, const bool keepempty) |
17696 | { |
17697 | if (!keepempty && str[len - 1] == NL) { |
17698 | len--; |
17699 | } |
17700 | list_T *const list = tv_list_alloc(kListLenMayKnow); |
17701 | encode_list_write(list, str, len); |
17702 | return list; |
17703 | } |
17704 | |
17705 | // os_system wrapper. Handles 'verbose', :profile, and v:shell_error. |
17706 | static void get_system_output_as_rettv(typval_T *argvars, typval_T *rettv, |
17707 | bool retlist) |
17708 | { |
17709 | proftime_T wait_time; |
17710 | bool profiling = do_profiling == PROF_YES; |
17711 | |
17712 | rettv->v_type = VAR_STRING; |
17713 | rettv->vval.v_string = NULL; |
17714 | |
17715 | if (check_restricted() || check_secure()) { |
17716 | return; |
17717 | } |
17718 | |
17719 | // get input to the shell command (if any), and its length |
17720 | ptrdiff_t input_len; |
17721 | char *input = save_tv_as_string(&argvars[1], &input_len, false); |
17722 | if (input_len < 0) { |
17723 | assert(input == NULL); |
17724 | return; |
17725 | } |
17726 | |
17727 | // get shell command to execute |
17728 | bool executable = true; |
17729 | char **argv = tv_to_argv(&argvars[0], NULL, &executable); |
17730 | if (!argv) { |
17731 | if (!executable) { |
17732 | set_vim_var_nr(VV_SHELL_ERROR, (long)-1); |
17733 | } |
17734 | xfree(input); |
17735 | return; // Already did emsg. |
17736 | } |
17737 | |
17738 | if (p_verbose > 3) { |
17739 | char *cmdstr = shell_argv_to_str(argv); |
17740 | verbose_enter_scroll(); |
17741 | smsg(_("Executing command: \"%s\"" ), cmdstr); |
17742 | msg_puts("\n\n" ); |
17743 | verbose_leave_scroll(); |
17744 | xfree(cmdstr); |
17745 | } |
17746 | |
17747 | if (profiling) { |
17748 | prof_child_enter(&wait_time); |
17749 | } |
17750 | |
17751 | // execute the command |
17752 | size_t nread = 0; |
17753 | char *res = NULL; |
17754 | int status = os_system(argv, input, input_len, &res, &nread); |
17755 | |
17756 | if (profiling) { |
17757 | prof_child_exit(&wait_time); |
17758 | } |
17759 | |
17760 | xfree(input); |
17761 | |
17762 | set_vim_var_nr(VV_SHELL_ERROR, (long) status); |
17763 | |
17764 | if (res == NULL) { |
17765 | if (retlist) { |
17766 | // return an empty list when there's no output |
17767 | tv_list_alloc_ret(rettv, 0); |
17768 | } else { |
17769 | rettv->vval.v_string = (char_u *) xstrdup("" ); |
17770 | } |
17771 | return; |
17772 | } |
17773 | |
17774 | if (retlist) { |
17775 | int keepempty = 0; |
17776 | if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN) { |
17777 | keepempty = tv_get_number(&argvars[2]); |
17778 | } |
17779 | rettv->vval.v_list = string_to_list(res, nread, (bool)keepempty); |
17780 | tv_list_ref(rettv->vval.v_list); |
17781 | rettv->v_type = VAR_LIST; |
17782 | |
17783 | xfree(res); |
17784 | } else { |
17785 | // res may contain several NULs before the final terminating one. |
17786 | // Replace them with SOH (1) like in get_cmd_output() to avoid truncation. |
17787 | memchrsub(res, NUL, 1, nread); |
17788 | #ifdef USE_CRNL |
17789 | // translate <CR><NL> into <NL> |
17790 | char *d = res; |
17791 | for (char *s = res; *s; ++s) { |
17792 | if (s[0] == CAR && s[1] == NL) { |
17793 | ++s; |
17794 | } |
17795 | |
17796 | *d++ = *s; |
17797 | } |
17798 | |
17799 | *d = NUL; |
17800 | #endif |
17801 | rettv->vval.v_string = (char_u *) res; |
17802 | } |
17803 | } |
17804 | |
17805 | /// f_system - the VimL system() function |
17806 | static void f_system(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
17807 | { |
17808 | get_system_output_as_rettv(argvars, rettv, false); |
17809 | } |
17810 | |
17811 | static void f_systemlist(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
17812 | { |
17813 | get_system_output_as_rettv(argvars, rettv, true); |
17814 | } |
17815 | |
17816 | |
17817 | /* |
17818 | * "tabpagebuflist()" function |
17819 | */ |
17820 | static void f_tabpagebuflist(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
17821 | { |
17822 | win_T *wp = NULL; |
17823 | |
17824 | if (argvars[0].v_type == VAR_UNKNOWN) { |
17825 | wp = firstwin; |
17826 | } else { |
17827 | tabpage_T *const tp = find_tabpage((int)tv_get_number(&argvars[0])); |
17828 | if (tp != NULL) { |
17829 | wp = (tp == curtab) ? firstwin : tp->tp_firstwin; |
17830 | } |
17831 | } |
17832 | if (wp != NULL) { |
17833 | tv_list_alloc_ret(rettv, kListLenMayKnow); |
17834 | while (wp != NULL) { |
17835 | tv_list_append_number(rettv->vval.v_list, wp->w_buffer->b_fnum); |
17836 | wp = wp->w_next; |
17837 | } |
17838 | } |
17839 | } |
17840 | |
17841 | /* |
17842 | * "tabpagenr()" function |
17843 | */ |
17844 | static void f_tabpagenr(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
17845 | { |
17846 | int nr = 1; |
17847 | |
17848 | if (argvars[0].v_type != VAR_UNKNOWN) { |
17849 | const char *const arg = tv_get_string_chk(&argvars[0]); |
17850 | nr = 0; |
17851 | if (arg != NULL) { |
17852 | if (strcmp(arg, "$" ) == 0) { |
17853 | nr = tabpage_index(NULL) - 1; |
17854 | } else { |
17855 | EMSG2(_(e_invexpr2), arg); |
17856 | } |
17857 | } |
17858 | } else { |
17859 | nr = tabpage_index(curtab); |
17860 | } |
17861 | rettv->vval.v_number = nr; |
17862 | } |
17863 | |
17864 | |
17865 | |
17866 | /* |
17867 | * Common code for tabpagewinnr() and winnr(). |
17868 | */ |
17869 | static int get_winnr(tabpage_T *tp, typval_T *argvar) |
17870 | { |
17871 | win_T *twin; |
17872 | int nr = 1; |
17873 | win_T *wp; |
17874 | |
17875 | twin = (tp == curtab) ? curwin : tp->tp_curwin; |
17876 | if (argvar->v_type != VAR_UNKNOWN) { |
17877 | bool invalid_arg = false; |
17878 | const char *const arg = tv_get_string_chk(argvar); |
17879 | if (arg == NULL) { |
17880 | nr = 0; // Type error; errmsg already given. |
17881 | } else if (strcmp(arg, "$" ) == 0) { |
17882 | twin = (tp == curtab) ? lastwin : tp->tp_lastwin; |
17883 | } else if (strcmp(arg, "#" ) == 0) { |
17884 | twin = (tp == curtab) ? prevwin : tp->tp_prevwin; |
17885 | if (twin == NULL) { |
17886 | nr = 0; |
17887 | } |
17888 | } else { |
17889 | // Extract the window count (if specified). e.g. winnr('3j') |
17890 | char_u *endp; |
17891 | long count = strtol((char *)arg, (char **)&endp, 10); |
17892 | if (count <= 0) { |
17893 | // if count is not specified, default to 1 |
17894 | count = 1; |
17895 | } |
17896 | if (endp != NULL && *endp != '\0') { |
17897 | if (strequal((char *)endp, "j" )) { |
17898 | twin = win_vert_neighbor(tp, twin, false, count); |
17899 | } else if (strequal((char *)endp, "k" )) { |
17900 | twin = win_vert_neighbor(tp, twin, true, count); |
17901 | } else if (strequal((char *)endp, "h" )) { |
17902 | twin = win_horz_neighbor(tp, twin, true, count); |
17903 | } else if (strequal((char *)endp, "l" )) { |
17904 | twin = win_horz_neighbor(tp, twin, false, count); |
17905 | } else { |
17906 | invalid_arg = true; |
17907 | } |
17908 | } else { |
17909 | invalid_arg = true; |
17910 | } |
17911 | } |
17912 | |
17913 | if (invalid_arg) { |
17914 | EMSG2(_(e_invexpr2), arg); |
17915 | nr = 0; |
17916 | } |
17917 | } |
17918 | |
17919 | if (nr > 0) |
17920 | for (wp = (tp == curtab) ? firstwin : tp->tp_firstwin; |
17921 | wp != twin; wp = wp->w_next) { |
17922 | if (wp == NULL) { |
17923 | /* didn't find it in this tabpage */ |
17924 | nr = 0; |
17925 | break; |
17926 | } |
17927 | ++nr; |
17928 | } |
17929 | return nr; |
17930 | } |
17931 | |
17932 | /* |
17933 | * "tabpagewinnr()" function |
17934 | */ |
17935 | static void f_tabpagewinnr(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
17936 | { |
17937 | int nr = 1; |
17938 | tabpage_T *const tp = find_tabpage((int)tv_get_number(&argvars[0])); |
17939 | if (tp == NULL) { |
17940 | nr = 0; |
17941 | } else { |
17942 | nr = get_winnr(tp, &argvars[1]); |
17943 | } |
17944 | rettv->vval.v_number = nr; |
17945 | } |
17946 | |
17947 | /* |
17948 | * "tagfiles()" function |
17949 | */ |
17950 | static void f_tagfiles(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
17951 | { |
17952 | char *fname; |
17953 | tagname_T tn; |
17954 | |
17955 | tv_list_alloc_ret(rettv, kListLenUnknown); |
17956 | fname = xmalloc(MAXPATHL); |
17957 | |
17958 | bool first = true; |
17959 | while (get_tagfname(&tn, first, (char_u *)fname) == OK) { |
17960 | tv_list_append_string(rettv->vval.v_list, fname, -1); |
17961 | first = false; |
17962 | } |
17963 | |
17964 | tagname_free(&tn); |
17965 | xfree(fname); |
17966 | } |
17967 | |
17968 | /* |
17969 | * "taglist()" function |
17970 | */ |
17971 | static void f_taglist(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
17972 | { |
17973 | const char *const tag_pattern = tv_get_string(&argvars[0]); |
17974 | |
17975 | rettv->vval.v_number = false; |
17976 | if (*tag_pattern == NUL) { |
17977 | return; |
17978 | } |
17979 | |
17980 | const char *fname = NULL; |
17981 | if (argvars[1].v_type != VAR_UNKNOWN) { |
17982 | fname = tv_get_string(&argvars[1]); |
17983 | } |
17984 | (void)get_tags(tv_list_alloc_ret(rettv, kListLenUnknown), |
17985 | (char_u *)tag_pattern, (char_u *)fname); |
17986 | } |
17987 | |
17988 | /* |
17989 | * "tempname()" function |
17990 | */ |
17991 | static void f_tempname(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
17992 | { |
17993 | rettv->v_type = VAR_STRING; |
17994 | rettv->vval.v_string = vim_tempname(); |
17995 | } |
17996 | |
17997 | // "termopen(cmd[, cwd])" function |
17998 | static void f_termopen(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
17999 | { |
18000 | if (check_restricted() || check_secure()) { |
18001 | return; |
18002 | } |
18003 | |
18004 | if (curbuf->b_changed) { |
18005 | EMSG(_("Can only call this function in an unmodified buffer" )); |
18006 | return; |
18007 | } |
18008 | |
18009 | const char *cmd; |
18010 | bool executable = true; |
18011 | char **argv = tv_to_argv(&argvars[0], &cmd, &executable); |
18012 | if (!argv) { |
18013 | rettv->vval.v_number = executable ? 0 : -1; |
18014 | return; // Did error message in tv_to_argv. |
18015 | } |
18016 | |
18017 | if (argvars[1].v_type != VAR_DICT && argvars[1].v_type != VAR_UNKNOWN) { |
18018 | // Wrong argument type |
18019 | EMSG2(_(e_invarg2), "expected dictionary" ); |
18020 | shell_free_argv(argv); |
18021 | return; |
18022 | } |
18023 | |
18024 | CallbackReader on_stdout = CALLBACK_READER_INIT, |
18025 | on_stderr = CALLBACK_READER_INIT; |
18026 | Callback on_exit = CALLBACK_NONE; |
18027 | dict_T *job_opts = NULL; |
18028 | const char *cwd = "." ; |
18029 | if (argvars[1].v_type == VAR_DICT) { |
18030 | job_opts = argvars[1].vval.v_dict; |
18031 | |
18032 | const char *const new_cwd = tv_dict_get_string(job_opts, "cwd" , false); |
18033 | if (new_cwd && *new_cwd != NUL) { |
18034 | cwd = new_cwd; |
18035 | // The new cwd must be a directory. |
18036 | if (!os_isdir_executable((const char *)cwd)) { |
18037 | EMSG2(_(e_invarg2), "expected valid directory" ); |
18038 | shell_free_argv(argv); |
18039 | return; |
18040 | } |
18041 | } |
18042 | |
18043 | if (!common_job_callbacks(job_opts, &on_stdout, &on_stderr, &on_exit)) { |
18044 | shell_free_argv(argv); |
18045 | return; |
18046 | } |
18047 | } |
18048 | |
18049 | uint16_t term_width = MAX(0, curwin->w_width_inner - win_col_off(curwin)); |
18050 | Channel *chan = channel_job_start(argv, on_stdout, on_stderr, on_exit, |
18051 | true, false, false, cwd, |
18052 | term_width, curwin->w_height_inner, |
18053 | xstrdup("xterm-256color" ), |
18054 | &rettv->vval.v_number); |
18055 | if (rettv->vval.v_number <= 0) { |
18056 | return; |
18057 | } |
18058 | |
18059 | int pid = chan->stream.pty.process.pid; |
18060 | |
18061 | char buf[1024]; |
18062 | // format the title with the pid to conform with the term:// URI |
18063 | snprintf(buf, sizeof(buf), "term://%s//%d:%s" , cwd, pid, cmd); |
18064 | // at this point the buffer has no terminal instance associated yet, so unset |
18065 | // the 'swapfile' option to ensure no swap file will be created |
18066 | curbuf->b_p_swf = false; |
18067 | (void)setfname(curbuf, (char_u *)buf, NULL, true); |
18068 | // Save the job id and pid in b:terminal_job_{id,pid} |
18069 | Error err = ERROR_INIT; |
18070 | // deprecated: use 'channel' buffer option |
18071 | dict_set_var(curbuf->b_vars, cstr_as_string("terminal_job_id" ), |
18072 | INTEGER_OBJ(chan->id), false, false, &err); |
18073 | api_clear_error(&err); |
18074 | dict_set_var(curbuf->b_vars, cstr_as_string("terminal_job_pid" ), |
18075 | INTEGER_OBJ(pid), false, false, &err); |
18076 | api_clear_error(&err); |
18077 | |
18078 | channel_terminal_open(chan); |
18079 | channel_create_event(chan, NULL); |
18080 | } |
18081 | |
18082 | // "test_garbagecollect_now()" function |
18083 | static void f_test_garbagecollect_now(typval_T *argvars, |
18084 | typval_T *rettv, FunPtr fptr) |
18085 | { |
18086 | // This is dangerous, any Lists and Dicts used internally may be freed |
18087 | // while still in use. |
18088 | garbage_collect(true); |
18089 | } |
18090 | |
18091 | // "test_write_list_log()" function |
18092 | static void f_test_write_list_log(typval_T *const argvars, |
18093 | typval_T *const rettv, |
18094 | FunPtr fptr) |
18095 | { |
18096 | const char *const fname = tv_get_string_chk(&argvars[0]); |
18097 | if (fname == NULL) { |
18098 | return; |
18099 | } |
18100 | list_write_log(fname); |
18101 | } |
18102 | |
18103 | bool callback_from_typval(Callback *const callback, typval_T *const arg) |
18104 | FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT |
18105 | { |
18106 | if (arg->v_type == VAR_PARTIAL && arg->vval.v_partial != NULL) { |
18107 | callback->data.partial = arg->vval.v_partial; |
18108 | callback->data.partial->pt_refcount++; |
18109 | callback->type = kCallbackPartial; |
18110 | } else if (arg->v_type == VAR_FUNC || arg->v_type == VAR_STRING) { |
18111 | char_u *name = arg->vval.v_string; |
18112 | func_ref(name); |
18113 | callback->data.funcref = vim_strsave(name); |
18114 | callback->type = kCallbackFuncref; |
18115 | } else if (arg->v_type == VAR_NUMBER && arg->vval.v_number == 0) { |
18116 | callback->type = kCallbackNone; |
18117 | } else { |
18118 | EMSG(_("E921: Invalid callback argument" )); |
18119 | return false; |
18120 | } |
18121 | return true; |
18122 | } |
18123 | |
18124 | bool callback_call(Callback *const callback, const int argcount_in, |
18125 | typval_T *const argvars_in, typval_T *const rettv) |
18126 | FUNC_ATTR_NONNULL_ALL |
18127 | { |
18128 | partial_T *partial; |
18129 | char_u *name; |
18130 | switch (callback->type) { |
18131 | case kCallbackFuncref: |
18132 | name = callback->data.funcref; |
18133 | partial = NULL; |
18134 | break; |
18135 | |
18136 | case kCallbackPartial: |
18137 | partial = callback->data.partial; |
18138 | name = partial_name(partial); |
18139 | break; |
18140 | |
18141 | case kCallbackNone: |
18142 | return false; |
18143 | break; |
18144 | |
18145 | default: |
18146 | abort(); |
18147 | } |
18148 | |
18149 | int dummy; |
18150 | return call_func(name, (int)STRLEN(name), rettv, argcount_in, argvars_in, |
18151 | NULL, curwin->w_cursor.lnum, curwin->w_cursor.lnum, &dummy, |
18152 | true, partial, NULL); |
18153 | } |
18154 | |
18155 | static bool set_ref_in_callback(Callback *callback, int copyID, |
18156 | ht_stack_T **ht_stack, |
18157 | list_stack_T **list_stack) |
18158 | { |
18159 | typval_T tv; |
18160 | switch (callback->type) { |
18161 | case kCallbackFuncref: |
18162 | case kCallbackNone: |
18163 | break; |
18164 | |
18165 | case kCallbackPartial: |
18166 | tv.v_type = VAR_PARTIAL; |
18167 | tv.vval.v_partial = callback->data.partial; |
18168 | return set_ref_in_item(&tv, copyID, ht_stack, list_stack); |
18169 | break; |
18170 | |
18171 | |
18172 | default: |
18173 | abort(); |
18174 | } |
18175 | return false; |
18176 | } |
18177 | |
18178 | static bool set_ref_in_callback_reader(CallbackReader *reader, int copyID, |
18179 | ht_stack_T **ht_stack, |
18180 | list_stack_T **list_stack) |
18181 | { |
18182 | if (set_ref_in_callback(&reader->cb, copyID, ht_stack, list_stack)) { |
18183 | return true; |
18184 | } |
18185 | |
18186 | if (reader->self) { |
18187 | typval_T tv; |
18188 | tv.v_type = VAR_DICT; |
18189 | tv.vval.v_dict = reader->self; |
18190 | return set_ref_in_item(&tv, copyID, ht_stack, list_stack); |
18191 | } |
18192 | return false; |
18193 | } |
18194 | |
18195 | static void add_timer_info(typval_T *rettv, timer_T *timer) |
18196 | { |
18197 | list_T *list = rettv->vval.v_list; |
18198 | dict_T *dict = tv_dict_alloc(); |
18199 | |
18200 | tv_list_append_dict(list, dict); |
18201 | tv_dict_add_nr(dict, S_LEN("id" ), timer->timer_id); |
18202 | tv_dict_add_nr(dict, S_LEN("time" ), timer->timeout); |
18203 | tv_dict_add_nr(dict, S_LEN("paused" ), timer->paused); |
18204 | |
18205 | tv_dict_add_nr(dict, S_LEN("repeat" ), |
18206 | (timer->repeat_count < 0 ? -1 : timer->repeat_count)); |
18207 | |
18208 | dictitem_T *di = tv_dict_item_alloc("callback" ); |
18209 | if (tv_dict_add(dict, di) == FAIL) { |
18210 | xfree(di); |
18211 | return; |
18212 | } |
18213 | |
18214 | if (timer->callback.type == kCallbackPartial) { |
18215 | di->di_tv.v_type = VAR_PARTIAL; |
18216 | di->di_tv.vval.v_partial = timer->callback.data.partial; |
18217 | timer->callback.data.partial->pt_refcount++; |
18218 | } else if (timer->callback.type == kCallbackFuncref) { |
18219 | di->di_tv.v_type = VAR_FUNC; |
18220 | di->di_tv.vval.v_string = vim_strsave(timer->callback.data.funcref); |
18221 | } |
18222 | } |
18223 | |
18224 | static void add_timer_info_all(typval_T *rettv) |
18225 | { |
18226 | timer_T *timer; |
18227 | map_foreach_value(timers, timer, { |
18228 | if (!timer->stopped) { |
18229 | add_timer_info(rettv, timer); |
18230 | } |
18231 | }) |
18232 | } |
18233 | |
18234 | /// "timer_info([timer])" function |
18235 | static void f_timer_info(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
18236 | { |
18237 | tv_list_alloc_ret(rettv, (argvars[0].v_type != VAR_UNKNOWN |
18238 | ? 1 |
18239 | : timers->table->n_occupied)); |
18240 | if (argvars[0].v_type != VAR_UNKNOWN) { |
18241 | if (argvars[0].v_type != VAR_NUMBER) { |
18242 | EMSG(_(e_number_exp)); |
18243 | return; |
18244 | } |
18245 | timer_T *timer = pmap_get(uint64_t)(timers, tv_get_number(&argvars[0])); |
18246 | if (timer != NULL && !timer->stopped) { |
18247 | add_timer_info(rettv, timer); |
18248 | } |
18249 | } else { |
18250 | add_timer_info_all(rettv); |
18251 | } |
18252 | } |
18253 | |
18254 | /// "timer_pause(timer, paused)" function |
18255 | static void f_timer_pause(typval_T *argvars, typval_T *unused, FunPtr fptr) |
18256 | { |
18257 | if (argvars[0].v_type != VAR_NUMBER) { |
18258 | EMSG(_(e_number_exp)); |
18259 | return; |
18260 | } |
18261 | int paused = (bool)tv_get_number(&argvars[1]); |
18262 | timer_T *timer = pmap_get(uint64_t)(timers, tv_get_number(&argvars[0])); |
18263 | if (timer != NULL) { |
18264 | if (!timer->paused && paused) { |
18265 | time_watcher_stop(&timer->tw); |
18266 | } else if (timer->paused && !paused) { |
18267 | time_watcher_start(&timer->tw, timer_due_cb, timer->timeout, |
18268 | timer->timeout); |
18269 | } |
18270 | timer->paused = paused; |
18271 | } |
18272 | } |
18273 | |
18274 | /// "timer_start(timeout, callback, opts)" function |
18275 | static void f_timer_start(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
18276 | { |
18277 | const long timeout = tv_get_number(&argvars[0]); |
18278 | timer_T *timer; |
18279 | int repeat = 1; |
18280 | dict_T *dict; |
18281 | |
18282 | rettv->vval.v_number = -1; |
18283 | |
18284 | if (argvars[2].v_type != VAR_UNKNOWN) { |
18285 | if (argvars[2].v_type != VAR_DICT |
18286 | || (dict = argvars[2].vval.v_dict) == NULL) { |
18287 | EMSG2(_(e_invarg2), tv_get_string(&argvars[2])); |
18288 | return; |
18289 | } |
18290 | dictitem_T *const di = tv_dict_find(dict, S_LEN("repeat" )); |
18291 | if (di != NULL) { |
18292 | repeat = tv_get_number(&di->di_tv); |
18293 | if (repeat == 0) { |
18294 | repeat = 1; |
18295 | } |
18296 | } |
18297 | } |
18298 | |
18299 | Callback callback; |
18300 | if (!callback_from_typval(&callback, &argvars[1])) { |
18301 | return; |
18302 | } |
18303 | |
18304 | timer = xmalloc(sizeof *timer); |
18305 | timer->refcount = 1; |
18306 | timer->stopped = false; |
18307 | timer->paused = false; |
18308 | timer->emsg_count = 0; |
18309 | timer->repeat_count = repeat; |
18310 | timer->timeout = timeout; |
18311 | timer->timer_id = last_timer_id++; |
18312 | timer->callback = callback; |
18313 | |
18314 | time_watcher_init(&main_loop, &timer->tw, timer); |
18315 | timer->tw.events = multiqueue_new_child(main_loop.events); |
18316 | // if main loop is blocked, don't queue up multiple events |
18317 | timer->tw.blockable = true; |
18318 | time_watcher_start(&timer->tw, timer_due_cb, timeout, timeout); |
18319 | |
18320 | pmap_put(uint64_t)(timers, timer->timer_id, timer); |
18321 | rettv->vval.v_number = timer->timer_id; |
18322 | } |
18323 | |
18324 | |
18325 | // "timer_stop(timerid)" function |
18326 | static void f_timer_stop(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
18327 | { |
18328 | if (argvars[0].v_type != VAR_NUMBER) { |
18329 | EMSG(_(e_number_exp)); |
18330 | return; |
18331 | } |
18332 | |
18333 | timer_T *timer = pmap_get(uint64_t)(timers, tv_get_number(&argvars[0])); |
18334 | |
18335 | if (timer == NULL) { |
18336 | return; |
18337 | } |
18338 | |
18339 | timer_stop(timer); |
18340 | } |
18341 | |
18342 | static void f_timer_stopall(typval_T *argvars, typval_T *unused, FunPtr fptr) |
18343 | { |
18344 | timer_stop_all(); |
18345 | } |
18346 | |
18347 | // invoked on the main loop |
18348 | static void timer_due_cb(TimeWatcher *tw, void *data) |
18349 | { |
18350 | timer_T *timer = (timer_T *)data; |
18351 | int save_did_emsg = did_emsg; |
18352 | int save_called_emsg = called_emsg; |
18353 | |
18354 | if (timer->stopped || timer->paused) { |
18355 | return; |
18356 | } |
18357 | |
18358 | timer->refcount++; |
18359 | // if repeat was negative repeat forever |
18360 | if (timer->repeat_count >= 0 && --timer->repeat_count == 0) { |
18361 | timer_stop(timer); |
18362 | } |
18363 | |
18364 | typval_T argv[2] = { TV_INITIAL_VALUE, TV_INITIAL_VALUE }; |
18365 | argv[0].v_type = VAR_NUMBER; |
18366 | argv[0].vval.v_number = timer->timer_id; |
18367 | typval_T rettv = TV_INITIAL_VALUE; |
18368 | called_emsg = false; |
18369 | |
18370 | callback_call(&timer->callback, 1, argv, &rettv); |
18371 | |
18372 | // Handle error message |
18373 | if (called_emsg && did_emsg) { |
18374 | timer->emsg_count++; |
18375 | if (current_exception != NULL) { |
18376 | discard_current_exception(); |
18377 | } |
18378 | } |
18379 | did_emsg = save_did_emsg; |
18380 | called_emsg = save_called_emsg; |
18381 | |
18382 | if (timer->emsg_count >= 3) { |
18383 | timer_stop(timer); |
18384 | } |
18385 | |
18386 | tv_clear(&rettv); |
18387 | |
18388 | if (!timer->stopped && timer->timeout == 0) { |
18389 | // special case: timeout=0 means the callback will be |
18390 | // invoked again on the next event loop tick. |
18391 | // we don't use uv_idle_t to not spin the event loop |
18392 | // when the main loop is blocked. |
18393 | time_watcher_start(&timer->tw, timer_due_cb, 0, 0); |
18394 | } |
18395 | timer_decref(timer); |
18396 | } |
18397 | |
18398 | static void timer_stop(timer_T *timer) |
18399 | { |
18400 | if (timer->stopped) { |
18401 | // avoid double free |
18402 | return; |
18403 | } |
18404 | timer->stopped = true; |
18405 | time_watcher_stop(&timer->tw); |
18406 | time_watcher_close(&timer->tw, timer_close_cb); |
18407 | } |
18408 | |
18409 | // This will be run on the main loop after the last timer_due_cb, so at this |
18410 | // point it is safe to free the callback. |
18411 | static void timer_close_cb(TimeWatcher *tw, void *data) |
18412 | { |
18413 | timer_T *timer = (timer_T *)data; |
18414 | multiqueue_free(timer->tw.events); |
18415 | callback_free(&timer->callback); |
18416 | pmap_del(uint64_t)(timers, timer->timer_id); |
18417 | timer_decref(timer); |
18418 | } |
18419 | |
18420 | static void timer_decref(timer_T *timer) |
18421 | { |
18422 | if (--timer->refcount == 0) { |
18423 | xfree(timer); |
18424 | } |
18425 | } |
18426 | |
18427 | static void timer_stop_all(void) |
18428 | { |
18429 | timer_T *timer; |
18430 | map_foreach_value(timers, timer, { |
18431 | timer_stop(timer); |
18432 | }) |
18433 | } |
18434 | |
18435 | void timer_teardown(void) |
18436 | { |
18437 | timer_stop_all(); |
18438 | } |
18439 | |
18440 | /* |
18441 | * "tolower(string)" function |
18442 | */ |
18443 | static void f_tolower(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
18444 | { |
18445 | rettv->v_type = VAR_STRING; |
18446 | rettv->vval.v_string = (char_u *)strcase_save(tv_get_string(&argvars[0]), |
18447 | false); |
18448 | } |
18449 | |
18450 | /* |
18451 | * "toupper(string)" function |
18452 | */ |
18453 | static void f_toupper(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
18454 | { |
18455 | rettv->v_type = VAR_STRING; |
18456 | rettv->vval.v_string = (char_u *)strcase_save(tv_get_string(&argvars[0]), |
18457 | true); |
18458 | } |
18459 | |
18460 | /* |
18461 | * "tr(string, fromstr, tostr)" function |
18462 | */ |
18463 | static void f_tr(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
18464 | { |
18465 | char buf[NUMBUFLEN]; |
18466 | char buf2[NUMBUFLEN]; |
18467 | |
18468 | const char *in_str = tv_get_string(&argvars[0]); |
18469 | const char *fromstr = tv_get_string_buf_chk(&argvars[1], buf); |
18470 | const char *tostr = tv_get_string_buf_chk(&argvars[2], buf2); |
18471 | |
18472 | // Default return value: empty string. |
18473 | rettv->v_type = VAR_STRING; |
18474 | rettv->vval.v_string = NULL; |
18475 | if (fromstr == NULL || tostr == NULL) { |
18476 | return; // Type error; errmsg already given. |
18477 | } |
18478 | garray_T ga; |
18479 | ga_init(&ga, (int)sizeof(char), 80); |
18480 | |
18481 | if (!has_mbyte) { |
18482 | // Not multi-byte: fromstr and tostr must be the same length. |
18483 | if (strlen(fromstr) != strlen(tostr)) { |
18484 | goto error; |
18485 | } |
18486 | } |
18487 | |
18488 | // fromstr and tostr have to contain the same number of chars. |
18489 | bool first = true; |
18490 | while (*in_str != NUL) { |
18491 | if (has_mbyte) { |
18492 | const char *cpstr = in_str; |
18493 | const int inlen = (*mb_ptr2len)((const char_u *)in_str); |
18494 | int cplen = inlen; |
18495 | int idx = 0; |
18496 | int fromlen; |
18497 | for (const char *p = fromstr; *p != NUL; p += fromlen) { |
18498 | fromlen = (*mb_ptr2len)((const char_u *)p); |
18499 | if (fromlen == inlen && STRNCMP(in_str, p, inlen) == 0) { |
18500 | int tolen; |
18501 | for (p = tostr; *p != NUL; p += tolen) { |
18502 | tolen = (*mb_ptr2len)((const char_u *)p); |
18503 | if (idx-- == 0) { |
18504 | cplen = tolen; |
18505 | cpstr = (char *)p; |
18506 | break; |
18507 | } |
18508 | } |
18509 | if (*p == NUL) { // tostr is shorter than fromstr. |
18510 | goto error; |
18511 | } |
18512 | break; |
18513 | } |
18514 | idx++; |
18515 | } |
18516 | |
18517 | if (first && cpstr == in_str) { |
18518 | // Check that fromstr and tostr have the same number of |
18519 | // (multi-byte) characters. Done only once when a character |
18520 | // of in_str doesn't appear in fromstr. |
18521 | first = false; |
18522 | int tolen; |
18523 | for (const char *p = tostr; *p != NUL; p += tolen) { |
18524 | tolen = (*mb_ptr2len)((const char_u *)p); |
18525 | idx--; |
18526 | } |
18527 | if (idx != 0) { |
18528 | goto error; |
18529 | } |
18530 | } |
18531 | |
18532 | ga_grow(&ga, cplen); |
18533 | memmove((char *)ga.ga_data + ga.ga_len, cpstr, (size_t)cplen); |
18534 | ga.ga_len += cplen; |
18535 | |
18536 | in_str += inlen; |
18537 | } else { |
18538 | // When not using multi-byte chars we can do it faster. |
18539 | const char *const p = strchr(fromstr, *in_str); |
18540 | if (p != NULL) { |
18541 | ga_append(&ga, tostr[p - fromstr]); |
18542 | } else { |
18543 | ga_append(&ga, *in_str); |
18544 | } |
18545 | in_str++; |
18546 | } |
18547 | } |
18548 | |
18549 | // add a terminating NUL |
18550 | ga_append(&ga, NUL); |
18551 | |
18552 | rettv->vval.v_string = ga.ga_data; |
18553 | return; |
18554 | error: |
18555 | EMSG2(_(e_invarg2), fromstr); |
18556 | ga_clear(&ga); |
18557 | return; |
18558 | } |
18559 | |
18560 | // "trim({expr})" function |
18561 | static void f_trim(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
18562 | { |
18563 | char buf1[NUMBUFLEN]; |
18564 | char buf2[NUMBUFLEN]; |
18565 | const char_u *head = (const char_u *)tv_get_string_buf_chk(&argvars[0], buf1); |
18566 | const char_u *mask = NULL; |
18567 | const char_u *tail; |
18568 | const char_u *prev; |
18569 | const char_u *p; |
18570 | int c1; |
18571 | |
18572 | rettv->v_type = VAR_STRING; |
18573 | if (head == NULL) { |
18574 | rettv->vval.v_string = NULL; |
18575 | return; |
18576 | } |
18577 | |
18578 | if (argvars[1].v_type == VAR_STRING) { |
18579 | mask = (const char_u *)tv_get_string_buf_chk(&argvars[1], buf2); |
18580 | } |
18581 | |
18582 | while (*head != NUL) { |
18583 | c1 = PTR2CHAR(head); |
18584 | if (mask == NULL) { |
18585 | if (c1 > ' ' && c1 != 0xa0) { |
18586 | break; |
18587 | } |
18588 | } else { |
18589 | for (p = mask; *p != NUL; MB_PTR_ADV(p)) { |
18590 | if (c1 == PTR2CHAR(p)) { |
18591 | break; |
18592 | } |
18593 | } |
18594 | if (*p == NUL) { |
18595 | break; |
18596 | } |
18597 | } |
18598 | MB_PTR_ADV(head); |
18599 | } |
18600 | |
18601 | for (tail = head + STRLEN(head); tail > head; tail = prev) { |
18602 | prev = tail; |
18603 | MB_PTR_BACK(head, prev); |
18604 | c1 = PTR2CHAR(prev); |
18605 | if (mask == NULL) { |
18606 | if (c1 > ' ' && c1 != 0xa0) { |
18607 | break; |
18608 | } |
18609 | } else { |
18610 | for (p = mask; *p != NUL; MB_PTR_ADV(p)) { |
18611 | if (c1 == PTR2CHAR(p)) { |
18612 | break; |
18613 | } |
18614 | } |
18615 | if (*p == NUL) { |
18616 | break; |
18617 | } |
18618 | } |
18619 | } |
18620 | rettv->vval.v_string = vim_strnsave(head, (int)(tail - head)); |
18621 | } |
18622 | |
18623 | /* |
18624 | * "type(expr)" function |
18625 | */ |
18626 | static void f_type(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
18627 | { |
18628 | int n = -1; |
18629 | |
18630 | switch (argvars[0].v_type) { |
18631 | case VAR_NUMBER: n = VAR_TYPE_NUMBER; break; |
18632 | case VAR_STRING: n = VAR_TYPE_STRING; break; |
18633 | case VAR_PARTIAL: |
18634 | case VAR_FUNC: n = VAR_TYPE_FUNC; break; |
18635 | case VAR_LIST: n = VAR_TYPE_LIST; break; |
18636 | case VAR_DICT: n = VAR_TYPE_DICT; break; |
18637 | case VAR_FLOAT: n = VAR_TYPE_FLOAT; break; |
18638 | case VAR_SPECIAL: { |
18639 | switch (argvars[0].vval.v_special) { |
18640 | case kSpecialVarTrue: |
18641 | case kSpecialVarFalse: { |
18642 | n = VAR_TYPE_BOOL; |
18643 | break; |
18644 | } |
18645 | case kSpecialVarNull: { |
18646 | n = 7; |
18647 | break; |
18648 | } |
18649 | } |
18650 | break; |
18651 | } |
18652 | case VAR_UNKNOWN: { |
18653 | internal_error("f_type(UNKNOWN)" ); |
18654 | break; |
18655 | } |
18656 | } |
18657 | rettv->vval.v_number = n; |
18658 | } |
18659 | |
18660 | /* |
18661 | * "undofile(name)" function |
18662 | */ |
18663 | static void f_undofile(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
18664 | { |
18665 | rettv->v_type = VAR_STRING; |
18666 | const char *const fname = tv_get_string(&argvars[0]); |
18667 | |
18668 | if (*fname == NUL) { |
18669 | // If there is no file name there will be no undo file. |
18670 | rettv->vval.v_string = NULL; |
18671 | } else { |
18672 | char *ffname = FullName_save(fname, true); |
18673 | |
18674 | if (ffname != NULL) { |
18675 | rettv->vval.v_string = (char_u *)u_get_undo_file_name(ffname, false); |
18676 | } |
18677 | xfree(ffname); |
18678 | } |
18679 | } |
18680 | |
18681 | /* |
18682 | * "undotree()" function |
18683 | */ |
18684 | static void f_undotree(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
18685 | { |
18686 | tv_dict_alloc_ret(rettv); |
18687 | |
18688 | dict_T *dict = rettv->vval.v_dict; |
18689 | |
18690 | tv_dict_add_nr(dict, S_LEN("synced" ), (varnumber_T)curbuf->b_u_synced); |
18691 | tv_dict_add_nr(dict, S_LEN("seq_last" ), (varnumber_T)curbuf->b_u_seq_last); |
18692 | tv_dict_add_nr(dict, S_LEN("save_last" ), |
18693 | (varnumber_T)curbuf->b_u_save_nr_last); |
18694 | tv_dict_add_nr(dict, S_LEN("seq_cur" ), (varnumber_T)curbuf->b_u_seq_cur); |
18695 | tv_dict_add_nr(dict, S_LEN("time_cur" ), (varnumber_T)curbuf->b_u_time_cur); |
18696 | tv_dict_add_nr(dict, S_LEN("save_cur" ), (varnumber_T)curbuf->b_u_save_nr_cur); |
18697 | |
18698 | tv_dict_add_list(dict, S_LEN("entries" ), u_eval_tree(curbuf->b_u_oldhead)); |
18699 | } |
18700 | |
18701 | /* |
18702 | * "values(dict)" function |
18703 | */ |
18704 | static void f_values(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
18705 | { |
18706 | dict_list(argvars, rettv, 1); |
18707 | } |
18708 | |
18709 | /* |
18710 | * "virtcol(string)" function |
18711 | */ |
18712 | static void f_virtcol(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
18713 | { |
18714 | colnr_T vcol = 0; |
18715 | pos_T *fp; |
18716 | int fnum = curbuf->b_fnum; |
18717 | |
18718 | fp = var2fpos(&argvars[0], FALSE, &fnum); |
18719 | if (fp != NULL && fp->lnum <= curbuf->b_ml.ml_line_count |
18720 | && fnum == curbuf->b_fnum) { |
18721 | getvvcol(curwin, fp, NULL, NULL, &vcol); |
18722 | ++vcol; |
18723 | } |
18724 | |
18725 | rettv->vval.v_number = vcol; |
18726 | } |
18727 | |
18728 | /* |
18729 | * "visualmode()" function |
18730 | */ |
18731 | static void f_visualmode(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
18732 | { |
18733 | char_u str[2]; |
18734 | |
18735 | rettv->v_type = VAR_STRING; |
18736 | str[0] = curbuf->b_visual_mode_eval; |
18737 | str[1] = NUL; |
18738 | rettv->vval.v_string = vim_strsave(str); |
18739 | |
18740 | /* A non-zero number or non-empty string argument: reset mode. */ |
18741 | if (non_zero_arg(&argvars[0])) |
18742 | curbuf->b_visual_mode_eval = NUL; |
18743 | } |
18744 | |
18745 | /* |
18746 | * "wildmenumode()" function |
18747 | */ |
18748 | static void (typval_T *argvars, typval_T *rettv, FunPtr fptr) |
18749 | { |
18750 | if (wild_menu_showing) |
18751 | rettv->vval.v_number = 1; |
18752 | } |
18753 | |
18754 | /// "win_findbuf()" function |
18755 | static void f_win_findbuf(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
18756 | { |
18757 | tv_list_alloc_ret(rettv, kListLenMayKnow); |
18758 | win_findbuf(argvars, rettv->vval.v_list); |
18759 | } |
18760 | |
18761 | /// "win_getid()" function |
18762 | static void f_win_getid(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
18763 | { |
18764 | rettv->vval.v_number = win_getid(argvars); |
18765 | } |
18766 | |
18767 | /// "win_gotoid()" function |
18768 | static void f_win_gotoid(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
18769 | { |
18770 | rettv->vval.v_number = win_gotoid(argvars); |
18771 | } |
18772 | |
18773 | /// "win_id2tabwin()" function |
18774 | static void f_win_id2tabwin(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
18775 | { |
18776 | win_id2tabwin(argvars, rettv); |
18777 | } |
18778 | |
18779 | /// "win_id2win()" function |
18780 | static void f_win_id2win(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
18781 | { |
18782 | rettv->vval.v_number = win_id2win(argvars); |
18783 | } |
18784 | |
18785 | /// "winbufnr(nr)" function |
18786 | static void f_winbufnr(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
18787 | { |
18788 | win_T *wp = find_win_by_nr_or_id(&argvars[0]); |
18789 | if (wp == NULL) { |
18790 | rettv->vval.v_number = -1; |
18791 | } else { |
18792 | rettv->vval.v_number = wp->w_buffer->b_fnum; |
18793 | } |
18794 | } |
18795 | |
18796 | /* |
18797 | * "wincol()" function |
18798 | */ |
18799 | static void f_wincol(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
18800 | { |
18801 | validate_cursor(); |
18802 | rettv->vval.v_number = curwin->w_wcol + 1; |
18803 | } |
18804 | |
18805 | /// "winheight(nr)" function |
18806 | static void f_winheight(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
18807 | { |
18808 | win_T *wp = find_win_by_nr_or_id(&argvars[0]); |
18809 | if (wp == NULL) { |
18810 | rettv->vval.v_number = -1; |
18811 | } else { |
18812 | rettv->vval.v_number = wp->w_height; |
18813 | } |
18814 | } |
18815 | |
18816 | // "winlayout()" function |
18817 | static void f_winlayout(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
18818 | { |
18819 | tabpage_T *tp; |
18820 | |
18821 | tv_list_alloc_ret(rettv, 2); |
18822 | |
18823 | if (argvars[0].v_type == VAR_UNKNOWN) { |
18824 | tp = curtab; |
18825 | } else { |
18826 | tp = find_tabpage((int)tv_get_number(&argvars[0])); |
18827 | if (tp == NULL) { |
18828 | return; |
18829 | } |
18830 | } |
18831 | |
18832 | get_framelayout(tp->tp_topframe, rettv->vval.v_list, true); |
18833 | } |
18834 | |
18835 | /* |
18836 | * "winline()" function |
18837 | */ |
18838 | static void f_winline(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
18839 | { |
18840 | validate_cursor(); |
18841 | rettv->vval.v_number = curwin->w_wrow + 1; |
18842 | } |
18843 | |
18844 | /* |
18845 | * "winnr()" function |
18846 | */ |
18847 | static void f_winnr(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
18848 | { |
18849 | int nr = 1; |
18850 | |
18851 | nr = get_winnr(curtab, &argvars[0]); |
18852 | rettv->vval.v_number = nr; |
18853 | } |
18854 | |
18855 | /* |
18856 | * "winrestcmd()" function |
18857 | */ |
18858 | static void f_winrestcmd(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
18859 | { |
18860 | int winnr = 1; |
18861 | garray_T ga; |
18862 | char_u buf[50]; |
18863 | |
18864 | ga_init(&ga, (int)sizeof(char), 70); |
18865 | FOR_ALL_WINDOWS_IN_TAB(wp, curtab) { |
18866 | sprintf((char *)buf, "%dresize %d|" , winnr, wp->w_height); |
18867 | ga_concat(&ga, buf); |
18868 | sprintf((char *)buf, "vert %dresize %d|" , winnr, wp->w_width); |
18869 | ga_concat(&ga, buf); |
18870 | ++winnr; |
18871 | } |
18872 | ga_append(&ga, NUL); |
18873 | |
18874 | rettv->vval.v_string = ga.ga_data; |
18875 | rettv->v_type = VAR_STRING; |
18876 | } |
18877 | |
18878 | /* |
18879 | * "winrestview()" function |
18880 | */ |
18881 | static void f_winrestview(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
18882 | { |
18883 | dict_T *dict; |
18884 | |
18885 | if (argvars[0].v_type != VAR_DICT |
18886 | || (dict = argvars[0].vval.v_dict) == NULL) { |
18887 | EMSG(_(e_invarg)); |
18888 | } else { |
18889 | dictitem_T *di; |
18890 | if ((di = tv_dict_find(dict, S_LEN("lnum" ))) != NULL) { |
18891 | curwin->w_cursor.lnum = tv_get_number(&di->di_tv); |
18892 | } |
18893 | if ((di = tv_dict_find(dict, S_LEN("col" ))) != NULL) { |
18894 | curwin->w_cursor.col = tv_get_number(&di->di_tv); |
18895 | } |
18896 | if ((di = tv_dict_find(dict, S_LEN("coladd" ))) != NULL) { |
18897 | curwin->w_cursor.coladd = tv_get_number(&di->di_tv); |
18898 | } |
18899 | if ((di = tv_dict_find(dict, S_LEN("curswant" ))) != NULL) { |
18900 | curwin->w_curswant = tv_get_number(&di->di_tv); |
18901 | curwin->w_set_curswant = false; |
18902 | } |
18903 | if ((di = tv_dict_find(dict, S_LEN("topline" ))) != NULL) { |
18904 | set_topline(curwin, tv_get_number(&di->di_tv)); |
18905 | } |
18906 | if ((di = tv_dict_find(dict, S_LEN("topfill" ))) != NULL) { |
18907 | curwin->w_topfill = tv_get_number(&di->di_tv); |
18908 | } |
18909 | if ((di = tv_dict_find(dict, S_LEN("leftcol" ))) != NULL) { |
18910 | curwin->w_leftcol = tv_get_number(&di->di_tv); |
18911 | } |
18912 | if ((di = tv_dict_find(dict, S_LEN("skipcol" ))) != NULL) { |
18913 | curwin->w_skipcol = tv_get_number(&di->di_tv); |
18914 | } |
18915 | |
18916 | check_cursor(); |
18917 | win_new_height(curwin, curwin->w_height); |
18918 | win_new_width(curwin, curwin->w_width); |
18919 | changed_window_setting(); |
18920 | |
18921 | if (curwin->w_topline <= 0) |
18922 | curwin->w_topline = 1; |
18923 | if (curwin->w_topline > curbuf->b_ml.ml_line_count) |
18924 | curwin->w_topline = curbuf->b_ml.ml_line_count; |
18925 | check_topfill(curwin, true); |
18926 | } |
18927 | } |
18928 | |
18929 | /* |
18930 | * "winsaveview()" function |
18931 | */ |
18932 | static void f_winsaveview(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
18933 | { |
18934 | dict_T *dict; |
18935 | |
18936 | tv_dict_alloc_ret(rettv); |
18937 | dict = rettv->vval.v_dict; |
18938 | |
18939 | tv_dict_add_nr(dict, S_LEN("lnum" ), (varnumber_T)curwin->w_cursor.lnum); |
18940 | tv_dict_add_nr(dict, S_LEN("col" ), (varnumber_T)curwin->w_cursor.col); |
18941 | tv_dict_add_nr(dict, S_LEN("coladd" ), (varnumber_T)curwin->w_cursor.coladd); |
18942 | update_curswant(); |
18943 | tv_dict_add_nr(dict, S_LEN("curswant" ), (varnumber_T)curwin->w_curswant); |
18944 | |
18945 | tv_dict_add_nr(dict, S_LEN("topline" ), (varnumber_T)curwin->w_topline); |
18946 | tv_dict_add_nr(dict, S_LEN("topfill" ), (varnumber_T)curwin->w_topfill); |
18947 | tv_dict_add_nr(dict, S_LEN("leftcol" ), (varnumber_T)curwin->w_leftcol); |
18948 | tv_dict_add_nr(dict, S_LEN("skipcol" ), (varnumber_T)curwin->w_skipcol); |
18949 | } |
18950 | |
18951 | /// Write "list" of strings to file "fd". |
18952 | /// |
18953 | /// @param fp File to write to. |
18954 | /// @param[in] list List to write. |
18955 | /// @param[in] binary Whether to write in binary mode. |
18956 | /// |
18957 | /// @return true in case of success, false otherwise. |
18958 | static bool write_list(FileDescriptor *const fp, const list_T *const list, |
18959 | const bool binary) |
18960 | FUNC_ATTR_NONNULL_ARG(1) |
18961 | { |
18962 | int error = 0; |
18963 | TV_LIST_ITER_CONST(list, li, { |
18964 | const char *const s = tv_get_string_chk(TV_LIST_ITEM_TV(li)); |
18965 | if (s == NULL) { |
18966 | return false; |
18967 | } |
18968 | const char *hunk_start = s; |
18969 | for (const char *p = hunk_start;; p++) { |
18970 | if (*p == NUL || *p == NL) { |
18971 | if (p != hunk_start) { |
18972 | const ptrdiff_t written = file_write(fp, hunk_start, |
18973 | (size_t)(p - hunk_start)); |
18974 | if (written < 0) { |
18975 | error = (int)written; |
18976 | goto write_list_error; |
18977 | } |
18978 | } |
18979 | if (*p == NUL) { |
18980 | break; |
18981 | } else { |
18982 | hunk_start = p + 1; |
18983 | const ptrdiff_t written = file_write(fp, (char[]){ NUL }, 1); |
18984 | if (written < 0) { |
18985 | error = (int)written; |
18986 | break; |
18987 | } |
18988 | } |
18989 | } |
18990 | } |
18991 | if (!binary || TV_LIST_ITEM_NEXT(list, li) != NULL) { |
18992 | const ptrdiff_t written = file_write(fp, "\n" , 1); |
18993 | if (written < 0) { |
18994 | error = (int)written; |
18995 | goto write_list_error; |
18996 | } |
18997 | } |
18998 | }); |
18999 | if ((error = file_flush(fp)) != 0) { |
19000 | goto write_list_error; |
19001 | } |
19002 | return true; |
19003 | write_list_error: |
19004 | emsgf(_("E80: Error while writing: %s" ), os_strerror(error)); |
19005 | return false; |
19006 | } |
19007 | |
19008 | /// Saves a typval_T as a string. |
19009 | /// |
19010 | /// For lists or buffers, replaces NLs with NUL and separates items with NLs. |
19011 | /// |
19012 | /// @param[in] tv Value to store as a string. |
19013 | /// @param[out] len Length of the resulting string or -1 on error. |
19014 | /// @param[in] endnl If true, the output will end in a newline (if a list). |
19015 | /// @returns an allocated string if `tv` represents a VimL string, list, or |
19016 | /// number; NULL otherwise. |
19017 | static char *save_tv_as_string(typval_T *tv, ptrdiff_t *const len, bool endnl) |
19018 | FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_ALL |
19019 | { |
19020 | *len = 0; |
19021 | if (tv->v_type == VAR_UNKNOWN) { |
19022 | return NULL; |
19023 | } |
19024 | |
19025 | // For other types, let tv_get_string_buf_chk() get the value or |
19026 | // print an error. |
19027 | if (tv->v_type != VAR_LIST && tv->v_type != VAR_NUMBER) { |
19028 | const char *ret = tv_get_string_chk(tv); |
19029 | if (ret) { |
19030 | *len = strlen(ret); |
19031 | return xmemdupz(ret, (size_t)(*len)); |
19032 | } else { |
19033 | *len = -1; |
19034 | return NULL; |
19035 | } |
19036 | } |
19037 | |
19038 | if (tv->v_type == VAR_NUMBER) { // Treat number as a buffer-id. |
19039 | buf_T *buf = buflist_findnr(tv->vval.v_number); |
19040 | if (buf) { |
19041 | for (linenr_T lnum = 1; lnum <= buf->b_ml.ml_line_count; lnum++) { |
19042 | for (char_u *p = ml_get_buf(buf, lnum, false); *p != NUL; p++) { |
19043 | *len += 1; |
19044 | } |
19045 | *len += 1; |
19046 | } |
19047 | } else { |
19048 | EMSGN(_(e_nobufnr), tv->vval.v_number); |
19049 | *len = -1; |
19050 | return NULL; |
19051 | } |
19052 | |
19053 | if (*len == 0) { |
19054 | return NULL; |
19055 | } |
19056 | |
19057 | char *ret = xmalloc(*len + 1); |
19058 | char *end = ret; |
19059 | for (linenr_T lnum = 1; lnum <= buf->b_ml.ml_line_count; lnum++) { |
19060 | for (char_u *p = ml_get_buf(buf, lnum, false); *p != NUL; p++) { |
19061 | *end++ = (*p == '\n') ? NUL : *p; |
19062 | } |
19063 | *end++ = '\n'; |
19064 | } |
19065 | *end = NUL; |
19066 | *len = end - ret; |
19067 | return ret; |
19068 | } |
19069 | |
19070 | assert(tv->v_type == VAR_LIST); |
19071 | // Pre-calculate the resulting length. |
19072 | list_T *list = tv->vval.v_list; |
19073 | TV_LIST_ITER_CONST(list, li, { |
19074 | *len += strlen(tv_get_string(TV_LIST_ITEM_TV(li))) + 1; |
19075 | }); |
19076 | |
19077 | if (*len == 0) { |
19078 | return NULL; |
19079 | } |
19080 | |
19081 | char *ret = xmalloc(*len + endnl); |
19082 | char *end = ret; |
19083 | TV_LIST_ITER_CONST(list, li, { |
19084 | for (const char *s = tv_get_string(TV_LIST_ITEM_TV(li)); *s != NUL; s++) { |
19085 | *end++ = (*s == '\n') ? NUL : *s; |
19086 | } |
19087 | if (endnl || TV_LIST_ITEM_NEXT(list, li) != NULL) { |
19088 | *end++ = '\n'; |
19089 | } |
19090 | }); |
19091 | *end = NUL; |
19092 | *len = end - ret; |
19093 | return ret; |
19094 | } |
19095 | |
19096 | /// "winwidth(nr)" function |
19097 | static void f_winwidth(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
19098 | { |
19099 | win_T *wp = find_win_by_nr_or_id(&argvars[0]); |
19100 | if (wp == NULL) { |
19101 | rettv->vval.v_number = -1; |
19102 | } else { |
19103 | rettv->vval.v_number = wp->w_width; |
19104 | } |
19105 | } |
19106 | |
19107 | /// "wordcount()" function |
19108 | static void f_wordcount(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
19109 | { |
19110 | tv_dict_alloc_ret(rettv); |
19111 | cursor_pos_info(rettv->vval.v_dict); |
19112 | } |
19113 | |
19114 | /// "writefile()" function |
19115 | static void f_writefile(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
19116 | { |
19117 | rettv->vval.v_number = -1; |
19118 | |
19119 | if (check_restricted() || check_secure()) { |
19120 | return; |
19121 | } |
19122 | |
19123 | if (argvars[0].v_type != VAR_LIST) { |
19124 | EMSG2(_(e_listarg), "writefile()" ); |
19125 | return; |
19126 | } |
19127 | const list_T *const list = argvars[0].vval.v_list; |
19128 | TV_LIST_ITER_CONST(list, li, { |
19129 | if (!tv_check_str_or_nr(TV_LIST_ITEM_TV(li))) { |
19130 | return; |
19131 | } |
19132 | }); |
19133 | |
19134 | bool binary = false; |
19135 | bool append = false; |
19136 | bool do_fsync = !!p_fs; |
19137 | if (argvars[2].v_type != VAR_UNKNOWN) { |
19138 | const char *const flags = tv_get_string_chk(&argvars[2]); |
19139 | if (flags == NULL) { |
19140 | return; |
19141 | } |
19142 | for (const char *p = flags; *p; p++) { |
19143 | switch (*p) { |
19144 | case 'b': { binary = true; break; } |
19145 | case 'a': { append = true; break; } |
19146 | case 's': { do_fsync = true; break; } |
19147 | case 'S': { do_fsync = false; break; } |
19148 | default: { |
19149 | // Using %s, p and not %c, *p to preserve multibyte characters |
19150 | emsgf(_("E5060: Unknown flag: %s" ), p); |
19151 | return; |
19152 | } |
19153 | } |
19154 | } |
19155 | } |
19156 | |
19157 | char buf[NUMBUFLEN]; |
19158 | const char *const fname = tv_get_string_buf_chk(&argvars[1], buf); |
19159 | if (fname == NULL) { |
19160 | return; |
19161 | } |
19162 | FileDescriptor fp; |
19163 | int error; |
19164 | if (*fname == NUL) { |
19165 | EMSG(_("E482: Can't open file with an empty name" )); |
19166 | } else if ((error = file_open(&fp, fname, |
19167 | ((append ? kFileAppend : kFileTruncate) |
19168 | | kFileCreate), 0666)) != 0) { |
19169 | emsgf(_("E482: Can't open file %s for writing: %s" ), |
19170 | fname, os_strerror(error)); |
19171 | } else { |
19172 | if (write_list(&fp, list, binary)) { |
19173 | rettv->vval.v_number = 0; |
19174 | } |
19175 | if ((error = file_close(&fp, do_fsync)) != 0) { |
19176 | emsgf(_("E80: Error when closing file %s: %s" ), |
19177 | fname, os_strerror(error)); |
19178 | } |
19179 | } |
19180 | } |
19181 | /* |
19182 | * "xor(expr, expr)" function |
19183 | */ |
19184 | static void f_xor(typval_T *argvars, typval_T *rettv, FunPtr fptr) |
19185 | { |
19186 | rettv->vval.v_number = tv_get_number_chk(&argvars[0], NULL) |
19187 | ^ tv_get_number_chk(&argvars[1], NULL); |
19188 | } |
19189 | |
19190 | |
19191 | /// Translate a VimL object into a position |
19192 | /// |
19193 | /// Accepts VAR_LIST and VAR_STRING objects. Does not give an error for invalid |
19194 | /// type. |
19195 | /// |
19196 | /// @param[in] tv Object to translate. |
19197 | /// @param[in] dollar_lnum True when "$" is last line. |
19198 | /// @param[out] ret_fnum Set to fnum for marks. |
19199 | /// |
19200 | /// @return Pointer to position or NULL in case of error (e.g. invalid type). |
19201 | pos_T *var2fpos(const typval_T *const tv, const int dollar_lnum, |
19202 | int *const ret_fnum) |
19203 | FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL |
19204 | { |
19205 | static pos_T pos; |
19206 | pos_T *pp; |
19207 | |
19208 | // Argument can be [lnum, col, coladd]. |
19209 | if (tv->v_type == VAR_LIST) { |
19210 | list_T *l; |
19211 | int len; |
19212 | bool error = false; |
19213 | listitem_T *li; |
19214 | |
19215 | l = tv->vval.v_list; |
19216 | if (l == NULL) { |
19217 | return NULL; |
19218 | } |
19219 | |
19220 | // Get the line number. |
19221 | pos.lnum = tv_list_find_nr(l, 0L, &error); |
19222 | if (error || pos.lnum <= 0 || pos.lnum > curbuf->b_ml.ml_line_count) { |
19223 | // Invalid line number. |
19224 | return NULL; |
19225 | } |
19226 | |
19227 | // Get the column number. |
19228 | pos.col = tv_list_find_nr(l, 1L, &error); |
19229 | if (error) { |
19230 | return NULL; |
19231 | } |
19232 | len = (long)STRLEN(ml_get(pos.lnum)); |
19233 | |
19234 | // We accept "$" for the column number: last column. |
19235 | li = tv_list_find(l, 1L); |
19236 | if (li != NULL && TV_LIST_ITEM_TV(li)->v_type == VAR_STRING |
19237 | && TV_LIST_ITEM_TV(li)->vval.v_string != NULL |
19238 | && STRCMP(TV_LIST_ITEM_TV(li)->vval.v_string, "$" ) == 0) { |
19239 | pos.col = len + 1; |
19240 | } |
19241 | |
19242 | // Accept a position up to the NUL after the line. |
19243 | if (pos.col == 0 || (int)pos.col > len + 1) { |
19244 | // Invalid column number. |
19245 | return NULL; |
19246 | } |
19247 | pos.col--; |
19248 | |
19249 | // Get the virtual offset. Defaults to zero. |
19250 | pos.coladd = tv_list_find_nr(l, 2L, &error); |
19251 | if (error) { |
19252 | pos.coladd = 0; |
19253 | } |
19254 | |
19255 | return &pos; |
19256 | } |
19257 | |
19258 | const char *const name = tv_get_string_chk(tv); |
19259 | if (name == NULL) { |
19260 | return NULL; |
19261 | } |
19262 | if (name[0] == '.') { // Cursor. |
19263 | return &curwin->w_cursor; |
19264 | } |
19265 | if (name[0] == 'v' && name[1] == NUL) { // Visual start. |
19266 | if (VIsual_active) { |
19267 | return &VIsual; |
19268 | } |
19269 | return &curwin->w_cursor; |
19270 | } |
19271 | if (name[0] == '\'') { // Mark. |
19272 | pp = getmark_buf_fnum(curbuf, (uint8_t)name[1], false, ret_fnum); |
19273 | if (pp == NULL || pp == (pos_T *)-1 || pp->lnum <= 0) { |
19274 | return NULL; |
19275 | } |
19276 | return pp; |
19277 | } |
19278 | |
19279 | pos.coladd = 0; |
19280 | |
19281 | if (name[0] == 'w' && dollar_lnum) { |
19282 | pos.col = 0; |
19283 | if (name[1] == '0') { /* "w0": first visible line */ |
19284 | update_topline(); |
19285 | // In silent Ex mode topline is zero, but that's not a valid line |
19286 | // number; use one instead. |
19287 | pos.lnum = curwin->w_topline > 0 ? curwin->w_topline : 1; |
19288 | return &pos; |
19289 | } else if (name[1] == '$') { /* "w$": last visible line */ |
19290 | validate_botline(); |
19291 | // In silent Ex mode botline is zero, return zero then. |
19292 | pos.lnum = curwin->w_botline > 0 ? curwin->w_botline - 1 : 0; |
19293 | return &pos; |
19294 | } |
19295 | } else if (name[0] == '$') { /* last column or line */ |
19296 | if (dollar_lnum) { |
19297 | pos.lnum = curbuf->b_ml.ml_line_count; |
19298 | pos.col = 0; |
19299 | } else { |
19300 | pos.lnum = curwin->w_cursor.lnum; |
19301 | pos.col = (colnr_T)STRLEN(get_cursor_line_ptr()); |
19302 | } |
19303 | return &pos; |
19304 | } |
19305 | return NULL; |
19306 | } |
19307 | |
19308 | /* |
19309 | * Convert list in "arg" into a position and optional file number. |
19310 | * When "fnump" is NULL there is no file number, only 3 items. |
19311 | * Note that the column is passed on as-is, the caller may want to decrement |
19312 | * it to use 1 for the first column. |
19313 | * Return FAIL when conversion is not possible, doesn't check the position for |
19314 | * validity. |
19315 | */ |
19316 | int list2fpos(typval_T *arg, pos_T *posp, int *fnump, colnr_T *curswantp) |
19317 | { |
19318 | list_T *l; |
19319 | long i = 0; |
19320 | long n; |
19321 | |
19322 | // List must be: [fnum, lnum, col, coladd, curswant], where "fnum" is only |
19323 | // there when "fnump" isn't NULL; "coladd" and "curswant" are optional. |
19324 | if (arg->v_type != VAR_LIST |
19325 | || (l = arg->vval.v_list) == NULL |
19326 | || tv_list_len(l) < (fnump == NULL ? 2 : 3) |
19327 | || tv_list_len(l) > (fnump == NULL ? 4 : 5)) { |
19328 | return FAIL; |
19329 | } |
19330 | |
19331 | if (fnump != NULL) { |
19332 | n = tv_list_find_nr(l, i++, NULL); // fnum |
19333 | if (n < 0) { |
19334 | return FAIL; |
19335 | } |
19336 | if (n == 0) { |
19337 | n = curbuf->b_fnum; // Current buffer. |
19338 | } |
19339 | *fnump = n; |
19340 | } |
19341 | |
19342 | n = tv_list_find_nr(l, i++, NULL); // lnum |
19343 | if (n < 0) { |
19344 | return FAIL; |
19345 | } |
19346 | posp->lnum = n; |
19347 | |
19348 | n = tv_list_find_nr(l, i++, NULL); // col |
19349 | if (n < 0) { |
19350 | return FAIL; |
19351 | } |
19352 | posp->col = n; |
19353 | |
19354 | n = tv_list_find_nr(l, i, NULL); // off |
19355 | if (n < 0) { |
19356 | posp->coladd = 0; |
19357 | } else { |
19358 | posp->coladd = n; |
19359 | } |
19360 | |
19361 | if (curswantp != NULL) { |
19362 | *curswantp = tv_list_find_nr(l, i + 1, NULL); // curswant |
19363 | } |
19364 | |
19365 | return OK; |
19366 | } |
19367 | |
19368 | /* |
19369 | * Get the length of an environment variable name. |
19370 | * Advance "arg" to the first character after the name. |
19371 | * Return 0 for error. |
19372 | */ |
19373 | static int get_env_len(const char_u **arg) |
19374 | { |
19375 | int len; |
19376 | |
19377 | const char_u *p; |
19378 | for (p = *arg; vim_isIDc(*p); p++) { |
19379 | } |
19380 | if (p == *arg) { // No name found. |
19381 | return 0; |
19382 | } |
19383 | |
19384 | len = (int)(p - *arg); |
19385 | *arg = p; |
19386 | return len; |
19387 | } |
19388 | |
19389 | // Get the length of the name of a function or internal variable. |
19390 | // "arg" is advanced to the first non-white character after the name. |
19391 | // Return 0 if something is wrong. |
19392 | static int get_id_len(const char **const arg) |
19393 | { |
19394 | int len; |
19395 | |
19396 | // Find the end of the name. |
19397 | const char *p; |
19398 | for (p = *arg; eval_isnamec(*p); p++) { |
19399 | if (*p == ':') { |
19400 | // "s:" is start of "s:var", but "n:" is not and can be used in |
19401 | // slice "[n:]". Also "xx:" is not a namespace. |
19402 | len = (int)(p - *arg); |
19403 | if (len > 1 |
19404 | || (len == 1 && vim_strchr(namespace_char, **arg) == NULL)) { |
19405 | break; |
19406 | } |
19407 | } |
19408 | } |
19409 | if (p == *arg) { // no name found |
19410 | return 0; |
19411 | } |
19412 | |
19413 | len = (int)(p - *arg); |
19414 | *arg = (const char *)skipwhite((const char_u *)p); |
19415 | |
19416 | return len; |
19417 | } |
19418 | |
19419 | /* |
19420 | * Get the length of the name of a variable or function. |
19421 | * Only the name is recognized, does not handle ".key" or "[idx]". |
19422 | * "arg" is advanced to the first non-white character after the name. |
19423 | * Return -1 if curly braces expansion failed. |
19424 | * Return 0 if something else is wrong. |
19425 | * If the name contains 'magic' {}'s, expand them and return the |
19426 | * expanded name in an allocated string via 'alias' - caller must free. |
19427 | */ |
19428 | static int get_name_len(const char **const arg, |
19429 | char **alias, |
19430 | int evaluate, |
19431 | int verbose) |
19432 | { |
19433 | int len; |
19434 | |
19435 | *alias = NULL; /* default to no alias */ |
19436 | |
19437 | if ((*arg)[0] == (char)K_SPECIAL && (*arg)[1] == (char)KS_EXTRA |
19438 | && (*arg)[2] == (char)KE_SNR) { |
19439 | // Hard coded <SNR>, already translated. |
19440 | *arg += 3; |
19441 | return get_id_len(arg) + 3; |
19442 | } |
19443 | len = eval_fname_script(*arg); |
19444 | if (len > 0) { |
19445 | /* literal "<SID>", "s:" or "<SNR>" */ |
19446 | *arg += len; |
19447 | } |
19448 | |
19449 | // Find the end of the name; check for {} construction. |
19450 | char_u *expr_start; |
19451 | char_u *expr_end; |
19452 | const char *p = (const char *)find_name_end((char_u *)(*arg), |
19453 | (const char_u **)&expr_start, |
19454 | (const char_u **)&expr_end, |
19455 | len > 0 ? 0 : FNE_CHECK_START); |
19456 | if (expr_start != NULL) { |
19457 | if (!evaluate) { |
19458 | len += (int)(p - *arg); |
19459 | *arg = (const char *)skipwhite((const char_u *)p); |
19460 | return len; |
19461 | } |
19462 | |
19463 | /* |
19464 | * Include any <SID> etc in the expanded string: |
19465 | * Thus the -len here. |
19466 | */ |
19467 | char_u *temp_string = make_expanded_name((char_u *)(*arg) - len, expr_start, |
19468 | expr_end, (char_u *)p); |
19469 | if (temp_string == NULL) { |
19470 | return -1; |
19471 | } |
19472 | *alias = (char *)temp_string; |
19473 | *arg = (const char *)skipwhite((const char_u *)p); |
19474 | return (int)STRLEN(temp_string); |
19475 | } |
19476 | |
19477 | len += get_id_len(arg); |
19478 | // Only give an error when there is something, otherwise it will be |
19479 | // reported at a higher level. |
19480 | if (len == 0 && verbose && **arg != NUL) { |
19481 | EMSG2(_(e_invexpr2), *arg); |
19482 | } |
19483 | |
19484 | return len; |
19485 | } |
19486 | |
19487 | // Find the end of a variable or function name, taking care of magic braces. |
19488 | // If "expr_start" is not NULL then "expr_start" and "expr_end" are set to the |
19489 | // start and end of the first magic braces item. |
19490 | // "flags" can have FNE_INCL_BR and FNE_CHECK_START. |
19491 | // Return a pointer to just after the name. Equal to "arg" if there is no |
19492 | // valid name. |
19493 | static const char_u *find_name_end(const char_u *arg, const char_u **expr_start, |
19494 | const char_u **expr_end, int flags) |
19495 | { |
19496 | int mb_nest = 0; |
19497 | int br_nest = 0; |
19498 | int len; |
19499 | |
19500 | if (expr_start != NULL) { |
19501 | *expr_start = NULL; |
19502 | *expr_end = NULL; |
19503 | } |
19504 | |
19505 | // Quick check for valid starting character. |
19506 | if ((flags & FNE_CHECK_START) && !eval_isnamec1(*arg) && *arg != '{') { |
19507 | return arg; |
19508 | } |
19509 | |
19510 | const char_u *p; |
19511 | for (p = arg; *p != NUL |
19512 | && (eval_isnamec(*p) |
19513 | || *p == '{' |
19514 | || ((flags & FNE_INCL_BR) && (*p == '[' || *p == '.')) |
19515 | || mb_nest != 0 |
19516 | || br_nest != 0); MB_PTR_ADV(p)) { |
19517 | if (*p == '\'') { |
19518 | // skip over 'string' to avoid counting [ and ] inside it. |
19519 | for (p = p + 1; *p != NUL && *p != '\''; MB_PTR_ADV(p)) { |
19520 | } |
19521 | if (*p == NUL) { |
19522 | break; |
19523 | } |
19524 | } else if (*p == '"') { |
19525 | // skip over "str\"ing" to avoid counting [ and ] inside it. |
19526 | for (p = p + 1; *p != NUL && *p != '"'; MB_PTR_ADV(p)) { |
19527 | if (*p == '\\' && p[1] != NUL) { |
19528 | ++p; |
19529 | } |
19530 | } |
19531 | if (*p == NUL) { |
19532 | break; |
19533 | } |
19534 | } else if (br_nest == 0 && mb_nest == 0 && *p == ':') { |
19535 | // "s:" is start of "s:var", but "n:" is not and can be used in |
19536 | // slice "[n:]". Also "xx:" is not a namespace. But {ns}: is. */ |
19537 | len = (int)(p - arg); |
19538 | if ((len > 1 && p[-1] != '}') |
19539 | || (len == 1 && vim_strchr(namespace_char, *arg) == NULL)) { |
19540 | break; |
19541 | } |
19542 | } |
19543 | |
19544 | if (mb_nest == 0) { |
19545 | if (*p == '[') { |
19546 | ++br_nest; |
19547 | } else if (*p == ']') { |
19548 | --br_nest; |
19549 | } |
19550 | } |
19551 | |
19552 | if (br_nest == 0) { |
19553 | if (*p == '{') { |
19554 | mb_nest++; |
19555 | if (expr_start != NULL && *expr_start == NULL) { |
19556 | *expr_start = p; |
19557 | } |
19558 | } else if (*p == '}') { |
19559 | mb_nest--; |
19560 | if (expr_start != NULL && mb_nest == 0 && *expr_end == NULL) { |
19561 | *expr_end = p; |
19562 | } |
19563 | } |
19564 | } |
19565 | } |
19566 | |
19567 | return p; |
19568 | } |
19569 | |
19570 | /* |
19571 | * Expands out the 'magic' {}'s in a variable/function name. |
19572 | * Note that this can call itself recursively, to deal with |
19573 | * constructs like foo{bar}{baz}{bam} |
19574 | * The four pointer arguments point to "foo{expre}ss{ion}bar" |
19575 | * "in_start" ^ |
19576 | * "expr_start" ^ |
19577 | * "expr_end" ^ |
19578 | * "in_end" ^ |
19579 | * |
19580 | * Returns a new allocated string, which the caller must free. |
19581 | * Returns NULL for failure. |
19582 | */ |
19583 | static char_u *make_expanded_name(const char_u *in_start, char_u *expr_start, |
19584 | char_u *expr_end, char_u *in_end) |
19585 | { |
19586 | char_u c1; |
19587 | char_u *retval = NULL; |
19588 | char_u *temp_result; |
19589 | char_u *nextcmd = NULL; |
19590 | |
19591 | if (expr_end == NULL || in_end == NULL) |
19592 | return NULL; |
19593 | *expr_start = NUL; |
19594 | *expr_end = NUL; |
19595 | c1 = *in_end; |
19596 | *in_end = NUL; |
19597 | |
19598 | temp_result = eval_to_string(expr_start + 1, &nextcmd, FALSE); |
19599 | if (temp_result != NULL && nextcmd == NULL) { |
19600 | retval = xmalloc(STRLEN(temp_result) + (expr_start - in_start) |
19601 | + (in_end - expr_end) + 1); |
19602 | STRCPY(retval, in_start); |
19603 | STRCAT(retval, temp_result); |
19604 | STRCAT(retval, expr_end + 1); |
19605 | } |
19606 | xfree(temp_result); |
19607 | |
19608 | *in_end = c1; /* put char back for error messages */ |
19609 | *expr_start = '{'; |
19610 | *expr_end = '}'; |
19611 | |
19612 | if (retval != NULL) { |
19613 | temp_result = (char_u *)find_name_end(retval, |
19614 | (const char_u **)&expr_start, |
19615 | (const char_u **)&expr_end, 0); |
19616 | if (expr_start != NULL) { |
19617 | /* Further expansion! */ |
19618 | temp_result = make_expanded_name(retval, expr_start, |
19619 | expr_end, temp_result); |
19620 | xfree(retval); |
19621 | retval = temp_result; |
19622 | } |
19623 | } |
19624 | |
19625 | return retval; |
19626 | } |
19627 | |
19628 | /* |
19629 | * Return TRUE if character "c" can be used in a variable or function name. |
19630 | * Does not include '{' or '}' for magic braces. |
19631 | */ |
19632 | static int eval_isnamec(int c) |
19633 | { |
19634 | return ASCII_ISALNUM(c) || c == '_' || c == ':' || c == AUTOLOAD_CHAR; |
19635 | } |
19636 | |
19637 | /* |
19638 | * Return TRUE if character "c" can be used as the first character in a |
19639 | * variable or function name (excluding '{' and '}'). |
19640 | */ |
19641 | static int eval_isnamec1(int c) |
19642 | { |
19643 | return ASCII_ISALPHA(c) || c == '_'; |
19644 | } |
19645 | |
19646 | /* |
19647 | * Get number v: variable value. |
19648 | */ |
19649 | varnumber_T get_vim_var_nr(int idx) FUNC_ATTR_PURE |
19650 | { |
19651 | return vimvars[idx].vv_nr; |
19652 | } |
19653 | |
19654 | // Get string v: variable value. Uses a static buffer, can only be used once. |
19655 | // If the String variable has never been set, return an empty string. |
19656 | // Never returns NULL; |
19657 | char_u *get_vim_var_str(int idx) FUNC_ATTR_PURE FUNC_ATTR_NONNULL_RET |
19658 | { |
19659 | return (char_u *)tv_get_string(&vimvars[idx].vv_tv); |
19660 | } |
19661 | |
19662 | /* |
19663 | * Get List v: variable value. Caller must take care of reference count when |
19664 | * needed. |
19665 | */ |
19666 | list_T *get_vim_var_list(int idx) FUNC_ATTR_PURE |
19667 | { |
19668 | return vimvars[idx].vv_list; |
19669 | } |
19670 | |
19671 | /// Get Dictionary v: variable value. Caller must take care of reference count |
19672 | /// when needed. |
19673 | dict_T *get_vim_var_dict(int idx) FUNC_ATTR_PURE |
19674 | { |
19675 | return vimvars[idx].vv_dict; |
19676 | } |
19677 | |
19678 | /* |
19679 | * Set v:char to character "c". |
19680 | */ |
19681 | void set_vim_var_char(int c) |
19682 | { |
19683 | char buf[MB_MAXBYTES + 1]; |
19684 | |
19685 | buf[utf_char2bytes(c, (char_u *)buf)] = NUL; |
19686 | set_vim_var_string(VV_CHAR, buf, -1); |
19687 | } |
19688 | |
19689 | /* |
19690 | * Set v:count to "count" and v:count1 to "count1". |
19691 | * When "set_prevcount" is TRUE first set v:prevcount from v:count. |
19692 | */ |
19693 | void set_vcount(long count, long count1, int set_prevcount) |
19694 | { |
19695 | if (set_prevcount) |
19696 | vimvars[VV_PREVCOUNT].vv_nr = vimvars[VV_COUNT].vv_nr; |
19697 | vimvars[VV_COUNT].vv_nr = count; |
19698 | vimvars[VV_COUNT1].vv_nr = count1; |
19699 | } |
19700 | |
19701 | /// Set number v: variable to the given value |
19702 | /// |
19703 | /// @param[in] idx Index of variable to set. |
19704 | /// @param[in] val Value to set to. |
19705 | void set_vim_var_nr(const VimVarIndex idx, const varnumber_T val) |
19706 | { |
19707 | tv_clear(&vimvars[idx].vv_tv); |
19708 | vimvars[idx].vv_type = VAR_NUMBER; |
19709 | vimvars[idx].vv_nr = val; |
19710 | } |
19711 | |
19712 | /// Set special v: variable to the given value |
19713 | /// |
19714 | /// @param[in] idx Index of variable to set. |
19715 | /// @param[in] val Value to set to. |
19716 | void set_vim_var_special(const VimVarIndex idx, const SpecialVarValue val) |
19717 | { |
19718 | tv_clear(&vimvars[idx].vv_tv); |
19719 | vimvars[idx].vv_type = VAR_SPECIAL; |
19720 | vimvars[idx].vv_special = val; |
19721 | } |
19722 | |
19723 | /// Set string v: variable to the given string |
19724 | /// |
19725 | /// @param[in] idx Index of variable to set. |
19726 | /// @param[in] val Value to set to. Will be copied. |
19727 | /// @param[in] len Legth of that value or -1 in which case strlen() will be |
19728 | /// used. |
19729 | void set_vim_var_string(const VimVarIndex idx, const char *const val, |
19730 | const ptrdiff_t len) |
19731 | { |
19732 | tv_clear(&vimvars[idx].vv_di.di_tv); |
19733 | vimvars[idx].vv_type = VAR_STRING; |
19734 | if (val == NULL) { |
19735 | vimvars[idx].vv_str = NULL; |
19736 | } else if (len == -1) { |
19737 | vimvars[idx].vv_str = (char_u *) xstrdup(val); |
19738 | } else { |
19739 | vimvars[idx].vv_str = (char_u *) xstrndup(val, (size_t) len); |
19740 | } |
19741 | } |
19742 | |
19743 | /// Set list v: variable to the given list |
19744 | /// |
19745 | /// @param[in] idx Index of variable to set. |
19746 | /// @param[in,out] val Value to set to. Reference count will be incremented. |
19747 | void set_vim_var_list(const VimVarIndex idx, list_T *const val) |
19748 | { |
19749 | tv_clear(&vimvars[idx].vv_di.di_tv); |
19750 | vimvars[idx].vv_type = VAR_LIST; |
19751 | vimvars[idx].vv_list = val; |
19752 | if (val != NULL) { |
19753 | tv_list_ref(val); |
19754 | } |
19755 | } |
19756 | |
19757 | /// Set Dictionary v: variable to the given dictionary |
19758 | /// |
19759 | /// @param[in] idx Index of variable to set. |
19760 | /// @param[in,out] val Value to set to. Reference count will be incremented. |
19761 | /// Also keys of the dictionary will be made read-only. |
19762 | void set_vim_var_dict(const VimVarIndex idx, dict_T *const val) |
19763 | { |
19764 | tv_clear(&vimvars[idx].vv_di.di_tv); |
19765 | vimvars[idx].vv_type = VAR_DICT; |
19766 | vimvars[idx].vv_dict = val; |
19767 | |
19768 | if (val != NULL) { |
19769 | val->dv_refcount++; |
19770 | // Set readonly |
19771 | tv_dict_set_keys_readonly(val); |
19772 | } |
19773 | } |
19774 | |
19775 | /* |
19776 | * Set v:register if needed. |
19777 | */ |
19778 | void set_reg_var(int c) |
19779 | { |
19780 | char regname; |
19781 | |
19782 | if (c == 0 || c == ' ') { |
19783 | regname = '"'; |
19784 | } else { |
19785 | regname = c; |
19786 | } |
19787 | // Avoid free/alloc when the value is already right. |
19788 | if (vimvars[VV_REG].vv_str == NULL || vimvars[VV_REG].vv_str[0] != c) { |
19789 | set_vim_var_string(VV_REG, ®name, 1); |
19790 | } |
19791 | } |
19792 | |
19793 | /* |
19794 | * Get or set v:exception. If "oldval" == NULL, return the current value. |
19795 | * Otherwise, restore the value to "oldval" and return NULL. |
19796 | * Must always be called in pairs to save and restore v:exception! Does not |
19797 | * take care of memory allocations. |
19798 | */ |
19799 | char_u *v_exception(char_u *oldval) |
19800 | { |
19801 | if (oldval == NULL) |
19802 | return vimvars[VV_EXCEPTION].vv_str; |
19803 | |
19804 | vimvars[VV_EXCEPTION].vv_str = oldval; |
19805 | return NULL; |
19806 | } |
19807 | |
19808 | /* |
19809 | * Get or set v:throwpoint. If "oldval" == NULL, return the current value. |
19810 | * Otherwise, restore the value to "oldval" and return NULL. |
19811 | * Must always be called in pairs to save and restore v:throwpoint! Does not |
19812 | * take care of memory allocations. |
19813 | */ |
19814 | char_u *v_throwpoint(char_u *oldval) |
19815 | { |
19816 | if (oldval == NULL) |
19817 | return vimvars[VV_THROWPOINT].vv_str; |
19818 | |
19819 | vimvars[VV_THROWPOINT].vv_str = oldval; |
19820 | return NULL; |
19821 | } |
19822 | |
19823 | /* |
19824 | * Set v:cmdarg. |
19825 | * If "eap" != NULL, use "eap" to generate the value and return the old value. |
19826 | * If "oldarg" != NULL, restore the value to "oldarg" and return NULL. |
19827 | * Must always be called in pairs! |
19828 | */ |
19829 | char_u *set_cmdarg(exarg_T *eap, char_u *oldarg) |
19830 | { |
19831 | char_u *oldval; |
19832 | char_u *newval; |
19833 | |
19834 | oldval = vimvars[VV_CMDARG].vv_str; |
19835 | if (eap == NULL) { |
19836 | xfree(oldval); |
19837 | vimvars[VV_CMDARG].vv_str = oldarg; |
19838 | return NULL; |
19839 | } |
19840 | |
19841 | size_t len = 0; |
19842 | if (eap->force_bin == FORCE_BIN) |
19843 | len = 6; |
19844 | else if (eap->force_bin == FORCE_NOBIN) |
19845 | len = 8; |
19846 | |
19847 | if (eap->read_edit) |
19848 | len += 7; |
19849 | |
19850 | if (eap->force_ff != 0) |
19851 | len += STRLEN(eap->cmd + eap->force_ff) + 6; |
19852 | if (eap->force_enc != 0) |
19853 | len += STRLEN(eap->cmd + eap->force_enc) + 7; |
19854 | if (eap->bad_char != 0) |
19855 | len += 7 + 4; /* " ++bad=" + "keep" or "drop" */ |
19856 | |
19857 | newval = xmalloc(len + 1); |
19858 | |
19859 | if (eap->force_bin == FORCE_BIN) |
19860 | sprintf((char *)newval, " ++bin" ); |
19861 | else if (eap->force_bin == FORCE_NOBIN) |
19862 | sprintf((char *)newval, " ++nobin" ); |
19863 | else |
19864 | *newval = NUL; |
19865 | |
19866 | if (eap->read_edit) |
19867 | STRCAT(newval, " ++edit" ); |
19868 | |
19869 | if (eap->force_ff != 0) |
19870 | sprintf((char *)newval + STRLEN(newval), " ++ff=%s" , |
19871 | eap->cmd + eap->force_ff); |
19872 | if (eap->force_enc != 0) |
19873 | sprintf((char *)newval + STRLEN(newval), " ++enc=%s" , |
19874 | eap->cmd + eap->force_enc); |
19875 | if (eap->bad_char == BAD_KEEP) |
19876 | STRCPY(newval + STRLEN(newval), " ++bad=keep" ); |
19877 | else if (eap->bad_char == BAD_DROP) |
19878 | STRCPY(newval + STRLEN(newval), " ++bad=drop" ); |
19879 | else if (eap->bad_char != 0) |
19880 | sprintf((char *)newval + STRLEN(newval), " ++bad=%c" , eap->bad_char); |
19881 | vimvars[VV_CMDARG].vv_str = newval; |
19882 | return oldval; |
19883 | } |
19884 | |
19885 | /* |
19886 | * Get the value of internal variable "name". |
19887 | * Return OK or FAIL. |
19888 | */ |
19889 | static int get_var_tv( |
19890 | const char *name, |
19891 | int len, // length of "name" |
19892 | typval_T *rettv, // NULL when only checking existence |
19893 | dictitem_T **dip, // non-NULL when typval's dict item is needed |
19894 | int verbose, // may give error message |
19895 | int no_autoload // do not use script autoloading |
19896 | ) |
19897 | { |
19898 | int ret = OK; |
19899 | typval_T *tv = NULL; |
19900 | dictitem_T *v; |
19901 | |
19902 | v = find_var(name, (size_t)len, NULL, no_autoload); |
19903 | if (v != NULL) { |
19904 | tv = &v->di_tv; |
19905 | if (dip != NULL) { |
19906 | *dip = v; |
19907 | } |
19908 | } |
19909 | |
19910 | if (tv == NULL) { |
19911 | if (rettv != NULL && verbose) { |
19912 | emsgf(_("E121: Undefined variable: %.*s" ), len, name); |
19913 | } |
19914 | ret = FAIL; |
19915 | } else if (rettv != NULL) { |
19916 | tv_copy(tv, rettv); |
19917 | } |
19918 | |
19919 | return ret; |
19920 | } |
19921 | |
19922 | /// Check if variable "name[len]" is a local variable or an argument. |
19923 | /// If so, "*eval_lavars_used" is set to TRUE. |
19924 | static void check_vars(const char *name, size_t len) |
19925 | { |
19926 | if (eval_lavars_used == NULL) { |
19927 | return; |
19928 | } |
19929 | |
19930 | const char *varname; |
19931 | hashtab_T *ht = find_var_ht(name, len, &varname); |
19932 | |
19933 | if (ht == get_funccal_local_ht() || ht == get_funccal_args_ht()) { |
19934 | if (find_var(name, len, NULL, true) != NULL) { |
19935 | *eval_lavars_used = true; |
19936 | } |
19937 | } |
19938 | } |
19939 | |
19940 | /// Handle expr[expr], expr[expr:expr] subscript and .name lookup. |
19941 | /// Also handle function call with Funcref variable: func(expr) |
19942 | /// Can all be combined: dict.func(expr)[idx]['func'](expr) |
19943 | static int |
19944 | handle_subscript( |
19945 | const char **const arg, |
19946 | typval_T *rettv, |
19947 | int evaluate, /* do more than finding the end */ |
19948 | int verbose /* give error messages */ |
19949 | ) |
19950 | { |
19951 | int ret = OK; |
19952 | dict_T *selfdict = NULL; |
19953 | char_u *s; |
19954 | int len; |
19955 | typval_T functv; |
19956 | |
19957 | while (ret == OK |
19958 | && (**arg == '[' |
19959 | || (**arg == '.' && rettv->v_type == VAR_DICT) |
19960 | || (**arg == '(' && (!evaluate || tv_is_func(*rettv)))) |
19961 | && !ascii_iswhite(*(*arg - 1))) { |
19962 | if (**arg == '(') { |
19963 | partial_T *pt = NULL; |
19964 | // need to copy the funcref so that we can clear rettv |
19965 | if (evaluate) { |
19966 | functv = *rettv; |
19967 | rettv->v_type = VAR_UNKNOWN; |
19968 | |
19969 | // Invoke the function. Recursive! |
19970 | if (functv.v_type == VAR_PARTIAL) { |
19971 | pt = functv.vval.v_partial; |
19972 | s = partial_name(pt); |
19973 | } else { |
19974 | s = functv.vval.v_string; |
19975 | } |
19976 | } else { |
19977 | s = (char_u *)"" ; |
19978 | } |
19979 | ret = get_func_tv(s, (int)STRLEN(s), rettv, (char_u **)arg, |
19980 | curwin->w_cursor.lnum, curwin->w_cursor.lnum, |
19981 | &len, evaluate, pt, selfdict); |
19982 | |
19983 | // Clear the funcref afterwards, so that deleting it while |
19984 | // evaluating the arguments is possible (see test55). |
19985 | if (evaluate) { |
19986 | tv_clear(&functv); |
19987 | } |
19988 | |
19989 | /* Stop the expression evaluation when immediately aborting on |
19990 | * error, or when an interrupt occurred or an exception was thrown |
19991 | * but not caught. */ |
19992 | if (aborting()) { |
19993 | if (ret == OK) { |
19994 | tv_clear(rettv); |
19995 | } |
19996 | ret = FAIL; |
19997 | } |
19998 | tv_dict_unref(selfdict); |
19999 | selfdict = NULL; |
20000 | } else { // **arg == '[' || **arg == '.' |
20001 | tv_dict_unref(selfdict); |
20002 | if (rettv->v_type == VAR_DICT) { |
20003 | selfdict = rettv->vval.v_dict; |
20004 | if (selfdict != NULL) |
20005 | ++selfdict->dv_refcount; |
20006 | } else |
20007 | selfdict = NULL; |
20008 | if (eval_index((char_u **)arg, rettv, evaluate, verbose) == FAIL) { |
20009 | tv_clear(rettv); |
20010 | ret = FAIL; |
20011 | } |
20012 | } |
20013 | } |
20014 | |
20015 | // Turn "dict.Func" into a partial for "Func" bound to "dict". |
20016 | if (selfdict != NULL && tv_is_func(*rettv)) { |
20017 | set_selfdict(rettv, selfdict); |
20018 | } |
20019 | |
20020 | tv_dict_unref(selfdict); |
20021 | return ret; |
20022 | } |
20023 | |
20024 | void set_selfdict(typval_T *rettv, dict_T *selfdict) |
20025 | { |
20026 | // Don't do this when "dict.Func" is already a partial that was bound |
20027 | // explicitly (pt_auto is false). |
20028 | if (rettv->v_type == VAR_PARTIAL && !rettv->vval.v_partial->pt_auto |
20029 | && rettv->vval.v_partial->pt_dict != NULL) { |
20030 | return; |
20031 | } |
20032 | char_u *fname; |
20033 | char_u *tofree = NULL; |
20034 | ufunc_T *fp; |
20035 | char_u fname_buf[FLEN_FIXED + 1]; |
20036 | int error; |
20037 | |
20038 | if (rettv->v_type == VAR_PARTIAL && rettv->vval.v_partial->pt_func != NULL) { |
20039 | fp = rettv->vval.v_partial->pt_func; |
20040 | } else { |
20041 | fname = rettv->v_type == VAR_FUNC || rettv->v_type == VAR_STRING |
20042 | ? rettv->vval.v_string |
20043 | : rettv->vval.v_partial->pt_name; |
20044 | // Translate "s:func" to the stored function name. |
20045 | fname = fname_trans_sid(fname, fname_buf, &tofree, &error); |
20046 | fp = find_func(fname); |
20047 | xfree(tofree); |
20048 | } |
20049 | |
20050 | // Turn "dict.Func" into a partial for "Func" with "dict". |
20051 | if (fp != NULL && (fp->uf_flags & FC_DICT)) { |
20052 | partial_T *pt = (partial_T *)xcalloc(1, sizeof(partial_T)); |
20053 | pt->pt_refcount = 1; |
20054 | pt->pt_dict = selfdict; |
20055 | (selfdict->dv_refcount)++; |
20056 | pt->pt_auto = true; |
20057 | if (rettv->v_type == VAR_FUNC || rettv->v_type == VAR_STRING) { |
20058 | // Just a function: Take over the function name and use selfdict. |
20059 | pt->pt_name = rettv->vval.v_string; |
20060 | } else { |
20061 | partial_T *ret_pt = rettv->vval.v_partial; |
20062 | int i; |
20063 | |
20064 | // Partial: copy the function name, use selfdict and copy |
20065 | // args. Can't take over name or args, the partial might |
20066 | // be referenced elsewhere. |
20067 | if (ret_pt->pt_name != NULL) { |
20068 | pt->pt_name = vim_strsave(ret_pt->pt_name); |
20069 | func_ref(pt->pt_name); |
20070 | } else { |
20071 | pt->pt_func = ret_pt->pt_func; |
20072 | func_ptr_ref(pt->pt_func); |
20073 | } |
20074 | if (ret_pt->pt_argc > 0) { |
20075 | size_t arg_size = sizeof(typval_T) * ret_pt->pt_argc; |
20076 | pt->pt_argv = (typval_T *)xmalloc(arg_size); |
20077 | pt->pt_argc = ret_pt->pt_argc; |
20078 | for (i = 0; i < pt->pt_argc; i++) { |
20079 | tv_copy(&ret_pt->pt_argv[i], &pt->pt_argv[i]); |
20080 | } |
20081 | } |
20082 | partial_unref(ret_pt); |
20083 | } |
20084 | rettv->v_type = VAR_PARTIAL; |
20085 | rettv->vval.v_partial = pt; |
20086 | } |
20087 | } |
20088 | |
20089 | // Find variable "name" in the list of variables. |
20090 | // Return a pointer to it if found, NULL if not found. |
20091 | // Careful: "a:0" variables don't have a name. |
20092 | // When "htp" is not NULL we are writing to the variable, set "htp" to the |
20093 | // hashtab_T used. |
20094 | static dictitem_T *find_var(const char *const name, const size_t name_len, |
20095 | hashtab_T **htp, int no_autoload) |
20096 | { |
20097 | const char *varname; |
20098 | hashtab_T *const ht = find_var_ht(name, name_len, &varname); |
20099 | if (htp != NULL) { |
20100 | *htp = ht; |
20101 | } |
20102 | if (ht == NULL) { |
20103 | return NULL; |
20104 | } |
20105 | dictitem_T *const ret = find_var_in_ht(ht, *name, |
20106 | varname, |
20107 | name_len - (size_t)(varname - name), |
20108 | no_autoload || htp != NULL); |
20109 | if (ret != NULL) { |
20110 | return ret; |
20111 | } |
20112 | |
20113 | // Search in parent scope for lambda |
20114 | return find_var_in_scoped_ht(name, name_len, no_autoload || htp != NULL); |
20115 | } |
20116 | |
20117 | /// Find variable in hashtab |
20118 | /// |
20119 | /// @param[in] ht Hashtab to find variable in. |
20120 | /// @param[in] htname Hashtab name (first character). |
20121 | /// @param[in] varname Variable name. |
20122 | /// @param[in] varname_len Variable name length. |
20123 | /// @param[in] no_autoload If true then autoload scripts will not be sourced |
20124 | /// if autoload variable was not found. |
20125 | /// |
20126 | /// @return pointer to the dictionary item with the found variable or NULL if it |
20127 | /// was not found. |
20128 | static dictitem_T *find_var_in_ht(hashtab_T *const ht, |
20129 | int htname, |
20130 | const char *const varname, |
20131 | const size_t varname_len, |
20132 | int no_autoload) |
20133 | FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL |
20134 | { |
20135 | hashitem_T *hi; |
20136 | |
20137 | if (varname_len == 0) { |
20138 | // Must be something like "s:", otherwise "ht" would be NULL. |
20139 | switch (htname) { |
20140 | case 's': return (dictitem_T *)&SCRIPT_SV(current_sctx.sc_sid)->sv_var; |
20141 | case 'g': return (dictitem_T *)&globvars_var; |
20142 | case 'v': return (dictitem_T *)&vimvars_var; |
20143 | case 'b': return (dictitem_T *)&curbuf->b_bufvar; |
20144 | case 'w': return (dictitem_T *)&curwin->w_winvar; |
20145 | case 't': return (dictitem_T *)&curtab->tp_winvar; |
20146 | case 'l': return (current_funccal == NULL |
20147 | ? NULL : (dictitem_T *)¤t_funccal->l_vars_var); |
20148 | case 'a': return (current_funccal == NULL |
20149 | ? NULL : (dictitem_T *)&get_funccal()->l_avars_var); |
20150 | } |
20151 | return NULL; |
20152 | } |
20153 | |
20154 | hi = hash_find_len(ht, varname, varname_len); |
20155 | if (HASHITEM_EMPTY(hi)) { |
20156 | // For global variables we may try auto-loading the script. If it |
20157 | // worked find the variable again. Don't auto-load a script if it was |
20158 | // loaded already, otherwise it would be loaded every time when |
20159 | // checking if a function name is a Funcref variable. |
20160 | if (ht == &globvarht && !no_autoload) { |
20161 | // Note: script_autoload() may make "hi" invalid. It must either |
20162 | // be obtained again or not used. |
20163 | if (!script_autoload(varname, varname_len, false) || aborting()) { |
20164 | return NULL; |
20165 | } |
20166 | hi = hash_find_len(ht, varname, varname_len); |
20167 | } |
20168 | if (HASHITEM_EMPTY(hi)) { |
20169 | return NULL; |
20170 | } |
20171 | } |
20172 | return TV_DICT_HI2DI(hi); |
20173 | } |
20174 | |
20175 | // Get function call environment based on backtrace debug level |
20176 | static funccall_T *get_funccal(void) |
20177 | { |
20178 | funccall_T *funccal = current_funccal; |
20179 | if (debug_backtrace_level > 0) { |
20180 | for (int i = 0; i < debug_backtrace_level; i++) { |
20181 | funccall_T *temp_funccal = funccal->caller; |
20182 | if (temp_funccal) { |
20183 | funccal = temp_funccal; |
20184 | } else { |
20185 | // backtrace level overflow. reset to max |
20186 | debug_backtrace_level = i; |
20187 | } |
20188 | } |
20189 | } |
20190 | |
20191 | return funccal; |
20192 | } |
20193 | |
20194 | /// Return the hashtable used for argument in the current funccal. |
20195 | /// Return NULL if there is no current funccal. |
20196 | static hashtab_T *get_funccal_args_ht(void) |
20197 | { |
20198 | if (current_funccal == NULL) { |
20199 | return NULL; |
20200 | } |
20201 | return &get_funccal()->l_avars.dv_hashtab; |
20202 | } |
20203 | |
20204 | /// Return the hashtable used for local variables in the current funccal. |
20205 | /// Return NULL if there is no current funccal. |
20206 | static hashtab_T *get_funccal_local_ht(void) |
20207 | { |
20208 | if (current_funccal == NULL) { |
20209 | return NULL; |
20210 | } |
20211 | return &get_funccal()->l_vars.dv_hashtab; |
20212 | } |
20213 | |
20214 | /// Find the dict and hashtable used for a variable |
20215 | /// |
20216 | /// @param[in] name Variable name, possibly with scope prefix. |
20217 | /// @param[in] name_len Variable name length. |
20218 | /// @param[out] varname Will be set to the start of the name without scope |
20219 | /// prefix. |
20220 | /// @param[out] d Scope dictionary. |
20221 | /// |
20222 | /// @return Scope hashtab, NULL if name is not valid. |
20223 | static hashtab_T *find_var_ht_dict(const char *name, const size_t name_len, |
20224 | const char **varname, dict_T **d) |
20225 | { |
20226 | hashitem_T *hi; |
20227 | *d = NULL; |
20228 | |
20229 | if (name_len == 0) { |
20230 | return NULL; |
20231 | } |
20232 | if (name_len == 1 || name[1] != ':') { |
20233 | // name has implicit scope |
20234 | if (name[0] == ':' || name[0] == AUTOLOAD_CHAR) { |
20235 | // The name must not start with a colon or #. |
20236 | return NULL; |
20237 | } |
20238 | *varname = name; |
20239 | |
20240 | // "version" is "v:version" in all scopes |
20241 | hi = hash_find_len(&compat_hashtab, name, name_len); |
20242 | if (!HASHITEM_EMPTY(hi)) { |
20243 | return &compat_hashtab; |
20244 | } |
20245 | |
20246 | if (current_funccal == NULL) { |
20247 | *d = &globvardict; |
20248 | } else { |
20249 | *d = &get_funccal()->l_vars; // l: variable |
20250 | } |
20251 | goto end; |
20252 | } |
20253 | |
20254 | *varname = name + 2; |
20255 | if (*name == 'g') { // global variable |
20256 | *d = &globvardict; |
20257 | } else if (name_len > 2 |
20258 | && (memchr(name + 2, ':', name_len - 2) != NULL |
20259 | || memchr(name + 2, AUTOLOAD_CHAR, name_len - 2) != NULL)) { |
20260 | // There must be no ':' or '#' in the rest of the name if g: was not used |
20261 | return NULL; |
20262 | } |
20263 | |
20264 | if (*name == 'b') { // buffer variable |
20265 | *d = curbuf->b_vars; |
20266 | } else if (*name == 'w') { // window variable |
20267 | *d = curwin->w_vars; |
20268 | } else if (*name == 't') { // tab page variable |
20269 | *d = curtab->tp_vars; |
20270 | } else if (*name == 'v') { // v: variable |
20271 | *d = &vimvardict; |
20272 | } else if (*name == 'a' && current_funccal != NULL) { // function argument |
20273 | *d = &get_funccal()->l_avars; |
20274 | } else if (*name == 'l' && current_funccal != NULL) { // local variable |
20275 | *d = &get_funccal()->l_vars; |
20276 | } else if (*name == 's' // script variable |
20277 | && current_sctx.sc_sid > 0 |
20278 | && current_sctx.sc_sid <= ga_scripts.ga_len) { |
20279 | *d = &SCRIPT_SV(current_sctx.sc_sid)->sv_dict; |
20280 | } |
20281 | |
20282 | end: |
20283 | return *d ? &(*d)->dv_hashtab : NULL; |
20284 | } |
20285 | |
20286 | /// Find the hashtable used for a variable |
20287 | /// |
20288 | /// @param[in] name Variable name, possibly with scope prefix. |
20289 | /// @param[in] name_len Variable name length. |
20290 | /// @param[out] varname Will be set to the start of the name without scope |
20291 | /// prefix. |
20292 | /// |
20293 | /// @return Scope hashtab, NULL if name is not valid. |
20294 | static hashtab_T *find_var_ht(const char *name, const size_t name_len, |
20295 | const char **varname) |
20296 | { |
20297 | dict_T *d; |
20298 | return find_var_ht_dict(name, name_len, varname, &d); |
20299 | } |
20300 | |
20301 | /* |
20302 | * Get the string value of a (global/local) variable. |
20303 | * Note: see tv_get_string() for how long the pointer remains valid. |
20304 | * Returns NULL when it doesn't exist. |
20305 | */ |
20306 | char_u *get_var_value(const char *const name) |
20307 | { |
20308 | dictitem_T *v; |
20309 | |
20310 | v = find_var(name, strlen(name), NULL, false); |
20311 | if (v == NULL) { |
20312 | return NULL; |
20313 | } |
20314 | return (char_u *)tv_get_string(&v->di_tv); |
20315 | } |
20316 | |
20317 | /* |
20318 | * Allocate a new hashtab for a sourced script. It will be used while |
20319 | * sourcing this script and when executing functions defined in the script. |
20320 | */ |
20321 | void new_script_vars(scid_T id) |
20322 | { |
20323 | hashtab_T *ht; |
20324 | scriptvar_T *sv; |
20325 | |
20326 | ga_grow(&ga_scripts, (int)(id - ga_scripts.ga_len)); |
20327 | { |
20328 | /* Re-allocating ga_data means that an ht_array pointing to |
20329 | * ht_smallarray becomes invalid. We can recognize this: ht_mask is |
20330 | * at its init value. Also reset "v_dict", it's always the same. */ |
20331 | for (int i = 1; i <= ga_scripts.ga_len; ++i) { |
20332 | ht = &SCRIPT_VARS(i); |
20333 | if (ht->ht_mask == HT_INIT_SIZE - 1) |
20334 | ht->ht_array = ht->ht_smallarray; |
20335 | sv = SCRIPT_SV(i); |
20336 | sv->sv_var.di_tv.vval.v_dict = &sv->sv_dict; |
20337 | } |
20338 | |
20339 | while (ga_scripts.ga_len < id) { |
20340 | sv = SCRIPT_SV(ga_scripts.ga_len + 1) = xcalloc(1, sizeof(scriptvar_T)); |
20341 | init_var_dict(&sv->sv_dict, &sv->sv_var, VAR_SCOPE); |
20342 | ++ga_scripts.ga_len; |
20343 | } |
20344 | } |
20345 | } |
20346 | |
20347 | /* |
20348 | * Initialize dictionary "dict" as a scope and set variable "dict_var" to |
20349 | * point to it. |
20350 | */ |
20351 | void init_var_dict(dict_T *dict, ScopeDictDictItem *dict_var, int scope) |
20352 | { |
20353 | hash_init(&dict->dv_hashtab); |
20354 | dict->dv_lock = VAR_UNLOCKED; |
20355 | dict->dv_scope = scope; |
20356 | dict->dv_refcount = DO_NOT_FREE_CNT; |
20357 | dict->dv_copyID = 0; |
20358 | dict_var->di_tv.vval.v_dict = dict; |
20359 | dict_var->di_tv.v_type = VAR_DICT; |
20360 | dict_var->di_tv.v_lock = VAR_FIXED; |
20361 | dict_var->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; |
20362 | dict_var->di_key[0] = NUL; |
20363 | QUEUE_INIT(&dict->watchers); |
20364 | } |
20365 | |
20366 | /* |
20367 | * Unreference a dictionary initialized by init_var_dict(). |
20368 | */ |
20369 | void unref_var_dict(dict_T *dict) |
20370 | { |
20371 | /* Now the dict needs to be freed if no one else is using it, go back to |
20372 | * normal reference counting. */ |
20373 | dict->dv_refcount -= DO_NOT_FREE_CNT - 1; |
20374 | tv_dict_unref(dict); |
20375 | } |
20376 | |
20377 | /* |
20378 | * Clean up a list of internal variables. |
20379 | * Frees all allocated variables and the value they contain. |
20380 | * Clears hashtab "ht", does not free it. |
20381 | */ |
20382 | void vars_clear(hashtab_T *ht) |
20383 | { |
20384 | vars_clear_ext(ht, TRUE); |
20385 | } |
20386 | |
20387 | /* |
20388 | * Like vars_clear(), but only free the value if "free_val" is TRUE. |
20389 | */ |
20390 | static void vars_clear_ext(hashtab_T *ht, int free_val) |
20391 | { |
20392 | int todo; |
20393 | hashitem_T *hi; |
20394 | dictitem_T *v; |
20395 | |
20396 | hash_lock(ht); |
20397 | todo = (int)ht->ht_used; |
20398 | for (hi = ht->ht_array; todo > 0; ++hi) { |
20399 | if (!HASHITEM_EMPTY(hi)) { |
20400 | --todo; |
20401 | |
20402 | // Free the variable. Don't remove it from the hashtab, |
20403 | // ht_array might change then. hash_clear() takes care of it |
20404 | // later. |
20405 | v = TV_DICT_HI2DI(hi); |
20406 | if (free_val) { |
20407 | tv_clear(&v->di_tv); |
20408 | } |
20409 | if (v->di_flags & DI_FLAGS_ALLOC) { |
20410 | xfree(v); |
20411 | } |
20412 | } |
20413 | } |
20414 | hash_clear(ht); |
20415 | ht->ht_used = 0; |
20416 | } |
20417 | |
20418 | /* |
20419 | * Delete a variable from hashtab "ht" at item "hi". |
20420 | * Clear the variable value and free the dictitem. |
20421 | */ |
20422 | static void delete_var(hashtab_T *ht, hashitem_T *hi) |
20423 | { |
20424 | dictitem_T *di = TV_DICT_HI2DI(hi); |
20425 | |
20426 | hash_remove(ht, hi); |
20427 | tv_clear(&di->di_tv); |
20428 | xfree(di); |
20429 | } |
20430 | |
20431 | /* |
20432 | * List the value of one internal variable. |
20433 | */ |
20434 | static void list_one_var(dictitem_T *v, const char *prefix, int *first) |
20435 | { |
20436 | char *const s = encode_tv2echo(&v->di_tv, NULL); |
20437 | list_one_var_a(prefix, (const char *)v->di_key, STRLEN(v->di_key), |
20438 | v->di_tv.v_type, (s == NULL ? "" : s), first); |
20439 | xfree(s); |
20440 | } |
20441 | |
20442 | /// @param[in] name_len Length of the name. May be -1, in this case strlen() |
20443 | /// will be used. |
20444 | /// @param[in,out] first When true clear rest of screen and set to false. |
20445 | static void list_one_var_a(const char *prefix, const char *name, |
20446 | const ptrdiff_t name_len, const int type, |
20447 | const char *string, int *first) |
20448 | { |
20449 | // don't use msg() or msg_attr() to avoid overwriting "v:statusmsg" |
20450 | msg_start(); |
20451 | msg_puts(prefix); |
20452 | if (name != NULL) { // "a:" vars don't have a name stored |
20453 | msg_puts_attr_len(name, name_len, 0); |
20454 | } |
20455 | msg_putchar(' '); |
20456 | msg_advance(22); |
20457 | if (type == VAR_NUMBER) { |
20458 | msg_putchar('#'); |
20459 | } else if (type == VAR_FUNC || type == VAR_PARTIAL) { |
20460 | msg_putchar('*'); |
20461 | } else if (type == VAR_LIST) { |
20462 | msg_putchar('['); |
20463 | if (*string == '[') |
20464 | ++string; |
20465 | } else if (type == VAR_DICT) { |
20466 | msg_putchar('{'); |
20467 | if (*string == '{') |
20468 | ++string; |
20469 | } else |
20470 | msg_putchar(' '); |
20471 | |
20472 | msg_outtrans((char_u *)string); |
20473 | |
20474 | if (type == VAR_FUNC || type == VAR_PARTIAL) { |
20475 | msg_puts("()" ); |
20476 | } |
20477 | if (*first) { |
20478 | msg_clr_eos(); |
20479 | *first = FALSE; |
20480 | } |
20481 | } |
20482 | |
20483 | /// Set variable to the given value |
20484 | /// |
20485 | /// If the variable already exists, the value is updated. Otherwise the variable |
20486 | /// is created. |
20487 | /// |
20488 | /// @param[in] name Variable name to set. |
20489 | /// @param[in] name_len Length of the variable name. |
20490 | /// @param tv Variable value. |
20491 | /// @param[in] copy True if value in tv is to be copied. |
20492 | static void set_var(const char *name, const size_t name_len, typval_T *const tv, |
20493 | const bool copy) |
20494 | FUNC_ATTR_NONNULL_ALL |
20495 | { |
20496 | set_var_const(name, name_len, tv, copy, false); |
20497 | } |
20498 | |
20499 | /// Set variable to the given value |
20500 | /// |
20501 | /// If the variable already exists, the value is updated. Otherwise the variable |
20502 | /// is created. |
20503 | /// |
20504 | /// @param[in] name Variable name to set. |
20505 | /// @param[in] name_len Length of the variable name. |
20506 | /// @param tv Variable value. |
20507 | /// @param[in] copy True if value in tv is to be copied. |
20508 | /// @param[in] is_const True if value in tv is to be locked. |
20509 | static void set_var_const(const char *name, const size_t name_len, |
20510 | typval_T *const tv, const bool copy, |
20511 | const bool is_const) |
20512 | FUNC_ATTR_NONNULL_ALL |
20513 | { |
20514 | dictitem_T *v; |
20515 | hashtab_T *ht; |
20516 | dict_T *dict; |
20517 | |
20518 | const char *varname; |
20519 | ht = find_var_ht_dict(name, name_len, &varname, &dict); |
20520 | const bool watched = tv_dict_is_watched(dict); |
20521 | |
20522 | if (ht == NULL || *varname == NUL) { |
20523 | EMSG2(_(e_illvar), name); |
20524 | return; |
20525 | } |
20526 | v = find_var_in_ht(ht, 0, varname, name_len - (size_t)(varname - name), true); |
20527 | |
20528 | // Search in parent scope which is possible to reference from lambda |
20529 | if (v == NULL) { |
20530 | v = find_var_in_scoped_ht((const char *)name, name_len, true); |
20531 | } |
20532 | |
20533 | if (tv_is_func(*tv) && !var_check_func_name(name, v == NULL)) { |
20534 | return; |
20535 | } |
20536 | |
20537 | typval_T oldtv = TV_INITIAL_VALUE; |
20538 | if (v != NULL) { |
20539 | if (is_const) { |
20540 | EMSG(_(e_cannot_mod)); |
20541 | return; |
20542 | } |
20543 | |
20544 | // existing variable, need to clear the value |
20545 | if (var_check_ro(v->di_flags, name, name_len) |
20546 | || tv_check_lock(v->di_tv.v_lock, name, name_len)) { |
20547 | return; |
20548 | } |
20549 | |
20550 | // Handle setting internal v: variables separately where needed to |
20551 | // prevent changing the type. |
20552 | if (ht == &vimvarht) { |
20553 | if (v->di_tv.v_type == VAR_STRING) { |
20554 | XFREE_CLEAR(v->di_tv.vval.v_string); |
20555 | if (copy || tv->v_type != VAR_STRING) { |
20556 | const char *const val = tv_get_string(tv); |
20557 | |
20558 | // Careful: when assigning to v:errmsg and tv_get_string() |
20559 | // causes an error message the variable will alrady be set. |
20560 | if (v->di_tv.vval.v_string == NULL) { |
20561 | v->di_tv.vval.v_string = (char_u *)xstrdup(val); |
20562 | } |
20563 | } else { |
20564 | // Take over the string to avoid an extra alloc/free. |
20565 | v->di_tv.vval.v_string = tv->vval.v_string; |
20566 | tv->vval.v_string = NULL; |
20567 | } |
20568 | return; |
20569 | } else if (v->di_tv.v_type == VAR_NUMBER) { |
20570 | v->di_tv.vval.v_number = tv_get_number(tv); |
20571 | if (strcmp(varname, "searchforward" ) == 0) { |
20572 | set_search_direction(v->di_tv.vval.v_number ? '/' : '?'); |
20573 | } else if (strcmp(varname, "hlsearch" ) == 0) { |
20574 | no_hlsearch = !v->di_tv.vval.v_number; |
20575 | redraw_all_later(SOME_VALID); |
20576 | } |
20577 | return; |
20578 | } else if (v->di_tv.v_type != tv->v_type) { |
20579 | EMSG2(_("E963: setting %s to value with wrong type" ), name); |
20580 | return; |
20581 | } |
20582 | } |
20583 | |
20584 | if (watched) { |
20585 | tv_copy(&v->di_tv, &oldtv); |
20586 | } |
20587 | tv_clear(&v->di_tv); |
20588 | } else { // Add a new variable. |
20589 | // Can't add "v:" or "a:" variable. |
20590 | if (ht == &vimvarht || ht == get_funccal_args_ht()) { |
20591 | emsgf(_(e_illvar), name); |
20592 | return; |
20593 | } |
20594 | |
20595 | // Make sure the variable name is valid. |
20596 | if (!valid_varname(varname)) { |
20597 | return; |
20598 | } |
20599 | |
20600 | // Make sure dict is valid |
20601 | assert(dict != NULL); |
20602 | |
20603 | v = xmalloc(sizeof(dictitem_T) + strlen(varname)); |
20604 | STRCPY(v->di_key, varname); |
20605 | if (tv_dict_add(dict, v) == FAIL) { |
20606 | xfree(v); |
20607 | return; |
20608 | } |
20609 | v->di_flags = DI_FLAGS_ALLOC; |
20610 | if (is_const) { |
20611 | v->di_flags |= DI_FLAGS_LOCK; |
20612 | } |
20613 | } |
20614 | |
20615 | if (copy || tv->v_type == VAR_NUMBER || tv->v_type == VAR_FLOAT) { |
20616 | tv_copy(tv, &v->di_tv); |
20617 | } else { |
20618 | v->di_tv = *tv; |
20619 | v->di_tv.v_lock = 0; |
20620 | tv_init(tv); |
20621 | } |
20622 | |
20623 | if (watched) { |
20624 | if (oldtv.v_type == VAR_UNKNOWN) { |
20625 | tv_dict_watcher_notify(dict, (char *)v->di_key, &v->di_tv, NULL); |
20626 | } else { |
20627 | tv_dict_watcher_notify(dict, (char *)v->di_key, &v->di_tv, &oldtv); |
20628 | tv_clear(&oldtv); |
20629 | } |
20630 | } |
20631 | |
20632 | if (is_const) { |
20633 | v->di_tv.v_lock |= VAR_LOCKED; |
20634 | } |
20635 | } |
20636 | |
20637 | /// Check whether variable is read-only (DI_FLAGS_RO, DI_FLAGS_RO_SBX) |
20638 | /// |
20639 | /// Also gives an error message. |
20640 | /// |
20641 | /// @param[in] flags di_flags attribute value. |
20642 | /// @param[in] name Variable name, for use in error message. |
20643 | /// @param[in] name_len Variable name length. Use #TV_TRANSLATE to translate |
20644 | /// variable name and compute the length. Use #TV_CSTRING |
20645 | /// to compute the length with strlen() without |
20646 | /// translating. |
20647 | /// |
20648 | /// Both #TV_… values are used for optimization purposes: |
20649 | /// variable name with its length is needed only in case |
20650 | /// of error, when no error occurs computing them is |
20651 | /// a waste of CPU resources. This especially applies to |
20652 | /// gettext. |
20653 | /// |
20654 | /// @return True if variable is read-only: either always or in sandbox when |
20655 | /// sandbox is enabled, false otherwise. |
20656 | bool var_check_ro(const int flags, const char *name, |
20657 | size_t name_len) |
20658 | FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL |
20659 | { |
20660 | const char *error_message = NULL; |
20661 | if (flags & DI_FLAGS_RO) { |
20662 | error_message = N_(e_readonlyvar); |
20663 | } else if ((flags & DI_FLAGS_RO_SBX) && sandbox) { |
20664 | error_message = N_("E794: Cannot set variable in the sandbox: \"%.*s\"" ); |
20665 | } |
20666 | |
20667 | if (error_message == NULL) { |
20668 | return false; |
20669 | } |
20670 | if (name_len == TV_TRANSLATE) { |
20671 | name = _(name); |
20672 | name_len = strlen(name); |
20673 | } else if (name_len == TV_CSTRING) { |
20674 | name_len = strlen(name); |
20675 | } |
20676 | |
20677 | emsgf(_(error_message), (int)name_len, name); |
20678 | |
20679 | return true; |
20680 | } |
20681 | |
20682 | /// Check whether variable is fixed (DI_FLAGS_FIX) |
20683 | /// |
20684 | /// Also gives an error message. |
20685 | /// |
20686 | /// @param[in] flags di_flags attribute value. |
20687 | /// @param[in] name Variable name, for use in error message. |
20688 | /// @param[in] name_len Variable name length. Use #TV_TRANSLATE to translate |
20689 | /// variable name and compute the length. Use #TV_CSTRING |
20690 | /// to compute the length with strlen() without |
20691 | /// translating. |
20692 | /// |
20693 | /// Both #TV_… values are used for optimization purposes: |
20694 | /// variable name with its length is needed only in case |
20695 | /// of error, when no error occurs computing them is |
20696 | /// a waste of CPU resources. This especially applies to |
20697 | /// gettext. |
20698 | /// |
20699 | /// @return True if variable is fixed, false otherwise. |
20700 | static bool var_check_fixed(const int flags, const char *name, |
20701 | size_t name_len) |
20702 | FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL |
20703 | { |
20704 | if (flags & DI_FLAGS_FIX) { |
20705 | if (name_len == TV_TRANSLATE) { |
20706 | name = _(name); |
20707 | name_len = strlen(name); |
20708 | } else if (name_len == TV_CSTRING) { |
20709 | name_len = strlen(name); |
20710 | } |
20711 | EMSG3(_("E795: Cannot delete variable %.*s" ), (int)name_len, name); |
20712 | return true; |
20713 | } |
20714 | return false; |
20715 | } |
20716 | |
20717 | // TODO(ZyX-I): move to eval/expressions |
20718 | |
20719 | /// Check if name is a valid name to assign funcref to |
20720 | /// |
20721 | /// @param[in] name Possible function/funcref name. |
20722 | /// @param[in] new_var True if it is a name for a variable. |
20723 | /// |
20724 | /// @return false in case of error, true in case of success. Also gives an |
20725 | /// error message if appropriate. |
20726 | bool var_check_func_name(const char *const name, const bool new_var) |
20727 | FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT |
20728 | { |
20729 | // Allow for w: b: s: and t:. |
20730 | if (!(vim_strchr((char_u *)"wbst" , name[0]) != NULL && name[1] == ':') |
20731 | && !ASCII_ISUPPER((name[0] != NUL && name[1] == ':') ? name[2] |
20732 | : name[0])) { |
20733 | EMSG2(_("E704: Funcref variable name must start with a capital: %s" ), name); |
20734 | return false; |
20735 | } |
20736 | // Don't allow hiding a function. When "v" is not NULL we might be |
20737 | // assigning another function to the same var, the type is checked |
20738 | // below. |
20739 | if (new_var && function_exists((const char *)name, false)) { |
20740 | EMSG2(_("E705: Variable name conflicts with existing function: %s" ), |
20741 | name); |
20742 | return false; |
20743 | } |
20744 | return true; |
20745 | } |
20746 | |
20747 | // TODO(ZyX-I): move to eval/expressions |
20748 | |
20749 | /// Check if a variable name is valid |
20750 | /// |
20751 | /// @param[in] varname Variable name to check. |
20752 | /// |
20753 | /// @return false when variable name is not valid, true when it is. Also gives |
20754 | /// an error message if appropriate. |
20755 | bool valid_varname(const char *varname) |
20756 | FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT |
20757 | { |
20758 | for (const char *p = varname; *p != NUL; p++) { |
20759 | if (!eval_isnamec1((int)(uint8_t)(*p)) |
20760 | && (p == varname || !ascii_isdigit(*p)) |
20761 | && *p != AUTOLOAD_CHAR) { |
20762 | emsgf(_(e_illvar), varname); |
20763 | return false; |
20764 | } |
20765 | } |
20766 | return true; |
20767 | } |
20768 | |
20769 | /// Make a copy of an item |
20770 | /// |
20771 | /// Lists and Dictionaries are also copied. |
20772 | /// |
20773 | /// @param[in] conv If not NULL, convert all copied strings. |
20774 | /// @param[in] from Value to copy. |
20775 | /// @param[out] to Location where to copy to. |
20776 | /// @param[in] deep If true, use copy the container and all of the contained |
20777 | /// containers (nested). |
20778 | /// @param[in] copyID If non-zero then when container is referenced more then |
20779 | /// once then copy of it that was already done is used. E.g. |
20780 | /// when copying list `list = [list2, list2]` (`list[0] is |
20781 | /// list[1]`) var_item_copy with zero copyID will emit |
20782 | /// a copy with (`copy[0] isnot copy[1]`), with non-zero it |
20783 | /// will emit a copy with (`copy[0] is copy[1]`) like in the |
20784 | /// original list. Not used when deep is false. |
20785 | int var_item_copy(const vimconv_T *const conv, |
20786 | typval_T *const from, |
20787 | typval_T *const to, |
20788 | const bool deep, |
20789 | const int copyID) |
20790 | FUNC_ATTR_NONNULL_ARG(2, 3) |
20791 | { |
20792 | static int recurse = 0; |
20793 | int ret = OK; |
20794 | |
20795 | if (recurse >= DICT_MAXNEST) { |
20796 | EMSG(_("E698: variable nested too deep for making a copy" )); |
20797 | return FAIL; |
20798 | } |
20799 | ++recurse; |
20800 | |
20801 | switch (from->v_type) { |
20802 | case VAR_NUMBER: |
20803 | case VAR_FLOAT: |
20804 | case VAR_FUNC: |
20805 | case VAR_PARTIAL: |
20806 | case VAR_SPECIAL: |
20807 | tv_copy(from, to); |
20808 | break; |
20809 | case VAR_STRING: |
20810 | if (conv == NULL || conv->vc_type == CONV_NONE |
20811 | || from->vval.v_string == NULL) { |
20812 | tv_copy(from, to); |
20813 | } else { |
20814 | to->v_type = VAR_STRING; |
20815 | to->v_lock = 0; |
20816 | if ((to->vval.v_string = string_convert((vimconv_T *)conv, |
20817 | from->vval.v_string, |
20818 | NULL)) |
20819 | == NULL) { |
20820 | to->vval.v_string = (char_u *) xstrdup((char *) from->vval.v_string); |
20821 | } |
20822 | } |
20823 | break; |
20824 | case VAR_LIST: |
20825 | to->v_type = VAR_LIST; |
20826 | to->v_lock = 0; |
20827 | if (from->vval.v_list == NULL) { |
20828 | to->vval.v_list = NULL; |
20829 | } else if (copyID != 0 && tv_list_copyid(from->vval.v_list) == copyID) { |
20830 | // Use the copy made earlier. |
20831 | to->vval.v_list = tv_list_latest_copy(from->vval.v_list); |
20832 | tv_list_ref(to->vval.v_list); |
20833 | } else { |
20834 | to->vval.v_list = tv_list_copy(conv, from->vval.v_list, deep, copyID); |
20835 | } |
20836 | if (to->vval.v_list == NULL && from->vval.v_list != NULL) { |
20837 | ret = FAIL; |
20838 | } |
20839 | break; |
20840 | case VAR_DICT: |
20841 | to->v_type = VAR_DICT; |
20842 | to->v_lock = 0; |
20843 | if (from->vval.v_dict == NULL) |
20844 | to->vval.v_dict = NULL; |
20845 | else if (copyID != 0 && from->vval.v_dict->dv_copyID == copyID) { |
20846 | /* use the copy made earlier */ |
20847 | to->vval.v_dict = from->vval.v_dict->dv_copydict; |
20848 | ++to->vval.v_dict->dv_refcount; |
20849 | } else { |
20850 | to->vval.v_dict = tv_dict_copy(conv, from->vval.v_dict, deep, copyID); |
20851 | } |
20852 | if (to->vval.v_dict == NULL && from->vval.v_dict != NULL) { |
20853 | ret = FAIL; |
20854 | } |
20855 | break; |
20856 | case VAR_UNKNOWN: |
20857 | internal_error("var_item_copy(UNKNOWN)" ); |
20858 | ret = FAIL; |
20859 | } |
20860 | --recurse; |
20861 | return ret; |
20862 | } |
20863 | |
20864 | /* |
20865 | * ":echo expr1 ..." print each argument separated with a space, add a |
20866 | * newline at the end. |
20867 | * ":echon expr1 ..." print each argument plain. |
20868 | */ |
20869 | void ex_echo(exarg_T *eap) |
20870 | { |
20871 | char_u *arg = eap->arg; |
20872 | typval_T rettv; |
20873 | bool atstart = true; |
20874 | const int did_emsg_before = did_emsg; |
20875 | |
20876 | if (eap->skip) |
20877 | ++emsg_skip; |
20878 | while (*arg != NUL && *arg != '|' && *arg != '\n' && !got_int) { |
20879 | // If eval1() causes an error message the text from the command may |
20880 | // still need to be cleared. E.g., "echo 22,44". |
20881 | need_clr_eos = true; |
20882 | |
20883 | { |
20884 | char_u *p = arg; |
20885 | if (eval1(&arg, &rettv, !eap->skip) == FAIL) { |
20886 | // Report the invalid expression unless the expression evaluation |
20887 | // has been cancelled due to an aborting error, an interrupt, or an |
20888 | // exception. |
20889 | if (!aborting() && did_emsg == did_emsg_before) { |
20890 | EMSG2(_(e_invexpr2), p); |
20891 | } |
20892 | need_clr_eos = false; |
20893 | break; |
20894 | } |
20895 | need_clr_eos = false; |
20896 | } |
20897 | |
20898 | if (!eap->skip) { |
20899 | if (atstart) { |
20900 | atstart = false; |
20901 | /* Call msg_start() after eval1(), evaluating the expression |
20902 | * may cause a message to appear. */ |
20903 | if (eap->cmdidx == CMD_echo) { |
20904 | /* Mark the saved text as finishing the line, so that what |
20905 | * follows is displayed on a new line when scrolling back |
20906 | * at the more prompt. */ |
20907 | msg_sb_eol(); |
20908 | msg_start(); |
20909 | } |
20910 | } else if (eap->cmdidx == CMD_echo) { |
20911 | msg_puts_attr(" " , echo_attr); |
20912 | } |
20913 | char *tofree = encode_tv2echo(&rettv, NULL); |
20914 | if (*tofree != NUL) { |
20915 | msg_ext_set_kind("echo" ); |
20916 | msg_multiline_attr(tofree, echo_attr, true); |
20917 | } |
20918 | xfree(tofree); |
20919 | } |
20920 | tv_clear(&rettv); |
20921 | arg = skipwhite(arg); |
20922 | } |
20923 | eap->nextcmd = check_nextcmd(arg); |
20924 | |
20925 | if (eap->skip) { |
20926 | emsg_skip--; |
20927 | } else { |
20928 | // remove text that may still be there from the command |
20929 | msg_clr_eos(); |
20930 | if (eap->cmdidx == CMD_echo) { |
20931 | msg_end(); |
20932 | } |
20933 | } |
20934 | } |
20935 | |
20936 | /* |
20937 | * ":echohl {name}". |
20938 | */ |
20939 | void ex_echohl(exarg_T *eap) |
20940 | { |
20941 | int id; |
20942 | |
20943 | id = syn_name2id(eap->arg); |
20944 | if (id == 0) |
20945 | echo_attr = 0; |
20946 | else |
20947 | echo_attr = syn_id2attr(id); |
20948 | } |
20949 | |
20950 | /* |
20951 | * ":execute expr1 ..." execute the result of an expression. |
20952 | * ":echomsg expr1 ..." Print a message |
20953 | * ":echoerr expr1 ..." Print an error |
20954 | * Each gets spaces around each argument and a newline at the end for |
20955 | * echo commands |
20956 | */ |
20957 | void ex_execute(exarg_T *eap) |
20958 | { |
20959 | char_u *arg = eap->arg; |
20960 | typval_T rettv; |
20961 | int ret = OK; |
20962 | garray_T ga; |
20963 | int save_did_emsg; |
20964 | |
20965 | ga_init(&ga, 1, 80); |
20966 | |
20967 | if (eap->skip) |
20968 | ++emsg_skip; |
20969 | while (*arg != NUL && *arg != '|' && *arg != '\n') { |
20970 | ret = eval1_emsg(&arg, &rettv, !eap->skip); |
20971 | if (ret == FAIL) { |
20972 | break; |
20973 | } |
20974 | |
20975 | if (!eap->skip) { |
20976 | const char *const argstr = tv_get_string(&rettv); |
20977 | const size_t len = strlen(argstr); |
20978 | ga_grow(&ga, len + 2); |
20979 | if (!GA_EMPTY(&ga)) { |
20980 | ((char_u *)(ga.ga_data))[ga.ga_len++] = ' '; |
20981 | } |
20982 | memcpy((char_u *)(ga.ga_data) + ga.ga_len, argstr, len + 1); |
20983 | ga.ga_len += len; |
20984 | } |
20985 | |
20986 | tv_clear(&rettv); |
20987 | arg = skipwhite(arg); |
20988 | } |
20989 | |
20990 | if (ret != FAIL && ga.ga_data != NULL) { |
20991 | if (eap->cmdidx == CMD_echomsg || eap->cmdidx == CMD_echoerr) { |
20992 | // Mark the already saved text as finishing the line, so that what |
20993 | // follows is displayed on a new line when scrolling back at the |
20994 | // more prompt. |
20995 | msg_sb_eol(); |
20996 | } |
20997 | |
20998 | if (eap->cmdidx == CMD_echomsg) { |
20999 | msg_ext_set_kind("echomsg" ); |
21000 | MSG_ATTR(ga.ga_data, echo_attr); |
21001 | ui_flush(); |
21002 | } else if (eap->cmdidx == CMD_echoerr) { |
21003 | /* We don't want to abort following commands, restore did_emsg. */ |
21004 | save_did_emsg = did_emsg; |
21005 | msg_ext_set_kind("echoerr" ); |
21006 | EMSG((char_u *)ga.ga_data); |
21007 | if (!force_abort) |
21008 | did_emsg = save_did_emsg; |
21009 | } else if (eap->cmdidx == CMD_execute) |
21010 | do_cmdline((char_u *)ga.ga_data, |
21011 | eap->getline, eap->cookie, DOCMD_NOWAIT|DOCMD_VERBOSE); |
21012 | } |
21013 | |
21014 | ga_clear(&ga); |
21015 | |
21016 | if (eap->skip) |
21017 | --emsg_skip; |
21018 | |
21019 | eap->nextcmd = check_nextcmd(arg); |
21020 | } |
21021 | |
21022 | /* |
21023 | * Skip over the name of an option: "&option", "&g:option" or "&l:option". |
21024 | * "arg" points to the "&" or '+' when called, to "option" when returning. |
21025 | * Returns NULL when no option name found. Otherwise pointer to the char |
21026 | * after the option name. |
21027 | */ |
21028 | static const char *find_option_end(const char **const arg, int *const opt_flags) |
21029 | { |
21030 | const char *p = *arg; |
21031 | |
21032 | ++p; |
21033 | if (*p == 'g' && p[1] == ':') { |
21034 | *opt_flags = OPT_GLOBAL; |
21035 | p += 2; |
21036 | } else if (*p == 'l' && p[1] == ':') { |
21037 | *opt_flags = OPT_LOCAL; |
21038 | p += 2; |
21039 | } else { |
21040 | *opt_flags = 0; |
21041 | } |
21042 | |
21043 | if (!ASCII_ISALPHA(*p)) { |
21044 | return NULL; |
21045 | } |
21046 | *arg = p; |
21047 | |
21048 | if (p[0] == 't' && p[1] == '_' && p[2] != NUL && p[3] != NUL) { |
21049 | p += 4; // t_xx/termcap option |
21050 | } else { |
21051 | while (ASCII_ISALPHA(*p)) { |
21052 | p++; |
21053 | } |
21054 | } |
21055 | return p; |
21056 | } |
21057 | |
21058 | /* |
21059 | * ":function" |
21060 | */ |
21061 | void ex_function(exarg_T *eap) |
21062 | { |
21063 | char_u *theline; |
21064 | char_u *line_to_free = NULL; |
21065 | int c; |
21066 | int saved_did_emsg; |
21067 | int saved_wait_return = need_wait_return; |
21068 | char_u *name = NULL; |
21069 | char_u *p; |
21070 | char_u *arg; |
21071 | char_u *line_arg = NULL; |
21072 | garray_T newargs; |
21073 | garray_T newlines; |
21074 | int varargs = false; |
21075 | int flags = 0; |
21076 | ufunc_T *fp; |
21077 | bool overwrite = false; |
21078 | int indent; |
21079 | int nesting; |
21080 | char_u *skip_until = NULL; |
21081 | dictitem_T *v; |
21082 | funcdict_T fudi; |
21083 | static int func_nr = 0; /* number for nameless function */ |
21084 | int paren; |
21085 | hashtab_T *ht; |
21086 | int todo; |
21087 | hashitem_T *hi; |
21088 | int sourcing_lnum_off; |
21089 | bool show_block = false; |
21090 | |
21091 | /* |
21092 | * ":function" without argument: list functions. |
21093 | */ |
21094 | if (ends_excmd(*eap->arg)) { |
21095 | if (!eap->skip) { |
21096 | todo = (int)func_hashtab.ht_used; |
21097 | for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi) { |
21098 | if (!HASHITEM_EMPTY(hi)) { |
21099 | --todo; |
21100 | fp = HI2UF(hi); |
21101 | if (message_filtered(fp->uf_name)) { |
21102 | continue; |
21103 | } |
21104 | if (!func_name_refcount(fp->uf_name)) { |
21105 | list_func_head(fp, false, false); |
21106 | } |
21107 | } |
21108 | } |
21109 | } |
21110 | eap->nextcmd = check_nextcmd(eap->arg); |
21111 | return; |
21112 | } |
21113 | |
21114 | /* |
21115 | * ":function /pat": list functions matching pattern. |
21116 | */ |
21117 | if (*eap->arg == '/') { |
21118 | p = skip_regexp(eap->arg + 1, '/', TRUE, NULL); |
21119 | if (!eap->skip) { |
21120 | regmatch_T regmatch; |
21121 | |
21122 | c = *p; |
21123 | *p = NUL; |
21124 | regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC); |
21125 | *p = c; |
21126 | if (regmatch.regprog != NULL) { |
21127 | regmatch.rm_ic = p_ic; |
21128 | |
21129 | todo = (int)func_hashtab.ht_used; |
21130 | for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi) { |
21131 | if (!HASHITEM_EMPTY(hi)) { |
21132 | --todo; |
21133 | fp = HI2UF(hi); |
21134 | if (!isdigit(*fp->uf_name) |
21135 | && vim_regexec(®match, fp->uf_name, 0)) |
21136 | list_func_head(fp, false, false); |
21137 | } |
21138 | } |
21139 | vim_regfree(regmatch.regprog); |
21140 | } |
21141 | } |
21142 | if (*p == '/') |
21143 | ++p; |
21144 | eap->nextcmd = check_nextcmd(p); |
21145 | return; |
21146 | } |
21147 | |
21148 | // Get the function name. There are these situations: |
21149 | // func function name |
21150 | // "name" == func, "fudi.fd_dict" == NULL |
21151 | // dict.func new dictionary entry |
21152 | // "name" == NULL, "fudi.fd_dict" set, |
21153 | // "fudi.fd_di" == NULL, "fudi.fd_newkey" == func |
21154 | // dict.func existing dict entry with a Funcref |
21155 | // "name" == func, "fudi.fd_dict" set, |
21156 | // "fudi.fd_di" set, "fudi.fd_newkey" == NULL |
21157 | // dict.func existing dict entry that's not a Funcref |
21158 | // "name" == NULL, "fudi.fd_dict" set, |
21159 | // "fudi.fd_di" set, "fudi.fd_newkey" == NULL |
21160 | // s:func script-local function name |
21161 | // g:func global function name, same as "func" |
21162 | p = eap->arg; |
21163 | name = trans_function_name(&p, eap->skip, TFN_NO_AUTOLOAD, &fudi, NULL); |
21164 | paren = (vim_strchr(p, '(') != NULL); |
21165 | if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip) { |
21166 | /* |
21167 | * Return on an invalid expression in braces, unless the expression |
21168 | * evaluation has been cancelled due to an aborting error, an |
21169 | * interrupt, or an exception. |
21170 | */ |
21171 | if (!aborting()) { |
21172 | if (fudi.fd_newkey != NULL) { |
21173 | EMSG2(_(e_dictkey), fudi.fd_newkey); |
21174 | } |
21175 | xfree(fudi.fd_newkey); |
21176 | return; |
21177 | } else |
21178 | eap->skip = TRUE; |
21179 | } |
21180 | |
21181 | /* An error in a function call during evaluation of an expression in magic |
21182 | * braces should not cause the function not to be defined. */ |
21183 | saved_did_emsg = did_emsg; |
21184 | did_emsg = FALSE; |
21185 | |
21186 | // |
21187 | // ":function func" with only function name: list function. |
21188 | // If bang is given: |
21189 | // - include "!" in function head |
21190 | // - exclude line numbers from function body |
21191 | // |
21192 | if (!paren) { |
21193 | if (!ends_excmd(*skipwhite(p))) { |
21194 | EMSG(_(e_trailing)); |
21195 | goto ret_free; |
21196 | } |
21197 | eap->nextcmd = check_nextcmd(p); |
21198 | if (eap->nextcmd != NULL) |
21199 | *p = NUL; |
21200 | if (!eap->skip && !got_int) { |
21201 | fp = find_func(name); |
21202 | if (fp != NULL) { |
21203 | list_func_head(fp, !eap->forceit, eap->forceit); |
21204 | for (int j = 0; j < fp->uf_lines.ga_len && !got_int; j++) { |
21205 | if (FUNCLINE(fp, j) == NULL) { |
21206 | continue; |
21207 | } |
21208 | msg_putchar('\n'); |
21209 | if (!eap->forceit) { |
21210 | msg_outnum((long)j + 1); |
21211 | if (j < 9) { |
21212 | msg_putchar(' '); |
21213 | } |
21214 | if (j < 99) { |
21215 | msg_putchar(' '); |
21216 | } |
21217 | } |
21218 | msg_prt_line(FUNCLINE(fp, j), false); |
21219 | ui_flush(); // show a line at a time |
21220 | os_breakcheck(); |
21221 | } |
21222 | if (!got_int) { |
21223 | msg_putchar('\n'); |
21224 | msg_puts(eap->forceit ? "endfunction" : " endfunction" ); |
21225 | } |
21226 | } else |
21227 | emsg_funcname(N_("E123: Undefined function: %s" ), name); |
21228 | } |
21229 | goto ret_free; |
21230 | } |
21231 | |
21232 | /* |
21233 | * ":function name(arg1, arg2)" Define function. |
21234 | */ |
21235 | p = skipwhite(p); |
21236 | if (*p != '(') { |
21237 | if (!eap->skip) { |
21238 | EMSG2(_("E124: Missing '(': %s" ), eap->arg); |
21239 | goto ret_free; |
21240 | } |
21241 | /* attempt to continue by skipping some text */ |
21242 | if (vim_strchr(p, '(') != NULL) |
21243 | p = vim_strchr(p, '('); |
21244 | } |
21245 | p = skipwhite(p + 1); |
21246 | |
21247 | ga_init(&newargs, (int)sizeof(char_u *), 3); |
21248 | ga_init(&newlines, (int)sizeof(char_u *), 3); |
21249 | |
21250 | if (!eap->skip) { |
21251 | /* Check the name of the function. Unless it's a dictionary function |
21252 | * (that we are overwriting). */ |
21253 | if (name != NULL) |
21254 | arg = name; |
21255 | else |
21256 | arg = fudi.fd_newkey; |
21257 | if (arg != NULL && (fudi.fd_di == NULL || !tv_is_func(fudi.fd_di->di_tv))) { |
21258 | int j = (*arg == K_SPECIAL) ? 3 : 0; |
21259 | while (arg[j] != NUL && (j == 0 ? eval_isnamec1(arg[j]) |
21260 | : eval_isnamec(arg[j]))) |
21261 | ++j; |
21262 | if (arg[j] != NUL) |
21263 | emsg_funcname((char *)e_invarg2, arg); |
21264 | } |
21265 | /* Disallow using the g: dict. */ |
21266 | if (fudi.fd_dict != NULL && fudi.fd_dict->dv_scope == VAR_DEF_SCOPE) |
21267 | EMSG(_("E862: Cannot use g: here" )); |
21268 | } |
21269 | |
21270 | if (get_function_args(&p, ')', &newargs, &varargs, eap->skip) == FAIL) { |
21271 | goto errret_2; |
21272 | } |
21273 | |
21274 | if (KeyTyped && ui_has(kUICmdline)) { |
21275 | show_block = true; |
21276 | ui_ext_cmdline_block_append(0, (const char *)eap->cmd); |
21277 | } |
21278 | |
21279 | // find extra arguments "range", "dict", "abort" and "closure" |
21280 | for (;; ) { |
21281 | p = skipwhite(p); |
21282 | if (STRNCMP(p, "range" , 5) == 0) { |
21283 | flags |= FC_RANGE; |
21284 | p += 5; |
21285 | } else if (STRNCMP(p, "dict" , 4) == 0) { |
21286 | flags |= FC_DICT; |
21287 | p += 4; |
21288 | } else if (STRNCMP(p, "abort" , 5) == 0) { |
21289 | flags |= FC_ABORT; |
21290 | p += 5; |
21291 | } else if (STRNCMP(p, "closure" , 7) == 0) { |
21292 | flags |= FC_CLOSURE; |
21293 | p += 7; |
21294 | if (current_funccal == NULL) { |
21295 | emsg_funcname(N_ |
21296 | ("E932: Closure function should not be at top level: %s" ), |
21297 | name == NULL ? (char_u *)"" : name); |
21298 | goto erret; |
21299 | } |
21300 | } else { |
21301 | break; |
21302 | } |
21303 | } |
21304 | |
21305 | /* When there is a line break use what follows for the function body. |
21306 | * Makes 'exe "func Test()\n...\nendfunc"' work. */ |
21307 | if (*p == '\n') { |
21308 | line_arg = p + 1; |
21309 | } else if (*p != NUL && *p != '"' && !eap->skip && !did_emsg) { |
21310 | EMSG(_(e_trailing)); |
21311 | } |
21312 | |
21313 | /* |
21314 | * Read the body of the function, until ":endfunction" is found. |
21315 | */ |
21316 | if (KeyTyped) { |
21317 | /* Check if the function already exists, don't let the user type the |
21318 | * whole function before telling him it doesn't work! For a script we |
21319 | * need to skip the body to be able to find what follows. */ |
21320 | if (!eap->skip && !eap->forceit) { |
21321 | if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL) |
21322 | EMSG(_(e_funcdict)); |
21323 | else if (name != NULL && find_func(name) != NULL) |
21324 | emsg_funcname(e_funcexts, name); |
21325 | } |
21326 | |
21327 | if (!eap->skip && did_emsg) |
21328 | goto erret; |
21329 | |
21330 | if (!ui_has(kUICmdline)) { |
21331 | msg_putchar('\n'); // don't overwrite the function name |
21332 | } |
21333 | cmdline_row = msg_row; |
21334 | } |
21335 | |
21336 | indent = 2; |
21337 | nesting = 0; |
21338 | for (;; ) { |
21339 | if (KeyTyped) { |
21340 | msg_scroll = TRUE; |
21341 | saved_wait_return = FALSE; |
21342 | } |
21343 | need_wait_return = FALSE; |
21344 | sourcing_lnum_off = sourcing_lnum; |
21345 | |
21346 | if (line_arg != NULL) { |
21347 | /* Use eap->arg, split up in parts by line breaks. */ |
21348 | theline = line_arg; |
21349 | p = vim_strchr(theline, '\n'); |
21350 | if (p == NULL) |
21351 | line_arg += STRLEN(line_arg); |
21352 | else { |
21353 | *p = NUL; |
21354 | line_arg = p + 1; |
21355 | } |
21356 | } else { |
21357 | xfree(line_to_free); |
21358 | if (eap->getline == NULL) { |
21359 | theline = getcmdline(':', 0L, indent); |
21360 | } else { |
21361 | theline = eap->getline(':', eap->cookie, indent); |
21362 | } |
21363 | line_to_free = theline; |
21364 | } |
21365 | if (KeyTyped) { |
21366 | lines_left = Rows - 1; |
21367 | } |
21368 | if (theline == NULL) { |
21369 | EMSG(_("E126: Missing :endfunction" )); |
21370 | goto erret; |
21371 | } |
21372 | if (show_block) { |
21373 | assert(indent >= 0); |
21374 | ui_ext_cmdline_block_append((size_t)indent, (const char *)theline); |
21375 | } |
21376 | |
21377 | /* Detect line continuation: sourcing_lnum increased more than one. */ |
21378 | if (sourcing_lnum > sourcing_lnum_off + 1) |
21379 | sourcing_lnum_off = sourcing_lnum - sourcing_lnum_off - 1; |
21380 | else |
21381 | sourcing_lnum_off = 0; |
21382 | |
21383 | if (skip_until != NULL) { |
21384 | /* between ":append" and "." and between ":python <<EOF" and "EOF" |
21385 | * don't check for ":endfunc". */ |
21386 | if (STRCMP(theline, skip_until) == 0) { |
21387 | XFREE_CLEAR(skip_until); |
21388 | } |
21389 | } else { |
21390 | /* skip ':' and blanks*/ |
21391 | for (p = theline; ascii_iswhite(*p) || *p == ':'; ++p) |
21392 | ; |
21393 | |
21394 | /* Check for "endfunction". */ |
21395 | if (checkforcmd(&p, "endfunction" , 4) && nesting-- == 0) { |
21396 | if (*p == '!') { |
21397 | p++; |
21398 | } |
21399 | char_u *nextcmd = NULL; |
21400 | if (*p == '|') { |
21401 | nextcmd = p + 1; |
21402 | } else if (line_arg != NULL && *skipwhite(line_arg) != NUL) { |
21403 | nextcmd = line_arg; |
21404 | } else if (*p != NUL && *p != '"' && p_verbose > 0) { |
21405 | give_warning2((char_u *)_("W22: Text found after :endfunction: %s" ), |
21406 | p, true); |
21407 | } |
21408 | if (nextcmd != NULL) { |
21409 | // Another command follows. If the line came from "eap" we |
21410 | // can simply point into it, otherwise we need to change |
21411 | // "eap->cmdlinep". |
21412 | eap->nextcmd = nextcmd; |
21413 | if (line_to_free != NULL) { |
21414 | xfree(*eap->cmdlinep); |
21415 | *eap->cmdlinep = line_to_free; |
21416 | line_to_free = NULL; |
21417 | } |
21418 | } |
21419 | break; |
21420 | } |
21421 | |
21422 | /* Increase indent inside "if", "while", "for" and "try", decrease |
21423 | * at "end". */ |
21424 | if (indent > 2 && STRNCMP(p, "end" , 3) == 0) |
21425 | indent -= 2; |
21426 | else if (STRNCMP(p, "if" , 2) == 0 |
21427 | || STRNCMP(p, "wh" , 2) == 0 |
21428 | || STRNCMP(p, "for" , 3) == 0 |
21429 | || STRNCMP(p, "try" , 3) == 0) |
21430 | indent += 2; |
21431 | |
21432 | /* Check for defining a function inside this function. */ |
21433 | if (checkforcmd(&p, "function" , 2)) { |
21434 | if (*p == '!') { |
21435 | p = skipwhite(p + 1); |
21436 | } |
21437 | p += eval_fname_script((const char *)p); |
21438 | xfree(trans_function_name(&p, true, 0, NULL, NULL)); |
21439 | if (*skipwhite(p) == '(') { |
21440 | nesting++; |
21441 | indent += 2; |
21442 | } |
21443 | } |
21444 | |
21445 | // Check for ":append", ":change", ":insert". |
21446 | p = skip_range(p, NULL); |
21447 | if ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p')) |
21448 | || (p[0] == 'c' |
21449 | && (!ASCII_ISALPHA(p[1]) |
21450 | || (p[1] == 'h' && (!ASCII_ISALPHA(p[2]) |
21451 | || (p[2] == 'a' |
21452 | && (STRNCMP(&p[3], "nge" , 3) != 0 |
21453 | || !ASCII_ISALPHA(p[6]))))))) |
21454 | || (p[0] == 'i' |
21455 | && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n' |
21456 | && (!ASCII_ISALPHA(p[2]) |
21457 | || (p[2] == 's')))))) { |
21458 | skip_until = vim_strsave((char_u *)"." ); |
21459 | } |
21460 | |
21461 | // heredoc: Check for ":python <<EOF", ":lua <<EOF", etc. |
21462 | arg = skipwhite(skiptowhite(p)); |
21463 | if (arg[0] == '<' && arg[1] =='<' |
21464 | && ((p[0] == 'p' && p[1] == 'y' |
21465 | && (!ASCII_ISALNUM(p[2]) || p[2] == 't' |
21466 | || ((p[2] == '3' || p[2] == 'x') |
21467 | && !ASCII_ISALPHA(p[3])))) |
21468 | || (p[0] == 'p' && p[1] == 'e' |
21469 | && (!ASCII_ISALPHA(p[2]) || p[2] == 'r')) |
21470 | || (p[0] == 't' && p[1] == 'c' |
21471 | && (!ASCII_ISALPHA(p[2]) || p[2] == 'l')) |
21472 | || (p[0] == 'l' && p[1] == 'u' && p[2] == 'a' |
21473 | && !ASCII_ISALPHA(p[3])) |
21474 | || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b' |
21475 | && (!ASCII_ISALPHA(p[3]) || p[3] == 'y')) |
21476 | || (p[0] == 'm' && p[1] == 'z' |
21477 | && (!ASCII_ISALPHA(p[2]) || p[2] == 's')) |
21478 | )) { |
21479 | /* ":python <<" continues until a dot, like ":append" */ |
21480 | p = skipwhite(arg + 2); |
21481 | if (*p == NUL) |
21482 | skip_until = vim_strsave((char_u *)"." ); |
21483 | else |
21484 | skip_until = vim_strsave(p); |
21485 | } |
21486 | } |
21487 | |
21488 | /* Add the line to the function. */ |
21489 | ga_grow(&newlines, 1 + sourcing_lnum_off); |
21490 | |
21491 | /* Copy the line to newly allocated memory. get_one_sourceline() |
21492 | * allocates 250 bytes per line, this saves 80% on average. The cost |
21493 | * is an extra alloc/free. */ |
21494 | p = vim_strsave(theline); |
21495 | ((char_u **)(newlines.ga_data))[newlines.ga_len++] = p; |
21496 | |
21497 | /* Add NULL lines for continuation lines, so that the line count is |
21498 | * equal to the index in the growarray. */ |
21499 | while (sourcing_lnum_off-- > 0) |
21500 | ((char_u **)(newlines.ga_data))[newlines.ga_len++] = NULL; |
21501 | |
21502 | /* Check for end of eap->arg. */ |
21503 | if (line_arg != NULL && *line_arg == NUL) |
21504 | line_arg = NULL; |
21505 | } |
21506 | |
21507 | /* Don't define the function when skipping commands or when an error was |
21508 | * detected. */ |
21509 | if (eap->skip || did_emsg) |
21510 | goto erret; |
21511 | |
21512 | /* |
21513 | * If there are no errors, add the function |
21514 | */ |
21515 | if (fudi.fd_dict == NULL) { |
21516 | v = find_var((const char *)name, STRLEN(name), &ht, false); |
21517 | if (v != NULL && v->di_tv.v_type == VAR_FUNC) { |
21518 | emsg_funcname(N_("E707: Function name conflicts with variable: %s" ), |
21519 | name); |
21520 | goto erret; |
21521 | } |
21522 | |
21523 | fp = find_func(name); |
21524 | if (fp != NULL) { |
21525 | // Function can be replaced with "function!" and when sourcing the |
21526 | // same script again, but only once. |
21527 | if (!eap->forceit |
21528 | && (fp->uf_script_ctx.sc_sid != current_sctx.sc_sid |
21529 | || fp->uf_script_ctx.sc_seq == current_sctx.sc_seq)) { |
21530 | emsg_funcname(e_funcexts, name); |
21531 | goto erret; |
21532 | } |
21533 | if (fp->uf_calls > 0) { |
21534 | emsg_funcname(N_("E127: Cannot redefine function %s: It is in use" ), |
21535 | name); |
21536 | goto erret; |
21537 | } |
21538 | if (fp->uf_refcount > 1) { |
21539 | // This function is referenced somewhere, don't redefine it but |
21540 | // create a new one. |
21541 | (fp->uf_refcount)--; |
21542 | fp->uf_flags |= FC_REMOVED; |
21543 | fp = NULL; |
21544 | overwrite = true; |
21545 | } else { |
21546 | // redefine existing function |
21547 | XFREE_CLEAR(name); |
21548 | func_clear_items(fp); |
21549 | fp->uf_profiling = false; |
21550 | fp->uf_prof_initialized = false; |
21551 | } |
21552 | } |
21553 | } else { |
21554 | char numbuf[20]; |
21555 | |
21556 | fp = NULL; |
21557 | if (fudi.fd_newkey == NULL && !eap->forceit) { |
21558 | EMSG(_(e_funcdict)); |
21559 | goto erret; |
21560 | } |
21561 | if (fudi.fd_di == NULL) { |
21562 | if (tv_check_lock(fudi.fd_dict->dv_lock, (const char *)eap->arg, |
21563 | TV_CSTRING)) { |
21564 | // Can't add a function to a locked dictionary |
21565 | goto erret; |
21566 | } |
21567 | } else if (tv_check_lock(fudi.fd_di->di_tv.v_lock, (const char *)eap->arg, |
21568 | TV_CSTRING)) { |
21569 | // Can't change an existing function if it is locked |
21570 | goto erret; |
21571 | } |
21572 | |
21573 | /* Give the function a sequential number. Can only be used with a |
21574 | * Funcref! */ |
21575 | xfree(name); |
21576 | sprintf(numbuf, "%d" , ++func_nr); |
21577 | name = vim_strsave((char_u *)numbuf); |
21578 | } |
21579 | |
21580 | if (fp == NULL) { |
21581 | if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL) { |
21582 | int slen, plen; |
21583 | char_u *scriptname; |
21584 | |
21585 | /* Check that the autoload name matches the script name. */ |
21586 | int j = FAIL; |
21587 | if (sourcing_name != NULL) { |
21588 | scriptname = (char_u *)autoload_name((const char *)name, STRLEN(name)); |
21589 | p = vim_strchr(scriptname, '/'); |
21590 | plen = (int)STRLEN(p); |
21591 | slen = (int)STRLEN(sourcing_name); |
21592 | if (slen > plen && fnamecmp(p, |
21593 | sourcing_name + slen - plen) == 0) |
21594 | j = OK; |
21595 | xfree(scriptname); |
21596 | } |
21597 | if (j == FAIL) { |
21598 | EMSG2(_( |
21599 | "E746: Function name does not match script file name: %s" ), |
21600 | name); |
21601 | goto erret; |
21602 | } |
21603 | } |
21604 | |
21605 | fp = xcalloc(1, offsetof(ufunc_T, uf_name) + STRLEN(name) + 1); |
21606 | |
21607 | if (fudi.fd_dict != NULL) { |
21608 | if (fudi.fd_di == NULL) { |
21609 | // Add new dict entry |
21610 | fudi.fd_di = tv_dict_item_alloc((const char *)fudi.fd_newkey); |
21611 | if (tv_dict_add(fudi.fd_dict, fudi.fd_di) == FAIL) { |
21612 | xfree(fudi.fd_di); |
21613 | xfree(fp); |
21614 | goto erret; |
21615 | } |
21616 | } else { |
21617 | // Overwrite existing dict entry. |
21618 | tv_clear(&fudi.fd_di->di_tv); |
21619 | } |
21620 | fudi.fd_di->di_tv.v_type = VAR_FUNC; |
21621 | fudi.fd_di->di_tv.vval.v_string = vim_strsave(name); |
21622 | |
21623 | /* behave like "dict" was used */ |
21624 | flags |= FC_DICT; |
21625 | } |
21626 | |
21627 | /* insert the new function in the function list */ |
21628 | STRCPY(fp->uf_name, name); |
21629 | if (overwrite) { |
21630 | hi = hash_find(&func_hashtab, name); |
21631 | hi->hi_key = UF2HIKEY(fp); |
21632 | } else if (hash_add(&func_hashtab, UF2HIKEY(fp)) == FAIL) { |
21633 | xfree(fp); |
21634 | goto erret; |
21635 | } |
21636 | fp->uf_refcount = 1; |
21637 | } |
21638 | fp->uf_args = newargs; |
21639 | fp->uf_lines = newlines; |
21640 | if ((flags & FC_CLOSURE) != 0) { |
21641 | register_closure(fp); |
21642 | } else { |
21643 | fp->uf_scoped = NULL; |
21644 | } |
21645 | if (prof_def_func()) { |
21646 | func_do_profile(fp); |
21647 | } |
21648 | fp->uf_varargs = varargs; |
21649 | if (sandbox) { |
21650 | flags |= FC_SANDBOX; |
21651 | } |
21652 | fp->uf_flags = flags; |
21653 | fp->uf_calls = 0; |
21654 | fp->uf_script_ctx = current_sctx; |
21655 | fp->uf_script_ctx.sc_lnum += sourcing_lnum - newlines.ga_len - 1; |
21656 | goto ret_free; |
21657 | |
21658 | erret: |
21659 | ga_clear_strings(&newargs); |
21660 | errret_2: |
21661 | ga_clear_strings(&newlines); |
21662 | ret_free: |
21663 | xfree(skip_until); |
21664 | xfree(line_to_free); |
21665 | xfree(fudi.fd_newkey); |
21666 | xfree(name); |
21667 | did_emsg |= saved_did_emsg; |
21668 | need_wait_return |= saved_wait_return; |
21669 | if (show_block) { |
21670 | ui_ext_cmdline_block_leave(); |
21671 | } |
21672 | } |
21673 | |
21674 | /// Get a function name, translating "<SID>" and "<SNR>". |
21675 | /// Also handles a Funcref in a List or Dictionary. |
21676 | /// flags: |
21677 | /// TFN_INT: internal function name OK |
21678 | /// TFN_QUIET: be quiet |
21679 | /// TFN_NO_AUTOLOAD: do not use script autoloading |
21680 | /// TFN_NO_DEREF: do not dereference a Funcref |
21681 | /// Advances "pp" to just after the function name (if no error). |
21682 | /// |
21683 | /// @return the function name in allocated memory, or NULL for failure. |
21684 | static char_u * |
21685 | trans_function_name( |
21686 | char_u **pp, |
21687 | int skip, // only find the end, don't evaluate |
21688 | int flags, |
21689 | funcdict_T *fdp, // return: info about dictionary used |
21690 | partial_T **partial // return: partial of a FuncRef |
21691 | ) |
21692 | { |
21693 | char_u *name = NULL; |
21694 | const char_u *start; |
21695 | const char_u *end; |
21696 | int lead; |
21697 | int len; |
21698 | lval_T lv; |
21699 | |
21700 | if (fdp != NULL) |
21701 | memset(fdp, 0, sizeof(funcdict_T)); |
21702 | start = *pp; |
21703 | |
21704 | /* Check for hard coded <SNR>: already translated function ID (from a user |
21705 | * command). */ |
21706 | if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA |
21707 | && (*pp)[2] == (int)KE_SNR) { |
21708 | *pp += 3; |
21709 | len = get_id_len((const char **)pp) + 3; |
21710 | return (char_u *)xmemdupz(start, len); |
21711 | } |
21712 | |
21713 | /* A name starting with "<SID>" or "<SNR>" is local to a script. But |
21714 | * don't skip over "s:", get_lval() needs it for "s:dict.func". */ |
21715 | lead = eval_fname_script((const char *)start); |
21716 | if (lead > 2) { |
21717 | start += lead; |
21718 | } |
21719 | |
21720 | // Note that TFN_ flags use the same values as GLV_ flags. |
21721 | end = get_lval((char_u *)start, NULL, &lv, false, skip, flags | GLV_READ_ONLY, |
21722 | lead > 2 ? 0 : FNE_CHECK_START); |
21723 | if (end == start) { |
21724 | if (!skip) |
21725 | EMSG(_("E129: Function name required" )); |
21726 | goto theend; |
21727 | } |
21728 | if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range))) { |
21729 | /* |
21730 | * Report an invalid expression in braces, unless the expression |
21731 | * evaluation has been cancelled due to an aborting error, an |
21732 | * interrupt, or an exception. |
21733 | */ |
21734 | if (!aborting()) { |
21735 | if (end != NULL) { |
21736 | emsgf(_(e_invarg2), start); |
21737 | } |
21738 | } else { |
21739 | *pp = (char_u *)find_name_end(start, NULL, NULL, FNE_INCL_BR); |
21740 | } |
21741 | goto theend; |
21742 | } |
21743 | |
21744 | if (lv.ll_tv != NULL) { |
21745 | if (fdp != NULL) { |
21746 | fdp->fd_dict = lv.ll_dict; |
21747 | fdp->fd_newkey = lv.ll_newkey; |
21748 | lv.ll_newkey = NULL; |
21749 | fdp->fd_di = lv.ll_di; |
21750 | } |
21751 | if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL) { |
21752 | name = vim_strsave(lv.ll_tv->vval.v_string); |
21753 | *pp = (char_u *)end; |
21754 | } else if (lv.ll_tv->v_type == VAR_PARTIAL |
21755 | && lv.ll_tv->vval.v_partial != NULL) { |
21756 | name = vim_strsave(partial_name(lv.ll_tv->vval.v_partial)); |
21757 | *pp = (char_u *)end; |
21758 | if (partial != NULL) { |
21759 | *partial = lv.ll_tv->vval.v_partial; |
21760 | } |
21761 | } else { |
21762 | if (!skip && !(flags & TFN_QUIET) && (fdp == NULL |
21763 | || lv.ll_dict == NULL |
21764 | || fdp->fd_newkey == NULL)) { |
21765 | EMSG(_(e_funcref)); |
21766 | } else { |
21767 | *pp = (char_u *)end; |
21768 | } |
21769 | name = NULL; |
21770 | } |
21771 | goto theend; |
21772 | } |
21773 | |
21774 | if (lv.ll_name == NULL) { |
21775 | // Error found, but continue after the function name. |
21776 | *pp = (char_u *)end; |
21777 | goto theend; |
21778 | } |
21779 | |
21780 | /* Check if the name is a Funcref. If so, use the value. */ |
21781 | if (lv.ll_exp_name != NULL) { |
21782 | len = (int)strlen(lv.ll_exp_name); |
21783 | name = deref_func_name(lv.ll_exp_name, &len, partial, |
21784 | flags & TFN_NO_AUTOLOAD); |
21785 | if ((const char *)name == lv.ll_exp_name) { |
21786 | name = NULL; |
21787 | } |
21788 | } else if (!(flags & TFN_NO_DEREF)) { |
21789 | len = (int)(end - *pp); |
21790 | name = deref_func_name((const char *)(*pp), &len, partial, |
21791 | flags & TFN_NO_AUTOLOAD); |
21792 | if (name == *pp) { |
21793 | name = NULL; |
21794 | } |
21795 | } |
21796 | if (name != NULL) { |
21797 | name = vim_strsave(name); |
21798 | *pp = (char_u *)end; |
21799 | if (strncmp((char *)name, "<SNR>" , 5) == 0) { |
21800 | // Change "<SNR>" to the byte sequence. |
21801 | name[0] = K_SPECIAL; |
21802 | name[1] = KS_EXTRA; |
21803 | name[2] = (int)KE_SNR; |
21804 | memmove(name + 3, name + 5, strlen((char *)name + 5) + 1); |
21805 | } |
21806 | goto theend; |
21807 | } |
21808 | |
21809 | if (lv.ll_exp_name != NULL) { |
21810 | len = (int)strlen(lv.ll_exp_name); |
21811 | if (lead <= 2 && lv.ll_name == lv.ll_exp_name |
21812 | && lv.ll_name_len >= 2 && memcmp(lv.ll_name, "s:" , 2) == 0) { |
21813 | // When there was "s:" already or the name expanded to get a |
21814 | // leading "s:" then remove it. |
21815 | lv.ll_name += 2; |
21816 | lv.ll_name_len -= 2; |
21817 | len -= 2; |
21818 | lead = 2; |
21819 | } |
21820 | } else { |
21821 | // Skip over "s:" and "g:". |
21822 | if (lead == 2 || (lv.ll_name[0] == 'g' && lv.ll_name[1] == ':')) { |
21823 | lv.ll_name += 2; |
21824 | lv.ll_name_len -= 2; |
21825 | } |
21826 | len = (int)((const char *)end - lv.ll_name); |
21827 | } |
21828 | |
21829 | size_t sid_buf_len = 0; |
21830 | char sid_buf[20]; |
21831 | |
21832 | // Copy the function name to allocated memory. |
21833 | // Accept <SID>name() inside a script, translate into <SNR>123_name(). |
21834 | // Accept <SNR>123_name() outside a script. |
21835 | if (skip) { |
21836 | lead = 0; // do nothing |
21837 | } else if (lead > 0) { |
21838 | lead = 3; |
21839 | if ((lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name)) |
21840 | || eval_fname_sid((const char *)(*pp))) { |
21841 | // It's "s:" or "<SID>". |
21842 | if (current_sctx.sc_sid <= 0) { |
21843 | EMSG(_(e_usingsid)); |
21844 | goto theend; |
21845 | } |
21846 | sid_buf_len = snprintf(sid_buf, sizeof(sid_buf), |
21847 | "%" PRIdSCID "_" , current_sctx.sc_sid); |
21848 | lead += sid_buf_len; |
21849 | } |
21850 | } else if (!(flags & TFN_INT) |
21851 | && builtin_function(lv.ll_name, lv.ll_name_len)) { |
21852 | EMSG2(_("E128: Function name must start with a capital or \"s:\": %s" ), |
21853 | start); |
21854 | goto theend; |
21855 | } |
21856 | |
21857 | if (!skip && !(flags & TFN_QUIET) && !(flags & TFN_NO_DEREF)) { |
21858 | char_u *cp = xmemrchr(lv.ll_name, ':', lv.ll_name_len); |
21859 | |
21860 | if (cp != NULL && cp < end) { |
21861 | EMSG2(_("E884: Function name cannot contain a colon: %s" ), start); |
21862 | goto theend; |
21863 | } |
21864 | } |
21865 | |
21866 | name = xmalloc(len + lead + 1); |
21867 | if (lead > 0){ |
21868 | name[0] = K_SPECIAL; |
21869 | name[1] = KS_EXTRA; |
21870 | name[2] = (int)KE_SNR; |
21871 | if (sid_buf_len > 0) { // If it's "<SID>" |
21872 | memcpy(name + 3, sid_buf, sid_buf_len); |
21873 | } |
21874 | } |
21875 | memmove(name + lead, lv.ll_name, len); |
21876 | name[lead + len] = NUL; |
21877 | *pp = (char_u *)end; |
21878 | |
21879 | theend: |
21880 | clear_lval(&lv); |
21881 | return name; |
21882 | } |
21883 | |
21884 | /* |
21885 | * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case). |
21886 | * Return 2 if "p" starts with "s:". |
21887 | * Return 0 otherwise. |
21888 | */ |
21889 | static int eval_fname_script(const char *const p) |
21890 | { |
21891 | // Use mb_strnicmp() because in Turkish comparing the "I" may not work with |
21892 | // the standard library function. |
21893 | if (p[0] == '<' |
21894 | && (mb_strnicmp((char_u *)p + 1, (char_u *)"SID>" , 4) == 0 |
21895 | || mb_strnicmp((char_u *)p + 1, (char_u *)"SNR>" , 4) == 0)) { |
21896 | return 5; |
21897 | } |
21898 | if (p[0] == 's' && p[1] == ':') { |
21899 | return 2; |
21900 | } |
21901 | return 0; |
21902 | } |
21903 | |
21904 | /// Check whether function name starts with <SID> or s: |
21905 | /// |
21906 | /// @warning Only works for names previously checked by eval_fname_script(), if |
21907 | /// it returned non-zero. |
21908 | /// |
21909 | /// @param[in] name Name to check. |
21910 | /// |
21911 | /// @return true if it starts with <SID> or s:, false otherwise. |
21912 | static inline bool eval_fname_sid(const char *const name) |
21913 | FUNC_ATTR_PURE FUNC_ATTR_ALWAYS_INLINE FUNC_ATTR_WARN_UNUSED_RESULT |
21914 | FUNC_ATTR_NONNULL_ALL |
21915 | { |
21916 | return *name == 's' || TOUPPER_ASC(name[2]) == 'I'; |
21917 | } |
21918 | |
21919 | /// List the head of the function: "name(arg1, arg2)". |
21920 | /// |
21921 | /// @param[in] fp Function pointer. |
21922 | /// @param[in] indent Indent line. |
21923 | /// @param[in] force Include bang "!" (i.e.: "function!"). |
21924 | static void list_func_head(ufunc_T *fp, int indent, bool force) |
21925 | { |
21926 | msg_start(); |
21927 | if (indent) |
21928 | MSG_PUTS(" " ); |
21929 | MSG_PUTS(force ? "function! " : "function " ); |
21930 | if (fp->uf_name[0] == K_SPECIAL) { |
21931 | MSG_PUTS_ATTR("<SNR>" , HL_ATTR(HLF_8)); |
21932 | msg_puts((const char *)fp->uf_name + 3); |
21933 | } else { |
21934 | msg_puts((const char *)fp->uf_name); |
21935 | } |
21936 | msg_putchar('('); |
21937 | int j; |
21938 | for (j = 0; j < fp->uf_args.ga_len; j++) { |
21939 | if (j) { |
21940 | msg_puts(", " ); |
21941 | } |
21942 | msg_puts((const char *)FUNCARG(fp, j)); |
21943 | } |
21944 | if (fp->uf_varargs) { |
21945 | if (j) { |
21946 | msg_puts(", " ); |
21947 | } |
21948 | msg_puts("..." ); |
21949 | } |
21950 | msg_putchar(')'); |
21951 | if (fp->uf_flags & FC_ABORT) { |
21952 | msg_puts(" abort" ); |
21953 | } |
21954 | if (fp->uf_flags & FC_RANGE) { |
21955 | msg_puts(" range" ); |
21956 | } |
21957 | if (fp->uf_flags & FC_DICT) { |
21958 | msg_puts(" dict" ); |
21959 | } |
21960 | if (fp->uf_flags & FC_CLOSURE) { |
21961 | msg_puts(" closure" ); |
21962 | } |
21963 | msg_clr_eos(); |
21964 | if (p_verbose > 0) { |
21965 | last_set_msg(fp->uf_script_ctx); |
21966 | } |
21967 | } |
21968 | |
21969 | /// Find a function by name, return pointer to it in ufuncs. |
21970 | /// @return NULL for unknown function. |
21971 | static ufunc_T *find_func(const char_u *name) |
21972 | { |
21973 | hashitem_T *hi; |
21974 | |
21975 | hi = hash_find(&func_hashtab, name); |
21976 | if (!HASHITEM_EMPTY(hi)) |
21977 | return HI2UF(hi); |
21978 | return NULL; |
21979 | } |
21980 | |
21981 | #if defined(EXITFREE) |
21982 | void free_all_functions(void) |
21983 | { |
21984 | hashitem_T *hi; |
21985 | ufunc_T *fp; |
21986 | uint64_t skipped = 0; |
21987 | uint64_t todo = 1; |
21988 | uint64_t used; |
21989 | |
21990 | // Clean up the call stack. |
21991 | while (current_funccal != NULL) { |
21992 | tv_clear(current_funccal->rettv); |
21993 | cleanup_function_call(current_funccal); |
21994 | } |
21995 | |
21996 | // First clear what the functions contain. Since this may lower the |
21997 | // reference count of a function, it may also free a function and change |
21998 | // the hash table. Restart if that happens. |
21999 | while (todo > 0) { |
22000 | todo = func_hashtab.ht_used; |
22001 | for (hi = func_hashtab.ht_array; todo > 0; hi++) { |
22002 | if (!HASHITEM_EMPTY(hi)) { |
22003 | // Only free functions that are not refcounted, those are |
22004 | // supposed to be freed when no longer referenced. |
22005 | fp = HI2UF(hi); |
22006 | if (func_name_refcount(fp->uf_name)) { |
22007 | skipped++; |
22008 | } else { |
22009 | used = func_hashtab.ht_used; |
22010 | func_clear(fp, true); |
22011 | if (used != func_hashtab.ht_used) { |
22012 | skipped = 0; |
22013 | break; |
22014 | } |
22015 | } |
22016 | todo--; |
22017 | } |
22018 | } |
22019 | } |
22020 | |
22021 | // Now actually free the functions. Need to start all over every time, |
22022 | // because func_free() may change the hash table. |
22023 | skipped = 0; |
22024 | while (func_hashtab.ht_used > skipped) { |
22025 | todo = func_hashtab.ht_used; |
22026 | for (hi = func_hashtab.ht_array; todo > 0; hi++) { |
22027 | if (!HASHITEM_EMPTY(hi)) { |
22028 | todo--; |
22029 | // Only free functions that are not refcounted, those are |
22030 | // supposed to be freed when no longer referenced. |
22031 | fp = HI2UF(hi); |
22032 | if (func_name_refcount(fp->uf_name)) { |
22033 | skipped++; |
22034 | } else { |
22035 | func_free(fp); |
22036 | skipped = 0; |
22037 | break; |
22038 | } |
22039 | } |
22040 | } |
22041 | } |
22042 | if (skipped == 0) { |
22043 | hash_clear(&func_hashtab); |
22044 | } |
22045 | } |
22046 | |
22047 | #endif |
22048 | |
22049 | bool translated_function_exists(const char *name) |
22050 | { |
22051 | if (builtin_function(name, -1)) { |
22052 | return find_internal_func((char *)name) != NULL; |
22053 | } |
22054 | return find_func((const char_u *)name) != NULL; |
22055 | } |
22056 | |
22057 | /// Check whether function with the given name exists |
22058 | /// |
22059 | /// @param[in] name Function name. |
22060 | /// @param[in] no_deref Whether to dereference a Funcref. |
22061 | /// |
22062 | /// @return True if it exists, false otherwise. |
22063 | static bool function_exists(const char *const name, bool no_deref) |
22064 | { |
22065 | const char_u *nm = (const char_u *)name; |
22066 | bool n = false; |
22067 | int flag = TFN_INT | TFN_QUIET | TFN_NO_AUTOLOAD; |
22068 | |
22069 | if (no_deref) { |
22070 | flag |= TFN_NO_DEREF; |
22071 | } |
22072 | char *const p = (char *)trans_function_name((char_u **)&nm, false, flag, NULL, |
22073 | NULL); |
22074 | nm = skipwhite(nm); |
22075 | |
22076 | /* Only accept "funcname", "funcname ", "funcname (..." and |
22077 | * "funcname(...", not "funcname!...". */ |
22078 | if (p != NULL && (*nm == NUL || *nm == '(')) { |
22079 | n = translated_function_exists(p); |
22080 | } |
22081 | xfree(p); |
22082 | return n; |
22083 | } |
22084 | |
22085 | /// Checks if a builtin function with the given name exists. |
22086 | /// |
22087 | /// @param[in] name name of the builtin function to check. |
22088 | /// @param[in] len length of "name", or -1 for NUL terminated. |
22089 | /// |
22090 | /// @return true if "name" looks like a builtin function name: starts with a |
22091 | /// lower case letter and doesn't contain AUTOLOAD_CHAR. |
22092 | static bool builtin_function(const char *name, int len) |
22093 | { |
22094 | if (!ASCII_ISLOWER(name[0])) { |
22095 | return false; |
22096 | } |
22097 | |
22098 | const char *p = (len == -1 |
22099 | ? strchr(name, AUTOLOAD_CHAR) |
22100 | : memchr(name, AUTOLOAD_CHAR, (size_t)len)); |
22101 | |
22102 | return p == NULL; |
22103 | } |
22104 | |
22105 | /* |
22106 | * Start profiling function "fp". |
22107 | */ |
22108 | static void func_do_profile(ufunc_T *fp) |
22109 | { |
22110 | int len = fp->uf_lines.ga_len; |
22111 | |
22112 | if (!fp->uf_prof_initialized) { |
22113 | if (len == 0) { |
22114 | len = 1; // avoid getting error for allocating zero bytes |
22115 | } |
22116 | fp->uf_tm_count = 0; |
22117 | fp->uf_tm_self = profile_zero(); |
22118 | fp->uf_tm_total = profile_zero(); |
22119 | |
22120 | if (fp->uf_tml_count == NULL) { |
22121 | fp->uf_tml_count = xcalloc(len, sizeof(int)); |
22122 | } |
22123 | |
22124 | if (fp->uf_tml_total == NULL) { |
22125 | fp->uf_tml_total = xcalloc(len, sizeof(proftime_T)); |
22126 | } |
22127 | |
22128 | if (fp->uf_tml_self == NULL) { |
22129 | fp->uf_tml_self = xcalloc(len, sizeof(proftime_T)); |
22130 | } |
22131 | |
22132 | fp->uf_tml_idx = -1; |
22133 | fp->uf_prof_initialized = true; |
22134 | } |
22135 | |
22136 | fp->uf_profiling = TRUE; |
22137 | } |
22138 | |
22139 | /* |
22140 | * Dump the profiling results for all functions in file "fd". |
22141 | */ |
22142 | void func_dump_profile(FILE *fd) |
22143 | { |
22144 | hashitem_T *hi; |
22145 | int todo; |
22146 | ufunc_T *fp; |
22147 | ufunc_T **sorttab; |
22148 | int st_len = 0; |
22149 | |
22150 | todo = (int)func_hashtab.ht_used; |
22151 | if (todo == 0) |
22152 | return; /* nothing to dump */ |
22153 | |
22154 | sorttab = xmalloc(sizeof(ufunc_T *) * todo); |
22155 | |
22156 | for (hi = func_hashtab.ht_array; todo > 0; ++hi) { |
22157 | if (!HASHITEM_EMPTY(hi)) { |
22158 | --todo; |
22159 | fp = HI2UF(hi); |
22160 | if (fp->uf_prof_initialized) { |
22161 | sorttab[st_len++] = fp; |
22162 | |
22163 | if (fp->uf_name[0] == K_SPECIAL) { |
22164 | fprintf(fd, "FUNCTION <SNR>%s()\n" , fp->uf_name + 3); |
22165 | } else { |
22166 | fprintf(fd, "FUNCTION %s()\n" , fp->uf_name); |
22167 | } |
22168 | if (fp->uf_script_ctx.sc_sid != 0) { |
22169 | bool should_free; |
22170 | const LastSet last_set = (LastSet){ |
22171 | .script_ctx = fp->uf_script_ctx, |
22172 | .channel_id = 0, |
22173 | }; |
22174 | char_u *p = get_scriptname(last_set, &should_free); |
22175 | fprintf(fd, " Defined: %s line %" PRIdLINENR "\n" , |
22176 | p, fp->uf_script_ctx.sc_lnum); |
22177 | if (should_free) { |
22178 | xfree(p); |
22179 | } |
22180 | } |
22181 | if (fp->uf_tm_count == 1) { |
22182 | fprintf(fd, "Called 1 time\n" ); |
22183 | } else { |
22184 | fprintf(fd, "Called %d times\n" , fp->uf_tm_count); |
22185 | } |
22186 | fprintf(fd, "Total time: %s\n" , profile_msg(fp->uf_tm_total)); |
22187 | fprintf(fd, " Self time: %s\n" , profile_msg(fp->uf_tm_self)); |
22188 | fprintf(fd, "\n" ); |
22189 | fprintf(fd, "count total (s) self (s)\n" ); |
22190 | |
22191 | for (int i = 0; i < fp->uf_lines.ga_len; ++i) { |
22192 | if (FUNCLINE(fp, i) == NULL) |
22193 | continue; |
22194 | prof_func_line(fd, fp->uf_tml_count[i], |
22195 | &fp->uf_tml_total[i], &fp->uf_tml_self[i], TRUE); |
22196 | fprintf(fd, "%s\n" , FUNCLINE(fp, i)); |
22197 | } |
22198 | fprintf(fd, "\n" ); |
22199 | } |
22200 | } |
22201 | } |
22202 | |
22203 | if (st_len > 0) { |
22204 | qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *), |
22205 | prof_total_cmp); |
22206 | prof_sort_list(fd, sorttab, st_len, "TOTAL" , FALSE); |
22207 | qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *), |
22208 | prof_self_cmp); |
22209 | prof_sort_list(fd, sorttab, st_len, "SELF" , TRUE); |
22210 | } |
22211 | |
22212 | xfree(sorttab); |
22213 | } |
22214 | |
22215 | static void |
22216 | prof_sort_list( |
22217 | FILE *fd, |
22218 | ufunc_T **sorttab, |
22219 | int st_len, |
22220 | char *title, |
22221 | int prefer_self /* when equal print only self time */ |
22222 | ) |
22223 | { |
22224 | int i; |
22225 | ufunc_T *fp; |
22226 | |
22227 | fprintf(fd, "FUNCTIONS SORTED ON %s TIME\n" , title); |
22228 | fprintf(fd, "count total (s) self (s) function\n" ); |
22229 | for (i = 0; i < 20 && i < st_len; ++i) { |
22230 | fp = sorttab[i]; |
22231 | prof_func_line(fd, fp->uf_tm_count, &fp->uf_tm_total, &fp->uf_tm_self, |
22232 | prefer_self); |
22233 | if (fp->uf_name[0] == K_SPECIAL) |
22234 | fprintf(fd, " <SNR>%s()\n" , fp->uf_name + 3); |
22235 | else |
22236 | fprintf(fd, " %s()\n" , fp->uf_name); |
22237 | } |
22238 | fprintf(fd, "\n" ); |
22239 | } |
22240 | |
22241 | /* |
22242 | * Print the count and times for one function or function line. |
22243 | */ |
22244 | static void prof_func_line( |
22245 | FILE *fd, |
22246 | int count, |
22247 | proftime_T *total, |
22248 | proftime_T *self, |
22249 | int prefer_self /* when equal print only self time */ |
22250 | ) |
22251 | { |
22252 | if (count > 0) { |
22253 | fprintf(fd, "%5d " , count); |
22254 | if (prefer_self && profile_equal(*total, *self)) |
22255 | fprintf(fd, " " ); |
22256 | else |
22257 | fprintf(fd, "%s " , profile_msg(*total)); |
22258 | if (!prefer_self && profile_equal(*total, *self)) |
22259 | fprintf(fd, " " ); |
22260 | else |
22261 | fprintf(fd, "%s " , profile_msg(*self)); |
22262 | } else |
22263 | fprintf(fd, " " ); |
22264 | } |
22265 | |
22266 | /* |
22267 | * Compare function for total time sorting. |
22268 | */ |
22269 | static int prof_total_cmp(const void *s1, const void *s2) |
22270 | { |
22271 | ufunc_T *p1 = *(ufunc_T **)s1; |
22272 | ufunc_T *p2 = *(ufunc_T **)s2; |
22273 | return profile_cmp(p1->uf_tm_total, p2->uf_tm_total); |
22274 | } |
22275 | |
22276 | /* |
22277 | * Compare function for self time sorting. |
22278 | */ |
22279 | static int prof_self_cmp(const void *s1, const void *s2) |
22280 | { |
22281 | ufunc_T *p1 = *(ufunc_T **)s1; |
22282 | ufunc_T *p2 = *(ufunc_T **)s2; |
22283 | return profile_cmp(p1->uf_tm_self, p2->uf_tm_self); |
22284 | } |
22285 | |
22286 | |
22287 | /// If name has a package name try autoloading the script for it |
22288 | /// |
22289 | /// @param[in] name Variable/function name. |
22290 | /// @param[in] name_len Name length. |
22291 | /// @param[in] reload If true, load script again when already loaded. |
22292 | /// |
22293 | /// @return true if a package was loaded. |
22294 | static bool script_autoload(const char *const name, const size_t name_len, |
22295 | const bool reload) |
22296 | { |
22297 | // If there is no '#' after name[0] there is no package name. |
22298 | const char *p = memchr(name, AUTOLOAD_CHAR, name_len); |
22299 | if (p == NULL || p == name) { |
22300 | return false; |
22301 | } |
22302 | |
22303 | bool ret = false; |
22304 | char *tofree = autoload_name(name, name_len); |
22305 | char *scriptname = tofree; |
22306 | |
22307 | // Find the name in the list of previously loaded package names. Skip |
22308 | // "autoload/", it's always the same. |
22309 | int i = 0; |
22310 | for (; i < ga_loaded.ga_len; i++) { |
22311 | if (STRCMP(((char **)ga_loaded.ga_data)[i] + 9, scriptname + 9) == 0) { |
22312 | break; |
22313 | } |
22314 | } |
22315 | if (!reload && i < ga_loaded.ga_len) { |
22316 | ret = false; // Was loaded already. |
22317 | } else { |
22318 | // Remember the name if it wasn't loaded already. |
22319 | if (i == ga_loaded.ga_len) { |
22320 | GA_APPEND(char *, &ga_loaded, scriptname); |
22321 | tofree = NULL; |
22322 | } |
22323 | |
22324 | // Try loading the package from $VIMRUNTIME/autoload/<name>.vim |
22325 | if (source_runtime((char_u *)scriptname, 0) == OK) { |
22326 | ret = true; |
22327 | } |
22328 | } |
22329 | |
22330 | xfree(tofree); |
22331 | return ret; |
22332 | } |
22333 | |
22334 | /// Return the autoload script name for a function or variable name |
22335 | /// Caller must make sure that "name" contains AUTOLOAD_CHAR. |
22336 | /// |
22337 | /// @param[in] name Variable/function name. |
22338 | /// @param[in] name_len Name length. |
22339 | /// |
22340 | /// @return [allocated] autoload script name. |
22341 | static char *autoload_name(const char *const name, const size_t name_len) |
22342 | FUNC_ATTR_MALLOC FUNC_ATTR_WARN_UNUSED_RESULT |
22343 | { |
22344 | // Get the script file name: replace '#' with '/', append ".vim". |
22345 | char *const scriptname = xmalloc(name_len + sizeof("autoload/.vim" )); |
22346 | memcpy(scriptname, "autoload/" , sizeof("autoload/" ) - 1); |
22347 | memcpy(scriptname + sizeof("autoload/" ) - 1, name, name_len); |
22348 | size_t auchar_idx = 0; |
22349 | for (size_t i = sizeof("autoload/" ) - 1; |
22350 | i - sizeof("autoload/" ) + 1 < name_len; |
22351 | i++) { |
22352 | if (scriptname[i] == AUTOLOAD_CHAR) { |
22353 | scriptname[i] = '/'; |
22354 | auchar_idx = i; |
22355 | } |
22356 | } |
22357 | memcpy(scriptname + auchar_idx, ".vim" , sizeof(".vim" )); |
22358 | |
22359 | return scriptname; |
22360 | } |
22361 | |
22362 | |
22363 | /* |
22364 | * Function given to ExpandGeneric() to obtain the list of user defined |
22365 | * function names. |
22366 | */ |
22367 | char_u *get_user_func_name(expand_T *xp, int idx) |
22368 | { |
22369 | static size_t done; |
22370 | static hashitem_T *hi; |
22371 | ufunc_T *fp; |
22372 | |
22373 | if (idx == 0) { |
22374 | done = 0; |
22375 | hi = func_hashtab.ht_array; |
22376 | } |
22377 | assert(hi); |
22378 | if (done < func_hashtab.ht_used) { |
22379 | if (done++ > 0) |
22380 | ++hi; |
22381 | while (HASHITEM_EMPTY(hi)) |
22382 | ++hi; |
22383 | fp = HI2UF(hi); |
22384 | |
22385 | if ((fp->uf_flags & FC_DICT) |
22386 | || STRNCMP(fp->uf_name, "<lambda>" , 8) == 0) { |
22387 | return (char_u *)"" ; // don't show dict and lambda functions |
22388 | } |
22389 | |
22390 | if (STRLEN(fp->uf_name) + 4 >= IOSIZE) { |
22391 | return fp->uf_name; // Prevent overflow. |
22392 | } |
22393 | |
22394 | cat_func_name(IObuff, fp); |
22395 | if (xp->xp_context != EXPAND_USER_FUNC) { |
22396 | STRCAT(IObuff, "(" ); |
22397 | if (!fp->uf_varargs && GA_EMPTY(&fp->uf_args)) |
22398 | STRCAT(IObuff, ")" ); |
22399 | } |
22400 | return IObuff; |
22401 | } |
22402 | return NULL; |
22403 | } |
22404 | |
22405 | |
22406 | /* |
22407 | * Copy the function name of "fp" to buffer "buf". |
22408 | * "buf" must be able to hold the function name plus three bytes. |
22409 | * Takes care of script-local function names. |
22410 | */ |
22411 | static void cat_func_name(char_u *buf, ufunc_T *fp) |
22412 | { |
22413 | if (fp->uf_name[0] == K_SPECIAL) { |
22414 | STRCPY(buf, "<SNR>" ); |
22415 | STRCAT(buf, fp->uf_name + 3); |
22416 | } else |
22417 | STRCPY(buf, fp->uf_name); |
22418 | } |
22419 | |
22420 | /// There are two kinds of function names: |
22421 | /// 1. ordinary names, function defined with :function |
22422 | /// 2. numbered functions and lambdas |
22423 | /// For the first we only count the name stored in func_hashtab as a reference, |
22424 | /// using function() does not count as a reference, because the function is |
22425 | /// looked up by name. |
22426 | static bool func_name_refcount(char_u *name) |
22427 | { |
22428 | return isdigit(*name) || *name == '<'; |
22429 | } |
22430 | |
22431 | /// ":delfunction {name}" |
22432 | void ex_delfunction(exarg_T *eap) |
22433 | { |
22434 | ufunc_T *fp = NULL; |
22435 | char_u *p; |
22436 | char_u *name; |
22437 | funcdict_T fudi; |
22438 | |
22439 | p = eap->arg; |
22440 | name = trans_function_name(&p, eap->skip, 0, &fudi, NULL); |
22441 | xfree(fudi.fd_newkey); |
22442 | if (name == NULL) { |
22443 | if (fudi.fd_dict != NULL && !eap->skip) |
22444 | EMSG(_(e_funcref)); |
22445 | return; |
22446 | } |
22447 | if (!ends_excmd(*skipwhite(p))) { |
22448 | xfree(name); |
22449 | EMSG(_(e_trailing)); |
22450 | return; |
22451 | } |
22452 | eap->nextcmd = check_nextcmd(p); |
22453 | if (eap->nextcmd != NULL) |
22454 | *p = NUL; |
22455 | |
22456 | if (!eap->skip) |
22457 | fp = find_func(name); |
22458 | xfree(name); |
22459 | |
22460 | if (!eap->skip) { |
22461 | if (fp == NULL) { |
22462 | if (!eap->forceit) { |
22463 | EMSG2(_(e_nofunc), eap->arg); |
22464 | } |
22465 | return; |
22466 | } |
22467 | if (fp->uf_calls > 0) { |
22468 | EMSG2(_("E131: Cannot delete function %s: It is in use" ), eap->arg); |
22469 | return; |
22470 | } |
22471 | // check `uf_refcount > 2` because deleting a function should also reduce |
22472 | // the reference count, and 1 is the initial refcount. |
22473 | if (fp->uf_refcount > 2) { |
22474 | EMSG2(_("Cannot delete function %s: It is being used internally" ), |
22475 | eap->arg); |
22476 | return; |
22477 | } |
22478 | |
22479 | if (fudi.fd_dict != NULL) { |
22480 | // Delete the dict item that refers to the function, it will |
22481 | // invoke func_unref() and possibly delete the function. |
22482 | tv_dict_item_remove(fudi.fd_dict, fudi.fd_di); |
22483 | } else { |
22484 | // A normal function (not a numbered function or lambda) has a |
22485 | // refcount of 1 for the entry in the hashtable. When deleting |
22486 | // it and the refcount is more than one, it should be kept. |
22487 | // A numbered function or lambda should be kept if the refcount is |
22488 | // one or more. |
22489 | if (fp->uf_refcount > (func_name_refcount(fp->uf_name) ? 0 : 1)) { |
22490 | // Function is still referenced somewhere. Don't free it but |
22491 | // do remove it from the hashtable. |
22492 | if (func_remove(fp)) { |
22493 | fp->uf_refcount--; |
22494 | } |
22495 | fp->uf_flags |= FC_DELETED; |
22496 | } else { |
22497 | func_clear_free(fp, false); |
22498 | } |
22499 | } |
22500 | } |
22501 | } |
22502 | |
22503 | /// Remove the function from the function hashtable. If the function was |
22504 | /// deleted while it still has references this was already done. |
22505 | /// |
22506 | /// @return true if the entry was deleted, false if it wasn't found. |
22507 | static bool func_remove(ufunc_T *fp) |
22508 | { |
22509 | hashitem_T *hi = hash_find(&func_hashtab, UF2HIKEY(fp)); |
22510 | |
22511 | if (!HASHITEM_EMPTY(hi)) { |
22512 | hash_remove(&func_hashtab, hi); |
22513 | return true; |
22514 | } |
22515 | |
22516 | return false; |
22517 | } |
22518 | |
22519 | static void func_clear_items(ufunc_T *fp) |
22520 | { |
22521 | ga_clear_strings(&(fp->uf_args)); |
22522 | ga_clear_strings(&(fp->uf_lines)); |
22523 | |
22524 | XFREE_CLEAR(fp->uf_tml_count); |
22525 | XFREE_CLEAR(fp->uf_tml_total); |
22526 | XFREE_CLEAR(fp->uf_tml_self); |
22527 | } |
22528 | |
22529 | /// Free all things that a function contains. Does not free the function |
22530 | /// itself, use func_free() for that. |
22531 | /// |
22532 | /// param[in] force When true, we are exiting. |
22533 | static void func_clear(ufunc_T *fp, bool force) |
22534 | { |
22535 | if (fp->uf_cleared) { |
22536 | return; |
22537 | } |
22538 | fp->uf_cleared = true; |
22539 | |
22540 | // clear this function |
22541 | func_clear_items(fp); |
22542 | funccal_unref(fp->uf_scoped, fp, force); |
22543 | } |
22544 | |
22545 | /// Free a function and remove it from the list of functions. Does not free |
22546 | /// what a function contains, call func_clear() first. |
22547 | /// |
22548 | /// param[in] fp The function to free. |
22549 | static void func_free(ufunc_T *fp) |
22550 | { |
22551 | // only remove it when not done already, otherwise we would remove a newer |
22552 | // version of the function |
22553 | if ((fp->uf_flags & (FC_DELETED | FC_REMOVED)) == 0) { |
22554 | func_remove(fp); |
22555 | } |
22556 | xfree(fp); |
22557 | } |
22558 | |
22559 | /// Free all things that a function contains and free the function itself. |
22560 | /// |
22561 | /// param[in] force When true, we are exiting. |
22562 | static void func_clear_free(ufunc_T *fp, bool force) |
22563 | { |
22564 | func_clear(fp, force); |
22565 | func_free(fp); |
22566 | } |
22567 | |
22568 | /* |
22569 | * Unreference a Function: decrement the reference count and free it when it |
22570 | * becomes zero. |
22571 | */ |
22572 | void func_unref(char_u *name) |
22573 | { |
22574 | ufunc_T *fp = NULL; |
22575 | |
22576 | if (name == NULL || !func_name_refcount(name)) { |
22577 | return; |
22578 | } |
22579 | |
22580 | fp = find_func(name); |
22581 | if (fp == NULL && isdigit(*name)) { |
22582 | #ifdef EXITFREE |
22583 | if (!entered_free_all_mem) { |
22584 | internal_error("func_unref()" ); |
22585 | abort(); |
22586 | } |
22587 | #else |
22588 | internal_error("func_unref()" ); |
22589 | abort(); |
22590 | #endif |
22591 | } |
22592 | func_ptr_unref(fp); |
22593 | } |
22594 | |
22595 | /// Unreference a Function: decrement the reference count and free it when it |
22596 | /// becomes zero. |
22597 | /// Unreference user function, freeing it if needed |
22598 | /// |
22599 | /// Decrements the reference count and frees when it becomes zero. |
22600 | /// |
22601 | /// @param fp Function to unreference. |
22602 | void func_ptr_unref(ufunc_T *fp) |
22603 | { |
22604 | if (fp != NULL && --fp->uf_refcount <= 0) { |
22605 | // Only delete it when it's not being used. Otherwise it's done |
22606 | // when "uf_calls" becomes zero. |
22607 | if (fp->uf_calls == 0) { |
22608 | func_clear_free(fp, false); |
22609 | } |
22610 | } |
22611 | } |
22612 | |
22613 | /// Count a reference to a Function. |
22614 | void func_ref(char_u *name) |
22615 | { |
22616 | ufunc_T *fp; |
22617 | |
22618 | if (name == NULL || !func_name_refcount(name)) { |
22619 | return; |
22620 | } |
22621 | fp = find_func(name); |
22622 | if (fp != NULL) { |
22623 | (fp->uf_refcount)++; |
22624 | } else if (isdigit(*name)) { |
22625 | // Only give an error for a numbered function. |
22626 | // Fail silently, when named or lambda function isn't found. |
22627 | internal_error("func_ref()" ); |
22628 | } |
22629 | } |
22630 | |
22631 | /// Count a reference to a Function. |
22632 | void func_ptr_ref(ufunc_T *fp) |
22633 | { |
22634 | if (fp != NULL) { |
22635 | (fp->uf_refcount)++; |
22636 | } |
22637 | } |
22638 | |
22639 | /// Check whether funccall is still referenced outside |
22640 | /// |
22641 | /// It is supposed to be referenced if either it is referenced itself or if l:, |
22642 | /// a: or a:000 are referenced as all these are statically allocated within |
22643 | /// funccall structure. |
22644 | static inline bool fc_referenced(const funccall_T *const fc) |
22645 | FUNC_ATTR_ALWAYS_INLINE FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT |
22646 | FUNC_ATTR_NONNULL_ALL |
22647 | { |
22648 | return ((fc->l_varlist.lv_refcount // NOLINT(runtime/deprecated) |
22649 | != DO_NOT_FREE_CNT) |
22650 | || fc->l_vars.dv_refcount != DO_NOT_FREE_CNT |
22651 | || fc->l_avars.dv_refcount != DO_NOT_FREE_CNT |
22652 | || fc->fc_refcount > 0); |
22653 | } |
22654 | |
22655 | /// Call a user function |
22656 | /// |
22657 | /// @param fp Function to call. |
22658 | /// @param[in] argcount Number of arguments. |
22659 | /// @param argvars Arguments. |
22660 | /// @param[out] rettv Return value. |
22661 | /// @param[in] firstline First line of range. |
22662 | /// @param[in] lastline Last line of range. |
22663 | /// @param selfdict Dictionary for "self" for dictionary functions. |
22664 | void call_user_func(ufunc_T *fp, int argcount, typval_T *argvars, |
22665 | typval_T *rettv, linenr_T firstline, linenr_T lastline, |
22666 | dict_T *selfdict) |
22667 | FUNC_ATTR_NONNULL_ARG(1, 3, 4) |
22668 | { |
22669 | char_u *save_sourcing_name; |
22670 | linenr_T save_sourcing_lnum; |
22671 | bool using_sandbox = false; |
22672 | funccall_T *fc; |
22673 | int save_did_emsg; |
22674 | static int depth = 0; |
22675 | dictitem_T *v; |
22676 | int fixvar_idx = 0; /* index in fixvar[] */ |
22677 | int ai; |
22678 | bool islambda = false; |
22679 | char_u numbuf[NUMBUFLEN]; |
22680 | char_u *name; |
22681 | proftime_T wait_start; |
22682 | proftime_T call_start; |
22683 | int started_profiling = false; |
22684 | bool did_save_redo = false; |
22685 | save_redo_T save_redo; |
22686 | |
22687 | /* If depth of calling is getting too high, don't execute the function */ |
22688 | if (depth >= p_mfd) { |
22689 | EMSG(_("E132: Function call depth is higher than 'maxfuncdepth'" )); |
22690 | rettv->v_type = VAR_NUMBER; |
22691 | rettv->vval.v_number = -1; |
22692 | return; |
22693 | } |
22694 | ++depth; |
22695 | // Save search patterns and redo buffer. |
22696 | save_search_patterns(); |
22697 | if (!ins_compl_active()) { |
22698 | saveRedobuff(&save_redo); |
22699 | did_save_redo = true; |
22700 | } |
22701 | ++fp->uf_calls; |
22702 | // check for CTRL-C hit |
22703 | line_breakcheck(); |
22704 | // prepare the funccall_T structure |
22705 | fc = xmalloc(sizeof(funccall_T)); |
22706 | fc->caller = current_funccal; |
22707 | current_funccal = fc; |
22708 | fc->func = fp; |
22709 | fc->rettv = rettv; |
22710 | rettv->vval.v_number = 0; |
22711 | fc->linenr = 0; |
22712 | fc->returned = FALSE; |
22713 | fc->level = ex_nesting_level; |
22714 | /* Check if this function has a breakpoint. */ |
22715 | fc->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, (linenr_T)0); |
22716 | fc->dbg_tick = debug_tick; |
22717 | |
22718 | // Set up fields for closure. |
22719 | fc->fc_refcount = 0; |
22720 | fc->fc_copyID = 0; |
22721 | ga_init(&fc->fc_funcs, sizeof(ufunc_T *), 1); |
22722 | func_ptr_ref(fp); |
22723 | |
22724 | if (STRNCMP(fp->uf_name, "<lambda>" , 8) == 0) { |
22725 | islambda = true; |
22726 | } |
22727 | |
22728 | // Note about using fc->fixvar[]: This is an array of FIXVAR_CNT variables |
22729 | // with names up to VAR_SHORT_LEN long. This avoids having to alloc/free |
22730 | // each argument variable and saves a lot of time. |
22731 | // |
22732 | // Init l: variables. |
22733 | init_var_dict(&fc->l_vars, &fc->l_vars_var, VAR_DEF_SCOPE); |
22734 | if (selfdict != NULL) { |
22735 | // Set l:self to "selfdict". Use "name" to avoid a warning from |
22736 | // some compiler that checks the destination size. |
22737 | v = (dictitem_T *)&fc->fixvar[fixvar_idx++]; |
22738 | #ifndef __clang_analyzer__ |
22739 | name = v->di_key; |
22740 | STRCPY(name, "self" ); |
22741 | #endif |
22742 | v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; |
22743 | tv_dict_add(&fc->l_vars, v); |
22744 | v->di_tv.v_type = VAR_DICT; |
22745 | v->di_tv.v_lock = 0; |
22746 | v->di_tv.vval.v_dict = selfdict; |
22747 | ++selfdict->dv_refcount; |
22748 | } |
22749 | |
22750 | /* |
22751 | * Init a: variables. |
22752 | * Set a:0 to "argcount". |
22753 | * Set a:000 to a list with room for the "..." arguments. |
22754 | */ |
22755 | init_var_dict(&fc->l_avars, &fc->l_avars_var, VAR_SCOPE); |
22756 | add_nr_var(&fc->l_avars, (dictitem_T *)&fc->fixvar[fixvar_idx++], "0" , |
22757 | (varnumber_T)(argcount - fp->uf_args.ga_len)); |
22758 | fc->l_avars.dv_lock = VAR_FIXED; |
22759 | // Use "name" to avoid a warning from some compiler that checks the |
22760 | // destination size. |
22761 | v = (dictitem_T *)&fc->fixvar[fixvar_idx++]; |
22762 | #ifndef __clang_analyzer__ |
22763 | name = v->di_key; |
22764 | STRCPY(name, "000" ); |
22765 | #endif |
22766 | v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; |
22767 | tv_dict_add(&fc->l_avars, v); |
22768 | v->di_tv.v_type = VAR_LIST; |
22769 | v->di_tv.v_lock = VAR_FIXED; |
22770 | v->di_tv.vval.v_list = &fc->l_varlist; |
22771 | tv_list_init_static(&fc->l_varlist); |
22772 | tv_list_set_lock(&fc->l_varlist, VAR_FIXED); |
22773 | |
22774 | // Set a:firstline to "firstline" and a:lastline to "lastline". |
22775 | // Set a:name to named arguments. |
22776 | // Set a:N to the "..." arguments. |
22777 | add_nr_var(&fc->l_avars, (dictitem_T *)&fc->fixvar[fixvar_idx++], |
22778 | "firstline" , (varnumber_T)firstline); |
22779 | add_nr_var(&fc->l_avars, (dictitem_T *)&fc->fixvar[fixvar_idx++], |
22780 | "lastline" , (varnumber_T)lastline); |
22781 | for (int i = 0; i < argcount; i++) { |
22782 | bool addlocal = false; |
22783 | |
22784 | ai = i - fp->uf_args.ga_len; |
22785 | if (ai < 0) { |
22786 | // named argument a:name |
22787 | name = FUNCARG(fp, i); |
22788 | if (islambda) { |
22789 | addlocal = true; |
22790 | } |
22791 | } else { |
22792 | // "..." argument a:1, a:2, etc. |
22793 | snprintf((char *)numbuf, sizeof(numbuf), "%d" , ai + 1); |
22794 | name = numbuf; |
22795 | } |
22796 | if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN) { |
22797 | v = (dictitem_T *)&fc->fixvar[fixvar_idx++]; |
22798 | v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; |
22799 | } else { |
22800 | v = xmalloc(sizeof(dictitem_T) + STRLEN(name)); |
22801 | v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX | DI_FLAGS_ALLOC; |
22802 | } |
22803 | STRCPY(v->di_key, name); |
22804 | |
22805 | // Note: the values are copied directly to avoid alloc/free. |
22806 | // "argvars" must have VAR_FIXED for v_lock. |
22807 | v->di_tv = argvars[i]; |
22808 | v->di_tv.v_lock = VAR_FIXED; |
22809 | |
22810 | if (addlocal) { |
22811 | // Named arguments can be accessed without the "a:" prefix in lambda |
22812 | // expressions. Add to the l: dict. |
22813 | tv_copy(&v->di_tv, &v->di_tv); |
22814 | tv_dict_add(&fc->l_vars, v); |
22815 | } else { |
22816 | tv_dict_add(&fc->l_avars, v); |
22817 | } |
22818 | |
22819 | if (ai >= 0 && ai < MAX_FUNC_ARGS) { |
22820 | tv_list_append(&fc->l_varlist, &fc->l_listitems[ai]); |
22821 | *TV_LIST_ITEM_TV(&fc->l_listitems[ai]) = argvars[i]; |
22822 | TV_LIST_ITEM_TV(&fc->l_listitems[ai])->v_lock = VAR_FIXED; |
22823 | } |
22824 | } |
22825 | |
22826 | /* Don't redraw while executing the function. */ |
22827 | ++RedrawingDisabled; |
22828 | save_sourcing_name = sourcing_name; |
22829 | save_sourcing_lnum = sourcing_lnum; |
22830 | sourcing_lnum = 1; |
22831 | |
22832 | if (fp->uf_flags & FC_SANDBOX) { |
22833 | using_sandbox = true; |
22834 | sandbox++; |
22835 | } |
22836 | |
22837 | // need space for new sourcing_name: |
22838 | // * save_sourcing_name |
22839 | // * "["number"].." or "function " |
22840 | // * "<SNR>" + fp->uf_name - 3 |
22841 | // * terminating NUL |
22842 | size_t len = (save_sourcing_name == NULL ? 0 : STRLEN(save_sourcing_name)) |
22843 | + STRLEN(fp->uf_name) + 27; |
22844 | sourcing_name = xmalloc(len); |
22845 | { |
22846 | if (save_sourcing_name != NULL |
22847 | && STRNCMP(save_sourcing_name, "function " , 9) == 0) { |
22848 | vim_snprintf((char *)sourcing_name, |
22849 | len, |
22850 | "%s[%" PRId64 "].." , |
22851 | save_sourcing_name, |
22852 | (int64_t)save_sourcing_lnum); |
22853 | } else { |
22854 | STRCPY(sourcing_name, "function " ); |
22855 | } |
22856 | cat_func_name(sourcing_name + STRLEN(sourcing_name), fp); |
22857 | |
22858 | if (p_verbose >= 12) { |
22859 | ++no_wait_return; |
22860 | verbose_enter_scroll(); |
22861 | |
22862 | smsg(_("calling %s" ), sourcing_name); |
22863 | if (p_verbose >= 14) { |
22864 | msg_puts("(" ); |
22865 | for (int i = 0; i < argcount; i++) { |
22866 | if (i > 0) { |
22867 | msg_puts(", " ); |
22868 | } |
22869 | if (argvars[i].v_type == VAR_NUMBER) { |
22870 | msg_outnum((long)argvars[i].vval.v_number); |
22871 | } else { |
22872 | // Do not want errors such as E724 here. |
22873 | emsg_off++; |
22874 | char *tofree = encode_tv2string(&argvars[i], NULL); |
22875 | emsg_off--; |
22876 | if (tofree != NULL) { |
22877 | char *s = tofree; |
22878 | char buf[MSG_BUF_LEN]; |
22879 | if (vim_strsize((char_u *)s) > MSG_BUF_CLEN) { |
22880 | trunc_string((char_u *)s, (char_u *)buf, MSG_BUF_CLEN, |
22881 | sizeof(buf)); |
22882 | s = buf; |
22883 | } |
22884 | msg_puts(s); |
22885 | xfree(tofree); |
22886 | } |
22887 | } |
22888 | } |
22889 | msg_puts(")" ); |
22890 | } |
22891 | msg_puts("\n" ); // don't overwrite this either |
22892 | |
22893 | verbose_leave_scroll(); |
22894 | --no_wait_return; |
22895 | } |
22896 | } |
22897 | |
22898 | const bool do_profiling_yes = do_profiling == PROF_YES; |
22899 | |
22900 | bool func_not_yet_profiling_but_should = |
22901 | do_profiling_yes |
22902 | && !fp->uf_profiling && has_profiling(false, fp->uf_name, NULL); |
22903 | |
22904 | if (func_not_yet_profiling_but_should) { |
22905 | started_profiling = true; |
22906 | func_do_profile(fp); |
22907 | } |
22908 | |
22909 | bool func_or_func_caller_profiling = |
22910 | do_profiling_yes |
22911 | && (fp->uf_profiling |
22912 | || (fc->caller != NULL && fc->caller->func->uf_profiling)); |
22913 | |
22914 | if (func_or_func_caller_profiling) { |
22915 | ++fp->uf_tm_count; |
22916 | call_start = profile_start(); |
22917 | fp->uf_tm_children = profile_zero(); |
22918 | } |
22919 | |
22920 | if (do_profiling_yes) { |
22921 | script_prof_save(&wait_start); |
22922 | } |
22923 | |
22924 | const sctx_T save_current_sctx = current_sctx; |
22925 | current_sctx = fp->uf_script_ctx; |
22926 | save_did_emsg = did_emsg; |
22927 | did_emsg = FALSE; |
22928 | |
22929 | /* call do_cmdline() to execute the lines */ |
22930 | do_cmdline(NULL, get_func_line, (void *)fc, |
22931 | DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT); |
22932 | |
22933 | --RedrawingDisabled; |
22934 | |
22935 | // when the function was aborted because of an error, return -1 |
22936 | if ((did_emsg |
22937 | && (fp->uf_flags & FC_ABORT)) || rettv->v_type == VAR_UNKNOWN) { |
22938 | tv_clear(rettv); |
22939 | rettv->v_type = VAR_NUMBER; |
22940 | rettv->vval.v_number = -1; |
22941 | } |
22942 | |
22943 | if (func_or_func_caller_profiling) { |
22944 | call_start = profile_end(call_start); |
22945 | call_start = profile_sub_wait(wait_start, call_start); // -V614 |
22946 | fp->uf_tm_total = profile_add(fp->uf_tm_total, call_start); |
22947 | fp->uf_tm_self = profile_self(fp->uf_tm_self, call_start, |
22948 | fp->uf_tm_children); |
22949 | if (fc->caller != NULL && fc->caller->func->uf_profiling) { |
22950 | fc->caller->func->uf_tm_children = |
22951 | profile_add(fc->caller->func->uf_tm_children, call_start); |
22952 | fc->caller->func->uf_tml_children = |
22953 | profile_add(fc->caller->func->uf_tml_children, call_start); |
22954 | } |
22955 | if (started_profiling) { |
22956 | // make a ":profdel func" stop profiling the function |
22957 | fp->uf_profiling = false; |
22958 | } |
22959 | } |
22960 | |
22961 | /* when being verbose, mention the return value */ |
22962 | if (p_verbose >= 12) { |
22963 | ++no_wait_return; |
22964 | verbose_enter_scroll(); |
22965 | |
22966 | if (aborting()) |
22967 | smsg(_("%s aborted" ), sourcing_name); |
22968 | else if (fc->rettv->v_type == VAR_NUMBER) |
22969 | smsg(_("%s returning #%" PRId64 "" ), |
22970 | sourcing_name, (int64_t)fc->rettv->vval.v_number); |
22971 | else { |
22972 | char_u buf[MSG_BUF_LEN]; |
22973 | |
22974 | // The value may be very long. Skip the middle part, so that we |
22975 | // have some idea how it starts and ends. smsg() would always |
22976 | // truncate it at the end. Don't want errors such as E724 here. |
22977 | emsg_off++; |
22978 | char_u *s = (char_u *) encode_tv2string(fc->rettv, NULL); |
22979 | char_u *tofree = s; |
22980 | emsg_off--; |
22981 | if (s != NULL) { |
22982 | if (vim_strsize(s) > MSG_BUF_CLEN) { |
22983 | trunc_string(s, buf, MSG_BUF_CLEN, MSG_BUF_LEN); |
22984 | s = buf; |
22985 | } |
22986 | smsg(_("%s returning %s" ), sourcing_name, s); |
22987 | xfree(tofree); |
22988 | } |
22989 | } |
22990 | msg_puts("\n" ); // don't overwrite this either |
22991 | |
22992 | verbose_leave_scroll(); |
22993 | --no_wait_return; |
22994 | } |
22995 | |
22996 | xfree(sourcing_name); |
22997 | sourcing_name = save_sourcing_name; |
22998 | sourcing_lnum = save_sourcing_lnum; |
22999 | current_sctx = save_current_sctx; |
23000 | if (do_profiling_yes) { |
23001 | script_prof_restore(&wait_start); |
23002 | } |
23003 | if (using_sandbox) { |
23004 | sandbox--; |
23005 | } |
23006 | |
23007 | if (p_verbose >= 12 && sourcing_name != NULL) { |
23008 | ++no_wait_return; |
23009 | verbose_enter_scroll(); |
23010 | |
23011 | smsg(_("continuing in %s" ), sourcing_name); |
23012 | msg_puts("\n" ); // don't overwrite this either |
23013 | |
23014 | verbose_leave_scroll(); |
23015 | --no_wait_return; |
23016 | } |
23017 | |
23018 | did_emsg |= save_did_emsg; |
23019 | depth--; |
23020 | |
23021 | cleanup_function_call(fc); |
23022 | |
23023 | if (--fp->uf_calls <= 0 && fp->uf_refcount <= 0) { |
23024 | // Function was unreferenced while being used, free it now. |
23025 | func_clear_free(fp, false); |
23026 | } |
23027 | // restore search patterns and redo buffer |
23028 | if (did_save_redo) { |
23029 | restoreRedobuff(&save_redo); |
23030 | } |
23031 | restore_search_patterns(); |
23032 | } |
23033 | |
23034 | /// Unreference "fc": decrement the reference count and free it when it |
23035 | /// becomes zero. "fp" is detached from "fc". |
23036 | /// |
23037 | /// @param[in] force When true, we are exiting. |
23038 | static void funccal_unref(funccall_T *fc, ufunc_T *fp, bool force) |
23039 | { |
23040 | funccall_T **pfc; |
23041 | int i; |
23042 | |
23043 | if (fc == NULL) { |
23044 | return; |
23045 | } |
23046 | |
23047 | fc->fc_refcount--; |
23048 | if (force ? fc->fc_refcount <= 0 : !fc_referenced(fc)) { |
23049 | for (pfc = &previous_funccal; *pfc != NULL; pfc = &(*pfc)->caller) { |
23050 | if (fc == *pfc) { |
23051 | *pfc = fc->caller; |
23052 | free_funccal(fc, true); |
23053 | return; |
23054 | } |
23055 | } |
23056 | } |
23057 | for (i = 0; i < fc->fc_funcs.ga_len; i++) { |
23058 | if (((ufunc_T **)(fc->fc_funcs.ga_data))[i] == fp) { |
23059 | ((ufunc_T **)(fc->fc_funcs.ga_data))[i] = NULL; |
23060 | } |
23061 | } |
23062 | } |
23063 | |
23064 | /// @return true if items in "fc" do not have "copyID". That means they are not |
23065 | /// referenced from anywhere that is in use. |
23066 | static int can_free_funccal(funccall_T *fc, int copyID) |
23067 | { |
23068 | return fc->l_varlist.lv_copyID != copyID |
23069 | && fc->l_vars.dv_copyID != copyID |
23070 | && fc->l_avars.dv_copyID != copyID |
23071 | && fc->fc_copyID != copyID; |
23072 | } |
23073 | |
23074 | /* |
23075 | * Free "fc" and what it contains. |
23076 | */ |
23077 | static void |
23078 | free_funccal( |
23079 | funccall_T *fc, |
23080 | int free_val /* a: vars were allocated */ |
23081 | ) |
23082 | { |
23083 | for (int i = 0; i < fc->fc_funcs.ga_len; i++) { |
23084 | ufunc_T *fp = ((ufunc_T **)(fc->fc_funcs.ga_data))[i]; |
23085 | |
23086 | // When garbage collecting a funccall_T may be freed before the |
23087 | // function that references it, clear its uf_scoped field. |
23088 | // The function may have been redefined and point to another |
23089 | // funccal_T, don't clear it then. |
23090 | if (fp != NULL && fp->uf_scoped == fc) { |
23091 | fp->uf_scoped = NULL; |
23092 | } |
23093 | } |
23094 | ga_clear(&fc->fc_funcs); |
23095 | |
23096 | // The a: variables typevals may not have been allocated, only free the |
23097 | // allocated variables. |
23098 | vars_clear_ext(&fc->l_avars.dv_hashtab, free_val); |
23099 | |
23100 | // Free all l: variables. |
23101 | vars_clear(&fc->l_vars.dv_hashtab); |
23102 | |
23103 | // Free the a:000 variables if they were allocated. |
23104 | if (free_val) { |
23105 | TV_LIST_ITER(&fc->l_varlist, li, { |
23106 | tv_clear(TV_LIST_ITEM_TV(li)); |
23107 | }); |
23108 | } |
23109 | |
23110 | func_ptr_unref(fc->func); |
23111 | xfree(fc); |
23112 | } |
23113 | |
23114 | /// Handle the last part of returning from a function: free the local hashtable. |
23115 | /// Unless it is still in use by a closure. |
23116 | static void cleanup_function_call(funccall_T *fc) |
23117 | { |
23118 | current_funccal = fc->caller; |
23119 | |
23120 | // If the a:000 list and the l: and a: dicts are not referenced and there |
23121 | // is no closure using it, we can free the funccall_T and what's in it. |
23122 | if (!fc_referenced(fc)) { |
23123 | free_funccal(fc, false); |
23124 | } else { |
23125 | // "fc" is still in use. This can happen when returning "a:000", |
23126 | // assigning "l:" to a global variable or defining a closure. |
23127 | // Link "fc" in the list for garbage collection later. |
23128 | fc->caller = previous_funccal; |
23129 | previous_funccal = fc; |
23130 | |
23131 | // Make a copy of the a: variables, since we didn't do that above. |
23132 | TV_DICT_ITER(&fc->l_avars, di, { |
23133 | tv_copy(&di->di_tv, &di->di_tv); |
23134 | }); |
23135 | |
23136 | // Make a copy of the a:000 items, since we didn't do that above. |
23137 | TV_LIST_ITER(&fc->l_varlist, li, { |
23138 | tv_copy(TV_LIST_ITEM_TV(li), TV_LIST_ITEM_TV(li)); |
23139 | }); |
23140 | } |
23141 | } |
23142 | |
23143 | /* |
23144 | * Add a number variable "name" to dict "dp" with value "nr". |
23145 | */ |
23146 | static void add_nr_var(dict_T *dp, dictitem_T *v, char *name, varnumber_T nr) |
23147 | { |
23148 | #ifndef __clang_analyzer__ |
23149 | STRCPY(v->di_key, name); |
23150 | #endif |
23151 | v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX; |
23152 | tv_dict_add(dp, v); |
23153 | v->di_tv.v_type = VAR_NUMBER; |
23154 | v->di_tv.v_lock = VAR_FIXED; |
23155 | v->di_tv.vval.v_number = nr; |
23156 | } |
23157 | |
23158 | /* |
23159 | * ":return [expr]" |
23160 | */ |
23161 | void ex_return(exarg_T *eap) |
23162 | { |
23163 | char_u *arg = eap->arg; |
23164 | typval_T rettv; |
23165 | int returning = FALSE; |
23166 | |
23167 | if (current_funccal == NULL) { |
23168 | EMSG(_("E133: :return not inside a function" )); |
23169 | return; |
23170 | } |
23171 | |
23172 | if (eap->skip) |
23173 | ++emsg_skip; |
23174 | |
23175 | eap->nextcmd = NULL; |
23176 | if ((*arg != NUL && *arg != '|' && *arg != '\n') |
23177 | && eval0(arg, &rettv, &eap->nextcmd, !eap->skip) != FAIL) { |
23178 | if (!eap->skip) { |
23179 | returning = do_return(eap, false, true, &rettv); |
23180 | } else { |
23181 | tv_clear(&rettv); |
23182 | } |
23183 | } else if (!eap->skip) { // It's safer to return also on error. |
23184 | // In return statement, cause_abort should be force_abort. |
23185 | update_force_abort(); |
23186 | |
23187 | // Return unless the expression evaluation has been cancelled due to an |
23188 | // aborting error, an interrupt, or an exception. |
23189 | if (!aborting()) { |
23190 | returning = do_return(eap, false, true, NULL); |
23191 | } |
23192 | } |
23193 | |
23194 | /* When skipping or the return gets pending, advance to the next command |
23195 | * in this line (!returning). Otherwise, ignore the rest of the line. |
23196 | * Following lines will be ignored by get_func_line(). */ |
23197 | if (returning) |
23198 | eap->nextcmd = NULL; |
23199 | else if (eap->nextcmd == NULL) /* no argument */ |
23200 | eap->nextcmd = check_nextcmd(arg); |
23201 | |
23202 | if (eap->skip) |
23203 | --emsg_skip; |
23204 | } |
23205 | |
23206 | /* |
23207 | * Return from a function. Possibly makes the return pending. Also called |
23208 | * for a pending return at the ":endtry" or after returning from an extra |
23209 | * do_cmdline(). "reanimate" is used in the latter case. "is_cmd" is set |
23210 | * when called due to a ":return" command. "rettv" may point to a typval_T |
23211 | * with the return rettv. Returns TRUE when the return can be carried out, |
23212 | * FALSE when the return gets pending. |
23213 | */ |
23214 | int do_return(exarg_T *eap, int reanimate, int is_cmd, void *rettv) |
23215 | { |
23216 | int idx; |
23217 | struct condstack *cstack = eap->cstack; |
23218 | |
23219 | if (reanimate) |
23220 | /* Undo the return. */ |
23221 | current_funccal->returned = FALSE; |
23222 | |
23223 | /* |
23224 | * Cleanup (and inactivate) conditionals, but stop when a try conditional |
23225 | * not in its finally clause (which then is to be executed next) is found. |
23226 | * In this case, make the ":return" pending for execution at the ":endtry". |
23227 | * Otherwise, return normally. |
23228 | */ |
23229 | idx = cleanup_conditionals(eap->cstack, 0, TRUE); |
23230 | if (idx >= 0) { |
23231 | cstack->cs_pending[idx] = CSTP_RETURN; |
23232 | |
23233 | if (!is_cmd && !reanimate) |
23234 | /* A pending return again gets pending. "rettv" points to an |
23235 | * allocated variable with the rettv of the original ":return"'s |
23236 | * argument if present or is NULL else. */ |
23237 | cstack->cs_rettv[idx] = rettv; |
23238 | else { |
23239 | /* When undoing a return in order to make it pending, get the stored |
23240 | * return rettv. */ |
23241 | if (reanimate) { |
23242 | assert(current_funccal->rettv); |
23243 | rettv = current_funccal->rettv; |
23244 | } |
23245 | |
23246 | if (rettv != NULL) { |
23247 | /* Store the value of the pending return. */ |
23248 | cstack->cs_rettv[idx] = xcalloc(1, sizeof(typval_T)); |
23249 | *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv; |
23250 | } else |
23251 | cstack->cs_rettv[idx] = NULL; |
23252 | |
23253 | if (reanimate) { |
23254 | /* The pending return value could be overwritten by a ":return" |
23255 | * without argument in a finally clause; reset the default |
23256 | * return value. */ |
23257 | current_funccal->rettv->v_type = VAR_NUMBER; |
23258 | current_funccal->rettv->vval.v_number = 0; |
23259 | } |
23260 | } |
23261 | report_make_pending(CSTP_RETURN, rettv); |
23262 | } else { |
23263 | current_funccal->returned = TRUE; |
23264 | |
23265 | /* If the return is carried out now, store the return value. For |
23266 | * a return immediately after reanimation, the value is already |
23267 | * there. */ |
23268 | if (!reanimate && rettv != NULL) { |
23269 | tv_clear(current_funccal->rettv); |
23270 | *current_funccal->rettv = *(typval_T *)rettv; |
23271 | if (!is_cmd) |
23272 | xfree(rettv); |
23273 | } |
23274 | } |
23275 | |
23276 | return idx < 0; |
23277 | } |
23278 | |
23279 | /* |
23280 | * Generate a return command for producing the value of "rettv". The result |
23281 | * is an allocated string. Used by report_pending() for verbose messages. |
23282 | */ |
23283 | char_u *get_return_cmd(void *rettv) |
23284 | { |
23285 | char_u *s = NULL; |
23286 | char_u *tofree = NULL; |
23287 | |
23288 | if (rettv != NULL) { |
23289 | tofree = s = (char_u *) encode_tv2echo((typval_T *) rettv, NULL); |
23290 | } |
23291 | if (s == NULL) { |
23292 | s = (char_u *)"" ; |
23293 | } |
23294 | |
23295 | STRCPY(IObuff, ":return " ); |
23296 | STRLCPY(IObuff + 8, s, IOSIZE - 8); |
23297 | if (STRLEN(s) + 8 >= IOSIZE) |
23298 | STRCPY(IObuff + IOSIZE - 4, "..." ); |
23299 | xfree(tofree); |
23300 | return vim_strsave(IObuff); |
23301 | } |
23302 | |
23303 | /* |
23304 | * Get next function line. |
23305 | * Called by do_cmdline() to get the next line. |
23306 | * Returns allocated string, or NULL for end of function. |
23307 | */ |
23308 | char_u *get_func_line(int c, void *cookie, int indent) |
23309 | { |
23310 | funccall_T *fcp = (funccall_T *)cookie; |
23311 | ufunc_T *fp = fcp->func; |
23312 | char_u *retval; |
23313 | garray_T *gap; /* growarray with function lines */ |
23314 | |
23315 | /* If breakpoints have been added/deleted need to check for it. */ |
23316 | if (fcp->dbg_tick != debug_tick) { |
23317 | fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, |
23318 | sourcing_lnum); |
23319 | fcp->dbg_tick = debug_tick; |
23320 | } |
23321 | if (do_profiling == PROF_YES) |
23322 | func_line_end(cookie); |
23323 | |
23324 | gap = &fp->uf_lines; |
23325 | if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try()) |
23326 | || fcp->returned) |
23327 | retval = NULL; |
23328 | else { |
23329 | /* Skip NULL lines (continuation lines). */ |
23330 | while (fcp->linenr < gap->ga_len |
23331 | && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL) |
23332 | ++fcp->linenr; |
23333 | if (fcp->linenr >= gap->ga_len) |
23334 | retval = NULL; |
23335 | else { |
23336 | retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]); |
23337 | sourcing_lnum = fcp->linenr; |
23338 | if (do_profiling == PROF_YES) |
23339 | func_line_start(cookie); |
23340 | } |
23341 | } |
23342 | |
23343 | /* Did we encounter a breakpoint? */ |
23344 | if (fcp->breakpoint != 0 && fcp->breakpoint <= sourcing_lnum) { |
23345 | dbg_breakpoint(fp->uf_name, sourcing_lnum); |
23346 | /* Find next breakpoint. */ |
23347 | fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, |
23348 | sourcing_lnum); |
23349 | fcp->dbg_tick = debug_tick; |
23350 | } |
23351 | |
23352 | return retval; |
23353 | } |
23354 | |
23355 | /* |
23356 | * Called when starting to read a function line. |
23357 | * "sourcing_lnum" must be correct! |
23358 | * When skipping lines it may not actually be executed, but we won't find out |
23359 | * until later and we need to store the time now. |
23360 | */ |
23361 | void func_line_start(void *cookie) |
23362 | { |
23363 | funccall_T *fcp = (funccall_T *)cookie; |
23364 | ufunc_T *fp = fcp->func; |
23365 | |
23366 | if (fp->uf_profiling && sourcing_lnum >= 1 |
23367 | && sourcing_lnum <= fp->uf_lines.ga_len) { |
23368 | fp->uf_tml_idx = sourcing_lnum - 1; |
23369 | /* Skip continuation lines. */ |
23370 | while (fp->uf_tml_idx > 0 && FUNCLINE(fp, fp->uf_tml_idx) == NULL) |
23371 | --fp->uf_tml_idx; |
23372 | fp->uf_tml_execed = FALSE; |
23373 | fp->uf_tml_start = profile_start(); |
23374 | fp->uf_tml_children = profile_zero(); |
23375 | fp->uf_tml_wait = profile_get_wait(); |
23376 | } |
23377 | } |
23378 | |
23379 | /* |
23380 | * Called when actually executing a function line. |
23381 | */ |
23382 | void func_line_exec(void *cookie) |
23383 | { |
23384 | funccall_T *fcp = (funccall_T *)cookie; |
23385 | ufunc_T *fp = fcp->func; |
23386 | |
23387 | if (fp->uf_profiling && fp->uf_tml_idx >= 0) |
23388 | fp->uf_tml_execed = TRUE; |
23389 | } |
23390 | |
23391 | /* |
23392 | * Called when done with a function line. |
23393 | */ |
23394 | void func_line_end(void *cookie) |
23395 | { |
23396 | funccall_T *fcp = (funccall_T *)cookie; |
23397 | ufunc_T *fp = fcp->func; |
23398 | |
23399 | if (fp->uf_profiling && fp->uf_tml_idx >= 0) { |
23400 | if (fp->uf_tml_execed) { |
23401 | ++fp->uf_tml_count[fp->uf_tml_idx]; |
23402 | fp->uf_tml_start = profile_end(fp->uf_tml_start); |
23403 | fp->uf_tml_start = profile_sub_wait(fp->uf_tml_wait, fp->uf_tml_start); |
23404 | fp->uf_tml_total[fp->uf_tml_idx] = |
23405 | profile_add(fp->uf_tml_total[fp->uf_tml_idx], fp->uf_tml_start); |
23406 | fp->uf_tml_self[fp->uf_tml_idx] = |
23407 | profile_self(fp->uf_tml_self[fp->uf_tml_idx], fp->uf_tml_start, |
23408 | fp->uf_tml_children); |
23409 | } |
23410 | fp->uf_tml_idx = -1; |
23411 | } |
23412 | } |
23413 | |
23414 | /* |
23415 | * Return TRUE if the currently active function should be ended, because a |
23416 | * return was encountered or an error occurred. Used inside a ":while". |
23417 | */ |
23418 | int func_has_ended(void *cookie) |
23419 | { |
23420 | funccall_T *fcp = (funccall_T *)cookie; |
23421 | |
23422 | /* Ignore the "abort" flag if the abortion behavior has been changed due to |
23423 | * an error inside a try conditional. */ |
23424 | return ((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try()) |
23425 | || fcp->returned; |
23426 | } |
23427 | |
23428 | /* |
23429 | * return TRUE if cookie indicates a function which "abort"s on errors. |
23430 | */ |
23431 | int func_has_abort(void *cookie) |
23432 | { |
23433 | return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT; |
23434 | } |
23435 | |
23436 | static var_flavour_T var_flavour(char_u *varname) |
23437 | { |
23438 | char_u *p = varname; |
23439 | |
23440 | if (ASCII_ISUPPER(*p)) { |
23441 | while (*(++p)) |
23442 | if (ASCII_ISLOWER(*p)) { |
23443 | return VAR_FLAVOUR_SESSION; |
23444 | } |
23445 | return VAR_FLAVOUR_SHADA; |
23446 | } else { |
23447 | return VAR_FLAVOUR_DEFAULT; |
23448 | } |
23449 | } |
23450 | |
23451 | /// Search hashitem in parent scope. |
23452 | hashitem_T *find_hi_in_scoped_ht(const char *name, hashtab_T **pht) |
23453 | { |
23454 | if (current_funccal == NULL || current_funccal->func->uf_scoped == NULL) { |
23455 | return NULL; |
23456 | } |
23457 | |
23458 | funccall_T *old_current_funccal = current_funccal; |
23459 | hashitem_T *hi = NULL; |
23460 | const size_t namelen = strlen(name); |
23461 | const char *varname; |
23462 | |
23463 | // Search in parent scope which is possible to reference from lambda |
23464 | current_funccal = current_funccal->func->uf_scoped; |
23465 | while (current_funccal != NULL) { |
23466 | hashtab_T *ht = find_var_ht(name, namelen, &varname); |
23467 | if (ht != NULL && *varname != NUL) { |
23468 | hi = hash_find_len(ht, varname, namelen - (varname - name)); |
23469 | if (!HASHITEM_EMPTY(hi)) { |
23470 | *pht = ht; |
23471 | break; |
23472 | } |
23473 | } |
23474 | if (current_funccal == current_funccal->func->uf_scoped) { |
23475 | break; |
23476 | } |
23477 | current_funccal = current_funccal->func->uf_scoped; |
23478 | } |
23479 | current_funccal = old_current_funccal; |
23480 | |
23481 | return hi; |
23482 | } |
23483 | |
23484 | /// Search variable in parent scope. |
23485 | dictitem_T *find_var_in_scoped_ht(const char *name, const size_t namelen, |
23486 | int no_autoload) |
23487 | { |
23488 | if (current_funccal == NULL || current_funccal->func->uf_scoped == NULL) { |
23489 | return NULL; |
23490 | } |
23491 | |
23492 | dictitem_T *v = NULL; |
23493 | funccall_T *old_current_funccal = current_funccal; |
23494 | const char *varname; |
23495 | |
23496 | // Search in parent scope which is possible to reference from lambda |
23497 | current_funccal = current_funccal->func->uf_scoped; |
23498 | while (current_funccal) { |
23499 | hashtab_T *ht = find_var_ht(name, namelen, &varname); |
23500 | if (ht != NULL && *varname != NUL) { |
23501 | v = find_var_in_ht(ht, *name, varname, |
23502 | namelen - (size_t)(varname - name), no_autoload); |
23503 | if (v != NULL) { |
23504 | break; |
23505 | } |
23506 | } |
23507 | if (current_funccal == current_funccal->func->uf_scoped) { |
23508 | break; |
23509 | } |
23510 | current_funccal = current_funccal->func->uf_scoped; |
23511 | } |
23512 | current_funccal = old_current_funccal; |
23513 | |
23514 | return v; |
23515 | } |
23516 | |
23517 | /// Iterate over global variables |
23518 | /// |
23519 | /// @warning No modifications to global variable dictionary must be performed |
23520 | /// while iteration is in progress. |
23521 | /// |
23522 | /// @param[in] iter Iterator. Pass NULL to start iteration. |
23523 | /// @param[out] name Variable name. |
23524 | /// @param[out] rettv Variable value. |
23525 | /// |
23526 | /// @return Pointer that needs to be passed to next `var_shada_iter` invocation |
23527 | /// or NULL to indicate that iteration is over. |
23528 | const void *var_shada_iter(const void *const iter, const char **const name, |
23529 | typval_T *rettv, var_flavour_T flavour) |
23530 | FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ARG(2, 3) |
23531 | { |
23532 | const hashitem_T *hi; |
23533 | const hashitem_T *hifirst = globvarht.ht_array; |
23534 | const size_t hinum = (size_t) globvarht.ht_mask + 1; |
23535 | *name = NULL; |
23536 | if (iter == NULL) { |
23537 | hi = globvarht.ht_array; |
23538 | while ((size_t) (hi - hifirst) < hinum |
23539 | && (HASHITEM_EMPTY(hi) |
23540 | || !(var_flavour(hi->hi_key) & flavour))) { |
23541 | hi++; |
23542 | } |
23543 | if ((size_t) (hi - hifirst) == hinum) { |
23544 | return NULL; |
23545 | } |
23546 | } else { |
23547 | hi = (const hashitem_T *) iter; |
23548 | } |
23549 | *name = (char *)TV_DICT_HI2DI(hi)->di_key; |
23550 | tv_copy(&TV_DICT_HI2DI(hi)->di_tv, rettv); |
23551 | while ((size_t)(++hi - hifirst) < hinum) { |
23552 | if (!HASHITEM_EMPTY(hi) && (var_flavour(hi->hi_key) & flavour)) { |
23553 | return hi; |
23554 | } |
23555 | } |
23556 | return NULL; |
23557 | } |
23558 | |
23559 | void var_set_global(const char *const name, typval_T vartv) |
23560 | { |
23561 | funccall_T *const saved_current_funccal = current_funccal; |
23562 | current_funccal = NULL; |
23563 | set_var(name, strlen(name), &vartv, false); |
23564 | current_funccal = saved_current_funccal; |
23565 | } |
23566 | |
23567 | int store_session_globals(FILE *fd) |
23568 | { |
23569 | TV_DICT_ITER(&globvardict, this_var, { |
23570 | if ((this_var->di_tv.v_type == VAR_NUMBER |
23571 | || this_var->di_tv.v_type == VAR_STRING) |
23572 | && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION) { |
23573 | // Escape special characters with a backslash. Turn a LF and |
23574 | // CR into \n and \r. |
23575 | char_u *const p = vim_strsave_escaped( |
23576 | (const char_u *)tv_get_string(&this_var->di_tv), |
23577 | (const char_u *)"\\\"\n\r" ); |
23578 | for (char_u *t = p; *t != NUL; t++) { |
23579 | if (*t == '\n') { |
23580 | *t = 'n'; |
23581 | } else if (*t == '\r') { |
23582 | *t = 'r'; |
23583 | } |
23584 | } |
23585 | if ((fprintf(fd, "let %s = %c%s%c" , |
23586 | this_var->di_key, |
23587 | ((this_var->di_tv.v_type == VAR_STRING) ? '"' |
23588 | : ' '), |
23589 | p, |
23590 | ((this_var->di_tv.v_type == VAR_STRING) ? '"' |
23591 | : ' ')) < 0) |
23592 | || put_eol(fd) == FAIL) { |
23593 | xfree(p); |
23594 | return FAIL; |
23595 | } |
23596 | xfree(p); |
23597 | } else if (this_var->di_tv.v_type == VAR_FLOAT |
23598 | && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION) { |
23599 | float_T f = this_var->di_tv.vval.v_float; |
23600 | int sign = ' '; |
23601 | |
23602 | if (f < 0) { |
23603 | f = -f; |
23604 | sign = '-'; |
23605 | } |
23606 | if ((fprintf(fd, "let %s = %c%f" , this_var->di_key, sign, f) < 0) |
23607 | || put_eol(fd) == FAIL) { |
23608 | return FAIL; |
23609 | } |
23610 | } |
23611 | }); |
23612 | return OK; |
23613 | } |
23614 | |
23615 | /* |
23616 | * Display script name where an item was last set. |
23617 | * Should only be invoked when 'verbose' is non-zero. |
23618 | */ |
23619 | void last_set_msg(sctx_T script_ctx) |
23620 | { |
23621 | const LastSet last_set = (LastSet){ |
23622 | .script_ctx = script_ctx, |
23623 | .channel_id = 0, |
23624 | }; |
23625 | option_last_set_msg(last_set); |
23626 | } |
23627 | |
23628 | /// Displays where an option was last set. |
23629 | /// |
23630 | /// Should only be invoked when 'verbose' is non-zero. |
23631 | void option_last_set_msg(LastSet last_set) |
23632 | { |
23633 | if (last_set.script_ctx.sc_sid != 0) { |
23634 | bool should_free; |
23635 | char_u *p = get_scriptname(last_set, &should_free); |
23636 | verbose_enter(); |
23637 | MSG_PUTS(_("\n\tLast set from " )); |
23638 | MSG_PUTS(p); |
23639 | if (last_set.script_ctx.sc_lnum > 0) { |
23640 | MSG_PUTS(_(" line " )); |
23641 | msg_outnum((long)last_set.script_ctx.sc_lnum); |
23642 | } |
23643 | if (should_free) { |
23644 | xfree(p); |
23645 | } |
23646 | verbose_leave(); |
23647 | } |
23648 | } |
23649 | |
23650 | // reset v:option_new, v:option_old and v:option_type |
23651 | void reset_v_option_vars(void) |
23652 | { |
23653 | set_vim_var_string(VV_OPTION_NEW, NULL, -1); |
23654 | set_vim_var_string(VV_OPTION_OLD, NULL, -1); |
23655 | set_vim_var_string(VV_OPTION_TYPE, NULL, -1); |
23656 | } |
23657 | |
23658 | /* |
23659 | * Adjust a filename, according to a string of modifiers. |
23660 | * *fnamep must be NUL terminated when called. When returning, the length is |
23661 | * determined by *fnamelen. |
23662 | * Returns VALID_ flags or -1 for failure. |
23663 | * When there is an error, *fnamep is set to NULL. |
23664 | */ |
23665 | int |
23666 | modify_fname( |
23667 | char_u *src, // string with modifiers |
23668 | bool tilde_file, // "~" is a file name, not $HOME |
23669 | size_t *usedlen, // characters after src that are used |
23670 | char_u **fnamep, // file name so far |
23671 | char_u **bufp, // buffer for allocated file name or NULL |
23672 | size_t *fnamelen // length of fnamep |
23673 | ) |
23674 | { |
23675 | int valid = 0; |
23676 | char_u *tail; |
23677 | char_u *s, *p, *pbuf; |
23678 | char_u dirname[MAXPATHL]; |
23679 | int c; |
23680 | int has_fullname = 0; |
23681 | |
23682 | repeat: |
23683 | /* ":p" - full path/file_name */ |
23684 | if (src[*usedlen] == ':' && src[*usedlen + 1] == 'p') { |
23685 | has_fullname = 1; |
23686 | |
23687 | valid |= VALID_PATH; |
23688 | *usedlen += 2; |
23689 | |
23690 | /* Expand "~/path" for all systems and "~user/path" for Unix */ |
23691 | if ((*fnamep)[0] == '~' |
23692 | #if !defined(UNIX) |
23693 | && ((*fnamep)[1] == '/' |
23694 | # ifdef BACKSLASH_IN_FILENAME |
23695 | || (*fnamep)[1] == '\\' |
23696 | # endif |
23697 | || (*fnamep)[1] == NUL) |
23698 | #endif |
23699 | && !(tilde_file && (*fnamep)[1] == NUL) |
23700 | ) { |
23701 | *fnamep = expand_env_save(*fnamep); |
23702 | xfree(*bufp); /* free any allocated file name */ |
23703 | *bufp = *fnamep; |
23704 | if (*fnamep == NULL) |
23705 | return -1; |
23706 | } |
23707 | |
23708 | // When "/." or "/.." is used: force expansion to get rid of it. |
23709 | for (p = *fnamep; *p != NUL; MB_PTR_ADV(p)) { |
23710 | if (vim_ispathsep(*p) |
23711 | && p[1] == '.' |
23712 | && (p[2] == NUL |
23713 | || vim_ispathsep(p[2]) |
23714 | || (p[2] == '.' |
23715 | && (p[3] == NUL || vim_ispathsep(p[3]))))) { |
23716 | break; |
23717 | } |
23718 | } |
23719 | |
23720 | /* FullName_save() is slow, don't use it when not needed. */ |
23721 | if (*p != NUL || !vim_isAbsName(*fnamep)) { |
23722 | *fnamep = (char_u *)FullName_save((char *)*fnamep, *p != NUL); |
23723 | xfree(*bufp); /* free any allocated file name */ |
23724 | *bufp = *fnamep; |
23725 | if (*fnamep == NULL) |
23726 | return -1; |
23727 | } |
23728 | |
23729 | /* Append a path separator to a directory. */ |
23730 | if (os_isdir(*fnamep)) { |
23731 | /* Make room for one or two extra characters. */ |
23732 | *fnamep = vim_strnsave(*fnamep, STRLEN(*fnamep) + 2); |
23733 | xfree(*bufp); /* free any allocated file name */ |
23734 | *bufp = *fnamep; |
23735 | if (*fnamep == NULL) |
23736 | return -1; |
23737 | add_pathsep((char *)*fnamep); |
23738 | } |
23739 | } |
23740 | |
23741 | /* ":." - path relative to the current directory */ |
23742 | /* ":~" - path relative to the home directory */ |
23743 | /* ":8" - shortname path - postponed till after */ |
23744 | while (src[*usedlen] == ':' |
23745 | && ((c = src[*usedlen + 1]) == '.' || c == '~' || c == '8')) { |
23746 | *usedlen += 2; |
23747 | if (c == '8') { |
23748 | continue; |
23749 | } |
23750 | pbuf = NULL; |
23751 | /* Need full path first (use expand_env() to remove a "~/") */ |
23752 | if (!has_fullname) { |
23753 | if (c == '.' && **fnamep == '~') |
23754 | p = pbuf = expand_env_save(*fnamep); |
23755 | else |
23756 | p = pbuf = (char_u *)FullName_save((char *)*fnamep, FALSE); |
23757 | } else |
23758 | p = *fnamep; |
23759 | |
23760 | has_fullname = 0; |
23761 | |
23762 | if (p != NULL) { |
23763 | if (c == '.') { |
23764 | os_dirname(dirname, MAXPATHL); |
23765 | s = path_shorten_fname(p, dirname); |
23766 | if (s != NULL) { |
23767 | *fnamep = s; |
23768 | if (pbuf != NULL) { |
23769 | xfree(*bufp); /* free any allocated file name */ |
23770 | *bufp = pbuf; |
23771 | pbuf = NULL; |
23772 | } |
23773 | } |
23774 | } else { |
23775 | home_replace(NULL, p, dirname, MAXPATHL, TRUE); |
23776 | /* Only replace it when it starts with '~' */ |
23777 | if (*dirname == '~') { |
23778 | s = vim_strsave(dirname); |
23779 | *fnamep = s; |
23780 | xfree(*bufp); |
23781 | *bufp = s; |
23782 | } |
23783 | } |
23784 | xfree(pbuf); |
23785 | } |
23786 | } |
23787 | |
23788 | tail = path_tail(*fnamep); |
23789 | *fnamelen = STRLEN(*fnamep); |
23790 | |
23791 | /* ":h" - head, remove "/file_name", can be repeated */ |
23792 | /* Don't remove the first "/" or "c:\" */ |
23793 | while (src[*usedlen] == ':' && src[*usedlen + 1] == 'h') { |
23794 | valid |= VALID_HEAD; |
23795 | *usedlen += 2; |
23796 | s = get_past_head(*fnamep); |
23797 | while (tail > s && after_pathsep((char *)s, (char *)tail)) { |
23798 | MB_PTR_BACK(*fnamep, tail); |
23799 | } |
23800 | *fnamelen = (size_t)(tail - *fnamep); |
23801 | if (*fnamelen == 0) { |
23802 | /* Result is empty. Turn it into "." to make ":cd %:h" work. */ |
23803 | xfree(*bufp); |
23804 | *bufp = *fnamep = tail = vim_strsave((char_u *)"." ); |
23805 | *fnamelen = 1; |
23806 | } else { |
23807 | while (tail > s && !after_pathsep((char *)s, (char *)tail)) { |
23808 | MB_PTR_BACK(*fnamep, tail); |
23809 | } |
23810 | } |
23811 | } |
23812 | |
23813 | /* ":8" - shortname */ |
23814 | if (src[*usedlen] == ':' && src[*usedlen + 1] == '8') { |
23815 | *usedlen += 2; |
23816 | } |
23817 | |
23818 | |
23819 | /* ":t" - tail, just the basename */ |
23820 | if (src[*usedlen] == ':' && src[*usedlen + 1] == 't') { |
23821 | *usedlen += 2; |
23822 | *fnamelen -= (size_t)(tail - *fnamep); |
23823 | *fnamep = tail; |
23824 | } |
23825 | |
23826 | /* ":e" - extension, can be repeated */ |
23827 | /* ":r" - root, without extension, can be repeated */ |
23828 | while (src[*usedlen] == ':' |
23829 | && (src[*usedlen + 1] == 'e' || src[*usedlen + 1] == 'r')) { |
23830 | /* find a '.' in the tail: |
23831 | * - for second :e: before the current fname |
23832 | * - otherwise: The last '.' |
23833 | */ |
23834 | if (src[*usedlen + 1] == 'e' && *fnamep > tail) |
23835 | s = *fnamep - 2; |
23836 | else |
23837 | s = *fnamep + *fnamelen - 1; |
23838 | for (; s > tail; --s) |
23839 | if (s[0] == '.') |
23840 | break; |
23841 | if (src[*usedlen + 1] == 'e') { /* :e */ |
23842 | if (s > tail) { |
23843 | *fnamelen += (size_t)(*fnamep - (s + 1)); |
23844 | *fnamep = s + 1; |
23845 | } else if (*fnamep <= tail) |
23846 | *fnamelen = 0; |
23847 | } else { /* :r */ |
23848 | if (s > tail) /* remove one extension */ |
23849 | *fnamelen = (size_t)(s - *fnamep); |
23850 | } |
23851 | *usedlen += 2; |
23852 | } |
23853 | |
23854 | /* ":s?pat?foo?" - substitute */ |
23855 | /* ":gs?pat?foo?" - global substitute */ |
23856 | if (src[*usedlen] == ':' |
23857 | && (src[*usedlen + 1] == 's' |
23858 | || (src[*usedlen + 1] == 'g' && src[*usedlen + 2] == 's'))) { |
23859 | char_u *str; |
23860 | char_u *pat; |
23861 | char_u *sub; |
23862 | int sep; |
23863 | char_u *flags; |
23864 | int didit = FALSE; |
23865 | |
23866 | flags = (char_u *)"" ; |
23867 | s = src + *usedlen + 2; |
23868 | if (src[*usedlen + 1] == 'g') { |
23869 | flags = (char_u *)"g" ; |
23870 | ++s; |
23871 | } |
23872 | |
23873 | sep = *s++; |
23874 | if (sep) { |
23875 | /* find end of pattern */ |
23876 | p = vim_strchr(s, sep); |
23877 | if (p != NULL) { |
23878 | pat = vim_strnsave(s, (int)(p - s)); |
23879 | s = p + 1; |
23880 | /* find end of substitution */ |
23881 | p = vim_strchr(s, sep); |
23882 | if (p != NULL) { |
23883 | sub = vim_strnsave(s, (int)(p - s)); |
23884 | str = vim_strnsave(*fnamep, *fnamelen); |
23885 | *usedlen = (size_t)(p + 1 - src); |
23886 | s = do_string_sub(str, pat, sub, NULL, flags); |
23887 | *fnamep = s; |
23888 | *fnamelen = STRLEN(s); |
23889 | xfree(*bufp); |
23890 | *bufp = s; |
23891 | didit = TRUE; |
23892 | xfree(sub); |
23893 | xfree(str); |
23894 | } |
23895 | xfree(pat); |
23896 | } |
23897 | /* after using ":s", repeat all the modifiers */ |
23898 | if (didit) |
23899 | goto repeat; |
23900 | } |
23901 | } |
23902 | |
23903 | if (src[*usedlen] == ':' && src[*usedlen + 1] == 'S') { |
23904 | // vim_strsave_shellescape() needs a NUL terminated string. |
23905 | c = (*fnamep)[*fnamelen]; |
23906 | if (c != NUL) { |
23907 | (*fnamep)[*fnamelen] = NUL; |
23908 | } |
23909 | p = vim_strsave_shellescape(*fnamep, false, false); |
23910 | if (c != NUL) { |
23911 | (*fnamep)[*fnamelen] = c; |
23912 | } |
23913 | xfree(*bufp); |
23914 | *bufp = *fnamep = p; |
23915 | *fnamelen = STRLEN(p); |
23916 | *usedlen += 2; |
23917 | } |
23918 | |
23919 | return valid; |
23920 | } |
23921 | |
23922 | /// Perform a substitution on "str" with pattern "pat" and substitute "sub". |
23923 | /// When "sub" is NULL "expr" is used, must be a VAR_FUNC or VAR_PARTIAL. |
23924 | /// "flags" can be "g" to do a global substitute. |
23925 | /// Returns an allocated string, NULL for error. |
23926 | char_u *do_string_sub(char_u *str, char_u *pat, char_u *sub, |
23927 | typval_T *expr, char_u *flags) |
23928 | { |
23929 | int sublen; |
23930 | regmatch_T regmatch; |
23931 | int do_all; |
23932 | char_u *tail; |
23933 | char_u *end; |
23934 | garray_T ga; |
23935 | char_u *save_cpo; |
23936 | char_u *zero_width = NULL; |
23937 | |
23938 | /* Make 'cpoptions' empty, so that the 'l' flag doesn't work here */ |
23939 | save_cpo = p_cpo; |
23940 | p_cpo = empty_option; |
23941 | |
23942 | ga_init(&ga, 1, 200); |
23943 | |
23944 | do_all = (flags[0] == 'g'); |
23945 | |
23946 | regmatch.rm_ic = p_ic; |
23947 | regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING); |
23948 | if (regmatch.regprog != NULL) { |
23949 | tail = str; |
23950 | end = str + STRLEN(str); |
23951 | while (vim_regexec_nl(®match, str, (colnr_T)(tail - str))) { |
23952 | /* Skip empty match except for first match. */ |
23953 | if (regmatch.startp[0] == regmatch.endp[0]) { |
23954 | if (zero_width == regmatch.startp[0]) { |
23955 | /* avoid getting stuck on a match with an empty string */ |
23956 | int i = MB_PTR2LEN(tail); |
23957 | memmove((char_u *)ga.ga_data + ga.ga_len, tail, (size_t)i); |
23958 | ga.ga_len += i; |
23959 | tail += i; |
23960 | continue; |
23961 | } |
23962 | zero_width = regmatch.startp[0]; |
23963 | } |
23964 | |
23965 | // Get some space for a temporary buffer to do the substitution |
23966 | // into. It will contain: |
23967 | // - The text up to where the match is. |
23968 | // - The substituted text. |
23969 | // - The text after the match. |
23970 | sublen = vim_regsub(®match, sub, expr, tail, false, true, false); |
23971 | ga_grow(&ga, (int)((end - tail) + sublen - |
23972 | (regmatch.endp[0] - regmatch.startp[0]))); |
23973 | |
23974 | /* copy the text up to where the match is */ |
23975 | int i = (int)(regmatch.startp[0] - tail); |
23976 | memmove((char_u *)ga.ga_data + ga.ga_len, tail, (size_t)i); |
23977 | // add the substituted text |
23978 | (void)vim_regsub(®match, sub, expr, (char_u *)ga.ga_data |
23979 | + ga.ga_len + i, true, true, false); |
23980 | ga.ga_len += i + sublen - 1; |
23981 | tail = regmatch.endp[0]; |
23982 | if (*tail == NUL) |
23983 | break; |
23984 | if (!do_all) |
23985 | break; |
23986 | } |
23987 | |
23988 | if (ga.ga_data != NULL) |
23989 | STRCPY((char *)ga.ga_data + ga.ga_len, tail); |
23990 | |
23991 | vim_regfree(regmatch.regprog); |
23992 | } |
23993 | |
23994 | char_u *ret = vim_strsave(ga.ga_data == NULL ? str : (char_u *)ga.ga_data); |
23995 | ga_clear(&ga); |
23996 | if (p_cpo == empty_option) { |
23997 | p_cpo = save_cpo; |
23998 | } else { |
23999 | // Darn, evaluating {sub} expression or {expr} changed the value. |
24000 | free_string_option(save_cpo); |
24001 | } |
24002 | |
24003 | return ret; |
24004 | } |
24005 | |
24006 | /// common code for getting job callbacks for jobstart, termopen and rpcstart |
24007 | /// |
24008 | /// @return true/false on success/failure. |
24009 | static inline bool common_job_callbacks(dict_T *vopts, |
24010 | CallbackReader *on_stdout, |
24011 | CallbackReader *on_stderr, |
24012 | Callback *on_exit) |
24013 | { |
24014 | if (tv_dict_get_callback(vopts, S_LEN("on_stdout" ), &on_stdout->cb) |
24015 | &&tv_dict_get_callback(vopts, S_LEN("on_stderr" ), &on_stderr->cb) |
24016 | && tv_dict_get_callback(vopts, S_LEN("on_exit" ), on_exit)) { |
24017 | on_stdout->buffered = tv_dict_get_number(vopts, "stdout_buffered" ); |
24018 | on_stderr->buffered = tv_dict_get_number(vopts, "stderr_buffered" ); |
24019 | if (on_stdout->buffered && on_stdout->cb.type == kCallbackNone) { |
24020 | on_stdout->self = vopts; |
24021 | } |
24022 | if (on_stderr->buffered && on_stderr->cb.type == kCallbackNone) { |
24023 | on_stderr->self = vopts; |
24024 | } |
24025 | vopts->dv_refcount++; |
24026 | return true; |
24027 | } |
24028 | |
24029 | callback_reader_free(on_stdout); |
24030 | callback_reader_free(on_stderr); |
24031 | callback_free(on_exit); |
24032 | return false; |
24033 | } |
24034 | |
24035 | |
24036 | static Channel *find_job(uint64_t id, bool show_error) |
24037 | { |
24038 | Channel *data = find_channel(id); |
24039 | if (!data || data->streamtype != kChannelStreamProc |
24040 | || process_is_stopped(&data->stream.proc)) { |
24041 | if (show_error) { |
24042 | if (data && data->streamtype != kChannelStreamProc) { |
24043 | EMSG(_(e_invchanjob)); |
24044 | } else { |
24045 | EMSG(_(e_invchan)); |
24046 | } |
24047 | } |
24048 | return NULL; |
24049 | } |
24050 | return data; |
24051 | } |
24052 | |
24053 | |
24054 | static void script_host_eval(char *name, typval_T *argvars, typval_T *rettv) |
24055 | { |
24056 | if (check_restricted() || check_secure()) { |
24057 | return; |
24058 | } |
24059 | |
24060 | if (argvars[0].v_type != VAR_STRING) { |
24061 | EMSG(_(e_invarg)); |
24062 | return; |
24063 | } |
24064 | |
24065 | list_T *args = tv_list_alloc(1); |
24066 | tv_list_append_string(args, (const char *)argvars[0].vval.v_string, -1); |
24067 | *rettv = eval_call_provider(name, "eval" , args); |
24068 | } |
24069 | |
24070 | typval_T eval_call_provider(char *provider, char *method, list_T *arguments) |
24071 | { |
24072 | if (!eval_has_provider(provider)) { |
24073 | emsgf("E319: No \"%s\" provider found. Run \":checkhealth provider\"" , |
24074 | provider); |
24075 | return (typval_T){ |
24076 | .v_type = VAR_NUMBER, |
24077 | .v_lock = VAR_UNLOCKED, |
24078 | .vval.v_number = (varnumber_T)0 |
24079 | }; |
24080 | } |
24081 | |
24082 | char func[256]; |
24083 | int name_len = snprintf(func, sizeof(func), "provider#%s#Call" , provider); |
24084 | |
24085 | // Save caller scope information |
24086 | struct caller_scope saved_provider_caller_scope = provider_caller_scope; |
24087 | provider_caller_scope = (struct caller_scope) { |
24088 | .script_ctx = current_sctx, |
24089 | .sourcing_name = sourcing_name, |
24090 | .sourcing_lnum = sourcing_lnum, |
24091 | .autocmd_fname = autocmd_fname, |
24092 | .autocmd_match = autocmd_match, |
24093 | .autocmd_bufnr = autocmd_bufnr, |
24094 | .funccalp = save_funccal() |
24095 | }; |
24096 | provider_call_nesting++; |
24097 | |
24098 | typval_T argvars[3] = { |
24099 | {.v_type = VAR_STRING, .vval.v_string = (uint8_t *)method, .v_lock = 0}, |
24100 | {.v_type = VAR_LIST, .vval.v_list = arguments, .v_lock = 0}, |
24101 | {.v_type = VAR_UNKNOWN} |
24102 | }; |
24103 | typval_T rettv = { .v_type = VAR_UNKNOWN, .v_lock = VAR_UNLOCKED }; |
24104 | tv_list_ref(arguments); |
24105 | |
24106 | int dummy; |
24107 | (void)call_func((const char_u *)func, |
24108 | name_len, |
24109 | &rettv, |
24110 | 2, |
24111 | argvars, |
24112 | NULL, |
24113 | curwin->w_cursor.lnum, |
24114 | curwin->w_cursor.lnum, |
24115 | &dummy, |
24116 | true, |
24117 | NULL, |
24118 | NULL); |
24119 | |
24120 | tv_list_unref(arguments); |
24121 | // Restore caller scope information |
24122 | restore_funccal(provider_caller_scope.funccalp); |
24123 | provider_caller_scope = saved_provider_caller_scope; |
24124 | provider_call_nesting--; |
24125 | assert(provider_call_nesting >= 0); |
24126 | |
24127 | return rettv; |
24128 | } |
24129 | |
24130 | /// Checks if provider for feature `feat` is enabled. |
24131 | bool eval_has_provider(const char *feat) |
24132 | { |
24133 | if (!strequal(feat, "clipboard" ) |
24134 | && !strequal(feat, "python" ) |
24135 | && !strequal(feat, "python3" ) |
24136 | && !strequal(feat, "python_compiled" ) |
24137 | && !strequal(feat, "python_dynamic" ) |
24138 | && !strequal(feat, "python3_compiled" ) |
24139 | && !strequal(feat, "python3_dynamic" ) |
24140 | && !strequal(feat, "ruby" ) |
24141 | && !strequal(feat, "node" )) { |
24142 | // Avoid autoload for non-provider has() features. |
24143 | return false; |
24144 | } |
24145 | |
24146 | char name[32]; // Normalized: "python_compiled" => "python". |
24147 | snprintf(name, sizeof(name), "%s" , feat); |
24148 | strchrsub(name, '_', '\0'); // Chop any "_xx" suffix. |
24149 | |
24150 | char buf[256]; |
24151 | typval_T tv; |
24152 | // Get the g:loaded_xx_provider variable. |
24153 | int len = snprintf(buf, sizeof(buf), "g:loaded_%s_provider" , name); |
24154 | if (get_var_tv(buf, len, &tv, NULL, false, true) == FAIL) { |
24155 | // Trigger autoload once. |
24156 | len = snprintf(buf, sizeof(buf), "provider#%s#bogus" , name); |
24157 | script_autoload(buf, len, false); |
24158 | |
24159 | // Retry the (non-autoload-style) variable. |
24160 | len = snprintf(buf, sizeof(buf), "g:loaded_%s_provider" , name); |
24161 | if (get_var_tv(buf, len, &tv, NULL, false, true) == FAIL) { |
24162 | // Show a hint if Call() is defined but g:loaded_xx_provider is missing. |
24163 | snprintf(buf, sizeof(buf), "provider#%s#Call" , name); |
24164 | if (!!find_func((char_u *)buf) && p_lpl) { |
24165 | emsgf("provider: %s: missing required variable g:loaded_%s_provider" , |
24166 | name, name); |
24167 | } |
24168 | return false; |
24169 | } |
24170 | } |
24171 | |
24172 | bool ok = (tv.v_type == VAR_NUMBER) |
24173 | ? 2 == tv.vval.v_number // Value of 2 means "loaded and working". |
24174 | : false; |
24175 | |
24176 | if (ok) { |
24177 | // Call() must be defined if provider claims to be working. |
24178 | snprintf(buf, sizeof(buf), "provider#%s#Call" , name); |
24179 | if (!find_func((char_u *)buf)) { |
24180 | emsgf("provider: %s: g:loaded_%s_provider=2 but %s is not defined" , |
24181 | name, name, buf); |
24182 | ok = false; |
24183 | } |
24184 | } |
24185 | |
24186 | return ok; |
24187 | } |
24188 | |
24189 | /// Writes "<sourcing_name>:<sourcing_lnum>" to `buf[bufsize]`. |
24190 | void eval_fmt_source_name_line(char *buf, size_t bufsize) |
24191 | { |
24192 | if (sourcing_name) { |
24193 | snprintf(buf, bufsize, "%s:%" PRIdLINENR, sourcing_name, sourcing_lnum); |
24194 | } else { |
24195 | snprintf(buf, bufsize, "?" ); |
24196 | } |
24197 | } |
24198 | |
24199 | /// ":checkhealth [plugins]" |
24200 | void ex_checkhealth(exarg_T *eap) |
24201 | { |
24202 | bool found = !!find_func((char_u *)"health#check" ); |
24203 | if (!found |
24204 | && script_autoload("health#check" , sizeof("health#check" ) - 1, false)) { |
24205 | found = !!find_func((char_u *)"health#check" ); |
24206 | } |
24207 | if (!found) { |
24208 | const char *vimruntime_env = os_getenv("VIMRUNTIME" ); |
24209 | if (vimruntime_env == NULL) { |
24210 | EMSG(_("E5009: $VIMRUNTIME is empty or unset" )); |
24211 | } else { |
24212 | bool rtp_ok = NULL != strstr((char *)p_rtp, vimruntime_env); |
24213 | if (rtp_ok) { |
24214 | EMSG2(_("E5009: Invalid $VIMRUNTIME: %s" ), vimruntime_env); |
24215 | } else { |
24216 | EMSG(_("E5009: Invalid 'runtimepath'" )); |
24217 | } |
24218 | } |
24219 | return; |
24220 | } |
24221 | |
24222 | size_t bufsize = STRLEN(eap->arg) + sizeof("call health#check('')" ); |
24223 | char *buf = xmalloc(bufsize); |
24224 | snprintf(buf, bufsize, "call health#check('%s')" , eap->arg); |
24225 | |
24226 | do_cmdline_cmd(buf); |
24227 | |
24228 | xfree(buf); |
24229 | } |
24230 | |