Add <D-BS> and <M-BS> insert mode mappings
[MacVim.git] / src / eval.c
blob9ef9aaeaf93d5e46d7dd22647897721b5b54d252
1 /* vi:set ts=8 sts=4 sw=4:
3 * VIM - Vi IMproved by Bram Moolenaar
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
11 * eval.c: Expression evaluation.
13 #if defined(MSDOS) || defined(WIN16) || defined(WIN32) || defined(_WIN64)
14 # include "vimio.h" /* for mch_open(), must be before vim.h */
15 #endif
17 #include "vim.h"
19 #if defined(FEAT_EVAL) || defined(PROTO)
21 #ifdef AMIGA
22 # include <time.h> /* for strftime() */
23 #endif
25 #ifdef MACOS
26 # include <time.h> /* for time_t */
27 #endif
29 #if defined(FEAT_FLOAT) && defined(HAVE_MATH_H)
30 # include <math.h>
31 #endif
33 #define DICT_MAXNEST 100 /* maximum nesting of lists and dicts */
36 * In a hashtab item "hi_key" points to "di_key" in a dictitem.
37 * This avoids adding a pointer to the hashtab item.
38 * DI2HIKEY() converts a dictitem pointer to a hashitem key pointer.
39 * HIKEY2DI() converts a hashitem key pointer to a dictitem pointer.
40 * HI2DI() converts a hashitem pointer to a dictitem pointer.
42 static dictitem_T dumdi;
43 #define DI2HIKEY(di) ((di)->di_key)
44 #define HIKEY2DI(p) ((dictitem_T *)(p - (dumdi.di_key - (char_u *)&dumdi)))
45 #define HI2DI(hi) HIKEY2DI((hi)->hi_key)
48 * Structure returned by get_lval() and used by set_var_lval().
49 * For a plain name:
50 * "name" points to the variable name.
51 * "exp_name" is NULL.
52 * "tv" is NULL
53 * For a magic braces name:
54 * "name" points to the expanded variable name.
55 * "exp_name" is non-NULL, to be freed later.
56 * "tv" is NULL
57 * For an index in a list:
58 * "name" points to the (expanded) variable name.
59 * "exp_name" NULL or non-NULL, to be freed later.
60 * "tv" points to the (first) list item value
61 * "li" points to the (first) list item
62 * "range", "n1", "n2" and "empty2" indicate what items are used.
63 * For an existing Dict item:
64 * "name" points to the (expanded) variable name.
65 * "exp_name" NULL or non-NULL, to be freed later.
66 * "tv" points to the dict item value
67 * "newkey" is NULL
68 * For a non-existing Dict item:
69 * "name" points to the (expanded) variable name.
70 * "exp_name" NULL or non-NULL, to be freed later.
71 * "tv" points to the Dictionary typval_T
72 * "newkey" is the key for the new item.
74 typedef struct lval_S
76 char_u *ll_name; /* start of variable name (can be NULL) */
77 char_u *ll_exp_name; /* NULL or expanded name in allocated memory. */
78 typval_T *ll_tv; /* Typeval of item being used. If "newkey"
79 isn't NULL it's the Dict to which to add
80 the item. */
81 listitem_T *ll_li; /* The list item or NULL. */
82 list_T *ll_list; /* The list or NULL. */
83 int ll_range; /* TRUE when a [i:j] range was used */
84 long ll_n1; /* First index for list */
85 long ll_n2; /* Second index for list range */
86 int ll_empty2; /* Second index is empty: [i:] */
87 dict_T *ll_dict; /* The Dictionary or NULL */
88 dictitem_T *ll_di; /* The dictitem or NULL */
89 char_u *ll_newkey; /* New key for Dict in alloc. mem or NULL. */
90 } lval_T;
93 static char *e_letunexp = N_("E18: Unexpected characters in :let");
94 static char *e_listidx = N_("E684: list index out of range: %ld");
95 static char *e_undefvar = N_("E121: Undefined variable: %s");
96 static char *e_missbrac = N_("E111: Missing ']'");
97 static char *e_listarg = N_("E686: Argument of %s must be a List");
98 static char *e_listdictarg = N_("E712: Argument of %s must be a List or Dictionary");
99 static char *e_emptykey = N_("E713: Cannot use empty key for Dictionary");
100 static char *e_listreq = N_("E714: List required");
101 static char *e_dictreq = N_("E715: Dictionary required");
102 static char *e_toomanyarg = N_("E118: Too many arguments for function: %s");
103 static char *e_dictkey = N_("E716: Key not present in Dictionary: %s");
104 static char *e_funcexts = N_("E122: Function %s already exists, add ! to replace it");
105 static char *e_funcdict = N_("E717: Dictionary entry already exists");
106 static char *e_funcref = N_("E718: Funcref required");
107 static char *e_dictrange = N_("E719: Cannot use [:] with a Dictionary");
108 static char *e_letwrong = N_("E734: Wrong variable type for %s=");
109 static char *e_nofunc = N_("E130: Unknown function: %s");
110 static char *e_illvar = N_("E461: Illegal variable name: %s");
113 * All user-defined global variables are stored in dictionary "globvardict".
114 * "globvars_var" is the variable that is used for "g:".
116 static dict_T globvardict;
117 static dictitem_T globvars_var;
118 #define globvarht globvardict.dv_hashtab
121 * Old Vim variables such as "v:version" are also available without the "v:".
122 * Also in functions. We need a special hashtable for them.
124 static hashtab_T compat_hashtab;
127 * When recursively copying lists and dicts we need to remember which ones we
128 * have done to avoid endless recursiveness. This unique ID is used for that.
130 static int current_copyID = 0;
133 * Array to hold the hashtab with variables local to each sourced script.
134 * Each item holds a variable (nameless) that points to the dict_T.
136 typedef struct
138 dictitem_T sv_var;
139 dict_T sv_dict;
140 } scriptvar_T;
142 static garray_T ga_scripts = {0, 0, sizeof(scriptvar_T), 4, NULL};
143 #define SCRIPT_SV(id) (((scriptvar_T *)ga_scripts.ga_data)[(id) - 1])
144 #define SCRIPT_VARS(id) (SCRIPT_SV(id).sv_dict.dv_hashtab)
146 static int echo_attr = 0; /* attributes used for ":echo" */
148 /* Values for trans_function_name() argument: */
149 #define TFN_INT 1 /* internal function name OK */
150 #define TFN_QUIET 2 /* no error messages */
153 * Structure to hold info for a user function.
155 typedef struct ufunc ufunc_T;
157 struct ufunc
159 int uf_varargs; /* variable nr of arguments */
160 int uf_flags;
161 int uf_calls; /* nr of active calls */
162 garray_T uf_args; /* arguments */
163 garray_T uf_lines; /* function lines */
164 #ifdef FEAT_PROFILE
165 int uf_profiling; /* TRUE when func is being profiled */
166 /* profiling the function as a whole */
167 int uf_tm_count; /* nr of calls */
168 proftime_T uf_tm_total; /* time spent in function + children */
169 proftime_T uf_tm_self; /* time spent in function itself */
170 proftime_T uf_tm_children; /* time spent in children this call */
171 /* profiling the function per line */
172 int *uf_tml_count; /* nr of times line was executed */
173 proftime_T *uf_tml_total; /* time spent in a line + children */
174 proftime_T *uf_tml_self; /* time spent in a line itself */
175 proftime_T uf_tml_start; /* start time for current line */
176 proftime_T uf_tml_children; /* time spent in children for this line */
177 proftime_T uf_tml_wait; /* start wait time for current line */
178 int uf_tml_idx; /* index of line being timed; -1 if none */
179 int uf_tml_execed; /* line being timed was executed */
180 #endif
181 scid_T uf_script_ID; /* ID of script where function was defined,
182 used for s: variables */
183 int uf_refcount; /* for numbered function: reference count */
184 char_u uf_name[1]; /* name of function (actually longer); can
185 start with <SNR>123_ (<SNR> is K_SPECIAL
186 KS_EXTRA KE_SNR) */
189 /* function flags */
190 #define FC_ABORT 1 /* abort function on error */
191 #define FC_RANGE 2 /* function accepts range */
192 #define FC_DICT 4 /* Dict function, uses "self" */
195 * All user-defined functions are found in this hashtable.
197 static hashtab_T func_hashtab;
199 /* The names of packages that once were loaded are remembered. */
200 static garray_T ga_loaded = {0, 0, sizeof(char_u *), 4, NULL};
202 /* list heads for garbage collection */
203 static dict_T *first_dict = NULL; /* list of all dicts */
204 static list_T *first_list = NULL; /* list of all lists */
206 /* From user function to hashitem and back. */
207 static ufunc_T dumuf;
208 #define UF2HIKEY(fp) ((fp)->uf_name)
209 #define HIKEY2UF(p) ((ufunc_T *)(p - (dumuf.uf_name - (char_u *)&dumuf)))
210 #define HI2UF(hi) HIKEY2UF((hi)->hi_key)
212 #define FUNCARG(fp, j) ((char_u **)(fp->uf_args.ga_data))[j]
213 #define FUNCLINE(fp, j) ((char_u **)(fp->uf_lines.ga_data))[j]
215 #define MAX_FUNC_ARGS 20 /* maximum number of function arguments */
216 #define VAR_SHORT_LEN 20 /* short variable name length */
217 #define FIXVAR_CNT 12 /* number of fixed variables */
219 /* structure to hold info for a function that is currently being executed. */
220 typedef struct funccall_S funccall_T;
222 struct funccall_S
224 ufunc_T *func; /* function being called */
225 int linenr; /* next line to be executed */
226 int returned; /* ":return" used */
227 struct /* fixed variables for arguments */
229 dictitem_T var; /* variable (without room for name) */
230 char_u room[VAR_SHORT_LEN]; /* room for the name */
231 } fixvar[FIXVAR_CNT];
232 dict_T l_vars; /* l: local function variables */
233 dictitem_T l_vars_var; /* variable for l: scope */
234 dict_T l_avars; /* a: argument variables */
235 dictitem_T l_avars_var; /* variable for a: scope */
236 list_T l_varlist; /* list for a:000 */
237 listitem_T l_listitems[MAX_FUNC_ARGS]; /* listitems for a:000 */
238 typval_T *rettv; /* return value */
239 linenr_T breakpoint; /* next line with breakpoint or zero */
240 int dbg_tick; /* debug_tick when breakpoint was set */
241 int level; /* top nesting level of executed function */
242 #ifdef FEAT_PROFILE
243 proftime_T prof_child; /* time spent in a child */
244 #endif
245 funccall_T *caller; /* calling function or NULL */
249 * Info used by a ":for" loop.
251 typedef struct
253 int fi_semicolon; /* TRUE if ending in '; var]' */
254 int fi_varcount; /* nr of variables in the list */
255 listwatch_T fi_lw; /* keep an eye on the item used. */
256 list_T *fi_list; /* list being used */
257 } forinfo_T;
260 * Struct used by trans_function_name()
262 typedef struct
264 dict_T *fd_dict; /* Dictionary used */
265 char_u *fd_newkey; /* new key in "dict" in allocated memory */
266 dictitem_T *fd_di; /* Dictionary item used */
267 } funcdict_T;
271 * Array to hold the value of v: variables.
272 * The value is in a dictitem, so that it can also be used in the v: scope.
273 * The reason to use this table anyway is for very quick access to the
274 * variables with the VV_ defines.
276 #include "version.h"
278 /* values for vv_flags: */
279 #define VV_COMPAT 1 /* compatible, also used without "v:" */
280 #define VV_RO 2 /* read-only */
281 #define VV_RO_SBX 4 /* read-only in the sandbox */
283 #define VV_NAME(s, t) s, {{t}}, {0}
285 static struct vimvar
287 char *vv_name; /* name of variable, without v: */
288 dictitem_T vv_di; /* value and name for key */
289 char vv_filler[16]; /* space for LONGEST name below!!! */
290 char vv_flags; /* VV_COMPAT, VV_RO, VV_RO_SBX */
291 } vimvars[VV_LEN] =
294 * The order here must match the VV_ defines in vim.h!
295 * Initializing a union does not work, leave tv.vval empty to get zero's.
297 {VV_NAME("count", VAR_NUMBER), VV_COMPAT+VV_RO},
298 {VV_NAME("count1", VAR_NUMBER), VV_RO},
299 {VV_NAME("prevcount", VAR_NUMBER), VV_RO},
300 {VV_NAME("errmsg", VAR_STRING), VV_COMPAT},
301 {VV_NAME("warningmsg", VAR_STRING), 0},
302 {VV_NAME("statusmsg", VAR_STRING), 0},
303 {VV_NAME("shell_error", VAR_NUMBER), VV_COMPAT+VV_RO},
304 {VV_NAME("this_session", VAR_STRING), VV_COMPAT},
305 {VV_NAME("version", VAR_NUMBER), VV_COMPAT+VV_RO},
306 {VV_NAME("lnum", VAR_NUMBER), VV_RO_SBX},
307 {VV_NAME("termresponse", VAR_STRING), VV_RO},
308 {VV_NAME("fname", VAR_STRING), VV_RO},
309 {VV_NAME("lang", VAR_STRING), VV_RO},
310 {VV_NAME("lc_time", VAR_STRING), VV_RO},
311 {VV_NAME("ctype", VAR_STRING), VV_RO},
312 {VV_NAME("charconvert_from", VAR_STRING), VV_RO},
313 {VV_NAME("charconvert_to", VAR_STRING), VV_RO},
314 {VV_NAME("fname_in", VAR_STRING), VV_RO},
315 {VV_NAME("fname_out", VAR_STRING), VV_RO},
316 {VV_NAME("fname_new", VAR_STRING), VV_RO},
317 {VV_NAME("fname_diff", VAR_STRING), VV_RO},
318 {VV_NAME("cmdarg", VAR_STRING), VV_RO},
319 {VV_NAME("foldstart", VAR_NUMBER), VV_RO_SBX},
320 {VV_NAME("foldend", VAR_NUMBER), VV_RO_SBX},
321 {VV_NAME("folddashes", VAR_STRING), VV_RO_SBX},
322 {VV_NAME("foldlevel", VAR_NUMBER), VV_RO_SBX},
323 {VV_NAME("progname", VAR_STRING), VV_RO},
324 {VV_NAME("servername", VAR_STRING), VV_RO},
325 {VV_NAME("dying", VAR_NUMBER), VV_RO},
326 {VV_NAME("exception", VAR_STRING), VV_RO},
327 {VV_NAME("throwpoint", VAR_STRING), VV_RO},
328 {VV_NAME("register", VAR_STRING), VV_RO},
329 {VV_NAME("cmdbang", VAR_NUMBER), VV_RO},
330 {VV_NAME("insertmode", VAR_STRING), VV_RO},
331 {VV_NAME("val", VAR_UNKNOWN), VV_RO},
332 {VV_NAME("key", VAR_UNKNOWN), VV_RO},
333 {VV_NAME("profiling", VAR_NUMBER), VV_RO},
334 {VV_NAME("fcs_reason", VAR_STRING), VV_RO},
335 {VV_NAME("fcs_choice", VAR_STRING), 0},
336 {VV_NAME("beval_bufnr", VAR_NUMBER), VV_RO},
337 {VV_NAME("beval_winnr", VAR_NUMBER), VV_RO},
338 {VV_NAME("beval_lnum", VAR_NUMBER), VV_RO},
339 {VV_NAME("beval_col", VAR_NUMBER), VV_RO},
340 {VV_NAME("beval_text", VAR_STRING), VV_RO},
341 {VV_NAME("scrollstart", VAR_STRING), 0},
342 {VV_NAME("swapname", VAR_STRING), VV_RO},
343 {VV_NAME("swapchoice", VAR_STRING), 0},
344 {VV_NAME("swapcommand", VAR_STRING), VV_RO},
345 {VV_NAME("char", VAR_STRING), VV_RO},
346 {VV_NAME("mouse_win", VAR_NUMBER), 0},
347 {VV_NAME("mouse_lnum", VAR_NUMBER), 0},
348 {VV_NAME("mouse_col", VAR_NUMBER), 0},
349 {VV_NAME("operator", VAR_STRING), VV_RO},
350 {VV_NAME("searchforward", VAR_NUMBER), 0},
351 {VV_NAME("oldfiles", VAR_LIST), 0},
354 /* shorthand */
355 #define vv_type vv_di.di_tv.v_type
356 #define vv_nr vv_di.di_tv.vval.v_number
357 #define vv_float vv_di.di_tv.vval.v_float
358 #define vv_str vv_di.di_tv.vval.v_string
359 #define vv_list vv_di.di_tv.vval.v_list
360 #define vv_tv vv_di.di_tv
363 * The v: variables are stored in dictionary "vimvardict".
364 * "vimvars_var" is the variable that is used for the "l:" scope.
366 static dict_T vimvardict;
367 static dictitem_T vimvars_var;
368 #define vimvarht vimvardict.dv_hashtab
370 static void prepare_vimvar __ARGS((int idx, typval_T *save_tv));
371 static void restore_vimvar __ARGS((int idx, typval_T *save_tv));
372 #if defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)
373 static int call_vim_function __ARGS((char_u *func, int argc, char_u **argv, int safe, typval_T *rettv));
374 #endif
375 static int ex_let_vars __ARGS((char_u *arg, typval_T *tv, int copy, int semicolon, int var_count, char_u *nextchars));
376 static char_u *skip_var_list __ARGS((char_u *arg, int *var_count, int *semicolon));
377 static char_u *skip_var_one __ARGS((char_u *arg));
378 static void list_hashtable_vars __ARGS((hashtab_T *ht, char_u *prefix, int empty, int *first));
379 static void list_glob_vars __ARGS((int *first));
380 static void list_buf_vars __ARGS((int *first));
381 static void list_win_vars __ARGS((int *first));
382 #ifdef FEAT_WINDOWS
383 static void list_tab_vars __ARGS((int *first));
384 #endif
385 static void list_vim_vars __ARGS((int *first));
386 static void list_script_vars __ARGS((int *first));
387 static void list_func_vars __ARGS((int *first));
388 static char_u *list_arg_vars __ARGS((exarg_T *eap, char_u *arg, int *first));
389 static char_u *ex_let_one __ARGS((char_u *arg, typval_T *tv, int copy, char_u *endchars, char_u *op));
390 static int check_changedtick __ARGS((char_u *arg));
391 static char_u *get_lval __ARGS((char_u *name, typval_T *rettv, lval_T *lp, int unlet, int skip, int quiet, int fne_flags));
392 static void clear_lval __ARGS((lval_T *lp));
393 static void set_var_lval __ARGS((lval_T *lp, char_u *endp, typval_T *rettv, int copy, char_u *op));
394 static int tv_op __ARGS((typval_T *tv1, typval_T *tv2, char_u *op));
395 static void list_add_watch __ARGS((list_T *l, listwatch_T *lw));
396 static void list_rem_watch __ARGS((list_T *l, listwatch_T *lwrem));
397 static void list_fix_watch __ARGS((list_T *l, listitem_T *item));
398 static void ex_unletlock __ARGS((exarg_T *eap, char_u *argstart, int deep));
399 static int do_unlet_var __ARGS((lval_T *lp, char_u *name_end, int forceit));
400 static int do_lock_var __ARGS((lval_T *lp, char_u *name_end, int deep, int lock));
401 static void item_lock __ARGS((typval_T *tv, int deep, int lock));
402 static int tv_islocked __ARGS((typval_T *tv));
404 static int eval0 __ARGS((char_u *arg, typval_T *rettv, char_u **nextcmd, int evaluate));
405 static int eval1 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
406 static int eval2 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
407 static int eval3 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
408 static int eval4 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
409 static int eval5 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
410 static int eval6 __ARGS((char_u **arg, typval_T *rettv, int evaluate, int want_string));
411 static int eval7 __ARGS((char_u **arg, typval_T *rettv, int evaluate, int want_string));
413 static int eval_index __ARGS((char_u **arg, typval_T *rettv, int evaluate, int verbose));
414 static int get_option_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
415 static int get_string_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
416 static int get_lit_string_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
417 static int get_list_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
418 static int rettv_list_alloc __ARGS((typval_T *rettv));
419 static listitem_T *listitem_alloc __ARGS((void));
420 static void listitem_free __ARGS((listitem_T *item));
421 static void listitem_remove __ARGS((list_T *l, listitem_T *item));
422 static long list_len __ARGS((list_T *l));
423 static int list_equal __ARGS((list_T *l1, list_T *l2, int ic));
424 static int dict_equal __ARGS((dict_T *d1, dict_T *d2, int ic));
425 static int tv_equal __ARGS((typval_T *tv1, typval_T *tv2, int ic));
426 static listitem_T *list_find __ARGS((list_T *l, long n));
427 static long list_find_nr __ARGS((list_T *l, long idx, int *errorp));
428 static long list_idx_of_item __ARGS((list_T *l, listitem_T *item));
429 static void list_append __ARGS((list_T *l, listitem_T *item));
430 static int list_append_tv __ARGS((list_T *l, typval_T *tv));
431 static int list_append_number __ARGS((list_T *l, varnumber_T n));
432 static int list_insert_tv __ARGS((list_T *l, typval_T *tv, listitem_T *item));
433 static int list_extend __ARGS((list_T *l1, list_T *l2, listitem_T *bef));
434 static int list_concat __ARGS((list_T *l1, list_T *l2, typval_T *tv));
435 static list_T *list_copy __ARGS((list_T *orig, int deep, int copyID));
436 static void list_remove __ARGS((list_T *l, listitem_T *item, listitem_T *item2));
437 static char_u *list2string __ARGS((typval_T *tv, int copyID));
438 static int list_join __ARGS((garray_T *gap, list_T *l, char_u *sep, int echo, int copyID));
439 static void set_ref_in_ht __ARGS((hashtab_T *ht, int copyID));
440 static void set_ref_in_list __ARGS((list_T *l, int copyID));
441 static void set_ref_in_item __ARGS((typval_T *tv, int copyID));
442 static void dict_unref __ARGS((dict_T *d));
443 static void dict_free __ARGS((dict_T *d, int recurse));
444 static dictitem_T *dictitem_alloc __ARGS((char_u *key));
445 static dictitem_T *dictitem_copy __ARGS((dictitem_T *org));
446 static void dictitem_remove __ARGS((dict_T *dict, dictitem_T *item));
447 static void dictitem_free __ARGS((dictitem_T *item));
448 static dict_T *dict_copy __ARGS((dict_T *orig, int deep, int copyID));
449 static int dict_add __ARGS((dict_T *d, dictitem_T *item));
450 static long dict_len __ARGS((dict_T *d));
451 static dictitem_T *dict_find __ARGS((dict_T *d, char_u *key, int len));
452 static char_u *dict2string __ARGS((typval_T *tv, int copyID));
453 static int get_dict_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
454 static char_u *echo_string __ARGS((typval_T *tv, char_u **tofree, char_u *numbuf, int copyID));
455 static char_u *tv2string __ARGS((typval_T *tv, char_u **tofree, char_u *numbuf, int copyID));
456 static char_u *string_quote __ARGS((char_u *str, int function));
457 #ifdef FEAT_FLOAT
458 static int string2float __ARGS((char_u *text, float_T *value));
459 #endif
460 static int get_env_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
461 static int find_internal_func __ARGS((char_u *name));
462 static char_u *deref_func_name __ARGS((char_u *name, int *lenp));
463 static int get_func_tv __ARGS((char_u *name, int len, typval_T *rettv, char_u **arg, linenr_T firstline, linenr_T lastline, int *doesrange, int evaluate, dict_T *selfdict));
464 static int call_func __ARGS((char_u *name, int len, typval_T *rettv, int argcount, typval_T *argvars, linenr_T firstline, linenr_T lastline, int *doesrange, int evaluate, dict_T *selfdict));
465 static void emsg_funcname __ARGS((char *ermsg, char_u *name));
466 static int non_zero_arg __ARGS((typval_T *argvars));
468 #ifdef FEAT_FLOAT
469 static void f_abs __ARGS((typval_T *argvars, typval_T *rettv));
470 #endif
471 static void f_add __ARGS((typval_T *argvars, typval_T *rettv));
472 static void f_append __ARGS((typval_T *argvars, typval_T *rettv));
473 static void f_argc __ARGS((typval_T *argvars, typval_T *rettv));
474 static void f_argidx __ARGS((typval_T *argvars, typval_T *rettv));
475 static void f_argv __ARGS((typval_T *argvars, typval_T *rettv));
476 #ifdef FEAT_FLOAT
477 static void f_atan __ARGS((typval_T *argvars, typval_T *rettv));
478 #endif
479 static void f_browse __ARGS((typval_T *argvars, typval_T *rettv));
480 static void f_browsedir __ARGS((typval_T *argvars, typval_T *rettv));
481 static void f_bufexists __ARGS((typval_T *argvars, typval_T *rettv));
482 static void f_buflisted __ARGS((typval_T *argvars, typval_T *rettv));
483 static void f_bufloaded __ARGS((typval_T *argvars, typval_T *rettv));
484 static void f_bufname __ARGS((typval_T *argvars, typval_T *rettv));
485 static void f_bufnr __ARGS((typval_T *argvars, typval_T *rettv));
486 static void f_bufwinnr __ARGS((typval_T *argvars, typval_T *rettv));
487 static void f_byte2line __ARGS((typval_T *argvars, typval_T *rettv));
488 static void f_byteidx __ARGS((typval_T *argvars, typval_T *rettv));
489 static void f_call __ARGS((typval_T *argvars, typval_T *rettv));
490 #ifdef FEAT_FLOAT
491 static void f_ceil __ARGS((typval_T *argvars, typval_T *rettv));
492 #endif
493 static void f_changenr __ARGS((typval_T *argvars, typval_T *rettv));
494 static void f_char2nr __ARGS((typval_T *argvars, typval_T *rettv));
495 static void f_cindent __ARGS((typval_T *argvars, typval_T *rettv));
496 static void f_clearmatches __ARGS((typval_T *argvars, typval_T *rettv));
497 static void f_col __ARGS((typval_T *argvars, typval_T *rettv));
498 #if defined(FEAT_INS_EXPAND)
499 static void f_complete __ARGS((typval_T *argvars, typval_T *rettv));
500 static void f_complete_add __ARGS((typval_T *argvars, typval_T *rettv));
501 static void f_complete_check __ARGS((typval_T *argvars, typval_T *rettv));
502 #endif
503 static void f_confirm __ARGS((typval_T *argvars, typval_T *rettv));
504 static void f_copy __ARGS((typval_T *argvars, typval_T *rettv));
505 #ifdef FEAT_FLOAT
506 static void f_cos __ARGS((typval_T *argvars, typval_T *rettv));
507 #endif
508 static void f_count __ARGS((typval_T *argvars, typval_T *rettv));
509 static void f_cscope_connection __ARGS((typval_T *argvars, typval_T *rettv));
510 static void f_cursor __ARGS((typval_T *argsvars, typval_T *rettv));
511 static void f_deepcopy __ARGS((typval_T *argvars, typval_T *rettv));
512 static void f_delete __ARGS((typval_T *argvars, typval_T *rettv));
513 static void f_did_filetype __ARGS((typval_T *argvars, typval_T *rettv));
514 static void f_diff_filler __ARGS((typval_T *argvars, typval_T *rettv));
515 static void f_diff_hlID __ARGS((typval_T *argvars, typval_T *rettv));
516 static void f_empty __ARGS((typval_T *argvars, typval_T *rettv));
517 static void f_escape __ARGS((typval_T *argvars, typval_T *rettv));
518 static void f_eval __ARGS((typval_T *argvars, typval_T *rettv));
519 static void f_eventhandler __ARGS((typval_T *argvars, typval_T *rettv));
520 static void f_executable __ARGS((typval_T *argvars, typval_T *rettv));
521 static void f_exists __ARGS((typval_T *argvars, typval_T *rettv));
522 static void f_expand __ARGS((typval_T *argvars, typval_T *rettv));
523 static void f_extend __ARGS((typval_T *argvars, typval_T *rettv));
524 static void f_feedkeys __ARGS((typval_T *argvars, typval_T *rettv));
525 static void f_filereadable __ARGS((typval_T *argvars, typval_T *rettv));
526 static void f_filewritable __ARGS((typval_T *argvars, typval_T *rettv));
527 static void f_filter __ARGS((typval_T *argvars, typval_T *rettv));
528 static void f_finddir __ARGS((typval_T *argvars, typval_T *rettv));
529 static void f_findfile __ARGS((typval_T *argvars, typval_T *rettv));
530 #ifdef FEAT_FLOAT
531 static void f_float2nr __ARGS((typval_T *argvars, typval_T *rettv));
532 static void f_floor __ARGS((typval_T *argvars, typval_T *rettv));
533 #endif
534 static void f_fnameescape __ARGS((typval_T *argvars, typval_T *rettv));
535 static void f_fnamemodify __ARGS((typval_T *argvars, typval_T *rettv));
536 static void f_foldclosed __ARGS((typval_T *argvars, typval_T *rettv));
537 static void f_foldclosedend __ARGS((typval_T *argvars, typval_T *rettv));
538 static void f_foldlevel __ARGS((typval_T *argvars, typval_T *rettv));
539 static void f_foldtext __ARGS((typval_T *argvars, typval_T *rettv));
540 static void f_foldtextresult __ARGS((typval_T *argvars, typval_T *rettv));
541 static void f_foreground __ARGS((typval_T *argvars, typval_T *rettv));
542 static void f_function __ARGS((typval_T *argvars, typval_T *rettv));
543 static void f_garbagecollect __ARGS((typval_T *argvars, typval_T *rettv));
544 static void f_get __ARGS((typval_T *argvars, typval_T *rettv));
545 static void f_getbufline __ARGS((typval_T *argvars, typval_T *rettv));
546 static void f_getbufvar __ARGS((typval_T *argvars, typval_T *rettv));
547 static void f_getchar __ARGS((typval_T *argvars, typval_T *rettv));
548 static void f_getcharmod __ARGS((typval_T *argvars, typval_T *rettv));
549 static void f_getcmdline __ARGS((typval_T *argvars, typval_T *rettv));
550 static void f_getcmdpos __ARGS((typval_T *argvars, typval_T *rettv));
551 static void f_getcmdtype __ARGS((typval_T *argvars, typval_T *rettv));
552 static void f_getcwd __ARGS((typval_T *argvars, typval_T *rettv));
553 static void f_getfontname __ARGS((typval_T *argvars, typval_T *rettv));
554 static void f_getfperm __ARGS((typval_T *argvars, typval_T *rettv));
555 static void f_getfsize __ARGS((typval_T *argvars, typval_T *rettv));
556 static void f_getftime __ARGS((typval_T *argvars, typval_T *rettv));
557 static void f_getftype __ARGS((typval_T *argvars, typval_T *rettv));
558 static void f_getline __ARGS((typval_T *argvars, typval_T *rettv));
559 static void f_getmatches __ARGS((typval_T *argvars, typval_T *rettv));
560 static void f_getpid __ARGS((typval_T *argvars, typval_T *rettv));
561 static void f_getpos __ARGS((typval_T *argvars, typval_T *rettv));
562 static void f_getqflist __ARGS((typval_T *argvars, typval_T *rettv));
563 static void f_getreg __ARGS((typval_T *argvars, typval_T *rettv));
564 static void f_getregtype __ARGS((typval_T *argvars, typval_T *rettv));
565 static void f_gettabwinvar __ARGS((typval_T *argvars, typval_T *rettv));
566 static void f_getwinposx __ARGS((typval_T *argvars, typval_T *rettv));
567 static void f_getwinposy __ARGS((typval_T *argvars, typval_T *rettv));
568 static void f_getwinvar __ARGS((typval_T *argvars, typval_T *rettv));
569 static void f_glob __ARGS((typval_T *argvars, typval_T *rettv));
570 static void f_globpath __ARGS((typval_T *argvars, typval_T *rettv));
571 static void f_has __ARGS((typval_T *argvars, typval_T *rettv));
572 static void f_has_key __ARGS((typval_T *argvars, typval_T *rettv));
573 static void f_haslocaldir __ARGS((typval_T *argvars, typval_T *rettv));
574 static void f_hasmapto __ARGS((typval_T *argvars, typval_T *rettv));
575 static void f_histadd __ARGS((typval_T *argvars, typval_T *rettv));
576 static void f_histdel __ARGS((typval_T *argvars, typval_T *rettv));
577 static void f_histget __ARGS((typval_T *argvars, typval_T *rettv));
578 static void f_histnr __ARGS((typval_T *argvars, typval_T *rettv));
579 static void f_hlID __ARGS((typval_T *argvars, typval_T *rettv));
580 static void f_hlexists __ARGS((typval_T *argvars, typval_T *rettv));
581 static void f_hostname __ARGS((typval_T *argvars, typval_T *rettv));
582 static void f_iconv __ARGS((typval_T *argvars, typval_T *rettv));
583 static void f_indent __ARGS((typval_T *argvars, typval_T *rettv));
584 static void f_index __ARGS((typval_T *argvars, typval_T *rettv));
585 static void f_input __ARGS((typval_T *argvars, typval_T *rettv));
586 static void f_inputdialog __ARGS((typval_T *argvars, typval_T *rettv));
587 static void f_inputlist __ARGS((typval_T *argvars, typval_T *rettv));
588 static void f_inputrestore __ARGS((typval_T *argvars, typval_T *rettv));
589 static void f_inputsave __ARGS((typval_T *argvars, typval_T *rettv));
590 static void f_inputsecret __ARGS((typval_T *argvars, typval_T *rettv));
591 static void f_insert __ARGS((typval_T *argvars, typval_T *rettv));
592 static void f_isdirectory __ARGS((typval_T *argvars, typval_T *rettv));
593 static void f_islocked __ARGS((typval_T *argvars, typval_T *rettv));
594 static void f_items __ARGS((typval_T *argvars, typval_T *rettv));
595 static void f_join __ARGS((typval_T *argvars, typval_T *rettv));
596 static void f_keys __ARGS((typval_T *argvars, typval_T *rettv));
597 static void f_last_buffer_nr __ARGS((typval_T *argvars, typval_T *rettv));
598 static void f_len __ARGS((typval_T *argvars, typval_T *rettv));
599 static void f_libcall __ARGS((typval_T *argvars, typval_T *rettv));
600 static void f_libcallnr __ARGS((typval_T *argvars, typval_T *rettv));
601 static void f_line __ARGS((typval_T *argvars, typval_T *rettv));
602 static void f_line2byte __ARGS((typval_T *argvars, typval_T *rettv));
603 static void f_lispindent __ARGS((typval_T *argvars, typval_T *rettv));
604 static void f_localtime __ARGS((typval_T *argvars, typval_T *rettv));
605 #ifdef FEAT_FLOAT
606 static void f_log10 __ARGS((typval_T *argvars, typval_T *rettv));
607 #endif
608 static void f_map __ARGS((typval_T *argvars, typval_T *rettv));
609 static void f_maparg __ARGS((typval_T *argvars, typval_T *rettv));
610 static void f_mapcheck __ARGS((typval_T *argvars, typval_T *rettv));
611 static void f_match __ARGS((typval_T *argvars, typval_T *rettv));
612 static void f_matchadd __ARGS((typval_T *argvars, typval_T *rettv));
613 static void f_matcharg __ARGS((typval_T *argvars, typval_T *rettv));
614 static void f_matchdelete __ARGS((typval_T *argvars, typval_T *rettv));
615 static void f_matchend __ARGS((typval_T *argvars, typval_T *rettv));
616 static void f_matchlist __ARGS((typval_T *argvars, typval_T *rettv));
617 static void f_matchstr __ARGS((typval_T *argvars, typval_T *rettv));
618 static void f_max __ARGS((typval_T *argvars, typval_T *rettv));
619 static void f_min __ARGS((typval_T *argvars, typval_T *rettv));
620 #ifdef vim_mkdir
621 static void f_mkdir __ARGS((typval_T *argvars, typval_T *rettv));
622 #endif
623 static void f_mode __ARGS((typval_T *argvars, typval_T *rettv));
624 static void f_nextnonblank __ARGS((typval_T *argvars, typval_T *rettv));
625 static void f_nr2char __ARGS((typval_T *argvars, typval_T *rettv));
626 static void f_pathshorten __ARGS((typval_T *argvars, typval_T *rettv));
627 #ifdef FEAT_FLOAT
628 static void f_pow __ARGS((typval_T *argvars, typval_T *rettv));
629 #endif
630 static void f_prevnonblank __ARGS((typval_T *argvars, typval_T *rettv));
631 static void f_printf __ARGS((typval_T *argvars, typval_T *rettv));
632 static void f_pumvisible __ARGS((typval_T *argvars, typval_T *rettv));
633 static void f_range __ARGS((typval_T *argvars, typval_T *rettv));
634 static void f_readfile __ARGS((typval_T *argvars, typval_T *rettv));
635 static void f_reltime __ARGS((typval_T *argvars, typval_T *rettv));
636 static void f_reltimestr __ARGS((typval_T *argvars, typval_T *rettv));
637 static void f_remote_expr __ARGS((typval_T *argvars, typval_T *rettv));
638 static void f_remote_foreground __ARGS((typval_T *argvars, typval_T *rettv));
639 static void f_remote_peek __ARGS((typval_T *argvars, typval_T *rettv));
640 static void f_remote_read __ARGS((typval_T *argvars, typval_T *rettv));
641 static void f_remote_send __ARGS((typval_T *argvars, typval_T *rettv));
642 static void f_remove __ARGS((typval_T *argvars, typval_T *rettv));
643 static void f_rename __ARGS((typval_T *argvars, typval_T *rettv));
644 static void f_repeat __ARGS((typval_T *argvars, typval_T *rettv));
645 static void f_resolve __ARGS((typval_T *argvars, typval_T *rettv));
646 static void f_reverse __ARGS((typval_T *argvars, typval_T *rettv));
647 #ifdef FEAT_FLOAT
648 static void f_round __ARGS((typval_T *argvars, typval_T *rettv));
649 #endif
650 static void f_search __ARGS((typval_T *argvars, typval_T *rettv));
651 static void f_searchdecl __ARGS((typval_T *argvars, typval_T *rettv));
652 static void f_searchpair __ARGS((typval_T *argvars, typval_T *rettv));
653 static void f_searchpairpos __ARGS((typval_T *argvars, typval_T *rettv));
654 static void f_searchpos __ARGS((typval_T *argvars, typval_T *rettv));
655 static void f_server2client __ARGS((typval_T *argvars, typval_T *rettv));
656 static void f_serverlist __ARGS((typval_T *argvars, typval_T *rettv));
657 static void f_setbufvar __ARGS((typval_T *argvars, typval_T *rettv));
658 static void f_setcmdpos __ARGS((typval_T *argvars, typval_T *rettv));
659 static void f_setline __ARGS((typval_T *argvars, typval_T *rettv));
660 static void f_setloclist __ARGS((typval_T *argvars, typval_T *rettv));
661 static void f_setmatches __ARGS((typval_T *argvars, typval_T *rettv));
662 static void f_setpos __ARGS((typval_T *argvars, typval_T *rettv));
663 static void f_setqflist __ARGS((typval_T *argvars, typval_T *rettv));
664 static void f_setreg __ARGS((typval_T *argvars, typval_T *rettv));
665 static void f_settabwinvar __ARGS((typval_T *argvars, typval_T *rettv));
666 static void f_setwinvar __ARGS((typval_T *argvars, typval_T *rettv));
667 static void f_shellescape __ARGS((typval_T *argvars, typval_T *rettv));
668 static void f_simplify __ARGS((typval_T *argvars, typval_T *rettv));
669 #ifdef FEAT_FLOAT
670 static void f_sin __ARGS((typval_T *argvars, typval_T *rettv));
671 #endif
672 static void f_sort __ARGS((typval_T *argvars, typval_T *rettv));
673 static void f_soundfold __ARGS((typval_T *argvars, typval_T *rettv));
674 static void f_spellbadword __ARGS((typval_T *argvars, typval_T *rettv));
675 static void f_spellsuggest __ARGS((typval_T *argvars, typval_T *rettv));
676 static void f_split __ARGS((typval_T *argvars, typval_T *rettv));
677 #ifdef FEAT_FLOAT
678 static void f_sqrt __ARGS((typval_T *argvars, typval_T *rettv));
679 static void f_str2float __ARGS((typval_T *argvars, typval_T *rettv));
680 #endif
681 static void f_str2nr __ARGS((typval_T *argvars, typval_T *rettv));
682 #ifdef HAVE_STRFTIME
683 static void f_strftime __ARGS((typval_T *argvars, typval_T *rettv));
684 #endif
685 static void f_stridx __ARGS((typval_T *argvars, typval_T *rettv));
686 static void f_string __ARGS((typval_T *argvars, typval_T *rettv));
687 static void f_strlen __ARGS((typval_T *argvars, typval_T *rettv));
688 static void f_strpart __ARGS((typval_T *argvars, typval_T *rettv));
689 static void f_strridx __ARGS((typval_T *argvars, typval_T *rettv));
690 static void f_strtrans __ARGS((typval_T *argvars, typval_T *rettv));
691 static void f_submatch __ARGS((typval_T *argvars, typval_T *rettv));
692 static void f_substitute __ARGS((typval_T *argvars, typval_T *rettv));
693 static void f_synID __ARGS((typval_T *argvars, typval_T *rettv));
694 static void f_synIDattr __ARGS((typval_T *argvars, typval_T *rettv));
695 static void f_synIDtrans __ARGS((typval_T *argvars, typval_T *rettv));
696 static void f_synstack __ARGS((typval_T *argvars, typval_T *rettv));
697 static void f_system __ARGS((typval_T *argvars, typval_T *rettv));
698 static void f_tabpagebuflist __ARGS((typval_T *argvars, typval_T *rettv));
699 static void f_tabpagenr __ARGS((typval_T *argvars, typval_T *rettv));
700 static void f_tabpagewinnr __ARGS((typval_T *argvars, typval_T *rettv));
701 static void f_taglist __ARGS((typval_T *argvars, typval_T *rettv));
702 static void f_tagfiles __ARGS((typval_T *argvars, typval_T *rettv));
703 static void f_tempname __ARGS((typval_T *argvars, typval_T *rettv));
704 static void f_test __ARGS((typval_T *argvars, typval_T *rettv));
705 static void f_tolower __ARGS((typval_T *argvars, typval_T *rettv));
706 static void f_toupper __ARGS((typval_T *argvars, typval_T *rettv));
707 static void f_tr __ARGS((typval_T *argvars, typval_T *rettv));
708 #ifdef FEAT_FLOAT
709 static void f_trunc __ARGS((typval_T *argvars, typval_T *rettv));
710 #endif
711 static void f_type __ARGS((typval_T *argvars, typval_T *rettv));
712 static void f_values __ARGS((typval_T *argvars, typval_T *rettv));
713 static void f_virtcol __ARGS((typval_T *argvars, typval_T *rettv));
714 static void f_visualmode __ARGS((typval_T *argvars, typval_T *rettv));
715 static void f_winbufnr __ARGS((typval_T *argvars, typval_T *rettv));
716 static void f_wincol __ARGS((typval_T *argvars, typval_T *rettv));
717 static void f_winheight __ARGS((typval_T *argvars, typval_T *rettv));
718 static void f_winline __ARGS((typval_T *argvars, typval_T *rettv));
719 static void f_winnr __ARGS((typval_T *argvars, typval_T *rettv));
720 static void f_winrestcmd __ARGS((typval_T *argvars, typval_T *rettv));
721 static void f_winrestview __ARGS((typval_T *argvars, typval_T *rettv));
722 static void f_winsaveview __ARGS((typval_T *argvars, typval_T *rettv));
723 static void f_winwidth __ARGS((typval_T *argvars, typval_T *rettv));
724 static void f_writefile __ARGS((typval_T *argvars, typval_T *rettv));
726 static int list2fpos __ARGS((typval_T *arg, pos_T *posp, int *fnump));
727 static pos_T *var2fpos __ARGS((typval_T *varp, int dollar_lnum, int *fnum));
728 static int get_env_len __ARGS((char_u **arg));
729 static int get_id_len __ARGS((char_u **arg));
730 static int get_name_len __ARGS((char_u **arg, char_u **alias, int evaluate, int verbose));
731 static char_u *find_name_end __ARGS((char_u *arg, char_u **expr_start, char_u **expr_end, int flags));
732 #define FNE_INCL_BR 1 /* find_name_end(): include [] in name */
733 #define FNE_CHECK_START 2 /* find_name_end(): check name starts with
734 valid character */
735 static char_u * make_expanded_name __ARGS((char_u *in_start, char_u *expr_start, char_u *expr_end, char_u *in_end));
736 static int eval_isnamec __ARGS((int c));
737 static int eval_isnamec1 __ARGS((int c));
738 static int get_var_tv __ARGS((char_u *name, int len, typval_T *rettv, int verbose));
739 static int handle_subscript __ARGS((char_u **arg, typval_T *rettv, int evaluate, int verbose));
740 static typval_T *alloc_tv __ARGS((void));
741 static typval_T *alloc_string_tv __ARGS((char_u *string));
742 static void init_tv __ARGS((typval_T *varp));
743 static long get_tv_number __ARGS((typval_T *varp));
744 static linenr_T get_tv_lnum __ARGS((typval_T *argvars));
745 static linenr_T get_tv_lnum_buf __ARGS((typval_T *argvars, buf_T *buf));
746 static char_u *get_tv_string __ARGS((typval_T *varp));
747 static char_u *get_tv_string_buf __ARGS((typval_T *varp, char_u *buf));
748 static char_u *get_tv_string_buf_chk __ARGS((typval_T *varp, char_u *buf));
749 static dictitem_T *find_var __ARGS((char_u *name, hashtab_T **htp));
750 static dictitem_T *find_var_in_ht __ARGS((hashtab_T *ht, char_u *varname, int writing));
751 static hashtab_T *find_var_ht __ARGS((char_u *name, char_u **varname));
752 static void vars_clear_ext __ARGS((hashtab_T *ht, int free_val));
753 static void delete_var __ARGS((hashtab_T *ht, hashitem_T *hi));
754 static void list_one_var __ARGS((dictitem_T *v, char_u *prefix, int *first));
755 static void list_one_var_a __ARGS((char_u *prefix, char_u *name, int type, char_u *string, int *first));
756 static void set_var __ARGS((char_u *name, typval_T *varp, int copy));
757 static int var_check_ro __ARGS((int flags, char_u *name));
758 static int var_check_fixed __ARGS((int flags, char_u *name));
759 static int tv_check_lock __ARGS((int lock, char_u *name));
760 static void copy_tv __ARGS((typval_T *from, typval_T *to));
761 static int item_copy __ARGS((typval_T *from, typval_T *to, int deep, int copyID));
762 static char_u *find_option_end __ARGS((char_u **arg, int *opt_flags));
763 static char_u *trans_function_name __ARGS((char_u **pp, int skip, int flags, funcdict_T *fd));
764 static int eval_fname_script __ARGS((char_u *p));
765 static int eval_fname_sid __ARGS((char_u *p));
766 static void list_func_head __ARGS((ufunc_T *fp, int indent));
767 static ufunc_T *find_func __ARGS((char_u *name));
768 static int function_exists __ARGS((char_u *name));
769 static int builtin_function __ARGS((char_u *name));
770 #ifdef FEAT_PROFILE
771 static void func_do_profile __ARGS((ufunc_T *fp));
772 static void prof_sort_list __ARGS((FILE *fd, ufunc_T **sorttab, int st_len, char *title, int prefer_self));
773 static void prof_func_line __ARGS((FILE *fd, int count, proftime_T *total, proftime_T *self, int prefer_self));
774 static int
775 # ifdef __BORLANDC__
776 _RTLENTRYF
777 # endif
778 prof_total_cmp __ARGS((const void *s1, const void *s2));
779 static int
780 # ifdef __BORLANDC__
781 _RTLENTRYF
782 # endif
783 prof_self_cmp __ARGS((const void *s1, const void *s2));
784 #endif
785 static int script_autoload __ARGS((char_u *name, int reload));
786 static char_u *autoload_name __ARGS((char_u *name));
787 static void cat_func_name __ARGS((char_u *buf, ufunc_T *fp));
788 static void func_free __ARGS((ufunc_T *fp));
789 static void func_unref __ARGS((char_u *name));
790 static void func_ref __ARGS((char_u *name));
791 static void call_user_func __ARGS((ufunc_T *fp, int argcount, typval_T *argvars, typval_T *rettv, linenr_T firstline, linenr_T lastline, dict_T *selfdict));
792 static void add_nr_var __ARGS((dict_T *dp, dictitem_T *v, char *name, varnumber_T nr));
793 static win_T *find_win_by_nr __ARGS((typval_T *vp, tabpage_T *tp));
794 static void getwinvar __ARGS((typval_T *argvars, typval_T *rettv, int off));
795 static int searchpair_cmn __ARGS((typval_T *argvars, pos_T *match_pos));
796 static int search_cmn __ARGS((typval_T *argvars, pos_T *match_pos, int *flagsp));
797 static void setwinvar __ARGS((typval_T *argvars, typval_T *rettv, int off));
799 /* Character used as separated in autoload function/variable names. */
800 #define AUTOLOAD_CHAR '#'
803 * Initialize the global and v: variables.
805 void
806 eval_init()
808 int i;
809 struct vimvar *p;
811 init_var_dict(&globvardict, &globvars_var);
812 init_var_dict(&vimvardict, &vimvars_var);
813 hash_init(&compat_hashtab);
814 hash_init(&func_hashtab);
816 for (i = 0; i < VV_LEN; ++i)
818 p = &vimvars[i];
819 STRCPY(p->vv_di.di_key, p->vv_name);
820 if (p->vv_flags & VV_RO)
821 p->vv_di.di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
822 else if (p->vv_flags & VV_RO_SBX)
823 p->vv_di.di_flags = DI_FLAGS_RO_SBX | DI_FLAGS_FIX;
824 else
825 p->vv_di.di_flags = DI_FLAGS_FIX;
827 /* add to v: scope dict, unless the value is not always available */
828 if (p->vv_type != VAR_UNKNOWN)
829 hash_add(&vimvarht, p->vv_di.di_key);
830 if (p->vv_flags & VV_COMPAT)
831 /* add to compat scope dict */
832 hash_add(&compat_hashtab, p->vv_di.di_key);
834 set_vim_var_nr(VV_SEARCHFORWARD, 1L);
837 #if defined(EXITFREE) || defined(PROTO)
838 void
839 eval_clear()
841 int i;
842 struct vimvar *p;
844 for (i = 0; i < VV_LEN; ++i)
846 p = &vimvars[i];
847 if (p->vv_di.di_tv.v_type == VAR_STRING)
849 vim_free(p->vv_str);
850 p->vv_str = NULL;
852 else if (p->vv_di.di_tv.v_type == VAR_LIST)
854 list_unref(p->vv_list);
855 p->vv_list = NULL;
858 hash_clear(&vimvarht);
859 hash_clear(&compat_hashtab);
861 /* script-local variables */
862 for (i = 1; i <= ga_scripts.ga_len; ++i)
863 vars_clear(&SCRIPT_VARS(i));
864 ga_clear(&ga_scripts);
865 free_scriptnames();
867 /* global variables */
868 vars_clear(&globvarht);
870 /* autoloaded script names */
871 ga_clear_strings(&ga_loaded);
873 /* unreferenced lists and dicts */
874 (void)garbage_collect();
876 /* functions */
877 free_all_functions();
878 hash_clear(&func_hashtab);
880 #endif
883 * Return the name of the executed function.
885 char_u *
886 func_name(cookie)
887 void *cookie;
889 return ((funccall_T *)cookie)->func->uf_name;
893 * Return the address holding the next breakpoint line for a funccall cookie.
895 linenr_T *
896 func_breakpoint(cookie)
897 void *cookie;
899 return &((funccall_T *)cookie)->breakpoint;
903 * Return the address holding the debug tick for a funccall cookie.
905 int *
906 func_dbg_tick(cookie)
907 void *cookie;
909 return &((funccall_T *)cookie)->dbg_tick;
913 * Return the nesting level for a funccall cookie.
916 func_level(cookie)
917 void *cookie;
919 return ((funccall_T *)cookie)->level;
922 /* pointer to funccal for currently active function */
923 funccall_T *current_funccal = NULL;
926 * Return TRUE when a function was ended by a ":return" command.
929 current_func_returned()
931 return current_funccal->returned;
936 * Set an internal variable to a string value. Creates the variable if it does
937 * not already exist.
939 void
940 set_internal_string_var(name, value)
941 char_u *name;
942 char_u *value;
944 char_u *val;
945 typval_T *tvp;
947 val = vim_strsave(value);
948 if (val != NULL)
950 tvp = alloc_string_tv(val);
951 if (tvp != NULL)
953 set_var(name, tvp, FALSE);
954 free_tv(tvp);
959 static lval_T *redir_lval = NULL;
960 static garray_T redir_ga; /* only valid when redir_lval is not NULL */
961 static char_u *redir_endp = NULL;
962 static char_u *redir_varname = NULL;
965 * Start recording command output to a variable
966 * Returns OK if successfully completed the setup. FAIL otherwise.
969 var_redir_start(name, append)
970 char_u *name;
971 int append; /* append to an existing variable */
973 int save_emsg;
974 int err;
975 typval_T tv;
977 /* Make sure a valid variable name is specified */
978 if (!eval_isnamec1(*name))
980 EMSG(_(e_invarg));
981 return FAIL;
984 redir_varname = vim_strsave(name);
985 if (redir_varname == NULL)
986 return FAIL;
988 redir_lval = (lval_T *)alloc_clear((unsigned)sizeof(lval_T));
989 if (redir_lval == NULL)
991 var_redir_stop();
992 return FAIL;
995 /* The output is stored in growarray "redir_ga" until redirection ends. */
996 ga_init2(&redir_ga, (int)sizeof(char), 500);
998 /* Parse the variable name (can be a dict or list entry). */
999 redir_endp = get_lval(redir_varname, NULL, redir_lval, FALSE, FALSE, FALSE,
1000 FNE_CHECK_START);
1001 if (redir_endp == NULL || redir_lval->ll_name == NULL || *redir_endp != NUL)
1003 if (redir_endp != NULL && *redir_endp != NUL)
1004 /* Trailing characters are present after the variable name */
1005 EMSG(_(e_trailing));
1006 else
1007 EMSG(_(e_invarg));
1008 var_redir_stop();
1009 return FAIL;
1012 /* check if we can write to the variable: set it to or append an empty
1013 * string */
1014 save_emsg = did_emsg;
1015 did_emsg = FALSE;
1016 tv.v_type = VAR_STRING;
1017 tv.vval.v_string = (char_u *)"";
1018 if (append)
1019 set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)".");
1020 else
1021 set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)"=");
1022 err = did_emsg;
1023 did_emsg |= save_emsg;
1024 if (err)
1026 var_redir_stop();
1027 return FAIL;
1029 if (redir_lval->ll_newkey != NULL)
1031 /* Dictionary item was created, don't do it again. */
1032 vim_free(redir_lval->ll_newkey);
1033 redir_lval->ll_newkey = NULL;
1036 return OK;
1040 * Append "value[value_len]" to the variable set by var_redir_start().
1041 * The actual appending is postponed until redirection ends, because the value
1042 * appended may in fact be the string we write to, changing it may cause freed
1043 * memory to be used:
1044 * :redir => foo
1045 * :let foo
1046 * :redir END
1048 void
1049 var_redir_str(value, value_len)
1050 char_u *value;
1051 int value_len;
1053 int len;
1055 if (redir_lval == NULL)
1056 return;
1058 if (value_len == -1)
1059 len = (int)STRLEN(value); /* Append the entire string */
1060 else
1061 len = value_len; /* Append only "value_len" characters */
1063 if (ga_grow(&redir_ga, len) == OK)
1065 mch_memmove((char *)redir_ga.ga_data + redir_ga.ga_len, value, len);
1066 redir_ga.ga_len += len;
1068 else
1069 var_redir_stop();
1073 * Stop redirecting command output to a variable.
1075 void
1076 var_redir_stop()
1078 typval_T tv;
1080 if (redir_lval != NULL)
1082 /* Append the trailing NUL. */
1083 ga_append(&redir_ga, NUL);
1085 /* Assign the text to the variable. */
1086 tv.v_type = VAR_STRING;
1087 tv.vval.v_string = redir_ga.ga_data;
1088 set_var_lval(redir_lval, redir_endp, &tv, FALSE, (char_u *)".");
1089 vim_free(tv.vval.v_string);
1091 clear_lval(redir_lval);
1092 vim_free(redir_lval);
1093 redir_lval = NULL;
1095 vim_free(redir_varname);
1096 redir_varname = NULL;
1099 # if defined(FEAT_MBYTE) || defined(PROTO)
1101 eval_charconvert(enc_from, enc_to, fname_from, fname_to)
1102 char_u *enc_from;
1103 char_u *enc_to;
1104 char_u *fname_from;
1105 char_u *fname_to;
1107 int err = FALSE;
1109 set_vim_var_string(VV_CC_FROM, enc_from, -1);
1110 set_vim_var_string(VV_CC_TO, enc_to, -1);
1111 set_vim_var_string(VV_FNAME_IN, fname_from, -1);
1112 set_vim_var_string(VV_FNAME_OUT, fname_to, -1);
1113 if (eval_to_bool(p_ccv, &err, NULL, FALSE))
1114 err = TRUE;
1115 set_vim_var_string(VV_CC_FROM, NULL, -1);
1116 set_vim_var_string(VV_CC_TO, NULL, -1);
1117 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1118 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1120 if (err)
1121 return FAIL;
1122 return OK;
1124 # endif
1126 # if defined(FEAT_POSTSCRIPT) || defined(PROTO)
1128 eval_printexpr(fname, args)
1129 char_u *fname;
1130 char_u *args;
1132 int err = FALSE;
1134 set_vim_var_string(VV_FNAME_IN, fname, -1);
1135 set_vim_var_string(VV_CMDARG, args, -1);
1136 if (eval_to_bool(p_pexpr, &err, NULL, FALSE))
1137 err = TRUE;
1138 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1139 set_vim_var_string(VV_CMDARG, NULL, -1);
1141 if (err)
1143 mch_remove(fname);
1144 return FAIL;
1146 return OK;
1148 # endif
1150 # if defined(FEAT_DIFF) || defined(PROTO)
1151 void
1152 eval_diff(origfile, newfile, outfile)
1153 char_u *origfile;
1154 char_u *newfile;
1155 char_u *outfile;
1157 int err = FALSE;
1159 set_vim_var_string(VV_FNAME_IN, origfile, -1);
1160 set_vim_var_string(VV_FNAME_NEW, newfile, -1);
1161 set_vim_var_string(VV_FNAME_OUT, outfile, -1);
1162 (void)eval_to_bool(p_dex, &err, NULL, FALSE);
1163 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1164 set_vim_var_string(VV_FNAME_NEW, NULL, -1);
1165 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1168 void
1169 eval_patch(origfile, difffile, outfile)
1170 char_u *origfile;
1171 char_u *difffile;
1172 char_u *outfile;
1174 int err;
1176 set_vim_var_string(VV_FNAME_IN, origfile, -1);
1177 set_vim_var_string(VV_FNAME_DIFF, difffile, -1);
1178 set_vim_var_string(VV_FNAME_OUT, outfile, -1);
1179 (void)eval_to_bool(p_pex, &err, NULL, FALSE);
1180 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1181 set_vim_var_string(VV_FNAME_DIFF, NULL, -1);
1182 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1184 # endif
1187 * Top level evaluation function, returning a boolean.
1188 * Sets "error" to TRUE if there was an error.
1189 * Return TRUE or FALSE.
1192 eval_to_bool(arg, error, nextcmd, skip)
1193 char_u *arg;
1194 int *error;
1195 char_u **nextcmd;
1196 int skip; /* only parse, don't execute */
1198 typval_T tv;
1199 int retval = FALSE;
1201 if (skip)
1202 ++emsg_skip;
1203 if (eval0(arg, &tv, nextcmd, !skip) == FAIL)
1204 *error = TRUE;
1205 else
1207 *error = FALSE;
1208 if (!skip)
1210 retval = (get_tv_number_chk(&tv, error) != 0);
1211 clear_tv(&tv);
1214 if (skip)
1215 --emsg_skip;
1217 return retval;
1221 * Top level evaluation function, returning a string. If "skip" is TRUE,
1222 * only parsing to "nextcmd" is done, without reporting errors. Return
1223 * pointer to allocated memory, or NULL for failure or when "skip" is TRUE.
1225 char_u *
1226 eval_to_string_skip(arg, nextcmd, skip)
1227 char_u *arg;
1228 char_u **nextcmd;
1229 int skip; /* only parse, don't execute */
1231 typval_T tv;
1232 char_u *retval;
1234 if (skip)
1235 ++emsg_skip;
1236 if (eval0(arg, &tv, nextcmd, !skip) == FAIL || skip)
1237 retval = NULL;
1238 else
1240 retval = vim_strsave(get_tv_string(&tv));
1241 clear_tv(&tv);
1243 if (skip)
1244 --emsg_skip;
1246 return retval;
1250 * Skip over an expression at "*pp".
1251 * Return FAIL for an error, OK otherwise.
1254 skip_expr(pp)
1255 char_u **pp;
1257 typval_T rettv;
1259 *pp = skipwhite(*pp);
1260 return eval1(pp, &rettv, FALSE);
1264 * Top level evaluation function, returning a string.
1265 * When "convert" is TRUE convert a List into a sequence of lines and convert
1266 * a Float to a String.
1267 * Return pointer to allocated memory, or NULL for failure.
1269 char_u *
1270 eval_to_string(arg, nextcmd, convert)
1271 char_u *arg;
1272 char_u **nextcmd;
1273 int convert;
1275 typval_T tv;
1276 char_u *retval;
1277 garray_T ga;
1278 char_u numbuf[NUMBUFLEN];
1280 if (eval0(arg, &tv, nextcmd, TRUE) == FAIL)
1281 retval = NULL;
1282 else
1284 if (convert && tv.v_type == VAR_LIST)
1286 ga_init2(&ga, (int)sizeof(char), 80);
1287 if (tv.vval.v_list != NULL)
1288 list_join(&ga, tv.vval.v_list, (char_u *)"\n", TRUE, 0);
1289 ga_append(&ga, NUL);
1290 retval = (char_u *)ga.ga_data;
1292 #ifdef FEAT_FLOAT
1293 else if (convert && tv.v_type == VAR_FLOAT)
1295 vim_snprintf((char *)numbuf, NUMBUFLEN, "%g", tv.vval.v_float);
1296 retval = vim_strsave(numbuf);
1298 #endif
1299 else
1300 retval = vim_strsave(get_tv_string(&tv));
1301 clear_tv(&tv);
1304 return retval;
1308 * Call eval_to_string() without using current local variables and using
1309 * textlock. When "use_sandbox" is TRUE use the sandbox.
1311 char_u *
1312 eval_to_string_safe(arg, nextcmd, use_sandbox)
1313 char_u *arg;
1314 char_u **nextcmd;
1315 int use_sandbox;
1317 char_u *retval;
1318 void *save_funccalp;
1320 save_funccalp = save_funccal();
1321 if (use_sandbox)
1322 ++sandbox;
1323 ++textlock;
1324 retval = eval_to_string(arg, nextcmd, FALSE);
1325 if (use_sandbox)
1326 --sandbox;
1327 --textlock;
1328 restore_funccal(save_funccalp);
1329 return retval;
1333 * Top level evaluation function, returning a number.
1334 * Evaluates "expr" silently.
1335 * Returns -1 for an error.
1338 eval_to_number(expr)
1339 char_u *expr;
1341 typval_T rettv;
1342 int retval;
1343 char_u *p = skipwhite(expr);
1345 ++emsg_off;
1347 if (eval1(&p, &rettv, TRUE) == FAIL)
1348 retval = -1;
1349 else
1351 retval = get_tv_number_chk(&rettv, NULL);
1352 clear_tv(&rettv);
1354 --emsg_off;
1356 return retval;
1360 * Prepare v: variable "idx" to be used.
1361 * Save the current typeval in "save_tv".
1362 * When not used yet add the variable to the v: hashtable.
1364 static void
1365 prepare_vimvar(idx, save_tv)
1366 int idx;
1367 typval_T *save_tv;
1369 *save_tv = vimvars[idx].vv_tv;
1370 if (vimvars[idx].vv_type == VAR_UNKNOWN)
1371 hash_add(&vimvarht, vimvars[idx].vv_di.di_key);
1375 * Restore v: variable "idx" to typeval "save_tv".
1376 * When no longer defined, remove the variable from the v: hashtable.
1378 static void
1379 restore_vimvar(idx, save_tv)
1380 int idx;
1381 typval_T *save_tv;
1383 hashitem_T *hi;
1385 vimvars[idx].vv_tv = *save_tv;
1386 if (vimvars[idx].vv_type == VAR_UNKNOWN)
1388 hi = hash_find(&vimvarht, vimvars[idx].vv_di.di_key);
1389 if (HASHITEM_EMPTY(hi))
1390 EMSG2(_(e_intern2), "restore_vimvar()");
1391 else
1392 hash_remove(&vimvarht, hi);
1396 #if defined(FEAT_SPELL) || defined(PROTO)
1398 * Evaluate an expression to a list with suggestions.
1399 * For the "expr:" part of 'spellsuggest'.
1400 * Returns NULL when there is an error.
1402 list_T *
1403 eval_spell_expr(badword, expr)
1404 char_u *badword;
1405 char_u *expr;
1407 typval_T save_val;
1408 typval_T rettv;
1409 list_T *list = NULL;
1410 char_u *p = skipwhite(expr);
1412 /* Set "v:val" to the bad word. */
1413 prepare_vimvar(VV_VAL, &save_val);
1414 vimvars[VV_VAL].vv_type = VAR_STRING;
1415 vimvars[VV_VAL].vv_str = badword;
1416 if (p_verbose == 0)
1417 ++emsg_off;
1419 if (eval1(&p, &rettv, TRUE) == OK)
1421 if (rettv.v_type != VAR_LIST)
1422 clear_tv(&rettv);
1423 else
1424 list = rettv.vval.v_list;
1427 if (p_verbose == 0)
1428 --emsg_off;
1429 restore_vimvar(VV_VAL, &save_val);
1431 return list;
1435 * "list" is supposed to contain two items: a word and a number. Return the
1436 * word in "pp" and the number as the return value.
1437 * Return -1 if anything isn't right.
1438 * Used to get the good word and score from the eval_spell_expr() result.
1441 get_spellword(list, pp)
1442 list_T *list;
1443 char_u **pp;
1445 listitem_T *li;
1447 li = list->lv_first;
1448 if (li == NULL)
1449 return -1;
1450 *pp = get_tv_string(&li->li_tv);
1452 li = li->li_next;
1453 if (li == NULL)
1454 return -1;
1455 return get_tv_number(&li->li_tv);
1457 #endif
1460 * Top level evaluation function.
1461 * Returns an allocated typval_T with the result.
1462 * Returns NULL when there is an error.
1464 typval_T *
1465 eval_expr(arg, nextcmd)
1466 char_u *arg;
1467 char_u **nextcmd;
1469 typval_T *tv;
1471 tv = (typval_T *)alloc(sizeof(typval_T));
1472 if (tv != NULL && eval0(arg, tv, nextcmd, TRUE) == FAIL)
1474 vim_free(tv);
1475 tv = NULL;
1478 return tv;
1482 #if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) \
1483 || defined(FEAT_COMPL_FUNC) || defined(PROTO)
1485 * Call some vimL function and return the result in "*rettv".
1486 * Uses argv[argc] for the function arguments. Only Number and String
1487 * arguments are currently supported.
1488 * Returns OK or FAIL.
1490 static int
1491 call_vim_function(func, argc, argv, safe, rettv)
1492 char_u *func;
1493 int argc;
1494 char_u **argv;
1495 int safe; /* use the sandbox */
1496 typval_T *rettv;
1498 typval_T *argvars;
1499 long n;
1500 int len;
1501 int i;
1502 int doesrange;
1503 void *save_funccalp = NULL;
1504 int ret;
1506 argvars = (typval_T *)alloc((unsigned)((argc + 1) * sizeof(typval_T)));
1507 if (argvars == NULL)
1508 return FAIL;
1510 for (i = 0; i < argc; i++)
1512 /* Pass a NULL or empty argument as an empty string */
1513 if (argv[i] == NULL || *argv[i] == NUL)
1515 argvars[i].v_type = VAR_STRING;
1516 argvars[i].vval.v_string = (char_u *)"";
1517 continue;
1520 /* Recognize a number argument, the others must be strings. */
1521 vim_str2nr(argv[i], NULL, &len, TRUE, TRUE, &n, NULL);
1522 if (len != 0 && len == (int)STRLEN(argv[i]))
1524 argvars[i].v_type = VAR_NUMBER;
1525 argvars[i].vval.v_number = n;
1527 else
1529 argvars[i].v_type = VAR_STRING;
1530 argvars[i].vval.v_string = argv[i];
1534 if (safe)
1536 save_funccalp = save_funccal();
1537 ++sandbox;
1540 rettv->v_type = VAR_UNKNOWN; /* clear_tv() uses this */
1541 ret = call_func(func, (int)STRLEN(func), rettv, argc, argvars,
1542 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
1543 &doesrange, TRUE, NULL);
1544 if (safe)
1546 --sandbox;
1547 restore_funccal(save_funccalp);
1549 vim_free(argvars);
1551 if (ret == FAIL)
1552 clear_tv(rettv);
1554 return ret;
1557 # if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) || defined(PROTO)
1559 * Call vimL function "func" and return the result as a string.
1560 * Returns NULL when calling the function fails.
1561 * Uses argv[argc] for the function arguments.
1563 void *
1564 call_func_retstr(func, argc, argv, safe)
1565 char_u *func;
1566 int argc;
1567 char_u **argv;
1568 int safe; /* use the sandbox */
1570 typval_T rettv;
1571 char_u *retval;
1573 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1574 return NULL;
1576 retval = vim_strsave(get_tv_string(&rettv));
1577 clear_tv(&rettv);
1578 return retval;
1580 # endif
1582 # if defined(FEAT_COMPL_FUNC) || defined(PROTO)
1584 * Call vimL function "func" and return the result as a number.
1585 * Returns -1 when calling the function fails.
1586 * Uses argv[argc] for the function arguments.
1588 long
1589 call_func_retnr(func, argc, argv, safe)
1590 char_u *func;
1591 int argc;
1592 char_u **argv;
1593 int safe; /* use the sandbox */
1595 typval_T rettv;
1596 long retval;
1598 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1599 return -1;
1601 retval = get_tv_number_chk(&rettv, NULL);
1602 clear_tv(&rettv);
1603 return retval;
1605 # endif
1608 * Call vimL function "func" and return the result as a List.
1609 * Uses argv[argc] for the function arguments.
1610 * Returns NULL when there is something wrong.
1612 void *
1613 call_func_retlist(func, argc, argv, safe)
1614 char_u *func;
1615 int argc;
1616 char_u **argv;
1617 int safe; /* use the sandbox */
1619 typval_T rettv;
1621 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1622 return NULL;
1624 if (rettv.v_type != VAR_LIST)
1626 clear_tv(&rettv);
1627 return NULL;
1630 return rettv.vval.v_list;
1632 #endif
1636 * Save the current function call pointer, and set it to NULL.
1637 * Used when executing autocommands and for ":source".
1639 void *
1640 save_funccal()
1642 funccall_T *fc = current_funccal;
1644 current_funccal = NULL;
1645 return (void *)fc;
1648 void
1649 restore_funccal(vfc)
1650 void *vfc;
1652 funccall_T *fc = (funccall_T *)vfc;
1654 current_funccal = fc;
1657 #if defined(FEAT_PROFILE) || defined(PROTO)
1659 * Prepare profiling for entering a child or something else that is not
1660 * counted for the script/function itself.
1661 * Should always be called in pair with prof_child_exit().
1663 void
1664 prof_child_enter(tm)
1665 proftime_T *tm; /* place to store waittime */
1667 funccall_T *fc = current_funccal;
1669 if (fc != NULL && fc->func->uf_profiling)
1670 profile_start(&fc->prof_child);
1671 script_prof_save(tm);
1675 * Take care of time spent in a child.
1676 * Should always be called after prof_child_enter().
1678 void
1679 prof_child_exit(tm)
1680 proftime_T *tm; /* where waittime was stored */
1682 funccall_T *fc = current_funccal;
1684 if (fc != NULL && fc->func->uf_profiling)
1686 profile_end(&fc->prof_child);
1687 profile_sub_wait(tm, &fc->prof_child); /* don't count waiting time */
1688 profile_add(&fc->func->uf_tm_children, &fc->prof_child);
1689 profile_add(&fc->func->uf_tml_children, &fc->prof_child);
1691 script_prof_restore(tm);
1693 #endif
1696 #ifdef FEAT_FOLDING
1698 * Evaluate 'foldexpr'. Returns the foldlevel, and any character preceding
1699 * it in "*cp". Doesn't give error messages.
1702 eval_foldexpr(arg, cp)
1703 char_u *arg;
1704 int *cp;
1706 typval_T tv;
1707 int retval;
1708 char_u *s;
1709 int use_sandbox = was_set_insecurely((char_u *)"foldexpr",
1710 OPT_LOCAL);
1712 ++emsg_off;
1713 if (use_sandbox)
1714 ++sandbox;
1715 ++textlock;
1716 *cp = NUL;
1717 if (eval0(arg, &tv, NULL, TRUE) == FAIL)
1718 retval = 0;
1719 else
1721 /* If the result is a number, just return the number. */
1722 if (tv.v_type == VAR_NUMBER)
1723 retval = tv.vval.v_number;
1724 else if (tv.v_type != VAR_STRING || tv.vval.v_string == NULL)
1725 retval = 0;
1726 else
1728 /* If the result is a string, check if there is a non-digit before
1729 * the number. */
1730 s = tv.vval.v_string;
1731 if (!VIM_ISDIGIT(*s) && *s != '-')
1732 *cp = *s++;
1733 retval = atol((char *)s);
1735 clear_tv(&tv);
1737 --emsg_off;
1738 if (use_sandbox)
1739 --sandbox;
1740 --textlock;
1742 return retval;
1744 #endif
1747 * ":let" list all variable values
1748 * ":let var1 var2" list variable values
1749 * ":let var = expr" assignment command.
1750 * ":let var += expr" assignment command.
1751 * ":let var -= expr" assignment command.
1752 * ":let var .= expr" assignment command.
1753 * ":let [var1, var2] = expr" unpack list.
1755 void
1756 ex_let(eap)
1757 exarg_T *eap;
1759 char_u *arg = eap->arg;
1760 char_u *expr = NULL;
1761 typval_T rettv;
1762 int i;
1763 int var_count = 0;
1764 int semicolon = 0;
1765 char_u op[2];
1766 char_u *argend;
1767 int first = TRUE;
1769 argend = skip_var_list(arg, &var_count, &semicolon);
1770 if (argend == NULL)
1771 return;
1772 if (argend > arg && argend[-1] == '.') /* for var.='str' */
1773 --argend;
1774 expr = vim_strchr(argend, '=');
1775 if (expr == NULL)
1778 * ":let" without "=": list variables
1780 if (*arg == '[')
1781 EMSG(_(e_invarg));
1782 else if (!ends_excmd(*arg))
1783 /* ":let var1 var2" */
1784 arg = list_arg_vars(eap, arg, &first);
1785 else if (!eap->skip)
1787 /* ":let" */
1788 list_glob_vars(&first);
1789 list_buf_vars(&first);
1790 list_win_vars(&first);
1791 #ifdef FEAT_WINDOWS
1792 list_tab_vars(&first);
1793 #endif
1794 list_script_vars(&first);
1795 list_func_vars(&first);
1796 list_vim_vars(&first);
1798 eap->nextcmd = check_nextcmd(arg);
1800 else
1802 op[0] = '=';
1803 op[1] = NUL;
1804 if (expr > argend)
1806 if (vim_strchr((char_u *)"+-.", expr[-1]) != NULL)
1807 op[0] = expr[-1]; /* +=, -= or .= */
1809 expr = skipwhite(expr + 1);
1811 if (eap->skip)
1812 ++emsg_skip;
1813 i = eval0(expr, &rettv, &eap->nextcmd, !eap->skip);
1814 if (eap->skip)
1816 if (i != FAIL)
1817 clear_tv(&rettv);
1818 --emsg_skip;
1820 else if (i != FAIL)
1822 (void)ex_let_vars(eap->arg, &rettv, FALSE, semicolon, var_count,
1823 op);
1824 clear_tv(&rettv);
1830 * Assign the typevalue "tv" to the variable or variables at "arg_start".
1831 * Handles both "var" with any type and "[var, var; var]" with a list type.
1832 * When "nextchars" is not NULL it points to a string with characters that
1833 * must appear after the variable(s). Use "+", "-" or "." for add, subtract
1834 * or concatenate.
1835 * Returns OK or FAIL;
1837 static int
1838 ex_let_vars(arg_start, tv, copy, semicolon, var_count, nextchars)
1839 char_u *arg_start;
1840 typval_T *tv;
1841 int copy; /* copy values from "tv", don't move */
1842 int semicolon; /* from skip_var_list() */
1843 int var_count; /* from skip_var_list() */
1844 char_u *nextchars;
1846 char_u *arg = arg_start;
1847 list_T *l;
1848 int i;
1849 listitem_T *item;
1850 typval_T ltv;
1852 if (*arg != '[')
1855 * ":let var = expr" or ":for var in list"
1857 if (ex_let_one(arg, tv, copy, nextchars, nextchars) == NULL)
1858 return FAIL;
1859 return OK;
1863 * ":let [v1, v2] = list" or ":for [v1, v2] in listlist"
1865 if (tv->v_type != VAR_LIST || (l = tv->vval.v_list) == NULL)
1867 EMSG(_(e_listreq));
1868 return FAIL;
1871 i = list_len(l);
1872 if (semicolon == 0 && var_count < i)
1874 EMSG(_("E687: Less targets than List items"));
1875 return FAIL;
1877 if (var_count - semicolon > i)
1879 EMSG(_("E688: More targets than List items"));
1880 return FAIL;
1883 item = l->lv_first;
1884 while (*arg != ']')
1886 arg = skipwhite(arg + 1);
1887 arg = ex_let_one(arg, &item->li_tv, TRUE, (char_u *)",;]", nextchars);
1888 item = item->li_next;
1889 if (arg == NULL)
1890 return FAIL;
1892 arg = skipwhite(arg);
1893 if (*arg == ';')
1895 /* Put the rest of the list (may be empty) in the var after ';'.
1896 * Create a new list for this. */
1897 l = list_alloc();
1898 if (l == NULL)
1899 return FAIL;
1900 while (item != NULL)
1902 list_append_tv(l, &item->li_tv);
1903 item = item->li_next;
1906 ltv.v_type = VAR_LIST;
1907 ltv.v_lock = 0;
1908 ltv.vval.v_list = l;
1909 l->lv_refcount = 1;
1911 arg = ex_let_one(skipwhite(arg + 1), &ltv, FALSE,
1912 (char_u *)"]", nextchars);
1913 clear_tv(&ltv);
1914 if (arg == NULL)
1915 return FAIL;
1916 break;
1918 else if (*arg != ',' && *arg != ']')
1920 EMSG2(_(e_intern2), "ex_let_vars()");
1921 return FAIL;
1925 return OK;
1929 * Skip over assignable variable "var" or list of variables "[var, var]".
1930 * Used for ":let varvar = expr" and ":for varvar in expr".
1931 * For "[var, var]" increment "*var_count" for each variable.
1932 * for "[var, var; var]" set "semicolon".
1933 * Return NULL for an error.
1935 static char_u *
1936 skip_var_list(arg, var_count, semicolon)
1937 char_u *arg;
1938 int *var_count;
1939 int *semicolon;
1941 char_u *p, *s;
1943 if (*arg == '[')
1945 /* "[var, var]": find the matching ']'. */
1946 p = arg;
1947 for (;;)
1949 p = skipwhite(p + 1); /* skip whites after '[', ';' or ',' */
1950 s = skip_var_one(p);
1951 if (s == p)
1953 EMSG2(_(e_invarg2), p);
1954 return NULL;
1956 ++*var_count;
1958 p = skipwhite(s);
1959 if (*p == ']')
1960 break;
1961 else if (*p == ';')
1963 if (*semicolon == 1)
1965 EMSG(_("Double ; in list of variables"));
1966 return NULL;
1968 *semicolon = 1;
1970 else if (*p != ',')
1972 EMSG2(_(e_invarg2), p);
1973 return NULL;
1976 return p + 1;
1978 else
1979 return skip_var_one(arg);
1983 * Skip one (assignable) variable name, including @r, $VAR, &option, d.key,
1984 * l[idx].
1986 static char_u *
1987 skip_var_one(arg)
1988 char_u *arg;
1990 if (*arg == '@' && arg[1] != NUL)
1991 return arg + 2;
1992 return find_name_end(*arg == '$' || *arg == '&' ? arg + 1 : arg,
1993 NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
1997 * List variables for hashtab "ht" with prefix "prefix".
1998 * If "empty" is TRUE also list NULL strings as empty strings.
2000 static void
2001 list_hashtable_vars(ht, prefix, empty, first)
2002 hashtab_T *ht;
2003 char_u *prefix;
2004 int empty;
2005 int *first;
2007 hashitem_T *hi;
2008 dictitem_T *di;
2009 int todo;
2011 todo = (int)ht->ht_used;
2012 for (hi = ht->ht_array; todo > 0 && !got_int; ++hi)
2014 if (!HASHITEM_EMPTY(hi))
2016 --todo;
2017 di = HI2DI(hi);
2018 if (empty || di->di_tv.v_type != VAR_STRING
2019 || di->di_tv.vval.v_string != NULL)
2020 list_one_var(di, prefix, first);
2026 * List global variables.
2028 static void
2029 list_glob_vars(first)
2030 int *first;
2032 list_hashtable_vars(&globvarht, (char_u *)"", TRUE, first);
2036 * List buffer variables.
2038 static void
2039 list_buf_vars(first)
2040 int *first;
2042 char_u numbuf[NUMBUFLEN];
2044 list_hashtable_vars(&curbuf->b_vars.dv_hashtab, (char_u *)"b:",
2045 TRUE, first);
2047 sprintf((char *)numbuf, "%ld", (long)curbuf->b_changedtick);
2048 list_one_var_a((char_u *)"b:", (char_u *)"changedtick", VAR_NUMBER,
2049 numbuf, first);
2053 * List window variables.
2055 static void
2056 list_win_vars(first)
2057 int *first;
2059 list_hashtable_vars(&curwin->w_vars.dv_hashtab,
2060 (char_u *)"w:", TRUE, first);
2063 #ifdef FEAT_WINDOWS
2065 * List tab page variables.
2067 static void
2068 list_tab_vars(first)
2069 int *first;
2071 list_hashtable_vars(&curtab->tp_vars.dv_hashtab,
2072 (char_u *)"t:", TRUE, first);
2074 #endif
2077 * List Vim variables.
2079 static void
2080 list_vim_vars(first)
2081 int *first;
2083 list_hashtable_vars(&vimvarht, (char_u *)"v:", FALSE, first);
2087 * List script-local variables, if there is a script.
2089 static void
2090 list_script_vars(first)
2091 int *first;
2093 if (current_SID > 0 && current_SID <= ga_scripts.ga_len)
2094 list_hashtable_vars(&SCRIPT_VARS(current_SID),
2095 (char_u *)"s:", FALSE, first);
2099 * List function variables, if there is a function.
2101 static void
2102 list_func_vars(first)
2103 int *first;
2105 if (current_funccal != NULL)
2106 list_hashtable_vars(&current_funccal->l_vars.dv_hashtab,
2107 (char_u *)"l:", FALSE, first);
2111 * List variables in "arg".
2113 static char_u *
2114 list_arg_vars(eap, arg, first)
2115 exarg_T *eap;
2116 char_u *arg;
2117 int *first;
2119 int error = FALSE;
2120 int len;
2121 char_u *name;
2122 char_u *name_start;
2123 char_u *arg_subsc;
2124 char_u *tofree;
2125 typval_T tv;
2127 while (!ends_excmd(*arg) && !got_int)
2129 if (error || eap->skip)
2131 arg = find_name_end(arg, NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
2132 if (!vim_iswhite(*arg) && !ends_excmd(*arg))
2134 emsg_severe = TRUE;
2135 EMSG(_(e_trailing));
2136 break;
2139 else
2141 /* get_name_len() takes care of expanding curly braces */
2142 name_start = name = arg;
2143 len = get_name_len(&arg, &tofree, TRUE, TRUE);
2144 if (len <= 0)
2146 /* This is mainly to keep test 49 working: when expanding
2147 * curly braces fails overrule the exception error message. */
2148 if (len < 0 && !aborting())
2150 emsg_severe = TRUE;
2151 EMSG2(_(e_invarg2), arg);
2152 break;
2154 error = TRUE;
2156 else
2158 if (tofree != NULL)
2159 name = tofree;
2160 if (get_var_tv(name, len, &tv, TRUE) == FAIL)
2161 error = TRUE;
2162 else
2164 /* handle d.key, l[idx], f(expr) */
2165 arg_subsc = arg;
2166 if (handle_subscript(&arg, &tv, TRUE, TRUE) == FAIL)
2167 error = TRUE;
2168 else
2170 if (arg == arg_subsc && len == 2 && name[1] == ':')
2172 switch (*name)
2174 case 'g': list_glob_vars(first); break;
2175 case 'b': list_buf_vars(first); break;
2176 case 'w': list_win_vars(first); break;
2177 #ifdef FEAT_WINDOWS
2178 case 't': list_tab_vars(first); break;
2179 #endif
2180 case 'v': list_vim_vars(first); break;
2181 case 's': list_script_vars(first); break;
2182 case 'l': list_func_vars(first); break;
2183 default:
2184 EMSG2(_("E738: Can't list variables for %s"), name);
2187 else
2189 char_u numbuf[NUMBUFLEN];
2190 char_u *tf;
2191 int c;
2192 char_u *s;
2194 s = echo_string(&tv, &tf, numbuf, 0);
2195 c = *arg;
2196 *arg = NUL;
2197 list_one_var_a((char_u *)"",
2198 arg == arg_subsc ? name : name_start,
2199 tv.v_type,
2200 s == NULL ? (char_u *)"" : s,
2201 first);
2202 *arg = c;
2203 vim_free(tf);
2205 clear_tv(&tv);
2210 vim_free(tofree);
2213 arg = skipwhite(arg);
2216 return arg;
2220 * Set one item of ":let var = expr" or ":let [v1, v2] = list" to its value.
2221 * Returns a pointer to the char just after the var name.
2222 * Returns NULL if there is an error.
2224 static char_u *
2225 ex_let_one(arg, tv, copy, endchars, op)
2226 char_u *arg; /* points to variable name */
2227 typval_T *tv; /* value to assign to variable */
2228 int copy; /* copy value from "tv" */
2229 char_u *endchars; /* valid chars after variable name or NULL */
2230 char_u *op; /* "+", "-", "." or NULL*/
2232 int c1;
2233 char_u *name;
2234 char_u *p;
2235 char_u *arg_end = NULL;
2236 int len;
2237 int opt_flags;
2238 char_u *tofree = NULL;
2241 * ":let $VAR = expr": Set environment variable.
2243 if (*arg == '$')
2245 /* Find the end of the name. */
2246 ++arg;
2247 name = arg;
2248 len = get_env_len(&arg);
2249 if (len == 0)
2250 EMSG2(_(e_invarg2), name - 1);
2251 else
2253 if (op != NULL && (*op == '+' || *op == '-'))
2254 EMSG2(_(e_letwrong), op);
2255 else if (endchars != NULL
2256 && vim_strchr(endchars, *skipwhite(arg)) == NULL)
2257 EMSG(_(e_letunexp));
2258 else
2260 c1 = name[len];
2261 name[len] = NUL;
2262 p = get_tv_string_chk(tv);
2263 if (p != NULL && op != NULL && *op == '.')
2265 int mustfree = FALSE;
2266 char_u *s = vim_getenv(name, &mustfree);
2268 if (s != NULL)
2270 p = tofree = concat_str(s, p);
2271 if (mustfree)
2272 vim_free(s);
2275 if (p != NULL)
2277 vim_setenv(name, p);
2278 if (STRICMP(name, "HOME") == 0)
2279 init_homedir();
2280 else if (didset_vim && STRICMP(name, "VIM") == 0)
2281 didset_vim = FALSE;
2282 else if (didset_vimruntime
2283 && STRICMP(name, "VIMRUNTIME") == 0)
2284 didset_vimruntime = FALSE;
2285 arg_end = arg;
2287 name[len] = c1;
2288 vim_free(tofree);
2294 * ":let &option = expr": Set option value.
2295 * ":let &l:option = expr": Set local option value.
2296 * ":let &g:option = expr": Set global option value.
2298 else if (*arg == '&')
2300 /* Find the end of the name. */
2301 p = find_option_end(&arg, &opt_flags);
2302 if (p == NULL || (endchars != NULL
2303 && vim_strchr(endchars, *skipwhite(p)) == NULL))
2304 EMSG(_(e_letunexp));
2305 else
2307 long n;
2308 int opt_type;
2309 long numval;
2310 char_u *stringval = NULL;
2311 char_u *s;
2313 c1 = *p;
2314 *p = NUL;
2316 n = get_tv_number(tv);
2317 s = get_tv_string_chk(tv); /* != NULL if number or string */
2318 if (s != NULL && op != NULL && *op != '=')
2320 opt_type = get_option_value(arg, &numval,
2321 &stringval, opt_flags);
2322 if ((opt_type == 1 && *op == '.')
2323 || (opt_type == 0 && *op != '.'))
2324 EMSG2(_(e_letwrong), op);
2325 else
2327 if (opt_type == 1) /* number */
2329 if (*op == '+')
2330 n = numval + n;
2331 else
2332 n = numval - n;
2334 else if (opt_type == 0 && stringval != NULL) /* string */
2336 s = concat_str(stringval, s);
2337 vim_free(stringval);
2338 stringval = s;
2342 if (s != NULL)
2344 set_option_value(arg, n, s, opt_flags);
2345 arg_end = p;
2347 *p = c1;
2348 vim_free(stringval);
2353 * ":let @r = expr": Set register contents.
2355 else if (*arg == '@')
2357 ++arg;
2358 if (op != NULL && (*op == '+' || *op == '-'))
2359 EMSG2(_(e_letwrong), op);
2360 else if (endchars != NULL
2361 && vim_strchr(endchars, *skipwhite(arg + 1)) == NULL)
2362 EMSG(_(e_letunexp));
2363 else
2365 char_u *ptofree = NULL;
2366 char_u *s;
2368 p = get_tv_string_chk(tv);
2369 if (p != NULL && op != NULL && *op == '.')
2371 s = get_reg_contents(*arg == '@' ? '"' : *arg, TRUE, TRUE);
2372 if (s != NULL)
2374 p = ptofree = concat_str(s, p);
2375 vim_free(s);
2378 if (p != NULL)
2380 write_reg_contents(*arg == '@' ? '"' : *arg, p, -1, FALSE);
2381 arg_end = arg + 1;
2383 vim_free(ptofree);
2388 * ":let var = expr": Set internal variable.
2389 * ":let {expr} = expr": Idem, name made with curly braces
2391 else if (eval_isnamec1(*arg) || *arg == '{')
2393 lval_T lv;
2395 p = get_lval(arg, tv, &lv, FALSE, FALSE, FALSE, FNE_CHECK_START);
2396 if (p != NULL && lv.ll_name != NULL)
2398 if (endchars != NULL && vim_strchr(endchars, *skipwhite(p)) == NULL)
2399 EMSG(_(e_letunexp));
2400 else
2402 set_var_lval(&lv, p, tv, copy, op);
2403 arg_end = p;
2406 clear_lval(&lv);
2409 else
2410 EMSG2(_(e_invarg2), arg);
2412 return arg_end;
2416 * If "arg" is equal to "b:changedtick" give an error and return TRUE.
2418 static int
2419 check_changedtick(arg)
2420 char_u *arg;
2422 if (STRNCMP(arg, "b:changedtick", 13) == 0 && !eval_isnamec(arg[13]))
2424 EMSG2(_(e_readonlyvar), arg);
2425 return TRUE;
2427 return FALSE;
2431 * Get an lval: variable, Dict item or List item that can be assigned a value
2432 * to: "name", "na{me}", "name[expr]", "name[expr:expr]", "name[expr][expr]",
2433 * "name.key", "name.key[expr]" etc.
2434 * Indexing only works if "name" is an existing List or Dictionary.
2435 * "name" points to the start of the name.
2436 * If "rettv" is not NULL it points to the value to be assigned.
2437 * "unlet" is TRUE for ":unlet": slightly different behavior when something is
2438 * wrong; must end in space or cmd separator.
2440 * Returns a pointer to just after the name, including indexes.
2441 * When an evaluation error occurs "lp->ll_name" is NULL;
2442 * Returns NULL for a parsing error. Still need to free items in "lp"!
2444 static char_u *
2445 get_lval(name, rettv, lp, unlet, skip, quiet, fne_flags)
2446 char_u *name;
2447 typval_T *rettv;
2448 lval_T *lp;
2449 int unlet;
2450 int skip;
2451 int quiet; /* don't give error messages */
2452 int fne_flags; /* flags for find_name_end() */
2454 char_u *p;
2455 char_u *expr_start, *expr_end;
2456 int cc;
2457 dictitem_T *v;
2458 typval_T var1;
2459 typval_T var2;
2460 int empty1 = FALSE;
2461 listitem_T *ni;
2462 char_u *key = NULL;
2463 int len;
2464 hashtab_T *ht;
2466 /* Clear everything in "lp". */
2467 vim_memset(lp, 0, sizeof(lval_T));
2469 if (skip)
2471 /* When skipping just find the end of the name. */
2472 lp->ll_name = name;
2473 return find_name_end(name, NULL, NULL, FNE_INCL_BR | fne_flags);
2476 /* Find the end of the name. */
2477 p = find_name_end(name, &expr_start, &expr_end, fne_flags);
2478 if (expr_start != NULL)
2480 /* Don't expand the name when we already know there is an error. */
2481 if (unlet && !vim_iswhite(*p) && !ends_excmd(*p)
2482 && *p != '[' && *p != '.')
2484 EMSG(_(e_trailing));
2485 return NULL;
2488 lp->ll_exp_name = make_expanded_name(name, expr_start, expr_end, p);
2489 if (lp->ll_exp_name == NULL)
2491 /* Report an invalid expression in braces, unless the
2492 * expression evaluation has been cancelled due to an
2493 * aborting error, an interrupt, or an exception. */
2494 if (!aborting() && !quiet)
2496 emsg_severe = TRUE;
2497 EMSG2(_(e_invarg2), name);
2498 return NULL;
2501 lp->ll_name = lp->ll_exp_name;
2503 else
2504 lp->ll_name = name;
2506 /* Without [idx] or .key we are done. */
2507 if ((*p != '[' && *p != '.') || lp->ll_name == NULL)
2508 return p;
2510 cc = *p;
2511 *p = NUL;
2512 v = find_var(lp->ll_name, &ht);
2513 if (v == NULL && !quiet)
2514 EMSG2(_(e_undefvar), lp->ll_name);
2515 *p = cc;
2516 if (v == NULL)
2517 return NULL;
2520 * Loop until no more [idx] or .key is following.
2522 lp->ll_tv = &v->di_tv;
2523 while (*p == '[' || (*p == '.' && lp->ll_tv->v_type == VAR_DICT))
2525 if (!(lp->ll_tv->v_type == VAR_LIST && lp->ll_tv->vval.v_list != NULL)
2526 && !(lp->ll_tv->v_type == VAR_DICT
2527 && lp->ll_tv->vval.v_dict != NULL))
2529 if (!quiet)
2530 EMSG(_("E689: Can only index a List or Dictionary"));
2531 return NULL;
2533 if (lp->ll_range)
2535 if (!quiet)
2536 EMSG(_("E708: [:] must come last"));
2537 return NULL;
2540 len = -1;
2541 if (*p == '.')
2543 key = p + 1;
2544 for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
2546 if (len == 0)
2548 if (!quiet)
2549 EMSG(_(e_emptykey));
2550 return NULL;
2552 p = key + len;
2554 else
2556 /* Get the index [expr] or the first index [expr: ]. */
2557 p = skipwhite(p + 1);
2558 if (*p == ':')
2559 empty1 = TRUE;
2560 else
2562 empty1 = FALSE;
2563 if (eval1(&p, &var1, TRUE) == FAIL) /* recursive! */
2564 return NULL;
2565 if (get_tv_string_chk(&var1) == NULL)
2567 /* not a number or string */
2568 clear_tv(&var1);
2569 return NULL;
2573 /* Optionally get the second index [ :expr]. */
2574 if (*p == ':')
2576 if (lp->ll_tv->v_type == VAR_DICT)
2578 if (!quiet)
2579 EMSG(_(e_dictrange));
2580 if (!empty1)
2581 clear_tv(&var1);
2582 return NULL;
2584 if (rettv != NULL && (rettv->v_type != VAR_LIST
2585 || rettv->vval.v_list == NULL))
2587 if (!quiet)
2588 EMSG(_("E709: [:] requires a List value"));
2589 if (!empty1)
2590 clear_tv(&var1);
2591 return NULL;
2593 p = skipwhite(p + 1);
2594 if (*p == ']')
2595 lp->ll_empty2 = TRUE;
2596 else
2598 lp->ll_empty2 = FALSE;
2599 if (eval1(&p, &var2, TRUE) == FAIL) /* recursive! */
2601 if (!empty1)
2602 clear_tv(&var1);
2603 return NULL;
2605 if (get_tv_string_chk(&var2) == NULL)
2607 /* not a number or string */
2608 if (!empty1)
2609 clear_tv(&var1);
2610 clear_tv(&var2);
2611 return NULL;
2614 lp->ll_range = TRUE;
2616 else
2617 lp->ll_range = FALSE;
2619 if (*p != ']')
2621 if (!quiet)
2622 EMSG(_(e_missbrac));
2623 if (!empty1)
2624 clear_tv(&var1);
2625 if (lp->ll_range && !lp->ll_empty2)
2626 clear_tv(&var2);
2627 return NULL;
2630 /* Skip to past ']'. */
2631 ++p;
2634 if (lp->ll_tv->v_type == VAR_DICT)
2636 if (len == -1)
2638 /* "[key]": get key from "var1" */
2639 key = get_tv_string(&var1); /* is number or string */
2640 if (*key == NUL)
2642 if (!quiet)
2643 EMSG(_(e_emptykey));
2644 clear_tv(&var1);
2645 return NULL;
2648 lp->ll_list = NULL;
2649 lp->ll_dict = lp->ll_tv->vval.v_dict;
2650 lp->ll_di = dict_find(lp->ll_dict, key, len);
2651 if (lp->ll_di == NULL)
2653 /* Key does not exist in dict: may need to add it. */
2654 if (*p == '[' || *p == '.' || unlet)
2656 if (!quiet)
2657 EMSG2(_(e_dictkey), key);
2658 if (len == -1)
2659 clear_tv(&var1);
2660 return NULL;
2662 if (len == -1)
2663 lp->ll_newkey = vim_strsave(key);
2664 else
2665 lp->ll_newkey = vim_strnsave(key, len);
2666 if (len == -1)
2667 clear_tv(&var1);
2668 if (lp->ll_newkey == NULL)
2669 p = NULL;
2670 break;
2672 if (len == -1)
2673 clear_tv(&var1);
2674 lp->ll_tv = &lp->ll_di->di_tv;
2676 else
2679 * Get the number and item for the only or first index of the List.
2681 if (empty1)
2682 lp->ll_n1 = 0;
2683 else
2685 lp->ll_n1 = get_tv_number(&var1); /* is number or string */
2686 clear_tv(&var1);
2688 lp->ll_dict = NULL;
2689 lp->ll_list = lp->ll_tv->vval.v_list;
2690 lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2691 if (lp->ll_li == NULL)
2693 if (lp->ll_n1 < 0)
2695 lp->ll_n1 = 0;
2696 lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2699 if (lp->ll_li == NULL)
2701 if (lp->ll_range && !lp->ll_empty2)
2702 clear_tv(&var2);
2703 return NULL;
2707 * May need to find the item or absolute index for the second
2708 * index of a range.
2709 * When no index given: "lp->ll_empty2" is TRUE.
2710 * Otherwise "lp->ll_n2" is set to the second index.
2712 if (lp->ll_range && !lp->ll_empty2)
2714 lp->ll_n2 = get_tv_number(&var2); /* is number or string */
2715 clear_tv(&var2);
2716 if (lp->ll_n2 < 0)
2718 ni = list_find(lp->ll_list, lp->ll_n2);
2719 if (ni == NULL)
2720 return NULL;
2721 lp->ll_n2 = list_idx_of_item(lp->ll_list, ni);
2724 /* Check that lp->ll_n2 isn't before lp->ll_n1. */
2725 if (lp->ll_n1 < 0)
2726 lp->ll_n1 = list_idx_of_item(lp->ll_list, lp->ll_li);
2727 if (lp->ll_n2 < lp->ll_n1)
2728 return NULL;
2731 lp->ll_tv = &lp->ll_li->li_tv;
2735 return p;
2739 * Clear lval "lp" that was filled by get_lval().
2741 static void
2742 clear_lval(lp)
2743 lval_T *lp;
2745 vim_free(lp->ll_exp_name);
2746 vim_free(lp->ll_newkey);
2750 * Set a variable that was parsed by get_lval() to "rettv".
2751 * "endp" points to just after the parsed name.
2752 * "op" is NULL, "+" for "+=", "-" for "-=", "." for ".=" or "=" for "=".
2754 static void
2755 set_var_lval(lp, endp, rettv, copy, op)
2756 lval_T *lp;
2757 char_u *endp;
2758 typval_T *rettv;
2759 int copy;
2760 char_u *op;
2762 int cc;
2763 listitem_T *ri;
2764 dictitem_T *di;
2766 if (lp->ll_tv == NULL)
2768 if (!check_changedtick(lp->ll_name))
2770 cc = *endp;
2771 *endp = NUL;
2772 if (op != NULL && *op != '=')
2774 typval_T tv;
2776 /* handle +=, -= and .= */
2777 if (get_var_tv(lp->ll_name, (int)STRLEN(lp->ll_name),
2778 &tv, TRUE) == OK)
2780 if (tv_op(&tv, rettv, op) == OK)
2781 set_var(lp->ll_name, &tv, FALSE);
2782 clear_tv(&tv);
2785 else
2786 set_var(lp->ll_name, rettv, copy);
2787 *endp = cc;
2790 else if (tv_check_lock(lp->ll_newkey == NULL
2791 ? lp->ll_tv->v_lock
2792 : lp->ll_tv->vval.v_dict->dv_lock, lp->ll_name))
2794 else if (lp->ll_range)
2797 * Assign the List values to the list items.
2799 for (ri = rettv->vval.v_list->lv_first; ri != NULL; )
2801 if (op != NULL && *op != '=')
2802 tv_op(&lp->ll_li->li_tv, &ri->li_tv, op);
2803 else
2805 clear_tv(&lp->ll_li->li_tv);
2806 copy_tv(&ri->li_tv, &lp->ll_li->li_tv);
2808 ri = ri->li_next;
2809 if (ri == NULL || (!lp->ll_empty2 && lp->ll_n2 == lp->ll_n1))
2810 break;
2811 if (lp->ll_li->li_next == NULL)
2813 /* Need to add an empty item. */
2814 if (list_append_number(lp->ll_list, 0) == FAIL)
2816 ri = NULL;
2817 break;
2820 lp->ll_li = lp->ll_li->li_next;
2821 ++lp->ll_n1;
2823 if (ri != NULL)
2824 EMSG(_("E710: List value has more items than target"));
2825 else if (lp->ll_empty2
2826 ? (lp->ll_li != NULL && lp->ll_li->li_next != NULL)
2827 : lp->ll_n1 != lp->ll_n2)
2828 EMSG(_("E711: List value has not enough items"));
2830 else
2833 * Assign to a List or Dictionary item.
2835 if (lp->ll_newkey != NULL)
2837 if (op != NULL && *op != '=')
2839 EMSG2(_(e_letwrong), op);
2840 return;
2843 /* Need to add an item to the Dictionary. */
2844 di = dictitem_alloc(lp->ll_newkey);
2845 if (di == NULL)
2846 return;
2847 if (dict_add(lp->ll_tv->vval.v_dict, di) == FAIL)
2849 vim_free(di);
2850 return;
2852 lp->ll_tv = &di->di_tv;
2854 else if (op != NULL && *op != '=')
2856 tv_op(lp->ll_tv, rettv, op);
2857 return;
2859 else
2860 clear_tv(lp->ll_tv);
2863 * Assign the value to the variable or list item.
2865 if (copy)
2866 copy_tv(rettv, lp->ll_tv);
2867 else
2869 *lp->ll_tv = *rettv;
2870 lp->ll_tv->v_lock = 0;
2871 init_tv(rettv);
2877 * Handle "tv1 += tv2", "tv1 -= tv2" and "tv1 .= tv2"
2878 * Returns OK or FAIL.
2880 static int
2881 tv_op(tv1, tv2, op)
2882 typval_T *tv1;
2883 typval_T *tv2;
2884 char_u *op;
2886 long n;
2887 char_u numbuf[NUMBUFLEN];
2888 char_u *s;
2890 /* Can't do anything with a Funcref or a Dict on the right. */
2891 if (tv2->v_type != VAR_FUNC && tv2->v_type != VAR_DICT)
2893 switch (tv1->v_type)
2895 case VAR_DICT:
2896 case VAR_FUNC:
2897 break;
2899 case VAR_LIST:
2900 if (*op != '+' || tv2->v_type != VAR_LIST)
2901 break;
2902 /* List += List */
2903 if (tv1->vval.v_list != NULL && tv2->vval.v_list != NULL)
2904 list_extend(tv1->vval.v_list, tv2->vval.v_list, NULL);
2905 return OK;
2907 case VAR_NUMBER:
2908 case VAR_STRING:
2909 if (tv2->v_type == VAR_LIST)
2910 break;
2911 if (*op == '+' || *op == '-')
2913 /* nr += nr or nr -= nr*/
2914 n = get_tv_number(tv1);
2915 #ifdef FEAT_FLOAT
2916 if (tv2->v_type == VAR_FLOAT)
2918 float_T f = n;
2920 if (*op == '+')
2921 f += tv2->vval.v_float;
2922 else
2923 f -= tv2->vval.v_float;
2924 clear_tv(tv1);
2925 tv1->v_type = VAR_FLOAT;
2926 tv1->vval.v_float = f;
2928 else
2929 #endif
2931 if (*op == '+')
2932 n += get_tv_number(tv2);
2933 else
2934 n -= get_tv_number(tv2);
2935 clear_tv(tv1);
2936 tv1->v_type = VAR_NUMBER;
2937 tv1->vval.v_number = n;
2940 else
2942 if (tv2->v_type == VAR_FLOAT)
2943 break;
2945 /* str .= str */
2946 s = get_tv_string(tv1);
2947 s = concat_str(s, get_tv_string_buf(tv2, numbuf));
2948 clear_tv(tv1);
2949 tv1->v_type = VAR_STRING;
2950 tv1->vval.v_string = s;
2952 return OK;
2954 #ifdef FEAT_FLOAT
2955 case VAR_FLOAT:
2957 float_T f;
2959 if (*op == '.' || (tv2->v_type != VAR_FLOAT
2960 && tv2->v_type != VAR_NUMBER
2961 && tv2->v_type != VAR_STRING))
2962 break;
2963 if (tv2->v_type == VAR_FLOAT)
2964 f = tv2->vval.v_float;
2965 else
2966 f = get_tv_number(tv2);
2967 if (*op == '+')
2968 tv1->vval.v_float += f;
2969 else
2970 tv1->vval.v_float -= f;
2972 return OK;
2973 #endif
2977 EMSG2(_(e_letwrong), op);
2978 return FAIL;
2982 * Add a watcher to a list.
2984 static void
2985 list_add_watch(l, lw)
2986 list_T *l;
2987 listwatch_T *lw;
2989 lw->lw_next = l->lv_watch;
2990 l->lv_watch = lw;
2994 * Remove a watcher from a list.
2995 * No warning when it isn't found...
2997 static void
2998 list_rem_watch(l, lwrem)
2999 list_T *l;
3000 listwatch_T *lwrem;
3002 listwatch_T *lw, **lwp;
3004 lwp = &l->lv_watch;
3005 for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
3007 if (lw == lwrem)
3009 *lwp = lw->lw_next;
3010 break;
3012 lwp = &lw->lw_next;
3017 * Just before removing an item from a list: advance watchers to the next
3018 * item.
3020 static void
3021 list_fix_watch(l, item)
3022 list_T *l;
3023 listitem_T *item;
3025 listwatch_T *lw;
3027 for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
3028 if (lw->lw_item == item)
3029 lw->lw_item = item->li_next;
3033 * Evaluate the expression used in a ":for var in expr" command.
3034 * "arg" points to "var".
3035 * Set "*errp" to TRUE for an error, FALSE otherwise;
3036 * Return a pointer that holds the info. Null when there is an error.
3038 void *
3039 eval_for_line(arg, errp, nextcmdp, skip)
3040 char_u *arg;
3041 int *errp;
3042 char_u **nextcmdp;
3043 int skip;
3045 forinfo_T *fi;
3046 char_u *expr;
3047 typval_T tv;
3048 list_T *l;
3050 *errp = TRUE; /* default: there is an error */
3052 fi = (forinfo_T *)alloc_clear(sizeof(forinfo_T));
3053 if (fi == NULL)
3054 return NULL;
3056 expr = skip_var_list(arg, &fi->fi_varcount, &fi->fi_semicolon);
3057 if (expr == NULL)
3058 return fi;
3060 expr = skipwhite(expr);
3061 if (expr[0] != 'i' || expr[1] != 'n' || !vim_iswhite(expr[2]))
3063 EMSG(_("E690: Missing \"in\" after :for"));
3064 return fi;
3067 if (skip)
3068 ++emsg_skip;
3069 if (eval0(skipwhite(expr + 2), &tv, nextcmdp, !skip) == OK)
3071 *errp = FALSE;
3072 if (!skip)
3074 l = tv.vval.v_list;
3075 if (tv.v_type != VAR_LIST || l == NULL)
3077 EMSG(_(e_listreq));
3078 clear_tv(&tv);
3080 else
3082 /* No need to increment the refcount, it's already set for the
3083 * list being used in "tv". */
3084 fi->fi_list = l;
3085 list_add_watch(l, &fi->fi_lw);
3086 fi->fi_lw.lw_item = l->lv_first;
3090 if (skip)
3091 --emsg_skip;
3093 return fi;
3097 * Use the first item in a ":for" list. Advance to the next.
3098 * Assign the values to the variable (list). "arg" points to the first one.
3099 * Return TRUE when a valid item was found, FALSE when at end of list or
3100 * something wrong.
3103 next_for_item(fi_void, arg)
3104 void *fi_void;
3105 char_u *arg;
3107 forinfo_T *fi = (forinfo_T *)fi_void;
3108 int result;
3109 listitem_T *item;
3111 item = fi->fi_lw.lw_item;
3112 if (item == NULL)
3113 result = FALSE;
3114 else
3116 fi->fi_lw.lw_item = item->li_next;
3117 result = (ex_let_vars(arg, &item->li_tv, TRUE,
3118 fi->fi_semicolon, fi->fi_varcount, NULL) == OK);
3120 return result;
3124 * Free the structure used to store info used by ":for".
3126 void
3127 free_for_info(fi_void)
3128 void *fi_void;
3130 forinfo_T *fi = (forinfo_T *)fi_void;
3132 if (fi != NULL && fi->fi_list != NULL)
3134 list_rem_watch(fi->fi_list, &fi->fi_lw);
3135 list_unref(fi->fi_list);
3137 vim_free(fi);
3140 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3142 void
3143 set_context_for_expression(xp, arg, cmdidx)
3144 expand_T *xp;
3145 char_u *arg;
3146 cmdidx_T cmdidx;
3148 int got_eq = FALSE;
3149 int c;
3150 char_u *p;
3152 if (cmdidx == CMD_let)
3154 xp->xp_context = EXPAND_USER_VARS;
3155 if (vim_strpbrk(arg, (char_u *)"\"'+-*/%.=!?~|&$([<>,#") == NULL)
3157 /* ":let var1 var2 ...": find last space. */
3158 for (p = arg + STRLEN(arg); p >= arg; )
3160 xp->xp_pattern = p;
3161 mb_ptr_back(arg, p);
3162 if (vim_iswhite(*p))
3163 break;
3165 return;
3168 else
3169 xp->xp_context = cmdidx == CMD_call ? EXPAND_FUNCTIONS
3170 : EXPAND_EXPRESSION;
3171 while ((xp->xp_pattern = vim_strpbrk(arg,
3172 (char_u *)"\"'+-*/%.=!?~|&$([<>,#")) != NULL)
3174 c = *xp->xp_pattern;
3175 if (c == '&')
3177 c = xp->xp_pattern[1];
3178 if (c == '&')
3180 ++xp->xp_pattern;
3181 xp->xp_context = cmdidx != CMD_let || got_eq
3182 ? EXPAND_EXPRESSION : EXPAND_NOTHING;
3184 else if (c != ' ')
3186 xp->xp_context = EXPAND_SETTINGS;
3187 if ((c == 'l' || c == 'g') && xp->xp_pattern[2] == ':')
3188 xp->xp_pattern += 2;
3192 else if (c == '$')
3194 /* environment variable */
3195 xp->xp_context = EXPAND_ENV_VARS;
3197 else if (c == '=')
3199 got_eq = TRUE;
3200 xp->xp_context = EXPAND_EXPRESSION;
3202 else if (c == '<'
3203 && xp->xp_context == EXPAND_FUNCTIONS
3204 && vim_strchr(xp->xp_pattern, '(') == NULL)
3206 /* Function name can start with "<SNR>" */
3207 break;
3209 else if (cmdidx != CMD_let || got_eq)
3211 if (c == '"') /* string */
3213 while ((c = *++xp->xp_pattern) != NUL && c != '"')
3214 if (c == '\\' && xp->xp_pattern[1] != NUL)
3215 ++xp->xp_pattern;
3216 xp->xp_context = EXPAND_NOTHING;
3218 else if (c == '\'') /* literal string */
3220 /* Trick: '' is like stopping and starting a literal string. */
3221 while ((c = *++xp->xp_pattern) != NUL && c != '\'')
3222 /* skip */ ;
3223 xp->xp_context = EXPAND_NOTHING;
3225 else if (c == '|')
3227 if (xp->xp_pattern[1] == '|')
3229 ++xp->xp_pattern;
3230 xp->xp_context = EXPAND_EXPRESSION;
3232 else
3233 xp->xp_context = EXPAND_COMMANDS;
3235 else
3236 xp->xp_context = EXPAND_EXPRESSION;
3238 else
3239 /* Doesn't look like something valid, expand as an expression
3240 * anyway. */
3241 xp->xp_context = EXPAND_EXPRESSION;
3242 arg = xp->xp_pattern;
3243 if (*arg != NUL)
3244 while ((c = *++arg) != NUL && (c == ' ' || c == '\t'))
3245 /* skip */ ;
3247 xp->xp_pattern = arg;
3250 #endif /* FEAT_CMDL_COMPL */
3253 * ":1,25call func(arg1, arg2)" function call.
3255 void
3256 ex_call(eap)
3257 exarg_T *eap;
3259 char_u *arg = eap->arg;
3260 char_u *startarg;
3261 char_u *name;
3262 char_u *tofree;
3263 int len;
3264 typval_T rettv;
3265 linenr_T lnum;
3266 int doesrange;
3267 int failed = FALSE;
3268 funcdict_T fudi;
3270 tofree = trans_function_name(&arg, eap->skip, TFN_INT, &fudi);
3271 if (fudi.fd_newkey != NULL)
3273 /* Still need to give an error message for missing key. */
3274 EMSG2(_(e_dictkey), fudi.fd_newkey);
3275 vim_free(fudi.fd_newkey);
3277 if (tofree == NULL)
3278 return;
3280 /* Increase refcount on dictionary, it could get deleted when evaluating
3281 * the arguments. */
3282 if (fudi.fd_dict != NULL)
3283 ++fudi.fd_dict->dv_refcount;
3285 /* If it is the name of a variable of type VAR_FUNC use its contents. */
3286 len = (int)STRLEN(tofree);
3287 name = deref_func_name(tofree, &len);
3289 /* Skip white space to allow ":call func ()". Not good, but required for
3290 * backward compatibility. */
3291 startarg = skipwhite(arg);
3292 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
3294 if (*startarg != '(')
3296 EMSG2(_("E107: Missing parentheses: %s"), eap->arg);
3297 goto end;
3301 * When skipping, evaluate the function once, to find the end of the
3302 * arguments.
3303 * When the function takes a range, this is discovered after the first
3304 * call, and the loop is broken.
3306 if (eap->skip)
3308 ++emsg_skip;
3309 lnum = eap->line2; /* do it once, also with an invalid range */
3311 else
3312 lnum = eap->line1;
3313 for ( ; lnum <= eap->line2; ++lnum)
3315 if (!eap->skip && eap->addr_count > 0)
3317 curwin->w_cursor.lnum = lnum;
3318 curwin->w_cursor.col = 0;
3320 arg = startarg;
3321 if (get_func_tv(name, (int)STRLEN(name), &rettv, &arg,
3322 eap->line1, eap->line2, &doesrange,
3323 !eap->skip, fudi.fd_dict) == FAIL)
3325 failed = TRUE;
3326 break;
3329 /* Handle a function returning a Funcref, Dictionary or List. */
3330 if (handle_subscript(&arg, &rettv, !eap->skip, TRUE) == FAIL)
3332 failed = TRUE;
3333 break;
3336 clear_tv(&rettv);
3337 if (doesrange || eap->skip)
3338 break;
3340 /* Stop when immediately aborting on error, or when an interrupt
3341 * occurred or an exception was thrown but not caught.
3342 * get_func_tv() returned OK, so that the check for trailing
3343 * characters below is executed. */
3344 if (aborting())
3345 break;
3347 if (eap->skip)
3348 --emsg_skip;
3350 if (!failed)
3352 /* Check for trailing illegal characters and a following command. */
3353 if (!ends_excmd(*arg))
3355 emsg_severe = TRUE;
3356 EMSG(_(e_trailing));
3358 else
3359 eap->nextcmd = check_nextcmd(arg);
3362 end:
3363 dict_unref(fudi.fd_dict);
3364 vim_free(tofree);
3368 * ":unlet[!] var1 ... " command.
3370 void
3371 ex_unlet(eap)
3372 exarg_T *eap;
3374 ex_unletlock(eap, eap->arg, 0);
3378 * ":lockvar" and ":unlockvar" commands
3380 void
3381 ex_lockvar(eap)
3382 exarg_T *eap;
3384 char_u *arg = eap->arg;
3385 int deep = 2;
3387 if (eap->forceit)
3388 deep = -1;
3389 else if (vim_isdigit(*arg))
3391 deep = getdigits(&arg);
3392 arg = skipwhite(arg);
3395 ex_unletlock(eap, arg, deep);
3399 * ":unlet", ":lockvar" and ":unlockvar" are quite similar.
3401 static void
3402 ex_unletlock(eap, argstart, deep)
3403 exarg_T *eap;
3404 char_u *argstart;
3405 int deep;
3407 char_u *arg = argstart;
3408 char_u *name_end;
3409 int error = FALSE;
3410 lval_T lv;
3414 /* Parse the name and find the end. */
3415 name_end = get_lval(arg, NULL, &lv, TRUE, eap->skip || error, FALSE,
3416 FNE_CHECK_START);
3417 if (lv.ll_name == NULL)
3418 error = TRUE; /* error but continue parsing */
3419 if (name_end == NULL || (!vim_iswhite(*name_end)
3420 && !ends_excmd(*name_end)))
3422 if (name_end != NULL)
3424 emsg_severe = TRUE;
3425 EMSG(_(e_trailing));
3427 if (!(eap->skip || error))
3428 clear_lval(&lv);
3429 break;
3432 if (!error && !eap->skip)
3434 if (eap->cmdidx == CMD_unlet)
3436 if (do_unlet_var(&lv, name_end, eap->forceit) == FAIL)
3437 error = TRUE;
3439 else
3441 if (do_lock_var(&lv, name_end, deep,
3442 eap->cmdidx == CMD_lockvar) == FAIL)
3443 error = TRUE;
3447 if (!eap->skip)
3448 clear_lval(&lv);
3450 arg = skipwhite(name_end);
3451 } while (!ends_excmd(*arg));
3453 eap->nextcmd = check_nextcmd(arg);
3456 static int
3457 do_unlet_var(lp, name_end, forceit)
3458 lval_T *lp;
3459 char_u *name_end;
3460 int forceit;
3462 int ret = OK;
3463 int cc;
3465 if (lp->ll_tv == NULL)
3467 cc = *name_end;
3468 *name_end = NUL;
3470 /* Normal name or expanded name. */
3471 if (check_changedtick(lp->ll_name))
3472 ret = FAIL;
3473 else if (do_unlet(lp->ll_name, forceit) == FAIL)
3474 ret = FAIL;
3475 *name_end = cc;
3477 else if (tv_check_lock(lp->ll_tv->v_lock, lp->ll_name))
3478 return FAIL;
3479 else if (lp->ll_range)
3481 listitem_T *li;
3483 /* Delete a range of List items. */
3484 while (lp->ll_li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3486 li = lp->ll_li->li_next;
3487 listitem_remove(lp->ll_list, lp->ll_li);
3488 lp->ll_li = li;
3489 ++lp->ll_n1;
3492 else
3494 if (lp->ll_list != NULL)
3495 /* unlet a List item. */
3496 listitem_remove(lp->ll_list, lp->ll_li);
3497 else
3498 /* unlet a Dictionary item. */
3499 dictitem_remove(lp->ll_dict, lp->ll_di);
3502 return ret;
3506 * "unlet" a variable. Return OK if it existed, FAIL if not.
3507 * When "forceit" is TRUE don't complain if the variable doesn't exist.
3510 do_unlet(name, forceit)
3511 char_u *name;
3512 int forceit;
3514 hashtab_T *ht;
3515 hashitem_T *hi;
3516 char_u *varname;
3517 dictitem_T *di;
3519 ht = find_var_ht(name, &varname);
3520 if (ht != NULL && *varname != NUL)
3522 hi = hash_find(ht, varname);
3523 if (!HASHITEM_EMPTY(hi))
3525 di = HI2DI(hi);
3526 if (var_check_fixed(di->di_flags, name)
3527 || var_check_ro(di->di_flags, name))
3528 return FAIL;
3529 delete_var(ht, hi);
3530 return OK;
3533 if (forceit)
3534 return OK;
3535 EMSG2(_("E108: No such variable: \"%s\""), name);
3536 return FAIL;
3540 * Lock or unlock variable indicated by "lp".
3541 * "deep" is the levels to go (-1 for unlimited);
3542 * "lock" is TRUE for ":lockvar", FALSE for ":unlockvar".
3544 static int
3545 do_lock_var(lp, name_end, deep, lock)
3546 lval_T *lp;
3547 char_u *name_end;
3548 int deep;
3549 int lock;
3551 int ret = OK;
3552 int cc;
3553 dictitem_T *di;
3555 if (deep == 0) /* nothing to do */
3556 return OK;
3558 if (lp->ll_tv == NULL)
3560 cc = *name_end;
3561 *name_end = NUL;
3563 /* Normal name or expanded name. */
3564 if (check_changedtick(lp->ll_name))
3565 ret = FAIL;
3566 else
3568 di = find_var(lp->ll_name, NULL);
3569 if (di == NULL)
3570 ret = FAIL;
3571 else
3573 if (lock)
3574 di->di_flags |= DI_FLAGS_LOCK;
3575 else
3576 di->di_flags &= ~DI_FLAGS_LOCK;
3577 item_lock(&di->di_tv, deep, lock);
3580 *name_end = cc;
3582 else if (lp->ll_range)
3584 listitem_T *li = lp->ll_li;
3586 /* (un)lock a range of List items. */
3587 while (li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3589 item_lock(&li->li_tv, deep, lock);
3590 li = li->li_next;
3591 ++lp->ll_n1;
3594 else if (lp->ll_list != NULL)
3595 /* (un)lock a List item. */
3596 item_lock(&lp->ll_li->li_tv, deep, lock);
3597 else
3598 /* un(lock) a Dictionary item. */
3599 item_lock(&lp->ll_di->di_tv, deep, lock);
3601 return ret;
3605 * Lock or unlock an item. "deep" is nr of levels to go.
3607 static void
3608 item_lock(tv, deep, lock)
3609 typval_T *tv;
3610 int deep;
3611 int lock;
3613 static int recurse = 0;
3614 list_T *l;
3615 listitem_T *li;
3616 dict_T *d;
3617 hashitem_T *hi;
3618 int todo;
3620 if (recurse >= DICT_MAXNEST)
3622 EMSG(_("E743: variable nested too deep for (un)lock"));
3623 return;
3625 if (deep == 0)
3626 return;
3627 ++recurse;
3629 /* lock/unlock the item itself */
3630 if (lock)
3631 tv->v_lock |= VAR_LOCKED;
3632 else
3633 tv->v_lock &= ~VAR_LOCKED;
3635 switch (tv->v_type)
3637 case VAR_LIST:
3638 if ((l = tv->vval.v_list) != NULL)
3640 if (lock)
3641 l->lv_lock |= VAR_LOCKED;
3642 else
3643 l->lv_lock &= ~VAR_LOCKED;
3644 if (deep < 0 || deep > 1)
3645 /* recursive: lock/unlock the items the List contains */
3646 for (li = l->lv_first; li != NULL; li = li->li_next)
3647 item_lock(&li->li_tv, deep - 1, lock);
3649 break;
3650 case VAR_DICT:
3651 if ((d = tv->vval.v_dict) != NULL)
3653 if (lock)
3654 d->dv_lock |= VAR_LOCKED;
3655 else
3656 d->dv_lock &= ~VAR_LOCKED;
3657 if (deep < 0 || deep > 1)
3659 /* recursive: lock/unlock the items the List contains */
3660 todo = (int)d->dv_hashtab.ht_used;
3661 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
3663 if (!HASHITEM_EMPTY(hi))
3665 --todo;
3666 item_lock(&HI2DI(hi)->di_tv, deep - 1, lock);
3672 --recurse;
3676 * Return TRUE if typeval "tv" is locked: Either that value is locked itself
3677 * or it refers to a List or Dictionary that is locked.
3679 static int
3680 tv_islocked(tv)
3681 typval_T *tv;
3683 return (tv->v_lock & VAR_LOCKED)
3684 || (tv->v_type == VAR_LIST
3685 && tv->vval.v_list != NULL
3686 && (tv->vval.v_list->lv_lock & VAR_LOCKED))
3687 || (tv->v_type == VAR_DICT
3688 && tv->vval.v_dict != NULL
3689 && (tv->vval.v_dict->dv_lock & VAR_LOCKED));
3692 #if (defined(FEAT_MENU) && defined(FEAT_MULTI_LANG)) || defined(PROTO)
3694 * Delete all "menutrans_" variables.
3696 void
3697 del_menutrans_vars()
3699 hashitem_T *hi;
3700 int todo;
3702 hash_lock(&globvarht);
3703 todo = (int)globvarht.ht_used;
3704 for (hi = globvarht.ht_array; todo > 0 && !got_int; ++hi)
3706 if (!HASHITEM_EMPTY(hi))
3708 --todo;
3709 if (STRNCMP(HI2DI(hi)->di_key, "menutrans_", 10) == 0)
3710 delete_var(&globvarht, hi);
3713 hash_unlock(&globvarht);
3715 #endif
3717 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3720 * Local string buffer for the next two functions to store a variable name
3721 * with its prefix. Allocated in cat_prefix_varname(), freed later in
3722 * get_user_var_name().
3725 static char_u *cat_prefix_varname __ARGS((int prefix, char_u *name));
3727 static char_u *varnamebuf = NULL;
3728 static int varnamebuflen = 0;
3731 * Function to concatenate a prefix and a variable name.
3733 static char_u *
3734 cat_prefix_varname(prefix, name)
3735 int prefix;
3736 char_u *name;
3738 int len;
3740 len = (int)STRLEN(name) + 3;
3741 if (len > varnamebuflen)
3743 vim_free(varnamebuf);
3744 len += 10; /* some additional space */
3745 varnamebuf = alloc(len);
3746 if (varnamebuf == NULL)
3748 varnamebuflen = 0;
3749 return NULL;
3751 varnamebuflen = len;
3753 *varnamebuf = prefix;
3754 varnamebuf[1] = ':';
3755 STRCPY(varnamebuf + 2, name);
3756 return varnamebuf;
3760 * Function given to ExpandGeneric() to obtain the list of user defined
3761 * (global/buffer/window/built-in) variable names.
3763 /*ARGSUSED*/
3764 char_u *
3765 get_user_var_name(xp, idx)
3766 expand_T *xp;
3767 int idx;
3769 static long_u gdone;
3770 static long_u bdone;
3771 static long_u wdone;
3772 #ifdef FEAT_WINDOWS
3773 static long_u tdone;
3774 #endif
3775 static int vidx;
3776 static hashitem_T *hi;
3777 hashtab_T *ht;
3779 if (idx == 0)
3781 gdone = bdone = wdone = vidx = 0;
3782 #ifdef FEAT_WINDOWS
3783 tdone = 0;
3784 #endif
3787 /* Global variables */
3788 if (gdone < globvarht.ht_used)
3790 if (gdone++ == 0)
3791 hi = globvarht.ht_array;
3792 else
3793 ++hi;
3794 while (HASHITEM_EMPTY(hi))
3795 ++hi;
3796 if (STRNCMP("g:", xp->xp_pattern, 2) == 0)
3797 return cat_prefix_varname('g', hi->hi_key);
3798 return hi->hi_key;
3801 /* b: variables */
3802 ht = &curbuf->b_vars.dv_hashtab;
3803 if (bdone < ht->ht_used)
3805 if (bdone++ == 0)
3806 hi = ht->ht_array;
3807 else
3808 ++hi;
3809 while (HASHITEM_EMPTY(hi))
3810 ++hi;
3811 return cat_prefix_varname('b', hi->hi_key);
3813 if (bdone == ht->ht_used)
3815 ++bdone;
3816 return (char_u *)"b:changedtick";
3819 /* w: variables */
3820 ht = &curwin->w_vars.dv_hashtab;
3821 if (wdone < ht->ht_used)
3823 if (wdone++ == 0)
3824 hi = ht->ht_array;
3825 else
3826 ++hi;
3827 while (HASHITEM_EMPTY(hi))
3828 ++hi;
3829 return cat_prefix_varname('w', hi->hi_key);
3832 #ifdef FEAT_WINDOWS
3833 /* t: variables */
3834 ht = &curtab->tp_vars.dv_hashtab;
3835 if (tdone < ht->ht_used)
3837 if (tdone++ == 0)
3838 hi = ht->ht_array;
3839 else
3840 ++hi;
3841 while (HASHITEM_EMPTY(hi))
3842 ++hi;
3843 return cat_prefix_varname('t', hi->hi_key);
3845 #endif
3847 /* v: variables */
3848 if (vidx < VV_LEN)
3849 return cat_prefix_varname('v', (char_u *)vimvars[vidx++].vv_name);
3851 vim_free(varnamebuf);
3852 varnamebuf = NULL;
3853 varnamebuflen = 0;
3854 return NULL;
3857 #endif /* FEAT_CMDL_COMPL */
3860 * types for expressions.
3862 typedef enum
3864 TYPE_UNKNOWN = 0
3865 , TYPE_EQUAL /* == */
3866 , TYPE_NEQUAL /* != */
3867 , TYPE_GREATER /* > */
3868 , TYPE_GEQUAL /* >= */
3869 , TYPE_SMALLER /* < */
3870 , TYPE_SEQUAL /* <= */
3871 , TYPE_MATCH /* =~ */
3872 , TYPE_NOMATCH /* !~ */
3873 } exptype_T;
3876 * The "evaluate" argument: When FALSE, the argument is only parsed but not
3877 * executed. The function may return OK, but the rettv will be of type
3878 * VAR_UNKNOWN. The function still returns FAIL for a syntax error.
3882 * Handle zero level expression.
3883 * This calls eval1() and handles error message and nextcmd.
3884 * Put the result in "rettv" when returning OK and "evaluate" is TRUE.
3885 * Note: "rettv.v_lock" is not set.
3886 * Return OK or FAIL.
3888 static int
3889 eval0(arg, rettv, nextcmd, evaluate)
3890 char_u *arg;
3891 typval_T *rettv;
3892 char_u **nextcmd;
3893 int evaluate;
3895 int ret;
3896 char_u *p;
3898 p = skipwhite(arg);
3899 ret = eval1(&p, rettv, evaluate);
3900 if (ret == FAIL || !ends_excmd(*p))
3902 if (ret != FAIL)
3903 clear_tv(rettv);
3905 * Report the invalid expression unless the expression evaluation has
3906 * been cancelled due to an aborting error, an interrupt, or an
3907 * exception.
3909 if (!aborting())
3910 EMSG2(_(e_invexpr2), arg);
3911 ret = FAIL;
3913 if (nextcmd != NULL)
3914 *nextcmd = check_nextcmd(p);
3916 return ret;
3920 * Handle top level expression:
3921 * expr1 ? expr0 : expr0
3923 * "arg" must point to the first non-white of the expression.
3924 * "arg" is advanced to the next non-white after the recognized expression.
3926 * Note: "rettv.v_lock" is not set.
3928 * Return OK or FAIL.
3930 static int
3931 eval1(arg, rettv, evaluate)
3932 char_u **arg;
3933 typval_T *rettv;
3934 int evaluate;
3936 int result;
3937 typval_T var2;
3940 * Get the first variable.
3942 if (eval2(arg, rettv, evaluate) == FAIL)
3943 return FAIL;
3945 if ((*arg)[0] == '?')
3947 result = FALSE;
3948 if (evaluate)
3950 int error = FALSE;
3952 if (get_tv_number_chk(rettv, &error) != 0)
3953 result = TRUE;
3954 clear_tv(rettv);
3955 if (error)
3956 return FAIL;
3960 * Get the second variable.
3962 *arg = skipwhite(*arg + 1);
3963 if (eval1(arg, rettv, evaluate && result) == FAIL) /* recursive! */
3964 return FAIL;
3967 * Check for the ":".
3969 if ((*arg)[0] != ':')
3971 EMSG(_("E109: Missing ':' after '?'"));
3972 if (evaluate && result)
3973 clear_tv(rettv);
3974 return FAIL;
3978 * Get the third variable.
3980 *arg = skipwhite(*arg + 1);
3981 if (eval1(arg, &var2, evaluate && !result) == FAIL) /* recursive! */
3983 if (evaluate && result)
3984 clear_tv(rettv);
3985 return FAIL;
3987 if (evaluate && !result)
3988 *rettv = var2;
3991 return OK;
3995 * Handle first level expression:
3996 * expr2 || expr2 || expr2 logical OR
3998 * "arg" must point to the first non-white of the expression.
3999 * "arg" is advanced to the next non-white after the recognized expression.
4001 * Return OK or FAIL.
4003 static int
4004 eval2(arg, rettv, evaluate)
4005 char_u **arg;
4006 typval_T *rettv;
4007 int evaluate;
4009 typval_T var2;
4010 long result;
4011 int first;
4012 int error = FALSE;
4015 * Get the first variable.
4017 if (eval3(arg, rettv, evaluate) == FAIL)
4018 return FAIL;
4021 * Repeat until there is no following "||".
4023 first = TRUE;
4024 result = FALSE;
4025 while ((*arg)[0] == '|' && (*arg)[1] == '|')
4027 if (evaluate && first)
4029 if (get_tv_number_chk(rettv, &error) != 0)
4030 result = TRUE;
4031 clear_tv(rettv);
4032 if (error)
4033 return FAIL;
4034 first = FALSE;
4038 * Get the second variable.
4040 *arg = skipwhite(*arg + 2);
4041 if (eval3(arg, &var2, evaluate && !result) == FAIL)
4042 return FAIL;
4045 * Compute the result.
4047 if (evaluate && !result)
4049 if (get_tv_number_chk(&var2, &error) != 0)
4050 result = TRUE;
4051 clear_tv(&var2);
4052 if (error)
4053 return FAIL;
4055 if (evaluate)
4057 rettv->v_type = VAR_NUMBER;
4058 rettv->vval.v_number = result;
4062 return OK;
4066 * Handle second level expression:
4067 * expr3 && expr3 && expr3 logical AND
4069 * "arg" must point to the first non-white of the expression.
4070 * "arg" is advanced to the next non-white after the recognized expression.
4072 * Return OK or FAIL.
4074 static int
4075 eval3(arg, rettv, evaluate)
4076 char_u **arg;
4077 typval_T *rettv;
4078 int evaluate;
4080 typval_T var2;
4081 long result;
4082 int first;
4083 int error = FALSE;
4086 * Get the first variable.
4088 if (eval4(arg, rettv, evaluate) == FAIL)
4089 return FAIL;
4092 * Repeat until there is no following "&&".
4094 first = TRUE;
4095 result = TRUE;
4096 while ((*arg)[0] == '&' && (*arg)[1] == '&')
4098 if (evaluate && first)
4100 if (get_tv_number_chk(rettv, &error) == 0)
4101 result = FALSE;
4102 clear_tv(rettv);
4103 if (error)
4104 return FAIL;
4105 first = FALSE;
4109 * Get the second variable.
4111 *arg = skipwhite(*arg + 2);
4112 if (eval4(arg, &var2, evaluate && result) == FAIL)
4113 return FAIL;
4116 * Compute the result.
4118 if (evaluate && result)
4120 if (get_tv_number_chk(&var2, &error) == 0)
4121 result = FALSE;
4122 clear_tv(&var2);
4123 if (error)
4124 return FAIL;
4126 if (evaluate)
4128 rettv->v_type = VAR_NUMBER;
4129 rettv->vval.v_number = result;
4133 return OK;
4137 * Handle third level expression:
4138 * var1 == var2
4139 * var1 =~ var2
4140 * var1 != var2
4141 * var1 !~ var2
4142 * var1 > var2
4143 * var1 >= var2
4144 * var1 < var2
4145 * var1 <= var2
4146 * var1 is var2
4147 * var1 isnot var2
4149 * "arg" must point to the first non-white of the expression.
4150 * "arg" is advanced to the next non-white after the recognized expression.
4152 * Return OK or FAIL.
4154 static int
4155 eval4(arg, rettv, evaluate)
4156 char_u **arg;
4157 typval_T *rettv;
4158 int evaluate;
4160 typval_T var2;
4161 char_u *p;
4162 int i;
4163 exptype_T type = TYPE_UNKNOWN;
4164 int type_is = FALSE; /* TRUE for "is" and "isnot" */
4165 int len = 2;
4166 long n1, n2;
4167 char_u *s1, *s2;
4168 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
4169 regmatch_T regmatch;
4170 int ic;
4171 char_u *save_cpo;
4174 * Get the first variable.
4176 if (eval5(arg, rettv, evaluate) == FAIL)
4177 return FAIL;
4179 p = *arg;
4180 switch (p[0])
4182 case '=': if (p[1] == '=')
4183 type = TYPE_EQUAL;
4184 else if (p[1] == '~')
4185 type = TYPE_MATCH;
4186 break;
4187 case '!': if (p[1] == '=')
4188 type = TYPE_NEQUAL;
4189 else if (p[1] == '~')
4190 type = TYPE_NOMATCH;
4191 break;
4192 case '>': if (p[1] != '=')
4194 type = TYPE_GREATER;
4195 len = 1;
4197 else
4198 type = TYPE_GEQUAL;
4199 break;
4200 case '<': if (p[1] != '=')
4202 type = TYPE_SMALLER;
4203 len = 1;
4205 else
4206 type = TYPE_SEQUAL;
4207 break;
4208 case 'i': if (p[1] == 's')
4210 if (p[2] == 'n' && p[3] == 'o' && p[4] == 't')
4211 len = 5;
4212 if (!vim_isIDc(p[len]))
4214 type = len == 2 ? TYPE_EQUAL : TYPE_NEQUAL;
4215 type_is = TRUE;
4218 break;
4222 * If there is a comparative operator, use it.
4224 if (type != TYPE_UNKNOWN)
4226 /* extra question mark appended: ignore case */
4227 if (p[len] == '?')
4229 ic = TRUE;
4230 ++len;
4232 /* extra '#' appended: match case */
4233 else if (p[len] == '#')
4235 ic = FALSE;
4236 ++len;
4238 /* nothing appended: use 'ignorecase' */
4239 else
4240 ic = p_ic;
4243 * Get the second variable.
4245 *arg = skipwhite(p + len);
4246 if (eval5(arg, &var2, evaluate) == FAIL)
4248 clear_tv(rettv);
4249 return FAIL;
4252 if (evaluate)
4254 if (type_is && rettv->v_type != var2.v_type)
4256 /* For "is" a different type always means FALSE, for "notis"
4257 * it means TRUE. */
4258 n1 = (type == TYPE_NEQUAL);
4260 else if (rettv->v_type == VAR_LIST || var2.v_type == VAR_LIST)
4262 if (type_is)
4264 n1 = (rettv->v_type == var2.v_type
4265 && rettv->vval.v_list == var2.vval.v_list);
4266 if (type == TYPE_NEQUAL)
4267 n1 = !n1;
4269 else if (rettv->v_type != var2.v_type
4270 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4272 if (rettv->v_type != var2.v_type)
4273 EMSG(_("E691: Can only compare List with List"));
4274 else
4275 EMSG(_("E692: Invalid operation for Lists"));
4276 clear_tv(rettv);
4277 clear_tv(&var2);
4278 return FAIL;
4280 else
4282 /* Compare two Lists for being equal or unequal. */
4283 n1 = list_equal(rettv->vval.v_list, var2.vval.v_list, ic);
4284 if (type == TYPE_NEQUAL)
4285 n1 = !n1;
4289 else if (rettv->v_type == VAR_DICT || var2.v_type == VAR_DICT)
4291 if (type_is)
4293 n1 = (rettv->v_type == var2.v_type
4294 && rettv->vval.v_dict == var2.vval.v_dict);
4295 if (type == TYPE_NEQUAL)
4296 n1 = !n1;
4298 else if (rettv->v_type != var2.v_type
4299 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4301 if (rettv->v_type != var2.v_type)
4302 EMSG(_("E735: Can only compare Dictionary with Dictionary"));
4303 else
4304 EMSG(_("E736: Invalid operation for Dictionary"));
4305 clear_tv(rettv);
4306 clear_tv(&var2);
4307 return FAIL;
4309 else
4311 /* Compare two Dictionaries for being equal or unequal. */
4312 n1 = dict_equal(rettv->vval.v_dict, var2.vval.v_dict, ic);
4313 if (type == TYPE_NEQUAL)
4314 n1 = !n1;
4318 else if (rettv->v_type == VAR_FUNC || var2.v_type == VAR_FUNC)
4320 if (rettv->v_type != var2.v_type
4321 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4323 if (rettv->v_type != var2.v_type)
4324 EMSG(_("E693: Can only compare Funcref with Funcref"));
4325 else
4326 EMSG(_("E694: Invalid operation for Funcrefs"));
4327 clear_tv(rettv);
4328 clear_tv(&var2);
4329 return FAIL;
4331 else
4333 /* Compare two Funcrefs for being equal or unequal. */
4334 if (rettv->vval.v_string == NULL
4335 || var2.vval.v_string == NULL)
4336 n1 = FALSE;
4337 else
4338 n1 = STRCMP(rettv->vval.v_string,
4339 var2.vval.v_string) == 0;
4340 if (type == TYPE_NEQUAL)
4341 n1 = !n1;
4345 #ifdef FEAT_FLOAT
4347 * If one of the two variables is a float, compare as a float.
4348 * When using "=~" or "!~", always compare as string.
4350 else if ((rettv->v_type == VAR_FLOAT || var2.v_type == VAR_FLOAT)
4351 && type != TYPE_MATCH && type != TYPE_NOMATCH)
4353 float_T f1, f2;
4355 if (rettv->v_type == VAR_FLOAT)
4356 f1 = rettv->vval.v_float;
4357 else
4358 f1 = get_tv_number(rettv);
4359 if (var2.v_type == VAR_FLOAT)
4360 f2 = var2.vval.v_float;
4361 else
4362 f2 = get_tv_number(&var2);
4363 n1 = FALSE;
4364 switch (type)
4366 case TYPE_EQUAL: n1 = (f1 == f2); break;
4367 case TYPE_NEQUAL: n1 = (f1 != f2); break;
4368 case TYPE_GREATER: n1 = (f1 > f2); break;
4369 case TYPE_GEQUAL: n1 = (f1 >= f2); break;
4370 case TYPE_SMALLER: n1 = (f1 < f2); break;
4371 case TYPE_SEQUAL: n1 = (f1 <= f2); break;
4372 case TYPE_UNKNOWN:
4373 case TYPE_MATCH:
4374 case TYPE_NOMATCH: break; /* avoid gcc warning */
4377 #endif
4380 * If one of the two variables is a number, compare as a number.
4381 * When using "=~" or "!~", always compare as string.
4383 else if ((rettv->v_type == VAR_NUMBER || var2.v_type == VAR_NUMBER)
4384 && type != TYPE_MATCH && type != TYPE_NOMATCH)
4386 n1 = get_tv_number(rettv);
4387 n2 = get_tv_number(&var2);
4388 switch (type)
4390 case TYPE_EQUAL: n1 = (n1 == n2); break;
4391 case TYPE_NEQUAL: n1 = (n1 != n2); break;
4392 case TYPE_GREATER: n1 = (n1 > n2); break;
4393 case TYPE_GEQUAL: n1 = (n1 >= n2); break;
4394 case TYPE_SMALLER: n1 = (n1 < n2); break;
4395 case TYPE_SEQUAL: n1 = (n1 <= n2); break;
4396 case TYPE_UNKNOWN:
4397 case TYPE_MATCH:
4398 case TYPE_NOMATCH: break; /* avoid gcc warning */
4401 else
4403 s1 = get_tv_string_buf(rettv, buf1);
4404 s2 = get_tv_string_buf(&var2, buf2);
4405 if (type != TYPE_MATCH && type != TYPE_NOMATCH)
4406 i = ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2);
4407 else
4408 i = 0;
4409 n1 = FALSE;
4410 switch (type)
4412 case TYPE_EQUAL: n1 = (i == 0); break;
4413 case TYPE_NEQUAL: n1 = (i != 0); break;
4414 case TYPE_GREATER: n1 = (i > 0); break;
4415 case TYPE_GEQUAL: n1 = (i >= 0); break;
4416 case TYPE_SMALLER: n1 = (i < 0); break;
4417 case TYPE_SEQUAL: n1 = (i <= 0); break;
4419 case TYPE_MATCH:
4420 case TYPE_NOMATCH:
4421 /* avoid 'l' flag in 'cpoptions' */
4422 save_cpo = p_cpo;
4423 p_cpo = (char_u *)"";
4424 regmatch.regprog = vim_regcomp(s2,
4425 RE_MAGIC + RE_STRING);
4426 regmatch.rm_ic = ic;
4427 if (regmatch.regprog != NULL)
4429 n1 = vim_regexec_nl(&regmatch, s1, (colnr_T)0);
4430 vim_free(regmatch.regprog);
4431 if (type == TYPE_NOMATCH)
4432 n1 = !n1;
4434 p_cpo = save_cpo;
4435 break;
4437 case TYPE_UNKNOWN: break; /* avoid gcc warning */
4440 clear_tv(rettv);
4441 clear_tv(&var2);
4442 rettv->v_type = VAR_NUMBER;
4443 rettv->vval.v_number = n1;
4447 return OK;
4451 * Handle fourth level expression:
4452 * + number addition
4453 * - number subtraction
4454 * . string concatenation
4456 * "arg" must point to the first non-white of the expression.
4457 * "arg" is advanced to the next non-white after the recognized expression.
4459 * Return OK or FAIL.
4461 static int
4462 eval5(arg, rettv, evaluate)
4463 char_u **arg;
4464 typval_T *rettv;
4465 int evaluate;
4467 typval_T var2;
4468 typval_T var3;
4469 int op;
4470 long n1, n2;
4471 #ifdef FEAT_FLOAT
4472 float_T f1 = 0, f2 = 0;
4473 #endif
4474 char_u *s1, *s2;
4475 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
4476 char_u *p;
4479 * Get the first variable.
4481 if (eval6(arg, rettv, evaluate, FALSE) == FAIL)
4482 return FAIL;
4485 * Repeat computing, until no '+', '-' or '.' is following.
4487 for (;;)
4489 op = **arg;
4490 if (op != '+' && op != '-' && op != '.')
4491 break;
4493 if ((op != '+' || rettv->v_type != VAR_LIST)
4494 #ifdef FEAT_FLOAT
4495 && (op == '.' || rettv->v_type != VAR_FLOAT)
4496 #endif
4499 /* For "list + ...", an illegal use of the first operand as
4500 * a number cannot be determined before evaluating the 2nd
4501 * operand: if this is also a list, all is ok.
4502 * For "something . ...", "something - ..." or "non-list + ...",
4503 * we know that the first operand needs to be a string or number
4504 * without evaluating the 2nd operand. So check before to avoid
4505 * side effects after an error. */
4506 if (evaluate && get_tv_string_chk(rettv) == NULL)
4508 clear_tv(rettv);
4509 return FAIL;
4514 * Get the second variable.
4516 *arg = skipwhite(*arg + 1);
4517 if (eval6(arg, &var2, evaluate, op == '.') == FAIL)
4519 clear_tv(rettv);
4520 return FAIL;
4523 if (evaluate)
4526 * Compute the result.
4528 if (op == '.')
4530 s1 = get_tv_string_buf(rettv, buf1); /* already checked */
4531 s2 = get_tv_string_buf_chk(&var2, buf2);
4532 if (s2 == NULL) /* type error ? */
4534 clear_tv(rettv);
4535 clear_tv(&var2);
4536 return FAIL;
4538 p = concat_str(s1, s2);
4539 clear_tv(rettv);
4540 rettv->v_type = VAR_STRING;
4541 rettv->vval.v_string = p;
4543 else if (op == '+' && rettv->v_type == VAR_LIST
4544 && var2.v_type == VAR_LIST)
4546 /* concatenate Lists */
4547 if (list_concat(rettv->vval.v_list, var2.vval.v_list,
4548 &var3) == FAIL)
4550 clear_tv(rettv);
4551 clear_tv(&var2);
4552 return FAIL;
4554 clear_tv(rettv);
4555 *rettv = var3;
4557 else
4559 int error = FALSE;
4561 #ifdef FEAT_FLOAT
4562 if (rettv->v_type == VAR_FLOAT)
4564 f1 = rettv->vval.v_float;
4565 n1 = 0;
4567 else
4568 #endif
4570 n1 = get_tv_number_chk(rettv, &error);
4571 if (error)
4573 /* This can only happen for "list + non-list". For
4574 * "non-list + ..." or "something - ...", we returned
4575 * before evaluating the 2nd operand. */
4576 clear_tv(rettv);
4577 return FAIL;
4579 #ifdef FEAT_FLOAT
4580 if (var2.v_type == VAR_FLOAT)
4581 f1 = n1;
4582 #endif
4584 #ifdef FEAT_FLOAT
4585 if (var2.v_type == VAR_FLOAT)
4587 f2 = var2.vval.v_float;
4588 n2 = 0;
4590 else
4591 #endif
4593 n2 = get_tv_number_chk(&var2, &error);
4594 if (error)
4596 clear_tv(rettv);
4597 clear_tv(&var2);
4598 return FAIL;
4600 #ifdef FEAT_FLOAT
4601 if (rettv->v_type == VAR_FLOAT)
4602 f2 = n2;
4603 #endif
4605 clear_tv(rettv);
4607 #ifdef FEAT_FLOAT
4608 /* If there is a float on either side the result is a float. */
4609 if (rettv->v_type == VAR_FLOAT || var2.v_type == VAR_FLOAT)
4611 if (op == '+')
4612 f1 = f1 + f2;
4613 else
4614 f1 = f1 - f2;
4615 rettv->v_type = VAR_FLOAT;
4616 rettv->vval.v_float = f1;
4618 else
4619 #endif
4621 if (op == '+')
4622 n1 = n1 + n2;
4623 else
4624 n1 = n1 - n2;
4625 rettv->v_type = VAR_NUMBER;
4626 rettv->vval.v_number = n1;
4629 clear_tv(&var2);
4632 return OK;
4636 * Handle fifth level expression:
4637 * * number multiplication
4638 * / number division
4639 * % number modulo
4641 * "arg" must point to the first non-white of the expression.
4642 * "arg" is advanced to the next non-white after the recognized expression.
4644 * Return OK or FAIL.
4646 static int
4647 eval6(arg, rettv, evaluate, want_string)
4648 char_u **arg;
4649 typval_T *rettv;
4650 int evaluate;
4651 int want_string; /* after "." operator */
4653 typval_T var2;
4654 int op;
4655 long n1, n2;
4656 #ifdef FEAT_FLOAT
4657 int use_float = FALSE;
4658 float_T f1 = 0, f2;
4659 #endif
4660 int error = FALSE;
4663 * Get the first variable.
4665 if (eval7(arg, rettv, evaluate, want_string) == FAIL)
4666 return FAIL;
4669 * Repeat computing, until no '*', '/' or '%' is following.
4671 for (;;)
4673 op = **arg;
4674 if (op != '*' && op != '/' && op != '%')
4675 break;
4677 if (evaluate)
4679 #ifdef FEAT_FLOAT
4680 if (rettv->v_type == VAR_FLOAT)
4682 f1 = rettv->vval.v_float;
4683 use_float = TRUE;
4684 n1 = 0;
4686 else
4687 #endif
4688 n1 = get_tv_number_chk(rettv, &error);
4689 clear_tv(rettv);
4690 if (error)
4691 return FAIL;
4693 else
4694 n1 = 0;
4697 * Get the second variable.
4699 *arg = skipwhite(*arg + 1);
4700 if (eval7(arg, &var2, evaluate, FALSE) == FAIL)
4701 return FAIL;
4703 if (evaluate)
4705 #ifdef FEAT_FLOAT
4706 if (var2.v_type == VAR_FLOAT)
4708 if (!use_float)
4710 f1 = n1;
4711 use_float = TRUE;
4713 f2 = var2.vval.v_float;
4714 n2 = 0;
4716 else
4717 #endif
4719 n2 = get_tv_number_chk(&var2, &error);
4720 clear_tv(&var2);
4721 if (error)
4722 return FAIL;
4723 #ifdef FEAT_FLOAT
4724 if (use_float)
4725 f2 = n2;
4726 #endif
4730 * Compute the result.
4731 * When either side is a float the result is a float.
4733 #ifdef FEAT_FLOAT
4734 if (use_float)
4736 if (op == '*')
4737 f1 = f1 * f2;
4738 else if (op == '/')
4740 /* We rely on the floating point library to handle divide
4741 * by zero to result in "inf" and not a crash. */
4742 f1 = f1 / f2;
4744 else
4746 EMSG(_("E804: Cannot use '%' with Float"));
4747 return FAIL;
4749 rettv->v_type = VAR_FLOAT;
4750 rettv->vval.v_float = f1;
4752 else
4753 #endif
4755 if (op == '*')
4756 n1 = n1 * n2;
4757 else if (op == '/')
4759 if (n2 == 0) /* give an error message? */
4761 if (n1 == 0)
4762 n1 = -0x7fffffffL - 1L; /* similar to NaN */
4763 else if (n1 < 0)
4764 n1 = -0x7fffffffL;
4765 else
4766 n1 = 0x7fffffffL;
4768 else
4769 n1 = n1 / n2;
4771 else
4773 if (n2 == 0) /* give an error message? */
4774 n1 = 0;
4775 else
4776 n1 = n1 % n2;
4778 rettv->v_type = VAR_NUMBER;
4779 rettv->vval.v_number = n1;
4784 return OK;
4788 * Handle sixth level expression:
4789 * number number constant
4790 * "string" string constant
4791 * 'string' literal string constant
4792 * &option-name option value
4793 * @r register contents
4794 * identifier variable value
4795 * function() function call
4796 * $VAR environment variable
4797 * (expression) nested expression
4798 * [expr, expr] List
4799 * {key: val, key: val} Dictionary
4801 * Also handle:
4802 * ! in front logical NOT
4803 * - in front unary minus
4804 * + in front unary plus (ignored)
4805 * trailing [] subscript in String or List
4806 * trailing .name entry in Dictionary
4808 * "arg" must point to the first non-white of the expression.
4809 * "arg" is advanced to the next non-white after the recognized expression.
4811 * Return OK or FAIL.
4813 static int
4814 eval7(arg, rettv, evaluate, want_string)
4815 char_u **arg;
4816 typval_T *rettv;
4817 int evaluate;
4818 int want_string; /* after "." operator */
4820 long n;
4821 int len;
4822 char_u *s;
4823 char_u *start_leader, *end_leader;
4824 int ret = OK;
4825 char_u *alias;
4828 * Initialise variable so that clear_tv() can't mistake this for a
4829 * string and free a string that isn't there.
4831 rettv->v_type = VAR_UNKNOWN;
4834 * Skip '!' and '-' characters. They are handled later.
4836 start_leader = *arg;
4837 while (**arg == '!' || **arg == '-' || **arg == '+')
4838 *arg = skipwhite(*arg + 1);
4839 end_leader = *arg;
4841 switch (**arg)
4844 * Number constant.
4846 case '0':
4847 case '1':
4848 case '2':
4849 case '3':
4850 case '4':
4851 case '5':
4852 case '6':
4853 case '7':
4854 case '8':
4855 case '9':
4857 #ifdef FEAT_FLOAT
4858 char_u *p = skipdigits(*arg + 1);
4859 int get_float = FALSE;
4861 /* We accept a float when the format matches
4862 * "[0-9]\+\.[0-9]\+\([eE][+-]\?[0-9]\+\)\?". This is very
4863 * strict to avoid backwards compatibility problems.
4864 * Don't look for a float after the "." operator, so that
4865 * ":let vers = 1.2.3" doesn't fail. */
4866 if (!want_string && p[0] == '.' && vim_isdigit(p[1]))
4868 get_float = TRUE;
4869 p = skipdigits(p + 2);
4870 if (*p == 'e' || *p == 'E')
4872 ++p;
4873 if (*p == '-' || *p == '+')
4874 ++p;
4875 if (!vim_isdigit(*p))
4876 get_float = FALSE;
4877 else
4878 p = skipdigits(p + 1);
4880 if (ASCII_ISALPHA(*p) || *p == '.')
4881 get_float = FALSE;
4883 if (get_float)
4885 float_T f;
4887 *arg += string2float(*arg, &f);
4888 if (evaluate)
4890 rettv->v_type = VAR_FLOAT;
4891 rettv->vval.v_float = f;
4894 else
4895 #endif
4897 vim_str2nr(*arg, NULL, &len, TRUE, TRUE, &n, NULL);
4898 *arg += len;
4899 if (evaluate)
4901 rettv->v_type = VAR_NUMBER;
4902 rettv->vval.v_number = n;
4905 break;
4909 * String constant: "string".
4911 case '"': ret = get_string_tv(arg, rettv, evaluate);
4912 break;
4915 * Literal string constant: 'str''ing'.
4917 case '\'': ret = get_lit_string_tv(arg, rettv, evaluate);
4918 break;
4921 * List: [expr, expr]
4923 case '[': ret = get_list_tv(arg, rettv, evaluate);
4924 break;
4927 * Dictionary: {key: val, key: val}
4929 case '{': ret = get_dict_tv(arg, rettv, evaluate);
4930 break;
4933 * Option value: &name
4935 case '&': ret = get_option_tv(arg, rettv, evaluate);
4936 break;
4939 * Environment variable: $VAR.
4941 case '$': ret = get_env_tv(arg, rettv, evaluate);
4942 break;
4945 * Register contents: @r.
4947 case '@': ++*arg;
4948 if (evaluate)
4950 rettv->v_type = VAR_STRING;
4951 rettv->vval.v_string = get_reg_contents(**arg, TRUE, TRUE);
4953 if (**arg != NUL)
4954 ++*arg;
4955 break;
4958 * nested expression: (expression).
4960 case '(': *arg = skipwhite(*arg + 1);
4961 ret = eval1(arg, rettv, evaluate); /* recursive! */
4962 if (**arg == ')')
4963 ++*arg;
4964 else if (ret == OK)
4966 EMSG(_("E110: Missing ')'"));
4967 clear_tv(rettv);
4968 ret = FAIL;
4970 break;
4972 default: ret = NOTDONE;
4973 break;
4976 if (ret == NOTDONE)
4979 * Must be a variable or function name.
4980 * Can also be a curly-braces kind of name: {expr}.
4982 s = *arg;
4983 len = get_name_len(arg, &alias, evaluate, TRUE);
4984 if (alias != NULL)
4985 s = alias;
4987 if (len <= 0)
4988 ret = FAIL;
4989 else
4991 if (**arg == '(') /* recursive! */
4993 /* If "s" is the name of a variable of type VAR_FUNC
4994 * use its contents. */
4995 s = deref_func_name(s, &len);
4997 /* Invoke the function. */
4998 ret = get_func_tv(s, len, rettv, arg,
4999 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
5000 &len, evaluate, NULL);
5001 /* Stop the expression evaluation when immediately
5002 * aborting on error, or when an interrupt occurred or
5003 * an exception was thrown but not caught. */
5004 if (aborting())
5006 if (ret == OK)
5007 clear_tv(rettv);
5008 ret = FAIL;
5011 else if (evaluate)
5012 ret = get_var_tv(s, len, rettv, TRUE);
5013 else
5014 ret = OK;
5017 if (alias != NULL)
5018 vim_free(alias);
5021 *arg = skipwhite(*arg);
5023 /* Handle following '[', '(' and '.' for expr[expr], expr.name,
5024 * expr(expr). */
5025 if (ret == OK)
5026 ret = handle_subscript(arg, rettv, evaluate, TRUE);
5029 * Apply logical NOT and unary '-', from right to left, ignore '+'.
5031 if (ret == OK && evaluate && end_leader > start_leader)
5033 int error = FALSE;
5034 int val = 0;
5035 #ifdef FEAT_FLOAT
5036 float_T f = 0.0;
5038 if (rettv->v_type == VAR_FLOAT)
5039 f = rettv->vval.v_float;
5040 else
5041 #endif
5042 val = get_tv_number_chk(rettv, &error);
5043 if (error)
5045 clear_tv(rettv);
5046 ret = FAIL;
5048 else
5050 while (end_leader > start_leader)
5052 --end_leader;
5053 if (*end_leader == '!')
5055 #ifdef FEAT_FLOAT
5056 if (rettv->v_type == VAR_FLOAT)
5057 f = !f;
5058 else
5059 #endif
5060 val = !val;
5062 else if (*end_leader == '-')
5064 #ifdef FEAT_FLOAT
5065 if (rettv->v_type == VAR_FLOAT)
5066 f = -f;
5067 else
5068 #endif
5069 val = -val;
5072 #ifdef FEAT_FLOAT
5073 if (rettv->v_type == VAR_FLOAT)
5075 clear_tv(rettv);
5076 rettv->vval.v_float = f;
5078 else
5079 #endif
5081 clear_tv(rettv);
5082 rettv->v_type = VAR_NUMBER;
5083 rettv->vval.v_number = val;
5088 return ret;
5092 * Evaluate an "[expr]" or "[expr:expr]" index. Also "dict.key".
5093 * "*arg" points to the '[' or '.'.
5094 * Returns FAIL or OK. "*arg" is advanced to after the ']'.
5096 static int
5097 eval_index(arg, rettv, evaluate, verbose)
5098 char_u **arg;
5099 typval_T *rettv;
5100 int evaluate;
5101 int verbose; /* give error messages */
5103 int empty1 = FALSE, empty2 = FALSE;
5104 typval_T var1, var2;
5105 long n1, n2 = 0;
5106 long len = -1;
5107 int range = FALSE;
5108 char_u *s;
5109 char_u *key = NULL;
5111 if (rettv->v_type == VAR_FUNC
5112 #ifdef FEAT_FLOAT
5113 || rettv->v_type == VAR_FLOAT
5114 #endif
5117 if (verbose)
5118 EMSG(_("E695: Cannot index a Funcref"));
5119 return FAIL;
5122 if (**arg == '.')
5125 * dict.name
5127 key = *arg + 1;
5128 for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
5130 if (len == 0)
5131 return FAIL;
5132 *arg = skipwhite(key + len);
5134 else
5137 * something[idx]
5139 * Get the (first) variable from inside the [].
5141 *arg = skipwhite(*arg + 1);
5142 if (**arg == ':')
5143 empty1 = TRUE;
5144 else if (eval1(arg, &var1, evaluate) == FAIL) /* recursive! */
5145 return FAIL;
5146 else if (evaluate && get_tv_string_chk(&var1) == NULL)
5148 /* not a number or string */
5149 clear_tv(&var1);
5150 return FAIL;
5154 * Get the second variable from inside the [:].
5156 if (**arg == ':')
5158 range = TRUE;
5159 *arg = skipwhite(*arg + 1);
5160 if (**arg == ']')
5161 empty2 = TRUE;
5162 else if (eval1(arg, &var2, evaluate) == FAIL) /* recursive! */
5164 if (!empty1)
5165 clear_tv(&var1);
5166 return FAIL;
5168 else if (evaluate && get_tv_string_chk(&var2) == NULL)
5170 /* not a number or string */
5171 if (!empty1)
5172 clear_tv(&var1);
5173 clear_tv(&var2);
5174 return FAIL;
5178 /* Check for the ']'. */
5179 if (**arg != ']')
5181 if (verbose)
5182 EMSG(_(e_missbrac));
5183 clear_tv(&var1);
5184 if (range)
5185 clear_tv(&var2);
5186 return FAIL;
5188 *arg = skipwhite(*arg + 1); /* skip the ']' */
5191 if (evaluate)
5193 n1 = 0;
5194 if (!empty1 && rettv->v_type != VAR_DICT)
5196 n1 = get_tv_number(&var1);
5197 clear_tv(&var1);
5199 if (range)
5201 if (empty2)
5202 n2 = -1;
5203 else
5205 n2 = get_tv_number(&var2);
5206 clear_tv(&var2);
5210 switch (rettv->v_type)
5212 case VAR_NUMBER:
5213 case VAR_STRING:
5214 s = get_tv_string(rettv);
5215 len = (long)STRLEN(s);
5216 if (range)
5218 /* The resulting variable is a substring. If the indexes
5219 * are out of range the result is empty. */
5220 if (n1 < 0)
5222 n1 = len + n1;
5223 if (n1 < 0)
5224 n1 = 0;
5226 if (n2 < 0)
5227 n2 = len + n2;
5228 else if (n2 >= len)
5229 n2 = len;
5230 if (n1 >= len || n2 < 0 || n1 > n2)
5231 s = NULL;
5232 else
5233 s = vim_strnsave(s + n1, (int)(n2 - n1 + 1));
5235 else
5237 /* The resulting variable is a string of a single
5238 * character. If the index is too big or negative the
5239 * result is empty. */
5240 if (n1 >= len || n1 < 0)
5241 s = NULL;
5242 else
5243 s = vim_strnsave(s + n1, 1);
5245 clear_tv(rettv);
5246 rettv->v_type = VAR_STRING;
5247 rettv->vval.v_string = s;
5248 break;
5250 case VAR_LIST:
5251 len = list_len(rettv->vval.v_list);
5252 if (n1 < 0)
5253 n1 = len + n1;
5254 if (!empty1 && (n1 < 0 || n1 >= len))
5256 /* For a range we allow invalid values and return an empty
5257 * list. A list index out of range is an error. */
5258 if (!range)
5260 if (verbose)
5261 EMSGN(_(e_listidx), n1);
5262 return FAIL;
5264 n1 = len;
5266 if (range)
5268 list_T *l;
5269 listitem_T *item;
5271 if (n2 < 0)
5272 n2 = len + n2;
5273 else if (n2 >= len)
5274 n2 = len - 1;
5275 if (!empty2 && (n2 < 0 || n2 + 1 < n1))
5276 n2 = -1;
5277 l = list_alloc();
5278 if (l == NULL)
5279 return FAIL;
5280 for (item = list_find(rettv->vval.v_list, n1);
5281 n1 <= n2; ++n1)
5283 if (list_append_tv(l, &item->li_tv) == FAIL)
5285 list_free(l, TRUE);
5286 return FAIL;
5288 item = item->li_next;
5290 clear_tv(rettv);
5291 rettv->v_type = VAR_LIST;
5292 rettv->vval.v_list = l;
5293 ++l->lv_refcount;
5295 else
5297 copy_tv(&list_find(rettv->vval.v_list, n1)->li_tv, &var1);
5298 clear_tv(rettv);
5299 *rettv = var1;
5301 break;
5303 case VAR_DICT:
5304 if (range)
5306 if (verbose)
5307 EMSG(_(e_dictrange));
5308 if (len == -1)
5309 clear_tv(&var1);
5310 return FAIL;
5313 dictitem_T *item;
5315 if (len == -1)
5317 key = get_tv_string(&var1);
5318 if (*key == NUL)
5320 if (verbose)
5321 EMSG(_(e_emptykey));
5322 clear_tv(&var1);
5323 return FAIL;
5327 item = dict_find(rettv->vval.v_dict, key, (int)len);
5329 if (item == NULL && verbose)
5330 EMSG2(_(e_dictkey), key);
5331 if (len == -1)
5332 clear_tv(&var1);
5333 if (item == NULL)
5334 return FAIL;
5336 copy_tv(&item->di_tv, &var1);
5337 clear_tv(rettv);
5338 *rettv = var1;
5340 break;
5344 return OK;
5348 * Get an option value.
5349 * "arg" points to the '&' or '+' before the option name.
5350 * "arg" is advanced to character after the option name.
5351 * Return OK or FAIL.
5353 static int
5354 get_option_tv(arg, rettv, evaluate)
5355 char_u **arg;
5356 typval_T *rettv; /* when NULL, only check if option exists */
5357 int evaluate;
5359 char_u *option_end;
5360 long numval;
5361 char_u *stringval;
5362 int opt_type;
5363 int c;
5364 int working = (**arg == '+'); /* has("+option") */
5365 int ret = OK;
5366 int opt_flags;
5369 * Isolate the option name and find its value.
5371 option_end = find_option_end(arg, &opt_flags);
5372 if (option_end == NULL)
5374 if (rettv != NULL)
5375 EMSG2(_("E112: Option name missing: %s"), *arg);
5376 return FAIL;
5379 if (!evaluate)
5381 *arg = option_end;
5382 return OK;
5385 c = *option_end;
5386 *option_end = NUL;
5387 opt_type = get_option_value(*arg, &numval,
5388 rettv == NULL ? NULL : &stringval, opt_flags);
5390 if (opt_type == -3) /* invalid name */
5392 if (rettv != NULL)
5393 EMSG2(_("E113: Unknown option: %s"), *arg);
5394 ret = FAIL;
5396 else if (rettv != NULL)
5398 if (opt_type == -2) /* hidden string option */
5400 rettv->v_type = VAR_STRING;
5401 rettv->vval.v_string = NULL;
5403 else if (opt_type == -1) /* hidden number option */
5405 rettv->v_type = VAR_NUMBER;
5406 rettv->vval.v_number = 0;
5408 else if (opt_type == 1) /* number option */
5410 rettv->v_type = VAR_NUMBER;
5411 rettv->vval.v_number = numval;
5413 else /* string option */
5415 rettv->v_type = VAR_STRING;
5416 rettv->vval.v_string = stringval;
5419 else if (working && (opt_type == -2 || opt_type == -1))
5420 ret = FAIL;
5422 *option_end = c; /* put back for error messages */
5423 *arg = option_end;
5425 return ret;
5429 * Allocate a variable for a string constant.
5430 * Return OK or FAIL.
5432 static int
5433 get_string_tv(arg, rettv, evaluate)
5434 char_u **arg;
5435 typval_T *rettv;
5436 int evaluate;
5438 char_u *p;
5439 char_u *name;
5440 int extra = 0;
5443 * Find the end of the string, skipping backslashed characters.
5445 for (p = *arg + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
5447 if (*p == '\\' && p[1] != NUL)
5449 ++p;
5450 /* A "\<x>" form occupies at least 4 characters, and produces up
5451 * to 6 characters: reserve space for 2 extra */
5452 if (*p == '<')
5453 extra += 2;
5457 if (*p != '"')
5459 EMSG2(_("E114: Missing quote: %s"), *arg);
5460 return FAIL;
5463 /* If only parsing, set *arg and return here */
5464 if (!evaluate)
5466 *arg = p + 1;
5467 return OK;
5471 * Copy the string into allocated memory, handling backslashed
5472 * characters.
5474 name = alloc((unsigned)(p - *arg + extra));
5475 if (name == NULL)
5476 return FAIL;
5477 rettv->v_type = VAR_STRING;
5478 rettv->vval.v_string = name;
5480 for (p = *arg + 1; *p != NUL && *p != '"'; )
5482 if (*p == '\\')
5484 switch (*++p)
5486 case 'b': *name++ = BS; ++p; break;
5487 case 'e': *name++ = ESC; ++p; break;
5488 case 'f': *name++ = FF; ++p; break;
5489 case 'n': *name++ = NL; ++p; break;
5490 case 'r': *name++ = CAR; ++p; break;
5491 case 't': *name++ = TAB; ++p; break;
5493 case 'X': /* hex: "\x1", "\x12" */
5494 case 'x':
5495 case 'u': /* Unicode: "\u0023" */
5496 case 'U':
5497 if (vim_isxdigit(p[1]))
5499 int n, nr;
5500 int c = toupper(*p);
5502 if (c == 'X')
5503 n = 2;
5504 else
5505 n = 4;
5506 nr = 0;
5507 while (--n >= 0 && vim_isxdigit(p[1]))
5509 ++p;
5510 nr = (nr << 4) + hex2nr(*p);
5512 ++p;
5513 #ifdef FEAT_MBYTE
5514 /* For "\u" store the number according to
5515 * 'encoding'. */
5516 if (c != 'X')
5517 name += (*mb_char2bytes)(nr, name);
5518 else
5519 #endif
5520 *name++ = nr;
5522 break;
5524 /* octal: "\1", "\12", "\123" */
5525 case '0':
5526 case '1':
5527 case '2':
5528 case '3':
5529 case '4':
5530 case '5':
5531 case '6':
5532 case '7': *name = *p++ - '0';
5533 if (*p >= '0' && *p <= '7')
5535 *name = (*name << 3) + *p++ - '0';
5536 if (*p >= '0' && *p <= '7')
5537 *name = (*name << 3) + *p++ - '0';
5539 ++name;
5540 break;
5542 /* Special key, e.g.: "\<C-W>" */
5543 case '<': extra = trans_special(&p, name, TRUE);
5544 if (extra != 0)
5546 name += extra;
5547 break;
5549 /* FALLTHROUGH */
5551 default: MB_COPY_CHAR(p, name);
5552 break;
5555 else
5556 MB_COPY_CHAR(p, name);
5559 *name = NUL;
5560 *arg = p + 1;
5562 return OK;
5566 * Allocate a variable for a 'str''ing' constant.
5567 * Return OK or FAIL.
5569 static int
5570 get_lit_string_tv(arg, rettv, evaluate)
5571 char_u **arg;
5572 typval_T *rettv;
5573 int evaluate;
5575 char_u *p;
5576 char_u *str;
5577 int reduce = 0;
5580 * Find the end of the string, skipping ''.
5582 for (p = *arg + 1; *p != NUL; mb_ptr_adv(p))
5584 if (*p == '\'')
5586 if (p[1] != '\'')
5587 break;
5588 ++reduce;
5589 ++p;
5593 if (*p != '\'')
5595 EMSG2(_("E115: Missing quote: %s"), *arg);
5596 return FAIL;
5599 /* If only parsing return after setting "*arg" */
5600 if (!evaluate)
5602 *arg = p + 1;
5603 return OK;
5607 * Copy the string into allocated memory, handling '' to ' reduction.
5609 str = alloc((unsigned)((p - *arg) - reduce));
5610 if (str == NULL)
5611 return FAIL;
5612 rettv->v_type = VAR_STRING;
5613 rettv->vval.v_string = str;
5615 for (p = *arg + 1; *p != NUL; )
5617 if (*p == '\'')
5619 if (p[1] != '\'')
5620 break;
5621 ++p;
5623 MB_COPY_CHAR(p, str);
5625 *str = NUL;
5626 *arg = p + 1;
5628 return OK;
5632 * Allocate a variable for a List and fill it from "*arg".
5633 * Return OK or FAIL.
5635 static int
5636 get_list_tv(arg, rettv, evaluate)
5637 char_u **arg;
5638 typval_T *rettv;
5639 int evaluate;
5641 list_T *l = NULL;
5642 typval_T tv;
5643 listitem_T *item;
5645 if (evaluate)
5647 l = list_alloc();
5648 if (l == NULL)
5649 return FAIL;
5652 *arg = skipwhite(*arg + 1);
5653 while (**arg != ']' && **arg != NUL)
5655 if (eval1(arg, &tv, evaluate) == FAIL) /* recursive! */
5656 goto failret;
5657 if (evaluate)
5659 item = listitem_alloc();
5660 if (item != NULL)
5662 item->li_tv = tv;
5663 item->li_tv.v_lock = 0;
5664 list_append(l, item);
5666 else
5667 clear_tv(&tv);
5670 if (**arg == ']')
5671 break;
5672 if (**arg != ',')
5674 EMSG2(_("E696: Missing comma in List: %s"), *arg);
5675 goto failret;
5677 *arg = skipwhite(*arg + 1);
5680 if (**arg != ']')
5682 EMSG2(_("E697: Missing end of List ']': %s"), *arg);
5683 failret:
5684 if (evaluate)
5685 list_free(l, TRUE);
5686 return FAIL;
5689 *arg = skipwhite(*arg + 1);
5690 if (evaluate)
5692 rettv->v_type = VAR_LIST;
5693 rettv->vval.v_list = l;
5694 ++l->lv_refcount;
5697 return OK;
5701 * Allocate an empty header for a list.
5702 * Caller should take care of the reference count.
5704 list_T *
5705 list_alloc()
5707 list_T *l;
5709 l = (list_T *)alloc_clear(sizeof(list_T));
5710 if (l != NULL)
5712 /* Prepend the list to the list of lists for garbage collection. */
5713 if (first_list != NULL)
5714 first_list->lv_used_prev = l;
5715 l->lv_used_prev = NULL;
5716 l->lv_used_next = first_list;
5717 first_list = l;
5719 return l;
5723 * Allocate an empty list for a return value.
5724 * Returns OK or FAIL.
5726 static int
5727 rettv_list_alloc(rettv)
5728 typval_T *rettv;
5730 list_T *l = list_alloc();
5732 if (l == NULL)
5733 return FAIL;
5735 rettv->vval.v_list = l;
5736 rettv->v_type = VAR_LIST;
5737 ++l->lv_refcount;
5738 return OK;
5742 * Unreference a list: decrement the reference count and free it when it
5743 * becomes zero.
5745 void
5746 list_unref(l)
5747 list_T *l;
5749 if (l != NULL && --l->lv_refcount <= 0)
5750 list_free(l, TRUE);
5754 * Free a list, including all items it points to.
5755 * Ignores the reference count.
5757 void
5758 list_free(l, recurse)
5759 list_T *l;
5760 int recurse; /* Free Lists and Dictionaries recursively. */
5762 listitem_T *item;
5764 /* Remove the list from the list of lists for garbage collection. */
5765 if (l->lv_used_prev == NULL)
5766 first_list = l->lv_used_next;
5767 else
5768 l->lv_used_prev->lv_used_next = l->lv_used_next;
5769 if (l->lv_used_next != NULL)
5770 l->lv_used_next->lv_used_prev = l->lv_used_prev;
5772 for (item = l->lv_first; item != NULL; item = l->lv_first)
5774 /* Remove the item before deleting it. */
5775 l->lv_first = item->li_next;
5776 if (recurse || (item->li_tv.v_type != VAR_LIST
5777 && item->li_tv.v_type != VAR_DICT))
5778 clear_tv(&item->li_tv);
5779 vim_free(item);
5781 vim_free(l);
5785 * Allocate a list item.
5787 static listitem_T *
5788 listitem_alloc()
5790 return (listitem_T *)alloc(sizeof(listitem_T));
5794 * Free a list item. Also clears the value. Does not notify watchers.
5796 static void
5797 listitem_free(item)
5798 listitem_T *item;
5800 clear_tv(&item->li_tv);
5801 vim_free(item);
5805 * Remove a list item from a List and free it. Also clears the value.
5807 static void
5808 listitem_remove(l, item)
5809 list_T *l;
5810 listitem_T *item;
5812 list_remove(l, item, item);
5813 listitem_free(item);
5817 * Get the number of items in a list.
5819 static long
5820 list_len(l)
5821 list_T *l;
5823 if (l == NULL)
5824 return 0L;
5825 return l->lv_len;
5829 * Return TRUE when two lists have exactly the same values.
5831 static int
5832 list_equal(l1, l2, ic)
5833 list_T *l1;
5834 list_T *l2;
5835 int ic; /* ignore case for strings */
5837 listitem_T *item1, *item2;
5839 if (l1 == NULL || l2 == NULL)
5840 return FALSE;
5841 if (l1 == l2)
5842 return TRUE;
5843 if (list_len(l1) != list_len(l2))
5844 return FALSE;
5846 for (item1 = l1->lv_first, item2 = l2->lv_first;
5847 item1 != NULL && item2 != NULL;
5848 item1 = item1->li_next, item2 = item2->li_next)
5849 if (!tv_equal(&item1->li_tv, &item2->li_tv, ic))
5850 return FALSE;
5851 return item1 == NULL && item2 == NULL;
5854 #if defined(FEAT_PYTHON) || defined(PROTO) || defined(FEAT_GUI_MACVIM)
5856 * Return the dictitem that an entry in a hashtable points to.
5858 dictitem_T *
5859 dict_lookup(hi)
5860 hashitem_T *hi;
5862 return HI2DI(hi);
5864 #endif
5867 * Return TRUE when two dictionaries have exactly the same key/values.
5869 static int
5870 dict_equal(d1, d2, ic)
5871 dict_T *d1;
5872 dict_T *d2;
5873 int ic; /* ignore case for strings */
5875 hashitem_T *hi;
5876 dictitem_T *item2;
5877 int todo;
5879 if (d1 == NULL || d2 == NULL)
5880 return FALSE;
5881 if (d1 == d2)
5882 return TRUE;
5883 if (dict_len(d1) != dict_len(d2))
5884 return FALSE;
5886 todo = (int)d1->dv_hashtab.ht_used;
5887 for (hi = d1->dv_hashtab.ht_array; todo > 0; ++hi)
5889 if (!HASHITEM_EMPTY(hi))
5891 item2 = dict_find(d2, hi->hi_key, -1);
5892 if (item2 == NULL)
5893 return FALSE;
5894 if (!tv_equal(&HI2DI(hi)->di_tv, &item2->di_tv, ic))
5895 return FALSE;
5896 --todo;
5899 return TRUE;
5903 * Return TRUE if "tv1" and "tv2" have the same value.
5904 * Compares the items just like "==" would compare them, but strings and
5905 * numbers are different. Floats and numbers are also different.
5907 static int
5908 tv_equal(tv1, tv2, ic)
5909 typval_T *tv1;
5910 typval_T *tv2;
5911 int ic; /* ignore case */
5913 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
5914 char_u *s1, *s2;
5915 static int recursive = 0; /* cach recursive loops */
5916 int r;
5918 if (tv1->v_type != tv2->v_type)
5919 return FALSE;
5920 /* Catch lists and dicts that have an endless loop by limiting
5921 * recursiveness to 1000. We guess they are equal then. */
5922 if (recursive >= 1000)
5923 return TRUE;
5925 switch (tv1->v_type)
5927 case VAR_LIST:
5928 ++recursive;
5929 r = list_equal(tv1->vval.v_list, tv2->vval.v_list, ic);
5930 --recursive;
5931 return r;
5933 case VAR_DICT:
5934 ++recursive;
5935 r = dict_equal(tv1->vval.v_dict, tv2->vval.v_dict, ic);
5936 --recursive;
5937 return r;
5939 case VAR_FUNC:
5940 return (tv1->vval.v_string != NULL
5941 && tv2->vval.v_string != NULL
5942 && STRCMP(tv1->vval.v_string, tv2->vval.v_string) == 0);
5944 case VAR_NUMBER:
5945 return tv1->vval.v_number == tv2->vval.v_number;
5947 #ifdef FEAT_FLOAT
5948 case VAR_FLOAT:
5949 return tv1->vval.v_float == tv2->vval.v_float;
5950 #endif
5952 case VAR_STRING:
5953 s1 = get_tv_string_buf(tv1, buf1);
5954 s2 = get_tv_string_buf(tv2, buf2);
5955 return ((ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2)) == 0);
5958 EMSG2(_(e_intern2), "tv_equal()");
5959 return TRUE;
5963 * Locate item with index "n" in list "l" and return it.
5964 * A negative index is counted from the end; -1 is the last item.
5965 * Returns NULL when "n" is out of range.
5967 static listitem_T *
5968 list_find(l, n)
5969 list_T *l;
5970 long n;
5972 listitem_T *item;
5973 long idx;
5975 if (l == NULL)
5976 return NULL;
5978 /* Negative index is relative to the end. */
5979 if (n < 0)
5980 n = l->lv_len + n;
5982 /* Check for index out of range. */
5983 if (n < 0 || n >= l->lv_len)
5984 return NULL;
5986 /* When there is a cached index may start search from there. */
5987 if (l->lv_idx_item != NULL)
5989 if (n < l->lv_idx / 2)
5991 /* closest to the start of the list */
5992 item = l->lv_first;
5993 idx = 0;
5995 else if (n > (l->lv_idx + l->lv_len) / 2)
5997 /* closest to the end of the list */
5998 item = l->lv_last;
5999 idx = l->lv_len - 1;
6001 else
6003 /* closest to the cached index */
6004 item = l->lv_idx_item;
6005 idx = l->lv_idx;
6008 else
6010 if (n < l->lv_len / 2)
6012 /* closest to the start of the list */
6013 item = l->lv_first;
6014 idx = 0;
6016 else
6018 /* closest to the end of the list */
6019 item = l->lv_last;
6020 idx = l->lv_len - 1;
6024 while (n > idx)
6026 /* search forward */
6027 item = item->li_next;
6028 ++idx;
6030 while (n < idx)
6032 /* search backward */
6033 item = item->li_prev;
6034 --idx;
6037 /* cache the used index */
6038 l->lv_idx = idx;
6039 l->lv_idx_item = item;
6041 return item;
6045 * Get list item "l[idx]" as a number.
6047 static long
6048 list_find_nr(l, idx, errorp)
6049 list_T *l;
6050 long idx;
6051 int *errorp; /* set to TRUE when something wrong */
6053 listitem_T *li;
6055 li = list_find(l, idx);
6056 if (li == NULL)
6058 if (errorp != NULL)
6059 *errorp = TRUE;
6060 return -1L;
6062 return get_tv_number_chk(&li->li_tv, errorp);
6066 * Get list item "l[idx - 1]" as a string. Returns NULL for failure.
6068 char_u *
6069 list_find_str(l, idx)
6070 list_T *l;
6071 long idx;
6073 listitem_T *li;
6075 li = list_find(l, idx - 1);
6076 if (li == NULL)
6078 EMSGN(_(e_listidx), idx);
6079 return NULL;
6081 return get_tv_string(&li->li_tv);
6085 * Locate "item" list "l" and return its index.
6086 * Returns -1 when "item" is not in the list.
6088 static long
6089 list_idx_of_item(l, item)
6090 list_T *l;
6091 listitem_T *item;
6093 long idx = 0;
6094 listitem_T *li;
6096 if (l == NULL)
6097 return -1;
6098 idx = 0;
6099 for (li = l->lv_first; li != NULL && li != item; li = li->li_next)
6100 ++idx;
6101 if (li == NULL)
6102 return -1;
6103 return idx;
6107 * Append item "item" to the end of list "l".
6109 static void
6110 list_append(l, item)
6111 list_T *l;
6112 listitem_T *item;
6114 if (l->lv_last == NULL)
6116 /* empty list */
6117 l->lv_first = item;
6118 l->lv_last = item;
6119 item->li_prev = NULL;
6121 else
6123 l->lv_last->li_next = item;
6124 item->li_prev = l->lv_last;
6125 l->lv_last = item;
6127 ++l->lv_len;
6128 item->li_next = NULL;
6132 * Append typval_T "tv" to the end of list "l".
6133 * Return FAIL when out of memory.
6135 static int
6136 list_append_tv(l, tv)
6137 list_T *l;
6138 typval_T *tv;
6140 listitem_T *li = listitem_alloc();
6142 if (li == NULL)
6143 return FAIL;
6144 copy_tv(tv, &li->li_tv);
6145 list_append(l, li);
6146 return OK;
6150 * Add a dictionary to a list. Used by getqflist().
6151 * Return FAIL when out of memory.
6154 list_append_dict(list, dict)
6155 list_T *list;
6156 dict_T *dict;
6158 listitem_T *li = listitem_alloc();
6160 if (li == NULL)
6161 return FAIL;
6162 li->li_tv.v_type = VAR_DICT;
6163 li->li_tv.v_lock = 0;
6164 li->li_tv.vval.v_dict = dict;
6165 list_append(list, li);
6166 ++dict->dv_refcount;
6167 return OK;
6171 * Make a copy of "str" and append it as an item to list "l".
6172 * When "len" >= 0 use "str[len]".
6173 * Returns FAIL when out of memory.
6176 list_append_string(l, str, len)
6177 list_T *l;
6178 char_u *str;
6179 int len;
6181 listitem_T *li = listitem_alloc();
6183 if (li == NULL)
6184 return FAIL;
6185 list_append(l, li);
6186 li->li_tv.v_type = VAR_STRING;
6187 li->li_tv.v_lock = 0;
6188 if (str == NULL)
6189 li->li_tv.vval.v_string = NULL;
6190 else if ((li->li_tv.vval.v_string = (len >= 0 ? vim_strnsave(str, len)
6191 : vim_strsave(str))) == NULL)
6192 return FAIL;
6193 return OK;
6197 * Append "n" to list "l".
6198 * Returns FAIL when out of memory.
6200 static int
6201 list_append_number(l, n)
6202 list_T *l;
6203 varnumber_T n;
6205 listitem_T *li;
6207 li = listitem_alloc();
6208 if (li == NULL)
6209 return FAIL;
6210 li->li_tv.v_type = VAR_NUMBER;
6211 li->li_tv.v_lock = 0;
6212 li->li_tv.vval.v_number = n;
6213 list_append(l, li);
6214 return OK;
6218 * Insert typval_T "tv" in list "l" before "item".
6219 * If "item" is NULL append at the end.
6220 * Return FAIL when out of memory.
6222 static int
6223 list_insert_tv(l, tv, item)
6224 list_T *l;
6225 typval_T *tv;
6226 listitem_T *item;
6228 listitem_T *ni = listitem_alloc();
6230 if (ni == NULL)
6231 return FAIL;
6232 copy_tv(tv, &ni->li_tv);
6233 if (item == NULL)
6234 /* Append new item at end of list. */
6235 list_append(l, ni);
6236 else
6238 /* Insert new item before existing item. */
6239 ni->li_prev = item->li_prev;
6240 ni->li_next = item;
6241 if (item->li_prev == NULL)
6243 l->lv_first = ni;
6244 ++l->lv_idx;
6246 else
6248 item->li_prev->li_next = ni;
6249 l->lv_idx_item = NULL;
6251 item->li_prev = ni;
6252 ++l->lv_len;
6254 return OK;
6258 * Extend "l1" with "l2".
6259 * If "bef" is NULL append at the end, otherwise insert before this item.
6260 * Returns FAIL when out of memory.
6262 static int
6263 list_extend(l1, l2, bef)
6264 list_T *l1;
6265 list_T *l2;
6266 listitem_T *bef;
6268 listitem_T *item;
6269 int todo = l2->lv_len;
6271 /* We also quit the loop when we have inserted the original item count of
6272 * the list, avoid a hang when we extend a list with itself. */
6273 for (item = l2->lv_first; item != NULL && --todo >= 0; item = item->li_next)
6274 if (list_insert_tv(l1, &item->li_tv, bef) == FAIL)
6275 return FAIL;
6276 return OK;
6280 * Concatenate lists "l1" and "l2" into a new list, stored in "tv".
6281 * Return FAIL when out of memory.
6283 static int
6284 list_concat(l1, l2, tv)
6285 list_T *l1;
6286 list_T *l2;
6287 typval_T *tv;
6289 list_T *l;
6291 if (l1 == NULL || l2 == NULL)
6292 return FAIL;
6294 /* make a copy of the first list. */
6295 l = list_copy(l1, FALSE, 0);
6296 if (l == NULL)
6297 return FAIL;
6298 tv->v_type = VAR_LIST;
6299 tv->vval.v_list = l;
6301 /* append all items from the second list */
6302 return list_extend(l, l2, NULL);
6306 * Make a copy of list "orig". Shallow if "deep" is FALSE.
6307 * The refcount of the new list is set to 1.
6308 * See item_copy() for "copyID".
6309 * Returns NULL when out of memory.
6311 static list_T *
6312 list_copy(orig, deep, copyID)
6313 list_T *orig;
6314 int deep;
6315 int copyID;
6317 list_T *copy;
6318 listitem_T *item;
6319 listitem_T *ni;
6321 if (orig == NULL)
6322 return NULL;
6324 copy = list_alloc();
6325 if (copy != NULL)
6327 if (copyID != 0)
6329 /* Do this before adding the items, because one of the items may
6330 * refer back to this list. */
6331 orig->lv_copyID = copyID;
6332 orig->lv_copylist = copy;
6334 for (item = orig->lv_first; item != NULL && !got_int;
6335 item = item->li_next)
6337 ni = listitem_alloc();
6338 if (ni == NULL)
6339 break;
6340 if (deep)
6342 if (item_copy(&item->li_tv, &ni->li_tv, deep, copyID) == FAIL)
6344 vim_free(ni);
6345 break;
6348 else
6349 copy_tv(&item->li_tv, &ni->li_tv);
6350 list_append(copy, ni);
6352 ++copy->lv_refcount;
6353 if (item != NULL)
6355 list_unref(copy);
6356 copy = NULL;
6360 return copy;
6364 * Remove items "item" to "item2" from list "l".
6365 * Does not free the listitem or the value!
6367 static void
6368 list_remove(l, item, item2)
6369 list_T *l;
6370 listitem_T *item;
6371 listitem_T *item2;
6373 listitem_T *ip;
6375 /* notify watchers */
6376 for (ip = item; ip != NULL; ip = ip->li_next)
6378 --l->lv_len;
6379 list_fix_watch(l, ip);
6380 if (ip == item2)
6381 break;
6384 if (item2->li_next == NULL)
6385 l->lv_last = item->li_prev;
6386 else
6387 item2->li_next->li_prev = item->li_prev;
6388 if (item->li_prev == NULL)
6389 l->lv_first = item2->li_next;
6390 else
6391 item->li_prev->li_next = item2->li_next;
6392 l->lv_idx_item = NULL;
6396 * Return an allocated string with the string representation of a list.
6397 * May return NULL.
6399 static char_u *
6400 list2string(tv, copyID)
6401 typval_T *tv;
6402 int copyID;
6404 garray_T ga;
6406 if (tv->vval.v_list == NULL)
6407 return NULL;
6408 ga_init2(&ga, (int)sizeof(char), 80);
6409 ga_append(&ga, '[');
6410 if (list_join(&ga, tv->vval.v_list, (char_u *)", ", FALSE, copyID) == FAIL)
6412 vim_free(ga.ga_data);
6413 return NULL;
6415 ga_append(&ga, ']');
6416 ga_append(&ga, NUL);
6417 return (char_u *)ga.ga_data;
6421 * Join list "l" into a string in "*gap", using separator "sep".
6422 * When "echo" is TRUE use String as echoed, otherwise as inside a List.
6423 * Return FAIL or OK.
6425 static int
6426 list_join(gap, l, sep, echo, copyID)
6427 garray_T *gap;
6428 list_T *l;
6429 char_u *sep;
6430 int echo;
6431 int copyID;
6433 int first = TRUE;
6434 char_u *tofree;
6435 char_u numbuf[NUMBUFLEN];
6436 listitem_T *item;
6437 char_u *s;
6439 for (item = l->lv_first; item != NULL && !got_int; item = item->li_next)
6441 if (first)
6442 first = FALSE;
6443 else
6444 ga_concat(gap, sep);
6446 if (echo)
6447 s = echo_string(&item->li_tv, &tofree, numbuf, copyID);
6448 else
6449 s = tv2string(&item->li_tv, &tofree, numbuf, copyID);
6450 if (s != NULL)
6451 ga_concat(gap, s);
6452 vim_free(tofree);
6453 if (s == NULL)
6454 return FAIL;
6456 return OK;
6460 * Garbage collection for lists and dictionaries.
6462 * We use reference counts to be able to free most items right away when they
6463 * are no longer used. But for composite items it's possible that it becomes
6464 * unused while the reference count is > 0: When there is a recursive
6465 * reference. Example:
6466 * :let l = [1, 2, 3]
6467 * :let d = {9: l}
6468 * :let l[1] = d
6470 * Since this is quite unusual we handle this with garbage collection: every
6471 * once in a while find out which lists and dicts are not referenced from any
6472 * variable.
6474 * Here is a good reference text about garbage collection (refers to Python
6475 * but it applies to all reference-counting mechanisms):
6476 * http://python.ca/nas/python/gc/
6480 * Do garbage collection for lists and dicts.
6481 * Return TRUE if some memory was freed.
6484 garbage_collect()
6486 dict_T *dd;
6487 list_T *ll;
6488 int copyID = ++current_copyID;
6489 buf_T *buf;
6490 win_T *wp;
6491 int i;
6492 funccall_T *fc;
6493 int did_free = FALSE;
6494 #ifdef FEAT_WINDOWS
6495 tabpage_T *tp;
6496 #endif
6498 /* Only do this once. */
6499 want_garbage_collect = FALSE;
6500 may_garbage_collect = FALSE;
6501 garbage_collect_at_exit = FALSE;
6504 * 1. Go through all accessible variables and mark all lists and dicts
6505 * with copyID.
6507 /* script-local variables */
6508 for (i = 1; i <= ga_scripts.ga_len; ++i)
6509 set_ref_in_ht(&SCRIPT_VARS(i), copyID);
6511 /* buffer-local variables */
6512 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
6513 set_ref_in_ht(&buf->b_vars.dv_hashtab, copyID);
6515 /* window-local variables */
6516 FOR_ALL_TAB_WINDOWS(tp, wp)
6517 set_ref_in_ht(&wp->w_vars.dv_hashtab, copyID);
6519 #ifdef FEAT_WINDOWS
6520 /* tabpage-local variables */
6521 for (tp = first_tabpage; tp != NULL; tp = tp->tp_next)
6522 set_ref_in_ht(&tp->tp_vars.dv_hashtab, copyID);
6523 #endif
6525 /* global variables */
6526 set_ref_in_ht(&globvarht, copyID);
6528 /* function-local variables */
6529 for (fc = current_funccal; fc != NULL; fc = fc->caller)
6531 set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID);
6532 set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID);
6535 /* v: vars */
6536 set_ref_in_ht(&vimvarht, copyID);
6539 * 2. Go through the list of dicts and free items without the copyID.
6541 for (dd = first_dict; dd != NULL; )
6542 if (dd->dv_copyID != copyID)
6544 /* Free the Dictionary and ordinary items it contains, but don't
6545 * recurse into Lists and Dictionaries, they will be in the list
6546 * of dicts or list of lists. */
6547 dict_free(dd, FALSE);
6548 did_free = TRUE;
6550 /* restart, next dict may also have been freed */
6551 dd = first_dict;
6553 else
6554 dd = dd->dv_used_next;
6557 * 3. Go through the list of lists and free items without the copyID.
6558 * But don't free a list that has a watcher (used in a for loop), these
6559 * are not referenced anywhere.
6561 for (ll = first_list; ll != NULL; )
6562 if (ll->lv_copyID != copyID && ll->lv_watch == NULL)
6564 /* Free the List and ordinary items it contains, but don't recurse
6565 * into Lists and Dictionaries, they will be in the list of dicts
6566 * or list of lists. */
6567 list_free(ll, FALSE);
6568 did_free = TRUE;
6570 /* restart, next list may also have been freed */
6571 ll = first_list;
6573 else
6574 ll = ll->lv_used_next;
6576 return did_free;
6580 * Mark all lists and dicts referenced through hashtab "ht" with "copyID".
6582 static void
6583 set_ref_in_ht(ht, copyID)
6584 hashtab_T *ht;
6585 int copyID;
6587 int todo;
6588 hashitem_T *hi;
6590 todo = (int)ht->ht_used;
6591 for (hi = ht->ht_array; todo > 0; ++hi)
6592 if (!HASHITEM_EMPTY(hi))
6594 --todo;
6595 set_ref_in_item(&HI2DI(hi)->di_tv, copyID);
6600 * Mark all lists and dicts referenced through list "l" with "copyID".
6602 static void
6603 set_ref_in_list(l, copyID)
6604 list_T *l;
6605 int copyID;
6607 listitem_T *li;
6609 for (li = l->lv_first; li != NULL; li = li->li_next)
6610 set_ref_in_item(&li->li_tv, copyID);
6614 * Mark all lists and dicts referenced through typval "tv" with "copyID".
6616 static void
6617 set_ref_in_item(tv, copyID)
6618 typval_T *tv;
6619 int copyID;
6621 dict_T *dd;
6622 list_T *ll;
6624 switch (tv->v_type)
6626 case VAR_DICT:
6627 dd = tv->vval.v_dict;
6628 if (dd != NULL && dd->dv_copyID != copyID)
6630 /* Didn't see this dict yet. */
6631 dd->dv_copyID = copyID;
6632 set_ref_in_ht(&dd->dv_hashtab, copyID);
6634 break;
6636 case VAR_LIST:
6637 ll = tv->vval.v_list;
6638 if (ll != NULL && ll->lv_copyID != copyID)
6640 /* Didn't see this list yet. */
6641 ll->lv_copyID = copyID;
6642 set_ref_in_list(ll, copyID);
6644 break;
6646 return;
6650 * Allocate an empty header for a dictionary.
6652 dict_T *
6653 dict_alloc()
6655 dict_T *d;
6657 d = (dict_T *)alloc(sizeof(dict_T));
6658 if (d != NULL)
6660 /* Add the list to the list of dicts for garbage collection. */
6661 if (first_dict != NULL)
6662 first_dict->dv_used_prev = d;
6663 d->dv_used_next = first_dict;
6664 d->dv_used_prev = NULL;
6665 first_dict = d;
6667 hash_init(&d->dv_hashtab);
6668 d->dv_lock = 0;
6669 d->dv_refcount = 0;
6670 d->dv_copyID = 0;
6672 return d;
6676 * Unreference a Dictionary: decrement the reference count and free it when it
6677 * becomes zero.
6679 static void
6680 dict_unref(d)
6681 dict_T *d;
6683 if (d != NULL && --d->dv_refcount <= 0)
6684 dict_free(d, TRUE);
6688 * Free a Dictionary, including all items it contains.
6689 * Ignores the reference count.
6691 static void
6692 dict_free(d, recurse)
6693 dict_T *d;
6694 int recurse; /* Free Lists and Dictionaries recursively. */
6696 int todo;
6697 hashitem_T *hi;
6698 dictitem_T *di;
6700 /* Remove the dict from the list of dicts for garbage collection. */
6701 if (d->dv_used_prev == NULL)
6702 first_dict = d->dv_used_next;
6703 else
6704 d->dv_used_prev->dv_used_next = d->dv_used_next;
6705 if (d->dv_used_next != NULL)
6706 d->dv_used_next->dv_used_prev = d->dv_used_prev;
6708 /* Lock the hashtab, we don't want it to resize while freeing items. */
6709 hash_lock(&d->dv_hashtab);
6710 todo = (int)d->dv_hashtab.ht_used;
6711 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
6713 if (!HASHITEM_EMPTY(hi))
6715 /* Remove the item before deleting it, just in case there is
6716 * something recursive causing trouble. */
6717 di = HI2DI(hi);
6718 hash_remove(&d->dv_hashtab, hi);
6719 if (recurse || (di->di_tv.v_type != VAR_LIST
6720 && di->di_tv.v_type != VAR_DICT))
6721 clear_tv(&di->di_tv);
6722 vim_free(di);
6723 --todo;
6726 hash_clear(&d->dv_hashtab);
6727 vim_free(d);
6731 * Allocate a Dictionary item.
6732 * The "key" is copied to the new item.
6733 * Note that the value of the item "di_tv" still needs to be initialized!
6734 * Returns NULL when out of memory.
6736 static dictitem_T *
6737 dictitem_alloc(key)
6738 char_u *key;
6740 dictitem_T *di;
6742 di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T) + STRLEN(key)));
6743 if (di != NULL)
6745 STRCPY(di->di_key, key);
6746 di->di_flags = 0;
6748 return di;
6752 * Make a copy of a Dictionary item.
6754 static dictitem_T *
6755 dictitem_copy(org)
6756 dictitem_T *org;
6758 dictitem_T *di;
6760 di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
6761 + STRLEN(org->di_key)));
6762 if (di != NULL)
6764 STRCPY(di->di_key, org->di_key);
6765 di->di_flags = 0;
6766 copy_tv(&org->di_tv, &di->di_tv);
6768 return di;
6772 * Remove item "item" from Dictionary "dict" and free it.
6774 static void
6775 dictitem_remove(dict, item)
6776 dict_T *dict;
6777 dictitem_T *item;
6779 hashitem_T *hi;
6781 hi = hash_find(&dict->dv_hashtab, item->di_key);
6782 if (HASHITEM_EMPTY(hi))
6783 EMSG2(_(e_intern2), "dictitem_remove()");
6784 else
6785 hash_remove(&dict->dv_hashtab, hi);
6786 dictitem_free(item);
6790 * Free a dict item. Also clears the value.
6792 static void
6793 dictitem_free(item)
6794 dictitem_T *item;
6796 clear_tv(&item->di_tv);
6797 vim_free(item);
6801 * Make a copy of dict "d". Shallow if "deep" is FALSE.
6802 * The refcount of the new dict is set to 1.
6803 * See item_copy() for "copyID".
6804 * Returns NULL when out of memory.
6806 static dict_T *
6807 dict_copy(orig, deep, copyID)
6808 dict_T *orig;
6809 int deep;
6810 int copyID;
6812 dict_T *copy;
6813 dictitem_T *di;
6814 int todo;
6815 hashitem_T *hi;
6817 if (orig == NULL)
6818 return NULL;
6820 copy = dict_alloc();
6821 if (copy != NULL)
6823 if (copyID != 0)
6825 orig->dv_copyID = copyID;
6826 orig->dv_copydict = copy;
6828 todo = (int)orig->dv_hashtab.ht_used;
6829 for (hi = orig->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
6831 if (!HASHITEM_EMPTY(hi))
6833 --todo;
6835 di = dictitem_alloc(hi->hi_key);
6836 if (di == NULL)
6837 break;
6838 if (deep)
6840 if (item_copy(&HI2DI(hi)->di_tv, &di->di_tv, deep,
6841 copyID) == FAIL)
6843 vim_free(di);
6844 break;
6847 else
6848 copy_tv(&HI2DI(hi)->di_tv, &di->di_tv);
6849 if (dict_add(copy, di) == FAIL)
6851 dictitem_free(di);
6852 break;
6857 ++copy->dv_refcount;
6858 if (todo > 0)
6860 dict_unref(copy);
6861 copy = NULL;
6865 return copy;
6869 * Add item "item" to Dictionary "d".
6870 * Returns FAIL when out of memory and when key already existed.
6872 static int
6873 dict_add(d, item)
6874 dict_T *d;
6875 dictitem_T *item;
6877 return hash_add(&d->dv_hashtab, item->di_key);
6881 * Add a number or string entry to dictionary "d".
6882 * When "str" is NULL use number "nr", otherwise use "str".
6883 * Returns FAIL when out of memory and when key already exists.
6886 dict_add_nr_str(d, key, nr, str)
6887 dict_T *d;
6888 char *key;
6889 long nr;
6890 char_u *str;
6892 dictitem_T *item;
6894 item = dictitem_alloc((char_u *)key);
6895 if (item == NULL)
6896 return FAIL;
6897 item->di_tv.v_lock = 0;
6898 if (str == NULL)
6900 item->di_tv.v_type = VAR_NUMBER;
6901 item->di_tv.vval.v_number = nr;
6903 else
6905 item->di_tv.v_type = VAR_STRING;
6906 item->di_tv.vval.v_string = vim_strsave(str);
6908 if (dict_add(d, item) == FAIL)
6910 dictitem_free(item);
6911 return FAIL;
6913 return OK;
6917 * Get the number of items in a Dictionary.
6919 static long
6920 dict_len(d)
6921 dict_T *d;
6923 if (d == NULL)
6924 return 0L;
6925 return (long)d->dv_hashtab.ht_used;
6929 * Find item "key[len]" in Dictionary "d".
6930 * If "len" is negative use strlen(key).
6931 * Returns NULL when not found.
6933 static dictitem_T *
6934 dict_find(d, key, len)
6935 dict_T *d;
6936 char_u *key;
6937 int len;
6939 #define AKEYLEN 200
6940 char_u buf[AKEYLEN];
6941 char_u *akey;
6942 char_u *tofree = NULL;
6943 hashitem_T *hi;
6945 if (len < 0)
6946 akey = key;
6947 else if (len >= AKEYLEN)
6949 tofree = akey = vim_strnsave(key, len);
6950 if (akey == NULL)
6951 return NULL;
6953 else
6955 /* Avoid a malloc/free by using buf[]. */
6956 vim_strncpy(buf, key, len);
6957 akey = buf;
6960 hi = hash_find(&d->dv_hashtab, akey);
6961 vim_free(tofree);
6962 if (HASHITEM_EMPTY(hi))
6963 return NULL;
6964 return HI2DI(hi);
6968 * Get a string item from a dictionary.
6969 * When "save" is TRUE allocate memory for it.
6970 * Returns NULL if the entry doesn't exist or out of memory.
6972 char_u *
6973 get_dict_string(d, key, save)
6974 dict_T *d;
6975 char_u *key;
6976 int save;
6978 dictitem_T *di;
6979 char_u *s;
6981 di = dict_find(d, key, -1);
6982 if (di == NULL)
6983 return NULL;
6984 s = get_tv_string(&di->di_tv);
6985 if (save && s != NULL)
6986 s = vim_strsave(s);
6987 return s;
6991 * Get a number item from a dictionary.
6992 * Returns 0 if the entry doesn't exist or out of memory.
6994 long
6995 get_dict_number(d, key)
6996 dict_T *d;
6997 char_u *key;
6999 dictitem_T *di;
7001 di = dict_find(d, key, -1);
7002 if (di == NULL)
7003 return 0;
7004 return get_tv_number(&di->di_tv);
7008 * Return an allocated string with the string representation of a Dictionary.
7009 * May return NULL.
7011 static char_u *
7012 dict2string(tv, copyID)
7013 typval_T *tv;
7014 int copyID;
7016 garray_T ga;
7017 int first = TRUE;
7018 char_u *tofree;
7019 char_u numbuf[NUMBUFLEN];
7020 hashitem_T *hi;
7021 char_u *s;
7022 dict_T *d;
7023 int todo;
7025 if ((d = tv->vval.v_dict) == NULL)
7026 return NULL;
7027 ga_init2(&ga, (int)sizeof(char), 80);
7028 ga_append(&ga, '{');
7030 todo = (int)d->dv_hashtab.ht_used;
7031 for (hi = d->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
7033 if (!HASHITEM_EMPTY(hi))
7035 --todo;
7037 if (first)
7038 first = FALSE;
7039 else
7040 ga_concat(&ga, (char_u *)", ");
7042 tofree = string_quote(hi->hi_key, FALSE);
7043 if (tofree != NULL)
7045 ga_concat(&ga, tofree);
7046 vim_free(tofree);
7048 ga_concat(&ga, (char_u *)": ");
7049 s = tv2string(&HI2DI(hi)->di_tv, &tofree, numbuf, copyID);
7050 if (s != NULL)
7051 ga_concat(&ga, s);
7052 vim_free(tofree);
7053 if (s == NULL)
7054 break;
7057 if (todo > 0)
7059 vim_free(ga.ga_data);
7060 return NULL;
7063 ga_append(&ga, '}');
7064 ga_append(&ga, NUL);
7065 return (char_u *)ga.ga_data;
7069 * Allocate a variable for a Dictionary and fill it from "*arg".
7070 * Return OK or FAIL. Returns NOTDONE for {expr}.
7072 static int
7073 get_dict_tv(arg, rettv, evaluate)
7074 char_u **arg;
7075 typval_T *rettv;
7076 int evaluate;
7078 dict_T *d = NULL;
7079 typval_T tvkey;
7080 typval_T tv;
7081 char_u *key = NULL;
7082 dictitem_T *item;
7083 char_u *start = skipwhite(*arg + 1);
7084 char_u buf[NUMBUFLEN];
7087 * First check if it's not a curly-braces thing: {expr}.
7088 * Must do this without evaluating, otherwise a function may be called
7089 * twice. Unfortunately this means we need to call eval1() twice for the
7090 * first item.
7091 * But {} is an empty Dictionary.
7093 if (*start != '}')
7095 if (eval1(&start, &tv, FALSE) == FAIL) /* recursive! */
7096 return FAIL;
7097 if (*start == '}')
7098 return NOTDONE;
7101 if (evaluate)
7103 d = dict_alloc();
7104 if (d == NULL)
7105 return FAIL;
7107 tvkey.v_type = VAR_UNKNOWN;
7108 tv.v_type = VAR_UNKNOWN;
7110 *arg = skipwhite(*arg + 1);
7111 while (**arg != '}' && **arg != NUL)
7113 if (eval1(arg, &tvkey, evaluate) == FAIL) /* recursive! */
7114 goto failret;
7115 if (**arg != ':')
7117 EMSG2(_("E720: Missing colon in Dictionary: %s"), *arg);
7118 clear_tv(&tvkey);
7119 goto failret;
7121 if (evaluate)
7123 key = get_tv_string_buf_chk(&tvkey, buf);
7124 if (key == NULL || *key == NUL)
7126 /* "key" is NULL when get_tv_string_buf_chk() gave an errmsg */
7127 if (key != NULL)
7128 EMSG(_(e_emptykey));
7129 clear_tv(&tvkey);
7130 goto failret;
7134 *arg = skipwhite(*arg + 1);
7135 if (eval1(arg, &tv, evaluate) == FAIL) /* recursive! */
7137 if (evaluate)
7138 clear_tv(&tvkey);
7139 goto failret;
7141 if (evaluate)
7143 item = dict_find(d, key, -1);
7144 if (item != NULL)
7146 EMSG2(_("E721: Duplicate key in Dictionary: \"%s\""), key);
7147 clear_tv(&tvkey);
7148 clear_tv(&tv);
7149 goto failret;
7151 item = dictitem_alloc(key);
7152 clear_tv(&tvkey);
7153 if (item != NULL)
7155 item->di_tv = tv;
7156 item->di_tv.v_lock = 0;
7157 if (dict_add(d, item) == FAIL)
7158 dictitem_free(item);
7162 if (**arg == '}')
7163 break;
7164 if (**arg != ',')
7166 EMSG2(_("E722: Missing comma in Dictionary: %s"), *arg);
7167 goto failret;
7169 *arg = skipwhite(*arg + 1);
7172 if (**arg != '}')
7174 EMSG2(_("E723: Missing end of Dictionary '}': %s"), *arg);
7175 failret:
7176 if (evaluate)
7177 dict_free(d, TRUE);
7178 return FAIL;
7181 *arg = skipwhite(*arg + 1);
7182 if (evaluate)
7184 rettv->v_type = VAR_DICT;
7185 rettv->vval.v_dict = d;
7186 ++d->dv_refcount;
7189 return OK;
7193 * Return a string with the string representation of a variable.
7194 * If the memory is allocated "tofree" is set to it, otherwise NULL.
7195 * "numbuf" is used for a number.
7196 * Does not put quotes around strings, as ":echo" displays values.
7197 * When "copyID" is not NULL replace recursive lists and dicts with "...".
7198 * May return NULL.
7200 static char_u *
7201 echo_string(tv, tofree, numbuf, copyID)
7202 typval_T *tv;
7203 char_u **tofree;
7204 char_u *numbuf;
7205 int copyID;
7207 static int recurse = 0;
7208 char_u *r = NULL;
7210 if (recurse >= DICT_MAXNEST)
7212 EMSG(_("E724: variable nested too deep for displaying"));
7213 *tofree = NULL;
7214 return NULL;
7216 ++recurse;
7218 switch (tv->v_type)
7220 case VAR_FUNC:
7221 *tofree = NULL;
7222 r = tv->vval.v_string;
7223 break;
7225 case VAR_LIST:
7226 if (tv->vval.v_list == NULL)
7228 *tofree = NULL;
7229 r = NULL;
7231 else if (copyID != 0 && tv->vval.v_list->lv_copyID == copyID)
7233 *tofree = NULL;
7234 r = (char_u *)"[...]";
7236 else
7238 tv->vval.v_list->lv_copyID = copyID;
7239 *tofree = list2string(tv, copyID);
7240 r = *tofree;
7242 break;
7244 case VAR_DICT:
7245 if (tv->vval.v_dict == NULL)
7247 *tofree = NULL;
7248 r = NULL;
7250 else if (copyID != 0 && tv->vval.v_dict->dv_copyID == copyID)
7252 *tofree = NULL;
7253 r = (char_u *)"{...}";
7255 else
7257 tv->vval.v_dict->dv_copyID = copyID;
7258 *tofree = dict2string(tv, copyID);
7259 r = *tofree;
7261 break;
7263 case VAR_STRING:
7264 case VAR_NUMBER:
7265 *tofree = NULL;
7266 r = get_tv_string_buf(tv, numbuf);
7267 break;
7269 #ifdef FEAT_FLOAT
7270 case VAR_FLOAT:
7271 *tofree = NULL;
7272 vim_snprintf((char *)numbuf, NUMBUFLEN, "%g", tv->vval.v_float);
7273 r = numbuf;
7274 break;
7275 #endif
7277 default:
7278 EMSG2(_(e_intern2), "echo_string()");
7279 *tofree = NULL;
7282 --recurse;
7283 return r;
7287 * Return a string with the string representation of a variable.
7288 * If the memory is allocated "tofree" is set to it, otherwise NULL.
7289 * "numbuf" is used for a number.
7290 * Puts quotes around strings, so that they can be parsed back by eval().
7291 * May return NULL.
7293 static char_u *
7294 tv2string(tv, tofree, numbuf, copyID)
7295 typval_T *tv;
7296 char_u **tofree;
7297 char_u *numbuf;
7298 int copyID;
7300 switch (tv->v_type)
7302 case VAR_FUNC:
7303 *tofree = string_quote(tv->vval.v_string, TRUE);
7304 return *tofree;
7305 case VAR_STRING:
7306 *tofree = string_quote(tv->vval.v_string, FALSE);
7307 return *tofree;
7308 #ifdef FEAT_FLOAT
7309 case VAR_FLOAT:
7310 *tofree = NULL;
7311 vim_snprintf((char *)numbuf, NUMBUFLEN - 1, "%g", tv->vval.v_float);
7312 return numbuf;
7313 #endif
7314 case VAR_NUMBER:
7315 case VAR_LIST:
7316 case VAR_DICT:
7317 break;
7318 default:
7319 EMSG2(_(e_intern2), "tv2string()");
7321 return echo_string(tv, tofree, numbuf, copyID);
7325 * Return string "str" in ' quotes, doubling ' characters.
7326 * If "str" is NULL an empty string is assumed.
7327 * If "function" is TRUE make it function('string').
7329 static char_u *
7330 string_quote(str, function)
7331 char_u *str;
7332 int function;
7334 unsigned len;
7335 char_u *p, *r, *s;
7337 len = (function ? 13 : 3);
7338 if (str != NULL)
7340 len += (unsigned)STRLEN(str);
7341 for (p = str; *p != NUL; mb_ptr_adv(p))
7342 if (*p == '\'')
7343 ++len;
7345 s = r = alloc(len);
7346 if (r != NULL)
7348 if (function)
7350 STRCPY(r, "function('");
7351 r += 10;
7353 else
7354 *r++ = '\'';
7355 if (str != NULL)
7356 for (p = str; *p != NUL; )
7358 if (*p == '\'')
7359 *r++ = '\'';
7360 MB_COPY_CHAR(p, r);
7362 *r++ = '\'';
7363 if (function)
7364 *r++ = ')';
7365 *r++ = NUL;
7367 return s;
7370 #ifdef FEAT_FLOAT
7372 * Convert the string "text" to a floating point number.
7373 * This uses strtod(). setlocale(LC_NUMERIC, "C") has been used to make sure
7374 * this always uses a decimal point.
7375 * Returns the length of the text that was consumed.
7377 static int
7378 string2float(text, value)
7379 char_u *text;
7380 float_T *value; /* result stored here */
7382 char *s = (char *)text;
7383 float_T f;
7385 f = strtod(s, &s);
7386 *value = f;
7387 return (int)((char_u *)s - text);
7389 #endif
7392 * Get the value of an environment variable.
7393 * "arg" is pointing to the '$'. It is advanced to after the name.
7394 * If the environment variable was not set, silently assume it is empty.
7395 * Always return OK.
7397 static int
7398 get_env_tv(arg, rettv, evaluate)
7399 char_u **arg;
7400 typval_T *rettv;
7401 int evaluate;
7403 char_u *string = NULL;
7404 int len;
7405 int cc;
7406 char_u *name;
7407 int mustfree = FALSE;
7409 ++*arg;
7410 name = *arg;
7411 len = get_env_len(arg);
7412 if (evaluate)
7414 if (len != 0)
7416 cc = name[len];
7417 name[len] = NUL;
7418 /* first try vim_getenv(), fast for normal environment vars */
7419 string = vim_getenv(name, &mustfree);
7420 if (string != NULL && *string != NUL)
7422 if (!mustfree)
7423 string = vim_strsave(string);
7425 else
7427 if (mustfree)
7428 vim_free(string);
7430 /* next try expanding things like $VIM and ${HOME} */
7431 string = expand_env_save(name - 1);
7432 if (string != NULL && *string == '$')
7434 vim_free(string);
7435 string = NULL;
7438 name[len] = cc;
7440 rettv->v_type = VAR_STRING;
7441 rettv->vval.v_string = string;
7444 return OK;
7448 * Array with names and number of arguments of all internal functions
7449 * MUST BE KEPT SORTED IN strcmp() ORDER FOR BINARY SEARCH!
7451 static struct fst
7453 char *f_name; /* function name */
7454 char f_min_argc; /* minimal number of arguments */
7455 char f_max_argc; /* maximal number of arguments */
7456 void (*f_func) __ARGS((typval_T *args, typval_T *rvar));
7457 /* implementation of function */
7458 } functions[] =
7460 #ifdef FEAT_FLOAT
7461 {"abs", 1, 1, f_abs},
7462 #endif
7463 {"add", 2, 2, f_add},
7464 {"append", 2, 2, f_append},
7465 {"argc", 0, 0, f_argc},
7466 {"argidx", 0, 0, f_argidx},
7467 {"argv", 0, 1, f_argv},
7468 #ifdef FEAT_FLOAT
7469 {"atan", 1, 1, f_atan},
7470 #endif
7471 {"browse", 4, 4, f_browse},
7472 {"browsedir", 2, 2, f_browsedir},
7473 {"bufexists", 1, 1, f_bufexists},
7474 {"buffer_exists", 1, 1, f_bufexists}, /* obsolete */
7475 {"buffer_name", 1, 1, f_bufname}, /* obsolete */
7476 {"buffer_number", 1, 1, f_bufnr}, /* obsolete */
7477 {"buflisted", 1, 1, f_buflisted},
7478 {"bufloaded", 1, 1, f_bufloaded},
7479 {"bufname", 1, 1, f_bufname},
7480 {"bufnr", 1, 2, f_bufnr},
7481 {"bufwinnr", 1, 1, f_bufwinnr},
7482 {"byte2line", 1, 1, f_byte2line},
7483 {"byteidx", 2, 2, f_byteidx},
7484 {"call", 2, 3, f_call},
7485 #ifdef FEAT_FLOAT
7486 {"ceil", 1, 1, f_ceil},
7487 #endif
7488 {"changenr", 0, 0, f_changenr},
7489 {"char2nr", 1, 1, f_char2nr},
7490 {"cindent", 1, 1, f_cindent},
7491 {"clearmatches", 0, 0, f_clearmatches},
7492 {"col", 1, 1, f_col},
7493 #if defined(FEAT_INS_EXPAND)
7494 {"complete", 2, 2, f_complete},
7495 {"complete_add", 1, 1, f_complete_add},
7496 {"complete_check", 0, 0, f_complete_check},
7497 #endif
7498 {"confirm", 1, 4, f_confirm},
7499 {"copy", 1, 1, f_copy},
7500 #ifdef FEAT_FLOAT
7501 {"cos", 1, 1, f_cos},
7502 #endif
7503 {"count", 2, 4, f_count},
7504 {"cscope_connection",0,3, f_cscope_connection},
7505 {"cursor", 1, 3, f_cursor},
7506 {"deepcopy", 1, 2, f_deepcopy},
7507 {"delete", 1, 1, f_delete},
7508 {"did_filetype", 0, 0, f_did_filetype},
7509 {"diff_filler", 1, 1, f_diff_filler},
7510 {"diff_hlID", 2, 2, f_diff_hlID},
7511 {"empty", 1, 1, f_empty},
7512 {"escape", 2, 2, f_escape},
7513 {"eval", 1, 1, f_eval},
7514 {"eventhandler", 0, 0, f_eventhandler},
7515 {"executable", 1, 1, f_executable},
7516 {"exists", 1, 1, f_exists},
7517 {"expand", 1, 2, f_expand},
7518 {"extend", 2, 3, f_extend},
7519 {"feedkeys", 1, 2, f_feedkeys},
7520 {"file_readable", 1, 1, f_filereadable}, /* obsolete */
7521 {"filereadable", 1, 1, f_filereadable},
7522 {"filewritable", 1, 1, f_filewritable},
7523 {"filter", 2, 2, f_filter},
7524 {"finddir", 1, 3, f_finddir},
7525 {"findfile", 1, 3, f_findfile},
7526 #ifdef FEAT_FLOAT
7527 {"float2nr", 1, 1, f_float2nr},
7528 {"floor", 1, 1, f_floor},
7529 #endif
7530 {"fnameescape", 1, 1, f_fnameescape},
7531 {"fnamemodify", 2, 2, f_fnamemodify},
7532 {"foldclosed", 1, 1, f_foldclosed},
7533 {"foldclosedend", 1, 1, f_foldclosedend},
7534 {"foldlevel", 1, 1, f_foldlevel},
7535 {"foldtext", 0, 0, f_foldtext},
7536 {"foldtextresult", 1, 1, f_foldtextresult},
7537 {"foreground", 0, 0, f_foreground},
7538 {"function", 1, 1, f_function},
7539 {"garbagecollect", 0, 1, f_garbagecollect},
7540 {"get", 2, 3, f_get},
7541 {"getbufline", 2, 3, f_getbufline},
7542 {"getbufvar", 2, 2, f_getbufvar},
7543 {"getchar", 0, 1, f_getchar},
7544 {"getcharmod", 0, 0, f_getcharmod},
7545 {"getcmdline", 0, 0, f_getcmdline},
7546 {"getcmdpos", 0, 0, f_getcmdpos},
7547 {"getcmdtype", 0, 0, f_getcmdtype},
7548 {"getcwd", 0, 0, f_getcwd},
7549 {"getfontname", 0, 1, f_getfontname},
7550 {"getfperm", 1, 1, f_getfperm},
7551 {"getfsize", 1, 1, f_getfsize},
7552 {"getftime", 1, 1, f_getftime},
7553 {"getftype", 1, 1, f_getftype},
7554 {"getline", 1, 2, f_getline},
7555 {"getloclist", 1, 1, f_getqflist},
7556 {"getmatches", 0, 0, f_getmatches},
7557 {"getpid", 0, 0, f_getpid},
7558 {"getpos", 1, 1, f_getpos},
7559 {"getqflist", 0, 0, f_getqflist},
7560 {"getreg", 0, 2, f_getreg},
7561 {"getregtype", 0, 1, f_getregtype},
7562 {"gettabwinvar", 3, 3, f_gettabwinvar},
7563 {"getwinposx", 0, 0, f_getwinposx},
7564 {"getwinposy", 0, 0, f_getwinposy},
7565 {"getwinvar", 2, 2, f_getwinvar},
7566 {"glob", 1, 1, f_glob},
7567 {"globpath", 2, 2, f_globpath},
7568 {"has", 1, 1, f_has},
7569 {"has_key", 2, 2, f_has_key},
7570 {"haslocaldir", 0, 0, f_haslocaldir},
7571 {"hasmapto", 1, 3, f_hasmapto},
7572 {"highlightID", 1, 1, f_hlID}, /* obsolete */
7573 {"highlight_exists",1, 1, f_hlexists}, /* obsolete */
7574 {"histadd", 2, 2, f_histadd},
7575 {"histdel", 1, 2, f_histdel},
7576 {"histget", 1, 2, f_histget},
7577 {"histnr", 1, 1, f_histnr},
7578 {"hlID", 1, 1, f_hlID},
7579 {"hlexists", 1, 1, f_hlexists},
7580 {"hostname", 0, 0, f_hostname},
7581 {"iconv", 3, 3, f_iconv},
7582 {"indent", 1, 1, f_indent},
7583 {"index", 2, 4, f_index},
7584 {"input", 1, 3, f_input},
7585 {"inputdialog", 1, 3, f_inputdialog},
7586 {"inputlist", 1, 1, f_inputlist},
7587 {"inputrestore", 0, 0, f_inputrestore},
7588 {"inputsave", 0, 0, f_inputsave},
7589 {"inputsecret", 1, 2, f_inputsecret},
7590 {"insert", 2, 3, f_insert},
7591 {"isdirectory", 1, 1, f_isdirectory},
7592 {"islocked", 1, 1, f_islocked},
7593 {"items", 1, 1, f_items},
7594 {"join", 1, 2, f_join},
7595 {"keys", 1, 1, f_keys},
7596 {"last_buffer_nr", 0, 0, f_last_buffer_nr},/* obsolete */
7597 {"len", 1, 1, f_len},
7598 {"libcall", 3, 3, f_libcall},
7599 {"libcallnr", 3, 3, f_libcallnr},
7600 {"line", 1, 1, f_line},
7601 {"line2byte", 1, 1, f_line2byte},
7602 {"lispindent", 1, 1, f_lispindent},
7603 {"localtime", 0, 0, f_localtime},
7604 #ifdef FEAT_FLOAT
7605 {"log10", 1, 1, f_log10},
7606 #endif
7607 {"map", 2, 2, f_map},
7608 {"maparg", 1, 3, f_maparg},
7609 {"mapcheck", 1, 3, f_mapcheck},
7610 {"match", 2, 4, f_match},
7611 {"matchadd", 2, 4, f_matchadd},
7612 {"matcharg", 1, 1, f_matcharg},
7613 {"matchdelete", 1, 1, f_matchdelete},
7614 {"matchend", 2, 4, f_matchend},
7615 {"matchlist", 2, 4, f_matchlist},
7616 {"matchstr", 2, 4, f_matchstr},
7617 {"max", 1, 1, f_max},
7618 {"min", 1, 1, f_min},
7619 #ifdef vim_mkdir
7620 {"mkdir", 1, 3, f_mkdir},
7621 #endif
7622 {"mode", 0, 1, f_mode},
7623 {"nextnonblank", 1, 1, f_nextnonblank},
7624 {"nr2char", 1, 1, f_nr2char},
7625 {"pathshorten", 1, 1, f_pathshorten},
7626 #ifdef FEAT_FLOAT
7627 {"pow", 2, 2, f_pow},
7628 #endif
7629 {"prevnonblank", 1, 1, f_prevnonblank},
7630 {"printf", 2, 19, f_printf},
7631 {"pumvisible", 0, 0, f_pumvisible},
7632 {"range", 1, 3, f_range},
7633 {"readfile", 1, 3, f_readfile},
7634 {"reltime", 0, 2, f_reltime},
7635 {"reltimestr", 1, 1, f_reltimestr},
7636 {"remote_expr", 2, 3, f_remote_expr},
7637 {"remote_foreground", 1, 1, f_remote_foreground},
7638 {"remote_peek", 1, 2, f_remote_peek},
7639 {"remote_read", 1, 1, f_remote_read},
7640 {"remote_send", 2, 3, f_remote_send},
7641 {"remove", 2, 3, f_remove},
7642 {"rename", 2, 2, f_rename},
7643 {"repeat", 2, 2, f_repeat},
7644 {"resolve", 1, 1, f_resolve},
7645 {"reverse", 1, 1, f_reverse},
7646 #ifdef FEAT_FLOAT
7647 {"round", 1, 1, f_round},
7648 #endif
7649 {"search", 1, 4, f_search},
7650 {"searchdecl", 1, 3, f_searchdecl},
7651 {"searchpair", 3, 7, f_searchpair},
7652 {"searchpairpos", 3, 7, f_searchpairpos},
7653 {"searchpos", 1, 4, f_searchpos},
7654 {"server2client", 2, 2, f_server2client},
7655 {"serverlist", 0, 0, f_serverlist},
7656 {"setbufvar", 3, 3, f_setbufvar},
7657 {"setcmdpos", 1, 1, f_setcmdpos},
7658 {"setline", 2, 2, f_setline},
7659 {"setloclist", 2, 3, f_setloclist},
7660 {"setmatches", 1, 1, f_setmatches},
7661 {"setpos", 2, 2, f_setpos},
7662 {"setqflist", 1, 2, f_setqflist},
7663 {"setreg", 2, 3, f_setreg},
7664 {"settabwinvar", 4, 4, f_settabwinvar},
7665 {"setwinvar", 3, 3, f_setwinvar},
7666 {"shellescape", 1, 2, f_shellescape},
7667 {"simplify", 1, 1, f_simplify},
7668 #ifdef FEAT_FLOAT
7669 {"sin", 1, 1, f_sin},
7670 #endif
7671 {"sort", 1, 2, f_sort},
7672 {"soundfold", 1, 1, f_soundfold},
7673 {"spellbadword", 0, 1, f_spellbadword},
7674 {"spellsuggest", 1, 3, f_spellsuggest},
7675 {"split", 1, 3, f_split},
7676 #ifdef FEAT_FLOAT
7677 {"sqrt", 1, 1, f_sqrt},
7678 {"str2float", 1, 1, f_str2float},
7679 #endif
7680 {"str2nr", 1, 2, f_str2nr},
7681 #ifdef HAVE_STRFTIME
7682 {"strftime", 1, 2, f_strftime},
7683 #endif
7684 {"stridx", 2, 3, f_stridx},
7685 {"string", 1, 1, f_string},
7686 {"strlen", 1, 1, f_strlen},
7687 {"strpart", 2, 3, f_strpart},
7688 {"strridx", 2, 3, f_strridx},
7689 {"strtrans", 1, 1, f_strtrans},
7690 {"submatch", 1, 1, f_submatch},
7691 {"substitute", 4, 4, f_substitute},
7692 {"synID", 3, 3, f_synID},
7693 {"synIDattr", 2, 3, f_synIDattr},
7694 {"synIDtrans", 1, 1, f_synIDtrans},
7695 {"synstack", 2, 2, f_synstack},
7696 {"system", 1, 2, f_system},
7697 {"tabpagebuflist", 0, 1, f_tabpagebuflist},
7698 {"tabpagenr", 0, 1, f_tabpagenr},
7699 {"tabpagewinnr", 1, 2, f_tabpagewinnr},
7700 {"tagfiles", 0, 0, f_tagfiles},
7701 {"taglist", 1, 1, f_taglist},
7702 {"tempname", 0, 0, f_tempname},
7703 {"test", 1, 1, f_test},
7704 {"tolower", 1, 1, f_tolower},
7705 {"toupper", 1, 1, f_toupper},
7706 {"tr", 3, 3, f_tr},
7707 #ifdef FEAT_FLOAT
7708 {"trunc", 1, 1, f_trunc},
7709 #endif
7710 {"type", 1, 1, f_type},
7711 {"values", 1, 1, f_values},
7712 {"virtcol", 1, 1, f_virtcol},
7713 {"visualmode", 0, 1, f_visualmode},
7714 {"winbufnr", 1, 1, f_winbufnr},
7715 {"wincol", 0, 0, f_wincol},
7716 {"winheight", 1, 1, f_winheight},
7717 {"winline", 0, 0, f_winline},
7718 {"winnr", 0, 1, f_winnr},
7719 {"winrestcmd", 0, 0, f_winrestcmd},
7720 {"winrestview", 1, 1, f_winrestview},
7721 {"winsaveview", 0, 0, f_winsaveview},
7722 {"winwidth", 1, 1, f_winwidth},
7723 {"writefile", 2, 3, f_writefile},
7726 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
7729 * Function given to ExpandGeneric() to obtain the list of internal
7730 * or user defined function names.
7732 char_u *
7733 get_function_name(xp, idx)
7734 expand_T *xp;
7735 int idx;
7737 static int intidx = -1;
7738 char_u *name;
7740 if (idx == 0)
7741 intidx = -1;
7742 if (intidx < 0)
7744 name = get_user_func_name(xp, idx);
7745 if (name != NULL)
7746 return name;
7748 if (++intidx < (int)(sizeof(functions) / sizeof(struct fst)))
7750 STRCPY(IObuff, functions[intidx].f_name);
7751 STRCAT(IObuff, "(");
7752 if (functions[intidx].f_max_argc == 0)
7753 STRCAT(IObuff, ")");
7754 return IObuff;
7757 return NULL;
7761 * Function given to ExpandGeneric() to obtain the list of internal or
7762 * user defined variable or function names.
7764 /*ARGSUSED*/
7765 char_u *
7766 get_expr_name(xp, idx)
7767 expand_T *xp;
7768 int idx;
7770 static int intidx = -1;
7771 char_u *name;
7773 if (idx == 0)
7774 intidx = -1;
7775 if (intidx < 0)
7777 name = get_function_name(xp, idx);
7778 if (name != NULL)
7779 return name;
7781 return get_user_var_name(xp, ++intidx);
7784 #endif /* FEAT_CMDL_COMPL */
7787 * Find internal function in table above.
7788 * Return index, or -1 if not found
7790 static int
7791 find_internal_func(name)
7792 char_u *name; /* name of the function */
7794 int first = 0;
7795 int last = (int)(sizeof(functions) / sizeof(struct fst)) - 1;
7796 int cmp;
7797 int x;
7800 * Find the function name in the table. Binary search.
7802 while (first <= last)
7804 x = first + ((unsigned)(last - first) >> 1);
7805 cmp = STRCMP(name, functions[x].f_name);
7806 if (cmp < 0)
7807 last = x - 1;
7808 else if (cmp > 0)
7809 first = x + 1;
7810 else
7811 return x;
7813 return -1;
7817 * Check if "name" is a variable of type VAR_FUNC. If so, return the function
7818 * name it contains, otherwise return "name".
7820 static char_u *
7821 deref_func_name(name, lenp)
7822 char_u *name;
7823 int *lenp;
7825 dictitem_T *v;
7826 int cc;
7828 cc = name[*lenp];
7829 name[*lenp] = NUL;
7830 v = find_var(name, NULL);
7831 name[*lenp] = cc;
7832 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
7834 if (v->di_tv.vval.v_string == NULL)
7836 *lenp = 0;
7837 return (char_u *)""; /* just in case */
7839 *lenp = (int)STRLEN(v->di_tv.vval.v_string);
7840 return v->di_tv.vval.v_string;
7843 return name;
7847 * Allocate a variable for the result of a function.
7848 * Return OK or FAIL.
7850 static int
7851 get_func_tv(name, len, rettv, arg, firstline, lastline, doesrange,
7852 evaluate, selfdict)
7853 char_u *name; /* name of the function */
7854 int len; /* length of "name" */
7855 typval_T *rettv;
7856 char_u **arg; /* argument, pointing to the '(' */
7857 linenr_T firstline; /* first line of range */
7858 linenr_T lastline; /* last line of range */
7859 int *doesrange; /* return: function handled range */
7860 int evaluate;
7861 dict_T *selfdict; /* Dictionary for "self" */
7863 char_u *argp;
7864 int ret = OK;
7865 typval_T argvars[MAX_FUNC_ARGS + 1]; /* vars for arguments */
7866 int argcount = 0; /* number of arguments found */
7869 * Get the arguments.
7871 argp = *arg;
7872 while (argcount < MAX_FUNC_ARGS)
7874 argp = skipwhite(argp + 1); /* skip the '(' or ',' */
7875 if (*argp == ')' || *argp == ',' || *argp == NUL)
7876 break;
7877 if (eval1(&argp, &argvars[argcount], evaluate) == FAIL)
7879 ret = FAIL;
7880 break;
7882 ++argcount;
7883 if (*argp != ',')
7884 break;
7886 if (*argp == ')')
7887 ++argp;
7888 else
7889 ret = FAIL;
7891 if (ret == OK)
7892 ret = call_func(name, len, rettv, argcount, argvars,
7893 firstline, lastline, doesrange, evaluate, selfdict);
7894 else if (!aborting())
7896 if (argcount == MAX_FUNC_ARGS)
7897 emsg_funcname("E740: Too many arguments for function %s", name);
7898 else
7899 emsg_funcname("E116: Invalid arguments for function %s", name);
7902 while (--argcount >= 0)
7903 clear_tv(&argvars[argcount]);
7905 *arg = skipwhite(argp);
7906 return ret;
7911 * Call a function with its resolved parameters
7912 * Return OK when the function can't be called, FAIL otherwise.
7913 * Also returns OK when an error was encountered while executing the function.
7915 static int
7916 call_func(name, len, rettv, argcount, argvars, firstline, lastline,
7917 doesrange, evaluate, selfdict)
7918 char_u *name; /* name of the function */
7919 int len; /* length of "name" */
7920 typval_T *rettv; /* return value goes here */
7921 int argcount; /* number of "argvars" */
7922 typval_T *argvars; /* vars for arguments, must have "argcount"
7923 PLUS ONE elements! */
7924 linenr_T firstline; /* first line of range */
7925 linenr_T lastline; /* last line of range */
7926 int *doesrange; /* return: function handled range */
7927 int evaluate;
7928 dict_T *selfdict; /* Dictionary for "self" */
7930 int ret = FAIL;
7931 #define ERROR_UNKNOWN 0
7932 #define ERROR_TOOMANY 1
7933 #define ERROR_TOOFEW 2
7934 #define ERROR_SCRIPT 3
7935 #define ERROR_DICT 4
7936 #define ERROR_NONE 5
7937 #define ERROR_OTHER 6
7938 int error = ERROR_NONE;
7939 int i;
7940 int llen;
7941 ufunc_T *fp;
7942 int cc;
7943 #define FLEN_FIXED 40
7944 char_u fname_buf[FLEN_FIXED + 1];
7945 char_u *fname;
7948 * In a script change <SID>name() and s:name() to K_SNR 123_name().
7949 * Change <SNR>123_name() to K_SNR 123_name().
7950 * Use fname_buf[] when it fits, otherwise allocate memory (slow).
7952 cc = name[len];
7953 name[len] = NUL;
7954 llen = eval_fname_script(name);
7955 if (llen > 0)
7957 fname_buf[0] = K_SPECIAL;
7958 fname_buf[1] = KS_EXTRA;
7959 fname_buf[2] = (int)KE_SNR;
7960 i = 3;
7961 if (eval_fname_sid(name)) /* "<SID>" or "s:" */
7963 if (current_SID <= 0)
7964 error = ERROR_SCRIPT;
7965 else
7967 sprintf((char *)fname_buf + 3, "%ld_", (long)current_SID);
7968 i = (int)STRLEN(fname_buf);
7971 if (i + STRLEN(name + llen) < FLEN_FIXED)
7973 STRCPY(fname_buf + i, name + llen);
7974 fname = fname_buf;
7976 else
7978 fname = alloc((unsigned)(i + STRLEN(name + llen) + 1));
7979 if (fname == NULL)
7980 error = ERROR_OTHER;
7981 else
7983 mch_memmove(fname, fname_buf, (size_t)i);
7984 STRCPY(fname + i, name + llen);
7988 else
7989 fname = name;
7991 *doesrange = FALSE;
7994 /* execute the function if no errors detected and executing */
7995 if (evaluate && error == ERROR_NONE)
7997 rettv->v_type = VAR_NUMBER; /* default is number rettv */
7998 error = ERROR_UNKNOWN;
8000 if (!builtin_function(fname))
8003 * User defined function.
8005 fp = find_func(fname);
8007 #ifdef FEAT_AUTOCMD
8008 /* Trigger FuncUndefined event, may load the function. */
8009 if (fp == NULL
8010 && apply_autocmds(EVENT_FUNCUNDEFINED,
8011 fname, fname, TRUE, NULL)
8012 && !aborting())
8014 /* executed an autocommand, search for the function again */
8015 fp = find_func(fname);
8017 #endif
8018 /* Try loading a package. */
8019 if (fp == NULL && script_autoload(fname, TRUE) && !aborting())
8021 /* loaded a package, search for the function again */
8022 fp = find_func(fname);
8025 if (fp != NULL)
8027 if (fp->uf_flags & FC_RANGE)
8028 *doesrange = TRUE;
8029 if (argcount < fp->uf_args.ga_len)
8030 error = ERROR_TOOFEW;
8031 else if (!fp->uf_varargs && argcount > fp->uf_args.ga_len)
8032 error = ERROR_TOOMANY;
8033 else if ((fp->uf_flags & FC_DICT) && selfdict == NULL)
8034 error = ERROR_DICT;
8035 else
8038 * Call the user function.
8039 * Save and restore search patterns, script variables and
8040 * redo buffer.
8042 save_search_patterns();
8043 saveRedobuff();
8044 ++fp->uf_calls;
8045 call_user_func(fp, argcount, argvars, rettv,
8046 firstline, lastline,
8047 (fp->uf_flags & FC_DICT) ? selfdict : NULL);
8048 if (--fp->uf_calls <= 0 && isdigit(*fp->uf_name)
8049 && fp->uf_refcount <= 0)
8050 /* Function was unreferenced while being used, free it
8051 * now. */
8052 func_free(fp);
8053 restoreRedobuff();
8054 restore_search_patterns();
8055 error = ERROR_NONE;
8059 else
8062 * Find the function name in the table, call its implementation.
8064 i = find_internal_func(fname);
8065 if (i >= 0)
8067 if (argcount < functions[i].f_min_argc)
8068 error = ERROR_TOOFEW;
8069 else if (argcount > functions[i].f_max_argc)
8070 error = ERROR_TOOMANY;
8071 else
8073 argvars[argcount].v_type = VAR_UNKNOWN;
8074 functions[i].f_func(argvars, rettv);
8075 error = ERROR_NONE;
8080 * The function call (or "FuncUndefined" autocommand sequence) might
8081 * have been aborted by an error, an interrupt, or an explicitly thrown
8082 * exception that has not been caught so far. This situation can be
8083 * tested for by calling aborting(). For an error in an internal
8084 * function or for the "E132" error in call_user_func(), however, the
8085 * throw point at which the "force_abort" flag (temporarily reset by
8086 * emsg()) is normally updated has not been reached yet. We need to
8087 * update that flag first to make aborting() reliable.
8089 update_force_abort();
8091 if (error == ERROR_NONE)
8092 ret = OK;
8095 * Report an error unless the argument evaluation or function call has been
8096 * cancelled due to an aborting error, an interrupt, or an exception.
8098 if (!aborting())
8100 switch (error)
8102 case ERROR_UNKNOWN:
8103 emsg_funcname(N_("E117: Unknown function: %s"), name);
8104 break;
8105 case ERROR_TOOMANY:
8106 emsg_funcname(e_toomanyarg, name);
8107 break;
8108 case ERROR_TOOFEW:
8109 emsg_funcname(N_("E119: Not enough arguments for function: %s"),
8110 name);
8111 break;
8112 case ERROR_SCRIPT:
8113 emsg_funcname(N_("E120: Using <SID> not in a script context: %s"),
8114 name);
8115 break;
8116 case ERROR_DICT:
8117 emsg_funcname(N_("E725: Calling dict function without Dictionary: %s"),
8118 name);
8119 break;
8123 name[len] = cc;
8124 if (fname != name && fname != fname_buf)
8125 vim_free(fname);
8127 return ret;
8131 * Give an error message with a function name. Handle <SNR> things.
8133 static void
8134 emsg_funcname(ermsg, name)
8135 char *ermsg;
8136 char_u *name;
8138 char_u *p;
8140 if (*name == K_SPECIAL)
8141 p = concat_str((char_u *)"<SNR>", name + 3);
8142 else
8143 p = name;
8144 EMSG2(_(ermsg), p);
8145 if (p != name)
8146 vim_free(p);
8150 * Return TRUE for a non-zero Number and a non-empty String.
8152 static int
8153 non_zero_arg(argvars)
8154 typval_T *argvars;
8156 return ((argvars[0].v_type == VAR_NUMBER
8157 && argvars[0].vval.v_number != 0)
8158 || (argvars[0].v_type == VAR_STRING
8159 && argvars[0].vval.v_string != NULL
8160 && *argvars[0].vval.v_string != NUL));
8163 /*********************************************
8164 * Implementation of the built-in functions
8167 #ifdef FEAT_FLOAT
8169 * "abs(expr)" function
8171 static void
8172 f_abs(argvars, rettv)
8173 typval_T *argvars;
8174 typval_T *rettv;
8176 if (argvars[0].v_type == VAR_FLOAT)
8178 rettv->v_type = VAR_FLOAT;
8179 rettv->vval.v_float = fabs(argvars[0].vval.v_float);
8181 else
8183 varnumber_T n;
8184 int error = FALSE;
8186 n = get_tv_number_chk(&argvars[0], &error);
8187 if (error)
8188 rettv->vval.v_number = -1;
8189 else if (n > 0)
8190 rettv->vval.v_number = n;
8191 else
8192 rettv->vval.v_number = -n;
8195 #endif
8198 * "add(list, item)" function
8200 static void
8201 f_add(argvars, rettv)
8202 typval_T *argvars;
8203 typval_T *rettv;
8205 list_T *l;
8207 rettv->vval.v_number = 1; /* Default: Failed */
8208 if (argvars[0].v_type == VAR_LIST)
8210 if ((l = argvars[0].vval.v_list) != NULL
8211 && !tv_check_lock(l->lv_lock, (char_u *)"add()")
8212 && list_append_tv(l, &argvars[1]) == OK)
8213 copy_tv(&argvars[0], rettv);
8215 else
8216 EMSG(_(e_listreq));
8220 * "append(lnum, string/list)" function
8222 static void
8223 f_append(argvars, rettv)
8224 typval_T *argvars;
8225 typval_T *rettv;
8227 long lnum;
8228 char_u *line;
8229 list_T *l = NULL;
8230 listitem_T *li = NULL;
8231 typval_T *tv;
8232 long added = 0;
8234 lnum = get_tv_lnum(argvars);
8235 if (lnum >= 0
8236 && lnum <= curbuf->b_ml.ml_line_count
8237 && u_save(lnum, lnum + 1) == OK)
8239 if (argvars[1].v_type == VAR_LIST)
8241 l = argvars[1].vval.v_list;
8242 if (l == NULL)
8243 return;
8244 li = l->lv_first;
8246 rettv->vval.v_number = 0; /* Default: Success */
8247 for (;;)
8249 if (l == NULL)
8250 tv = &argvars[1]; /* append a string */
8251 else if (li == NULL)
8252 break; /* end of list */
8253 else
8254 tv = &li->li_tv; /* append item from list */
8255 line = get_tv_string_chk(tv);
8256 if (line == NULL) /* type error */
8258 rettv->vval.v_number = 1; /* Failed */
8259 break;
8261 ml_append(lnum + added, line, (colnr_T)0, FALSE);
8262 ++added;
8263 if (l == NULL)
8264 break;
8265 li = li->li_next;
8268 appended_lines_mark(lnum, added);
8269 if (curwin->w_cursor.lnum > lnum)
8270 curwin->w_cursor.lnum += added;
8272 else
8273 rettv->vval.v_number = 1; /* Failed */
8277 * "argc()" function
8279 /* ARGSUSED */
8280 static void
8281 f_argc(argvars, rettv)
8282 typval_T *argvars;
8283 typval_T *rettv;
8285 rettv->vval.v_number = ARGCOUNT;
8289 * "argidx()" function
8291 /* ARGSUSED */
8292 static void
8293 f_argidx(argvars, rettv)
8294 typval_T *argvars;
8295 typval_T *rettv;
8297 rettv->vval.v_number = curwin->w_arg_idx;
8301 * "argv(nr)" function
8303 static void
8304 f_argv(argvars, rettv)
8305 typval_T *argvars;
8306 typval_T *rettv;
8308 int idx;
8310 if (argvars[0].v_type != VAR_UNKNOWN)
8312 idx = get_tv_number_chk(&argvars[0], NULL);
8313 if (idx >= 0 && idx < ARGCOUNT)
8314 rettv->vval.v_string = vim_strsave(alist_name(&ARGLIST[idx]));
8315 else
8316 rettv->vval.v_string = NULL;
8317 rettv->v_type = VAR_STRING;
8319 else if (rettv_list_alloc(rettv) == OK)
8320 for (idx = 0; idx < ARGCOUNT; ++idx)
8321 list_append_string(rettv->vval.v_list,
8322 alist_name(&ARGLIST[idx]), -1);
8325 #ifdef FEAT_FLOAT
8326 static int get_float_arg __ARGS((typval_T *argvars, float_T *f));
8329 * Get the float value of "argvars[0]" into "f".
8330 * Returns FAIL when the argument is not a Number or Float.
8332 static int
8333 get_float_arg(argvars, f)
8334 typval_T *argvars;
8335 float_T *f;
8337 if (argvars[0].v_type == VAR_FLOAT)
8339 *f = argvars[0].vval.v_float;
8340 return OK;
8342 if (argvars[0].v_type == VAR_NUMBER)
8344 *f = (float_T)argvars[0].vval.v_number;
8345 return OK;
8347 EMSG(_("E808: Number or Float required"));
8348 return FAIL;
8352 * "atan()" function
8354 static void
8355 f_atan(argvars, rettv)
8356 typval_T *argvars;
8357 typval_T *rettv;
8359 float_T f;
8361 rettv->v_type = VAR_FLOAT;
8362 if (get_float_arg(argvars, &f) == OK)
8363 rettv->vval.v_float = atan(f);
8364 else
8365 rettv->vval.v_float = 0.0;
8367 #endif
8370 * "browse(save, title, initdir, default)" function
8372 /* ARGSUSED */
8373 static void
8374 f_browse(argvars, rettv)
8375 typval_T *argvars;
8376 typval_T *rettv;
8378 #ifdef FEAT_BROWSE
8379 int save;
8380 char_u *title;
8381 char_u *initdir;
8382 char_u *defname;
8383 char_u buf[NUMBUFLEN];
8384 char_u buf2[NUMBUFLEN];
8385 int error = FALSE;
8387 save = get_tv_number_chk(&argvars[0], &error);
8388 title = get_tv_string_chk(&argvars[1]);
8389 initdir = get_tv_string_buf_chk(&argvars[2], buf);
8390 defname = get_tv_string_buf_chk(&argvars[3], buf2);
8392 if (error || title == NULL || initdir == NULL || defname == NULL)
8393 rettv->vval.v_string = NULL;
8394 else
8395 rettv->vval.v_string =
8396 do_browse(save ? BROWSE_SAVE : 0,
8397 title, defname, NULL, initdir, NULL, curbuf);
8398 #else
8399 rettv->vval.v_string = NULL;
8400 #endif
8401 rettv->v_type = VAR_STRING;
8405 * "browsedir(title, initdir)" function
8407 /* ARGSUSED */
8408 static void
8409 f_browsedir(argvars, rettv)
8410 typval_T *argvars;
8411 typval_T *rettv;
8413 #ifdef FEAT_BROWSE
8414 char_u *title;
8415 char_u *initdir;
8416 char_u buf[NUMBUFLEN];
8418 title = get_tv_string_chk(&argvars[0]);
8419 initdir = get_tv_string_buf_chk(&argvars[1], buf);
8421 if (title == NULL || initdir == NULL)
8422 rettv->vval.v_string = NULL;
8423 else
8424 rettv->vval.v_string = do_browse(BROWSE_DIR,
8425 title, NULL, NULL, initdir, NULL, curbuf);
8426 #else
8427 rettv->vval.v_string = NULL;
8428 #endif
8429 rettv->v_type = VAR_STRING;
8432 static buf_T *find_buffer __ARGS((typval_T *avar));
8435 * Find a buffer by number or exact name.
8437 static buf_T *
8438 find_buffer(avar)
8439 typval_T *avar;
8441 buf_T *buf = NULL;
8443 if (avar->v_type == VAR_NUMBER)
8444 buf = buflist_findnr((int)avar->vval.v_number);
8445 else if (avar->v_type == VAR_STRING && avar->vval.v_string != NULL)
8447 buf = buflist_findname_exp(avar->vval.v_string);
8448 if (buf == NULL)
8450 /* No full path name match, try a match with a URL or a "nofile"
8451 * buffer, these don't use the full path. */
8452 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8453 if (buf->b_fname != NULL
8454 && (path_with_url(buf->b_fname)
8455 #ifdef FEAT_QUICKFIX
8456 || bt_nofile(buf)
8457 #endif
8459 && STRCMP(buf->b_fname, avar->vval.v_string) == 0)
8460 break;
8463 return buf;
8467 * "bufexists(expr)" function
8469 static void
8470 f_bufexists(argvars, rettv)
8471 typval_T *argvars;
8472 typval_T *rettv;
8474 rettv->vval.v_number = (find_buffer(&argvars[0]) != NULL);
8478 * "buflisted(expr)" function
8480 static void
8481 f_buflisted(argvars, rettv)
8482 typval_T *argvars;
8483 typval_T *rettv;
8485 buf_T *buf;
8487 buf = find_buffer(&argvars[0]);
8488 rettv->vval.v_number = (buf != NULL && buf->b_p_bl);
8492 * "bufloaded(expr)" function
8494 static void
8495 f_bufloaded(argvars, rettv)
8496 typval_T *argvars;
8497 typval_T *rettv;
8499 buf_T *buf;
8501 buf = find_buffer(&argvars[0]);
8502 rettv->vval.v_number = (buf != NULL && buf->b_ml.ml_mfp != NULL);
8505 static buf_T *get_buf_tv __ARGS((typval_T *tv));
8508 * Get buffer by number or pattern.
8510 static buf_T *
8511 get_buf_tv(tv)
8512 typval_T *tv;
8514 char_u *name = tv->vval.v_string;
8515 int save_magic;
8516 char_u *save_cpo;
8517 buf_T *buf;
8519 if (tv->v_type == VAR_NUMBER)
8520 return buflist_findnr((int)tv->vval.v_number);
8521 if (tv->v_type != VAR_STRING)
8522 return NULL;
8523 if (name == NULL || *name == NUL)
8524 return curbuf;
8525 if (name[0] == '$' && name[1] == NUL)
8526 return lastbuf;
8528 /* Ignore 'magic' and 'cpoptions' here to make scripts portable */
8529 save_magic = p_magic;
8530 p_magic = TRUE;
8531 save_cpo = p_cpo;
8532 p_cpo = (char_u *)"";
8534 buf = buflist_findnr(buflist_findpat(name, name + STRLEN(name),
8535 TRUE, FALSE));
8537 p_magic = save_magic;
8538 p_cpo = save_cpo;
8540 /* If not found, try expanding the name, like done for bufexists(). */
8541 if (buf == NULL)
8542 buf = find_buffer(tv);
8544 return buf;
8548 * "bufname(expr)" function
8550 static void
8551 f_bufname(argvars, rettv)
8552 typval_T *argvars;
8553 typval_T *rettv;
8555 buf_T *buf;
8557 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8558 ++emsg_off;
8559 buf = get_buf_tv(&argvars[0]);
8560 rettv->v_type = VAR_STRING;
8561 if (buf != NULL && buf->b_fname != NULL)
8562 rettv->vval.v_string = vim_strsave(buf->b_fname);
8563 else
8564 rettv->vval.v_string = NULL;
8565 --emsg_off;
8569 * "bufnr(expr)" function
8571 static void
8572 f_bufnr(argvars, rettv)
8573 typval_T *argvars;
8574 typval_T *rettv;
8576 buf_T *buf;
8577 int error = FALSE;
8578 char_u *name;
8580 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8581 ++emsg_off;
8582 buf = get_buf_tv(&argvars[0]);
8583 --emsg_off;
8585 /* If the buffer isn't found and the second argument is not zero create a
8586 * new buffer. */
8587 if (buf == NULL
8588 && argvars[1].v_type != VAR_UNKNOWN
8589 && get_tv_number_chk(&argvars[1], &error) != 0
8590 && !error
8591 && (name = get_tv_string_chk(&argvars[0])) != NULL
8592 && !error)
8593 buf = buflist_new(name, NULL, (linenr_T)1, 0);
8595 if (buf != NULL)
8596 rettv->vval.v_number = buf->b_fnum;
8597 else
8598 rettv->vval.v_number = -1;
8602 * "bufwinnr(nr)" function
8604 static void
8605 f_bufwinnr(argvars, rettv)
8606 typval_T *argvars;
8607 typval_T *rettv;
8609 #ifdef FEAT_WINDOWS
8610 win_T *wp;
8611 int winnr = 0;
8612 #endif
8613 buf_T *buf;
8615 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8616 ++emsg_off;
8617 buf = get_buf_tv(&argvars[0]);
8618 #ifdef FEAT_WINDOWS
8619 for (wp = firstwin; wp; wp = wp->w_next)
8621 ++winnr;
8622 if (wp->w_buffer == buf)
8623 break;
8625 rettv->vval.v_number = (wp != NULL ? winnr : -1);
8626 #else
8627 rettv->vval.v_number = (curwin->w_buffer == buf ? 1 : -1);
8628 #endif
8629 --emsg_off;
8633 * "byte2line(byte)" function
8635 /*ARGSUSED*/
8636 static void
8637 f_byte2line(argvars, rettv)
8638 typval_T *argvars;
8639 typval_T *rettv;
8641 #ifndef FEAT_BYTEOFF
8642 rettv->vval.v_number = -1;
8643 #else
8644 long boff = 0;
8646 boff = get_tv_number(&argvars[0]) - 1; /* boff gets -1 on type error */
8647 if (boff < 0)
8648 rettv->vval.v_number = -1;
8649 else
8650 rettv->vval.v_number = ml_find_line_or_offset(curbuf,
8651 (linenr_T)0, &boff);
8652 #endif
8656 * "byteidx()" function
8658 /*ARGSUSED*/
8659 static void
8660 f_byteidx(argvars, rettv)
8661 typval_T *argvars;
8662 typval_T *rettv;
8664 #ifdef FEAT_MBYTE
8665 char_u *t;
8666 #endif
8667 char_u *str;
8668 long idx;
8670 str = get_tv_string_chk(&argvars[0]);
8671 idx = get_tv_number_chk(&argvars[1], NULL);
8672 rettv->vval.v_number = -1;
8673 if (str == NULL || idx < 0)
8674 return;
8676 #ifdef FEAT_MBYTE
8677 t = str;
8678 for ( ; idx > 0; idx--)
8680 if (*t == NUL) /* EOL reached */
8681 return;
8682 t += (*mb_ptr2len)(t);
8684 rettv->vval.v_number = (varnumber_T)(t - str);
8685 #else
8686 if ((size_t)idx <= STRLEN(str))
8687 rettv->vval.v_number = idx;
8688 #endif
8692 * "call(func, arglist)" function
8694 static void
8695 f_call(argvars, rettv)
8696 typval_T *argvars;
8697 typval_T *rettv;
8699 char_u *func;
8700 typval_T argv[MAX_FUNC_ARGS + 1];
8701 int argc = 0;
8702 listitem_T *item;
8703 int dummy;
8704 dict_T *selfdict = NULL;
8706 rettv->vval.v_number = 0;
8707 if (argvars[1].v_type != VAR_LIST)
8709 EMSG(_(e_listreq));
8710 return;
8712 if (argvars[1].vval.v_list == NULL)
8713 return;
8715 if (argvars[0].v_type == VAR_FUNC)
8716 func = argvars[0].vval.v_string;
8717 else
8718 func = get_tv_string(&argvars[0]);
8719 if (*func == NUL)
8720 return; /* type error or empty name */
8722 if (argvars[2].v_type != VAR_UNKNOWN)
8724 if (argvars[2].v_type != VAR_DICT)
8726 EMSG(_(e_dictreq));
8727 return;
8729 selfdict = argvars[2].vval.v_dict;
8732 for (item = argvars[1].vval.v_list->lv_first; item != NULL;
8733 item = item->li_next)
8735 if (argc == MAX_FUNC_ARGS)
8737 EMSG(_("E699: Too many arguments"));
8738 break;
8740 /* Make a copy of each argument. This is needed to be able to set
8741 * v_lock to VAR_FIXED in the copy without changing the original list.
8743 copy_tv(&item->li_tv, &argv[argc++]);
8746 if (item == NULL)
8747 (void)call_func(func, (int)STRLEN(func), rettv, argc, argv,
8748 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
8749 &dummy, TRUE, selfdict);
8751 /* Free the arguments. */
8752 while (argc > 0)
8753 clear_tv(&argv[--argc]);
8756 #ifdef FEAT_FLOAT
8758 * "ceil({float})" function
8760 static void
8761 f_ceil(argvars, rettv)
8762 typval_T *argvars;
8763 typval_T *rettv;
8765 float_T f;
8767 rettv->v_type = VAR_FLOAT;
8768 if (get_float_arg(argvars, &f) == OK)
8769 rettv->vval.v_float = ceil(f);
8770 else
8771 rettv->vval.v_float = 0.0;
8773 #endif
8776 * "changenr()" function
8778 /*ARGSUSED*/
8779 static void
8780 f_changenr(argvars, rettv)
8781 typval_T *argvars;
8782 typval_T *rettv;
8784 rettv->vval.v_number = curbuf->b_u_seq_cur;
8788 * "char2nr(string)" function
8790 static void
8791 f_char2nr(argvars, rettv)
8792 typval_T *argvars;
8793 typval_T *rettv;
8795 #ifdef FEAT_MBYTE
8796 if (has_mbyte)
8797 rettv->vval.v_number = (*mb_ptr2char)(get_tv_string(&argvars[0]));
8798 else
8799 #endif
8800 rettv->vval.v_number = get_tv_string(&argvars[0])[0];
8804 * "cindent(lnum)" function
8806 static void
8807 f_cindent(argvars, rettv)
8808 typval_T *argvars;
8809 typval_T *rettv;
8811 #ifdef FEAT_CINDENT
8812 pos_T pos;
8813 linenr_T lnum;
8815 pos = curwin->w_cursor;
8816 lnum = get_tv_lnum(argvars);
8817 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
8819 curwin->w_cursor.lnum = lnum;
8820 rettv->vval.v_number = get_c_indent();
8821 curwin->w_cursor = pos;
8823 else
8824 #endif
8825 rettv->vval.v_number = -1;
8829 * "clearmatches()" function
8831 /*ARGSUSED*/
8832 static void
8833 f_clearmatches(argvars, rettv)
8834 typval_T *argvars;
8835 typval_T *rettv;
8837 #ifdef FEAT_SEARCH_EXTRA
8838 clear_matches(curwin);
8839 #endif
8843 * "col(string)" function
8845 static void
8846 f_col(argvars, rettv)
8847 typval_T *argvars;
8848 typval_T *rettv;
8850 colnr_T col = 0;
8851 pos_T *fp;
8852 int fnum = curbuf->b_fnum;
8854 fp = var2fpos(&argvars[0], FALSE, &fnum);
8855 if (fp != NULL && fnum == curbuf->b_fnum)
8857 if (fp->col == MAXCOL)
8859 /* '> can be MAXCOL, get the length of the line then */
8860 if (fp->lnum <= curbuf->b_ml.ml_line_count)
8861 col = (colnr_T)STRLEN(ml_get(fp->lnum)) + 1;
8862 else
8863 col = MAXCOL;
8865 else
8867 col = fp->col + 1;
8868 #ifdef FEAT_VIRTUALEDIT
8869 /* col(".") when the cursor is on the NUL at the end of the line
8870 * because of "coladd" can be seen as an extra column. */
8871 if (virtual_active() && fp == &curwin->w_cursor)
8873 char_u *p = ml_get_cursor();
8875 if (curwin->w_cursor.coladd >= (colnr_T)chartabsize(p,
8876 curwin->w_virtcol - curwin->w_cursor.coladd))
8878 # ifdef FEAT_MBYTE
8879 int l;
8881 if (*p != NUL && p[(l = (*mb_ptr2len)(p))] == NUL)
8882 col += l;
8883 # else
8884 if (*p != NUL && p[1] == NUL)
8885 ++col;
8886 # endif
8889 #endif
8892 rettv->vval.v_number = col;
8895 #if defined(FEAT_INS_EXPAND)
8897 * "complete()" function
8899 /*ARGSUSED*/
8900 static void
8901 f_complete(argvars, rettv)
8902 typval_T *argvars;
8903 typval_T *rettv;
8905 int startcol;
8907 if ((State & INSERT) == 0)
8909 EMSG(_("E785: complete() can only be used in Insert mode"));
8910 return;
8913 /* Check for undo allowed here, because if something was already inserted
8914 * the line was already saved for undo and this check isn't done. */
8915 if (!undo_allowed())
8916 return;
8918 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
8920 EMSG(_(e_invarg));
8921 return;
8924 startcol = get_tv_number_chk(&argvars[0], NULL);
8925 if (startcol <= 0)
8926 return;
8928 set_completion(startcol - 1, argvars[1].vval.v_list);
8932 * "complete_add()" function
8934 /*ARGSUSED*/
8935 static void
8936 f_complete_add(argvars, rettv)
8937 typval_T *argvars;
8938 typval_T *rettv;
8940 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0);
8944 * "complete_check()" function
8946 /*ARGSUSED*/
8947 static void
8948 f_complete_check(argvars, rettv)
8949 typval_T *argvars;
8950 typval_T *rettv;
8952 int saved = RedrawingDisabled;
8954 RedrawingDisabled = 0;
8955 ins_compl_check_keys(0);
8956 rettv->vval.v_number = compl_interrupted;
8957 RedrawingDisabled = saved;
8959 #endif
8962 * "confirm(message, buttons[, default [, type]])" function
8964 /*ARGSUSED*/
8965 static void
8966 f_confirm(argvars, rettv)
8967 typval_T *argvars;
8968 typval_T *rettv;
8970 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
8971 char_u *message;
8972 char_u *buttons = NULL;
8973 char_u buf[NUMBUFLEN];
8974 char_u buf2[NUMBUFLEN];
8975 int def = 1;
8976 int type = VIM_GENERIC;
8977 char_u *typestr;
8978 int error = FALSE;
8980 message = get_tv_string_chk(&argvars[0]);
8981 if (message == NULL)
8982 error = TRUE;
8983 if (argvars[1].v_type != VAR_UNKNOWN)
8985 buttons = get_tv_string_buf_chk(&argvars[1], buf);
8986 if (buttons == NULL)
8987 error = TRUE;
8988 if (argvars[2].v_type != VAR_UNKNOWN)
8990 def = get_tv_number_chk(&argvars[2], &error);
8991 if (argvars[3].v_type != VAR_UNKNOWN)
8993 typestr = get_tv_string_buf_chk(&argvars[3], buf2);
8994 if (typestr == NULL)
8995 error = TRUE;
8996 else
8998 switch (TOUPPER_ASC(*typestr))
9000 case 'E': type = VIM_ERROR; break;
9001 case 'Q': type = VIM_QUESTION; break;
9002 case 'I': type = VIM_INFO; break;
9003 case 'W': type = VIM_WARNING; break;
9004 case 'G': type = VIM_GENERIC; break;
9011 if (buttons == NULL || *buttons == NUL)
9012 buttons = (char_u *)_("&Ok");
9014 if (error)
9015 rettv->vval.v_number = 0;
9016 else
9017 rettv->vval.v_number = do_dialog(type, NULL, message, buttons,
9018 def, NULL);
9019 #else
9020 rettv->vval.v_number = 0;
9021 #endif
9025 * "copy()" function
9027 static void
9028 f_copy(argvars, rettv)
9029 typval_T *argvars;
9030 typval_T *rettv;
9032 item_copy(&argvars[0], rettv, FALSE, 0);
9035 #ifdef FEAT_FLOAT
9037 * "cos()" function
9039 static void
9040 f_cos(argvars, rettv)
9041 typval_T *argvars;
9042 typval_T *rettv;
9044 float_T f;
9046 rettv->v_type = VAR_FLOAT;
9047 if (get_float_arg(argvars, &f) == OK)
9048 rettv->vval.v_float = cos(f);
9049 else
9050 rettv->vval.v_float = 0.0;
9052 #endif
9055 * "count()" function
9057 static void
9058 f_count(argvars, rettv)
9059 typval_T *argvars;
9060 typval_T *rettv;
9062 long n = 0;
9063 int ic = FALSE;
9065 if (argvars[0].v_type == VAR_LIST)
9067 listitem_T *li;
9068 list_T *l;
9069 long idx;
9071 if ((l = argvars[0].vval.v_list) != NULL)
9073 li = l->lv_first;
9074 if (argvars[2].v_type != VAR_UNKNOWN)
9076 int error = FALSE;
9078 ic = get_tv_number_chk(&argvars[2], &error);
9079 if (argvars[3].v_type != VAR_UNKNOWN)
9081 idx = get_tv_number_chk(&argvars[3], &error);
9082 if (!error)
9084 li = list_find(l, idx);
9085 if (li == NULL)
9086 EMSGN(_(e_listidx), idx);
9089 if (error)
9090 li = NULL;
9093 for ( ; li != NULL; li = li->li_next)
9094 if (tv_equal(&li->li_tv, &argvars[1], ic))
9095 ++n;
9098 else if (argvars[0].v_type == VAR_DICT)
9100 int todo;
9101 dict_T *d;
9102 hashitem_T *hi;
9104 if ((d = argvars[0].vval.v_dict) != NULL)
9106 int error = FALSE;
9108 if (argvars[2].v_type != VAR_UNKNOWN)
9110 ic = get_tv_number_chk(&argvars[2], &error);
9111 if (argvars[3].v_type != VAR_UNKNOWN)
9112 EMSG(_(e_invarg));
9115 todo = error ? 0 : (int)d->dv_hashtab.ht_used;
9116 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
9118 if (!HASHITEM_EMPTY(hi))
9120 --todo;
9121 if (tv_equal(&HI2DI(hi)->di_tv, &argvars[1], ic))
9122 ++n;
9127 else
9128 EMSG2(_(e_listdictarg), "count()");
9129 rettv->vval.v_number = n;
9133 * "cscope_connection([{num} , {dbpath} [, {prepend}]])" function
9135 * Checks the existence of a cscope connection.
9137 /*ARGSUSED*/
9138 static void
9139 f_cscope_connection(argvars, rettv)
9140 typval_T *argvars;
9141 typval_T *rettv;
9143 #ifdef FEAT_CSCOPE
9144 int num = 0;
9145 char_u *dbpath = NULL;
9146 char_u *prepend = NULL;
9147 char_u buf[NUMBUFLEN];
9149 if (argvars[0].v_type != VAR_UNKNOWN
9150 && argvars[1].v_type != VAR_UNKNOWN)
9152 num = (int)get_tv_number(&argvars[0]);
9153 dbpath = get_tv_string(&argvars[1]);
9154 if (argvars[2].v_type != VAR_UNKNOWN)
9155 prepend = get_tv_string_buf(&argvars[2], buf);
9158 rettv->vval.v_number = cs_connection(num, dbpath, prepend);
9159 #else
9160 rettv->vval.v_number = 0;
9161 #endif
9165 * "cursor(lnum, col)" function
9167 * Moves the cursor to the specified line and column
9169 /*ARGSUSED*/
9170 static void
9171 f_cursor(argvars, rettv)
9172 typval_T *argvars;
9173 typval_T *rettv;
9175 long line, col;
9176 #ifdef FEAT_VIRTUALEDIT
9177 long coladd = 0;
9178 #endif
9180 if (argvars[1].v_type == VAR_UNKNOWN)
9182 pos_T pos;
9184 if (list2fpos(argvars, &pos, NULL) == FAIL)
9185 return;
9186 line = pos.lnum;
9187 col = pos.col;
9188 #ifdef FEAT_VIRTUALEDIT
9189 coladd = pos.coladd;
9190 #endif
9192 else
9194 line = get_tv_lnum(argvars);
9195 col = get_tv_number_chk(&argvars[1], NULL);
9196 #ifdef FEAT_VIRTUALEDIT
9197 if (argvars[2].v_type != VAR_UNKNOWN)
9198 coladd = get_tv_number_chk(&argvars[2], NULL);
9199 #endif
9201 if (line < 0 || col < 0
9202 #ifdef FEAT_VIRTUALEDIT
9203 || coladd < 0
9204 #endif
9206 return; /* type error; errmsg already given */
9207 if (line > 0)
9208 curwin->w_cursor.lnum = line;
9209 if (col > 0)
9210 curwin->w_cursor.col = col - 1;
9211 #ifdef FEAT_VIRTUALEDIT
9212 curwin->w_cursor.coladd = coladd;
9213 #endif
9215 /* Make sure the cursor is in a valid position. */
9216 check_cursor();
9217 #ifdef FEAT_MBYTE
9218 /* Correct cursor for multi-byte character. */
9219 if (has_mbyte)
9220 mb_adjust_cursor();
9221 #endif
9223 curwin->w_set_curswant = TRUE;
9227 * "deepcopy()" function
9229 static void
9230 f_deepcopy(argvars, rettv)
9231 typval_T *argvars;
9232 typval_T *rettv;
9234 int noref = 0;
9236 if (argvars[1].v_type != VAR_UNKNOWN)
9237 noref = get_tv_number_chk(&argvars[1], NULL);
9238 if (noref < 0 || noref > 1)
9239 EMSG(_(e_invarg));
9240 else
9241 item_copy(&argvars[0], rettv, TRUE, noref == 0 ? ++current_copyID : 0);
9245 * "delete()" function
9247 static void
9248 f_delete(argvars, rettv)
9249 typval_T *argvars;
9250 typval_T *rettv;
9252 if (check_restricted() || check_secure())
9253 rettv->vval.v_number = -1;
9254 else
9255 rettv->vval.v_number = mch_remove(get_tv_string(&argvars[0]));
9259 * "did_filetype()" function
9261 /*ARGSUSED*/
9262 static void
9263 f_did_filetype(argvars, rettv)
9264 typval_T *argvars;
9265 typval_T *rettv;
9267 #ifdef FEAT_AUTOCMD
9268 rettv->vval.v_number = did_filetype;
9269 #else
9270 rettv->vval.v_number = 0;
9271 #endif
9275 * "diff_filler()" function
9277 /*ARGSUSED*/
9278 static void
9279 f_diff_filler(argvars, rettv)
9280 typval_T *argvars;
9281 typval_T *rettv;
9283 #ifdef FEAT_DIFF
9284 rettv->vval.v_number = diff_check_fill(curwin, get_tv_lnum(argvars));
9285 #endif
9289 * "diff_hlID()" function
9291 /*ARGSUSED*/
9292 static void
9293 f_diff_hlID(argvars, rettv)
9294 typval_T *argvars;
9295 typval_T *rettv;
9297 #ifdef FEAT_DIFF
9298 linenr_T lnum = get_tv_lnum(argvars);
9299 static linenr_T prev_lnum = 0;
9300 static int changedtick = 0;
9301 static int fnum = 0;
9302 static int change_start = 0;
9303 static int change_end = 0;
9304 static hlf_T hlID = (hlf_T)0;
9305 int filler_lines;
9306 int col;
9308 if (lnum < 0) /* ignore type error in {lnum} arg */
9309 lnum = 0;
9310 if (lnum != prev_lnum
9311 || changedtick != curbuf->b_changedtick
9312 || fnum != curbuf->b_fnum)
9314 /* New line, buffer, change: need to get the values. */
9315 filler_lines = diff_check(curwin, lnum);
9316 if (filler_lines < 0)
9318 if (filler_lines == -1)
9320 change_start = MAXCOL;
9321 change_end = -1;
9322 if (diff_find_change(curwin, lnum, &change_start, &change_end))
9323 hlID = HLF_ADD; /* added line */
9324 else
9325 hlID = HLF_CHD; /* changed line */
9327 else
9328 hlID = HLF_ADD; /* added line */
9330 else
9331 hlID = (hlf_T)0;
9332 prev_lnum = lnum;
9333 changedtick = curbuf->b_changedtick;
9334 fnum = curbuf->b_fnum;
9337 if (hlID == HLF_CHD || hlID == HLF_TXD)
9339 col = get_tv_number(&argvars[1]) - 1; /* ignore type error in {col} */
9340 if (col >= change_start && col <= change_end)
9341 hlID = HLF_TXD; /* changed text */
9342 else
9343 hlID = HLF_CHD; /* changed line */
9345 rettv->vval.v_number = hlID == (hlf_T)0 ? 0 : (int)hlID;
9346 #endif
9350 * "empty({expr})" function
9352 static void
9353 f_empty(argvars, rettv)
9354 typval_T *argvars;
9355 typval_T *rettv;
9357 int n;
9359 switch (argvars[0].v_type)
9361 case VAR_STRING:
9362 case VAR_FUNC:
9363 n = argvars[0].vval.v_string == NULL
9364 || *argvars[0].vval.v_string == NUL;
9365 break;
9366 case VAR_NUMBER:
9367 n = argvars[0].vval.v_number == 0;
9368 break;
9369 #ifdef FEAT_FLOAT
9370 case VAR_FLOAT:
9371 n = argvars[0].vval.v_float == 0.0;
9372 break;
9373 #endif
9374 case VAR_LIST:
9375 n = argvars[0].vval.v_list == NULL
9376 || argvars[0].vval.v_list->lv_first == NULL;
9377 break;
9378 case VAR_DICT:
9379 n = argvars[0].vval.v_dict == NULL
9380 || argvars[0].vval.v_dict->dv_hashtab.ht_used == 0;
9381 break;
9382 default:
9383 EMSG2(_(e_intern2), "f_empty()");
9384 n = 0;
9387 rettv->vval.v_number = n;
9391 * "escape({string}, {chars})" function
9393 static void
9394 f_escape(argvars, rettv)
9395 typval_T *argvars;
9396 typval_T *rettv;
9398 char_u buf[NUMBUFLEN];
9400 rettv->vval.v_string = vim_strsave_escaped(get_tv_string(&argvars[0]),
9401 get_tv_string_buf(&argvars[1], buf));
9402 rettv->v_type = VAR_STRING;
9406 * "eval()" function
9408 /*ARGSUSED*/
9409 static void
9410 f_eval(argvars, rettv)
9411 typval_T *argvars;
9412 typval_T *rettv;
9414 char_u *s;
9416 s = get_tv_string_chk(&argvars[0]);
9417 if (s != NULL)
9418 s = skipwhite(s);
9420 if (s == NULL || eval1(&s, rettv, TRUE) == FAIL)
9422 rettv->v_type = VAR_NUMBER;
9423 rettv->vval.v_number = 0;
9425 else if (*s != NUL)
9426 EMSG(_(e_trailing));
9430 * "eventhandler()" function
9432 /*ARGSUSED*/
9433 static void
9434 f_eventhandler(argvars, rettv)
9435 typval_T *argvars;
9436 typval_T *rettv;
9438 rettv->vval.v_number = vgetc_busy;
9442 * "executable()" function
9444 static void
9445 f_executable(argvars, rettv)
9446 typval_T *argvars;
9447 typval_T *rettv;
9449 rettv->vval.v_number = mch_can_exe(get_tv_string(&argvars[0]));
9453 * "exists()" function
9455 static void
9456 f_exists(argvars, rettv)
9457 typval_T *argvars;
9458 typval_T *rettv;
9460 char_u *p;
9461 char_u *name;
9462 int n = FALSE;
9463 int len = 0;
9465 p = get_tv_string(&argvars[0]);
9466 if (*p == '$') /* environment variable */
9468 /* first try "normal" environment variables (fast) */
9469 if (mch_getenv(p + 1) != NULL)
9470 n = TRUE;
9471 else
9473 /* try expanding things like $VIM and ${HOME} */
9474 p = expand_env_save(p);
9475 if (p != NULL && *p != '$')
9476 n = TRUE;
9477 vim_free(p);
9480 else if (*p == '&' || *p == '+') /* option */
9482 n = (get_option_tv(&p, NULL, TRUE) == OK);
9483 if (*skipwhite(p) != NUL)
9484 n = FALSE; /* trailing garbage */
9486 else if (*p == '*') /* internal or user defined function */
9488 n = function_exists(p + 1);
9490 else if (*p == ':')
9492 n = cmd_exists(p + 1);
9494 else if (*p == '#')
9496 #ifdef FEAT_AUTOCMD
9497 if (p[1] == '#')
9498 n = autocmd_supported(p + 2);
9499 else
9500 n = au_exists(p + 1);
9501 #endif
9503 else /* internal variable */
9505 char_u *tofree;
9506 typval_T tv;
9508 /* get_name_len() takes care of expanding curly braces */
9509 name = p;
9510 len = get_name_len(&p, &tofree, TRUE, FALSE);
9511 if (len > 0)
9513 if (tofree != NULL)
9514 name = tofree;
9515 n = (get_var_tv(name, len, &tv, FALSE) == OK);
9516 if (n)
9518 /* handle d.key, l[idx], f(expr) */
9519 n = (handle_subscript(&p, &tv, TRUE, FALSE) == OK);
9520 if (n)
9521 clear_tv(&tv);
9524 if (*p != NUL)
9525 n = FALSE;
9527 vim_free(tofree);
9530 rettv->vval.v_number = n;
9534 * "expand()" function
9536 static void
9537 f_expand(argvars, rettv)
9538 typval_T *argvars;
9539 typval_T *rettv;
9541 char_u *s;
9542 int len;
9543 char_u *errormsg;
9544 int flags = WILD_SILENT|WILD_USE_NL|WILD_LIST_NOTFOUND;
9545 expand_T xpc;
9546 int error = FALSE;
9548 rettv->v_type = VAR_STRING;
9549 s = get_tv_string(&argvars[0]);
9550 if (*s == '%' || *s == '#' || *s == '<')
9552 ++emsg_off;
9553 rettv->vval.v_string = eval_vars(s, s, &len, NULL, &errormsg, NULL);
9554 --emsg_off;
9556 else
9558 /* When the optional second argument is non-zero, don't remove matches
9559 * for 'suffixes' and 'wildignore' */
9560 if (argvars[1].v_type != VAR_UNKNOWN
9561 && get_tv_number_chk(&argvars[1], &error))
9562 flags |= WILD_KEEP_ALL;
9563 if (!error)
9565 ExpandInit(&xpc);
9566 xpc.xp_context = EXPAND_FILES;
9567 rettv->vval.v_string = ExpandOne(&xpc, s, NULL, flags, WILD_ALL);
9569 else
9570 rettv->vval.v_string = NULL;
9575 * "extend(list, list [, idx])" function
9576 * "extend(dict, dict [, action])" function
9578 static void
9579 f_extend(argvars, rettv)
9580 typval_T *argvars;
9581 typval_T *rettv;
9583 rettv->vval.v_number = 0;
9584 if (argvars[0].v_type == VAR_LIST && argvars[1].v_type == VAR_LIST)
9586 list_T *l1, *l2;
9587 listitem_T *item;
9588 long before;
9589 int error = FALSE;
9591 l1 = argvars[0].vval.v_list;
9592 l2 = argvars[1].vval.v_list;
9593 if (l1 != NULL && !tv_check_lock(l1->lv_lock, (char_u *)"extend()")
9594 && l2 != NULL)
9596 if (argvars[2].v_type != VAR_UNKNOWN)
9598 before = get_tv_number_chk(&argvars[2], &error);
9599 if (error)
9600 return; /* type error; errmsg already given */
9602 if (before == l1->lv_len)
9603 item = NULL;
9604 else
9606 item = list_find(l1, before);
9607 if (item == NULL)
9609 EMSGN(_(e_listidx), before);
9610 return;
9614 else
9615 item = NULL;
9616 list_extend(l1, l2, item);
9618 copy_tv(&argvars[0], rettv);
9621 else if (argvars[0].v_type == VAR_DICT && argvars[1].v_type == VAR_DICT)
9623 dict_T *d1, *d2;
9624 dictitem_T *di1;
9625 char_u *action;
9626 int i;
9627 hashitem_T *hi2;
9628 int todo;
9630 d1 = argvars[0].vval.v_dict;
9631 d2 = argvars[1].vval.v_dict;
9632 if (d1 != NULL && !tv_check_lock(d1->dv_lock, (char_u *)"extend()")
9633 && d2 != NULL)
9635 /* Check the third argument. */
9636 if (argvars[2].v_type != VAR_UNKNOWN)
9638 static char *(av[]) = {"keep", "force", "error"};
9640 action = get_tv_string_chk(&argvars[2]);
9641 if (action == NULL)
9642 return; /* type error; errmsg already given */
9643 for (i = 0; i < 3; ++i)
9644 if (STRCMP(action, av[i]) == 0)
9645 break;
9646 if (i == 3)
9648 EMSG2(_(e_invarg2), action);
9649 return;
9652 else
9653 action = (char_u *)"force";
9655 /* Go over all entries in the second dict and add them to the
9656 * first dict. */
9657 todo = (int)d2->dv_hashtab.ht_used;
9658 for (hi2 = d2->dv_hashtab.ht_array; todo > 0; ++hi2)
9660 if (!HASHITEM_EMPTY(hi2))
9662 --todo;
9663 di1 = dict_find(d1, hi2->hi_key, -1);
9664 if (di1 == NULL)
9666 di1 = dictitem_copy(HI2DI(hi2));
9667 if (di1 != NULL && dict_add(d1, di1) == FAIL)
9668 dictitem_free(di1);
9670 else if (*action == 'e')
9672 EMSG2(_("E737: Key already exists: %s"), hi2->hi_key);
9673 break;
9675 else if (*action == 'f')
9677 clear_tv(&di1->di_tv);
9678 copy_tv(&HI2DI(hi2)->di_tv, &di1->di_tv);
9683 copy_tv(&argvars[0], rettv);
9686 else
9687 EMSG2(_(e_listdictarg), "extend()");
9691 * "feedkeys()" function
9693 /*ARGSUSED*/
9694 static void
9695 f_feedkeys(argvars, rettv)
9696 typval_T *argvars;
9697 typval_T *rettv;
9699 int remap = TRUE;
9700 char_u *keys, *flags;
9701 char_u nbuf[NUMBUFLEN];
9702 int typed = FALSE;
9703 char_u *keys_esc;
9705 /* This is not allowed in the sandbox. If the commands would still be
9706 * executed in the sandbox it would be OK, but it probably happens later,
9707 * when "sandbox" is no longer set. */
9708 if (check_secure())
9709 return;
9711 rettv->vval.v_number = 0;
9712 keys = get_tv_string(&argvars[0]);
9713 if (*keys != NUL)
9715 if (argvars[1].v_type != VAR_UNKNOWN)
9717 flags = get_tv_string_buf(&argvars[1], nbuf);
9718 for ( ; *flags != NUL; ++flags)
9720 switch (*flags)
9722 case 'n': remap = FALSE; break;
9723 case 'm': remap = TRUE; break;
9724 case 't': typed = TRUE; break;
9729 /* Need to escape K_SPECIAL and CSI before putting the string in the
9730 * typeahead buffer. */
9731 keys_esc = vim_strsave_escape_csi(keys);
9732 if (keys_esc != NULL)
9734 ins_typebuf(keys_esc, (remap ? REMAP_YES : REMAP_NONE),
9735 typebuf.tb_len, !typed, FALSE);
9736 vim_free(keys_esc);
9737 if (vgetc_busy)
9738 typebuf_was_filled = TRUE;
9744 * "filereadable()" function
9746 static void
9747 f_filereadable(argvars, rettv)
9748 typval_T *argvars;
9749 typval_T *rettv;
9751 int fd;
9752 char_u *p;
9753 int n;
9755 #ifndef O_NONBLOCK
9756 # define O_NONBLOCK 0
9757 #endif
9758 p = get_tv_string(&argvars[0]);
9759 if (*p && !mch_isdir(p) && (fd = mch_open((char *)p,
9760 O_RDONLY | O_NONBLOCK, 0)) >= 0)
9762 n = TRUE;
9763 close(fd);
9765 else
9766 n = FALSE;
9768 rettv->vval.v_number = n;
9772 * Return 0 for not writable, 1 for writable file, 2 for a dir which we have
9773 * rights to write into.
9775 static void
9776 f_filewritable(argvars, rettv)
9777 typval_T *argvars;
9778 typval_T *rettv;
9780 rettv->vval.v_number = filewritable(get_tv_string(&argvars[0]));
9783 static void findfilendir __ARGS((typval_T *argvars, typval_T *rettv, int find_what));
9785 static void
9786 findfilendir(argvars, rettv, find_what)
9787 typval_T *argvars;
9788 typval_T *rettv;
9789 int find_what;
9791 #ifdef FEAT_SEARCHPATH
9792 char_u *fname;
9793 char_u *fresult = NULL;
9794 char_u *path = *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path;
9795 char_u *p;
9796 char_u pathbuf[NUMBUFLEN];
9797 int count = 1;
9798 int first = TRUE;
9799 int error = FALSE;
9800 #endif
9802 rettv->vval.v_string = NULL;
9803 rettv->v_type = VAR_STRING;
9805 #ifdef FEAT_SEARCHPATH
9806 fname = get_tv_string(&argvars[0]);
9808 if (argvars[1].v_type != VAR_UNKNOWN)
9810 p = get_tv_string_buf_chk(&argvars[1], pathbuf);
9811 if (p == NULL)
9812 error = TRUE;
9813 else
9815 if (*p != NUL)
9816 path = p;
9818 if (argvars[2].v_type != VAR_UNKNOWN)
9819 count = get_tv_number_chk(&argvars[2], &error);
9823 if (count < 0 && rettv_list_alloc(rettv) == FAIL)
9824 error = TRUE;
9826 if (*fname != NUL && !error)
9830 if (rettv->v_type == VAR_STRING)
9831 vim_free(fresult);
9832 fresult = find_file_in_path_option(first ? fname : NULL,
9833 first ? (int)STRLEN(fname) : 0,
9834 0, first, path,
9835 find_what,
9836 curbuf->b_ffname,
9837 find_what == FINDFILE_DIR
9838 ? (char_u *)"" : curbuf->b_p_sua);
9839 first = FALSE;
9841 if (fresult != NULL && rettv->v_type == VAR_LIST)
9842 list_append_string(rettv->vval.v_list, fresult, -1);
9844 } while ((rettv->v_type == VAR_LIST || --count > 0) && fresult != NULL);
9847 if (rettv->v_type == VAR_STRING)
9848 rettv->vval.v_string = fresult;
9849 #endif
9852 static void filter_map __ARGS((typval_T *argvars, typval_T *rettv, int map));
9853 static int filter_map_one __ARGS((typval_T *tv, char_u *expr, int map, int *remp));
9856 * Implementation of map() and filter().
9858 static void
9859 filter_map(argvars, rettv, map)
9860 typval_T *argvars;
9861 typval_T *rettv;
9862 int map;
9864 char_u buf[NUMBUFLEN];
9865 char_u *expr;
9866 listitem_T *li, *nli;
9867 list_T *l = NULL;
9868 dictitem_T *di;
9869 hashtab_T *ht;
9870 hashitem_T *hi;
9871 dict_T *d = NULL;
9872 typval_T save_val;
9873 typval_T save_key;
9874 int rem;
9875 int todo;
9876 char_u *ermsg = map ? (char_u *)"map()" : (char_u *)"filter()";
9877 int save_did_emsg;
9879 rettv->vval.v_number = 0;
9880 if (argvars[0].v_type == VAR_LIST)
9882 if ((l = argvars[0].vval.v_list) == NULL
9883 || (map && tv_check_lock(l->lv_lock, ermsg)))
9884 return;
9886 else if (argvars[0].v_type == VAR_DICT)
9888 if ((d = argvars[0].vval.v_dict) == NULL
9889 || (map && tv_check_lock(d->dv_lock, ermsg)))
9890 return;
9892 else
9894 EMSG2(_(e_listdictarg), ermsg);
9895 return;
9898 expr = get_tv_string_buf_chk(&argvars[1], buf);
9899 /* On type errors, the preceding call has already displayed an error
9900 * message. Avoid a misleading error message for an empty string that
9901 * was not passed as argument. */
9902 if (expr != NULL)
9904 prepare_vimvar(VV_VAL, &save_val);
9905 expr = skipwhite(expr);
9907 /* We reset "did_emsg" to be able to detect whether an error
9908 * occurred during evaluation of the expression. */
9909 save_did_emsg = did_emsg;
9910 did_emsg = FALSE;
9912 if (argvars[0].v_type == VAR_DICT)
9914 prepare_vimvar(VV_KEY, &save_key);
9915 vimvars[VV_KEY].vv_type = VAR_STRING;
9917 ht = &d->dv_hashtab;
9918 hash_lock(ht);
9919 todo = (int)ht->ht_used;
9920 for (hi = ht->ht_array; todo > 0; ++hi)
9922 if (!HASHITEM_EMPTY(hi))
9924 --todo;
9925 di = HI2DI(hi);
9926 if (tv_check_lock(di->di_tv.v_lock, ermsg))
9927 break;
9928 vimvars[VV_KEY].vv_str = vim_strsave(di->di_key);
9929 if (filter_map_one(&di->di_tv, expr, map, &rem) == FAIL
9930 || did_emsg)
9931 break;
9932 if (!map && rem)
9933 dictitem_remove(d, di);
9934 clear_tv(&vimvars[VV_KEY].vv_tv);
9937 hash_unlock(ht);
9939 restore_vimvar(VV_KEY, &save_key);
9941 else
9943 for (li = l->lv_first; li != NULL; li = nli)
9945 if (tv_check_lock(li->li_tv.v_lock, ermsg))
9946 break;
9947 nli = li->li_next;
9948 if (filter_map_one(&li->li_tv, expr, map, &rem) == FAIL
9949 || did_emsg)
9950 break;
9951 if (!map && rem)
9952 listitem_remove(l, li);
9956 restore_vimvar(VV_VAL, &save_val);
9958 did_emsg |= save_did_emsg;
9961 copy_tv(&argvars[0], rettv);
9964 static int
9965 filter_map_one(tv, expr, map, remp)
9966 typval_T *tv;
9967 char_u *expr;
9968 int map;
9969 int *remp;
9971 typval_T rettv;
9972 char_u *s;
9973 int retval = FAIL;
9975 copy_tv(tv, &vimvars[VV_VAL].vv_tv);
9976 s = expr;
9977 if (eval1(&s, &rettv, TRUE) == FAIL)
9978 goto theend;
9979 if (*s != NUL) /* check for trailing chars after expr */
9981 EMSG2(_(e_invexpr2), s);
9982 goto theend;
9984 if (map)
9986 /* map(): replace the list item value */
9987 clear_tv(tv);
9988 rettv.v_lock = 0;
9989 *tv = rettv;
9991 else
9993 int error = FALSE;
9995 /* filter(): when expr is zero remove the item */
9996 *remp = (get_tv_number_chk(&rettv, &error) == 0);
9997 clear_tv(&rettv);
9998 /* On type error, nothing has been removed; return FAIL to stop the
9999 * loop. The error message was given by get_tv_number_chk(). */
10000 if (error)
10001 goto theend;
10003 retval = OK;
10004 theend:
10005 clear_tv(&vimvars[VV_VAL].vv_tv);
10006 return retval;
10010 * "filter()" function
10012 static void
10013 f_filter(argvars, rettv)
10014 typval_T *argvars;
10015 typval_T *rettv;
10017 filter_map(argvars, rettv, FALSE);
10021 * "finddir({fname}[, {path}[, {count}]])" function
10023 static void
10024 f_finddir(argvars, rettv)
10025 typval_T *argvars;
10026 typval_T *rettv;
10028 findfilendir(argvars, rettv, FINDFILE_DIR);
10032 * "findfile({fname}[, {path}[, {count}]])" function
10034 static void
10035 f_findfile(argvars, rettv)
10036 typval_T *argvars;
10037 typval_T *rettv;
10039 findfilendir(argvars, rettv, FINDFILE_FILE);
10042 #ifdef FEAT_FLOAT
10044 * "float2nr({float})" function
10046 static void
10047 f_float2nr(argvars, rettv)
10048 typval_T *argvars;
10049 typval_T *rettv;
10051 float_T f;
10053 if (get_float_arg(argvars, &f) == OK)
10055 if (f < -0x7fffffff)
10056 rettv->vval.v_number = -0x7fffffff;
10057 else if (f > 0x7fffffff)
10058 rettv->vval.v_number = 0x7fffffff;
10059 else
10060 rettv->vval.v_number = (varnumber_T)f;
10062 else
10063 rettv->vval.v_number = 0;
10067 * "floor({float})" function
10069 static void
10070 f_floor(argvars, rettv)
10071 typval_T *argvars;
10072 typval_T *rettv;
10074 float_T f;
10076 rettv->v_type = VAR_FLOAT;
10077 if (get_float_arg(argvars, &f) == OK)
10078 rettv->vval.v_float = floor(f);
10079 else
10080 rettv->vval.v_float = 0.0;
10082 #endif
10085 * "fnameescape({string})" function
10087 static void
10088 f_fnameescape(argvars, rettv)
10089 typval_T *argvars;
10090 typval_T *rettv;
10092 rettv->vval.v_string = vim_strsave_fnameescape(
10093 get_tv_string(&argvars[0]), FALSE);
10094 rettv->v_type = VAR_STRING;
10098 * "fnamemodify({fname}, {mods})" function
10100 static void
10101 f_fnamemodify(argvars, rettv)
10102 typval_T *argvars;
10103 typval_T *rettv;
10105 char_u *fname;
10106 char_u *mods;
10107 int usedlen = 0;
10108 int len;
10109 char_u *fbuf = NULL;
10110 char_u buf[NUMBUFLEN];
10112 fname = get_tv_string_chk(&argvars[0]);
10113 mods = get_tv_string_buf_chk(&argvars[1], buf);
10114 if (fname == NULL || mods == NULL)
10115 fname = NULL;
10116 else
10118 len = (int)STRLEN(fname);
10119 (void)modify_fname(mods, &usedlen, &fname, &fbuf, &len);
10122 rettv->v_type = VAR_STRING;
10123 if (fname == NULL)
10124 rettv->vval.v_string = NULL;
10125 else
10126 rettv->vval.v_string = vim_strnsave(fname, len);
10127 vim_free(fbuf);
10130 static void foldclosed_both __ARGS((typval_T *argvars, typval_T *rettv, int end));
10133 * "foldclosed()" function
10135 static void
10136 foldclosed_both(argvars, rettv, end)
10137 typval_T *argvars;
10138 typval_T *rettv;
10139 int end;
10141 #ifdef FEAT_FOLDING
10142 linenr_T lnum;
10143 linenr_T first, last;
10145 lnum = get_tv_lnum(argvars);
10146 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
10148 if (hasFoldingWin(curwin, lnum, &first, &last, FALSE, NULL))
10150 if (end)
10151 rettv->vval.v_number = (varnumber_T)last;
10152 else
10153 rettv->vval.v_number = (varnumber_T)first;
10154 return;
10157 #endif
10158 rettv->vval.v_number = -1;
10162 * "foldclosed()" function
10164 static void
10165 f_foldclosed(argvars, rettv)
10166 typval_T *argvars;
10167 typval_T *rettv;
10169 foldclosed_both(argvars, rettv, FALSE);
10173 * "foldclosedend()" function
10175 static void
10176 f_foldclosedend(argvars, rettv)
10177 typval_T *argvars;
10178 typval_T *rettv;
10180 foldclosed_both(argvars, rettv, TRUE);
10184 * "foldlevel()" function
10186 static void
10187 f_foldlevel(argvars, rettv)
10188 typval_T *argvars;
10189 typval_T *rettv;
10191 #ifdef FEAT_FOLDING
10192 linenr_T lnum;
10194 lnum = get_tv_lnum(argvars);
10195 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
10196 rettv->vval.v_number = foldLevel(lnum);
10197 else
10198 #endif
10199 rettv->vval.v_number = 0;
10203 * "foldtext()" function
10205 /*ARGSUSED*/
10206 static void
10207 f_foldtext(argvars, rettv)
10208 typval_T *argvars;
10209 typval_T *rettv;
10211 #ifdef FEAT_FOLDING
10212 linenr_T lnum;
10213 char_u *s;
10214 char_u *r;
10215 int len;
10216 char *txt;
10217 #endif
10219 rettv->v_type = VAR_STRING;
10220 rettv->vval.v_string = NULL;
10221 #ifdef FEAT_FOLDING
10222 if ((linenr_T)vimvars[VV_FOLDSTART].vv_nr > 0
10223 && (linenr_T)vimvars[VV_FOLDEND].vv_nr
10224 <= curbuf->b_ml.ml_line_count
10225 && vimvars[VV_FOLDDASHES].vv_str != NULL)
10227 /* Find first non-empty line in the fold. */
10228 lnum = (linenr_T)vimvars[VV_FOLDSTART].vv_nr;
10229 while (lnum < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
10231 if (!linewhite(lnum))
10232 break;
10233 ++lnum;
10236 /* Find interesting text in this line. */
10237 s = skipwhite(ml_get(lnum));
10238 /* skip C comment-start */
10239 if (s[0] == '/' && (s[1] == '*' || s[1] == '/'))
10241 s = skipwhite(s + 2);
10242 if (*skipwhite(s) == NUL
10243 && lnum + 1 < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
10245 s = skipwhite(ml_get(lnum + 1));
10246 if (*s == '*')
10247 s = skipwhite(s + 1);
10250 txt = _("+-%s%3ld lines: ");
10251 r = alloc((unsigned)(STRLEN(txt)
10252 + STRLEN(vimvars[VV_FOLDDASHES].vv_str) /* for %s */
10253 + 20 /* for %3ld */
10254 + STRLEN(s))); /* concatenated */
10255 if (r != NULL)
10257 sprintf((char *)r, txt, vimvars[VV_FOLDDASHES].vv_str,
10258 (long)((linenr_T)vimvars[VV_FOLDEND].vv_nr
10259 - (linenr_T)vimvars[VV_FOLDSTART].vv_nr + 1));
10260 len = (int)STRLEN(r);
10261 STRCAT(r, s);
10262 /* remove 'foldmarker' and 'commentstring' */
10263 foldtext_cleanup(r + len);
10264 rettv->vval.v_string = r;
10267 #endif
10271 * "foldtextresult(lnum)" function
10273 /*ARGSUSED*/
10274 static void
10275 f_foldtextresult(argvars, rettv)
10276 typval_T *argvars;
10277 typval_T *rettv;
10279 #ifdef FEAT_FOLDING
10280 linenr_T lnum;
10281 char_u *text;
10282 char_u buf[51];
10283 foldinfo_T foldinfo;
10284 int fold_count;
10285 #endif
10287 rettv->v_type = VAR_STRING;
10288 rettv->vval.v_string = NULL;
10289 #ifdef FEAT_FOLDING
10290 lnum = get_tv_lnum(argvars);
10291 /* treat illegal types and illegal string values for {lnum} the same */
10292 if (lnum < 0)
10293 lnum = 0;
10294 fold_count = foldedCount(curwin, lnum, &foldinfo);
10295 if (fold_count > 0)
10297 text = get_foldtext(curwin, lnum, lnum + fold_count - 1,
10298 &foldinfo, buf);
10299 if (text == buf)
10300 text = vim_strsave(text);
10301 rettv->vval.v_string = text;
10303 #endif
10307 * "foreground()" function
10309 /*ARGSUSED*/
10310 static void
10311 f_foreground(argvars, rettv)
10312 typval_T *argvars;
10313 typval_T *rettv;
10315 rettv->vval.v_number = 0;
10316 #ifdef FEAT_GUI
10317 if (gui.in_use)
10318 gui_mch_set_foreground();
10319 #else
10320 # ifdef WIN32
10321 win32_set_foreground();
10322 # endif
10323 #endif
10327 * "function()" function
10329 /*ARGSUSED*/
10330 static void
10331 f_function(argvars, rettv)
10332 typval_T *argvars;
10333 typval_T *rettv;
10335 char_u *s;
10337 rettv->vval.v_number = 0;
10338 s = get_tv_string(&argvars[0]);
10339 if (s == NULL || *s == NUL || VIM_ISDIGIT(*s))
10340 EMSG2(_(e_invarg2), s);
10341 else if (!function_exists(s))
10342 EMSG2(_("E700: Unknown function: %s"), s);
10343 else
10345 rettv->vval.v_string = vim_strsave(s);
10346 rettv->v_type = VAR_FUNC;
10351 * "garbagecollect()" function
10353 /*ARGSUSED*/
10354 static void
10355 f_garbagecollect(argvars, rettv)
10356 typval_T *argvars;
10357 typval_T *rettv;
10359 /* This is postponed until we are back at the toplevel, because we may be
10360 * using Lists and Dicts internally. E.g.: ":echo [garbagecollect()]". */
10361 want_garbage_collect = TRUE;
10363 if (argvars[0].v_type != VAR_UNKNOWN && get_tv_number(&argvars[0]) == 1)
10364 garbage_collect_at_exit = TRUE;
10368 * "get()" function
10370 static void
10371 f_get(argvars, rettv)
10372 typval_T *argvars;
10373 typval_T *rettv;
10375 listitem_T *li;
10376 list_T *l;
10377 dictitem_T *di;
10378 dict_T *d;
10379 typval_T *tv = NULL;
10381 if (argvars[0].v_type == VAR_LIST)
10383 if ((l = argvars[0].vval.v_list) != NULL)
10385 int error = FALSE;
10387 li = list_find(l, get_tv_number_chk(&argvars[1], &error));
10388 if (!error && li != NULL)
10389 tv = &li->li_tv;
10392 else if (argvars[0].v_type == VAR_DICT)
10394 if ((d = argvars[0].vval.v_dict) != NULL)
10396 di = dict_find(d, get_tv_string(&argvars[1]), -1);
10397 if (di != NULL)
10398 tv = &di->di_tv;
10401 else
10402 EMSG2(_(e_listdictarg), "get()");
10404 if (tv == NULL)
10406 if (argvars[2].v_type == VAR_UNKNOWN)
10407 rettv->vval.v_number = 0;
10408 else
10409 copy_tv(&argvars[2], rettv);
10411 else
10412 copy_tv(tv, rettv);
10415 static void get_buffer_lines __ARGS((buf_T *buf, linenr_T start, linenr_T end, int retlist, typval_T *rettv));
10418 * Get line or list of lines from buffer "buf" into "rettv".
10419 * Return a range (from start to end) of lines in rettv from the specified
10420 * buffer.
10421 * If 'retlist' is TRUE, then the lines are returned as a Vim List.
10423 static void
10424 get_buffer_lines(buf, start, end, retlist, rettv)
10425 buf_T *buf;
10426 linenr_T start;
10427 linenr_T end;
10428 int retlist;
10429 typval_T *rettv;
10431 char_u *p;
10433 if (retlist)
10435 if (rettv_list_alloc(rettv) == FAIL)
10436 return;
10438 else
10439 rettv->vval.v_number = 0;
10441 if (buf == NULL || buf->b_ml.ml_mfp == NULL || start < 0)
10442 return;
10444 if (!retlist)
10446 if (start >= 1 && start <= buf->b_ml.ml_line_count)
10447 p = ml_get_buf(buf, start, FALSE);
10448 else
10449 p = (char_u *)"";
10451 rettv->v_type = VAR_STRING;
10452 rettv->vval.v_string = vim_strsave(p);
10454 else
10456 if (end < start)
10457 return;
10459 if (start < 1)
10460 start = 1;
10461 if (end > buf->b_ml.ml_line_count)
10462 end = buf->b_ml.ml_line_count;
10463 while (start <= end)
10464 if (list_append_string(rettv->vval.v_list,
10465 ml_get_buf(buf, start++, FALSE), -1) == FAIL)
10466 break;
10471 * "getbufline()" function
10473 static void
10474 f_getbufline(argvars, rettv)
10475 typval_T *argvars;
10476 typval_T *rettv;
10478 linenr_T lnum;
10479 linenr_T end;
10480 buf_T *buf;
10482 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
10483 ++emsg_off;
10484 buf = get_buf_tv(&argvars[0]);
10485 --emsg_off;
10487 lnum = get_tv_lnum_buf(&argvars[1], buf);
10488 if (argvars[2].v_type == VAR_UNKNOWN)
10489 end = lnum;
10490 else
10491 end = get_tv_lnum_buf(&argvars[2], buf);
10493 get_buffer_lines(buf, lnum, end, TRUE, rettv);
10497 * "getbufvar()" function
10499 static void
10500 f_getbufvar(argvars, rettv)
10501 typval_T *argvars;
10502 typval_T *rettv;
10504 buf_T *buf;
10505 buf_T *save_curbuf;
10506 char_u *varname;
10507 dictitem_T *v;
10509 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
10510 varname = get_tv_string_chk(&argvars[1]);
10511 ++emsg_off;
10512 buf = get_buf_tv(&argvars[0]);
10514 rettv->v_type = VAR_STRING;
10515 rettv->vval.v_string = NULL;
10517 if (buf != NULL && varname != NULL)
10519 /* set curbuf to be our buf, temporarily */
10520 save_curbuf = curbuf;
10521 curbuf = buf;
10523 if (*varname == '&') /* buffer-local-option */
10524 get_option_tv(&varname, rettv, TRUE);
10525 else
10527 if (*varname == NUL)
10528 /* let getbufvar({nr}, "") return the "b:" dictionary. The
10529 * scope prefix before the NUL byte is required by
10530 * find_var_in_ht(). */
10531 varname = (char_u *)"b:" + 2;
10532 /* look up the variable */
10533 v = find_var_in_ht(&curbuf->b_vars.dv_hashtab, varname, FALSE);
10534 if (v != NULL)
10535 copy_tv(&v->di_tv, rettv);
10538 /* restore previous notion of curbuf */
10539 curbuf = save_curbuf;
10542 --emsg_off;
10546 * "getchar()" function
10548 static void
10549 f_getchar(argvars, rettv)
10550 typval_T *argvars;
10551 typval_T *rettv;
10553 varnumber_T n;
10554 int error = FALSE;
10556 /* Position the cursor. Needed after a message that ends in a space. */
10557 windgoto(msg_row, msg_col);
10559 ++no_mapping;
10560 ++allow_keys;
10561 for (;;)
10563 if (argvars[0].v_type == VAR_UNKNOWN)
10564 /* getchar(): blocking wait. */
10565 n = safe_vgetc();
10566 else if (get_tv_number_chk(&argvars[0], &error) == 1)
10567 /* getchar(1): only check if char avail */
10568 n = vpeekc();
10569 else if (error || vpeekc() == NUL)
10570 /* illegal argument or getchar(0) and no char avail: return zero */
10571 n = 0;
10572 else
10573 /* getchar(0) and char avail: return char */
10574 n = safe_vgetc();
10575 if (n == K_IGNORE)
10576 continue;
10577 break;
10579 --no_mapping;
10580 --allow_keys;
10582 vimvars[VV_MOUSE_WIN].vv_nr = 0;
10583 vimvars[VV_MOUSE_LNUM].vv_nr = 0;
10584 vimvars[VV_MOUSE_COL].vv_nr = 0;
10586 rettv->vval.v_number = n;
10587 if (IS_SPECIAL(n) || mod_mask != 0)
10589 char_u temp[10]; /* modifier: 3, mbyte-char: 6, NUL: 1 */
10590 int i = 0;
10592 /* Turn a special key into three bytes, plus modifier. */
10593 if (mod_mask != 0)
10595 temp[i++] = K_SPECIAL;
10596 temp[i++] = KS_MODIFIER;
10597 temp[i++] = mod_mask;
10599 if (IS_SPECIAL(n))
10601 temp[i++] = K_SPECIAL;
10602 temp[i++] = K_SECOND(n);
10603 temp[i++] = K_THIRD(n);
10605 #ifdef FEAT_MBYTE
10606 else if (has_mbyte)
10607 i += (*mb_char2bytes)(n, temp + i);
10608 #endif
10609 else
10610 temp[i++] = n;
10611 temp[i++] = NUL;
10612 rettv->v_type = VAR_STRING;
10613 rettv->vval.v_string = vim_strsave(temp);
10615 #ifdef FEAT_MOUSE
10616 if (n == K_LEFTMOUSE
10617 || n == K_LEFTMOUSE_NM
10618 || n == K_LEFTDRAG
10619 || n == K_LEFTRELEASE
10620 || n == K_LEFTRELEASE_NM
10621 || n == K_MIDDLEMOUSE
10622 || n == K_MIDDLEDRAG
10623 || n == K_MIDDLERELEASE
10624 || n == K_RIGHTMOUSE
10625 || n == K_RIGHTDRAG
10626 || n == K_RIGHTRELEASE
10627 || n == K_X1MOUSE
10628 || n == K_X1DRAG
10629 || n == K_X1RELEASE
10630 || n == K_X2MOUSE
10631 || n == K_X2DRAG
10632 || n == K_X2RELEASE
10633 || n == K_MOUSEDOWN
10634 || n == K_MOUSEUP)
10636 int row = mouse_row;
10637 int col = mouse_col;
10638 win_T *win;
10639 linenr_T lnum;
10640 # ifdef FEAT_WINDOWS
10641 win_T *wp;
10642 # endif
10643 int n = 1;
10645 if (row >= 0 && col >= 0)
10647 /* Find the window at the mouse coordinates and compute the
10648 * text position. */
10649 win = mouse_find_win(&row, &col);
10650 (void)mouse_comp_pos(win, &row, &col, &lnum);
10651 # ifdef FEAT_WINDOWS
10652 for (wp = firstwin; wp != win; wp = wp->w_next)
10653 ++n;
10654 # endif
10655 vimvars[VV_MOUSE_WIN].vv_nr = n;
10656 vimvars[VV_MOUSE_LNUM].vv_nr = lnum;
10657 vimvars[VV_MOUSE_COL].vv_nr = col + 1;
10660 #endif
10665 * "getcharmod()" function
10667 /*ARGSUSED*/
10668 static void
10669 f_getcharmod(argvars, rettv)
10670 typval_T *argvars;
10671 typval_T *rettv;
10673 rettv->vval.v_number = mod_mask;
10677 * "getcmdline()" function
10679 /*ARGSUSED*/
10680 static void
10681 f_getcmdline(argvars, rettv)
10682 typval_T *argvars;
10683 typval_T *rettv;
10685 rettv->v_type = VAR_STRING;
10686 rettv->vval.v_string = get_cmdline_str();
10690 * "getcmdpos()" function
10692 /*ARGSUSED*/
10693 static void
10694 f_getcmdpos(argvars, rettv)
10695 typval_T *argvars;
10696 typval_T *rettv;
10698 rettv->vval.v_number = get_cmdline_pos() + 1;
10702 * "getcmdtype()" function
10704 /*ARGSUSED*/
10705 static void
10706 f_getcmdtype(argvars, rettv)
10707 typval_T *argvars;
10708 typval_T *rettv;
10710 rettv->v_type = VAR_STRING;
10711 rettv->vval.v_string = alloc(2);
10712 if (rettv->vval.v_string != NULL)
10714 rettv->vval.v_string[0] = get_cmdline_type();
10715 rettv->vval.v_string[1] = NUL;
10720 * "getcwd()" function
10722 /*ARGSUSED*/
10723 static void
10724 f_getcwd(argvars, rettv)
10725 typval_T *argvars;
10726 typval_T *rettv;
10728 char_u cwd[MAXPATHL];
10730 rettv->v_type = VAR_STRING;
10731 if (mch_dirname(cwd, MAXPATHL) == FAIL)
10732 rettv->vval.v_string = NULL;
10733 else
10735 rettv->vval.v_string = vim_strsave(cwd);
10736 #ifdef BACKSLASH_IN_FILENAME
10737 if (rettv->vval.v_string != NULL)
10738 slash_adjust(rettv->vval.v_string);
10739 #endif
10744 * "getfontname()" function
10746 /*ARGSUSED*/
10747 static void
10748 f_getfontname(argvars, rettv)
10749 typval_T *argvars;
10750 typval_T *rettv;
10752 rettv->v_type = VAR_STRING;
10753 rettv->vval.v_string = NULL;
10754 #ifdef FEAT_GUI
10755 if (gui.in_use)
10757 GuiFont font;
10758 char_u *name = NULL;
10760 if (argvars[0].v_type == VAR_UNKNOWN)
10762 /* Get the "Normal" font. Either the name saved by
10763 * hl_set_font_name() or from the font ID. */
10764 font = gui.norm_font;
10765 name = hl_get_font_name();
10767 else
10769 name = get_tv_string(&argvars[0]);
10770 if (STRCMP(name, "*") == 0) /* don't use font dialog */
10771 return;
10772 font = gui_mch_get_font(name, FALSE);
10773 if (font == NOFONT)
10774 return; /* Invalid font name, return empty string. */
10776 rettv->vval.v_string = gui_mch_get_fontname(font, name);
10777 if (argvars[0].v_type != VAR_UNKNOWN)
10778 gui_mch_free_font(font);
10780 #endif
10784 * "getfperm({fname})" function
10786 static void
10787 f_getfperm(argvars, rettv)
10788 typval_T *argvars;
10789 typval_T *rettv;
10791 char_u *fname;
10792 struct stat st;
10793 char_u *perm = NULL;
10794 char_u flags[] = "rwx";
10795 int i;
10797 fname = get_tv_string(&argvars[0]);
10799 rettv->v_type = VAR_STRING;
10800 if (mch_stat((char *)fname, &st) >= 0)
10802 perm = vim_strsave((char_u *)"---------");
10803 if (perm != NULL)
10805 for (i = 0; i < 9; i++)
10807 if (st.st_mode & (1 << (8 - i)))
10808 perm[i] = flags[i % 3];
10812 rettv->vval.v_string = perm;
10816 * "getfsize({fname})" function
10818 static void
10819 f_getfsize(argvars, rettv)
10820 typval_T *argvars;
10821 typval_T *rettv;
10823 char_u *fname;
10824 struct stat st;
10826 fname = get_tv_string(&argvars[0]);
10828 rettv->v_type = VAR_NUMBER;
10830 if (mch_stat((char *)fname, &st) >= 0)
10832 if (mch_isdir(fname))
10833 rettv->vval.v_number = 0;
10834 else
10836 rettv->vval.v_number = (varnumber_T)st.st_size;
10838 /* non-perfect check for overflow */
10839 if ((off_t)rettv->vval.v_number != (off_t)st.st_size)
10840 rettv->vval.v_number = -2;
10843 else
10844 rettv->vval.v_number = -1;
10848 * "getftime({fname})" function
10850 static void
10851 f_getftime(argvars, rettv)
10852 typval_T *argvars;
10853 typval_T *rettv;
10855 char_u *fname;
10856 struct stat st;
10858 fname = get_tv_string(&argvars[0]);
10860 if (mch_stat((char *)fname, &st) >= 0)
10861 rettv->vval.v_number = (varnumber_T)st.st_mtime;
10862 else
10863 rettv->vval.v_number = -1;
10867 * "getftype({fname})" function
10869 static void
10870 f_getftype(argvars, rettv)
10871 typval_T *argvars;
10872 typval_T *rettv;
10874 char_u *fname;
10875 struct stat st;
10876 char_u *type = NULL;
10877 char *t;
10879 fname = get_tv_string(&argvars[0]);
10881 rettv->v_type = VAR_STRING;
10882 if (mch_lstat((char *)fname, &st) >= 0)
10884 #ifdef S_ISREG
10885 if (S_ISREG(st.st_mode))
10886 t = "file";
10887 else if (S_ISDIR(st.st_mode))
10888 t = "dir";
10889 # ifdef S_ISLNK
10890 else if (S_ISLNK(st.st_mode))
10891 t = "link";
10892 # endif
10893 # ifdef S_ISBLK
10894 else if (S_ISBLK(st.st_mode))
10895 t = "bdev";
10896 # endif
10897 # ifdef S_ISCHR
10898 else if (S_ISCHR(st.st_mode))
10899 t = "cdev";
10900 # endif
10901 # ifdef S_ISFIFO
10902 else if (S_ISFIFO(st.st_mode))
10903 t = "fifo";
10904 # endif
10905 # ifdef S_ISSOCK
10906 else if (S_ISSOCK(st.st_mode))
10907 t = "fifo";
10908 # endif
10909 else
10910 t = "other";
10911 #else
10912 # ifdef S_IFMT
10913 switch (st.st_mode & S_IFMT)
10915 case S_IFREG: t = "file"; break;
10916 case S_IFDIR: t = "dir"; break;
10917 # ifdef S_IFLNK
10918 case S_IFLNK: t = "link"; break;
10919 # endif
10920 # ifdef S_IFBLK
10921 case S_IFBLK: t = "bdev"; break;
10922 # endif
10923 # ifdef S_IFCHR
10924 case S_IFCHR: t = "cdev"; break;
10925 # endif
10926 # ifdef S_IFIFO
10927 case S_IFIFO: t = "fifo"; break;
10928 # endif
10929 # ifdef S_IFSOCK
10930 case S_IFSOCK: t = "socket"; break;
10931 # endif
10932 default: t = "other";
10934 # else
10935 if (mch_isdir(fname))
10936 t = "dir";
10937 else
10938 t = "file";
10939 # endif
10940 #endif
10941 type = vim_strsave((char_u *)t);
10943 rettv->vval.v_string = type;
10947 * "getline(lnum, [end])" function
10949 static void
10950 f_getline(argvars, rettv)
10951 typval_T *argvars;
10952 typval_T *rettv;
10954 linenr_T lnum;
10955 linenr_T end;
10956 int retlist;
10958 lnum = get_tv_lnum(argvars);
10959 if (argvars[1].v_type == VAR_UNKNOWN)
10961 end = 0;
10962 retlist = FALSE;
10964 else
10966 end = get_tv_lnum(&argvars[1]);
10967 retlist = TRUE;
10970 get_buffer_lines(curbuf, lnum, end, retlist, rettv);
10974 * "getmatches()" function
10976 /*ARGSUSED*/
10977 static void
10978 f_getmatches(argvars, rettv)
10979 typval_T *argvars;
10980 typval_T *rettv;
10982 #ifdef FEAT_SEARCH_EXTRA
10983 dict_T *dict;
10984 matchitem_T *cur = curwin->w_match_head;
10986 rettv->vval.v_number = 0;
10988 if (rettv_list_alloc(rettv) == OK)
10990 while (cur != NULL)
10992 dict = dict_alloc();
10993 if (dict == NULL)
10994 return;
10995 dict_add_nr_str(dict, "group", 0L, syn_id2name(cur->hlg_id));
10996 dict_add_nr_str(dict, "pattern", 0L, cur->pattern);
10997 dict_add_nr_str(dict, "priority", (long)cur->priority, NULL);
10998 dict_add_nr_str(dict, "id", (long)cur->id, NULL);
10999 list_append_dict(rettv->vval.v_list, dict);
11000 cur = cur->next;
11003 #endif
11007 * "getpid()" function
11009 /*ARGSUSED*/
11010 static void
11011 f_getpid(argvars, rettv)
11012 typval_T *argvars;
11013 typval_T *rettv;
11015 rettv->vval.v_number = mch_get_pid();
11019 * "getpos(string)" function
11021 static void
11022 f_getpos(argvars, rettv)
11023 typval_T *argvars;
11024 typval_T *rettv;
11026 pos_T *fp;
11027 list_T *l;
11028 int fnum = -1;
11030 if (rettv_list_alloc(rettv) == OK)
11032 l = rettv->vval.v_list;
11033 fp = var2fpos(&argvars[0], TRUE, &fnum);
11034 if (fnum != -1)
11035 list_append_number(l, (varnumber_T)fnum);
11036 else
11037 list_append_number(l, (varnumber_T)0);
11038 list_append_number(l, (fp != NULL) ? (varnumber_T)fp->lnum
11039 : (varnumber_T)0);
11040 list_append_number(l, (fp != NULL)
11041 ? (varnumber_T)(fp->col == MAXCOL ? MAXCOL : fp->col + 1)
11042 : (varnumber_T)0);
11043 list_append_number(l,
11044 #ifdef FEAT_VIRTUALEDIT
11045 (fp != NULL) ? (varnumber_T)fp->coladd :
11046 #endif
11047 (varnumber_T)0);
11049 else
11050 rettv->vval.v_number = FALSE;
11054 * "getqflist()" and "getloclist()" functions
11056 /*ARGSUSED*/
11057 static void
11058 f_getqflist(argvars, rettv)
11059 typval_T *argvars;
11060 typval_T *rettv;
11062 #ifdef FEAT_QUICKFIX
11063 win_T *wp;
11064 #endif
11066 rettv->vval.v_number = 0;
11067 #ifdef FEAT_QUICKFIX
11068 if (rettv_list_alloc(rettv) == OK)
11070 wp = NULL;
11071 if (argvars[0].v_type != VAR_UNKNOWN) /* getloclist() */
11073 wp = find_win_by_nr(&argvars[0], NULL);
11074 if (wp == NULL)
11075 return;
11078 (void)get_errorlist(wp, rettv->vval.v_list);
11080 #endif
11084 * "getreg()" function
11086 static void
11087 f_getreg(argvars, rettv)
11088 typval_T *argvars;
11089 typval_T *rettv;
11091 char_u *strregname;
11092 int regname;
11093 int arg2 = FALSE;
11094 int error = FALSE;
11096 if (argvars[0].v_type != VAR_UNKNOWN)
11098 strregname = get_tv_string_chk(&argvars[0]);
11099 error = strregname == NULL;
11100 if (argvars[1].v_type != VAR_UNKNOWN)
11101 arg2 = get_tv_number_chk(&argvars[1], &error);
11103 else
11104 strregname = vimvars[VV_REG].vv_str;
11105 regname = (strregname == NULL ? '"' : *strregname);
11106 if (regname == 0)
11107 regname = '"';
11109 rettv->v_type = VAR_STRING;
11110 rettv->vval.v_string = error ? NULL :
11111 get_reg_contents(regname, TRUE, arg2);
11115 * "getregtype()" function
11117 static void
11118 f_getregtype(argvars, rettv)
11119 typval_T *argvars;
11120 typval_T *rettv;
11122 char_u *strregname;
11123 int regname;
11124 char_u buf[NUMBUFLEN + 2];
11125 long reglen = 0;
11127 if (argvars[0].v_type != VAR_UNKNOWN)
11129 strregname = get_tv_string_chk(&argvars[0]);
11130 if (strregname == NULL) /* type error; errmsg already given */
11132 rettv->v_type = VAR_STRING;
11133 rettv->vval.v_string = NULL;
11134 return;
11137 else
11138 /* Default to v:register */
11139 strregname = vimvars[VV_REG].vv_str;
11141 regname = (strregname == NULL ? '"' : *strregname);
11142 if (regname == 0)
11143 regname = '"';
11145 buf[0] = NUL;
11146 buf[1] = NUL;
11147 switch (get_reg_type(regname, &reglen))
11149 case MLINE: buf[0] = 'V'; break;
11150 case MCHAR: buf[0] = 'v'; break;
11151 #ifdef FEAT_VISUAL
11152 case MBLOCK:
11153 buf[0] = Ctrl_V;
11154 sprintf((char *)buf + 1, "%ld", reglen + 1);
11155 break;
11156 #endif
11158 rettv->v_type = VAR_STRING;
11159 rettv->vval.v_string = vim_strsave(buf);
11163 * "gettabwinvar()" function
11165 static void
11166 f_gettabwinvar(argvars, rettv)
11167 typval_T *argvars;
11168 typval_T *rettv;
11170 getwinvar(argvars, rettv, 1);
11174 * "getwinposx()" function
11176 /*ARGSUSED*/
11177 static void
11178 f_getwinposx(argvars, rettv)
11179 typval_T *argvars;
11180 typval_T *rettv;
11182 rettv->vval.v_number = -1;
11183 #ifdef FEAT_GUI
11184 if (gui.in_use)
11186 int x, y;
11188 if (gui_mch_get_winpos(&x, &y) == OK)
11189 rettv->vval.v_number = x;
11191 #endif
11195 * "getwinposy()" function
11197 /*ARGSUSED*/
11198 static void
11199 f_getwinposy(argvars, rettv)
11200 typval_T *argvars;
11201 typval_T *rettv;
11203 rettv->vval.v_number = -1;
11204 #ifdef FEAT_GUI
11205 if (gui.in_use)
11207 int x, y;
11209 if (gui_mch_get_winpos(&x, &y) == OK)
11210 rettv->vval.v_number = y;
11212 #endif
11216 * Find window specified by "vp" in tabpage "tp".
11218 static win_T *
11219 find_win_by_nr(vp, tp)
11220 typval_T *vp;
11221 tabpage_T *tp; /* NULL for current tab page */
11223 #ifdef FEAT_WINDOWS
11224 win_T *wp;
11225 #endif
11226 int nr;
11228 nr = get_tv_number_chk(vp, NULL);
11230 #ifdef FEAT_WINDOWS
11231 if (nr < 0)
11232 return NULL;
11233 if (nr == 0)
11234 return curwin;
11236 for (wp = (tp == NULL || tp == curtab) ? firstwin : tp->tp_firstwin;
11237 wp != NULL; wp = wp->w_next)
11238 if (--nr <= 0)
11239 break;
11240 return wp;
11241 #else
11242 if (nr == 0 || nr == 1)
11243 return curwin;
11244 return NULL;
11245 #endif
11249 * "getwinvar()" function
11251 static void
11252 f_getwinvar(argvars, rettv)
11253 typval_T *argvars;
11254 typval_T *rettv;
11256 getwinvar(argvars, rettv, 0);
11260 * getwinvar() and gettabwinvar()
11262 static void
11263 getwinvar(argvars, rettv, off)
11264 typval_T *argvars;
11265 typval_T *rettv;
11266 int off; /* 1 for gettabwinvar() */
11268 win_T *win, *oldcurwin;
11269 char_u *varname;
11270 dictitem_T *v;
11271 tabpage_T *tp;
11273 #ifdef FEAT_WINDOWS
11274 if (off == 1)
11275 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
11276 else
11277 tp = curtab;
11278 #endif
11279 win = find_win_by_nr(&argvars[off], tp);
11280 varname = get_tv_string_chk(&argvars[off + 1]);
11281 ++emsg_off;
11283 rettv->v_type = VAR_STRING;
11284 rettv->vval.v_string = NULL;
11286 if (win != NULL && varname != NULL)
11288 /* Set curwin to be our win, temporarily. Also set curbuf, so
11289 * that we can get buffer-local options. */
11290 oldcurwin = curwin;
11291 curwin = win;
11292 curbuf = win->w_buffer;
11294 if (*varname == '&') /* window-local-option */
11295 get_option_tv(&varname, rettv, 1);
11296 else
11298 if (*varname == NUL)
11299 /* let getwinvar({nr}, "") return the "w:" dictionary. The
11300 * scope prefix before the NUL byte is required by
11301 * find_var_in_ht(). */
11302 varname = (char_u *)"w:" + 2;
11303 /* look up the variable */
11304 v = find_var_in_ht(&win->w_vars.dv_hashtab, varname, FALSE);
11305 if (v != NULL)
11306 copy_tv(&v->di_tv, rettv);
11309 /* restore previous notion of curwin */
11310 curwin = oldcurwin;
11311 curbuf = curwin->w_buffer;
11314 --emsg_off;
11318 * "glob()" function
11320 static void
11321 f_glob(argvars, rettv)
11322 typval_T *argvars;
11323 typval_T *rettv;
11325 expand_T xpc;
11327 ExpandInit(&xpc);
11328 xpc.xp_context = EXPAND_FILES;
11329 rettv->v_type = VAR_STRING;
11330 rettv->vval.v_string = ExpandOne(&xpc, get_tv_string(&argvars[0]),
11331 NULL, WILD_USE_NL|WILD_SILENT, WILD_ALL);
11335 * "globpath()" function
11337 static void
11338 f_globpath(argvars, rettv)
11339 typval_T *argvars;
11340 typval_T *rettv;
11342 char_u buf1[NUMBUFLEN];
11343 char_u *file = get_tv_string_buf_chk(&argvars[1], buf1);
11345 rettv->v_type = VAR_STRING;
11346 if (file == NULL)
11347 rettv->vval.v_string = NULL;
11348 else
11349 rettv->vval.v_string = globpath(get_tv_string(&argvars[0]), file);
11353 * "has()" function
11355 static void
11356 f_has(argvars, rettv)
11357 typval_T *argvars;
11358 typval_T *rettv;
11360 int i;
11361 char_u *name;
11362 int n = FALSE;
11363 static char *(has_list[]) =
11365 #ifdef AMIGA
11366 "amiga",
11367 # ifdef FEAT_ARP
11368 "arp",
11369 # endif
11370 #endif
11371 #ifdef __BEOS__
11372 "beos",
11373 #endif
11374 #ifdef MSDOS
11375 # ifdef DJGPP
11376 "dos32",
11377 # else
11378 "dos16",
11379 # endif
11380 #endif
11381 #ifdef MACOS
11382 "mac",
11383 #endif
11384 #if defined(MACOS_X_UNIX)
11385 "macunix",
11386 #endif
11387 #ifdef OS2
11388 "os2",
11389 #endif
11390 #ifdef __QNX__
11391 "qnx",
11392 #endif
11393 #ifdef RISCOS
11394 "riscos",
11395 #endif
11396 #ifdef UNIX
11397 "unix",
11398 #endif
11399 #ifdef VMS
11400 "vms",
11401 #endif
11402 #ifdef WIN16
11403 "win16",
11404 #endif
11405 #ifdef WIN32
11406 "win32",
11407 #endif
11408 #if defined(UNIX) && (defined(__CYGWIN32__) || defined(__CYGWIN__))
11409 "win32unix",
11410 #endif
11411 #ifdef WIN64
11412 "win64",
11413 #endif
11414 #ifdef EBCDIC
11415 "ebcdic",
11416 #endif
11417 #ifndef CASE_INSENSITIVE_FILENAME
11418 "fname_case",
11419 #endif
11420 #ifdef FEAT_ARABIC
11421 "arabic",
11422 #endif
11423 #ifdef FEAT_AUTOCMD
11424 "autocmd",
11425 #endif
11426 #ifdef FEAT_BEVAL
11427 "balloon_eval",
11428 # ifndef FEAT_GUI_W32 /* other GUIs always have multiline balloons */
11429 "balloon_multiline",
11430 # endif
11431 #endif
11432 #if defined(SOME_BUILTIN_TCAPS) || defined(ALL_BUILTIN_TCAPS)
11433 "builtin_terms",
11434 # ifdef ALL_BUILTIN_TCAPS
11435 "all_builtin_terms",
11436 # endif
11437 #endif
11438 #ifdef FEAT_BYTEOFF
11439 "byte_offset",
11440 #endif
11441 #ifdef FEAT_CINDENT
11442 "cindent",
11443 #endif
11444 #ifdef FEAT_CLIENTSERVER
11445 "clientserver",
11446 #endif
11447 #ifdef FEAT_CLIPBOARD
11448 "clipboard",
11449 #endif
11450 #ifdef FEAT_CMDL_COMPL
11451 "cmdline_compl",
11452 #endif
11453 #ifdef FEAT_CMDHIST
11454 "cmdline_hist",
11455 #endif
11456 #ifdef FEAT_COMMENTS
11457 "comments",
11458 #endif
11459 #ifdef FEAT_CRYPT
11460 "cryptv",
11461 #endif
11462 #ifdef FEAT_CSCOPE
11463 "cscope",
11464 #endif
11465 #ifdef CURSOR_SHAPE
11466 "cursorshape",
11467 #endif
11468 #ifdef DEBUG
11469 "debug",
11470 #endif
11471 #ifdef FEAT_CON_DIALOG
11472 "dialog_con",
11473 #endif
11474 #ifdef FEAT_GUI_DIALOG
11475 "dialog_gui",
11476 #endif
11477 #ifdef FEAT_DIFF
11478 "diff",
11479 #endif
11480 #ifdef FEAT_DIGRAPHS
11481 "digraphs",
11482 #endif
11483 #ifdef FEAT_DND
11484 "dnd",
11485 #endif
11486 #ifdef FEAT_EMACS_TAGS
11487 "emacs_tags",
11488 #endif
11489 "eval", /* always present, of course! */
11490 #ifdef FEAT_EX_EXTRA
11491 "ex_extra",
11492 #endif
11493 #ifdef FEAT_SEARCH_EXTRA
11494 "extra_search",
11495 #endif
11496 #ifdef FEAT_FKMAP
11497 "farsi",
11498 #endif
11499 #ifdef FEAT_SEARCHPATH
11500 "file_in_path",
11501 #endif
11502 #if defined(UNIX) && !defined(USE_SYSTEM)
11503 "filterpipe",
11504 #endif
11505 #ifdef FEAT_FIND_ID
11506 "find_in_path",
11507 #endif
11508 #ifdef FEAT_FLOAT
11509 "float",
11510 #endif
11511 #ifdef FEAT_FOLDING
11512 "folding",
11513 #endif
11514 #ifdef FEAT_FOOTER
11515 "footer",
11516 #endif
11517 #if !defined(USE_SYSTEM) && defined(UNIX)
11518 "fork",
11519 #endif
11520 #ifdef FEAT_FULLSCREEN
11521 "fullscreen",
11522 #endif
11523 #ifdef FEAT_GETTEXT
11524 "gettext",
11525 #endif
11526 #ifdef FEAT_GUI
11527 "gui",
11528 #endif
11529 #ifdef FEAT_GUI_ATHENA
11530 # ifdef FEAT_GUI_NEXTAW
11531 "gui_neXtaw",
11532 # else
11533 "gui_athena",
11534 # endif
11535 #endif
11536 #ifdef FEAT_GUI_GTK
11537 "gui_gtk",
11538 # ifdef HAVE_GTK2
11539 "gui_gtk2",
11540 # endif
11541 #endif
11542 #ifdef FEAT_GUI_GNOME
11543 "gui_gnome",
11544 #endif
11545 #ifdef FEAT_GUI_MAC
11546 "gui_mac",
11547 #endif
11548 #ifdef FEAT_GUI_MACVIM
11549 "gui_macvim",
11550 #endif
11551 #ifdef FEAT_GUI_MOTIF
11552 "gui_motif",
11553 #endif
11554 #ifdef FEAT_GUI_PHOTON
11555 "gui_photon",
11556 #endif
11557 #ifdef FEAT_GUI_W16
11558 "gui_win16",
11559 #endif
11560 #ifdef FEAT_GUI_W32
11561 "gui_win32",
11562 #endif
11563 #ifdef FEAT_HANGULIN
11564 "hangul_input",
11565 #endif
11566 #if defined(HAVE_ICONV_H) && defined(USE_ICONV)
11567 "iconv",
11568 #endif
11569 #ifdef FEAT_INS_EXPAND
11570 "insert_expand",
11571 #endif
11572 #ifdef FEAT_JUMPLIST
11573 "jumplist",
11574 #endif
11575 #ifdef FEAT_KEYMAP
11576 "keymap",
11577 #endif
11578 #ifdef FEAT_LANGMAP
11579 "langmap",
11580 #endif
11581 #ifdef FEAT_LIBCALL
11582 "libcall",
11583 #endif
11584 #ifdef FEAT_LINEBREAK
11585 "linebreak",
11586 #endif
11587 #ifdef FEAT_LISP
11588 "lispindent",
11589 #endif
11590 #ifdef FEAT_LISTCMDS
11591 "listcmds",
11592 #endif
11593 #ifdef FEAT_LOCALMAP
11594 "localmap",
11595 #endif
11596 #ifdef FEAT_MENU
11597 "menu",
11598 #endif
11599 #ifdef FEAT_SESSION
11600 "mksession",
11601 #endif
11602 #ifdef FEAT_MODIFY_FNAME
11603 "modify_fname",
11604 #endif
11605 #ifdef FEAT_MOUSE
11606 "mouse",
11607 #endif
11608 #ifdef FEAT_MOUSESHAPE
11609 "mouseshape",
11610 #endif
11611 #if defined(UNIX) || defined(VMS)
11612 # ifdef FEAT_MOUSE_DEC
11613 "mouse_dec",
11614 # endif
11615 # ifdef FEAT_MOUSE_GPM
11616 "mouse_gpm",
11617 # endif
11618 # ifdef FEAT_MOUSE_JSB
11619 "mouse_jsbterm",
11620 # endif
11621 # ifdef FEAT_MOUSE_NET
11622 "mouse_netterm",
11623 # endif
11624 # ifdef FEAT_MOUSE_PTERM
11625 "mouse_pterm",
11626 # endif
11627 # ifdef FEAT_SYSMOUSE
11628 "mouse_sysmouse",
11629 # endif
11630 # ifdef FEAT_MOUSE_XTERM
11631 "mouse_xterm",
11632 # endif
11633 #endif
11634 #ifdef FEAT_MBYTE
11635 "multi_byte",
11636 #endif
11637 #ifdef FEAT_MBYTE_IME
11638 "multi_byte_ime",
11639 #endif
11640 #ifdef FEAT_MULTI_LANG
11641 "multi_lang",
11642 #endif
11643 #ifdef FEAT_MZSCHEME
11644 #ifndef DYNAMIC_MZSCHEME
11645 "mzscheme",
11646 #endif
11647 #endif
11648 #ifdef FEAT_OLE
11649 "ole",
11650 #endif
11651 #ifdef FEAT_OSFILETYPE
11652 "osfiletype",
11653 #endif
11654 #ifdef FEAT_PATH_EXTRA
11655 "path_extra",
11656 #endif
11657 #ifdef FEAT_PERL
11658 #ifndef DYNAMIC_PERL
11659 "perl",
11660 #endif
11661 #endif
11662 #ifdef FEAT_PYTHON
11663 #ifndef DYNAMIC_PYTHON
11664 "python",
11665 #endif
11666 #endif
11667 #ifdef FEAT_POSTSCRIPT
11668 "postscript",
11669 #endif
11670 #ifdef FEAT_PRINTER
11671 "printer",
11672 #endif
11673 #ifdef FEAT_PROFILE
11674 "profile",
11675 #endif
11676 #ifdef FEAT_RELTIME
11677 "reltime",
11678 #endif
11679 #ifdef FEAT_QUICKFIX
11680 "quickfix",
11681 #endif
11682 #ifdef FEAT_RIGHTLEFT
11683 "rightleft",
11684 #endif
11685 #if defined(FEAT_RUBY) && !defined(DYNAMIC_RUBY)
11686 "ruby",
11687 #endif
11688 #ifdef FEAT_SCROLLBIND
11689 "scrollbind",
11690 #endif
11691 #ifdef FEAT_CMDL_INFO
11692 "showcmd",
11693 "cmdline_info",
11694 #endif
11695 #ifdef FEAT_SIGNS
11696 "signs",
11697 #endif
11698 #ifdef FEAT_SMARTINDENT
11699 "smartindent",
11700 #endif
11701 #ifdef FEAT_SNIFF
11702 "sniff",
11703 #endif
11704 #ifdef FEAT_STL_OPT
11705 "statusline",
11706 #endif
11707 #ifdef FEAT_SUN_WORKSHOP
11708 "sun_workshop",
11709 #endif
11710 #ifdef FEAT_NETBEANS_INTG
11711 "netbeans_intg",
11712 #endif
11713 #ifdef FEAT_ODB_EDITOR
11714 "odbeditor",
11715 #endif
11716 #ifdef FEAT_SPELL
11717 "spell",
11718 #endif
11719 #ifdef FEAT_SYN_HL
11720 "syntax",
11721 #endif
11722 #if defined(USE_SYSTEM) || !defined(UNIX)
11723 "system",
11724 #endif
11725 #ifdef FEAT_TAG_BINS
11726 "tag_binary",
11727 #endif
11728 #ifdef FEAT_TAG_OLDSTATIC
11729 "tag_old_static",
11730 #endif
11731 #ifdef FEAT_TAG_ANYWHITE
11732 "tag_any_white",
11733 #endif
11734 #ifdef FEAT_TCL
11735 # ifndef DYNAMIC_TCL
11736 "tcl",
11737 # endif
11738 #endif
11739 #ifdef TERMINFO
11740 "terminfo",
11741 #endif
11742 #ifdef FEAT_TERMRESPONSE
11743 "termresponse",
11744 #endif
11745 #ifdef FEAT_TEXTOBJ
11746 "textobjects",
11747 #endif
11748 #ifdef HAVE_TGETENT
11749 "tgetent",
11750 #endif
11751 #ifdef FEAT_TITLE
11752 "title",
11753 #endif
11754 #ifdef FEAT_TOOLBAR
11755 "toolbar",
11756 #endif
11757 #ifdef FEAT_TRANSPARENCY
11758 "transparency",
11759 #endif
11760 #ifdef FEAT_USR_CMDS
11761 "user-commands", /* was accidentally included in 5.4 */
11762 "user_commands",
11763 #endif
11764 #ifdef FEAT_VIMINFO
11765 "viminfo",
11766 #endif
11767 #ifdef FEAT_VERTSPLIT
11768 "vertsplit",
11769 #endif
11770 #ifdef FEAT_VIRTUALEDIT
11771 "virtualedit",
11772 #endif
11773 #ifdef FEAT_VISUAL
11774 "visual",
11775 #endif
11776 #ifdef FEAT_VISUALEXTRA
11777 "visualextra",
11778 #endif
11779 #ifdef FEAT_VREPLACE
11780 "vreplace",
11781 #endif
11782 #ifdef FEAT_WILDIGN
11783 "wildignore",
11784 #endif
11785 #ifdef FEAT_WILDMENU
11786 "wildmenu",
11787 #endif
11788 #ifdef FEAT_WINDOWS
11789 "windows",
11790 #endif
11791 #ifdef FEAT_WAK
11792 "winaltkeys",
11793 #endif
11794 #ifdef FEAT_WRITEBACKUP
11795 "writebackup",
11796 #endif
11797 #ifdef FEAT_XIM
11798 "xim",
11799 #endif
11800 #ifdef FEAT_XFONTSET
11801 "xfontset",
11802 #endif
11803 #ifdef USE_XSMP
11804 "xsmp",
11805 #endif
11806 #ifdef USE_XSMP_INTERACT
11807 "xsmp_interact",
11808 #endif
11809 #ifdef FEAT_XCLIPBOARD
11810 "xterm_clipboard",
11811 #endif
11812 #ifdef FEAT_XTERM_SAVE
11813 "xterm_save",
11814 #endif
11815 #if defined(UNIX) && defined(FEAT_X11)
11816 "X11",
11817 #endif
11818 NULL
11821 name = get_tv_string(&argvars[0]);
11822 for (i = 0; has_list[i] != NULL; ++i)
11823 if (STRICMP(name, has_list[i]) == 0)
11825 n = TRUE;
11826 break;
11829 if (n == FALSE)
11831 if (STRNICMP(name, "patch", 5) == 0)
11832 n = has_patch(atoi((char *)name + 5));
11833 else if (STRICMP(name, "vim_starting") == 0)
11834 n = (starting != 0);
11835 #if defined(FEAT_BEVAL) && defined(FEAT_GUI_W32)
11836 else if (STRICMP(name, "balloon_multiline") == 0)
11837 n = multiline_balloon_available();
11838 #endif
11839 #ifdef DYNAMIC_TCL
11840 else if (STRICMP(name, "tcl") == 0)
11841 n = tcl_enabled(FALSE);
11842 #endif
11843 #if defined(USE_ICONV) && defined(DYNAMIC_ICONV)
11844 else if (STRICMP(name, "iconv") == 0)
11845 n = iconv_enabled(FALSE);
11846 #endif
11847 #ifdef DYNAMIC_MZSCHEME
11848 else if (STRICMP(name, "mzscheme") == 0)
11849 n = mzscheme_enabled(FALSE);
11850 #endif
11851 #ifdef DYNAMIC_RUBY
11852 else if (STRICMP(name, "ruby") == 0)
11853 n = ruby_enabled(FALSE);
11854 #endif
11855 #ifdef DYNAMIC_PYTHON
11856 else if (STRICMP(name, "python") == 0)
11857 n = python_enabled(FALSE);
11858 #endif
11859 #ifdef DYNAMIC_PERL
11860 else if (STRICMP(name, "perl") == 0)
11861 n = perl_enabled(FALSE);
11862 #endif
11863 #ifdef FEAT_GUI
11864 else if (STRICMP(name, "gui_running") == 0)
11865 n = (gui.in_use || gui.starting);
11866 # ifdef FEAT_GUI_W32
11867 else if (STRICMP(name, "gui_win32s") == 0)
11868 n = gui_is_win32s();
11869 # endif
11870 # ifdef FEAT_BROWSE
11871 else if (STRICMP(name, "browse") == 0)
11872 n = gui.in_use; /* gui_mch_browse() works when GUI is running */
11873 # endif
11874 #endif
11875 #ifdef FEAT_SYN_HL
11876 else if (STRICMP(name, "syntax_items") == 0)
11877 n = syntax_present(curbuf);
11878 #endif
11879 #if defined(WIN3264)
11880 else if (STRICMP(name, "win95") == 0)
11881 n = mch_windows95();
11882 #endif
11883 #ifdef FEAT_NETBEANS_INTG
11884 else if (STRICMP(name, "netbeans_enabled") == 0)
11885 n = usingNetbeans;
11886 #endif
11889 rettv->vval.v_number = n;
11893 * "has_key()" function
11895 static void
11896 f_has_key(argvars, rettv)
11897 typval_T *argvars;
11898 typval_T *rettv;
11900 rettv->vval.v_number = 0;
11901 if (argvars[0].v_type != VAR_DICT)
11903 EMSG(_(e_dictreq));
11904 return;
11906 if (argvars[0].vval.v_dict == NULL)
11907 return;
11909 rettv->vval.v_number = dict_find(argvars[0].vval.v_dict,
11910 get_tv_string(&argvars[1]), -1) != NULL;
11914 * "haslocaldir()" function
11916 /*ARGSUSED*/
11917 static void
11918 f_haslocaldir(argvars, rettv)
11919 typval_T *argvars;
11920 typval_T *rettv;
11922 rettv->vval.v_number = (curwin->w_localdir != NULL);
11926 * "hasmapto()" function
11928 static void
11929 f_hasmapto(argvars, rettv)
11930 typval_T *argvars;
11931 typval_T *rettv;
11933 char_u *name;
11934 char_u *mode;
11935 char_u buf[NUMBUFLEN];
11936 int abbr = FALSE;
11938 name = get_tv_string(&argvars[0]);
11939 if (argvars[1].v_type == VAR_UNKNOWN)
11940 mode = (char_u *)"nvo";
11941 else
11943 mode = get_tv_string_buf(&argvars[1], buf);
11944 if (argvars[2].v_type != VAR_UNKNOWN)
11945 abbr = get_tv_number(&argvars[2]);
11948 if (map_to_exists(name, mode, abbr))
11949 rettv->vval.v_number = TRUE;
11950 else
11951 rettv->vval.v_number = FALSE;
11955 * "histadd()" function
11957 /*ARGSUSED*/
11958 static void
11959 f_histadd(argvars, rettv)
11960 typval_T *argvars;
11961 typval_T *rettv;
11963 #ifdef FEAT_CMDHIST
11964 int histype;
11965 char_u *str;
11966 char_u buf[NUMBUFLEN];
11967 #endif
11969 rettv->vval.v_number = FALSE;
11970 if (check_restricted() || check_secure())
11971 return;
11972 #ifdef FEAT_CMDHIST
11973 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
11974 histype = str != NULL ? get_histtype(str) : -1;
11975 if (histype >= 0)
11977 str = get_tv_string_buf(&argvars[1], buf);
11978 if (*str != NUL)
11980 add_to_history(histype, str, FALSE, NUL);
11981 rettv->vval.v_number = TRUE;
11982 return;
11985 #endif
11989 * "histdel()" function
11991 /*ARGSUSED*/
11992 static void
11993 f_histdel(argvars, rettv)
11994 typval_T *argvars;
11995 typval_T *rettv;
11997 #ifdef FEAT_CMDHIST
11998 int n;
11999 char_u buf[NUMBUFLEN];
12000 char_u *str;
12002 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
12003 if (str == NULL)
12004 n = 0;
12005 else if (argvars[1].v_type == VAR_UNKNOWN)
12006 /* only one argument: clear entire history */
12007 n = clr_history(get_histtype(str));
12008 else if (argvars[1].v_type == VAR_NUMBER)
12009 /* index given: remove that entry */
12010 n = del_history_idx(get_histtype(str),
12011 (int)get_tv_number(&argvars[1]));
12012 else
12013 /* string given: remove all matching entries */
12014 n = del_history_entry(get_histtype(str),
12015 get_tv_string_buf(&argvars[1], buf));
12016 rettv->vval.v_number = n;
12017 #else
12018 rettv->vval.v_number = 0;
12019 #endif
12023 * "histget()" function
12025 /*ARGSUSED*/
12026 static void
12027 f_histget(argvars, rettv)
12028 typval_T *argvars;
12029 typval_T *rettv;
12031 #ifdef FEAT_CMDHIST
12032 int type;
12033 int idx;
12034 char_u *str;
12036 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
12037 if (str == NULL)
12038 rettv->vval.v_string = NULL;
12039 else
12041 type = get_histtype(str);
12042 if (argvars[1].v_type == VAR_UNKNOWN)
12043 idx = get_history_idx(type);
12044 else
12045 idx = (int)get_tv_number_chk(&argvars[1], NULL);
12046 /* -1 on type error */
12047 rettv->vval.v_string = vim_strsave(get_history_entry(type, idx));
12049 #else
12050 rettv->vval.v_string = NULL;
12051 #endif
12052 rettv->v_type = VAR_STRING;
12056 * "histnr()" function
12058 /*ARGSUSED*/
12059 static void
12060 f_histnr(argvars, rettv)
12061 typval_T *argvars;
12062 typval_T *rettv;
12064 int i;
12066 #ifdef FEAT_CMDHIST
12067 char_u *history = get_tv_string_chk(&argvars[0]);
12069 i = history == NULL ? HIST_CMD - 1 : get_histtype(history);
12070 if (i >= HIST_CMD && i < HIST_COUNT)
12071 i = get_history_idx(i);
12072 else
12073 #endif
12074 i = -1;
12075 rettv->vval.v_number = i;
12079 * "highlightID(name)" function
12081 static void
12082 f_hlID(argvars, rettv)
12083 typval_T *argvars;
12084 typval_T *rettv;
12086 rettv->vval.v_number = syn_name2id(get_tv_string(&argvars[0]));
12090 * "highlight_exists()" function
12092 static void
12093 f_hlexists(argvars, rettv)
12094 typval_T *argvars;
12095 typval_T *rettv;
12097 rettv->vval.v_number = highlight_exists(get_tv_string(&argvars[0]));
12101 * "hostname()" function
12103 /*ARGSUSED*/
12104 static void
12105 f_hostname(argvars, rettv)
12106 typval_T *argvars;
12107 typval_T *rettv;
12109 char_u hostname[256];
12111 mch_get_host_name(hostname, 256);
12112 rettv->v_type = VAR_STRING;
12113 rettv->vval.v_string = vim_strsave(hostname);
12117 * iconv() function
12119 /*ARGSUSED*/
12120 static void
12121 f_iconv(argvars, rettv)
12122 typval_T *argvars;
12123 typval_T *rettv;
12125 #ifdef FEAT_MBYTE
12126 char_u buf1[NUMBUFLEN];
12127 char_u buf2[NUMBUFLEN];
12128 char_u *from, *to, *str;
12129 vimconv_T vimconv;
12130 #endif
12132 rettv->v_type = VAR_STRING;
12133 rettv->vval.v_string = NULL;
12135 #ifdef FEAT_MBYTE
12136 str = get_tv_string(&argvars[0]);
12137 from = enc_canonize(enc_skip(get_tv_string_buf(&argvars[1], buf1)));
12138 to = enc_canonize(enc_skip(get_tv_string_buf(&argvars[2], buf2)));
12139 vimconv.vc_type = CONV_NONE;
12140 convert_setup(&vimconv, from, to);
12142 /* If the encodings are equal, no conversion needed. */
12143 if (vimconv.vc_type == CONV_NONE)
12144 rettv->vval.v_string = vim_strsave(str);
12145 else
12146 rettv->vval.v_string = string_convert(&vimconv, str, NULL);
12148 convert_setup(&vimconv, NULL, NULL);
12149 vim_free(from);
12150 vim_free(to);
12151 #endif
12155 * "indent()" function
12157 static void
12158 f_indent(argvars, rettv)
12159 typval_T *argvars;
12160 typval_T *rettv;
12162 linenr_T lnum;
12164 lnum = get_tv_lnum(argvars);
12165 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
12166 rettv->vval.v_number = get_indent_lnum(lnum);
12167 else
12168 rettv->vval.v_number = -1;
12172 * "index()" function
12174 static void
12175 f_index(argvars, rettv)
12176 typval_T *argvars;
12177 typval_T *rettv;
12179 list_T *l;
12180 listitem_T *item;
12181 long idx = 0;
12182 int ic = FALSE;
12184 rettv->vval.v_number = -1;
12185 if (argvars[0].v_type != VAR_LIST)
12187 EMSG(_(e_listreq));
12188 return;
12190 l = argvars[0].vval.v_list;
12191 if (l != NULL)
12193 item = l->lv_first;
12194 if (argvars[2].v_type != VAR_UNKNOWN)
12196 int error = FALSE;
12198 /* Start at specified item. Use the cached index that list_find()
12199 * sets, so that a negative number also works. */
12200 item = list_find(l, get_tv_number_chk(&argvars[2], &error));
12201 idx = l->lv_idx;
12202 if (argvars[3].v_type != VAR_UNKNOWN)
12203 ic = get_tv_number_chk(&argvars[3], &error);
12204 if (error)
12205 item = NULL;
12208 for ( ; item != NULL; item = item->li_next, ++idx)
12209 if (tv_equal(&item->li_tv, &argvars[1], ic))
12211 rettv->vval.v_number = idx;
12212 break;
12217 static int inputsecret_flag = 0;
12219 static void get_user_input __ARGS((typval_T *argvars, typval_T *rettv, int inputdialog));
12222 * This function is used by f_input() and f_inputdialog() functions. The third
12223 * argument to f_input() specifies the type of completion to use at the
12224 * prompt. The third argument to f_inputdialog() specifies the value to return
12225 * when the user cancels the prompt.
12227 static void
12228 get_user_input(argvars, rettv, inputdialog)
12229 typval_T *argvars;
12230 typval_T *rettv;
12231 int inputdialog;
12233 char_u *prompt = get_tv_string_chk(&argvars[0]);
12234 char_u *p = NULL;
12235 int c;
12236 char_u buf[NUMBUFLEN];
12237 int cmd_silent_save = cmd_silent;
12238 char_u *defstr = (char_u *)"";
12239 int xp_type = EXPAND_NOTHING;
12240 char_u *xp_arg = NULL;
12242 rettv->v_type = VAR_STRING;
12243 rettv->vval.v_string = NULL;
12245 #ifdef NO_CONSOLE_INPUT
12246 /* While starting up, there is no place to enter text. */
12247 if (no_console_input())
12248 return;
12249 #endif
12251 cmd_silent = FALSE; /* Want to see the prompt. */
12252 if (prompt != NULL)
12254 /* Only the part of the message after the last NL is considered as
12255 * prompt for the command line */
12256 p = vim_strrchr(prompt, '\n');
12257 if (p == NULL)
12258 p = prompt;
12259 else
12261 ++p;
12262 c = *p;
12263 *p = NUL;
12264 msg_start();
12265 msg_clr_eos();
12266 msg_puts_attr(prompt, echo_attr);
12267 msg_didout = FALSE;
12268 msg_starthere();
12269 *p = c;
12271 cmdline_row = msg_row;
12273 if (argvars[1].v_type != VAR_UNKNOWN)
12275 defstr = get_tv_string_buf_chk(&argvars[1], buf);
12276 if (defstr != NULL)
12277 stuffReadbuffSpec(defstr);
12279 if (!inputdialog && argvars[2].v_type != VAR_UNKNOWN)
12281 char_u *xp_name;
12282 int xp_namelen;
12283 long argt;
12285 rettv->vval.v_string = NULL;
12287 xp_name = get_tv_string_buf_chk(&argvars[2], buf);
12288 if (xp_name == NULL)
12289 return;
12291 xp_namelen = (int)STRLEN(xp_name);
12293 if (parse_compl_arg(xp_name, xp_namelen, &xp_type, &argt,
12294 &xp_arg) == FAIL)
12295 return;
12299 if (defstr != NULL)
12300 rettv->vval.v_string =
12301 getcmdline_prompt(inputsecret_flag ? NUL : '@', p, echo_attr,
12302 xp_type, xp_arg);
12304 vim_free(xp_arg);
12306 /* since the user typed this, no need to wait for return */
12307 need_wait_return = FALSE;
12308 msg_didout = FALSE;
12310 cmd_silent = cmd_silent_save;
12314 * "input()" function
12315 * Also handles inputsecret() when inputsecret is set.
12317 static void
12318 f_input(argvars, rettv)
12319 typval_T *argvars;
12320 typval_T *rettv;
12322 get_user_input(argvars, rettv, FALSE);
12326 * "inputdialog()" function
12328 static void
12329 f_inputdialog(argvars, rettv)
12330 typval_T *argvars;
12331 typval_T *rettv;
12333 #if defined(FEAT_GUI_TEXTDIALOG)
12334 /* Use a GUI dialog if the GUI is running and 'c' is not in 'guioptions' */
12335 if (gui.in_use && vim_strchr(p_go, GO_CONDIALOG) == NULL)
12337 char_u *message;
12338 char_u buf[NUMBUFLEN];
12339 char_u *defstr = (char_u *)"";
12341 message = get_tv_string_chk(&argvars[0]);
12342 if (argvars[1].v_type != VAR_UNKNOWN
12343 && (defstr = get_tv_string_buf_chk(&argvars[1], buf)) != NULL)
12344 vim_strncpy(IObuff, defstr, IOSIZE - 1);
12345 else
12346 IObuff[0] = NUL;
12347 if (message != NULL && defstr != NULL
12348 && do_dialog(VIM_QUESTION, NULL, message,
12349 (char_u *)_("&OK\n&Cancel"), 1, IObuff) == 1)
12350 rettv->vval.v_string = vim_strsave(IObuff);
12351 else
12353 if (message != NULL && defstr != NULL
12354 && argvars[1].v_type != VAR_UNKNOWN
12355 && argvars[2].v_type != VAR_UNKNOWN)
12356 rettv->vval.v_string = vim_strsave(
12357 get_tv_string_buf(&argvars[2], buf));
12358 else
12359 rettv->vval.v_string = NULL;
12361 rettv->v_type = VAR_STRING;
12363 else
12364 #endif
12365 get_user_input(argvars, rettv, TRUE);
12369 * "inputlist()" function
12371 static void
12372 f_inputlist(argvars, rettv)
12373 typval_T *argvars;
12374 typval_T *rettv;
12376 listitem_T *li;
12377 int selected;
12378 int mouse_used;
12380 rettv->vval.v_number = 0;
12381 #ifdef NO_CONSOLE_INPUT
12382 /* While starting up, there is no place to enter text. */
12383 if (no_console_input())
12384 return;
12385 #endif
12386 if (argvars[0].v_type != VAR_LIST || argvars[0].vval.v_list == NULL)
12388 EMSG2(_(e_listarg), "inputlist()");
12389 return;
12392 msg_start();
12393 msg_row = Rows - 1; /* for when 'cmdheight' > 1 */
12394 lines_left = Rows; /* avoid more prompt */
12395 msg_scroll = TRUE;
12396 msg_clr_eos();
12398 for (li = argvars[0].vval.v_list->lv_first; li != NULL; li = li->li_next)
12400 msg_puts(get_tv_string(&li->li_tv));
12401 msg_putchar('\n');
12404 /* Ask for choice. */
12405 selected = prompt_for_number(&mouse_used);
12406 if (mouse_used)
12407 selected -= lines_left;
12409 rettv->vval.v_number = selected;
12413 static garray_T ga_userinput = {0, 0, sizeof(tasave_T), 4, NULL};
12416 * "inputrestore()" function
12418 /*ARGSUSED*/
12419 static void
12420 f_inputrestore(argvars, rettv)
12421 typval_T *argvars;
12422 typval_T *rettv;
12424 if (ga_userinput.ga_len > 0)
12426 --ga_userinput.ga_len;
12427 restore_typeahead((tasave_T *)(ga_userinput.ga_data)
12428 + ga_userinput.ga_len);
12429 rettv->vval.v_number = 0; /* OK */
12431 else if (p_verbose > 1)
12433 verb_msg((char_u *)_("called inputrestore() more often than inputsave()"));
12434 rettv->vval.v_number = 1; /* Failed */
12439 * "inputsave()" function
12441 /*ARGSUSED*/
12442 static void
12443 f_inputsave(argvars, rettv)
12444 typval_T *argvars;
12445 typval_T *rettv;
12447 /* Add an entry to the stack of typeahead storage. */
12448 if (ga_grow(&ga_userinput, 1) == OK)
12450 save_typeahead((tasave_T *)(ga_userinput.ga_data)
12451 + ga_userinput.ga_len);
12452 ++ga_userinput.ga_len;
12453 rettv->vval.v_number = 0; /* OK */
12455 else
12456 rettv->vval.v_number = 1; /* Failed */
12460 * "inputsecret()" function
12462 static void
12463 f_inputsecret(argvars, rettv)
12464 typval_T *argvars;
12465 typval_T *rettv;
12467 ++cmdline_star;
12468 ++inputsecret_flag;
12469 f_input(argvars, rettv);
12470 --cmdline_star;
12471 --inputsecret_flag;
12475 * "insert()" function
12477 static void
12478 f_insert(argvars, rettv)
12479 typval_T *argvars;
12480 typval_T *rettv;
12482 long before = 0;
12483 listitem_T *item;
12484 list_T *l;
12485 int error = FALSE;
12487 rettv->vval.v_number = 0;
12488 if (argvars[0].v_type != VAR_LIST)
12489 EMSG2(_(e_listarg), "insert()");
12490 else if ((l = argvars[0].vval.v_list) != NULL
12491 && !tv_check_lock(l->lv_lock, (char_u *)"insert()"))
12493 if (argvars[2].v_type != VAR_UNKNOWN)
12494 before = get_tv_number_chk(&argvars[2], &error);
12495 if (error)
12496 return; /* type error; errmsg already given */
12498 if (before == l->lv_len)
12499 item = NULL;
12500 else
12502 item = list_find(l, before);
12503 if (item == NULL)
12505 EMSGN(_(e_listidx), before);
12506 l = NULL;
12509 if (l != NULL)
12511 list_insert_tv(l, &argvars[1], item);
12512 copy_tv(&argvars[0], rettv);
12518 * "isdirectory()" function
12520 static void
12521 f_isdirectory(argvars, rettv)
12522 typval_T *argvars;
12523 typval_T *rettv;
12525 rettv->vval.v_number = mch_isdir(get_tv_string(&argvars[0]));
12529 * "islocked()" function
12531 static void
12532 f_islocked(argvars, rettv)
12533 typval_T *argvars;
12534 typval_T *rettv;
12536 lval_T lv;
12537 char_u *end;
12538 dictitem_T *di;
12540 rettv->vval.v_number = -1;
12541 end = get_lval(get_tv_string(&argvars[0]), NULL, &lv, FALSE, FALSE, FALSE,
12542 FNE_CHECK_START);
12543 if (end != NULL && lv.ll_name != NULL)
12545 if (*end != NUL)
12546 EMSG(_(e_trailing));
12547 else
12549 if (lv.ll_tv == NULL)
12551 if (check_changedtick(lv.ll_name))
12552 rettv->vval.v_number = 1; /* always locked */
12553 else
12555 di = find_var(lv.ll_name, NULL);
12556 if (di != NULL)
12558 /* Consider a variable locked when:
12559 * 1. the variable itself is locked
12560 * 2. the value of the variable is locked.
12561 * 3. the List or Dict value is locked.
12563 rettv->vval.v_number = ((di->di_flags & DI_FLAGS_LOCK)
12564 || tv_islocked(&di->di_tv));
12568 else if (lv.ll_range)
12569 EMSG(_("E786: Range not allowed"));
12570 else if (lv.ll_newkey != NULL)
12571 EMSG2(_(e_dictkey), lv.ll_newkey);
12572 else if (lv.ll_list != NULL)
12573 /* List item. */
12574 rettv->vval.v_number = tv_islocked(&lv.ll_li->li_tv);
12575 else
12576 /* Dictionary item. */
12577 rettv->vval.v_number = tv_islocked(&lv.ll_di->di_tv);
12581 clear_lval(&lv);
12584 static void dict_list __ARGS((typval_T *argvars, typval_T *rettv, int what));
12587 * Turn a dict into a list:
12588 * "what" == 0: list of keys
12589 * "what" == 1: list of values
12590 * "what" == 2: list of items
12592 static void
12593 dict_list(argvars, rettv, what)
12594 typval_T *argvars;
12595 typval_T *rettv;
12596 int what;
12598 list_T *l2;
12599 dictitem_T *di;
12600 hashitem_T *hi;
12601 listitem_T *li;
12602 listitem_T *li2;
12603 dict_T *d;
12604 int todo;
12606 rettv->vval.v_number = 0;
12607 if (argvars[0].v_type != VAR_DICT)
12609 EMSG(_(e_dictreq));
12610 return;
12612 if ((d = argvars[0].vval.v_dict) == NULL)
12613 return;
12615 if (rettv_list_alloc(rettv) == FAIL)
12616 return;
12618 todo = (int)d->dv_hashtab.ht_used;
12619 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
12621 if (!HASHITEM_EMPTY(hi))
12623 --todo;
12624 di = HI2DI(hi);
12626 li = listitem_alloc();
12627 if (li == NULL)
12628 break;
12629 list_append(rettv->vval.v_list, li);
12631 if (what == 0)
12633 /* keys() */
12634 li->li_tv.v_type = VAR_STRING;
12635 li->li_tv.v_lock = 0;
12636 li->li_tv.vval.v_string = vim_strsave(di->di_key);
12638 else if (what == 1)
12640 /* values() */
12641 copy_tv(&di->di_tv, &li->li_tv);
12643 else
12645 /* items() */
12646 l2 = list_alloc();
12647 li->li_tv.v_type = VAR_LIST;
12648 li->li_tv.v_lock = 0;
12649 li->li_tv.vval.v_list = l2;
12650 if (l2 == NULL)
12651 break;
12652 ++l2->lv_refcount;
12654 li2 = listitem_alloc();
12655 if (li2 == NULL)
12656 break;
12657 list_append(l2, li2);
12658 li2->li_tv.v_type = VAR_STRING;
12659 li2->li_tv.v_lock = 0;
12660 li2->li_tv.vval.v_string = vim_strsave(di->di_key);
12662 li2 = listitem_alloc();
12663 if (li2 == NULL)
12664 break;
12665 list_append(l2, li2);
12666 copy_tv(&di->di_tv, &li2->li_tv);
12673 * "items(dict)" function
12675 static void
12676 f_items(argvars, rettv)
12677 typval_T *argvars;
12678 typval_T *rettv;
12680 dict_list(argvars, rettv, 2);
12684 * "join()" function
12686 static void
12687 f_join(argvars, rettv)
12688 typval_T *argvars;
12689 typval_T *rettv;
12691 garray_T ga;
12692 char_u *sep;
12694 rettv->vval.v_number = 0;
12695 if (argvars[0].v_type != VAR_LIST)
12697 EMSG(_(e_listreq));
12698 return;
12700 if (argvars[0].vval.v_list == NULL)
12701 return;
12702 if (argvars[1].v_type == VAR_UNKNOWN)
12703 sep = (char_u *)" ";
12704 else
12705 sep = get_tv_string_chk(&argvars[1]);
12707 rettv->v_type = VAR_STRING;
12709 if (sep != NULL)
12711 ga_init2(&ga, (int)sizeof(char), 80);
12712 list_join(&ga, argvars[0].vval.v_list, sep, TRUE, 0);
12713 ga_append(&ga, NUL);
12714 rettv->vval.v_string = (char_u *)ga.ga_data;
12716 else
12717 rettv->vval.v_string = NULL;
12721 * "keys()" function
12723 static void
12724 f_keys(argvars, rettv)
12725 typval_T *argvars;
12726 typval_T *rettv;
12728 dict_list(argvars, rettv, 0);
12732 * "last_buffer_nr()" function.
12734 /*ARGSUSED*/
12735 static void
12736 f_last_buffer_nr(argvars, rettv)
12737 typval_T *argvars;
12738 typval_T *rettv;
12740 int n = 0;
12741 buf_T *buf;
12743 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
12744 if (n < buf->b_fnum)
12745 n = buf->b_fnum;
12747 rettv->vval.v_number = n;
12751 * "len()" function
12753 static void
12754 f_len(argvars, rettv)
12755 typval_T *argvars;
12756 typval_T *rettv;
12758 switch (argvars[0].v_type)
12760 case VAR_STRING:
12761 case VAR_NUMBER:
12762 rettv->vval.v_number = (varnumber_T)STRLEN(
12763 get_tv_string(&argvars[0]));
12764 break;
12765 case VAR_LIST:
12766 rettv->vval.v_number = list_len(argvars[0].vval.v_list);
12767 break;
12768 case VAR_DICT:
12769 rettv->vval.v_number = dict_len(argvars[0].vval.v_dict);
12770 break;
12771 default:
12772 EMSG(_("E701: Invalid type for len()"));
12773 break;
12777 static void libcall_common __ARGS((typval_T *argvars, typval_T *rettv, int type));
12779 static void
12780 libcall_common(argvars, rettv, type)
12781 typval_T *argvars;
12782 typval_T *rettv;
12783 int type;
12785 #ifdef FEAT_LIBCALL
12786 char_u *string_in;
12787 char_u **string_result;
12788 int nr_result;
12789 #endif
12791 rettv->v_type = type;
12792 if (type == VAR_NUMBER)
12793 rettv->vval.v_number = 0;
12794 else
12795 rettv->vval.v_string = NULL;
12797 if (check_restricted() || check_secure())
12798 return;
12800 #ifdef FEAT_LIBCALL
12801 /* The first two args must be strings, otherwise its meaningless */
12802 if (argvars[0].v_type == VAR_STRING && argvars[1].v_type == VAR_STRING)
12804 string_in = NULL;
12805 if (argvars[2].v_type == VAR_STRING)
12806 string_in = argvars[2].vval.v_string;
12807 if (type == VAR_NUMBER)
12808 string_result = NULL;
12809 else
12810 string_result = &rettv->vval.v_string;
12811 if (mch_libcall(argvars[0].vval.v_string,
12812 argvars[1].vval.v_string,
12813 string_in,
12814 argvars[2].vval.v_number,
12815 string_result,
12816 &nr_result) == OK
12817 && type == VAR_NUMBER)
12818 rettv->vval.v_number = nr_result;
12820 #endif
12824 * "libcall()" function
12826 static void
12827 f_libcall(argvars, rettv)
12828 typval_T *argvars;
12829 typval_T *rettv;
12831 libcall_common(argvars, rettv, VAR_STRING);
12835 * "libcallnr()" function
12837 static void
12838 f_libcallnr(argvars, rettv)
12839 typval_T *argvars;
12840 typval_T *rettv;
12842 libcall_common(argvars, rettv, VAR_NUMBER);
12846 * "line(string)" function
12848 static void
12849 f_line(argvars, rettv)
12850 typval_T *argvars;
12851 typval_T *rettv;
12853 linenr_T lnum = 0;
12854 pos_T *fp;
12855 int fnum;
12857 fp = var2fpos(&argvars[0], TRUE, &fnum);
12858 if (fp != NULL)
12859 lnum = fp->lnum;
12860 rettv->vval.v_number = lnum;
12864 * "line2byte(lnum)" function
12866 /*ARGSUSED*/
12867 static void
12868 f_line2byte(argvars, rettv)
12869 typval_T *argvars;
12870 typval_T *rettv;
12872 #ifndef FEAT_BYTEOFF
12873 rettv->vval.v_number = -1;
12874 #else
12875 linenr_T lnum;
12877 lnum = get_tv_lnum(argvars);
12878 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
12879 rettv->vval.v_number = -1;
12880 else
12881 rettv->vval.v_number = ml_find_line_or_offset(curbuf, lnum, NULL);
12882 if (rettv->vval.v_number >= 0)
12883 ++rettv->vval.v_number;
12884 #endif
12888 * "lispindent(lnum)" function
12890 static void
12891 f_lispindent(argvars, rettv)
12892 typval_T *argvars;
12893 typval_T *rettv;
12895 #ifdef FEAT_LISP
12896 pos_T pos;
12897 linenr_T lnum;
12899 pos = curwin->w_cursor;
12900 lnum = get_tv_lnum(argvars);
12901 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
12903 curwin->w_cursor.lnum = lnum;
12904 rettv->vval.v_number = get_lisp_indent();
12905 curwin->w_cursor = pos;
12907 else
12908 #endif
12909 rettv->vval.v_number = -1;
12913 * "localtime()" function
12915 /*ARGSUSED*/
12916 static void
12917 f_localtime(argvars, rettv)
12918 typval_T *argvars;
12919 typval_T *rettv;
12921 rettv->vval.v_number = (varnumber_T)time(NULL);
12924 static void get_maparg __ARGS((typval_T *argvars, typval_T *rettv, int exact));
12926 static void
12927 get_maparg(argvars, rettv, exact)
12928 typval_T *argvars;
12929 typval_T *rettv;
12930 int exact;
12932 char_u *keys;
12933 char_u *which;
12934 char_u buf[NUMBUFLEN];
12935 char_u *keys_buf = NULL;
12936 char_u *rhs;
12937 int mode;
12938 garray_T ga;
12939 int abbr = FALSE;
12941 /* return empty string for failure */
12942 rettv->v_type = VAR_STRING;
12943 rettv->vval.v_string = NULL;
12945 keys = get_tv_string(&argvars[0]);
12946 if (*keys == NUL)
12947 return;
12949 if (argvars[1].v_type != VAR_UNKNOWN)
12951 which = get_tv_string_buf_chk(&argvars[1], buf);
12952 if (argvars[2].v_type != VAR_UNKNOWN)
12953 abbr = get_tv_number(&argvars[2]);
12955 else
12956 which = (char_u *)"";
12957 if (which == NULL)
12958 return;
12960 mode = get_map_mode(&which, 0);
12962 keys = replace_termcodes(keys, &keys_buf, TRUE, TRUE, FALSE);
12963 rhs = check_map(keys, mode, exact, FALSE, abbr);
12964 vim_free(keys_buf);
12965 if (rhs != NULL)
12967 ga_init(&ga);
12968 ga.ga_itemsize = 1;
12969 ga.ga_growsize = 40;
12971 while (*rhs != NUL)
12972 ga_concat(&ga, str2special(&rhs, FALSE));
12974 ga_append(&ga, NUL);
12975 rettv->vval.v_string = (char_u *)ga.ga_data;
12979 #ifdef FEAT_FLOAT
12981 * "log10()" function
12983 static void
12984 f_log10(argvars, rettv)
12985 typval_T *argvars;
12986 typval_T *rettv;
12988 float_T f;
12990 rettv->v_type = VAR_FLOAT;
12991 if (get_float_arg(argvars, &f) == OK)
12992 rettv->vval.v_float = log10(f);
12993 else
12994 rettv->vval.v_float = 0.0;
12996 #endif
12999 * "map()" function
13001 static void
13002 f_map(argvars, rettv)
13003 typval_T *argvars;
13004 typval_T *rettv;
13006 filter_map(argvars, rettv, TRUE);
13010 * "maparg()" function
13012 static void
13013 f_maparg(argvars, rettv)
13014 typval_T *argvars;
13015 typval_T *rettv;
13017 get_maparg(argvars, rettv, TRUE);
13021 * "mapcheck()" function
13023 static void
13024 f_mapcheck(argvars, rettv)
13025 typval_T *argvars;
13026 typval_T *rettv;
13028 get_maparg(argvars, rettv, FALSE);
13031 static void find_some_match __ARGS((typval_T *argvars, typval_T *rettv, int start));
13033 static void
13034 find_some_match(argvars, rettv, type)
13035 typval_T *argvars;
13036 typval_T *rettv;
13037 int type;
13039 char_u *str = NULL;
13040 char_u *expr = NULL;
13041 char_u *pat;
13042 regmatch_T regmatch;
13043 char_u patbuf[NUMBUFLEN];
13044 char_u strbuf[NUMBUFLEN];
13045 char_u *save_cpo;
13046 long start = 0;
13047 long nth = 1;
13048 colnr_T startcol = 0;
13049 int match = 0;
13050 list_T *l = NULL;
13051 listitem_T *li = NULL;
13052 long idx = 0;
13053 char_u *tofree = NULL;
13055 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
13056 save_cpo = p_cpo;
13057 p_cpo = (char_u *)"";
13059 rettv->vval.v_number = -1;
13060 if (type == 3)
13062 /* return empty list when there are no matches */
13063 if (rettv_list_alloc(rettv) == FAIL)
13064 goto theend;
13066 else if (type == 2)
13068 rettv->v_type = VAR_STRING;
13069 rettv->vval.v_string = NULL;
13072 if (argvars[0].v_type == VAR_LIST)
13074 if ((l = argvars[0].vval.v_list) == NULL)
13075 goto theend;
13076 li = l->lv_first;
13078 else
13079 expr = str = get_tv_string(&argvars[0]);
13081 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
13082 if (pat == NULL)
13083 goto theend;
13085 if (argvars[2].v_type != VAR_UNKNOWN)
13087 int error = FALSE;
13089 start = get_tv_number_chk(&argvars[2], &error);
13090 if (error)
13091 goto theend;
13092 if (l != NULL)
13094 li = list_find(l, start);
13095 if (li == NULL)
13096 goto theend;
13097 idx = l->lv_idx; /* use the cached index */
13099 else
13101 if (start < 0)
13102 start = 0;
13103 if (start > (long)STRLEN(str))
13104 goto theend;
13105 /* When "count" argument is there ignore matches before "start",
13106 * otherwise skip part of the string. Differs when pattern is "^"
13107 * or "\<". */
13108 if (argvars[3].v_type != VAR_UNKNOWN)
13109 startcol = start;
13110 else
13111 str += start;
13114 if (argvars[3].v_type != VAR_UNKNOWN)
13115 nth = get_tv_number_chk(&argvars[3], &error);
13116 if (error)
13117 goto theend;
13120 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
13121 if (regmatch.regprog != NULL)
13123 regmatch.rm_ic = p_ic;
13125 for (;;)
13127 if (l != NULL)
13129 if (li == NULL)
13131 match = FALSE;
13132 break;
13134 vim_free(tofree);
13135 str = echo_string(&li->li_tv, &tofree, strbuf, 0);
13136 if (str == NULL)
13137 break;
13140 match = vim_regexec_nl(&regmatch, str, (colnr_T)startcol);
13142 if (match && --nth <= 0)
13143 break;
13144 if (l == NULL && !match)
13145 break;
13147 /* Advance to just after the match. */
13148 if (l != NULL)
13150 li = li->li_next;
13151 ++idx;
13153 else
13155 #ifdef FEAT_MBYTE
13156 startcol = (colnr_T)(regmatch.startp[0]
13157 + (*mb_ptr2len)(regmatch.startp[0]) - str);
13158 #else
13159 startcol = regmatch.startp[0] + 1 - str;
13160 #endif
13164 if (match)
13166 if (type == 3)
13168 int i;
13170 /* return list with matched string and submatches */
13171 for (i = 0; i < NSUBEXP; ++i)
13173 if (regmatch.endp[i] == NULL)
13175 if (list_append_string(rettv->vval.v_list,
13176 (char_u *)"", 0) == FAIL)
13177 break;
13179 else if (list_append_string(rettv->vval.v_list,
13180 regmatch.startp[i],
13181 (int)(regmatch.endp[i] - regmatch.startp[i]))
13182 == FAIL)
13183 break;
13186 else if (type == 2)
13188 /* return matched string */
13189 if (l != NULL)
13190 copy_tv(&li->li_tv, rettv);
13191 else
13192 rettv->vval.v_string = vim_strnsave(regmatch.startp[0],
13193 (int)(regmatch.endp[0] - regmatch.startp[0]));
13195 else if (l != NULL)
13196 rettv->vval.v_number = idx;
13197 else
13199 if (type != 0)
13200 rettv->vval.v_number =
13201 (varnumber_T)(regmatch.startp[0] - str);
13202 else
13203 rettv->vval.v_number =
13204 (varnumber_T)(regmatch.endp[0] - str);
13205 rettv->vval.v_number += (varnumber_T)(str - expr);
13208 vim_free(regmatch.regprog);
13211 theend:
13212 vim_free(tofree);
13213 p_cpo = save_cpo;
13217 * "match()" function
13219 static void
13220 f_match(argvars, rettv)
13221 typval_T *argvars;
13222 typval_T *rettv;
13224 find_some_match(argvars, rettv, 1);
13228 * "matchadd()" function
13230 static void
13231 f_matchadd(argvars, rettv)
13232 typval_T *argvars;
13233 typval_T *rettv;
13235 #ifdef FEAT_SEARCH_EXTRA
13236 char_u buf[NUMBUFLEN];
13237 char_u *grp = get_tv_string_buf_chk(&argvars[0], buf); /* group */
13238 char_u *pat = get_tv_string_buf_chk(&argvars[1], buf); /* pattern */
13239 int prio = 10; /* default priority */
13240 int id = -1;
13241 int error = FALSE;
13243 rettv->vval.v_number = -1;
13245 if (grp == NULL || pat == NULL)
13246 return;
13247 if (argvars[2].v_type != VAR_UNKNOWN)
13249 prio = get_tv_number_chk(&argvars[2], &error);
13250 if (argvars[3].v_type != VAR_UNKNOWN)
13251 id = get_tv_number_chk(&argvars[3], &error);
13253 if (error == TRUE)
13254 return;
13255 if (id >= 1 && id <= 3)
13257 EMSGN("E798: ID is reserved for \":match\": %ld", id);
13258 return;
13261 rettv->vval.v_number = match_add(curwin, grp, pat, prio, id);
13262 #endif
13266 * "matcharg()" function
13268 static void
13269 f_matcharg(argvars, rettv)
13270 typval_T *argvars;
13271 typval_T *rettv;
13273 if (rettv_list_alloc(rettv) == OK)
13275 #ifdef FEAT_SEARCH_EXTRA
13276 int id = get_tv_number(&argvars[0]);
13277 matchitem_T *m;
13279 if (id >= 1 && id <= 3)
13281 if ((m = (matchitem_T *)get_match(curwin, id)) != NULL)
13283 list_append_string(rettv->vval.v_list,
13284 syn_id2name(m->hlg_id), -1);
13285 list_append_string(rettv->vval.v_list, m->pattern, -1);
13287 else
13289 list_append_string(rettv->vval.v_list, NUL, -1);
13290 list_append_string(rettv->vval.v_list, NUL, -1);
13293 #endif
13298 * "matchdelete()" function
13300 static void
13301 f_matchdelete(argvars, rettv)
13302 typval_T *argvars;
13303 typval_T *rettv;
13305 #ifdef FEAT_SEARCH_EXTRA
13306 rettv->vval.v_number = match_delete(curwin,
13307 (int)get_tv_number(&argvars[0]), TRUE);
13308 #endif
13312 * "matchend()" function
13314 static void
13315 f_matchend(argvars, rettv)
13316 typval_T *argvars;
13317 typval_T *rettv;
13319 find_some_match(argvars, rettv, 0);
13323 * "matchlist()" function
13325 static void
13326 f_matchlist(argvars, rettv)
13327 typval_T *argvars;
13328 typval_T *rettv;
13330 find_some_match(argvars, rettv, 3);
13334 * "matchstr()" function
13336 static void
13337 f_matchstr(argvars, rettv)
13338 typval_T *argvars;
13339 typval_T *rettv;
13341 find_some_match(argvars, rettv, 2);
13344 static void max_min __ARGS((typval_T *argvars, typval_T *rettv, int domax));
13346 static void
13347 max_min(argvars, rettv, domax)
13348 typval_T *argvars;
13349 typval_T *rettv;
13350 int domax;
13352 long n = 0;
13353 long i;
13354 int error = FALSE;
13356 if (argvars[0].v_type == VAR_LIST)
13358 list_T *l;
13359 listitem_T *li;
13361 l = argvars[0].vval.v_list;
13362 if (l != NULL)
13364 li = l->lv_first;
13365 if (li != NULL)
13367 n = get_tv_number_chk(&li->li_tv, &error);
13368 for (;;)
13370 li = li->li_next;
13371 if (li == NULL)
13372 break;
13373 i = get_tv_number_chk(&li->li_tv, &error);
13374 if (domax ? i > n : i < n)
13375 n = i;
13380 else if (argvars[0].v_type == VAR_DICT)
13382 dict_T *d;
13383 int first = TRUE;
13384 hashitem_T *hi;
13385 int todo;
13387 d = argvars[0].vval.v_dict;
13388 if (d != NULL)
13390 todo = (int)d->dv_hashtab.ht_used;
13391 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
13393 if (!HASHITEM_EMPTY(hi))
13395 --todo;
13396 i = get_tv_number_chk(&HI2DI(hi)->di_tv, &error);
13397 if (first)
13399 n = i;
13400 first = FALSE;
13402 else if (domax ? i > n : i < n)
13403 n = i;
13408 else
13409 EMSG(_(e_listdictarg));
13410 rettv->vval.v_number = error ? 0 : n;
13414 * "max()" function
13416 static void
13417 f_max(argvars, rettv)
13418 typval_T *argvars;
13419 typval_T *rettv;
13421 max_min(argvars, rettv, TRUE);
13425 * "min()" function
13427 static void
13428 f_min(argvars, rettv)
13429 typval_T *argvars;
13430 typval_T *rettv;
13432 max_min(argvars, rettv, FALSE);
13435 static int mkdir_recurse __ARGS((char_u *dir, int prot));
13438 * Create the directory in which "dir" is located, and higher levels when
13439 * needed.
13441 static int
13442 mkdir_recurse(dir, prot)
13443 char_u *dir;
13444 int prot;
13446 char_u *p;
13447 char_u *updir;
13448 int r = FAIL;
13450 /* Get end of directory name in "dir".
13451 * We're done when it's "/" or "c:/". */
13452 p = gettail_sep(dir);
13453 if (p <= get_past_head(dir))
13454 return OK;
13456 /* If the directory exists we're done. Otherwise: create it.*/
13457 updir = vim_strnsave(dir, (int)(p - dir));
13458 if (updir == NULL)
13459 return FAIL;
13460 if (mch_isdir(updir))
13461 r = OK;
13462 else if (mkdir_recurse(updir, prot) == OK)
13463 r = vim_mkdir_emsg(updir, prot);
13464 vim_free(updir);
13465 return r;
13468 #ifdef vim_mkdir
13470 * "mkdir()" function
13472 static void
13473 f_mkdir(argvars, rettv)
13474 typval_T *argvars;
13475 typval_T *rettv;
13477 char_u *dir;
13478 char_u buf[NUMBUFLEN];
13479 int prot = 0755;
13481 rettv->vval.v_number = FAIL;
13482 if (check_restricted() || check_secure())
13483 return;
13485 dir = get_tv_string_buf(&argvars[0], buf);
13486 if (argvars[1].v_type != VAR_UNKNOWN)
13488 if (argvars[2].v_type != VAR_UNKNOWN)
13489 prot = get_tv_number_chk(&argvars[2], NULL);
13490 if (prot != -1 && STRCMP(get_tv_string(&argvars[1]), "p") == 0)
13491 mkdir_recurse(dir, prot);
13493 rettv->vval.v_number = prot != -1 ? vim_mkdir_emsg(dir, prot) : 0;
13495 #endif
13498 * "mode()" function
13500 /*ARGSUSED*/
13501 static void
13502 f_mode(argvars, rettv)
13503 typval_T *argvars;
13504 typval_T *rettv;
13506 char_u buf[3];
13508 buf[1] = NUL;
13509 buf[2] = NUL;
13511 #ifdef FEAT_VISUAL
13512 if (VIsual_active)
13514 if (VIsual_select)
13515 buf[0] = VIsual_mode + 's' - 'v';
13516 else
13517 buf[0] = VIsual_mode;
13519 else
13520 #endif
13521 if (State == HITRETURN || State == ASKMORE || State == SETWSIZE
13522 || State == CONFIRM)
13524 buf[0] = 'r';
13525 if (State == ASKMORE)
13526 buf[1] = 'm';
13527 else if (State == CONFIRM)
13528 buf[1] = '?';
13530 else if (State == EXTERNCMD)
13531 buf[0] = '!';
13532 else if (State & INSERT)
13534 #ifdef FEAT_VREPLACE
13535 if (State & VREPLACE_FLAG)
13537 buf[0] = 'R';
13538 buf[1] = 'v';
13540 else
13541 #endif
13542 if (State & REPLACE_FLAG)
13543 buf[0] = 'R';
13544 else
13545 buf[0] = 'i';
13547 else if (State & CMDLINE)
13549 buf[0] = 'c';
13550 if (exmode_active)
13551 buf[1] = 'v';
13553 else if (exmode_active)
13555 buf[0] = 'c';
13556 buf[1] = 'e';
13558 else
13560 buf[0] = 'n';
13561 if (finish_op)
13562 buf[1] = 'o';
13565 /* Clear out the minor mode when the argument is not a non-zero number or
13566 * non-empty string. */
13567 if (!non_zero_arg(&argvars[0]))
13568 buf[1] = NUL;
13570 rettv->vval.v_string = vim_strsave(buf);
13571 rettv->v_type = VAR_STRING;
13575 * "nextnonblank()" function
13577 static void
13578 f_nextnonblank(argvars, rettv)
13579 typval_T *argvars;
13580 typval_T *rettv;
13582 linenr_T lnum;
13584 for (lnum = get_tv_lnum(argvars); ; ++lnum)
13586 if (lnum < 0 || lnum > curbuf->b_ml.ml_line_count)
13588 lnum = 0;
13589 break;
13591 if (*skipwhite(ml_get(lnum)) != NUL)
13592 break;
13594 rettv->vval.v_number = lnum;
13598 * "nr2char()" function
13600 static void
13601 f_nr2char(argvars, rettv)
13602 typval_T *argvars;
13603 typval_T *rettv;
13605 char_u buf[NUMBUFLEN];
13607 #ifdef FEAT_MBYTE
13608 if (has_mbyte)
13609 buf[(*mb_char2bytes)((int)get_tv_number(&argvars[0]), buf)] = NUL;
13610 else
13611 #endif
13613 buf[0] = (char_u)get_tv_number(&argvars[0]);
13614 buf[1] = NUL;
13616 rettv->v_type = VAR_STRING;
13617 rettv->vval.v_string = vim_strsave(buf);
13621 * "pathshorten()" function
13623 static void
13624 f_pathshorten(argvars, rettv)
13625 typval_T *argvars;
13626 typval_T *rettv;
13628 char_u *p;
13630 rettv->v_type = VAR_STRING;
13631 p = get_tv_string_chk(&argvars[0]);
13632 if (p == NULL)
13633 rettv->vval.v_string = NULL;
13634 else
13636 p = vim_strsave(p);
13637 rettv->vval.v_string = p;
13638 if (p != NULL)
13639 shorten_dir(p);
13643 #ifdef FEAT_FLOAT
13645 * "pow()" function
13647 static void
13648 f_pow(argvars, rettv)
13649 typval_T *argvars;
13650 typval_T *rettv;
13652 float_T fx, fy;
13654 rettv->v_type = VAR_FLOAT;
13655 if (get_float_arg(argvars, &fx) == OK
13656 && get_float_arg(&argvars[1], &fy) == OK)
13657 rettv->vval.v_float = pow(fx, fy);
13658 else
13659 rettv->vval.v_float = 0.0;
13661 #endif
13664 * "prevnonblank()" function
13666 static void
13667 f_prevnonblank(argvars, rettv)
13668 typval_T *argvars;
13669 typval_T *rettv;
13671 linenr_T lnum;
13673 lnum = get_tv_lnum(argvars);
13674 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
13675 lnum = 0;
13676 else
13677 while (lnum >= 1 && *skipwhite(ml_get(lnum)) == NUL)
13678 --lnum;
13679 rettv->vval.v_number = lnum;
13682 #ifdef HAVE_STDARG_H
13683 /* This dummy va_list is here because:
13684 * - passing a NULL pointer doesn't work when va_list isn't a pointer
13685 * - locally in the function results in a "used before set" warning
13686 * - using va_start() to initialize it gives "function with fixed args" error */
13687 static va_list ap;
13688 #endif
13691 * "printf()" function
13693 static void
13694 f_printf(argvars, rettv)
13695 typval_T *argvars;
13696 typval_T *rettv;
13698 rettv->v_type = VAR_STRING;
13699 rettv->vval.v_string = NULL;
13700 #ifdef HAVE_STDARG_H /* only very old compilers can't do this */
13702 char_u buf[NUMBUFLEN];
13703 int len;
13704 char_u *s;
13705 int saved_did_emsg = did_emsg;
13706 char *fmt;
13708 /* Get the required length, allocate the buffer and do it for real. */
13709 did_emsg = FALSE;
13710 fmt = (char *)get_tv_string_buf(&argvars[0], buf);
13711 len = vim_vsnprintf(NULL, 0, fmt, ap, argvars + 1);
13712 if (!did_emsg)
13714 s = alloc(len + 1);
13715 if (s != NULL)
13717 rettv->vval.v_string = s;
13718 (void)vim_vsnprintf((char *)s, len + 1, fmt, ap, argvars + 1);
13721 did_emsg |= saved_did_emsg;
13723 #endif
13727 * "pumvisible()" function
13729 /*ARGSUSED*/
13730 static void
13731 f_pumvisible(argvars, rettv)
13732 typval_T *argvars;
13733 typval_T *rettv;
13735 rettv->vval.v_number = 0;
13736 #ifdef FEAT_INS_EXPAND
13737 if (pum_visible())
13738 rettv->vval.v_number = 1;
13739 #endif
13743 * "range()" function
13745 static void
13746 f_range(argvars, rettv)
13747 typval_T *argvars;
13748 typval_T *rettv;
13750 long start;
13751 long end;
13752 long stride = 1;
13753 long i;
13754 int error = FALSE;
13756 start = get_tv_number_chk(&argvars[0], &error);
13757 if (argvars[1].v_type == VAR_UNKNOWN)
13759 end = start - 1;
13760 start = 0;
13762 else
13764 end = get_tv_number_chk(&argvars[1], &error);
13765 if (argvars[2].v_type != VAR_UNKNOWN)
13766 stride = get_tv_number_chk(&argvars[2], &error);
13769 rettv->vval.v_number = 0;
13770 if (error)
13771 return; /* type error; errmsg already given */
13772 if (stride == 0)
13773 EMSG(_("E726: Stride is zero"));
13774 else if (stride > 0 ? end + 1 < start : end - 1 > start)
13775 EMSG(_("E727: Start past end"));
13776 else
13778 if (rettv_list_alloc(rettv) == OK)
13779 for (i = start; stride > 0 ? i <= end : i >= end; i += stride)
13780 if (list_append_number(rettv->vval.v_list,
13781 (varnumber_T)i) == FAIL)
13782 break;
13787 * "readfile()" function
13789 static void
13790 f_readfile(argvars, rettv)
13791 typval_T *argvars;
13792 typval_T *rettv;
13794 int binary = FALSE;
13795 char_u *fname;
13796 FILE *fd;
13797 listitem_T *li;
13798 #define FREAD_SIZE 200 /* optimized for text lines */
13799 char_u buf[FREAD_SIZE];
13800 int readlen; /* size of last fread() */
13801 int buflen; /* nr of valid chars in buf[] */
13802 int filtd; /* how much in buf[] was NUL -> '\n' filtered */
13803 int tolist; /* first byte in buf[] still to be put in list */
13804 int chop; /* how many CR to chop off */
13805 char_u *prev = NULL; /* previously read bytes, if any */
13806 int prevlen = 0; /* length of "prev" if not NULL */
13807 char_u *s;
13808 int len;
13809 long maxline = MAXLNUM;
13810 long cnt = 0;
13812 if (argvars[1].v_type != VAR_UNKNOWN)
13814 if (STRCMP(get_tv_string(&argvars[1]), "b") == 0)
13815 binary = TRUE;
13816 if (argvars[2].v_type != VAR_UNKNOWN)
13817 maxline = get_tv_number(&argvars[2]);
13820 if (rettv_list_alloc(rettv) == FAIL)
13821 return;
13823 /* Always open the file in binary mode, library functions have a mind of
13824 * their own about CR-LF conversion. */
13825 fname = get_tv_string(&argvars[0]);
13826 if (*fname == NUL || (fd = mch_fopen((char *)fname, READBIN)) == NULL)
13828 EMSG2(_(e_notopen), *fname == NUL ? (char_u *)_("<empty>") : fname);
13829 return;
13832 filtd = 0;
13833 while (cnt < maxline || maxline < 0)
13835 readlen = (int)fread(buf + filtd, 1, FREAD_SIZE - filtd, fd);
13836 buflen = filtd + readlen;
13837 tolist = 0;
13838 for ( ; filtd < buflen || readlen <= 0; ++filtd)
13840 if (buf[filtd] == '\n' || readlen <= 0)
13842 /* Only when in binary mode add an empty list item when the
13843 * last line ends in a '\n'. */
13844 if (!binary && readlen == 0 && filtd == 0)
13845 break;
13847 /* Found end-of-line or end-of-file: add a text line to the
13848 * list. */
13849 chop = 0;
13850 if (!binary)
13851 while (filtd - chop - 1 >= tolist
13852 && buf[filtd - chop - 1] == '\r')
13853 ++chop;
13854 len = filtd - tolist - chop;
13855 if (prev == NULL)
13856 s = vim_strnsave(buf + tolist, len);
13857 else
13859 s = alloc((unsigned)(prevlen + len + 1));
13860 if (s != NULL)
13862 mch_memmove(s, prev, prevlen);
13863 vim_free(prev);
13864 prev = NULL;
13865 mch_memmove(s + prevlen, buf + tolist, len);
13866 s[prevlen + len] = NUL;
13869 tolist = filtd + 1;
13871 li = listitem_alloc();
13872 if (li == NULL)
13874 vim_free(s);
13875 break;
13877 li->li_tv.v_type = VAR_STRING;
13878 li->li_tv.v_lock = 0;
13879 li->li_tv.vval.v_string = s;
13880 list_append(rettv->vval.v_list, li);
13882 if (++cnt >= maxline && maxline >= 0)
13883 break;
13884 if (readlen <= 0)
13885 break;
13887 else if (buf[filtd] == NUL)
13888 buf[filtd] = '\n';
13890 if (readlen <= 0)
13891 break;
13893 if (tolist == 0)
13895 /* "buf" is full, need to move text to an allocated buffer */
13896 if (prev == NULL)
13898 prev = vim_strnsave(buf, buflen);
13899 prevlen = buflen;
13901 else
13903 s = alloc((unsigned)(prevlen + buflen));
13904 if (s != NULL)
13906 mch_memmove(s, prev, prevlen);
13907 mch_memmove(s + prevlen, buf, buflen);
13908 vim_free(prev);
13909 prev = s;
13910 prevlen += buflen;
13913 filtd = 0;
13915 else
13917 mch_memmove(buf, buf + tolist, buflen - tolist);
13918 filtd -= tolist;
13923 * For a negative line count use only the lines at the end of the file,
13924 * free the rest.
13926 if (maxline < 0)
13927 while (cnt > -maxline)
13929 listitem_remove(rettv->vval.v_list, rettv->vval.v_list->lv_first);
13930 --cnt;
13933 vim_free(prev);
13934 fclose(fd);
13937 #if defined(FEAT_RELTIME)
13938 static int list2proftime __ARGS((typval_T *arg, proftime_T *tm));
13941 * Convert a List to proftime_T.
13942 * Return FAIL when there is something wrong.
13944 static int
13945 list2proftime(arg, tm)
13946 typval_T *arg;
13947 proftime_T *tm;
13949 long n1, n2;
13950 int error = FALSE;
13952 if (arg->v_type != VAR_LIST || arg->vval.v_list == NULL
13953 || arg->vval.v_list->lv_len != 2)
13954 return FAIL;
13955 n1 = list_find_nr(arg->vval.v_list, 0L, &error);
13956 n2 = list_find_nr(arg->vval.v_list, 1L, &error);
13957 # ifdef WIN3264
13958 tm->HighPart = n1;
13959 tm->LowPart = n2;
13960 # else
13961 tm->tv_sec = n1;
13962 tm->tv_usec = n2;
13963 # endif
13964 return error ? FAIL : OK;
13966 #endif /* FEAT_RELTIME */
13969 * "reltime()" function
13971 static void
13972 f_reltime(argvars, rettv)
13973 typval_T *argvars;
13974 typval_T *rettv;
13976 #ifdef FEAT_RELTIME
13977 proftime_T res;
13978 proftime_T start;
13980 if (argvars[0].v_type == VAR_UNKNOWN)
13982 /* No arguments: get current time. */
13983 profile_start(&res);
13985 else if (argvars[1].v_type == VAR_UNKNOWN)
13987 if (list2proftime(&argvars[0], &res) == FAIL)
13988 return;
13989 profile_end(&res);
13991 else
13993 /* Two arguments: compute the difference. */
13994 if (list2proftime(&argvars[0], &start) == FAIL
13995 || list2proftime(&argvars[1], &res) == FAIL)
13996 return;
13997 profile_sub(&res, &start);
14000 if (rettv_list_alloc(rettv) == OK)
14002 long n1, n2;
14004 # ifdef WIN3264
14005 n1 = res.HighPart;
14006 n2 = res.LowPart;
14007 # else
14008 n1 = res.tv_sec;
14009 n2 = res.tv_usec;
14010 # endif
14011 list_append_number(rettv->vval.v_list, (varnumber_T)n1);
14012 list_append_number(rettv->vval.v_list, (varnumber_T)n2);
14014 #endif
14018 * "reltimestr()" function
14020 static void
14021 f_reltimestr(argvars, rettv)
14022 typval_T *argvars;
14023 typval_T *rettv;
14025 #ifdef FEAT_RELTIME
14026 proftime_T tm;
14027 #endif
14029 rettv->v_type = VAR_STRING;
14030 rettv->vval.v_string = NULL;
14031 #ifdef FEAT_RELTIME
14032 if (list2proftime(&argvars[0], &tm) == OK)
14033 rettv->vval.v_string = vim_strsave((char_u *)profile_msg(&tm));
14034 #endif
14037 #if defined(FEAT_CLIENTSERVER) && defined(FEAT_X11)
14038 static void make_connection __ARGS((void));
14039 static int check_connection __ARGS((void));
14041 static void
14042 make_connection()
14044 if (X_DISPLAY == NULL
14045 # ifdef FEAT_GUI
14046 && !gui.in_use
14047 # endif
14050 x_force_connect = TRUE;
14051 setup_term_clip();
14052 x_force_connect = FALSE;
14056 static int
14057 check_connection()
14059 make_connection();
14060 if (X_DISPLAY == NULL)
14062 EMSG(_("E240: No connection to Vim server"));
14063 return FAIL;
14065 return OK;
14067 #endif
14069 #ifdef FEAT_CLIENTSERVER
14070 static void remote_common __ARGS((typval_T *argvars, typval_T *rettv, int expr));
14072 static void
14073 remote_common(argvars, rettv, expr)
14074 typval_T *argvars;
14075 typval_T *rettv;
14076 int expr;
14078 char_u *server_name;
14079 char_u *keys;
14080 char_u *r = NULL;
14081 char_u buf[NUMBUFLEN];
14082 # ifdef WIN32
14083 HWND w;
14084 # elif defined(FEAT_X11)
14085 Window w;
14086 # elif defined(MAC_CLIENTSERVER)
14087 int w; // This is the port number ('w' is a bit confusing)
14088 # endif
14090 if (check_restricted() || check_secure())
14091 return;
14093 # ifdef FEAT_X11
14094 if (check_connection() == FAIL)
14095 return;
14096 # endif
14098 server_name = get_tv_string_chk(&argvars[0]);
14099 if (server_name == NULL)
14100 return; /* type error; errmsg already given */
14101 keys = get_tv_string_buf(&argvars[1], buf);
14102 # ifdef WIN32
14103 if (serverSendToVim(server_name, keys, &r, &w, expr, TRUE) < 0)
14104 # elif defined(FEAT_X11)
14105 if (serverSendToVim(X_DISPLAY, server_name, keys, &r, &w, expr, 0, TRUE)
14106 < 0)
14107 # elif defined(MAC_CLIENTSERVER)
14108 if (serverSendToVim(server_name, keys, &r, &w, expr, TRUE) < 0)
14109 # endif
14111 if (r != NULL)
14112 EMSG(r); /* sending worked but evaluation failed */
14113 else
14114 EMSG2(_("E241: Unable to send to %s"), server_name);
14115 return;
14118 rettv->vval.v_string = r;
14120 if (argvars[2].v_type != VAR_UNKNOWN)
14122 dictitem_T v;
14123 char_u str[30];
14124 char_u *idvar;
14126 sprintf((char *)str, PRINTF_HEX_LONG_U, (long_u)w);
14127 v.di_tv.v_type = VAR_STRING;
14128 v.di_tv.vval.v_string = vim_strsave(str);
14129 idvar = get_tv_string_chk(&argvars[2]);
14130 if (idvar != NULL)
14131 set_var(idvar, &v.di_tv, FALSE);
14132 vim_free(v.di_tv.vval.v_string);
14135 #endif
14138 * "remote_expr()" function
14140 /*ARGSUSED*/
14141 static void
14142 f_remote_expr(argvars, rettv)
14143 typval_T *argvars;
14144 typval_T *rettv;
14146 rettv->v_type = VAR_STRING;
14147 rettv->vval.v_string = NULL;
14148 #ifdef FEAT_CLIENTSERVER
14149 remote_common(argvars, rettv, TRUE);
14150 #endif
14154 * "remote_foreground()" function
14156 /*ARGSUSED*/
14157 static void
14158 f_remote_foreground(argvars, rettv)
14159 typval_T *argvars;
14160 typval_T *rettv;
14162 rettv->vval.v_number = 0;
14163 #ifdef FEAT_CLIENTSERVER
14164 # ifdef WIN32
14165 /* On Win32 it's done in this application. */
14167 char_u *server_name = get_tv_string_chk(&argvars[0]);
14169 if (server_name != NULL)
14170 serverForeground(server_name);
14172 # elif defined(FEAT_X11) || defined(MAC_CLIENTSERVER)
14173 /* Send a foreground() expression to the server. */
14174 argvars[1].v_type = VAR_STRING;
14175 argvars[1].vval.v_string = vim_strsave((char_u *)"foreground()");
14176 argvars[2].v_type = VAR_UNKNOWN;
14177 remote_common(argvars, rettv, TRUE);
14178 vim_free(argvars[1].vval.v_string);
14179 # endif
14180 #endif
14183 /*ARGSUSED*/
14184 static void
14185 f_remote_peek(argvars, rettv)
14186 typval_T *argvars;
14187 typval_T *rettv;
14189 #ifdef FEAT_CLIENTSERVER
14190 dictitem_T v;
14191 char_u *s = NULL;
14192 # ifdef WIN32
14193 long_u n = 0;
14194 # endif
14195 char_u *serverid;
14197 if (check_restricted() || check_secure())
14199 rettv->vval.v_number = -1;
14200 return;
14202 serverid = get_tv_string_chk(&argvars[0]);
14203 if (serverid == NULL)
14205 rettv->vval.v_number = -1;
14206 return; /* type error; errmsg already given */
14208 # ifdef WIN32
14209 sscanf(serverid, SCANF_HEX_LONG_U, &n);
14210 if (n == 0)
14211 rettv->vval.v_number = -1;
14212 else
14214 s = serverGetReply((HWND)n, FALSE, FALSE, FALSE);
14215 rettv->vval.v_number = (s != NULL);
14217 # elif defined(FEAT_X11)
14218 rettv->vval.v_number = 0;
14219 if (check_connection() == FAIL)
14220 return;
14222 rettv->vval.v_number = serverPeekReply(X_DISPLAY,
14223 serverStrToWin(serverid), &s);
14224 # elif defined(MAC_CLIENTSERVER)
14225 rettv->vval.v_number = serverPeekReply(serverStrToPort(serverid), &s);
14226 # endif
14228 if (argvars[1].v_type != VAR_UNKNOWN && rettv->vval.v_number > 0)
14230 char_u *retvar;
14232 v.di_tv.v_type = VAR_STRING;
14233 v.di_tv.vval.v_string = vim_strsave(s);
14234 retvar = get_tv_string_chk(&argvars[1]);
14235 if (retvar != NULL)
14236 set_var(retvar, &v.di_tv, FALSE);
14237 vim_free(v.di_tv.vval.v_string);
14239 #else
14240 rettv->vval.v_number = -1;
14241 #endif
14244 /*ARGSUSED*/
14245 static void
14246 f_remote_read(argvars, rettv)
14247 typval_T *argvars;
14248 typval_T *rettv;
14250 char_u *r = NULL;
14252 #ifdef FEAT_CLIENTSERVER
14253 char_u *serverid = get_tv_string_chk(&argvars[0]);
14255 if (serverid != NULL && !check_restricted() && !check_secure())
14257 # ifdef WIN32
14258 /* The server's HWND is encoded in the 'id' parameter */
14259 long_u n = 0;
14261 sscanf(serverid, SCANF_HEX_LONG_U, &n);
14262 if (n != 0)
14263 r = serverGetReply((HWND)n, FALSE, TRUE, TRUE);
14264 if (r == NULL)
14265 # elif defined(FEAT_X11)
14266 if (check_connection() == FAIL || serverReadReply(X_DISPLAY,
14267 serverStrToWin(serverid), &r, FALSE) < 0)
14268 # elif defined(MAC_CLIENTSERVER)
14269 if (serverReadReply(serverStrToPort(serverid), &r) < 0)
14270 # endif
14271 EMSG(_("E277: Unable to read a server reply"));
14273 #endif
14274 rettv->v_type = VAR_STRING;
14275 rettv->vval.v_string = r;
14279 * "remote_send()" function
14281 /*ARGSUSED*/
14282 static void
14283 f_remote_send(argvars, rettv)
14284 typval_T *argvars;
14285 typval_T *rettv;
14287 rettv->v_type = VAR_STRING;
14288 rettv->vval.v_string = NULL;
14289 #ifdef FEAT_CLIENTSERVER
14290 remote_common(argvars, rettv, FALSE);
14291 #endif
14295 * "remove()" function
14297 static void
14298 f_remove(argvars, rettv)
14299 typval_T *argvars;
14300 typval_T *rettv;
14302 list_T *l;
14303 listitem_T *item, *item2;
14304 listitem_T *li;
14305 long idx;
14306 long end;
14307 char_u *key;
14308 dict_T *d;
14309 dictitem_T *di;
14311 rettv->vval.v_number = 0;
14312 if (argvars[0].v_type == VAR_DICT)
14314 if (argvars[2].v_type != VAR_UNKNOWN)
14315 EMSG2(_(e_toomanyarg), "remove()");
14316 else if ((d = argvars[0].vval.v_dict) != NULL
14317 && !tv_check_lock(d->dv_lock, (char_u *)"remove() argument"))
14319 key = get_tv_string_chk(&argvars[1]);
14320 if (key != NULL)
14322 di = dict_find(d, key, -1);
14323 if (di == NULL)
14324 EMSG2(_(e_dictkey), key);
14325 else
14327 *rettv = di->di_tv;
14328 init_tv(&di->di_tv);
14329 dictitem_remove(d, di);
14334 else if (argvars[0].v_type != VAR_LIST)
14335 EMSG2(_(e_listdictarg), "remove()");
14336 else if ((l = argvars[0].vval.v_list) != NULL
14337 && !tv_check_lock(l->lv_lock, (char_u *)"remove() argument"))
14339 int error = FALSE;
14341 idx = get_tv_number_chk(&argvars[1], &error);
14342 if (error)
14343 ; /* type error: do nothing, errmsg already given */
14344 else if ((item = list_find(l, idx)) == NULL)
14345 EMSGN(_(e_listidx), idx);
14346 else
14348 if (argvars[2].v_type == VAR_UNKNOWN)
14350 /* Remove one item, return its value. */
14351 list_remove(l, item, item);
14352 *rettv = item->li_tv;
14353 vim_free(item);
14355 else
14357 /* Remove range of items, return list with values. */
14358 end = get_tv_number_chk(&argvars[2], &error);
14359 if (error)
14360 ; /* type error: do nothing */
14361 else if ((item2 = list_find(l, end)) == NULL)
14362 EMSGN(_(e_listidx), end);
14363 else
14365 int cnt = 0;
14367 for (li = item; li != NULL; li = li->li_next)
14369 ++cnt;
14370 if (li == item2)
14371 break;
14373 if (li == NULL) /* didn't find "item2" after "item" */
14374 EMSG(_(e_invrange));
14375 else
14377 list_remove(l, item, item2);
14378 if (rettv_list_alloc(rettv) == OK)
14380 l = rettv->vval.v_list;
14381 l->lv_first = item;
14382 l->lv_last = item2;
14383 item->li_prev = NULL;
14384 item2->li_next = NULL;
14385 l->lv_len = cnt;
14395 * "rename({from}, {to})" function
14397 static void
14398 f_rename(argvars, rettv)
14399 typval_T *argvars;
14400 typval_T *rettv;
14402 char_u buf[NUMBUFLEN];
14404 if (check_restricted() || check_secure())
14405 rettv->vval.v_number = -1;
14406 else
14407 rettv->vval.v_number = vim_rename(get_tv_string(&argvars[0]),
14408 get_tv_string_buf(&argvars[1], buf));
14412 * "repeat()" function
14414 /*ARGSUSED*/
14415 static void
14416 f_repeat(argvars, rettv)
14417 typval_T *argvars;
14418 typval_T *rettv;
14420 char_u *p;
14421 int n;
14422 int slen;
14423 int len;
14424 char_u *r;
14425 int i;
14427 n = get_tv_number(&argvars[1]);
14428 if (argvars[0].v_type == VAR_LIST)
14430 if (rettv_list_alloc(rettv) == OK && argvars[0].vval.v_list != NULL)
14431 while (n-- > 0)
14432 if (list_extend(rettv->vval.v_list,
14433 argvars[0].vval.v_list, NULL) == FAIL)
14434 break;
14436 else
14438 p = get_tv_string(&argvars[0]);
14439 rettv->v_type = VAR_STRING;
14440 rettv->vval.v_string = NULL;
14442 slen = (int)STRLEN(p);
14443 len = slen * n;
14444 if (len <= 0)
14445 return;
14447 r = alloc(len + 1);
14448 if (r != NULL)
14450 for (i = 0; i < n; i++)
14451 mch_memmove(r + i * slen, p, (size_t)slen);
14452 r[len] = NUL;
14455 rettv->vval.v_string = r;
14460 * "resolve()" function
14462 static void
14463 f_resolve(argvars, rettv)
14464 typval_T *argvars;
14465 typval_T *rettv;
14467 char_u *p;
14469 p = get_tv_string(&argvars[0]);
14470 #ifdef FEAT_SHORTCUT
14472 char_u *v = NULL;
14474 v = mch_resolve_shortcut(p);
14475 if (v != NULL)
14476 rettv->vval.v_string = v;
14477 else
14478 rettv->vval.v_string = vim_strsave(p);
14480 #else
14481 # ifdef HAVE_READLINK
14483 char_u buf[MAXPATHL + 1];
14484 char_u *cpy;
14485 int len;
14486 char_u *remain = NULL;
14487 char_u *q;
14488 int is_relative_to_current = FALSE;
14489 int has_trailing_pathsep = FALSE;
14490 int limit = 100;
14492 p = vim_strsave(p);
14494 if (p[0] == '.' && (vim_ispathsep(p[1])
14495 || (p[1] == '.' && (vim_ispathsep(p[2])))))
14496 is_relative_to_current = TRUE;
14498 len = STRLEN(p);
14499 if (len > 0 && after_pathsep(p, p + len))
14500 has_trailing_pathsep = TRUE;
14502 q = getnextcomp(p);
14503 if (*q != NUL)
14505 /* Separate the first path component in "p", and keep the
14506 * remainder (beginning with the path separator). */
14507 remain = vim_strsave(q - 1);
14508 q[-1] = NUL;
14511 for (;;)
14513 for (;;)
14515 len = readlink((char *)p, (char *)buf, MAXPATHL);
14516 if (len <= 0)
14517 break;
14518 buf[len] = NUL;
14520 if (limit-- == 0)
14522 vim_free(p);
14523 vim_free(remain);
14524 EMSG(_("E655: Too many symbolic links (cycle?)"));
14525 rettv->vval.v_string = NULL;
14526 goto fail;
14529 /* Ensure that the result will have a trailing path separator
14530 * if the argument has one. */
14531 if (remain == NULL && has_trailing_pathsep)
14532 add_pathsep(buf);
14534 /* Separate the first path component in the link value and
14535 * concatenate the remainders. */
14536 q = getnextcomp(vim_ispathsep(*buf) ? buf + 1 : buf);
14537 if (*q != NUL)
14539 if (remain == NULL)
14540 remain = vim_strsave(q - 1);
14541 else
14543 cpy = concat_str(q - 1, remain);
14544 if (cpy != NULL)
14546 vim_free(remain);
14547 remain = cpy;
14550 q[-1] = NUL;
14553 q = gettail(p);
14554 if (q > p && *q == NUL)
14556 /* Ignore trailing path separator. */
14557 q[-1] = NUL;
14558 q = gettail(p);
14560 if (q > p && !mch_isFullName(buf))
14562 /* symlink is relative to directory of argument */
14563 cpy = alloc((unsigned)(STRLEN(p) + STRLEN(buf) + 1));
14564 if (cpy != NULL)
14566 STRCPY(cpy, p);
14567 STRCPY(gettail(cpy), buf);
14568 vim_free(p);
14569 p = cpy;
14572 else
14574 vim_free(p);
14575 p = vim_strsave(buf);
14579 if (remain == NULL)
14580 break;
14582 /* Append the first path component of "remain" to "p". */
14583 q = getnextcomp(remain + 1);
14584 len = q - remain - (*q != NUL);
14585 cpy = vim_strnsave(p, STRLEN(p) + len);
14586 if (cpy != NULL)
14588 STRNCAT(cpy, remain, len);
14589 vim_free(p);
14590 p = cpy;
14592 /* Shorten "remain". */
14593 if (*q != NUL)
14594 STRMOVE(remain, q - 1);
14595 else
14597 vim_free(remain);
14598 remain = NULL;
14602 /* If the result is a relative path name, make it explicitly relative to
14603 * the current directory if and only if the argument had this form. */
14604 if (!vim_ispathsep(*p))
14606 if (is_relative_to_current
14607 && *p != NUL
14608 && !(p[0] == '.'
14609 && (p[1] == NUL
14610 || vim_ispathsep(p[1])
14611 || (p[1] == '.'
14612 && (p[2] == NUL
14613 || vim_ispathsep(p[2]))))))
14615 /* Prepend "./". */
14616 cpy = concat_str((char_u *)"./", p);
14617 if (cpy != NULL)
14619 vim_free(p);
14620 p = cpy;
14623 else if (!is_relative_to_current)
14625 /* Strip leading "./". */
14626 q = p;
14627 while (q[0] == '.' && vim_ispathsep(q[1]))
14628 q += 2;
14629 if (q > p)
14630 STRMOVE(p, p + 2);
14634 /* Ensure that the result will have no trailing path separator
14635 * if the argument had none. But keep "/" or "//". */
14636 if (!has_trailing_pathsep)
14638 q = p + STRLEN(p);
14639 if (after_pathsep(p, q))
14640 *gettail_sep(p) = NUL;
14643 rettv->vval.v_string = p;
14645 # else
14646 rettv->vval.v_string = vim_strsave(p);
14647 # endif
14648 #endif
14650 simplify_filename(rettv->vval.v_string);
14652 #ifdef HAVE_READLINK
14653 fail:
14654 #endif
14655 rettv->v_type = VAR_STRING;
14659 * "reverse({list})" function
14661 static void
14662 f_reverse(argvars, rettv)
14663 typval_T *argvars;
14664 typval_T *rettv;
14666 list_T *l;
14667 listitem_T *li, *ni;
14669 rettv->vval.v_number = 0;
14670 if (argvars[0].v_type != VAR_LIST)
14671 EMSG2(_(e_listarg), "reverse()");
14672 else if ((l = argvars[0].vval.v_list) != NULL
14673 && !tv_check_lock(l->lv_lock, (char_u *)"reverse()"))
14675 li = l->lv_last;
14676 l->lv_first = l->lv_last = NULL;
14677 l->lv_len = 0;
14678 while (li != NULL)
14680 ni = li->li_prev;
14681 list_append(l, li);
14682 li = ni;
14684 rettv->vval.v_list = l;
14685 rettv->v_type = VAR_LIST;
14686 ++l->lv_refcount;
14687 l->lv_idx = l->lv_len - l->lv_idx - 1;
14691 #define SP_NOMOVE 0x01 /* don't move cursor */
14692 #define SP_REPEAT 0x02 /* repeat to find outer pair */
14693 #define SP_RETCOUNT 0x04 /* return matchcount */
14694 #define SP_SETPCMARK 0x08 /* set previous context mark */
14695 #define SP_START 0x10 /* accept match at start position */
14696 #define SP_SUBPAT 0x20 /* return nr of matching sub-pattern */
14697 #define SP_END 0x40 /* leave cursor at end of match */
14699 static int get_search_arg __ARGS((typval_T *varp, int *flagsp));
14702 * Get flags for a search function.
14703 * Possibly sets "p_ws".
14704 * Returns BACKWARD, FORWARD or zero (for an error).
14706 static int
14707 get_search_arg(varp, flagsp)
14708 typval_T *varp;
14709 int *flagsp;
14711 int dir = FORWARD;
14712 char_u *flags;
14713 char_u nbuf[NUMBUFLEN];
14714 int mask;
14716 if (varp->v_type != VAR_UNKNOWN)
14718 flags = get_tv_string_buf_chk(varp, nbuf);
14719 if (flags == NULL)
14720 return 0; /* type error; errmsg already given */
14721 while (*flags != NUL)
14723 switch (*flags)
14725 case 'b': dir = BACKWARD; break;
14726 case 'w': p_ws = TRUE; break;
14727 case 'W': p_ws = FALSE; break;
14728 default: mask = 0;
14729 if (flagsp != NULL)
14730 switch (*flags)
14732 case 'c': mask = SP_START; break;
14733 case 'e': mask = SP_END; break;
14734 case 'm': mask = SP_RETCOUNT; break;
14735 case 'n': mask = SP_NOMOVE; break;
14736 case 'p': mask = SP_SUBPAT; break;
14737 case 'r': mask = SP_REPEAT; break;
14738 case 's': mask = SP_SETPCMARK; break;
14740 if (mask == 0)
14742 EMSG2(_(e_invarg2), flags);
14743 dir = 0;
14745 else
14746 *flagsp |= mask;
14748 if (dir == 0)
14749 break;
14750 ++flags;
14753 return dir;
14757 * Shared by search() and searchpos() functions
14759 static int
14760 search_cmn(argvars, match_pos, flagsp)
14761 typval_T *argvars;
14762 pos_T *match_pos;
14763 int *flagsp;
14765 int flags;
14766 char_u *pat;
14767 pos_T pos;
14768 pos_T save_cursor;
14769 int save_p_ws = p_ws;
14770 int dir;
14771 int retval = 0; /* default: FAIL */
14772 long lnum_stop = 0;
14773 proftime_T tm;
14774 #ifdef FEAT_RELTIME
14775 long time_limit = 0;
14776 #endif
14777 int options = SEARCH_KEEP;
14778 int subpatnum;
14780 pat = get_tv_string(&argvars[0]);
14781 dir = get_search_arg(&argvars[1], flagsp); /* may set p_ws */
14782 if (dir == 0)
14783 goto theend;
14784 flags = *flagsp;
14785 if (flags & SP_START)
14786 options |= SEARCH_START;
14787 if (flags & SP_END)
14788 options |= SEARCH_END;
14790 /* Optional arguments: line number to stop searching and timeout. */
14791 if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN)
14793 lnum_stop = get_tv_number_chk(&argvars[2], NULL);
14794 if (lnum_stop < 0)
14795 goto theend;
14796 #ifdef FEAT_RELTIME
14797 if (argvars[3].v_type != VAR_UNKNOWN)
14799 time_limit = get_tv_number_chk(&argvars[3], NULL);
14800 if (time_limit < 0)
14801 goto theend;
14803 #endif
14806 #ifdef FEAT_RELTIME
14807 /* Set the time limit, if there is one. */
14808 profile_setlimit(time_limit, &tm);
14809 #endif
14812 * This function does not accept SP_REPEAT and SP_RETCOUNT flags.
14813 * Check to make sure only those flags are set.
14814 * Also, Only the SP_NOMOVE or the SP_SETPCMARK flag can be set. Both
14815 * flags cannot be set. Check for that condition also.
14817 if (((flags & (SP_REPEAT | SP_RETCOUNT)) != 0)
14818 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
14820 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
14821 goto theend;
14824 pos = save_cursor = curwin->w_cursor;
14825 subpatnum = searchit(curwin, curbuf, &pos, dir, pat, 1L,
14826 options, RE_SEARCH, (linenr_T)lnum_stop, &tm);
14827 if (subpatnum != FAIL)
14829 if (flags & SP_SUBPAT)
14830 retval = subpatnum;
14831 else
14832 retval = pos.lnum;
14833 if (flags & SP_SETPCMARK)
14834 setpcmark();
14835 curwin->w_cursor = pos;
14836 if (match_pos != NULL)
14838 /* Store the match cursor position */
14839 match_pos->lnum = pos.lnum;
14840 match_pos->col = pos.col + 1;
14842 /* "/$" will put the cursor after the end of the line, may need to
14843 * correct that here */
14844 check_cursor();
14847 /* If 'n' flag is used: restore cursor position. */
14848 if (flags & SP_NOMOVE)
14849 curwin->w_cursor = save_cursor;
14850 else
14851 curwin->w_set_curswant = TRUE;
14852 theend:
14853 p_ws = save_p_ws;
14855 return retval;
14858 #ifdef FEAT_FLOAT
14860 * "round({float})" function
14862 static void
14863 f_round(argvars, rettv)
14864 typval_T *argvars;
14865 typval_T *rettv;
14867 float_T f;
14869 rettv->v_type = VAR_FLOAT;
14870 if (get_float_arg(argvars, &f) == OK)
14871 /* round() is not in C90, use ceil() or floor() instead. */
14872 rettv->vval.v_float = f > 0 ? floor(f + 0.5) : ceil(f - 0.5);
14873 else
14874 rettv->vval.v_float = 0.0;
14876 #endif
14879 * "search()" function
14881 static void
14882 f_search(argvars, rettv)
14883 typval_T *argvars;
14884 typval_T *rettv;
14886 int flags = 0;
14888 rettv->vval.v_number = search_cmn(argvars, NULL, &flags);
14892 * "searchdecl()" function
14894 static void
14895 f_searchdecl(argvars, rettv)
14896 typval_T *argvars;
14897 typval_T *rettv;
14899 int locally = 1;
14900 int thisblock = 0;
14901 int error = FALSE;
14902 char_u *name;
14904 rettv->vval.v_number = 1; /* default: FAIL */
14906 name = get_tv_string_chk(&argvars[0]);
14907 if (argvars[1].v_type != VAR_UNKNOWN)
14909 locally = get_tv_number_chk(&argvars[1], &error) == 0;
14910 if (!error && argvars[2].v_type != VAR_UNKNOWN)
14911 thisblock = get_tv_number_chk(&argvars[2], &error) != 0;
14913 if (!error && name != NULL)
14914 rettv->vval.v_number = find_decl(name, (int)STRLEN(name),
14915 locally, thisblock, SEARCH_KEEP) == FAIL;
14919 * Used by searchpair() and searchpairpos()
14921 static int
14922 searchpair_cmn(argvars, match_pos)
14923 typval_T *argvars;
14924 pos_T *match_pos;
14926 char_u *spat, *mpat, *epat;
14927 char_u *skip;
14928 int save_p_ws = p_ws;
14929 int dir;
14930 int flags = 0;
14931 char_u nbuf1[NUMBUFLEN];
14932 char_u nbuf2[NUMBUFLEN];
14933 char_u nbuf3[NUMBUFLEN];
14934 int retval = 0; /* default: FAIL */
14935 long lnum_stop = 0;
14936 long time_limit = 0;
14938 /* Get the three pattern arguments: start, middle, end. */
14939 spat = get_tv_string_chk(&argvars[0]);
14940 mpat = get_tv_string_buf_chk(&argvars[1], nbuf1);
14941 epat = get_tv_string_buf_chk(&argvars[2], nbuf2);
14942 if (spat == NULL || mpat == NULL || epat == NULL)
14943 goto theend; /* type error */
14945 /* Handle the optional fourth argument: flags */
14946 dir = get_search_arg(&argvars[3], &flags); /* may set p_ws */
14947 if (dir == 0)
14948 goto theend;
14950 /* Don't accept SP_END or SP_SUBPAT.
14951 * Only one of the SP_NOMOVE or SP_SETPCMARK flags can be set.
14953 if ((flags & (SP_END | SP_SUBPAT)) != 0
14954 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
14956 EMSG2(_(e_invarg2), get_tv_string(&argvars[3]));
14957 goto theend;
14960 /* Using 'r' implies 'W', otherwise it doesn't work. */
14961 if (flags & SP_REPEAT)
14962 p_ws = FALSE;
14964 /* Optional fifth argument: skip expression */
14965 if (argvars[3].v_type == VAR_UNKNOWN
14966 || argvars[4].v_type == VAR_UNKNOWN)
14967 skip = (char_u *)"";
14968 else
14970 skip = get_tv_string_buf_chk(&argvars[4], nbuf3);
14971 if (argvars[5].v_type != VAR_UNKNOWN)
14973 lnum_stop = get_tv_number_chk(&argvars[5], NULL);
14974 if (lnum_stop < 0)
14975 goto theend;
14976 #ifdef FEAT_RELTIME
14977 if (argvars[6].v_type != VAR_UNKNOWN)
14979 time_limit = get_tv_number_chk(&argvars[6], NULL);
14980 if (time_limit < 0)
14981 goto theend;
14983 #endif
14986 if (skip == NULL)
14987 goto theend; /* type error */
14989 retval = do_searchpair(spat, mpat, epat, dir, skip, flags,
14990 match_pos, lnum_stop, time_limit);
14992 theend:
14993 p_ws = save_p_ws;
14995 return retval;
14999 * "searchpair()" function
15001 static void
15002 f_searchpair(argvars, rettv)
15003 typval_T *argvars;
15004 typval_T *rettv;
15006 rettv->vval.v_number = searchpair_cmn(argvars, NULL);
15010 * "searchpairpos()" function
15012 static void
15013 f_searchpairpos(argvars, rettv)
15014 typval_T *argvars;
15015 typval_T *rettv;
15017 pos_T match_pos;
15018 int lnum = 0;
15019 int col = 0;
15021 rettv->vval.v_number = 0;
15023 if (rettv_list_alloc(rettv) == FAIL)
15024 return;
15026 if (searchpair_cmn(argvars, &match_pos) > 0)
15028 lnum = match_pos.lnum;
15029 col = match_pos.col;
15032 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
15033 list_append_number(rettv->vval.v_list, (varnumber_T)col);
15037 * Search for a start/middle/end thing.
15038 * Used by searchpair(), see its documentation for the details.
15039 * Returns 0 or -1 for no match,
15041 long
15042 do_searchpair(spat, mpat, epat, dir, skip, flags, match_pos,
15043 lnum_stop, time_limit)
15044 char_u *spat; /* start pattern */
15045 char_u *mpat; /* middle pattern */
15046 char_u *epat; /* end pattern */
15047 int dir; /* BACKWARD or FORWARD */
15048 char_u *skip; /* skip expression */
15049 int flags; /* SP_SETPCMARK and other SP_ values */
15050 pos_T *match_pos;
15051 linenr_T lnum_stop; /* stop at this line if not zero */
15052 long time_limit; /* stop after this many msec */
15054 char_u *save_cpo;
15055 char_u *pat, *pat2 = NULL, *pat3 = NULL;
15056 long retval = 0;
15057 pos_T pos;
15058 pos_T firstpos;
15059 pos_T foundpos;
15060 pos_T save_cursor;
15061 pos_T save_pos;
15062 int n;
15063 int r;
15064 int nest = 1;
15065 int err;
15066 int options = SEARCH_KEEP;
15067 proftime_T tm;
15069 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
15070 save_cpo = p_cpo;
15071 p_cpo = empty_option;
15073 #ifdef FEAT_RELTIME
15074 /* Set the time limit, if there is one. */
15075 profile_setlimit(time_limit, &tm);
15076 #endif
15078 /* Make two search patterns: start/end (pat2, for in nested pairs) and
15079 * start/middle/end (pat3, for the top pair). */
15080 pat2 = alloc((unsigned)(STRLEN(spat) + STRLEN(epat) + 15));
15081 pat3 = alloc((unsigned)(STRLEN(spat) + STRLEN(mpat) + STRLEN(epat) + 23));
15082 if (pat2 == NULL || pat3 == NULL)
15083 goto theend;
15084 sprintf((char *)pat2, "\\(%s\\m\\)\\|\\(%s\\m\\)", spat, epat);
15085 if (*mpat == NUL)
15086 STRCPY(pat3, pat2);
15087 else
15088 sprintf((char *)pat3, "\\(%s\\m\\)\\|\\(%s\\m\\)\\|\\(%s\\m\\)",
15089 spat, epat, mpat);
15090 if (flags & SP_START)
15091 options |= SEARCH_START;
15093 save_cursor = curwin->w_cursor;
15094 pos = curwin->w_cursor;
15095 clearpos(&firstpos);
15096 clearpos(&foundpos);
15097 pat = pat3;
15098 for (;;)
15100 n = searchit(curwin, curbuf, &pos, dir, pat, 1L,
15101 options, RE_SEARCH, lnum_stop, &tm);
15102 if (n == FAIL || (firstpos.lnum != 0 && equalpos(pos, firstpos)))
15103 /* didn't find it or found the first match again: FAIL */
15104 break;
15106 if (firstpos.lnum == 0)
15107 firstpos = pos;
15108 if (equalpos(pos, foundpos))
15110 /* Found the same position again. Can happen with a pattern that
15111 * has "\zs" at the end and searching backwards. Advance one
15112 * character and try again. */
15113 if (dir == BACKWARD)
15114 decl(&pos);
15115 else
15116 incl(&pos);
15118 foundpos = pos;
15120 /* clear the start flag to avoid getting stuck here */
15121 options &= ~SEARCH_START;
15123 /* If the skip pattern matches, ignore this match. */
15124 if (*skip != NUL)
15126 save_pos = curwin->w_cursor;
15127 curwin->w_cursor = pos;
15128 r = eval_to_bool(skip, &err, NULL, FALSE);
15129 curwin->w_cursor = save_pos;
15130 if (err)
15132 /* Evaluating {skip} caused an error, break here. */
15133 curwin->w_cursor = save_cursor;
15134 retval = -1;
15135 break;
15137 if (r)
15138 continue;
15141 if ((dir == BACKWARD && n == 3) || (dir == FORWARD && n == 2))
15143 /* Found end when searching backwards or start when searching
15144 * forward: nested pair. */
15145 ++nest;
15146 pat = pat2; /* nested, don't search for middle */
15148 else
15150 /* Found end when searching forward or start when searching
15151 * backward: end of (nested) pair; or found middle in outer pair. */
15152 if (--nest == 1)
15153 pat = pat3; /* outer level, search for middle */
15156 if (nest == 0)
15158 /* Found the match: return matchcount or line number. */
15159 if (flags & SP_RETCOUNT)
15160 ++retval;
15161 else
15162 retval = pos.lnum;
15163 if (flags & SP_SETPCMARK)
15164 setpcmark();
15165 curwin->w_cursor = pos;
15166 if (!(flags & SP_REPEAT))
15167 break;
15168 nest = 1; /* search for next unmatched */
15172 if (match_pos != NULL)
15174 /* Store the match cursor position */
15175 match_pos->lnum = curwin->w_cursor.lnum;
15176 match_pos->col = curwin->w_cursor.col + 1;
15179 /* If 'n' flag is used or search failed: restore cursor position. */
15180 if ((flags & SP_NOMOVE) || retval == 0)
15181 curwin->w_cursor = save_cursor;
15183 theend:
15184 vim_free(pat2);
15185 vim_free(pat3);
15186 if (p_cpo == empty_option)
15187 p_cpo = save_cpo;
15188 else
15189 /* Darn, evaluating the {skip} expression changed the value. */
15190 free_string_option(save_cpo);
15192 return retval;
15196 * "searchpos()" function
15198 static void
15199 f_searchpos(argvars, rettv)
15200 typval_T *argvars;
15201 typval_T *rettv;
15203 pos_T match_pos;
15204 int lnum = 0;
15205 int col = 0;
15206 int n;
15207 int flags = 0;
15209 rettv->vval.v_number = 0;
15211 if (rettv_list_alloc(rettv) == FAIL)
15212 return;
15214 n = search_cmn(argvars, &match_pos, &flags);
15215 if (n > 0)
15217 lnum = match_pos.lnum;
15218 col = match_pos.col;
15221 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
15222 list_append_number(rettv->vval.v_list, (varnumber_T)col);
15223 if (flags & SP_SUBPAT)
15224 list_append_number(rettv->vval.v_list, (varnumber_T)n);
15228 /*ARGSUSED*/
15229 static void
15230 f_server2client(argvars, rettv)
15231 typval_T *argvars;
15232 typval_T *rettv;
15234 #ifdef FEAT_CLIENTSERVER
15235 char_u buf[NUMBUFLEN];
15236 char_u *server = get_tv_string_chk(&argvars[0]);
15237 char_u *reply = get_tv_string_buf_chk(&argvars[1], buf);
15239 rettv->vval.v_number = -1;
15240 if (server == NULL || reply == NULL)
15241 return;
15242 if (check_restricted() || check_secure())
15243 return;
15244 # ifdef FEAT_X11
15245 if (check_connection() == FAIL)
15246 return;
15247 # endif
15249 if (serverSendReply(server, reply) < 0)
15251 EMSG(_("E258: Unable to send to client"));
15252 return;
15254 rettv->vval.v_number = 0;
15255 #else
15256 rettv->vval.v_number = -1;
15257 #endif
15260 /*ARGSUSED*/
15261 static void
15262 f_serverlist(argvars, rettv)
15263 typval_T *argvars;
15264 typval_T *rettv;
15266 char_u *r = NULL;
15268 #ifdef FEAT_CLIENTSERVER
15269 # if defined(WIN32) || defined(MAC_CLIENTSERVER)
15270 r = serverGetVimNames();
15271 # elif defined(FEAT_X11)
15272 make_connection();
15273 if (X_DISPLAY != NULL)
15274 r = serverGetVimNames(X_DISPLAY);
15275 # endif
15276 #endif
15277 rettv->v_type = VAR_STRING;
15278 rettv->vval.v_string = r;
15282 * "setbufvar()" function
15284 /*ARGSUSED*/
15285 static void
15286 f_setbufvar(argvars, rettv)
15287 typval_T *argvars;
15288 typval_T *rettv;
15290 buf_T *buf;
15291 aco_save_T aco;
15292 char_u *varname, *bufvarname;
15293 typval_T *varp;
15294 char_u nbuf[NUMBUFLEN];
15296 rettv->vval.v_number = 0;
15298 if (check_restricted() || check_secure())
15299 return;
15300 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
15301 varname = get_tv_string_chk(&argvars[1]);
15302 buf = get_buf_tv(&argvars[0]);
15303 varp = &argvars[2];
15305 if (buf != NULL && varname != NULL && varp != NULL)
15307 /* set curbuf to be our buf, temporarily */
15308 aucmd_prepbuf(&aco, buf);
15310 if (*varname == '&')
15312 long numval;
15313 char_u *strval;
15314 int error = FALSE;
15316 ++varname;
15317 numval = get_tv_number_chk(varp, &error);
15318 strval = get_tv_string_buf_chk(varp, nbuf);
15319 if (!error && strval != NULL)
15320 set_option_value(varname, numval, strval, OPT_LOCAL);
15322 else
15324 bufvarname = alloc((unsigned)STRLEN(varname) + 3);
15325 if (bufvarname != NULL)
15327 STRCPY(bufvarname, "b:");
15328 STRCPY(bufvarname + 2, varname);
15329 set_var(bufvarname, varp, TRUE);
15330 vim_free(bufvarname);
15334 /* reset notion of buffer */
15335 aucmd_restbuf(&aco);
15340 * "setcmdpos()" function
15342 static void
15343 f_setcmdpos(argvars, rettv)
15344 typval_T *argvars;
15345 typval_T *rettv;
15347 int pos = (int)get_tv_number(&argvars[0]) - 1;
15349 if (pos >= 0)
15350 rettv->vval.v_number = set_cmdline_pos(pos);
15354 * "setline()" function
15356 static void
15357 f_setline(argvars, rettv)
15358 typval_T *argvars;
15359 typval_T *rettv;
15361 linenr_T lnum;
15362 char_u *line = NULL;
15363 list_T *l = NULL;
15364 listitem_T *li = NULL;
15365 long added = 0;
15366 linenr_T lcount = curbuf->b_ml.ml_line_count;
15368 lnum = get_tv_lnum(&argvars[0]);
15369 if (argvars[1].v_type == VAR_LIST)
15371 l = argvars[1].vval.v_list;
15372 li = l->lv_first;
15374 else
15375 line = get_tv_string_chk(&argvars[1]);
15377 rettv->vval.v_number = 0; /* OK */
15378 for (;;)
15380 if (l != NULL)
15382 /* list argument, get next string */
15383 if (li == NULL)
15384 break;
15385 line = get_tv_string_chk(&li->li_tv);
15386 li = li->li_next;
15389 rettv->vval.v_number = 1; /* FAIL */
15390 if (line == NULL || lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
15391 break;
15392 if (lnum <= curbuf->b_ml.ml_line_count)
15394 /* existing line, replace it */
15395 if (u_savesub(lnum) == OK && ml_replace(lnum, line, TRUE) == OK)
15397 changed_bytes(lnum, 0);
15398 if (lnum == curwin->w_cursor.lnum)
15399 check_cursor_col();
15400 rettv->vval.v_number = 0; /* OK */
15403 else if (added > 0 || u_save(lnum - 1, lnum) == OK)
15405 /* lnum is one past the last line, append the line */
15406 ++added;
15407 if (ml_append(lnum - 1, line, (colnr_T)0, FALSE) == OK)
15408 rettv->vval.v_number = 0; /* OK */
15411 if (l == NULL) /* only one string argument */
15412 break;
15413 ++lnum;
15416 if (added > 0)
15417 appended_lines_mark(lcount, added);
15420 static void set_qf_ll_list __ARGS((win_T *wp, typval_T *list_arg, typval_T *action_arg, typval_T *rettv));
15423 * Used by "setqflist()" and "setloclist()" functions
15425 /*ARGSUSED*/
15426 static void
15427 set_qf_ll_list(wp, list_arg, action_arg, rettv)
15428 win_T *wp;
15429 typval_T *list_arg;
15430 typval_T *action_arg;
15431 typval_T *rettv;
15433 #ifdef FEAT_QUICKFIX
15434 char_u *act;
15435 int action = ' ';
15436 #endif
15438 rettv->vval.v_number = -1;
15440 #ifdef FEAT_QUICKFIX
15441 if (list_arg->v_type != VAR_LIST)
15442 EMSG(_(e_listreq));
15443 else
15445 list_T *l = list_arg->vval.v_list;
15447 if (action_arg->v_type == VAR_STRING)
15449 act = get_tv_string_chk(action_arg);
15450 if (act == NULL)
15451 return; /* type error; errmsg already given */
15452 if (*act == 'a' || *act == 'r')
15453 action = *act;
15456 if (l != NULL && set_errorlist(wp, l, action) == OK)
15457 rettv->vval.v_number = 0;
15459 #endif
15463 * "setloclist()" function
15465 /*ARGSUSED*/
15466 static void
15467 f_setloclist(argvars, rettv)
15468 typval_T *argvars;
15469 typval_T *rettv;
15471 win_T *win;
15473 rettv->vval.v_number = -1;
15475 win = find_win_by_nr(&argvars[0], NULL);
15476 if (win != NULL)
15477 set_qf_ll_list(win, &argvars[1], &argvars[2], rettv);
15481 * "setmatches()" function
15483 static void
15484 f_setmatches(argvars, rettv)
15485 typval_T *argvars;
15486 typval_T *rettv;
15488 #ifdef FEAT_SEARCH_EXTRA
15489 list_T *l;
15490 listitem_T *li;
15491 dict_T *d;
15493 rettv->vval.v_number = -1;
15494 if (argvars[0].v_type != VAR_LIST)
15496 EMSG(_(e_listreq));
15497 return;
15499 if ((l = argvars[0].vval.v_list) != NULL)
15502 /* To some extent make sure that we are dealing with a list from
15503 * "getmatches()". */
15504 li = l->lv_first;
15505 while (li != NULL)
15507 if (li->li_tv.v_type != VAR_DICT
15508 || (d = li->li_tv.vval.v_dict) == NULL)
15510 EMSG(_(e_invarg));
15511 return;
15513 if (!(dict_find(d, (char_u *)"group", -1) != NULL
15514 && dict_find(d, (char_u *)"pattern", -1) != NULL
15515 && dict_find(d, (char_u *)"priority", -1) != NULL
15516 && dict_find(d, (char_u *)"id", -1) != NULL))
15518 EMSG(_(e_invarg));
15519 return;
15521 li = li->li_next;
15524 clear_matches(curwin);
15525 li = l->lv_first;
15526 while (li != NULL)
15528 d = li->li_tv.vval.v_dict;
15529 match_add(curwin, get_dict_string(d, (char_u *)"group", FALSE),
15530 get_dict_string(d, (char_u *)"pattern", FALSE),
15531 (int)get_dict_number(d, (char_u *)"priority"),
15532 (int)get_dict_number(d, (char_u *)"id"));
15533 li = li->li_next;
15535 rettv->vval.v_number = 0;
15537 #endif
15541 * "setpos()" function
15543 /*ARGSUSED*/
15544 static void
15545 f_setpos(argvars, rettv)
15546 typval_T *argvars;
15547 typval_T *rettv;
15549 pos_T pos;
15550 int fnum;
15551 char_u *name;
15553 rettv->vval.v_number = -1;
15554 name = get_tv_string_chk(argvars);
15555 if (name != NULL)
15557 if (list2fpos(&argvars[1], &pos, &fnum) == OK)
15559 --pos.col;
15560 if (name[0] == '.' && name[1] == NUL)
15562 /* set cursor */
15563 if (fnum == curbuf->b_fnum)
15565 curwin->w_cursor = pos;
15566 check_cursor();
15567 rettv->vval.v_number = 0;
15569 else
15570 EMSG(_(e_invarg));
15572 else if (name[0] == '\'' && name[1] != NUL && name[2] == NUL)
15574 /* set mark */
15575 if (setmark_pos(name[1], &pos, fnum) == OK)
15576 rettv->vval.v_number = 0;
15578 else
15579 EMSG(_(e_invarg));
15585 * "setqflist()" function
15587 /*ARGSUSED*/
15588 static void
15589 f_setqflist(argvars, rettv)
15590 typval_T *argvars;
15591 typval_T *rettv;
15593 set_qf_ll_list(NULL, &argvars[0], &argvars[1], rettv);
15597 * "setreg()" function
15599 static void
15600 f_setreg(argvars, rettv)
15601 typval_T *argvars;
15602 typval_T *rettv;
15604 int regname;
15605 char_u *strregname;
15606 char_u *stropt;
15607 char_u *strval;
15608 int append;
15609 char_u yank_type;
15610 long block_len;
15612 block_len = -1;
15613 yank_type = MAUTO;
15614 append = FALSE;
15616 strregname = get_tv_string_chk(argvars);
15617 rettv->vval.v_number = 1; /* FAIL is default */
15619 if (strregname == NULL)
15620 return; /* type error; errmsg already given */
15621 regname = *strregname;
15622 if (regname == 0 || regname == '@')
15623 regname = '"';
15624 else if (regname == '=')
15625 return;
15627 if (argvars[2].v_type != VAR_UNKNOWN)
15629 stropt = get_tv_string_chk(&argvars[2]);
15630 if (stropt == NULL)
15631 return; /* type error */
15632 for (; *stropt != NUL; ++stropt)
15633 switch (*stropt)
15635 case 'a': case 'A': /* append */
15636 append = TRUE;
15637 break;
15638 case 'v': case 'c': /* character-wise selection */
15639 yank_type = MCHAR;
15640 break;
15641 case 'V': case 'l': /* line-wise selection */
15642 yank_type = MLINE;
15643 break;
15644 #ifdef FEAT_VISUAL
15645 case 'b': case Ctrl_V: /* block-wise selection */
15646 yank_type = MBLOCK;
15647 if (VIM_ISDIGIT(stropt[1]))
15649 ++stropt;
15650 block_len = getdigits(&stropt) - 1;
15651 --stropt;
15653 break;
15654 #endif
15658 strval = get_tv_string_chk(&argvars[1]);
15659 if (strval != NULL)
15660 write_reg_contents_ex(regname, strval, -1,
15661 append, yank_type, block_len);
15662 rettv->vval.v_number = 0;
15666 * "settabwinvar()" function
15668 static void
15669 f_settabwinvar(argvars, rettv)
15670 typval_T *argvars;
15671 typval_T *rettv;
15673 setwinvar(argvars, rettv, 1);
15677 * "setwinvar()" function
15679 static void
15680 f_setwinvar(argvars, rettv)
15681 typval_T *argvars;
15682 typval_T *rettv;
15684 setwinvar(argvars, rettv, 0);
15688 * "setwinvar()" and "settabwinvar()" functions
15690 static void
15691 setwinvar(argvars, rettv, off)
15692 typval_T *argvars;
15693 typval_T *rettv;
15694 int off;
15696 win_T *win;
15697 #ifdef FEAT_WINDOWS
15698 win_T *save_curwin;
15699 tabpage_T *save_curtab;
15700 #endif
15701 char_u *varname, *winvarname;
15702 typval_T *varp;
15703 char_u nbuf[NUMBUFLEN];
15704 tabpage_T *tp;
15706 rettv->vval.v_number = 0;
15708 if (check_restricted() || check_secure())
15709 return;
15711 #ifdef FEAT_WINDOWS
15712 if (off == 1)
15713 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
15714 else
15715 tp = curtab;
15716 #endif
15717 win = find_win_by_nr(&argvars[off], tp);
15718 varname = get_tv_string_chk(&argvars[off + 1]);
15719 varp = &argvars[off + 2];
15721 if (win != NULL && varname != NULL && varp != NULL)
15723 #ifdef FEAT_WINDOWS
15724 /* set curwin to be our win, temporarily */
15725 save_curwin = curwin;
15726 save_curtab = curtab;
15727 goto_tabpage_tp(tp);
15728 if (!win_valid(win))
15729 return;
15730 curwin = win;
15731 curbuf = curwin->w_buffer;
15732 #endif
15734 if (*varname == '&')
15736 long numval;
15737 char_u *strval;
15738 int error = FALSE;
15740 ++varname;
15741 numval = get_tv_number_chk(varp, &error);
15742 strval = get_tv_string_buf_chk(varp, nbuf);
15743 if (!error && strval != NULL)
15744 set_option_value(varname, numval, strval, OPT_LOCAL);
15746 else
15748 winvarname = alloc((unsigned)STRLEN(varname) + 3);
15749 if (winvarname != NULL)
15751 STRCPY(winvarname, "w:");
15752 STRCPY(winvarname + 2, varname);
15753 set_var(winvarname, varp, TRUE);
15754 vim_free(winvarname);
15758 #ifdef FEAT_WINDOWS
15759 /* Restore current tabpage and window, if still valid (autocomands can
15760 * make them invalid). */
15761 if (valid_tabpage(save_curtab))
15762 goto_tabpage_tp(save_curtab);
15763 if (win_valid(save_curwin))
15765 curwin = save_curwin;
15766 curbuf = curwin->w_buffer;
15768 #endif
15773 * "shellescape({string})" function
15775 static void
15776 f_shellescape(argvars, rettv)
15777 typval_T *argvars;
15778 typval_T *rettv;
15780 rettv->vval.v_string = vim_strsave_shellescape(
15781 get_tv_string(&argvars[0]), non_zero_arg(&argvars[1]));
15782 rettv->v_type = VAR_STRING;
15786 * "simplify()" function
15788 static void
15789 f_simplify(argvars, rettv)
15790 typval_T *argvars;
15791 typval_T *rettv;
15793 char_u *p;
15795 p = get_tv_string(&argvars[0]);
15796 rettv->vval.v_string = vim_strsave(p);
15797 simplify_filename(rettv->vval.v_string); /* simplify in place */
15798 rettv->v_type = VAR_STRING;
15801 #ifdef FEAT_FLOAT
15803 * "sin()" function
15805 static void
15806 f_sin(argvars, rettv)
15807 typval_T *argvars;
15808 typval_T *rettv;
15810 float_T f;
15812 rettv->v_type = VAR_FLOAT;
15813 if (get_float_arg(argvars, &f) == OK)
15814 rettv->vval.v_float = sin(f);
15815 else
15816 rettv->vval.v_float = 0.0;
15818 #endif
15820 static int
15821 #ifdef __BORLANDC__
15822 _RTLENTRYF
15823 #endif
15824 item_compare __ARGS((const void *s1, const void *s2));
15825 static int
15826 #ifdef __BORLANDC__
15827 _RTLENTRYF
15828 #endif
15829 item_compare2 __ARGS((const void *s1, const void *s2));
15831 static int item_compare_ic;
15832 static char_u *item_compare_func;
15833 static int item_compare_func_err;
15834 #define ITEM_COMPARE_FAIL 999
15837 * Compare functions for f_sort() below.
15839 static int
15840 #ifdef __BORLANDC__
15841 _RTLENTRYF
15842 #endif
15843 item_compare(s1, s2)
15844 const void *s1;
15845 const void *s2;
15847 char_u *p1, *p2;
15848 char_u *tofree1, *tofree2;
15849 int res;
15850 char_u numbuf1[NUMBUFLEN];
15851 char_u numbuf2[NUMBUFLEN];
15853 p1 = tv2string(&(*(listitem_T **)s1)->li_tv, &tofree1, numbuf1, 0);
15854 p2 = tv2string(&(*(listitem_T **)s2)->li_tv, &tofree2, numbuf2, 0);
15855 if (p1 == NULL)
15856 p1 = (char_u *)"";
15857 if (p2 == NULL)
15858 p2 = (char_u *)"";
15859 if (item_compare_ic)
15860 res = STRICMP(p1, p2);
15861 else
15862 res = STRCMP(p1, p2);
15863 vim_free(tofree1);
15864 vim_free(tofree2);
15865 return res;
15868 static int
15869 #ifdef __BORLANDC__
15870 _RTLENTRYF
15871 #endif
15872 item_compare2(s1, s2)
15873 const void *s1;
15874 const void *s2;
15876 int res;
15877 typval_T rettv;
15878 typval_T argv[3];
15879 int dummy;
15881 /* shortcut after failure in previous call; compare all items equal */
15882 if (item_compare_func_err)
15883 return 0;
15885 /* copy the values. This is needed to be able to set v_lock to VAR_FIXED
15886 * in the copy without changing the original list items. */
15887 copy_tv(&(*(listitem_T **)s1)->li_tv, &argv[0]);
15888 copy_tv(&(*(listitem_T **)s2)->li_tv, &argv[1]);
15890 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
15891 res = call_func(item_compare_func, (int)STRLEN(item_compare_func),
15892 &rettv, 2, argv, 0L, 0L, &dummy, TRUE, NULL);
15893 clear_tv(&argv[0]);
15894 clear_tv(&argv[1]);
15896 if (res == FAIL)
15897 res = ITEM_COMPARE_FAIL;
15898 else
15899 res = get_tv_number_chk(&rettv, &item_compare_func_err);
15900 if (item_compare_func_err)
15901 res = ITEM_COMPARE_FAIL; /* return value has wrong type */
15902 clear_tv(&rettv);
15903 return res;
15907 * "sort({list})" function
15909 static void
15910 f_sort(argvars, rettv)
15911 typval_T *argvars;
15912 typval_T *rettv;
15914 list_T *l;
15915 listitem_T *li;
15916 listitem_T **ptrs;
15917 long len;
15918 long i;
15920 rettv->vval.v_number = 0;
15921 if (argvars[0].v_type != VAR_LIST)
15922 EMSG2(_(e_listarg), "sort()");
15923 else
15925 l = argvars[0].vval.v_list;
15926 if (l == NULL || tv_check_lock(l->lv_lock, (char_u *)"sort()"))
15927 return;
15928 rettv->vval.v_list = l;
15929 rettv->v_type = VAR_LIST;
15930 ++l->lv_refcount;
15932 len = list_len(l);
15933 if (len <= 1)
15934 return; /* short list sorts pretty quickly */
15936 item_compare_ic = FALSE;
15937 item_compare_func = NULL;
15938 if (argvars[1].v_type != VAR_UNKNOWN)
15940 if (argvars[1].v_type == VAR_FUNC)
15941 item_compare_func = argvars[1].vval.v_string;
15942 else
15944 int error = FALSE;
15946 i = get_tv_number_chk(&argvars[1], &error);
15947 if (error)
15948 return; /* type error; errmsg already given */
15949 if (i == 1)
15950 item_compare_ic = TRUE;
15951 else
15952 item_compare_func = get_tv_string(&argvars[1]);
15956 /* Make an array with each entry pointing to an item in the List. */
15957 ptrs = (listitem_T **)alloc((int)(len * sizeof(listitem_T *)));
15958 if (ptrs == NULL)
15959 return;
15960 i = 0;
15961 for (li = l->lv_first; li != NULL; li = li->li_next)
15962 ptrs[i++] = li;
15964 item_compare_func_err = FALSE;
15965 /* test the compare function */
15966 if (item_compare_func != NULL
15967 && item_compare2((void *)&ptrs[0], (void *)&ptrs[1])
15968 == ITEM_COMPARE_FAIL)
15969 EMSG(_("E702: Sort compare function failed"));
15970 else
15972 /* Sort the array with item pointers. */
15973 qsort((void *)ptrs, (size_t)len, sizeof(listitem_T *),
15974 item_compare_func == NULL ? item_compare : item_compare2);
15976 if (!item_compare_func_err)
15978 /* Clear the List and append the items in the sorted order. */
15979 l->lv_first = l->lv_last = l->lv_idx_item = NULL;
15980 l->lv_len = 0;
15981 for (i = 0; i < len; ++i)
15982 list_append(l, ptrs[i]);
15986 vim_free(ptrs);
15991 * "soundfold({word})" function
15993 static void
15994 f_soundfold(argvars, rettv)
15995 typval_T *argvars;
15996 typval_T *rettv;
15998 char_u *s;
16000 rettv->v_type = VAR_STRING;
16001 s = get_tv_string(&argvars[0]);
16002 #ifdef FEAT_SPELL
16003 rettv->vval.v_string = eval_soundfold(s);
16004 #else
16005 rettv->vval.v_string = vim_strsave(s);
16006 #endif
16010 * "spellbadword()" function
16012 /* ARGSUSED */
16013 static void
16014 f_spellbadword(argvars, rettv)
16015 typval_T *argvars;
16016 typval_T *rettv;
16018 char_u *word = (char_u *)"";
16019 hlf_T attr = HLF_COUNT;
16020 int len = 0;
16022 if (rettv_list_alloc(rettv) == FAIL)
16023 return;
16025 #ifdef FEAT_SPELL
16026 if (argvars[0].v_type == VAR_UNKNOWN)
16028 /* Find the start and length of the badly spelled word. */
16029 len = spell_move_to(curwin, FORWARD, TRUE, TRUE, &attr);
16030 if (len != 0)
16031 word = ml_get_cursor();
16033 else if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
16035 char_u *str = get_tv_string_chk(&argvars[0]);
16036 int capcol = -1;
16038 if (str != NULL)
16040 /* Check the argument for spelling. */
16041 while (*str != NUL)
16043 len = spell_check(curwin, str, &attr, &capcol, FALSE);
16044 if (attr != HLF_COUNT)
16046 word = str;
16047 break;
16049 str += len;
16053 #endif
16055 list_append_string(rettv->vval.v_list, word, len);
16056 list_append_string(rettv->vval.v_list, (char_u *)(
16057 attr == HLF_SPB ? "bad" :
16058 attr == HLF_SPR ? "rare" :
16059 attr == HLF_SPL ? "local" :
16060 attr == HLF_SPC ? "caps" :
16061 ""), -1);
16065 * "spellsuggest()" function
16067 /*ARGSUSED*/
16068 static void
16069 f_spellsuggest(argvars, rettv)
16070 typval_T *argvars;
16071 typval_T *rettv;
16073 #ifdef FEAT_SPELL
16074 char_u *str;
16075 int typeerr = FALSE;
16076 int maxcount;
16077 garray_T ga;
16078 int i;
16079 listitem_T *li;
16080 int need_capital = FALSE;
16081 #endif
16083 if (rettv_list_alloc(rettv) == FAIL)
16084 return;
16086 #ifdef FEAT_SPELL
16087 if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
16089 str = get_tv_string(&argvars[0]);
16090 if (argvars[1].v_type != VAR_UNKNOWN)
16092 maxcount = get_tv_number_chk(&argvars[1], &typeerr);
16093 if (maxcount <= 0)
16094 return;
16095 if (argvars[2].v_type != VAR_UNKNOWN)
16097 need_capital = get_tv_number_chk(&argvars[2], &typeerr);
16098 if (typeerr)
16099 return;
16102 else
16103 maxcount = 25;
16105 spell_suggest_list(&ga, str, maxcount, need_capital, FALSE);
16107 for (i = 0; i < ga.ga_len; ++i)
16109 str = ((char_u **)ga.ga_data)[i];
16111 li = listitem_alloc();
16112 if (li == NULL)
16113 vim_free(str);
16114 else
16116 li->li_tv.v_type = VAR_STRING;
16117 li->li_tv.v_lock = 0;
16118 li->li_tv.vval.v_string = str;
16119 list_append(rettv->vval.v_list, li);
16122 ga_clear(&ga);
16124 #endif
16127 static void
16128 f_split(argvars, rettv)
16129 typval_T *argvars;
16130 typval_T *rettv;
16132 char_u *str;
16133 char_u *end;
16134 char_u *pat = NULL;
16135 regmatch_T regmatch;
16136 char_u patbuf[NUMBUFLEN];
16137 char_u *save_cpo;
16138 int match;
16139 colnr_T col = 0;
16140 int keepempty = FALSE;
16141 int typeerr = FALSE;
16143 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
16144 save_cpo = p_cpo;
16145 p_cpo = (char_u *)"";
16147 str = get_tv_string(&argvars[0]);
16148 if (argvars[1].v_type != VAR_UNKNOWN)
16150 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
16151 if (pat == NULL)
16152 typeerr = TRUE;
16153 if (argvars[2].v_type != VAR_UNKNOWN)
16154 keepempty = get_tv_number_chk(&argvars[2], &typeerr);
16156 if (pat == NULL || *pat == NUL)
16157 pat = (char_u *)"[\\x01- ]\\+";
16159 if (rettv_list_alloc(rettv) == FAIL)
16160 return;
16161 if (typeerr)
16162 return;
16164 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
16165 if (regmatch.regprog != NULL)
16167 regmatch.rm_ic = FALSE;
16168 while (*str != NUL || keepempty)
16170 if (*str == NUL)
16171 match = FALSE; /* empty item at the end */
16172 else
16173 match = vim_regexec_nl(&regmatch, str, col);
16174 if (match)
16175 end = regmatch.startp[0];
16176 else
16177 end = str + STRLEN(str);
16178 if (keepempty || end > str || (rettv->vval.v_list->lv_len > 0
16179 && *str != NUL && match && end < regmatch.endp[0]))
16181 if (list_append_string(rettv->vval.v_list, str,
16182 (int)(end - str)) == FAIL)
16183 break;
16185 if (!match)
16186 break;
16187 /* Advance to just after the match. */
16188 if (regmatch.endp[0] > str)
16189 col = 0;
16190 else
16192 /* Don't get stuck at the same match. */
16193 #ifdef FEAT_MBYTE
16194 col = (*mb_ptr2len)(regmatch.endp[0]);
16195 #else
16196 col = 1;
16197 #endif
16199 str = regmatch.endp[0];
16202 vim_free(regmatch.regprog);
16205 p_cpo = save_cpo;
16208 #ifdef FEAT_FLOAT
16210 * "sqrt()" function
16212 static void
16213 f_sqrt(argvars, rettv)
16214 typval_T *argvars;
16215 typval_T *rettv;
16217 float_T f;
16219 rettv->v_type = VAR_FLOAT;
16220 if (get_float_arg(argvars, &f) == OK)
16221 rettv->vval.v_float = sqrt(f);
16222 else
16223 rettv->vval.v_float = 0.0;
16227 * "str2float()" function
16229 static void
16230 f_str2float(argvars, rettv)
16231 typval_T *argvars;
16232 typval_T *rettv;
16234 char_u *p = skipwhite(get_tv_string(&argvars[0]));
16236 if (*p == '+')
16237 p = skipwhite(p + 1);
16238 (void)string2float(p, &rettv->vval.v_float);
16239 rettv->v_type = VAR_FLOAT;
16241 #endif
16244 * "str2nr()" function
16246 static void
16247 f_str2nr(argvars, rettv)
16248 typval_T *argvars;
16249 typval_T *rettv;
16251 int base = 10;
16252 char_u *p;
16253 long n;
16255 if (argvars[1].v_type != VAR_UNKNOWN)
16257 base = get_tv_number(&argvars[1]);
16258 if (base != 8 && base != 10 && base != 16)
16260 EMSG(_(e_invarg));
16261 return;
16265 p = skipwhite(get_tv_string(&argvars[0]));
16266 if (*p == '+')
16267 p = skipwhite(p + 1);
16268 vim_str2nr(p, NULL, NULL, base == 8 ? 2 : 0, base == 16 ? 2 : 0, &n, NULL);
16269 rettv->vval.v_number = n;
16272 #ifdef HAVE_STRFTIME
16274 * "strftime({format}[, {time}])" function
16276 static void
16277 f_strftime(argvars, rettv)
16278 typval_T *argvars;
16279 typval_T *rettv;
16281 char_u result_buf[256];
16282 struct tm *curtime;
16283 time_t seconds;
16284 char_u *p;
16286 rettv->v_type = VAR_STRING;
16288 p = get_tv_string(&argvars[0]);
16289 if (argvars[1].v_type == VAR_UNKNOWN)
16290 seconds = time(NULL);
16291 else
16292 seconds = (time_t)get_tv_number(&argvars[1]);
16293 curtime = localtime(&seconds);
16294 /* MSVC returns NULL for an invalid value of seconds. */
16295 if (curtime == NULL)
16296 rettv->vval.v_string = vim_strsave((char_u *)_("(Invalid)"));
16297 else
16299 # ifdef FEAT_MBYTE
16300 vimconv_T conv;
16301 char_u *enc;
16303 conv.vc_type = CONV_NONE;
16304 enc = enc_locale();
16305 convert_setup(&conv, p_enc, enc);
16306 if (conv.vc_type != CONV_NONE)
16307 p = string_convert(&conv, p, NULL);
16308 # endif
16309 if (p != NULL)
16310 (void)strftime((char *)result_buf, sizeof(result_buf),
16311 (char *)p, curtime);
16312 else
16313 result_buf[0] = NUL;
16315 # ifdef FEAT_MBYTE
16316 if (conv.vc_type != CONV_NONE)
16317 vim_free(p);
16318 convert_setup(&conv, enc, p_enc);
16319 if (conv.vc_type != CONV_NONE)
16320 rettv->vval.v_string = string_convert(&conv, result_buf, NULL);
16321 else
16322 # endif
16323 rettv->vval.v_string = vim_strsave(result_buf);
16325 # ifdef FEAT_MBYTE
16326 /* Release conversion descriptors */
16327 convert_setup(&conv, NULL, NULL);
16328 vim_free(enc);
16329 # endif
16332 #endif
16335 * "stridx()" function
16337 static void
16338 f_stridx(argvars, rettv)
16339 typval_T *argvars;
16340 typval_T *rettv;
16342 char_u buf[NUMBUFLEN];
16343 char_u *needle;
16344 char_u *haystack;
16345 char_u *save_haystack;
16346 char_u *pos;
16347 int start_idx;
16349 needle = get_tv_string_chk(&argvars[1]);
16350 save_haystack = haystack = get_tv_string_buf_chk(&argvars[0], buf);
16351 rettv->vval.v_number = -1;
16352 if (needle == NULL || haystack == NULL)
16353 return; /* type error; errmsg already given */
16355 if (argvars[2].v_type != VAR_UNKNOWN)
16357 int error = FALSE;
16359 start_idx = get_tv_number_chk(&argvars[2], &error);
16360 if (error || start_idx >= (int)STRLEN(haystack))
16361 return;
16362 if (start_idx >= 0)
16363 haystack += start_idx;
16366 pos = (char_u *)strstr((char *)haystack, (char *)needle);
16367 if (pos != NULL)
16368 rettv->vval.v_number = (varnumber_T)(pos - save_haystack);
16372 * "string()" function
16374 static void
16375 f_string(argvars, rettv)
16376 typval_T *argvars;
16377 typval_T *rettv;
16379 char_u *tofree;
16380 char_u numbuf[NUMBUFLEN];
16382 rettv->v_type = VAR_STRING;
16383 rettv->vval.v_string = tv2string(&argvars[0], &tofree, numbuf, 0);
16384 /* Make a copy if we have a value but it's not in allocated memory. */
16385 if (rettv->vval.v_string != NULL && tofree == NULL)
16386 rettv->vval.v_string = vim_strsave(rettv->vval.v_string);
16390 * "strlen()" function
16392 static void
16393 f_strlen(argvars, rettv)
16394 typval_T *argvars;
16395 typval_T *rettv;
16397 rettv->vval.v_number = (varnumber_T)(STRLEN(
16398 get_tv_string(&argvars[0])));
16402 * "strpart()" function
16404 static void
16405 f_strpart(argvars, rettv)
16406 typval_T *argvars;
16407 typval_T *rettv;
16409 char_u *p;
16410 int n;
16411 int len;
16412 int slen;
16413 int error = FALSE;
16415 p = get_tv_string(&argvars[0]);
16416 slen = (int)STRLEN(p);
16418 n = get_tv_number_chk(&argvars[1], &error);
16419 if (error)
16420 len = 0;
16421 else if (argvars[2].v_type != VAR_UNKNOWN)
16422 len = get_tv_number(&argvars[2]);
16423 else
16424 len = slen - n; /* default len: all bytes that are available. */
16427 * Only return the overlap between the specified part and the actual
16428 * string.
16430 if (n < 0)
16432 len += n;
16433 n = 0;
16435 else if (n > slen)
16436 n = slen;
16437 if (len < 0)
16438 len = 0;
16439 else if (n + len > slen)
16440 len = slen - n;
16442 rettv->v_type = VAR_STRING;
16443 rettv->vval.v_string = vim_strnsave(p + n, len);
16447 * "strridx()" function
16449 static void
16450 f_strridx(argvars, rettv)
16451 typval_T *argvars;
16452 typval_T *rettv;
16454 char_u buf[NUMBUFLEN];
16455 char_u *needle;
16456 char_u *haystack;
16457 char_u *rest;
16458 char_u *lastmatch = NULL;
16459 int haystack_len, end_idx;
16461 needle = get_tv_string_chk(&argvars[1]);
16462 haystack = get_tv_string_buf_chk(&argvars[0], buf);
16464 rettv->vval.v_number = -1;
16465 if (needle == NULL || haystack == NULL)
16466 return; /* type error; errmsg already given */
16468 haystack_len = (int)STRLEN(haystack);
16469 if (argvars[2].v_type != VAR_UNKNOWN)
16471 /* Third argument: upper limit for index */
16472 end_idx = get_tv_number_chk(&argvars[2], NULL);
16473 if (end_idx < 0)
16474 return; /* can never find a match */
16476 else
16477 end_idx = haystack_len;
16479 if (*needle == NUL)
16481 /* Empty string matches past the end. */
16482 lastmatch = haystack + end_idx;
16484 else
16486 for (rest = haystack; *rest != '\0'; ++rest)
16488 rest = (char_u *)strstr((char *)rest, (char *)needle);
16489 if (rest == NULL || rest > haystack + end_idx)
16490 break;
16491 lastmatch = rest;
16495 if (lastmatch == NULL)
16496 rettv->vval.v_number = -1;
16497 else
16498 rettv->vval.v_number = (varnumber_T)(lastmatch - haystack);
16502 * "strtrans()" function
16504 static void
16505 f_strtrans(argvars, rettv)
16506 typval_T *argvars;
16507 typval_T *rettv;
16509 rettv->v_type = VAR_STRING;
16510 rettv->vval.v_string = transstr(get_tv_string(&argvars[0]));
16514 * "submatch()" function
16516 static void
16517 f_submatch(argvars, rettv)
16518 typval_T *argvars;
16519 typval_T *rettv;
16521 rettv->v_type = VAR_STRING;
16522 rettv->vval.v_string =
16523 reg_submatch((int)get_tv_number_chk(&argvars[0], NULL));
16527 * "substitute()" function
16529 static void
16530 f_substitute(argvars, rettv)
16531 typval_T *argvars;
16532 typval_T *rettv;
16534 char_u patbuf[NUMBUFLEN];
16535 char_u subbuf[NUMBUFLEN];
16536 char_u flagsbuf[NUMBUFLEN];
16538 char_u *str = get_tv_string_chk(&argvars[0]);
16539 char_u *pat = get_tv_string_buf_chk(&argvars[1], patbuf);
16540 char_u *sub = get_tv_string_buf_chk(&argvars[2], subbuf);
16541 char_u *flg = get_tv_string_buf_chk(&argvars[3], flagsbuf);
16543 rettv->v_type = VAR_STRING;
16544 if (str == NULL || pat == NULL || sub == NULL || flg == NULL)
16545 rettv->vval.v_string = NULL;
16546 else
16547 rettv->vval.v_string = do_string_sub(str, pat, sub, flg);
16551 * "synID(lnum, col, trans)" function
16553 /*ARGSUSED*/
16554 static void
16555 f_synID(argvars, rettv)
16556 typval_T *argvars;
16557 typval_T *rettv;
16559 int id = 0;
16560 #ifdef FEAT_SYN_HL
16561 long lnum;
16562 long col;
16563 int trans;
16564 int transerr = FALSE;
16566 lnum = get_tv_lnum(argvars); /* -1 on type error */
16567 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
16568 trans = get_tv_number_chk(&argvars[2], &transerr);
16570 if (!transerr && lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
16571 && col >= 0 && col < (long)STRLEN(ml_get(lnum)))
16572 id = syn_get_id(curwin, lnum, (colnr_T)col, trans, NULL, FALSE);
16573 #endif
16575 rettv->vval.v_number = id;
16579 * "synIDattr(id, what [, mode])" function
16581 /*ARGSUSED*/
16582 static void
16583 f_synIDattr(argvars, rettv)
16584 typval_T *argvars;
16585 typval_T *rettv;
16587 char_u *p = NULL;
16588 #ifdef FEAT_SYN_HL
16589 int id;
16590 char_u *what;
16591 char_u *mode;
16592 char_u modebuf[NUMBUFLEN];
16593 int modec;
16595 id = get_tv_number(&argvars[0]);
16596 what = get_tv_string(&argvars[1]);
16597 if (argvars[2].v_type != VAR_UNKNOWN)
16599 mode = get_tv_string_buf(&argvars[2], modebuf);
16600 modec = TOLOWER_ASC(mode[0]);
16601 if (modec != 't' && modec != 'c'
16602 #ifdef FEAT_GUI
16603 && modec != 'g'
16604 #endif
16606 modec = 0; /* replace invalid with current */
16608 else
16610 #ifdef FEAT_GUI
16611 if (gui.in_use)
16612 modec = 'g';
16613 else
16614 #endif
16615 if (t_colors > 1)
16616 modec = 'c';
16617 else
16618 modec = 't';
16622 switch (TOLOWER_ASC(what[0]))
16624 case 'b':
16625 if (TOLOWER_ASC(what[1]) == 'g') /* bg[#] */
16626 p = highlight_color(id, what, modec);
16627 else /* bold */
16628 p = highlight_has_attr(id, HL_BOLD, modec);
16629 break;
16631 case 'f': /* fg[#] */
16632 p = highlight_color(id, what, modec);
16633 break;
16635 case 'i':
16636 if (TOLOWER_ASC(what[1]) == 'n') /* inverse */
16637 p = highlight_has_attr(id, HL_INVERSE, modec);
16638 else /* italic */
16639 p = highlight_has_attr(id, HL_ITALIC, modec);
16640 break;
16642 case 'n': /* name */
16643 p = get_highlight_name(NULL, id - 1);
16644 break;
16646 case 'r': /* reverse */
16647 p = highlight_has_attr(id, HL_INVERSE, modec);
16648 break;
16650 case 's': /* standout */
16651 p = highlight_has_attr(id, HL_STANDOUT, modec);
16652 break;
16654 case 'u':
16655 if (STRLEN(what) <= 5 || TOLOWER_ASC(what[5]) != 'c')
16656 /* underline */
16657 p = highlight_has_attr(id, HL_UNDERLINE, modec);
16658 else
16659 /* undercurl */
16660 p = highlight_has_attr(id, HL_UNDERCURL, modec);
16661 break;
16664 if (p != NULL)
16665 p = vim_strsave(p);
16666 #endif
16667 rettv->v_type = VAR_STRING;
16668 rettv->vval.v_string = p;
16672 * "synIDtrans(id)" function
16674 /*ARGSUSED*/
16675 static void
16676 f_synIDtrans(argvars, rettv)
16677 typval_T *argvars;
16678 typval_T *rettv;
16680 int id;
16682 #ifdef FEAT_SYN_HL
16683 id = get_tv_number(&argvars[0]);
16685 if (id > 0)
16686 id = syn_get_final_id(id);
16687 else
16688 #endif
16689 id = 0;
16691 rettv->vval.v_number = id;
16695 * "synstack(lnum, col)" function
16697 /*ARGSUSED*/
16698 static void
16699 f_synstack(argvars, rettv)
16700 typval_T *argvars;
16701 typval_T *rettv;
16703 #ifdef FEAT_SYN_HL
16704 long lnum;
16705 long col;
16706 int i;
16707 int id;
16708 #endif
16710 rettv->v_type = VAR_LIST;
16711 rettv->vval.v_list = NULL;
16713 #ifdef FEAT_SYN_HL
16714 lnum = get_tv_lnum(argvars); /* -1 on type error */
16715 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
16717 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
16718 && col >= 0 && (col == 0 || col < (long)STRLEN(ml_get(lnum)))
16719 && rettv_list_alloc(rettv) != FAIL)
16721 (void)syn_get_id(curwin, lnum, (colnr_T)col, FALSE, NULL, TRUE);
16722 for (i = 0; ; ++i)
16724 id = syn_get_stack_item(i);
16725 if (id < 0)
16726 break;
16727 if (list_append_number(rettv->vval.v_list, id) == FAIL)
16728 break;
16731 #endif
16735 * "system()" function
16737 static void
16738 f_system(argvars, rettv)
16739 typval_T *argvars;
16740 typval_T *rettv;
16742 char_u *res = NULL;
16743 char_u *p;
16744 char_u *infile = NULL;
16745 char_u buf[NUMBUFLEN];
16746 int err = FALSE;
16747 FILE *fd;
16749 if (check_restricted() || check_secure())
16750 goto done;
16752 if (argvars[1].v_type != VAR_UNKNOWN)
16755 * Write the string to a temp file, to be used for input of the shell
16756 * command.
16758 if ((infile = vim_tempname('i')) == NULL)
16760 EMSG(_(e_notmp));
16761 goto done;
16764 fd = mch_fopen((char *)infile, WRITEBIN);
16765 if (fd == NULL)
16767 EMSG2(_(e_notopen), infile);
16768 goto done;
16770 p = get_tv_string_buf_chk(&argvars[1], buf);
16771 if (p == NULL)
16773 fclose(fd);
16774 goto done; /* type error; errmsg already given */
16776 if (fwrite(p, STRLEN(p), 1, fd) != 1)
16777 err = TRUE;
16778 if (fclose(fd) != 0)
16779 err = TRUE;
16780 if (err)
16782 EMSG(_("E677: Error writing temp file"));
16783 goto done;
16787 res = get_cmd_output(get_tv_string(&argvars[0]), infile,
16788 SHELL_SILENT | SHELL_COOKED);
16790 #ifdef USE_CR
16791 /* translate <CR> into <NL> */
16792 if (res != NULL)
16794 char_u *s;
16796 for (s = res; *s; ++s)
16798 if (*s == CAR)
16799 *s = NL;
16802 #else
16803 # ifdef USE_CRNL
16804 /* translate <CR><NL> into <NL> */
16805 if (res != NULL)
16807 char_u *s, *d;
16809 d = res;
16810 for (s = res; *s; ++s)
16812 if (s[0] == CAR && s[1] == NL)
16813 ++s;
16814 *d++ = *s;
16816 *d = NUL;
16818 # endif
16819 #endif
16821 done:
16822 if (infile != NULL)
16824 mch_remove(infile);
16825 vim_free(infile);
16827 rettv->v_type = VAR_STRING;
16828 rettv->vval.v_string = res;
16832 * "tabpagebuflist()" function
16834 /* ARGSUSED */
16835 static void
16836 f_tabpagebuflist(argvars, rettv)
16837 typval_T *argvars;
16838 typval_T *rettv;
16840 #ifndef FEAT_WINDOWS
16841 rettv->vval.v_number = 0;
16842 #else
16843 tabpage_T *tp;
16844 win_T *wp = NULL;
16846 if (argvars[0].v_type == VAR_UNKNOWN)
16847 wp = firstwin;
16848 else
16850 tp = find_tabpage((int)get_tv_number(&argvars[0]));
16851 if (tp != NULL)
16852 wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
16854 if (wp == NULL)
16855 rettv->vval.v_number = 0;
16856 else
16858 if (rettv_list_alloc(rettv) == FAIL)
16859 rettv->vval.v_number = 0;
16860 else
16862 for (; wp != NULL; wp = wp->w_next)
16863 if (list_append_number(rettv->vval.v_list,
16864 wp->w_buffer->b_fnum) == FAIL)
16865 break;
16868 #endif
16873 * "tabpagenr()" function
16875 /* ARGSUSED */
16876 static void
16877 f_tabpagenr(argvars, rettv)
16878 typval_T *argvars;
16879 typval_T *rettv;
16881 int nr = 1;
16882 #ifdef FEAT_WINDOWS
16883 char_u *arg;
16885 if (argvars[0].v_type != VAR_UNKNOWN)
16887 arg = get_tv_string_chk(&argvars[0]);
16888 nr = 0;
16889 if (arg != NULL)
16891 if (STRCMP(arg, "$") == 0)
16892 nr = tabpage_index(NULL) - 1;
16893 else
16894 EMSG2(_(e_invexpr2), arg);
16897 else
16898 nr = tabpage_index(curtab);
16899 #endif
16900 rettv->vval.v_number = nr;
16904 #ifdef FEAT_WINDOWS
16905 static int get_winnr __ARGS((tabpage_T *tp, typval_T *argvar));
16908 * Common code for tabpagewinnr() and winnr().
16910 static int
16911 get_winnr(tp, argvar)
16912 tabpage_T *tp;
16913 typval_T *argvar;
16915 win_T *twin;
16916 int nr = 1;
16917 win_T *wp;
16918 char_u *arg;
16920 twin = (tp == curtab) ? curwin : tp->tp_curwin;
16921 if (argvar->v_type != VAR_UNKNOWN)
16923 arg = get_tv_string_chk(argvar);
16924 if (arg == NULL)
16925 nr = 0; /* type error; errmsg already given */
16926 else if (STRCMP(arg, "$") == 0)
16927 twin = (tp == curtab) ? lastwin : tp->tp_lastwin;
16928 else if (STRCMP(arg, "#") == 0)
16930 twin = (tp == curtab) ? prevwin : tp->tp_prevwin;
16931 if (twin == NULL)
16932 nr = 0;
16934 else
16936 EMSG2(_(e_invexpr2), arg);
16937 nr = 0;
16941 if (nr > 0)
16942 for (wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
16943 wp != twin; wp = wp->w_next)
16945 if (wp == NULL)
16947 /* didn't find it in this tabpage */
16948 nr = 0;
16949 break;
16951 ++nr;
16953 return nr;
16955 #endif
16958 * "tabpagewinnr()" function
16960 /* ARGSUSED */
16961 static void
16962 f_tabpagewinnr(argvars, rettv)
16963 typval_T *argvars;
16964 typval_T *rettv;
16966 int nr = 1;
16967 #ifdef FEAT_WINDOWS
16968 tabpage_T *tp;
16970 tp = find_tabpage((int)get_tv_number(&argvars[0]));
16971 if (tp == NULL)
16972 nr = 0;
16973 else
16974 nr = get_winnr(tp, &argvars[1]);
16975 #endif
16976 rettv->vval.v_number = nr;
16981 * "tagfiles()" function
16983 /*ARGSUSED*/
16984 static void
16985 f_tagfiles(argvars, rettv)
16986 typval_T *argvars;
16987 typval_T *rettv;
16989 char_u fname[MAXPATHL + 1];
16990 tagname_T tn;
16991 int first;
16993 if (rettv_list_alloc(rettv) == FAIL)
16995 rettv->vval.v_number = 0;
16996 return;
16999 for (first = TRUE; ; first = FALSE)
17000 if (get_tagfname(&tn, first, fname) == FAIL
17001 || list_append_string(rettv->vval.v_list, fname, -1) == FAIL)
17002 break;
17003 tagname_free(&tn);
17007 * "taglist()" function
17009 static void
17010 f_taglist(argvars, rettv)
17011 typval_T *argvars;
17012 typval_T *rettv;
17014 char_u *tag_pattern;
17016 tag_pattern = get_tv_string(&argvars[0]);
17018 rettv->vval.v_number = FALSE;
17019 if (*tag_pattern == NUL)
17020 return;
17022 if (rettv_list_alloc(rettv) == OK)
17023 (void)get_tags(rettv->vval.v_list, tag_pattern);
17027 * "tempname()" function
17029 /*ARGSUSED*/
17030 static void
17031 f_tempname(argvars, rettv)
17032 typval_T *argvars;
17033 typval_T *rettv;
17035 static int x = 'A';
17037 rettv->v_type = VAR_STRING;
17038 rettv->vval.v_string = vim_tempname(x);
17040 /* Advance 'x' to use A-Z and 0-9, so that there are at least 34 different
17041 * names. Skip 'I' and 'O', they are used for shell redirection. */
17044 if (x == 'Z')
17045 x = '0';
17046 else if (x == '9')
17047 x = 'A';
17048 else
17050 #ifdef EBCDIC
17051 if (x == 'I')
17052 x = 'J';
17053 else if (x == 'R')
17054 x = 'S';
17055 else
17056 #endif
17057 ++x;
17059 } while (x == 'I' || x == 'O');
17063 * "test(list)" function: Just checking the walls...
17065 /*ARGSUSED*/
17066 static void
17067 f_test(argvars, rettv)
17068 typval_T *argvars;
17069 typval_T *rettv;
17071 /* Used for unit testing. Change the code below to your liking. */
17072 #if 0
17073 listitem_T *li;
17074 list_T *l;
17075 char_u *bad, *good;
17077 if (argvars[0].v_type != VAR_LIST)
17078 return;
17079 l = argvars[0].vval.v_list;
17080 if (l == NULL)
17081 return;
17082 li = l->lv_first;
17083 if (li == NULL)
17084 return;
17085 bad = get_tv_string(&li->li_tv);
17086 li = li->li_next;
17087 if (li == NULL)
17088 return;
17089 good = get_tv_string(&li->li_tv);
17090 rettv->vval.v_number = test_edit_score(bad, good);
17091 #endif
17095 * "tolower(string)" function
17097 static void
17098 f_tolower(argvars, rettv)
17099 typval_T *argvars;
17100 typval_T *rettv;
17102 char_u *p;
17104 p = vim_strsave(get_tv_string(&argvars[0]));
17105 rettv->v_type = VAR_STRING;
17106 rettv->vval.v_string = p;
17108 if (p != NULL)
17109 while (*p != NUL)
17111 #ifdef FEAT_MBYTE
17112 int l;
17114 if (enc_utf8)
17116 int c, lc;
17118 c = utf_ptr2char(p);
17119 lc = utf_tolower(c);
17120 l = utf_ptr2len(p);
17121 /* TODO: reallocate string when byte count changes. */
17122 if (utf_char2len(lc) == l)
17123 utf_char2bytes(lc, p);
17124 p += l;
17126 else if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
17127 p += l; /* skip multi-byte character */
17128 else
17129 #endif
17131 *p = TOLOWER_LOC(*p); /* note that tolower() can be a macro */
17132 ++p;
17138 * "toupper(string)" function
17140 static void
17141 f_toupper(argvars, rettv)
17142 typval_T *argvars;
17143 typval_T *rettv;
17145 rettv->v_type = VAR_STRING;
17146 rettv->vval.v_string = strup_save(get_tv_string(&argvars[0]));
17150 * "tr(string, fromstr, tostr)" function
17152 static void
17153 f_tr(argvars, rettv)
17154 typval_T *argvars;
17155 typval_T *rettv;
17157 char_u *instr;
17158 char_u *fromstr;
17159 char_u *tostr;
17160 char_u *p;
17161 #ifdef FEAT_MBYTE
17162 int inlen;
17163 int fromlen;
17164 int tolen;
17165 int idx;
17166 char_u *cpstr;
17167 int cplen;
17168 int first = TRUE;
17169 #endif
17170 char_u buf[NUMBUFLEN];
17171 char_u buf2[NUMBUFLEN];
17172 garray_T ga;
17174 instr = get_tv_string(&argvars[0]);
17175 fromstr = get_tv_string_buf_chk(&argvars[1], buf);
17176 tostr = get_tv_string_buf_chk(&argvars[2], buf2);
17178 /* Default return value: empty string. */
17179 rettv->v_type = VAR_STRING;
17180 rettv->vval.v_string = NULL;
17181 if (fromstr == NULL || tostr == NULL)
17182 return; /* type error; errmsg already given */
17183 ga_init2(&ga, (int)sizeof(char), 80);
17185 #ifdef FEAT_MBYTE
17186 if (!has_mbyte)
17187 #endif
17188 /* not multi-byte: fromstr and tostr must be the same length */
17189 if (STRLEN(fromstr) != STRLEN(tostr))
17191 #ifdef FEAT_MBYTE
17192 error:
17193 #endif
17194 EMSG2(_(e_invarg2), fromstr);
17195 ga_clear(&ga);
17196 return;
17199 /* fromstr and tostr have to contain the same number of chars */
17200 while (*instr != NUL)
17202 #ifdef FEAT_MBYTE
17203 if (has_mbyte)
17205 inlen = (*mb_ptr2len)(instr);
17206 cpstr = instr;
17207 cplen = inlen;
17208 idx = 0;
17209 for (p = fromstr; *p != NUL; p += fromlen)
17211 fromlen = (*mb_ptr2len)(p);
17212 if (fromlen == inlen && STRNCMP(instr, p, inlen) == 0)
17214 for (p = tostr; *p != NUL; p += tolen)
17216 tolen = (*mb_ptr2len)(p);
17217 if (idx-- == 0)
17219 cplen = tolen;
17220 cpstr = p;
17221 break;
17224 if (*p == NUL) /* tostr is shorter than fromstr */
17225 goto error;
17226 break;
17228 ++idx;
17231 if (first && cpstr == instr)
17233 /* Check that fromstr and tostr have the same number of
17234 * (multi-byte) characters. Done only once when a character
17235 * of instr doesn't appear in fromstr. */
17236 first = FALSE;
17237 for (p = tostr; *p != NUL; p += tolen)
17239 tolen = (*mb_ptr2len)(p);
17240 --idx;
17242 if (idx != 0)
17243 goto error;
17246 ga_grow(&ga, cplen);
17247 mch_memmove((char *)ga.ga_data + ga.ga_len, cpstr, (size_t)cplen);
17248 ga.ga_len += cplen;
17250 instr += inlen;
17252 else
17253 #endif
17255 /* When not using multi-byte chars we can do it faster. */
17256 p = vim_strchr(fromstr, *instr);
17257 if (p != NULL)
17258 ga_append(&ga, tostr[p - fromstr]);
17259 else
17260 ga_append(&ga, *instr);
17261 ++instr;
17265 /* add a terminating NUL */
17266 ga_grow(&ga, 1);
17267 ga_append(&ga, NUL);
17269 rettv->vval.v_string = ga.ga_data;
17272 #ifdef FEAT_FLOAT
17274 * "trunc({float})" function
17276 static void
17277 f_trunc(argvars, rettv)
17278 typval_T *argvars;
17279 typval_T *rettv;
17281 float_T f;
17283 rettv->v_type = VAR_FLOAT;
17284 if (get_float_arg(argvars, &f) == OK)
17285 /* trunc() is not in C90, use floor() or ceil() instead. */
17286 rettv->vval.v_float = f > 0 ? floor(f) : ceil(f);
17287 else
17288 rettv->vval.v_float = 0.0;
17290 #endif
17293 * "type(expr)" function
17295 static void
17296 f_type(argvars, rettv)
17297 typval_T *argvars;
17298 typval_T *rettv;
17300 int n;
17302 switch (argvars[0].v_type)
17304 case VAR_NUMBER: n = 0; break;
17305 case VAR_STRING: n = 1; break;
17306 case VAR_FUNC: n = 2; break;
17307 case VAR_LIST: n = 3; break;
17308 case VAR_DICT: n = 4; break;
17309 #ifdef FEAT_FLOAT
17310 case VAR_FLOAT: n = 5; break;
17311 #endif
17312 default: EMSG2(_(e_intern2), "f_type()"); n = 0; break;
17314 rettv->vval.v_number = n;
17318 * "values(dict)" function
17320 static void
17321 f_values(argvars, rettv)
17322 typval_T *argvars;
17323 typval_T *rettv;
17325 dict_list(argvars, rettv, 1);
17329 * "virtcol(string)" function
17331 static void
17332 f_virtcol(argvars, rettv)
17333 typval_T *argvars;
17334 typval_T *rettv;
17336 colnr_T vcol = 0;
17337 pos_T *fp;
17338 int fnum = curbuf->b_fnum;
17340 fp = var2fpos(&argvars[0], FALSE, &fnum);
17341 if (fp != NULL && fp->lnum <= curbuf->b_ml.ml_line_count
17342 && fnum == curbuf->b_fnum)
17344 getvvcol(curwin, fp, NULL, NULL, &vcol);
17345 ++vcol;
17348 rettv->vval.v_number = vcol;
17352 * "visualmode()" function
17354 /*ARGSUSED*/
17355 static void
17356 f_visualmode(argvars, rettv)
17357 typval_T *argvars;
17358 typval_T *rettv;
17360 #ifdef FEAT_VISUAL
17361 char_u str[2];
17363 rettv->v_type = VAR_STRING;
17364 str[0] = curbuf->b_visual_mode_eval;
17365 str[1] = NUL;
17366 rettv->vval.v_string = vim_strsave(str);
17368 /* A non-zero number or non-empty string argument: reset mode. */
17369 if (non_zero_arg(&argvars[0]))
17370 curbuf->b_visual_mode_eval = NUL;
17371 #else
17372 rettv->vval.v_number = 0; /* return anything, it won't work anyway */
17373 #endif
17377 * "winbufnr(nr)" function
17379 static void
17380 f_winbufnr(argvars, rettv)
17381 typval_T *argvars;
17382 typval_T *rettv;
17384 win_T *wp;
17386 wp = find_win_by_nr(&argvars[0], NULL);
17387 if (wp == NULL)
17388 rettv->vval.v_number = -1;
17389 else
17390 rettv->vval.v_number = wp->w_buffer->b_fnum;
17394 * "wincol()" function
17396 /*ARGSUSED*/
17397 static void
17398 f_wincol(argvars, rettv)
17399 typval_T *argvars;
17400 typval_T *rettv;
17402 validate_cursor();
17403 rettv->vval.v_number = curwin->w_wcol + 1;
17407 * "winheight(nr)" function
17409 static void
17410 f_winheight(argvars, rettv)
17411 typval_T *argvars;
17412 typval_T *rettv;
17414 win_T *wp;
17416 wp = find_win_by_nr(&argvars[0], NULL);
17417 if (wp == NULL)
17418 rettv->vval.v_number = -1;
17419 else
17420 rettv->vval.v_number = wp->w_height;
17424 * "winline()" function
17426 /*ARGSUSED*/
17427 static void
17428 f_winline(argvars, rettv)
17429 typval_T *argvars;
17430 typval_T *rettv;
17432 validate_cursor();
17433 rettv->vval.v_number = curwin->w_wrow + 1;
17437 * "winnr()" function
17439 /* ARGSUSED */
17440 static void
17441 f_winnr(argvars, rettv)
17442 typval_T *argvars;
17443 typval_T *rettv;
17445 int nr = 1;
17447 #ifdef FEAT_WINDOWS
17448 nr = get_winnr(curtab, &argvars[0]);
17449 #endif
17450 rettv->vval.v_number = nr;
17454 * "winrestcmd()" function
17456 /* ARGSUSED */
17457 static void
17458 f_winrestcmd(argvars, rettv)
17459 typval_T *argvars;
17460 typval_T *rettv;
17462 #ifdef FEAT_WINDOWS
17463 win_T *wp;
17464 int winnr = 1;
17465 garray_T ga;
17466 char_u buf[50];
17468 ga_init2(&ga, (int)sizeof(char), 70);
17469 for (wp = firstwin; wp != NULL; wp = wp->w_next)
17471 sprintf((char *)buf, "%dresize %d|", winnr, wp->w_height);
17472 ga_concat(&ga, buf);
17473 # ifdef FEAT_VERTSPLIT
17474 sprintf((char *)buf, "vert %dresize %d|", winnr, wp->w_width);
17475 ga_concat(&ga, buf);
17476 # endif
17477 ++winnr;
17479 ga_append(&ga, NUL);
17481 rettv->vval.v_string = ga.ga_data;
17482 #else
17483 rettv->vval.v_string = NULL;
17484 #endif
17485 rettv->v_type = VAR_STRING;
17489 * "winrestview()" function
17491 /* ARGSUSED */
17492 static void
17493 f_winrestview(argvars, rettv)
17494 typval_T *argvars;
17495 typval_T *rettv;
17497 dict_T *dict;
17499 if (argvars[0].v_type != VAR_DICT
17500 || (dict = argvars[0].vval.v_dict) == NULL)
17501 EMSG(_(e_invarg));
17502 else
17504 curwin->w_cursor.lnum = get_dict_number(dict, (char_u *)"lnum");
17505 curwin->w_cursor.col = get_dict_number(dict, (char_u *)"col");
17506 #ifdef FEAT_VIRTUALEDIT
17507 curwin->w_cursor.coladd = get_dict_number(dict, (char_u *)"coladd");
17508 #endif
17509 curwin->w_curswant = get_dict_number(dict, (char_u *)"curswant");
17510 curwin->w_set_curswant = FALSE;
17512 set_topline(curwin, get_dict_number(dict, (char_u *)"topline"));
17513 #ifdef FEAT_DIFF
17514 curwin->w_topfill = get_dict_number(dict, (char_u *)"topfill");
17515 #endif
17516 curwin->w_leftcol = get_dict_number(dict, (char_u *)"leftcol");
17517 curwin->w_skipcol = get_dict_number(dict, (char_u *)"skipcol");
17519 check_cursor();
17520 changed_cline_bef_curs();
17521 invalidate_botline();
17522 redraw_later(VALID);
17524 if (curwin->w_topline == 0)
17525 curwin->w_topline = 1;
17526 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
17527 curwin->w_topline = curbuf->b_ml.ml_line_count;
17528 #ifdef FEAT_DIFF
17529 check_topfill(curwin, TRUE);
17530 #endif
17535 * "winsaveview()" function
17537 /* ARGSUSED */
17538 static void
17539 f_winsaveview(argvars, rettv)
17540 typval_T *argvars;
17541 typval_T *rettv;
17543 dict_T *dict;
17545 dict = dict_alloc();
17546 if (dict == NULL)
17547 return;
17548 rettv->v_type = VAR_DICT;
17549 rettv->vval.v_dict = dict;
17550 ++dict->dv_refcount;
17552 dict_add_nr_str(dict, "lnum", (long)curwin->w_cursor.lnum, NULL);
17553 dict_add_nr_str(dict, "col", (long)curwin->w_cursor.col, NULL);
17554 #ifdef FEAT_VIRTUALEDIT
17555 dict_add_nr_str(dict, "coladd", (long)curwin->w_cursor.coladd, NULL);
17556 #endif
17557 update_curswant();
17558 dict_add_nr_str(dict, "curswant", (long)curwin->w_curswant, NULL);
17560 dict_add_nr_str(dict, "topline", (long)curwin->w_topline, NULL);
17561 #ifdef FEAT_DIFF
17562 dict_add_nr_str(dict, "topfill", (long)curwin->w_topfill, NULL);
17563 #endif
17564 dict_add_nr_str(dict, "leftcol", (long)curwin->w_leftcol, NULL);
17565 dict_add_nr_str(dict, "skipcol", (long)curwin->w_skipcol, NULL);
17569 * "winwidth(nr)" function
17571 static void
17572 f_winwidth(argvars, rettv)
17573 typval_T *argvars;
17574 typval_T *rettv;
17576 win_T *wp;
17578 wp = find_win_by_nr(&argvars[0], NULL);
17579 if (wp == NULL)
17580 rettv->vval.v_number = -1;
17581 else
17582 #ifdef FEAT_VERTSPLIT
17583 rettv->vval.v_number = wp->w_width;
17584 #else
17585 rettv->vval.v_number = Columns;
17586 #endif
17590 * "writefile()" function
17592 static void
17593 f_writefile(argvars, rettv)
17594 typval_T *argvars;
17595 typval_T *rettv;
17597 int binary = FALSE;
17598 char_u *fname;
17599 FILE *fd;
17600 listitem_T *li;
17601 char_u *s;
17602 int ret = 0;
17603 int c;
17605 if (check_restricted() || check_secure())
17606 return;
17608 if (argvars[0].v_type != VAR_LIST)
17610 EMSG2(_(e_listarg), "writefile()");
17611 return;
17613 if (argvars[0].vval.v_list == NULL)
17614 return;
17616 if (argvars[2].v_type != VAR_UNKNOWN
17617 && STRCMP(get_tv_string(&argvars[2]), "b") == 0)
17618 binary = TRUE;
17620 /* Always open the file in binary mode, library functions have a mind of
17621 * their own about CR-LF conversion. */
17622 fname = get_tv_string(&argvars[1]);
17623 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
17625 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
17626 ret = -1;
17628 else
17630 for (li = argvars[0].vval.v_list->lv_first; li != NULL;
17631 li = li->li_next)
17633 for (s = get_tv_string(&li->li_tv); *s != NUL; ++s)
17635 if (*s == '\n')
17636 c = putc(NUL, fd);
17637 else
17638 c = putc(*s, fd);
17639 if (c == EOF)
17641 ret = -1;
17642 break;
17645 if (!binary || li->li_next != NULL)
17646 if (putc('\n', fd) == EOF)
17648 ret = -1;
17649 break;
17651 if (ret < 0)
17653 EMSG(_(e_write));
17654 break;
17657 fclose(fd);
17660 rettv->vval.v_number = ret;
17664 * Translate a String variable into a position.
17665 * Returns NULL when there is an error.
17667 static pos_T *
17668 var2fpos(varp, dollar_lnum, fnum)
17669 typval_T *varp;
17670 int dollar_lnum; /* TRUE when $ is last line */
17671 int *fnum; /* set to fnum for '0, 'A, etc. */
17673 char_u *name;
17674 static pos_T pos;
17675 pos_T *pp;
17677 /* Argument can be [lnum, col, coladd]. */
17678 if (varp->v_type == VAR_LIST)
17680 list_T *l;
17681 int len;
17682 int error = FALSE;
17683 listitem_T *li;
17685 l = varp->vval.v_list;
17686 if (l == NULL)
17687 return NULL;
17689 /* Get the line number */
17690 pos.lnum = list_find_nr(l, 0L, &error);
17691 if (error || pos.lnum <= 0 || pos.lnum > curbuf->b_ml.ml_line_count)
17692 return NULL; /* invalid line number */
17694 /* Get the column number */
17695 pos.col = list_find_nr(l, 1L, &error);
17696 if (error)
17697 return NULL;
17698 len = (long)STRLEN(ml_get(pos.lnum));
17700 /* We accept "$" for the column number: last column. */
17701 li = list_find(l, 1L);
17702 if (li != NULL && li->li_tv.v_type == VAR_STRING
17703 && li->li_tv.vval.v_string != NULL
17704 && STRCMP(li->li_tv.vval.v_string, "$") == 0)
17705 pos.col = len + 1;
17707 /* Accept a position up to the NUL after the line. */
17708 if (pos.col == 0 || (int)pos.col > len + 1)
17709 return NULL; /* invalid column number */
17710 --pos.col;
17712 #ifdef FEAT_VIRTUALEDIT
17713 /* Get the virtual offset. Defaults to zero. */
17714 pos.coladd = list_find_nr(l, 2L, &error);
17715 if (error)
17716 pos.coladd = 0;
17717 #endif
17719 return &pos;
17722 name = get_tv_string_chk(varp);
17723 if (name == NULL)
17724 return NULL;
17725 if (name[0] == '.') /* cursor */
17726 return &curwin->w_cursor;
17727 #ifdef FEAT_VISUAL
17728 if (name[0] == 'v' && name[1] == NUL) /* Visual start */
17730 if (VIsual_active)
17731 return &VIsual;
17732 return &curwin->w_cursor;
17734 #endif
17735 if (name[0] == '\'') /* mark */
17737 pp = getmark_fnum(name[1], FALSE, fnum);
17738 if (pp == NULL || pp == (pos_T *)-1 || pp->lnum <= 0)
17739 return NULL;
17740 return pp;
17743 #ifdef FEAT_VIRTUALEDIT
17744 pos.coladd = 0;
17745 #endif
17747 if (name[0] == 'w' && dollar_lnum)
17749 pos.col = 0;
17750 if (name[1] == '0') /* "w0": first visible line */
17752 update_topline();
17753 pos.lnum = curwin->w_topline;
17754 return &pos;
17756 else if (name[1] == '$') /* "w$": last visible line */
17758 validate_botline();
17759 pos.lnum = curwin->w_botline - 1;
17760 return &pos;
17763 else if (name[0] == '$') /* last column or line */
17765 if (dollar_lnum)
17767 pos.lnum = curbuf->b_ml.ml_line_count;
17768 pos.col = 0;
17770 else
17772 pos.lnum = curwin->w_cursor.lnum;
17773 pos.col = (colnr_T)STRLEN(ml_get_curline());
17775 return &pos;
17777 return NULL;
17781 * Convert list in "arg" into a position and optional file number.
17782 * When "fnump" is NULL there is no file number, only 3 items.
17783 * Note that the column is passed on as-is, the caller may want to decrement
17784 * it to use 1 for the first column.
17785 * Return FAIL when conversion is not possible, doesn't check the position for
17786 * validity.
17788 static int
17789 list2fpos(arg, posp, fnump)
17790 typval_T *arg;
17791 pos_T *posp;
17792 int *fnump;
17794 list_T *l = arg->vval.v_list;
17795 long i = 0;
17796 long n;
17798 /* List must be: [fnum, lnum, col, coladd], where "fnum" is only there
17799 * when "fnump" isn't NULL and "coladd" is optional. */
17800 if (arg->v_type != VAR_LIST
17801 || l == NULL
17802 || l->lv_len < (fnump == NULL ? 2 : 3)
17803 || l->lv_len > (fnump == NULL ? 3 : 4))
17804 return FAIL;
17806 if (fnump != NULL)
17808 n = list_find_nr(l, i++, NULL); /* fnum */
17809 if (n < 0)
17810 return FAIL;
17811 if (n == 0)
17812 n = curbuf->b_fnum; /* current buffer */
17813 *fnump = n;
17816 n = list_find_nr(l, i++, NULL); /* lnum */
17817 if (n < 0)
17818 return FAIL;
17819 posp->lnum = n;
17821 n = list_find_nr(l, i++, NULL); /* col */
17822 if (n < 0)
17823 return FAIL;
17824 posp->col = n;
17826 #ifdef FEAT_VIRTUALEDIT
17827 n = list_find_nr(l, i, NULL);
17828 if (n < 0)
17829 posp->coladd = 0;
17830 else
17831 posp->coladd = n;
17832 #endif
17834 return OK;
17838 * Get the length of an environment variable name.
17839 * Advance "arg" to the first character after the name.
17840 * Return 0 for error.
17842 static int
17843 get_env_len(arg)
17844 char_u **arg;
17846 char_u *p;
17847 int len;
17849 for (p = *arg; vim_isIDc(*p); ++p)
17851 if (p == *arg) /* no name found */
17852 return 0;
17854 len = (int)(p - *arg);
17855 *arg = p;
17856 return len;
17860 * Get the length of the name of a function or internal variable.
17861 * "arg" is advanced to the first non-white character after the name.
17862 * Return 0 if something is wrong.
17864 static int
17865 get_id_len(arg)
17866 char_u **arg;
17868 char_u *p;
17869 int len;
17871 /* Find the end of the name. */
17872 for (p = *arg; eval_isnamec(*p); ++p)
17874 if (p == *arg) /* no name found */
17875 return 0;
17877 len = (int)(p - *arg);
17878 *arg = skipwhite(p);
17880 return len;
17884 * Get the length of the name of a variable or function.
17885 * Only the name is recognized, does not handle ".key" or "[idx]".
17886 * "arg" is advanced to the first non-white character after the name.
17887 * Return -1 if curly braces expansion failed.
17888 * Return 0 if something else is wrong.
17889 * If the name contains 'magic' {}'s, expand them and return the
17890 * expanded name in an allocated string via 'alias' - caller must free.
17892 static int
17893 get_name_len(arg, alias, evaluate, verbose)
17894 char_u **arg;
17895 char_u **alias;
17896 int evaluate;
17897 int verbose;
17899 int len;
17900 char_u *p;
17901 char_u *expr_start;
17902 char_u *expr_end;
17904 *alias = NULL; /* default to no alias */
17906 if ((*arg)[0] == K_SPECIAL && (*arg)[1] == KS_EXTRA
17907 && (*arg)[2] == (int)KE_SNR)
17909 /* hard coded <SNR>, already translated */
17910 *arg += 3;
17911 return get_id_len(arg) + 3;
17913 len = eval_fname_script(*arg);
17914 if (len > 0)
17916 /* literal "<SID>", "s:" or "<SNR>" */
17917 *arg += len;
17921 * Find the end of the name; check for {} construction.
17923 p = find_name_end(*arg, &expr_start, &expr_end,
17924 len > 0 ? 0 : FNE_CHECK_START);
17925 if (expr_start != NULL)
17927 char_u *temp_string;
17929 if (!evaluate)
17931 len += (int)(p - *arg);
17932 *arg = skipwhite(p);
17933 return len;
17937 * Include any <SID> etc in the expanded string:
17938 * Thus the -len here.
17940 temp_string = make_expanded_name(*arg - len, expr_start, expr_end, p);
17941 if (temp_string == NULL)
17942 return -1;
17943 *alias = temp_string;
17944 *arg = skipwhite(p);
17945 return (int)STRLEN(temp_string);
17948 len += get_id_len(arg);
17949 if (len == 0 && verbose)
17950 EMSG2(_(e_invexpr2), *arg);
17952 return len;
17956 * Find the end of a variable or function name, taking care of magic braces.
17957 * If "expr_start" is not NULL then "expr_start" and "expr_end" are set to the
17958 * start and end of the first magic braces item.
17959 * "flags" can have FNE_INCL_BR and FNE_CHECK_START.
17960 * Return a pointer to just after the name. Equal to "arg" if there is no
17961 * valid name.
17963 static char_u *
17964 find_name_end(arg, expr_start, expr_end, flags)
17965 char_u *arg;
17966 char_u **expr_start;
17967 char_u **expr_end;
17968 int flags;
17970 int mb_nest = 0;
17971 int br_nest = 0;
17972 char_u *p;
17974 if (expr_start != NULL)
17976 *expr_start = NULL;
17977 *expr_end = NULL;
17980 /* Quick check for valid starting character. */
17981 if ((flags & FNE_CHECK_START) && !eval_isnamec1(*arg) && *arg != '{')
17982 return arg;
17984 for (p = arg; *p != NUL
17985 && (eval_isnamec(*p)
17986 || *p == '{'
17987 || ((flags & FNE_INCL_BR) && (*p == '[' || *p == '.'))
17988 || mb_nest != 0
17989 || br_nest != 0); mb_ptr_adv(p))
17991 if (*p == '\'')
17993 /* skip over 'string' to avoid counting [ and ] inside it. */
17994 for (p = p + 1; *p != NUL && *p != '\''; mb_ptr_adv(p))
17996 if (*p == NUL)
17997 break;
17999 else if (*p == '"')
18001 /* skip over "str\"ing" to avoid counting [ and ] inside it. */
18002 for (p = p + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
18003 if (*p == '\\' && p[1] != NUL)
18004 ++p;
18005 if (*p == NUL)
18006 break;
18009 if (mb_nest == 0)
18011 if (*p == '[')
18012 ++br_nest;
18013 else if (*p == ']')
18014 --br_nest;
18017 if (br_nest == 0)
18019 if (*p == '{')
18021 mb_nest++;
18022 if (expr_start != NULL && *expr_start == NULL)
18023 *expr_start = p;
18025 else if (*p == '}')
18027 mb_nest--;
18028 if (expr_start != NULL && mb_nest == 0 && *expr_end == NULL)
18029 *expr_end = p;
18034 return p;
18038 * Expands out the 'magic' {}'s in a variable/function name.
18039 * Note that this can call itself recursively, to deal with
18040 * constructs like foo{bar}{baz}{bam}
18041 * The four pointer arguments point to "foo{expre}ss{ion}bar"
18042 * "in_start" ^
18043 * "expr_start" ^
18044 * "expr_end" ^
18045 * "in_end" ^
18047 * Returns a new allocated string, which the caller must free.
18048 * Returns NULL for failure.
18050 static char_u *
18051 make_expanded_name(in_start, expr_start, expr_end, in_end)
18052 char_u *in_start;
18053 char_u *expr_start;
18054 char_u *expr_end;
18055 char_u *in_end;
18057 char_u c1;
18058 char_u *retval = NULL;
18059 char_u *temp_result;
18060 char_u *nextcmd = NULL;
18062 if (expr_end == NULL || in_end == NULL)
18063 return NULL;
18064 *expr_start = NUL;
18065 *expr_end = NUL;
18066 c1 = *in_end;
18067 *in_end = NUL;
18069 temp_result = eval_to_string(expr_start + 1, &nextcmd, FALSE);
18070 if (temp_result != NULL && nextcmd == NULL)
18072 retval = alloc((unsigned)(STRLEN(temp_result) + (expr_start - in_start)
18073 + (in_end - expr_end) + 1));
18074 if (retval != NULL)
18076 STRCPY(retval, in_start);
18077 STRCAT(retval, temp_result);
18078 STRCAT(retval, expr_end + 1);
18081 vim_free(temp_result);
18083 *in_end = c1; /* put char back for error messages */
18084 *expr_start = '{';
18085 *expr_end = '}';
18087 if (retval != NULL)
18089 temp_result = find_name_end(retval, &expr_start, &expr_end, 0);
18090 if (expr_start != NULL)
18092 /* Further expansion! */
18093 temp_result = make_expanded_name(retval, expr_start,
18094 expr_end, temp_result);
18095 vim_free(retval);
18096 retval = temp_result;
18100 return retval;
18104 * Return TRUE if character "c" can be used in a variable or function name.
18105 * Does not include '{' or '}' for magic braces.
18107 static int
18108 eval_isnamec(c)
18109 int c;
18111 return (ASCII_ISALNUM(c) || c == '_' || c == ':' || c == AUTOLOAD_CHAR);
18115 * Return TRUE if character "c" can be used as the first character in a
18116 * variable or function name (excluding '{' and '}').
18118 static int
18119 eval_isnamec1(c)
18120 int c;
18122 return (ASCII_ISALPHA(c) || c == '_');
18126 * Set number v: variable to "val".
18128 void
18129 set_vim_var_nr(idx, val)
18130 int idx;
18131 long val;
18133 vimvars[idx].vv_nr = val;
18137 * Get number v: variable value.
18139 long
18140 get_vim_var_nr(idx)
18141 int idx;
18143 return vimvars[idx].vv_nr;
18147 * Get string v: variable value. Uses a static buffer, can only be used once.
18149 char_u *
18150 get_vim_var_str(idx)
18151 int idx;
18153 return get_tv_string(&vimvars[idx].vv_tv);
18157 * Get List v: variable value. Caller must take care of reference count when
18158 * needed.
18160 list_T *
18161 get_vim_var_list(idx)
18162 int idx;
18164 return vimvars[idx].vv_list;
18168 * Set v:count, v:count1 and v:prevcount.
18170 void
18171 set_vcount(count, count1)
18172 long count;
18173 long count1;
18175 vimvars[VV_PREVCOUNT].vv_nr = vimvars[VV_COUNT].vv_nr;
18176 vimvars[VV_COUNT].vv_nr = count;
18177 vimvars[VV_COUNT1].vv_nr = count1;
18181 * Set string v: variable to a copy of "val".
18183 void
18184 set_vim_var_string(idx, val, len)
18185 int idx;
18186 char_u *val;
18187 int len; /* length of "val" to use or -1 (whole string) */
18189 /* Need to do this (at least) once, since we can't initialize a union.
18190 * Will always be invoked when "v:progname" is set. */
18191 vimvars[VV_VERSION].vv_nr = VIM_VERSION_100;
18193 vim_free(vimvars[idx].vv_str);
18194 if (val == NULL)
18195 vimvars[idx].vv_str = NULL;
18196 else if (len == -1)
18197 vimvars[idx].vv_str = vim_strsave(val);
18198 else
18199 vimvars[idx].vv_str = vim_strnsave(val, len);
18203 * Set List v: variable to "val".
18205 void
18206 set_vim_var_list(idx, val)
18207 int idx;
18208 list_T *val;
18210 list_unref(vimvars[idx].vv_list);
18211 vimvars[idx].vv_list = val;
18212 if (val != NULL)
18213 ++val->lv_refcount;
18217 * Set v:register if needed.
18219 void
18220 set_reg_var(c)
18221 int c;
18223 char_u regname;
18225 if (c == 0 || c == ' ')
18226 regname = '"';
18227 else
18228 regname = c;
18229 /* Avoid free/alloc when the value is already right. */
18230 if (vimvars[VV_REG].vv_str == NULL || vimvars[VV_REG].vv_str[0] != c)
18231 set_vim_var_string(VV_REG, &regname, 1);
18235 * Get or set v:exception. If "oldval" == NULL, return the current value.
18236 * Otherwise, restore the value to "oldval" and return NULL.
18237 * Must always be called in pairs to save and restore v:exception! Does not
18238 * take care of memory allocations.
18240 char_u *
18241 v_exception(oldval)
18242 char_u *oldval;
18244 if (oldval == NULL)
18245 return vimvars[VV_EXCEPTION].vv_str;
18247 vimvars[VV_EXCEPTION].vv_str = oldval;
18248 return NULL;
18252 * Get or set v:throwpoint. If "oldval" == NULL, return the current value.
18253 * Otherwise, restore the value to "oldval" and return NULL.
18254 * Must always be called in pairs to save and restore v:throwpoint! Does not
18255 * take care of memory allocations.
18257 char_u *
18258 v_throwpoint(oldval)
18259 char_u *oldval;
18261 if (oldval == NULL)
18262 return vimvars[VV_THROWPOINT].vv_str;
18264 vimvars[VV_THROWPOINT].vv_str = oldval;
18265 return NULL;
18268 #if defined(FEAT_AUTOCMD) || defined(PROTO)
18270 * Set v:cmdarg.
18271 * If "eap" != NULL, use "eap" to generate the value and return the old value.
18272 * If "oldarg" != NULL, restore the value to "oldarg" and return NULL.
18273 * Must always be called in pairs!
18275 char_u *
18276 set_cmdarg(eap, oldarg)
18277 exarg_T *eap;
18278 char_u *oldarg;
18280 char_u *oldval;
18281 char_u *newval;
18282 unsigned len;
18284 oldval = vimvars[VV_CMDARG].vv_str;
18285 if (eap == NULL)
18287 vim_free(oldval);
18288 vimvars[VV_CMDARG].vv_str = oldarg;
18289 return NULL;
18292 if (eap->force_bin == FORCE_BIN)
18293 len = 6;
18294 else if (eap->force_bin == FORCE_NOBIN)
18295 len = 8;
18296 else
18297 len = 0;
18299 if (eap->read_edit)
18300 len += 7;
18302 if (eap->force_ff != 0)
18303 len += (unsigned)STRLEN(eap->cmd + eap->force_ff) + 6;
18304 # ifdef FEAT_MBYTE
18305 if (eap->force_enc != 0)
18306 len += (unsigned)STRLEN(eap->cmd + eap->force_enc) + 7;
18307 if (eap->bad_char != 0)
18308 len += (unsigned)STRLEN(eap->cmd + eap->bad_char) + 7;
18309 # endif
18311 newval = alloc(len + 1);
18312 if (newval == NULL)
18313 return NULL;
18315 if (eap->force_bin == FORCE_BIN)
18316 sprintf((char *)newval, " ++bin");
18317 else if (eap->force_bin == FORCE_NOBIN)
18318 sprintf((char *)newval, " ++nobin");
18319 else
18320 *newval = NUL;
18322 if (eap->read_edit)
18323 STRCAT(newval, " ++edit");
18325 if (eap->force_ff != 0)
18326 sprintf((char *)newval + STRLEN(newval), " ++ff=%s",
18327 eap->cmd + eap->force_ff);
18328 # ifdef FEAT_MBYTE
18329 if (eap->force_enc != 0)
18330 sprintf((char *)newval + STRLEN(newval), " ++enc=%s",
18331 eap->cmd + eap->force_enc);
18332 if (eap->bad_char != 0)
18333 sprintf((char *)newval + STRLEN(newval), " ++bad=%s",
18334 eap->cmd + eap->bad_char);
18335 # endif
18336 vimvars[VV_CMDARG].vv_str = newval;
18337 return oldval;
18339 #endif
18342 * Get the value of internal variable "name".
18343 * Return OK or FAIL.
18345 static int
18346 get_var_tv(name, len, rettv, verbose)
18347 char_u *name;
18348 int len; /* length of "name" */
18349 typval_T *rettv; /* NULL when only checking existence */
18350 int verbose; /* may give error message */
18352 int ret = OK;
18353 typval_T *tv = NULL;
18354 typval_T atv;
18355 dictitem_T *v;
18356 int cc;
18358 /* truncate the name, so that we can use strcmp() */
18359 cc = name[len];
18360 name[len] = NUL;
18363 * Check for "b:changedtick".
18365 if (STRCMP(name, "b:changedtick") == 0)
18367 atv.v_type = VAR_NUMBER;
18368 atv.vval.v_number = curbuf->b_changedtick;
18369 tv = &atv;
18373 * Check for user-defined variables.
18375 else
18377 v = find_var(name, NULL);
18378 if (v != NULL)
18379 tv = &v->di_tv;
18382 if (tv == NULL)
18384 if (rettv != NULL && verbose)
18385 EMSG2(_(e_undefvar), name);
18386 ret = FAIL;
18388 else if (rettv != NULL)
18389 copy_tv(tv, rettv);
18391 name[len] = cc;
18393 return ret;
18397 * Handle expr[expr], expr[expr:expr] subscript and .name lookup.
18398 * Also handle function call with Funcref variable: func(expr)
18399 * Can all be combined: dict.func(expr)[idx]['func'](expr)
18401 static int
18402 handle_subscript(arg, rettv, evaluate, verbose)
18403 char_u **arg;
18404 typval_T *rettv;
18405 int evaluate; /* do more than finding the end */
18406 int verbose; /* give error messages */
18408 int ret = OK;
18409 dict_T *selfdict = NULL;
18410 char_u *s;
18411 int len;
18412 typval_T functv;
18414 while (ret == OK
18415 && (**arg == '['
18416 || (**arg == '.' && rettv->v_type == VAR_DICT)
18417 || (**arg == '(' && rettv->v_type == VAR_FUNC))
18418 && !vim_iswhite(*(*arg - 1)))
18420 if (**arg == '(')
18422 /* need to copy the funcref so that we can clear rettv */
18423 functv = *rettv;
18424 rettv->v_type = VAR_UNKNOWN;
18426 /* Invoke the function. Recursive! */
18427 s = functv.vval.v_string;
18428 ret = get_func_tv(s, (int)STRLEN(s), rettv, arg,
18429 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
18430 &len, evaluate, selfdict);
18432 /* Clear the funcref afterwards, so that deleting it while
18433 * evaluating the arguments is possible (see test55). */
18434 clear_tv(&functv);
18436 /* Stop the expression evaluation when immediately aborting on
18437 * error, or when an interrupt occurred or an exception was thrown
18438 * but not caught. */
18439 if (aborting())
18441 if (ret == OK)
18442 clear_tv(rettv);
18443 ret = FAIL;
18445 dict_unref(selfdict);
18446 selfdict = NULL;
18448 else /* **arg == '[' || **arg == '.' */
18450 dict_unref(selfdict);
18451 if (rettv->v_type == VAR_DICT)
18453 selfdict = rettv->vval.v_dict;
18454 if (selfdict != NULL)
18455 ++selfdict->dv_refcount;
18457 else
18458 selfdict = NULL;
18459 if (eval_index(arg, rettv, evaluate, verbose) == FAIL)
18461 clear_tv(rettv);
18462 ret = FAIL;
18466 dict_unref(selfdict);
18467 return ret;
18471 * Allocate memory for a variable type-value, and make it empty (0 or NULL
18472 * value).
18474 static typval_T *
18475 alloc_tv()
18477 return (typval_T *)alloc_clear((unsigned)sizeof(typval_T));
18481 * Allocate memory for a variable type-value, and assign a string to it.
18482 * The string "s" must have been allocated, it is consumed.
18483 * Return NULL for out of memory, the variable otherwise.
18485 static typval_T *
18486 alloc_string_tv(s)
18487 char_u *s;
18489 typval_T *rettv;
18491 rettv = alloc_tv();
18492 if (rettv != NULL)
18494 rettv->v_type = VAR_STRING;
18495 rettv->vval.v_string = s;
18497 else
18498 vim_free(s);
18499 return rettv;
18503 * Free the memory for a variable type-value.
18505 void
18506 free_tv(varp)
18507 typval_T *varp;
18509 if (varp != NULL)
18511 switch (varp->v_type)
18513 case VAR_FUNC:
18514 func_unref(varp->vval.v_string);
18515 /*FALLTHROUGH*/
18516 case VAR_STRING:
18517 vim_free(varp->vval.v_string);
18518 break;
18519 case VAR_LIST:
18520 list_unref(varp->vval.v_list);
18521 break;
18522 case VAR_DICT:
18523 dict_unref(varp->vval.v_dict);
18524 break;
18525 case VAR_NUMBER:
18526 #ifdef FEAT_FLOAT
18527 case VAR_FLOAT:
18528 #endif
18529 case VAR_UNKNOWN:
18530 break;
18531 default:
18532 EMSG2(_(e_intern2), "free_tv()");
18533 break;
18535 vim_free(varp);
18540 * Free the memory for a variable value and set the value to NULL or 0.
18542 void
18543 clear_tv(varp)
18544 typval_T *varp;
18546 if (varp != NULL)
18548 switch (varp->v_type)
18550 case VAR_FUNC:
18551 func_unref(varp->vval.v_string);
18552 /*FALLTHROUGH*/
18553 case VAR_STRING:
18554 vim_free(varp->vval.v_string);
18555 varp->vval.v_string = NULL;
18556 break;
18557 case VAR_LIST:
18558 list_unref(varp->vval.v_list);
18559 varp->vval.v_list = NULL;
18560 break;
18561 case VAR_DICT:
18562 dict_unref(varp->vval.v_dict);
18563 varp->vval.v_dict = NULL;
18564 break;
18565 case VAR_NUMBER:
18566 varp->vval.v_number = 0;
18567 break;
18568 #ifdef FEAT_FLOAT
18569 case VAR_FLOAT:
18570 varp->vval.v_float = 0.0;
18571 break;
18572 #endif
18573 case VAR_UNKNOWN:
18574 break;
18575 default:
18576 EMSG2(_(e_intern2), "clear_tv()");
18578 varp->v_lock = 0;
18583 * Set the value of a variable to NULL without freeing items.
18585 static void
18586 init_tv(varp)
18587 typval_T *varp;
18589 if (varp != NULL)
18590 vim_memset(varp, 0, sizeof(typval_T));
18594 * Get the number value of a variable.
18595 * If it is a String variable, uses vim_str2nr().
18596 * For incompatible types, return 0.
18597 * get_tv_number_chk() is similar to get_tv_number(), but informs the
18598 * caller of incompatible types: it sets *denote to TRUE if "denote"
18599 * is not NULL or returns -1 otherwise.
18601 static long
18602 get_tv_number(varp)
18603 typval_T *varp;
18605 int error = FALSE;
18607 return get_tv_number_chk(varp, &error); /* return 0L on error */
18610 long
18611 get_tv_number_chk(varp, denote)
18612 typval_T *varp;
18613 int *denote;
18615 long n = 0L;
18617 switch (varp->v_type)
18619 case VAR_NUMBER:
18620 return (long)(varp->vval.v_number);
18621 #ifdef FEAT_FLOAT
18622 case VAR_FLOAT:
18623 EMSG(_("E805: Using a Float as a Number"));
18624 break;
18625 #endif
18626 case VAR_FUNC:
18627 EMSG(_("E703: Using a Funcref as a Number"));
18628 break;
18629 case VAR_STRING:
18630 if (varp->vval.v_string != NULL)
18631 vim_str2nr(varp->vval.v_string, NULL, NULL,
18632 TRUE, TRUE, &n, NULL);
18633 return n;
18634 case VAR_LIST:
18635 EMSG(_("E745: Using a List as a Number"));
18636 break;
18637 case VAR_DICT:
18638 EMSG(_("E728: Using a Dictionary as a Number"));
18639 break;
18640 default:
18641 EMSG2(_(e_intern2), "get_tv_number()");
18642 break;
18644 if (denote == NULL) /* useful for values that must be unsigned */
18645 n = -1;
18646 else
18647 *denote = TRUE;
18648 return n;
18652 * Get the lnum from the first argument.
18653 * Also accepts ".", "$", etc., but that only works for the current buffer.
18654 * Returns -1 on error.
18656 static linenr_T
18657 get_tv_lnum(argvars)
18658 typval_T *argvars;
18660 typval_T rettv;
18661 linenr_T lnum;
18663 lnum = get_tv_number_chk(&argvars[0], NULL);
18664 if (lnum == 0) /* no valid number, try using line() */
18666 rettv.v_type = VAR_NUMBER;
18667 f_line(argvars, &rettv);
18668 lnum = rettv.vval.v_number;
18669 clear_tv(&rettv);
18671 return lnum;
18675 * Get the lnum from the first argument.
18676 * Also accepts "$", then "buf" is used.
18677 * Returns 0 on error.
18679 static linenr_T
18680 get_tv_lnum_buf(argvars, buf)
18681 typval_T *argvars;
18682 buf_T *buf;
18684 if (argvars[0].v_type == VAR_STRING
18685 && argvars[0].vval.v_string != NULL
18686 && argvars[0].vval.v_string[0] == '$'
18687 && buf != NULL)
18688 return buf->b_ml.ml_line_count;
18689 return get_tv_number_chk(&argvars[0], NULL);
18693 * Get the string value of a variable.
18694 * If it is a Number variable, the number is converted into a string.
18695 * get_tv_string() uses a single, static buffer. YOU CAN ONLY USE IT ONCE!
18696 * get_tv_string_buf() uses a given buffer.
18697 * If the String variable has never been set, return an empty string.
18698 * Never returns NULL;
18699 * get_tv_string_chk() and get_tv_string_buf_chk() are similar, but return
18700 * NULL on error.
18702 static char_u *
18703 get_tv_string(varp)
18704 typval_T *varp;
18706 static char_u mybuf[NUMBUFLEN];
18708 return get_tv_string_buf(varp, mybuf);
18711 static char_u *
18712 get_tv_string_buf(varp, buf)
18713 typval_T *varp;
18714 char_u *buf;
18716 char_u *res = get_tv_string_buf_chk(varp, buf);
18718 return res != NULL ? res : (char_u *)"";
18721 char_u *
18722 get_tv_string_chk(varp)
18723 typval_T *varp;
18725 static char_u mybuf[NUMBUFLEN];
18727 return get_tv_string_buf_chk(varp, mybuf);
18730 static char_u *
18731 get_tv_string_buf_chk(varp, buf)
18732 typval_T *varp;
18733 char_u *buf;
18735 switch (varp->v_type)
18737 case VAR_NUMBER:
18738 sprintf((char *)buf, "%ld", (long)varp->vval.v_number);
18739 return buf;
18740 case VAR_FUNC:
18741 EMSG(_("E729: using Funcref as a String"));
18742 break;
18743 case VAR_LIST:
18744 EMSG(_("E730: using List as a String"));
18745 break;
18746 case VAR_DICT:
18747 EMSG(_("E731: using Dictionary as a String"));
18748 break;
18749 #ifdef FEAT_FLOAT
18750 case VAR_FLOAT:
18751 EMSG(_("E806: using Float as a String"));
18752 break;
18753 #endif
18754 case VAR_STRING:
18755 if (varp->vval.v_string != NULL)
18756 return varp->vval.v_string;
18757 return (char_u *)"";
18758 default:
18759 EMSG2(_(e_intern2), "get_tv_string_buf()");
18760 break;
18762 return NULL;
18766 * Find variable "name" in the list of variables.
18767 * Return a pointer to it if found, NULL if not found.
18768 * Careful: "a:0" variables don't have a name.
18769 * When "htp" is not NULL we are writing to the variable, set "htp" to the
18770 * hashtab_T used.
18772 static dictitem_T *
18773 find_var(name, htp)
18774 char_u *name;
18775 hashtab_T **htp;
18777 char_u *varname;
18778 hashtab_T *ht;
18780 ht = find_var_ht(name, &varname);
18781 if (htp != NULL)
18782 *htp = ht;
18783 if (ht == NULL)
18784 return NULL;
18785 return find_var_in_ht(ht, varname, htp != NULL);
18789 * Find variable "varname" in hashtab "ht".
18790 * Returns NULL if not found.
18792 static dictitem_T *
18793 find_var_in_ht(ht, varname, writing)
18794 hashtab_T *ht;
18795 char_u *varname;
18796 int writing;
18798 hashitem_T *hi;
18800 if (*varname == NUL)
18802 /* Must be something like "s:", otherwise "ht" would be NULL. */
18803 switch (varname[-2])
18805 case 's': return &SCRIPT_SV(current_SID).sv_var;
18806 case 'g': return &globvars_var;
18807 case 'v': return &vimvars_var;
18808 case 'b': return &curbuf->b_bufvar;
18809 case 'w': return &curwin->w_winvar;
18810 #ifdef FEAT_WINDOWS
18811 case 't': return &curtab->tp_winvar;
18812 #endif
18813 case 'l': return current_funccal == NULL
18814 ? NULL : &current_funccal->l_vars_var;
18815 case 'a': return current_funccal == NULL
18816 ? NULL : &current_funccal->l_avars_var;
18818 return NULL;
18821 hi = hash_find(ht, varname);
18822 if (HASHITEM_EMPTY(hi))
18824 /* For global variables we may try auto-loading the script. If it
18825 * worked find the variable again. Don't auto-load a script if it was
18826 * loaded already, otherwise it would be loaded every time when
18827 * checking if a function name is a Funcref variable. */
18828 if (ht == &globvarht && !writing
18829 && script_autoload(varname, FALSE) && !aborting())
18830 hi = hash_find(ht, varname);
18831 if (HASHITEM_EMPTY(hi))
18832 return NULL;
18834 return HI2DI(hi);
18838 * Find the hashtab used for a variable name.
18839 * Set "varname" to the start of name without ':'.
18841 static hashtab_T *
18842 find_var_ht(name, varname)
18843 char_u *name;
18844 char_u **varname;
18846 hashitem_T *hi;
18848 if (name[1] != ':')
18850 /* The name must not start with a colon or #. */
18851 if (name[0] == ':' || name[0] == AUTOLOAD_CHAR)
18852 return NULL;
18853 *varname = name;
18855 /* "version" is "v:version" in all scopes */
18856 hi = hash_find(&compat_hashtab, name);
18857 if (!HASHITEM_EMPTY(hi))
18858 return &compat_hashtab;
18860 if (current_funccal == NULL)
18861 return &globvarht; /* global variable */
18862 return &current_funccal->l_vars.dv_hashtab; /* l: variable */
18864 *varname = name + 2;
18865 if (*name == 'g') /* global variable */
18866 return &globvarht;
18867 /* There must be no ':' or '#' in the rest of the name, unless g: is used
18869 if (vim_strchr(name + 2, ':') != NULL
18870 || vim_strchr(name + 2, AUTOLOAD_CHAR) != NULL)
18871 return NULL;
18872 if (*name == 'b') /* buffer variable */
18873 return &curbuf->b_vars.dv_hashtab;
18874 if (*name == 'w') /* window variable */
18875 return &curwin->w_vars.dv_hashtab;
18876 #ifdef FEAT_WINDOWS
18877 if (*name == 't') /* tab page variable */
18878 return &curtab->tp_vars.dv_hashtab;
18879 #endif
18880 if (*name == 'v') /* v: variable */
18881 return &vimvarht;
18882 if (*name == 'a' && current_funccal != NULL) /* function argument */
18883 return &current_funccal->l_avars.dv_hashtab;
18884 if (*name == 'l' && current_funccal != NULL) /* local function variable */
18885 return &current_funccal->l_vars.dv_hashtab;
18886 if (*name == 's' /* script variable */
18887 && current_SID > 0 && current_SID <= ga_scripts.ga_len)
18888 return &SCRIPT_VARS(current_SID);
18889 return NULL;
18893 * Get the string value of a (global/local) variable.
18894 * Returns NULL when it doesn't exist.
18896 char_u *
18897 get_var_value(name)
18898 char_u *name;
18900 dictitem_T *v;
18902 v = find_var(name, NULL);
18903 if (v == NULL)
18904 return NULL;
18905 return get_tv_string(&v->di_tv);
18909 * Allocate a new hashtab for a sourced script. It will be used while
18910 * sourcing this script and when executing functions defined in the script.
18912 void
18913 new_script_vars(id)
18914 scid_T id;
18916 int i;
18917 hashtab_T *ht;
18918 scriptvar_T *sv;
18920 if (ga_grow(&ga_scripts, (int)(id - ga_scripts.ga_len)) == OK)
18922 /* Re-allocating ga_data means that an ht_array pointing to
18923 * ht_smallarray becomes invalid. We can recognize this: ht_mask is
18924 * at its init value. Also reset "v_dict", it's always the same. */
18925 for (i = 1; i <= ga_scripts.ga_len; ++i)
18927 ht = &SCRIPT_VARS(i);
18928 if (ht->ht_mask == HT_INIT_SIZE - 1)
18929 ht->ht_array = ht->ht_smallarray;
18930 sv = &SCRIPT_SV(i);
18931 sv->sv_var.di_tv.vval.v_dict = &sv->sv_dict;
18934 while (ga_scripts.ga_len < id)
18936 sv = &SCRIPT_SV(ga_scripts.ga_len + 1);
18937 init_var_dict(&sv->sv_dict, &sv->sv_var);
18938 ++ga_scripts.ga_len;
18944 * Initialize dictionary "dict" as a scope and set variable "dict_var" to
18945 * point to it.
18947 void
18948 init_var_dict(dict, dict_var)
18949 dict_T *dict;
18950 dictitem_T *dict_var;
18952 hash_init(&dict->dv_hashtab);
18953 dict->dv_refcount = 99999;
18954 dict_var->di_tv.vval.v_dict = dict;
18955 dict_var->di_tv.v_type = VAR_DICT;
18956 dict_var->di_tv.v_lock = VAR_FIXED;
18957 dict_var->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
18958 dict_var->di_key[0] = NUL;
18962 * Clean up a list of internal variables.
18963 * Frees all allocated variables and the value they contain.
18964 * Clears hashtab "ht", does not free it.
18966 void
18967 vars_clear(ht)
18968 hashtab_T *ht;
18970 vars_clear_ext(ht, TRUE);
18974 * Like vars_clear(), but only free the value if "free_val" is TRUE.
18976 static void
18977 vars_clear_ext(ht, free_val)
18978 hashtab_T *ht;
18979 int free_val;
18981 int todo;
18982 hashitem_T *hi;
18983 dictitem_T *v;
18985 hash_lock(ht);
18986 todo = (int)ht->ht_used;
18987 for (hi = ht->ht_array; todo > 0; ++hi)
18989 if (!HASHITEM_EMPTY(hi))
18991 --todo;
18993 /* Free the variable. Don't remove it from the hashtab,
18994 * ht_array might change then. hash_clear() takes care of it
18995 * later. */
18996 v = HI2DI(hi);
18997 if (free_val)
18998 clear_tv(&v->di_tv);
18999 if ((v->di_flags & DI_FLAGS_FIX) == 0)
19000 vim_free(v);
19003 hash_clear(ht);
19004 ht->ht_used = 0;
19008 * Delete a variable from hashtab "ht" at item "hi".
19009 * Clear the variable value and free the dictitem.
19011 static void
19012 delete_var(ht, hi)
19013 hashtab_T *ht;
19014 hashitem_T *hi;
19016 dictitem_T *di = HI2DI(hi);
19018 hash_remove(ht, hi);
19019 clear_tv(&di->di_tv);
19020 vim_free(di);
19024 * List the value of one internal variable.
19026 static void
19027 list_one_var(v, prefix, first)
19028 dictitem_T *v;
19029 char_u *prefix;
19030 int *first;
19032 char_u *tofree;
19033 char_u *s;
19034 char_u numbuf[NUMBUFLEN];
19036 s = echo_string(&v->di_tv, &tofree, numbuf, ++current_copyID);
19037 list_one_var_a(prefix, v->di_key, v->di_tv.v_type,
19038 s == NULL ? (char_u *)"" : s, first);
19039 vim_free(tofree);
19042 static void
19043 list_one_var_a(prefix, name, type, string, first)
19044 char_u *prefix;
19045 char_u *name;
19046 int type;
19047 char_u *string;
19048 int *first; /* when TRUE clear rest of screen and set to FALSE */
19050 /* don't use msg() or msg_attr() to avoid overwriting "v:statusmsg" */
19051 msg_start();
19052 msg_puts(prefix);
19053 if (name != NULL) /* "a:" vars don't have a name stored */
19054 msg_puts(name);
19055 msg_putchar(' ');
19056 msg_advance(22);
19057 if (type == VAR_NUMBER)
19058 msg_putchar('#');
19059 else if (type == VAR_FUNC)
19060 msg_putchar('*');
19061 else if (type == VAR_LIST)
19063 msg_putchar('[');
19064 if (*string == '[')
19065 ++string;
19067 else if (type == VAR_DICT)
19069 msg_putchar('{');
19070 if (*string == '{')
19071 ++string;
19073 else
19074 msg_putchar(' ');
19076 msg_outtrans(string);
19078 if (type == VAR_FUNC)
19079 msg_puts((char_u *)"()");
19080 if (*first)
19082 msg_clr_eos();
19083 *first = FALSE;
19088 * Set variable "name" to value in "tv".
19089 * If the variable already exists, the value is updated.
19090 * Otherwise the variable is created.
19092 static void
19093 set_var(name, tv, copy)
19094 char_u *name;
19095 typval_T *tv;
19096 int copy; /* make copy of value in "tv" */
19098 dictitem_T *v;
19099 char_u *varname;
19100 hashtab_T *ht;
19101 char_u *p;
19103 if (tv->v_type == VAR_FUNC)
19105 if (!(vim_strchr((char_u *)"wbs", name[0]) != NULL && name[1] == ':')
19106 && !ASCII_ISUPPER((name[0] != NUL && name[1] == ':')
19107 ? name[2] : name[0]))
19109 EMSG2(_("E704: Funcref variable name must start with a capital: %s"), name);
19110 return;
19112 if (function_exists(name))
19114 EMSG2(_("E705: Variable name conflicts with existing function: %s"),
19115 name);
19116 return;
19120 ht = find_var_ht(name, &varname);
19121 if (ht == NULL || *varname == NUL)
19123 EMSG2(_(e_illvar), name);
19124 return;
19127 v = find_var_in_ht(ht, varname, TRUE);
19128 if (v != NULL)
19130 /* existing variable, need to clear the value */
19131 if (var_check_ro(v->di_flags, name)
19132 || tv_check_lock(v->di_tv.v_lock, name))
19133 return;
19134 if (v->di_tv.v_type != tv->v_type
19135 && !((v->di_tv.v_type == VAR_STRING
19136 || v->di_tv.v_type == VAR_NUMBER)
19137 && (tv->v_type == VAR_STRING
19138 || tv->v_type == VAR_NUMBER))
19139 #ifdef FEAT_FLOAT
19140 && !((v->di_tv.v_type == VAR_NUMBER
19141 || v->di_tv.v_type == VAR_FLOAT)
19142 && (tv->v_type == VAR_NUMBER
19143 || tv->v_type == VAR_FLOAT))
19144 #endif
19147 EMSG2(_("E706: Variable type mismatch for: %s"), name);
19148 return;
19152 * Handle setting internal v: variables separately: we don't change
19153 * the type.
19155 if (ht == &vimvarht)
19157 if (v->di_tv.v_type == VAR_STRING)
19159 vim_free(v->di_tv.vval.v_string);
19160 if (copy || tv->v_type != VAR_STRING)
19161 v->di_tv.vval.v_string = vim_strsave(get_tv_string(tv));
19162 else
19164 /* Take over the string to avoid an extra alloc/free. */
19165 v->di_tv.vval.v_string = tv->vval.v_string;
19166 tv->vval.v_string = NULL;
19169 else if (v->di_tv.v_type != VAR_NUMBER)
19170 EMSG2(_(e_intern2), "set_var()");
19171 else
19173 v->di_tv.vval.v_number = get_tv_number(tv);
19174 if (STRCMP(varname, "searchforward") == 0)
19175 set_search_direction(v->di_tv.vval.v_number ? '/' : '?');
19177 return;
19180 clear_tv(&v->di_tv);
19182 else /* add a new variable */
19184 /* Can't add "v:" variable. */
19185 if (ht == &vimvarht)
19187 EMSG2(_(e_illvar), name);
19188 return;
19191 /* Make sure the variable name is valid. */
19192 for (p = varname; *p != NUL; ++p)
19193 if (!eval_isnamec1(*p) && (p == varname || !VIM_ISDIGIT(*p))
19194 && *p != AUTOLOAD_CHAR)
19196 EMSG2(_(e_illvar), varname);
19197 return;
19200 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
19201 + STRLEN(varname)));
19202 if (v == NULL)
19203 return;
19204 STRCPY(v->di_key, varname);
19205 if (hash_add(ht, DI2HIKEY(v)) == FAIL)
19207 vim_free(v);
19208 return;
19210 v->di_flags = 0;
19213 if (copy || tv->v_type == VAR_NUMBER || tv->v_type == VAR_FLOAT)
19214 copy_tv(tv, &v->di_tv);
19215 else
19217 v->di_tv = *tv;
19218 v->di_tv.v_lock = 0;
19219 init_tv(tv);
19224 * Return TRUE if di_flags "flags" indicates variable "name" is read-only.
19225 * Also give an error message.
19227 static int
19228 var_check_ro(flags, name)
19229 int flags;
19230 char_u *name;
19232 if (flags & DI_FLAGS_RO)
19234 EMSG2(_(e_readonlyvar), name);
19235 return TRUE;
19237 if ((flags & DI_FLAGS_RO_SBX) && sandbox)
19239 EMSG2(_(e_readonlysbx), name);
19240 return TRUE;
19242 return FALSE;
19246 * Return TRUE if di_flags "flags" indicates variable "name" is fixed.
19247 * Also give an error message.
19249 static int
19250 var_check_fixed(flags, name)
19251 int flags;
19252 char_u *name;
19254 if (flags & DI_FLAGS_FIX)
19256 EMSG2(_("E795: Cannot delete variable %s"), name);
19257 return TRUE;
19259 return FALSE;
19263 * Return TRUE if typeval "tv" is set to be locked (immutable).
19264 * Also give an error message, using "name".
19266 static int
19267 tv_check_lock(lock, name)
19268 int lock;
19269 char_u *name;
19271 if (lock & VAR_LOCKED)
19273 EMSG2(_("E741: Value is locked: %s"),
19274 name == NULL ? (char_u *)_("Unknown") : name);
19275 return TRUE;
19277 if (lock & VAR_FIXED)
19279 EMSG2(_("E742: Cannot change value of %s"),
19280 name == NULL ? (char_u *)_("Unknown") : name);
19281 return TRUE;
19283 return FALSE;
19287 * Copy the values from typval_T "from" to typval_T "to".
19288 * When needed allocates string or increases reference count.
19289 * Does not make a copy of a list or dict but copies the reference!
19291 static void
19292 copy_tv(from, to)
19293 typval_T *from;
19294 typval_T *to;
19296 to->v_type = from->v_type;
19297 to->v_lock = 0;
19298 switch (from->v_type)
19300 case VAR_NUMBER:
19301 to->vval.v_number = from->vval.v_number;
19302 break;
19303 #ifdef FEAT_FLOAT
19304 case VAR_FLOAT:
19305 to->vval.v_float = from->vval.v_float;
19306 break;
19307 #endif
19308 case VAR_STRING:
19309 case VAR_FUNC:
19310 if (from->vval.v_string == NULL)
19311 to->vval.v_string = NULL;
19312 else
19314 to->vval.v_string = vim_strsave(from->vval.v_string);
19315 if (from->v_type == VAR_FUNC)
19316 func_ref(to->vval.v_string);
19318 break;
19319 case VAR_LIST:
19320 if (from->vval.v_list == NULL)
19321 to->vval.v_list = NULL;
19322 else
19324 to->vval.v_list = from->vval.v_list;
19325 ++to->vval.v_list->lv_refcount;
19327 break;
19328 case VAR_DICT:
19329 if (from->vval.v_dict == NULL)
19330 to->vval.v_dict = NULL;
19331 else
19333 to->vval.v_dict = from->vval.v_dict;
19334 ++to->vval.v_dict->dv_refcount;
19336 break;
19337 default:
19338 EMSG2(_(e_intern2), "copy_tv()");
19339 break;
19344 * Make a copy of an item.
19345 * Lists and Dictionaries are also copied. A deep copy if "deep" is set.
19346 * For deepcopy() "copyID" is zero for a full copy or the ID for when a
19347 * reference to an already copied list/dict can be used.
19348 * Returns FAIL or OK.
19350 static int
19351 item_copy(from, to, deep, copyID)
19352 typval_T *from;
19353 typval_T *to;
19354 int deep;
19355 int copyID;
19357 static int recurse = 0;
19358 int ret = OK;
19360 if (recurse >= DICT_MAXNEST)
19362 EMSG(_("E698: variable nested too deep for making a copy"));
19363 return FAIL;
19365 ++recurse;
19367 switch (from->v_type)
19369 case VAR_NUMBER:
19370 #ifdef FEAT_FLOAT
19371 case VAR_FLOAT:
19372 #endif
19373 case VAR_STRING:
19374 case VAR_FUNC:
19375 copy_tv(from, to);
19376 break;
19377 case VAR_LIST:
19378 to->v_type = VAR_LIST;
19379 to->v_lock = 0;
19380 if (from->vval.v_list == NULL)
19381 to->vval.v_list = NULL;
19382 else if (copyID != 0 && from->vval.v_list->lv_copyID == copyID)
19384 /* use the copy made earlier */
19385 to->vval.v_list = from->vval.v_list->lv_copylist;
19386 ++to->vval.v_list->lv_refcount;
19388 else
19389 to->vval.v_list = list_copy(from->vval.v_list, deep, copyID);
19390 if (to->vval.v_list == NULL)
19391 ret = FAIL;
19392 break;
19393 case VAR_DICT:
19394 to->v_type = VAR_DICT;
19395 to->v_lock = 0;
19396 if (from->vval.v_dict == NULL)
19397 to->vval.v_dict = NULL;
19398 else if (copyID != 0 && from->vval.v_dict->dv_copyID == copyID)
19400 /* use the copy made earlier */
19401 to->vval.v_dict = from->vval.v_dict->dv_copydict;
19402 ++to->vval.v_dict->dv_refcount;
19404 else
19405 to->vval.v_dict = dict_copy(from->vval.v_dict, deep, copyID);
19406 if (to->vval.v_dict == NULL)
19407 ret = FAIL;
19408 break;
19409 default:
19410 EMSG2(_(e_intern2), "item_copy()");
19411 ret = FAIL;
19413 --recurse;
19414 return ret;
19418 * ":echo expr1 ..." print each argument separated with a space, add a
19419 * newline at the end.
19420 * ":echon expr1 ..." print each argument plain.
19422 void
19423 ex_echo(eap)
19424 exarg_T *eap;
19426 char_u *arg = eap->arg;
19427 typval_T rettv;
19428 char_u *tofree;
19429 char_u *p;
19430 int needclr = TRUE;
19431 int atstart = TRUE;
19432 char_u numbuf[NUMBUFLEN];
19434 if (eap->skip)
19435 ++emsg_skip;
19436 while (*arg != NUL && *arg != '|' && *arg != '\n' && !got_int)
19438 /* If eval1() causes an error message the text from the command may
19439 * still need to be cleared. E.g., "echo 22,44". */
19440 need_clr_eos = needclr;
19442 p = arg;
19443 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
19446 * Report the invalid expression unless the expression evaluation
19447 * has been cancelled due to an aborting error, an interrupt, or an
19448 * exception.
19450 if (!aborting())
19451 EMSG2(_(e_invexpr2), p);
19452 need_clr_eos = FALSE;
19453 break;
19455 need_clr_eos = FALSE;
19457 if (!eap->skip)
19459 if (atstart)
19461 atstart = FALSE;
19462 /* Call msg_start() after eval1(), evaluating the expression
19463 * may cause a message to appear. */
19464 if (eap->cmdidx == CMD_echo)
19465 msg_start();
19467 else if (eap->cmdidx == CMD_echo)
19468 msg_puts_attr((char_u *)" ", echo_attr);
19469 p = echo_string(&rettv, &tofree, numbuf, ++current_copyID);
19470 if (p != NULL)
19471 for ( ; *p != NUL && !got_int; ++p)
19473 if (*p == '\n' || *p == '\r' || *p == TAB)
19475 if (*p != TAB && needclr)
19477 /* remove any text still there from the command */
19478 msg_clr_eos();
19479 needclr = FALSE;
19481 msg_putchar_attr(*p, echo_attr);
19483 else
19485 #ifdef FEAT_MBYTE
19486 if (has_mbyte)
19488 int i = (*mb_ptr2len)(p);
19490 (void)msg_outtrans_len_attr(p, i, echo_attr);
19491 p += i - 1;
19493 else
19494 #endif
19495 (void)msg_outtrans_len_attr(p, 1, echo_attr);
19498 vim_free(tofree);
19500 clear_tv(&rettv);
19501 arg = skipwhite(arg);
19503 eap->nextcmd = check_nextcmd(arg);
19505 if (eap->skip)
19506 --emsg_skip;
19507 else
19509 /* remove text that may still be there from the command */
19510 if (needclr)
19511 msg_clr_eos();
19512 if (eap->cmdidx == CMD_echo)
19513 msg_end();
19518 * ":echohl {name}".
19520 void
19521 ex_echohl(eap)
19522 exarg_T *eap;
19524 int id;
19526 id = syn_name2id(eap->arg);
19527 if (id == 0)
19528 echo_attr = 0;
19529 else
19530 echo_attr = syn_id2attr(id);
19534 * ":execute expr1 ..." execute the result of an expression.
19535 * ":echomsg expr1 ..." Print a message
19536 * ":echoerr expr1 ..." Print an error
19537 * Each gets spaces around each argument and a newline at the end for
19538 * echo commands
19540 void
19541 ex_execute(eap)
19542 exarg_T *eap;
19544 char_u *arg = eap->arg;
19545 typval_T rettv;
19546 int ret = OK;
19547 char_u *p;
19548 garray_T ga;
19549 int len;
19550 int save_did_emsg;
19552 ga_init2(&ga, 1, 80);
19554 if (eap->skip)
19555 ++emsg_skip;
19556 while (*arg != NUL && *arg != '|' && *arg != '\n')
19558 p = arg;
19559 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
19562 * Report the invalid expression unless the expression evaluation
19563 * has been cancelled due to an aborting error, an interrupt, or an
19564 * exception.
19566 if (!aborting())
19567 EMSG2(_(e_invexpr2), p);
19568 ret = FAIL;
19569 break;
19572 if (!eap->skip)
19574 p = get_tv_string(&rettv);
19575 len = (int)STRLEN(p);
19576 if (ga_grow(&ga, len + 2) == FAIL)
19578 clear_tv(&rettv);
19579 ret = FAIL;
19580 break;
19582 if (ga.ga_len)
19583 ((char_u *)(ga.ga_data))[ga.ga_len++] = ' ';
19584 STRCPY((char_u *)(ga.ga_data) + ga.ga_len, p);
19585 ga.ga_len += len;
19588 clear_tv(&rettv);
19589 arg = skipwhite(arg);
19592 if (ret != FAIL && ga.ga_data != NULL)
19594 if (eap->cmdidx == CMD_echomsg)
19596 MSG_ATTR(ga.ga_data, echo_attr);
19597 out_flush();
19599 else if (eap->cmdidx == CMD_echoerr)
19601 /* We don't want to abort following commands, restore did_emsg. */
19602 save_did_emsg = did_emsg;
19603 EMSG((char_u *)ga.ga_data);
19604 if (!force_abort)
19605 did_emsg = save_did_emsg;
19607 else if (eap->cmdidx == CMD_execute)
19608 do_cmdline((char_u *)ga.ga_data,
19609 eap->getline, eap->cookie, DOCMD_NOWAIT|DOCMD_VERBOSE);
19612 ga_clear(&ga);
19614 if (eap->skip)
19615 --emsg_skip;
19617 eap->nextcmd = check_nextcmd(arg);
19621 * Skip over the name of an option: "&option", "&g:option" or "&l:option".
19622 * "arg" points to the "&" or '+' when called, to "option" when returning.
19623 * Returns NULL when no option name found. Otherwise pointer to the char
19624 * after the option name.
19626 static char_u *
19627 find_option_end(arg, opt_flags)
19628 char_u **arg;
19629 int *opt_flags;
19631 char_u *p = *arg;
19633 ++p;
19634 if (*p == 'g' && p[1] == ':')
19636 *opt_flags = OPT_GLOBAL;
19637 p += 2;
19639 else if (*p == 'l' && p[1] == ':')
19641 *opt_flags = OPT_LOCAL;
19642 p += 2;
19644 else
19645 *opt_flags = 0;
19647 if (!ASCII_ISALPHA(*p))
19648 return NULL;
19649 *arg = p;
19651 if (p[0] == 't' && p[1] == '_' && p[2] != NUL && p[3] != NUL)
19652 p += 4; /* termcap option */
19653 else
19654 while (ASCII_ISALPHA(*p))
19655 ++p;
19656 return p;
19660 * ":function"
19662 void
19663 ex_function(eap)
19664 exarg_T *eap;
19666 char_u *theline;
19667 int j;
19668 int c;
19669 int saved_did_emsg;
19670 char_u *name = NULL;
19671 char_u *p;
19672 char_u *arg;
19673 char_u *line_arg = NULL;
19674 garray_T newargs;
19675 garray_T newlines;
19676 int varargs = FALSE;
19677 int mustend = FALSE;
19678 int flags = 0;
19679 ufunc_T *fp;
19680 int indent;
19681 int nesting;
19682 char_u *skip_until = NULL;
19683 dictitem_T *v;
19684 funcdict_T fudi;
19685 static int func_nr = 0; /* number for nameless function */
19686 int paren;
19687 hashtab_T *ht;
19688 int todo;
19689 hashitem_T *hi;
19690 int sourcing_lnum_off;
19693 * ":function" without argument: list functions.
19695 if (ends_excmd(*eap->arg))
19697 if (!eap->skip)
19699 todo = (int)func_hashtab.ht_used;
19700 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
19702 if (!HASHITEM_EMPTY(hi))
19704 --todo;
19705 fp = HI2UF(hi);
19706 if (!isdigit(*fp->uf_name))
19707 list_func_head(fp, FALSE);
19711 eap->nextcmd = check_nextcmd(eap->arg);
19712 return;
19716 * ":function /pat": list functions matching pattern.
19718 if (*eap->arg == '/')
19720 p = skip_regexp(eap->arg + 1, '/', TRUE, NULL);
19721 if (!eap->skip)
19723 regmatch_T regmatch;
19725 c = *p;
19726 *p = NUL;
19727 regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC);
19728 *p = c;
19729 if (regmatch.regprog != NULL)
19731 regmatch.rm_ic = p_ic;
19733 todo = (int)func_hashtab.ht_used;
19734 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
19736 if (!HASHITEM_EMPTY(hi))
19738 --todo;
19739 fp = HI2UF(hi);
19740 if (!isdigit(*fp->uf_name)
19741 && vim_regexec(&regmatch, fp->uf_name, 0))
19742 list_func_head(fp, FALSE);
19747 if (*p == '/')
19748 ++p;
19749 eap->nextcmd = check_nextcmd(p);
19750 return;
19754 * Get the function name. There are these situations:
19755 * func normal function name
19756 * "name" == func, "fudi.fd_dict" == NULL
19757 * dict.func new dictionary entry
19758 * "name" == NULL, "fudi.fd_dict" set,
19759 * "fudi.fd_di" == NULL, "fudi.fd_newkey" == func
19760 * dict.func existing dict entry with a Funcref
19761 * "name" == func, "fudi.fd_dict" set,
19762 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
19763 * dict.func existing dict entry that's not a Funcref
19764 * "name" == NULL, "fudi.fd_dict" set,
19765 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
19767 p = eap->arg;
19768 name = trans_function_name(&p, eap->skip, 0, &fudi);
19769 paren = (vim_strchr(p, '(') != NULL);
19770 if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip)
19773 * Return on an invalid expression in braces, unless the expression
19774 * evaluation has been cancelled due to an aborting error, an
19775 * interrupt, or an exception.
19777 if (!aborting())
19779 if (!eap->skip && fudi.fd_newkey != NULL)
19780 EMSG2(_(e_dictkey), fudi.fd_newkey);
19781 vim_free(fudi.fd_newkey);
19782 return;
19784 else
19785 eap->skip = TRUE;
19788 /* An error in a function call during evaluation of an expression in magic
19789 * braces should not cause the function not to be defined. */
19790 saved_did_emsg = did_emsg;
19791 did_emsg = FALSE;
19794 * ":function func" with only function name: list function.
19796 if (!paren)
19798 if (!ends_excmd(*skipwhite(p)))
19800 EMSG(_(e_trailing));
19801 goto ret_free;
19803 eap->nextcmd = check_nextcmd(p);
19804 if (eap->nextcmd != NULL)
19805 *p = NUL;
19806 if (!eap->skip && !got_int)
19808 fp = find_func(name);
19809 if (fp != NULL)
19811 list_func_head(fp, TRUE);
19812 for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j)
19814 if (FUNCLINE(fp, j) == NULL)
19815 continue;
19816 msg_putchar('\n');
19817 msg_outnum((long)(j + 1));
19818 if (j < 9)
19819 msg_putchar(' ');
19820 if (j < 99)
19821 msg_putchar(' ');
19822 msg_prt_line(FUNCLINE(fp, j), FALSE);
19823 out_flush(); /* show a line at a time */
19824 ui_breakcheck();
19826 if (!got_int)
19828 msg_putchar('\n');
19829 msg_puts((char_u *)" endfunction");
19832 else
19833 emsg_funcname("E123: Undefined function: %s", name);
19835 goto ret_free;
19839 * ":function name(arg1, arg2)" Define function.
19841 p = skipwhite(p);
19842 if (*p != '(')
19844 if (!eap->skip)
19846 EMSG2(_("E124: Missing '(': %s"), eap->arg);
19847 goto ret_free;
19849 /* attempt to continue by skipping some text */
19850 if (vim_strchr(p, '(') != NULL)
19851 p = vim_strchr(p, '(');
19853 p = skipwhite(p + 1);
19855 ga_init2(&newargs, (int)sizeof(char_u *), 3);
19856 ga_init2(&newlines, (int)sizeof(char_u *), 3);
19858 if (!eap->skip)
19860 /* Check the name of the function. Unless it's a dictionary function
19861 * (that we are overwriting). */
19862 if (name != NULL)
19863 arg = name;
19864 else
19865 arg = fudi.fd_newkey;
19866 if (arg != NULL && (fudi.fd_di == NULL
19867 || fudi.fd_di->di_tv.v_type != VAR_FUNC))
19869 if (*arg == K_SPECIAL)
19870 j = 3;
19871 else
19872 j = 0;
19873 while (arg[j] != NUL && (j == 0 ? eval_isnamec1(arg[j])
19874 : eval_isnamec(arg[j])))
19875 ++j;
19876 if (arg[j] != NUL)
19877 emsg_funcname(_(e_invarg2), arg);
19882 * Isolate the arguments: "arg1, arg2, ...)"
19884 while (*p != ')')
19886 if (p[0] == '.' && p[1] == '.' && p[2] == '.')
19888 varargs = TRUE;
19889 p += 3;
19890 mustend = TRUE;
19892 else
19894 arg = p;
19895 while (ASCII_ISALNUM(*p) || *p == '_')
19896 ++p;
19897 if (arg == p || isdigit(*arg)
19898 || (p - arg == 9 && STRNCMP(arg, "firstline", 9) == 0)
19899 || (p - arg == 8 && STRNCMP(arg, "lastline", 8) == 0))
19901 if (!eap->skip)
19902 EMSG2(_("E125: Illegal argument: %s"), arg);
19903 break;
19905 if (ga_grow(&newargs, 1) == FAIL)
19906 goto erret;
19907 c = *p;
19908 *p = NUL;
19909 arg = vim_strsave(arg);
19910 if (arg == NULL)
19911 goto erret;
19912 ((char_u **)(newargs.ga_data))[newargs.ga_len] = arg;
19913 *p = c;
19914 newargs.ga_len++;
19915 if (*p == ',')
19916 ++p;
19917 else
19918 mustend = TRUE;
19920 p = skipwhite(p);
19921 if (mustend && *p != ')')
19923 if (!eap->skip)
19924 EMSG2(_(e_invarg2), eap->arg);
19925 break;
19928 ++p; /* skip the ')' */
19930 /* find extra arguments "range", "dict" and "abort" */
19931 for (;;)
19933 p = skipwhite(p);
19934 if (STRNCMP(p, "range", 5) == 0)
19936 flags |= FC_RANGE;
19937 p += 5;
19939 else if (STRNCMP(p, "dict", 4) == 0)
19941 flags |= FC_DICT;
19942 p += 4;
19944 else if (STRNCMP(p, "abort", 5) == 0)
19946 flags |= FC_ABORT;
19947 p += 5;
19949 else
19950 break;
19953 /* When there is a line break use what follows for the function body.
19954 * Makes 'exe "func Test()\n...\nendfunc"' work. */
19955 if (*p == '\n')
19956 line_arg = p + 1;
19957 else if (*p != NUL && *p != '"' && !eap->skip && !did_emsg)
19958 EMSG(_(e_trailing));
19961 * Read the body of the function, until ":endfunction" is found.
19963 if (KeyTyped)
19965 /* Check if the function already exists, don't let the user type the
19966 * whole function before telling him it doesn't work! For a script we
19967 * need to skip the body to be able to find what follows. */
19968 if (!eap->skip && !eap->forceit)
19970 if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL)
19971 EMSG(_(e_funcdict));
19972 else if (name != NULL && find_func(name) != NULL)
19973 emsg_funcname(e_funcexts, name);
19976 if (!eap->skip && did_emsg)
19977 goto erret;
19979 msg_putchar('\n'); /* don't overwrite the function name */
19980 cmdline_row = msg_row;
19983 indent = 2;
19984 nesting = 0;
19985 for (;;)
19987 msg_scroll = TRUE;
19988 need_wait_return = FALSE;
19989 sourcing_lnum_off = sourcing_lnum;
19991 if (line_arg != NULL)
19993 /* Use eap->arg, split up in parts by line breaks. */
19994 theline = line_arg;
19995 p = vim_strchr(theline, '\n');
19996 if (p == NULL)
19997 line_arg += STRLEN(line_arg);
19998 else
20000 *p = NUL;
20001 line_arg = p + 1;
20004 else if (eap->getline == NULL)
20005 theline = getcmdline(':', 0L, indent);
20006 else
20007 theline = eap->getline(':', eap->cookie, indent);
20008 if (KeyTyped)
20009 lines_left = Rows - 1;
20010 if (theline == NULL)
20012 EMSG(_("E126: Missing :endfunction"));
20013 goto erret;
20016 /* Detect line continuation: sourcing_lnum increased more than one. */
20017 if (sourcing_lnum > sourcing_lnum_off + 1)
20018 sourcing_lnum_off = sourcing_lnum - sourcing_lnum_off - 1;
20019 else
20020 sourcing_lnum_off = 0;
20022 if (skip_until != NULL)
20024 /* between ":append" and "." and between ":python <<EOF" and "EOF"
20025 * don't check for ":endfunc". */
20026 if (STRCMP(theline, skip_until) == 0)
20028 vim_free(skip_until);
20029 skip_until = NULL;
20032 else
20034 /* skip ':' and blanks*/
20035 for (p = theline; vim_iswhite(*p) || *p == ':'; ++p)
20038 /* Check for "endfunction". */
20039 if (checkforcmd(&p, "endfunction", 4) && nesting-- == 0)
20041 if (line_arg == NULL)
20042 vim_free(theline);
20043 break;
20046 /* Increase indent inside "if", "while", "for" and "try", decrease
20047 * at "end". */
20048 if (indent > 2 && STRNCMP(p, "end", 3) == 0)
20049 indent -= 2;
20050 else if (STRNCMP(p, "if", 2) == 0
20051 || STRNCMP(p, "wh", 2) == 0
20052 || STRNCMP(p, "for", 3) == 0
20053 || STRNCMP(p, "try", 3) == 0)
20054 indent += 2;
20056 /* Check for defining a function inside this function. */
20057 if (checkforcmd(&p, "function", 2))
20059 if (*p == '!')
20060 p = skipwhite(p + 1);
20061 p += eval_fname_script(p);
20062 if (ASCII_ISALPHA(*p))
20064 vim_free(trans_function_name(&p, TRUE, 0, NULL));
20065 if (*skipwhite(p) == '(')
20067 ++nesting;
20068 indent += 2;
20073 /* Check for ":append" or ":insert". */
20074 p = skip_range(p, NULL);
20075 if ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p'))
20076 || (p[0] == 'i'
20077 && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n'
20078 && (!ASCII_ISALPHA(p[2]) || (p[2] == 's'))))))
20079 skip_until = vim_strsave((char_u *)".");
20081 /* Check for ":python <<EOF", ":tcl <<EOF", etc. */
20082 arg = skipwhite(skiptowhite(p));
20083 if (arg[0] == '<' && arg[1] =='<'
20084 && ((p[0] == 'p' && p[1] == 'y'
20085 && (!ASCII_ISALPHA(p[2]) || p[2] == 't'))
20086 || (p[0] == 'p' && p[1] == 'e'
20087 && (!ASCII_ISALPHA(p[2]) || p[2] == 'r'))
20088 || (p[0] == 't' && p[1] == 'c'
20089 && (!ASCII_ISALPHA(p[2]) || p[2] == 'l'))
20090 || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b'
20091 && (!ASCII_ISALPHA(p[3]) || p[3] == 'y'))
20092 || (p[0] == 'm' && p[1] == 'z'
20093 && (!ASCII_ISALPHA(p[2]) || p[2] == 's'))
20096 /* ":python <<" continues until a dot, like ":append" */
20097 p = skipwhite(arg + 2);
20098 if (*p == NUL)
20099 skip_until = vim_strsave((char_u *)".");
20100 else
20101 skip_until = vim_strsave(p);
20105 /* Add the line to the function. */
20106 if (ga_grow(&newlines, 1 + sourcing_lnum_off) == FAIL)
20108 if (line_arg == NULL)
20109 vim_free(theline);
20110 goto erret;
20113 /* Copy the line to newly allocated memory. get_one_sourceline()
20114 * allocates 250 bytes per line, this saves 80% on average. The cost
20115 * is an extra alloc/free. */
20116 p = vim_strsave(theline);
20117 if (p != NULL)
20119 if (line_arg == NULL)
20120 vim_free(theline);
20121 theline = p;
20124 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = theline;
20126 /* Add NULL lines for continuation lines, so that the line count is
20127 * equal to the index in the growarray. */
20128 while (sourcing_lnum_off-- > 0)
20129 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = NULL;
20131 /* Check for end of eap->arg. */
20132 if (line_arg != NULL && *line_arg == NUL)
20133 line_arg = NULL;
20136 /* Don't define the function when skipping commands or when an error was
20137 * detected. */
20138 if (eap->skip || did_emsg)
20139 goto erret;
20142 * If there are no errors, add the function
20144 if (fudi.fd_dict == NULL)
20146 v = find_var(name, &ht);
20147 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
20149 emsg_funcname("E707: Function name conflicts with variable: %s",
20150 name);
20151 goto erret;
20154 fp = find_func(name);
20155 if (fp != NULL)
20157 if (!eap->forceit)
20159 emsg_funcname(e_funcexts, name);
20160 goto erret;
20162 if (fp->uf_calls > 0)
20164 emsg_funcname("E127: Cannot redefine function %s: It is in use",
20165 name);
20166 goto erret;
20168 /* redefine existing function */
20169 ga_clear_strings(&(fp->uf_args));
20170 ga_clear_strings(&(fp->uf_lines));
20171 vim_free(name);
20172 name = NULL;
20175 else
20177 char numbuf[20];
20179 fp = NULL;
20180 if (fudi.fd_newkey == NULL && !eap->forceit)
20182 EMSG(_(e_funcdict));
20183 goto erret;
20185 if (fudi.fd_di == NULL)
20187 /* Can't add a function to a locked dictionary */
20188 if (tv_check_lock(fudi.fd_dict->dv_lock, eap->arg))
20189 goto erret;
20191 /* Can't change an existing function if it is locked */
20192 else if (tv_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg))
20193 goto erret;
20195 /* Give the function a sequential number. Can only be used with a
20196 * Funcref! */
20197 vim_free(name);
20198 sprintf(numbuf, "%d", ++func_nr);
20199 name = vim_strsave((char_u *)numbuf);
20200 if (name == NULL)
20201 goto erret;
20204 if (fp == NULL)
20206 if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL)
20208 int slen, plen;
20209 char_u *scriptname;
20211 /* Check that the autoload name matches the script name. */
20212 j = FAIL;
20213 if (sourcing_name != NULL)
20215 scriptname = autoload_name(name);
20216 if (scriptname != NULL)
20218 p = vim_strchr(scriptname, '/');
20219 plen = (int)STRLEN(p);
20220 slen = (int)STRLEN(sourcing_name);
20221 if (slen > plen && fnamecmp(p,
20222 sourcing_name + slen - plen) == 0)
20223 j = OK;
20224 vim_free(scriptname);
20227 if (j == FAIL)
20229 EMSG2(_("E746: Function name does not match script file name: %s"), name);
20230 goto erret;
20234 fp = (ufunc_T *)alloc((unsigned)(sizeof(ufunc_T) + STRLEN(name)));
20235 if (fp == NULL)
20236 goto erret;
20238 if (fudi.fd_dict != NULL)
20240 if (fudi.fd_di == NULL)
20242 /* add new dict entry */
20243 fudi.fd_di = dictitem_alloc(fudi.fd_newkey);
20244 if (fudi.fd_di == NULL)
20246 vim_free(fp);
20247 goto erret;
20249 if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL)
20251 vim_free(fudi.fd_di);
20252 vim_free(fp);
20253 goto erret;
20256 else
20257 /* overwrite existing dict entry */
20258 clear_tv(&fudi.fd_di->di_tv);
20259 fudi.fd_di->di_tv.v_type = VAR_FUNC;
20260 fudi.fd_di->di_tv.v_lock = 0;
20261 fudi.fd_di->di_tv.vval.v_string = vim_strsave(name);
20262 fp->uf_refcount = 1;
20264 /* behave like "dict" was used */
20265 flags |= FC_DICT;
20268 /* insert the new function in the function list */
20269 STRCPY(fp->uf_name, name);
20270 hash_add(&func_hashtab, UF2HIKEY(fp));
20272 fp->uf_args = newargs;
20273 fp->uf_lines = newlines;
20274 #ifdef FEAT_PROFILE
20275 fp->uf_tml_count = NULL;
20276 fp->uf_tml_total = NULL;
20277 fp->uf_tml_self = NULL;
20278 fp->uf_profiling = FALSE;
20279 if (prof_def_func())
20280 func_do_profile(fp);
20281 #endif
20282 fp->uf_varargs = varargs;
20283 fp->uf_flags = flags;
20284 fp->uf_calls = 0;
20285 fp->uf_script_ID = current_SID;
20286 goto ret_free;
20288 erret:
20289 ga_clear_strings(&newargs);
20290 ga_clear_strings(&newlines);
20291 ret_free:
20292 vim_free(skip_until);
20293 vim_free(fudi.fd_newkey);
20294 vim_free(name);
20295 did_emsg |= saved_did_emsg;
20299 * Get a function name, translating "<SID>" and "<SNR>".
20300 * Also handles a Funcref in a List or Dictionary.
20301 * Returns the function name in allocated memory, or NULL for failure.
20302 * flags:
20303 * TFN_INT: internal function name OK
20304 * TFN_QUIET: be quiet
20305 * Advances "pp" to just after the function name (if no error).
20307 static char_u *
20308 trans_function_name(pp, skip, flags, fdp)
20309 char_u **pp;
20310 int skip; /* only find the end, don't evaluate */
20311 int flags;
20312 funcdict_T *fdp; /* return: info about dictionary used */
20314 char_u *name = NULL;
20315 char_u *start;
20316 char_u *end;
20317 int lead;
20318 char_u sid_buf[20];
20319 int len;
20320 lval_T lv;
20322 if (fdp != NULL)
20323 vim_memset(fdp, 0, sizeof(funcdict_T));
20324 start = *pp;
20326 /* Check for hard coded <SNR>: already translated function ID (from a user
20327 * command). */
20328 if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA
20329 && (*pp)[2] == (int)KE_SNR)
20331 *pp += 3;
20332 len = get_id_len(pp) + 3;
20333 return vim_strnsave(start, len);
20336 /* A name starting with "<SID>" or "<SNR>" is local to a script. But
20337 * don't skip over "s:", get_lval() needs it for "s:dict.func". */
20338 lead = eval_fname_script(start);
20339 if (lead > 2)
20340 start += lead;
20342 end = get_lval(start, NULL, &lv, FALSE, skip, flags & TFN_QUIET,
20343 lead > 2 ? 0 : FNE_CHECK_START);
20344 if (end == start)
20346 if (!skip)
20347 EMSG(_("E129: Function name required"));
20348 goto theend;
20350 if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range)))
20353 * Report an invalid expression in braces, unless the expression
20354 * evaluation has been cancelled due to an aborting error, an
20355 * interrupt, or an exception.
20357 if (!aborting())
20359 if (end != NULL)
20360 EMSG2(_(e_invarg2), start);
20362 else
20363 *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR);
20364 goto theend;
20367 if (lv.ll_tv != NULL)
20369 if (fdp != NULL)
20371 fdp->fd_dict = lv.ll_dict;
20372 fdp->fd_newkey = lv.ll_newkey;
20373 lv.ll_newkey = NULL;
20374 fdp->fd_di = lv.ll_di;
20376 if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL)
20378 name = vim_strsave(lv.ll_tv->vval.v_string);
20379 *pp = end;
20381 else
20383 if (!skip && !(flags & TFN_QUIET) && (fdp == NULL
20384 || lv.ll_dict == NULL || fdp->fd_newkey == NULL))
20385 EMSG(_(e_funcref));
20386 else
20387 *pp = end;
20388 name = NULL;
20390 goto theend;
20393 if (lv.ll_name == NULL)
20395 /* Error found, but continue after the function name. */
20396 *pp = end;
20397 goto theend;
20400 /* Check if the name is a Funcref. If so, use the value. */
20401 if (lv.ll_exp_name != NULL)
20403 len = (int)STRLEN(lv.ll_exp_name);
20404 name = deref_func_name(lv.ll_exp_name, &len);
20405 if (name == lv.ll_exp_name)
20406 name = NULL;
20408 else
20410 len = (int)(end - *pp);
20411 name = deref_func_name(*pp, &len);
20412 if (name == *pp)
20413 name = NULL;
20415 if (name != NULL)
20417 name = vim_strsave(name);
20418 *pp = end;
20419 goto theend;
20422 if (lv.ll_exp_name != NULL)
20424 len = (int)STRLEN(lv.ll_exp_name);
20425 if (lead <= 2 && lv.ll_name == lv.ll_exp_name
20426 && STRNCMP(lv.ll_name, "s:", 2) == 0)
20428 /* When there was "s:" already or the name expanded to get a
20429 * leading "s:" then remove it. */
20430 lv.ll_name += 2;
20431 len -= 2;
20432 lead = 2;
20435 else
20437 if (lead == 2) /* skip over "s:" */
20438 lv.ll_name += 2;
20439 len = (int)(end - lv.ll_name);
20443 * Copy the function name to allocated memory.
20444 * Accept <SID>name() inside a script, translate into <SNR>123_name().
20445 * Accept <SNR>123_name() outside a script.
20447 if (skip)
20448 lead = 0; /* do nothing */
20449 else if (lead > 0)
20451 lead = 3;
20452 if ((lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name))
20453 || eval_fname_sid(*pp))
20455 /* It's "s:" or "<SID>" */
20456 if (current_SID <= 0)
20458 EMSG(_(e_usingsid));
20459 goto theend;
20461 sprintf((char *)sid_buf, "%ld_", (long)current_SID);
20462 lead += (int)STRLEN(sid_buf);
20465 else if (!(flags & TFN_INT) && builtin_function(lv.ll_name))
20467 EMSG2(_("E128: Function name must start with a capital or contain a colon: %s"), lv.ll_name);
20468 goto theend;
20470 name = alloc((unsigned)(len + lead + 1));
20471 if (name != NULL)
20473 if (lead > 0)
20475 name[0] = K_SPECIAL;
20476 name[1] = KS_EXTRA;
20477 name[2] = (int)KE_SNR;
20478 if (lead > 3) /* If it's "<SID>" */
20479 STRCPY(name + 3, sid_buf);
20481 mch_memmove(name + lead, lv.ll_name, (size_t)len);
20482 name[len + lead] = NUL;
20484 *pp = end;
20486 theend:
20487 clear_lval(&lv);
20488 return name;
20492 * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case).
20493 * Return 2 if "p" starts with "s:".
20494 * Return 0 otherwise.
20496 static int
20497 eval_fname_script(p)
20498 char_u *p;
20500 if (p[0] == '<' && (STRNICMP(p + 1, "SID>", 4) == 0
20501 || STRNICMP(p + 1, "SNR>", 4) == 0))
20502 return 5;
20503 if (p[0] == 's' && p[1] == ':')
20504 return 2;
20505 return 0;
20509 * Return TRUE if "p" starts with "<SID>" or "s:".
20510 * Only works if eval_fname_script() returned non-zero for "p"!
20512 static int
20513 eval_fname_sid(p)
20514 char_u *p;
20516 return (*p == 's' || TOUPPER_ASC(p[2]) == 'I');
20520 * List the head of the function: "name(arg1, arg2)".
20522 static void
20523 list_func_head(fp, indent)
20524 ufunc_T *fp;
20525 int indent;
20527 int j;
20529 msg_start();
20530 if (indent)
20531 MSG_PUTS(" ");
20532 MSG_PUTS("function ");
20533 if (fp->uf_name[0] == K_SPECIAL)
20535 MSG_PUTS_ATTR("<SNR>", hl_attr(HLF_8));
20536 msg_puts(fp->uf_name + 3);
20538 else
20539 msg_puts(fp->uf_name);
20540 msg_putchar('(');
20541 for (j = 0; j < fp->uf_args.ga_len; ++j)
20543 if (j)
20544 MSG_PUTS(", ");
20545 msg_puts(FUNCARG(fp, j));
20547 if (fp->uf_varargs)
20549 if (j)
20550 MSG_PUTS(", ");
20551 MSG_PUTS("...");
20553 msg_putchar(')');
20554 msg_clr_eos();
20555 if (p_verbose > 0)
20556 last_set_msg(fp->uf_script_ID);
20560 * Find a function by name, return pointer to it in ufuncs.
20561 * Return NULL for unknown function.
20563 static ufunc_T *
20564 find_func(name)
20565 char_u *name;
20567 hashitem_T *hi;
20569 hi = hash_find(&func_hashtab, name);
20570 if (!HASHITEM_EMPTY(hi))
20571 return HI2UF(hi);
20572 return NULL;
20575 #if defined(EXITFREE) || defined(PROTO)
20576 void
20577 free_all_functions()
20579 hashitem_T *hi;
20581 /* Need to start all over every time, because func_free() may change the
20582 * hash table. */
20583 while (func_hashtab.ht_used > 0)
20584 for (hi = func_hashtab.ht_array; ; ++hi)
20585 if (!HASHITEM_EMPTY(hi))
20587 func_free(HI2UF(hi));
20588 break;
20591 #endif
20594 * Return TRUE if a function "name" exists.
20596 static int
20597 function_exists(name)
20598 char_u *name;
20600 char_u *nm = name;
20601 char_u *p;
20602 int n = FALSE;
20604 p = trans_function_name(&nm, FALSE, TFN_INT|TFN_QUIET, NULL);
20605 nm = skipwhite(nm);
20607 /* Only accept "funcname", "funcname ", "funcname (..." and
20608 * "funcname(...", not "funcname!...". */
20609 if (p != NULL && (*nm == NUL || *nm == '('))
20611 if (builtin_function(p))
20612 n = (find_internal_func(p) >= 0);
20613 else
20614 n = (find_func(p) != NULL);
20616 vim_free(p);
20617 return n;
20621 * Return TRUE if "name" looks like a builtin function name: starts with a
20622 * lower case letter and doesn't contain a ':' or AUTOLOAD_CHAR.
20624 static int
20625 builtin_function(name)
20626 char_u *name;
20628 return ASCII_ISLOWER(name[0]) && vim_strchr(name, ':') == NULL
20629 && vim_strchr(name, AUTOLOAD_CHAR) == NULL;
20632 #if defined(FEAT_PROFILE) || defined(PROTO)
20634 * Start profiling function "fp".
20636 static void
20637 func_do_profile(fp)
20638 ufunc_T *fp;
20640 fp->uf_tm_count = 0;
20641 profile_zero(&fp->uf_tm_self);
20642 profile_zero(&fp->uf_tm_total);
20643 if (fp->uf_tml_count == NULL)
20644 fp->uf_tml_count = (int *)alloc_clear((unsigned)
20645 (sizeof(int) * fp->uf_lines.ga_len));
20646 if (fp->uf_tml_total == NULL)
20647 fp->uf_tml_total = (proftime_T *)alloc_clear((unsigned)
20648 (sizeof(proftime_T) * fp->uf_lines.ga_len));
20649 if (fp->uf_tml_self == NULL)
20650 fp->uf_tml_self = (proftime_T *)alloc_clear((unsigned)
20651 (sizeof(proftime_T) * fp->uf_lines.ga_len));
20652 fp->uf_tml_idx = -1;
20653 if (fp->uf_tml_count == NULL || fp->uf_tml_total == NULL
20654 || fp->uf_tml_self == NULL)
20655 return; /* out of memory */
20657 fp->uf_profiling = TRUE;
20661 * Dump the profiling results for all functions in file "fd".
20663 void
20664 func_dump_profile(fd)
20665 FILE *fd;
20667 hashitem_T *hi;
20668 int todo;
20669 ufunc_T *fp;
20670 int i;
20671 ufunc_T **sorttab;
20672 int st_len = 0;
20674 todo = (int)func_hashtab.ht_used;
20675 if (todo == 0)
20676 return; /* nothing to dump */
20678 sorttab = (ufunc_T **)alloc((unsigned)(sizeof(ufunc_T) * todo));
20680 for (hi = func_hashtab.ht_array; todo > 0; ++hi)
20682 if (!HASHITEM_EMPTY(hi))
20684 --todo;
20685 fp = HI2UF(hi);
20686 if (fp->uf_profiling)
20688 if (sorttab != NULL)
20689 sorttab[st_len++] = fp;
20691 if (fp->uf_name[0] == K_SPECIAL)
20692 fprintf(fd, "FUNCTION <SNR>%s()\n", fp->uf_name + 3);
20693 else
20694 fprintf(fd, "FUNCTION %s()\n", fp->uf_name);
20695 if (fp->uf_tm_count == 1)
20696 fprintf(fd, "Called 1 time\n");
20697 else
20698 fprintf(fd, "Called %d times\n", fp->uf_tm_count);
20699 fprintf(fd, "Total time: %s\n", profile_msg(&fp->uf_tm_total));
20700 fprintf(fd, " Self time: %s\n", profile_msg(&fp->uf_tm_self));
20701 fprintf(fd, "\n");
20702 fprintf(fd, "count total (s) self (s)\n");
20704 for (i = 0; i < fp->uf_lines.ga_len; ++i)
20706 if (FUNCLINE(fp, i) == NULL)
20707 continue;
20708 prof_func_line(fd, fp->uf_tml_count[i],
20709 &fp->uf_tml_total[i], &fp->uf_tml_self[i], TRUE);
20710 fprintf(fd, "%s\n", FUNCLINE(fp, i));
20712 fprintf(fd, "\n");
20717 if (sorttab != NULL && st_len > 0)
20719 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
20720 prof_total_cmp);
20721 prof_sort_list(fd, sorttab, st_len, "TOTAL", FALSE);
20722 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
20723 prof_self_cmp);
20724 prof_sort_list(fd, sorttab, st_len, "SELF", TRUE);
20727 vim_free(sorttab);
20730 static void
20731 prof_sort_list(fd, sorttab, st_len, title, prefer_self)
20732 FILE *fd;
20733 ufunc_T **sorttab;
20734 int st_len;
20735 char *title;
20736 int prefer_self; /* when equal print only self time */
20738 int i;
20739 ufunc_T *fp;
20741 fprintf(fd, "FUNCTIONS SORTED ON %s TIME\n", title);
20742 fprintf(fd, "count total (s) self (s) function\n");
20743 for (i = 0; i < 20 && i < st_len; ++i)
20745 fp = sorttab[i];
20746 prof_func_line(fd, fp->uf_tm_count, &fp->uf_tm_total, &fp->uf_tm_self,
20747 prefer_self);
20748 if (fp->uf_name[0] == K_SPECIAL)
20749 fprintf(fd, " <SNR>%s()\n", fp->uf_name + 3);
20750 else
20751 fprintf(fd, " %s()\n", fp->uf_name);
20753 fprintf(fd, "\n");
20757 * Print the count and times for one function or function line.
20759 static void
20760 prof_func_line(fd, count, total, self, prefer_self)
20761 FILE *fd;
20762 int count;
20763 proftime_T *total;
20764 proftime_T *self;
20765 int prefer_self; /* when equal print only self time */
20767 if (count > 0)
20769 fprintf(fd, "%5d ", count);
20770 if (prefer_self && profile_equal(total, self))
20771 fprintf(fd, " ");
20772 else
20773 fprintf(fd, "%s ", profile_msg(total));
20774 if (!prefer_self && profile_equal(total, self))
20775 fprintf(fd, " ");
20776 else
20777 fprintf(fd, "%s ", profile_msg(self));
20779 else
20780 fprintf(fd, " ");
20784 * Compare function for total time sorting.
20786 static int
20787 #ifdef __BORLANDC__
20788 _RTLENTRYF
20789 #endif
20790 prof_total_cmp(s1, s2)
20791 const void *s1;
20792 const void *s2;
20794 ufunc_T *p1, *p2;
20796 p1 = *(ufunc_T **)s1;
20797 p2 = *(ufunc_T **)s2;
20798 return profile_cmp(&p1->uf_tm_total, &p2->uf_tm_total);
20802 * Compare function for self time sorting.
20804 static int
20805 #ifdef __BORLANDC__
20806 _RTLENTRYF
20807 #endif
20808 prof_self_cmp(s1, s2)
20809 const void *s1;
20810 const void *s2;
20812 ufunc_T *p1, *p2;
20814 p1 = *(ufunc_T **)s1;
20815 p2 = *(ufunc_T **)s2;
20816 return profile_cmp(&p1->uf_tm_self, &p2->uf_tm_self);
20819 #endif
20822 * If "name" has a package name try autoloading the script for it.
20823 * Return TRUE if a package was loaded.
20825 static int
20826 script_autoload(name, reload)
20827 char_u *name;
20828 int reload; /* load script again when already loaded */
20830 char_u *p;
20831 char_u *scriptname, *tofree;
20832 int ret = FALSE;
20833 int i;
20835 /* If there is no '#' after name[0] there is no package name. */
20836 p = vim_strchr(name, AUTOLOAD_CHAR);
20837 if (p == NULL || p == name)
20838 return FALSE;
20840 tofree = scriptname = autoload_name(name);
20842 /* Find the name in the list of previously loaded package names. Skip
20843 * "autoload/", it's always the same. */
20844 for (i = 0; i < ga_loaded.ga_len; ++i)
20845 if (STRCMP(((char_u **)ga_loaded.ga_data)[i] + 9, scriptname + 9) == 0)
20846 break;
20847 if (!reload && i < ga_loaded.ga_len)
20848 ret = FALSE; /* was loaded already */
20849 else
20851 /* Remember the name if it wasn't loaded already. */
20852 if (i == ga_loaded.ga_len && ga_grow(&ga_loaded, 1) == OK)
20854 ((char_u **)ga_loaded.ga_data)[ga_loaded.ga_len++] = scriptname;
20855 tofree = NULL;
20858 /* Try loading the package from $VIMRUNTIME/autoload/<name>.vim */
20859 if (source_runtime(scriptname, FALSE) == OK)
20860 ret = TRUE;
20863 vim_free(tofree);
20864 return ret;
20868 * Return the autoload script name for a function or variable name.
20869 * Returns NULL when out of memory.
20871 static char_u *
20872 autoload_name(name)
20873 char_u *name;
20875 char_u *p;
20876 char_u *scriptname;
20878 /* Get the script file name: replace '#' with '/', append ".vim". */
20879 scriptname = alloc((unsigned)(STRLEN(name) + 14));
20880 if (scriptname == NULL)
20881 return FALSE;
20882 STRCPY(scriptname, "autoload/");
20883 STRCAT(scriptname, name);
20884 *vim_strrchr(scriptname, AUTOLOAD_CHAR) = NUL;
20885 STRCAT(scriptname, ".vim");
20886 while ((p = vim_strchr(scriptname, AUTOLOAD_CHAR)) != NULL)
20887 *p = '/';
20888 return scriptname;
20891 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
20894 * Function given to ExpandGeneric() to obtain the list of user defined
20895 * function names.
20897 char_u *
20898 get_user_func_name(xp, idx)
20899 expand_T *xp;
20900 int idx;
20902 static long_u done;
20903 static hashitem_T *hi;
20904 ufunc_T *fp;
20906 if (idx == 0)
20908 done = 0;
20909 hi = func_hashtab.ht_array;
20911 if (done < func_hashtab.ht_used)
20913 if (done++ > 0)
20914 ++hi;
20915 while (HASHITEM_EMPTY(hi))
20916 ++hi;
20917 fp = HI2UF(hi);
20919 if (STRLEN(fp->uf_name) + 4 >= IOSIZE)
20920 return fp->uf_name; /* prevents overflow */
20922 cat_func_name(IObuff, fp);
20923 if (xp->xp_context != EXPAND_USER_FUNC)
20925 STRCAT(IObuff, "(");
20926 if (!fp->uf_varargs && fp->uf_args.ga_len == 0)
20927 STRCAT(IObuff, ")");
20929 return IObuff;
20931 return NULL;
20934 #endif /* FEAT_CMDL_COMPL */
20937 * Copy the function name of "fp" to buffer "buf".
20938 * "buf" must be able to hold the function name plus three bytes.
20939 * Takes care of script-local function names.
20941 static void
20942 cat_func_name(buf, fp)
20943 char_u *buf;
20944 ufunc_T *fp;
20946 if (fp->uf_name[0] == K_SPECIAL)
20948 STRCPY(buf, "<SNR>");
20949 STRCAT(buf, fp->uf_name + 3);
20951 else
20952 STRCPY(buf, fp->uf_name);
20956 * ":delfunction {name}"
20958 void
20959 ex_delfunction(eap)
20960 exarg_T *eap;
20962 ufunc_T *fp = NULL;
20963 char_u *p;
20964 char_u *name;
20965 funcdict_T fudi;
20967 p = eap->arg;
20968 name = trans_function_name(&p, eap->skip, 0, &fudi);
20969 vim_free(fudi.fd_newkey);
20970 if (name == NULL)
20972 if (fudi.fd_dict != NULL && !eap->skip)
20973 EMSG(_(e_funcref));
20974 return;
20976 if (!ends_excmd(*skipwhite(p)))
20978 vim_free(name);
20979 EMSG(_(e_trailing));
20980 return;
20982 eap->nextcmd = check_nextcmd(p);
20983 if (eap->nextcmd != NULL)
20984 *p = NUL;
20986 if (!eap->skip)
20987 fp = find_func(name);
20988 vim_free(name);
20990 if (!eap->skip)
20992 if (fp == NULL)
20994 EMSG2(_(e_nofunc), eap->arg);
20995 return;
20997 if (fp->uf_calls > 0)
20999 EMSG2(_("E131: Cannot delete function %s: It is in use"), eap->arg);
21000 return;
21003 if (fudi.fd_dict != NULL)
21005 /* Delete the dict item that refers to the function, it will
21006 * invoke func_unref() and possibly delete the function. */
21007 dictitem_remove(fudi.fd_dict, fudi.fd_di);
21009 else
21010 func_free(fp);
21015 * Free a function and remove it from the list of functions.
21017 static void
21018 func_free(fp)
21019 ufunc_T *fp;
21021 hashitem_T *hi;
21023 /* clear this function */
21024 ga_clear_strings(&(fp->uf_args));
21025 ga_clear_strings(&(fp->uf_lines));
21026 #ifdef FEAT_PROFILE
21027 vim_free(fp->uf_tml_count);
21028 vim_free(fp->uf_tml_total);
21029 vim_free(fp->uf_tml_self);
21030 #endif
21032 /* remove the function from the function hashtable */
21033 hi = hash_find(&func_hashtab, UF2HIKEY(fp));
21034 if (HASHITEM_EMPTY(hi))
21035 EMSG2(_(e_intern2), "func_free()");
21036 else
21037 hash_remove(&func_hashtab, hi);
21039 vim_free(fp);
21043 * Unreference a Function: decrement the reference count and free it when it
21044 * becomes zero. Only for numbered functions.
21046 static void
21047 func_unref(name)
21048 char_u *name;
21050 ufunc_T *fp;
21052 if (name != NULL && isdigit(*name))
21054 fp = find_func(name);
21055 if (fp == NULL)
21056 EMSG2(_(e_intern2), "func_unref()");
21057 else if (--fp->uf_refcount <= 0)
21059 /* Only delete it when it's not being used. Otherwise it's done
21060 * when "uf_calls" becomes zero. */
21061 if (fp->uf_calls == 0)
21062 func_free(fp);
21068 * Count a reference to a Function.
21070 static void
21071 func_ref(name)
21072 char_u *name;
21074 ufunc_T *fp;
21076 if (name != NULL && isdigit(*name))
21078 fp = find_func(name);
21079 if (fp == NULL)
21080 EMSG2(_(e_intern2), "func_ref()");
21081 else
21082 ++fp->uf_refcount;
21087 * Call a user function.
21089 static void
21090 call_user_func(fp, argcount, argvars, rettv, firstline, lastline, selfdict)
21091 ufunc_T *fp; /* pointer to function */
21092 int argcount; /* nr of args */
21093 typval_T *argvars; /* arguments */
21094 typval_T *rettv; /* return value */
21095 linenr_T firstline; /* first line of range */
21096 linenr_T lastline; /* last line of range */
21097 dict_T *selfdict; /* Dictionary for "self" */
21099 char_u *save_sourcing_name;
21100 linenr_T save_sourcing_lnum;
21101 scid_T save_current_SID;
21102 funccall_T fc;
21103 int save_did_emsg;
21104 static int depth = 0;
21105 dictitem_T *v;
21106 int fixvar_idx = 0; /* index in fixvar[] */
21107 int i;
21108 int ai;
21109 char_u numbuf[NUMBUFLEN];
21110 char_u *name;
21111 #ifdef FEAT_PROFILE
21112 proftime_T wait_start;
21113 proftime_T call_start;
21114 #endif
21116 /* If depth of calling is getting too high, don't execute the function */
21117 if (depth >= p_mfd)
21119 EMSG(_("E132: Function call depth is higher than 'maxfuncdepth'"));
21120 rettv->v_type = VAR_NUMBER;
21121 rettv->vval.v_number = -1;
21122 return;
21124 ++depth;
21126 line_breakcheck(); /* check for CTRL-C hit */
21128 fc.caller = current_funccal;
21129 current_funccal = &fc;
21130 fc.func = fp;
21131 fc.rettv = rettv;
21132 rettv->vval.v_number = 0;
21133 fc.linenr = 0;
21134 fc.returned = FALSE;
21135 fc.level = ex_nesting_level;
21136 /* Check if this function has a breakpoint. */
21137 fc.breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, (linenr_T)0);
21138 fc.dbg_tick = debug_tick;
21141 * Note about using fc.fixvar[]: This is an array of FIXVAR_CNT variables
21142 * with names up to VAR_SHORT_LEN long. This avoids having to alloc/free
21143 * each argument variable and saves a lot of time.
21146 * Init l: variables.
21148 init_var_dict(&fc.l_vars, &fc.l_vars_var);
21149 if (selfdict != NULL)
21151 /* Set l:self to "selfdict". Use "name" to avoid a warning from
21152 * some compiler that checks the destination size. */
21153 v = &fc.fixvar[fixvar_idx++].var;
21154 name = v->di_key;
21155 STRCPY(name, "self");
21156 v->di_flags = DI_FLAGS_RO + DI_FLAGS_FIX;
21157 hash_add(&fc.l_vars.dv_hashtab, DI2HIKEY(v));
21158 v->di_tv.v_type = VAR_DICT;
21159 v->di_tv.v_lock = 0;
21160 v->di_tv.vval.v_dict = selfdict;
21161 ++selfdict->dv_refcount;
21165 * Init a: variables.
21166 * Set a:0 to "argcount".
21167 * Set a:000 to a list with room for the "..." arguments.
21169 init_var_dict(&fc.l_avars, &fc.l_avars_var);
21170 add_nr_var(&fc.l_avars, &fc.fixvar[fixvar_idx++].var, "0",
21171 (varnumber_T)(argcount - fp->uf_args.ga_len));
21172 v = &fc.fixvar[fixvar_idx++].var;
21173 STRCPY(v->di_key, "000");
21174 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21175 hash_add(&fc.l_avars.dv_hashtab, DI2HIKEY(v));
21176 v->di_tv.v_type = VAR_LIST;
21177 v->di_tv.v_lock = VAR_FIXED;
21178 v->di_tv.vval.v_list = &fc.l_varlist;
21179 vim_memset(&fc.l_varlist, 0, sizeof(list_T));
21180 fc.l_varlist.lv_refcount = 99999;
21181 fc.l_varlist.lv_lock = VAR_FIXED;
21184 * Set a:firstline to "firstline" and a:lastline to "lastline".
21185 * Set a:name to named arguments.
21186 * Set a:N to the "..." arguments.
21188 add_nr_var(&fc.l_avars, &fc.fixvar[fixvar_idx++].var, "firstline",
21189 (varnumber_T)firstline);
21190 add_nr_var(&fc.l_avars, &fc.fixvar[fixvar_idx++].var, "lastline",
21191 (varnumber_T)lastline);
21192 for (i = 0; i < argcount; ++i)
21194 ai = i - fp->uf_args.ga_len;
21195 if (ai < 0)
21196 /* named argument a:name */
21197 name = FUNCARG(fp, i);
21198 else
21200 /* "..." argument a:1, a:2, etc. */
21201 sprintf((char *)numbuf, "%d", ai + 1);
21202 name = numbuf;
21204 if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN)
21206 v = &fc.fixvar[fixvar_idx++].var;
21207 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21209 else
21211 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
21212 + STRLEN(name)));
21213 if (v == NULL)
21214 break;
21215 v->di_flags = DI_FLAGS_RO;
21217 STRCPY(v->di_key, name);
21218 hash_add(&fc.l_avars.dv_hashtab, DI2HIKEY(v));
21220 /* Note: the values are copied directly to avoid alloc/free.
21221 * "argvars" must have VAR_FIXED for v_lock. */
21222 v->di_tv = argvars[i];
21223 v->di_tv.v_lock = VAR_FIXED;
21225 if (ai >= 0 && ai < MAX_FUNC_ARGS)
21227 list_append(&fc.l_varlist, &fc.l_listitems[ai]);
21228 fc.l_listitems[ai].li_tv = argvars[i];
21229 fc.l_listitems[ai].li_tv.v_lock = VAR_FIXED;
21233 /* Don't redraw while executing the function. */
21234 ++RedrawingDisabled;
21235 save_sourcing_name = sourcing_name;
21236 save_sourcing_lnum = sourcing_lnum;
21237 sourcing_lnum = 1;
21238 sourcing_name = alloc((unsigned)((save_sourcing_name == NULL ? 0
21239 : STRLEN(save_sourcing_name)) + STRLEN(fp->uf_name) + 13));
21240 if (sourcing_name != NULL)
21242 if (save_sourcing_name != NULL
21243 && STRNCMP(save_sourcing_name, "function ", 9) == 0)
21244 sprintf((char *)sourcing_name, "%s..", save_sourcing_name);
21245 else
21246 STRCPY(sourcing_name, "function ");
21247 cat_func_name(sourcing_name + STRLEN(sourcing_name), fp);
21249 if (p_verbose >= 12)
21251 ++no_wait_return;
21252 verbose_enter_scroll();
21254 smsg((char_u *)_("calling %s"), sourcing_name);
21255 if (p_verbose >= 14)
21257 char_u buf[MSG_BUF_LEN];
21258 char_u numbuf2[NUMBUFLEN];
21259 char_u *tofree;
21260 char_u *s;
21262 msg_puts((char_u *)"(");
21263 for (i = 0; i < argcount; ++i)
21265 if (i > 0)
21266 msg_puts((char_u *)", ");
21267 if (argvars[i].v_type == VAR_NUMBER)
21268 msg_outnum((long)argvars[i].vval.v_number);
21269 else
21271 s = tv2string(&argvars[i], &tofree, numbuf2, 0);
21272 if (s != NULL)
21274 trunc_string(s, buf, MSG_BUF_CLEN);
21275 msg_puts(buf);
21276 vim_free(tofree);
21280 msg_puts((char_u *)")");
21282 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21284 verbose_leave_scroll();
21285 --no_wait_return;
21288 #ifdef FEAT_PROFILE
21289 if (do_profiling == PROF_YES)
21291 if (!fp->uf_profiling && has_profiling(FALSE, fp->uf_name, NULL))
21292 func_do_profile(fp);
21293 if (fp->uf_profiling
21294 || (fc.caller != NULL && fc.caller->func->uf_profiling))
21296 ++fp->uf_tm_count;
21297 profile_start(&call_start);
21298 profile_zero(&fp->uf_tm_children);
21300 script_prof_save(&wait_start);
21302 #endif
21304 save_current_SID = current_SID;
21305 current_SID = fp->uf_script_ID;
21306 save_did_emsg = did_emsg;
21307 did_emsg = FALSE;
21309 /* call do_cmdline() to execute the lines */
21310 do_cmdline(NULL, get_func_line, (void *)&fc,
21311 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
21313 --RedrawingDisabled;
21315 /* when the function was aborted because of an error, return -1 */
21316 if ((did_emsg && (fp->uf_flags & FC_ABORT)) || rettv->v_type == VAR_UNKNOWN)
21318 clear_tv(rettv);
21319 rettv->v_type = VAR_NUMBER;
21320 rettv->vval.v_number = -1;
21323 #ifdef FEAT_PROFILE
21324 if (do_profiling == PROF_YES && (fp->uf_profiling
21325 || (fc.caller != NULL && fc.caller->func->uf_profiling)))
21327 profile_end(&call_start);
21328 profile_sub_wait(&wait_start, &call_start);
21329 profile_add(&fp->uf_tm_total, &call_start);
21330 profile_self(&fp->uf_tm_self, &call_start, &fp->uf_tm_children);
21331 if (fc.caller != NULL && fc.caller->func->uf_profiling)
21333 profile_add(&fc.caller->func->uf_tm_children, &call_start);
21334 profile_add(&fc.caller->func->uf_tml_children, &call_start);
21337 #endif
21339 /* when being verbose, mention the return value */
21340 if (p_verbose >= 12)
21342 ++no_wait_return;
21343 verbose_enter_scroll();
21345 if (aborting())
21346 smsg((char_u *)_("%s aborted"), sourcing_name);
21347 else if (fc.rettv->v_type == VAR_NUMBER)
21348 smsg((char_u *)_("%s returning #%ld"), sourcing_name,
21349 (long)fc.rettv->vval.v_number);
21350 else
21352 char_u buf[MSG_BUF_LEN];
21353 char_u numbuf2[NUMBUFLEN];
21354 char_u *tofree;
21355 char_u *s;
21357 /* The value may be very long. Skip the middle part, so that we
21358 * have some idea how it starts and ends. smsg() would always
21359 * truncate it at the end. */
21360 s = tv2string(fc.rettv, &tofree, numbuf2, 0);
21361 if (s != NULL)
21363 trunc_string(s, buf, MSG_BUF_CLEN);
21364 smsg((char_u *)_("%s returning %s"), sourcing_name, buf);
21365 vim_free(tofree);
21368 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21370 verbose_leave_scroll();
21371 --no_wait_return;
21374 vim_free(sourcing_name);
21375 sourcing_name = save_sourcing_name;
21376 sourcing_lnum = save_sourcing_lnum;
21377 current_SID = save_current_SID;
21378 #ifdef FEAT_PROFILE
21379 if (do_profiling == PROF_YES)
21380 script_prof_restore(&wait_start);
21381 #endif
21383 if (p_verbose >= 12 && sourcing_name != NULL)
21385 ++no_wait_return;
21386 verbose_enter_scroll();
21388 smsg((char_u *)_("continuing in %s"), sourcing_name);
21389 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21391 verbose_leave_scroll();
21392 --no_wait_return;
21395 did_emsg |= save_did_emsg;
21396 current_funccal = fc.caller;
21398 /* The a: variables typevals were not allocated, only free the allocated
21399 * variables. */
21400 vars_clear_ext(&fc.l_avars.dv_hashtab, FALSE);
21402 vars_clear(&fc.l_vars.dv_hashtab); /* free all l: variables */
21403 --depth;
21407 * Add a number variable "name" to dict "dp" with value "nr".
21409 static void
21410 add_nr_var(dp, v, name, nr)
21411 dict_T *dp;
21412 dictitem_T *v;
21413 char *name;
21414 varnumber_T nr;
21416 STRCPY(v->di_key, name);
21417 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21418 hash_add(&dp->dv_hashtab, DI2HIKEY(v));
21419 v->di_tv.v_type = VAR_NUMBER;
21420 v->di_tv.v_lock = VAR_FIXED;
21421 v->di_tv.vval.v_number = nr;
21425 * ":return [expr]"
21427 void
21428 ex_return(eap)
21429 exarg_T *eap;
21431 char_u *arg = eap->arg;
21432 typval_T rettv;
21433 int returning = FALSE;
21435 if (current_funccal == NULL)
21437 EMSG(_("E133: :return not inside a function"));
21438 return;
21441 if (eap->skip)
21442 ++emsg_skip;
21444 eap->nextcmd = NULL;
21445 if ((*arg != NUL && *arg != '|' && *arg != '\n')
21446 && eval0(arg, &rettv, &eap->nextcmd, !eap->skip) != FAIL)
21448 if (!eap->skip)
21449 returning = do_return(eap, FALSE, TRUE, &rettv);
21450 else
21451 clear_tv(&rettv);
21453 /* It's safer to return also on error. */
21454 else if (!eap->skip)
21457 * Return unless the expression evaluation has been cancelled due to an
21458 * aborting error, an interrupt, or an exception.
21460 if (!aborting())
21461 returning = do_return(eap, FALSE, TRUE, NULL);
21464 /* When skipping or the return gets pending, advance to the next command
21465 * in this line (!returning). Otherwise, ignore the rest of the line.
21466 * Following lines will be ignored by get_func_line(). */
21467 if (returning)
21468 eap->nextcmd = NULL;
21469 else if (eap->nextcmd == NULL) /* no argument */
21470 eap->nextcmd = check_nextcmd(arg);
21472 if (eap->skip)
21473 --emsg_skip;
21477 * Return from a function. Possibly makes the return pending. Also called
21478 * for a pending return at the ":endtry" or after returning from an extra
21479 * do_cmdline(). "reanimate" is used in the latter case. "is_cmd" is set
21480 * when called due to a ":return" command. "rettv" may point to a typval_T
21481 * with the return rettv. Returns TRUE when the return can be carried out,
21482 * FALSE when the return gets pending.
21485 do_return(eap, reanimate, is_cmd, rettv)
21486 exarg_T *eap;
21487 int reanimate;
21488 int is_cmd;
21489 void *rettv;
21491 int idx;
21492 struct condstack *cstack = eap->cstack;
21494 if (reanimate)
21495 /* Undo the return. */
21496 current_funccal->returned = FALSE;
21499 * Cleanup (and inactivate) conditionals, but stop when a try conditional
21500 * not in its finally clause (which then is to be executed next) is found.
21501 * In this case, make the ":return" pending for execution at the ":endtry".
21502 * Otherwise, return normally.
21504 idx = cleanup_conditionals(eap->cstack, 0, TRUE);
21505 if (idx >= 0)
21507 cstack->cs_pending[idx] = CSTP_RETURN;
21509 if (!is_cmd && !reanimate)
21510 /* A pending return again gets pending. "rettv" points to an
21511 * allocated variable with the rettv of the original ":return"'s
21512 * argument if present or is NULL else. */
21513 cstack->cs_rettv[idx] = rettv;
21514 else
21516 /* When undoing a return in order to make it pending, get the stored
21517 * return rettv. */
21518 if (reanimate)
21519 rettv = current_funccal->rettv;
21521 if (rettv != NULL)
21523 /* Store the value of the pending return. */
21524 if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL)
21525 *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv;
21526 else
21527 EMSG(_(e_outofmem));
21529 else
21530 cstack->cs_rettv[idx] = NULL;
21532 if (reanimate)
21534 /* The pending return value could be overwritten by a ":return"
21535 * without argument in a finally clause; reset the default
21536 * return value. */
21537 current_funccal->rettv->v_type = VAR_NUMBER;
21538 current_funccal->rettv->vval.v_number = 0;
21541 report_make_pending(CSTP_RETURN, rettv);
21543 else
21545 current_funccal->returned = TRUE;
21547 /* If the return is carried out now, store the return value. For
21548 * a return immediately after reanimation, the value is already
21549 * there. */
21550 if (!reanimate && rettv != NULL)
21552 clear_tv(current_funccal->rettv);
21553 *current_funccal->rettv = *(typval_T *)rettv;
21554 if (!is_cmd)
21555 vim_free(rettv);
21559 return idx < 0;
21563 * Free the variable with a pending return value.
21565 void
21566 discard_pending_return(rettv)
21567 void *rettv;
21569 free_tv((typval_T *)rettv);
21573 * Generate a return command for producing the value of "rettv". The result
21574 * is an allocated string. Used by report_pending() for verbose messages.
21576 char_u *
21577 get_return_cmd(rettv)
21578 void *rettv;
21580 char_u *s = NULL;
21581 char_u *tofree = NULL;
21582 char_u numbuf[NUMBUFLEN];
21584 if (rettv != NULL)
21585 s = echo_string((typval_T *)rettv, &tofree, numbuf, 0);
21586 if (s == NULL)
21587 s = (char_u *)"";
21589 STRCPY(IObuff, ":return ");
21590 STRNCPY(IObuff + 8, s, IOSIZE - 8);
21591 if (STRLEN(s) + 8 >= IOSIZE)
21592 STRCPY(IObuff + IOSIZE - 4, "...");
21593 vim_free(tofree);
21594 return vim_strsave(IObuff);
21598 * Get next function line.
21599 * Called by do_cmdline() to get the next line.
21600 * Returns allocated string, or NULL for end of function.
21602 /* ARGSUSED */
21603 char_u *
21604 get_func_line(c, cookie, indent)
21605 int c; /* not used */
21606 void *cookie;
21607 int indent; /* not used */
21609 funccall_T *fcp = (funccall_T *)cookie;
21610 ufunc_T *fp = fcp->func;
21611 char_u *retval;
21612 garray_T *gap; /* growarray with function lines */
21614 /* If breakpoints have been added/deleted need to check for it. */
21615 if (fcp->dbg_tick != debug_tick)
21617 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
21618 sourcing_lnum);
21619 fcp->dbg_tick = debug_tick;
21621 #ifdef FEAT_PROFILE
21622 if (do_profiling == PROF_YES)
21623 func_line_end(cookie);
21624 #endif
21626 gap = &fp->uf_lines;
21627 if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
21628 || fcp->returned)
21629 retval = NULL;
21630 else
21632 /* Skip NULL lines (continuation lines). */
21633 while (fcp->linenr < gap->ga_len
21634 && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL)
21635 ++fcp->linenr;
21636 if (fcp->linenr >= gap->ga_len)
21637 retval = NULL;
21638 else
21640 retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]);
21641 sourcing_lnum = fcp->linenr;
21642 #ifdef FEAT_PROFILE
21643 if (do_profiling == PROF_YES)
21644 func_line_start(cookie);
21645 #endif
21649 /* Did we encounter a breakpoint? */
21650 if (fcp->breakpoint != 0 && fcp->breakpoint <= sourcing_lnum)
21652 dbg_breakpoint(fp->uf_name, sourcing_lnum);
21653 /* Find next breakpoint. */
21654 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
21655 sourcing_lnum);
21656 fcp->dbg_tick = debug_tick;
21659 return retval;
21662 #if defined(FEAT_PROFILE) || defined(PROTO)
21664 * Called when starting to read a function line.
21665 * "sourcing_lnum" must be correct!
21666 * When skipping lines it may not actually be executed, but we won't find out
21667 * until later and we need to store the time now.
21669 void
21670 func_line_start(cookie)
21671 void *cookie;
21673 funccall_T *fcp = (funccall_T *)cookie;
21674 ufunc_T *fp = fcp->func;
21676 if (fp->uf_profiling && sourcing_lnum >= 1
21677 && sourcing_lnum <= fp->uf_lines.ga_len)
21679 fp->uf_tml_idx = sourcing_lnum - 1;
21680 /* Skip continuation lines. */
21681 while (fp->uf_tml_idx > 0 && FUNCLINE(fp, fp->uf_tml_idx) == NULL)
21682 --fp->uf_tml_idx;
21683 fp->uf_tml_execed = FALSE;
21684 profile_start(&fp->uf_tml_start);
21685 profile_zero(&fp->uf_tml_children);
21686 profile_get_wait(&fp->uf_tml_wait);
21691 * Called when actually executing a function line.
21693 void
21694 func_line_exec(cookie)
21695 void *cookie;
21697 funccall_T *fcp = (funccall_T *)cookie;
21698 ufunc_T *fp = fcp->func;
21700 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
21701 fp->uf_tml_execed = TRUE;
21705 * Called when done with a function line.
21707 void
21708 func_line_end(cookie)
21709 void *cookie;
21711 funccall_T *fcp = (funccall_T *)cookie;
21712 ufunc_T *fp = fcp->func;
21714 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
21716 if (fp->uf_tml_execed)
21718 ++fp->uf_tml_count[fp->uf_tml_idx];
21719 profile_end(&fp->uf_tml_start);
21720 profile_sub_wait(&fp->uf_tml_wait, &fp->uf_tml_start);
21721 profile_add(&fp->uf_tml_total[fp->uf_tml_idx], &fp->uf_tml_start);
21722 profile_self(&fp->uf_tml_self[fp->uf_tml_idx], &fp->uf_tml_start,
21723 &fp->uf_tml_children);
21725 fp->uf_tml_idx = -1;
21728 #endif
21731 * Return TRUE if the currently active function should be ended, because a
21732 * return was encountered or an error occurred. Used inside a ":while".
21735 func_has_ended(cookie)
21736 void *cookie;
21738 funccall_T *fcp = (funccall_T *)cookie;
21740 /* Ignore the "abort" flag if the abortion behavior has been changed due to
21741 * an error inside a try conditional. */
21742 return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
21743 || fcp->returned);
21747 * return TRUE if cookie indicates a function which "abort"s on errors.
21750 func_has_abort(cookie)
21751 void *cookie;
21753 return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT;
21756 #if defined(FEAT_VIMINFO) || defined(FEAT_SESSION)
21757 typedef enum
21759 VAR_FLAVOUR_DEFAULT, /* doesn't start with uppercase */
21760 VAR_FLAVOUR_SESSION, /* starts with uppercase, some lower */
21761 VAR_FLAVOUR_VIMINFO /* all uppercase */
21762 } var_flavour_T;
21764 static var_flavour_T var_flavour __ARGS((char_u *varname));
21766 static var_flavour_T
21767 var_flavour(varname)
21768 char_u *varname;
21770 char_u *p = varname;
21772 if (ASCII_ISUPPER(*p))
21774 while (*(++p))
21775 if (ASCII_ISLOWER(*p))
21776 return VAR_FLAVOUR_SESSION;
21777 return VAR_FLAVOUR_VIMINFO;
21779 else
21780 return VAR_FLAVOUR_DEFAULT;
21782 #endif
21784 #if defined(FEAT_VIMINFO) || defined(PROTO)
21786 * Restore global vars that start with a capital from the viminfo file
21789 read_viminfo_varlist(virp, writing)
21790 vir_T *virp;
21791 int writing;
21793 char_u *tab;
21794 int type = VAR_NUMBER;
21795 typval_T tv;
21797 if (!writing && (find_viminfo_parameter('!') != NULL))
21799 tab = vim_strchr(virp->vir_line + 1, '\t');
21800 if (tab != NULL)
21802 *tab++ = '\0'; /* isolate the variable name */
21803 if (*tab == 'S') /* string var */
21804 type = VAR_STRING;
21805 #ifdef FEAT_FLOAT
21806 else if (*tab == 'F')
21807 type = VAR_FLOAT;
21808 #endif
21810 tab = vim_strchr(tab, '\t');
21811 if (tab != NULL)
21813 tv.v_type = type;
21814 if (type == VAR_STRING)
21815 tv.vval.v_string = viminfo_readstring(virp,
21816 (int)(tab - virp->vir_line + 1), TRUE);
21817 #ifdef FEAT_FLOAT
21818 else if (type == VAR_FLOAT)
21819 (void)string2float(tab + 1, &tv.vval.v_float);
21820 #endif
21821 else
21822 tv.vval.v_number = atol((char *)tab + 1);
21823 set_var(virp->vir_line + 1, &tv, FALSE);
21824 if (type == VAR_STRING)
21825 vim_free(tv.vval.v_string);
21830 return viminfo_readline(virp);
21834 * Write global vars that start with a capital to the viminfo file
21836 void
21837 write_viminfo_varlist(fp)
21838 FILE *fp;
21840 hashitem_T *hi;
21841 dictitem_T *this_var;
21842 int todo;
21843 char *s;
21844 char_u *p;
21845 char_u *tofree;
21846 char_u numbuf[NUMBUFLEN];
21848 if (find_viminfo_parameter('!') == NULL)
21849 return;
21851 fprintf(fp, _("\n# global variables:\n"));
21853 todo = (int)globvarht.ht_used;
21854 for (hi = globvarht.ht_array; todo > 0; ++hi)
21856 if (!HASHITEM_EMPTY(hi))
21858 --todo;
21859 this_var = HI2DI(hi);
21860 if (var_flavour(this_var->di_key) == VAR_FLAVOUR_VIMINFO)
21862 switch (this_var->di_tv.v_type)
21864 case VAR_STRING: s = "STR"; break;
21865 case VAR_NUMBER: s = "NUM"; break;
21866 #ifdef FEAT_FLOAT
21867 case VAR_FLOAT: s = "FLO"; break;
21868 #endif
21869 default: continue;
21871 fprintf(fp, "!%s\t%s\t", this_var->di_key, s);
21872 p = echo_string(&this_var->di_tv, &tofree, numbuf, 0);
21873 if (p != NULL)
21874 viminfo_writestring(fp, p);
21875 vim_free(tofree);
21880 #endif
21882 #if defined(FEAT_SESSION) || defined(PROTO)
21884 store_session_globals(fd)
21885 FILE *fd;
21887 hashitem_T *hi;
21888 dictitem_T *this_var;
21889 int todo;
21890 char_u *p, *t;
21892 todo = (int)globvarht.ht_used;
21893 for (hi = globvarht.ht_array; todo > 0; ++hi)
21895 if (!HASHITEM_EMPTY(hi))
21897 --todo;
21898 this_var = HI2DI(hi);
21899 if ((this_var->di_tv.v_type == VAR_NUMBER
21900 || this_var->di_tv.v_type == VAR_STRING)
21901 && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
21903 /* Escape special characters with a backslash. Turn a LF and
21904 * CR into \n and \r. */
21905 p = vim_strsave_escaped(get_tv_string(&this_var->di_tv),
21906 (char_u *)"\\\"\n\r");
21907 if (p == NULL) /* out of memory */
21908 break;
21909 for (t = p; *t != NUL; ++t)
21910 if (*t == '\n')
21911 *t = 'n';
21912 else if (*t == '\r')
21913 *t = 'r';
21914 if ((fprintf(fd, "let %s = %c%s%c",
21915 this_var->di_key,
21916 (this_var->di_tv.v_type == VAR_STRING) ? '"'
21917 : ' ',
21919 (this_var->di_tv.v_type == VAR_STRING) ? '"'
21920 : ' ') < 0)
21921 || put_eol(fd) == FAIL)
21923 vim_free(p);
21924 return FAIL;
21926 vim_free(p);
21928 #ifdef FEAT_FLOAT
21929 else if (this_var->di_tv.v_type == VAR_FLOAT
21930 && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
21932 float_T f = this_var->di_tv.vval.v_float;
21933 int sign = ' ';
21935 if (f < 0)
21937 f = -f;
21938 sign = '-';
21940 if ((fprintf(fd, "let %s = %c&%f",
21941 this_var->di_key, sign, f) < 0)
21942 || put_eol(fd) == FAIL)
21943 return FAIL;
21945 #endif
21948 return OK;
21950 #endif
21953 * Display script name where an item was last set.
21954 * Should only be invoked when 'verbose' is non-zero.
21956 void
21957 last_set_msg(scriptID)
21958 scid_T scriptID;
21960 char_u *p;
21962 if (scriptID != 0)
21964 p = home_replace_save(NULL, get_scriptname(scriptID));
21965 if (p != NULL)
21967 verbose_enter();
21968 MSG_PUTS(_("\n\tLast set from "));
21969 MSG_PUTS(p);
21970 vim_free(p);
21971 verbose_leave();
21977 * List v:oldfiles in a nice way.
21979 /*ARGSUSED*/
21980 void
21981 ex_oldfiles(eap)
21982 exarg_T *eap;
21984 list_T *l = vimvars[VV_OLDFILES].vv_list;
21985 listitem_T *li;
21986 int nr = 0;
21988 if (l == NULL)
21989 msg((char_u *)_("No old files"));
21990 else
21992 msg_start();
21993 msg_scroll = TRUE;
21994 for (li = l->lv_first; li != NULL && !got_int; li = li->li_next)
21996 msg_outnum((long)++nr);
21997 MSG_PUTS(": ");
21998 msg_outtrans(get_tv_string(&li->li_tv));
21999 msg_putchar('\n');
22000 out_flush(); /* output one line at a time */
22001 ui_breakcheck();
22003 /* Assume "got_int" was set to truncate the listing. */
22004 got_int = FALSE;
22006 #ifdef FEAT_BROWSE_CMD
22007 if (cmdmod.browse)
22009 quit_more = FALSE;
22010 nr = prompt_for_number(FALSE);
22011 msg_starthere();
22012 if (nr > 0)
22014 char_u *p = list_find_str(get_vim_var_list(VV_OLDFILES),
22015 (long)nr);
22017 if (p != NULL)
22019 p = expand_env_save(p);
22020 eap->arg = p;
22021 eap->cmdidx = CMD_edit;
22022 cmdmod.browse = FALSE;
22023 do_exedit(eap, NULL);
22024 vim_free(p);
22028 #endif
22032 #endif /* FEAT_EVAL */
22035 #if defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) || defined(PROTO)
22037 #ifdef WIN3264
22039 * Functions for ":8" filename modifier: get 8.3 version of a filename.
22041 static int get_short_pathname __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
22042 static int shortpath_for_invalid_fname __ARGS((char_u **fname, char_u **bufp, int *fnamelen));
22043 static int shortpath_for_partial __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
22046 * Get the short path (8.3) for the filename in "fnamep".
22047 * Only works for a valid file name.
22048 * When the path gets longer "fnamep" is changed and the allocated buffer
22049 * is put in "bufp".
22050 * *fnamelen is the length of "fnamep" and set to 0 for a nonexistent path.
22051 * Returns OK on success, FAIL on failure.
22053 static int
22054 get_short_pathname(fnamep, bufp, fnamelen)
22055 char_u **fnamep;
22056 char_u **bufp;
22057 int *fnamelen;
22059 int l, len;
22060 char_u *newbuf;
22062 len = *fnamelen;
22063 l = GetShortPathName(*fnamep, *fnamep, len);
22064 if (l > len - 1)
22066 /* If that doesn't work (not enough space), then save the string
22067 * and try again with a new buffer big enough. */
22068 newbuf = vim_strnsave(*fnamep, l);
22069 if (newbuf == NULL)
22070 return FAIL;
22072 vim_free(*bufp);
22073 *fnamep = *bufp = newbuf;
22075 /* Really should always succeed, as the buffer is big enough. */
22076 l = GetShortPathName(*fnamep, *fnamep, l+1);
22079 *fnamelen = l;
22080 return OK;
22084 * Get the short path (8.3) for the filename in "fname". The converted
22085 * path is returned in "bufp".
22087 * Some of the directories specified in "fname" may not exist. This function
22088 * will shorten the existing directories at the beginning of the path and then
22089 * append the remaining non-existing path.
22091 * fname - Pointer to the filename to shorten. On return, contains the
22092 * pointer to the shortened pathname
22093 * bufp - Pointer to an allocated buffer for the filename.
22094 * fnamelen - Length of the filename pointed to by fname
22096 * Returns OK on success (or nothing done) and FAIL on failure (out of memory).
22098 static int
22099 shortpath_for_invalid_fname(fname, bufp, fnamelen)
22100 char_u **fname;
22101 char_u **bufp;
22102 int *fnamelen;
22104 char_u *short_fname, *save_fname, *pbuf_unused;
22105 char_u *endp, *save_endp;
22106 char_u ch;
22107 int old_len, len;
22108 int new_len, sfx_len;
22109 int retval = OK;
22111 /* Make a copy */
22112 old_len = *fnamelen;
22113 save_fname = vim_strnsave(*fname, old_len);
22114 pbuf_unused = NULL;
22115 short_fname = NULL;
22117 endp = save_fname + old_len - 1; /* Find the end of the copy */
22118 save_endp = endp;
22121 * Try shortening the supplied path till it succeeds by removing one
22122 * directory at a time from the tail of the path.
22124 len = 0;
22125 for (;;)
22127 /* go back one path-separator */
22128 while (endp > save_fname && !after_pathsep(save_fname, endp + 1))
22129 --endp;
22130 if (endp <= save_fname)
22131 break; /* processed the complete path */
22134 * Replace the path separator with a NUL and try to shorten the
22135 * resulting path.
22137 ch = *endp;
22138 *endp = 0;
22139 short_fname = save_fname;
22140 len = (int)STRLEN(short_fname) + 1;
22141 if (get_short_pathname(&short_fname, &pbuf_unused, &len) == FAIL)
22143 retval = FAIL;
22144 goto theend;
22146 *endp = ch; /* preserve the string */
22148 if (len > 0)
22149 break; /* successfully shortened the path */
22151 /* failed to shorten the path. Skip the path separator */
22152 --endp;
22155 if (len > 0)
22158 * Succeeded in shortening the path. Now concatenate the shortened
22159 * path with the remaining path at the tail.
22162 /* Compute the length of the new path. */
22163 sfx_len = (int)(save_endp - endp) + 1;
22164 new_len = len + sfx_len;
22166 *fnamelen = new_len;
22167 vim_free(*bufp);
22168 if (new_len > old_len)
22170 /* There is not enough space in the currently allocated string,
22171 * copy it to a buffer big enough. */
22172 *fname = *bufp = vim_strnsave(short_fname, new_len);
22173 if (*fname == NULL)
22175 retval = FAIL;
22176 goto theend;
22179 else
22181 /* Transfer short_fname to the main buffer (it's big enough),
22182 * unless get_short_pathname() did its work in-place. */
22183 *fname = *bufp = save_fname;
22184 if (short_fname != save_fname)
22185 vim_strncpy(save_fname, short_fname, len);
22186 save_fname = NULL;
22189 /* concat the not-shortened part of the path */
22190 vim_strncpy(*fname + len, endp, sfx_len);
22191 (*fname)[new_len] = NUL;
22194 theend:
22195 vim_free(pbuf_unused);
22196 vim_free(save_fname);
22198 return retval;
22202 * Get a pathname for a partial path.
22203 * Returns OK for success, FAIL for failure.
22205 static int
22206 shortpath_for_partial(fnamep, bufp, fnamelen)
22207 char_u **fnamep;
22208 char_u **bufp;
22209 int *fnamelen;
22211 int sepcount, len, tflen;
22212 char_u *p;
22213 char_u *pbuf, *tfname;
22214 int hasTilde;
22216 /* Count up the path separators from the RHS.. so we know which part
22217 * of the path to return. */
22218 sepcount = 0;
22219 for (p = *fnamep; p < *fnamep + *fnamelen; mb_ptr_adv(p))
22220 if (vim_ispathsep(*p))
22221 ++sepcount;
22223 /* Need full path first (use expand_env() to remove a "~/") */
22224 hasTilde = (**fnamep == '~');
22225 if (hasTilde)
22226 pbuf = tfname = expand_env_save(*fnamep);
22227 else
22228 pbuf = tfname = FullName_save(*fnamep, FALSE);
22230 len = tflen = (int)STRLEN(tfname);
22232 if (get_short_pathname(&tfname, &pbuf, &len) == FAIL)
22233 return FAIL;
22235 if (len == 0)
22237 /* Don't have a valid filename, so shorten the rest of the
22238 * path if we can. This CAN give us invalid 8.3 filenames, but
22239 * there's not a lot of point in guessing what it might be.
22241 len = tflen;
22242 if (shortpath_for_invalid_fname(&tfname, &pbuf, &len) == FAIL)
22243 return FAIL;
22246 /* Count the paths backward to find the beginning of the desired string. */
22247 for (p = tfname + len - 1; p >= tfname; --p)
22249 #ifdef FEAT_MBYTE
22250 if (has_mbyte)
22251 p -= mb_head_off(tfname, p);
22252 #endif
22253 if (vim_ispathsep(*p))
22255 if (sepcount == 0 || (hasTilde && sepcount == 1))
22256 break;
22257 else
22258 sepcount --;
22261 if (hasTilde)
22263 --p;
22264 if (p >= tfname)
22265 *p = '~';
22266 else
22267 return FAIL;
22269 else
22270 ++p;
22272 /* Copy in the string - p indexes into tfname - allocated at pbuf */
22273 vim_free(*bufp);
22274 *fnamelen = (int)STRLEN(p);
22275 *bufp = pbuf;
22276 *fnamep = p;
22278 return OK;
22280 #endif /* WIN3264 */
22283 * Adjust a filename, according to a string of modifiers.
22284 * *fnamep must be NUL terminated when called. When returning, the length is
22285 * determined by *fnamelen.
22286 * Returns VALID_ flags or -1 for failure.
22287 * When there is an error, *fnamep is set to NULL.
22290 modify_fname(src, usedlen, fnamep, bufp, fnamelen)
22291 char_u *src; /* string with modifiers */
22292 int *usedlen; /* characters after src that are used */
22293 char_u **fnamep; /* file name so far */
22294 char_u **bufp; /* buffer for allocated file name or NULL */
22295 int *fnamelen; /* length of fnamep */
22297 int valid = 0;
22298 char_u *tail;
22299 char_u *s, *p, *pbuf;
22300 char_u dirname[MAXPATHL];
22301 int c;
22302 int has_fullname = 0;
22303 #ifdef WIN3264
22304 int has_shortname = 0;
22305 #endif
22307 repeat:
22308 /* ":p" - full path/file_name */
22309 if (src[*usedlen] == ':' && src[*usedlen + 1] == 'p')
22311 has_fullname = 1;
22313 valid |= VALID_PATH;
22314 *usedlen += 2;
22316 /* Expand "~/path" for all systems and "~user/path" for Unix and VMS */
22317 if ((*fnamep)[0] == '~'
22318 #if !defined(UNIX) && !(defined(VMS) && defined(USER_HOME))
22319 && ((*fnamep)[1] == '/'
22320 # ifdef BACKSLASH_IN_FILENAME
22321 || (*fnamep)[1] == '\\'
22322 # endif
22323 || (*fnamep)[1] == NUL)
22325 #endif
22328 *fnamep = expand_env_save(*fnamep);
22329 vim_free(*bufp); /* free any allocated file name */
22330 *bufp = *fnamep;
22331 if (*fnamep == NULL)
22332 return -1;
22335 /* When "/." or "/.." is used: force expansion to get rid of it. */
22336 for (p = *fnamep; *p != NUL; mb_ptr_adv(p))
22338 if (vim_ispathsep(*p)
22339 && p[1] == '.'
22340 && (p[2] == NUL
22341 || vim_ispathsep(p[2])
22342 || (p[2] == '.'
22343 && (p[3] == NUL || vim_ispathsep(p[3])))))
22344 break;
22347 /* FullName_save() is slow, don't use it when not needed. */
22348 if (*p != NUL || !vim_isAbsName(*fnamep))
22350 *fnamep = FullName_save(*fnamep, *p != NUL);
22351 vim_free(*bufp); /* free any allocated file name */
22352 *bufp = *fnamep;
22353 if (*fnamep == NULL)
22354 return -1;
22357 /* Append a path separator to a directory. */
22358 if (mch_isdir(*fnamep))
22360 /* Make room for one or two extra characters. */
22361 *fnamep = vim_strnsave(*fnamep, (int)STRLEN(*fnamep) + 2);
22362 vim_free(*bufp); /* free any allocated file name */
22363 *bufp = *fnamep;
22364 if (*fnamep == NULL)
22365 return -1;
22366 add_pathsep(*fnamep);
22370 /* ":." - path relative to the current directory */
22371 /* ":~" - path relative to the home directory */
22372 /* ":8" - shortname path - postponed till after */
22373 while (src[*usedlen] == ':'
22374 && ((c = src[*usedlen + 1]) == '.' || c == '~' || c == '8'))
22376 *usedlen += 2;
22377 if (c == '8')
22379 #ifdef WIN3264
22380 has_shortname = 1; /* Postpone this. */
22381 #endif
22382 continue;
22384 pbuf = NULL;
22385 /* Need full path first (use expand_env() to remove a "~/") */
22386 if (!has_fullname)
22388 if (c == '.' && **fnamep == '~')
22389 p = pbuf = expand_env_save(*fnamep);
22390 else
22391 p = pbuf = FullName_save(*fnamep, FALSE);
22393 else
22394 p = *fnamep;
22396 has_fullname = 0;
22398 if (p != NULL)
22400 if (c == '.')
22402 mch_dirname(dirname, MAXPATHL);
22403 s = shorten_fname(p, dirname);
22404 if (s != NULL)
22406 *fnamep = s;
22407 if (pbuf != NULL)
22409 vim_free(*bufp); /* free any allocated file name */
22410 *bufp = pbuf;
22411 pbuf = NULL;
22415 else
22417 home_replace(NULL, p, dirname, MAXPATHL, TRUE);
22418 /* Only replace it when it starts with '~' */
22419 if (*dirname == '~')
22421 s = vim_strsave(dirname);
22422 if (s != NULL)
22424 *fnamep = s;
22425 vim_free(*bufp);
22426 *bufp = s;
22430 vim_free(pbuf);
22434 tail = gettail(*fnamep);
22435 *fnamelen = (int)STRLEN(*fnamep);
22437 /* ":h" - head, remove "/file_name", can be repeated */
22438 /* Don't remove the first "/" or "c:\" */
22439 while (src[*usedlen] == ':' && src[*usedlen + 1] == 'h')
22441 valid |= VALID_HEAD;
22442 *usedlen += 2;
22443 s = get_past_head(*fnamep);
22444 while (tail > s && after_pathsep(s, tail))
22445 mb_ptr_back(*fnamep, tail);
22446 *fnamelen = (int)(tail - *fnamep);
22447 #ifdef VMS
22448 if (*fnamelen > 0)
22449 *fnamelen += 1; /* the path separator is part of the path */
22450 #endif
22451 if (*fnamelen == 0)
22453 /* Result is empty. Turn it into "." to make ":cd %:h" work. */
22454 p = vim_strsave((char_u *)".");
22455 if (p == NULL)
22456 return -1;
22457 vim_free(*bufp);
22458 *bufp = *fnamep = tail = p;
22459 *fnamelen = 1;
22461 else
22463 while (tail > s && !after_pathsep(s, tail))
22464 mb_ptr_back(*fnamep, tail);
22468 /* ":8" - shortname */
22469 if (src[*usedlen] == ':' && src[*usedlen + 1] == '8')
22471 *usedlen += 2;
22472 #ifdef WIN3264
22473 has_shortname = 1;
22474 #endif
22477 #ifdef WIN3264
22478 /* Check shortname after we have done 'heads' and before we do 'tails'
22480 if (has_shortname)
22482 pbuf = NULL;
22483 /* Copy the string if it is shortened by :h */
22484 if (*fnamelen < (int)STRLEN(*fnamep))
22486 p = vim_strnsave(*fnamep, *fnamelen);
22487 if (p == 0)
22488 return -1;
22489 vim_free(*bufp);
22490 *bufp = *fnamep = p;
22493 /* Split into two implementations - makes it easier. First is where
22494 * there isn't a full name already, second is where there is.
22496 if (!has_fullname && !vim_isAbsName(*fnamep))
22498 if (shortpath_for_partial(fnamep, bufp, fnamelen) == FAIL)
22499 return -1;
22501 else
22503 int l;
22505 /* Simple case, already have the full-name
22506 * Nearly always shorter, so try first time. */
22507 l = *fnamelen;
22508 if (get_short_pathname(fnamep, bufp, &l) == FAIL)
22509 return -1;
22511 if (l == 0)
22513 /* Couldn't find the filename.. search the paths.
22515 l = *fnamelen;
22516 if (shortpath_for_invalid_fname(fnamep, bufp, &l) == FAIL)
22517 return -1;
22519 *fnamelen = l;
22522 #endif /* WIN3264 */
22524 /* ":t" - tail, just the basename */
22525 if (src[*usedlen] == ':' && src[*usedlen + 1] == 't')
22527 *usedlen += 2;
22528 *fnamelen -= (int)(tail - *fnamep);
22529 *fnamep = tail;
22532 /* ":e" - extension, can be repeated */
22533 /* ":r" - root, without extension, can be repeated */
22534 while (src[*usedlen] == ':'
22535 && (src[*usedlen + 1] == 'e' || src[*usedlen + 1] == 'r'))
22537 /* find a '.' in the tail:
22538 * - for second :e: before the current fname
22539 * - otherwise: The last '.'
22541 if (src[*usedlen + 1] == 'e' && *fnamep > tail)
22542 s = *fnamep - 2;
22543 else
22544 s = *fnamep + *fnamelen - 1;
22545 for ( ; s > tail; --s)
22546 if (s[0] == '.')
22547 break;
22548 if (src[*usedlen + 1] == 'e') /* :e */
22550 if (s > tail)
22552 *fnamelen += (int)(*fnamep - (s + 1));
22553 *fnamep = s + 1;
22554 #ifdef VMS
22555 /* cut version from the extension */
22556 s = *fnamep + *fnamelen - 1;
22557 for ( ; s > *fnamep; --s)
22558 if (s[0] == ';')
22559 break;
22560 if (s > *fnamep)
22561 *fnamelen = s - *fnamep;
22562 #endif
22564 else if (*fnamep <= tail)
22565 *fnamelen = 0;
22567 else /* :r */
22569 if (s > tail) /* remove one extension */
22570 *fnamelen = (int)(s - *fnamep);
22572 *usedlen += 2;
22575 /* ":s?pat?foo?" - substitute */
22576 /* ":gs?pat?foo?" - global substitute */
22577 if (src[*usedlen] == ':'
22578 && (src[*usedlen + 1] == 's'
22579 || (src[*usedlen + 1] == 'g' && src[*usedlen + 2] == 's')))
22581 char_u *str;
22582 char_u *pat;
22583 char_u *sub;
22584 int sep;
22585 char_u *flags;
22586 int didit = FALSE;
22588 flags = (char_u *)"";
22589 s = src + *usedlen + 2;
22590 if (src[*usedlen + 1] == 'g')
22592 flags = (char_u *)"g";
22593 ++s;
22596 sep = *s++;
22597 if (sep)
22599 /* find end of pattern */
22600 p = vim_strchr(s, sep);
22601 if (p != NULL)
22603 pat = vim_strnsave(s, (int)(p - s));
22604 if (pat != NULL)
22606 s = p + 1;
22607 /* find end of substitution */
22608 p = vim_strchr(s, sep);
22609 if (p != NULL)
22611 sub = vim_strnsave(s, (int)(p - s));
22612 str = vim_strnsave(*fnamep, *fnamelen);
22613 if (sub != NULL && str != NULL)
22615 *usedlen = (int)(p + 1 - src);
22616 s = do_string_sub(str, pat, sub, flags);
22617 if (s != NULL)
22619 *fnamep = s;
22620 *fnamelen = (int)STRLEN(s);
22621 vim_free(*bufp);
22622 *bufp = s;
22623 didit = TRUE;
22626 vim_free(sub);
22627 vim_free(str);
22629 vim_free(pat);
22632 /* after using ":s", repeat all the modifiers */
22633 if (didit)
22634 goto repeat;
22638 return valid;
22642 * Perform a substitution on "str" with pattern "pat" and substitute "sub".
22643 * "flags" can be "g" to do a global substitute.
22644 * Returns an allocated string, NULL for error.
22646 char_u *
22647 do_string_sub(str, pat, sub, flags)
22648 char_u *str;
22649 char_u *pat;
22650 char_u *sub;
22651 char_u *flags;
22653 int sublen;
22654 regmatch_T regmatch;
22655 int i;
22656 int do_all;
22657 char_u *tail;
22658 garray_T ga;
22659 char_u *ret;
22660 char_u *save_cpo;
22662 /* Make 'cpoptions' empty, so that the 'l' flag doesn't work here */
22663 save_cpo = p_cpo;
22664 p_cpo = empty_option;
22666 ga_init2(&ga, 1, 200);
22668 do_all = (flags[0] == 'g');
22670 regmatch.rm_ic = p_ic;
22671 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
22672 if (regmatch.regprog != NULL)
22674 tail = str;
22675 while (vim_regexec_nl(&regmatch, str, (colnr_T)(tail - str)))
22678 * Get some space for a temporary buffer to do the substitution
22679 * into. It will contain:
22680 * - The text up to where the match is.
22681 * - The substituted text.
22682 * - The text after the match.
22684 sublen = vim_regsub(&regmatch, sub, tail, FALSE, TRUE, FALSE);
22685 if (ga_grow(&ga, (int)(STRLEN(tail) + sublen -
22686 (regmatch.endp[0] - regmatch.startp[0]))) == FAIL)
22688 ga_clear(&ga);
22689 break;
22692 /* copy the text up to where the match is */
22693 i = (int)(regmatch.startp[0] - tail);
22694 mch_memmove((char_u *)ga.ga_data + ga.ga_len, tail, (size_t)i);
22695 /* add the substituted text */
22696 (void)vim_regsub(&regmatch, sub, (char_u *)ga.ga_data
22697 + ga.ga_len + i, TRUE, TRUE, FALSE);
22698 ga.ga_len += i + sublen - 1;
22699 /* avoid getting stuck on a match with an empty string */
22700 if (tail == regmatch.endp[0])
22702 if (*tail == NUL)
22703 break;
22704 *((char_u *)ga.ga_data + ga.ga_len) = *tail++;
22705 ++ga.ga_len;
22707 else
22709 tail = regmatch.endp[0];
22710 if (*tail == NUL)
22711 break;
22713 if (!do_all)
22714 break;
22717 if (ga.ga_data != NULL)
22718 STRCPY((char *)ga.ga_data + ga.ga_len, tail);
22720 vim_free(regmatch.regprog);
22723 ret = vim_strsave(ga.ga_data == NULL ? str : (char_u *)ga.ga_data);
22724 ga_clear(&ga);
22725 if (p_cpo == empty_option)
22726 p_cpo = save_cpo;
22727 else
22728 /* Darn, evaluating {sub} expression changed the value. */
22729 free_string_option(save_cpo);
22731 return ret;
22734 #endif /* defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) */