Merged from the latest developing branch.
[MacVim/KaoriYa.git] / src / eval.c
blob00e199fba3387000ab629252201d53443e2b6036
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 */
35 #define DO_NOT_FREE_CNT 99999 /* refcount for dict or list that should not
36 be freed. */
39 * In a hashtab item "hi_key" points to "di_key" in a dictitem.
40 * This avoids adding a pointer to the hashtab item.
41 * DI2HIKEY() converts a dictitem pointer to a hashitem key pointer.
42 * HIKEY2DI() converts a hashitem key pointer to a dictitem pointer.
43 * HI2DI() converts a hashitem pointer to a dictitem pointer.
45 static dictitem_T dumdi;
46 #define DI2HIKEY(di) ((di)->di_key)
47 #define HIKEY2DI(p) ((dictitem_T *)(p - (dumdi.di_key - (char_u *)&dumdi)))
48 #define HI2DI(hi) HIKEY2DI((hi)->hi_key)
51 * Structure returned by get_lval() and used by set_var_lval().
52 * For a plain name:
53 * "name" points to the variable name.
54 * "exp_name" is NULL.
55 * "tv" is NULL
56 * For a magic braces name:
57 * "name" points to the expanded variable name.
58 * "exp_name" is non-NULL, to be freed later.
59 * "tv" is NULL
60 * For an index in a list:
61 * "name" points to the (expanded) variable name.
62 * "exp_name" NULL or non-NULL, to be freed later.
63 * "tv" points to the (first) list item value
64 * "li" points to the (first) list item
65 * "range", "n1", "n2" and "empty2" indicate what items are used.
66 * For an existing Dict item:
67 * "name" points to the (expanded) variable name.
68 * "exp_name" NULL or non-NULL, to be freed later.
69 * "tv" points to the dict item value
70 * "newkey" is NULL
71 * For a non-existing Dict item:
72 * "name" points to the (expanded) variable name.
73 * "exp_name" NULL or non-NULL, to be freed later.
74 * "tv" points to the Dictionary typval_T
75 * "newkey" is the key for the new item.
77 typedef struct lval_S
79 char_u *ll_name; /* start of variable name (can be NULL) */
80 char_u *ll_exp_name; /* NULL or expanded name in allocated memory. */
81 typval_T *ll_tv; /* Typeval of item being used. If "newkey"
82 isn't NULL it's the Dict to which to add
83 the item. */
84 listitem_T *ll_li; /* The list item or NULL. */
85 list_T *ll_list; /* The list or NULL. */
86 int ll_range; /* TRUE when a [i:j] range was used */
87 long ll_n1; /* First index for list */
88 long ll_n2; /* Second index for list range */
89 int ll_empty2; /* Second index is empty: [i:] */
90 dict_T *ll_dict; /* The Dictionary or NULL */
91 dictitem_T *ll_di; /* The dictitem or NULL */
92 char_u *ll_newkey; /* New key for Dict in alloc. mem or NULL. */
93 } lval_T;
96 static char *e_letunexp = N_("E18: Unexpected characters in :let");
97 static char *e_listidx = N_("E684: list index out of range: %ld");
98 static char *e_undefvar = N_("E121: Undefined variable: %s");
99 static char *e_missbrac = N_("E111: Missing ']'");
100 static char *e_listarg = N_("E686: Argument of %s must be a List");
101 static char *e_listdictarg = N_("E712: Argument of %s must be a List or Dictionary");
102 static char *e_emptykey = N_("E713: Cannot use empty key for Dictionary");
103 static char *e_listreq = N_("E714: List required");
104 static char *e_dictreq = N_("E715: Dictionary required");
105 static char *e_toomanyarg = N_("E118: Too many arguments for function: %s");
106 static char *e_dictkey = N_("E716: Key not present in Dictionary: %s");
107 static char *e_funcexts = N_("E122: Function %s already exists, add ! to replace it");
108 static char *e_funcdict = N_("E717: Dictionary entry already exists");
109 static char *e_funcref = N_("E718: Funcref required");
110 static char *e_dictrange = N_("E719: Cannot use [:] with a Dictionary");
111 static char *e_letwrong = N_("E734: Wrong variable type for %s=");
112 static char *e_nofunc = N_("E130: Unknown function: %s");
113 static char *e_illvar = N_("E461: Illegal variable name: %s");
116 * All user-defined global variables are stored in dictionary "globvardict".
117 * "globvars_var" is the variable that is used for "g:".
119 static dict_T globvardict;
120 static dictitem_T globvars_var;
121 #define globvarht globvardict.dv_hashtab
124 * Old Vim variables such as "v:version" are also available without the "v:".
125 * Also in functions. We need a special hashtable for them.
127 static hashtab_T compat_hashtab;
130 * When recursively copying lists and dicts we need to remember which ones we
131 * have done to avoid endless recursiveness. This unique ID is used for that.
133 static int current_copyID = 0;
136 * Array to hold the hashtab with variables local to each sourced script.
137 * Each item holds a variable (nameless) that points to the dict_T.
139 typedef struct
141 dictitem_T sv_var;
142 dict_T sv_dict;
143 } scriptvar_T;
145 static garray_T ga_scripts = {0, 0, sizeof(scriptvar_T), 4, NULL};
146 #define SCRIPT_SV(id) (((scriptvar_T *)ga_scripts.ga_data)[(id) - 1])
147 #define SCRIPT_VARS(id) (SCRIPT_SV(id).sv_dict.dv_hashtab)
149 static int echo_attr = 0; /* attributes used for ":echo" */
151 /* Values for trans_function_name() argument: */
152 #define TFN_INT 1 /* internal function name OK */
153 #define TFN_QUIET 2 /* no error messages */
156 * Structure to hold info for a user function.
158 typedef struct ufunc ufunc_T;
160 struct ufunc
162 int uf_varargs; /* variable nr of arguments */
163 int uf_flags;
164 int uf_calls; /* nr of active calls */
165 garray_T uf_args; /* arguments */
166 garray_T uf_lines; /* function lines */
167 #ifdef FEAT_PROFILE
168 int uf_profiling; /* TRUE when func is being profiled */
169 /* profiling the function as a whole */
170 int uf_tm_count; /* nr of calls */
171 proftime_T uf_tm_total; /* time spent in function + children */
172 proftime_T uf_tm_self; /* time spent in function itself */
173 proftime_T uf_tm_children; /* time spent in children this call */
174 /* profiling the function per line */
175 int *uf_tml_count; /* nr of times line was executed */
176 proftime_T *uf_tml_total; /* time spent in a line + children */
177 proftime_T *uf_tml_self; /* time spent in a line itself */
178 proftime_T uf_tml_start; /* start time for current line */
179 proftime_T uf_tml_children; /* time spent in children for this line */
180 proftime_T uf_tml_wait; /* start wait time for current line */
181 int uf_tml_idx; /* index of line being timed; -1 if none */
182 int uf_tml_execed; /* line being timed was executed */
183 #endif
184 scid_T uf_script_ID; /* ID of script where function was defined,
185 used for s: variables */
186 int uf_refcount; /* for numbered function: reference count */
187 char_u uf_name[1]; /* name of function (actually longer); can
188 start with <SNR>123_ (<SNR> is K_SPECIAL
189 KS_EXTRA KE_SNR) */
192 /* function flags */
193 #define FC_ABORT 1 /* abort function on error */
194 #define FC_RANGE 2 /* function accepts range */
195 #define FC_DICT 4 /* Dict function, uses "self" */
198 * All user-defined functions are found in this hashtable.
200 static hashtab_T func_hashtab;
202 /* The names of packages that once were loaded are remembered. */
203 static garray_T ga_loaded = {0, 0, sizeof(char_u *), 4, NULL};
205 /* list heads for garbage collection */
206 static dict_T *first_dict = NULL; /* list of all dicts */
207 static list_T *first_list = NULL; /* list of all lists */
209 /* From user function to hashitem and back. */
210 static ufunc_T dumuf;
211 #define UF2HIKEY(fp) ((fp)->uf_name)
212 #define HIKEY2UF(p) ((ufunc_T *)(p - (dumuf.uf_name - (char_u *)&dumuf)))
213 #define HI2UF(hi) HIKEY2UF((hi)->hi_key)
215 #define FUNCARG(fp, j) ((char_u **)(fp->uf_args.ga_data))[j]
216 #define FUNCLINE(fp, j) ((char_u **)(fp->uf_lines.ga_data))[j]
218 #define MAX_FUNC_ARGS 20 /* maximum number of function arguments */
219 #define VAR_SHORT_LEN 20 /* short variable name length */
220 #define FIXVAR_CNT 12 /* number of fixed variables */
222 /* structure to hold info for a function that is currently being executed. */
223 typedef struct funccall_S funccall_T;
225 struct funccall_S
227 ufunc_T *func; /* function being called */
228 int linenr; /* next line to be executed */
229 int returned; /* ":return" used */
230 struct /* fixed variables for arguments */
232 dictitem_T var; /* variable (without room for name) */
233 char_u room[VAR_SHORT_LEN]; /* room for the name */
234 } fixvar[FIXVAR_CNT];
235 dict_T l_vars; /* l: local function variables */
236 dictitem_T l_vars_var; /* variable for l: scope */
237 dict_T l_avars; /* a: argument variables */
238 dictitem_T l_avars_var; /* variable for a: scope */
239 list_T l_varlist; /* list for a:000 */
240 listitem_T l_listitems[MAX_FUNC_ARGS]; /* listitems for a:000 */
241 typval_T *rettv; /* return value */
242 linenr_T breakpoint; /* next line with breakpoint or zero */
243 int dbg_tick; /* debug_tick when breakpoint was set */
244 int level; /* top nesting level of executed function */
245 #ifdef FEAT_PROFILE
246 proftime_T prof_child; /* time spent in a child */
247 #endif
248 funccall_T *caller; /* calling function or NULL */
252 * Info used by a ":for" loop.
254 typedef struct
256 int fi_semicolon; /* TRUE if ending in '; var]' */
257 int fi_varcount; /* nr of variables in the list */
258 listwatch_T fi_lw; /* keep an eye on the item used. */
259 list_T *fi_list; /* list being used */
260 } forinfo_T;
263 * Struct used by trans_function_name()
265 typedef struct
267 dict_T *fd_dict; /* Dictionary used */
268 char_u *fd_newkey; /* new key in "dict" in allocated memory */
269 dictitem_T *fd_di; /* Dictionary item used */
270 } funcdict_T;
274 * Array to hold the value of v: variables.
275 * The value is in a dictitem, so that it can also be used in the v: scope.
276 * The reason to use this table anyway is for very quick access to the
277 * variables with the VV_ defines.
279 #include "version.h"
281 /* values for vv_flags: */
282 #define VV_COMPAT 1 /* compatible, also used without "v:" */
283 #define VV_RO 2 /* read-only */
284 #define VV_RO_SBX 4 /* read-only in the sandbox */
286 #define VV_NAME(s, t) s, {{t}}, {0}
288 static struct vimvar
290 char *vv_name; /* name of variable, without v: */
291 dictitem_T vv_di; /* value and name for key */
292 char vv_filler[16]; /* space for LONGEST name below!!! */
293 char vv_flags; /* VV_COMPAT, VV_RO, VV_RO_SBX */
294 } vimvars[VV_LEN] =
297 * The order here must match the VV_ defines in vim.h!
298 * Initializing a union does not work, leave tv.vval empty to get zero's.
300 {VV_NAME("count", VAR_NUMBER), VV_COMPAT+VV_RO},
301 {VV_NAME("count1", VAR_NUMBER), VV_RO},
302 {VV_NAME("prevcount", VAR_NUMBER), VV_RO},
303 {VV_NAME("errmsg", VAR_STRING), VV_COMPAT},
304 {VV_NAME("warningmsg", VAR_STRING), 0},
305 {VV_NAME("statusmsg", VAR_STRING), 0},
306 {VV_NAME("shell_error", VAR_NUMBER), VV_COMPAT+VV_RO},
307 {VV_NAME("this_session", VAR_STRING), VV_COMPAT},
308 {VV_NAME("version", VAR_NUMBER), VV_COMPAT+VV_RO},
309 {VV_NAME("lnum", VAR_NUMBER), VV_RO_SBX},
310 {VV_NAME("termresponse", VAR_STRING), VV_RO},
311 {VV_NAME("fname", VAR_STRING), VV_RO},
312 {VV_NAME("lang", VAR_STRING), VV_RO},
313 {VV_NAME("lc_time", VAR_STRING), VV_RO},
314 {VV_NAME("ctype", VAR_STRING), VV_RO},
315 {VV_NAME("charconvert_from", VAR_STRING), VV_RO},
316 {VV_NAME("charconvert_to", VAR_STRING), VV_RO},
317 {VV_NAME("fname_in", VAR_STRING), VV_RO},
318 {VV_NAME("fname_out", VAR_STRING), VV_RO},
319 {VV_NAME("fname_new", VAR_STRING), VV_RO},
320 {VV_NAME("fname_diff", VAR_STRING), VV_RO},
321 {VV_NAME("cmdarg", VAR_STRING), VV_RO},
322 {VV_NAME("foldstart", VAR_NUMBER), VV_RO_SBX},
323 {VV_NAME("foldend", VAR_NUMBER), VV_RO_SBX},
324 {VV_NAME("folddashes", VAR_STRING), VV_RO_SBX},
325 {VV_NAME("foldlevel", VAR_NUMBER), VV_RO_SBX},
326 {VV_NAME("progname", VAR_STRING), VV_RO},
327 {VV_NAME("servername", VAR_STRING), VV_RO},
328 {VV_NAME("dying", VAR_NUMBER), VV_RO},
329 {VV_NAME("exception", VAR_STRING), VV_RO},
330 {VV_NAME("throwpoint", VAR_STRING), VV_RO},
331 {VV_NAME("register", VAR_STRING), VV_RO},
332 {VV_NAME("cmdbang", VAR_NUMBER), VV_RO},
333 {VV_NAME("insertmode", VAR_STRING), VV_RO},
334 {VV_NAME("val", VAR_UNKNOWN), VV_RO},
335 {VV_NAME("key", VAR_UNKNOWN), VV_RO},
336 {VV_NAME("profiling", VAR_NUMBER), VV_RO},
337 {VV_NAME("fcs_reason", VAR_STRING), VV_RO},
338 {VV_NAME("fcs_choice", VAR_STRING), 0},
339 {VV_NAME("beval_bufnr", VAR_NUMBER), VV_RO},
340 {VV_NAME("beval_winnr", VAR_NUMBER), VV_RO},
341 {VV_NAME("beval_lnum", VAR_NUMBER), VV_RO},
342 {VV_NAME("beval_col", VAR_NUMBER), VV_RO},
343 {VV_NAME("beval_text", VAR_STRING), VV_RO},
344 {VV_NAME("scrollstart", VAR_STRING), 0},
345 {VV_NAME("swapname", VAR_STRING), VV_RO},
346 {VV_NAME("swapchoice", VAR_STRING), 0},
347 {VV_NAME("swapcommand", VAR_STRING), VV_RO},
348 {VV_NAME("char", VAR_STRING), VV_RO},
349 {VV_NAME("mouse_win", VAR_NUMBER), 0},
350 {VV_NAME("mouse_lnum", VAR_NUMBER), 0},
351 {VV_NAME("mouse_col", VAR_NUMBER), 0},
352 {VV_NAME("operator", VAR_STRING), VV_RO},
353 {VV_NAME("searchforward", VAR_NUMBER), 0},
354 {VV_NAME("oldfiles", VAR_LIST), 0},
357 /* shorthand */
358 #define vv_type vv_di.di_tv.v_type
359 #define vv_nr vv_di.di_tv.vval.v_number
360 #define vv_float vv_di.di_tv.vval.v_float
361 #define vv_str vv_di.di_tv.vval.v_string
362 #define vv_list vv_di.di_tv.vval.v_list
363 #define vv_tv vv_di.di_tv
366 * The v: variables are stored in dictionary "vimvardict".
367 * "vimvars_var" is the variable that is used for the "l:" scope.
369 static dict_T vimvardict;
370 static dictitem_T vimvars_var;
371 #define vimvarht vimvardict.dv_hashtab
373 static void prepare_vimvar __ARGS((int idx, typval_T *save_tv));
374 static void restore_vimvar __ARGS((int idx, typval_T *save_tv));
375 #if defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)
376 static int call_vim_function __ARGS((char_u *func, int argc, char_u **argv, int safe, typval_T *rettv));
377 #endif
378 static int ex_let_vars __ARGS((char_u *arg, typval_T *tv, int copy, int semicolon, int var_count, char_u *nextchars));
379 static char_u *skip_var_list __ARGS((char_u *arg, int *var_count, int *semicolon));
380 static char_u *skip_var_one __ARGS((char_u *arg));
381 static void list_hashtable_vars __ARGS((hashtab_T *ht, char_u *prefix, int empty, int *first));
382 static void list_glob_vars __ARGS((int *first));
383 static void list_buf_vars __ARGS((int *first));
384 static void list_win_vars __ARGS((int *first));
385 #ifdef FEAT_WINDOWS
386 static void list_tab_vars __ARGS((int *first));
387 #endif
388 static void list_vim_vars __ARGS((int *first));
389 static void list_script_vars __ARGS((int *first));
390 static void list_func_vars __ARGS((int *first));
391 static char_u *list_arg_vars __ARGS((exarg_T *eap, char_u *arg, int *first));
392 static char_u *ex_let_one __ARGS((char_u *arg, typval_T *tv, int copy, char_u *endchars, char_u *op));
393 static int check_changedtick __ARGS((char_u *arg));
394 static char_u *get_lval __ARGS((char_u *name, typval_T *rettv, lval_T *lp, int unlet, int skip, int quiet, int fne_flags));
395 static void clear_lval __ARGS((lval_T *lp));
396 static void set_var_lval __ARGS((lval_T *lp, char_u *endp, typval_T *rettv, int copy, char_u *op));
397 static int tv_op __ARGS((typval_T *tv1, typval_T *tv2, char_u *op));
398 static void list_add_watch __ARGS((list_T *l, listwatch_T *lw));
399 static void list_rem_watch __ARGS((list_T *l, listwatch_T *lwrem));
400 static void list_fix_watch __ARGS((list_T *l, listitem_T *item));
401 static void ex_unletlock __ARGS((exarg_T *eap, char_u *argstart, int deep));
402 static int do_unlet_var __ARGS((lval_T *lp, char_u *name_end, int forceit));
403 static int do_lock_var __ARGS((lval_T *lp, char_u *name_end, int deep, int lock));
404 static void item_lock __ARGS((typval_T *tv, int deep, int lock));
405 static int tv_islocked __ARGS((typval_T *tv));
407 static int eval0 __ARGS((char_u *arg, typval_T *rettv, char_u **nextcmd, int evaluate));
408 static int eval1 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
409 static int eval2 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
410 static int eval3 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
411 static int eval4 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
412 static int eval5 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
413 static int eval6 __ARGS((char_u **arg, typval_T *rettv, int evaluate, int want_string));
414 static int eval7 __ARGS((char_u **arg, typval_T *rettv, int evaluate, int want_string));
416 static int eval_index __ARGS((char_u **arg, typval_T *rettv, int evaluate, int verbose));
417 static int get_option_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
418 static int get_string_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
419 static int get_lit_string_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
420 static int get_list_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
421 static int rettv_list_alloc __ARGS((typval_T *rettv));
422 static listitem_T *listitem_alloc __ARGS((void));
423 static void listitem_free __ARGS((listitem_T *item));
424 static void listitem_remove __ARGS((list_T *l, listitem_T *item));
425 static long list_len __ARGS((list_T *l));
426 static int list_equal __ARGS((list_T *l1, list_T *l2, int ic));
427 static int dict_equal __ARGS((dict_T *d1, dict_T *d2, int ic));
428 static int tv_equal __ARGS((typval_T *tv1, typval_T *tv2, int ic));
429 static listitem_T *list_find __ARGS((list_T *l, long n));
430 static long list_find_nr __ARGS((list_T *l, long idx, int *errorp));
431 static long list_idx_of_item __ARGS((list_T *l, listitem_T *item));
432 static void list_append __ARGS((list_T *l, listitem_T *item));
433 static int list_append_tv __ARGS((list_T *l, typval_T *tv));
434 static int list_append_number __ARGS((list_T *l, varnumber_T n));
435 static int list_insert_tv __ARGS((list_T *l, typval_T *tv, listitem_T *item));
436 static int list_extend __ARGS((list_T *l1, list_T *l2, listitem_T *bef));
437 static int list_concat __ARGS((list_T *l1, list_T *l2, typval_T *tv));
438 static list_T *list_copy __ARGS((list_T *orig, int deep, int copyID));
439 static void list_remove __ARGS((list_T *l, listitem_T *item, listitem_T *item2));
440 static char_u *list2string __ARGS((typval_T *tv, int copyID));
441 static int list_join __ARGS((garray_T *gap, list_T *l, char_u *sep, int echo, int copyID));
442 static void set_ref_in_ht __ARGS((hashtab_T *ht, int copyID));
443 static void set_ref_in_list __ARGS((list_T *l, int copyID));
444 static void set_ref_in_item __ARGS((typval_T *tv, int copyID));
445 static void dict_unref __ARGS((dict_T *d));
446 static void dict_free __ARGS((dict_T *d, int recurse));
447 static dictitem_T *dictitem_alloc __ARGS((char_u *key));
448 static dictitem_T *dictitem_copy __ARGS((dictitem_T *org));
449 static void dictitem_remove __ARGS((dict_T *dict, dictitem_T *item));
450 static void dictitem_free __ARGS((dictitem_T *item));
451 static dict_T *dict_copy __ARGS((dict_T *orig, int deep, int copyID));
452 static int dict_add __ARGS((dict_T *d, dictitem_T *item));
453 static long dict_len __ARGS((dict_T *d));
454 static dictitem_T *dict_find __ARGS((dict_T *d, char_u *key, int len));
455 static char_u *dict2string __ARGS((typval_T *tv, int copyID));
456 static int get_dict_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
457 static char_u *echo_string __ARGS((typval_T *tv, char_u **tofree, char_u *numbuf, int copyID));
458 static char_u *tv2string __ARGS((typval_T *tv, char_u **tofree, char_u *numbuf, int copyID));
459 static char_u *string_quote __ARGS((char_u *str, int function));
460 #ifdef FEAT_FLOAT
461 static int string2float __ARGS((char_u *text, float_T *value));
462 #endif
463 static int get_env_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
464 static int find_internal_func __ARGS((char_u *name));
465 static char_u *deref_func_name __ARGS((char_u *name, int *lenp));
466 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));
467 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));
468 static void emsg_funcname __ARGS((char *ermsg, char_u *name));
469 static int non_zero_arg __ARGS((typval_T *argvars));
471 #ifdef FEAT_FLOAT
472 static void f_abs __ARGS((typval_T *argvars, typval_T *rettv));
473 #endif
474 static void f_add __ARGS((typval_T *argvars, typval_T *rettv));
475 static void f_append __ARGS((typval_T *argvars, typval_T *rettv));
476 static void f_argc __ARGS((typval_T *argvars, typval_T *rettv));
477 static void f_argidx __ARGS((typval_T *argvars, typval_T *rettv));
478 static void f_argv __ARGS((typval_T *argvars, typval_T *rettv));
479 #ifdef FEAT_FLOAT
480 static void f_atan __ARGS((typval_T *argvars, typval_T *rettv));
481 #endif
482 static void f_browse __ARGS((typval_T *argvars, typval_T *rettv));
483 static void f_browsedir __ARGS((typval_T *argvars, typval_T *rettv));
484 static void f_bufexists __ARGS((typval_T *argvars, typval_T *rettv));
485 static void f_buflisted __ARGS((typval_T *argvars, typval_T *rettv));
486 static void f_bufloaded __ARGS((typval_T *argvars, typval_T *rettv));
487 static void f_bufname __ARGS((typval_T *argvars, typval_T *rettv));
488 static void f_bufnr __ARGS((typval_T *argvars, typval_T *rettv));
489 static void f_bufwinnr __ARGS((typval_T *argvars, typval_T *rettv));
490 static void f_byte2line __ARGS((typval_T *argvars, typval_T *rettv));
491 static void f_byteidx __ARGS((typval_T *argvars, typval_T *rettv));
492 static void f_call __ARGS((typval_T *argvars, typval_T *rettv));
493 #ifdef FEAT_FLOAT
494 static void f_ceil __ARGS((typval_T *argvars, typval_T *rettv));
495 #endif
496 static void f_changenr __ARGS((typval_T *argvars, typval_T *rettv));
497 static void f_char2nr __ARGS((typval_T *argvars, typval_T *rettv));
498 static void f_cindent __ARGS((typval_T *argvars, typval_T *rettv));
499 static void f_clearmatches __ARGS((typval_T *argvars, typval_T *rettv));
500 static void f_col __ARGS((typval_T *argvars, typval_T *rettv));
501 #if defined(FEAT_INS_EXPAND)
502 static void f_complete __ARGS((typval_T *argvars, typval_T *rettv));
503 static void f_complete_add __ARGS((typval_T *argvars, typval_T *rettv));
504 static void f_complete_check __ARGS((typval_T *argvars, typval_T *rettv));
505 #endif
506 static void f_confirm __ARGS((typval_T *argvars, typval_T *rettv));
507 static void f_copy __ARGS((typval_T *argvars, typval_T *rettv));
508 #ifdef FEAT_FLOAT
509 static void f_cos __ARGS((typval_T *argvars, typval_T *rettv));
510 #endif
511 static void f_count __ARGS((typval_T *argvars, typval_T *rettv));
512 static void f_cscope_connection __ARGS((typval_T *argvars, typval_T *rettv));
513 static void f_cursor __ARGS((typval_T *argsvars, typval_T *rettv));
514 static void f_deepcopy __ARGS((typval_T *argvars, typval_T *rettv));
515 static void f_delete __ARGS((typval_T *argvars, typval_T *rettv));
516 static void f_did_filetype __ARGS((typval_T *argvars, typval_T *rettv));
517 static void f_diff_filler __ARGS((typval_T *argvars, typval_T *rettv));
518 static void f_diff_hlID __ARGS((typval_T *argvars, typval_T *rettv));
519 static void f_empty __ARGS((typval_T *argvars, typval_T *rettv));
520 static void f_escape __ARGS((typval_T *argvars, typval_T *rettv));
521 static void f_eval __ARGS((typval_T *argvars, typval_T *rettv));
522 static void f_eventhandler __ARGS((typval_T *argvars, typval_T *rettv));
523 static void f_executable __ARGS((typval_T *argvars, typval_T *rettv));
524 static void f_exists __ARGS((typval_T *argvars, typval_T *rettv));
525 static void f_expand __ARGS((typval_T *argvars, typval_T *rettv));
526 static void f_extend __ARGS((typval_T *argvars, typval_T *rettv));
527 static void f_feedkeys __ARGS((typval_T *argvars, typval_T *rettv));
528 static void f_filereadable __ARGS((typval_T *argvars, typval_T *rettv));
529 static void f_filewritable __ARGS((typval_T *argvars, typval_T *rettv));
530 static void f_filter __ARGS((typval_T *argvars, typval_T *rettv));
531 static void f_finddir __ARGS((typval_T *argvars, typval_T *rettv));
532 static void f_findfile __ARGS((typval_T *argvars, typval_T *rettv));
533 #ifdef FEAT_FLOAT
534 static void f_float2nr __ARGS((typval_T *argvars, typval_T *rettv));
535 static void f_floor __ARGS((typval_T *argvars, typval_T *rettv));
536 #endif
537 static void f_fnameescape __ARGS((typval_T *argvars, typval_T *rettv));
538 static void f_fnamemodify __ARGS((typval_T *argvars, typval_T *rettv));
539 static void f_foldclosed __ARGS((typval_T *argvars, typval_T *rettv));
540 static void f_foldclosedend __ARGS((typval_T *argvars, typval_T *rettv));
541 static void f_foldlevel __ARGS((typval_T *argvars, typval_T *rettv));
542 static void f_foldtext __ARGS((typval_T *argvars, typval_T *rettv));
543 static void f_foldtextresult __ARGS((typval_T *argvars, typval_T *rettv));
544 static void f_foreground __ARGS((typval_T *argvars, typval_T *rettv));
545 static void f_function __ARGS((typval_T *argvars, typval_T *rettv));
546 static void f_garbagecollect __ARGS((typval_T *argvars, typval_T *rettv));
547 static void f_get __ARGS((typval_T *argvars, typval_T *rettv));
548 static void f_getbufline __ARGS((typval_T *argvars, typval_T *rettv));
549 static void f_getbufvar __ARGS((typval_T *argvars, typval_T *rettv));
550 static void f_getchar __ARGS((typval_T *argvars, typval_T *rettv));
551 static void f_getcharmod __ARGS((typval_T *argvars, typval_T *rettv));
552 static void f_getcmdline __ARGS((typval_T *argvars, typval_T *rettv));
553 static void f_getcmdpos __ARGS((typval_T *argvars, typval_T *rettv));
554 static void f_getcmdtype __ARGS((typval_T *argvars, typval_T *rettv));
555 static void f_getcwd __ARGS((typval_T *argvars, typval_T *rettv));
556 static void f_getfontname __ARGS((typval_T *argvars, typval_T *rettv));
557 static void f_getfperm __ARGS((typval_T *argvars, typval_T *rettv));
558 static void f_getfsize __ARGS((typval_T *argvars, typval_T *rettv));
559 static void f_getftime __ARGS((typval_T *argvars, typval_T *rettv));
560 static void f_getftype __ARGS((typval_T *argvars, typval_T *rettv));
561 static void f_getline __ARGS((typval_T *argvars, typval_T *rettv));
562 static void f_getmatches __ARGS((typval_T *argvars, typval_T *rettv));
563 static void f_getpid __ARGS((typval_T *argvars, typval_T *rettv));
564 static void f_getpos __ARGS((typval_T *argvars, typval_T *rettv));
565 static void f_getqflist __ARGS((typval_T *argvars, typval_T *rettv));
566 static void f_getreg __ARGS((typval_T *argvars, typval_T *rettv));
567 static void f_getregtype __ARGS((typval_T *argvars, typval_T *rettv));
568 static void f_gettabwinvar __ARGS((typval_T *argvars, typval_T *rettv));
569 static void f_getwinposx __ARGS((typval_T *argvars, typval_T *rettv));
570 static void f_getwinposy __ARGS((typval_T *argvars, typval_T *rettv));
571 static void f_getwinvar __ARGS((typval_T *argvars, typval_T *rettv));
572 static void f_glob __ARGS((typval_T *argvars, typval_T *rettv));
573 static void f_globpath __ARGS((typval_T *argvars, typval_T *rettv));
574 static void f_has __ARGS((typval_T *argvars, typval_T *rettv));
575 static void f_has_key __ARGS((typval_T *argvars, typval_T *rettv));
576 static void f_haslocaldir __ARGS((typval_T *argvars, typval_T *rettv));
577 static void f_hasmapto __ARGS((typval_T *argvars, typval_T *rettv));
578 static void f_histadd __ARGS((typval_T *argvars, typval_T *rettv));
579 static void f_histdel __ARGS((typval_T *argvars, typval_T *rettv));
580 static void f_histget __ARGS((typval_T *argvars, typval_T *rettv));
581 static void f_histnr __ARGS((typval_T *argvars, typval_T *rettv));
582 static void f_hlID __ARGS((typval_T *argvars, typval_T *rettv));
583 static void f_hlexists __ARGS((typval_T *argvars, typval_T *rettv));
584 static void f_hostname __ARGS((typval_T *argvars, typval_T *rettv));
585 static void f_iconv __ARGS((typval_T *argvars, typval_T *rettv));
586 static void f_indent __ARGS((typval_T *argvars, typval_T *rettv));
587 static void f_index __ARGS((typval_T *argvars, typval_T *rettv));
588 static void f_input __ARGS((typval_T *argvars, typval_T *rettv));
589 static void f_inputdialog __ARGS((typval_T *argvars, typval_T *rettv));
590 static void f_inputlist __ARGS((typval_T *argvars, typval_T *rettv));
591 static void f_inputrestore __ARGS((typval_T *argvars, typval_T *rettv));
592 static void f_inputsave __ARGS((typval_T *argvars, typval_T *rettv));
593 static void f_inputsecret __ARGS((typval_T *argvars, typval_T *rettv));
594 static void f_insert __ARGS((typval_T *argvars, typval_T *rettv));
595 static void f_isdirectory __ARGS((typval_T *argvars, typval_T *rettv));
596 static void f_islocked __ARGS((typval_T *argvars, typval_T *rettv));
597 static void f_items __ARGS((typval_T *argvars, typval_T *rettv));
598 static void f_join __ARGS((typval_T *argvars, typval_T *rettv));
599 static void f_keys __ARGS((typval_T *argvars, typval_T *rettv));
600 static void f_last_buffer_nr __ARGS((typval_T *argvars, typval_T *rettv));
601 static void f_len __ARGS((typval_T *argvars, typval_T *rettv));
602 static void f_libcall __ARGS((typval_T *argvars, typval_T *rettv));
603 static void f_libcallnr __ARGS((typval_T *argvars, typval_T *rettv));
604 static void f_line __ARGS((typval_T *argvars, typval_T *rettv));
605 static void f_line2byte __ARGS((typval_T *argvars, typval_T *rettv));
606 static void f_lispindent __ARGS((typval_T *argvars, typval_T *rettv));
607 static void f_localtime __ARGS((typval_T *argvars, typval_T *rettv));
608 #ifdef FEAT_FLOAT
609 static void f_log10 __ARGS((typval_T *argvars, typval_T *rettv));
610 #endif
611 static void f_map __ARGS((typval_T *argvars, typval_T *rettv));
612 static void f_maparg __ARGS((typval_T *argvars, typval_T *rettv));
613 static void f_mapcheck __ARGS((typval_T *argvars, typval_T *rettv));
614 static void f_match __ARGS((typval_T *argvars, typval_T *rettv));
615 static void f_matchadd __ARGS((typval_T *argvars, typval_T *rettv));
616 static void f_matcharg __ARGS((typval_T *argvars, typval_T *rettv));
617 static void f_matchdelete __ARGS((typval_T *argvars, typval_T *rettv));
618 static void f_matchend __ARGS((typval_T *argvars, typval_T *rettv));
619 static void f_matchlist __ARGS((typval_T *argvars, typval_T *rettv));
620 static void f_matchstr __ARGS((typval_T *argvars, typval_T *rettv));
621 static void f_max __ARGS((typval_T *argvars, typval_T *rettv));
622 static void f_min __ARGS((typval_T *argvars, typval_T *rettv));
623 #ifdef vim_mkdir
624 static void f_mkdir __ARGS((typval_T *argvars, typval_T *rettv));
625 #endif
626 static void f_mode __ARGS((typval_T *argvars, typval_T *rettv));
627 static void f_nextnonblank __ARGS((typval_T *argvars, typval_T *rettv));
628 static void f_nr2char __ARGS((typval_T *argvars, typval_T *rettv));
629 static void f_pathshorten __ARGS((typval_T *argvars, typval_T *rettv));
630 #ifdef FEAT_FLOAT
631 static void f_pow __ARGS((typval_T *argvars, typval_T *rettv));
632 #endif
633 static void f_prevnonblank __ARGS((typval_T *argvars, typval_T *rettv));
634 static void f_printf __ARGS((typval_T *argvars, typval_T *rettv));
635 static void f_pumvisible __ARGS((typval_T *argvars, typval_T *rettv));
636 static void f_range __ARGS((typval_T *argvars, typval_T *rettv));
637 static void f_readfile __ARGS((typval_T *argvars, typval_T *rettv));
638 static void f_reltime __ARGS((typval_T *argvars, typval_T *rettv));
639 static void f_reltimestr __ARGS((typval_T *argvars, typval_T *rettv));
640 static void f_remote_expr __ARGS((typval_T *argvars, typval_T *rettv));
641 static void f_remote_foreground __ARGS((typval_T *argvars, typval_T *rettv));
642 static void f_remote_peek __ARGS((typval_T *argvars, typval_T *rettv));
643 static void f_remote_read __ARGS((typval_T *argvars, typval_T *rettv));
644 static void f_remote_send __ARGS((typval_T *argvars, typval_T *rettv));
645 static void f_remove __ARGS((typval_T *argvars, typval_T *rettv));
646 static void f_rename __ARGS((typval_T *argvars, typval_T *rettv));
647 static void f_repeat __ARGS((typval_T *argvars, typval_T *rettv));
648 static void f_resolve __ARGS((typval_T *argvars, typval_T *rettv));
649 static void f_reverse __ARGS((typval_T *argvars, typval_T *rettv));
650 #ifdef FEAT_FLOAT
651 static void f_round __ARGS((typval_T *argvars, typval_T *rettv));
652 #endif
653 static void f_search __ARGS((typval_T *argvars, typval_T *rettv));
654 static void f_searchdecl __ARGS((typval_T *argvars, typval_T *rettv));
655 static void f_searchpair __ARGS((typval_T *argvars, typval_T *rettv));
656 static void f_searchpairpos __ARGS((typval_T *argvars, typval_T *rettv));
657 static void f_searchpos __ARGS((typval_T *argvars, typval_T *rettv));
658 static void f_server2client __ARGS((typval_T *argvars, typval_T *rettv));
659 static void f_serverlist __ARGS((typval_T *argvars, typval_T *rettv));
660 static void f_setbufvar __ARGS((typval_T *argvars, typval_T *rettv));
661 static void f_setcmdpos __ARGS((typval_T *argvars, typval_T *rettv));
662 static void f_setline __ARGS((typval_T *argvars, typval_T *rettv));
663 static void f_setloclist __ARGS((typval_T *argvars, typval_T *rettv));
664 static void f_setmatches __ARGS((typval_T *argvars, typval_T *rettv));
665 static void f_setpos __ARGS((typval_T *argvars, typval_T *rettv));
666 static void f_setqflist __ARGS((typval_T *argvars, typval_T *rettv));
667 static void f_setreg __ARGS((typval_T *argvars, typval_T *rettv));
668 static void f_settabwinvar __ARGS((typval_T *argvars, typval_T *rettv));
669 static void f_setwinvar __ARGS((typval_T *argvars, typval_T *rettv));
670 static void f_shellescape __ARGS((typval_T *argvars, typval_T *rettv));
671 static void f_simplify __ARGS((typval_T *argvars, typval_T *rettv));
672 #ifdef FEAT_FLOAT
673 static void f_sin __ARGS((typval_T *argvars, typval_T *rettv));
674 #endif
675 static void f_sort __ARGS((typval_T *argvars, typval_T *rettv));
676 static void f_soundfold __ARGS((typval_T *argvars, typval_T *rettv));
677 static void f_spellbadword __ARGS((typval_T *argvars, typval_T *rettv));
678 static void f_spellsuggest __ARGS((typval_T *argvars, typval_T *rettv));
679 static void f_split __ARGS((typval_T *argvars, typval_T *rettv));
680 #ifdef FEAT_FLOAT
681 static void f_sqrt __ARGS((typval_T *argvars, typval_T *rettv));
682 static void f_str2float __ARGS((typval_T *argvars, typval_T *rettv));
683 #endif
684 static void f_str2nr __ARGS((typval_T *argvars, typval_T *rettv));
685 #ifdef HAVE_STRFTIME
686 static void f_strftime __ARGS((typval_T *argvars, typval_T *rettv));
687 #endif
688 static void f_stridx __ARGS((typval_T *argvars, typval_T *rettv));
689 static void f_string __ARGS((typval_T *argvars, typval_T *rettv));
690 static void f_strlen __ARGS((typval_T *argvars, typval_T *rettv));
691 static void f_strpart __ARGS((typval_T *argvars, typval_T *rettv));
692 static void f_strridx __ARGS((typval_T *argvars, typval_T *rettv));
693 static void f_strtrans __ARGS((typval_T *argvars, typval_T *rettv));
694 static void f_submatch __ARGS((typval_T *argvars, typval_T *rettv));
695 static void f_substitute __ARGS((typval_T *argvars, typval_T *rettv));
696 static void f_synID __ARGS((typval_T *argvars, typval_T *rettv));
697 static void f_synIDattr __ARGS((typval_T *argvars, typval_T *rettv));
698 static void f_synIDtrans __ARGS((typval_T *argvars, typval_T *rettv));
699 static void f_synstack __ARGS((typval_T *argvars, typval_T *rettv));
700 static void f_system __ARGS((typval_T *argvars, typval_T *rettv));
701 static void f_tabpagebuflist __ARGS((typval_T *argvars, typval_T *rettv));
702 static void f_tabpagenr __ARGS((typval_T *argvars, typval_T *rettv));
703 static void f_tabpagewinnr __ARGS((typval_T *argvars, typval_T *rettv));
704 static void f_taglist __ARGS((typval_T *argvars, typval_T *rettv));
705 static void f_tagfiles __ARGS((typval_T *argvars, typval_T *rettv));
706 static void f_tempname __ARGS((typval_T *argvars, typval_T *rettv));
707 static void f_test __ARGS((typval_T *argvars, typval_T *rettv));
708 static void f_tolower __ARGS((typval_T *argvars, typval_T *rettv));
709 static void f_toupper __ARGS((typval_T *argvars, typval_T *rettv));
710 static void f_tr __ARGS((typval_T *argvars, typval_T *rettv));
711 #ifdef FEAT_FLOAT
712 static void f_trunc __ARGS((typval_T *argvars, typval_T *rettv));
713 #endif
714 static void f_type __ARGS((typval_T *argvars, typval_T *rettv));
715 static void f_values __ARGS((typval_T *argvars, typval_T *rettv));
716 static void f_virtcol __ARGS((typval_T *argvars, typval_T *rettv));
717 static void f_visualmode __ARGS((typval_T *argvars, typval_T *rettv));
718 static void f_winbufnr __ARGS((typval_T *argvars, typval_T *rettv));
719 static void f_wincol __ARGS((typval_T *argvars, typval_T *rettv));
720 static void f_winheight __ARGS((typval_T *argvars, typval_T *rettv));
721 static void f_winline __ARGS((typval_T *argvars, typval_T *rettv));
722 static void f_winnr __ARGS((typval_T *argvars, typval_T *rettv));
723 static void f_winrestcmd __ARGS((typval_T *argvars, typval_T *rettv));
724 static void f_winrestview __ARGS((typval_T *argvars, typval_T *rettv));
725 static void f_winsaveview __ARGS((typval_T *argvars, typval_T *rettv));
726 static void f_winwidth __ARGS((typval_T *argvars, typval_T *rettv));
727 static void f_writefile __ARGS((typval_T *argvars, typval_T *rettv));
729 static int list2fpos __ARGS((typval_T *arg, pos_T *posp, int *fnump));
730 static pos_T *var2fpos __ARGS((typval_T *varp, int dollar_lnum, int *fnum));
731 static int get_env_len __ARGS((char_u **arg));
732 static int get_id_len __ARGS((char_u **arg));
733 static int get_name_len __ARGS((char_u **arg, char_u **alias, int evaluate, int verbose));
734 static char_u *find_name_end __ARGS((char_u *arg, char_u **expr_start, char_u **expr_end, int flags));
735 #define FNE_INCL_BR 1 /* find_name_end(): include [] in name */
736 #define FNE_CHECK_START 2 /* find_name_end(): check name starts with
737 valid character */
738 static char_u * make_expanded_name __ARGS((char_u *in_start, char_u *expr_start, char_u *expr_end, char_u *in_end));
739 static int eval_isnamec __ARGS((int c));
740 static int eval_isnamec1 __ARGS((int c));
741 static int get_var_tv __ARGS((char_u *name, int len, typval_T *rettv, int verbose));
742 static int handle_subscript __ARGS((char_u **arg, typval_T *rettv, int evaluate, int verbose));
743 static typval_T *alloc_tv __ARGS((void));
744 static typval_T *alloc_string_tv __ARGS((char_u *string));
745 static void init_tv __ARGS((typval_T *varp));
746 static long get_tv_number __ARGS((typval_T *varp));
747 static linenr_T get_tv_lnum __ARGS((typval_T *argvars));
748 static linenr_T get_tv_lnum_buf __ARGS((typval_T *argvars, buf_T *buf));
749 static char_u *get_tv_string __ARGS((typval_T *varp));
750 static char_u *get_tv_string_buf __ARGS((typval_T *varp, char_u *buf));
751 static char_u *get_tv_string_buf_chk __ARGS((typval_T *varp, char_u *buf));
752 static dictitem_T *find_var __ARGS((char_u *name, hashtab_T **htp));
753 static dictitem_T *find_var_in_ht __ARGS((hashtab_T *ht, char_u *varname, int writing));
754 static hashtab_T *find_var_ht __ARGS((char_u *name, char_u **varname));
755 static void vars_clear_ext __ARGS((hashtab_T *ht, int free_val));
756 static void delete_var __ARGS((hashtab_T *ht, hashitem_T *hi));
757 static void list_one_var __ARGS((dictitem_T *v, char_u *prefix, int *first));
758 static void list_one_var_a __ARGS((char_u *prefix, char_u *name, int type, char_u *string, int *first));
759 static void set_var __ARGS((char_u *name, typval_T *varp, int copy));
760 static int var_check_ro __ARGS((int flags, char_u *name));
761 static int var_check_fixed __ARGS((int flags, char_u *name));
762 static int tv_check_lock __ARGS((int lock, char_u *name));
763 static void copy_tv __ARGS((typval_T *from, typval_T *to));
764 static int item_copy __ARGS((typval_T *from, typval_T *to, int deep, int copyID));
765 static char_u *find_option_end __ARGS((char_u **arg, int *opt_flags));
766 static char_u *trans_function_name __ARGS((char_u **pp, int skip, int flags, funcdict_T *fd));
767 static int eval_fname_script __ARGS((char_u *p));
768 static int eval_fname_sid __ARGS((char_u *p));
769 static void list_func_head __ARGS((ufunc_T *fp, int indent));
770 static ufunc_T *find_func __ARGS((char_u *name));
771 static int function_exists __ARGS((char_u *name));
772 static int builtin_function __ARGS((char_u *name));
773 #ifdef FEAT_PROFILE
774 static void func_do_profile __ARGS((ufunc_T *fp));
775 static void prof_sort_list __ARGS((FILE *fd, ufunc_T **sorttab, int st_len, char *title, int prefer_self));
776 static void prof_func_line __ARGS((FILE *fd, int count, proftime_T *total, proftime_T *self, int prefer_self));
777 static int
778 # ifdef __BORLANDC__
779 _RTLENTRYF
780 # endif
781 prof_total_cmp __ARGS((const void *s1, const void *s2));
782 static int
783 # ifdef __BORLANDC__
784 _RTLENTRYF
785 # endif
786 prof_self_cmp __ARGS((const void *s1, const void *s2));
787 #endif
788 static int script_autoload __ARGS((char_u *name, int reload));
789 static char_u *autoload_name __ARGS((char_u *name));
790 static void cat_func_name __ARGS((char_u *buf, ufunc_T *fp));
791 static void func_free __ARGS((ufunc_T *fp));
792 static void func_unref __ARGS((char_u *name));
793 static void func_ref __ARGS((char_u *name));
794 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));
795 static int can_free_funccal __ARGS((funccall_T *fc, int copyID)) ;
796 static void free_funccal __ARGS((funccall_T *fc, int free_val));
797 static void add_nr_var __ARGS((dict_T *dp, dictitem_T *v, char *name, varnumber_T nr));
798 static win_T *find_win_by_nr __ARGS((typval_T *vp, tabpage_T *tp));
799 static void getwinvar __ARGS((typval_T *argvars, typval_T *rettv, int off));
800 static int searchpair_cmn __ARGS((typval_T *argvars, pos_T *match_pos));
801 static int search_cmn __ARGS((typval_T *argvars, pos_T *match_pos, int *flagsp));
802 static void setwinvar __ARGS((typval_T *argvars, typval_T *rettv, int off));
804 /* Character used as separated in autoload function/variable names. */
805 #define AUTOLOAD_CHAR '#'
808 * Initialize the global and v: variables.
810 void
811 eval_init()
813 int i;
814 struct vimvar *p;
816 init_var_dict(&globvardict, &globvars_var);
817 init_var_dict(&vimvardict, &vimvars_var);
818 hash_init(&compat_hashtab);
819 hash_init(&func_hashtab);
821 for (i = 0; i < VV_LEN; ++i)
823 p = &vimvars[i];
824 STRCPY(p->vv_di.di_key, p->vv_name);
825 if (p->vv_flags & VV_RO)
826 p->vv_di.di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
827 else if (p->vv_flags & VV_RO_SBX)
828 p->vv_di.di_flags = DI_FLAGS_RO_SBX | DI_FLAGS_FIX;
829 else
830 p->vv_di.di_flags = DI_FLAGS_FIX;
832 /* add to v: scope dict, unless the value is not always available */
833 if (p->vv_type != VAR_UNKNOWN)
834 hash_add(&vimvarht, p->vv_di.di_key);
835 if (p->vv_flags & VV_COMPAT)
836 /* add to compat scope dict */
837 hash_add(&compat_hashtab, p->vv_di.di_key);
839 set_vim_var_nr(VV_SEARCHFORWARD, 1L);
842 #if defined(EXITFREE) || defined(PROTO)
843 void
844 eval_clear()
846 int i;
847 struct vimvar *p;
849 for (i = 0; i < VV_LEN; ++i)
851 p = &vimvars[i];
852 if (p->vv_di.di_tv.v_type == VAR_STRING)
854 vim_free(p->vv_str);
855 p->vv_str = NULL;
857 else if (p->vv_di.di_tv.v_type == VAR_LIST)
859 list_unref(p->vv_list);
860 p->vv_list = NULL;
863 hash_clear(&vimvarht);
864 hash_init(&vimvarht); /* garbage_collect() will access it */
865 hash_clear(&compat_hashtab);
867 /* script-local variables */
868 for (i = 1; i <= ga_scripts.ga_len; ++i)
869 vars_clear(&SCRIPT_VARS(i));
870 ga_clear(&ga_scripts);
871 free_scriptnames();
873 /* global variables */
874 vars_clear(&globvarht);
876 /* autoloaded script names */
877 ga_clear_strings(&ga_loaded);
879 /* unreferenced lists and dicts */
880 (void)garbage_collect();
882 /* functions */
883 free_all_functions();
884 hash_clear(&func_hashtab);
886 #endif
889 * Return the name of the executed function.
891 char_u *
892 func_name(cookie)
893 void *cookie;
895 return ((funccall_T *)cookie)->func->uf_name;
899 * Return the address holding the next breakpoint line for a funccall cookie.
901 linenr_T *
902 func_breakpoint(cookie)
903 void *cookie;
905 return &((funccall_T *)cookie)->breakpoint;
909 * Return the address holding the debug tick for a funccall cookie.
911 int *
912 func_dbg_tick(cookie)
913 void *cookie;
915 return &((funccall_T *)cookie)->dbg_tick;
919 * Return the nesting level for a funccall cookie.
922 func_level(cookie)
923 void *cookie;
925 return ((funccall_T *)cookie)->level;
928 /* pointer to funccal for currently active function */
929 funccall_T *current_funccal = NULL;
931 /* pointer to list of previously used funccal, still around because some
932 * item in it is still being used. */
933 funccall_T *previous_funccal = NULL;
936 * Return TRUE when a function was ended by a ":return" command.
939 current_func_returned()
941 return current_funccal->returned;
946 * Set an internal variable to a string value. Creates the variable if it does
947 * not already exist.
949 void
950 set_internal_string_var(name, value)
951 char_u *name;
952 char_u *value;
954 char_u *val;
955 typval_T *tvp;
957 val = vim_strsave(value);
958 if (val != NULL)
960 tvp = alloc_string_tv(val);
961 if (tvp != NULL)
963 set_var(name, tvp, FALSE);
964 free_tv(tvp);
969 static lval_T *redir_lval = NULL;
970 static garray_T redir_ga; /* only valid when redir_lval is not NULL */
971 static char_u *redir_endp = NULL;
972 static char_u *redir_varname = NULL;
975 * Start recording command output to a variable
976 * Returns OK if successfully completed the setup. FAIL otherwise.
979 var_redir_start(name, append)
980 char_u *name;
981 int append; /* append to an existing variable */
983 int save_emsg;
984 int err;
985 typval_T tv;
987 /* Make sure a valid variable name is specified */
988 if (!eval_isnamec1(*name))
990 EMSG(_(e_invarg));
991 return FAIL;
994 redir_varname = vim_strsave(name);
995 if (redir_varname == NULL)
996 return FAIL;
998 redir_lval = (lval_T *)alloc_clear((unsigned)sizeof(lval_T));
999 if (redir_lval == NULL)
1001 var_redir_stop();
1002 return FAIL;
1005 /* The output is stored in growarray "redir_ga" until redirection ends. */
1006 ga_init2(&redir_ga, (int)sizeof(char), 500);
1008 /* Parse the variable name (can be a dict or list entry). */
1009 redir_endp = get_lval(redir_varname, NULL, redir_lval, FALSE, FALSE, FALSE,
1010 FNE_CHECK_START);
1011 if (redir_endp == NULL || redir_lval->ll_name == NULL || *redir_endp != NUL)
1013 if (redir_endp != NULL && *redir_endp != NUL)
1014 /* Trailing characters are present after the variable name */
1015 EMSG(_(e_trailing));
1016 else
1017 EMSG(_(e_invarg));
1018 var_redir_stop();
1019 return FAIL;
1022 /* check if we can write to the variable: set it to or append an empty
1023 * string */
1024 save_emsg = did_emsg;
1025 did_emsg = FALSE;
1026 tv.v_type = VAR_STRING;
1027 tv.vval.v_string = (char_u *)"";
1028 if (append)
1029 set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)".");
1030 else
1031 set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)"=");
1032 err = did_emsg;
1033 did_emsg |= save_emsg;
1034 if (err)
1036 var_redir_stop();
1037 return FAIL;
1039 if (redir_lval->ll_newkey != NULL)
1041 /* Dictionary item was created, don't do it again. */
1042 vim_free(redir_lval->ll_newkey);
1043 redir_lval->ll_newkey = NULL;
1046 return OK;
1050 * Append "value[value_len]" to the variable set by var_redir_start().
1051 * The actual appending is postponed until redirection ends, because the value
1052 * appended may in fact be the string we write to, changing it may cause freed
1053 * memory to be used:
1054 * :redir => foo
1055 * :let foo
1056 * :redir END
1058 void
1059 var_redir_str(value, value_len)
1060 char_u *value;
1061 int value_len;
1063 int len;
1065 if (redir_lval == NULL)
1066 return;
1068 if (value_len == -1)
1069 len = (int)STRLEN(value); /* Append the entire string */
1070 else
1071 len = value_len; /* Append only "value_len" characters */
1073 if (ga_grow(&redir_ga, len) == OK)
1075 mch_memmove((char *)redir_ga.ga_data + redir_ga.ga_len, value, len);
1076 redir_ga.ga_len += len;
1078 else
1079 var_redir_stop();
1083 * Stop redirecting command output to a variable.
1085 void
1086 var_redir_stop()
1088 typval_T tv;
1090 if (redir_lval != NULL)
1092 /* Append the trailing NUL. */
1093 ga_append(&redir_ga, NUL);
1095 /* Assign the text to the variable. */
1096 tv.v_type = VAR_STRING;
1097 tv.vval.v_string = redir_ga.ga_data;
1098 set_var_lval(redir_lval, redir_endp, &tv, FALSE, (char_u *)".");
1099 vim_free(tv.vval.v_string);
1101 clear_lval(redir_lval);
1102 vim_free(redir_lval);
1103 redir_lval = NULL;
1105 vim_free(redir_varname);
1106 redir_varname = NULL;
1109 # if defined(FEAT_MBYTE) || defined(PROTO)
1111 eval_charconvert(enc_from, enc_to, fname_from, fname_to)
1112 char_u *enc_from;
1113 char_u *enc_to;
1114 char_u *fname_from;
1115 char_u *fname_to;
1117 int err = FALSE;
1119 set_vim_var_string(VV_CC_FROM, enc_from, -1);
1120 set_vim_var_string(VV_CC_TO, enc_to, -1);
1121 set_vim_var_string(VV_FNAME_IN, fname_from, -1);
1122 set_vim_var_string(VV_FNAME_OUT, fname_to, -1);
1123 if (eval_to_bool(p_ccv, &err, NULL, FALSE))
1124 err = TRUE;
1125 set_vim_var_string(VV_CC_FROM, NULL, -1);
1126 set_vim_var_string(VV_CC_TO, NULL, -1);
1127 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1128 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1130 if (err)
1131 return FAIL;
1132 return OK;
1134 # endif
1136 # if defined(FEAT_POSTSCRIPT) || defined(PROTO)
1138 eval_printexpr(fname, args)
1139 char_u *fname;
1140 char_u *args;
1142 int err = FALSE;
1144 set_vim_var_string(VV_FNAME_IN, fname, -1);
1145 set_vim_var_string(VV_CMDARG, args, -1);
1146 if (eval_to_bool(p_pexpr, &err, NULL, FALSE))
1147 err = TRUE;
1148 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1149 set_vim_var_string(VV_CMDARG, NULL, -1);
1151 if (err)
1153 mch_remove(fname);
1154 return FAIL;
1156 return OK;
1158 # endif
1160 # if defined(FEAT_DIFF) || defined(PROTO)
1161 void
1162 eval_diff(origfile, newfile, outfile)
1163 char_u *origfile;
1164 char_u *newfile;
1165 char_u *outfile;
1167 int err = FALSE;
1169 set_vim_var_string(VV_FNAME_IN, origfile, -1);
1170 set_vim_var_string(VV_FNAME_NEW, newfile, -1);
1171 set_vim_var_string(VV_FNAME_OUT, outfile, -1);
1172 (void)eval_to_bool(p_dex, &err, NULL, FALSE);
1173 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1174 set_vim_var_string(VV_FNAME_NEW, NULL, -1);
1175 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1178 void
1179 eval_patch(origfile, difffile, outfile)
1180 char_u *origfile;
1181 char_u *difffile;
1182 char_u *outfile;
1184 int err;
1186 set_vim_var_string(VV_FNAME_IN, origfile, -1);
1187 set_vim_var_string(VV_FNAME_DIFF, difffile, -1);
1188 set_vim_var_string(VV_FNAME_OUT, outfile, -1);
1189 (void)eval_to_bool(p_pex, &err, NULL, FALSE);
1190 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1191 set_vim_var_string(VV_FNAME_DIFF, NULL, -1);
1192 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1194 # endif
1197 * Top level evaluation function, returning a boolean.
1198 * Sets "error" to TRUE if there was an error.
1199 * Return TRUE or FALSE.
1202 eval_to_bool(arg, error, nextcmd, skip)
1203 char_u *arg;
1204 int *error;
1205 char_u **nextcmd;
1206 int skip; /* only parse, don't execute */
1208 typval_T tv;
1209 int retval = FALSE;
1211 if (skip)
1212 ++emsg_skip;
1213 if (eval0(arg, &tv, nextcmd, !skip) == FAIL)
1214 *error = TRUE;
1215 else
1217 *error = FALSE;
1218 if (!skip)
1220 retval = (get_tv_number_chk(&tv, error) != 0);
1221 clear_tv(&tv);
1224 if (skip)
1225 --emsg_skip;
1227 return retval;
1231 * Top level evaluation function, returning a string. If "skip" is TRUE,
1232 * only parsing to "nextcmd" is done, without reporting errors. Return
1233 * pointer to allocated memory, or NULL for failure or when "skip" is TRUE.
1235 char_u *
1236 eval_to_string_skip(arg, nextcmd, skip)
1237 char_u *arg;
1238 char_u **nextcmd;
1239 int skip; /* only parse, don't execute */
1241 typval_T tv;
1242 char_u *retval;
1244 if (skip)
1245 ++emsg_skip;
1246 if (eval0(arg, &tv, nextcmd, !skip) == FAIL || skip)
1247 retval = NULL;
1248 else
1250 retval = vim_strsave(get_tv_string(&tv));
1251 clear_tv(&tv);
1253 if (skip)
1254 --emsg_skip;
1256 return retval;
1260 * Skip over an expression at "*pp".
1261 * Return FAIL for an error, OK otherwise.
1264 skip_expr(pp)
1265 char_u **pp;
1267 typval_T rettv;
1269 *pp = skipwhite(*pp);
1270 return eval1(pp, &rettv, FALSE);
1274 * Top level evaluation function, returning a string.
1275 * When "convert" is TRUE convert a List into a sequence of lines and convert
1276 * a Float to a String.
1277 * Return pointer to allocated memory, or NULL for failure.
1279 char_u *
1280 eval_to_string(arg, nextcmd, convert)
1281 char_u *arg;
1282 char_u **nextcmd;
1283 int convert;
1285 typval_T tv;
1286 char_u *retval;
1287 garray_T ga;
1288 #ifdef FEAT_FLOAT
1289 char_u numbuf[NUMBUFLEN];
1290 #endif
1292 if (eval0(arg, &tv, nextcmd, TRUE) == FAIL)
1293 retval = NULL;
1294 else
1296 if (convert && tv.v_type == VAR_LIST)
1298 ga_init2(&ga, (int)sizeof(char), 80);
1299 if (tv.vval.v_list != NULL)
1300 list_join(&ga, tv.vval.v_list, (char_u *)"\n", TRUE, 0);
1301 ga_append(&ga, NUL);
1302 retval = (char_u *)ga.ga_data;
1304 #ifdef FEAT_FLOAT
1305 else if (convert && tv.v_type == VAR_FLOAT)
1307 vim_snprintf((char *)numbuf, NUMBUFLEN, "%g", tv.vval.v_float);
1308 retval = vim_strsave(numbuf);
1310 #endif
1311 else
1312 retval = vim_strsave(get_tv_string(&tv));
1313 clear_tv(&tv);
1316 return retval;
1320 * Call eval_to_string() without using current local variables and using
1321 * textlock. When "use_sandbox" is TRUE use the sandbox.
1323 char_u *
1324 eval_to_string_safe(arg, nextcmd, use_sandbox)
1325 char_u *arg;
1326 char_u **nextcmd;
1327 int use_sandbox;
1329 char_u *retval;
1330 void *save_funccalp;
1332 save_funccalp = save_funccal();
1333 if (use_sandbox)
1334 ++sandbox;
1335 ++textlock;
1336 retval = eval_to_string(arg, nextcmd, FALSE);
1337 if (use_sandbox)
1338 --sandbox;
1339 --textlock;
1340 restore_funccal(save_funccalp);
1341 return retval;
1345 * Top level evaluation function, returning a number.
1346 * Evaluates "expr" silently.
1347 * Returns -1 for an error.
1350 eval_to_number(expr)
1351 char_u *expr;
1353 typval_T rettv;
1354 int retval;
1355 char_u *p = skipwhite(expr);
1357 ++emsg_off;
1359 if (eval1(&p, &rettv, TRUE) == FAIL)
1360 retval = -1;
1361 else
1363 retval = get_tv_number_chk(&rettv, NULL);
1364 clear_tv(&rettv);
1366 --emsg_off;
1368 return retval;
1372 * Prepare v: variable "idx" to be used.
1373 * Save the current typeval in "save_tv".
1374 * When not used yet add the variable to the v: hashtable.
1376 static void
1377 prepare_vimvar(idx, save_tv)
1378 int idx;
1379 typval_T *save_tv;
1381 *save_tv = vimvars[idx].vv_tv;
1382 if (vimvars[idx].vv_type == VAR_UNKNOWN)
1383 hash_add(&vimvarht, vimvars[idx].vv_di.di_key);
1387 * Restore v: variable "idx" to typeval "save_tv".
1388 * When no longer defined, remove the variable from the v: hashtable.
1390 static void
1391 restore_vimvar(idx, save_tv)
1392 int idx;
1393 typval_T *save_tv;
1395 hashitem_T *hi;
1397 vimvars[idx].vv_tv = *save_tv;
1398 if (vimvars[idx].vv_type == VAR_UNKNOWN)
1400 hi = hash_find(&vimvarht, vimvars[idx].vv_di.di_key);
1401 if (HASHITEM_EMPTY(hi))
1402 EMSG2(_(e_intern2), "restore_vimvar()");
1403 else
1404 hash_remove(&vimvarht, hi);
1408 #if defined(FEAT_SPELL) || defined(PROTO)
1410 * Evaluate an expression to a list with suggestions.
1411 * For the "expr:" part of 'spellsuggest'.
1412 * Returns NULL when there is an error.
1414 list_T *
1415 eval_spell_expr(badword, expr)
1416 char_u *badword;
1417 char_u *expr;
1419 typval_T save_val;
1420 typval_T rettv;
1421 list_T *list = NULL;
1422 char_u *p = skipwhite(expr);
1424 /* Set "v:val" to the bad word. */
1425 prepare_vimvar(VV_VAL, &save_val);
1426 vimvars[VV_VAL].vv_type = VAR_STRING;
1427 vimvars[VV_VAL].vv_str = badword;
1428 if (p_verbose == 0)
1429 ++emsg_off;
1431 if (eval1(&p, &rettv, TRUE) == OK)
1433 if (rettv.v_type != VAR_LIST)
1434 clear_tv(&rettv);
1435 else
1436 list = rettv.vval.v_list;
1439 if (p_verbose == 0)
1440 --emsg_off;
1441 restore_vimvar(VV_VAL, &save_val);
1443 return list;
1447 * "list" is supposed to contain two items: a word and a number. Return the
1448 * word in "pp" and the number as the return value.
1449 * Return -1 if anything isn't right.
1450 * Used to get the good word and score from the eval_spell_expr() result.
1453 get_spellword(list, pp)
1454 list_T *list;
1455 char_u **pp;
1457 listitem_T *li;
1459 li = list->lv_first;
1460 if (li == NULL)
1461 return -1;
1462 *pp = get_tv_string(&li->li_tv);
1464 li = li->li_next;
1465 if (li == NULL)
1466 return -1;
1467 return get_tv_number(&li->li_tv);
1469 #endif
1472 * Top level evaluation function.
1473 * Returns an allocated typval_T with the result.
1474 * Returns NULL when there is an error.
1476 typval_T *
1477 eval_expr(arg, nextcmd)
1478 char_u *arg;
1479 char_u **nextcmd;
1481 typval_T *tv;
1483 tv = (typval_T *)alloc(sizeof(typval_T));
1484 if (tv != NULL && eval0(arg, tv, nextcmd, TRUE) == FAIL)
1486 vim_free(tv);
1487 tv = NULL;
1490 return tv;
1494 #if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) \
1495 || defined(FEAT_COMPL_FUNC) || defined(PROTO)
1497 * Call some vimL function and return the result in "*rettv".
1498 * Uses argv[argc] for the function arguments. Only Number and String
1499 * arguments are currently supported.
1500 * Returns OK or FAIL.
1502 static int
1503 call_vim_function(func, argc, argv, safe, rettv)
1504 char_u *func;
1505 int argc;
1506 char_u **argv;
1507 int safe; /* use the sandbox */
1508 typval_T *rettv;
1510 typval_T *argvars;
1511 long n;
1512 int len;
1513 int i;
1514 int doesrange;
1515 void *save_funccalp = NULL;
1516 int ret;
1518 argvars = (typval_T *)alloc((unsigned)((argc + 1) * sizeof(typval_T)));
1519 if (argvars == NULL)
1520 return FAIL;
1522 for (i = 0; i < argc; i++)
1524 /* Pass a NULL or empty argument as an empty string */
1525 if (argv[i] == NULL || *argv[i] == NUL)
1527 argvars[i].v_type = VAR_STRING;
1528 argvars[i].vval.v_string = (char_u *)"";
1529 continue;
1532 /* Recognize a number argument, the others must be strings. */
1533 vim_str2nr(argv[i], NULL, &len, TRUE, TRUE, &n, NULL);
1534 if (len != 0 && len == (int)STRLEN(argv[i]))
1536 argvars[i].v_type = VAR_NUMBER;
1537 argvars[i].vval.v_number = n;
1539 else
1541 argvars[i].v_type = VAR_STRING;
1542 argvars[i].vval.v_string = argv[i];
1546 if (safe)
1548 save_funccalp = save_funccal();
1549 ++sandbox;
1552 rettv->v_type = VAR_UNKNOWN; /* clear_tv() uses this */
1553 ret = call_func(func, (int)STRLEN(func), rettv, argc, argvars,
1554 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
1555 &doesrange, TRUE, NULL);
1556 if (safe)
1558 --sandbox;
1559 restore_funccal(save_funccalp);
1561 vim_free(argvars);
1563 if (ret == FAIL)
1564 clear_tv(rettv);
1566 return ret;
1569 # if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) || defined(PROTO)
1571 * Call vimL function "func" and return the result as a string.
1572 * Returns NULL when calling the function fails.
1573 * Uses argv[argc] for the function arguments.
1575 void *
1576 call_func_retstr(func, argc, argv, safe)
1577 char_u *func;
1578 int argc;
1579 char_u **argv;
1580 int safe; /* use the sandbox */
1582 typval_T rettv;
1583 char_u *retval;
1585 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1586 return NULL;
1588 retval = vim_strsave(get_tv_string(&rettv));
1589 clear_tv(&rettv);
1590 return retval;
1592 # endif
1594 # if defined(FEAT_COMPL_FUNC) || defined(PROTO)
1596 * Call vimL function "func" and return the result as a number.
1597 * Returns -1 when calling the function fails.
1598 * Uses argv[argc] for the function arguments.
1600 long
1601 call_func_retnr(func, argc, argv, safe)
1602 char_u *func;
1603 int argc;
1604 char_u **argv;
1605 int safe; /* use the sandbox */
1607 typval_T rettv;
1608 long retval;
1610 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1611 return -1;
1613 retval = get_tv_number_chk(&rettv, NULL);
1614 clear_tv(&rettv);
1615 return retval;
1617 # endif
1620 * Call vimL function "func" and return the result as a List.
1621 * Uses argv[argc] for the function arguments.
1622 * Returns NULL when there is something wrong.
1624 void *
1625 call_func_retlist(func, argc, argv, safe)
1626 char_u *func;
1627 int argc;
1628 char_u **argv;
1629 int safe; /* use the sandbox */
1631 typval_T rettv;
1633 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1634 return NULL;
1636 if (rettv.v_type != VAR_LIST)
1638 clear_tv(&rettv);
1639 return NULL;
1642 return rettv.vval.v_list;
1644 #endif
1648 * Save the current function call pointer, and set it to NULL.
1649 * Used when executing autocommands and for ":source".
1651 void *
1652 save_funccal()
1654 funccall_T *fc = current_funccal;
1656 current_funccal = NULL;
1657 return (void *)fc;
1660 void
1661 restore_funccal(vfc)
1662 void *vfc;
1664 funccall_T *fc = (funccall_T *)vfc;
1666 current_funccal = fc;
1669 #if defined(FEAT_PROFILE) || defined(PROTO)
1671 * Prepare profiling for entering a child or something else that is not
1672 * counted for the script/function itself.
1673 * Should always be called in pair with prof_child_exit().
1675 void
1676 prof_child_enter(tm)
1677 proftime_T *tm; /* place to store waittime */
1679 funccall_T *fc = current_funccal;
1681 if (fc != NULL && fc->func->uf_profiling)
1682 profile_start(&fc->prof_child);
1683 script_prof_save(tm);
1687 * Take care of time spent in a child.
1688 * Should always be called after prof_child_enter().
1690 void
1691 prof_child_exit(tm)
1692 proftime_T *tm; /* where waittime was stored */
1694 funccall_T *fc = current_funccal;
1696 if (fc != NULL && fc->func->uf_profiling)
1698 profile_end(&fc->prof_child);
1699 profile_sub_wait(tm, &fc->prof_child); /* don't count waiting time */
1700 profile_add(&fc->func->uf_tm_children, &fc->prof_child);
1701 profile_add(&fc->func->uf_tml_children, &fc->prof_child);
1703 script_prof_restore(tm);
1705 #endif
1708 #ifdef FEAT_FOLDING
1710 * Evaluate 'foldexpr'. Returns the foldlevel, and any character preceding
1711 * it in "*cp". Doesn't give error messages.
1714 eval_foldexpr(arg, cp)
1715 char_u *arg;
1716 int *cp;
1718 typval_T tv;
1719 int retval;
1720 char_u *s;
1721 int use_sandbox = was_set_insecurely((char_u *)"foldexpr",
1722 OPT_LOCAL);
1724 ++emsg_off;
1725 if (use_sandbox)
1726 ++sandbox;
1727 ++textlock;
1728 *cp = NUL;
1729 if (eval0(arg, &tv, NULL, TRUE) == FAIL)
1730 retval = 0;
1731 else
1733 /* If the result is a number, just return the number. */
1734 if (tv.v_type == VAR_NUMBER)
1735 retval = tv.vval.v_number;
1736 else if (tv.v_type != VAR_STRING || tv.vval.v_string == NULL)
1737 retval = 0;
1738 else
1740 /* If the result is a string, check if there is a non-digit before
1741 * the number. */
1742 s = tv.vval.v_string;
1743 if (!VIM_ISDIGIT(*s) && *s != '-')
1744 *cp = *s++;
1745 retval = atol((char *)s);
1747 clear_tv(&tv);
1749 --emsg_off;
1750 if (use_sandbox)
1751 --sandbox;
1752 --textlock;
1754 return retval;
1756 #endif
1759 * ":let" list all variable values
1760 * ":let var1 var2" list variable values
1761 * ":let var = expr" assignment command.
1762 * ":let var += expr" assignment command.
1763 * ":let var -= expr" assignment command.
1764 * ":let var .= expr" assignment command.
1765 * ":let [var1, var2] = expr" unpack list.
1767 void
1768 ex_let(eap)
1769 exarg_T *eap;
1771 char_u *arg = eap->arg;
1772 char_u *expr = NULL;
1773 typval_T rettv;
1774 int i;
1775 int var_count = 0;
1776 int semicolon = 0;
1777 char_u op[2];
1778 char_u *argend;
1779 int first = TRUE;
1781 argend = skip_var_list(arg, &var_count, &semicolon);
1782 if (argend == NULL)
1783 return;
1784 if (argend > arg && argend[-1] == '.') /* for var.='str' */
1785 --argend;
1786 expr = vim_strchr(argend, '=');
1787 if (expr == NULL)
1790 * ":let" without "=": list variables
1792 if (*arg == '[')
1793 EMSG(_(e_invarg));
1794 else if (!ends_excmd(*arg))
1795 /* ":let var1 var2" */
1796 arg = list_arg_vars(eap, arg, &first);
1797 else if (!eap->skip)
1799 /* ":let" */
1800 list_glob_vars(&first);
1801 list_buf_vars(&first);
1802 list_win_vars(&first);
1803 #ifdef FEAT_WINDOWS
1804 list_tab_vars(&first);
1805 #endif
1806 list_script_vars(&first);
1807 list_func_vars(&first);
1808 list_vim_vars(&first);
1810 eap->nextcmd = check_nextcmd(arg);
1812 else
1814 op[0] = '=';
1815 op[1] = NUL;
1816 if (expr > argend)
1818 if (vim_strchr((char_u *)"+-.", expr[-1]) != NULL)
1819 op[0] = expr[-1]; /* +=, -= or .= */
1821 expr = skipwhite(expr + 1);
1823 if (eap->skip)
1824 ++emsg_skip;
1825 i = eval0(expr, &rettv, &eap->nextcmd, !eap->skip);
1826 if (eap->skip)
1828 if (i != FAIL)
1829 clear_tv(&rettv);
1830 --emsg_skip;
1832 else if (i != FAIL)
1834 (void)ex_let_vars(eap->arg, &rettv, FALSE, semicolon, var_count,
1835 op);
1836 clear_tv(&rettv);
1842 * Assign the typevalue "tv" to the variable or variables at "arg_start".
1843 * Handles both "var" with any type and "[var, var; var]" with a list type.
1844 * When "nextchars" is not NULL it points to a string with characters that
1845 * must appear after the variable(s). Use "+", "-" or "." for add, subtract
1846 * or concatenate.
1847 * Returns OK or FAIL;
1849 static int
1850 ex_let_vars(arg_start, tv, copy, semicolon, var_count, nextchars)
1851 char_u *arg_start;
1852 typval_T *tv;
1853 int copy; /* copy values from "tv", don't move */
1854 int semicolon; /* from skip_var_list() */
1855 int var_count; /* from skip_var_list() */
1856 char_u *nextchars;
1858 char_u *arg = arg_start;
1859 list_T *l;
1860 int i;
1861 listitem_T *item;
1862 typval_T ltv;
1864 if (*arg != '[')
1867 * ":let var = expr" or ":for var in list"
1869 if (ex_let_one(arg, tv, copy, nextchars, nextchars) == NULL)
1870 return FAIL;
1871 return OK;
1875 * ":let [v1, v2] = list" or ":for [v1, v2] in listlist"
1877 if (tv->v_type != VAR_LIST || (l = tv->vval.v_list) == NULL)
1879 EMSG(_(e_listreq));
1880 return FAIL;
1883 i = list_len(l);
1884 if (semicolon == 0 && var_count < i)
1886 EMSG(_("E687: Less targets than List items"));
1887 return FAIL;
1889 if (var_count - semicolon > i)
1891 EMSG(_("E688: More targets than List items"));
1892 return FAIL;
1895 item = l->lv_first;
1896 while (*arg != ']')
1898 arg = skipwhite(arg + 1);
1899 arg = ex_let_one(arg, &item->li_tv, TRUE, (char_u *)",;]", nextchars);
1900 item = item->li_next;
1901 if (arg == NULL)
1902 return FAIL;
1904 arg = skipwhite(arg);
1905 if (*arg == ';')
1907 /* Put the rest of the list (may be empty) in the var after ';'.
1908 * Create a new list for this. */
1909 l = list_alloc();
1910 if (l == NULL)
1911 return FAIL;
1912 while (item != NULL)
1914 list_append_tv(l, &item->li_tv);
1915 item = item->li_next;
1918 ltv.v_type = VAR_LIST;
1919 ltv.v_lock = 0;
1920 ltv.vval.v_list = l;
1921 l->lv_refcount = 1;
1923 arg = ex_let_one(skipwhite(arg + 1), &ltv, FALSE,
1924 (char_u *)"]", nextchars);
1925 clear_tv(&ltv);
1926 if (arg == NULL)
1927 return FAIL;
1928 break;
1930 else if (*arg != ',' && *arg != ']')
1932 EMSG2(_(e_intern2), "ex_let_vars()");
1933 return FAIL;
1937 return OK;
1941 * Skip over assignable variable "var" or list of variables "[var, var]".
1942 * Used for ":let varvar = expr" and ":for varvar in expr".
1943 * For "[var, var]" increment "*var_count" for each variable.
1944 * for "[var, var; var]" set "semicolon".
1945 * Return NULL for an error.
1947 static char_u *
1948 skip_var_list(arg, var_count, semicolon)
1949 char_u *arg;
1950 int *var_count;
1951 int *semicolon;
1953 char_u *p, *s;
1955 if (*arg == '[')
1957 /* "[var, var]": find the matching ']'. */
1958 p = arg;
1959 for (;;)
1961 p = skipwhite(p + 1); /* skip whites after '[', ';' or ',' */
1962 s = skip_var_one(p);
1963 if (s == p)
1965 EMSG2(_(e_invarg2), p);
1966 return NULL;
1968 ++*var_count;
1970 p = skipwhite(s);
1971 if (*p == ']')
1972 break;
1973 else if (*p == ';')
1975 if (*semicolon == 1)
1977 EMSG(_("Double ; in list of variables"));
1978 return NULL;
1980 *semicolon = 1;
1982 else if (*p != ',')
1984 EMSG2(_(e_invarg2), p);
1985 return NULL;
1988 return p + 1;
1990 else
1991 return skip_var_one(arg);
1995 * Skip one (assignable) variable name, including @r, $VAR, &option, d.key,
1996 * l[idx].
1998 static char_u *
1999 skip_var_one(arg)
2000 char_u *arg;
2002 if (*arg == '@' && arg[1] != NUL)
2003 return arg + 2;
2004 return find_name_end(*arg == '$' || *arg == '&' ? arg + 1 : arg,
2005 NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
2009 * List variables for hashtab "ht" with prefix "prefix".
2010 * If "empty" is TRUE also list NULL strings as empty strings.
2012 static void
2013 list_hashtable_vars(ht, prefix, empty, first)
2014 hashtab_T *ht;
2015 char_u *prefix;
2016 int empty;
2017 int *first;
2019 hashitem_T *hi;
2020 dictitem_T *di;
2021 int todo;
2023 todo = (int)ht->ht_used;
2024 for (hi = ht->ht_array; todo > 0 && !got_int; ++hi)
2026 if (!HASHITEM_EMPTY(hi))
2028 --todo;
2029 di = HI2DI(hi);
2030 if (empty || di->di_tv.v_type != VAR_STRING
2031 || di->di_tv.vval.v_string != NULL)
2032 list_one_var(di, prefix, first);
2038 * List global variables.
2040 static void
2041 list_glob_vars(first)
2042 int *first;
2044 list_hashtable_vars(&globvarht, (char_u *)"", TRUE, first);
2048 * List buffer variables.
2050 static void
2051 list_buf_vars(first)
2052 int *first;
2054 char_u numbuf[NUMBUFLEN];
2056 list_hashtable_vars(&curbuf->b_vars.dv_hashtab, (char_u *)"b:",
2057 TRUE, first);
2059 sprintf((char *)numbuf, "%ld", (long)curbuf->b_changedtick);
2060 list_one_var_a((char_u *)"b:", (char_u *)"changedtick", VAR_NUMBER,
2061 numbuf, first);
2065 * List window variables.
2067 static void
2068 list_win_vars(first)
2069 int *first;
2071 list_hashtable_vars(&curwin->w_vars.dv_hashtab,
2072 (char_u *)"w:", TRUE, first);
2075 #ifdef FEAT_WINDOWS
2077 * List tab page variables.
2079 static void
2080 list_tab_vars(first)
2081 int *first;
2083 list_hashtable_vars(&curtab->tp_vars.dv_hashtab,
2084 (char_u *)"t:", TRUE, first);
2086 #endif
2089 * List Vim variables.
2091 static void
2092 list_vim_vars(first)
2093 int *first;
2095 list_hashtable_vars(&vimvarht, (char_u *)"v:", FALSE, first);
2099 * List script-local variables, if there is a script.
2101 static void
2102 list_script_vars(first)
2103 int *first;
2105 if (current_SID > 0 && current_SID <= ga_scripts.ga_len)
2106 list_hashtable_vars(&SCRIPT_VARS(current_SID),
2107 (char_u *)"s:", FALSE, first);
2111 * List function variables, if there is a function.
2113 static void
2114 list_func_vars(first)
2115 int *first;
2117 if (current_funccal != NULL)
2118 list_hashtable_vars(&current_funccal->l_vars.dv_hashtab,
2119 (char_u *)"l:", FALSE, first);
2123 * List variables in "arg".
2125 static char_u *
2126 list_arg_vars(eap, arg, first)
2127 exarg_T *eap;
2128 char_u *arg;
2129 int *first;
2131 int error = FALSE;
2132 int len;
2133 char_u *name;
2134 char_u *name_start;
2135 char_u *arg_subsc;
2136 char_u *tofree;
2137 typval_T tv;
2139 while (!ends_excmd(*arg) && !got_int)
2141 if (error || eap->skip)
2143 arg = find_name_end(arg, NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
2144 if (!vim_iswhite(*arg) && !ends_excmd(*arg))
2146 emsg_severe = TRUE;
2147 EMSG(_(e_trailing));
2148 break;
2151 else
2153 /* get_name_len() takes care of expanding curly braces */
2154 name_start = name = arg;
2155 len = get_name_len(&arg, &tofree, TRUE, TRUE);
2156 if (len <= 0)
2158 /* This is mainly to keep test 49 working: when expanding
2159 * curly braces fails overrule the exception error message. */
2160 if (len < 0 && !aborting())
2162 emsg_severe = TRUE;
2163 EMSG2(_(e_invarg2), arg);
2164 break;
2166 error = TRUE;
2168 else
2170 if (tofree != NULL)
2171 name = tofree;
2172 if (get_var_tv(name, len, &tv, TRUE) == FAIL)
2173 error = TRUE;
2174 else
2176 /* handle d.key, l[idx], f(expr) */
2177 arg_subsc = arg;
2178 if (handle_subscript(&arg, &tv, TRUE, TRUE) == FAIL)
2179 error = TRUE;
2180 else
2182 if (arg == arg_subsc && len == 2 && name[1] == ':')
2184 switch (*name)
2186 case 'g': list_glob_vars(first); break;
2187 case 'b': list_buf_vars(first); break;
2188 case 'w': list_win_vars(first); break;
2189 #ifdef FEAT_WINDOWS
2190 case 't': list_tab_vars(first); break;
2191 #endif
2192 case 'v': list_vim_vars(first); break;
2193 case 's': list_script_vars(first); break;
2194 case 'l': list_func_vars(first); break;
2195 default:
2196 EMSG2(_("E738: Can't list variables for %s"), name);
2199 else
2201 char_u numbuf[NUMBUFLEN];
2202 char_u *tf;
2203 int c;
2204 char_u *s;
2206 s = echo_string(&tv, &tf, numbuf, 0);
2207 c = *arg;
2208 *arg = NUL;
2209 list_one_var_a((char_u *)"",
2210 arg == arg_subsc ? name : name_start,
2211 tv.v_type,
2212 s == NULL ? (char_u *)"" : s,
2213 first);
2214 *arg = c;
2215 vim_free(tf);
2217 clear_tv(&tv);
2222 vim_free(tofree);
2225 arg = skipwhite(arg);
2228 return arg;
2232 * Set one item of ":let var = expr" or ":let [v1, v2] = list" to its value.
2233 * Returns a pointer to the char just after the var name.
2234 * Returns NULL if there is an error.
2236 static char_u *
2237 ex_let_one(arg, tv, copy, endchars, op)
2238 char_u *arg; /* points to variable name */
2239 typval_T *tv; /* value to assign to variable */
2240 int copy; /* copy value from "tv" */
2241 char_u *endchars; /* valid chars after variable name or NULL */
2242 char_u *op; /* "+", "-", "." or NULL*/
2244 int c1;
2245 char_u *name;
2246 char_u *p;
2247 char_u *arg_end = NULL;
2248 int len;
2249 int opt_flags;
2250 char_u *tofree = NULL;
2253 * ":let $VAR = expr": Set environment variable.
2255 if (*arg == '$')
2257 /* Find the end of the name. */
2258 ++arg;
2259 name = arg;
2260 len = get_env_len(&arg);
2261 if (len == 0)
2262 EMSG2(_(e_invarg2), name - 1);
2263 else
2265 if (op != NULL && (*op == '+' || *op == '-'))
2266 EMSG2(_(e_letwrong), op);
2267 else if (endchars != NULL
2268 && vim_strchr(endchars, *skipwhite(arg)) == NULL)
2269 EMSG(_(e_letunexp));
2270 else
2272 c1 = name[len];
2273 name[len] = NUL;
2274 p = get_tv_string_chk(tv);
2275 if (p != NULL && op != NULL && *op == '.')
2277 int mustfree = FALSE;
2278 char_u *s = vim_getenv(name, &mustfree);
2280 if (s != NULL)
2282 p = tofree = concat_str(s, p);
2283 if (mustfree)
2284 vim_free(s);
2287 if (p != NULL)
2289 vim_setenv(name, p);
2290 if (STRICMP(name, "HOME") == 0)
2291 init_homedir();
2292 else if (didset_vim && STRICMP(name, "VIM") == 0)
2293 didset_vim = FALSE;
2294 else if (didset_vimruntime
2295 && STRICMP(name, "VIMRUNTIME") == 0)
2296 didset_vimruntime = FALSE;
2297 arg_end = arg;
2299 name[len] = c1;
2300 vim_free(tofree);
2306 * ":let &option = expr": Set option value.
2307 * ":let &l:option = expr": Set local option value.
2308 * ":let &g:option = expr": Set global option value.
2310 else if (*arg == '&')
2312 /* Find the end of the name. */
2313 p = find_option_end(&arg, &opt_flags);
2314 if (p == NULL || (endchars != NULL
2315 && vim_strchr(endchars, *skipwhite(p)) == NULL))
2316 EMSG(_(e_letunexp));
2317 else
2319 long n;
2320 int opt_type;
2321 long numval;
2322 char_u *stringval = NULL;
2323 char_u *s;
2325 c1 = *p;
2326 *p = NUL;
2328 n = get_tv_number(tv);
2329 s = get_tv_string_chk(tv); /* != NULL if number or string */
2330 if (s != NULL && op != NULL && *op != '=')
2332 opt_type = get_option_value(arg, &numval,
2333 &stringval, opt_flags);
2334 if ((opt_type == 1 && *op == '.')
2335 || (opt_type == 0 && *op != '.'))
2336 EMSG2(_(e_letwrong), op);
2337 else
2339 if (opt_type == 1) /* number */
2341 if (*op == '+')
2342 n = numval + n;
2343 else
2344 n = numval - n;
2346 else if (opt_type == 0 && stringval != NULL) /* string */
2348 s = concat_str(stringval, s);
2349 vim_free(stringval);
2350 stringval = s;
2354 if (s != NULL)
2356 set_option_value(arg, n, s, opt_flags);
2357 arg_end = p;
2359 *p = c1;
2360 vim_free(stringval);
2365 * ":let @r = expr": Set register contents.
2367 else if (*arg == '@')
2369 ++arg;
2370 if (op != NULL && (*op == '+' || *op == '-'))
2371 EMSG2(_(e_letwrong), op);
2372 else if (endchars != NULL
2373 && vim_strchr(endchars, *skipwhite(arg + 1)) == NULL)
2374 EMSG(_(e_letunexp));
2375 else
2377 char_u *ptofree = NULL;
2378 char_u *s;
2380 p = get_tv_string_chk(tv);
2381 if (p != NULL && op != NULL && *op == '.')
2383 s = get_reg_contents(*arg == '@' ? '"' : *arg, TRUE, TRUE);
2384 if (s != NULL)
2386 p = ptofree = concat_str(s, p);
2387 vim_free(s);
2390 if (p != NULL)
2392 write_reg_contents(*arg == '@' ? '"' : *arg, p, -1, FALSE);
2393 arg_end = arg + 1;
2395 vim_free(ptofree);
2400 * ":let var = expr": Set internal variable.
2401 * ":let {expr} = expr": Idem, name made with curly braces
2403 else if (eval_isnamec1(*arg) || *arg == '{')
2405 lval_T lv;
2407 p = get_lval(arg, tv, &lv, FALSE, FALSE, FALSE, FNE_CHECK_START);
2408 if (p != NULL && lv.ll_name != NULL)
2410 if (endchars != NULL && vim_strchr(endchars, *skipwhite(p)) == NULL)
2411 EMSG(_(e_letunexp));
2412 else
2414 set_var_lval(&lv, p, tv, copy, op);
2415 arg_end = p;
2418 clear_lval(&lv);
2421 else
2422 EMSG2(_(e_invarg2), arg);
2424 return arg_end;
2428 * If "arg" is equal to "b:changedtick" give an error and return TRUE.
2430 static int
2431 check_changedtick(arg)
2432 char_u *arg;
2434 if (STRNCMP(arg, "b:changedtick", 13) == 0 && !eval_isnamec(arg[13]))
2436 EMSG2(_(e_readonlyvar), arg);
2437 return TRUE;
2439 return FALSE;
2443 * Get an lval: variable, Dict item or List item that can be assigned a value
2444 * to: "name", "na{me}", "name[expr]", "name[expr:expr]", "name[expr][expr]",
2445 * "name.key", "name.key[expr]" etc.
2446 * Indexing only works if "name" is an existing List or Dictionary.
2447 * "name" points to the start of the name.
2448 * If "rettv" is not NULL it points to the value to be assigned.
2449 * "unlet" is TRUE for ":unlet": slightly different behavior when something is
2450 * wrong; must end in space or cmd separator.
2452 * Returns a pointer to just after the name, including indexes.
2453 * When an evaluation error occurs "lp->ll_name" is NULL;
2454 * Returns NULL for a parsing error. Still need to free items in "lp"!
2456 static char_u *
2457 get_lval(name, rettv, lp, unlet, skip, quiet, fne_flags)
2458 char_u *name;
2459 typval_T *rettv;
2460 lval_T *lp;
2461 int unlet;
2462 int skip;
2463 int quiet; /* don't give error messages */
2464 int fne_flags; /* flags for find_name_end() */
2466 char_u *p;
2467 char_u *expr_start, *expr_end;
2468 int cc;
2469 dictitem_T *v;
2470 typval_T var1;
2471 typval_T var2;
2472 int empty1 = FALSE;
2473 listitem_T *ni;
2474 char_u *key = NULL;
2475 int len;
2476 hashtab_T *ht;
2478 /* Clear everything in "lp". */
2479 vim_memset(lp, 0, sizeof(lval_T));
2481 if (skip)
2483 /* When skipping just find the end of the name. */
2484 lp->ll_name = name;
2485 return find_name_end(name, NULL, NULL, FNE_INCL_BR | fne_flags);
2488 /* Find the end of the name. */
2489 p = find_name_end(name, &expr_start, &expr_end, fne_flags);
2490 if (expr_start != NULL)
2492 /* Don't expand the name when we already know there is an error. */
2493 if (unlet && !vim_iswhite(*p) && !ends_excmd(*p)
2494 && *p != '[' && *p != '.')
2496 EMSG(_(e_trailing));
2497 return NULL;
2500 lp->ll_exp_name = make_expanded_name(name, expr_start, expr_end, p);
2501 if (lp->ll_exp_name == NULL)
2503 /* Report an invalid expression in braces, unless the
2504 * expression evaluation has been cancelled due to an
2505 * aborting error, an interrupt, or an exception. */
2506 if (!aborting() && !quiet)
2508 emsg_severe = TRUE;
2509 EMSG2(_(e_invarg2), name);
2510 return NULL;
2513 lp->ll_name = lp->ll_exp_name;
2515 else
2516 lp->ll_name = name;
2518 /* Without [idx] or .key we are done. */
2519 if ((*p != '[' && *p != '.') || lp->ll_name == NULL)
2520 return p;
2522 cc = *p;
2523 *p = NUL;
2524 v = find_var(lp->ll_name, &ht);
2525 if (v == NULL && !quiet)
2526 EMSG2(_(e_undefvar), lp->ll_name);
2527 *p = cc;
2528 if (v == NULL)
2529 return NULL;
2532 * Loop until no more [idx] or .key is following.
2534 lp->ll_tv = &v->di_tv;
2535 while (*p == '[' || (*p == '.' && lp->ll_tv->v_type == VAR_DICT))
2537 if (!(lp->ll_tv->v_type == VAR_LIST && lp->ll_tv->vval.v_list != NULL)
2538 && !(lp->ll_tv->v_type == VAR_DICT
2539 && lp->ll_tv->vval.v_dict != NULL))
2541 if (!quiet)
2542 EMSG(_("E689: Can only index a List or Dictionary"));
2543 return NULL;
2545 if (lp->ll_range)
2547 if (!quiet)
2548 EMSG(_("E708: [:] must come last"));
2549 return NULL;
2552 len = -1;
2553 if (*p == '.')
2555 key = p + 1;
2556 for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
2558 if (len == 0)
2560 if (!quiet)
2561 EMSG(_(e_emptykey));
2562 return NULL;
2564 p = key + len;
2566 else
2568 /* Get the index [expr] or the first index [expr: ]. */
2569 p = skipwhite(p + 1);
2570 if (*p == ':')
2571 empty1 = TRUE;
2572 else
2574 empty1 = FALSE;
2575 if (eval1(&p, &var1, TRUE) == FAIL) /* recursive! */
2576 return NULL;
2577 if (get_tv_string_chk(&var1) == NULL)
2579 /* not a number or string */
2580 clear_tv(&var1);
2581 return NULL;
2585 /* Optionally get the second index [ :expr]. */
2586 if (*p == ':')
2588 if (lp->ll_tv->v_type == VAR_DICT)
2590 if (!quiet)
2591 EMSG(_(e_dictrange));
2592 if (!empty1)
2593 clear_tv(&var1);
2594 return NULL;
2596 if (rettv != NULL && (rettv->v_type != VAR_LIST
2597 || rettv->vval.v_list == NULL))
2599 if (!quiet)
2600 EMSG(_("E709: [:] requires a List value"));
2601 if (!empty1)
2602 clear_tv(&var1);
2603 return NULL;
2605 p = skipwhite(p + 1);
2606 if (*p == ']')
2607 lp->ll_empty2 = TRUE;
2608 else
2610 lp->ll_empty2 = FALSE;
2611 if (eval1(&p, &var2, TRUE) == FAIL) /* recursive! */
2613 if (!empty1)
2614 clear_tv(&var1);
2615 return NULL;
2617 if (get_tv_string_chk(&var2) == NULL)
2619 /* not a number or string */
2620 if (!empty1)
2621 clear_tv(&var1);
2622 clear_tv(&var2);
2623 return NULL;
2626 lp->ll_range = TRUE;
2628 else
2629 lp->ll_range = FALSE;
2631 if (*p != ']')
2633 if (!quiet)
2634 EMSG(_(e_missbrac));
2635 if (!empty1)
2636 clear_tv(&var1);
2637 if (lp->ll_range && !lp->ll_empty2)
2638 clear_tv(&var2);
2639 return NULL;
2642 /* Skip to past ']'. */
2643 ++p;
2646 if (lp->ll_tv->v_type == VAR_DICT)
2648 if (len == -1)
2650 /* "[key]": get key from "var1" */
2651 key = get_tv_string(&var1); /* is number or string */
2652 if (*key == NUL)
2654 if (!quiet)
2655 EMSG(_(e_emptykey));
2656 clear_tv(&var1);
2657 return NULL;
2660 lp->ll_list = NULL;
2661 lp->ll_dict = lp->ll_tv->vval.v_dict;
2662 lp->ll_di = dict_find(lp->ll_dict, key, len);
2663 if (lp->ll_di == NULL)
2665 /* Key does not exist in dict: may need to add it. */
2666 if (*p == '[' || *p == '.' || unlet)
2668 if (!quiet)
2669 EMSG2(_(e_dictkey), key);
2670 if (len == -1)
2671 clear_tv(&var1);
2672 return NULL;
2674 if (len == -1)
2675 lp->ll_newkey = vim_strsave(key);
2676 else
2677 lp->ll_newkey = vim_strnsave(key, len);
2678 if (len == -1)
2679 clear_tv(&var1);
2680 if (lp->ll_newkey == NULL)
2681 p = NULL;
2682 break;
2684 if (len == -1)
2685 clear_tv(&var1);
2686 lp->ll_tv = &lp->ll_di->di_tv;
2688 else
2691 * Get the number and item for the only or first index of the List.
2693 if (empty1)
2694 lp->ll_n1 = 0;
2695 else
2697 lp->ll_n1 = get_tv_number(&var1); /* is number or string */
2698 clear_tv(&var1);
2700 lp->ll_dict = NULL;
2701 lp->ll_list = lp->ll_tv->vval.v_list;
2702 lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2703 if (lp->ll_li == NULL)
2705 if (lp->ll_n1 < 0)
2707 lp->ll_n1 = 0;
2708 lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2711 if (lp->ll_li == NULL)
2713 if (lp->ll_range && !lp->ll_empty2)
2714 clear_tv(&var2);
2715 return NULL;
2719 * May need to find the item or absolute index for the second
2720 * index of a range.
2721 * When no index given: "lp->ll_empty2" is TRUE.
2722 * Otherwise "lp->ll_n2" is set to the second index.
2724 if (lp->ll_range && !lp->ll_empty2)
2726 lp->ll_n2 = get_tv_number(&var2); /* is number or string */
2727 clear_tv(&var2);
2728 if (lp->ll_n2 < 0)
2730 ni = list_find(lp->ll_list, lp->ll_n2);
2731 if (ni == NULL)
2732 return NULL;
2733 lp->ll_n2 = list_idx_of_item(lp->ll_list, ni);
2736 /* Check that lp->ll_n2 isn't before lp->ll_n1. */
2737 if (lp->ll_n1 < 0)
2738 lp->ll_n1 = list_idx_of_item(lp->ll_list, lp->ll_li);
2739 if (lp->ll_n2 < lp->ll_n1)
2740 return NULL;
2743 lp->ll_tv = &lp->ll_li->li_tv;
2747 return p;
2751 * Clear lval "lp" that was filled by get_lval().
2753 static void
2754 clear_lval(lp)
2755 lval_T *lp;
2757 vim_free(lp->ll_exp_name);
2758 vim_free(lp->ll_newkey);
2762 * Set a variable that was parsed by get_lval() to "rettv".
2763 * "endp" points to just after the parsed name.
2764 * "op" is NULL, "+" for "+=", "-" for "-=", "." for ".=" or "=" for "=".
2766 static void
2767 set_var_lval(lp, endp, rettv, copy, op)
2768 lval_T *lp;
2769 char_u *endp;
2770 typval_T *rettv;
2771 int copy;
2772 char_u *op;
2774 int cc;
2775 listitem_T *ri;
2776 dictitem_T *di;
2778 if (lp->ll_tv == NULL)
2780 if (!check_changedtick(lp->ll_name))
2782 cc = *endp;
2783 *endp = NUL;
2784 if (op != NULL && *op != '=')
2786 typval_T tv;
2788 /* handle +=, -= and .= */
2789 if (get_var_tv(lp->ll_name, (int)STRLEN(lp->ll_name),
2790 &tv, TRUE) == OK)
2792 if (tv_op(&tv, rettv, op) == OK)
2793 set_var(lp->ll_name, &tv, FALSE);
2794 clear_tv(&tv);
2797 else
2798 set_var(lp->ll_name, rettv, copy);
2799 *endp = cc;
2802 else if (tv_check_lock(lp->ll_newkey == NULL
2803 ? lp->ll_tv->v_lock
2804 : lp->ll_tv->vval.v_dict->dv_lock, lp->ll_name))
2806 else if (lp->ll_range)
2809 * Assign the List values to the list items.
2811 for (ri = rettv->vval.v_list->lv_first; ri != NULL; )
2813 if (op != NULL && *op != '=')
2814 tv_op(&lp->ll_li->li_tv, &ri->li_tv, op);
2815 else
2817 clear_tv(&lp->ll_li->li_tv);
2818 copy_tv(&ri->li_tv, &lp->ll_li->li_tv);
2820 ri = ri->li_next;
2821 if (ri == NULL || (!lp->ll_empty2 && lp->ll_n2 == lp->ll_n1))
2822 break;
2823 if (lp->ll_li->li_next == NULL)
2825 /* Need to add an empty item. */
2826 if (list_append_number(lp->ll_list, 0) == FAIL)
2828 ri = NULL;
2829 break;
2832 lp->ll_li = lp->ll_li->li_next;
2833 ++lp->ll_n1;
2835 if (ri != NULL)
2836 EMSG(_("E710: List value has more items than target"));
2837 else if (lp->ll_empty2
2838 ? (lp->ll_li != NULL && lp->ll_li->li_next != NULL)
2839 : lp->ll_n1 != lp->ll_n2)
2840 EMSG(_("E711: List value has not enough items"));
2842 else
2845 * Assign to a List or Dictionary item.
2847 if (lp->ll_newkey != NULL)
2849 if (op != NULL && *op != '=')
2851 EMSG2(_(e_letwrong), op);
2852 return;
2855 /* Need to add an item to the Dictionary. */
2856 di = dictitem_alloc(lp->ll_newkey);
2857 if (di == NULL)
2858 return;
2859 if (dict_add(lp->ll_tv->vval.v_dict, di) == FAIL)
2861 vim_free(di);
2862 return;
2864 lp->ll_tv = &di->di_tv;
2866 else if (op != NULL && *op != '=')
2868 tv_op(lp->ll_tv, rettv, op);
2869 return;
2871 else
2872 clear_tv(lp->ll_tv);
2875 * Assign the value to the variable or list item.
2877 if (copy)
2878 copy_tv(rettv, lp->ll_tv);
2879 else
2881 *lp->ll_tv = *rettv;
2882 lp->ll_tv->v_lock = 0;
2883 init_tv(rettv);
2889 * Handle "tv1 += tv2", "tv1 -= tv2" and "tv1 .= tv2"
2890 * Returns OK or FAIL.
2892 static int
2893 tv_op(tv1, tv2, op)
2894 typval_T *tv1;
2895 typval_T *tv2;
2896 char_u *op;
2898 long n;
2899 char_u numbuf[NUMBUFLEN];
2900 char_u *s;
2902 /* Can't do anything with a Funcref or a Dict on the right. */
2903 if (tv2->v_type != VAR_FUNC && tv2->v_type != VAR_DICT)
2905 switch (tv1->v_type)
2907 case VAR_DICT:
2908 case VAR_FUNC:
2909 break;
2911 case VAR_LIST:
2912 if (*op != '+' || tv2->v_type != VAR_LIST)
2913 break;
2914 /* List += List */
2915 if (tv1->vval.v_list != NULL && tv2->vval.v_list != NULL)
2916 list_extend(tv1->vval.v_list, tv2->vval.v_list, NULL);
2917 return OK;
2919 case VAR_NUMBER:
2920 case VAR_STRING:
2921 if (tv2->v_type == VAR_LIST)
2922 break;
2923 if (*op == '+' || *op == '-')
2925 /* nr += nr or nr -= nr*/
2926 n = get_tv_number(tv1);
2927 #ifdef FEAT_FLOAT
2928 if (tv2->v_type == VAR_FLOAT)
2930 float_T f = n;
2932 if (*op == '+')
2933 f += tv2->vval.v_float;
2934 else
2935 f -= tv2->vval.v_float;
2936 clear_tv(tv1);
2937 tv1->v_type = VAR_FLOAT;
2938 tv1->vval.v_float = f;
2940 else
2941 #endif
2943 if (*op == '+')
2944 n += get_tv_number(tv2);
2945 else
2946 n -= get_tv_number(tv2);
2947 clear_tv(tv1);
2948 tv1->v_type = VAR_NUMBER;
2949 tv1->vval.v_number = n;
2952 else
2954 if (tv2->v_type == VAR_FLOAT)
2955 break;
2957 /* str .= str */
2958 s = get_tv_string(tv1);
2959 s = concat_str(s, get_tv_string_buf(tv2, numbuf));
2960 clear_tv(tv1);
2961 tv1->v_type = VAR_STRING;
2962 tv1->vval.v_string = s;
2964 return OK;
2966 #ifdef FEAT_FLOAT
2967 case VAR_FLOAT:
2969 float_T f;
2971 if (*op == '.' || (tv2->v_type != VAR_FLOAT
2972 && tv2->v_type != VAR_NUMBER
2973 && tv2->v_type != VAR_STRING))
2974 break;
2975 if (tv2->v_type == VAR_FLOAT)
2976 f = tv2->vval.v_float;
2977 else
2978 f = get_tv_number(tv2);
2979 if (*op == '+')
2980 tv1->vval.v_float += f;
2981 else
2982 tv1->vval.v_float -= f;
2984 return OK;
2985 #endif
2989 EMSG2(_(e_letwrong), op);
2990 return FAIL;
2994 * Add a watcher to a list.
2996 static void
2997 list_add_watch(l, lw)
2998 list_T *l;
2999 listwatch_T *lw;
3001 lw->lw_next = l->lv_watch;
3002 l->lv_watch = lw;
3006 * Remove a watcher from a list.
3007 * No warning when it isn't found...
3009 static void
3010 list_rem_watch(l, lwrem)
3011 list_T *l;
3012 listwatch_T *lwrem;
3014 listwatch_T *lw, **lwp;
3016 lwp = &l->lv_watch;
3017 for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
3019 if (lw == lwrem)
3021 *lwp = lw->lw_next;
3022 break;
3024 lwp = &lw->lw_next;
3029 * Just before removing an item from a list: advance watchers to the next
3030 * item.
3032 static void
3033 list_fix_watch(l, item)
3034 list_T *l;
3035 listitem_T *item;
3037 listwatch_T *lw;
3039 for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
3040 if (lw->lw_item == item)
3041 lw->lw_item = item->li_next;
3045 * Evaluate the expression used in a ":for var in expr" command.
3046 * "arg" points to "var".
3047 * Set "*errp" to TRUE for an error, FALSE otherwise;
3048 * Return a pointer that holds the info. Null when there is an error.
3050 void *
3051 eval_for_line(arg, errp, nextcmdp, skip)
3052 char_u *arg;
3053 int *errp;
3054 char_u **nextcmdp;
3055 int skip;
3057 forinfo_T *fi;
3058 char_u *expr;
3059 typval_T tv;
3060 list_T *l;
3062 *errp = TRUE; /* default: there is an error */
3064 fi = (forinfo_T *)alloc_clear(sizeof(forinfo_T));
3065 if (fi == NULL)
3066 return NULL;
3068 expr = skip_var_list(arg, &fi->fi_varcount, &fi->fi_semicolon);
3069 if (expr == NULL)
3070 return fi;
3072 expr = skipwhite(expr);
3073 if (expr[0] != 'i' || expr[1] != 'n' || !vim_iswhite(expr[2]))
3075 EMSG(_("E690: Missing \"in\" after :for"));
3076 return fi;
3079 if (skip)
3080 ++emsg_skip;
3081 if (eval0(skipwhite(expr + 2), &tv, nextcmdp, !skip) == OK)
3083 *errp = FALSE;
3084 if (!skip)
3086 l = tv.vval.v_list;
3087 if (tv.v_type != VAR_LIST || l == NULL)
3089 EMSG(_(e_listreq));
3090 clear_tv(&tv);
3092 else
3094 /* No need to increment the refcount, it's already set for the
3095 * list being used in "tv". */
3096 fi->fi_list = l;
3097 list_add_watch(l, &fi->fi_lw);
3098 fi->fi_lw.lw_item = l->lv_first;
3102 if (skip)
3103 --emsg_skip;
3105 return fi;
3109 * Use the first item in a ":for" list. Advance to the next.
3110 * Assign the values to the variable (list). "arg" points to the first one.
3111 * Return TRUE when a valid item was found, FALSE when at end of list or
3112 * something wrong.
3115 next_for_item(fi_void, arg)
3116 void *fi_void;
3117 char_u *arg;
3119 forinfo_T *fi = (forinfo_T *)fi_void;
3120 int result;
3121 listitem_T *item;
3123 item = fi->fi_lw.lw_item;
3124 if (item == NULL)
3125 result = FALSE;
3126 else
3128 fi->fi_lw.lw_item = item->li_next;
3129 result = (ex_let_vars(arg, &item->li_tv, TRUE,
3130 fi->fi_semicolon, fi->fi_varcount, NULL) == OK);
3132 return result;
3136 * Free the structure used to store info used by ":for".
3138 void
3139 free_for_info(fi_void)
3140 void *fi_void;
3142 forinfo_T *fi = (forinfo_T *)fi_void;
3144 if (fi != NULL && fi->fi_list != NULL)
3146 list_rem_watch(fi->fi_list, &fi->fi_lw);
3147 list_unref(fi->fi_list);
3149 vim_free(fi);
3152 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3154 void
3155 set_context_for_expression(xp, arg, cmdidx)
3156 expand_T *xp;
3157 char_u *arg;
3158 cmdidx_T cmdidx;
3160 int got_eq = FALSE;
3161 int c;
3162 char_u *p;
3164 if (cmdidx == CMD_let)
3166 xp->xp_context = EXPAND_USER_VARS;
3167 if (vim_strpbrk(arg, (char_u *)"\"'+-*/%.=!?~|&$([<>,#") == NULL)
3169 /* ":let var1 var2 ...": find last space. */
3170 for (p = arg + STRLEN(arg); p >= arg; )
3172 xp->xp_pattern = p;
3173 mb_ptr_back(arg, p);
3174 if (vim_iswhite(*p))
3175 break;
3177 return;
3180 else
3181 xp->xp_context = cmdidx == CMD_call ? EXPAND_FUNCTIONS
3182 : EXPAND_EXPRESSION;
3183 while ((xp->xp_pattern = vim_strpbrk(arg,
3184 (char_u *)"\"'+-*/%.=!?~|&$([<>,#")) != NULL)
3186 c = *xp->xp_pattern;
3187 if (c == '&')
3189 c = xp->xp_pattern[1];
3190 if (c == '&')
3192 ++xp->xp_pattern;
3193 xp->xp_context = cmdidx != CMD_let || got_eq
3194 ? EXPAND_EXPRESSION : EXPAND_NOTHING;
3196 else if (c != ' ')
3198 xp->xp_context = EXPAND_SETTINGS;
3199 if ((c == 'l' || c == 'g') && xp->xp_pattern[2] == ':')
3200 xp->xp_pattern += 2;
3204 else if (c == '$')
3206 /* environment variable */
3207 xp->xp_context = EXPAND_ENV_VARS;
3209 else if (c == '=')
3211 got_eq = TRUE;
3212 xp->xp_context = EXPAND_EXPRESSION;
3214 else if (c == '<'
3215 && xp->xp_context == EXPAND_FUNCTIONS
3216 && vim_strchr(xp->xp_pattern, '(') == NULL)
3218 /* Function name can start with "<SNR>" */
3219 break;
3221 else if (cmdidx != CMD_let || got_eq)
3223 if (c == '"') /* string */
3225 while ((c = *++xp->xp_pattern) != NUL && c != '"')
3226 if (c == '\\' && xp->xp_pattern[1] != NUL)
3227 ++xp->xp_pattern;
3228 xp->xp_context = EXPAND_NOTHING;
3230 else if (c == '\'') /* literal string */
3232 /* Trick: '' is like stopping and starting a literal string. */
3233 while ((c = *++xp->xp_pattern) != NUL && c != '\'')
3234 /* skip */ ;
3235 xp->xp_context = EXPAND_NOTHING;
3237 else if (c == '|')
3239 if (xp->xp_pattern[1] == '|')
3241 ++xp->xp_pattern;
3242 xp->xp_context = EXPAND_EXPRESSION;
3244 else
3245 xp->xp_context = EXPAND_COMMANDS;
3247 else
3248 xp->xp_context = EXPAND_EXPRESSION;
3250 else
3251 /* Doesn't look like something valid, expand as an expression
3252 * anyway. */
3253 xp->xp_context = EXPAND_EXPRESSION;
3254 arg = xp->xp_pattern;
3255 if (*arg != NUL)
3256 while ((c = *++arg) != NUL && (c == ' ' || c == '\t'))
3257 /* skip */ ;
3259 xp->xp_pattern = arg;
3262 #endif /* FEAT_CMDL_COMPL */
3265 * ":1,25call func(arg1, arg2)" function call.
3267 void
3268 ex_call(eap)
3269 exarg_T *eap;
3271 char_u *arg = eap->arg;
3272 char_u *startarg;
3273 char_u *name;
3274 char_u *tofree;
3275 int len;
3276 typval_T rettv;
3277 linenr_T lnum;
3278 int doesrange;
3279 int failed = FALSE;
3280 funcdict_T fudi;
3282 tofree = trans_function_name(&arg, eap->skip, TFN_INT, &fudi);
3283 if (fudi.fd_newkey != NULL)
3285 /* Still need to give an error message for missing key. */
3286 EMSG2(_(e_dictkey), fudi.fd_newkey);
3287 vim_free(fudi.fd_newkey);
3289 if (tofree == NULL)
3290 return;
3292 /* Increase refcount on dictionary, it could get deleted when evaluating
3293 * the arguments. */
3294 if (fudi.fd_dict != NULL)
3295 ++fudi.fd_dict->dv_refcount;
3297 /* If it is the name of a variable of type VAR_FUNC use its contents. */
3298 len = (int)STRLEN(tofree);
3299 name = deref_func_name(tofree, &len);
3301 /* Skip white space to allow ":call func ()". Not good, but required for
3302 * backward compatibility. */
3303 startarg = skipwhite(arg);
3304 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
3306 if (*startarg != '(')
3308 EMSG2(_("E107: Missing parentheses: %s"), eap->arg);
3309 goto end;
3313 * When skipping, evaluate the function once, to find the end of the
3314 * arguments.
3315 * When the function takes a range, this is discovered after the first
3316 * call, and the loop is broken.
3318 if (eap->skip)
3320 ++emsg_skip;
3321 lnum = eap->line2; /* do it once, also with an invalid range */
3323 else
3324 lnum = eap->line1;
3325 for ( ; lnum <= eap->line2; ++lnum)
3327 if (!eap->skip && eap->addr_count > 0)
3329 curwin->w_cursor.lnum = lnum;
3330 curwin->w_cursor.col = 0;
3332 arg = startarg;
3333 if (get_func_tv(name, (int)STRLEN(name), &rettv, &arg,
3334 eap->line1, eap->line2, &doesrange,
3335 !eap->skip, fudi.fd_dict) == FAIL)
3337 failed = TRUE;
3338 break;
3341 /* Handle a function returning a Funcref, Dictionary or List. */
3342 if (handle_subscript(&arg, &rettv, !eap->skip, TRUE) == FAIL)
3344 failed = TRUE;
3345 break;
3348 clear_tv(&rettv);
3349 if (doesrange || eap->skip)
3350 break;
3352 /* Stop when immediately aborting on error, or when an interrupt
3353 * occurred or an exception was thrown but not caught.
3354 * get_func_tv() returned OK, so that the check for trailing
3355 * characters below is executed. */
3356 if (aborting())
3357 break;
3359 if (eap->skip)
3360 --emsg_skip;
3362 if (!failed)
3364 /* Check for trailing illegal characters and a following command. */
3365 if (!ends_excmd(*arg))
3367 emsg_severe = TRUE;
3368 EMSG(_(e_trailing));
3370 else
3371 eap->nextcmd = check_nextcmd(arg);
3374 end:
3375 dict_unref(fudi.fd_dict);
3376 vim_free(tofree);
3380 * ":unlet[!] var1 ... " command.
3382 void
3383 ex_unlet(eap)
3384 exarg_T *eap;
3386 ex_unletlock(eap, eap->arg, 0);
3390 * ":lockvar" and ":unlockvar" commands
3392 void
3393 ex_lockvar(eap)
3394 exarg_T *eap;
3396 char_u *arg = eap->arg;
3397 int deep = 2;
3399 if (eap->forceit)
3400 deep = -1;
3401 else if (vim_isdigit(*arg))
3403 deep = getdigits(&arg);
3404 arg = skipwhite(arg);
3407 ex_unletlock(eap, arg, deep);
3411 * ":unlet", ":lockvar" and ":unlockvar" are quite similar.
3413 static void
3414 ex_unletlock(eap, argstart, deep)
3415 exarg_T *eap;
3416 char_u *argstart;
3417 int deep;
3419 char_u *arg = argstart;
3420 char_u *name_end;
3421 int error = FALSE;
3422 lval_T lv;
3426 /* Parse the name and find the end. */
3427 name_end = get_lval(arg, NULL, &lv, TRUE, eap->skip || error, FALSE,
3428 FNE_CHECK_START);
3429 if (lv.ll_name == NULL)
3430 error = TRUE; /* error but continue parsing */
3431 if (name_end == NULL || (!vim_iswhite(*name_end)
3432 && !ends_excmd(*name_end)))
3434 if (name_end != NULL)
3436 emsg_severe = TRUE;
3437 EMSG(_(e_trailing));
3439 if (!(eap->skip || error))
3440 clear_lval(&lv);
3441 break;
3444 if (!error && !eap->skip)
3446 if (eap->cmdidx == CMD_unlet)
3448 if (do_unlet_var(&lv, name_end, eap->forceit) == FAIL)
3449 error = TRUE;
3451 else
3453 if (do_lock_var(&lv, name_end, deep,
3454 eap->cmdidx == CMD_lockvar) == FAIL)
3455 error = TRUE;
3459 if (!eap->skip)
3460 clear_lval(&lv);
3462 arg = skipwhite(name_end);
3463 } while (!ends_excmd(*arg));
3465 eap->nextcmd = check_nextcmd(arg);
3468 static int
3469 do_unlet_var(lp, name_end, forceit)
3470 lval_T *lp;
3471 char_u *name_end;
3472 int forceit;
3474 int ret = OK;
3475 int cc;
3477 if (lp->ll_tv == NULL)
3479 cc = *name_end;
3480 *name_end = NUL;
3482 /* Normal name or expanded name. */
3483 if (check_changedtick(lp->ll_name))
3484 ret = FAIL;
3485 else if (do_unlet(lp->ll_name, forceit) == FAIL)
3486 ret = FAIL;
3487 *name_end = cc;
3489 else if (tv_check_lock(lp->ll_tv->v_lock, lp->ll_name))
3490 return FAIL;
3491 else if (lp->ll_range)
3493 listitem_T *li;
3495 /* Delete a range of List items. */
3496 while (lp->ll_li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3498 li = lp->ll_li->li_next;
3499 listitem_remove(lp->ll_list, lp->ll_li);
3500 lp->ll_li = li;
3501 ++lp->ll_n1;
3504 else
3506 if (lp->ll_list != NULL)
3507 /* unlet a List item. */
3508 listitem_remove(lp->ll_list, lp->ll_li);
3509 else
3510 /* unlet a Dictionary item. */
3511 dictitem_remove(lp->ll_dict, lp->ll_di);
3514 return ret;
3518 * "unlet" a variable. Return OK if it existed, FAIL if not.
3519 * When "forceit" is TRUE don't complain if the variable doesn't exist.
3522 do_unlet(name, forceit)
3523 char_u *name;
3524 int forceit;
3526 hashtab_T *ht;
3527 hashitem_T *hi;
3528 char_u *varname;
3529 dictitem_T *di;
3531 ht = find_var_ht(name, &varname);
3532 if (ht != NULL && *varname != NUL)
3534 hi = hash_find(ht, varname);
3535 if (!HASHITEM_EMPTY(hi))
3537 di = HI2DI(hi);
3538 if (var_check_fixed(di->di_flags, name)
3539 || var_check_ro(di->di_flags, name))
3540 return FAIL;
3541 delete_var(ht, hi);
3542 return OK;
3545 if (forceit)
3546 return OK;
3547 EMSG2(_("E108: No such variable: \"%s\""), name);
3548 return FAIL;
3552 * Lock or unlock variable indicated by "lp".
3553 * "deep" is the levels to go (-1 for unlimited);
3554 * "lock" is TRUE for ":lockvar", FALSE for ":unlockvar".
3556 static int
3557 do_lock_var(lp, name_end, deep, lock)
3558 lval_T *lp;
3559 char_u *name_end;
3560 int deep;
3561 int lock;
3563 int ret = OK;
3564 int cc;
3565 dictitem_T *di;
3567 if (deep == 0) /* nothing to do */
3568 return OK;
3570 if (lp->ll_tv == NULL)
3572 cc = *name_end;
3573 *name_end = NUL;
3575 /* Normal name or expanded name. */
3576 if (check_changedtick(lp->ll_name))
3577 ret = FAIL;
3578 else
3580 di = find_var(lp->ll_name, NULL);
3581 if (di == NULL)
3582 ret = FAIL;
3583 else
3585 if (lock)
3586 di->di_flags |= DI_FLAGS_LOCK;
3587 else
3588 di->di_flags &= ~DI_FLAGS_LOCK;
3589 item_lock(&di->di_tv, deep, lock);
3592 *name_end = cc;
3594 else if (lp->ll_range)
3596 listitem_T *li = lp->ll_li;
3598 /* (un)lock a range of List items. */
3599 while (li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3601 item_lock(&li->li_tv, deep, lock);
3602 li = li->li_next;
3603 ++lp->ll_n1;
3606 else if (lp->ll_list != NULL)
3607 /* (un)lock a List item. */
3608 item_lock(&lp->ll_li->li_tv, deep, lock);
3609 else
3610 /* un(lock) a Dictionary item. */
3611 item_lock(&lp->ll_di->di_tv, deep, lock);
3613 return ret;
3617 * Lock or unlock an item. "deep" is nr of levels to go.
3619 static void
3620 item_lock(tv, deep, lock)
3621 typval_T *tv;
3622 int deep;
3623 int lock;
3625 static int recurse = 0;
3626 list_T *l;
3627 listitem_T *li;
3628 dict_T *d;
3629 hashitem_T *hi;
3630 int todo;
3632 if (recurse >= DICT_MAXNEST)
3634 EMSG(_("E743: variable nested too deep for (un)lock"));
3635 return;
3637 if (deep == 0)
3638 return;
3639 ++recurse;
3641 /* lock/unlock the item itself */
3642 if (lock)
3643 tv->v_lock |= VAR_LOCKED;
3644 else
3645 tv->v_lock &= ~VAR_LOCKED;
3647 switch (tv->v_type)
3649 case VAR_LIST:
3650 if ((l = tv->vval.v_list) != NULL)
3652 if (lock)
3653 l->lv_lock |= VAR_LOCKED;
3654 else
3655 l->lv_lock &= ~VAR_LOCKED;
3656 if (deep < 0 || deep > 1)
3657 /* recursive: lock/unlock the items the List contains */
3658 for (li = l->lv_first; li != NULL; li = li->li_next)
3659 item_lock(&li->li_tv, deep - 1, lock);
3661 break;
3662 case VAR_DICT:
3663 if ((d = tv->vval.v_dict) != NULL)
3665 if (lock)
3666 d->dv_lock |= VAR_LOCKED;
3667 else
3668 d->dv_lock &= ~VAR_LOCKED;
3669 if (deep < 0 || deep > 1)
3671 /* recursive: lock/unlock the items the List contains */
3672 todo = (int)d->dv_hashtab.ht_used;
3673 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
3675 if (!HASHITEM_EMPTY(hi))
3677 --todo;
3678 item_lock(&HI2DI(hi)->di_tv, deep - 1, lock);
3684 --recurse;
3688 * Return TRUE if typeval "tv" is locked: Either that value is locked itself
3689 * or it refers to a List or Dictionary that is locked.
3691 static int
3692 tv_islocked(tv)
3693 typval_T *tv;
3695 return (tv->v_lock & VAR_LOCKED)
3696 || (tv->v_type == VAR_LIST
3697 && tv->vval.v_list != NULL
3698 && (tv->vval.v_list->lv_lock & VAR_LOCKED))
3699 || (tv->v_type == VAR_DICT
3700 && tv->vval.v_dict != NULL
3701 && (tv->vval.v_dict->dv_lock & VAR_LOCKED));
3704 #if (defined(FEAT_MENU) && defined(FEAT_MULTI_LANG)) || defined(PROTO)
3706 * Delete all "menutrans_" variables.
3708 void
3709 del_menutrans_vars()
3711 hashitem_T *hi;
3712 int todo;
3714 hash_lock(&globvarht);
3715 todo = (int)globvarht.ht_used;
3716 for (hi = globvarht.ht_array; todo > 0 && !got_int; ++hi)
3718 if (!HASHITEM_EMPTY(hi))
3720 --todo;
3721 if (STRNCMP(HI2DI(hi)->di_key, "menutrans_", 10) == 0)
3722 delete_var(&globvarht, hi);
3725 hash_unlock(&globvarht);
3727 #endif
3729 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3732 * Local string buffer for the next two functions to store a variable name
3733 * with its prefix. Allocated in cat_prefix_varname(), freed later in
3734 * get_user_var_name().
3737 static char_u *cat_prefix_varname __ARGS((int prefix, char_u *name));
3739 static char_u *varnamebuf = NULL;
3740 static int varnamebuflen = 0;
3743 * Function to concatenate a prefix and a variable name.
3745 static char_u *
3746 cat_prefix_varname(prefix, name)
3747 int prefix;
3748 char_u *name;
3750 int len;
3752 len = (int)STRLEN(name) + 3;
3753 if (len > varnamebuflen)
3755 vim_free(varnamebuf);
3756 len += 10; /* some additional space */
3757 varnamebuf = alloc(len);
3758 if (varnamebuf == NULL)
3760 varnamebuflen = 0;
3761 return NULL;
3763 varnamebuflen = len;
3765 *varnamebuf = prefix;
3766 varnamebuf[1] = ':';
3767 STRCPY(varnamebuf + 2, name);
3768 return varnamebuf;
3772 * Function given to ExpandGeneric() to obtain the list of user defined
3773 * (global/buffer/window/built-in) variable names.
3775 /*ARGSUSED*/
3776 char_u *
3777 get_user_var_name(xp, idx)
3778 expand_T *xp;
3779 int idx;
3781 static long_u gdone;
3782 static long_u bdone;
3783 static long_u wdone;
3784 #ifdef FEAT_WINDOWS
3785 static long_u tdone;
3786 #endif
3787 static int vidx;
3788 static hashitem_T *hi;
3789 hashtab_T *ht;
3791 if (idx == 0)
3793 gdone = bdone = wdone = vidx = 0;
3794 #ifdef FEAT_WINDOWS
3795 tdone = 0;
3796 #endif
3799 /* Global variables */
3800 if (gdone < globvarht.ht_used)
3802 if (gdone++ == 0)
3803 hi = globvarht.ht_array;
3804 else
3805 ++hi;
3806 while (HASHITEM_EMPTY(hi))
3807 ++hi;
3808 if (STRNCMP("g:", xp->xp_pattern, 2) == 0)
3809 return cat_prefix_varname('g', hi->hi_key);
3810 return hi->hi_key;
3813 /* b: variables */
3814 ht = &curbuf->b_vars.dv_hashtab;
3815 if (bdone < ht->ht_used)
3817 if (bdone++ == 0)
3818 hi = ht->ht_array;
3819 else
3820 ++hi;
3821 while (HASHITEM_EMPTY(hi))
3822 ++hi;
3823 return cat_prefix_varname('b', hi->hi_key);
3825 if (bdone == ht->ht_used)
3827 ++bdone;
3828 return (char_u *)"b:changedtick";
3831 /* w: variables */
3832 ht = &curwin->w_vars.dv_hashtab;
3833 if (wdone < ht->ht_used)
3835 if (wdone++ == 0)
3836 hi = ht->ht_array;
3837 else
3838 ++hi;
3839 while (HASHITEM_EMPTY(hi))
3840 ++hi;
3841 return cat_prefix_varname('w', hi->hi_key);
3844 #ifdef FEAT_WINDOWS
3845 /* t: variables */
3846 ht = &curtab->tp_vars.dv_hashtab;
3847 if (tdone < ht->ht_used)
3849 if (tdone++ == 0)
3850 hi = ht->ht_array;
3851 else
3852 ++hi;
3853 while (HASHITEM_EMPTY(hi))
3854 ++hi;
3855 return cat_prefix_varname('t', hi->hi_key);
3857 #endif
3859 /* v: variables */
3860 if (vidx < VV_LEN)
3861 return cat_prefix_varname('v', (char_u *)vimvars[vidx++].vv_name);
3863 vim_free(varnamebuf);
3864 varnamebuf = NULL;
3865 varnamebuflen = 0;
3866 return NULL;
3869 #endif /* FEAT_CMDL_COMPL */
3872 * types for expressions.
3874 typedef enum
3876 TYPE_UNKNOWN = 0
3877 , TYPE_EQUAL /* == */
3878 , TYPE_NEQUAL /* != */
3879 , TYPE_GREATER /* > */
3880 , TYPE_GEQUAL /* >= */
3881 , TYPE_SMALLER /* < */
3882 , TYPE_SEQUAL /* <= */
3883 , TYPE_MATCH /* =~ */
3884 , TYPE_NOMATCH /* !~ */
3885 } exptype_T;
3888 * The "evaluate" argument: When FALSE, the argument is only parsed but not
3889 * executed. The function may return OK, but the rettv will be of type
3890 * VAR_UNKNOWN. The function still returns FAIL for a syntax error.
3894 * Handle zero level expression.
3895 * This calls eval1() and handles error message and nextcmd.
3896 * Put the result in "rettv" when returning OK and "evaluate" is TRUE.
3897 * Note: "rettv.v_lock" is not set.
3898 * Return OK or FAIL.
3900 static int
3901 eval0(arg, rettv, nextcmd, evaluate)
3902 char_u *arg;
3903 typval_T *rettv;
3904 char_u **nextcmd;
3905 int evaluate;
3907 int ret;
3908 char_u *p;
3910 p = skipwhite(arg);
3911 ret = eval1(&p, rettv, evaluate);
3912 if (ret == FAIL || !ends_excmd(*p))
3914 if (ret != FAIL)
3915 clear_tv(rettv);
3917 * Report the invalid expression unless the expression evaluation has
3918 * been cancelled due to an aborting error, an interrupt, or an
3919 * exception.
3921 if (!aborting())
3922 EMSG2(_(e_invexpr2), arg);
3923 ret = FAIL;
3925 if (nextcmd != NULL)
3926 *nextcmd = check_nextcmd(p);
3928 return ret;
3932 * Handle top level expression:
3933 * expr2 ? expr1 : expr1
3935 * "arg" must point to the first non-white of the expression.
3936 * "arg" is advanced to the next non-white after the recognized expression.
3938 * Note: "rettv.v_lock" is not set.
3940 * Return OK or FAIL.
3942 static int
3943 eval1(arg, rettv, evaluate)
3944 char_u **arg;
3945 typval_T *rettv;
3946 int evaluate;
3948 int result;
3949 typval_T var2;
3952 * Get the first variable.
3954 if (eval2(arg, rettv, evaluate) == FAIL)
3955 return FAIL;
3957 if ((*arg)[0] == '?')
3959 result = FALSE;
3960 if (evaluate)
3962 int error = FALSE;
3964 if (get_tv_number_chk(rettv, &error) != 0)
3965 result = TRUE;
3966 clear_tv(rettv);
3967 if (error)
3968 return FAIL;
3972 * Get the second variable.
3974 *arg = skipwhite(*arg + 1);
3975 if (eval1(arg, rettv, evaluate && result) == FAIL) /* recursive! */
3976 return FAIL;
3979 * Check for the ":".
3981 if ((*arg)[0] != ':')
3983 EMSG(_("E109: Missing ':' after '?'"));
3984 if (evaluate && result)
3985 clear_tv(rettv);
3986 return FAIL;
3990 * Get the third variable.
3992 *arg = skipwhite(*arg + 1);
3993 if (eval1(arg, &var2, evaluate && !result) == FAIL) /* recursive! */
3995 if (evaluate && result)
3996 clear_tv(rettv);
3997 return FAIL;
3999 if (evaluate && !result)
4000 *rettv = var2;
4003 return OK;
4007 * Handle first level expression:
4008 * expr2 || expr2 || expr2 logical OR
4010 * "arg" must point to the first non-white of the expression.
4011 * "arg" is advanced to the next non-white after the recognized expression.
4013 * Return OK or FAIL.
4015 static int
4016 eval2(arg, rettv, evaluate)
4017 char_u **arg;
4018 typval_T *rettv;
4019 int evaluate;
4021 typval_T var2;
4022 long result;
4023 int first;
4024 int error = FALSE;
4027 * Get the first variable.
4029 if (eval3(arg, rettv, evaluate) == FAIL)
4030 return FAIL;
4033 * Repeat until there is no following "||".
4035 first = TRUE;
4036 result = FALSE;
4037 while ((*arg)[0] == '|' && (*arg)[1] == '|')
4039 if (evaluate && first)
4041 if (get_tv_number_chk(rettv, &error) != 0)
4042 result = TRUE;
4043 clear_tv(rettv);
4044 if (error)
4045 return FAIL;
4046 first = FALSE;
4050 * Get the second variable.
4052 *arg = skipwhite(*arg + 2);
4053 if (eval3(arg, &var2, evaluate && !result) == FAIL)
4054 return FAIL;
4057 * Compute the result.
4059 if (evaluate && !result)
4061 if (get_tv_number_chk(&var2, &error) != 0)
4062 result = TRUE;
4063 clear_tv(&var2);
4064 if (error)
4065 return FAIL;
4067 if (evaluate)
4069 rettv->v_type = VAR_NUMBER;
4070 rettv->vval.v_number = result;
4074 return OK;
4078 * Handle second level expression:
4079 * expr3 && expr3 && expr3 logical AND
4081 * "arg" must point to the first non-white of the expression.
4082 * "arg" is advanced to the next non-white after the recognized expression.
4084 * Return OK or FAIL.
4086 static int
4087 eval3(arg, rettv, evaluate)
4088 char_u **arg;
4089 typval_T *rettv;
4090 int evaluate;
4092 typval_T var2;
4093 long result;
4094 int first;
4095 int error = FALSE;
4098 * Get the first variable.
4100 if (eval4(arg, rettv, evaluate) == FAIL)
4101 return FAIL;
4104 * Repeat until there is no following "&&".
4106 first = TRUE;
4107 result = TRUE;
4108 while ((*arg)[0] == '&' && (*arg)[1] == '&')
4110 if (evaluate && first)
4112 if (get_tv_number_chk(rettv, &error) == 0)
4113 result = FALSE;
4114 clear_tv(rettv);
4115 if (error)
4116 return FAIL;
4117 first = FALSE;
4121 * Get the second variable.
4123 *arg = skipwhite(*arg + 2);
4124 if (eval4(arg, &var2, evaluate && result) == FAIL)
4125 return FAIL;
4128 * Compute the result.
4130 if (evaluate && result)
4132 if (get_tv_number_chk(&var2, &error) == 0)
4133 result = FALSE;
4134 clear_tv(&var2);
4135 if (error)
4136 return FAIL;
4138 if (evaluate)
4140 rettv->v_type = VAR_NUMBER;
4141 rettv->vval.v_number = result;
4145 return OK;
4149 * Handle third level expression:
4150 * var1 == var2
4151 * var1 =~ var2
4152 * var1 != var2
4153 * var1 !~ var2
4154 * var1 > var2
4155 * var1 >= var2
4156 * var1 < var2
4157 * var1 <= var2
4158 * var1 is var2
4159 * var1 isnot var2
4161 * "arg" must point to the first non-white of the expression.
4162 * "arg" is advanced to the next non-white after the recognized expression.
4164 * Return OK or FAIL.
4166 static int
4167 eval4(arg, rettv, evaluate)
4168 char_u **arg;
4169 typval_T *rettv;
4170 int evaluate;
4172 typval_T var2;
4173 char_u *p;
4174 int i;
4175 exptype_T type = TYPE_UNKNOWN;
4176 int type_is = FALSE; /* TRUE for "is" and "isnot" */
4177 int len = 2;
4178 long n1, n2;
4179 char_u *s1, *s2;
4180 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
4181 regmatch_T regmatch;
4182 int ic;
4183 char_u *save_cpo;
4186 * Get the first variable.
4188 if (eval5(arg, rettv, evaluate) == FAIL)
4189 return FAIL;
4191 p = *arg;
4192 switch (p[0])
4194 case '=': if (p[1] == '=')
4195 type = TYPE_EQUAL;
4196 else if (p[1] == '~')
4197 type = TYPE_MATCH;
4198 break;
4199 case '!': if (p[1] == '=')
4200 type = TYPE_NEQUAL;
4201 else if (p[1] == '~')
4202 type = TYPE_NOMATCH;
4203 break;
4204 case '>': if (p[1] != '=')
4206 type = TYPE_GREATER;
4207 len = 1;
4209 else
4210 type = TYPE_GEQUAL;
4211 break;
4212 case '<': if (p[1] != '=')
4214 type = TYPE_SMALLER;
4215 len = 1;
4217 else
4218 type = TYPE_SEQUAL;
4219 break;
4220 case 'i': if (p[1] == 's')
4222 if (p[2] == 'n' && p[3] == 'o' && p[4] == 't')
4223 len = 5;
4224 if (!vim_isIDc(p[len]))
4226 type = len == 2 ? TYPE_EQUAL : TYPE_NEQUAL;
4227 type_is = TRUE;
4230 break;
4234 * If there is a comparative operator, use it.
4236 if (type != TYPE_UNKNOWN)
4238 /* extra question mark appended: ignore case */
4239 if (p[len] == '?')
4241 ic = TRUE;
4242 ++len;
4244 /* extra '#' appended: match case */
4245 else if (p[len] == '#')
4247 ic = FALSE;
4248 ++len;
4250 /* nothing appended: use 'ignorecase' */
4251 else
4252 ic = p_ic;
4255 * Get the second variable.
4257 *arg = skipwhite(p + len);
4258 if (eval5(arg, &var2, evaluate) == FAIL)
4260 clear_tv(rettv);
4261 return FAIL;
4264 if (evaluate)
4266 if (type_is && rettv->v_type != var2.v_type)
4268 /* For "is" a different type always means FALSE, for "notis"
4269 * it means TRUE. */
4270 n1 = (type == TYPE_NEQUAL);
4272 else if (rettv->v_type == VAR_LIST || var2.v_type == VAR_LIST)
4274 if (type_is)
4276 n1 = (rettv->v_type == var2.v_type
4277 && rettv->vval.v_list == var2.vval.v_list);
4278 if (type == TYPE_NEQUAL)
4279 n1 = !n1;
4281 else if (rettv->v_type != var2.v_type
4282 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4284 if (rettv->v_type != var2.v_type)
4285 EMSG(_("E691: Can only compare List with List"));
4286 else
4287 EMSG(_("E692: Invalid operation for Lists"));
4288 clear_tv(rettv);
4289 clear_tv(&var2);
4290 return FAIL;
4292 else
4294 /* Compare two Lists for being equal or unequal. */
4295 n1 = list_equal(rettv->vval.v_list, var2.vval.v_list, ic);
4296 if (type == TYPE_NEQUAL)
4297 n1 = !n1;
4301 else if (rettv->v_type == VAR_DICT || var2.v_type == VAR_DICT)
4303 if (type_is)
4305 n1 = (rettv->v_type == var2.v_type
4306 && rettv->vval.v_dict == var2.vval.v_dict);
4307 if (type == TYPE_NEQUAL)
4308 n1 = !n1;
4310 else if (rettv->v_type != var2.v_type
4311 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4313 if (rettv->v_type != var2.v_type)
4314 EMSG(_("E735: Can only compare Dictionary with Dictionary"));
4315 else
4316 EMSG(_("E736: Invalid operation for Dictionary"));
4317 clear_tv(rettv);
4318 clear_tv(&var2);
4319 return FAIL;
4321 else
4323 /* Compare two Dictionaries for being equal or unequal. */
4324 n1 = dict_equal(rettv->vval.v_dict, var2.vval.v_dict, ic);
4325 if (type == TYPE_NEQUAL)
4326 n1 = !n1;
4330 else if (rettv->v_type == VAR_FUNC || var2.v_type == VAR_FUNC)
4332 if (rettv->v_type != var2.v_type
4333 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4335 if (rettv->v_type != var2.v_type)
4336 EMSG(_("E693: Can only compare Funcref with Funcref"));
4337 else
4338 EMSG(_("E694: Invalid operation for Funcrefs"));
4339 clear_tv(rettv);
4340 clear_tv(&var2);
4341 return FAIL;
4343 else
4345 /* Compare two Funcrefs for being equal or unequal. */
4346 if (rettv->vval.v_string == NULL
4347 || var2.vval.v_string == NULL)
4348 n1 = FALSE;
4349 else
4350 n1 = STRCMP(rettv->vval.v_string,
4351 var2.vval.v_string) == 0;
4352 if (type == TYPE_NEQUAL)
4353 n1 = !n1;
4357 #ifdef FEAT_FLOAT
4359 * If one of the two variables is a float, compare as a float.
4360 * When using "=~" or "!~", always compare as string.
4362 else if ((rettv->v_type == VAR_FLOAT || var2.v_type == VAR_FLOAT)
4363 && type != TYPE_MATCH && type != TYPE_NOMATCH)
4365 float_T f1, f2;
4367 if (rettv->v_type == VAR_FLOAT)
4368 f1 = rettv->vval.v_float;
4369 else
4370 f1 = get_tv_number(rettv);
4371 if (var2.v_type == VAR_FLOAT)
4372 f2 = var2.vval.v_float;
4373 else
4374 f2 = get_tv_number(&var2);
4375 n1 = FALSE;
4376 switch (type)
4378 case TYPE_EQUAL: n1 = (f1 == f2); break;
4379 case TYPE_NEQUAL: n1 = (f1 != f2); break;
4380 case TYPE_GREATER: n1 = (f1 > f2); break;
4381 case TYPE_GEQUAL: n1 = (f1 >= f2); break;
4382 case TYPE_SMALLER: n1 = (f1 < f2); break;
4383 case TYPE_SEQUAL: n1 = (f1 <= f2); break;
4384 case TYPE_UNKNOWN:
4385 case TYPE_MATCH:
4386 case TYPE_NOMATCH: break; /* avoid gcc warning */
4389 #endif
4392 * If one of the two variables is a number, compare as a number.
4393 * When using "=~" or "!~", always compare as string.
4395 else if ((rettv->v_type == VAR_NUMBER || var2.v_type == VAR_NUMBER)
4396 && type != TYPE_MATCH && type != TYPE_NOMATCH)
4398 n1 = get_tv_number(rettv);
4399 n2 = get_tv_number(&var2);
4400 switch (type)
4402 case TYPE_EQUAL: n1 = (n1 == n2); break;
4403 case TYPE_NEQUAL: n1 = (n1 != n2); break;
4404 case TYPE_GREATER: n1 = (n1 > n2); break;
4405 case TYPE_GEQUAL: n1 = (n1 >= n2); break;
4406 case TYPE_SMALLER: n1 = (n1 < n2); break;
4407 case TYPE_SEQUAL: n1 = (n1 <= n2); break;
4408 case TYPE_UNKNOWN:
4409 case TYPE_MATCH:
4410 case TYPE_NOMATCH: break; /* avoid gcc warning */
4413 else
4415 s1 = get_tv_string_buf(rettv, buf1);
4416 s2 = get_tv_string_buf(&var2, buf2);
4417 if (type != TYPE_MATCH && type != TYPE_NOMATCH)
4418 i = ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2);
4419 else
4420 i = 0;
4421 n1 = FALSE;
4422 switch (type)
4424 case TYPE_EQUAL: n1 = (i == 0); break;
4425 case TYPE_NEQUAL: n1 = (i != 0); break;
4426 case TYPE_GREATER: n1 = (i > 0); break;
4427 case TYPE_GEQUAL: n1 = (i >= 0); break;
4428 case TYPE_SMALLER: n1 = (i < 0); break;
4429 case TYPE_SEQUAL: n1 = (i <= 0); break;
4431 case TYPE_MATCH:
4432 case TYPE_NOMATCH:
4433 /* avoid 'l' flag in 'cpoptions' */
4434 save_cpo = p_cpo;
4435 p_cpo = (char_u *)"";
4436 regmatch.regprog = vim_regcomp(s2,
4437 RE_MAGIC + RE_STRING);
4438 regmatch.rm_ic = ic;
4439 if (regmatch.regprog != NULL)
4441 n1 = vim_regexec_nl(&regmatch, s1, (colnr_T)0);
4442 vim_free(regmatch.regprog);
4443 if (type == TYPE_NOMATCH)
4444 n1 = !n1;
4446 p_cpo = save_cpo;
4447 break;
4449 case TYPE_UNKNOWN: break; /* avoid gcc warning */
4452 clear_tv(rettv);
4453 clear_tv(&var2);
4454 rettv->v_type = VAR_NUMBER;
4455 rettv->vval.v_number = n1;
4459 return OK;
4463 * Handle fourth level expression:
4464 * + number addition
4465 * - number subtraction
4466 * . string concatenation
4468 * "arg" must point to the first non-white of the expression.
4469 * "arg" is advanced to the next non-white after the recognized expression.
4471 * Return OK or FAIL.
4473 static int
4474 eval5(arg, rettv, evaluate)
4475 char_u **arg;
4476 typval_T *rettv;
4477 int evaluate;
4479 typval_T var2;
4480 typval_T var3;
4481 int op;
4482 long n1, n2;
4483 #ifdef FEAT_FLOAT
4484 float_T f1 = 0, f2 = 0;
4485 #endif
4486 char_u *s1, *s2;
4487 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
4488 char_u *p;
4491 * Get the first variable.
4493 if (eval6(arg, rettv, evaluate, FALSE) == FAIL)
4494 return FAIL;
4497 * Repeat computing, until no '+', '-' or '.' is following.
4499 for (;;)
4501 op = **arg;
4502 if (op != '+' && op != '-' && op != '.')
4503 break;
4505 if ((op != '+' || rettv->v_type != VAR_LIST)
4506 #ifdef FEAT_FLOAT
4507 && (op == '.' || rettv->v_type != VAR_FLOAT)
4508 #endif
4511 /* For "list + ...", an illegal use of the first operand as
4512 * a number cannot be determined before evaluating the 2nd
4513 * operand: if this is also a list, all is ok.
4514 * For "something . ...", "something - ..." or "non-list + ...",
4515 * we know that the first operand needs to be a string or number
4516 * without evaluating the 2nd operand. So check before to avoid
4517 * side effects after an error. */
4518 if (evaluate && get_tv_string_chk(rettv) == NULL)
4520 clear_tv(rettv);
4521 return FAIL;
4526 * Get the second variable.
4528 *arg = skipwhite(*arg + 1);
4529 if (eval6(arg, &var2, evaluate, op == '.') == FAIL)
4531 clear_tv(rettv);
4532 return FAIL;
4535 if (evaluate)
4538 * Compute the result.
4540 if (op == '.')
4542 s1 = get_tv_string_buf(rettv, buf1); /* already checked */
4543 s2 = get_tv_string_buf_chk(&var2, buf2);
4544 if (s2 == NULL) /* type error ? */
4546 clear_tv(rettv);
4547 clear_tv(&var2);
4548 return FAIL;
4550 p = concat_str(s1, s2);
4551 clear_tv(rettv);
4552 rettv->v_type = VAR_STRING;
4553 rettv->vval.v_string = p;
4555 else if (op == '+' && rettv->v_type == VAR_LIST
4556 && var2.v_type == VAR_LIST)
4558 /* concatenate Lists */
4559 if (list_concat(rettv->vval.v_list, var2.vval.v_list,
4560 &var3) == FAIL)
4562 clear_tv(rettv);
4563 clear_tv(&var2);
4564 return FAIL;
4566 clear_tv(rettv);
4567 *rettv = var3;
4569 else
4571 int error = FALSE;
4573 #ifdef FEAT_FLOAT
4574 if (rettv->v_type == VAR_FLOAT)
4576 f1 = rettv->vval.v_float;
4577 n1 = 0;
4579 else
4580 #endif
4582 n1 = get_tv_number_chk(rettv, &error);
4583 if (error)
4585 /* This can only happen for "list + non-list". For
4586 * "non-list + ..." or "something - ...", we returned
4587 * before evaluating the 2nd operand. */
4588 clear_tv(rettv);
4589 return FAIL;
4591 #ifdef FEAT_FLOAT
4592 if (var2.v_type == VAR_FLOAT)
4593 f1 = n1;
4594 #endif
4596 #ifdef FEAT_FLOAT
4597 if (var2.v_type == VAR_FLOAT)
4599 f2 = var2.vval.v_float;
4600 n2 = 0;
4602 else
4603 #endif
4605 n2 = get_tv_number_chk(&var2, &error);
4606 if (error)
4608 clear_tv(rettv);
4609 clear_tv(&var2);
4610 return FAIL;
4612 #ifdef FEAT_FLOAT
4613 if (rettv->v_type == VAR_FLOAT)
4614 f2 = n2;
4615 #endif
4617 clear_tv(rettv);
4619 #ifdef FEAT_FLOAT
4620 /* If there is a float on either side the result is a float. */
4621 if (rettv->v_type == VAR_FLOAT || var2.v_type == VAR_FLOAT)
4623 if (op == '+')
4624 f1 = f1 + f2;
4625 else
4626 f1 = f1 - f2;
4627 rettv->v_type = VAR_FLOAT;
4628 rettv->vval.v_float = f1;
4630 else
4631 #endif
4633 if (op == '+')
4634 n1 = n1 + n2;
4635 else
4636 n1 = n1 - n2;
4637 rettv->v_type = VAR_NUMBER;
4638 rettv->vval.v_number = n1;
4641 clear_tv(&var2);
4644 return OK;
4648 * Handle fifth level expression:
4649 * * number multiplication
4650 * / number division
4651 * % number modulo
4653 * "arg" must point to the first non-white of the expression.
4654 * "arg" is advanced to the next non-white after the recognized expression.
4656 * Return OK or FAIL.
4658 static int
4659 eval6(arg, rettv, evaluate, want_string)
4660 char_u **arg;
4661 typval_T *rettv;
4662 int evaluate;
4663 int want_string; /* after "." operator */
4665 typval_T var2;
4666 int op;
4667 long n1, n2;
4668 #ifdef FEAT_FLOAT
4669 int use_float = FALSE;
4670 float_T f1 = 0, f2;
4671 #endif
4672 int error = FALSE;
4675 * Get the first variable.
4677 if (eval7(arg, rettv, evaluate, want_string) == FAIL)
4678 return FAIL;
4681 * Repeat computing, until no '*', '/' or '%' is following.
4683 for (;;)
4685 op = **arg;
4686 if (op != '*' && op != '/' && op != '%')
4687 break;
4689 if (evaluate)
4691 #ifdef FEAT_FLOAT
4692 if (rettv->v_type == VAR_FLOAT)
4694 f1 = rettv->vval.v_float;
4695 use_float = TRUE;
4696 n1 = 0;
4698 else
4699 #endif
4700 n1 = get_tv_number_chk(rettv, &error);
4701 clear_tv(rettv);
4702 if (error)
4703 return FAIL;
4705 else
4706 n1 = 0;
4709 * Get the second variable.
4711 *arg = skipwhite(*arg + 1);
4712 if (eval7(arg, &var2, evaluate, FALSE) == FAIL)
4713 return FAIL;
4715 if (evaluate)
4717 #ifdef FEAT_FLOAT
4718 if (var2.v_type == VAR_FLOAT)
4720 if (!use_float)
4722 f1 = n1;
4723 use_float = TRUE;
4725 f2 = var2.vval.v_float;
4726 n2 = 0;
4728 else
4729 #endif
4731 n2 = get_tv_number_chk(&var2, &error);
4732 clear_tv(&var2);
4733 if (error)
4734 return FAIL;
4735 #ifdef FEAT_FLOAT
4736 if (use_float)
4737 f2 = n2;
4738 #endif
4742 * Compute the result.
4743 * When either side is a float the result is a float.
4745 #ifdef FEAT_FLOAT
4746 if (use_float)
4748 if (op == '*')
4749 f1 = f1 * f2;
4750 else if (op == '/')
4752 /* We rely on the floating point library to handle divide
4753 * by zero to result in "inf" and not a crash. */
4754 f1 = f1 / f2;
4756 else
4758 EMSG(_("E804: Cannot use '%' with Float"));
4759 return FAIL;
4761 rettv->v_type = VAR_FLOAT;
4762 rettv->vval.v_float = f1;
4764 else
4765 #endif
4767 if (op == '*')
4768 n1 = n1 * n2;
4769 else if (op == '/')
4771 if (n2 == 0) /* give an error message? */
4773 if (n1 == 0)
4774 n1 = -0x7fffffffL - 1L; /* similar to NaN */
4775 else if (n1 < 0)
4776 n1 = -0x7fffffffL;
4777 else
4778 n1 = 0x7fffffffL;
4780 else
4781 n1 = n1 / n2;
4783 else
4785 if (n2 == 0) /* give an error message? */
4786 n1 = 0;
4787 else
4788 n1 = n1 % n2;
4790 rettv->v_type = VAR_NUMBER;
4791 rettv->vval.v_number = n1;
4796 return OK;
4800 * Handle sixth level expression:
4801 * number number constant
4802 * "string" string constant
4803 * 'string' literal string constant
4804 * &option-name option value
4805 * @r register contents
4806 * identifier variable value
4807 * function() function call
4808 * $VAR environment variable
4809 * (expression) nested expression
4810 * [expr, expr] List
4811 * {key: val, key: val} Dictionary
4813 * Also handle:
4814 * ! in front logical NOT
4815 * - in front unary minus
4816 * + in front unary plus (ignored)
4817 * trailing [] subscript in String or List
4818 * trailing .name entry in Dictionary
4820 * "arg" must point to the first non-white of the expression.
4821 * "arg" is advanced to the next non-white after the recognized expression.
4823 * Return OK or FAIL.
4825 static int
4826 eval7(arg, rettv, evaluate, want_string)
4827 char_u **arg;
4828 typval_T *rettv;
4829 int evaluate;
4830 int want_string; /* after "." operator */
4832 long n;
4833 int len;
4834 char_u *s;
4835 char_u *start_leader, *end_leader;
4836 int ret = OK;
4837 char_u *alias;
4840 * Initialise variable so that clear_tv() can't mistake this for a
4841 * string and free a string that isn't there.
4843 rettv->v_type = VAR_UNKNOWN;
4846 * Skip '!' and '-' characters. They are handled later.
4848 start_leader = *arg;
4849 while (**arg == '!' || **arg == '-' || **arg == '+')
4850 *arg = skipwhite(*arg + 1);
4851 end_leader = *arg;
4853 switch (**arg)
4856 * Number constant.
4858 case '0':
4859 case '1':
4860 case '2':
4861 case '3':
4862 case '4':
4863 case '5':
4864 case '6':
4865 case '7':
4866 case '8':
4867 case '9':
4869 #ifdef FEAT_FLOAT
4870 char_u *p = skipdigits(*arg + 1);
4871 int get_float = FALSE;
4873 /* We accept a float when the format matches
4874 * "[0-9]\+\.[0-9]\+\([eE][+-]\?[0-9]\+\)\?". This is very
4875 * strict to avoid backwards compatibility problems.
4876 * Don't look for a float after the "." operator, so that
4877 * ":let vers = 1.2.3" doesn't fail. */
4878 if (!want_string && p[0] == '.' && vim_isdigit(p[1]))
4880 get_float = TRUE;
4881 p = skipdigits(p + 2);
4882 if (*p == 'e' || *p == 'E')
4884 ++p;
4885 if (*p == '-' || *p == '+')
4886 ++p;
4887 if (!vim_isdigit(*p))
4888 get_float = FALSE;
4889 else
4890 p = skipdigits(p + 1);
4892 if (ASCII_ISALPHA(*p) || *p == '.')
4893 get_float = FALSE;
4895 if (get_float)
4897 float_T f;
4899 *arg += string2float(*arg, &f);
4900 if (evaluate)
4902 rettv->v_type = VAR_FLOAT;
4903 rettv->vval.v_float = f;
4906 else
4907 #endif
4909 vim_str2nr(*arg, NULL, &len, TRUE, TRUE, &n, NULL);
4910 *arg += len;
4911 if (evaluate)
4913 rettv->v_type = VAR_NUMBER;
4914 rettv->vval.v_number = n;
4917 break;
4921 * String constant: "string".
4923 case '"': ret = get_string_tv(arg, rettv, evaluate);
4924 break;
4927 * Literal string constant: 'str''ing'.
4929 case '\'': ret = get_lit_string_tv(arg, rettv, evaluate);
4930 break;
4933 * List: [expr, expr]
4935 case '[': ret = get_list_tv(arg, rettv, evaluate);
4936 break;
4939 * Dictionary: {key: val, key: val}
4941 case '{': ret = get_dict_tv(arg, rettv, evaluate);
4942 break;
4945 * Option value: &name
4947 case '&': ret = get_option_tv(arg, rettv, evaluate);
4948 break;
4951 * Environment variable: $VAR.
4953 case '$': ret = get_env_tv(arg, rettv, evaluate);
4954 break;
4957 * Register contents: @r.
4959 case '@': ++*arg;
4960 if (evaluate)
4962 rettv->v_type = VAR_STRING;
4963 rettv->vval.v_string = get_reg_contents(**arg, TRUE, TRUE);
4965 if (**arg != NUL)
4966 ++*arg;
4967 break;
4970 * nested expression: (expression).
4972 case '(': *arg = skipwhite(*arg + 1);
4973 ret = eval1(arg, rettv, evaluate); /* recursive! */
4974 if (**arg == ')')
4975 ++*arg;
4976 else if (ret == OK)
4978 EMSG(_("E110: Missing ')'"));
4979 clear_tv(rettv);
4980 ret = FAIL;
4982 break;
4984 default: ret = NOTDONE;
4985 break;
4988 if (ret == NOTDONE)
4991 * Must be a variable or function name.
4992 * Can also be a curly-braces kind of name: {expr}.
4994 s = *arg;
4995 len = get_name_len(arg, &alias, evaluate, TRUE);
4996 if (alias != NULL)
4997 s = alias;
4999 if (len <= 0)
5000 ret = FAIL;
5001 else
5003 if (**arg == '(') /* recursive! */
5005 /* If "s" is the name of a variable of type VAR_FUNC
5006 * use its contents. */
5007 s = deref_func_name(s, &len);
5009 /* Invoke the function. */
5010 ret = get_func_tv(s, len, rettv, arg,
5011 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
5012 &len, evaluate, NULL);
5013 /* Stop the expression evaluation when immediately
5014 * aborting on error, or when an interrupt occurred or
5015 * an exception was thrown but not caught. */
5016 if (aborting())
5018 if (ret == OK)
5019 clear_tv(rettv);
5020 ret = FAIL;
5023 else if (evaluate)
5024 ret = get_var_tv(s, len, rettv, TRUE);
5025 else
5026 ret = OK;
5029 if (alias != NULL)
5030 vim_free(alias);
5033 *arg = skipwhite(*arg);
5035 /* Handle following '[', '(' and '.' for expr[expr], expr.name,
5036 * expr(expr). */
5037 if (ret == OK)
5038 ret = handle_subscript(arg, rettv, evaluate, TRUE);
5041 * Apply logical NOT and unary '-', from right to left, ignore '+'.
5043 if (ret == OK && evaluate && end_leader > start_leader)
5045 int error = FALSE;
5046 int val = 0;
5047 #ifdef FEAT_FLOAT
5048 float_T f = 0.0;
5050 if (rettv->v_type == VAR_FLOAT)
5051 f = rettv->vval.v_float;
5052 else
5053 #endif
5054 val = get_tv_number_chk(rettv, &error);
5055 if (error)
5057 clear_tv(rettv);
5058 ret = FAIL;
5060 else
5062 while (end_leader > start_leader)
5064 --end_leader;
5065 if (*end_leader == '!')
5067 #ifdef FEAT_FLOAT
5068 if (rettv->v_type == VAR_FLOAT)
5069 f = !f;
5070 else
5071 #endif
5072 val = !val;
5074 else if (*end_leader == '-')
5076 #ifdef FEAT_FLOAT
5077 if (rettv->v_type == VAR_FLOAT)
5078 f = -f;
5079 else
5080 #endif
5081 val = -val;
5084 #ifdef FEAT_FLOAT
5085 if (rettv->v_type == VAR_FLOAT)
5087 clear_tv(rettv);
5088 rettv->vval.v_float = f;
5090 else
5091 #endif
5093 clear_tv(rettv);
5094 rettv->v_type = VAR_NUMBER;
5095 rettv->vval.v_number = val;
5100 return ret;
5104 * Evaluate an "[expr]" or "[expr:expr]" index. Also "dict.key".
5105 * "*arg" points to the '[' or '.'.
5106 * Returns FAIL or OK. "*arg" is advanced to after the ']'.
5108 static int
5109 eval_index(arg, rettv, evaluate, verbose)
5110 char_u **arg;
5111 typval_T *rettv;
5112 int evaluate;
5113 int verbose; /* give error messages */
5115 int empty1 = FALSE, empty2 = FALSE;
5116 typval_T var1, var2;
5117 long n1, n2 = 0;
5118 long len = -1;
5119 int range = FALSE;
5120 char_u *s;
5121 char_u *key = NULL;
5123 if (rettv->v_type == VAR_FUNC
5124 #ifdef FEAT_FLOAT
5125 || rettv->v_type == VAR_FLOAT
5126 #endif
5129 if (verbose)
5130 EMSG(_("E695: Cannot index a Funcref"));
5131 return FAIL;
5134 if (**arg == '.')
5137 * dict.name
5139 key = *arg + 1;
5140 for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
5142 if (len == 0)
5143 return FAIL;
5144 *arg = skipwhite(key + len);
5146 else
5149 * something[idx]
5151 * Get the (first) variable from inside the [].
5153 *arg = skipwhite(*arg + 1);
5154 if (**arg == ':')
5155 empty1 = TRUE;
5156 else if (eval1(arg, &var1, evaluate) == FAIL) /* recursive! */
5157 return FAIL;
5158 else if (evaluate && get_tv_string_chk(&var1) == NULL)
5160 /* not a number or string */
5161 clear_tv(&var1);
5162 return FAIL;
5166 * Get the second variable from inside the [:].
5168 if (**arg == ':')
5170 range = TRUE;
5171 *arg = skipwhite(*arg + 1);
5172 if (**arg == ']')
5173 empty2 = TRUE;
5174 else if (eval1(arg, &var2, evaluate) == FAIL) /* recursive! */
5176 if (!empty1)
5177 clear_tv(&var1);
5178 return FAIL;
5180 else if (evaluate && get_tv_string_chk(&var2) == NULL)
5182 /* not a number or string */
5183 if (!empty1)
5184 clear_tv(&var1);
5185 clear_tv(&var2);
5186 return FAIL;
5190 /* Check for the ']'. */
5191 if (**arg != ']')
5193 if (verbose)
5194 EMSG(_(e_missbrac));
5195 clear_tv(&var1);
5196 if (range)
5197 clear_tv(&var2);
5198 return FAIL;
5200 *arg = skipwhite(*arg + 1); /* skip the ']' */
5203 if (evaluate)
5205 n1 = 0;
5206 if (!empty1 && rettv->v_type != VAR_DICT)
5208 n1 = get_tv_number(&var1);
5209 clear_tv(&var1);
5211 if (range)
5213 if (empty2)
5214 n2 = -1;
5215 else
5217 n2 = get_tv_number(&var2);
5218 clear_tv(&var2);
5222 switch (rettv->v_type)
5224 case VAR_NUMBER:
5225 case VAR_STRING:
5226 s = get_tv_string(rettv);
5227 len = (long)STRLEN(s);
5228 if (range)
5230 /* The resulting variable is a substring. If the indexes
5231 * are out of range the result is empty. */
5232 if (n1 < 0)
5234 n1 = len + n1;
5235 if (n1 < 0)
5236 n1 = 0;
5238 if (n2 < 0)
5239 n2 = len + n2;
5240 else if (n2 >= len)
5241 n2 = len;
5242 if (n1 >= len || n2 < 0 || n1 > n2)
5243 s = NULL;
5244 else
5245 s = vim_strnsave(s + n1, (int)(n2 - n1 + 1));
5247 else
5249 /* The resulting variable is a string of a single
5250 * character. If the index is too big or negative the
5251 * result is empty. */
5252 if (n1 >= len || n1 < 0)
5253 s = NULL;
5254 else
5255 s = vim_strnsave(s + n1, 1);
5257 clear_tv(rettv);
5258 rettv->v_type = VAR_STRING;
5259 rettv->vval.v_string = s;
5260 break;
5262 case VAR_LIST:
5263 len = list_len(rettv->vval.v_list);
5264 if (n1 < 0)
5265 n1 = len + n1;
5266 if (!empty1 && (n1 < 0 || n1 >= len))
5268 /* For a range we allow invalid values and return an empty
5269 * list. A list index out of range is an error. */
5270 if (!range)
5272 if (verbose)
5273 EMSGN(_(e_listidx), n1);
5274 return FAIL;
5276 n1 = len;
5278 if (range)
5280 list_T *l;
5281 listitem_T *item;
5283 if (n2 < 0)
5284 n2 = len + n2;
5285 else if (n2 >= len)
5286 n2 = len - 1;
5287 if (!empty2 && (n2 < 0 || n2 + 1 < n1))
5288 n2 = -1;
5289 l = list_alloc();
5290 if (l == NULL)
5291 return FAIL;
5292 for (item = list_find(rettv->vval.v_list, n1);
5293 n1 <= n2; ++n1)
5295 if (list_append_tv(l, &item->li_tv) == FAIL)
5297 list_free(l, TRUE);
5298 return FAIL;
5300 item = item->li_next;
5302 clear_tv(rettv);
5303 rettv->v_type = VAR_LIST;
5304 rettv->vval.v_list = l;
5305 ++l->lv_refcount;
5307 else
5309 copy_tv(&list_find(rettv->vval.v_list, n1)->li_tv, &var1);
5310 clear_tv(rettv);
5311 *rettv = var1;
5313 break;
5315 case VAR_DICT:
5316 if (range)
5318 if (verbose)
5319 EMSG(_(e_dictrange));
5320 if (len == -1)
5321 clear_tv(&var1);
5322 return FAIL;
5325 dictitem_T *item;
5327 if (len == -1)
5329 key = get_tv_string(&var1);
5330 if (*key == NUL)
5332 if (verbose)
5333 EMSG(_(e_emptykey));
5334 clear_tv(&var1);
5335 return FAIL;
5339 item = dict_find(rettv->vval.v_dict, key, (int)len);
5341 if (item == NULL && verbose)
5342 EMSG2(_(e_dictkey), key);
5343 if (len == -1)
5344 clear_tv(&var1);
5345 if (item == NULL)
5346 return FAIL;
5348 copy_tv(&item->di_tv, &var1);
5349 clear_tv(rettv);
5350 *rettv = var1;
5352 break;
5356 return OK;
5360 * Get an option value.
5361 * "arg" points to the '&' or '+' before the option name.
5362 * "arg" is advanced to character after the option name.
5363 * Return OK or FAIL.
5365 static int
5366 get_option_tv(arg, rettv, evaluate)
5367 char_u **arg;
5368 typval_T *rettv; /* when NULL, only check if option exists */
5369 int evaluate;
5371 char_u *option_end;
5372 long numval;
5373 char_u *stringval;
5374 int opt_type;
5375 int c;
5376 int working = (**arg == '+'); /* has("+option") */
5377 int ret = OK;
5378 int opt_flags;
5381 * Isolate the option name and find its value.
5383 option_end = find_option_end(arg, &opt_flags);
5384 if (option_end == NULL)
5386 if (rettv != NULL)
5387 EMSG2(_("E112: Option name missing: %s"), *arg);
5388 return FAIL;
5391 if (!evaluate)
5393 *arg = option_end;
5394 return OK;
5397 c = *option_end;
5398 *option_end = NUL;
5399 opt_type = get_option_value(*arg, &numval,
5400 rettv == NULL ? NULL : &stringval, opt_flags);
5402 if (opt_type == -3) /* invalid name */
5404 if (rettv != NULL)
5405 EMSG2(_("E113: Unknown option: %s"), *arg);
5406 ret = FAIL;
5408 else if (rettv != NULL)
5410 if (opt_type == -2) /* hidden string option */
5412 rettv->v_type = VAR_STRING;
5413 rettv->vval.v_string = NULL;
5415 else if (opt_type == -1) /* hidden number option */
5417 rettv->v_type = VAR_NUMBER;
5418 rettv->vval.v_number = 0;
5420 else if (opt_type == 1) /* number option */
5422 rettv->v_type = VAR_NUMBER;
5423 rettv->vval.v_number = numval;
5425 else /* string option */
5427 rettv->v_type = VAR_STRING;
5428 rettv->vval.v_string = stringval;
5431 else if (working && (opt_type == -2 || opt_type == -1))
5432 ret = FAIL;
5434 *option_end = c; /* put back for error messages */
5435 *arg = option_end;
5437 return ret;
5441 * Allocate a variable for a string constant.
5442 * Return OK or FAIL.
5444 static int
5445 get_string_tv(arg, rettv, evaluate)
5446 char_u **arg;
5447 typval_T *rettv;
5448 int evaluate;
5450 char_u *p;
5451 char_u *name;
5452 int extra = 0;
5455 * Find the end of the string, skipping backslashed characters.
5457 for (p = *arg + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
5459 if (*p == '\\' && p[1] != NUL)
5461 ++p;
5462 /* A "\<x>" form occupies at least 4 characters, and produces up
5463 * to 6 characters: reserve space for 2 extra */
5464 if (*p == '<')
5465 extra += 2;
5469 if (*p != '"')
5471 EMSG2(_("E114: Missing quote: %s"), *arg);
5472 return FAIL;
5475 /* If only parsing, set *arg and return here */
5476 if (!evaluate)
5478 *arg = p + 1;
5479 return OK;
5483 * Copy the string into allocated memory, handling backslashed
5484 * characters.
5486 name = alloc((unsigned)(p - *arg + extra));
5487 if (name == NULL)
5488 return FAIL;
5489 rettv->v_type = VAR_STRING;
5490 rettv->vval.v_string = name;
5492 for (p = *arg + 1; *p != NUL && *p != '"'; )
5494 if (*p == '\\')
5496 switch (*++p)
5498 case 'b': *name++ = BS; ++p; break;
5499 case 'e': *name++ = ESC; ++p; break;
5500 case 'f': *name++ = FF; ++p; break;
5501 case 'n': *name++ = NL; ++p; break;
5502 case 'r': *name++ = CAR; ++p; break;
5503 case 't': *name++ = TAB; ++p; break;
5505 case 'X': /* hex: "\x1", "\x12" */
5506 case 'x':
5507 case 'u': /* Unicode: "\u0023" */
5508 case 'U':
5509 if (vim_isxdigit(p[1]))
5511 int n, nr;
5512 int c = toupper(*p);
5514 if (c == 'X')
5515 n = 2;
5516 else
5517 n = 4;
5518 nr = 0;
5519 while (--n >= 0 && vim_isxdigit(p[1]))
5521 ++p;
5522 nr = (nr << 4) + hex2nr(*p);
5524 ++p;
5525 #ifdef FEAT_MBYTE
5526 /* For "\u" store the number according to
5527 * 'encoding'. */
5528 if (c != 'X')
5529 name += (*mb_char2bytes)(nr, name);
5530 else
5531 #endif
5532 *name++ = nr;
5534 break;
5536 /* octal: "\1", "\12", "\123" */
5537 case '0':
5538 case '1':
5539 case '2':
5540 case '3':
5541 case '4':
5542 case '5':
5543 case '6':
5544 case '7': *name = *p++ - '0';
5545 if (*p >= '0' && *p <= '7')
5547 *name = (*name << 3) + *p++ - '0';
5548 if (*p >= '0' && *p <= '7')
5549 *name = (*name << 3) + *p++ - '0';
5551 ++name;
5552 break;
5554 /* Special key, e.g.: "\<C-W>" */
5555 case '<': extra = trans_special(&p, name, TRUE);
5556 if (extra != 0)
5558 name += extra;
5559 break;
5561 /* FALLTHROUGH */
5563 default: MB_COPY_CHAR(p, name);
5564 break;
5567 else
5568 MB_COPY_CHAR(p, name);
5571 *name = NUL;
5572 *arg = p + 1;
5574 return OK;
5578 * Allocate a variable for a 'str''ing' constant.
5579 * Return OK or FAIL.
5581 static int
5582 get_lit_string_tv(arg, rettv, evaluate)
5583 char_u **arg;
5584 typval_T *rettv;
5585 int evaluate;
5587 char_u *p;
5588 char_u *str;
5589 int reduce = 0;
5592 * Find the end of the string, skipping ''.
5594 for (p = *arg + 1; *p != NUL; mb_ptr_adv(p))
5596 if (*p == '\'')
5598 if (p[1] != '\'')
5599 break;
5600 ++reduce;
5601 ++p;
5605 if (*p != '\'')
5607 EMSG2(_("E115: Missing quote: %s"), *arg);
5608 return FAIL;
5611 /* If only parsing return after setting "*arg" */
5612 if (!evaluate)
5614 *arg = p + 1;
5615 return OK;
5619 * Copy the string into allocated memory, handling '' to ' reduction.
5621 str = alloc((unsigned)((p - *arg) - reduce));
5622 if (str == NULL)
5623 return FAIL;
5624 rettv->v_type = VAR_STRING;
5625 rettv->vval.v_string = str;
5627 for (p = *arg + 1; *p != NUL; )
5629 if (*p == '\'')
5631 if (p[1] != '\'')
5632 break;
5633 ++p;
5635 MB_COPY_CHAR(p, str);
5637 *str = NUL;
5638 *arg = p + 1;
5640 return OK;
5644 * Allocate a variable for a List and fill it from "*arg".
5645 * Return OK or FAIL.
5647 static int
5648 get_list_tv(arg, rettv, evaluate)
5649 char_u **arg;
5650 typval_T *rettv;
5651 int evaluate;
5653 list_T *l = NULL;
5654 typval_T tv;
5655 listitem_T *item;
5657 if (evaluate)
5659 l = list_alloc();
5660 if (l == NULL)
5661 return FAIL;
5664 *arg = skipwhite(*arg + 1);
5665 while (**arg != ']' && **arg != NUL)
5667 if (eval1(arg, &tv, evaluate) == FAIL) /* recursive! */
5668 goto failret;
5669 if (evaluate)
5671 item = listitem_alloc();
5672 if (item != NULL)
5674 item->li_tv = tv;
5675 item->li_tv.v_lock = 0;
5676 list_append(l, item);
5678 else
5679 clear_tv(&tv);
5682 if (**arg == ']')
5683 break;
5684 if (**arg != ',')
5686 EMSG2(_("E696: Missing comma in List: %s"), *arg);
5687 goto failret;
5689 *arg = skipwhite(*arg + 1);
5692 if (**arg != ']')
5694 EMSG2(_("E697: Missing end of List ']': %s"), *arg);
5695 failret:
5696 if (evaluate)
5697 list_free(l, TRUE);
5698 return FAIL;
5701 *arg = skipwhite(*arg + 1);
5702 if (evaluate)
5704 rettv->v_type = VAR_LIST;
5705 rettv->vval.v_list = l;
5706 ++l->lv_refcount;
5709 return OK;
5713 * Allocate an empty header for a list.
5714 * Caller should take care of the reference count.
5716 list_T *
5717 list_alloc()
5719 list_T *l;
5721 l = (list_T *)alloc_clear(sizeof(list_T));
5722 if (l != NULL)
5724 /* Prepend the list to the list of lists for garbage collection. */
5725 if (first_list != NULL)
5726 first_list->lv_used_prev = l;
5727 l->lv_used_prev = NULL;
5728 l->lv_used_next = first_list;
5729 first_list = l;
5731 return l;
5735 * Allocate an empty list for a return value.
5736 * Returns OK or FAIL.
5738 static int
5739 rettv_list_alloc(rettv)
5740 typval_T *rettv;
5742 list_T *l = list_alloc();
5744 if (l == NULL)
5745 return FAIL;
5747 rettv->vval.v_list = l;
5748 rettv->v_type = VAR_LIST;
5749 ++l->lv_refcount;
5750 return OK;
5754 * Unreference a list: decrement the reference count and free it when it
5755 * becomes zero.
5757 void
5758 list_unref(l)
5759 list_T *l;
5761 if (l != NULL && --l->lv_refcount <= 0)
5762 list_free(l, TRUE);
5766 * Free a list, including all items it points to.
5767 * Ignores the reference count.
5769 void
5770 list_free(l, recurse)
5771 list_T *l;
5772 int recurse; /* Free Lists and Dictionaries recursively. */
5774 listitem_T *item;
5776 /* Remove the list from the list of lists for garbage collection. */
5777 if (l->lv_used_prev == NULL)
5778 first_list = l->lv_used_next;
5779 else
5780 l->lv_used_prev->lv_used_next = l->lv_used_next;
5781 if (l->lv_used_next != NULL)
5782 l->lv_used_next->lv_used_prev = l->lv_used_prev;
5784 for (item = l->lv_first; item != NULL; item = l->lv_first)
5786 /* Remove the item before deleting it. */
5787 l->lv_first = item->li_next;
5788 if (recurse || (item->li_tv.v_type != VAR_LIST
5789 && item->li_tv.v_type != VAR_DICT))
5790 clear_tv(&item->li_tv);
5791 vim_free(item);
5793 vim_free(l);
5797 * Allocate a list item.
5799 static listitem_T *
5800 listitem_alloc()
5802 return (listitem_T *)alloc(sizeof(listitem_T));
5806 * Free a list item. Also clears the value. Does not notify watchers.
5808 static void
5809 listitem_free(item)
5810 listitem_T *item;
5812 clear_tv(&item->li_tv);
5813 vim_free(item);
5817 * Remove a list item from a List and free it. Also clears the value.
5819 static void
5820 listitem_remove(l, item)
5821 list_T *l;
5822 listitem_T *item;
5824 list_remove(l, item, item);
5825 listitem_free(item);
5829 * Get the number of items in a list.
5831 static long
5832 list_len(l)
5833 list_T *l;
5835 if (l == NULL)
5836 return 0L;
5837 return l->lv_len;
5841 * Return TRUE when two lists have exactly the same values.
5843 static int
5844 list_equal(l1, l2, ic)
5845 list_T *l1;
5846 list_T *l2;
5847 int ic; /* ignore case for strings */
5849 listitem_T *item1, *item2;
5851 if (l1 == NULL || l2 == NULL)
5852 return FALSE;
5853 if (l1 == l2)
5854 return TRUE;
5855 if (list_len(l1) != list_len(l2))
5856 return FALSE;
5858 for (item1 = l1->lv_first, item2 = l2->lv_first;
5859 item1 != NULL && item2 != NULL;
5860 item1 = item1->li_next, item2 = item2->li_next)
5861 if (!tv_equal(&item1->li_tv, &item2->li_tv, ic))
5862 return FALSE;
5863 return item1 == NULL && item2 == NULL;
5866 #if defined(FEAT_PYTHON) || defined(PROTO)
5868 * Return the dictitem that an entry in a hashtable points to.
5870 dictitem_T *
5871 dict_lookup(hi)
5872 hashitem_T *hi;
5874 return HI2DI(hi);
5876 #endif
5879 * Return TRUE when two dictionaries have exactly the same key/values.
5881 static int
5882 dict_equal(d1, d2, ic)
5883 dict_T *d1;
5884 dict_T *d2;
5885 int ic; /* ignore case for strings */
5887 hashitem_T *hi;
5888 dictitem_T *item2;
5889 int todo;
5891 if (d1 == NULL || d2 == NULL)
5892 return FALSE;
5893 if (d1 == d2)
5894 return TRUE;
5895 if (dict_len(d1) != dict_len(d2))
5896 return FALSE;
5898 todo = (int)d1->dv_hashtab.ht_used;
5899 for (hi = d1->dv_hashtab.ht_array; todo > 0; ++hi)
5901 if (!HASHITEM_EMPTY(hi))
5903 item2 = dict_find(d2, hi->hi_key, -1);
5904 if (item2 == NULL)
5905 return FALSE;
5906 if (!tv_equal(&HI2DI(hi)->di_tv, &item2->di_tv, ic))
5907 return FALSE;
5908 --todo;
5911 return TRUE;
5915 * Return TRUE if "tv1" and "tv2" have the same value.
5916 * Compares the items just like "==" would compare them, but strings and
5917 * numbers are different. Floats and numbers are also different.
5919 static int
5920 tv_equal(tv1, tv2, ic)
5921 typval_T *tv1;
5922 typval_T *tv2;
5923 int ic; /* ignore case */
5925 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
5926 char_u *s1, *s2;
5927 static int recursive = 0; /* cach recursive loops */
5928 int r;
5930 if (tv1->v_type != tv2->v_type)
5931 return FALSE;
5932 /* Catch lists and dicts that have an endless loop by limiting
5933 * recursiveness to 1000. We guess they are equal then. */
5934 if (recursive >= 1000)
5935 return TRUE;
5937 switch (tv1->v_type)
5939 case VAR_LIST:
5940 ++recursive;
5941 r = list_equal(tv1->vval.v_list, tv2->vval.v_list, ic);
5942 --recursive;
5943 return r;
5945 case VAR_DICT:
5946 ++recursive;
5947 r = dict_equal(tv1->vval.v_dict, tv2->vval.v_dict, ic);
5948 --recursive;
5949 return r;
5951 case VAR_FUNC:
5952 return (tv1->vval.v_string != NULL
5953 && tv2->vval.v_string != NULL
5954 && STRCMP(tv1->vval.v_string, tv2->vval.v_string) == 0);
5956 case VAR_NUMBER:
5957 return tv1->vval.v_number == tv2->vval.v_number;
5959 #ifdef FEAT_FLOAT
5960 case VAR_FLOAT:
5961 return tv1->vval.v_float == tv2->vval.v_float;
5962 #endif
5964 case VAR_STRING:
5965 s1 = get_tv_string_buf(tv1, buf1);
5966 s2 = get_tv_string_buf(tv2, buf2);
5967 return ((ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2)) == 0);
5970 EMSG2(_(e_intern2), "tv_equal()");
5971 return TRUE;
5975 * Locate item with index "n" in list "l" and return it.
5976 * A negative index is counted from the end; -1 is the last item.
5977 * Returns NULL when "n" is out of range.
5979 static listitem_T *
5980 list_find(l, n)
5981 list_T *l;
5982 long n;
5984 listitem_T *item;
5985 long idx;
5987 if (l == NULL)
5988 return NULL;
5990 /* Negative index is relative to the end. */
5991 if (n < 0)
5992 n = l->lv_len + n;
5994 /* Check for index out of range. */
5995 if (n < 0 || n >= l->lv_len)
5996 return NULL;
5998 /* When there is a cached index may start search from there. */
5999 if (l->lv_idx_item != NULL)
6001 if (n < l->lv_idx / 2)
6003 /* closest to the start of the list */
6004 item = l->lv_first;
6005 idx = 0;
6007 else if (n > (l->lv_idx + l->lv_len) / 2)
6009 /* closest to the end of the list */
6010 item = l->lv_last;
6011 idx = l->lv_len - 1;
6013 else
6015 /* closest to the cached index */
6016 item = l->lv_idx_item;
6017 idx = l->lv_idx;
6020 else
6022 if (n < l->lv_len / 2)
6024 /* closest to the start of the list */
6025 item = l->lv_first;
6026 idx = 0;
6028 else
6030 /* closest to the end of the list */
6031 item = l->lv_last;
6032 idx = l->lv_len - 1;
6036 while (n > idx)
6038 /* search forward */
6039 item = item->li_next;
6040 ++idx;
6042 while (n < idx)
6044 /* search backward */
6045 item = item->li_prev;
6046 --idx;
6049 /* cache the used index */
6050 l->lv_idx = idx;
6051 l->lv_idx_item = item;
6053 return item;
6057 * Get list item "l[idx]" as a number.
6059 static long
6060 list_find_nr(l, idx, errorp)
6061 list_T *l;
6062 long idx;
6063 int *errorp; /* set to TRUE when something wrong */
6065 listitem_T *li;
6067 li = list_find(l, idx);
6068 if (li == NULL)
6070 if (errorp != NULL)
6071 *errorp = TRUE;
6072 return -1L;
6074 return get_tv_number_chk(&li->li_tv, errorp);
6078 * Get list item "l[idx - 1]" as a string. Returns NULL for failure.
6080 char_u *
6081 list_find_str(l, idx)
6082 list_T *l;
6083 long idx;
6085 listitem_T *li;
6087 li = list_find(l, idx - 1);
6088 if (li == NULL)
6090 EMSGN(_(e_listidx), idx);
6091 return NULL;
6093 return get_tv_string(&li->li_tv);
6097 * Locate "item" list "l" and return its index.
6098 * Returns -1 when "item" is not in the list.
6100 static long
6101 list_idx_of_item(l, item)
6102 list_T *l;
6103 listitem_T *item;
6105 long idx = 0;
6106 listitem_T *li;
6108 if (l == NULL)
6109 return -1;
6110 idx = 0;
6111 for (li = l->lv_first; li != NULL && li != item; li = li->li_next)
6112 ++idx;
6113 if (li == NULL)
6114 return -1;
6115 return idx;
6119 * Append item "item" to the end of list "l".
6121 static void
6122 list_append(l, item)
6123 list_T *l;
6124 listitem_T *item;
6126 if (l->lv_last == NULL)
6128 /* empty list */
6129 l->lv_first = item;
6130 l->lv_last = item;
6131 item->li_prev = NULL;
6133 else
6135 l->lv_last->li_next = item;
6136 item->li_prev = l->lv_last;
6137 l->lv_last = item;
6139 ++l->lv_len;
6140 item->li_next = NULL;
6144 * Append typval_T "tv" to the end of list "l".
6145 * Return FAIL when out of memory.
6147 static int
6148 list_append_tv(l, tv)
6149 list_T *l;
6150 typval_T *tv;
6152 listitem_T *li = listitem_alloc();
6154 if (li == NULL)
6155 return FAIL;
6156 copy_tv(tv, &li->li_tv);
6157 list_append(l, li);
6158 return OK;
6162 * Add a dictionary to a list. Used by getqflist().
6163 * Return FAIL when out of memory.
6166 list_append_dict(list, dict)
6167 list_T *list;
6168 dict_T *dict;
6170 listitem_T *li = listitem_alloc();
6172 if (li == NULL)
6173 return FAIL;
6174 li->li_tv.v_type = VAR_DICT;
6175 li->li_tv.v_lock = 0;
6176 li->li_tv.vval.v_dict = dict;
6177 list_append(list, li);
6178 ++dict->dv_refcount;
6179 return OK;
6183 * Make a copy of "str" and append it as an item to list "l".
6184 * When "len" >= 0 use "str[len]".
6185 * Returns FAIL when out of memory.
6188 list_append_string(l, str, len)
6189 list_T *l;
6190 char_u *str;
6191 int len;
6193 listitem_T *li = listitem_alloc();
6195 if (li == NULL)
6196 return FAIL;
6197 list_append(l, li);
6198 li->li_tv.v_type = VAR_STRING;
6199 li->li_tv.v_lock = 0;
6200 if (str == NULL)
6201 li->li_tv.vval.v_string = NULL;
6202 else if ((li->li_tv.vval.v_string = (len >= 0 ? vim_strnsave(str, len)
6203 : vim_strsave(str))) == NULL)
6204 return FAIL;
6205 return OK;
6209 * Append "n" to list "l".
6210 * Returns FAIL when out of memory.
6212 static int
6213 list_append_number(l, n)
6214 list_T *l;
6215 varnumber_T n;
6217 listitem_T *li;
6219 li = listitem_alloc();
6220 if (li == NULL)
6221 return FAIL;
6222 li->li_tv.v_type = VAR_NUMBER;
6223 li->li_tv.v_lock = 0;
6224 li->li_tv.vval.v_number = n;
6225 list_append(l, li);
6226 return OK;
6230 * Insert typval_T "tv" in list "l" before "item".
6231 * If "item" is NULL append at the end.
6232 * Return FAIL when out of memory.
6234 static int
6235 list_insert_tv(l, tv, item)
6236 list_T *l;
6237 typval_T *tv;
6238 listitem_T *item;
6240 listitem_T *ni = listitem_alloc();
6242 if (ni == NULL)
6243 return FAIL;
6244 copy_tv(tv, &ni->li_tv);
6245 if (item == NULL)
6246 /* Append new item at end of list. */
6247 list_append(l, ni);
6248 else
6250 /* Insert new item before existing item. */
6251 ni->li_prev = item->li_prev;
6252 ni->li_next = item;
6253 if (item->li_prev == NULL)
6255 l->lv_first = ni;
6256 ++l->lv_idx;
6258 else
6260 item->li_prev->li_next = ni;
6261 l->lv_idx_item = NULL;
6263 item->li_prev = ni;
6264 ++l->lv_len;
6266 return OK;
6270 * Extend "l1" with "l2".
6271 * If "bef" is NULL append at the end, otherwise insert before this item.
6272 * Returns FAIL when out of memory.
6274 static int
6275 list_extend(l1, l2, bef)
6276 list_T *l1;
6277 list_T *l2;
6278 listitem_T *bef;
6280 listitem_T *item;
6281 int todo = l2->lv_len;
6283 /* We also quit the loop when we have inserted the original item count of
6284 * the list, avoid a hang when we extend a list with itself. */
6285 for (item = l2->lv_first; item != NULL && --todo >= 0; item = item->li_next)
6286 if (list_insert_tv(l1, &item->li_tv, bef) == FAIL)
6287 return FAIL;
6288 return OK;
6292 * Concatenate lists "l1" and "l2" into a new list, stored in "tv".
6293 * Return FAIL when out of memory.
6295 static int
6296 list_concat(l1, l2, tv)
6297 list_T *l1;
6298 list_T *l2;
6299 typval_T *tv;
6301 list_T *l;
6303 if (l1 == NULL || l2 == NULL)
6304 return FAIL;
6306 /* make a copy of the first list. */
6307 l = list_copy(l1, FALSE, 0);
6308 if (l == NULL)
6309 return FAIL;
6310 tv->v_type = VAR_LIST;
6311 tv->vval.v_list = l;
6313 /* append all items from the second list */
6314 return list_extend(l, l2, NULL);
6318 * Make a copy of list "orig". Shallow if "deep" is FALSE.
6319 * The refcount of the new list is set to 1.
6320 * See item_copy() for "copyID".
6321 * Returns NULL when out of memory.
6323 static list_T *
6324 list_copy(orig, deep, copyID)
6325 list_T *orig;
6326 int deep;
6327 int copyID;
6329 list_T *copy;
6330 listitem_T *item;
6331 listitem_T *ni;
6333 if (orig == NULL)
6334 return NULL;
6336 copy = list_alloc();
6337 if (copy != NULL)
6339 if (copyID != 0)
6341 /* Do this before adding the items, because one of the items may
6342 * refer back to this list. */
6343 orig->lv_copyID = copyID;
6344 orig->lv_copylist = copy;
6346 for (item = orig->lv_first; item != NULL && !got_int;
6347 item = item->li_next)
6349 ni = listitem_alloc();
6350 if (ni == NULL)
6351 break;
6352 if (deep)
6354 if (item_copy(&item->li_tv, &ni->li_tv, deep, copyID) == FAIL)
6356 vim_free(ni);
6357 break;
6360 else
6361 copy_tv(&item->li_tv, &ni->li_tv);
6362 list_append(copy, ni);
6364 ++copy->lv_refcount;
6365 if (item != NULL)
6367 list_unref(copy);
6368 copy = NULL;
6372 return copy;
6376 * Remove items "item" to "item2" from list "l".
6377 * Does not free the listitem or the value!
6379 static void
6380 list_remove(l, item, item2)
6381 list_T *l;
6382 listitem_T *item;
6383 listitem_T *item2;
6385 listitem_T *ip;
6387 /* notify watchers */
6388 for (ip = item; ip != NULL; ip = ip->li_next)
6390 --l->lv_len;
6391 list_fix_watch(l, ip);
6392 if (ip == item2)
6393 break;
6396 if (item2->li_next == NULL)
6397 l->lv_last = item->li_prev;
6398 else
6399 item2->li_next->li_prev = item->li_prev;
6400 if (item->li_prev == NULL)
6401 l->lv_first = item2->li_next;
6402 else
6403 item->li_prev->li_next = item2->li_next;
6404 l->lv_idx_item = NULL;
6408 * Return an allocated string with the string representation of a list.
6409 * May return NULL.
6411 static char_u *
6412 list2string(tv, copyID)
6413 typval_T *tv;
6414 int copyID;
6416 garray_T ga;
6418 if (tv->vval.v_list == NULL)
6419 return NULL;
6420 ga_init2(&ga, (int)sizeof(char), 80);
6421 ga_append(&ga, '[');
6422 if (list_join(&ga, tv->vval.v_list, (char_u *)", ", FALSE, copyID) == FAIL)
6424 vim_free(ga.ga_data);
6425 return NULL;
6427 ga_append(&ga, ']');
6428 ga_append(&ga, NUL);
6429 return (char_u *)ga.ga_data;
6433 * Join list "l" into a string in "*gap", using separator "sep".
6434 * When "echo" is TRUE use String as echoed, otherwise as inside a List.
6435 * Return FAIL or OK.
6437 static int
6438 list_join(gap, l, sep, echo, copyID)
6439 garray_T *gap;
6440 list_T *l;
6441 char_u *sep;
6442 int echo;
6443 int copyID;
6445 int first = TRUE;
6446 char_u *tofree;
6447 char_u numbuf[NUMBUFLEN];
6448 listitem_T *item;
6449 char_u *s;
6451 for (item = l->lv_first; item != NULL && !got_int; item = item->li_next)
6453 if (first)
6454 first = FALSE;
6455 else
6456 ga_concat(gap, sep);
6458 if (echo)
6459 s = echo_string(&item->li_tv, &tofree, numbuf, copyID);
6460 else
6461 s = tv2string(&item->li_tv, &tofree, numbuf, copyID);
6462 if (s != NULL)
6463 ga_concat(gap, s);
6464 vim_free(tofree);
6465 if (s == NULL)
6466 return FAIL;
6468 return OK;
6472 * Garbage collection for lists and dictionaries.
6474 * We use reference counts to be able to free most items right away when they
6475 * are no longer used. But for composite items it's possible that it becomes
6476 * unused while the reference count is > 0: When there is a recursive
6477 * reference. Example:
6478 * :let l = [1, 2, 3]
6479 * :let d = {9: l}
6480 * :let l[1] = d
6482 * Since this is quite unusual we handle this with garbage collection: every
6483 * once in a while find out which lists and dicts are not referenced from any
6484 * variable.
6486 * Here is a good reference text about garbage collection (refers to Python
6487 * but it applies to all reference-counting mechanisms):
6488 * http://python.ca/nas/python/gc/
6492 * Do garbage collection for lists and dicts.
6493 * Return TRUE if some memory was freed.
6496 garbage_collect()
6498 dict_T *dd;
6499 list_T *ll;
6500 int copyID = ++current_copyID;
6501 buf_T *buf;
6502 win_T *wp;
6503 int i;
6504 funccall_T *fc, **pfc;
6505 int did_free = FALSE;
6506 #ifdef FEAT_WINDOWS
6507 tabpage_T *tp;
6508 #endif
6510 /* Only do this once. */
6511 want_garbage_collect = FALSE;
6512 may_garbage_collect = FALSE;
6513 garbage_collect_at_exit = FALSE;
6516 * 1. Go through all accessible variables and mark all lists and dicts
6517 * with copyID.
6519 /* script-local variables */
6520 for (i = 1; i <= ga_scripts.ga_len; ++i)
6521 set_ref_in_ht(&SCRIPT_VARS(i), copyID);
6523 /* buffer-local variables */
6524 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
6525 set_ref_in_ht(&buf->b_vars.dv_hashtab, copyID);
6527 /* window-local variables */
6528 FOR_ALL_TAB_WINDOWS(tp, wp)
6529 set_ref_in_ht(&wp->w_vars.dv_hashtab, copyID);
6531 #ifdef FEAT_WINDOWS
6532 /* tabpage-local variables */
6533 for (tp = first_tabpage; tp != NULL; tp = tp->tp_next)
6534 set_ref_in_ht(&tp->tp_vars.dv_hashtab, copyID);
6535 #endif
6537 /* global variables */
6538 set_ref_in_ht(&globvarht, copyID);
6540 /* function-local variables */
6541 for (fc = current_funccal; fc != NULL; fc = fc->caller)
6543 set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID);
6544 set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID);
6547 /* v: vars */
6548 set_ref_in_ht(&vimvarht, copyID);
6551 * 2. Go through the list of dicts and free items without the copyID.
6553 for (dd = first_dict; dd != NULL; )
6554 if (dd->dv_copyID != copyID)
6556 /* Free the Dictionary and ordinary items it contains, but don't
6557 * recurse into Lists and Dictionaries, they will be in the list
6558 * of dicts or list of lists. */
6559 dict_free(dd, FALSE);
6560 did_free = TRUE;
6562 /* restart, next dict may also have been freed */
6563 dd = first_dict;
6565 else
6566 dd = dd->dv_used_next;
6569 * 3. Go through the list of lists and free items without the copyID.
6570 * But don't free a list that has a watcher (used in a for loop), these
6571 * are not referenced anywhere.
6573 for (ll = first_list; ll != NULL; )
6574 if (ll->lv_copyID != copyID && ll->lv_watch == NULL)
6576 /* Free the List and ordinary items it contains, but don't recurse
6577 * into Lists and Dictionaries, they will be in the list of dicts
6578 * or list of lists. */
6579 list_free(ll, FALSE);
6580 did_free = TRUE;
6582 /* restart, next list may also have been freed */
6583 ll = first_list;
6585 else
6586 ll = ll->lv_used_next;
6588 /* check if any funccal can be freed now */
6589 for (pfc = &previous_funccal; *pfc != NULL; )
6591 if (can_free_funccal(*pfc, copyID))
6593 fc = *pfc;
6594 *pfc = fc->caller;
6595 free_funccal(fc, TRUE);
6596 did_free = TRUE;
6598 else
6599 pfc = &(*pfc)->caller;
6602 return did_free;
6606 * Mark all lists and dicts referenced through hashtab "ht" with "copyID".
6608 static void
6609 set_ref_in_ht(ht, copyID)
6610 hashtab_T *ht;
6611 int copyID;
6613 int todo;
6614 hashitem_T *hi;
6616 todo = (int)ht->ht_used;
6617 for (hi = ht->ht_array; todo > 0; ++hi)
6618 if (!HASHITEM_EMPTY(hi))
6620 --todo;
6621 set_ref_in_item(&HI2DI(hi)->di_tv, copyID);
6626 * Mark all lists and dicts referenced through list "l" with "copyID".
6628 static void
6629 set_ref_in_list(l, copyID)
6630 list_T *l;
6631 int copyID;
6633 listitem_T *li;
6635 for (li = l->lv_first; li != NULL; li = li->li_next)
6636 set_ref_in_item(&li->li_tv, copyID);
6640 * Mark all lists and dicts referenced through typval "tv" with "copyID".
6642 static void
6643 set_ref_in_item(tv, copyID)
6644 typval_T *tv;
6645 int copyID;
6647 dict_T *dd;
6648 list_T *ll;
6650 switch (tv->v_type)
6652 case VAR_DICT:
6653 dd = tv->vval.v_dict;
6654 if (dd != NULL && dd->dv_copyID != copyID)
6656 /* Didn't see this dict yet. */
6657 dd->dv_copyID = copyID;
6658 set_ref_in_ht(&dd->dv_hashtab, copyID);
6660 break;
6662 case VAR_LIST:
6663 ll = tv->vval.v_list;
6664 if (ll != NULL && ll->lv_copyID != copyID)
6666 /* Didn't see this list yet. */
6667 ll->lv_copyID = copyID;
6668 set_ref_in_list(ll, copyID);
6670 break;
6672 return;
6676 * Allocate an empty header for a dictionary.
6678 dict_T *
6679 dict_alloc()
6681 dict_T *d;
6683 d = (dict_T *)alloc(sizeof(dict_T));
6684 if (d != NULL)
6686 /* Add the list to the list of dicts for garbage collection. */
6687 if (first_dict != NULL)
6688 first_dict->dv_used_prev = d;
6689 d->dv_used_next = first_dict;
6690 d->dv_used_prev = NULL;
6691 first_dict = d;
6693 hash_init(&d->dv_hashtab);
6694 d->dv_lock = 0;
6695 d->dv_refcount = 0;
6696 d->dv_copyID = 0;
6698 return d;
6702 * Unreference a Dictionary: decrement the reference count and free it when it
6703 * becomes zero.
6705 static void
6706 dict_unref(d)
6707 dict_T *d;
6709 if (d != NULL && --d->dv_refcount <= 0)
6710 dict_free(d, TRUE);
6714 * Free a Dictionary, including all items it contains.
6715 * Ignores the reference count.
6717 static void
6718 dict_free(d, recurse)
6719 dict_T *d;
6720 int recurse; /* Free Lists and Dictionaries recursively. */
6722 int todo;
6723 hashitem_T *hi;
6724 dictitem_T *di;
6726 /* Remove the dict from the list of dicts for garbage collection. */
6727 if (d->dv_used_prev == NULL)
6728 first_dict = d->dv_used_next;
6729 else
6730 d->dv_used_prev->dv_used_next = d->dv_used_next;
6731 if (d->dv_used_next != NULL)
6732 d->dv_used_next->dv_used_prev = d->dv_used_prev;
6734 /* Lock the hashtab, we don't want it to resize while freeing items. */
6735 hash_lock(&d->dv_hashtab);
6736 todo = (int)d->dv_hashtab.ht_used;
6737 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
6739 if (!HASHITEM_EMPTY(hi))
6741 /* Remove the item before deleting it, just in case there is
6742 * something recursive causing trouble. */
6743 di = HI2DI(hi);
6744 hash_remove(&d->dv_hashtab, hi);
6745 if (recurse || (di->di_tv.v_type != VAR_LIST
6746 && di->di_tv.v_type != VAR_DICT))
6747 clear_tv(&di->di_tv);
6748 vim_free(di);
6749 --todo;
6752 hash_clear(&d->dv_hashtab);
6753 vim_free(d);
6757 * Allocate a Dictionary item.
6758 * The "key" is copied to the new item.
6759 * Note that the value of the item "di_tv" still needs to be initialized!
6760 * Returns NULL when out of memory.
6762 static dictitem_T *
6763 dictitem_alloc(key)
6764 char_u *key;
6766 dictitem_T *di;
6768 di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T) + STRLEN(key)));
6769 if (di != NULL)
6771 STRCPY(di->di_key, key);
6772 di->di_flags = 0;
6774 return di;
6778 * Make a copy of a Dictionary item.
6780 static dictitem_T *
6781 dictitem_copy(org)
6782 dictitem_T *org;
6784 dictitem_T *di;
6786 di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
6787 + STRLEN(org->di_key)));
6788 if (di != NULL)
6790 STRCPY(di->di_key, org->di_key);
6791 di->di_flags = 0;
6792 copy_tv(&org->di_tv, &di->di_tv);
6794 return di;
6798 * Remove item "item" from Dictionary "dict" and free it.
6800 static void
6801 dictitem_remove(dict, item)
6802 dict_T *dict;
6803 dictitem_T *item;
6805 hashitem_T *hi;
6807 hi = hash_find(&dict->dv_hashtab, item->di_key);
6808 if (HASHITEM_EMPTY(hi))
6809 EMSG2(_(e_intern2), "dictitem_remove()");
6810 else
6811 hash_remove(&dict->dv_hashtab, hi);
6812 dictitem_free(item);
6816 * Free a dict item. Also clears the value.
6818 static void
6819 dictitem_free(item)
6820 dictitem_T *item;
6822 clear_tv(&item->di_tv);
6823 vim_free(item);
6827 * Make a copy of dict "d". Shallow if "deep" is FALSE.
6828 * The refcount of the new dict is set to 1.
6829 * See item_copy() for "copyID".
6830 * Returns NULL when out of memory.
6832 static dict_T *
6833 dict_copy(orig, deep, copyID)
6834 dict_T *orig;
6835 int deep;
6836 int copyID;
6838 dict_T *copy;
6839 dictitem_T *di;
6840 int todo;
6841 hashitem_T *hi;
6843 if (orig == NULL)
6844 return NULL;
6846 copy = dict_alloc();
6847 if (copy != NULL)
6849 if (copyID != 0)
6851 orig->dv_copyID = copyID;
6852 orig->dv_copydict = copy;
6854 todo = (int)orig->dv_hashtab.ht_used;
6855 for (hi = orig->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
6857 if (!HASHITEM_EMPTY(hi))
6859 --todo;
6861 di = dictitem_alloc(hi->hi_key);
6862 if (di == NULL)
6863 break;
6864 if (deep)
6866 if (item_copy(&HI2DI(hi)->di_tv, &di->di_tv, deep,
6867 copyID) == FAIL)
6869 vim_free(di);
6870 break;
6873 else
6874 copy_tv(&HI2DI(hi)->di_tv, &di->di_tv);
6875 if (dict_add(copy, di) == FAIL)
6877 dictitem_free(di);
6878 break;
6883 ++copy->dv_refcount;
6884 if (todo > 0)
6886 dict_unref(copy);
6887 copy = NULL;
6891 return copy;
6895 * Add item "item" to Dictionary "d".
6896 * Returns FAIL when out of memory and when key already existed.
6898 static int
6899 dict_add(d, item)
6900 dict_T *d;
6901 dictitem_T *item;
6903 return hash_add(&d->dv_hashtab, item->di_key);
6907 * Add a number or string entry to dictionary "d".
6908 * When "str" is NULL use number "nr", otherwise use "str".
6909 * Returns FAIL when out of memory and when key already exists.
6912 dict_add_nr_str(d, key, nr, str)
6913 dict_T *d;
6914 char *key;
6915 long nr;
6916 char_u *str;
6918 dictitem_T *item;
6920 item = dictitem_alloc((char_u *)key);
6921 if (item == NULL)
6922 return FAIL;
6923 item->di_tv.v_lock = 0;
6924 if (str == NULL)
6926 item->di_tv.v_type = VAR_NUMBER;
6927 item->di_tv.vval.v_number = nr;
6929 else
6931 item->di_tv.v_type = VAR_STRING;
6932 item->di_tv.vval.v_string = vim_strsave(str);
6934 if (dict_add(d, item) == FAIL)
6936 dictitem_free(item);
6937 return FAIL;
6939 return OK;
6943 * Get the number of items in a Dictionary.
6945 static long
6946 dict_len(d)
6947 dict_T *d;
6949 if (d == NULL)
6950 return 0L;
6951 return (long)d->dv_hashtab.ht_used;
6955 * Find item "key[len]" in Dictionary "d".
6956 * If "len" is negative use strlen(key).
6957 * Returns NULL when not found.
6959 static dictitem_T *
6960 dict_find(d, key, len)
6961 dict_T *d;
6962 char_u *key;
6963 int len;
6965 #define AKEYLEN 200
6966 char_u buf[AKEYLEN];
6967 char_u *akey;
6968 char_u *tofree = NULL;
6969 hashitem_T *hi;
6971 if (len < 0)
6972 akey = key;
6973 else if (len >= AKEYLEN)
6975 tofree = akey = vim_strnsave(key, len);
6976 if (akey == NULL)
6977 return NULL;
6979 else
6981 /* Avoid a malloc/free by using buf[]. */
6982 vim_strncpy(buf, key, len);
6983 akey = buf;
6986 hi = hash_find(&d->dv_hashtab, akey);
6987 vim_free(tofree);
6988 if (HASHITEM_EMPTY(hi))
6989 return NULL;
6990 return HI2DI(hi);
6994 * Get a string item from a dictionary.
6995 * When "save" is TRUE allocate memory for it.
6996 * Returns NULL if the entry doesn't exist or out of memory.
6998 char_u *
6999 get_dict_string(d, key, save)
7000 dict_T *d;
7001 char_u *key;
7002 int save;
7004 dictitem_T *di;
7005 char_u *s;
7007 di = dict_find(d, key, -1);
7008 if (di == NULL)
7009 return NULL;
7010 s = get_tv_string(&di->di_tv);
7011 if (save && s != NULL)
7012 s = vim_strsave(s);
7013 return s;
7017 * Get a number item from a dictionary.
7018 * Returns 0 if the entry doesn't exist or out of memory.
7020 long
7021 get_dict_number(d, key)
7022 dict_T *d;
7023 char_u *key;
7025 dictitem_T *di;
7027 di = dict_find(d, key, -1);
7028 if (di == NULL)
7029 return 0;
7030 return get_tv_number(&di->di_tv);
7034 * Return an allocated string with the string representation of a Dictionary.
7035 * May return NULL.
7037 static char_u *
7038 dict2string(tv, copyID)
7039 typval_T *tv;
7040 int copyID;
7042 garray_T ga;
7043 int first = TRUE;
7044 char_u *tofree;
7045 char_u numbuf[NUMBUFLEN];
7046 hashitem_T *hi;
7047 char_u *s;
7048 dict_T *d;
7049 int todo;
7051 if ((d = tv->vval.v_dict) == NULL)
7052 return NULL;
7053 ga_init2(&ga, (int)sizeof(char), 80);
7054 ga_append(&ga, '{');
7056 todo = (int)d->dv_hashtab.ht_used;
7057 for (hi = d->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
7059 if (!HASHITEM_EMPTY(hi))
7061 --todo;
7063 if (first)
7064 first = FALSE;
7065 else
7066 ga_concat(&ga, (char_u *)", ");
7068 tofree = string_quote(hi->hi_key, FALSE);
7069 if (tofree != NULL)
7071 ga_concat(&ga, tofree);
7072 vim_free(tofree);
7074 ga_concat(&ga, (char_u *)": ");
7075 s = tv2string(&HI2DI(hi)->di_tv, &tofree, numbuf, copyID);
7076 if (s != NULL)
7077 ga_concat(&ga, s);
7078 vim_free(tofree);
7079 if (s == NULL)
7080 break;
7083 if (todo > 0)
7085 vim_free(ga.ga_data);
7086 return NULL;
7089 ga_append(&ga, '}');
7090 ga_append(&ga, NUL);
7091 return (char_u *)ga.ga_data;
7095 * Allocate a variable for a Dictionary and fill it from "*arg".
7096 * Return OK or FAIL. Returns NOTDONE for {expr}.
7098 static int
7099 get_dict_tv(arg, rettv, evaluate)
7100 char_u **arg;
7101 typval_T *rettv;
7102 int evaluate;
7104 dict_T *d = NULL;
7105 typval_T tvkey;
7106 typval_T tv;
7107 char_u *key = NULL;
7108 dictitem_T *item;
7109 char_u *start = skipwhite(*arg + 1);
7110 char_u buf[NUMBUFLEN];
7113 * First check if it's not a curly-braces thing: {expr}.
7114 * Must do this without evaluating, otherwise a function may be called
7115 * twice. Unfortunately this means we need to call eval1() twice for the
7116 * first item.
7117 * But {} is an empty Dictionary.
7119 if (*start != '}')
7121 if (eval1(&start, &tv, FALSE) == FAIL) /* recursive! */
7122 return FAIL;
7123 if (*start == '}')
7124 return NOTDONE;
7127 if (evaluate)
7129 d = dict_alloc();
7130 if (d == NULL)
7131 return FAIL;
7133 tvkey.v_type = VAR_UNKNOWN;
7134 tv.v_type = VAR_UNKNOWN;
7136 *arg = skipwhite(*arg + 1);
7137 while (**arg != '}' && **arg != NUL)
7139 if (eval1(arg, &tvkey, evaluate) == FAIL) /* recursive! */
7140 goto failret;
7141 if (**arg != ':')
7143 EMSG2(_("E720: Missing colon in Dictionary: %s"), *arg);
7144 clear_tv(&tvkey);
7145 goto failret;
7147 if (evaluate)
7149 key = get_tv_string_buf_chk(&tvkey, buf);
7150 if (key == NULL || *key == NUL)
7152 /* "key" is NULL when get_tv_string_buf_chk() gave an errmsg */
7153 if (key != NULL)
7154 EMSG(_(e_emptykey));
7155 clear_tv(&tvkey);
7156 goto failret;
7160 *arg = skipwhite(*arg + 1);
7161 if (eval1(arg, &tv, evaluate) == FAIL) /* recursive! */
7163 if (evaluate)
7164 clear_tv(&tvkey);
7165 goto failret;
7167 if (evaluate)
7169 item = dict_find(d, key, -1);
7170 if (item != NULL)
7172 EMSG2(_("E721: Duplicate key in Dictionary: \"%s\""), key);
7173 clear_tv(&tvkey);
7174 clear_tv(&tv);
7175 goto failret;
7177 item = dictitem_alloc(key);
7178 clear_tv(&tvkey);
7179 if (item != NULL)
7181 item->di_tv = tv;
7182 item->di_tv.v_lock = 0;
7183 if (dict_add(d, item) == FAIL)
7184 dictitem_free(item);
7188 if (**arg == '}')
7189 break;
7190 if (**arg != ',')
7192 EMSG2(_("E722: Missing comma in Dictionary: %s"), *arg);
7193 goto failret;
7195 *arg = skipwhite(*arg + 1);
7198 if (**arg != '}')
7200 EMSG2(_("E723: Missing end of Dictionary '}': %s"), *arg);
7201 failret:
7202 if (evaluate)
7203 dict_free(d, TRUE);
7204 return FAIL;
7207 *arg = skipwhite(*arg + 1);
7208 if (evaluate)
7210 rettv->v_type = VAR_DICT;
7211 rettv->vval.v_dict = d;
7212 ++d->dv_refcount;
7215 return OK;
7219 * Return a string with the string representation of a variable.
7220 * If the memory is allocated "tofree" is set to it, otherwise NULL.
7221 * "numbuf" is used for a number.
7222 * Does not put quotes around strings, as ":echo" displays values.
7223 * When "copyID" is not NULL replace recursive lists and dicts with "...".
7224 * May return NULL.
7226 static char_u *
7227 echo_string(tv, tofree, numbuf, copyID)
7228 typval_T *tv;
7229 char_u **tofree;
7230 char_u *numbuf;
7231 int copyID;
7233 static int recurse = 0;
7234 char_u *r = NULL;
7236 if (recurse >= DICT_MAXNEST)
7238 EMSG(_("E724: variable nested too deep for displaying"));
7239 *tofree = NULL;
7240 return NULL;
7242 ++recurse;
7244 switch (tv->v_type)
7246 case VAR_FUNC:
7247 *tofree = NULL;
7248 r = tv->vval.v_string;
7249 break;
7251 case VAR_LIST:
7252 if (tv->vval.v_list == NULL)
7254 *tofree = NULL;
7255 r = NULL;
7257 else if (copyID != 0 && tv->vval.v_list->lv_copyID == copyID)
7259 *tofree = NULL;
7260 r = (char_u *)"[...]";
7262 else
7264 tv->vval.v_list->lv_copyID = copyID;
7265 *tofree = list2string(tv, copyID);
7266 r = *tofree;
7268 break;
7270 case VAR_DICT:
7271 if (tv->vval.v_dict == NULL)
7273 *tofree = NULL;
7274 r = NULL;
7276 else if (copyID != 0 && tv->vval.v_dict->dv_copyID == copyID)
7278 *tofree = NULL;
7279 r = (char_u *)"{...}";
7281 else
7283 tv->vval.v_dict->dv_copyID = copyID;
7284 *tofree = dict2string(tv, copyID);
7285 r = *tofree;
7287 break;
7289 case VAR_STRING:
7290 case VAR_NUMBER:
7291 *tofree = NULL;
7292 r = get_tv_string_buf(tv, numbuf);
7293 break;
7295 #ifdef FEAT_FLOAT
7296 case VAR_FLOAT:
7297 *tofree = NULL;
7298 vim_snprintf((char *)numbuf, NUMBUFLEN, "%g", tv->vval.v_float);
7299 r = numbuf;
7300 break;
7301 #endif
7303 default:
7304 EMSG2(_(e_intern2), "echo_string()");
7305 *tofree = NULL;
7308 --recurse;
7309 return r;
7313 * Return a string with the string representation of a variable.
7314 * If the memory is allocated "tofree" is set to it, otherwise NULL.
7315 * "numbuf" is used for a number.
7316 * Puts quotes around strings, so that they can be parsed back by eval().
7317 * May return NULL.
7319 static char_u *
7320 tv2string(tv, tofree, numbuf, copyID)
7321 typval_T *tv;
7322 char_u **tofree;
7323 char_u *numbuf;
7324 int copyID;
7326 switch (tv->v_type)
7328 case VAR_FUNC:
7329 *tofree = string_quote(tv->vval.v_string, TRUE);
7330 return *tofree;
7331 case VAR_STRING:
7332 *tofree = string_quote(tv->vval.v_string, FALSE);
7333 return *tofree;
7334 #ifdef FEAT_FLOAT
7335 case VAR_FLOAT:
7336 *tofree = NULL;
7337 vim_snprintf((char *)numbuf, NUMBUFLEN - 1, "%g", tv->vval.v_float);
7338 return numbuf;
7339 #endif
7340 case VAR_NUMBER:
7341 case VAR_LIST:
7342 case VAR_DICT:
7343 break;
7344 default:
7345 EMSG2(_(e_intern2), "tv2string()");
7347 return echo_string(tv, tofree, numbuf, copyID);
7351 * Return string "str" in ' quotes, doubling ' characters.
7352 * If "str" is NULL an empty string is assumed.
7353 * If "function" is TRUE make it function('string').
7355 static char_u *
7356 string_quote(str, function)
7357 char_u *str;
7358 int function;
7360 unsigned len;
7361 char_u *p, *r, *s;
7363 len = (function ? 13 : 3);
7364 if (str != NULL)
7366 len += (unsigned)STRLEN(str);
7367 for (p = str; *p != NUL; mb_ptr_adv(p))
7368 if (*p == '\'')
7369 ++len;
7371 s = r = alloc(len);
7372 if (r != NULL)
7374 if (function)
7376 STRCPY(r, "function('");
7377 r += 10;
7379 else
7380 *r++ = '\'';
7381 if (str != NULL)
7382 for (p = str; *p != NUL; )
7384 if (*p == '\'')
7385 *r++ = '\'';
7386 MB_COPY_CHAR(p, r);
7388 *r++ = '\'';
7389 if (function)
7390 *r++ = ')';
7391 *r++ = NUL;
7393 return s;
7396 #ifdef FEAT_FLOAT
7398 * Convert the string "text" to a floating point number.
7399 * This uses strtod(). setlocale(LC_NUMERIC, "C") has been used to make sure
7400 * this always uses a decimal point.
7401 * Returns the length of the text that was consumed.
7403 static int
7404 string2float(text, value)
7405 char_u *text;
7406 float_T *value; /* result stored here */
7408 char *s = (char *)text;
7409 float_T f;
7411 f = strtod(s, &s);
7412 *value = f;
7413 return (int)((char_u *)s - text);
7415 #endif
7418 * Get the value of an environment variable.
7419 * "arg" is pointing to the '$'. It is advanced to after the name.
7420 * If the environment variable was not set, silently assume it is empty.
7421 * Always return OK.
7423 static int
7424 get_env_tv(arg, rettv, evaluate)
7425 char_u **arg;
7426 typval_T *rettv;
7427 int evaluate;
7429 char_u *string = NULL;
7430 int len;
7431 int cc;
7432 char_u *name;
7433 int mustfree = FALSE;
7435 ++*arg;
7436 name = *arg;
7437 len = get_env_len(arg);
7438 if (evaluate)
7440 if (len != 0)
7442 cc = name[len];
7443 name[len] = NUL;
7444 /* first try vim_getenv(), fast for normal environment vars */
7445 string = vim_getenv(name, &mustfree);
7446 if (string != NULL && *string != NUL)
7448 if (!mustfree)
7449 string = vim_strsave(string);
7451 else
7453 if (mustfree)
7454 vim_free(string);
7456 /* next try expanding things like $VIM and ${HOME} */
7457 string = expand_env_save(name - 1);
7458 if (string != NULL && *string == '$')
7460 vim_free(string);
7461 string = NULL;
7464 name[len] = cc;
7466 rettv->v_type = VAR_STRING;
7467 rettv->vval.v_string = string;
7470 return OK;
7474 * Array with names and number of arguments of all internal functions
7475 * MUST BE KEPT SORTED IN strcmp() ORDER FOR BINARY SEARCH!
7477 static struct fst
7479 char *f_name; /* function name */
7480 char f_min_argc; /* minimal number of arguments */
7481 char f_max_argc; /* maximal number of arguments */
7482 void (*f_func) __ARGS((typval_T *args, typval_T *rvar));
7483 /* implementation of function */
7484 } functions[] =
7486 #ifdef FEAT_FLOAT
7487 {"abs", 1, 1, f_abs},
7488 #endif
7489 {"add", 2, 2, f_add},
7490 {"append", 2, 2, f_append},
7491 {"argc", 0, 0, f_argc},
7492 {"argidx", 0, 0, f_argidx},
7493 {"argv", 0, 1, f_argv},
7494 #ifdef FEAT_FLOAT
7495 {"atan", 1, 1, f_atan},
7496 #endif
7497 {"browse", 4, 4, f_browse},
7498 {"browsedir", 2, 2, f_browsedir},
7499 {"bufexists", 1, 1, f_bufexists},
7500 {"buffer_exists", 1, 1, f_bufexists}, /* obsolete */
7501 {"buffer_name", 1, 1, f_bufname}, /* obsolete */
7502 {"buffer_number", 1, 1, f_bufnr}, /* obsolete */
7503 {"buflisted", 1, 1, f_buflisted},
7504 {"bufloaded", 1, 1, f_bufloaded},
7505 {"bufname", 1, 1, f_bufname},
7506 {"bufnr", 1, 2, f_bufnr},
7507 {"bufwinnr", 1, 1, f_bufwinnr},
7508 {"byte2line", 1, 1, f_byte2line},
7509 {"byteidx", 2, 2, f_byteidx},
7510 {"call", 2, 3, f_call},
7511 #ifdef FEAT_FLOAT
7512 {"ceil", 1, 1, f_ceil},
7513 #endif
7514 {"changenr", 0, 0, f_changenr},
7515 {"char2nr", 1, 1, f_char2nr},
7516 {"cindent", 1, 1, f_cindent},
7517 {"clearmatches", 0, 0, f_clearmatches},
7518 {"col", 1, 1, f_col},
7519 #if defined(FEAT_INS_EXPAND)
7520 {"complete", 2, 2, f_complete},
7521 {"complete_add", 1, 1, f_complete_add},
7522 {"complete_check", 0, 0, f_complete_check},
7523 #endif
7524 {"confirm", 1, 4, f_confirm},
7525 {"copy", 1, 1, f_copy},
7526 #ifdef FEAT_FLOAT
7527 {"cos", 1, 1, f_cos},
7528 #endif
7529 {"count", 2, 4, f_count},
7530 {"cscope_connection",0,3, f_cscope_connection},
7531 {"cursor", 1, 3, f_cursor},
7532 {"deepcopy", 1, 2, f_deepcopy},
7533 {"delete", 1, 1, f_delete},
7534 {"did_filetype", 0, 0, f_did_filetype},
7535 {"diff_filler", 1, 1, f_diff_filler},
7536 {"diff_hlID", 2, 2, f_diff_hlID},
7537 {"empty", 1, 1, f_empty},
7538 {"escape", 2, 2, f_escape},
7539 {"eval", 1, 1, f_eval},
7540 {"eventhandler", 0, 0, f_eventhandler},
7541 {"executable", 1, 1, f_executable},
7542 {"exists", 1, 1, f_exists},
7543 {"expand", 1, 2, f_expand},
7544 {"extend", 2, 3, f_extend},
7545 {"feedkeys", 1, 2, f_feedkeys},
7546 {"file_readable", 1, 1, f_filereadable}, /* obsolete */
7547 {"filereadable", 1, 1, f_filereadable},
7548 {"filewritable", 1, 1, f_filewritable},
7549 {"filter", 2, 2, f_filter},
7550 {"finddir", 1, 3, f_finddir},
7551 {"findfile", 1, 3, f_findfile},
7552 #ifdef FEAT_FLOAT
7553 {"float2nr", 1, 1, f_float2nr},
7554 {"floor", 1, 1, f_floor},
7555 #endif
7556 {"fnameescape", 1, 1, f_fnameescape},
7557 {"fnamemodify", 2, 2, f_fnamemodify},
7558 {"foldclosed", 1, 1, f_foldclosed},
7559 {"foldclosedend", 1, 1, f_foldclosedend},
7560 {"foldlevel", 1, 1, f_foldlevel},
7561 {"foldtext", 0, 0, f_foldtext},
7562 {"foldtextresult", 1, 1, f_foldtextresult},
7563 {"foreground", 0, 0, f_foreground},
7564 {"function", 1, 1, f_function},
7565 {"garbagecollect", 0, 1, f_garbagecollect},
7566 {"get", 2, 3, f_get},
7567 {"getbufline", 2, 3, f_getbufline},
7568 {"getbufvar", 2, 2, f_getbufvar},
7569 {"getchar", 0, 1, f_getchar},
7570 {"getcharmod", 0, 0, f_getcharmod},
7571 {"getcmdline", 0, 0, f_getcmdline},
7572 {"getcmdpos", 0, 0, f_getcmdpos},
7573 {"getcmdtype", 0, 0, f_getcmdtype},
7574 {"getcwd", 0, 0, f_getcwd},
7575 {"getfontname", 0, 1, f_getfontname},
7576 {"getfperm", 1, 1, f_getfperm},
7577 {"getfsize", 1, 1, f_getfsize},
7578 {"getftime", 1, 1, f_getftime},
7579 {"getftype", 1, 1, f_getftype},
7580 {"getline", 1, 2, f_getline},
7581 {"getloclist", 1, 1, f_getqflist},
7582 {"getmatches", 0, 0, f_getmatches},
7583 {"getpid", 0, 0, f_getpid},
7584 {"getpos", 1, 1, f_getpos},
7585 {"getqflist", 0, 0, f_getqflist},
7586 {"getreg", 0, 2, f_getreg},
7587 {"getregtype", 0, 1, f_getregtype},
7588 {"gettabwinvar", 3, 3, f_gettabwinvar},
7589 {"getwinposx", 0, 0, f_getwinposx},
7590 {"getwinposy", 0, 0, f_getwinposy},
7591 {"getwinvar", 2, 2, f_getwinvar},
7592 {"glob", 1, 2, f_glob},
7593 {"globpath", 2, 3, f_globpath},
7594 {"has", 1, 1, f_has},
7595 {"has_key", 2, 2, f_has_key},
7596 {"haslocaldir", 0, 0, f_haslocaldir},
7597 {"hasmapto", 1, 3, f_hasmapto},
7598 {"highlightID", 1, 1, f_hlID}, /* obsolete */
7599 {"highlight_exists",1, 1, f_hlexists}, /* obsolete */
7600 {"histadd", 2, 2, f_histadd},
7601 {"histdel", 1, 2, f_histdel},
7602 {"histget", 1, 2, f_histget},
7603 {"histnr", 1, 1, f_histnr},
7604 {"hlID", 1, 1, f_hlID},
7605 {"hlexists", 1, 1, f_hlexists},
7606 {"hostname", 0, 0, f_hostname},
7607 {"iconv", 3, 3, f_iconv},
7608 {"indent", 1, 1, f_indent},
7609 {"index", 2, 4, f_index},
7610 {"input", 1, 3, f_input},
7611 {"inputdialog", 1, 3, f_inputdialog},
7612 {"inputlist", 1, 1, f_inputlist},
7613 {"inputrestore", 0, 0, f_inputrestore},
7614 {"inputsave", 0, 0, f_inputsave},
7615 {"inputsecret", 1, 2, f_inputsecret},
7616 {"insert", 2, 3, f_insert},
7617 {"isdirectory", 1, 1, f_isdirectory},
7618 {"islocked", 1, 1, f_islocked},
7619 {"items", 1, 1, f_items},
7620 {"join", 1, 2, f_join},
7621 {"keys", 1, 1, f_keys},
7622 {"last_buffer_nr", 0, 0, f_last_buffer_nr},/* obsolete */
7623 {"len", 1, 1, f_len},
7624 {"libcall", 3, 3, f_libcall},
7625 {"libcallnr", 3, 3, f_libcallnr},
7626 {"line", 1, 1, f_line},
7627 {"line2byte", 1, 1, f_line2byte},
7628 {"lispindent", 1, 1, f_lispindent},
7629 {"localtime", 0, 0, f_localtime},
7630 #ifdef FEAT_FLOAT
7631 {"log10", 1, 1, f_log10},
7632 #endif
7633 {"map", 2, 2, f_map},
7634 {"maparg", 1, 3, f_maparg},
7635 {"mapcheck", 1, 3, f_mapcheck},
7636 {"match", 2, 4, f_match},
7637 {"matchadd", 2, 4, f_matchadd},
7638 {"matcharg", 1, 1, f_matcharg},
7639 {"matchdelete", 1, 1, f_matchdelete},
7640 {"matchend", 2, 4, f_matchend},
7641 {"matchlist", 2, 4, f_matchlist},
7642 {"matchstr", 2, 4, f_matchstr},
7643 {"max", 1, 1, f_max},
7644 {"min", 1, 1, f_min},
7645 #ifdef vim_mkdir
7646 {"mkdir", 1, 3, f_mkdir},
7647 #endif
7648 {"mode", 0, 1, f_mode},
7649 {"nextnonblank", 1, 1, f_nextnonblank},
7650 {"nr2char", 1, 1, f_nr2char},
7651 {"pathshorten", 1, 1, f_pathshorten},
7652 #ifdef FEAT_FLOAT
7653 {"pow", 2, 2, f_pow},
7654 #endif
7655 {"prevnonblank", 1, 1, f_prevnonblank},
7656 {"printf", 2, 19, f_printf},
7657 {"pumvisible", 0, 0, f_pumvisible},
7658 {"range", 1, 3, f_range},
7659 {"readfile", 1, 3, f_readfile},
7660 {"reltime", 0, 2, f_reltime},
7661 {"reltimestr", 1, 1, f_reltimestr},
7662 {"remote_expr", 2, 3, f_remote_expr},
7663 {"remote_foreground", 1, 1, f_remote_foreground},
7664 {"remote_peek", 1, 2, f_remote_peek},
7665 {"remote_read", 1, 1, f_remote_read},
7666 {"remote_send", 2, 3, f_remote_send},
7667 {"remove", 2, 3, f_remove},
7668 {"rename", 2, 2, f_rename},
7669 {"repeat", 2, 2, f_repeat},
7670 {"resolve", 1, 1, f_resolve},
7671 {"reverse", 1, 1, f_reverse},
7672 #ifdef FEAT_FLOAT
7673 {"round", 1, 1, f_round},
7674 #endif
7675 {"search", 1, 4, f_search},
7676 {"searchdecl", 1, 3, f_searchdecl},
7677 {"searchpair", 3, 7, f_searchpair},
7678 {"searchpairpos", 3, 7, f_searchpairpos},
7679 {"searchpos", 1, 4, f_searchpos},
7680 {"server2client", 2, 2, f_server2client},
7681 {"serverlist", 0, 0, f_serverlist},
7682 {"setbufvar", 3, 3, f_setbufvar},
7683 {"setcmdpos", 1, 1, f_setcmdpos},
7684 {"setline", 2, 2, f_setline},
7685 {"setloclist", 2, 3, f_setloclist},
7686 {"setmatches", 1, 1, f_setmatches},
7687 {"setpos", 2, 2, f_setpos},
7688 {"setqflist", 1, 2, f_setqflist},
7689 {"setreg", 2, 3, f_setreg},
7690 {"settabwinvar", 4, 4, f_settabwinvar},
7691 {"setwinvar", 3, 3, f_setwinvar},
7692 {"shellescape", 1, 2, f_shellescape},
7693 {"simplify", 1, 1, f_simplify},
7694 #ifdef FEAT_FLOAT
7695 {"sin", 1, 1, f_sin},
7696 #endif
7697 {"sort", 1, 2, f_sort},
7698 {"soundfold", 1, 1, f_soundfold},
7699 {"spellbadword", 0, 1, f_spellbadword},
7700 {"spellsuggest", 1, 3, f_spellsuggest},
7701 {"split", 1, 3, f_split},
7702 #ifdef FEAT_FLOAT
7703 {"sqrt", 1, 1, f_sqrt},
7704 {"str2float", 1, 1, f_str2float},
7705 #endif
7706 {"str2nr", 1, 2, f_str2nr},
7707 #ifdef HAVE_STRFTIME
7708 {"strftime", 1, 2, f_strftime},
7709 #endif
7710 {"stridx", 2, 3, f_stridx},
7711 {"string", 1, 1, f_string},
7712 {"strlen", 1, 1, f_strlen},
7713 {"strpart", 2, 3, f_strpart},
7714 {"strridx", 2, 3, f_strridx},
7715 {"strtrans", 1, 1, f_strtrans},
7716 {"submatch", 1, 1, f_submatch},
7717 {"substitute", 4, 4, f_substitute},
7718 {"synID", 3, 3, f_synID},
7719 {"synIDattr", 2, 3, f_synIDattr},
7720 {"synIDtrans", 1, 1, f_synIDtrans},
7721 {"synstack", 2, 2, f_synstack},
7722 {"system", 1, 2, f_system},
7723 {"tabpagebuflist", 0, 1, f_tabpagebuflist},
7724 {"tabpagenr", 0, 1, f_tabpagenr},
7725 {"tabpagewinnr", 1, 2, f_tabpagewinnr},
7726 {"tagfiles", 0, 0, f_tagfiles},
7727 {"taglist", 1, 1, f_taglist},
7728 {"tempname", 0, 0, f_tempname},
7729 {"test", 1, 1, f_test},
7730 {"tolower", 1, 1, f_tolower},
7731 {"toupper", 1, 1, f_toupper},
7732 {"tr", 3, 3, f_tr},
7733 #ifdef FEAT_FLOAT
7734 {"trunc", 1, 1, f_trunc},
7735 #endif
7736 {"type", 1, 1, f_type},
7737 {"values", 1, 1, f_values},
7738 {"virtcol", 1, 1, f_virtcol},
7739 {"visualmode", 0, 1, f_visualmode},
7740 {"winbufnr", 1, 1, f_winbufnr},
7741 {"wincol", 0, 0, f_wincol},
7742 {"winheight", 1, 1, f_winheight},
7743 {"winline", 0, 0, f_winline},
7744 {"winnr", 0, 1, f_winnr},
7745 {"winrestcmd", 0, 0, f_winrestcmd},
7746 {"winrestview", 1, 1, f_winrestview},
7747 {"winsaveview", 0, 0, f_winsaveview},
7748 {"winwidth", 1, 1, f_winwidth},
7749 {"writefile", 2, 3, f_writefile},
7752 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
7755 * Function given to ExpandGeneric() to obtain the list of internal
7756 * or user defined function names.
7758 char_u *
7759 get_function_name(xp, idx)
7760 expand_T *xp;
7761 int idx;
7763 static int intidx = -1;
7764 char_u *name;
7766 if (idx == 0)
7767 intidx = -1;
7768 if (intidx < 0)
7770 name = get_user_func_name(xp, idx);
7771 if (name != NULL)
7772 return name;
7774 if (++intidx < (int)(sizeof(functions) / sizeof(struct fst)))
7776 STRCPY(IObuff, functions[intidx].f_name);
7777 STRCAT(IObuff, "(");
7778 if (functions[intidx].f_max_argc == 0)
7779 STRCAT(IObuff, ")");
7780 return IObuff;
7783 return NULL;
7787 * Function given to ExpandGeneric() to obtain the list of internal or
7788 * user defined variable or function names.
7790 /*ARGSUSED*/
7791 char_u *
7792 get_expr_name(xp, idx)
7793 expand_T *xp;
7794 int idx;
7796 static int intidx = -1;
7797 char_u *name;
7799 if (idx == 0)
7800 intidx = -1;
7801 if (intidx < 0)
7803 name = get_function_name(xp, idx);
7804 if (name != NULL)
7805 return name;
7807 return get_user_var_name(xp, ++intidx);
7810 #endif /* FEAT_CMDL_COMPL */
7813 * Find internal function in table above.
7814 * Return index, or -1 if not found
7816 static int
7817 find_internal_func(name)
7818 char_u *name; /* name of the function */
7820 int first = 0;
7821 int last = (int)(sizeof(functions) / sizeof(struct fst)) - 1;
7822 int cmp;
7823 int x;
7826 * Find the function name in the table. Binary search.
7828 while (first <= last)
7830 x = first + ((unsigned)(last - first) >> 1);
7831 cmp = STRCMP(name, functions[x].f_name);
7832 if (cmp < 0)
7833 last = x - 1;
7834 else if (cmp > 0)
7835 first = x + 1;
7836 else
7837 return x;
7839 return -1;
7843 * Check if "name" is a variable of type VAR_FUNC. If so, return the function
7844 * name it contains, otherwise return "name".
7846 static char_u *
7847 deref_func_name(name, lenp)
7848 char_u *name;
7849 int *lenp;
7851 dictitem_T *v;
7852 int cc;
7854 cc = name[*lenp];
7855 name[*lenp] = NUL;
7856 v = find_var(name, NULL);
7857 name[*lenp] = cc;
7858 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
7860 if (v->di_tv.vval.v_string == NULL)
7862 *lenp = 0;
7863 return (char_u *)""; /* just in case */
7865 *lenp = (int)STRLEN(v->di_tv.vval.v_string);
7866 return v->di_tv.vval.v_string;
7869 return name;
7873 * Allocate a variable for the result of a function.
7874 * Return OK or FAIL.
7876 static int
7877 get_func_tv(name, len, rettv, arg, firstline, lastline, doesrange,
7878 evaluate, selfdict)
7879 char_u *name; /* name of the function */
7880 int len; /* length of "name" */
7881 typval_T *rettv;
7882 char_u **arg; /* argument, pointing to the '(' */
7883 linenr_T firstline; /* first line of range */
7884 linenr_T lastline; /* last line of range */
7885 int *doesrange; /* return: function handled range */
7886 int evaluate;
7887 dict_T *selfdict; /* Dictionary for "self" */
7889 char_u *argp;
7890 int ret = OK;
7891 typval_T argvars[MAX_FUNC_ARGS + 1]; /* vars for arguments */
7892 int argcount = 0; /* number of arguments found */
7895 * Get the arguments.
7897 argp = *arg;
7898 while (argcount < MAX_FUNC_ARGS)
7900 argp = skipwhite(argp + 1); /* skip the '(' or ',' */
7901 if (*argp == ')' || *argp == ',' || *argp == NUL)
7902 break;
7903 if (eval1(&argp, &argvars[argcount], evaluate) == FAIL)
7905 ret = FAIL;
7906 break;
7908 ++argcount;
7909 if (*argp != ',')
7910 break;
7912 if (*argp == ')')
7913 ++argp;
7914 else
7915 ret = FAIL;
7917 if (ret == OK)
7918 ret = call_func(name, len, rettv, argcount, argvars,
7919 firstline, lastline, doesrange, evaluate, selfdict);
7920 else if (!aborting())
7922 if (argcount == MAX_FUNC_ARGS)
7923 emsg_funcname(N_("E740: Too many arguments for function %s"), name);
7924 else
7925 emsg_funcname(N_("E116: Invalid arguments for function %s"), name);
7928 while (--argcount >= 0)
7929 clear_tv(&argvars[argcount]);
7931 *arg = skipwhite(argp);
7932 return ret;
7937 * Call a function with its resolved parameters
7938 * Return OK when the function can't be called, FAIL otherwise.
7939 * Also returns OK when an error was encountered while executing the function.
7941 static int
7942 call_func(name, len, rettv, argcount, argvars, firstline, lastline,
7943 doesrange, evaluate, selfdict)
7944 char_u *name; /* name of the function */
7945 int len; /* length of "name" */
7946 typval_T *rettv; /* return value goes here */
7947 int argcount; /* number of "argvars" */
7948 typval_T *argvars; /* vars for arguments, must have "argcount"
7949 PLUS ONE elements! */
7950 linenr_T firstline; /* first line of range */
7951 linenr_T lastline; /* last line of range */
7952 int *doesrange; /* return: function handled range */
7953 int evaluate;
7954 dict_T *selfdict; /* Dictionary for "self" */
7956 int ret = FAIL;
7957 #define ERROR_UNKNOWN 0
7958 #define ERROR_TOOMANY 1
7959 #define ERROR_TOOFEW 2
7960 #define ERROR_SCRIPT 3
7961 #define ERROR_DICT 4
7962 #define ERROR_NONE 5
7963 #define ERROR_OTHER 6
7964 int error = ERROR_NONE;
7965 int i;
7966 int llen;
7967 ufunc_T *fp;
7968 int cc;
7969 #define FLEN_FIXED 40
7970 char_u fname_buf[FLEN_FIXED + 1];
7971 char_u *fname;
7974 * In a script change <SID>name() and s:name() to K_SNR 123_name().
7975 * Change <SNR>123_name() to K_SNR 123_name().
7976 * Use fname_buf[] when it fits, otherwise allocate memory (slow).
7978 cc = name[len];
7979 name[len] = NUL;
7980 llen = eval_fname_script(name);
7981 if (llen > 0)
7983 fname_buf[0] = K_SPECIAL;
7984 fname_buf[1] = KS_EXTRA;
7985 fname_buf[2] = (int)KE_SNR;
7986 i = 3;
7987 if (eval_fname_sid(name)) /* "<SID>" or "s:" */
7989 if (current_SID <= 0)
7990 error = ERROR_SCRIPT;
7991 else
7993 sprintf((char *)fname_buf + 3, "%ld_", (long)current_SID);
7994 i = (int)STRLEN(fname_buf);
7997 if (i + STRLEN(name + llen) < FLEN_FIXED)
7999 STRCPY(fname_buf + i, name + llen);
8000 fname = fname_buf;
8002 else
8004 fname = alloc((unsigned)(i + STRLEN(name + llen) + 1));
8005 if (fname == NULL)
8006 error = ERROR_OTHER;
8007 else
8009 mch_memmove(fname, fname_buf, (size_t)i);
8010 STRCPY(fname + i, name + llen);
8014 else
8015 fname = name;
8017 *doesrange = FALSE;
8020 /* execute the function if no errors detected and executing */
8021 if (evaluate && error == ERROR_NONE)
8023 rettv->v_type = VAR_NUMBER; /* default rettv is number zero */
8024 rettv->vval.v_number = 0;
8025 error = ERROR_UNKNOWN;
8027 if (!builtin_function(fname))
8030 * User defined function.
8032 fp = find_func(fname);
8034 #ifdef FEAT_AUTOCMD
8035 /* Trigger FuncUndefined event, may load the function. */
8036 if (fp == NULL
8037 && apply_autocmds(EVENT_FUNCUNDEFINED,
8038 fname, fname, TRUE, NULL)
8039 && !aborting())
8041 /* executed an autocommand, search for the function again */
8042 fp = find_func(fname);
8044 #endif
8045 /* Try loading a package. */
8046 if (fp == NULL && script_autoload(fname, TRUE) && !aborting())
8048 /* loaded a package, search for the function again */
8049 fp = find_func(fname);
8052 if (fp != NULL)
8054 if (fp->uf_flags & FC_RANGE)
8055 *doesrange = TRUE;
8056 if (argcount < fp->uf_args.ga_len)
8057 error = ERROR_TOOFEW;
8058 else if (!fp->uf_varargs && argcount > fp->uf_args.ga_len)
8059 error = ERROR_TOOMANY;
8060 else if ((fp->uf_flags & FC_DICT) && selfdict == NULL)
8061 error = ERROR_DICT;
8062 else
8065 * Call the user function.
8066 * Save and restore search patterns, script variables and
8067 * redo buffer.
8069 save_search_patterns();
8070 saveRedobuff();
8071 ++fp->uf_calls;
8072 call_user_func(fp, argcount, argvars, rettv,
8073 firstline, lastline,
8074 (fp->uf_flags & FC_DICT) ? selfdict : NULL);
8075 if (--fp->uf_calls <= 0 && isdigit(*fp->uf_name)
8076 && fp->uf_refcount <= 0)
8077 /* Function was unreferenced while being used, free it
8078 * now. */
8079 func_free(fp);
8080 restoreRedobuff();
8081 restore_search_patterns();
8082 error = ERROR_NONE;
8086 else
8089 * Find the function name in the table, call its implementation.
8091 i = find_internal_func(fname);
8092 if (i >= 0)
8094 if (argcount < functions[i].f_min_argc)
8095 error = ERROR_TOOFEW;
8096 else if (argcount > functions[i].f_max_argc)
8097 error = ERROR_TOOMANY;
8098 else
8100 argvars[argcount].v_type = VAR_UNKNOWN;
8101 functions[i].f_func(argvars, rettv);
8102 error = ERROR_NONE;
8107 * The function call (or "FuncUndefined" autocommand sequence) might
8108 * have been aborted by an error, an interrupt, or an explicitly thrown
8109 * exception that has not been caught so far. This situation can be
8110 * tested for by calling aborting(). For an error in an internal
8111 * function or for the "E132" error in call_user_func(), however, the
8112 * throw point at which the "force_abort" flag (temporarily reset by
8113 * emsg()) is normally updated has not been reached yet. We need to
8114 * update that flag first to make aborting() reliable.
8116 update_force_abort();
8118 if (error == ERROR_NONE)
8119 ret = OK;
8122 * Report an error unless the argument evaluation or function call has been
8123 * cancelled due to an aborting error, an interrupt, or an exception.
8125 if (!aborting())
8127 switch (error)
8129 case ERROR_UNKNOWN:
8130 emsg_funcname(N_("E117: Unknown function: %s"), name);
8131 break;
8132 case ERROR_TOOMANY:
8133 emsg_funcname(e_toomanyarg, name);
8134 break;
8135 case ERROR_TOOFEW:
8136 emsg_funcname(N_("E119: Not enough arguments for function: %s"),
8137 name);
8138 break;
8139 case ERROR_SCRIPT:
8140 emsg_funcname(N_("E120: Using <SID> not in a script context: %s"),
8141 name);
8142 break;
8143 case ERROR_DICT:
8144 emsg_funcname(N_("E725: Calling dict function without Dictionary: %s"),
8145 name);
8146 break;
8150 name[len] = cc;
8151 if (fname != name && fname != fname_buf)
8152 vim_free(fname);
8154 return ret;
8158 * Give an error message with a function name. Handle <SNR> things.
8159 * "ermsg" is to be passed without translation, use N_() instead of _().
8161 static void
8162 emsg_funcname(ermsg, name)
8163 char *ermsg;
8164 char_u *name;
8166 char_u *p;
8168 if (*name == K_SPECIAL)
8169 p = concat_str((char_u *)"<SNR>", name + 3);
8170 else
8171 p = name;
8172 EMSG2(_(ermsg), p);
8173 if (p != name)
8174 vim_free(p);
8178 * Return TRUE for a non-zero Number and a non-empty String.
8180 static int
8181 non_zero_arg(argvars)
8182 typval_T *argvars;
8184 return ((argvars[0].v_type == VAR_NUMBER
8185 && argvars[0].vval.v_number != 0)
8186 || (argvars[0].v_type == VAR_STRING
8187 && argvars[0].vval.v_string != NULL
8188 && *argvars[0].vval.v_string != NUL));
8191 /*********************************************
8192 * Implementation of the built-in functions
8195 #ifdef FEAT_FLOAT
8197 * "abs(expr)" function
8199 static void
8200 f_abs(argvars, rettv)
8201 typval_T *argvars;
8202 typval_T *rettv;
8204 if (argvars[0].v_type == VAR_FLOAT)
8206 rettv->v_type = VAR_FLOAT;
8207 rettv->vval.v_float = fabs(argvars[0].vval.v_float);
8209 else
8211 varnumber_T n;
8212 int error = FALSE;
8214 n = get_tv_number_chk(&argvars[0], &error);
8215 if (error)
8216 rettv->vval.v_number = -1;
8217 else if (n > 0)
8218 rettv->vval.v_number = n;
8219 else
8220 rettv->vval.v_number = -n;
8223 #endif
8226 * "add(list, item)" function
8228 static void
8229 f_add(argvars, rettv)
8230 typval_T *argvars;
8231 typval_T *rettv;
8233 list_T *l;
8235 rettv->vval.v_number = 1; /* Default: Failed */
8236 if (argvars[0].v_type == VAR_LIST)
8238 if ((l = argvars[0].vval.v_list) != NULL
8239 && !tv_check_lock(l->lv_lock, (char_u *)"add()")
8240 && list_append_tv(l, &argvars[1]) == OK)
8241 copy_tv(&argvars[0], rettv);
8243 else
8244 EMSG(_(e_listreq));
8248 * "append(lnum, string/list)" function
8250 static void
8251 f_append(argvars, rettv)
8252 typval_T *argvars;
8253 typval_T *rettv;
8255 long lnum;
8256 char_u *line;
8257 list_T *l = NULL;
8258 listitem_T *li = NULL;
8259 typval_T *tv;
8260 long added = 0;
8262 lnum = get_tv_lnum(argvars);
8263 if (lnum >= 0
8264 && lnum <= curbuf->b_ml.ml_line_count
8265 && u_save(lnum, lnum + 1) == OK)
8267 if (argvars[1].v_type == VAR_LIST)
8269 l = argvars[1].vval.v_list;
8270 if (l == NULL)
8271 return;
8272 li = l->lv_first;
8274 for (;;)
8276 if (l == NULL)
8277 tv = &argvars[1]; /* append a string */
8278 else if (li == NULL)
8279 break; /* end of list */
8280 else
8281 tv = &li->li_tv; /* append item from list */
8282 line = get_tv_string_chk(tv);
8283 if (line == NULL) /* type error */
8285 rettv->vval.v_number = 1; /* Failed */
8286 break;
8288 ml_append(lnum + added, line, (colnr_T)0, FALSE);
8289 ++added;
8290 if (l == NULL)
8291 break;
8292 li = li->li_next;
8295 appended_lines_mark(lnum, added);
8296 if (curwin->w_cursor.lnum > lnum)
8297 curwin->w_cursor.lnum += added;
8299 else
8300 rettv->vval.v_number = 1; /* Failed */
8304 * "argc()" function
8306 static void
8307 f_argc(argvars, rettv)
8308 typval_T *argvars UNUSED;
8309 typval_T *rettv;
8311 rettv->vval.v_number = ARGCOUNT;
8315 * "argidx()" function
8317 static void
8318 f_argidx(argvars, rettv)
8319 typval_T *argvars UNUSED;
8320 typval_T *rettv;
8322 rettv->vval.v_number = curwin->w_arg_idx;
8326 * "argv(nr)" function
8328 static void
8329 f_argv(argvars, rettv)
8330 typval_T *argvars;
8331 typval_T *rettv;
8333 int idx;
8335 if (argvars[0].v_type != VAR_UNKNOWN)
8337 idx = get_tv_number_chk(&argvars[0], NULL);
8338 if (idx >= 0 && idx < ARGCOUNT)
8339 rettv->vval.v_string = vim_strsave(alist_name(&ARGLIST[idx]));
8340 else
8341 rettv->vval.v_string = NULL;
8342 rettv->v_type = VAR_STRING;
8344 else if (rettv_list_alloc(rettv) == OK)
8345 for (idx = 0; idx < ARGCOUNT; ++idx)
8346 list_append_string(rettv->vval.v_list,
8347 alist_name(&ARGLIST[idx]), -1);
8350 #ifdef FEAT_FLOAT
8351 static int get_float_arg __ARGS((typval_T *argvars, float_T *f));
8354 * Get the float value of "argvars[0]" into "f".
8355 * Returns FAIL when the argument is not a Number or Float.
8357 static int
8358 get_float_arg(argvars, f)
8359 typval_T *argvars;
8360 float_T *f;
8362 if (argvars[0].v_type == VAR_FLOAT)
8364 *f = argvars[0].vval.v_float;
8365 return OK;
8367 if (argvars[0].v_type == VAR_NUMBER)
8369 *f = (float_T)argvars[0].vval.v_number;
8370 return OK;
8372 EMSG(_("E808: Number or Float required"));
8373 return FAIL;
8377 * "atan()" function
8379 static void
8380 f_atan(argvars, rettv)
8381 typval_T *argvars;
8382 typval_T *rettv;
8384 float_T f;
8386 rettv->v_type = VAR_FLOAT;
8387 if (get_float_arg(argvars, &f) == OK)
8388 rettv->vval.v_float = atan(f);
8389 else
8390 rettv->vval.v_float = 0.0;
8392 #endif
8395 * "browse(save, title, initdir, default)" function
8397 static void
8398 f_browse(argvars, rettv)
8399 typval_T *argvars UNUSED;
8400 typval_T *rettv;
8402 #ifdef FEAT_BROWSE
8403 int save;
8404 char_u *title;
8405 char_u *initdir;
8406 char_u *defname;
8407 char_u buf[NUMBUFLEN];
8408 char_u buf2[NUMBUFLEN];
8409 int error = FALSE;
8411 save = get_tv_number_chk(&argvars[0], &error);
8412 title = get_tv_string_chk(&argvars[1]);
8413 initdir = get_tv_string_buf_chk(&argvars[2], buf);
8414 defname = get_tv_string_buf_chk(&argvars[3], buf2);
8416 if (error || title == NULL || initdir == NULL || defname == NULL)
8417 rettv->vval.v_string = NULL;
8418 else
8419 rettv->vval.v_string =
8420 do_browse(save ? BROWSE_SAVE : 0,
8421 title, defname, NULL, initdir, NULL, curbuf);
8422 #else
8423 rettv->vval.v_string = NULL;
8424 #endif
8425 rettv->v_type = VAR_STRING;
8429 * "browsedir(title, initdir)" function
8431 static void
8432 f_browsedir(argvars, rettv)
8433 typval_T *argvars UNUSED;
8434 typval_T *rettv;
8436 #ifdef FEAT_BROWSE
8437 char_u *title;
8438 char_u *initdir;
8439 char_u buf[NUMBUFLEN];
8441 title = get_tv_string_chk(&argvars[0]);
8442 initdir = get_tv_string_buf_chk(&argvars[1], buf);
8444 if (title == NULL || initdir == NULL)
8445 rettv->vval.v_string = NULL;
8446 else
8447 rettv->vval.v_string = do_browse(BROWSE_DIR,
8448 title, NULL, NULL, initdir, NULL, curbuf);
8449 #else
8450 rettv->vval.v_string = NULL;
8451 #endif
8452 rettv->v_type = VAR_STRING;
8455 static buf_T *find_buffer __ARGS((typval_T *avar));
8458 * Find a buffer by number or exact name.
8460 static buf_T *
8461 find_buffer(avar)
8462 typval_T *avar;
8464 buf_T *buf = NULL;
8466 if (avar->v_type == VAR_NUMBER)
8467 buf = buflist_findnr((int)avar->vval.v_number);
8468 else if (avar->v_type == VAR_STRING && avar->vval.v_string != NULL)
8470 buf = buflist_findname_exp(avar->vval.v_string);
8471 if (buf == NULL)
8473 /* No full path name match, try a match with a URL or a "nofile"
8474 * buffer, these don't use the full path. */
8475 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8476 if (buf->b_fname != NULL
8477 && (path_with_url(buf->b_fname)
8478 #ifdef FEAT_QUICKFIX
8479 || bt_nofile(buf)
8480 #endif
8482 && STRCMP(buf->b_fname, avar->vval.v_string) == 0)
8483 break;
8486 return buf;
8490 * "bufexists(expr)" function
8492 static void
8493 f_bufexists(argvars, rettv)
8494 typval_T *argvars;
8495 typval_T *rettv;
8497 rettv->vval.v_number = (find_buffer(&argvars[0]) != NULL);
8501 * "buflisted(expr)" function
8503 static void
8504 f_buflisted(argvars, rettv)
8505 typval_T *argvars;
8506 typval_T *rettv;
8508 buf_T *buf;
8510 buf = find_buffer(&argvars[0]);
8511 rettv->vval.v_number = (buf != NULL && buf->b_p_bl);
8515 * "bufloaded(expr)" function
8517 static void
8518 f_bufloaded(argvars, rettv)
8519 typval_T *argvars;
8520 typval_T *rettv;
8522 buf_T *buf;
8524 buf = find_buffer(&argvars[0]);
8525 rettv->vval.v_number = (buf != NULL && buf->b_ml.ml_mfp != NULL);
8528 static buf_T *get_buf_tv __ARGS((typval_T *tv));
8531 * Get buffer by number or pattern.
8533 static buf_T *
8534 get_buf_tv(tv)
8535 typval_T *tv;
8537 char_u *name = tv->vval.v_string;
8538 int save_magic;
8539 char_u *save_cpo;
8540 buf_T *buf;
8542 if (tv->v_type == VAR_NUMBER)
8543 return buflist_findnr((int)tv->vval.v_number);
8544 if (tv->v_type != VAR_STRING)
8545 return NULL;
8546 if (name == NULL || *name == NUL)
8547 return curbuf;
8548 if (name[0] == '$' && name[1] == NUL)
8549 return lastbuf;
8551 /* Ignore 'magic' and 'cpoptions' here to make scripts portable */
8552 save_magic = p_magic;
8553 p_magic = TRUE;
8554 save_cpo = p_cpo;
8555 p_cpo = (char_u *)"";
8557 buf = buflist_findnr(buflist_findpat(name, name + STRLEN(name),
8558 TRUE, FALSE));
8560 p_magic = save_magic;
8561 p_cpo = save_cpo;
8563 /* If not found, try expanding the name, like done for bufexists(). */
8564 if (buf == NULL)
8565 buf = find_buffer(tv);
8567 return buf;
8571 * "bufname(expr)" function
8573 static void
8574 f_bufname(argvars, rettv)
8575 typval_T *argvars;
8576 typval_T *rettv;
8578 buf_T *buf;
8580 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8581 ++emsg_off;
8582 buf = get_buf_tv(&argvars[0]);
8583 rettv->v_type = VAR_STRING;
8584 if (buf != NULL && buf->b_fname != NULL)
8585 rettv->vval.v_string = vim_strsave(buf->b_fname);
8586 else
8587 rettv->vval.v_string = NULL;
8588 --emsg_off;
8592 * "bufnr(expr)" function
8594 static void
8595 f_bufnr(argvars, rettv)
8596 typval_T *argvars;
8597 typval_T *rettv;
8599 buf_T *buf;
8600 int error = FALSE;
8601 char_u *name;
8603 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8604 ++emsg_off;
8605 buf = get_buf_tv(&argvars[0]);
8606 --emsg_off;
8608 /* If the buffer isn't found and the second argument is not zero create a
8609 * new buffer. */
8610 if (buf == NULL
8611 && argvars[1].v_type != VAR_UNKNOWN
8612 && get_tv_number_chk(&argvars[1], &error) != 0
8613 && !error
8614 && (name = get_tv_string_chk(&argvars[0])) != NULL
8615 && !error)
8616 buf = buflist_new(name, NULL, (linenr_T)1, 0);
8618 if (buf != NULL)
8619 rettv->vval.v_number = buf->b_fnum;
8620 else
8621 rettv->vval.v_number = -1;
8625 * "bufwinnr(nr)" function
8627 static void
8628 f_bufwinnr(argvars, rettv)
8629 typval_T *argvars;
8630 typval_T *rettv;
8632 #ifdef FEAT_WINDOWS
8633 win_T *wp;
8634 int winnr = 0;
8635 #endif
8636 buf_T *buf;
8638 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8639 ++emsg_off;
8640 buf = get_buf_tv(&argvars[0]);
8641 #ifdef FEAT_WINDOWS
8642 for (wp = firstwin; wp; wp = wp->w_next)
8644 ++winnr;
8645 if (wp->w_buffer == buf)
8646 break;
8648 rettv->vval.v_number = (wp != NULL ? winnr : -1);
8649 #else
8650 rettv->vval.v_number = (curwin->w_buffer == buf ? 1 : -1);
8651 #endif
8652 --emsg_off;
8656 * "byte2line(byte)" function
8658 /*ARGSUSED*/
8659 static void
8660 f_byte2line(argvars, rettv)
8661 typval_T *argvars;
8662 typval_T *rettv;
8664 #ifndef FEAT_BYTEOFF
8665 rettv->vval.v_number = -1;
8666 #else
8667 long boff = 0;
8669 boff = get_tv_number(&argvars[0]) - 1; /* boff gets -1 on type error */
8670 if (boff < 0)
8671 rettv->vval.v_number = -1;
8672 else
8673 rettv->vval.v_number = ml_find_line_or_offset(curbuf,
8674 (linenr_T)0, &boff);
8675 #endif
8679 * "byteidx()" function
8681 /*ARGSUSED*/
8682 static void
8683 f_byteidx(argvars, rettv)
8684 typval_T *argvars;
8685 typval_T *rettv;
8687 #ifdef FEAT_MBYTE
8688 char_u *t;
8689 #endif
8690 char_u *str;
8691 long idx;
8693 str = get_tv_string_chk(&argvars[0]);
8694 idx = get_tv_number_chk(&argvars[1], NULL);
8695 rettv->vval.v_number = -1;
8696 if (str == NULL || idx < 0)
8697 return;
8699 #ifdef FEAT_MBYTE
8700 t = str;
8701 for ( ; idx > 0; idx--)
8703 if (*t == NUL) /* EOL reached */
8704 return;
8705 t += (*mb_ptr2len)(t);
8707 rettv->vval.v_number = (varnumber_T)(t - str);
8708 #else
8709 if ((size_t)idx <= STRLEN(str))
8710 rettv->vval.v_number = idx;
8711 #endif
8715 * "call(func, arglist)" function
8717 static void
8718 f_call(argvars, rettv)
8719 typval_T *argvars;
8720 typval_T *rettv;
8722 char_u *func;
8723 typval_T argv[MAX_FUNC_ARGS + 1];
8724 int argc = 0;
8725 listitem_T *item;
8726 int dummy;
8727 dict_T *selfdict = NULL;
8729 if (argvars[1].v_type != VAR_LIST)
8731 EMSG(_(e_listreq));
8732 return;
8734 if (argvars[1].vval.v_list == NULL)
8735 return;
8737 if (argvars[0].v_type == VAR_FUNC)
8738 func = argvars[0].vval.v_string;
8739 else
8740 func = get_tv_string(&argvars[0]);
8741 if (*func == NUL)
8742 return; /* type error or empty name */
8744 if (argvars[2].v_type != VAR_UNKNOWN)
8746 if (argvars[2].v_type != VAR_DICT)
8748 EMSG(_(e_dictreq));
8749 return;
8751 selfdict = argvars[2].vval.v_dict;
8754 for (item = argvars[1].vval.v_list->lv_first; item != NULL;
8755 item = item->li_next)
8757 if (argc == MAX_FUNC_ARGS)
8759 EMSG(_("E699: Too many arguments"));
8760 break;
8762 /* Make a copy of each argument. This is needed to be able to set
8763 * v_lock to VAR_FIXED in the copy without changing the original list.
8765 copy_tv(&item->li_tv, &argv[argc++]);
8768 if (item == NULL)
8769 (void)call_func(func, (int)STRLEN(func), rettv, argc, argv,
8770 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
8771 &dummy, TRUE, selfdict);
8773 /* Free the arguments. */
8774 while (argc > 0)
8775 clear_tv(&argv[--argc]);
8778 #ifdef FEAT_FLOAT
8780 * "ceil({float})" function
8782 static void
8783 f_ceil(argvars, rettv)
8784 typval_T *argvars;
8785 typval_T *rettv;
8787 float_T f;
8789 rettv->v_type = VAR_FLOAT;
8790 if (get_float_arg(argvars, &f) == OK)
8791 rettv->vval.v_float = ceil(f);
8792 else
8793 rettv->vval.v_float = 0.0;
8795 #endif
8798 * "changenr()" function
8800 static void
8801 f_changenr(argvars, rettv)
8802 typval_T *argvars UNUSED;
8803 typval_T *rettv;
8805 rettv->vval.v_number = curbuf->b_u_seq_cur;
8809 * "char2nr(string)" function
8811 static void
8812 f_char2nr(argvars, rettv)
8813 typval_T *argvars;
8814 typval_T *rettv;
8816 #ifdef FEAT_MBYTE
8817 if (has_mbyte)
8818 rettv->vval.v_number = (*mb_ptr2char)(get_tv_string(&argvars[0]));
8819 else
8820 #endif
8821 rettv->vval.v_number = get_tv_string(&argvars[0])[0];
8825 * "cindent(lnum)" function
8827 static void
8828 f_cindent(argvars, rettv)
8829 typval_T *argvars;
8830 typval_T *rettv;
8832 #ifdef FEAT_CINDENT
8833 pos_T pos;
8834 linenr_T lnum;
8836 pos = curwin->w_cursor;
8837 lnum = get_tv_lnum(argvars);
8838 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
8840 curwin->w_cursor.lnum = lnum;
8841 rettv->vval.v_number = get_c_indent();
8842 curwin->w_cursor = pos;
8844 else
8845 #endif
8846 rettv->vval.v_number = -1;
8850 * "clearmatches()" function
8852 static void
8853 f_clearmatches(argvars, rettv)
8854 typval_T *argvars UNUSED;
8855 typval_T *rettv;
8857 #ifdef FEAT_SEARCH_EXTRA
8858 clear_matches(curwin);
8859 #endif
8863 * "col(string)" function
8865 static void
8866 f_col(argvars, rettv)
8867 typval_T *argvars;
8868 typval_T *rettv;
8870 colnr_T col = 0;
8871 pos_T *fp;
8872 int fnum = curbuf->b_fnum;
8874 fp = var2fpos(&argvars[0], FALSE, &fnum);
8875 if (fp != NULL && fnum == curbuf->b_fnum)
8877 if (fp->col == MAXCOL)
8879 /* '> can be MAXCOL, get the length of the line then */
8880 if (fp->lnum <= curbuf->b_ml.ml_line_count)
8881 col = (colnr_T)STRLEN(ml_get(fp->lnum)) + 1;
8882 else
8883 col = MAXCOL;
8885 else
8887 col = fp->col + 1;
8888 #ifdef FEAT_VIRTUALEDIT
8889 /* col(".") when the cursor is on the NUL at the end of the line
8890 * because of "coladd" can be seen as an extra column. */
8891 if (virtual_active() && fp == &curwin->w_cursor)
8893 char_u *p = ml_get_cursor();
8895 if (curwin->w_cursor.coladd >= (colnr_T)chartabsize(p,
8896 curwin->w_virtcol - curwin->w_cursor.coladd))
8898 # ifdef FEAT_MBYTE
8899 int l;
8901 if (*p != NUL && p[(l = (*mb_ptr2len)(p))] == NUL)
8902 col += l;
8903 # else
8904 if (*p != NUL && p[1] == NUL)
8905 ++col;
8906 # endif
8909 #endif
8912 rettv->vval.v_number = col;
8915 #if defined(FEAT_INS_EXPAND)
8917 * "complete()" function
8919 /*ARGSUSED*/
8920 static void
8921 f_complete(argvars, rettv)
8922 typval_T *argvars;
8923 typval_T *rettv;
8925 int startcol;
8927 if ((State & INSERT) == 0)
8929 EMSG(_("E785: complete() can only be used in Insert mode"));
8930 return;
8933 /* Check for undo allowed here, because if something was already inserted
8934 * the line was already saved for undo and this check isn't done. */
8935 if (!undo_allowed())
8936 return;
8938 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
8940 EMSG(_(e_invarg));
8941 return;
8944 startcol = get_tv_number_chk(&argvars[0], NULL);
8945 if (startcol <= 0)
8946 return;
8948 set_completion(startcol - 1, argvars[1].vval.v_list);
8952 * "complete_add()" function
8954 /*ARGSUSED*/
8955 static void
8956 f_complete_add(argvars, rettv)
8957 typval_T *argvars;
8958 typval_T *rettv;
8960 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0);
8964 * "complete_check()" function
8966 /*ARGSUSED*/
8967 static void
8968 f_complete_check(argvars, rettv)
8969 typval_T *argvars;
8970 typval_T *rettv;
8972 int saved = RedrawingDisabled;
8974 RedrawingDisabled = 0;
8975 ins_compl_check_keys(0);
8976 rettv->vval.v_number = compl_interrupted;
8977 RedrawingDisabled = saved;
8979 #endif
8982 * "confirm(message, buttons[, default [, type]])" function
8984 /*ARGSUSED*/
8985 static void
8986 f_confirm(argvars, rettv)
8987 typval_T *argvars;
8988 typval_T *rettv;
8990 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
8991 char_u *message;
8992 char_u *buttons = NULL;
8993 char_u buf[NUMBUFLEN];
8994 char_u buf2[NUMBUFLEN];
8995 int def = 1;
8996 int type = VIM_GENERIC;
8997 char_u *typestr;
8998 int error = FALSE;
9000 message = get_tv_string_chk(&argvars[0]);
9001 if (message == NULL)
9002 error = TRUE;
9003 if (argvars[1].v_type != VAR_UNKNOWN)
9005 buttons = get_tv_string_buf_chk(&argvars[1], buf);
9006 if (buttons == NULL)
9007 error = TRUE;
9008 if (argvars[2].v_type != VAR_UNKNOWN)
9010 def = get_tv_number_chk(&argvars[2], &error);
9011 if (argvars[3].v_type != VAR_UNKNOWN)
9013 typestr = get_tv_string_buf_chk(&argvars[3], buf2);
9014 if (typestr == NULL)
9015 error = TRUE;
9016 else
9018 switch (TOUPPER_ASC(*typestr))
9020 case 'E': type = VIM_ERROR; break;
9021 case 'Q': type = VIM_QUESTION; break;
9022 case 'I': type = VIM_INFO; break;
9023 case 'W': type = VIM_WARNING; break;
9024 case 'G': type = VIM_GENERIC; break;
9031 if (buttons == NULL || *buttons == NUL)
9032 buttons = (char_u *)_("&Ok");
9034 if (!error)
9035 rettv->vval.v_number = do_dialog(type, NULL, message, buttons,
9036 def, NULL);
9037 #endif
9041 * "copy()" function
9043 static void
9044 f_copy(argvars, rettv)
9045 typval_T *argvars;
9046 typval_T *rettv;
9048 item_copy(&argvars[0], rettv, FALSE, 0);
9051 #ifdef FEAT_FLOAT
9053 * "cos()" function
9055 static void
9056 f_cos(argvars, rettv)
9057 typval_T *argvars;
9058 typval_T *rettv;
9060 float_T f;
9062 rettv->v_type = VAR_FLOAT;
9063 if (get_float_arg(argvars, &f) == OK)
9064 rettv->vval.v_float = cos(f);
9065 else
9066 rettv->vval.v_float = 0.0;
9068 #endif
9071 * "count()" function
9073 static void
9074 f_count(argvars, rettv)
9075 typval_T *argvars;
9076 typval_T *rettv;
9078 long n = 0;
9079 int ic = FALSE;
9081 if (argvars[0].v_type == VAR_LIST)
9083 listitem_T *li;
9084 list_T *l;
9085 long idx;
9087 if ((l = argvars[0].vval.v_list) != NULL)
9089 li = l->lv_first;
9090 if (argvars[2].v_type != VAR_UNKNOWN)
9092 int error = FALSE;
9094 ic = get_tv_number_chk(&argvars[2], &error);
9095 if (argvars[3].v_type != VAR_UNKNOWN)
9097 idx = get_tv_number_chk(&argvars[3], &error);
9098 if (!error)
9100 li = list_find(l, idx);
9101 if (li == NULL)
9102 EMSGN(_(e_listidx), idx);
9105 if (error)
9106 li = NULL;
9109 for ( ; li != NULL; li = li->li_next)
9110 if (tv_equal(&li->li_tv, &argvars[1], ic))
9111 ++n;
9114 else if (argvars[0].v_type == VAR_DICT)
9116 int todo;
9117 dict_T *d;
9118 hashitem_T *hi;
9120 if ((d = argvars[0].vval.v_dict) != NULL)
9122 int error = FALSE;
9124 if (argvars[2].v_type != VAR_UNKNOWN)
9126 ic = get_tv_number_chk(&argvars[2], &error);
9127 if (argvars[3].v_type != VAR_UNKNOWN)
9128 EMSG(_(e_invarg));
9131 todo = error ? 0 : (int)d->dv_hashtab.ht_used;
9132 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
9134 if (!HASHITEM_EMPTY(hi))
9136 --todo;
9137 if (tv_equal(&HI2DI(hi)->di_tv, &argvars[1], ic))
9138 ++n;
9143 else
9144 EMSG2(_(e_listdictarg), "count()");
9145 rettv->vval.v_number = n;
9149 * "cscope_connection([{num} , {dbpath} [, {prepend}]])" function
9151 * Checks the existence of a cscope connection.
9153 /*ARGSUSED*/
9154 static void
9155 f_cscope_connection(argvars, rettv)
9156 typval_T *argvars;
9157 typval_T *rettv;
9159 #ifdef FEAT_CSCOPE
9160 int num = 0;
9161 char_u *dbpath = NULL;
9162 char_u *prepend = NULL;
9163 char_u buf[NUMBUFLEN];
9165 if (argvars[0].v_type != VAR_UNKNOWN
9166 && argvars[1].v_type != VAR_UNKNOWN)
9168 num = (int)get_tv_number(&argvars[0]);
9169 dbpath = get_tv_string(&argvars[1]);
9170 if (argvars[2].v_type != VAR_UNKNOWN)
9171 prepend = get_tv_string_buf(&argvars[2], buf);
9174 rettv->vval.v_number = cs_connection(num, dbpath, prepend);
9175 #endif
9179 * "cursor(lnum, col)" function
9181 * Moves the cursor to the specified line and column.
9182 * Returns 0 when the position could be set, -1 otherwise.
9184 /*ARGSUSED*/
9185 static void
9186 f_cursor(argvars, rettv)
9187 typval_T *argvars;
9188 typval_T *rettv;
9190 long line, col;
9191 #ifdef FEAT_VIRTUALEDIT
9192 long coladd = 0;
9193 #endif
9195 rettv->vval.v_number = -1;
9196 if (argvars[1].v_type == VAR_UNKNOWN)
9198 pos_T pos;
9200 if (list2fpos(argvars, &pos, NULL) == FAIL)
9201 return;
9202 line = pos.lnum;
9203 col = pos.col;
9204 #ifdef FEAT_VIRTUALEDIT
9205 coladd = pos.coladd;
9206 #endif
9208 else
9210 line = get_tv_lnum(argvars);
9211 col = get_tv_number_chk(&argvars[1], NULL);
9212 #ifdef FEAT_VIRTUALEDIT
9213 if (argvars[2].v_type != VAR_UNKNOWN)
9214 coladd = get_tv_number_chk(&argvars[2], NULL);
9215 #endif
9217 if (line < 0 || col < 0
9218 #ifdef FEAT_VIRTUALEDIT
9219 || coladd < 0
9220 #endif
9222 return; /* type error; errmsg already given */
9223 if (line > 0)
9224 curwin->w_cursor.lnum = line;
9225 if (col > 0)
9226 curwin->w_cursor.col = col - 1;
9227 #ifdef FEAT_VIRTUALEDIT
9228 curwin->w_cursor.coladd = coladd;
9229 #endif
9231 /* Make sure the cursor is in a valid position. */
9232 check_cursor();
9233 #ifdef FEAT_MBYTE
9234 /* Correct cursor for multi-byte character. */
9235 if (has_mbyte)
9236 mb_adjust_cursor();
9237 #endif
9239 curwin->w_set_curswant = TRUE;
9240 rettv->vval.v_number = 0;
9244 * "deepcopy()" function
9246 static void
9247 f_deepcopy(argvars, rettv)
9248 typval_T *argvars;
9249 typval_T *rettv;
9251 int noref = 0;
9253 if (argvars[1].v_type != VAR_UNKNOWN)
9254 noref = get_tv_number_chk(&argvars[1], NULL);
9255 if (noref < 0 || noref > 1)
9256 EMSG(_(e_invarg));
9257 else
9258 item_copy(&argvars[0], rettv, TRUE, noref == 0 ? ++current_copyID : 0);
9262 * "delete()" function
9264 static void
9265 f_delete(argvars, rettv)
9266 typval_T *argvars;
9267 typval_T *rettv;
9269 if (check_restricted() || check_secure())
9270 rettv->vval.v_number = -1;
9271 else
9272 rettv->vval.v_number = mch_remove(get_tv_string(&argvars[0]));
9276 * "did_filetype()" function
9278 /*ARGSUSED*/
9279 static void
9280 f_did_filetype(argvars, rettv)
9281 typval_T *argvars;
9282 typval_T *rettv;
9284 #ifdef FEAT_AUTOCMD
9285 rettv->vval.v_number = did_filetype;
9286 #endif
9290 * "diff_filler()" function
9292 /*ARGSUSED*/
9293 static void
9294 f_diff_filler(argvars, rettv)
9295 typval_T *argvars;
9296 typval_T *rettv;
9298 #ifdef FEAT_DIFF
9299 rettv->vval.v_number = diff_check_fill(curwin, get_tv_lnum(argvars));
9300 #endif
9304 * "diff_hlID()" function
9306 /*ARGSUSED*/
9307 static void
9308 f_diff_hlID(argvars, rettv)
9309 typval_T *argvars;
9310 typval_T *rettv;
9312 #ifdef FEAT_DIFF
9313 linenr_T lnum = get_tv_lnum(argvars);
9314 static linenr_T prev_lnum = 0;
9315 static int changedtick = 0;
9316 static int fnum = 0;
9317 static int change_start = 0;
9318 static int change_end = 0;
9319 static hlf_T hlID = (hlf_T)0;
9320 int filler_lines;
9321 int col;
9323 if (lnum < 0) /* ignore type error in {lnum} arg */
9324 lnum = 0;
9325 if (lnum != prev_lnum
9326 || changedtick != curbuf->b_changedtick
9327 || fnum != curbuf->b_fnum)
9329 /* New line, buffer, change: need to get the values. */
9330 filler_lines = diff_check(curwin, lnum);
9331 if (filler_lines < 0)
9333 if (filler_lines == -1)
9335 change_start = MAXCOL;
9336 change_end = -1;
9337 if (diff_find_change(curwin, lnum, &change_start, &change_end))
9338 hlID = HLF_ADD; /* added line */
9339 else
9340 hlID = HLF_CHD; /* changed line */
9342 else
9343 hlID = HLF_ADD; /* added line */
9345 else
9346 hlID = (hlf_T)0;
9347 prev_lnum = lnum;
9348 changedtick = curbuf->b_changedtick;
9349 fnum = curbuf->b_fnum;
9352 if (hlID == HLF_CHD || hlID == HLF_TXD)
9354 col = get_tv_number(&argvars[1]) - 1; /* ignore type error in {col} */
9355 if (col >= change_start && col <= change_end)
9356 hlID = HLF_TXD; /* changed text */
9357 else
9358 hlID = HLF_CHD; /* changed line */
9360 rettv->vval.v_number = hlID == (hlf_T)0 ? 0 : (int)hlID;
9361 #endif
9365 * "empty({expr})" function
9367 static void
9368 f_empty(argvars, rettv)
9369 typval_T *argvars;
9370 typval_T *rettv;
9372 int n;
9374 switch (argvars[0].v_type)
9376 case VAR_STRING:
9377 case VAR_FUNC:
9378 n = argvars[0].vval.v_string == NULL
9379 || *argvars[0].vval.v_string == NUL;
9380 break;
9381 case VAR_NUMBER:
9382 n = argvars[0].vval.v_number == 0;
9383 break;
9384 #ifdef FEAT_FLOAT
9385 case VAR_FLOAT:
9386 n = argvars[0].vval.v_float == 0.0;
9387 break;
9388 #endif
9389 case VAR_LIST:
9390 n = argvars[0].vval.v_list == NULL
9391 || argvars[0].vval.v_list->lv_first == NULL;
9392 break;
9393 case VAR_DICT:
9394 n = argvars[0].vval.v_dict == NULL
9395 || argvars[0].vval.v_dict->dv_hashtab.ht_used == 0;
9396 break;
9397 default:
9398 EMSG2(_(e_intern2), "f_empty()");
9399 n = 0;
9402 rettv->vval.v_number = n;
9406 * "escape({string}, {chars})" function
9408 static void
9409 f_escape(argvars, rettv)
9410 typval_T *argvars;
9411 typval_T *rettv;
9413 char_u buf[NUMBUFLEN];
9415 rettv->vval.v_string = vim_strsave_escaped(get_tv_string(&argvars[0]),
9416 get_tv_string_buf(&argvars[1], buf));
9417 rettv->v_type = VAR_STRING;
9421 * "eval()" function
9423 /*ARGSUSED*/
9424 static void
9425 f_eval(argvars, rettv)
9426 typval_T *argvars;
9427 typval_T *rettv;
9429 char_u *s;
9431 s = get_tv_string_chk(&argvars[0]);
9432 if (s != NULL)
9433 s = skipwhite(s);
9435 if (s == NULL || eval1(&s, rettv, TRUE) == FAIL)
9437 rettv->v_type = VAR_NUMBER;
9438 rettv->vval.v_number = 0;
9440 else if (*s != NUL)
9441 EMSG(_(e_trailing));
9445 * "eventhandler()" function
9447 /*ARGSUSED*/
9448 static void
9449 f_eventhandler(argvars, rettv)
9450 typval_T *argvars;
9451 typval_T *rettv;
9453 rettv->vval.v_number = vgetc_busy;
9457 * "executable()" function
9459 static void
9460 f_executable(argvars, rettv)
9461 typval_T *argvars;
9462 typval_T *rettv;
9464 rettv->vval.v_number = mch_can_exe(get_tv_string(&argvars[0]));
9468 * "exists()" function
9470 static void
9471 f_exists(argvars, rettv)
9472 typval_T *argvars;
9473 typval_T *rettv;
9475 char_u *p;
9476 char_u *name;
9477 int n = FALSE;
9478 int len = 0;
9480 p = get_tv_string(&argvars[0]);
9481 if (*p == '$') /* environment variable */
9483 /* first try "normal" environment variables (fast) */
9484 if (mch_getenv(p + 1) != NULL)
9485 n = TRUE;
9486 else
9488 /* try expanding things like $VIM and ${HOME} */
9489 p = expand_env_save(p);
9490 if (p != NULL && *p != '$')
9491 n = TRUE;
9492 vim_free(p);
9495 else if (*p == '&' || *p == '+') /* option */
9497 n = (get_option_tv(&p, NULL, TRUE) == OK);
9498 if (*skipwhite(p) != NUL)
9499 n = FALSE; /* trailing garbage */
9501 else if (*p == '*') /* internal or user defined function */
9503 n = function_exists(p + 1);
9505 else if (*p == ':')
9507 n = cmd_exists(p + 1);
9509 else if (*p == '#')
9511 #ifdef FEAT_AUTOCMD
9512 if (p[1] == '#')
9513 n = autocmd_supported(p + 2);
9514 else
9515 n = au_exists(p + 1);
9516 #endif
9518 else /* internal variable */
9520 char_u *tofree;
9521 typval_T tv;
9523 /* get_name_len() takes care of expanding curly braces */
9524 name = p;
9525 len = get_name_len(&p, &tofree, TRUE, FALSE);
9526 if (len > 0)
9528 if (tofree != NULL)
9529 name = tofree;
9530 n = (get_var_tv(name, len, &tv, FALSE) == OK);
9531 if (n)
9533 /* handle d.key, l[idx], f(expr) */
9534 n = (handle_subscript(&p, &tv, TRUE, FALSE) == OK);
9535 if (n)
9536 clear_tv(&tv);
9539 if (*p != NUL)
9540 n = FALSE;
9542 vim_free(tofree);
9545 rettv->vval.v_number = n;
9549 * "expand()" function
9551 static void
9552 f_expand(argvars, rettv)
9553 typval_T *argvars;
9554 typval_T *rettv;
9556 char_u *s;
9557 int len;
9558 char_u *errormsg;
9559 int flags = WILD_SILENT|WILD_USE_NL|WILD_LIST_NOTFOUND;
9560 expand_T xpc;
9561 int error = FALSE;
9563 rettv->v_type = VAR_STRING;
9564 s = get_tv_string(&argvars[0]);
9565 if (*s == '%' || *s == '#' || *s == '<')
9567 ++emsg_off;
9568 rettv->vval.v_string = eval_vars(s, s, &len, NULL, &errormsg, NULL);
9569 --emsg_off;
9571 else
9573 /* When the optional second argument is non-zero, don't remove matches
9574 * for 'wildignore' and don't put matches for 'suffixes' at the end. */
9575 if (argvars[1].v_type != VAR_UNKNOWN
9576 && get_tv_number_chk(&argvars[1], &error))
9577 flags |= WILD_KEEP_ALL;
9578 if (!error)
9580 ExpandInit(&xpc);
9581 xpc.xp_context = EXPAND_FILES;
9582 rettv->vval.v_string = ExpandOne(&xpc, s, NULL, flags, WILD_ALL);
9584 else
9585 rettv->vval.v_string = NULL;
9590 * "extend(list, list [, idx])" function
9591 * "extend(dict, dict [, action])" function
9593 static void
9594 f_extend(argvars, rettv)
9595 typval_T *argvars;
9596 typval_T *rettv;
9598 if (argvars[0].v_type == VAR_LIST && argvars[1].v_type == VAR_LIST)
9600 list_T *l1, *l2;
9601 listitem_T *item;
9602 long before;
9603 int error = FALSE;
9605 l1 = argvars[0].vval.v_list;
9606 l2 = argvars[1].vval.v_list;
9607 if (l1 != NULL && !tv_check_lock(l1->lv_lock, (char_u *)"extend()")
9608 && l2 != NULL)
9610 if (argvars[2].v_type != VAR_UNKNOWN)
9612 before = get_tv_number_chk(&argvars[2], &error);
9613 if (error)
9614 return; /* type error; errmsg already given */
9616 if (before == l1->lv_len)
9617 item = NULL;
9618 else
9620 item = list_find(l1, before);
9621 if (item == NULL)
9623 EMSGN(_(e_listidx), before);
9624 return;
9628 else
9629 item = NULL;
9630 list_extend(l1, l2, item);
9632 copy_tv(&argvars[0], rettv);
9635 else if (argvars[0].v_type == VAR_DICT && argvars[1].v_type == VAR_DICT)
9637 dict_T *d1, *d2;
9638 dictitem_T *di1;
9639 char_u *action;
9640 int i;
9641 hashitem_T *hi2;
9642 int todo;
9644 d1 = argvars[0].vval.v_dict;
9645 d2 = argvars[1].vval.v_dict;
9646 if (d1 != NULL && !tv_check_lock(d1->dv_lock, (char_u *)"extend()")
9647 && d2 != NULL)
9649 /* Check the third argument. */
9650 if (argvars[2].v_type != VAR_UNKNOWN)
9652 static char *(av[]) = {"keep", "force", "error"};
9654 action = get_tv_string_chk(&argvars[2]);
9655 if (action == NULL)
9656 return; /* type error; errmsg already given */
9657 for (i = 0; i < 3; ++i)
9658 if (STRCMP(action, av[i]) == 0)
9659 break;
9660 if (i == 3)
9662 EMSG2(_(e_invarg2), action);
9663 return;
9666 else
9667 action = (char_u *)"force";
9669 /* Go over all entries in the second dict and add them to the
9670 * first dict. */
9671 todo = (int)d2->dv_hashtab.ht_used;
9672 for (hi2 = d2->dv_hashtab.ht_array; todo > 0; ++hi2)
9674 if (!HASHITEM_EMPTY(hi2))
9676 --todo;
9677 di1 = dict_find(d1, hi2->hi_key, -1);
9678 if (di1 == NULL)
9680 di1 = dictitem_copy(HI2DI(hi2));
9681 if (di1 != NULL && dict_add(d1, di1) == FAIL)
9682 dictitem_free(di1);
9684 else if (*action == 'e')
9686 EMSG2(_("E737: Key already exists: %s"), hi2->hi_key);
9687 break;
9689 else if (*action == 'f')
9691 clear_tv(&di1->di_tv);
9692 copy_tv(&HI2DI(hi2)->di_tv, &di1->di_tv);
9697 copy_tv(&argvars[0], rettv);
9700 else
9701 EMSG2(_(e_listdictarg), "extend()");
9705 * "feedkeys()" function
9707 /*ARGSUSED*/
9708 static void
9709 f_feedkeys(argvars, rettv)
9710 typval_T *argvars;
9711 typval_T *rettv;
9713 int remap = TRUE;
9714 char_u *keys, *flags;
9715 char_u nbuf[NUMBUFLEN];
9716 int typed = FALSE;
9717 char_u *keys_esc;
9719 /* This is not allowed in the sandbox. If the commands would still be
9720 * executed in the sandbox it would be OK, but it probably happens later,
9721 * when "sandbox" is no longer set. */
9722 if (check_secure())
9723 return;
9725 keys = get_tv_string(&argvars[0]);
9726 if (*keys != NUL)
9728 if (argvars[1].v_type != VAR_UNKNOWN)
9730 flags = get_tv_string_buf(&argvars[1], nbuf);
9731 for ( ; *flags != NUL; ++flags)
9733 switch (*flags)
9735 case 'n': remap = FALSE; break;
9736 case 'm': remap = TRUE; break;
9737 case 't': typed = TRUE; break;
9742 /* Need to escape K_SPECIAL and CSI before putting the string in the
9743 * typeahead buffer. */
9744 keys_esc = vim_strsave_escape_csi(keys);
9745 if (keys_esc != NULL)
9747 ins_typebuf(keys_esc, (remap ? REMAP_YES : REMAP_NONE),
9748 typebuf.tb_len, !typed, FALSE);
9749 vim_free(keys_esc);
9750 if (vgetc_busy)
9751 typebuf_was_filled = TRUE;
9757 * "filereadable()" function
9759 static void
9760 f_filereadable(argvars, rettv)
9761 typval_T *argvars;
9762 typval_T *rettv;
9764 int fd;
9765 char_u *p;
9766 int n;
9768 #ifndef O_NONBLOCK
9769 # define O_NONBLOCK 0
9770 #endif
9771 p = get_tv_string(&argvars[0]);
9772 if (*p && !mch_isdir(p) && (fd = mch_open((char *)p,
9773 O_RDONLY | O_NONBLOCK, 0)) >= 0)
9775 n = TRUE;
9776 close(fd);
9778 else
9779 n = FALSE;
9781 rettv->vval.v_number = n;
9785 * Return 0 for not writable, 1 for writable file, 2 for a dir which we have
9786 * rights to write into.
9788 static void
9789 f_filewritable(argvars, rettv)
9790 typval_T *argvars;
9791 typval_T *rettv;
9793 rettv->vval.v_number = filewritable(get_tv_string(&argvars[0]));
9796 static void findfilendir __ARGS((typval_T *argvars, typval_T *rettv, int find_what));
9798 static void
9799 findfilendir(argvars, rettv, find_what)
9800 typval_T *argvars;
9801 typval_T *rettv;
9802 int find_what;
9804 #ifdef FEAT_SEARCHPATH
9805 char_u *fname;
9806 char_u *fresult = NULL;
9807 char_u *path = *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path;
9808 char_u *p;
9809 char_u pathbuf[NUMBUFLEN];
9810 int count = 1;
9811 int first = TRUE;
9812 int error = FALSE;
9813 #endif
9815 rettv->vval.v_string = NULL;
9816 rettv->v_type = VAR_STRING;
9818 #ifdef FEAT_SEARCHPATH
9819 fname = get_tv_string(&argvars[0]);
9821 if (argvars[1].v_type != VAR_UNKNOWN)
9823 p = get_tv_string_buf_chk(&argvars[1], pathbuf);
9824 if (p == NULL)
9825 error = TRUE;
9826 else
9828 if (*p != NUL)
9829 path = p;
9831 if (argvars[2].v_type != VAR_UNKNOWN)
9832 count = get_tv_number_chk(&argvars[2], &error);
9836 if (count < 0 && rettv_list_alloc(rettv) == FAIL)
9837 error = TRUE;
9839 if (*fname != NUL && !error)
9843 if (rettv->v_type == VAR_STRING)
9844 vim_free(fresult);
9845 fresult = find_file_in_path_option(first ? fname : NULL,
9846 first ? (int)STRLEN(fname) : 0,
9847 0, first, path,
9848 find_what,
9849 curbuf->b_ffname,
9850 find_what == FINDFILE_DIR
9851 ? (char_u *)"" : curbuf->b_p_sua);
9852 first = FALSE;
9854 if (fresult != NULL && rettv->v_type == VAR_LIST)
9855 list_append_string(rettv->vval.v_list, fresult, -1);
9857 } while ((rettv->v_type == VAR_LIST || --count > 0) && fresult != NULL);
9860 if (rettv->v_type == VAR_STRING)
9861 rettv->vval.v_string = fresult;
9862 #endif
9865 static void filter_map __ARGS((typval_T *argvars, typval_T *rettv, int map));
9866 static int filter_map_one __ARGS((typval_T *tv, char_u *expr, int map, int *remp));
9869 * Implementation of map() and filter().
9871 static void
9872 filter_map(argvars, rettv, map)
9873 typval_T *argvars;
9874 typval_T *rettv;
9875 int map;
9877 char_u buf[NUMBUFLEN];
9878 char_u *expr;
9879 listitem_T *li, *nli;
9880 list_T *l = NULL;
9881 dictitem_T *di;
9882 hashtab_T *ht;
9883 hashitem_T *hi;
9884 dict_T *d = NULL;
9885 typval_T save_val;
9886 typval_T save_key;
9887 int rem;
9888 int todo;
9889 char_u *ermsg = map ? (char_u *)"map()" : (char_u *)"filter()";
9890 int save_did_emsg;
9892 if (argvars[0].v_type == VAR_LIST)
9894 if ((l = argvars[0].vval.v_list) == NULL
9895 || (map && tv_check_lock(l->lv_lock, ermsg)))
9896 return;
9898 else if (argvars[0].v_type == VAR_DICT)
9900 if ((d = argvars[0].vval.v_dict) == NULL
9901 || (map && tv_check_lock(d->dv_lock, ermsg)))
9902 return;
9904 else
9906 EMSG2(_(e_listdictarg), ermsg);
9907 return;
9910 expr = get_tv_string_buf_chk(&argvars[1], buf);
9911 /* On type errors, the preceding call has already displayed an error
9912 * message. Avoid a misleading error message for an empty string that
9913 * was not passed as argument. */
9914 if (expr != NULL)
9916 prepare_vimvar(VV_VAL, &save_val);
9917 expr = skipwhite(expr);
9919 /* We reset "did_emsg" to be able to detect whether an error
9920 * occurred during evaluation of the expression. */
9921 save_did_emsg = did_emsg;
9922 did_emsg = FALSE;
9924 if (argvars[0].v_type == VAR_DICT)
9926 prepare_vimvar(VV_KEY, &save_key);
9927 vimvars[VV_KEY].vv_type = VAR_STRING;
9929 ht = &d->dv_hashtab;
9930 hash_lock(ht);
9931 todo = (int)ht->ht_used;
9932 for (hi = ht->ht_array; todo > 0; ++hi)
9934 if (!HASHITEM_EMPTY(hi))
9936 --todo;
9937 di = HI2DI(hi);
9938 if (tv_check_lock(di->di_tv.v_lock, ermsg))
9939 break;
9940 vimvars[VV_KEY].vv_str = vim_strsave(di->di_key);
9941 if (filter_map_one(&di->di_tv, expr, map, &rem) == FAIL
9942 || did_emsg)
9943 break;
9944 if (!map && rem)
9945 dictitem_remove(d, di);
9946 clear_tv(&vimvars[VV_KEY].vv_tv);
9949 hash_unlock(ht);
9951 restore_vimvar(VV_KEY, &save_key);
9953 else
9955 for (li = l->lv_first; li != NULL; li = nli)
9957 if (tv_check_lock(li->li_tv.v_lock, ermsg))
9958 break;
9959 nli = li->li_next;
9960 if (filter_map_one(&li->li_tv, expr, map, &rem) == FAIL
9961 || did_emsg)
9962 break;
9963 if (!map && rem)
9964 listitem_remove(l, li);
9968 restore_vimvar(VV_VAL, &save_val);
9970 did_emsg |= save_did_emsg;
9973 copy_tv(&argvars[0], rettv);
9976 static int
9977 filter_map_one(tv, expr, map, remp)
9978 typval_T *tv;
9979 char_u *expr;
9980 int map;
9981 int *remp;
9983 typval_T rettv;
9984 char_u *s;
9985 int retval = FAIL;
9987 copy_tv(tv, &vimvars[VV_VAL].vv_tv);
9988 s = expr;
9989 if (eval1(&s, &rettv, TRUE) == FAIL)
9990 goto theend;
9991 if (*s != NUL) /* check for trailing chars after expr */
9993 EMSG2(_(e_invexpr2), s);
9994 goto theend;
9996 if (map)
9998 /* map(): replace the list item value */
9999 clear_tv(tv);
10000 rettv.v_lock = 0;
10001 *tv = rettv;
10003 else
10005 int error = FALSE;
10007 /* filter(): when expr is zero remove the item */
10008 *remp = (get_tv_number_chk(&rettv, &error) == 0);
10009 clear_tv(&rettv);
10010 /* On type error, nothing has been removed; return FAIL to stop the
10011 * loop. The error message was given by get_tv_number_chk(). */
10012 if (error)
10013 goto theend;
10015 retval = OK;
10016 theend:
10017 clear_tv(&vimvars[VV_VAL].vv_tv);
10018 return retval;
10022 * "filter()" function
10024 static void
10025 f_filter(argvars, rettv)
10026 typval_T *argvars;
10027 typval_T *rettv;
10029 filter_map(argvars, rettv, FALSE);
10033 * "finddir({fname}[, {path}[, {count}]])" function
10035 static void
10036 f_finddir(argvars, rettv)
10037 typval_T *argvars;
10038 typval_T *rettv;
10040 findfilendir(argvars, rettv, FINDFILE_DIR);
10044 * "findfile({fname}[, {path}[, {count}]])" function
10046 static void
10047 f_findfile(argvars, rettv)
10048 typval_T *argvars;
10049 typval_T *rettv;
10051 findfilendir(argvars, rettv, FINDFILE_FILE);
10054 #ifdef FEAT_FLOAT
10056 * "float2nr({float})" function
10058 static void
10059 f_float2nr(argvars, rettv)
10060 typval_T *argvars;
10061 typval_T *rettv;
10063 float_T f;
10065 if (get_float_arg(argvars, &f) == OK)
10067 if (f < -0x7fffffff)
10068 rettv->vval.v_number = -0x7fffffff;
10069 else if (f > 0x7fffffff)
10070 rettv->vval.v_number = 0x7fffffff;
10071 else
10072 rettv->vval.v_number = (varnumber_T)f;
10077 * "floor({float})" function
10079 static void
10080 f_floor(argvars, rettv)
10081 typval_T *argvars;
10082 typval_T *rettv;
10084 float_T f;
10086 rettv->v_type = VAR_FLOAT;
10087 if (get_float_arg(argvars, &f) == OK)
10088 rettv->vval.v_float = floor(f);
10089 else
10090 rettv->vval.v_float = 0.0;
10092 #endif
10095 * "fnameescape({string})" function
10097 static void
10098 f_fnameescape(argvars, rettv)
10099 typval_T *argvars;
10100 typval_T *rettv;
10102 rettv->vval.v_string = vim_strsave_fnameescape(
10103 get_tv_string(&argvars[0]), FALSE);
10104 rettv->v_type = VAR_STRING;
10108 * "fnamemodify({fname}, {mods})" function
10110 static void
10111 f_fnamemodify(argvars, rettv)
10112 typval_T *argvars;
10113 typval_T *rettv;
10115 char_u *fname;
10116 char_u *mods;
10117 int usedlen = 0;
10118 int len;
10119 char_u *fbuf = NULL;
10120 char_u buf[NUMBUFLEN];
10122 fname = get_tv_string_chk(&argvars[0]);
10123 mods = get_tv_string_buf_chk(&argvars[1], buf);
10124 if (fname == NULL || mods == NULL)
10125 fname = NULL;
10126 else
10128 len = (int)STRLEN(fname);
10129 (void)modify_fname(mods, &usedlen, &fname, &fbuf, &len);
10132 rettv->v_type = VAR_STRING;
10133 if (fname == NULL)
10134 rettv->vval.v_string = NULL;
10135 else
10136 rettv->vval.v_string = vim_strnsave(fname, len);
10137 vim_free(fbuf);
10140 static void foldclosed_both __ARGS((typval_T *argvars, typval_T *rettv, int end));
10143 * "foldclosed()" function
10145 static void
10146 foldclosed_both(argvars, rettv, end)
10147 typval_T *argvars;
10148 typval_T *rettv;
10149 int end;
10151 #ifdef FEAT_FOLDING
10152 linenr_T lnum;
10153 linenr_T first, last;
10155 lnum = get_tv_lnum(argvars);
10156 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
10158 if (hasFoldingWin(curwin, lnum, &first, &last, FALSE, NULL))
10160 if (end)
10161 rettv->vval.v_number = (varnumber_T)last;
10162 else
10163 rettv->vval.v_number = (varnumber_T)first;
10164 return;
10167 #endif
10168 rettv->vval.v_number = -1;
10172 * "foldclosed()" function
10174 static void
10175 f_foldclosed(argvars, rettv)
10176 typval_T *argvars;
10177 typval_T *rettv;
10179 foldclosed_both(argvars, rettv, FALSE);
10183 * "foldclosedend()" function
10185 static void
10186 f_foldclosedend(argvars, rettv)
10187 typval_T *argvars;
10188 typval_T *rettv;
10190 foldclosed_both(argvars, rettv, TRUE);
10194 * "foldlevel()" function
10196 static void
10197 f_foldlevel(argvars, rettv)
10198 typval_T *argvars;
10199 typval_T *rettv;
10201 #ifdef FEAT_FOLDING
10202 linenr_T lnum;
10204 lnum = get_tv_lnum(argvars);
10205 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
10206 rettv->vval.v_number = foldLevel(lnum);
10207 #endif
10211 * "foldtext()" function
10213 /*ARGSUSED*/
10214 static void
10215 f_foldtext(argvars, rettv)
10216 typval_T *argvars;
10217 typval_T *rettv;
10219 #ifdef FEAT_FOLDING
10220 linenr_T lnum;
10221 char_u *s;
10222 char_u *r;
10223 int len;
10224 char *txt;
10225 #endif
10227 rettv->v_type = VAR_STRING;
10228 rettv->vval.v_string = NULL;
10229 #ifdef FEAT_FOLDING
10230 if ((linenr_T)vimvars[VV_FOLDSTART].vv_nr > 0
10231 && (linenr_T)vimvars[VV_FOLDEND].vv_nr
10232 <= curbuf->b_ml.ml_line_count
10233 && vimvars[VV_FOLDDASHES].vv_str != NULL)
10235 /* Find first non-empty line in the fold. */
10236 lnum = (linenr_T)vimvars[VV_FOLDSTART].vv_nr;
10237 while (lnum < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
10239 if (!linewhite(lnum))
10240 break;
10241 ++lnum;
10244 /* Find interesting text in this line. */
10245 s = skipwhite(ml_get(lnum));
10246 /* skip C comment-start */
10247 if (s[0] == '/' && (s[1] == '*' || s[1] == '/'))
10249 s = skipwhite(s + 2);
10250 if (*skipwhite(s) == NUL
10251 && lnum + 1 < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
10253 s = skipwhite(ml_get(lnum + 1));
10254 if (*s == '*')
10255 s = skipwhite(s + 1);
10258 txt = _("+-%s%3ld lines: ");
10259 r = alloc((unsigned)(STRLEN(txt)
10260 + STRLEN(vimvars[VV_FOLDDASHES].vv_str) /* for %s */
10261 + 20 /* for %3ld */
10262 + STRLEN(s))); /* concatenated */
10263 if (r != NULL)
10265 sprintf((char *)r, txt, vimvars[VV_FOLDDASHES].vv_str,
10266 (long)((linenr_T)vimvars[VV_FOLDEND].vv_nr
10267 - (linenr_T)vimvars[VV_FOLDSTART].vv_nr + 1));
10268 len = (int)STRLEN(r);
10269 STRCAT(r, s);
10270 /* remove 'foldmarker' and 'commentstring' */
10271 foldtext_cleanup(r + len);
10272 rettv->vval.v_string = r;
10275 #endif
10279 * "foldtextresult(lnum)" function
10281 /*ARGSUSED*/
10282 static void
10283 f_foldtextresult(argvars, rettv)
10284 typval_T *argvars;
10285 typval_T *rettv;
10287 #ifdef FEAT_FOLDING
10288 linenr_T lnum;
10289 char_u *text;
10290 char_u buf[51];
10291 foldinfo_T foldinfo;
10292 int fold_count;
10293 #endif
10295 rettv->v_type = VAR_STRING;
10296 rettv->vval.v_string = NULL;
10297 #ifdef FEAT_FOLDING
10298 lnum = get_tv_lnum(argvars);
10299 /* treat illegal types and illegal string values for {lnum} the same */
10300 if (lnum < 0)
10301 lnum = 0;
10302 fold_count = foldedCount(curwin, lnum, &foldinfo);
10303 if (fold_count > 0)
10305 text = get_foldtext(curwin, lnum, lnum + fold_count - 1,
10306 &foldinfo, buf);
10307 if (text == buf)
10308 text = vim_strsave(text);
10309 rettv->vval.v_string = text;
10311 #endif
10315 * "foreground()" function
10317 /*ARGSUSED*/
10318 static void
10319 f_foreground(argvars, rettv)
10320 typval_T *argvars;
10321 typval_T *rettv;
10323 #ifdef FEAT_GUI
10324 if (gui.in_use)
10325 gui_mch_set_foreground();
10326 #else
10327 # ifdef WIN32
10328 win32_set_foreground();
10329 # endif
10330 #endif
10334 * "function()" function
10336 /*ARGSUSED*/
10337 static void
10338 f_function(argvars, rettv)
10339 typval_T *argvars;
10340 typval_T *rettv;
10342 char_u *s;
10344 s = get_tv_string(&argvars[0]);
10345 if (s == NULL || *s == NUL || VIM_ISDIGIT(*s))
10346 EMSG2(_(e_invarg2), s);
10347 /* Don't check an autoload name for existence here. */
10348 else if (vim_strchr(s, AUTOLOAD_CHAR) == NULL && !function_exists(s))
10349 EMSG2(_("E700: Unknown function: %s"), s);
10350 else
10352 rettv->vval.v_string = vim_strsave(s);
10353 rettv->v_type = VAR_FUNC;
10358 * "garbagecollect()" function
10360 /*ARGSUSED*/
10361 static void
10362 f_garbagecollect(argvars, rettv)
10363 typval_T *argvars;
10364 typval_T *rettv;
10366 /* This is postponed until we are back at the toplevel, because we may be
10367 * using Lists and Dicts internally. E.g.: ":echo [garbagecollect()]". */
10368 want_garbage_collect = TRUE;
10370 if (argvars[0].v_type != VAR_UNKNOWN && get_tv_number(&argvars[0]) == 1)
10371 garbage_collect_at_exit = TRUE;
10375 * "get()" function
10377 static void
10378 f_get(argvars, rettv)
10379 typval_T *argvars;
10380 typval_T *rettv;
10382 listitem_T *li;
10383 list_T *l;
10384 dictitem_T *di;
10385 dict_T *d;
10386 typval_T *tv = NULL;
10388 if (argvars[0].v_type == VAR_LIST)
10390 if ((l = argvars[0].vval.v_list) != NULL)
10392 int error = FALSE;
10394 li = list_find(l, get_tv_number_chk(&argvars[1], &error));
10395 if (!error && li != NULL)
10396 tv = &li->li_tv;
10399 else if (argvars[0].v_type == VAR_DICT)
10401 if ((d = argvars[0].vval.v_dict) != NULL)
10403 di = dict_find(d, get_tv_string(&argvars[1]), -1);
10404 if (di != NULL)
10405 tv = &di->di_tv;
10408 else
10409 EMSG2(_(e_listdictarg), "get()");
10411 if (tv == NULL)
10413 if (argvars[2].v_type != VAR_UNKNOWN)
10414 copy_tv(&argvars[2], rettv);
10416 else
10417 copy_tv(tv, rettv);
10420 static void get_buffer_lines __ARGS((buf_T *buf, linenr_T start, linenr_T end, int retlist, typval_T *rettv));
10423 * Get line or list of lines from buffer "buf" into "rettv".
10424 * Return a range (from start to end) of lines in rettv from the specified
10425 * buffer.
10426 * If 'retlist' is TRUE, then the lines are returned as a Vim List.
10428 static void
10429 get_buffer_lines(buf, start, end, retlist, rettv)
10430 buf_T *buf;
10431 linenr_T start;
10432 linenr_T end;
10433 int retlist;
10434 typval_T *rettv;
10436 char_u *p;
10438 if (retlist && rettv_list_alloc(rettv) == FAIL)
10439 return;
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 winnr = 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 ++winnr;
10654 # endif
10655 vimvars[VV_MOUSE_WIN].vv_nr = winnr;
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 if (rettv_list_alloc(rettv) == OK)
10988 while (cur != NULL)
10990 dict = dict_alloc();
10991 if (dict == NULL)
10992 return;
10993 dict_add_nr_str(dict, "group", 0L, syn_id2name(cur->hlg_id));
10994 dict_add_nr_str(dict, "pattern", 0L, cur->pattern);
10995 dict_add_nr_str(dict, "priority", (long)cur->priority, NULL);
10996 dict_add_nr_str(dict, "id", (long)cur->id, NULL);
10997 list_append_dict(rettv->vval.v_list, dict);
10998 cur = cur->next;
11001 #endif
11005 * "getpid()" function
11007 /*ARGSUSED*/
11008 static void
11009 f_getpid(argvars, rettv)
11010 typval_T *argvars;
11011 typval_T *rettv;
11013 rettv->vval.v_number = mch_get_pid();
11017 * "getpos(string)" function
11019 static void
11020 f_getpos(argvars, rettv)
11021 typval_T *argvars;
11022 typval_T *rettv;
11024 pos_T *fp;
11025 list_T *l;
11026 int fnum = -1;
11028 if (rettv_list_alloc(rettv) == OK)
11030 l = rettv->vval.v_list;
11031 fp = var2fpos(&argvars[0], TRUE, &fnum);
11032 if (fnum != -1)
11033 list_append_number(l, (varnumber_T)fnum);
11034 else
11035 list_append_number(l, (varnumber_T)0);
11036 list_append_number(l, (fp != NULL) ? (varnumber_T)fp->lnum
11037 : (varnumber_T)0);
11038 list_append_number(l, (fp != NULL)
11039 ? (varnumber_T)(fp->col == MAXCOL ? MAXCOL : fp->col + 1)
11040 : (varnumber_T)0);
11041 list_append_number(l,
11042 #ifdef FEAT_VIRTUALEDIT
11043 (fp != NULL) ? (varnumber_T)fp->coladd :
11044 #endif
11045 (varnumber_T)0);
11047 else
11048 rettv->vval.v_number = FALSE;
11052 * "getqflist()" and "getloclist()" functions
11054 /*ARGSUSED*/
11055 static void
11056 f_getqflist(argvars, rettv)
11057 typval_T *argvars;
11058 typval_T *rettv;
11060 #ifdef FEAT_QUICKFIX
11061 win_T *wp;
11062 #endif
11064 #ifdef FEAT_QUICKFIX
11065 if (rettv_list_alloc(rettv) == OK)
11067 wp = NULL;
11068 if (argvars[0].v_type != VAR_UNKNOWN) /* getloclist() */
11070 wp = find_win_by_nr(&argvars[0], NULL);
11071 if (wp == NULL)
11072 return;
11075 (void)get_errorlist(wp, rettv->vval.v_list);
11077 #endif
11081 * "getreg()" function
11083 static void
11084 f_getreg(argvars, rettv)
11085 typval_T *argvars;
11086 typval_T *rettv;
11088 char_u *strregname;
11089 int regname;
11090 int arg2 = FALSE;
11091 int error = FALSE;
11093 if (argvars[0].v_type != VAR_UNKNOWN)
11095 strregname = get_tv_string_chk(&argvars[0]);
11096 error = strregname == NULL;
11097 if (argvars[1].v_type != VAR_UNKNOWN)
11098 arg2 = get_tv_number_chk(&argvars[1], &error);
11100 else
11101 strregname = vimvars[VV_REG].vv_str;
11102 regname = (strregname == NULL ? '"' : *strregname);
11103 if (regname == 0)
11104 regname = '"';
11106 rettv->v_type = VAR_STRING;
11107 rettv->vval.v_string = error ? NULL :
11108 get_reg_contents(regname, TRUE, arg2);
11112 * "getregtype()" function
11114 static void
11115 f_getregtype(argvars, rettv)
11116 typval_T *argvars;
11117 typval_T *rettv;
11119 char_u *strregname;
11120 int regname;
11121 char_u buf[NUMBUFLEN + 2];
11122 long reglen = 0;
11124 if (argvars[0].v_type != VAR_UNKNOWN)
11126 strregname = get_tv_string_chk(&argvars[0]);
11127 if (strregname == NULL) /* type error; errmsg already given */
11129 rettv->v_type = VAR_STRING;
11130 rettv->vval.v_string = NULL;
11131 return;
11134 else
11135 /* Default to v:register */
11136 strregname = vimvars[VV_REG].vv_str;
11138 regname = (strregname == NULL ? '"' : *strregname);
11139 if (regname == 0)
11140 regname = '"';
11142 buf[0] = NUL;
11143 buf[1] = NUL;
11144 switch (get_reg_type(regname, &reglen))
11146 case MLINE: buf[0] = 'V'; break;
11147 case MCHAR: buf[0] = 'v'; break;
11148 #ifdef FEAT_VISUAL
11149 case MBLOCK:
11150 buf[0] = Ctrl_V;
11151 sprintf((char *)buf + 1, "%ld", reglen + 1);
11152 break;
11153 #endif
11155 rettv->v_type = VAR_STRING;
11156 rettv->vval.v_string = vim_strsave(buf);
11160 * "gettabwinvar()" function
11162 static void
11163 f_gettabwinvar(argvars, rettv)
11164 typval_T *argvars;
11165 typval_T *rettv;
11167 getwinvar(argvars, rettv, 1);
11171 * "getwinposx()" function
11173 /*ARGSUSED*/
11174 static void
11175 f_getwinposx(argvars, rettv)
11176 typval_T *argvars;
11177 typval_T *rettv;
11179 rettv->vval.v_number = -1;
11180 #ifdef FEAT_GUI
11181 if (gui.in_use)
11183 int x, y;
11185 if (gui_mch_get_winpos(&x, &y) == OK)
11186 rettv->vval.v_number = x;
11188 #endif
11192 * "getwinposy()" function
11194 /*ARGSUSED*/
11195 static void
11196 f_getwinposy(argvars, rettv)
11197 typval_T *argvars;
11198 typval_T *rettv;
11200 rettv->vval.v_number = -1;
11201 #ifdef FEAT_GUI
11202 if (gui.in_use)
11204 int x, y;
11206 if (gui_mch_get_winpos(&x, &y) == OK)
11207 rettv->vval.v_number = y;
11209 #endif
11213 * Find window specified by "vp" in tabpage "tp".
11215 static win_T *
11216 find_win_by_nr(vp, tp)
11217 typval_T *vp;
11218 tabpage_T *tp; /* NULL for current tab page */
11220 #ifdef FEAT_WINDOWS
11221 win_T *wp;
11222 #endif
11223 int nr;
11225 nr = get_tv_number_chk(vp, NULL);
11227 #ifdef FEAT_WINDOWS
11228 if (nr < 0)
11229 return NULL;
11230 if (nr == 0)
11231 return curwin;
11233 for (wp = (tp == NULL || tp == curtab) ? firstwin : tp->tp_firstwin;
11234 wp != NULL; wp = wp->w_next)
11235 if (--nr <= 0)
11236 break;
11237 return wp;
11238 #else
11239 if (nr == 0 || nr == 1)
11240 return curwin;
11241 return NULL;
11242 #endif
11246 * "getwinvar()" function
11248 static void
11249 f_getwinvar(argvars, rettv)
11250 typval_T *argvars;
11251 typval_T *rettv;
11253 getwinvar(argvars, rettv, 0);
11257 * getwinvar() and gettabwinvar()
11259 static void
11260 getwinvar(argvars, rettv, off)
11261 typval_T *argvars;
11262 typval_T *rettv;
11263 int off; /* 1 for gettabwinvar() */
11265 win_T *win, *oldcurwin;
11266 char_u *varname;
11267 dictitem_T *v;
11268 tabpage_T *tp;
11270 #ifdef FEAT_WINDOWS
11271 if (off == 1)
11272 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
11273 else
11274 tp = curtab;
11275 #endif
11276 win = find_win_by_nr(&argvars[off], tp);
11277 varname = get_tv_string_chk(&argvars[off + 1]);
11278 ++emsg_off;
11280 rettv->v_type = VAR_STRING;
11281 rettv->vval.v_string = NULL;
11283 if (win != NULL && varname != NULL)
11285 /* Set curwin to be our win, temporarily. Also set curbuf, so
11286 * that we can get buffer-local options. */
11287 oldcurwin = curwin;
11288 curwin = win;
11289 curbuf = win->w_buffer;
11291 if (*varname == '&') /* window-local-option */
11292 get_option_tv(&varname, rettv, 1);
11293 else
11295 if (*varname == NUL)
11296 /* let getwinvar({nr}, "") return the "w:" dictionary. The
11297 * scope prefix before the NUL byte is required by
11298 * find_var_in_ht(). */
11299 varname = (char_u *)"w:" + 2;
11300 /* look up the variable */
11301 v = find_var_in_ht(&win->w_vars.dv_hashtab, varname, FALSE);
11302 if (v != NULL)
11303 copy_tv(&v->di_tv, rettv);
11306 /* restore previous notion of curwin */
11307 curwin = oldcurwin;
11308 curbuf = curwin->w_buffer;
11311 --emsg_off;
11315 * "glob()" function
11317 static void
11318 f_glob(argvars, rettv)
11319 typval_T *argvars;
11320 typval_T *rettv;
11322 int flags = WILD_SILENT|WILD_USE_NL;
11323 expand_T xpc;
11324 int error = FALSE;
11326 /* When the optional second argument is non-zero, don't remove matches
11327 * for 'wildignore' and don't put matches for 'suffixes' at the end. */
11328 if (argvars[1].v_type != VAR_UNKNOWN
11329 && get_tv_number_chk(&argvars[1], &error))
11330 flags |= WILD_KEEP_ALL;
11331 rettv->v_type = VAR_STRING;
11332 if (!error)
11334 ExpandInit(&xpc);
11335 xpc.xp_context = EXPAND_FILES;
11336 rettv->vval.v_string = ExpandOne(&xpc, get_tv_string(&argvars[0]),
11337 NULL, flags, WILD_ALL);
11339 else
11340 rettv->vval.v_string = NULL;
11344 * "globpath()" function
11346 static void
11347 f_globpath(argvars, rettv)
11348 typval_T *argvars;
11349 typval_T *rettv;
11351 int flags = 0;
11352 char_u buf1[NUMBUFLEN];
11353 char_u *file = get_tv_string_buf_chk(&argvars[1], buf1);
11354 int error = FALSE;
11356 /* When the optional second argument is non-zero, don't remove matches
11357 * for 'wildignore' and don't put matches for 'suffixes' at the end. */
11358 if (argvars[2].v_type != VAR_UNKNOWN
11359 && get_tv_number_chk(&argvars[2], &error))
11360 flags |= WILD_KEEP_ALL;
11361 rettv->v_type = VAR_STRING;
11362 if (file == NULL || error)
11363 rettv->vval.v_string = NULL;
11364 else
11365 rettv->vval.v_string = globpath(get_tv_string(&argvars[0]), file,
11366 flags);
11370 * "has()" function
11372 static void
11373 f_has(argvars, rettv)
11374 typval_T *argvars;
11375 typval_T *rettv;
11377 int i;
11378 char_u *name;
11379 int n = FALSE;
11380 static char *(has_list[]) =
11382 #ifdef AMIGA
11383 "amiga",
11384 # ifdef FEAT_ARP
11385 "arp",
11386 # endif
11387 #endif
11388 #ifdef __BEOS__
11389 "beos",
11390 #endif
11391 #ifdef MSDOS
11392 # ifdef DJGPP
11393 "dos32",
11394 # else
11395 "dos16",
11396 # endif
11397 #endif
11398 #ifdef MACOS
11399 "mac",
11400 #endif
11401 #if defined(MACOS_X_UNIX)
11402 "macunix",
11403 #endif
11404 #ifdef OS2
11405 "os2",
11406 #endif
11407 #ifdef __QNX__
11408 "qnx",
11409 #endif
11410 #ifdef RISCOS
11411 "riscos",
11412 #endif
11413 #ifdef UNIX
11414 "unix",
11415 #endif
11416 #ifdef VMS
11417 "vms",
11418 #endif
11419 #ifdef WIN16
11420 "win16",
11421 #endif
11422 #ifdef WIN32
11423 "win32",
11424 #endif
11425 #if defined(UNIX) && (defined(__CYGWIN32__) || defined(__CYGWIN__))
11426 "win32unix",
11427 #endif
11428 #ifdef WIN64
11429 "win64",
11430 #endif
11431 #ifdef EBCDIC
11432 "ebcdic",
11433 #endif
11434 #ifndef CASE_INSENSITIVE_FILENAME
11435 "fname_case",
11436 #endif
11437 #ifdef FEAT_ARABIC
11438 "arabic",
11439 #endif
11440 #ifdef FEAT_AUTOCMD
11441 "autocmd",
11442 #endif
11443 #ifdef FEAT_BEVAL
11444 "balloon_eval",
11445 # ifndef FEAT_GUI_W32 /* other GUIs always have multiline balloons */
11446 "balloon_multiline",
11447 # endif
11448 #endif
11449 #if defined(SOME_BUILTIN_TCAPS) || defined(ALL_BUILTIN_TCAPS)
11450 "builtin_terms",
11451 # ifdef ALL_BUILTIN_TCAPS
11452 "all_builtin_terms",
11453 # endif
11454 #endif
11455 #ifdef FEAT_BYTEOFF
11456 "byte_offset",
11457 #endif
11458 #ifdef FEAT_CINDENT
11459 "cindent",
11460 #endif
11461 #ifdef FEAT_CLIENTSERVER
11462 "clientserver",
11463 #endif
11464 #ifdef FEAT_CLIPBOARD
11465 "clipboard",
11466 #endif
11467 #ifdef FEAT_CMDL_COMPL
11468 "cmdline_compl",
11469 #endif
11470 #ifdef FEAT_CMDHIST
11471 "cmdline_hist",
11472 #endif
11473 #ifdef FEAT_COMMENTS
11474 "comments",
11475 #endif
11476 #ifdef FEAT_CRYPT
11477 "cryptv",
11478 #endif
11479 #ifdef FEAT_CSCOPE
11480 "cscope",
11481 #endif
11482 #ifdef CURSOR_SHAPE
11483 "cursorshape",
11484 #endif
11485 #ifdef DEBUG
11486 "debug",
11487 #endif
11488 #ifdef FEAT_CON_DIALOG
11489 "dialog_con",
11490 #endif
11491 #ifdef FEAT_GUI_DIALOG
11492 "dialog_gui",
11493 #endif
11494 #ifdef FEAT_DIFF
11495 "diff",
11496 #endif
11497 #ifdef FEAT_DIGRAPHS
11498 "digraphs",
11499 #endif
11500 #ifdef FEAT_DND
11501 "dnd",
11502 #endif
11503 #ifdef FEAT_EMACS_TAGS
11504 "emacs_tags",
11505 #endif
11506 "eval", /* always present, of course! */
11507 #ifdef FEAT_EX_EXTRA
11508 "ex_extra",
11509 #endif
11510 #ifdef FEAT_SEARCH_EXTRA
11511 "extra_search",
11512 #endif
11513 #ifdef FEAT_FKMAP
11514 "farsi",
11515 #endif
11516 #ifdef FEAT_SEARCHPATH
11517 "file_in_path",
11518 #endif
11519 #if defined(UNIX) && !defined(USE_SYSTEM)
11520 "filterpipe",
11521 #endif
11522 #ifdef FEAT_FIND_ID
11523 "find_in_path",
11524 #endif
11525 #ifdef FEAT_FLOAT
11526 "float",
11527 #endif
11528 #ifdef FEAT_FOLDING
11529 "folding",
11530 #endif
11531 #ifdef FEAT_FOOTER
11532 "footer",
11533 #endif
11534 #if !defined(USE_SYSTEM) && defined(UNIX)
11535 "fork",
11536 #endif
11537 #ifdef FEAT_GETTEXT
11538 "gettext",
11539 #endif
11540 #ifdef FEAT_GUI
11541 "gui",
11542 #endif
11543 #ifdef FEAT_GUI_ATHENA
11544 # ifdef FEAT_GUI_NEXTAW
11545 "gui_neXtaw",
11546 # else
11547 "gui_athena",
11548 # endif
11549 #endif
11550 #ifdef FEAT_GUI_GTK
11551 "gui_gtk",
11552 # ifdef HAVE_GTK2
11553 "gui_gtk2",
11554 # endif
11555 #endif
11556 #ifdef FEAT_GUI_GNOME
11557 "gui_gnome",
11558 #endif
11559 #ifdef FEAT_GUI_MAC
11560 "gui_mac",
11561 #endif
11562 #ifdef FEAT_GUI_MOTIF
11563 "gui_motif",
11564 #endif
11565 #ifdef FEAT_GUI_PHOTON
11566 "gui_photon",
11567 #endif
11568 #ifdef FEAT_GUI_W16
11569 "gui_win16",
11570 #endif
11571 #ifdef FEAT_GUI_W32
11572 "gui_win32",
11573 #endif
11574 #ifdef FEAT_HANGULIN
11575 "hangul_input",
11576 #endif
11577 #if defined(HAVE_ICONV_H) && defined(USE_ICONV)
11578 "iconv",
11579 #endif
11580 #ifdef FEAT_INS_EXPAND
11581 "insert_expand",
11582 #endif
11583 #ifdef FEAT_JUMPLIST
11584 "jumplist",
11585 #endif
11586 #ifdef FEAT_KEYMAP
11587 "keymap",
11588 #endif
11589 #ifdef FEAT_LANGMAP
11590 "langmap",
11591 #endif
11592 #ifdef FEAT_LIBCALL
11593 "libcall",
11594 #endif
11595 #ifdef FEAT_LINEBREAK
11596 "linebreak",
11597 #endif
11598 #ifdef FEAT_LISP
11599 "lispindent",
11600 #endif
11601 #ifdef FEAT_LISTCMDS
11602 "listcmds",
11603 #endif
11604 #ifdef FEAT_LOCALMAP
11605 "localmap",
11606 #endif
11607 #ifdef FEAT_MENU
11608 "menu",
11609 #endif
11610 #ifdef FEAT_SESSION
11611 "mksession",
11612 #endif
11613 #ifdef FEAT_MODIFY_FNAME
11614 "modify_fname",
11615 #endif
11616 #ifdef FEAT_MOUSE
11617 "mouse",
11618 #endif
11619 #ifdef FEAT_MOUSESHAPE
11620 "mouseshape",
11621 #endif
11622 #if defined(UNIX) || defined(VMS)
11623 # ifdef FEAT_MOUSE_DEC
11624 "mouse_dec",
11625 # endif
11626 # ifdef FEAT_MOUSE_GPM
11627 "mouse_gpm",
11628 # endif
11629 # ifdef FEAT_MOUSE_JSB
11630 "mouse_jsbterm",
11631 # endif
11632 # ifdef FEAT_MOUSE_NET
11633 "mouse_netterm",
11634 # endif
11635 # ifdef FEAT_MOUSE_PTERM
11636 "mouse_pterm",
11637 # endif
11638 # ifdef FEAT_SYSMOUSE
11639 "mouse_sysmouse",
11640 # endif
11641 # ifdef FEAT_MOUSE_XTERM
11642 "mouse_xterm",
11643 # endif
11644 #endif
11645 #ifdef FEAT_MBYTE
11646 "multi_byte",
11647 #endif
11648 #ifdef FEAT_MBYTE_IME
11649 "multi_byte_ime",
11650 #endif
11651 #ifdef FEAT_MULTI_LANG
11652 "multi_lang",
11653 #endif
11654 #ifdef FEAT_MZSCHEME
11655 #ifndef DYNAMIC_MZSCHEME
11656 "mzscheme",
11657 #endif
11658 #endif
11659 #ifdef FEAT_OLE
11660 "ole",
11661 #endif
11662 #ifdef FEAT_OSFILETYPE
11663 "osfiletype",
11664 #endif
11665 #ifdef FEAT_PATH_EXTRA
11666 "path_extra",
11667 #endif
11668 #ifdef FEAT_PERL
11669 #ifndef DYNAMIC_PERL
11670 "perl",
11671 #endif
11672 #endif
11673 #ifdef FEAT_PYTHON
11674 #ifndef DYNAMIC_PYTHON
11675 "python",
11676 #endif
11677 #endif
11678 #ifdef FEAT_POSTSCRIPT
11679 "postscript",
11680 #endif
11681 #ifdef FEAT_PRINTER
11682 "printer",
11683 #endif
11684 #ifdef FEAT_PROFILE
11685 "profile",
11686 #endif
11687 #ifdef FEAT_RELTIME
11688 "reltime",
11689 #endif
11690 #ifdef FEAT_QUICKFIX
11691 "quickfix",
11692 #endif
11693 #ifdef FEAT_RIGHTLEFT
11694 "rightleft",
11695 #endif
11696 #if defined(FEAT_RUBY) && !defined(DYNAMIC_RUBY)
11697 "ruby",
11698 #endif
11699 #ifdef FEAT_SCROLLBIND
11700 "scrollbind",
11701 #endif
11702 #ifdef FEAT_CMDL_INFO
11703 "showcmd",
11704 "cmdline_info",
11705 #endif
11706 #ifdef FEAT_SIGNS
11707 "signs",
11708 #endif
11709 #ifdef FEAT_SMARTINDENT
11710 "smartindent",
11711 #endif
11712 #ifdef FEAT_SNIFF
11713 "sniff",
11714 #endif
11715 #ifdef FEAT_STL_OPT
11716 "statusline",
11717 #endif
11718 #ifdef FEAT_SUN_WORKSHOP
11719 "sun_workshop",
11720 #endif
11721 #ifdef FEAT_NETBEANS_INTG
11722 "netbeans_intg",
11723 #endif
11724 #ifdef FEAT_SPELL
11725 "spell",
11726 #endif
11727 #ifdef FEAT_SYN_HL
11728 "syntax",
11729 #endif
11730 #if defined(USE_SYSTEM) || !defined(UNIX)
11731 "system",
11732 #endif
11733 #ifdef FEAT_TAG_BINS
11734 "tag_binary",
11735 #endif
11736 #ifdef FEAT_TAG_OLDSTATIC
11737 "tag_old_static",
11738 #endif
11739 #ifdef FEAT_TAG_ANYWHITE
11740 "tag_any_white",
11741 #endif
11742 #ifdef FEAT_TCL
11743 # ifndef DYNAMIC_TCL
11744 "tcl",
11745 # endif
11746 #endif
11747 #ifdef TERMINFO
11748 "terminfo",
11749 #endif
11750 #ifdef FEAT_TERMRESPONSE
11751 "termresponse",
11752 #endif
11753 #ifdef FEAT_TEXTOBJ
11754 "textobjects",
11755 #endif
11756 #ifdef HAVE_TGETENT
11757 "tgetent",
11758 #endif
11759 #ifdef FEAT_TITLE
11760 "title",
11761 #endif
11762 #ifdef FEAT_TOOLBAR
11763 "toolbar",
11764 #endif
11765 #ifdef FEAT_USR_CMDS
11766 "user-commands", /* was accidentally included in 5.4 */
11767 "user_commands",
11768 #endif
11769 #ifdef FEAT_VIMINFO
11770 "viminfo",
11771 #endif
11772 #ifdef FEAT_VERTSPLIT
11773 "vertsplit",
11774 #endif
11775 #ifdef FEAT_VIRTUALEDIT
11776 "virtualedit",
11777 #endif
11778 #ifdef FEAT_VISUAL
11779 "visual",
11780 #endif
11781 #ifdef FEAT_VISUALEXTRA
11782 "visualextra",
11783 #endif
11784 #ifdef FEAT_VREPLACE
11785 "vreplace",
11786 #endif
11787 #ifdef FEAT_WILDIGN
11788 "wildignore",
11789 #endif
11790 #ifdef FEAT_WILDMENU
11791 "wildmenu",
11792 #endif
11793 #ifdef FEAT_WINDOWS
11794 "windows",
11795 #endif
11796 #ifdef FEAT_WAK
11797 "winaltkeys",
11798 #endif
11799 #ifdef FEAT_WRITEBACKUP
11800 "writebackup",
11801 #endif
11802 #ifdef FEAT_XIM
11803 "xim",
11804 #endif
11805 #ifdef FEAT_XFONTSET
11806 "xfontset",
11807 #endif
11808 #ifdef USE_XSMP
11809 "xsmp",
11810 #endif
11811 #ifdef USE_XSMP_INTERACT
11812 "xsmp_interact",
11813 #endif
11814 #ifdef FEAT_XCLIPBOARD
11815 "xterm_clipboard",
11816 #endif
11817 #ifdef FEAT_XTERM_SAVE
11818 "xterm_save",
11819 #endif
11820 #if defined(UNIX) && defined(FEAT_X11)
11821 "X11",
11822 #endif
11823 NULL
11826 name = get_tv_string(&argvars[0]);
11827 for (i = 0; has_list[i] != NULL; ++i)
11828 if (STRICMP(name, has_list[i]) == 0)
11830 n = TRUE;
11831 break;
11834 if (n == FALSE)
11836 if (STRNICMP(name, "patch", 5) == 0)
11837 n = has_patch(atoi((char *)name + 5));
11838 else if (STRICMP(name, "vim_starting") == 0)
11839 n = (starting != 0);
11840 #ifdef FEAT_MBYTE
11841 else if (STRICMP(name, "multi_byte_encoding") == 0)
11842 n = has_mbyte;
11843 #endif
11844 #if defined(FEAT_BEVAL) && defined(FEAT_GUI_W32)
11845 else if (STRICMP(name, "balloon_multiline") == 0)
11846 n = multiline_balloon_available();
11847 #endif
11848 #ifdef DYNAMIC_TCL
11849 else if (STRICMP(name, "tcl") == 0)
11850 n = tcl_enabled(FALSE);
11851 #endif
11852 #if defined(USE_ICONV) && defined(DYNAMIC_ICONV)
11853 else if (STRICMP(name, "iconv") == 0)
11854 n = iconv_enabled(FALSE);
11855 #endif
11856 #ifdef DYNAMIC_MZSCHEME
11857 else if (STRICMP(name, "mzscheme") == 0)
11858 n = mzscheme_enabled(FALSE);
11859 #endif
11860 #ifdef DYNAMIC_RUBY
11861 else if (STRICMP(name, "ruby") == 0)
11862 n = ruby_enabled(FALSE);
11863 #endif
11864 #ifdef DYNAMIC_PYTHON
11865 else if (STRICMP(name, "python") == 0)
11866 n = python_enabled(FALSE);
11867 #endif
11868 #ifdef DYNAMIC_PERL
11869 else if (STRICMP(name, "perl") == 0)
11870 n = perl_enabled(FALSE);
11871 #endif
11872 #ifdef FEAT_GUI
11873 else if (STRICMP(name, "gui_running") == 0)
11874 n = (gui.in_use || gui.starting);
11875 # ifdef FEAT_GUI_W32
11876 else if (STRICMP(name, "gui_win32s") == 0)
11877 n = gui_is_win32s();
11878 # endif
11879 # ifdef FEAT_BROWSE
11880 else if (STRICMP(name, "browse") == 0)
11881 n = gui.in_use; /* gui_mch_browse() works when GUI is running */
11882 # endif
11883 #endif
11884 #ifdef FEAT_SYN_HL
11885 else if (STRICMP(name, "syntax_items") == 0)
11886 n = syntax_present(curbuf);
11887 #endif
11888 #if defined(WIN3264)
11889 else if (STRICMP(name, "win95") == 0)
11890 n = mch_windows95();
11891 #endif
11892 #ifdef FEAT_NETBEANS_INTG
11893 else if (STRICMP(name, "netbeans_enabled") == 0)
11894 n = usingNetbeans;
11895 #endif
11898 rettv->vval.v_number = n;
11902 * "has_key()" function
11904 static void
11905 f_has_key(argvars, rettv)
11906 typval_T *argvars;
11907 typval_T *rettv;
11909 if (argvars[0].v_type != VAR_DICT)
11911 EMSG(_(e_dictreq));
11912 return;
11914 if (argvars[0].vval.v_dict == NULL)
11915 return;
11917 rettv->vval.v_number = dict_find(argvars[0].vval.v_dict,
11918 get_tv_string(&argvars[1]), -1) != NULL;
11922 * "haslocaldir()" function
11924 /*ARGSUSED*/
11925 static void
11926 f_haslocaldir(argvars, rettv)
11927 typval_T *argvars;
11928 typval_T *rettv;
11930 rettv->vval.v_number = (curwin->w_localdir != NULL);
11934 * "hasmapto()" function
11936 static void
11937 f_hasmapto(argvars, rettv)
11938 typval_T *argvars;
11939 typval_T *rettv;
11941 char_u *name;
11942 char_u *mode;
11943 char_u buf[NUMBUFLEN];
11944 int abbr = FALSE;
11946 name = get_tv_string(&argvars[0]);
11947 if (argvars[1].v_type == VAR_UNKNOWN)
11948 mode = (char_u *)"nvo";
11949 else
11951 mode = get_tv_string_buf(&argvars[1], buf);
11952 if (argvars[2].v_type != VAR_UNKNOWN)
11953 abbr = get_tv_number(&argvars[2]);
11956 if (map_to_exists(name, mode, abbr))
11957 rettv->vval.v_number = TRUE;
11958 else
11959 rettv->vval.v_number = FALSE;
11963 * "histadd()" function
11965 /*ARGSUSED*/
11966 static void
11967 f_histadd(argvars, rettv)
11968 typval_T *argvars;
11969 typval_T *rettv;
11971 #ifdef FEAT_CMDHIST
11972 int histype;
11973 char_u *str;
11974 char_u buf[NUMBUFLEN];
11975 #endif
11977 rettv->vval.v_number = FALSE;
11978 if (check_restricted() || check_secure())
11979 return;
11980 #ifdef FEAT_CMDHIST
11981 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
11982 histype = str != NULL ? get_histtype(str) : -1;
11983 if (histype >= 0)
11985 str = get_tv_string_buf(&argvars[1], buf);
11986 if (*str != NUL)
11988 add_to_history(histype, str, FALSE, NUL);
11989 rettv->vval.v_number = TRUE;
11990 return;
11993 #endif
11997 * "histdel()" function
11999 /*ARGSUSED*/
12000 static void
12001 f_histdel(argvars, rettv)
12002 typval_T *argvars;
12003 typval_T *rettv;
12005 #ifdef FEAT_CMDHIST
12006 int n;
12007 char_u buf[NUMBUFLEN];
12008 char_u *str;
12010 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
12011 if (str == NULL)
12012 n = 0;
12013 else if (argvars[1].v_type == VAR_UNKNOWN)
12014 /* only one argument: clear entire history */
12015 n = clr_history(get_histtype(str));
12016 else if (argvars[1].v_type == VAR_NUMBER)
12017 /* index given: remove that entry */
12018 n = del_history_idx(get_histtype(str),
12019 (int)get_tv_number(&argvars[1]));
12020 else
12021 /* string given: remove all matching entries */
12022 n = del_history_entry(get_histtype(str),
12023 get_tv_string_buf(&argvars[1], buf));
12024 rettv->vval.v_number = n;
12025 #endif
12029 * "histget()" function
12031 /*ARGSUSED*/
12032 static void
12033 f_histget(argvars, rettv)
12034 typval_T *argvars;
12035 typval_T *rettv;
12037 #ifdef FEAT_CMDHIST
12038 int type;
12039 int idx;
12040 char_u *str;
12042 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
12043 if (str == NULL)
12044 rettv->vval.v_string = NULL;
12045 else
12047 type = get_histtype(str);
12048 if (argvars[1].v_type == VAR_UNKNOWN)
12049 idx = get_history_idx(type);
12050 else
12051 idx = (int)get_tv_number_chk(&argvars[1], NULL);
12052 /* -1 on type error */
12053 rettv->vval.v_string = vim_strsave(get_history_entry(type, idx));
12055 #else
12056 rettv->vval.v_string = NULL;
12057 #endif
12058 rettv->v_type = VAR_STRING;
12062 * "histnr()" function
12064 /*ARGSUSED*/
12065 static void
12066 f_histnr(argvars, rettv)
12067 typval_T *argvars;
12068 typval_T *rettv;
12070 int i;
12072 #ifdef FEAT_CMDHIST
12073 char_u *history = get_tv_string_chk(&argvars[0]);
12075 i = history == NULL ? HIST_CMD - 1 : get_histtype(history);
12076 if (i >= HIST_CMD && i < HIST_COUNT)
12077 i = get_history_idx(i);
12078 else
12079 #endif
12080 i = -1;
12081 rettv->vval.v_number = i;
12085 * "highlightID(name)" function
12087 static void
12088 f_hlID(argvars, rettv)
12089 typval_T *argvars;
12090 typval_T *rettv;
12092 rettv->vval.v_number = syn_name2id(get_tv_string(&argvars[0]));
12096 * "highlight_exists()" function
12098 static void
12099 f_hlexists(argvars, rettv)
12100 typval_T *argvars;
12101 typval_T *rettv;
12103 rettv->vval.v_number = highlight_exists(get_tv_string(&argvars[0]));
12107 * "hostname()" function
12109 /*ARGSUSED*/
12110 static void
12111 f_hostname(argvars, rettv)
12112 typval_T *argvars;
12113 typval_T *rettv;
12115 char_u hostname[256];
12117 mch_get_host_name(hostname, 256);
12118 rettv->v_type = VAR_STRING;
12119 rettv->vval.v_string = vim_strsave(hostname);
12123 * iconv() function
12125 /*ARGSUSED*/
12126 static void
12127 f_iconv(argvars, rettv)
12128 typval_T *argvars;
12129 typval_T *rettv;
12131 #ifdef FEAT_MBYTE
12132 char_u buf1[NUMBUFLEN];
12133 char_u buf2[NUMBUFLEN];
12134 char_u *from, *to, *str;
12135 vimconv_T vimconv;
12136 #endif
12138 rettv->v_type = VAR_STRING;
12139 rettv->vval.v_string = NULL;
12141 #ifdef FEAT_MBYTE
12142 str = get_tv_string(&argvars[0]);
12143 from = enc_canonize(enc_skip(get_tv_string_buf(&argvars[1], buf1)));
12144 to = enc_canonize(enc_skip(get_tv_string_buf(&argvars[2], buf2)));
12145 vimconv.vc_type = CONV_NONE;
12146 convert_setup(&vimconv, from, to);
12148 /* If the encodings are equal, no conversion needed. */
12149 if (vimconv.vc_type == CONV_NONE)
12150 rettv->vval.v_string = vim_strsave(str);
12151 else
12152 rettv->vval.v_string = string_convert(&vimconv, str, NULL);
12154 convert_setup(&vimconv, NULL, NULL);
12155 vim_free(from);
12156 vim_free(to);
12157 #endif
12161 * "indent()" function
12163 static void
12164 f_indent(argvars, rettv)
12165 typval_T *argvars;
12166 typval_T *rettv;
12168 linenr_T lnum;
12170 lnum = get_tv_lnum(argvars);
12171 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
12172 rettv->vval.v_number = get_indent_lnum(lnum);
12173 else
12174 rettv->vval.v_number = -1;
12178 * "index()" function
12180 static void
12181 f_index(argvars, rettv)
12182 typval_T *argvars;
12183 typval_T *rettv;
12185 list_T *l;
12186 listitem_T *item;
12187 long idx = 0;
12188 int ic = FALSE;
12190 rettv->vval.v_number = -1;
12191 if (argvars[0].v_type != VAR_LIST)
12193 EMSG(_(e_listreq));
12194 return;
12196 l = argvars[0].vval.v_list;
12197 if (l != NULL)
12199 item = l->lv_first;
12200 if (argvars[2].v_type != VAR_UNKNOWN)
12202 int error = FALSE;
12204 /* Start at specified item. Use the cached index that list_find()
12205 * sets, so that a negative number also works. */
12206 item = list_find(l, get_tv_number_chk(&argvars[2], &error));
12207 idx = l->lv_idx;
12208 if (argvars[3].v_type != VAR_UNKNOWN)
12209 ic = get_tv_number_chk(&argvars[3], &error);
12210 if (error)
12211 item = NULL;
12214 for ( ; item != NULL; item = item->li_next, ++idx)
12215 if (tv_equal(&item->li_tv, &argvars[1], ic))
12217 rettv->vval.v_number = idx;
12218 break;
12223 static int inputsecret_flag = 0;
12225 static void get_user_input __ARGS((typval_T *argvars, typval_T *rettv, int inputdialog));
12228 * This function is used by f_input() and f_inputdialog() functions. The third
12229 * argument to f_input() specifies the type of completion to use at the
12230 * prompt. The third argument to f_inputdialog() specifies the value to return
12231 * when the user cancels the prompt.
12233 static void
12234 get_user_input(argvars, rettv, inputdialog)
12235 typval_T *argvars;
12236 typval_T *rettv;
12237 int inputdialog;
12239 char_u *prompt = get_tv_string_chk(&argvars[0]);
12240 char_u *p = NULL;
12241 int c;
12242 char_u buf[NUMBUFLEN];
12243 int cmd_silent_save = cmd_silent;
12244 char_u *defstr = (char_u *)"";
12245 int xp_type = EXPAND_NOTHING;
12246 char_u *xp_arg = NULL;
12248 rettv->v_type = VAR_STRING;
12249 rettv->vval.v_string = NULL;
12251 #ifdef NO_CONSOLE_INPUT
12252 /* While starting up, there is no place to enter text. */
12253 if (no_console_input())
12254 return;
12255 #endif
12257 cmd_silent = FALSE; /* Want to see the prompt. */
12258 if (prompt != NULL)
12260 /* Only the part of the message after the last NL is considered as
12261 * prompt for the command line */
12262 p = vim_strrchr(prompt, '\n');
12263 if (p == NULL)
12264 p = prompt;
12265 else
12267 ++p;
12268 c = *p;
12269 *p = NUL;
12270 msg_start();
12271 msg_clr_eos();
12272 msg_puts_attr(prompt, echo_attr);
12273 msg_didout = FALSE;
12274 msg_starthere();
12275 *p = c;
12277 cmdline_row = msg_row;
12279 if (argvars[1].v_type != VAR_UNKNOWN)
12281 defstr = get_tv_string_buf_chk(&argvars[1], buf);
12282 if (defstr != NULL)
12283 stuffReadbuffSpec(defstr);
12285 if (!inputdialog && argvars[2].v_type != VAR_UNKNOWN)
12287 char_u *xp_name;
12288 int xp_namelen;
12289 long argt;
12291 rettv->vval.v_string = NULL;
12293 xp_name = get_tv_string_buf_chk(&argvars[2], buf);
12294 if (xp_name == NULL)
12295 return;
12297 xp_namelen = (int)STRLEN(xp_name);
12299 if (parse_compl_arg(xp_name, xp_namelen, &xp_type, &argt,
12300 &xp_arg) == FAIL)
12301 return;
12305 if (defstr != NULL)
12306 rettv->vval.v_string =
12307 getcmdline_prompt(inputsecret_flag ? NUL : '@', p, echo_attr,
12308 xp_type, xp_arg);
12310 vim_free(xp_arg);
12312 /* since the user typed this, no need to wait for return */
12313 need_wait_return = FALSE;
12314 msg_didout = FALSE;
12316 cmd_silent = cmd_silent_save;
12320 * "input()" function
12321 * Also handles inputsecret() when inputsecret is set.
12323 static void
12324 f_input(argvars, rettv)
12325 typval_T *argvars;
12326 typval_T *rettv;
12328 get_user_input(argvars, rettv, FALSE);
12332 * "inputdialog()" function
12334 static void
12335 f_inputdialog(argvars, rettv)
12336 typval_T *argvars;
12337 typval_T *rettv;
12339 #if defined(FEAT_GUI_TEXTDIALOG)
12340 /* Use a GUI dialog if the GUI is running and 'c' is not in 'guioptions' */
12341 if (gui.in_use && vim_strchr(p_go, GO_CONDIALOG) == NULL)
12343 char_u *message;
12344 char_u buf[NUMBUFLEN];
12345 char_u *defstr = (char_u *)"";
12347 message = get_tv_string_chk(&argvars[0]);
12348 if (argvars[1].v_type != VAR_UNKNOWN
12349 && (defstr = get_tv_string_buf_chk(&argvars[1], buf)) != NULL)
12350 vim_strncpy(IObuff, defstr, IOSIZE - 1);
12351 else
12352 IObuff[0] = NUL;
12353 if (message != NULL && defstr != NULL
12354 && do_dialog(VIM_QUESTION, NULL, message,
12355 (char_u *)_("&OK\n&Cancel"), 1, IObuff) == 1)
12356 rettv->vval.v_string = vim_strsave(IObuff);
12357 else
12359 if (message != NULL && defstr != NULL
12360 && argvars[1].v_type != VAR_UNKNOWN
12361 && argvars[2].v_type != VAR_UNKNOWN)
12362 rettv->vval.v_string = vim_strsave(
12363 get_tv_string_buf(&argvars[2], buf));
12364 else
12365 rettv->vval.v_string = NULL;
12367 rettv->v_type = VAR_STRING;
12369 else
12370 #endif
12371 get_user_input(argvars, rettv, TRUE);
12375 * "inputlist()" function
12377 static void
12378 f_inputlist(argvars, rettv)
12379 typval_T *argvars;
12380 typval_T *rettv;
12382 listitem_T *li;
12383 int selected;
12384 int mouse_used;
12386 #ifdef NO_CONSOLE_INPUT
12387 /* While starting up, there is no place to enter text. */
12388 if (no_console_input())
12389 return;
12390 #endif
12391 if (argvars[0].v_type != VAR_LIST || argvars[0].vval.v_list == NULL)
12393 EMSG2(_(e_listarg), "inputlist()");
12394 return;
12397 msg_start();
12398 msg_row = Rows - 1; /* for when 'cmdheight' > 1 */
12399 lines_left = Rows; /* avoid more prompt */
12400 msg_scroll = TRUE;
12401 msg_clr_eos();
12403 for (li = argvars[0].vval.v_list->lv_first; li != NULL; li = li->li_next)
12405 msg_puts(get_tv_string(&li->li_tv));
12406 msg_putchar('\n');
12409 /* Ask for choice. */
12410 selected = prompt_for_number(&mouse_used);
12411 if (mouse_used)
12412 selected -= lines_left;
12414 rettv->vval.v_number = selected;
12418 static garray_T ga_userinput = {0, 0, sizeof(tasave_T), 4, NULL};
12421 * "inputrestore()" function
12423 /*ARGSUSED*/
12424 static void
12425 f_inputrestore(argvars, rettv)
12426 typval_T *argvars;
12427 typval_T *rettv;
12429 if (ga_userinput.ga_len > 0)
12431 --ga_userinput.ga_len;
12432 restore_typeahead((tasave_T *)(ga_userinput.ga_data)
12433 + ga_userinput.ga_len);
12434 /* default return is zero == OK */
12436 else if (p_verbose > 1)
12438 verb_msg((char_u *)_("called inputrestore() more often than inputsave()"));
12439 rettv->vval.v_number = 1; /* Failed */
12444 * "inputsave()" function
12446 /*ARGSUSED*/
12447 static void
12448 f_inputsave(argvars, rettv)
12449 typval_T *argvars;
12450 typval_T *rettv;
12452 /* Add an entry to the stack of typeahead storage. */
12453 if (ga_grow(&ga_userinput, 1) == OK)
12455 save_typeahead((tasave_T *)(ga_userinput.ga_data)
12456 + ga_userinput.ga_len);
12457 ++ga_userinput.ga_len;
12458 /* default return is zero == OK */
12460 else
12461 rettv->vval.v_number = 1; /* Failed */
12465 * "inputsecret()" function
12467 static void
12468 f_inputsecret(argvars, rettv)
12469 typval_T *argvars;
12470 typval_T *rettv;
12472 ++cmdline_star;
12473 ++inputsecret_flag;
12474 f_input(argvars, rettv);
12475 --cmdline_star;
12476 --inputsecret_flag;
12480 * "insert()" function
12482 static void
12483 f_insert(argvars, rettv)
12484 typval_T *argvars;
12485 typval_T *rettv;
12487 long before = 0;
12488 listitem_T *item;
12489 list_T *l;
12490 int error = FALSE;
12492 if (argvars[0].v_type != VAR_LIST)
12493 EMSG2(_(e_listarg), "insert()");
12494 else if ((l = argvars[0].vval.v_list) != NULL
12495 && !tv_check_lock(l->lv_lock, (char_u *)"insert()"))
12497 if (argvars[2].v_type != VAR_UNKNOWN)
12498 before = get_tv_number_chk(&argvars[2], &error);
12499 if (error)
12500 return; /* type error; errmsg already given */
12502 if (before == l->lv_len)
12503 item = NULL;
12504 else
12506 item = list_find(l, before);
12507 if (item == NULL)
12509 EMSGN(_(e_listidx), before);
12510 l = NULL;
12513 if (l != NULL)
12515 list_insert_tv(l, &argvars[1], item);
12516 copy_tv(&argvars[0], rettv);
12522 * "isdirectory()" function
12524 static void
12525 f_isdirectory(argvars, rettv)
12526 typval_T *argvars;
12527 typval_T *rettv;
12529 rettv->vval.v_number = mch_isdir(get_tv_string(&argvars[0]));
12533 * "islocked()" function
12535 static void
12536 f_islocked(argvars, rettv)
12537 typval_T *argvars;
12538 typval_T *rettv;
12540 lval_T lv;
12541 char_u *end;
12542 dictitem_T *di;
12544 rettv->vval.v_number = -1;
12545 end = get_lval(get_tv_string(&argvars[0]), NULL, &lv, FALSE, FALSE, FALSE,
12546 FNE_CHECK_START);
12547 if (end != NULL && lv.ll_name != NULL)
12549 if (*end != NUL)
12550 EMSG(_(e_trailing));
12551 else
12553 if (lv.ll_tv == NULL)
12555 if (check_changedtick(lv.ll_name))
12556 rettv->vval.v_number = 1; /* always locked */
12557 else
12559 di = find_var(lv.ll_name, NULL);
12560 if (di != NULL)
12562 /* Consider a variable locked when:
12563 * 1. the variable itself is locked
12564 * 2. the value of the variable is locked.
12565 * 3. the List or Dict value is locked.
12567 rettv->vval.v_number = ((di->di_flags & DI_FLAGS_LOCK)
12568 || tv_islocked(&di->di_tv));
12572 else if (lv.ll_range)
12573 EMSG(_("E786: Range not allowed"));
12574 else if (lv.ll_newkey != NULL)
12575 EMSG2(_(e_dictkey), lv.ll_newkey);
12576 else if (lv.ll_list != NULL)
12577 /* List item. */
12578 rettv->vval.v_number = tv_islocked(&lv.ll_li->li_tv);
12579 else
12580 /* Dictionary item. */
12581 rettv->vval.v_number = tv_islocked(&lv.ll_di->di_tv);
12585 clear_lval(&lv);
12588 static void dict_list __ARGS((typval_T *argvars, typval_T *rettv, int what));
12591 * Turn a dict into a list:
12592 * "what" == 0: list of keys
12593 * "what" == 1: list of values
12594 * "what" == 2: list of items
12596 static void
12597 dict_list(argvars, rettv, what)
12598 typval_T *argvars;
12599 typval_T *rettv;
12600 int what;
12602 list_T *l2;
12603 dictitem_T *di;
12604 hashitem_T *hi;
12605 listitem_T *li;
12606 listitem_T *li2;
12607 dict_T *d;
12608 int todo;
12610 if (argvars[0].v_type != VAR_DICT)
12612 EMSG(_(e_dictreq));
12613 return;
12615 if ((d = argvars[0].vval.v_dict) == NULL)
12616 return;
12618 if (rettv_list_alloc(rettv) == FAIL)
12619 return;
12621 todo = (int)d->dv_hashtab.ht_used;
12622 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
12624 if (!HASHITEM_EMPTY(hi))
12626 --todo;
12627 di = HI2DI(hi);
12629 li = listitem_alloc();
12630 if (li == NULL)
12631 break;
12632 list_append(rettv->vval.v_list, li);
12634 if (what == 0)
12636 /* keys() */
12637 li->li_tv.v_type = VAR_STRING;
12638 li->li_tv.v_lock = 0;
12639 li->li_tv.vval.v_string = vim_strsave(di->di_key);
12641 else if (what == 1)
12643 /* values() */
12644 copy_tv(&di->di_tv, &li->li_tv);
12646 else
12648 /* items() */
12649 l2 = list_alloc();
12650 li->li_tv.v_type = VAR_LIST;
12651 li->li_tv.v_lock = 0;
12652 li->li_tv.vval.v_list = l2;
12653 if (l2 == NULL)
12654 break;
12655 ++l2->lv_refcount;
12657 li2 = listitem_alloc();
12658 if (li2 == NULL)
12659 break;
12660 list_append(l2, li2);
12661 li2->li_tv.v_type = VAR_STRING;
12662 li2->li_tv.v_lock = 0;
12663 li2->li_tv.vval.v_string = vim_strsave(di->di_key);
12665 li2 = listitem_alloc();
12666 if (li2 == NULL)
12667 break;
12668 list_append(l2, li2);
12669 copy_tv(&di->di_tv, &li2->li_tv);
12676 * "items(dict)" function
12678 static void
12679 f_items(argvars, rettv)
12680 typval_T *argvars;
12681 typval_T *rettv;
12683 dict_list(argvars, rettv, 2);
12687 * "join()" function
12689 static void
12690 f_join(argvars, rettv)
12691 typval_T *argvars;
12692 typval_T *rettv;
12694 garray_T ga;
12695 char_u *sep;
12697 if (argvars[0].v_type != VAR_LIST)
12699 EMSG(_(e_listreq));
12700 return;
12702 if (argvars[0].vval.v_list == NULL)
12703 return;
12704 if (argvars[1].v_type == VAR_UNKNOWN)
12705 sep = (char_u *)" ";
12706 else
12707 sep = get_tv_string_chk(&argvars[1]);
12709 rettv->v_type = VAR_STRING;
12711 if (sep != NULL)
12713 ga_init2(&ga, (int)sizeof(char), 80);
12714 list_join(&ga, argvars[0].vval.v_list, sep, TRUE, 0);
12715 ga_append(&ga, NUL);
12716 rettv->vval.v_string = (char_u *)ga.ga_data;
12718 else
12719 rettv->vval.v_string = NULL;
12723 * "keys()" function
12725 static void
12726 f_keys(argvars, rettv)
12727 typval_T *argvars;
12728 typval_T *rettv;
12730 dict_list(argvars, rettv, 0);
12734 * "last_buffer_nr()" function.
12736 /*ARGSUSED*/
12737 static void
12738 f_last_buffer_nr(argvars, rettv)
12739 typval_T *argvars;
12740 typval_T *rettv;
12742 int n = 0;
12743 buf_T *buf;
12745 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
12746 if (n < buf->b_fnum)
12747 n = buf->b_fnum;
12749 rettv->vval.v_number = n;
12753 * "len()" function
12755 static void
12756 f_len(argvars, rettv)
12757 typval_T *argvars;
12758 typval_T *rettv;
12760 switch (argvars[0].v_type)
12762 case VAR_STRING:
12763 case VAR_NUMBER:
12764 rettv->vval.v_number = (varnumber_T)STRLEN(
12765 get_tv_string(&argvars[0]));
12766 break;
12767 case VAR_LIST:
12768 rettv->vval.v_number = list_len(argvars[0].vval.v_list);
12769 break;
12770 case VAR_DICT:
12771 rettv->vval.v_number = dict_len(argvars[0].vval.v_dict);
12772 break;
12773 default:
12774 EMSG(_("E701: Invalid type for len()"));
12775 break;
12779 static void libcall_common __ARGS((typval_T *argvars, typval_T *rettv, int type));
12781 static void
12782 libcall_common(argvars, rettv, type)
12783 typval_T *argvars;
12784 typval_T *rettv;
12785 int type;
12787 #ifdef FEAT_LIBCALL
12788 char_u *string_in;
12789 char_u **string_result;
12790 int nr_result;
12791 #endif
12793 rettv->v_type = type;
12794 if (type != VAR_NUMBER)
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 #ifdef FEAT_INS_EXPAND
13736 if (pum_visible())
13737 rettv->vval.v_number = 1;
13738 #endif
13742 * "range()" function
13744 static void
13745 f_range(argvars, rettv)
13746 typval_T *argvars;
13747 typval_T *rettv;
13749 long start;
13750 long end;
13751 long stride = 1;
13752 long i;
13753 int error = FALSE;
13755 start = get_tv_number_chk(&argvars[0], &error);
13756 if (argvars[1].v_type == VAR_UNKNOWN)
13758 end = start - 1;
13759 start = 0;
13761 else
13763 end = get_tv_number_chk(&argvars[1], &error);
13764 if (argvars[2].v_type != VAR_UNKNOWN)
13765 stride = get_tv_number_chk(&argvars[2], &error);
13768 if (error)
13769 return; /* type error; errmsg already given */
13770 if (stride == 0)
13771 EMSG(_("E726: Stride is zero"));
13772 else if (stride > 0 ? end + 1 < start : end - 1 > start)
13773 EMSG(_("E727: Start past end"));
13774 else
13776 if (rettv_list_alloc(rettv) == OK)
13777 for (i = start; stride > 0 ? i <= end : i >= end; i += stride)
13778 if (list_append_number(rettv->vval.v_list,
13779 (varnumber_T)i) == FAIL)
13780 break;
13785 * "readfile()" function
13787 static void
13788 f_readfile(argvars, rettv)
13789 typval_T *argvars;
13790 typval_T *rettv;
13792 int binary = FALSE;
13793 char_u *fname;
13794 FILE *fd;
13795 listitem_T *li;
13796 #define FREAD_SIZE 200 /* optimized for text lines */
13797 char_u buf[FREAD_SIZE];
13798 int readlen; /* size of last fread() */
13799 int buflen; /* nr of valid chars in buf[] */
13800 int filtd; /* how much in buf[] was NUL -> '\n' filtered */
13801 int tolist; /* first byte in buf[] still to be put in list */
13802 int chop; /* how many CR to chop off */
13803 char_u *prev = NULL; /* previously read bytes, if any */
13804 int prevlen = 0; /* length of "prev" if not NULL */
13805 char_u *s;
13806 int len;
13807 long maxline = MAXLNUM;
13808 long cnt = 0;
13810 if (argvars[1].v_type != VAR_UNKNOWN)
13812 if (STRCMP(get_tv_string(&argvars[1]), "b") == 0)
13813 binary = TRUE;
13814 if (argvars[2].v_type != VAR_UNKNOWN)
13815 maxline = get_tv_number(&argvars[2]);
13818 if (rettv_list_alloc(rettv) == FAIL)
13819 return;
13821 /* Always open the file in binary mode, library functions have a mind of
13822 * their own about CR-LF conversion. */
13823 fname = get_tv_string(&argvars[0]);
13824 if (*fname == NUL || (fd = mch_fopen((char *)fname, READBIN)) == NULL)
13826 EMSG2(_(e_notopen), *fname == NUL ? (char_u *)_("<empty>") : fname);
13827 return;
13830 filtd = 0;
13831 while (cnt < maxline || maxline < 0)
13833 readlen = (int)fread(buf + filtd, 1, FREAD_SIZE - filtd, fd);
13834 buflen = filtd + readlen;
13835 tolist = 0;
13836 for ( ; filtd < buflen || readlen <= 0; ++filtd)
13838 if (buf[filtd] == '\n' || readlen <= 0)
13840 /* Only when in binary mode add an empty list item when the
13841 * last line ends in a '\n'. */
13842 if (!binary && readlen == 0 && filtd == 0)
13843 break;
13845 /* Found end-of-line or end-of-file: add a text line to the
13846 * list. */
13847 chop = 0;
13848 if (!binary)
13849 while (filtd - chop - 1 >= tolist
13850 && buf[filtd - chop - 1] == '\r')
13851 ++chop;
13852 len = filtd - tolist - chop;
13853 if (prev == NULL)
13854 s = vim_strnsave(buf + tolist, len);
13855 else
13857 s = alloc((unsigned)(prevlen + len + 1));
13858 if (s != NULL)
13860 mch_memmove(s, prev, prevlen);
13861 vim_free(prev);
13862 prev = NULL;
13863 mch_memmove(s + prevlen, buf + tolist, len);
13864 s[prevlen + len] = NUL;
13867 tolist = filtd + 1;
13869 li = listitem_alloc();
13870 if (li == NULL)
13872 vim_free(s);
13873 break;
13875 li->li_tv.v_type = VAR_STRING;
13876 li->li_tv.v_lock = 0;
13877 li->li_tv.vval.v_string = s;
13878 list_append(rettv->vval.v_list, li);
13880 if (++cnt >= maxline && maxline >= 0)
13881 break;
13882 if (readlen <= 0)
13883 break;
13885 else if (buf[filtd] == NUL)
13886 buf[filtd] = '\n';
13888 if (readlen <= 0)
13889 break;
13891 if (tolist == 0)
13893 /* "buf" is full, need to move text to an allocated buffer */
13894 if (prev == NULL)
13896 prev = vim_strnsave(buf, buflen);
13897 prevlen = buflen;
13899 else
13901 s = alloc((unsigned)(prevlen + buflen));
13902 if (s != NULL)
13904 mch_memmove(s, prev, prevlen);
13905 mch_memmove(s + prevlen, buf, buflen);
13906 vim_free(prev);
13907 prev = s;
13908 prevlen += buflen;
13911 filtd = 0;
13913 else
13915 mch_memmove(buf, buf + tolist, buflen - tolist);
13916 filtd -= tolist;
13921 * For a negative line count use only the lines at the end of the file,
13922 * free the rest.
13924 if (maxline < 0)
13925 while (cnt > -maxline)
13927 listitem_remove(rettv->vval.v_list, rettv->vval.v_list->lv_first);
13928 --cnt;
13931 vim_free(prev);
13932 fclose(fd);
13935 #if defined(FEAT_RELTIME)
13936 static int list2proftime __ARGS((typval_T *arg, proftime_T *tm));
13939 * Convert a List to proftime_T.
13940 * Return FAIL when there is something wrong.
13942 static int
13943 list2proftime(arg, tm)
13944 typval_T *arg;
13945 proftime_T *tm;
13947 long n1, n2;
13948 int error = FALSE;
13950 if (arg->v_type != VAR_LIST || arg->vval.v_list == NULL
13951 || arg->vval.v_list->lv_len != 2)
13952 return FAIL;
13953 n1 = list_find_nr(arg->vval.v_list, 0L, &error);
13954 n2 = list_find_nr(arg->vval.v_list, 1L, &error);
13955 # ifdef WIN3264
13956 tm->HighPart = n1;
13957 tm->LowPart = n2;
13958 # else
13959 tm->tv_sec = n1;
13960 tm->tv_usec = n2;
13961 # endif
13962 return error ? FAIL : OK;
13964 #endif /* FEAT_RELTIME */
13967 * "reltime()" function
13969 static void
13970 f_reltime(argvars, rettv)
13971 typval_T *argvars;
13972 typval_T *rettv;
13974 #ifdef FEAT_RELTIME
13975 proftime_T res;
13976 proftime_T start;
13978 if (argvars[0].v_type == VAR_UNKNOWN)
13980 /* No arguments: get current time. */
13981 profile_start(&res);
13983 else if (argvars[1].v_type == VAR_UNKNOWN)
13985 if (list2proftime(&argvars[0], &res) == FAIL)
13986 return;
13987 profile_end(&res);
13989 else
13991 /* Two arguments: compute the difference. */
13992 if (list2proftime(&argvars[0], &start) == FAIL
13993 || list2proftime(&argvars[1], &res) == FAIL)
13994 return;
13995 profile_sub(&res, &start);
13998 if (rettv_list_alloc(rettv) == OK)
14000 long n1, n2;
14002 # ifdef WIN3264
14003 n1 = res.HighPart;
14004 n2 = res.LowPart;
14005 # else
14006 n1 = res.tv_sec;
14007 n2 = res.tv_usec;
14008 # endif
14009 list_append_number(rettv->vval.v_list, (varnumber_T)n1);
14010 list_append_number(rettv->vval.v_list, (varnumber_T)n2);
14012 #endif
14016 * "reltimestr()" function
14018 static void
14019 f_reltimestr(argvars, rettv)
14020 typval_T *argvars;
14021 typval_T *rettv;
14023 #ifdef FEAT_RELTIME
14024 proftime_T tm;
14025 #endif
14027 rettv->v_type = VAR_STRING;
14028 rettv->vval.v_string = NULL;
14029 #ifdef FEAT_RELTIME
14030 if (list2proftime(&argvars[0], &tm) == OK)
14031 rettv->vval.v_string = vim_strsave((char_u *)profile_msg(&tm));
14032 #endif
14035 #if defined(FEAT_CLIENTSERVER) && defined(FEAT_X11)
14036 static void make_connection __ARGS((void));
14037 static int check_connection __ARGS((void));
14039 static void
14040 make_connection()
14042 if (X_DISPLAY == NULL
14043 # ifdef FEAT_GUI
14044 && !gui.in_use
14045 # endif
14048 x_force_connect = TRUE;
14049 setup_term_clip();
14050 x_force_connect = FALSE;
14054 static int
14055 check_connection()
14057 make_connection();
14058 if (X_DISPLAY == NULL)
14060 EMSG(_("E240: No connection to Vim server"));
14061 return FAIL;
14063 return OK;
14065 #endif
14067 #ifdef FEAT_CLIENTSERVER
14068 static void remote_common __ARGS((typval_T *argvars, typval_T *rettv, int expr));
14070 static void
14071 remote_common(argvars, rettv, expr)
14072 typval_T *argvars;
14073 typval_T *rettv;
14074 int expr;
14076 char_u *server_name;
14077 char_u *keys;
14078 char_u *r = NULL;
14079 char_u buf[NUMBUFLEN];
14080 # ifdef WIN32
14081 HWND w;
14082 # else
14083 Window w;
14084 # endif
14086 if (check_restricted() || check_secure())
14087 return;
14089 # ifdef FEAT_X11
14090 if (check_connection() == FAIL)
14091 return;
14092 # endif
14094 server_name = get_tv_string_chk(&argvars[0]);
14095 if (server_name == NULL)
14096 return; /* type error; errmsg already given */
14097 keys = get_tv_string_buf(&argvars[1], buf);
14098 # ifdef WIN32
14099 if (serverSendToVim(server_name, keys, &r, &w, expr, TRUE) < 0)
14100 # else
14101 if (serverSendToVim(X_DISPLAY, server_name, keys, &r, &w, expr, 0, TRUE)
14102 < 0)
14103 # endif
14105 if (r != NULL)
14106 EMSG(r); /* sending worked but evaluation failed */
14107 else
14108 EMSG2(_("E241: Unable to send to %s"), server_name);
14109 return;
14112 rettv->vval.v_string = r;
14114 if (argvars[2].v_type != VAR_UNKNOWN)
14116 dictitem_T v;
14117 char_u str[30];
14118 char_u *idvar;
14120 sprintf((char *)str, PRINTF_HEX_LONG_U, (long_u)w);
14121 v.di_tv.v_type = VAR_STRING;
14122 v.di_tv.vval.v_string = vim_strsave(str);
14123 idvar = get_tv_string_chk(&argvars[2]);
14124 if (idvar != NULL)
14125 set_var(idvar, &v.di_tv, FALSE);
14126 vim_free(v.di_tv.vval.v_string);
14129 #endif
14132 * "remote_expr()" function
14134 /*ARGSUSED*/
14135 static void
14136 f_remote_expr(argvars, rettv)
14137 typval_T *argvars;
14138 typval_T *rettv;
14140 rettv->v_type = VAR_STRING;
14141 rettv->vval.v_string = NULL;
14142 #ifdef FEAT_CLIENTSERVER
14143 remote_common(argvars, rettv, TRUE);
14144 #endif
14148 * "remote_foreground()" function
14150 /*ARGSUSED*/
14151 static void
14152 f_remote_foreground(argvars, rettv)
14153 typval_T *argvars;
14154 typval_T *rettv;
14156 #ifdef FEAT_CLIENTSERVER
14157 # ifdef WIN32
14158 /* On Win32 it's done in this application. */
14160 char_u *server_name = get_tv_string_chk(&argvars[0]);
14162 if (server_name != NULL)
14163 serverForeground(server_name);
14165 # else
14166 /* Send a foreground() expression to the server. */
14167 argvars[1].v_type = VAR_STRING;
14168 argvars[1].vval.v_string = vim_strsave((char_u *)"foreground()");
14169 argvars[2].v_type = VAR_UNKNOWN;
14170 remote_common(argvars, rettv, TRUE);
14171 vim_free(argvars[1].vval.v_string);
14172 # endif
14173 #endif
14176 /*ARGSUSED*/
14177 static void
14178 f_remote_peek(argvars, rettv)
14179 typval_T *argvars;
14180 typval_T *rettv;
14182 #ifdef FEAT_CLIENTSERVER
14183 dictitem_T v;
14184 char_u *s = NULL;
14185 # ifdef WIN32
14186 long_u n = 0;
14187 # endif
14188 char_u *serverid;
14190 if (check_restricted() || check_secure())
14192 rettv->vval.v_number = -1;
14193 return;
14195 serverid = get_tv_string_chk(&argvars[0]);
14196 if (serverid == NULL)
14198 rettv->vval.v_number = -1;
14199 return; /* type error; errmsg already given */
14201 # ifdef WIN32
14202 sscanf(serverid, SCANF_HEX_LONG_U, &n);
14203 if (n == 0)
14204 rettv->vval.v_number = -1;
14205 else
14207 s = serverGetReply((HWND)n, FALSE, FALSE, FALSE);
14208 rettv->vval.v_number = (s != NULL);
14210 # else
14211 if (check_connection() == FAIL)
14212 return;
14214 rettv->vval.v_number = serverPeekReply(X_DISPLAY,
14215 serverStrToWin(serverid), &s);
14216 # endif
14218 if (argvars[1].v_type != VAR_UNKNOWN && rettv->vval.v_number > 0)
14220 char_u *retvar;
14222 v.di_tv.v_type = VAR_STRING;
14223 v.di_tv.vval.v_string = vim_strsave(s);
14224 retvar = get_tv_string_chk(&argvars[1]);
14225 if (retvar != NULL)
14226 set_var(retvar, &v.di_tv, FALSE);
14227 vim_free(v.di_tv.vval.v_string);
14229 #else
14230 rettv->vval.v_number = -1;
14231 #endif
14234 /*ARGSUSED*/
14235 static void
14236 f_remote_read(argvars, rettv)
14237 typval_T *argvars;
14238 typval_T *rettv;
14240 char_u *r = NULL;
14242 #ifdef FEAT_CLIENTSERVER
14243 char_u *serverid = get_tv_string_chk(&argvars[0]);
14245 if (serverid != NULL && !check_restricted() && !check_secure())
14247 # ifdef WIN32
14248 /* The server's HWND is encoded in the 'id' parameter */
14249 long_u n = 0;
14251 sscanf(serverid, SCANF_HEX_LONG_U, &n);
14252 if (n != 0)
14253 r = serverGetReply((HWND)n, FALSE, TRUE, TRUE);
14254 if (r == NULL)
14255 # else
14256 if (check_connection() == FAIL || serverReadReply(X_DISPLAY,
14257 serverStrToWin(serverid), &r, FALSE) < 0)
14258 # endif
14259 EMSG(_("E277: Unable to read a server reply"));
14261 #endif
14262 rettv->v_type = VAR_STRING;
14263 rettv->vval.v_string = r;
14267 * "remote_send()" function
14269 /*ARGSUSED*/
14270 static void
14271 f_remote_send(argvars, rettv)
14272 typval_T *argvars;
14273 typval_T *rettv;
14275 rettv->v_type = VAR_STRING;
14276 rettv->vval.v_string = NULL;
14277 #ifdef FEAT_CLIENTSERVER
14278 remote_common(argvars, rettv, FALSE);
14279 #endif
14283 * "remove()" function
14285 static void
14286 f_remove(argvars, rettv)
14287 typval_T *argvars;
14288 typval_T *rettv;
14290 list_T *l;
14291 listitem_T *item, *item2;
14292 listitem_T *li;
14293 long idx;
14294 long end;
14295 char_u *key;
14296 dict_T *d;
14297 dictitem_T *di;
14299 if (argvars[0].v_type == VAR_DICT)
14301 if (argvars[2].v_type != VAR_UNKNOWN)
14302 EMSG2(_(e_toomanyarg), "remove()");
14303 else if ((d = argvars[0].vval.v_dict) != NULL
14304 && !tv_check_lock(d->dv_lock, (char_u *)"remove() argument"))
14306 key = get_tv_string_chk(&argvars[1]);
14307 if (key != NULL)
14309 di = dict_find(d, key, -1);
14310 if (di == NULL)
14311 EMSG2(_(e_dictkey), key);
14312 else
14314 *rettv = di->di_tv;
14315 init_tv(&di->di_tv);
14316 dictitem_remove(d, di);
14321 else if (argvars[0].v_type != VAR_LIST)
14322 EMSG2(_(e_listdictarg), "remove()");
14323 else if ((l = argvars[0].vval.v_list) != NULL
14324 && !tv_check_lock(l->lv_lock, (char_u *)"remove() argument"))
14326 int error = FALSE;
14328 idx = get_tv_number_chk(&argvars[1], &error);
14329 if (error)
14330 ; /* type error: do nothing, errmsg already given */
14331 else if ((item = list_find(l, idx)) == NULL)
14332 EMSGN(_(e_listidx), idx);
14333 else
14335 if (argvars[2].v_type == VAR_UNKNOWN)
14337 /* Remove one item, return its value. */
14338 list_remove(l, item, item);
14339 *rettv = item->li_tv;
14340 vim_free(item);
14342 else
14344 /* Remove range of items, return list with values. */
14345 end = get_tv_number_chk(&argvars[2], &error);
14346 if (error)
14347 ; /* type error: do nothing */
14348 else if ((item2 = list_find(l, end)) == NULL)
14349 EMSGN(_(e_listidx), end);
14350 else
14352 int cnt = 0;
14354 for (li = item; li != NULL; li = li->li_next)
14356 ++cnt;
14357 if (li == item2)
14358 break;
14360 if (li == NULL) /* didn't find "item2" after "item" */
14361 EMSG(_(e_invrange));
14362 else
14364 list_remove(l, item, item2);
14365 if (rettv_list_alloc(rettv) == OK)
14367 l = rettv->vval.v_list;
14368 l->lv_first = item;
14369 l->lv_last = item2;
14370 item->li_prev = NULL;
14371 item2->li_next = NULL;
14372 l->lv_len = cnt;
14382 * "rename({from}, {to})" function
14384 static void
14385 f_rename(argvars, rettv)
14386 typval_T *argvars;
14387 typval_T *rettv;
14389 char_u buf[NUMBUFLEN];
14391 if (check_restricted() || check_secure())
14392 rettv->vval.v_number = -1;
14393 else
14394 rettv->vval.v_number = vim_rename(get_tv_string(&argvars[0]),
14395 get_tv_string_buf(&argvars[1], buf));
14399 * "repeat()" function
14401 /*ARGSUSED*/
14402 static void
14403 f_repeat(argvars, rettv)
14404 typval_T *argvars;
14405 typval_T *rettv;
14407 char_u *p;
14408 int n;
14409 int slen;
14410 int len;
14411 char_u *r;
14412 int i;
14414 n = get_tv_number(&argvars[1]);
14415 if (argvars[0].v_type == VAR_LIST)
14417 if (rettv_list_alloc(rettv) == OK && argvars[0].vval.v_list != NULL)
14418 while (n-- > 0)
14419 if (list_extend(rettv->vval.v_list,
14420 argvars[0].vval.v_list, NULL) == FAIL)
14421 break;
14423 else
14425 p = get_tv_string(&argvars[0]);
14426 rettv->v_type = VAR_STRING;
14427 rettv->vval.v_string = NULL;
14429 slen = (int)STRLEN(p);
14430 len = slen * n;
14431 if (len <= 0)
14432 return;
14434 r = alloc(len + 1);
14435 if (r != NULL)
14437 for (i = 0; i < n; i++)
14438 mch_memmove(r + i * slen, p, (size_t)slen);
14439 r[len] = NUL;
14442 rettv->vval.v_string = r;
14447 * "resolve()" function
14449 static void
14450 f_resolve(argvars, rettv)
14451 typval_T *argvars;
14452 typval_T *rettv;
14454 char_u *p;
14456 p = get_tv_string(&argvars[0]);
14457 #ifdef FEAT_SHORTCUT
14459 char_u *v = NULL;
14461 v = mch_resolve_shortcut(p);
14462 if (v != NULL)
14463 rettv->vval.v_string = v;
14464 else
14465 rettv->vval.v_string = vim_strsave(p);
14467 #else
14468 # ifdef HAVE_READLINK
14470 char_u buf[MAXPATHL + 1];
14471 char_u *cpy;
14472 int len;
14473 char_u *remain = NULL;
14474 char_u *q;
14475 int is_relative_to_current = FALSE;
14476 int has_trailing_pathsep = FALSE;
14477 int limit = 100;
14479 p = vim_strsave(p);
14481 if (p[0] == '.' && (vim_ispathsep(p[1])
14482 || (p[1] == '.' && (vim_ispathsep(p[2])))))
14483 is_relative_to_current = TRUE;
14485 len = STRLEN(p);
14486 if (len > 0 && after_pathsep(p, p + len))
14487 has_trailing_pathsep = TRUE;
14489 q = getnextcomp(p);
14490 if (*q != NUL)
14492 /* Separate the first path component in "p", and keep the
14493 * remainder (beginning with the path separator). */
14494 remain = vim_strsave(q - 1);
14495 q[-1] = NUL;
14498 for (;;)
14500 for (;;)
14502 len = readlink((char *)p, (char *)buf, MAXPATHL);
14503 if (len <= 0)
14504 break;
14505 buf[len] = NUL;
14507 if (limit-- == 0)
14509 vim_free(p);
14510 vim_free(remain);
14511 EMSG(_("E655: Too many symbolic links (cycle?)"));
14512 rettv->vval.v_string = NULL;
14513 goto fail;
14516 /* Ensure that the result will have a trailing path separator
14517 * if the argument has one. */
14518 if (remain == NULL && has_trailing_pathsep)
14519 add_pathsep(buf);
14521 /* Separate the first path component in the link value and
14522 * concatenate the remainders. */
14523 q = getnextcomp(vim_ispathsep(*buf) ? buf + 1 : buf);
14524 if (*q != NUL)
14526 if (remain == NULL)
14527 remain = vim_strsave(q - 1);
14528 else
14530 cpy = concat_str(q - 1, remain);
14531 if (cpy != NULL)
14533 vim_free(remain);
14534 remain = cpy;
14537 q[-1] = NUL;
14540 q = gettail(p);
14541 if (q > p && *q == NUL)
14543 /* Ignore trailing path separator. */
14544 q[-1] = NUL;
14545 q = gettail(p);
14547 if (q > p && !mch_isFullName(buf))
14549 /* symlink is relative to directory of argument */
14550 cpy = alloc((unsigned)(STRLEN(p) + STRLEN(buf) + 1));
14551 if (cpy != NULL)
14553 STRCPY(cpy, p);
14554 STRCPY(gettail(cpy), buf);
14555 vim_free(p);
14556 p = cpy;
14559 else
14561 vim_free(p);
14562 p = vim_strsave(buf);
14566 if (remain == NULL)
14567 break;
14569 /* Append the first path component of "remain" to "p". */
14570 q = getnextcomp(remain + 1);
14571 len = q - remain - (*q != NUL);
14572 cpy = vim_strnsave(p, STRLEN(p) + len);
14573 if (cpy != NULL)
14575 STRNCAT(cpy, remain, len);
14576 vim_free(p);
14577 p = cpy;
14579 /* Shorten "remain". */
14580 if (*q != NUL)
14581 STRMOVE(remain, q - 1);
14582 else
14584 vim_free(remain);
14585 remain = NULL;
14589 /* If the result is a relative path name, make it explicitly relative to
14590 * the current directory if and only if the argument had this form. */
14591 if (!vim_ispathsep(*p))
14593 if (is_relative_to_current
14594 && *p != NUL
14595 && !(p[0] == '.'
14596 && (p[1] == NUL
14597 || vim_ispathsep(p[1])
14598 || (p[1] == '.'
14599 && (p[2] == NUL
14600 || vim_ispathsep(p[2]))))))
14602 /* Prepend "./". */
14603 cpy = concat_str((char_u *)"./", p);
14604 if (cpy != NULL)
14606 vim_free(p);
14607 p = cpy;
14610 else if (!is_relative_to_current)
14612 /* Strip leading "./". */
14613 q = p;
14614 while (q[0] == '.' && vim_ispathsep(q[1]))
14615 q += 2;
14616 if (q > p)
14617 STRMOVE(p, p + 2);
14621 /* Ensure that the result will have no trailing path separator
14622 * if the argument had none. But keep "/" or "//". */
14623 if (!has_trailing_pathsep)
14625 q = p + STRLEN(p);
14626 if (after_pathsep(p, q))
14627 *gettail_sep(p) = NUL;
14630 rettv->vval.v_string = p;
14632 # else
14633 rettv->vval.v_string = vim_strsave(p);
14634 # endif
14635 #endif
14637 simplify_filename(rettv->vval.v_string);
14639 #ifdef HAVE_READLINK
14640 fail:
14641 #endif
14642 rettv->v_type = VAR_STRING;
14646 * "reverse({list})" function
14648 static void
14649 f_reverse(argvars, rettv)
14650 typval_T *argvars;
14651 typval_T *rettv;
14653 list_T *l;
14654 listitem_T *li, *ni;
14656 if (argvars[0].v_type != VAR_LIST)
14657 EMSG2(_(e_listarg), "reverse()");
14658 else if ((l = argvars[0].vval.v_list) != NULL
14659 && !tv_check_lock(l->lv_lock, (char_u *)"reverse()"))
14661 li = l->lv_last;
14662 l->lv_first = l->lv_last = NULL;
14663 l->lv_len = 0;
14664 while (li != NULL)
14666 ni = li->li_prev;
14667 list_append(l, li);
14668 li = ni;
14670 rettv->vval.v_list = l;
14671 rettv->v_type = VAR_LIST;
14672 ++l->lv_refcount;
14673 l->lv_idx = l->lv_len - l->lv_idx - 1;
14677 #define SP_NOMOVE 0x01 /* don't move cursor */
14678 #define SP_REPEAT 0x02 /* repeat to find outer pair */
14679 #define SP_RETCOUNT 0x04 /* return matchcount */
14680 #define SP_SETPCMARK 0x08 /* set previous context mark */
14681 #define SP_START 0x10 /* accept match at start position */
14682 #define SP_SUBPAT 0x20 /* return nr of matching sub-pattern */
14683 #define SP_END 0x40 /* leave cursor at end of match */
14685 static int get_search_arg __ARGS((typval_T *varp, int *flagsp));
14688 * Get flags for a search function.
14689 * Possibly sets "p_ws".
14690 * Returns BACKWARD, FORWARD or zero (for an error).
14692 static int
14693 get_search_arg(varp, flagsp)
14694 typval_T *varp;
14695 int *flagsp;
14697 int dir = FORWARD;
14698 char_u *flags;
14699 char_u nbuf[NUMBUFLEN];
14700 int mask;
14702 if (varp->v_type != VAR_UNKNOWN)
14704 flags = get_tv_string_buf_chk(varp, nbuf);
14705 if (flags == NULL)
14706 return 0; /* type error; errmsg already given */
14707 while (*flags != NUL)
14709 switch (*flags)
14711 case 'b': dir = BACKWARD; break;
14712 case 'w': p_ws = TRUE; break;
14713 case 'W': p_ws = FALSE; break;
14714 default: mask = 0;
14715 if (flagsp != NULL)
14716 switch (*flags)
14718 case 'c': mask = SP_START; break;
14719 case 'e': mask = SP_END; break;
14720 case 'm': mask = SP_RETCOUNT; break;
14721 case 'n': mask = SP_NOMOVE; break;
14722 case 'p': mask = SP_SUBPAT; break;
14723 case 'r': mask = SP_REPEAT; break;
14724 case 's': mask = SP_SETPCMARK; break;
14726 if (mask == 0)
14728 EMSG2(_(e_invarg2), flags);
14729 dir = 0;
14731 else
14732 *flagsp |= mask;
14734 if (dir == 0)
14735 break;
14736 ++flags;
14739 return dir;
14743 * Shared by search() and searchpos() functions
14745 static int
14746 search_cmn(argvars, match_pos, flagsp)
14747 typval_T *argvars;
14748 pos_T *match_pos;
14749 int *flagsp;
14751 int flags;
14752 char_u *pat;
14753 pos_T pos;
14754 pos_T save_cursor;
14755 int save_p_ws = p_ws;
14756 int dir;
14757 int retval = 0; /* default: FAIL */
14758 long lnum_stop = 0;
14759 proftime_T tm;
14760 #ifdef FEAT_RELTIME
14761 long time_limit = 0;
14762 #endif
14763 int options = SEARCH_KEEP;
14764 int subpatnum;
14766 pat = get_tv_string(&argvars[0]);
14767 dir = get_search_arg(&argvars[1], flagsp); /* may set p_ws */
14768 if (dir == 0)
14769 goto theend;
14770 flags = *flagsp;
14771 if (flags & SP_START)
14772 options |= SEARCH_START;
14773 if (flags & SP_END)
14774 options |= SEARCH_END;
14776 /* Optional arguments: line number to stop searching and timeout. */
14777 if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN)
14779 lnum_stop = get_tv_number_chk(&argvars[2], NULL);
14780 if (lnum_stop < 0)
14781 goto theend;
14782 #ifdef FEAT_RELTIME
14783 if (argvars[3].v_type != VAR_UNKNOWN)
14785 time_limit = get_tv_number_chk(&argvars[3], NULL);
14786 if (time_limit < 0)
14787 goto theend;
14789 #endif
14792 #ifdef FEAT_RELTIME
14793 /* Set the time limit, if there is one. */
14794 profile_setlimit(time_limit, &tm);
14795 #endif
14798 * This function does not accept SP_REPEAT and SP_RETCOUNT flags.
14799 * Check to make sure only those flags are set.
14800 * Also, Only the SP_NOMOVE or the SP_SETPCMARK flag can be set. Both
14801 * flags cannot be set. Check for that condition also.
14803 if (((flags & (SP_REPEAT | SP_RETCOUNT)) != 0)
14804 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
14806 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
14807 goto theend;
14810 pos = save_cursor = curwin->w_cursor;
14811 subpatnum = searchit(curwin, curbuf, &pos, dir, pat, 1L,
14812 options, RE_SEARCH, (linenr_T)lnum_stop, &tm);
14813 if (subpatnum != FAIL)
14815 if (flags & SP_SUBPAT)
14816 retval = subpatnum;
14817 else
14818 retval = pos.lnum;
14819 if (flags & SP_SETPCMARK)
14820 setpcmark();
14821 curwin->w_cursor = pos;
14822 if (match_pos != NULL)
14824 /* Store the match cursor position */
14825 match_pos->lnum = pos.lnum;
14826 match_pos->col = pos.col + 1;
14828 /* "/$" will put the cursor after the end of the line, may need to
14829 * correct that here */
14830 check_cursor();
14833 /* If 'n' flag is used: restore cursor position. */
14834 if (flags & SP_NOMOVE)
14835 curwin->w_cursor = save_cursor;
14836 else
14837 curwin->w_set_curswant = TRUE;
14838 theend:
14839 p_ws = save_p_ws;
14841 return retval;
14844 #ifdef FEAT_FLOAT
14846 * "round({float})" function
14848 static void
14849 f_round(argvars, rettv)
14850 typval_T *argvars;
14851 typval_T *rettv;
14853 float_T f;
14855 rettv->v_type = VAR_FLOAT;
14856 if (get_float_arg(argvars, &f) == OK)
14857 /* round() is not in C90, use ceil() or floor() instead. */
14858 rettv->vval.v_float = f > 0 ? floor(f + 0.5) : ceil(f - 0.5);
14859 else
14860 rettv->vval.v_float = 0.0;
14862 #endif
14865 * "search()" function
14867 static void
14868 f_search(argvars, rettv)
14869 typval_T *argvars;
14870 typval_T *rettv;
14872 int flags = 0;
14874 rettv->vval.v_number = search_cmn(argvars, NULL, &flags);
14878 * "searchdecl()" function
14880 static void
14881 f_searchdecl(argvars, rettv)
14882 typval_T *argvars;
14883 typval_T *rettv;
14885 int locally = 1;
14886 int thisblock = 0;
14887 int error = FALSE;
14888 char_u *name;
14890 rettv->vval.v_number = 1; /* default: FAIL */
14892 name = get_tv_string_chk(&argvars[0]);
14893 if (argvars[1].v_type != VAR_UNKNOWN)
14895 locally = get_tv_number_chk(&argvars[1], &error) == 0;
14896 if (!error && argvars[2].v_type != VAR_UNKNOWN)
14897 thisblock = get_tv_number_chk(&argvars[2], &error) != 0;
14899 if (!error && name != NULL)
14900 rettv->vval.v_number = find_decl(name, (int)STRLEN(name),
14901 locally, thisblock, SEARCH_KEEP) == FAIL;
14905 * Used by searchpair() and searchpairpos()
14907 static int
14908 searchpair_cmn(argvars, match_pos)
14909 typval_T *argvars;
14910 pos_T *match_pos;
14912 char_u *spat, *mpat, *epat;
14913 char_u *skip;
14914 int save_p_ws = p_ws;
14915 int dir;
14916 int flags = 0;
14917 char_u nbuf1[NUMBUFLEN];
14918 char_u nbuf2[NUMBUFLEN];
14919 char_u nbuf3[NUMBUFLEN];
14920 int retval = 0; /* default: FAIL */
14921 long lnum_stop = 0;
14922 long time_limit = 0;
14924 /* Get the three pattern arguments: start, middle, end. */
14925 spat = get_tv_string_chk(&argvars[0]);
14926 mpat = get_tv_string_buf_chk(&argvars[1], nbuf1);
14927 epat = get_tv_string_buf_chk(&argvars[2], nbuf2);
14928 if (spat == NULL || mpat == NULL || epat == NULL)
14929 goto theend; /* type error */
14931 /* Handle the optional fourth argument: flags */
14932 dir = get_search_arg(&argvars[3], &flags); /* may set p_ws */
14933 if (dir == 0)
14934 goto theend;
14936 /* Don't accept SP_END or SP_SUBPAT.
14937 * Only one of the SP_NOMOVE or SP_SETPCMARK flags can be set.
14939 if ((flags & (SP_END | SP_SUBPAT)) != 0
14940 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
14942 EMSG2(_(e_invarg2), get_tv_string(&argvars[3]));
14943 goto theend;
14946 /* Using 'r' implies 'W', otherwise it doesn't work. */
14947 if (flags & SP_REPEAT)
14948 p_ws = FALSE;
14950 /* Optional fifth argument: skip expression */
14951 if (argvars[3].v_type == VAR_UNKNOWN
14952 || argvars[4].v_type == VAR_UNKNOWN)
14953 skip = (char_u *)"";
14954 else
14956 skip = get_tv_string_buf_chk(&argvars[4], nbuf3);
14957 if (argvars[5].v_type != VAR_UNKNOWN)
14959 lnum_stop = get_tv_number_chk(&argvars[5], NULL);
14960 if (lnum_stop < 0)
14961 goto theend;
14962 #ifdef FEAT_RELTIME
14963 if (argvars[6].v_type != VAR_UNKNOWN)
14965 time_limit = get_tv_number_chk(&argvars[6], NULL);
14966 if (time_limit < 0)
14967 goto theend;
14969 #endif
14972 if (skip == NULL)
14973 goto theend; /* type error */
14975 retval = do_searchpair(spat, mpat, epat, dir, skip, flags,
14976 match_pos, lnum_stop, time_limit);
14978 theend:
14979 p_ws = save_p_ws;
14981 return retval;
14985 * "searchpair()" function
14987 static void
14988 f_searchpair(argvars, rettv)
14989 typval_T *argvars;
14990 typval_T *rettv;
14992 rettv->vval.v_number = searchpair_cmn(argvars, NULL);
14996 * "searchpairpos()" function
14998 static void
14999 f_searchpairpos(argvars, rettv)
15000 typval_T *argvars;
15001 typval_T *rettv;
15003 pos_T match_pos;
15004 int lnum = 0;
15005 int col = 0;
15007 if (rettv_list_alloc(rettv) == FAIL)
15008 return;
15010 if (searchpair_cmn(argvars, &match_pos) > 0)
15012 lnum = match_pos.lnum;
15013 col = match_pos.col;
15016 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
15017 list_append_number(rettv->vval.v_list, (varnumber_T)col);
15021 * Search for a start/middle/end thing.
15022 * Used by searchpair(), see its documentation for the details.
15023 * Returns 0 or -1 for no match,
15025 long
15026 do_searchpair(spat, mpat, epat, dir, skip, flags, match_pos,
15027 lnum_stop, time_limit)
15028 char_u *spat; /* start pattern */
15029 char_u *mpat; /* middle pattern */
15030 char_u *epat; /* end pattern */
15031 int dir; /* BACKWARD or FORWARD */
15032 char_u *skip; /* skip expression */
15033 int flags; /* SP_SETPCMARK and other SP_ values */
15034 pos_T *match_pos;
15035 linenr_T lnum_stop; /* stop at this line if not zero */
15036 long time_limit; /* stop after this many msec */
15038 char_u *save_cpo;
15039 char_u *pat, *pat2 = NULL, *pat3 = NULL;
15040 long retval = 0;
15041 pos_T pos;
15042 pos_T firstpos;
15043 pos_T foundpos;
15044 pos_T save_cursor;
15045 pos_T save_pos;
15046 int n;
15047 int r;
15048 int nest = 1;
15049 int err;
15050 int options = SEARCH_KEEP;
15051 proftime_T tm;
15053 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
15054 save_cpo = p_cpo;
15055 p_cpo = empty_option;
15057 #ifdef FEAT_RELTIME
15058 /* Set the time limit, if there is one. */
15059 profile_setlimit(time_limit, &tm);
15060 #endif
15062 /* Make two search patterns: start/end (pat2, for in nested pairs) and
15063 * start/middle/end (pat3, for the top pair). */
15064 pat2 = alloc((unsigned)(STRLEN(spat) + STRLEN(epat) + 15));
15065 pat3 = alloc((unsigned)(STRLEN(spat) + STRLEN(mpat) + STRLEN(epat) + 23));
15066 if (pat2 == NULL || pat3 == NULL)
15067 goto theend;
15068 sprintf((char *)pat2, "\\(%s\\m\\)\\|\\(%s\\m\\)", spat, epat);
15069 if (*mpat == NUL)
15070 STRCPY(pat3, pat2);
15071 else
15072 sprintf((char *)pat3, "\\(%s\\m\\)\\|\\(%s\\m\\)\\|\\(%s\\m\\)",
15073 spat, epat, mpat);
15074 if (flags & SP_START)
15075 options |= SEARCH_START;
15077 save_cursor = curwin->w_cursor;
15078 pos = curwin->w_cursor;
15079 clearpos(&firstpos);
15080 clearpos(&foundpos);
15081 pat = pat3;
15082 for (;;)
15084 n = searchit(curwin, curbuf, &pos, dir, pat, 1L,
15085 options, RE_SEARCH, lnum_stop, &tm);
15086 if (n == FAIL || (firstpos.lnum != 0 && equalpos(pos, firstpos)))
15087 /* didn't find it or found the first match again: FAIL */
15088 break;
15090 if (firstpos.lnum == 0)
15091 firstpos = pos;
15092 if (equalpos(pos, foundpos))
15094 /* Found the same position again. Can happen with a pattern that
15095 * has "\zs" at the end and searching backwards. Advance one
15096 * character and try again. */
15097 if (dir == BACKWARD)
15098 decl(&pos);
15099 else
15100 incl(&pos);
15102 foundpos = pos;
15104 /* clear the start flag to avoid getting stuck here */
15105 options &= ~SEARCH_START;
15107 /* If the skip pattern matches, ignore this match. */
15108 if (*skip != NUL)
15110 save_pos = curwin->w_cursor;
15111 curwin->w_cursor = pos;
15112 r = eval_to_bool(skip, &err, NULL, FALSE);
15113 curwin->w_cursor = save_pos;
15114 if (err)
15116 /* Evaluating {skip} caused an error, break here. */
15117 curwin->w_cursor = save_cursor;
15118 retval = -1;
15119 break;
15121 if (r)
15122 continue;
15125 if ((dir == BACKWARD && n == 3) || (dir == FORWARD && n == 2))
15127 /* Found end when searching backwards or start when searching
15128 * forward: nested pair. */
15129 ++nest;
15130 pat = pat2; /* nested, don't search for middle */
15132 else
15134 /* Found end when searching forward or start when searching
15135 * backward: end of (nested) pair; or found middle in outer pair. */
15136 if (--nest == 1)
15137 pat = pat3; /* outer level, search for middle */
15140 if (nest == 0)
15142 /* Found the match: return matchcount or line number. */
15143 if (flags & SP_RETCOUNT)
15144 ++retval;
15145 else
15146 retval = pos.lnum;
15147 if (flags & SP_SETPCMARK)
15148 setpcmark();
15149 curwin->w_cursor = pos;
15150 if (!(flags & SP_REPEAT))
15151 break;
15152 nest = 1; /* search for next unmatched */
15156 if (match_pos != NULL)
15158 /* Store the match cursor position */
15159 match_pos->lnum = curwin->w_cursor.lnum;
15160 match_pos->col = curwin->w_cursor.col + 1;
15163 /* If 'n' flag is used or search failed: restore cursor position. */
15164 if ((flags & SP_NOMOVE) || retval == 0)
15165 curwin->w_cursor = save_cursor;
15167 theend:
15168 vim_free(pat2);
15169 vim_free(pat3);
15170 if (p_cpo == empty_option)
15171 p_cpo = save_cpo;
15172 else
15173 /* Darn, evaluating the {skip} expression changed the value. */
15174 free_string_option(save_cpo);
15176 return retval;
15180 * "searchpos()" function
15182 static void
15183 f_searchpos(argvars, rettv)
15184 typval_T *argvars;
15185 typval_T *rettv;
15187 pos_T match_pos;
15188 int lnum = 0;
15189 int col = 0;
15190 int n;
15191 int flags = 0;
15193 if (rettv_list_alloc(rettv) == FAIL)
15194 return;
15196 n = search_cmn(argvars, &match_pos, &flags);
15197 if (n > 0)
15199 lnum = match_pos.lnum;
15200 col = match_pos.col;
15203 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
15204 list_append_number(rettv->vval.v_list, (varnumber_T)col);
15205 if (flags & SP_SUBPAT)
15206 list_append_number(rettv->vval.v_list, (varnumber_T)n);
15210 /*ARGSUSED*/
15211 static void
15212 f_server2client(argvars, rettv)
15213 typval_T *argvars;
15214 typval_T *rettv;
15216 #ifdef FEAT_CLIENTSERVER
15217 char_u buf[NUMBUFLEN];
15218 char_u *server = get_tv_string_chk(&argvars[0]);
15219 char_u *reply = get_tv_string_buf_chk(&argvars[1], buf);
15221 rettv->vval.v_number = -1;
15222 if (server == NULL || reply == NULL)
15223 return;
15224 if (check_restricted() || check_secure())
15225 return;
15226 # ifdef FEAT_X11
15227 if (check_connection() == FAIL)
15228 return;
15229 # endif
15231 if (serverSendReply(server, reply) < 0)
15233 EMSG(_("E258: Unable to send to client"));
15234 return;
15236 rettv->vval.v_number = 0;
15237 #else
15238 rettv->vval.v_number = -1;
15239 #endif
15242 /*ARGSUSED*/
15243 static void
15244 f_serverlist(argvars, rettv)
15245 typval_T *argvars;
15246 typval_T *rettv;
15248 char_u *r = NULL;
15250 #ifdef FEAT_CLIENTSERVER
15251 # ifdef WIN32
15252 r = serverGetVimNames();
15253 # else
15254 make_connection();
15255 if (X_DISPLAY != NULL)
15256 r = serverGetVimNames(X_DISPLAY);
15257 # endif
15258 #endif
15259 rettv->v_type = VAR_STRING;
15260 rettv->vval.v_string = r;
15264 * "setbufvar()" function
15266 /*ARGSUSED*/
15267 static void
15268 f_setbufvar(argvars, rettv)
15269 typval_T *argvars;
15270 typval_T *rettv;
15272 buf_T *buf;
15273 aco_save_T aco;
15274 char_u *varname, *bufvarname;
15275 typval_T *varp;
15276 char_u nbuf[NUMBUFLEN];
15278 if (check_restricted() || check_secure())
15279 return;
15280 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
15281 varname = get_tv_string_chk(&argvars[1]);
15282 buf = get_buf_tv(&argvars[0]);
15283 varp = &argvars[2];
15285 if (buf != NULL && varname != NULL && varp != NULL)
15287 /* set curbuf to be our buf, temporarily */
15288 aucmd_prepbuf(&aco, buf);
15290 if (*varname == '&')
15292 long numval;
15293 char_u *strval;
15294 int error = FALSE;
15296 ++varname;
15297 numval = get_tv_number_chk(varp, &error);
15298 strval = get_tv_string_buf_chk(varp, nbuf);
15299 if (!error && strval != NULL)
15300 set_option_value(varname, numval, strval, OPT_LOCAL);
15302 else
15304 bufvarname = alloc((unsigned)STRLEN(varname) + 3);
15305 if (bufvarname != NULL)
15307 STRCPY(bufvarname, "b:");
15308 STRCPY(bufvarname + 2, varname);
15309 set_var(bufvarname, varp, TRUE);
15310 vim_free(bufvarname);
15314 /* reset notion of buffer */
15315 aucmd_restbuf(&aco);
15320 * "setcmdpos()" function
15322 static void
15323 f_setcmdpos(argvars, rettv)
15324 typval_T *argvars;
15325 typval_T *rettv;
15327 int pos = (int)get_tv_number(&argvars[0]) - 1;
15329 if (pos >= 0)
15330 rettv->vval.v_number = set_cmdline_pos(pos);
15334 * "setline()" function
15336 static void
15337 f_setline(argvars, rettv)
15338 typval_T *argvars;
15339 typval_T *rettv;
15341 linenr_T lnum;
15342 char_u *line = NULL;
15343 list_T *l = NULL;
15344 listitem_T *li = NULL;
15345 long added = 0;
15346 linenr_T lcount = curbuf->b_ml.ml_line_count;
15348 lnum = get_tv_lnum(&argvars[0]);
15349 if (argvars[1].v_type == VAR_LIST)
15351 l = argvars[1].vval.v_list;
15352 li = l->lv_first;
15354 else
15355 line = get_tv_string_chk(&argvars[1]);
15357 /* default result is zero == OK */
15358 for (;;)
15360 if (l != NULL)
15362 /* list argument, get next string */
15363 if (li == NULL)
15364 break;
15365 line = get_tv_string_chk(&li->li_tv);
15366 li = li->li_next;
15369 rettv->vval.v_number = 1; /* FAIL */
15370 if (line == NULL || lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
15371 break;
15372 if (lnum <= curbuf->b_ml.ml_line_count)
15374 /* existing line, replace it */
15375 if (u_savesub(lnum) == OK && ml_replace(lnum, line, TRUE) == OK)
15377 changed_bytes(lnum, 0);
15378 if (lnum == curwin->w_cursor.lnum)
15379 check_cursor_col();
15380 rettv->vval.v_number = 0; /* OK */
15383 else if (added > 0 || u_save(lnum - 1, lnum) == OK)
15385 /* lnum is one past the last line, append the line */
15386 ++added;
15387 if (ml_append(lnum - 1, line, (colnr_T)0, FALSE) == OK)
15388 rettv->vval.v_number = 0; /* OK */
15391 if (l == NULL) /* only one string argument */
15392 break;
15393 ++lnum;
15396 if (added > 0)
15397 appended_lines_mark(lcount, added);
15400 static void set_qf_ll_list __ARGS((win_T *wp, typval_T *list_arg, typval_T *action_arg, typval_T *rettv));
15403 * Used by "setqflist()" and "setloclist()" functions
15405 /*ARGSUSED*/
15406 static void
15407 set_qf_ll_list(wp, list_arg, action_arg, rettv)
15408 win_T *wp;
15409 typval_T *list_arg;
15410 typval_T *action_arg;
15411 typval_T *rettv;
15413 #ifdef FEAT_QUICKFIX
15414 char_u *act;
15415 int action = ' ';
15416 #endif
15418 rettv->vval.v_number = -1;
15420 #ifdef FEAT_QUICKFIX
15421 if (list_arg->v_type != VAR_LIST)
15422 EMSG(_(e_listreq));
15423 else
15425 list_T *l = list_arg->vval.v_list;
15427 if (action_arg->v_type == VAR_STRING)
15429 act = get_tv_string_chk(action_arg);
15430 if (act == NULL)
15431 return; /* type error; errmsg already given */
15432 if (*act == 'a' || *act == 'r')
15433 action = *act;
15436 if (l != NULL && set_errorlist(wp, l, action) == OK)
15437 rettv->vval.v_number = 0;
15439 #endif
15443 * "setloclist()" function
15445 /*ARGSUSED*/
15446 static void
15447 f_setloclist(argvars, rettv)
15448 typval_T *argvars;
15449 typval_T *rettv;
15451 win_T *win;
15453 rettv->vval.v_number = -1;
15455 win = find_win_by_nr(&argvars[0], NULL);
15456 if (win != NULL)
15457 set_qf_ll_list(win, &argvars[1], &argvars[2], rettv);
15461 * "setmatches()" function
15463 static void
15464 f_setmatches(argvars, rettv)
15465 typval_T *argvars;
15466 typval_T *rettv;
15468 #ifdef FEAT_SEARCH_EXTRA
15469 list_T *l;
15470 listitem_T *li;
15471 dict_T *d;
15473 rettv->vval.v_number = -1;
15474 if (argvars[0].v_type != VAR_LIST)
15476 EMSG(_(e_listreq));
15477 return;
15479 if ((l = argvars[0].vval.v_list) != NULL)
15482 /* To some extent make sure that we are dealing with a list from
15483 * "getmatches()". */
15484 li = l->lv_first;
15485 while (li != NULL)
15487 if (li->li_tv.v_type != VAR_DICT
15488 || (d = li->li_tv.vval.v_dict) == NULL)
15490 EMSG(_(e_invarg));
15491 return;
15493 if (!(dict_find(d, (char_u *)"group", -1) != NULL
15494 && dict_find(d, (char_u *)"pattern", -1) != NULL
15495 && dict_find(d, (char_u *)"priority", -1) != NULL
15496 && dict_find(d, (char_u *)"id", -1) != NULL))
15498 EMSG(_(e_invarg));
15499 return;
15501 li = li->li_next;
15504 clear_matches(curwin);
15505 li = l->lv_first;
15506 while (li != NULL)
15508 d = li->li_tv.vval.v_dict;
15509 match_add(curwin, get_dict_string(d, (char_u *)"group", FALSE),
15510 get_dict_string(d, (char_u *)"pattern", FALSE),
15511 (int)get_dict_number(d, (char_u *)"priority"),
15512 (int)get_dict_number(d, (char_u *)"id"));
15513 li = li->li_next;
15515 rettv->vval.v_number = 0;
15517 #endif
15521 * "setpos()" function
15523 /*ARGSUSED*/
15524 static void
15525 f_setpos(argvars, rettv)
15526 typval_T *argvars;
15527 typval_T *rettv;
15529 pos_T pos;
15530 int fnum;
15531 char_u *name;
15533 rettv->vval.v_number = -1;
15534 name = get_tv_string_chk(argvars);
15535 if (name != NULL)
15537 if (list2fpos(&argvars[1], &pos, &fnum) == OK)
15539 --pos.col;
15540 if (name[0] == '.' && name[1] == NUL)
15542 /* set cursor */
15543 if (fnum == curbuf->b_fnum)
15545 curwin->w_cursor = pos;
15546 check_cursor();
15547 rettv->vval.v_number = 0;
15549 else
15550 EMSG(_(e_invarg));
15552 else if (name[0] == '\'' && name[1] != NUL && name[2] == NUL)
15554 /* set mark */
15555 if (setmark_pos(name[1], &pos, fnum) == OK)
15556 rettv->vval.v_number = 0;
15558 else
15559 EMSG(_(e_invarg));
15565 * "setqflist()" function
15567 /*ARGSUSED*/
15568 static void
15569 f_setqflist(argvars, rettv)
15570 typval_T *argvars;
15571 typval_T *rettv;
15573 set_qf_ll_list(NULL, &argvars[0], &argvars[1], rettv);
15577 * "setreg()" function
15579 static void
15580 f_setreg(argvars, rettv)
15581 typval_T *argvars;
15582 typval_T *rettv;
15584 int regname;
15585 char_u *strregname;
15586 char_u *stropt;
15587 char_u *strval;
15588 int append;
15589 char_u yank_type;
15590 long block_len;
15592 block_len = -1;
15593 yank_type = MAUTO;
15594 append = FALSE;
15596 strregname = get_tv_string_chk(argvars);
15597 rettv->vval.v_number = 1; /* FAIL is default */
15599 if (strregname == NULL)
15600 return; /* type error; errmsg already given */
15601 regname = *strregname;
15602 if (regname == 0 || regname == '@')
15603 regname = '"';
15604 else if (regname == '=')
15605 return;
15607 if (argvars[2].v_type != VAR_UNKNOWN)
15609 stropt = get_tv_string_chk(&argvars[2]);
15610 if (stropt == NULL)
15611 return; /* type error */
15612 for (; *stropt != NUL; ++stropt)
15613 switch (*stropt)
15615 case 'a': case 'A': /* append */
15616 append = TRUE;
15617 break;
15618 case 'v': case 'c': /* character-wise selection */
15619 yank_type = MCHAR;
15620 break;
15621 case 'V': case 'l': /* line-wise selection */
15622 yank_type = MLINE;
15623 break;
15624 #ifdef FEAT_VISUAL
15625 case 'b': case Ctrl_V: /* block-wise selection */
15626 yank_type = MBLOCK;
15627 if (VIM_ISDIGIT(stropt[1]))
15629 ++stropt;
15630 block_len = getdigits(&stropt) - 1;
15631 --stropt;
15633 break;
15634 #endif
15638 strval = get_tv_string_chk(&argvars[1]);
15639 if (strval != NULL)
15640 write_reg_contents_ex(regname, strval, -1,
15641 append, yank_type, block_len);
15642 rettv->vval.v_number = 0;
15646 * "settabwinvar()" function
15648 static void
15649 f_settabwinvar(argvars, rettv)
15650 typval_T *argvars;
15651 typval_T *rettv;
15653 setwinvar(argvars, rettv, 1);
15657 * "setwinvar()" function
15659 static void
15660 f_setwinvar(argvars, rettv)
15661 typval_T *argvars;
15662 typval_T *rettv;
15664 setwinvar(argvars, rettv, 0);
15668 * "setwinvar()" and "settabwinvar()" functions
15670 /*ARGSUSED*/
15671 static void
15672 setwinvar(argvars, rettv, off)
15673 typval_T *argvars;
15674 typval_T *rettv;
15675 int off;
15677 win_T *win;
15678 #ifdef FEAT_WINDOWS
15679 win_T *save_curwin;
15680 tabpage_T *save_curtab;
15681 #endif
15682 char_u *varname, *winvarname;
15683 typval_T *varp;
15684 char_u nbuf[NUMBUFLEN];
15685 tabpage_T *tp;
15687 if (check_restricted() || check_secure())
15688 return;
15690 #ifdef FEAT_WINDOWS
15691 if (off == 1)
15692 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
15693 else
15694 tp = curtab;
15695 #endif
15696 win = find_win_by_nr(&argvars[off], tp);
15697 varname = get_tv_string_chk(&argvars[off + 1]);
15698 varp = &argvars[off + 2];
15700 if (win != NULL && varname != NULL && varp != NULL)
15702 #ifdef FEAT_WINDOWS
15703 /* set curwin to be our win, temporarily */
15704 save_curwin = curwin;
15705 save_curtab = curtab;
15706 goto_tabpage_tp(tp);
15707 if (!win_valid(win))
15708 return;
15709 curwin = win;
15710 curbuf = curwin->w_buffer;
15711 #endif
15713 if (*varname == '&')
15715 long numval;
15716 char_u *strval;
15717 int error = FALSE;
15719 ++varname;
15720 numval = get_tv_number_chk(varp, &error);
15721 strval = get_tv_string_buf_chk(varp, nbuf);
15722 if (!error && strval != NULL)
15723 set_option_value(varname, numval, strval, OPT_LOCAL);
15725 else
15727 winvarname = alloc((unsigned)STRLEN(varname) + 3);
15728 if (winvarname != NULL)
15730 STRCPY(winvarname, "w:");
15731 STRCPY(winvarname + 2, varname);
15732 set_var(winvarname, varp, TRUE);
15733 vim_free(winvarname);
15737 #ifdef FEAT_WINDOWS
15738 /* Restore current tabpage and window, if still valid (autocomands can
15739 * make them invalid). */
15740 if (valid_tabpage(save_curtab))
15741 goto_tabpage_tp(save_curtab);
15742 if (win_valid(save_curwin))
15744 curwin = save_curwin;
15745 curbuf = curwin->w_buffer;
15747 #endif
15752 * "shellescape({string})" function
15754 static void
15755 f_shellescape(argvars, rettv)
15756 typval_T *argvars;
15757 typval_T *rettv;
15759 rettv->vval.v_string = vim_strsave_shellescape(
15760 get_tv_string(&argvars[0]), non_zero_arg(&argvars[1]));
15761 rettv->v_type = VAR_STRING;
15765 * "simplify()" function
15767 static void
15768 f_simplify(argvars, rettv)
15769 typval_T *argvars;
15770 typval_T *rettv;
15772 char_u *p;
15774 p = get_tv_string(&argvars[0]);
15775 rettv->vval.v_string = vim_strsave(p);
15776 simplify_filename(rettv->vval.v_string); /* simplify in place */
15777 rettv->v_type = VAR_STRING;
15780 #ifdef FEAT_FLOAT
15782 * "sin()" function
15784 static void
15785 f_sin(argvars, rettv)
15786 typval_T *argvars;
15787 typval_T *rettv;
15789 float_T f;
15791 rettv->v_type = VAR_FLOAT;
15792 if (get_float_arg(argvars, &f) == OK)
15793 rettv->vval.v_float = sin(f);
15794 else
15795 rettv->vval.v_float = 0.0;
15797 #endif
15799 static int
15800 #ifdef __BORLANDC__
15801 _RTLENTRYF
15802 #endif
15803 item_compare __ARGS((const void *s1, const void *s2));
15804 static int
15805 #ifdef __BORLANDC__
15806 _RTLENTRYF
15807 #endif
15808 item_compare2 __ARGS((const void *s1, const void *s2));
15810 static int item_compare_ic;
15811 static char_u *item_compare_func;
15812 static int item_compare_func_err;
15813 #define ITEM_COMPARE_FAIL 999
15816 * Compare functions for f_sort() below.
15818 static int
15819 #ifdef __BORLANDC__
15820 _RTLENTRYF
15821 #endif
15822 item_compare(s1, s2)
15823 const void *s1;
15824 const void *s2;
15826 char_u *p1, *p2;
15827 char_u *tofree1, *tofree2;
15828 int res;
15829 char_u numbuf1[NUMBUFLEN];
15830 char_u numbuf2[NUMBUFLEN];
15832 p1 = tv2string(&(*(listitem_T **)s1)->li_tv, &tofree1, numbuf1, 0);
15833 p2 = tv2string(&(*(listitem_T **)s2)->li_tv, &tofree2, numbuf2, 0);
15834 if (p1 == NULL)
15835 p1 = (char_u *)"";
15836 if (p2 == NULL)
15837 p2 = (char_u *)"";
15838 if (item_compare_ic)
15839 res = STRICMP(p1, p2);
15840 else
15841 res = STRCMP(p1, p2);
15842 vim_free(tofree1);
15843 vim_free(tofree2);
15844 return res;
15847 static int
15848 #ifdef __BORLANDC__
15849 _RTLENTRYF
15850 #endif
15851 item_compare2(s1, s2)
15852 const void *s1;
15853 const void *s2;
15855 int res;
15856 typval_T rettv;
15857 typval_T argv[3];
15858 int dummy;
15860 /* shortcut after failure in previous call; compare all items equal */
15861 if (item_compare_func_err)
15862 return 0;
15864 /* copy the values. This is needed to be able to set v_lock to VAR_FIXED
15865 * in the copy without changing the original list items. */
15866 copy_tv(&(*(listitem_T **)s1)->li_tv, &argv[0]);
15867 copy_tv(&(*(listitem_T **)s2)->li_tv, &argv[1]);
15869 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
15870 res = call_func(item_compare_func, (int)STRLEN(item_compare_func),
15871 &rettv, 2, argv, 0L, 0L, &dummy, TRUE, NULL);
15872 clear_tv(&argv[0]);
15873 clear_tv(&argv[1]);
15875 if (res == FAIL)
15876 res = ITEM_COMPARE_FAIL;
15877 else
15878 res = get_tv_number_chk(&rettv, &item_compare_func_err);
15879 if (item_compare_func_err)
15880 res = ITEM_COMPARE_FAIL; /* return value has wrong type */
15881 clear_tv(&rettv);
15882 return res;
15886 * "sort({list})" function
15888 static void
15889 f_sort(argvars, rettv)
15890 typval_T *argvars;
15891 typval_T *rettv;
15893 list_T *l;
15894 listitem_T *li;
15895 listitem_T **ptrs;
15896 long len;
15897 long i;
15899 if (argvars[0].v_type != VAR_LIST)
15900 EMSG2(_(e_listarg), "sort()");
15901 else
15903 l = argvars[0].vval.v_list;
15904 if (l == NULL || tv_check_lock(l->lv_lock, (char_u *)"sort()"))
15905 return;
15906 rettv->vval.v_list = l;
15907 rettv->v_type = VAR_LIST;
15908 ++l->lv_refcount;
15910 len = list_len(l);
15911 if (len <= 1)
15912 return; /* short list sorts pretty quickly */
15914 item_compare_ic = FALSE;
15915 item_compare_func = NULL;
15916 if (argvars[1].v_type != VAR_UNKNOWN)
15918 if (argvars[1].v_type == VAR_FUNC)
15919 item_compare_func = argvars[1].vval.v_string;
15920 else
15922 int error = FALSE;
15924 i = get_tv_number_chk(&argvars[1], &error);
15925 if (error)
15926 return; /* type error; errmsg already given */
15927 if (i == 1)
15928 item_compare_ic = TRUE;
15929 else
15930 item_compare_func = get_tv_string(&argvars[1]);
15934 /* Make an array with each entry pointing to an item in the List. */
15935 ptrs = (listitem_T **)alloc((int)(len * sizeof(listitem_T *)));
15936 if (ptrs == NULL)
15937 return;
15938 i = 0;
15939 for (li = l->lv_first; li != NULL; li = li->li_next)
15940 ptrs[i++] = li;
15942 item_compare_func_err = FALSE;
15943 /* test the compare function */
15944 if (item_compare_func != NULL
15945 && item_compare2((void *)&ptrs[0], (void *)&ptrs[1])
15946 == ITEM_COMPARE_FAIL)
15947 EMSG(_("E702: Sort compare function failed"));
15948 else
15950 /* Sort the array with item pointers. */
15951 qsort((void *)ptrs, (size_t)len, sizeof(listitem_T *),
15952 item_compare_func == NULL ? item_compare : item_compare2);
15954 if (!item_compare_func_err)
15956 /* Clear the List and append the items in the sorted order. */
15957 l->lv_first = l->lv_last = l->lv_idx_item = NULL;
15958 l->lv_len = 0;
15959 for (i = 0; i < len; ++i)
15960 list_append(l, ptrs[i]);
15964 vim_free(ptrs);
15969 * "soundfold({word})" function
15971 static void
15972 f_soundfold(argvars, rettv)
15973 typval_T *argvars;
15974 typval_T *rettv;
15976 char_u *s;
15978 rettv->v_type = VAR_STRING;
15979 s = get_tv_string(&argvars[0]);
15980 #ifdef FEAT_SPELL
15981 rettv->vval.v_string = eval_soundfold(s);
15982 #else
15983 rettv->vval.v_string = vim_strsave(s);
15984 #endif
15988 * "spellbadword()" function
15990 /* ARGSUSED */
15991 static void
15992 f_spellbadword(argvars, rettv)
15993 typval_T *argvars;
15994 typval_T *rettv;
15996 char_u *word = (char_u *)"";
15997 hlf_T attr = HLF_COUNT;
15998 int len = 0;
16000 if (rettv_list_alloc(rettv) == FAIL)
16001 return;
16003 #ifdef FEAT_SPELL
16004 if (argvars[0].v_type == VAR_UNKNOWN)
16006 /* Find the start and length of the badly spelled word. */
16007 len = spell_move_to(curwin, FORWARD, TRUE, TRUE, &attr);
16008 if (len != 0)
16009 word = ml_get_cursor();
16011 else if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
16013 char_u *str = get_tv_string_chk(&argvars[0]);
16014 int capcol = -1;
16016 if (str != NULL)
16018 /* Check the argument for spelling. */
16019 while (*str != NUL)
16021 len = spell_check(curwin, str, &attr, &capcol, FALSE);
16022 if (attr != HLF_COUNT)
16024 word = str;
16025 break;
16027 str += len;
16031 #endif
16033 list_append_string(rettv->vval.v_list, word, len);
16034 list_append_string(rettv->vval.v_list, (char_u *)(
16035 attr == HLF_SPB ? "bad" :
16036 attr == HLF_SPR ? "rare" :
16037 attr == HLF_SPL ? "local" :
16038 attr == HLF_SPC ? "caps" :
16039 ""), -1);
16043 * "spellsuggest()" function
16045 /*ARGSUSED*/
16046 static void
16047 f_spellsuggest(argvars, rettv)
16048 typval_T *argvars;
16049 typval_T *rettv;
16051 #ifdef FEAT_SPELL
16052 char_u *str;
16053 int typeerr = FALSE;
16054 int maxcount;
16055 garray_T ga;
16056 int i;
16057 listitem_T *li;
16058 int need_capital = FALSE;
16059 #endif
16061 if (rettv_list_alloc(rettv) == FAIL)
16062 return;
16064 #ifdef FEAT_SPELL
16065 if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
16067 str = get_tv_string(&argvars[0]);
16068 if (argvars[1].v_type != VAR_UNKNOWN)
16070 maxcount = get_tv_number_chk(&argvars[1], &typeerr);
16071 if (maxcount <= 0)
16072 return;
16073 if (argvars[2].v_type != VAR_UNKNOWN)
16075 need_capital = get_tv_number_chk(&argvars[2], &typeerr);
16076 if (typeerr)
16077 return;
16080 else
16081 maxcount = 25;
16083 spell_suggest_list(&ga, str, maxcount, need_capital, FALSE);
16085 for (i = 0; i < ga.ga_len; ++i)
16087 str = ((char_u **)ga.ga_data)[i];
16089 li = listitem_alloc();
16090 if (li == NULL)
16091 vim_free(str);
16092 else
16094 li->li_tv.v_type = VAR_STRING;
16095 li->li_tv.v_lock = 0;
16096 li->li_tv.vval.v_string = str;
16097 list_append(rettv->vval.v_list, li);
16100 ga_clear(&ga);
16102 #endif
16105 static void
16106 f_split(argvars, rettv)
16107 typval_T *argvars;
16108 typval_T *rettv;
16110 char_u *str;
16111 char_u *end;
16112 char_u *pat = NULL;
16113 regmatch_T regmatch;
16114 char_u patbuf[NUMBUFLEN];
16115 char_u *save_cpo;
16116 int match;
16117 colnr_T col = 0;
16118 int keepempty = FALSE;
16119 int typeerr = FALSE;
16121 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
16122 save_cpo = p_cpo;
16123 p_cpo = (char_u *)"";
16125 str = get_tv_string(&argvars[0]);
16126 if (argvars[1].v_type != VAR_UNKNOWN)
16128 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
16129 if (pat == NULL)
16130 typeerr = TRUE;
16131 if (argvars[2].v_type != VAR_UNKNOWN)
16132 keepempty = get_tv_number_chk(&argvars[2], &typeerr);
16134 if (pat == NULL || *pat == NUL)
16135 pat = (char_u *)"[\\x01- ]\\+";
16137 if (rettv_list_alloc(rettv) == FAIL)
16138 return;
16139 if (typeerr)
16140 return;
16142 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
16143 if (regmatch.regprog != NULL)
16145 regmatch.rm_ic = FALSE;
16146 while (*str != NUL || keepempty)
16148 if (*str == NUL)
16149 match = FALSE; /* empty item at the end */
16150 else
16151 match = vim_regexec_nl(&regmatch, str, col);
16152 if (match)
16153 end = regmatch.startp[0];
16154 else
16155 end = str + STRLEN(str);
16156 if (keepempty || end > str || (rettv->vval.v_list->lv_len > 0
16157 && *str != NUL && match && end < regmatch.endp[0]))
16159 if (list_append_string(rettv->vval.v_list, str,
16160 (int)(end - str)) == FAIL)
16161 break;
16163 if (!match)
16164 break;
16165 /* Advance to just after the match. */
16166 if (regmatch.endp[0] > str)
16167 col = 0;
16168 else
16170 /* Don't get stuck at the same match. */
16171 #ifdef FEAT_MBYTE
16172 col = (*mb_ptr2len)(regmatch.endp[0]);
16173 #else
16174 col = 1;
16175 #endif
16177 str = regmatch.endp[0];
16180 vim_free(regmatch.regprog);
16183 p_cpo = save_cpo;
16186 #ifdef FEAT_FLOAT
16188 * "sqrt()" function
16190 static void
16191 f_sqrt(argvars, rettv)
16192 typval_T *argvars;
16193 typval_T *rettv;
16195 float_T f;
16197 rettv->v_type = VAR_FLOAT;
16198 if (get_float_arg(argvars, &f) == OK)
16199 rettv->vval.v_float = sqrt(f);
16200 else
16201 rettv->vval.v_float = 0.0;
16205 * "str2float()" function
16207 static void
16208 f_str2float(argvars, rettv)
16209 typval_T *argvars;
16210 typval_T *rettv;
16212 char_u *p = skipwhite(get_tv_string(&argvars[0]));
16214 if (*p == '+')
16215 p = skipwhite(p + 1);
16216 (void)string2float(p, &rettv->vval.v_float);
16217 rettv->v_type = VAR_FLOAT;
16219 #endif
16222 * "str2nr()" function
16224 static void
16225 f_str2nr(argvars, rettv)
16226 typval_T *argvars;
16227 typval_T *rettv;
16229 int base = 10;
16230 char_u *p;
16231 long n;
16233 if (argvars[1].v_type != VAR_UNKNOWN)
16235 base = get_tv_number(&argvars[1]);
16236 if (base != 8 && base != 10 && base != 16)
16238 EMSG(_(e_invarg));
16239 return;
16243 p = skipwhite(get_tv_string(&argvars[0]));
16244 if (*p == '+')
16245 p = skipwhite(p + 1);
16246 vim_str2nr(p, NULL, NULL, base == 8 ? 2 : 0, base == 16 ? 2 : 0, &n, NULL);
16247 rettv->vval.v_number = n;
16250 #ifdef HAVE_STRFTIME
16252 * "strftime({format}[, {time}])" function
16254 static void
16255 f_strftime(argvars, rettv)
16256 typval_T *argvars;
16257 typval_T *rettv;
16259 char_u result_buf[256];
16260 struct tm *curtime;
16261 time_t seconds;
16262 char_u *p;
16264 rettv->v_type = VAR_STRING;
16266 p = get_tv_string(&argvars[0]);
16267 if (argvars[1].v_type == VAR_UNKNOWN)
16268 seconds = time(NULL);
16269 else
16270 seconds = (time_t)get_tv_number(&argvars[1]);
16271 curtime = localtime(&seconds);
16272 /* MSVC returns NULL for an invalid value of seconds. */
16273 if (curtime == NULL)
16274 rettv->vval.v_string = vim_strsave((char_u *)_("(Invalid)"));
16275 else
16277 # ifdef FEAT_MBYTE
16278 vimconv_T conv;
16279 char_u *enc;
16281 conv.vc_type = CONV_NONE;
16282 enc = enc_locale();
16283 convert_setup(&conv, p_enc, enc);
16284 if (conv.vc_type != CONV_NONE)
16285 p = string_convert(&conv, p, NULL);
16286 # endif
16287 if (p != NULL)
16288 (void)strftime((char *)result_buf, sizeof(result_buf),
16289 (char *)p, curtime);
16290 else
16291 result_buf[0] = NUL;
16293 # ifdef FEAT_MBYTE
16294 if (conv.vc_type != CONV_NONE)
16295 vim_free(p);
16296 convert_setup(&conv, enc, p_enc);
16297 if (conv.vc_type != CONV_NONE)
16298 rettv->vval.v_string = string_convert(&conv, result_buf, NULL);
16299 else
16300 # endif
16301 rettv->vval.v_string = vim_strsave(result_buf);
16303 # ifdef FEAT_MBYTE
16304 /* Release conversion descriptors */
16305 convert_setup(&conv, NULL, NULL);
16306 vim_free(enc);
16307 # endif
16310 #endif
16313 * "stridx()" function
16315 static void
16316 f_stridx(argvars, rettv)
16317 typval_T *argvars;
16318 typval_T *rettv;
16320 char_u buf[NUMBUFLEN];
16321 char_u *needle;
16322 char_u *haystack;
16323 char_u *save_haystack;
16324 char_u *pos;
16325 int start_idx;
16327 needle = get_tv_string_chk(&argvars[1]);
16328 save_haystack = haystack = get_tv_string_buf_chk(&argvars[0], buf);
16329 rettv->vval.v_number = -1;
16330 if (needle == NULL || haystack == NULL)
16331 return; /* type error; errmsg already given */
16333 if (argvars[2].v_type != VAR_UNKNOWN)
16335 int error = FALSE;
16337 start_idx = get_tv_number_chk(&argvars[2], &error);
16338 if (error || start_idx >= (int)STRLEN(haystack))
16339 return;
16340 if (start_idx >= 0)
16341 haystack += start_idx;
16344 pos = (char_u *)strstr((char *)haystack, (char *)needle);
16345 if (pos != NULL)
16346 rettv->vval.v_number = (varnumber_T)(pos - save_haystack);
16350 * "string()" function
16352 static void
16353 f_string(argvars, rettv)
16354 typval_T *argvars;
16355 typval_T *rettv;
16357 char_u *tofree;
16358 char_u numbuf[NUMBUFLEN];
16360 rettv->v_type = VAR_STRING;
16361 rettv->vval.v_string = tv2string(&argvars[0], &tofree, numbuf, 0);
16362 /* Make a copy if we have a value but it's not in allocated memory. */
16363 if (rettv->vval.v_string != NULL && tofree == NULL)
16364 rettv->vval.v_string = vim_strsave(rettv->vval.v_string);
16368 * "strlen()" function
16370 static void
16371 f_strlen(argvars, rettv)
16372 typval_T *argvars;
16373 typval_T *rettv;
16375 rettv->vval.v_number = (varnumber_T)(STRLEN(
16376 get_tv_string(&argvars[0])));
16380 * "strpart()" function
16382 static void
16383 f_strpart(argvars, rettv)
16384 typval_T *argvars;
16385 typval_T *rettv;
16387 char_u *p;
16388 int n;
16389 int len;
16390 int slen;
16391 int error = FALSE;
16393 p = get_tv_string(&argvars[0]);
16394 slen = (int)STRLEN(p);
16396 n = get_tv_number_chk(&argvars[1], &error);
16397 if (error)
16398 len = 0;
16399 else if (argvars[2].v_type != VAR_UNKNOWN)
16400 len = get_tv_number(&argvars[2]);
16401 else
16402 len = slen - n; /* default len: all bytes that are available. */
16405 * Only return the overlap between the specified part and the actual
16406 * string.
16408 if (n < 0)
16410 len += n;
16411 n = 0;
16413 else if (n > slen)
16414 n = slen;
16415 if (len < 0)
16416 len = 0;
16417 else if (n + len > slen)
16418 len = slen - n;
16420 rettv->v_type = VAR_STRING;
16421 rettv->vval.v_string = vim_strnsave(p + n, len);
16425 * "strridx()" function
16427 static void
16428 f_strridx(argvars, rettv)
16429 typval_T *argvars;
16430 typval_T *rettv;
16432 char_u buf[NUMBUFLEN];
16433 char_u *needle;
16434 char_u *haystack;
16435 char_u *rest;
16436 char_u *lastmatch = NULL;
16437 int haystack_len, end_idx;
16439 needle = get_tv_string_chk(&argvars[1]);
16440 haystack = get_tv_string_buf_chk(&argvars[0], buf);
16442 rettv->vval.v_number = -1;
16443 if (needle == NULL || haystack == NULL)
16444 return; /* type error; errmsg already given */
16446 haystack_len = (int)STRLEN(haystack);
16447 if (argvars[2].v_type != VAR_UNKNOWN)
16449 /* Third argument: upper limit for index */
16450 end_idx = get_tv_number_chk(&argvars[2], NULL);
16451 if (end_idx < 0)
16452 return; /* can never find a match */
16454 else
16455 end_idx = haystack_len;
16457 if (*needle == NUL)
16459 /* Empty string matches past the end. */
16460 lastmatch = haystack + end_idx;
16462 else
16464 for (rest = haystack; *rest != '\0'; ++rest)
16466 rest = (char_u *)strstr((char *)rest, (char *)needle);
16467 if (rest == NULL || rest > haystack + end_idx)
16468 break;
16469 lastmatch = rest;
16473 if (lastmatch == NULL)
16474 rettv->vval.v_number = -1;
16475 else
16476 rettv->vval.v_number = (varnumber_T)(lastmatch - haystack);
16480 * "strtrans()" function
16482 static void
16483 f_strtrans(argvars, rettv)
16484 typval_T *argvars;
16485 typval_T *rettv;
16487 rettv->v_type = VAR_STRING;
16488 rettv->vval.v_string = transstr(get_tv_string(&argvars[0]));
16492 * "submatch()" function
16494 static void
16495 f_submatch(argvars, rettv)
16496 typval_T *argvars;
16497 typval_T *rettv;
16499 rettv->v_type = VAR_STRING;
16500 rettv->vval.v_string =
16501 reg_submatch((int)get_tv_number_chk(&argvars[0], NULL));
16505 * "substitute()" function
16507 static void
16508 f_substitute(argvars, rettv)
16509 typval_T *argvars;
16510 typval_T *rettv;
16512 char_u patbuf[NUMBUFLEN];
16513 char_u subbuf[NUMBUFLEN];
16514 char_u flagsbuf[NUMBUFLEN];
16516 char_u *str = get_tv_string_chk(&argvars[0]);
16517 char_u *pat = get_tv_string_buf_chk(&argvars[1], patbuf);
16518 char_u *sub = get_tv_string_buf_chk(&argvars[2], subbuf);
16519 char_u *flg = get_tv_string_buf_chk(&argvars[3], flagsbuf);
16521 rettv->v_type = VAR_STRING;
16522 if (str == NULL || pat == NULL || sub == NULL || flg == NULL)
16523 rettv->vval.v_string = NULL;
16524 else
16525 rettv->vval.v_string = do_string_sub(str, pat, sub, flg);
16529 * "synID(lnum, col, trans)" function
16531 /*ARGSUSED*/
16532 static void
16533 f_synID(argvars, rettv)
16534 typval_T *argvars;
16535 typval_T *rettv;
16537 int id = 0;
16538 #ifdef FEAT_SYN_HL
16539 long lnum;
16540 long col;
16541 int trans;
16542 int transerr = FALSE;
16544 lnum = get_tv_lnum(argvars); /* -1 on type error */
16545 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
16546 trans = get_tv_number_chk(&argvars[2], &transerr);
16548 if (!transerr && lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
16549 && col >= 0 && col < (long)STRLEN(ml_get(lnum)))
16550 id = syn_get_id(curwin, lnum, (colnr_T)col, trans, NULL, FALSE);
16551 #endif
16553 rettv->vval.v_number = id;
16557 * "synIDattr(id, what [, mode])" function
16559 /*ARGSUSED*/
16560 static void
16561 f_synIDattr(argvars, rettv)
16562 typval_T *argvars;
16563 typval_T *rettv;
16565 char_u *p = NULL;
16566 #ifdef FEAT_SYN_HL
16567 int id;
16568 char_u *what;
16569 char_u *mode;
16570 char_u modebuf[NUMBUFLEN];
16571 int modec;
16573 id = get_tv_number(&argvars[0]);
16574 what = get_tv_string(&argvars[1]);
16575 if (argvars[2].v_type != VAR_UNKNOWN)
16577 mode = get_tv_string_buf(&argvars[2], modebuf);
16578 modec = TOLOWER_ASC(mode[0]);
16579 if (modec != 't' && modec != 'c'
16580 #ifdef FEAT_GUI
16581 && modec != 'g'
16582 #endif
16584 modec = 0; /* replace invalid with current */
16586 else
16588 #ifdef FEAT_GUI
16589 if (gui.in_use)
16590 modec = 'g';
16591 else
16592 #endif
16593 if (t_colors > 1)
16594 modec = 'c';
16595 else
16596 modec = 't';
16600 switch (TOLOWER_ASC(what[0]))
16602 case 'b':
16603 if (TOLOWER_ASC(what[1]) == 'g') /* bg[#] */
16604 p = highlight_color(id, what, modec);
16605 else /* bold */
16606 p = highlight_has_attr(id, HL_BOLD, modec);
16607 break;
16609 case 'f': /* fg[#] */
16610 p = highlight_color(id, what, modec);
16611 break;
16613 case 'i':
16614 if (TOLOWER_ASC(what[1]) == 'n') /* inverse */
16615 p = highlight_has_attr(id, HL_INVERSE, modec);
16616 else /* italic */
16617 p = highlight_has_attr(id, HL_ITALIC, modec);
16618 break;
16620 case 'n': /* name */
16621 p = get_highlight_name(NULL, id - 1);
16622 break;
16624 case 'r': /* reverse */
16625 p = highlight_has_attr(id, HL_INVERSE, modec);
16626 break;
16628 case 's':
16629 if (TOLOWER_ASC(what[1]) == 'p') /* sp[#] */
16630 p = highlight_color(id, what, modec);
16631 else /* standout */
16632 p = highlight_has_attr(id, HL_STANDOUT, modec);
16633 break;
16635 case 'u':
16636 if (STRLEN(what) <= 5 || TOLOWER_ASC(what[5]) != 'c')
16637 /* underline */
16638 p = highlight_has_attr(id, HL_UNDERLINE, modec);
16639 else
16640 /* undercurl */
16641 p = highlight_has_attr(id, HL_UNDERCURL, modec);
16642 break;
16645 if (p != NULL)
16646 p = vim_strsave(p);
16647 #endif
16648 rettv->v_type = VAR_STRING;
16649 rettv->vval.v_string = p;
16653 * "synIDtrans(id)" function
16655 /*ARGSUSED*/
16656 static void
16657 f_synIDtrans(argvars, rettv)
16658 typval_T *argvars;
16659 typval_T *rettv;
16661 int id;
16663 #ifdef FEAT_SYN_HL
16664 id = get_tv_number(&argvars[0]);
16666 if (id > 0)
16667 id = syn_get_final_id(id);
16668 else
16669 #endif
16670 id = 0;
16672 rettv->vval.v_number = id;
16676 * "synstack(lnum, col)" function
16678 /*ARGSUSED*/
16679 static void
16680 f_synstack(argvars, rettv)
16681 typval_T *argvars;
16682 typval_T *rettv;
16684 #ifdef FEAT_SYN_HL
16685 long lnum;
16686 long col;
16687 int i;
16688 int id;
16689 #endif
16691 rettv->v_type = VAR_LIST;
16692 rettv->vval.v_list = NULL;
16694 #ifdef FEAT_SYN_HL
16695 lnum = get_tv_lnum(argvars); /* -1 on type error */
16696 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
16698 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
16699 && col >= 0 && (col == 0 || col < (long)STRLEN(ml_get(lnum)))
16700 && rettv_list_alloc(rettv) != FAIL)
16702 (void)syn_get_id(curwin, lnum, (colnr_T)col, FALSE, NULL, TRUE);
16703 for (i = 0; ; ++i)
16705 id = syn_get_stack_item(i);
16706 if (id < 0)
16707 break;
16708 if (list_append_number(rettv->vval.v_list, id) == FAIL)
16709 break;
16712 #endif
16716 * "system()" function
16718 static void
16719 f_system(argvars, rettv)
16720 typval_T *argvars;
16721 typval_T *rettv;
16723 char_u *res = NULL;
16724 char_u *p;
16725 char_u *infile = NULL;
16726 char_u buf[NUMBUFLEN];
16727 int err = FALSE;
16728 FILE *fd;
16730 if (check_restricted() || check_secure())
16731 goto done;
16733 if (argvars[1].v_type != VAR_UNKNOWN)
16736 * Write the string to a temp file, to be used for input of the shell
16737 * command.
16739 if ((infile = vim_tempname('i')) == NULL)
16741 EMSG(_(e_notmp));
16742 goto done;
16745 fd = mch_fopen((char *)infile, WRITEBIN);
16746 if (fd == NULL)
16748 EMSG2(_(e_notopen), infile);
16749 goto done;
16751 p = get_tv_string_buf_chk(&argvars[1], buf);
16752 if (p == NULL)
16754 fclose(fd);
16755 goto done; /* type error; errmsg already given */
16757 if (fwrite(p, STRLEN(p), 1, fd) != 1)
16758 err = TRUE;
16759 if (fclose(fd) != 0)
16760 err = TRUE;
16761 if (err)
16763 EMSG(_("E677: Error writing temp file"));
16764 goto done;
16768 res = get_cmd_output(get_tv_string(&argvars[0]), infile,
16769 SHELL_SILENT | SHELL_COOKED);
16771 #ifdef USE_CR
16772 /* translate <CR> into <NL> */
16773 if (res != NULL)
16775 char_u *s;
16777 for (s = res; *s; ++s)
16779 if (*s == CAR)
16780 *s = NL;
16783 #else
16784 # ifdef USE_CRNL
16785 /* translate <CR><NL> into <NL> */
16786 if (res != NULL)
16788 char_u *s, *d;
16790 d = res;
16791 for (s = res; *s; ++s)
16793 if (s[0] == CAR && s[1] == NL)
16794 ++s;
16795 *d++ = *s;
16797 *d = NUL;
16799 # endif
16800 #endif
16802 done:
16803 if (infile != NULL)
16805 mch_remove(infile);
16806 vim_free(infile);
16808 rettv->v_type = VAR_STRING;
16809 rettv->vval.v_string = res;
16813 * "tabpagebuflist()" function
16815 /* ARGSUSED */
16816 static void
16817 f_tabpagebuflist(argvars, rettv)
16818 typval_T *argvars;
16819 typval_T *rettv;
16821 #ifdef FEAT_WINDOWS
16822 tabpage_T *tp;
16823 win_T *wp = NULL;
16825 if (argvars[0].v_type == VAR_UNKNOWN)
16826 wp = firstwin;
16827 else
16829 tp = find_tabpage((int)get_tv_number(&argvars[0]));
16830 if (tp != NULL)
16831 wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
16833 if (wp != NULL && rettv_list_alloc(rettv) != FAIL)
16835 for (; wp != NULL; wp = wp->w_next)
16836 if (list_append_number(rettv->vval.v_list,
16837 wp->w_buffer->b_fnum) == FAIL)
16838 break;
16840 #endif
16845 * "tabpagenr()" function
16847 /* ARGSUSED */
16848 static void
16849 f_tabpagenr(argvars, rettv)
16850 typval_T *argvars;
16851 typval_T *rettv;
16853 int nr = 1;
16854 #ifdef FEAT_WINDOWS
16855 char_u *arg;
16857 if (argvars[0].v_type != VAR_UNKNOWN)
16859 arg = get_tv_string_chk(&argvars[0]);
16860 nr = 0;
16861 if (arg != NULL)
16863 if (STRCMP(arg, "$") == 0)
16864 nr = tabpage_index(NULL) - 1;
16865 else
16866 EMSG2(_(e_invexpr2), arg);
16869 else
16870 nr = tabpage_index(curtab);
16871 #endif
16872 rettv->vval.v_number = nr;
16876 #ifdef FEAT_WINDOWS
16877 static int get_winnr __ARGS((tabpage_T *tp, typval_T *argvar));
16880 * Common code for tabpagewinnr() and winnr().
16882 static int
16883 get_winnr(tp, argvar)
16884 tabpage_T *tp;
16885 typval_T *argvar;
16887 win_T *twin;
16888 int nr = 1;
16889 win_T *wp;
16890 char_u *arg;
16892 twin = (tp == curtab) ? curwin : tp->tp_curwin;
16893 if (argvar->v_type != VAR_UNKNOWN)
16895 arg = get_tv_string_chk(argvar);
16896 if (arg == NULL)
16897 nr = 0; /* type error; errmsg already given */
16898 else if (STRCMP(arg, "$") == 0)
16899 twin = (tp == curtab) ? lastwin : tp->tp_lastwin;
16900 else if (STRCMP(arg, "#") == 0)
16902 twin = (tp == curtab) ? prevwin : tp->tp_prevwin;
16903 if (twin == NULL)
16904 nr = 0;
16906 else
16908 EMSG2(_(e_invexpr2), arg);
16909 nr = 0;
16913 if (nr > 0)
16914 for (wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
16915 wp != twin; wp = wp->w_next)
16917 if (wp == NULL)
16919 /* didn't find it in this tabpage */
16920 nr = 0;
16921 break;
16923 ++nr;
16925 return nr;
16927 #endif
16930 * "tabpagewinnr()" function
16932 /* ARGSUSED */
16933 static void
16934 f_tabpagewinnr(argvars, rettv)
16935 typval_T *argvars;
16936 typval_T *rettv;
16938 int nr = 1;
16939 #ifdef FEAT_WINDOWS
16940 tabpage_T *tp;
16942 tp = find_tabpage((int)get_tv_number(&argvars[0]));
16943 if (tp == NULL)
16944 nr = 0;
16945 else
16946 nr = get_winnr(tp, &argvars[1]);
16947 #endif
16948 rettv->vval.v_number = nr;
16953 * "tagfiles()" function
16955 /*ARGSUSED*/
16956 static void
16957 f_tagfiles(argvars, rettv)
16958 typval_T *argvars;
16959 typval_T *rettv;
16961 char_u fname[MAXPATHL + 1];
16962 tagname_T tn;
16963 int first;
16965 if (rettv_list_alloc(rettv) == FAIL)
16966 return;
16968 for (first = TRUE; ; first = FALSE)
16969 if (get_tagfname(&tn, first, fname) == FAIL
16970 || list_append_string(rettv->vval.v_list, fname, -1) == FAIL)
16971 break;
16972 tagname_free(&tn);
16976 * "taglist()" function
16978 static void
16979 f_taglist(argvars, rettv)
16980 typval_T *argvars;
16981 typval_T *rettv;
16983 char_u *tag_pattern;
16985 tag_pattern = get_tv_string(&argvars[0]);
16987 rettv->vval.v_number = FALSE;
16988 if (*tag_pattern == NUL)
16989 return;
16991 if (rettv_list_alloc(rettv) == OK)
16992 (void)get_tags(rettv->vval.v_list, tag_pattern);
16996 * "tempname()" function
16998 /*ARGSUSED*/
16999 static void
17000 f_tempname(argvars, rettv)
17001 typval_T *argvars;
17002 typval_T *rettv;
17004 static int x = 'A';
17006 rettv->v_type = VAR_STRING;
17007 rettv->vval.v_string = vim_tempname(x);
17009 /* Advance 'x' to use A-Z and 0-9, so that there are at least 34 different
17010 * names. Skip 'I' and 'O', they are used for shell redirection. */
17013 if (x == 'Z')
17014 x = '0';
17015 else if (x == '9')
17016 x = 'A';
17017 else
17019 #ifdef EBCDIC
17020 if (x == 'I')
17021 x = 'J';
17022 else if (x == 'R')
17023 x = 'S';
17024 else
17025 #endif
17026 ++x;
17028 } while (x == 'I' || x == 'O');
17032 * "test(list)" function: Just checking the walls...
17034 /*ARGSUSED*/
17035 static void
17036 f_test(argvars, rettv)
17037 typval_T *argvars;
17038 typval_T *rettv;
17040 /* Used for unit testing. Change the code below to your liking. */
17041 #if 0
17042 listitem_T *li;
17043 list_T *l;
17044 char_u *bad, *good;
17046 if (argvars[0].v_type != VAR_LIST)
17047 return;
17048 l = argvars[0].vval.v_list;
17049 if (l == NULL)
17050 return;
17051 li = l->lv_first;
17052 if (li == NULL)
17053 return;
17054 bad = get_tv_string(&li->li_tv);
17055 li = li->li_next;
17056 if (li == NULL)
17057 return;
17058 good = get_tv_string(&li->li_tv);
17059 rettv->vval.v_number = test_edit_score(bad, good);
17060 #endif
17064 * "tolower(string)" function
17066 static void
17067 f_tolower(argvars, rettv)
17068 typval_T *argvars;
17069 typval_T *rettv;
17071 char_u *p;
17073 p = vim_strsave(get_tv_string(&argvars[0]));
17074 rettv->v_type = VAR_STRING;
17075 rettv->vval.v_string = p;
17077 if (p != NULL)
17078 while (*p != NUL)
17080 #ifdef FEAT_MBYTE
17081 int l;
17083 if (enc_utf8)
17085 int c, lc;
17087 c = utf_ptr2char(p);
17088 lc = utf_tolower(c);
17089 l = utf_ptr2len(p);
17090 /* TODO: reallocate string when byte count changes. */
17091 if (utf_char2len(lc) == l)
17092 utf_char2bytes(lc, p);
17093 p += l;
17095 else if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
17096 p += l; /* skip multi-byte character */
17097 else
17098 #endif
17100 *p = TOLOWER_LOC(*p); /* note that tolower() can be a macro */
17101 ++p;
17107 * "toupper(string)" function
17109 static void
17110 f_toupper(argvars, rettv)
17111 typval_T *argvars;
17112 typval_T *rettv;
17114 rettv->v_type = VAR_STRING;
17115 rettv->vval.v_string = strup_save(get_tv_string(&argvars[0]));
17119 * "tr(string, fromstr, tostr)" function
17121 static void
17122 f_tr(argvars, rettv)
17123 typval_T *argvars;
17124 typval_T *rettv;
17126 char_u *instr;
17127 char_u *fromstr;
17128 char_u *tostr;
17129 char_u *p;
17130 #ifdef FEAT_MBYTE
17131 int inlen;
17132 int fromlen;
17133 int tolen;
17134 int idx;
17135 char_u *cpstr;
17136 int cplen;
17137 int first = TRUE;
17138 #endif
17139 char_u buf[NUMBUFLEN];
17140 char_u buf2[NUMBUFLEN];
17141 garray_T ga;
17143 instr = get_tv_string(&argvars[0]);
17144 fromstr = get_tv_string_buf_chk(&argvars[1], buf);
17145 tostr = get_tv_string_buf_chk(&argvars[2], buf2);
17147 /* Default return value: empty string. */
17148 rettv->v_type = VAR_STRING;
17149 rettv->vval.v_string = NULL;
17150 if (fromstr == NULL || tostr == NULL)
17151 return; /* type error; errmsg already given */
17152 ga_init2(&ga, (int)sizeof(char), 80);
17154 #ifdef FEAT_MBYTE
17155 if (!has_mbyte)
17156 #endif
17157 /* not multi-byte: fromstr and tostr must be the same length */
17158 if (STRLEN(fromstr) != STRLEN(tostr))
17160 #ifdef FEAT_MBYTE
17161 error:
17162 #endif
17163 EMSG2(_(e_invarg2), fromstr);
17164 ga_clear(&ga);
17165 return;
17168 /* fromstr and tostr have to contain the same number of chars */
17169 while (*instr != NUL)
17171 #ifdef FEAT_MBYTE
17172 if (has_mbyte)
17174 inlen = (*mb_ptr2len)(instr);
17175 cpstr = instr;
17176 cplen = inlen;
17177 idx = 0;
17178 for (p = fromstr; *p != NUL; p += fromlen)
17180 fromlen = (*mb_ptr2len)(p);
17181 if (fromlen == inlen && STRNCMP(instr, p, inlen) == 0)
17183 for (p = tostr; *p != NUL; p += tolen)
17185 tolen = (*mb_ptr2len)(p);
17186 if (idx-- == 0)
17188 cplen = tolen;
17189 cpstr = p;
17190 break;
17193 if (*p == NUL) /* tostr is shorter than fromstr */
17194 goto error;
17195 break;
17197 ++idx;
17200 if (first && cpstr == instr)
17202 /* Check that fromstr and tostr have the same number of
17203 * (multi-byte) characters. Done only once when a character
17204 * of instr doesn't appear in fromstr. */
17205 first = FALSE;
17206 for (p = tostr; *p != NUL; p += tolen)
17208 tolen = (*mb_ptr2len)(p);
17209 --idx;
17211 if (idx != 0)
17212 goto error;
17215 ga_grow(&ga, cplen);
17216 mch_memmove((char *)ga.ga_data + ga.ga_len, cpstr, (size_t)cplen);
17217 ga.ga_len += cplen;
17219 instr += inlen;
17221 else
17222 #endif
17224 /* When not using multi-byte chars we can do it faster. */
17225 p = vim_strchr(fromstr, *instr);
17226 if (p != NULL)
17227 ga_append(&ga, tostr[p - fromstr]);
17228 else
17229 ga_append(&ga, *instr);
17230 ++instr;
17234 /* add a terminating NUL */
17235 ga_grow(&ga, 1);
17236 ga_append(&ga, NUL);
17238 rettv->vval.v_string = ga.ga_data;
17241 #ifdef FEAT_FLOAT
17243 * "trunc({float})" function
17245 static void
17246 f_trunc(argvars, rettv)
17247 typval_T *argvars;
17248 typval_T *rettv;
17250 float_T f;
17252 rettv->v_type = VAR_FLOAT;
17253 if (get_float_arg(argvars, &f) == OK)
17254 /* trunc() is not in C90, use floor() or ceil() instead. */
17255 rettv->vval.v_float = f > 0 ? floor(f) : ceil(f);
17256 else
17257 rettv->vval.v_float = 0.0;
17259 #endif
17262 * "type(expr)" function
17264 static void
17265 f_type(argvars, rettv)
17266 typval_T *argvars;
17267 typval_T *rettv;
17269 int n;
17271 switch (argvars[0].v_type)
17273 case VAR_NUMBER: n = 0; break;
17274 case VAR_STRING: n = 1; break;
17275 case VAR_FUNC: n = 2; break;
17276 case VAR_LIST: n = 3; break;
17277 case VAR_DICT: n = 4; break;
17278 #ifdef FEAT_FLOAT
17279 case VAR_FLOAT: n = 5; break;
17280 #endif
17281 default: EMSG2(_(e_intern2), "f_type()"); n = 0; break;
17283 rettv->vval.v_number = n;
17287 * "values(dict)" function
17289 static void
17290 f_values(argvars, rettv)
17291 typval_T *argvars;
17292 typval_T *rettv;
17294 dict_list(argvars, rettv, 1);
17298 * "virtcol(string)" function
17300 static void
17301 f_virtcol(argvars, rettv)
17302 typval_T *argvars;
17303 typval_T *rettv;
17305 colnr_T vcol = 0;
17306 pos_T *fp;
17307 int fnum = curbuf->b_fnum;
17309 fp = var2fpos(&argvars[0], FALSE, &fnum);
17310 if (fp != NULL && fp->lnum <= curbuf->b_ml.ml_line_count
17311 && fnum == curbuf->b_fnum)
17313 getvvcol(curwin, fp, NULL, NULL, &vcol);
17314 ++vcol;
17317 rettv->vval.v_number = vcol;
17321 * "visualmode()" function
17323 /*ARGSUSED*/
17324 static void
17325 f_visualmode(argvars, rettv)
17326 typval_T *argvars;
17327 typval_T *rettv;
17329 #ifdef FEAT_VISUAL
17330 char_u str[2];
17332 rettv->v_type = VAR_STRING;
17333 str[0] = curbuf->b_visual_mode_eval;
17334 str[1] = NUL;
17335 rettv->vval.v_string = vim_strsave(str);
17337 /* A non-zero number or non-empty string argument: reset mode. */
17338 if (non_zero_arg(&argvars[0]))
17339 curbuf->b_visual_mode_eval = NUL;
17340 #endif
17344 * "winbufnr(nr)" function
17346 static void
17347 f_winbufnr(argvars, rettv)
17348 typval_T *argvars;
17349 typval_T *rettv;
17351 win_T *wp;
17353 wp = find_win_by_nr(&argvars[0], NULL);
17354 if (wp == NULL)
17355 rettv->vval.v_number = -1;
17356 else
17357 rettv->vval.v_number = wp->w_buffer->b_fnum;
17361 * "wincol()" function
17363 /*ARGSUSED*/
17364 static void
17365 f_wincol(argvars, rettv)
17366 typval_T *argvars;
17367 typval_T *rettv;
17369 validate_cursor();
17370 rettv->vval.v_number = curwin->w_wcol + 1;
17374 * "winheight(nr)" function
17376 static void
17377 f_winheight(argvars, rettv)
17378 typval_T *argvars;
17379 typval_T *rettv;
17381 win_T *wp;
17383 wp = find_win_by_nr(&argvars[0], NULL);
17384 if (wp == NULL)
17385 rettv->vval.v_number = -1;
17386 else
17387 rettv->vval.v_number = wp->w_height;
17391 * "winline()" function
17393 /*ARGSUSED*/
17394 static void
17395 f_winline(argvars, rettv)
17396 typval_T *argvars;
17397 typval_T *rettv;
17399 validate_cursor();
17400 rettv->vval.v_number = curwin->w_wrow + 1;
17404 * "winnr()" function
17406 /* ARGSUSED */
17407 static void
17408 f_winnr(argvars, rettv)
17409 typval_T *argvars;
17410 typval_T *rettv;
17412 int nr = 1;
17414 #ifdef FEAT_WINDOWS
17415 nr = get_winnr(curtab, &argvars[0]);
17416 #endif
17417 rettv->vval.v_number = nr;
17421 * "winrestcmd()" function
17423 /* ARGSUSED */
17424 static void
17425 f_winrestcmd(argvars, rettv)
17426 typval_T *argvars;
17427 typval_T *rettv;
17429 #ifdef FEAT_WINDOWS
17430 win_T *wp;
17431 int winnr = 1;
17432 garray_T ga;
17433 char_u buf[50];
17435 ga_init2(&ga, (int)sizeof(char), 70);
17436 for (wp = firstwin; wp != NULL; wp = wp->w_next)
17438 sprintf((char *)buf, "%dresize %d|", winnr, wp->w_height);
17439 ga_concat(&ga, buf);
17440 # ifdef FEAT_VERTSPLIT
17441 sprintf((char *)buf, "vert %dresize %d|", winnr, wp->w_width);
17442 ga_concat(&ga, buf);
17443 # endif
17444 ++winnr;
17446 ga_append(&ga, NUL);
17448 rettv->vval.v_string = ga.ga_data;
17449 #else
17450 rettv->vval.v_string = NULL;
17451 #endif
17452 rettv->v_type = VAR_STRING;
17456 * "winrestview()" function
17458 /* ARGSUSED */
17459 static void
17460 f_winrestview(argvars, rettv)
17461 typval_T *argvars;
17462 typval_T *rettv;
17464 dict_T *dict;
17466 if (argvars[0].v_type != VAR_DICT
17467 || (dict = argvars[0].vval.v_dict) == NULL)
17468 EMSG(_(e_invarg));
17469 else
17471 curwin->w_cursor.lnum = get_dict_number(dict, (char_u *)"lnum");
17472 curwin->w_cursor.col = get_dict_number(dict, (char_u *)"col");
17473 #ifdef FEAT_VIRTUALEDIT
17474 curwin->w_cursor.coladd = get_dict_number(dict, (char_u *)"coladd");
17475 #endif
17476 curwin->w_curswant = get_dict_number(dict, (char_u *)"curswant");
17477 curwin->w_set_curswant = FALSE;
17479 set_topline(curwin, get_dict_number(dict, (char_u *)"topline"));
17480 #ifdef FEAT_DIFF
17481 curwin->w_topfill = get_dict_number(dict, (char_u *)"topfill");
17482 #endif
17483 curwin->w_leftcol = get_dict_number(dict, (char_u *)"leftcol");
17484 curwin->w_skipcol = get_dict_number(dict, (char_u *)"skipcol");
17486 check_cursor();
17487 changed_cline_bef_curs();
17488 invalidate_botline();
17489 redraw_later(VALID);
17491 if (curwin->w_topline == 0)
17492 curwin->w_topline = 1;
17493 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
17494 curwin->w_topline = curbuf->b_ml.ml_line_count;
17495 #ifdef FEAT_DIFF
17496 check_topfill(curwin, TRUE);
17497 #endif
17502 * "winsaveview()" function
17504 /* ARGSUSED */
17505 static void
17506 f_winsaveview(argvars, rettv)
17507 typval_T *argvars;
17508 typval_T *rettv;
17510 dict_T *dict;
17512 dict = dict_alloc();
17513 if (dict == NULL)
17514 return;
17515 rettv->v_type = VAR_DICT;
17516 rettv->vval.v_dict = dict;
17517 ++dict->dv_refcount;
17519 dict_add_nr_str(dict, "lnum", (long)curwin->w_cursor.lnum, NULL);
17520 dict_add_nr_str(dict, "col", (long)curwin->w_cursor.col, NULL);
17521 #ifdef FEAT_VIRTUALEDIT
17522 dict_add_nr_str(dict, "coladd", (long)curwin->w_cursor.coladd, NULL);
17523 #endif
17524 update_curswant();
17525 dict_add_nr_str(dict, "curswant", (long)curwin->w_curswant, NULL);
17527 dict_add_nr_str(dict, "topline", (long)curwin->w_topline, NULL);
17528 #ifdef FEAT_DIFF
17529 dict_add_nr_str(dict, "topfill", (long)curwin->w_topfill, NULL);
17530 #endif
17531 dict_add_nr_str(dict, "leftcol", (long)curwin->w_leftcol, NULL);
17532 dict_add_nr_str(dict, "skipcol", (long)curwin->w_skipcol, NULL);
17536 * "winwidth(nr)" function
17538 static void
17539 f_winwidth(argvars, rettv)
17540 typval_T *argvars;
17541 typval_T *rettv;
17543 win_T *wp;
17545 wp = find_win_by_nr(&argvars[0], NULL);
17546 if (wp == NULL)
17547 rettv->vval.v_number = -1;
17548 else
17549 #ifdef FEAT_VERTSPLIT
17550 rettv->vval.v_number = wp->w_width;
17551 #else
17552 rettv->vval.v_number = Columns;
17553 #endif
17557 * "writefile()" function
17559 static void
17560 f_writefile(argvars, rettv)
17561 typval_T *argvars;
17562 typval_T *rettv;
17564 int binary = FALSE;
17565 char_u *fname;
17566 FILE *fd;
17567 listitem_T *li;
17568 char_u *s;
17569 int ret = 0;
17570 int c;
17572 if (check_restricted() || check_secure())
17573 return;
17575 if (argvars[0].v_type != VAR_LIST)
17577 EMSG2(_(e_listarg), "writefile()");
17578 return;
17580 if (argvars[0].vval.v_list == NULL)
17581 return;
17583 if (argvars[2].v_type != VAR_UNKNOWN
17584 && STRCMP(get_tv_string(&argvars[2]), "b") == 0)
17585 binary = TRUE;
17587 /* Always open the file in binary mode, library functions have a mind of
17588 * their own about CR-LF conversion. */
17589 fname = get_tv_string(&argvars[1]);
17590 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
17592 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
17593 ret = -1;
17595 else
17597 for (li = argvars[0].vval.v_list->lv_first; li != NULL;
17598 li = li->li_next)
17600 for (s = get_tv_string(&li->li_tv); *s != NUL; ++s)
17602 if (*s == '\n')
17603 c = putc(NUL, fd);
17604 else
17605 c = putc(*s, fd);
17606 if (c == EOF)
17608 ret = -1;
17609 break;
17612 if (!binary || li->li_next != NULL)
17613 if (putc('\n', fd) == EOF)
17615 ret = -1;
17616 break;
17618 if (ret < 0)
17620 EMSG(_(e_write));
17621 break;
17624 fclose(fd);
17627 rettv->vval.v_number = ret;
17631 * Translate a String variable into a position.
17632 * Returns NULL when there is an error.
17634 static pos_T *
17635 var2fpos(varp, dollar_lnum, fnum)
17636 typval_T *varp;
17637 int dollar_lnum; /* TRUE when $ is last line */
17638 int *fnum; /* set to fnum for '0, 'A, etc. */
17640 char_u *name;
17641 static pos_T pos;
17642 pos_T *pp;
17644 /* Argument can be [lnum, col, coladd]. */
17645 if (varp->v_type == VAR_LIST)
17647 list_T *l;
17648 int len;
17649 int error = FALSE;
17650 listitem_T *li;
17652 l = varp->vval.v_list;
17653 if (l == NULL)
17654 return NULL;
17656 /* Get the line number */
17657 pos.lnum = list_find_nr(l, 0L, &error);
17658 if (error || pos.lnum <= 0 || pos.lnum > curbuf->b_ml.ml_line_count)
17659 return NULL; /* invalid line number */
17661 /* Get the column number */
17662 pos.col = list_find_nr(l, 1L, &error);
17663 if (error)
17664 return NULL;
17665 len = (long)STRLEN(ml_get(pos.lnum));
17667 /* We accept "$" for the column number: last column. */
17668 li = list_find(l, 1L);
17669 if (li != NULL && li->li_tv.v_type == VAR_STRING
17670 && li->li_tv.vval.v_string != NULL
17671 && STRCMP(li->li_tv.vval.v_string, "$") == 0)
17672 pos.col = len + 1;
17674 /* Accept a position up to the NUL after the line. */
17675 if (pos.col == 0 || (int)pos.col > len + 1)
17676 return NULL; /* invalid column number */
17677 --pos.col;
17679 #ifdef FEAT_VIRTUALEDIT
17680 /* Get the virtual offset. Defaults to zero. */
17681 pos.coladd = list_find_nr(l, 2L, &error);
17682 if (error)
17683 pos.coladd = 0;
17684 #endif
17686 return &pos;
17689 name = get_tv_string_chk(varp);
17690 if (name == NULL)
17691 return NULL;
17692 if (name[0] == '.') /* cursor */
17693 return &curwin->w_cursor;
17694 #ifdef FEAT_VISUAL
17695 if (name[0] == 'v' && name[1] == NUL) /* Visual start */
17697 if (VIsual_active)
17698 return &VIsual;
17699 return &curwin->w_cursor;
17701 #endif
17702 if (name[0] == '\'') /* mark */
17704 pp = getmark_fnum(name[1], FALSE, fnum);
17705 if (pp == NULL || pp == (pos_T *)-1 || pp->lnum <= 0)
17706 return NULL;
17707 return pp;
17710 #ifdef FEAT_VIRTUALEDIT
17711 pos.coladd = 0;
17712 #endif
17714 if (name[0] == 'w' && dollar_lnum)
17716 pos.col = 0;
17717 if (name[1] == '0') /* "w0": first visible line */
17719 update_topline();
17720 pos.lnum = curwin->w_topline;
17721 return &pos;
17723 else if (name[1] == '$') /* "w$": last visible line */
17725 validate_botline();
17726 pos.lnum = curwin->w_botline - 1;
17727 return &pos;
17730 else if (name[0] == '$') /* last column or line */
17732 if (dollar_lnum)
17734 pos.lnum = curbuf->b_ml.ml_line_count;
17735 pos.col = 0;
17737 else
17739 pos.lnum = curwin->w_cursor.lnum;
17740 pos.col = (colnr_T)STRLEN(ml_get_curline());
17742 return &pos;
17744 return NULL;
17748 * Convert list in "arg" into a position and optional file number.
17749 * When "fnump" is NULL there is no file number, only 3 items.
17750 * Note that the column is passed on as-is, the caller may want to decrement
17751 * it to use 1 for the first column.
17752 * Return FAIL when conversion is not possible, doesn't check the position for
17753 * validity.
17755 static int
17756 list2fpos(arg, posp, fnump)
17757 typval_T *arg;
17758 pos_T *posp;
17759 int *fnump;
17761 list_T *l = arg->vval.v_list;
17762 long i = 0;
17763 long n;
17765 /* List must be: [fnum, lnum, col, coladd], where "fnum" is only there
17766 * when "fnump" isn't NULL and "coladd" is optional. */
17767 if (arg->v_type != VAR_LIST
17768 || l == NULL
17769 || l->lv_len < (fnump == NULL ? 2 : 3)
17770 || l->lv_len > (fnump == NULL ? 3 : 4))
17771 return FAIL;
17773 if (fnump != NULL)
17775 n = list_find_nr(l, i++, NULL); /* fnum */
17776 if (n < 0)
17777 return FAIL;
17778 if (n == 0)
17779 n = curbuf->b_fnum; /* current buffer */
17780 *fnump = n;
17783 n = list_find_nr(l, i++, NULL); /* lnum */
17784 if (n < 0)
17785 return FAIL;
17786 posp->lnum = n;
17788 n = list_find_nr(l, i++, NULL); /* col */
17789 if (n < 0)
17790 return FAIL;
17791 posp->col = n;
17793 #ifdef FEAT_VIRTUALEDIT
17794 n = list_find_nr(l, i, NULL);
17795 if (n < 0)
17796 posp->coladd = 0;
17797 else
17798 posp->coladd = n;
17799 #endif
17801 return OK;
17805 * Get the length of an environment variable name.
17806 * Advance "arg" to the first character after the name.
17807 * Return 0 for error.
17809 static int
17810 get_env_len(arg)
17811 char_u **arg;
17813 char_u *p;
17814 int len;
17816 for (p = *arg; vim_isIDc(*p); ++p)
17818 if (p == *arg) /* no name found */
17819 return 0;
17821 len = (int)(p - *arg);
17822 *arg = p;
17823 return len;
17827 * Get the length of the name of a function or internal variable.
17828 * "arg" is advanced to the first non-white character after the name.
17829 * Return 0 if something is wrong.
17831 static int
17832 get_id_len(arg)
17833 char_u **arg;
17835 char_u *p;
17836 int len;
17838 /* Find the end of the name. */
17839 for (p = *arg; eval_isnamec(*p); ++p)
17841 if (p == *arg) /* no name found */
17842 return 0;
17844 len = (int)(p - *arg);
17845 *arg = skipwhite(p);
17847 return len;
17851 * Get the length of the name of a variable or function.
17852 * Only the name is recognized, does not handle ".key" or "[idx]".
17853 * "arg" is advanced to the first non-white character after the name.
17854 * Return -1 if curly braces expansion failed.
17855 * Return 0 if something else is wrong.
17856 * If the name contains 'magic' {}'s, expand them and return the
17857 * expanded name in an allocated string via 'alias' - caller must free.
17859 static int
17860 get_name_len(arg, alias, evaluate, verbose)
17861 char_u **arg;
17862 char_u **alias;
17863 int evaluate;
17864 int verbose;
17866 int len;
17867 char_u *p;
17868 char_u *expr_start;
17869 char_u *expr_end;
17871 *alias = NULL; /* default to no alias */
17873 if ((*arg)[0] == K_SPECIAL && (*arg)[1] == KS_EXTRA
17874 && (*arg)[2] == (int)KE_SNR)
17876 /* hard coded <SNR>, already translated */
17877 *arg += 3;
17878 return get_id_len(arg) + 3;
17880 len = eval_fname_script(*arg);
17881 if (len > 0)
17883 /* literal "<SID>", "s:" or "<SNR>" */
17884 *arg += len;
17888 * Find the end of the name; check for {} construction.
17890 p = find_name_end(*arg, &expr_start, &expr_end,
17891 len > 0 ? 0 : FNE_CHECK_START);
17892 if (expr_start != NULL)
17894 char_u *temp_string;
17896 if (!evaluate)
17898 len += (int)(p - *arg);
17899 *arg = skipwhite(p);
17900 return len;
17904 * Include any <SID> etc in the expanded string:
17905 * Thus the -len here.
17907 temp_string = make_expanded_name(*arg - len, expr_start, expr_end, p);
17908 if (temp_string == NULL)
17909 return -1;
17910 *alias = temp_string;
17911 *arg = skipwhite(p);
17912 return (int)STRLEN(temp_string);
17915 len += get_id_len(arg);
17916 if (len == 0 && verbose)
17917 EMSG2(_(e_invexpr2), *arg);
17919 return len;
17923 * Find the end of a variable or function name, taking care of magic braces.
17924 * If "expr_start" is not NULL then "expr_start" and "expr_end" are set to the
17925 * start and end of the first magic braces item.
17926 * "flags" can have FNE_INCL_BR and FNE_CHECK_START.
17927 * Return a pointer to just after the name. Equal to "arg" if there is no
17928 * valid name.
17930 static char_u *
17931 find_name_end(arg, expr_start, expr_end, flags)
17932 char_u *arg;
17933 char_u **expr_start;
17934 char_u **expr_end;
17935 int flags;
17937 int mb_nest = 0;
17938 int br_nest = 0;
17939 char_u *p;
17941 if (expr_start != NULL)
17943 *expr_start = NULL;
17944 *expr_end = NULL;
17947 /* Quick check for valid starting character. */
17948 if ((flags & FNE_CHECK_START) && !eval_isnamec1(*arg) && *arg != '{')
17949 return arg;
17951 for (p = arg; *p != NUL
17952 && (eval_isnamec(*p)
17953 || *p == '{'
17954 || ((flags & FNE_INCL_BR) && (*p == '[' || *p == '.'))
17955 || mb_nest != 0
17956 || br_nest != 0); mb_ptr_adv(p))
17958 if (*p == '\'')
17960 /* skip over 'string' to avoid counting [ and ] inside it. */
17961 for (p = p + 1; *p != NUL && *p != '\''; mb_ptr_adv(p))
17963 if (*p == NUL)
17964 break;
17966 else if (*p == '"')
17968 /* skip over "str\"ing" to avoid counting [ and ] inside it. */
17969 for (p = p + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
17970 if (*p == '\\' && p[1] != NUL)
17971 ++p;
17972 if (*p == NUL)
17973 break;
17976 if (mb_nest == 0)
17978 if (*p == '[')
17979 ++br_nest;
17980 else if (*p == ']')
17981 --br_nest;
17984 if (br_nest == 0)
17986 if (*p == '{')
17988 mb_nest++;
17989 if (expr_start != NULL && *expr_start == NULL)
17990 *expr_start = p;
17992 else if (*p == '}')
17994 mb_nest--;
17995 if (expr_start != NULL && mb_nest == 0 && *expr_end == NULL)
17996 *expr_end = p;
18001 return p;
18005 * Expands out the 'magic' {}'s in a variable/function name.
18006 * Note that this can call itself recursively, to deal with
18007 * constructs like foo{bar}{baz}{bam}
18008 * The four pointer arguments point to "foo{expre}ss{ion}bar"
18009 * "in_start" ^
18010 * "expr_start" ^
18011 * "expr_end" ^
18012 * "in_end" ^
18014 * Returns a new allocated string, which the caller must free.
18015 * Returns NULL for failure.
18017 static char_u *
18018 make_expanded_name(in_start, expr_start, expr_end, in_end)
18019 char_u *in_start;
18020 char_u *expr_start;
18021 char_u *expr_end;
18022 char_u *in_end;
18024 char_u c1;
18025 char_u *retval = NULL;
18026 char_u *temp_result;
18027 char_u *nextcmd = NULL;
18029 if (expr_end == NULL || in_end == NULL)
18030 return NULL;
18031 *expr_start = NUL;
18032 *expr_end = NUL;
18033 c1 = *in_end;
18034 *in_end = NUL;
18036 temp_result = eval_to_string(expr_start + 1, &nextcmd, FALSE);
18037 if (temp_result != NULL && nextcmd == NULL)
18039 retval = alloc((unsigned)(STRLEN(temp_result) + (expr_start - in_start)
18040 + (in_end - expr_end) + 1));
18041 if (retval != NULL)
18043 STRCPY(retval, in_start);
18044 STRCAT(retval, temp_result);
18045 STRCAT(retval, expr_end + 1);
18048 vim_free(temp_result);
18050 *in_end = c1; /* put char back for error messages */
18051 *expr_start = '{';
18052 *expr_end = '}';
18054 if (retval != NULL)
18056 temp_result = find_name_end(retval, &expr_start, &expr_end, 0);
18057 if (expr_start != NULL)
18059 /* Further expansion! */
18060 temp_result = make_expanded_name(retval, expr_start,
18061 expr_end, temp_result);
18062 vim_free(retval);
18063 retval = temp_result;
18067 return retval;
18071 * Return TRUE if character "c" can be used in a variable or function name.
18072 * Does not include '{' or '}' for magic braces.
18074 static int
18075 eval_isnamec(c)
18076 int c;
18078 return (ASCII_ISALNUM(c) || c == '_' || c == ':' || c == AUTOLOAD_CHAR);
18082 * Return TRUE if character "c" can be used as the first character in a
18083 * variable or function name (excluding '{' and '}').
18085 static int
18086 eval_isnamec1(c)
18087 int c;
18089 return (ASCII_ISALPHA(c) || c == '_');
18093 * Set number v: variable to "val".
18095 void
18096 set_vim_var_nr(idx, val)
18097 int idx;
18098 long val;
18100 vimvars[idx].vv_nr = val;
18104 * Get number v: variable value.
18106 long
18107 get_vim_var_nr(idx)
18108 int idx;
18110 return vimvars[idx].vv_nr;
18114 * Get string v: variable value. Uses a static buffer, can only be used once.
18116 char_u *
18117 get_vim_var_str(idx)
18118 int idx;
18120 return get_tv_string(&vimvars[idx].vv_tv);
18124 * Get List v: variable value. Caller must take care of reference count when
18125 * needed.
18127 list_T *
18128 get_vim_var_list(idx)
18129 int idx;
18131 return vimvars[idx].vv_list;
18135 * Set v:count to "count" and v:count1 to "count1".
18136 * When "set_prevcount" is TRUE first set v:prevcount from v:count.
18138 void
18139 set_vcount(count, count1, set_prevcount)
18140 long count;
18141 long count1;
18142 int set_prevcount;
18144 if (set_prevcount)
18145 vimvars[VV_PREVCOUNT].vv_nr = vimvars[VV_COUNT].vv_nr;
18146 vimvars[VV_COUNT].vv_nr = count;
18147 vimvars[VV_COUNT1].vv_nr = count1;
18151 * Set string v: variable to a copy of "val".
18153 void
18154 set_vim_var_string(idx, val, len)
18155 int idx;
18156 char_u *val;
18157 int len; /* length of "val" to use or -1 (whole string) */
18159 /* Need to do this (at least) once, since we can't initialize a union.
18160 * Will always be invoked when "v:progname" is set. */
18161 vimvars[VV_VERSION].vv_nr = VIM_VERSION_100;
18163 vim_free(vimvars[idx].vv_str);
18164 if (val == NULL)
18165 vimvars[idx].vv_str = NULL;
18166 else if (len == -1)
18167 vimvars[idx].vv_str = vim_strsave(val);
18168 else
18169 vimvars[idx].vv_str = vim_strnsave(val, len);
18173 * Set List v: variable to "val".
18175 void
18176 set_vim_var_list(idx, val)
18177 int idx;
18178 list_T *val;
18180 list_unref(vimvars[idx].vv_list);
18181 vimvars[idx].vv_list = val;
18182 if (val != NULL)
18183 ++val->lv_refcount;
18187 * Set v:register if needed.
18189 void
18190 set_reg_var(c)
18191 int c;
18193 char_u regname;
18195 if (c == 0 || c == ' ')
18196 regname = '"';
18197 else
18198 regname = c;
18199 /* Avoid free/alloc when the value is already right. */
18200 if (vimvars[VV_REG].vv_str == NULL || vimvars[VV_REG].vv_str[0] != c)
18201 set_vim_var_string(VV_REG, &regname, 1);
18205 * Get or set v:exception. If "oldval" == NULL, return the current value.
18206 * Otherwise, restore the value to "oldval" and return NULL.
18207 * Must always be called in pairs to save and restore v:exception! Does not
18208 * take care of memory allocations.
18210 char_u *
18211 v_exception(oldval)
18212 char_u *oldval;
18214 if (oldval == NULL)
18215 return vimvars[VV_EXCEPTION].vv_str;
18217 vimvars[VV_EXCEPTION].vv_str = oldval;
18218 return NULL;
18222 * Get or set v:throwpoint. If "oldval" == NULL, return the current value.
18223 * Otherwise, restore the value to "oldval" and return NULL.
18224 * Must always be called in pairs to save and restore v:throwpoint! Does not
18225 * take care of memory allocations.
18227 char_u *
18228 v_throwpoint(oldval)
18229 char_u *oldval;
18231 if (oldval == NULL)
18232 return vimvars[VV_THROWPOINT].vv_str;
18234 vimvars[VV_THROWPOINT].vv_str = oldval;
18235 return NULL;
18238 #if defined(FEAT_AUTOCMD) || defined(PROTO)
18240 * Set v:cmdarg.
18241 * If "eap" != NULL, use "eap" to generate the value and return the old value.
18242 * If "oldarg" != NULL, restore the value to "oldarg" and return NULL.
18243 * Must always be called in pairs!
18245 char_u *
18246 set_cmdarg(eap, oldarg)
18247 exarg_T *eap;
18248 char_u *oldarg;
18250 char_u *oldval;
18251 char_u *newval;
18252 unsigned len;
18254 oldval = vimvars[VV_CMDARG].vv_str;
18255 if (eap == NULL)
18257 vim_free(oldval);
18258 vimvars[VV_CMDARG].vv_str = oldarg;
18259 return NULL;
18262 if (eap->force_bin == FORCE_BIN)
18263 len = 6;
18264 else if (eap->force_bin == FORCE_NOBIN)
18265 len = 8;
18266 else
18267 len = 0;
18269 if (eap->read_edit)
18270 len += 7;
18272 if (eap->force_ff != 0)
18273 len += (unsigned)STRLEN(eap->cmd + eap->force_ff) + 6;
18274 # ifdef FEAT_MBYTE
18275 if (eap->force_enc != 0)
18276 len += (unsigned)STRLEN(eap->cmd + eap->force_enc) + 7;
18277 if (eap->bad_char != 0)
18278 len += (unsigned)STRLEN(eap->cmd + eap->bad_char) + 7;
18279 # endif
18281 newval = alloc(len + 1);
18282 if (newval == NULL)
18283 return NULL;
18285 if (eap->force_bin == FORCE_BIN)
18286 sprintf((char *)newval, " ++bin");
18287 else if (eap->force_bin == FORCE_NOBIN)
18288 sprintf((char *)newval, " ++nobin");
18289 else
18290 *newval = NUL;
18292 if (eap->read_edit)
18293 STRCAT(newval, " ++edit");
18295 if (eap->force_ff != 0)
18296 sprintf((char *)newval + STRLEN(newval), " ++ff=%s",
18297 eap->cmd + eap->force_ff);
18298 # ifdef FEAT_MBYTE
18299 if (eap->force_enc != 0)
18300 sprintf((char *)newval + STRLEN(newval), " ++enc=%s",
18301 eap->cmd + eap->force_enc);
18302 if (eap->bad_char != 0)
18303 sprintf((char *)newval + STRLEN(newval), " ++bad=%s",
18304 eap->cmd + eap->bad_char);
18305 # endif
18306 vimvars[VV_CMDARG].vv_str = newval;
18307 return oldval;
18309 #endif
18312 * Get the value of internal variable "name".
18313 * Return OK or FAIL.
18315 static int
18316 get_var_tv(name, len, rettv, verbose)
18317 char_u *name;
18318 int len; /* length of "name" */
18319 typval_T *rettv; /* NULL when only checking existence */
18320 int verbose; /* may give error message */
18322 int ret = OK;
18323 typval_T *tv = NULL;
18324 typval_T atv;
18325 dictitem_T *v;
18326 int cc;
18328 /* truncate the name, so that we can use strcmp() */
18329 cc = name[len];
18330 name[len] = NUL;
18333 * Check for "b:changedtick".
18335 if (STRCMP(name, "b:changedtick") == 0)
18337 atv.v_type = VAR_NUMBER;
18338 atv.vval.v_number = curbuf->b_changedtick;
18339 tv = &atv;
18343 * Check for user-defined variables.
18345 else
18347 v = find_var(name, NULL);
18348 if (v != NULL)
18349 tv = &v->di_tv;
18352 if (tv == NULL)
18354 if (rettv != NULL && verbose)
18355 EMSG2(_(e_undefvar), name);
18356 ret = FAIL;
18358 else if (rettv != NULL)
18359 copy_tv(tv, rettv);
18361 name[len] = cc;
18363 return ret;
18367 * Handle expr[expr], expr[expr:expr] subscript and .name lookup.
18368 * Also handle function call with Funcref variable: func(expr)
18369 * Can all be combined: dict.func(expr)[idx]['func'](expr)
18371 static int
18372 handle_subscript(arg, rettv, evaluate, verbose)
18373 char_u **arg;
18374 typval_T *rettv;
18375 int evaluate; /* do more than finding the end */
18376 int verbose; /* give error messages */
18378 int ret = OK;
18379 dict_T *selfdict = NULL;
18380 char_u *s;
18381 int len;
18382 typval_T functv;
18384 while (ret == OK
18385 && (**arg == '['
18386 || (**arg == '.' && rettv->v_type == VAR_DICT)
18387 || (**arg == '(' && rettv->v_type == VAR_FUNC))
18388 && !vim_iswhite(*(*arg - 1)))
18390 if (**arg == '(')
18392 /* need to copy the funcref so that we can clear rettv */
18393 functv = *rettv;
18394 rettv->v_type = VAR_UNKNOWN;
18396 /* Invoke the function. Recursive! */
18397 s = functv.vval.v_string;
18398 ret = get_func_tv(s, (int)STRLEN(s), rettv, arg,
18399 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
18400 &len, evaluate, selfdict);
18402 /* Clear the funcref afterwards, so that deleting it while
18403 * evaluating the arguments is possible (see test55). */
18404 clear_tv(&functv);
18406 /* Stop the expression evaluation when immediately aborting on
18407 * error, or when an interrupt occurred or an exception was thrown
18408 * but not caught. */
18409 if (aborting())
18411 if (ret == OK)
18412 clear_tv(rettv);
18413 ret = FAIL;
18415 dict_unref(selfdict);
18416 selfdict = NULL;
18418 else /* **arg == '[' || **arg == '.' */
18420 dict_unref(selfdict);
18421 if (rettv->v_type == VAR_DICT)
18423 selfdict = rettv->vval.v_dict;
18424 if (selfdict != NULL)
18425 ++selfdict->dv_refcount;
18427 else
18428 selfdict = NULL;
18429 if (eval_index(arg, rettv, evaluate, verbose) == FAIL)
18431 clear_tv(rettv);
18432 ret = FAIL;
18436 dict_unref(selfdict);
18437 return ret;
18441 * Allocate memory for a variable type-value, and make it empty (0 or NULL
18442 * value).
18444 static typval_T *
18445 alloc_tv()
18447 return (typval_T *)alloc_clear((unsigned)sizeof(typval_T));
18451 * Allocate memory for a variable type-value, and assign a string to it.
18452 * The string "s" must have been allocated, it is consumed.
18453 * Return NULL for out of memory, the variable otherwise.
18455 static typval_T *
18456 alloc_string_tv(s)
18457 char_u *s;
18459 typval_T *rettv;
18461 rettv = alloc_tv();
18462 if (rettv != NULL)
18464 rettv->v_type = VAR_STRING;
18465 rettv->vval.v_string = s;
18467 else
18468 vim_free(s);
18469 return rettv;
18473 * Free the memory for a variable type-value.
18475 void
18476 free_tv(varp)
18477 typval_T *varp;
18479 if (varp != NULL)
18481 switch (varp->v_type)
18483 case VAR_FUNC:
18484 func_unref(varp->vval.v_string);
18485 /*FALLTHROUGH*/
18486 case VAR_STRING:
18487 vim_free(varp->vval.v_string);
18488 break;
18489 case VAR_LIST:
18490 list_unref(varp->vval.v_list);
18491 break;
18492 case VAR_DICT:
18493 dict_unref(varp->vval.v_dict);
18494 break;
18495 case VAR_NUMBER:
18496 #ifdef FEAT_FLOAT
18497 case VAR_FLOAT:
18498 #endif
18499 case VAR_UNKNOWN:
18500 break;
18501 default:
18502 EMSG2(_(e_intern2), "free_tv()");
18503 break;
18505 vim_free(varp);
18510 * Free the memory for a variable value and set the value to NULL or 0.
18512 void
18513 clear_tv(varp)
18514 typval_T *varp;
18516 if (varp != NULL)
18518 switch (varp->v_type)
18520 case VAR_FUNC:
18521 func_unref(varp->vval.v_string);
18522 /*FALLTHROUGH*/
18523 case VAR_STRING:
18524 vim_free(varp->vval.v_string);
18525 varp->vval.v_string = NULL;
18526 break;
18527 case VAR_LIST:
18528 list_unref(varp->vval.v_list);
18529 varp->vval.v_list = NULL;
18530 break;
18531 case VAR_DICT:
18532 dict_unref(varp->vval.v_dict);
18533 varp->vval.v_dict = NULL;
18534 break;
18535 case VAR_NUMBER:
18536 varp->vval.v_number = 0;
18537 break;
18538 #ifdef FEAT_FLOAT
18539 case VAR_FLOAT:
18540 varp->vval.v_float = 0.0;
18541 break;
18542 #endif
18543 case VAR_UNKNOWN:
18544 break;
18545 default:
18546 EMSG2(_(e_intern2), "clear_tv()");
18548 varp->v_lock = 0;
18553 * Set the value of a variable to NULL without freeing items.
18555 static void
18556 init_tv(varp)
18557 typval_T *varp;
18559 if (varp != NULL)
18560 vim_memset(varp, 0, sizeof(typval_T));
18564 * Get the number value of a variable.
18565 * If it is a String variable, uses vim_str2nr().
18566 * For incompatible types, return 0.
18567 * get_tv_number_chk() is similar to get_tv_number(), but informs the
18568 * caller of incompatible types: it sets *denote to TRUE if "denote"
18569 * is not NULL or returns -1 otherwise.
18571 static long
18572 get_tv_number(varp)
18573 typval_T *varp;
18575 int error = FALSE;
18577 return get_tv_number_chk(varp, &error); /* return 0L on error */
18580 long
18581 get_tv_number_chk(varp, denote)
18582 typval_T *varp;
18583 int *denote;
18585 long n = 0L;
18587 switch (varp->v_type)
18589 case VAR_NUMBER:
18590 return (long)(varp->vval.v_number);
18591 #ifdef FEAT_FLOAT
18592 case VAR_FLOAT:
18593 EMSG(_("E805: Using a Float as a Number"));
18594 break;
18595 #endif
18596 case VAR_FUNC:
18597 EMSG(_("E703: Using a Funcref as a Number"));
18598 break;
18599 case VAR_STRING:
18600 if (varp->vval.v_string != NULL)
18601 vim_str2nr(varp->vval.v_string, NULL, NULL,
18602 TRUE, TRUE, &n, NULL);
18603 return n;
18604 case VAR_LIST:
18605 EMSG(_("E745: Using a List as a Number"));
18606 break;
18607 case VAR_DICT:
18608 EMSG(_("E728: Using a Dictionary as a Number"));
18609 break;
18610 default:
18611 EMSG2(_(e_intern2), "get_tv_number()");
18612 break;
18614 if (denote == NULL) /* useful for values that must be unsigned */
18615 n = -1;
18616 else
18617 *denote = TRUE;
18618 return n;
18622 * Get the lnum from the first argument.
18623 * Also accepts ".", "$", etc., but that only works for the current buffer.
18624 * Returns -1 on error.
18626 static linenr_T
18627 get_tv_lnum(argvars)
18628 typval_T *argvars;
18630 typval_T rettv;
18631 linenr_T lnum;
18633 lnum = get_tv_number_chk(&argvars[0], NULL);
18634 if (lnum == 0) /* no valid number, try using line() */
18636 rettv.v_type = VAR_NUMBER;
18637 f_line(argvars, &rettv);
18638 lnum = rettv.vval.v_number;
18639 clear_tv(&rettv);
18641 return lnum;
18645 * Get the lnum from the first argument.
18646 * Also accepts "$", then "buf" is used.
18647 * Returns 0 on error.
18649 static linenr_T
18650 get_tv_lnum_buf(argvars, buf)
18651 typval_T *argvars;
18652 buf_T *buf;
18654 if (argvars[0].v_type == VAR_STRING
18655 && argvars[0].vval.v_string != NULL
18656 && argvars[0].vval.v_string[0] == '$'
18657 && buf != NULL)
18658 return buf->b_ml.ml_line_count;
18659 return get_tv_number_chk(&argvars[0], NULL);
18663 * Get the string value of a variable.
18664 * If it is a Number variable, the number is converted into a string.
18665 * get_tv_string() uses a single, static buffer. YOU CAN ONLY USE IT ONCE!
18666 * get_tv_string_buf() uses a given buffer.
18667 * If the String variable has never been set, return an empty string.
18668 * Never returns NULL;
18669 * get_tv_string_chk() and get_tv_string_buf_chk() are similar, but return
18670 * NULL on error.
18672 static char_u *
18673 get_tv_string(varp)
18674 typval_T *varp;
18676 static char_u mybuf[NUMBUFLEN];
18678 return get_tv_string_buf(varp, mybuf);
18681 static char_u *
18682 get_tv_string_buf(varp, buf)
18683 typval_T *varp;
18684 char_u *buf;
18686 char_u *res = get_tv_string_buf_chk(varp, buf);
18688 return res != NULL ? res : (char_u *)"";
18691 char_u *
18692 get_tv_string_chk(varp)
18693 typval_T *varp;
18695 static char_u mybuf[NUMBUFLEN];
18697 return get_tv_string_buf_chk(varp, mybuf);
18700 static char_u *
18701 get_tv_string_buf_chk(varp, buf)
18702 typval_T *varp;
18703 char_u *buf;
18705 switch (varp->v_type)
18707 case VAR_NUMBER:
18708 sprintf((char *)buf, "%ld", (long)varp->vval.v_number);
18709 return buf;
18710 case VAR_FUNC:
18711 EMSG(_("E729: using Funcref as a String"));
18712 break;
18713 case VAR_LIST:
18714 EMSG(_("E730: using List as a String"));
18715 break;
18716 case VAR_DICT:
18717 EMSG(_("E731: using Dictionary as a String"));
18718 break;
18719 #ifdef FEAT_FLOAT
18720 case VAR_FLOAT:
18721 EMSG(_("E806: using Float as a String"));
18722 break;
18723 #endif
18724 case VAR_STRING:
18725 if (varp->vval.v_string != NULL)
18726 return varp->vval.v_string;
18727 return (char_u *)"";
18728 default:
18729 EMSG2(_(e_intern2), "get_tv_string_buf()");
18730 break;
18732 return NULL;
18736 * Find variable "name" in the list of variables.
18737 * Return a pointer to it if found, NULL if not found.
18738 * Careful: "a:0" variables don't have a name.
18739 * When "htp" is not NULL we are writing to the variable, set "htp" to the
18740 * hashtab_T used.
18742 static dictitem_T *
18743 find_var(name, htp)
18744 char_u *name;
18745 hashtab_T **htp;
18747 char_u *varname;
18748 hashtab_T *ht;
18750 ht = find_var_ht(name, &varname);
18751 if (htp != NULL)
18752 *htp = ht;
18753 if (ht == NULL)
18754 return NULL;
18755 return find_var_in_ht(ht, varname, htp != NULL);
18759 * Find variable "varname" in hashtab "ht".
18760 * Returns NULL if not found.
18762 static dictitem_T *
18763 find_var_in_ht(ht, varname, writing)
18764 hashtab_T *ht;
18765 char_u *varname;
18766 int writing;
18768 hashitem_T *hi;
18770 if (*varname == NUL)
18772 /* Must be something like "s:", otherwise "ht" would be NULL. */
18773 switch (varname[-2])
18775 case 's': return &SCRIPT_SV(current_SID).sv_var;
18776 case 'g': return &globvars_var;
18777 case 'v': return &vimvars_var;
18778 case 'b': return &curbuf->b_bufvar;
18779 case 'w': return &curwin->w_winvar;
18780 #ifdef FEAT_WINDOWS
18781 case 't': return &curtab->tp_winvar;
18782 #endif
18783 case 'l': return current_funccal == NULL
18784 ? NULL : &current_funccal->l_vars_var;
18785 case 'a': return current_funccal == NULL
18786 ? NULL : &current_funccal->l_avars_var;
18788 return NULL;
18791 hi = hash_find(ht, varname);
18792 if (HASHITEM_EMPTY(hi))
18794 /* For global variables we may try auto-loading the script. If it
18795 * worked find the variable again. Don't auto-load a script if it was
18796 * loaded already, otherwise it would be loaded every time when
18797 * checking if a function name is a Funcref variable. */
18798 if (ht == &globvarht && !writing
18799 && script_autoload(varname, FALSE) && !aborting())
18800 hi = hash_find(ht, varname);
18801 if (HASHITEM_EMPTY(hi))
18802 return NULL;
18804 return HI2DI(hi);
18808 * Find the hashtab used for a variable name.
18809 * Set "varname" to the start of name without ':'.
18811 static hashtab_T *
18812 find_var_ht(name, varname)
18813 char_u *name;
18814 char_u **varname;
18816 hashitem_T *hi;
18818 if (name[1] != ':')
18820 /* The name must not start with a colon or #. */
18821 if (name[0] == ':' || name[0] == AUTOLOAD_CHAR)
18822 return NULL;
18823 *varname = name;
18825 /* "version" is "v:version" in all scopes */
18826 hi = hash_find(&compat_hashtab, name);
18827 if (!HASHITEM_EMPTY(hi))
18828 return &compat_hashtab;
18830 if (current_funccal == NULL)
18831 return &globvarht; /* global variable */
18832 return &current_funccal->l_vars.dv_hashtab; /* l: variable */
18834 *varname = name + 2;
18835 if (*name == 'g') /* global variable */
18836 return &globvarht;
18837 /* There must be no ':' or '#' in the rest of the name, unless g: is used
18839 if (vim_strchr(name + 2, ':') != NULL
18840 || vim_strchr(name + 2, AUTOLOAD_CHAR) != NULL)
18841 return NULL;
18842 if (*name == 'b') /* buffer variable */
18843 return &curbuf->b_vars.dv_hashtab;
18844 if (*name == 'w') /* window variable */
18845 return &curwin->w_vars.dv_hashtab;
18846 #ifdef FEAT_WINDOWS
18847 if (*name == 't') /* tab page variable */
18848 return &curtab->tp_vars.dv_hashtab;
18849 #endif
18850 if (*name == 'v') /* v: variable */
18851 return &vimvarht;
18852 if (*name == 'a' && current_funccal != NULL) /* function argument */
18853 return &current_funccal->l_avars.dv_hashtab;
18854 if (*name == 'l' && current_funccal != NULL) /* local function variable */
18855 return &current_funccal->l_vars.dv_hashtab;
18856 if (*name == 's' /* script variable */
18857 && current_SID > 0 && current_SID <= ga_scripts.ga_len)
18858 return &SCRIPT_VARS(current_SID);
18859 return NULL;
18863 * Get the string value of a (global/local) variable.
18864 * Returns NULL when it doesn't exist.
18866 char_u *
18867 get_var_value(name)
18868 char_u *name;
18870 dictitem_T *v;
18872 v = find_var(name, NULL);
18873 if (v == NULL)
18874 return NULL;
18875 return get_tv_string(&v->di_tv);
18879 * Allocate a new hashtab for a sourced script. It will be used while
18880 * sourcing this script and when executing functions defined in the script.
18882 void
18883 new_script_vars(id)
18884 scid_T id;
18886 int i;
18887 hashtab_T *ht;
18888 scriptvar_T *sv;
18890 if (ga_grow(&ga_scripts, (int)(id - ga_scripts.ga_len)) == OK)
18892 /* Re-allocating ga_data means that an ht_array pointing to
18893 * ht_smallarray becomes invalid. We can recognize this: ht_mask is
18894 * at its init value. Also reset "v_dict", it's always the same. */
18895 for (i = 1; i <= ga_scripts.ga_len; ++i)
18897 ht = &SCRIPT_VARS(i);
18898 if (ht->ht_mask == HT_INIT_SIZE - 1)
18899 ht->ht_array = ht->ht_smallarray;
18900 sv = &SCRIPT_SV(i);
18901 sv->sv_var.di_tv.vval.v_dict = &sv->sv_dict;
18904 while (ga_scripts.ga_len < id)
18906 sv = &SCRIPT_SV(ga_scripts.ga_len + 1);
18907 init_var_dict(&sv->sv_dict, &sv->sv_var);
18908 ++ga_scripts.ga_len;
18914 * Initialize dictionary "dict" as a scope and set variable "dict_var" to
18915 * point to it.
18917 void
18918 init_var_dict(dict, dict_var)
18919 dict_T *dict;
18920 dictitem_T *dict_var;
18922 hash_init(&dict->dv_hashtab);
18923 dict->dv_refcount = DO_NOT_FREE_CNT;
18924 dict_var->di_tv.vval.v_dict = dict;
18925 dict_var->di_tv.v_type = VAR_DICT;
18926 dict_var->di_tv.v_lock = VAR_FIXED;
18927 dict_var->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
18928 dict_var->di_key[0] = NUL;
18932 * Clean up a list of internal variables.
18933 * Frees all allocated variables and the value they contain.
18934 * Clears hashtab "ht", does not free it.
18936 void
18937 vars_clear(ht)
18938 hashtab_T *ht;
18940 vars_clear_ext(ht, TRUE);
18944 * Like vars_clear(), but only free the value if "free_val" is TRUE.
18946 static void
18947 vars_clear_ext(ht, free_val)
18948 hashtab_T *ht;
18949 int free_val;
18951 int todo;
18952 hashitem_T *hi;
18953 dictitem_T *v;
18955 hash_lock(ht);
18956 todo = (int)ht->ht_used;
18957 for (hi = ht->ht_array; todo > 0; ++hi)
18959 if (!HASHITEM_EMPTY(hi))
18961 --todo;
18963 /* Free the variable. Don't remove it from the hashtab,
18964 * ht_array might change then. hash_clear() takes care of it
18965 * later. */
18966 v = HI2DI(hi);
18967 if (free_val)
18968 clear_tv(&v->di_tv);
18969 if ((v->di_flags & DI_FLAGS_FIX) == 0)
18970 vim_free(v);
18973 hash_clear(ht);
18974 ht->ht_used = 0;
18978 * Delete a variable from hashtab "ht" at item "hi".
18979 * Clear the variable value and free the dictitem.
18981 static void
18982 delete_var(ht, hi)
18983 hashtab_T *ht;
18984 hashitem_T *hi;
18986 dictitem_T *di = HI2DI(hi);
18988 hash_remove(ht, hi);
18989 clear_tv(&di->di_tv);
18990 vim_free(di);
18994 * List the value of one internal variable.
18996 static void
18997 list_one_var(v, prefix, first)
18998 dictitem_T *v;
18999 char_u *prefix;
19000 int *first;
19002 char_u *tofree;
19003 char_u *s;
19004 char_u numbuf[NUMBUFLEN];
19006 s = echo_string(&v->di_tv, &tofree, numbuf, ++current_copyID);
19007 list_one_var_a(prefix, v->di_key, v->di_tv.v_type,
19008 s == NULL ? (char_u *)"" : s, first);
19009 vim_free(tofree);
19012 static void
19013 list_one_var_a(prefix, name, type, string, first)
19014 char_u *prefix;
19015 char_u *name;
19016 int type;
19017 char_u *string;
19018 int *first; /* when TRUE clear rest of screen and set to FALSE */
19020 /* don't use msg() or msg_attr() to avoid overwriting "v:statusmsg" */
19021 msg_start();
19022 msg_puts(prefix);
19023 if (name != NULL) /* "a:" vars don't have a name stored */
19024 msg_puts(name);
19025 msg_putchar(' ');
19026 msg_advance(22);
19027 if (type == VAR_NUMBER)
19028 msg_putchar('#');
19029 else if (type == VAR_FUNC)
19030 msg_putchar('*');
19031 else if (type == VAR_LIST)
19033 msg_putchar('[');
19034 if (*string == '[')
19035 ++string;
19037 else if (type == VAR_DICT)
19039 msg_putchar('{');
19040 if (*string == '{')
19041 ++string;
19043 else
19044 msg_putchar(' ');
19046 msg_outtrans(string);
19048 if (type == VAR_FUNC)
19049 msg_puts((char_u *)"()");
19050 if (*first)
19052 msg_clr_eos();
19053 *first = FALSE;
19058 * Set variable "name" to value in "tv".
19059 * If the variable already exists, the value is updated.
19060 * Otherwise the variable is created.
19062 static void
19063 set_var(name, tv, copy)
19064 char_u *name;
19065 typval_T *tv;
19066 int copy; /* make copy of value in "tv" */
19068 dictitem_T *v;
19069 char_u *varname;
19070 hashtab_T *ht;
19071 char_u *p;
19073 if (tv->v_type == VAR_FUNC)
19075 if (!(vim_strchr((char_u *)"wbs", name[0]) != NULL && name[1] == ':')
19076 && !ASCII_ISUPPER((name[0] != NUL && name[1] == ':')
19077 ? name[2] : name[0]))
19079 EMSG2(_("E704: Funcref variable name must start with a capital: %s"), name);
19080 return;
19082 if (function_exists(name))
19084 EMSG2(_("E705: Variable name conflicts with existing function: %s"),
19085 name);
19086 return;
19090 ht = find_var_ht(name, &varname);
19091 if (ht == NULL || *varname == NUL)
19093 EMSG2(_(e_illvar), name);
19094 return;
19097 v = find_var_in_ht(ht, varname, TRUE);
19098 if (v != NULL)
19100 /* existing variable, need to clear the value */
19101 if (var_check_ro(v->di_flags, name)
19102 || tv_check_lock(v->di_tv.v_lock, name))
19103 return;
19104 if (v->di_tv.v_type != tv->v_type
19105 && !((v->di_tv.v_type == VAR_STRING
19106 || v->di_tv.v_type == VAR_NUMBER)
19107 && (tv->v_type == VAR_STRING
19108 || tv->v_type == VAR_NUMBER))
19109 #ifdef FEAT_FLOAT
19110 && !((v->di_tv.v_type == VAR_NUMBER
19111 || v->di_tv.v_type == VAR_FLOAT)
19112 && (tv->v_type == VAR_NUMBER
19113 || tv->v_type == VAR_FLOAT))
19114 #endif
19117 EMSG2(_("E706: Variable type mismatch for: %s"), name);
19118 return;
19122 * Handle setting internal v: variables separately: we don't change
19123 * the type.
19125 if (ht == &vimvarht)
19127 if (v->di_tv.v_type == VAR_STRING)
19129 vim_free(v->di_tv.vval.v_string);
19130 if (copy || tv->v_type != VAR_STRING)
19131 v->di_tv.vval.v_string = vim_strsave(get_tv_string(tv));
19132 else
19134 /* Take over the string to avoid an extra alloc/free. */
19135 v->di_tv.vval.v_string = tv->vval.v_string;
19136 tv->vval.v_string = NULL;
19139 else if (v->di_tv.v_type != VAR_NUMBER)
19140 EMSG2(_(e_intern2), "set_var()");
19141 else
19143 v->di_tv.vval.v_number = get_tv_number(tv);
19144 if (STRCMP(varname, "searchforward") == 0)
19145 set_search_direction(v->di_tv.vval.v_number ? '/' : '?');
19147 return;
19150 clear_tv(&v->di_tv);
19152 else /* add a new variable */
19154 /* Can't add "v:" variable. */
19155 if (ht == &vimvarht)
19157 EMSG2(_(e_illvar), name);
19158 return;
19161 /* Make sure the variable name is valid. */
19162 for (p = varname; *p != NUL; ++p)
19163 if (!eval_isnamec1(*p) && (p == varname || !VIM_ISDIGIT(*p))
19164 && *p != AUTOLOAD_CHAR)
19166 EMSG2(_(e_illvar), varname);
19167 return;
19170 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
19171 + STRLEN(varname)));
19172 if (v == NULL)
19173 return;
19174 STRCPY(v->di_key, varname);
19175 if (hash_add(ht, DI2HIKEY(v)) == FAIL)
19177 vim_free(v);
19178 return;
19180 v->di_flags = 0;
19183 if (copy || tv->v_type == VAR_NUMBER || tv->v_type == VAR_FLOAT)
19184 copy_tv(tv, &v->di_tv);
19185 else
19187 v->di_tv = *tv;
19188 v->di_tv.v_lock = 0;
19189 init_tv(tv);
19194 * Return TRUE if di_flags "flags" indicates variable "name" is read-only.
19195 * Also give an error message.
19197 static int
19198 var_check_ro(flags, name)
19199 int flags;
19200 char_u *name;
19202 if (flags & DI_FLAGS_RO)
19204 EMSG2(_(e_readonlyvar), name);
19205 return TRUE;
19207 if ((flags & DI_FLAGS_RO_SBX) && sandbox)
19209 EMSG2(_(e_readonlysbx), name);
19210 return TRUE;
19212 return FALSE;
19216 * Return TRUE if di_flags "flags" indicates variable "name" is fixed.
19217 * Also give an error message.
19219 static int
19220 var_check_fixed(flags, name)
19221 int flags;
19222 char_u *name;
19224 if (flags & DI_FLAGS_FIX)
19226 EMSG2(_("E795: Cannot delete variable %s"), name);
19227 return TRUE;
19229 return FALSE;
19233 * Return TRUE if typeval "tv" is set to be locked (immutable).
19234 * Also give an error message, using "name".
19236 static int
19237 tv_check_lock(lock, name)
19238 int lock;
19239 char_u *name;
19241 if (lock & VAR_LOCKED)
19243 EMSG2(_("E741: Value is locked: %s"),
19244 name == NULL ? (char_u *)_("Unknown") : name);
19245 return TRUE;
19247 if (lock & VAR_FIXED)
19249 EMSG2(_("E742: Cannot change value of %s"),
19250 name == NULL ? (char_u *)_("Unknown") : name);
19251 return TRUE;
19253 return FALSE;
19257 * Copy the values from typval_T "from" to typval_T "to".
19258 * When needed allocates string or increases reference count.
19259 * Does not make a copy of a list or dict but copies the reference!
19260 * It is OK for "from" and "to" to point to the same item. This is used to
19261 * make a copy later.
19263 static void
19264 copy_tv(from, to)
19265 typval_T *from;
19266 typval_T *to;
19268 to->v_type = from->v_type;
19269 to->v_lock = 0;
19270 switch (from->v_type)
19272 case VAR_NUMBER:
19273 to->vval.v_number = from->vval.v_number;
19274 break;
19275 #ifdef FEAT_FLOAT
19276 case VAR_FLOAT:
19277 to->vval.v_float = from->vval.v_float;
19278 break;
19279 #endif
19280 case VAR_STRING:
19281 case VAR_FUNC:
19282 if (from->vval.v_string == NULL)
19283 to->vval.v_string = NULL;
19284 else
19286 to->vval.v_string = vim_strsave(from->vval.v_string);
19287 if (from->v_type == VAR_FUNC)
19288 func_ref(to->vval.v_string);
19290 break;
19291 case VAR_LIST:
19292 if (from->vval.v_list == NULL)
19293 to->vval.v_list = NULL;
19294 else
19296 to->vval.v_list = from->vval.v_list;
19297 ++to->vval.v_list->lv_refcount;
19299 break;
19300 case VAR_DICT:
19301 if (from->vval.v_dict == NULL)
19302 to->vval.v_dict = NULL;
19303 else
19305 to->vval.v_dict = from->vval.v_dict;
19306 ++to->vval.v_dict->dv_refcount;
19308 break;
19309 default:
19310 EMSG2(_(e_intern2), "copy_tv()");
19311 break;
19316 * Make a copy of an item.
19317 * Lists and Dictionaries are also copied. A deep copy if "deep" is set.
19318 * For deepcopy() "copyID" is zero for a full copy or the ID for when a
19319 * reference to an already copied list/dict can be used.
19320 * Returns FAIL or OK.
19322 static int
19323 item_copy(from, to, deep, copyID)
19324 typval_T *from;
19325 typval_T *to;
19326 int deep;
19327 int copyID;
19329 static int recurse = 0;
19330 int ret = OK;
19332 if (recurse >= DICT_MAXNEST)
19334 EMSG(_("E698: variable nested too deep for making a copy"));
19335 return FAIL;
19337 ++recurse;
19339 switch (from->v_type)
19341 case VAR_NUMBER:
19342 #ifdef FEAT_FLOAT
19343 case VAR_FLOAT:
19344 #endif
19345 case VAR_STRING:
19346 case VAR_FUNC:
19347 copy_tv(from, to);
19348 break;
19349 case VAR_LIST:
19350 to->v_type = VAR_LIST;
19351 to->v_lock = 0;
19352 if (from->vval.v_list == NULL)
19353 to->vval.v_list = NULL;
19354 else if (copyID != 0 && from->vval.v_list->lv_copyID == copyID)
19356 /* use the copy made earlier */
19357 to->vval.v_list = from->vval.v_list->lv_copylist;
19358 ++to->vval.v_list->lv_refcount;
19360 else
19361 to->vval.v_list = list_copy(from->vval.v_list, deep, copyID);
19362 if (to->vval.v_list == NULL)
19363 ret = FAIL;
19364 break;
19365 case VAR_DICT:
19366 to->v_type = VAR_DICT;
19367 to->v_lock = 0;
19368 if (from->vval.v_dict == NULL)
19369 to->vval.v_dict = NULL;
19370 else if (copyID != 0 && from->vval.v_dict->dv_copyID == copyID)
19372 /* use the copy made earlier */
19373 to->vval.v_dict = from->vval.v_dict->dv_copydict;
19374 ++to->vval.v_dict->dv_refcount;
19376 else
19377 to->vval.v_dict = dict_copy(from->vval.v_dict, deep, copyID);
19378 if (to->vval.v_dict == NULL)
19379 ret = FAIL;
19380 break;
19381 default:
19382 EMSG2(_(e_intern2), "item_copy()");
19383 ret = FAIL;
19385 --recurse;
19386 return ret;
19390 * ":echo expr1 ..." print each argument separated with a space, add a
19391 * newline at the end.
19392 * ":echon expr1 ..." print each argument plain.
19394 void
19395 ex_echo(eap)
19396 exarg_T *eap;
19398 char_u *arg = eap->arg;
19399 typval_T rettv;
19400 char_u *tofree;
19401 char_u *p;
19402 int needclr = TRUE;
19403 int atstart = TRUE;
19404 char_u numbuf[NUMBUFLEN];
19406 if (eap->skip)
19407 ++emsg_skip;
19408 while (*arg != NUL && *arg != '|' && *arg != '\n' && !got_int)
19410 /* If eval1() causes an error message the text from the command may
19411 * still need to be cleared. E.g., "echo 22,44". */
19412 need_clr_eos = needclr;
19414 p = arg;
19415 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
19418 * Report the invalid expression unless the expression evaluation
19419 * has been cancelled due to an aborting error, an interrupt, or an
19420 * exception.
19422 if (!aborting())
19423 EMSG2(_(e_invexpr2), p);
19424 need_clr_eos = FALSE;
19425 break;
19427 need_clr_eos = FALSE;
19429 if (!eap->skip)
19431 if (atstart)
19433 atstart = FALSE;
19434 /* Call msg_start() after eval1(), evaluating the expression
19435 * may cause a message to appear. */
19436 if (eap->cmdidx == CMD_echo)
19437 msg_start();
19439 else if (eap->cmdidx == CMD_echo)
19440 msg_puts_attr((char_u *)" ", echo_attr);
19441 p = echo_string(&rettv, &tofree, numbuf, ++current_copyID);
19442 if (p != NULL)
19443 for ( ; *p != NUL && !got_int; ++p)
19445 if (*p == '\n' || *p == '\r' || *p == TAB)
19447 if (*p != TAB && needclr)
19449 /* remove any text still there from the command */
19450 msg_clr_eos();
19451 needclr = FALSE;
19453 msg_putchar_attr(*p, echo_attr);
19455 else
19457 #ifdef FEAT_MBYTE
19458 if (has_mbyte)
19460 int i = (*mb_ptr2len)(p);
19462 (void)msg_outtrans_len_attr(p, i, echo_attr);
19463 p += i - 1;
19465 else
19466 #endif
19467 (void)msg_outtrans_len_attr(p, 1, echo_attr);
19470 vim_free(tofree);
19472 clear_tv(&rettv);
19473 arg = skipwhite(arg);
19475 eap->nextcmd = check_nextcmd(arg);
19477 if (eap->skip)
19478 --emsg_skip;
19479 else
19481 /* remove text that may still be there from the command */
19482 if (needclr)
19483 msg_clr_eos();
19484 if (eap->cmdidx == CMD_echo)
19485 msg_end();
19490 * ":echohl {name}".
19492 void
19493 ex_echohl(eap)
19494 exarg_T *eap;
19496 int id;
19498 id = syn_name2id(eap->arg);
19499 if (id == 0)
19500 echo_attr = 0;
19501 else
19502 echo_attr = syn_id2attr(id);
19506 * ":execute expr1 ..." execute the result of an expression.
19507 * ":echomsg expr1 ..." Print a message
19508 * ":echoerr expr1 ..." Print an error
19509 * Each gets spaces around each argument and a newline at the end for
19510 * echo commands
19512 void
19513 ex_execute(eap)
19514 exarg_T *eap;
19516 char_u *arg = eap->arg;
19517 typval_T rettv;
19518 int ret = OK;
19519 char_u *p;
19520 garray_T ga;
19521 int len;
19522 int save_did_emsg;
19524 ga_init2(&ga, 1, 80);
19526 if (eap->skip)
19527 ++emsg_skip;
19528 while (*arg != NUL && *arg != '|' && *arg != '\n')
19530 p = arg;
19531 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
19534 * Report the invalid expression unless the expression evaluation
19535 * has been cancelled due to an aborting error, an interrupt, or an
19536 * exception.
19538 if (!aborting())
19539 EMSG2(_(e_invexpr2), p);
19540 ret = FAIL;
19541 break;
19544 if (!eap->skip)
19546 p = get_tv_string(&rettv);
19547 len = (int)STRLEN(p);
19548 if (ga_grow(&ga, len + 2) == FAIL)
19550 clear_tv(&rettv);
19551 ret = FAIL;
19552 break;
19554 if (ga.ga_len)
19555 ((char_u *)(ga.ga_data))[ga.ga_len++] = ' ';
19556 STRCPY((char_u *)(ga.ga_data) + ga.ga_len, p);
19557 ga.ga_len += len;
19560 clear_tv(&rettv);
19561 arg = skipwhite(arg);
19564 if (ret != FAIL && ga.ga_data != NULL)
19566 if (eap->cmdidx == CMD_echomsg)
19568 MSG_ATTR(ga.ga_data, echo_attr);
19569 out_flush();
19571 else if (eap->cmdidx == CMD_echoerr)
19573 /* We don't want to abort following commands, restore did_emsg. */
19574 save_did_emsg = did_emsg;
19575 EMSG((char_u *)ga.ga_data);
19576 if (!force_abort)
19577 did_emsg = save_did_emsg;
19579 else if (eap->cmdidx == CMD_execute)
19580 do_cmdline((char_u *)ga.ga_data,
19581 eap->getline, eap->cookie, DOCMD_NOWAIT|DOCMD_VERBOSE);
19584 ga_clear(&ga);
19586 if (eap->skip)
19587 --emsg_skip;
19589 eap->nextcmd = check_nextcmd(arg);
19593 * Skip over the name of an option: "&option", "&g:option" or "&l:option".
19594 * "arg" points to the "&" or '+' when called, to "option" when returning.
19595 * Returns NULL when no option name found. Otherwise pointer to the char
19596 * after the option name.
19598 static char_u *
19599 find_option_end(arg, opt_flags)
19600 char_u **arg;
19601 int *opt_flags;
19603 char_u *p = *arg;
19605 ++p;
19606 if (*p == 'g' && p[1] == ':')
19608 *opt_flags = OPT_GLOBAL;
19609 p += 2;
19611 else if (*p == 'l' && p[1] == ':')
19613 *opt_flags = OPT_LOCAL;
19614 p += 2;
19616 else
19617 *opt_flags = 0;
19619 if (!ASCII_ISALPHA(*p))
19620 return NULL;
19621 *arg = p;
19623 if (p[0] == 't' && p[1] == '_' && p[2] != NUL && p[3] != NUL)
19624 p += 4; /* termcap option */
19625 else
19626 while (ASCII_ISALPHA(*p))
19627 ++p;
19628 return p;
19632 * ":function"
19634 void
19635 ex_function(eap)
19636 exarg_T *eap;
19638 char_u *theline;
19639 int j;
19640 int c;
19641 int saved_did_emsg;
19642 char_u *name = NULL;
19643 char_u *p;
19644 char_u *arg;
19645 char_u *line_arg = NULL;
19646 garray_T newargs;
19647 garray_T newlines;
19648 int varargs = FALSE;
19649 int mustend = FALSE;
19650 int flags = 0;
19651 ufunc_T *fp;
19652 int indent;
19653 int nesting;
19654 char_u *skip_until = NULL;
19655 dictitem_T *v;
19656 funcdict_T fudi;
19657 static int func_nr = 0; /* number for nameless function */
19658 int paren;
19659 hashtab_T *ht;
19660 int todo;
19661 hashitem_T *hi;
19662 int sourcing_lnum_off;
19665 * ":function" without argument: list functions.
19667 if (ends_excmd(*eap->arg))
19669 if (!eap->skip)
19671 todo = (int)func_hashtab.ht_used;
19672 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
19674 if (!HASHITEM_EMPTY(hi))
19676 --todo;
19677 fp = HI2UF(hi);
19678 if (!isdigit(*fp->uf_name))
19679 list_func_head(fp, FALSE);
19683 eap->nextcmd = check_nextcmd(eap->arg);
19684 return;
19688 * ":function /pat": list functions matching pattern.
19690 if (*eap->arg == '/')
19692 p = skip_regexp(eap->arg + 1, '/', TRUE, NULL);
19693 if (!eap->skip)
19695 regmatch_T regmatch;
19697 c = *p;
19698 *p = NUL;
19699 regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC);
19700 *p = c;
19701 if (regmatch.regprog != NULL)
19703 regmatch.rm_ic = p_ic;
19705 todo = (int)func_hashtab.ht_used;
19706 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
19708 if (!HASHITEM_EMPTY(hi))
19710 --todo;
19711 fp = HI2UF(hi);
19712 if (!isdigit(*fp->uf_name)
19713 && vim_regexec(&regmatch, fp->uf_name, 0))
19714 list_func_head(fp, FALSE);
19717 vim_free(regmatch.regprog);
19720 if (*p == '/')
19721 ++p;
19722 eap->nextcmd = check_nextcmd(p);
19723 return;
19727 * Get the function name. There are these situations:
19728 * func normal function name
19729 * "name" == func, "fudi.fd_dict" == NULL
19730 * dict.func new dictionary entry
19731 * "name" == NULL, "fudi.fd_dict" set,
19732 * "fudi.fd_di" == NULL, "fudi.fd_newkey" == func
19733 * dict.func existing dict entry with a Funcref
19734 * "name" == func, "fudi.fd_dict" set,
19735 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
19736 * dict.func existing dict entry that's not a Funcref
19737 * "name" == NULL, "fudi.fd_dict" set,
19738 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
19740 p = eap->arg;
19741 name = trans_function_name(&p, eap->skip, 0, &fudi);
19742 paren = (vim_strchr(p, '(') != NULL);
19743 if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip)
19746 * Return on an invalid expression in braces, unless the expression
19747 * evaluation has been cancelled due to an aborting error, an
19748 * interrupt, or an exception.
19750 if (!aborting())
19752 if (!eap->skip && fudi.fd_newkey != NULL)
19753 EMSG2(_(e_dictkey), fudi.fd_newkey);
19754 vim_free(fudi.fd_newkey);
19755 return;
19757 else
19758 eap->skip = TRUE;
19761 /* An error in a function call during evaluation of an expression in magic
19762 * braces should not cause the function not to be defined. */
19763 saved_did_emsg = did_emsg;
19764 did_emsg = FALSE;
19767 * ":function func" with only function name: list function.
19769 if (!paren)
19771 if (!ends_excmd(*skipwhite(p)))
19773 EMSG(_(e_trailing));
19774 goto ret_free;
19776 eap->nextcmd = check_nextcmd(p);
19777 if (eap->nextcmd != NULL)
19778 *p = NUL;
19779 if (!eap->skip && !got_int)
19781 fp = find_func(name);
19782 if (fp != NULL)
19784 list_func_head(fp, TRUE);
19785 for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j)
19787 if (FUNCLINE(fp, j) == NULL)
19788 continue;
19789 msg_putchar('\n');
19790 msg_outnum((long)(j + 1));
19791 if (j < 9)
19792 msg_putchar(' ');
19793 if (j < 99)
19794 msg_putchar(' ');
19795 msg_prt_line(FUNCLINE(fp, j), FALSE);
19796 out_flush(); /* show a line at a time */
19797 ui_breakcheck();
19799 if (!got_int)
19801 msg_putchar('\n');
19802 msg_puts((char_u *)" endfunction");
19805 else
19806 emsg_funcname(N_("E123: Undefined function: %s"), name);
19808 goto ret_free;
19812 * ":function name(arg1, arg2)" Define function.
19814 p = skipwhite(p);
19815 if (*p != '(')
19817 if (!eap->skip)
19819 EMSG2(_("E124: Missing '(': %s"), eap->arg);
19820 goto ret_free;
19822 /* attempt to continue by skipping some text */
19823 if (vim_strchr(p, '(') != NULL)
19824 p = vim_strchr(p, '(');
19826 p = skipwhite(p + 1);
19828 ga_init2(&newargs, (int)sizeof(char_u *), 3);
19829 ga_init2(&newlines, (int)sizeof(char_u *), 3);
19831 if (!eap->skip)
19833 /* Check the name of the function. Unless it's a dictionary function
19834 * (that we are overwriting). */
19835 if (name != NULL)
19836 arg = name;
19837 else
19838 arg = fudi.fd_newkey;
19839 if (arg != NULL && (fudi.fd_di == NULL
19840 || fudi.fd_di->di_tv.v_type != VAR_FUNC))
19842 if (*arg == K_SPECIAL)
19843 j = 3;
19844 else
19845 j = 0;
19846 while (arg[j] != NUL && (j == 0 ? eval_isnamec1(arg[j])
19847 : eval_isnamec(arg[j])))
19848 ++j;
19849 if (arg[j] != NUL)
19850 emsg_funcname((char *)e_invarg2, arg);
19855 * Isolate the arguments: "arg1, arg2, ...)"
19857 while (*p != ')')
19859 if (p[0] == '.' && p[1] == '.' && p[2] == '.')
19861 varargs = TRUE;
19862 p += 3;
19863 mustend = TRUE;
19865 else
19867 arg = p;
19868 while (ASCII_ISALNUM(*p) || *p == '_')
19869 ++p;
19870 if (arg == p || isdigit(*arg)
19871 || (p - arg == 9 && STRNCMP(arg, "firstline", 9) == 0)
19872 || (p - arg == 8 && STRNCMP(arg, "lastline", 8) == 0))
19874 if (!eap->skip)
19875 EMSG2(_("E125: Illegal argument: %s"), arg);
19876 break;
19878 if (ga_grow(&newargs, 1) == FAIL)
19879 goto erret;
19880 c = *p;
19881 *p = NUL;
19882 arg = vim_strsave(arg);
19883 if (arg == NULL)
19884 goto erret;
19885 ((char_u **)(newargs.ga_data))[newargs.ga_len] = arg;
19886 *p = c;
19887 newargs.ga_len++;
19888 if (*p == ',')
19889 ++p;
19890 else
19891 mustend = TRUE;
19893 p = skipwhite(p);
19894 if (mustend && *p != ')')
19896 if (!eap->skip)
19897 EMSG2(_(e_invarg2), eap->arg);
19898 break;
19901 ++p; /* skip the ')' */
19903 /* find extra arguments "range", "dict" and "abort" */
19904 for (;;)
19906 p = skipwhite(p);
19907 if (STRNCMP(p, "range", 5) == 0)
19909 flags |= FC_RANGE;
19910 p += 5;
19912 else if (STRNCMP(p, "dict", 4) == 0)
19914 flags |= FC_DICT;
19915 p += 4;
19917 else if (STRNCMP(p, "abort", 5) == 0)
19919 flags |= FC_ABORT;
19920 p += 5;
19922 else
19923 break;
19926 /* When there is a line break use what follows for the function body.
19927 * Makes 'exe "func Test()\n...\nendfunc"' work. */
19928 if (*p == '\n')
19929 line_arg = p + 1;
19930 else if (*p != NUL && *p != '"' && !eap->skip && !did_emsg)
19931 EMSG(_(e_trailing));
19934 * Read the body of the function, until ":endfunction" is found.
19936 if (KeyTyped)
19938 /* Check if the function already exists, don't let the user type the
19939 * whole function before telling him it doesn't work! For a script we
19940 * need to skip the body to be able to find what follows. */
19941 if (!eap->skip && !eap->forceit)
19943 if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL)
19944 EMSG(_(e_funcdict));
19945 else if (name != NULL && find_func(name) != NULL)
19946 emsg_funcname(e_funcexts, name);
19949 if (!eap->skip && did_emsg)
19950 goto erret;
19952 msg_putchar('\n'); /* don't overwrite the function name */
19953 cmdline_row = msg_row;
19956 indent = 2;
19957 nesting = 0;
19958 for (;;)
19960 msg_scroll = TRUE;
19961 need_wait_return = FALSE;
19962 sourcing_lnum_off = sourcing_lnum;
19964 if (line_arg != NULL)
19966 /* Use eap->arg, split up in parts by line breaks. */
19967 theline = line_arg;
19968 p = vim_strchr(theline, '\n');
19969 if (p == NULL)
19970 line_arg += STRLEN(line_arg);
19971 else
19973 *p = NUL;
19974 line_arg = p + 1;
19977 else if (eap->getline == NULL)
19978 theline = getcmdline(':', 0L, indent);
19979 else
19980 theline = eap->getline(':', eap->cookie, indent);
19981 if (KeyTyped)
19982 lines_left = Rows - 1;
19983 if (theline == NULL)
19985 EMSG(_("E126: Missing :endfunction"));
19986 goto erret;
19989 /* Detect line continuation: sourcing_lnum increased more than one. */
19990 if (sourcing_lnum > sourcing_lnum_off + 1)
19991 sourcing_lnum_off = sourcing_lnum - sourcing_lnum_off - 1;
19992 else
19993 sourcing_lnum_off = 0;
19995 if (skip_until != NULL)
19997 /* between ":append" and "." and between ":python <<EOF" and "EOF"
19998 * don't check for ":endfunc". */
19999 if (STRCMP(theline, skip_until) == 0)
20001 vim_free(skip_until);
20002 skip_until = NULL;
20005 else
20007 /* skip ':' and blanks*/
20008 for (p = theline; vim_iswhite(*p) || *p == ':'; ++p)
20011 /* Check for "endfunction". */
20012 if (checkforcmd(&p, "endfunction", 4) && nesting-- == 0)
20014 if (line_arg == NULL)
20015 vim_free(theline);
20016 break;
20019 /* Increase indent inside "if", "while", "for" and "try", decrease
20020 * at "end". */
20021 if (indent > 2 && STRNCMP(p, "end", 3) == 0)
20022 indent -= 2;
20023 else if (STRNCMP(p, "if", 2) == 0
20024 || STRNCMP(p, "wh", 2) == 0
20025 || STRNCMP(p, "for", 3) == 0
20026 || STRNCMP(p, "try", 3) == 0)
20027 indent += 2;
20029 /* Check for defining a function inside this function. */
20030 if (checkforcmd(&p, "function", 2))
20032 if (*p == '!')
20033 p = skipwhite(p + 1);
20034 p += eval_fname_script(p);
20035 if (ASCII_ISALPHA(*p))
20037 vim_free(trans_function_name(&p, TRUE, 0, NULL));
20038 if (*skipwhite(p) == '(')
20040 ++nesting;
20041 indent += 2;
20046 /* Check for ":append" or ":insert". */
20047 p = skip_range(p, NULL);
20048 if ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p'))
20049 || (p[0] == 'i'
20050 && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n'
20051 && (!ASCII_ISALPHA(p[2]) || (p[2] == 's'))))))
20052 skip_until = vim_strsave((char_u *)".");
20054 /* Check for ":python <<EOF", ":tcl <<EOF", etc. */
20055 arg = skipwhite(skiptowhite(p));
20056 if (arg[0] == '<' && arg[1] =='<'
20057 && ((p[0] == 'p' && p[1] == 'y'
20058 && (!ASCII_ISALPHA(p[2]) || p[2] == 't'))
20059 || (p[0] == 'p' && p[1] == 'e'
20060 && (!ASCII_ISALPHA(p[2]) || p[2] == 'r'))
20061 || (p[0] == 't' && p[1] == 'c'
20062 && (!ASCII_ISALPHA(p[2]) || p[2] == 'l'))
20063 || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b'
20064 && (!ASCII_ISALPHA(p[3]) || p[3] == 'y'))
20065 || (p[0] == 'm' && p[1] == 'z'
20066 && (!ASCII_ISALPHA(p[2]) || p[2] == 's'))
20069 /* ":python <<" continues until a dot, like ":append" */
20070 p = skipwhite(arg + 2);
20071 if (*p == NUL)
20072 skip_until = vim_strsave((char_u *)".");
20073 else
20074 skip_until = vim_strsave(p);
20078 /* Add the line to the function. */
20079 if (ga_grow(&newlines, 1 + sourcing_lnum_off) == FAIL)
20081 if (line_arg == NULL)
20082 vim_free(theline);
20083 goto erret;
20086 /* Copy the line to newly allocated memory. get_one_sourceline()
20087 * allocates 250 bytes per line, this saves 80% on average. The cost
20088 * is an extra alloc/free. */
20089 p = vim_strsave(theline);
20090 if (p != NULL)
20092 if (line_arg == NULL)
20093 vim_free(theline);
20094 theline = p;
20097 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = theline;
20099 /* Add NULL lines for continuation lines, so that the line count is
20100 * equal to the index in the growarray. */
20101 while (sourcing_lnum_off-- > 0)
20102 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = NULL;
20104 /* Check for end of eap->arg. */
20105 if (line_arg != NULL && *line_arg == NUL)
20106 line_arg = NULL;
20109 /* Don't define the function when skipping commands or when an error was
20110 * detected. */
20111 if (eap->skip || did_emsg)
20112 goto erret;
20115 * If there are no errors, add the function
20117 if (fudi.fd_dict == NULL)
20119 v = find_var(name, &ht);
20120 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
20122 emsg_funcname(N_("E707: Function name conflicts with variable: %s"),
20123 name);
20124 goto erret;
20127 fp = find_func(name);
20128 if (fp != NULL)
20130 if (!eap->forceit)
20132 emsg_funcname(e_funcexts, name);
20133 goto erret;
20135 if (fp->uf_calls > 0)
20137 emsg_funcname(N_("E127: Cannot redefine function %s: It is in use"),
20138 name);
20139 goto erret;
20141 /* redefine existing function */
20142 ga_clear_strings(&(fp->uf_args));
20143 ga_clear_strings(&(fp->uf_lines));
20144 vim_free(name);
20145 name = NULL;
20148 else
20150 char numbuf[20];
20152 fp = NULL;
20153 if (fudi.fd_newkey == NULL && !eap->forceit)
20155 EMSG(_(e_funcdict));
20156 goto erret;
20158 if (fudi.fd_di == NULL)
20160 /* Can't add a function to a locked dictionary */
20161 if (tv_check_lock(fudi.fd_dict->dv_lock, eap->arg))
20162 goto erret;
20164 /* Can't change an existing function if it is locked */
20165 else if (tv_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg))
20166 goto erret;
20168 /* Give the function a sequential number. Can only be used with a
20169 * Funcref! */
20170 vim_free(name);
20171 sprintf(numbuf, "%d", ++func_nr);
20172 name = vim_strsave((char_u *)numbuf);
20173 if (name == NULL)
20174 goto erret;
20177 if (fp == NULL)
20179 if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL)
20181 int slen, plen;
20182 char_u *scriptname;
20184 /* Check that the autoload name matches the script name. */
20185 j = FAIL;
20186 if (sourcing_name != NULL)
20188 scriptname = autoload_name(name);
20189 if (scriptname != NULL)
20191 p = vim_strchr(scriptname, '/');
20192 plen = (int)STRLEN(p);
20193 slen = (int)STRLEN(sourcing_name);
20194 if (slen > plen && fnamecmp(p,
20195 sourcing_name + slen - plen) == 0)
20196 j = OK;
20197 vim_free(scriptname);
20200 if (j == FAIL)
20202 EMSG2(_("E746: Function name does not match script file name: %s"), name);
20203 goto erret;
20207 fp = (ufunc_T *)alloc((unsigned)(sizeof(ufunc_T) + STRLEN(name)));
20208 if (fp == NULL)
20209 goto erret;
20211 if (fudi.fd_dict != NULL)
20213 if (fudi.fd_di == NULL)
20215 /* add new dict entry */
20216 fudi.fd_di = dictitem_alloc(fudi.fd_newkey);
20217 if (fudi.fd_di == NULL)
20219 vim_free(fp);
20220 goto erret;
20222 if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL)
20224 vim_free(fudi.fd_di);
20225 vim_free(fp);
20226 goto erret;
20229 else
20230 /* overwrite existing dict entry */
20231 clear_tv(&fudi.fd_di->di_tv);
20232 fudi.fd_di->di_tv.v_type = VAR_FUNC;
20233 fudi.fd_di->di_tv.v_lock = 0;
20234 fudi.fd_di->di_tv.vval.v_string = vim_strsave(name);
20235 fp->uf_refcount = 1;
20237 /* behave like "dict" was used */
20238 flags |= FC_DICT;
20241 /* insert the new function in the function list */
20242 STRCPY(fp->uf_name, name);
20243 hash_add(&func_hashtab, UF2HIKEY(fp));
20245 fp->uf_args = newargs;
20246 fp->uf_lines = newlines;
20247 #ifdef FEAT_PROFILE
20248 fp->uf_tml_count = NULL;
20249 fp->uf_tml_total = NULL;
20250 fp->uf_tml_self = NULL;
20251 fp->uf_profiling = FALSE;
20252 if (prof_def_func())
20253 func_do_profile(fp);
20254 #endif
20255 fp->uf_varargs = varargs;
20256 fp->uf_flags = flags;
20257 fp->uf_calls = 0;
20258 fp->uf_script_ID = current_SID;
20259 goto ret_free;
20261 erret:
20262 ga_clear_strings(&newargs);
20263 ga_clear_strings(&newlines);
20264 ret_free:
20265 vim_free(skip_until);
20266 vim_free(fudi.fd_newkey);
20267 vim_free(name);
20268 did_emsg |= saved_did_emsg;
20272 * Get a function name, translating "<SID>" and "<SNR>".
20273 * Also handles a Funcref in a List or Dictionary.
20274 * Returns the function name in allocated memory, or NULL for failure.
20275 * flags:
20276 * TFN_INT: internal function name OK
20277 * TFN_QUIET: be quiet
20278 * Advances "pp" to just after the function name (if no error).
20280 static char_u *
20281 trans_function_name(pp, skip, flags, fdp)
20282 char_u **pp;
20283 int skip; /* only find the end, don't evaluate */
20284 int flags;
20285 funcdict_T *fdp; /* return: info about dictionary used */
20287 char_u *name = NULL;
20288 char_u *start;
20289 char_u *end;
20290 int lead;
20291 char_u sid_buf[20];
20292 int len;
20293 lval_T lv;
20295 if (fdp != NULL)
20296 vim_memset(fdp, 0, sizeof(funcdict_T));
20297 start = *pp;
20299 /* Check for hard coded <SNR>: already translated function ID (from a user
20300 * command). */
20301 if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA
20302 && (*pp)[2] == (int)KE_SNR)
20304 *pp += 3;
20305 len = get_id_len(pp) + 3;
20306 return vim_strnsave(start, len);
20309 /* A name starting with "<SID>" or "<SNR>" is local to a script. But
20310 * don't skip over "s:", get_lval() needs it for "s:dict.func". */
20311 lead = eval_fname_script(start);
20312 if (lead > 2)
20313 start += lead;
20315 end = get_lval(start, NULL, &lv, FALSE, skip, flags & TFN_QUIET,
20316 lead > 2 ? 0 : FNE_CHECK_START);
20317 if (end == start)
20319 if (!skip)
20320 EMSG(_("E129: Function name required"));
20321 goto theend;
20323 if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range)))
20326 * Report an invalid expression in braces, unless the expression
20327 * evaluation has been cancelled due to an aborting error, an
20328 * interrupt, or an exception.
20330 if (!aborting())
20332 if (end != NULL)
20333 EMSG2(_(e_invarg2), start);
20335 else
20336 *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR);
20337 goto theend;
20340 if (lv.ll_tv != NULL)
20342 if (fdp != NULL)
20344 fdp->fd_dict = lv.ll_dict;
20345 fdp->fd_newkey = lv.ll_newkey;
20346 lv.ll_newkey = NULL;
20347 fdp->fd_di = lv.ll_di;
20349 if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL)
20351 name = vim_strsave(lv.ll_tv->vval.v_string);
20352 *pp = end;
20354 else
20356 if (!skip && !(flags & TFN_QUIET) && (fdp == NULL
20357 || lv.ll_dict == NULL || fdp->fd_newkey == NULL))
20358 EMSG(_(e_funcref));
20359 else
20360 *pp = end;
20361 name = NULL;
20363 goto theend;
20366 if (lv.ll_name == NULL)
20368 /* Error found, but continue after the function name. */
20369 *pp = end;
20370 goto theend;
20373 /* Check if the name is a Funcref. If so, use the value. */
20374 if (lv.ll_exp_name != NULL)
20376 len = (int)STRLEN(lv.ll_exp_name);
20377 name = deref_func_name(lv.ll_exp_name, &len);
20378 if (name == lv.ll_exp_name)
20379 name = NULL;
20381 else
20383 len = (int)(end - *pp);
20384 name = deref_func_name(*pp, &len);
20385 if (name == *pp)
20386 name = NULL;
20388 if (name != NULL)
20390 name = vim_strsave(name);
20391 *pp = end;
20392 goto theend;
20395 if (lv.ll_exp_name != NULL)
20397 len = (int)STRLEN(lv.ll_exp_name);
20398 if (lead <= 2 && lv.ll_name == lv.ll_exp_name
20399 && STRNCMP(lv.ll_name, "s:", 2) == 0)
20401 /* When there was "s:" already or the name expanded to get a
20402 * leading "s:" then remove it. */
20403 lv.ll_name += 2;
20404 len -= 2;
20405 lead = 2;
20408 else
20410 if (lead == 2) /* skip over "s:" */
20411 lv.ll_name += 2;
20412 len = (int)(end - lv.ll_name);
20416 * Copy the function name to allocated memory.
20417 * Accept <SID>name() inside a script, translate into <SNR>123_name().
20418 * Accept <SNR>123_name() outside a script.
20420 if (skip)
20421 lead = 0; /* do nothing */
20422 else if (lead > 0)
20424 lead = 3;
20425 if ((lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name))
20426 || eval_fname_sid(*pp))
20428 /* It's "s:" or "<SID>" */
20429 if (current_SID <= 0)
20431 EMSG(_(e_usingsid));
20432 goto theend;
20434 sprintf((char *)sid_buf, "%ld_", (long)current_SID);
20435 lead += (int)STRLEN(sid_buf);
20438 else if (!(flags & TFN_INT) && builtin_function(lv.ll_name))
20440 EMSG2(_("E128: Function name must start with a capital or contain a colon: %s"), lv.ll_name);
20441 goto theend;
20443 name = alloc((unsigned)(len + lead + 1));
20444 if (name != NULL)
20446 if (lead > 0)
20448 name[0] = K_SPECIAL;
20449 name[1] = KS_EXTRA;
20450 name[2] = (int)KE_SNR;
20451 if (lead > 3) /* If it's "<SID>" */
20452 STRCPY(name + 3, sid_buf);
20454 mch_memmove(name + lead, lv.ll_name, (size_t)len);
20455 name[len + lead] = NUL;
20457 *pp = end;
20459 theend:
20460 clear_lval(&lv);
20461 return name;
20465 * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case).
20466 * Return 2 if "p" starts with "s:".
20467 * Return 0 otherwise.
20469 static int
20470 eval_fname_script(p)
20471 char_u *p;
20473 if (p[0] == '<' && (STRNICMP(p + 1, "SID>", 4) == 0
20474 || STRNICMP(p + 1, "SNR>", 4) == 0))
20475 return 5;
20476 if (p[0] == 's' && p[1] == ':')
20477 return 2;
20478 return 0;
20482 * Return TRUE if "p" starts with "<SID>" or "s:".
20483 * Only works if eval_fname_script() returned non-zero for "p"!
20485 static int
20486 eval_fname_sid(p)
20487 char_u *p;
20489 return (*p == 's' || TOUPPER_ASC(p[2]) == 'I');
20493 * List the head of the function: "name(arg1, arg2)".
20495 static void
20496 list_func_head(fp, indent)
20497 ufunc_T *fp;
20498 int indent;
20500 int j;
20502 msg_start();
20503 if (indent)
20504 MSG_PUTS(" ");
20505 MSG_PUTS("function ");
20506 if (fp->uf_name[0] == K_SPECIAL)
20508 MSG_PUTS_ATTR("<SNR>", hl_attr(HLF_8));
20509 msg_puts(fp->uf_name + 3);
20511 else
20512 msg_puts(fp->uf_name);
20513 msg_putchar('(');
20514 for (j = 0; j < fp->uf_args.ga_len; ++j)
20516 if (j)
20517 MSG_PUTS(", ");
20518 msg_puts(FUNCARG(fp, j));
20520 if (fp->uf_varargs)
20522 if (j)
20523 MSG_PUTS(", ");
20524 MSG_PUTS("...");
20526 msg_putchar(')');
20527 msg_clr_eos();
20528 if (p_verbose > 0)
20529 last_set_msg(fp->uf_script_ID);
20533 * Find a function by name, return pointer to it in ufuncs.
20534 * Return NULL for unknown function.
20536 static ufunc_T *
20537 find_func(name)
20538 char_u *name;
20540 hashitem_T *hi;
20542 hi = hash_find(&func_hashtab, name);
20543 if (!HASHITEM_EMPTY(hi))
20544 return HI2UF(hi);
20545 return NULL;
20548 #if defined(EXITFREE) || defined(PROTO)
20549 void
20550 free_all_functions()
20552 hashitem_T *hi;
20554 /* Need to start all over every time, because func_free() may change the
20555 * hash table. */
20556 while (func_hashtab.ht_used > 0)
20557 for (hi = func_hashtab.ht_array; ; ++hi)
20558 if (!HASHITEM_EMPTY(hi))
20560 func_free(HI2UF(hi));
20561 break;
20564 #endif
20567 * Return TRUE if a function "name" exists.
20569 static int
20570 function_exists(name)
20571 char_u *name;
20573 char_u *nm = name;
20574 char_u *p;
20575 int n = FALSE;
20577 p = trans_function_name(&nm, FALSE, TFN_INT|TFN_QUIET, NULL);
20578 nm = skipwhite(nm);
20580 /* Only accept "funcname", "funcname ", "funcname (..." and
20581 * "funcname(...", not "funcname!...". */
20582 if (p != NULL && (*nm == NUL || *nm == '('))
20584 if (builtin_function(p))
20585 n = (find_internal_func(p) >= 0);
20586 else
20587 n = (find_func(p) != NULL);
20589 vim_free(p);
20590 return n;
20594 * Return TRUE if "name" looks like a builtin function name: starts with a
20595 * lower case letter and doesn't contain a ':' or AUTOLOAD_CHAR.
20597 static int
20598 builtin_function(name)
20599 char_u *name;
20601 return ASCII_ISLOWER(name[0]) && vim_strchr(name, ':') == NULL
20602 && vim_strchr(name, AUTOLOAD_CHAR) == NULL;
20605 #if defined(FEAT_PROFILE) || defined(PROTO)
20607 * Start profiling function "fp".
20609 static void
20610 func_do_profile(fp)
20611 ufunc_T *fp;
20613 fp->uf_tm_count = 0;
20614 profile_zero(&fp->uf_tm_self);
20615 profile_zero(&fp->uf_tm_total);
20616 if (fp->uf_tml_count == NULL)
20617 fp->uf_tml_count = (int *)alloc_clear((unsigned)
20618 (sizeof(int) * fp->uf_lines.ga_len));
20619 if (fp->uf_tml_total == NULL)
20620 fp->uf_tml_total = (proftime_T *)alloc_clear((unsigned)
20621 (sizeof(proftime_T) * fp->uf_lines.ga_len));
20622 if (fp->uf_tml_self == NULL)
20623 fp->uf_tml_self = (proftime_T *)alloc_clear((unsigned)
20624 (sizeof(proftime_T) * fp->uf_lines.ga_len));
20625 fp->uf_tml_idx = -1;
20626 if (fp->uf_tml_count == NULL || fp->uf_tml_total == NULL
20627 || fp->uf_tml_self == NULL)
20628 return; /* out of memory */
20630 fp->uf_profiling = TRUE;
20634 * Dump the profiling results for all functions in file "fd".
20636 void
20637 func_dump_profile(fd)
20638 FILE *fd;
20640 hashitem_T *hi;
20641 int todo;
20642 ufunc_T *fp;
20643 int i;
20644 ufunc_T **sorttab;
20645 int st_len = 0;
20647 todo = (int)func_hashtab.ht_used;
20648 if (todo == 0)
20649 return; /* nothing to dump */
20651 sorttab = (ufunc_T **)alloc((unsigned)(sizeof(ufunc_T) * todo));
20653 for (hi = func_hashtab.ht_array; todo > 0; ++hi)
20655 if (!HASHITEM_EMPTY(hi))
20657 --todo;
20658 fp = HI2UF(hi);
20659 if (fp->uf_profiling)
20661 if (sorttab != NULL)
20662 sorttab[st_len++] = fp;
20664 if (fp->uf_name[0] == K_SPECIAL)
20665 fprintf(fd, "FUNCTION <SNR>%s()\n", fp->uf_name + 3);
20666 else
20667 fprintf(fd, "FUNCTION %s()\n", fp->uf_name);
20668 if (fp->uf_tm_count == 1)
20669 fprintf(fd, "Called 1 time\n");
20670 else
20671 fprintf(fd, "Called %d times\n", fp->uf_tm_count);
20672 fprintf(fd, "Total time: %s\n", profile_msg(&fp->uf_tm_total));
20673 fprintf(fd, " Self time: %s\n", profile_msg(&fp->uf_tm_self));
20674 fprintf(fd, "\n");
20675 fprintf(fd, "count total (s) self (s)\n");
20677 for (i = 0; i < fp->uf_lines.ga_len; ++i)
20679 if (FUNCLINE(fp, i) == NULL)
20680 continue;
20681 prof_func_line(fd, fp->uf_tml_count[i],
20682 &fp->uf_tml_total[i], &fp->uf_tml_self[i], TRUE);
20683 fprintf(fd, "%s\n", FUNCLINE(fp, i));
20685 fprintf(fd, "\n");
20690 if (sorttab != NULL && st_len > 0)
20692 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
20693 prof_total_cmp);
20694 prof_sort_list(fd, sorttab, st_len, "TOTAL", FALSE);
20695 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
20696 prof_self_cmp);
20697 prof_sort_list(fd, sorttab, st_len, "SELF", TRUE);
20700 vim_free(sorttab);
20703 static void
20704 prof_sort_list(fd, sorttab, st_len, title, prefer_self)
20705 FILE *fd;
20706 ufunc_T **sorttab;
20707 int st_len;
20708 char *title;
20709 int prefer_self; /* when equal print only self time */
20711 int i;
20712 ufunc_T *fp;
20714 fprintf(fd, "FUNCTIONS SORTED ON %s TIME\n", title);
20715 fprintf(fd, "count total (s) self (s) function\n");
20716 for (i = 0; i < 20 && i < st_len; ++i)
20718 fp = sorttab[i];
20719 prof_func_line(fd, fp->uf_tm_count, &fp->uf_tm_total, &fp->uf_tm_self,
20720 prefer_self);
20721 if (fp->uf_name[0] == K_SPECIAL)
20722 fprintf(fd, " <SNR>%s()\n", fp->uf_name + 3);
20723 else
20724 fprintf(fd, " %s()\n", fp->uf_name);
20726 fprintf(fd, "\n");
20730 * Print the count and times for one function or function line.
20732 static void
20733 prof_func_line(fd, count, total, self, prefer_self)
20734 FILE *fd;
20735 int count;
20736 proftime_T *total;
20737 proftime_T *self;
20738 int prefer_self; /* when equal print only self time */
20740 if (count > 0)
20742 fprintf(fd, "%5d ", count);
20743 if (prefer_self && profile_equal(total, self))
20744 fprintf(fd, " ");
20745 else
20746 fprintf(fd, "%s ", profile_msg(total));
20747 if (!prefer_self && profile_equal(total, self))
20748 fprintf(fd, " ");
20749 else
20750 fprintf(fd, "%s ", profile_msg(self));
20752 else
20753 fprintf(fd, " ");
20757 * Compare function for total time sorting.
20759 static int
20760 #ifdef __BORLANDC__
20761 _RTLENTRYF
20762 #endif
20763 prof_total_cmp(s1, s2)
20764 const void *s1;
20765 const void *s2;
20767 ufunc_T *p1, *p2;
20769 p1 = *(ufunc_T **)s1;
20770 p2 = *(ufunc_T **)s2;
20771 return profile_cmp(&p1->uf_tm_total, &p2->uf_tm_total);
20775 * Compare function for self time sorting.
20777 static int
20778 #ifdef __BORLANDC__
20779 _RTLENTRYF
20780 #endif
20781 prof_self_cmp(s1, s2)
20782 const void *s1;
20783 const void *s2;
20785 ufunc_T *p1, *p2;
20787 p1 = *(ufunc_T **)s1;
20788 p2 = *(ufunc_T **)s2;
20789 return profile_cmp(&p1->uf_tm_self, &p2->uf_tm_self);
20792 #endif
20795 * If "name" has a package name try autoloading the script for it.
20796 * Return TRUE if a package was loaded.
20798 static int
20799 script_autoload(name, reload)
20800 char_u *name;
20801 int reload; /* load script again when already loaded */
20803 char_u *p;
20804 char_u *scriptname, *tofree;
20805 int ret = FALSE;
20806 int i;
20808 /* If there is no '#' after name[0] there is no package name. */
20809 p = vim_strchr(name, AUTOLOAD_CHAR);
20810 if (p == NULL || p == name)
20811 return FALSE;
20813 tofree = scriptname = autoload_name(name);
20815 /* Find the name in the list of previously loaded package names. Skip
20816 * "autoload/", it's always the same. */
20817 for (i = 0; i < ga_loaded.ga_len; ++i)
20818 if (STRCMP(((char_u **)ga_loaded.ga_data)[i] + 9, scriptname + 9) == 0)
20819 break;
20820 if (!reload && i < ga_loaded.ga_len)
20821 ret = FALSE; /* was loaded already */
20822 else
20824 /* Remember the name if it wasn't loaded already. */
20825 if (i == ga_loaded.ga_len && ga_grow(&ga_loaded, 1) == OK)
20827 ((char_u **)ga_loaded.ga_data)[ga_loaded.ga_len++] = scriptname;
20828 tofree = NULL;
20831 /* Try loading the package from $VIMRUNTIME/autoload/<name>.vim */
20832 if (source_runtime(scriptname, FALSE) == OK)
20833 ret = TRUE;
20836 vim_free(tofree);
20837 return ret;
20841 * Return the autoload script name for a function or variable name.
20842 * Returns NULL when out of memory.
20844 static char_u *
20845 autoload_name(name)
20846 char_u *name;
20848 char_u *p;
20849 char_u *scriptname;
20851 /* Get the script file name: replace '#' with '/', append ".vim". */
20852 scriptname = alloc((unsigned)(STRLEN(name) + 14));
20853 if (scriptname == NULL)
20854 return FALSE;
20855 STRCPY(scriptname, "autoload/");
20856 STRCAT(scriptname, name);
20857 *vim_strrchr(scriptname, AUTOLOAD_CHAR) = NUL;
20858 STRCAT(scriptname, ".vim");
20859 while ((p = vim_strchr(scriptname, AUTOLOAD_CHAR)) != NULL)
20860 *p = '/';
20861 return scriptname;
20864 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
20867 * Function given to ExpandGeneric() to obtain the list of user defined
20868 * function names.
20870 char_u *
20871 get_user_func_name(xp, idx)
20872 expand_T *xp;
20873 int idx;
20875 static long_u done;
20876 static hashitem_T *hi;
20877 ufunc_T *fp;
20879 if (idx == 0)
20881 done = 0;
20882 hi = func_hashtab.ht_array;
20884 if (done < func_hashtab.ht_used)
20886 if (done++ > 0)
20887 ++hi;
20888 while (HASHITEM_EMPTY(hi))
20889 ++hi;
20890 fp = HI2UF(hi);
20892 if (STRLEN(fp->uf_name) + 4 >= IOSIZE)
20893 return fp->uf_name; /* prevents overflow */
20895 cat_func_name(IObuff, fp);
20896 if (xp->xp_context != EXPAND_USER_FUNC)
20898 STRCAT(IObuff, "(");
20899 if (!fp->uf_varargs && fp->uf_args.ga_len == 0)
20900 STRCAT(IObuff, ")");
20902 return IObuff;
20904 return NULL;
20907 #endif /* FEAT_CMDL_COMPL */
20910 * Copy the function name of "fp" to buffer "buf".
20911 * "buf" must be able to hold the function name plus three bytes.
20912 * Takes care of script-local function names.
20914 static void
20915 cat_func_name(buf, fp)
20916 char_u *buf;
20917 ufunc_T *fp;
20919 if (fp->uf_name[0] == K_SPECIAL)
20921 STRCPY(buf, "<SNR>");
20922 STRCAT(buf, fp->uf_name + 3);
20924 else
20925 STRCPY(buf, fp->uf_name);
20929 * ":delfunction {name}"
20931 void
20932 ex_delfunction(eap)
20933 exarg_T *eap;
20935 ufunc_T *fp = NULL;
20936 char_u *p;
20937 char_u *name;
20938 funcdict_T fudi;
20940 p = eap->arg;
20941 name = trans_function_name(&p, eap->skip, 0, &fudi);
20942 vim_free(fudi.fd_newkey);
20943 if (name == NULL)
20945 if (fudi.fd_dict != NULL && !eap->skip)
20946 EMSG(_(e_funcref));
20947 return;
20949 if (!ends_excmd(*skipwhite(p)))
20951 vim_free(name);
20952 EMSG(_(e_trailing));
20953 return;
20955 eap->nextcmd = check_nextcmd(p);
20956 if (eap->nextcmd != NULL)
20957 *p = NUL;
20959 if (!eap->skip)
20960 fp = find_func(name);
20961 vim_free(name);
20963 if (!eap->skip)
20965 if (fp == NULL)
20967 EMSG2(_(e_nofunc), eap->arg);
20968 return;
20970 if (fp->uf_calls > 0)
20972 EMSG2(_("E131: Cannot delete function %s: It is in use"), eap->arg);
20973 return;
20976 if (fudi.fd_dict != NULL)
20978 /* Delete the dict item that refers to the function, it will
20979 * invoke func_unref() and possibly delete the function. */
20980 dictitem_remove(fudi.fd_dict, fudi.fd_di);
20982 else
20983 func_free(fp);
20988 * Free a function and remove it from the list of functions.
20990 static void
20991 func_free(fp)
20992 ufunc_T *fp;
20994 hashitem_T *hi;
20996 /* clear this function */
20997 ga_clear_strings(&(fp->uf_args));
20998 ga_clear_strings(&(fp->uf_lines));
20999 #ifdef FEAT_PROFILE
21000 vim_free(fp->uf_tml_count);
21001 vim_free(fp->uf_tml_total);
21002 vim_free(fp->uf_tml_self);
21003 #endif
21005 /* remove the function from the function hashtable */
21006 hi = hash_find(&func_hashtab, UF2HIKEY(fp));
21007 if (HASHITEM_EMPTY(hi))
21008 EMSG2(_(e_intern2), "func_free()");
21009 else
21010 hash_remove(&func_hashtab, hi);
21012 vim_free(fp);
21016 * Unreference a Function: decrement the reference count and free it when it
21017 * becomes zero. Only for numbered functions.
21019 static void
21020 func_unref(name)
21021 char_u *name;
21023 ufunc_T *fp;
21025 if (name != NULL && isdigit(*name))
21027 fp = find_func(name);
21028 if (fp == NULL)
21029 EMSG2(_(e_intern2), "func_unref()");
21030 else if (--fp->uf_refcount <= 0)
21032 /* Only delete it when it's not being used. Otherwise it's done
21033 * when "uf_calls" becomes zero. */
21034 if (fp->uf_calls == 0)
21035 func_free(fp);
21041 * Count a reference to a Function.
21043 static void
21044 func_ref(name)
21045 char_u *name;
21047 ufunc_T *fp;
21049 if (name != NULL && isdigit(*name))
21051 fp = find_func(name);
21052 if (fp == NULL)
21053 EMSG2(_(e_intern2), "func_ref()");
21054 else
21055 ++fp->uf_refcount;
21060 * Call a user function.
21062 static void
21063 call_user_func(fp, argcount, argvars, rettv, firstline, lastline, selfdict)
21064 ufunc_T *fp; /* pointer to function */
21065 int argcount; /* nr of args */
21066 typval_T *argvars; /* arguments */
21067 typval_T *rettv; /* return value */
21068 linenr_T firstline; /* first line of range */
21069 linenr_T lastline; /* last line of range */
21070 dict_T *selfdict; /* Dictionary for "self" */
21072 char_u *save_sourcing_name;
21073 linenr_T save_sourcing_lnum;
21074 scid_T save_current_SID;
21075 funccall_T *fc;
21076 int save_did_emsg;
21077 static int depth = 0;
21078 dictitem_T *v;
21079 int fixvar_idx = 0; /* index in fixvar[] */
21080 int i;
21081 int ai;
21082 char_u numbuf[NUMBUFLEN];
21083 char_u *name;
21084 #ifdef FEAT_PROFILE
21085 proftime_T wait_start;
21086 proftime_T call_start;
21087 #endif
21089 /* If depth of calling is getting too high, don't execute the function */
21090 if (depth >= p_mfd)
21092 EMSG(_("E132: Function call depth is higher than 'maxfuncdepth'"));
21093 rettv->v_type = VAR_NUMBER;
21094 rettv->vval.v_number = -1;
21095 return;
21097 ++depth;
21099 line_breakcheck(); /* check for CTRL-C hit */
21101 fc = (funccall_T *)alloc(sizeof(funccall_T));
21102 fc->caller = current_funccal;
21103 current_funccal = fc;
21104 fc->func = fp;
21105 fc->rettv = rettv;
21106 rettv->vval.v_number = 0;
21107 fc->linenr = 0;
21108 fc->returned = FALSE;
21109 fc->level = ex_nesting_level;
21110 /* Check if this function has a breakpoint. */
21111 fc->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, (linenr_T)0);
21112 fc->dbg_tick = debug_tick;
21115 * Note about using fc->fixvar[]: This is an array of FIXVAR_CNT variables
21116 * with names up to VAR_SHORT_LEN long. This avoids having to alloc/free
21117 * each argument variable and saves a lot of time.
21120 * Init l: variables.
21122 init_var_dict(&fc->l_vars, &fc->l_vars_var);
21123 if (selfdict != NULL)
21125 /* Set l:self to "selfdict". Use "name" to avoid a warning from
21126 * some compiler that checks the destination size. */
21127 v = &fc->fixvar[fixvar_idx++].var;
21128 name = v->di_key;
21129 STRCPY(name, "self");
21130 v->di_flags = DI_FLAGS_RO + DI_FLAGS_FIX;
21131 hash_add(&fc->l_vars.dv_hashtab, DI2HIKEY(v));
21132 v->di_tv.v_type = VAR_DICT;
21133 v->di_tv.v_lock = 0;
21134 v->di_tv.vval.v_dict = selfdict;
21135 ++selfdict->dv_refcount;
21139 * Init a: variables.
21140 * Set a:0 to "argcount".
21141 * Set a:000 to a list with room for the "..." arguments.
21143 init_var_dict(&fc->l_avars, &fc->l_avars_var);
21144 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "0",
21145 (varnumber_T)(argcount - fp->uf_args.ga_len));
21146 /* Use "name" to avoid a warning from some compiler that checks the
21147 * destination size. */
21148 v = &fc->fixvar[fixvar_idx++].var;
21149 name = v->di_key;
21150 STRCPY(name, "000");
21151 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21152 hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v));
21153 v->di_tv.v_type = VAR_LIST;
21154 v->di_tv.v_lock = VAR_FIXED;
21155 v->di_tv.vval.v_list = &fc->l_varlist;
21156 vim_memset(&fc->l_varlist, 0, sizeof(list_T));
21157 fc->l_varlist.lv_refcount = DO_NOT_FREE_CNT;
21158 fc->l_varlist.lv_lock = VAR_FIXED;
21161 * Set a:firstline to "firstline" and a:lastline to "lastline".
21162 * Set a:name to named arguments.
21163 * Set a:N to the "..." arguments.
21165 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "firstline",
21166 (varnumber_T)firstline);
21167 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "lastline",
21168 (varnumber_T)lastline);
21169 for (i = 0; i < argcount; ++i)
21171 ai = i - fp->uf_args.ga_len;
21172 if (ai < 0)
21173 /* named argument a:name */
21174 name = FUNCARG(fp, i);
21175 else
21177 /* "..." argument a:1, a:2, etc. */
21178 sprintf((char *)numbuf, "%d", ai + 1);
21179 name = numbuf;
21181 if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN)
21183 v = &fc->fixvar[fixvar_idx++].var;
21184 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21186 else
21188 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
21189 + STRLEN(name)));
21190 if (v == NULL)
21191 break;
21192 v->di_flags = DI_FLAGS_RO;
21194 STRCPY(v->di_key, name);
21195 hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v));
21197 /* Note: the values are copied directly to avoid alloc/free.
21198 * "argvars" must have VAR_FIXED for v_lock. */
21199 v->di_tv = argvars[i];
21200 v->di_tv.v_lock = VAR_FIXED;
21202 if (ai >= 0 && ai < MAX_FUNC_ARGS)
21204 list_append(&fc->l_varlist, &fc->l_listitems[ai]);
21205 fc->l_listitems[ai].li_tv = argvars[i];
21206 fc->l_listitems[ai].li_tv.v_lock = VAR_FIXED;
21210 /* Don't redraw while executing the function. */
21211 ++RedrawingDisabled;
21212 save_sourcing_name = sourcing_name;
21213 save_sourcing_lnum = sourcing_lnum;
21214 sourcing_lnum = 1;
21215 sourcing_name = alloc((unsigned)((save_sourcing_name == NULL ? 0
21216 : STRLEN(save_sourcing_name)) + STRLEN(fp->uf_name) + 13));
21217 if (sourcing_name != NULL)
21219 if (save_sourcing_name != NULL
21220 && STRNCMP(save_sourcing_name, "function ", 9) == 0)
21221 sprintf((char *)sourcing_name, "%s..", save_sourcing_name);
21222 else
21223 STRCPY(sourcing_name, "function ");
21224 cat_func_name(sourcing_name + STRLEN(sourcing_name), fp);
21226 if (p_verbose >= 12)
21228 ++no_wait_return;
21229 verbose_enter_scroll();
21231 smsg((char_u *)_("calling %s"), sourcing_name);
21232 if (p_verbose >= 14)
21234 char_u buf[MSG_BUF_LEN];
21235 char_u numbuf2[NUMBUFLEN];
21236 char_u *tofree;
21237 char_u *s;
21239 msg_puts((char_u *)"(");
21240 for (i = 0; i < argcount; ++i)
21242 if (i > 0)
21243 msg_puts((char_u *)", ");
21244 if (argvars[i].v_type == VAR_NUMBER)
21245 msg_outnum((long)argvars[i].vval.v_number);
21246 else
21248 s = tv2string(&argvars[i], &tofree, numbuf2, 0);
21249 if (s != NULL)
21251 trunc_string(s, buf, MSG_BUF_CLEN);
21252 msg_puts(buf);
21253 vim_free(tofree);
21257 msg_puts((char_u *)")");
21259 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21261 verbose_leave_scroll();
21262 --no_wait_return;
21265 #ifdef FEAT_PROFILE
21266 if (do_profiling == PROF_YES)
21268 if (!fp->uf_profiling && has_profiling(FALSE, fp->uf_name, NULL))
21269 func_do_profile(fp);
21270 if (fp->uf_profiling
21271 || (fc->caller != NULL && fc->caller->func->uf_profiling))
21273 ++fp->uf_tm_count;
21274 profile_start(&call_start);
21275 profile_zero(&fp->uf_tm_children);
21277 script_prof_save(&wait_start);
21279 #endif
21281 save_current_SID = current_SID;
21282 current_SID = fp->uf_script_ID;
21283 save_did_emsg = did_emsg;
21284 did_emsg = FALSE;
21286 /* call do_cmdline() to execute the lines */
21287 do_cmdline(NULL, get_func_line, (void *)fc,
21288 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
21290 --RedrawingDisabled;
21292 /* when the function was aborted because of an error, return -1 */
21293 if ((did_emsg && (fp->uf_flags & FC_ABORT)) || rettv->v_type == VAR_UNKNOWN)
21295 clear_tv(rettv);
21296 rettv->v_type = VAR_NUMBER;
21297 rettv->vval.v_number = -1;
21300 #ifdef FEAT_PROFILE
21301 if (do_profiling == PROF_YES && (fp->uf_profiling
21302 || (fc->caller != NULL && fc->caller->func->uf_profiling)))
21304 profile_end(&call_start);
21305 profile_sub_wait(&wait_start, &call_start);
21306 profile_add(&fp->uf_tm_total, &call_start);
21307 profile_self(&fp->uf_tm_self, &call_start, &fp->uf_tm_children);
21308 if (fc->caller != NULL && fc->caller->func->uf_profiling)
21310 profile_add(&fc->caller->func->uf_tm_children, &call_start);
21311 profile_add(&fc->caller->func->uf_tml_children, &call_start);
21314 #endif
21316 /* when being verbose, mention the return value */
21317 if (p_verbose >= 12)
21319 ++no_wait_return;
21320 verbose_enter_scroll();
21322 if (aborting())
21323 smsg((char_u *)_("%s aborted"), sourcing_name);
21324 else if (fc->rettv->v_type == VAR_NUMBER)
21325 smsg((char_u *)_("%s returning #%ld"), sourcing_name,
21326 (long)fc->rettv->vval.v_number);
21327 else
21329 char_u buf[MSG_BUF_LEN];
21330 char_u numbuf2[NUMBUFLEN];
21331 char_u *tofree;
21332 char_u *s;
21334 /* The value may be very long. Skip the middle part, so that we
21335 * have some idea how it starts and ends. smsg() would always
21336 * truncate it at the end. */
21337 s = tv2string(fc->rettv, &tofree, numbuf2, 0);
21338 if (s != NULL)
21340 trunc_string(s, buf, MSG_BUF_CLEN);
21341 smsg((char_u *)_("%s returning %s"), sourcing_name, buf);
21342 vim_free(tofree);
21345 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21347 verbose_leave_scroll();
21348 --no_wait_return;
21351 vim_free(sourcing_name);
21352 sourcing_name = save_sourcing_name;
21353 sourcing_lnum = save_sourcing_lnum;
21354 current_SID = save_current_SID;
21355 #ifdef FEAT_PROFILE
21356 if (do_profiling == PROF_YES)
21357 script_prof_restore(&wait_start);
21358 #endif
21360 if (p_verbose >= 12 && sourcing_name != NULL)
21362 ++no_wait_return;
21363 verbose_enter_scroll();
21365 smsg((char_u *)_("continuing in %s"), sourcing_name);
21366 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21368 verbose_leave_scroll();
21369 --no_wait_return;
21372 did_emsg |= save_did_emsg;
21373 current_funccal = fc->caller;
21374 --depth;
21376 /* if the a:000 list and the a: dict are not referenced we can free the
21377 * funccall_T and what's in it. */
21378 if (fc->l_varlist.lv_refcount == DO_NOT_FREE_CNT
21379 && fc->l_vars.dv_refcount == DO_NOT_FREE_CNT
21380 && fc->l_avars.dv_refcount == DO_NOT_FREE_CNT)
21382 free_funccal(fc, FALSE);
21384 else
21386 hashitem_T *hi;
21387 listitem_T *li;
21388 int todo;
21390 /* "fc" is still in use. This can happen when returning "a:000" or
21391 * assigning "l:" to a global variable.
21392 * Link "fc" in the list for garbage collection later. */
21393 fc->caller = previous_funccal;
21394 previous_funccal = fc;
21396 /* Make a copy of the a: variables, since we didn't do that above. */
21397 todo = (int)fc->l_avars.dv_hashtab.ht_used;
21398 for (hi = fc->l_avars.dv_hashtab.ht_array; todo > 0; ++hi)
21400 if (!HASHITEM_EMPTY(hi))
21402 --todo;
21403 v = HI2DI(hi);
21404 copy_tv(&v->di_tv, &v->di_tv);
21408 /* Make a copy of the a:000 items, since we didn't do that above. */
21409 for (li = fc->l_varlist.lv_first; li != NULL; li = li->li_next)
21410 copy_tv(&li->li_tv, &li->li_tv);
21415 * Return TRUE if items in "fc" do not have "copyID". That means they are not
21416 * referenced from anywhere.
21418 static int
21419 can_free_funccal(fc, copyID)
21420 funccall_T *fc;
21421 int copyID;
21423 return (fc->l_varlist.lv_copyID != copyID
21424 && fc->l_vars.dv_copyID != copyID
21425 && fc->l_avars.dv_copyID != copyID);
21429 * Free "fc" and what it contains.
21431 static void
21432 free_funccal(fc, free_val)
21433 funccall_T *fc;
21434 int free_val; /* a: vars were allocated */
21436 listitem_T *li;
21438 /* The a: variables typevals may not have been allocated, only free the
21439 * allocated variables. */
21440 vars_clear_ext(&fc->l_avars.dv_hashtab, free_val);
21442 /* free all l: variables */
21443 vars_clear(&fc->l_vars.dv_hashtab);
21445 /* Free the a:000 variables if they were allocated. */
21446 if (free_val)
21447 for (li = fc->l_varlist.lv_first; li != NULL; li = li->li_next)
21448 clear_tv(&li->li_tv);
21450 vim_free(fc);
21454 * Add a number variable "name" to dict "dp" with value "nr".
21456 static void
21457 add_nr_var(dp, v, name, nr)
21458 dict_T *dp;
21459 dictitem_T *v;
21460 char *name;
21461 varnumber_T nr;
21463 STRCPY(v->di_key, name);
21464 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21465 hash_add(&dp->dv_hashtab, DI2HIKEY(v));
21466 v->di_tv.v_type = VAR_NUMBER;
21467 v->di_tv.v_lock = VAR_FIXED;
21468 v->di_tv.vval.v_number = nr;
21472 * ":return [expr]"
21474 void
21475 ex_return(eap)
21476 exarg_T *eap;
21478 char_u *arg = eap->arg;
21479 typval_T rettv;
21480 int returning = FALSE;
21482 if (current_funccal == NULL)
21484 EMSG(_("E133: :return not inside a function"));
21485 return;
21488 if (eap->skip)
21489 ++emsg_skip;
21491 eap->nextcmd = NULL;
21492 if ((*arg != NUL && *arg != '|' && *arg != '\n')
21493 && eval0(arg, &rettv, &eap->nextcmd, !eap->skip) != FAIL)
21495 if (!eap->skip)
21496 returning = do_return(eap, FALSE, TRUE, &rettv);
21497 else
21498 clear_tv(&rettv);
21500 /* It's safer to return also on error. */
21501 else if (!eap->skip)
21504 * Return unless the expression evaluation has been cancelled due to an
21505 * aborting error, an interrupt, or an exception.
21507 if (!aborting())
21508 returning = do_return(eap, FALSE, TRUE, NULL);
21511 /* When skipping or the return gets pending, advance to the next command
21512 * in this line (!returning). Otherwise, ignore the rest of the line.
21513 * Following lines will be ignored by get_func_line(). */
21514 if (returning)
21515 eap->nextcmd = NULL;
21516 else if (eap->nextcmd == NULL) /* no argument */
21517 eap->nextcmd = check_nextcmd(arg);
21519 if (eap->skip)
21520 --emsg_skip;
21524 * Return from a function. Possibly makes the return pending. Also called
21525 * for a pending return at the ":endtry" or after returning from an extra
21526 * do_cmdline(). "reanimate" is used in the latter case. "is_cmd" is set
21527 * when called due to a ":return" command. "rettv" may point to a typval_T
21528 * with the return rettv. Returns TRUE when the return can be carried out,
21529 * FALSE when the return gets pending.
21532 do_return(eap, reanimate, is_cmd, rettv)
21533 exarg_T *eap;
21534 int reanimate;
21535 int is_cmd;
21536 void *rettv;
21538 int idx;
21539 struct condstack *cstack = eap->cstack;
21541 if (reanimate)
21542 /* Undo the return. */
21543 current_funccal->returned = FALSE;
21546 * Cleanup (and inactivate) conditionals, but stop when a try conditional
21547 * not in its finally clause (which then is to be executed next) is found.
21548 * In this case, make the ":return" pending for execution at the ":endtry".
21549 * Otherwise, return normally.
21551 idx = cleanup_conditionals(eap->cstack, 0, TRUE);
21552 if (idx >= 0)
21554 cstack->cs_pending[idx] = CSTP_RETURN;
21556 if (!is_cmd && !reanimate)
21557 /* A pending return again gets pending. "rettv" points to an
21558 * allocated variable with the rettv of the original ":return"'s
21559 * argument if present or is NULL else. */
21560 cstack->cs_rettv[idx] = rettv;
21561 else
21563 /* When undoing a return in order to make it pending, get the stored
21564 * return rettv. */
21565 if (reanimate)
21566 rettv = current_funccal->rettv;
21568 if (rettv != NULL)
21570 /* Store the value of the pending return. */
21571 if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL)
21572 *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv;
21573 else
21574 EMSG(_(e_outofmem));
21576 else
21577 cstack->cs_rettv[idx] = NULL;
21579 if (reanimate)
21581 /* The pending return value could be overwritten by a ":return"
21582 * without argument in a finally clause; reset the default
21583 * return value. */
21584 current_funccal->rettv->v_type = VAR_NUMBER;
21585 current_funccal->rettv->vval.v_number = 0;
21588 report_make_pending(CSTP_RETURN, rettv);
21590 else
21592 current_funccal->returned = TRUE;
21594 /* If the return is carried out now, store the return value. For
21595 * a return immediately after reanimation, the value is already
21596 * there. */
21597 if (!reanimate && rettv != NULL)
21599 clear_tv(current_funccal->rettv);
21600 *current_funccal->rettv = *(typval_T *)rettv;
21601 if (!is_cmd)
21602 vim_free(rettv);
21606 return idx < 0;
21610 * Free the variable with a pending return value.
21612 void
21613 discard_pending_return(rettv)
21614 void *rettv;
21616 free_tv((typval_T *)rettv);
21620 * Generate a return command for producing the value of "rettv". The result
21621 * is an allocated string. Used by report_pending() for verbose messages.
21623 char_u *
21624 get_return_cmd(rettv)
21625 void *rettv;
21627 char_u *s = NULL;
21628 char_u *tofree = NULL;
21629 char_u numbuf[NUMBUFLEN];
21631 if (rettv != NULL)
21632 s = echo_string((typval_T *)rettv, &tofree, numbuf, 0);
21633 if (s == NULL)
21634 s = (char_u *)"";
21636 STRCPY(IObuff, ":return ");
21637 STRNCPY(IObuff + 8, s, IOSIZE - 8);
21638 if (STRLEN(s) + 8 >= IOSIZE)
21639 STRCPY(IObuff + IOSIZE - 4, "...");
21640 vim_free(tofree);
21641 return vim_strsave(IObuff);
21645 * Get next function line.
21646 * Called by do_cmdline() to get the next line.
21647 * Returns allocated string, or NULL for end of function.
21649 /* ARGSUSED */
21650 char_u *
21651 get_func_line(c, cookie, indent)
21652 int c; /* not used */
21653 void *cookie;
21654 int indent; /* not used */
21656 funccall_T *fcp = (funccall_T *)cookie;
21657 ufunc_T *fp = fcp->func;
21658 char_u *retval;
21659 garray_T *gap; /* growarray with function lines */
21661 /* If breakpoints have been added/deleted need to check for it. */
21662 if (fcp->dbg_tick != debug_tick)
21664 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
21665 sourcing_lnum);
21666 fcp->dbg_tick = debug_tick;
21668 #ifdef FEAT_PROFILE
21669 if (do_profiling == PROF_YES)
21670 func_line_end(cookie);
21671 #endif
21673 gap = &fp->uf_lines;
21674 if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
21675 || fcp->returned)
21676 retval = NULL;
21677 else
21679 /* Skip NULL lines (continuation lines). */
21680 while (fcp->linenr < gap->ga_len
21681 && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL)
21682 ++fcp->linenr;
21683 if (fcp->linenr >= gap->ga_len)
21684 retval = NULL;
21685 else
21687 retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]);
21688 sourcing_lnum = fcp->linenr;
21689 #ifdef FEAT_PROFILE
21690 if (do_profiling == PROF_YES)
21691 func_line_start(cookie);
21692 #endif
21696 /* Did we encounter a breakpoint? */
21697 if (fcp->breakpoint != 0 && fcp->breakpoint <= sourcing_lnum)
21699 dbg_breakpoint(fp->uf_name, sourcing_lnum);
21700 /* Find next breakpoint. */
21701 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
21702 sourcing_lnum);
21703 fcp->dbg_tick = debug_tick;
21706 return retval;
21709 #if defined(FEAT_PROFILE) || defined(PROTO)
21711 * Called when starting to read a function line.
21712 * "sourcing_lnum" must be correct!
21713 * When skipping lines it may not actually be executed, but we won't find out
21714 * until later and we need to store the time now.
21716 void
21717 func_line_start(cookie)
21718 void *cookie;
21720 funccall_T *fcp = (funccall_T *)cookie;
21721 ufunc_T *fp = fcp->func;
21723 if (fp->uf_profiling && sourcing_lnum >= 1
21724 && sourcing_lnum <= fp->uf_lines.ga_len)
21726 fp->uf_tml_idx = sourcing_lnum - 1;
21727 /* Skip continuation lines. */
21728 while (fp->uf_tml_idx > 0 && FUNCLINE(fp, fp->uf_tml_idx) == NULL)
21729 --fp->uf_tml_idx;
21730 fp->uf_tml_execed = FALSE;
21731 profile_start(&fp->uf_tml_start);
21732 profile_zero(&fp->uf_tml_children);
21733 profile_get_wait(&fp->uf_tml_wait);
21738 * Called when actually executing a function line.
21740 void
21741 func_line_exec(cookie)
21742 void *cookie;
21744 funccall_T *fcp = (funccall_T *)cookie;
21745 ufunc_T *fp = fcp->func;
21747 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
21748 fp->uf_tml_execed = TRUE;
21752 * Called when done with a function line.
21754 void
21755 func_line_end(cookie)
21756 void *cookie;
21758 funccall_T *fcp = (funccall_T *)cookie;
21759 ufunc_T *fp = fcp->func;
21761 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
21763 if (fp->uf_tml_execed)
21765 ++fp->uf_tml_count[fp->uf_tml_idx];
21766 profile_end(&fp->uf_tml_start);
21767 profile_sub_wait(&fp->uf_tml_wait, &fp->uf_tml_start);
21768 profile_add(&fp->uf_tml_total[fp->uf_tml_idx], &fp->uf_tml_start);
21769 profile_self(&fp->uf_tml_self[fp->uf_tml_idx], &fp->uf_tml_start,
21770 &fp->uf_tml_children);
21772 fp->uf_tml_idx = -1;
21775 #endif
21778 * Return TRUE if the currently active function should be ended, because a
21779 * return was encountered or an error occurred. Used inside a ":while".
21782 func_has_ended(cookie)
21783 void *cookie;
21785 funccall_T *fcp = (funccall_T *)cookie;
21787 /* Ignore the "abort" flag if the abortion behavior has been changed due to
21788 * an error inside a try conditional. */
21789 return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
21790 || fcp->returned);
21794 * return TRUE if cookie indicates a function which "abort"s on errors.
21797 func_has_abort(cookie)
21798 void *cookie;
21800 return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT;
21803 #if defined(FEAT_VIMINFO) || defined(FEAT_SESSION)
21804 typedef enum
21806 VAR_FLAVOUR_DEFAULT, /* doesn't start with uppercase */
21807 VAR_FLAVOUR_SESSION, /* starts with uppercase, some lower */
21808 VAR_FLAVOUR_VIMINFO /* all uppercase */
21809 } var_flavour_T;
21811 static var_flavour_T var_flavour __ARGS((char_u *varname));
21813 static var_flavour_T
21814 var_flavour(varname)
21815 char_u *varname;
21817 char_u *p = varname;
21819 if (ASCII_ISUPPER(*p))
21821 while (*(++p))
21822 if (ASCII_ISLOWER(*p))
21823 return VAR_FLAVOUR_SESSION;
21824 return VAR_FLAVOUR_VIMINFO;
21826 else
21827 return VAR_FLAVOUR_DEFAULT;
21829 #endif
21831 #if defined(FEAT_VIMINFO) || defined(PROTO)
21833 * Restore global vars that start with a capital from the viminfo file
21836 read_viminfo_varlist(virp, writing)
21837 vir_T *virp;
21838 int writing;
21840 char_u *tab;
21841 int type = VAR_NUMBER;
21842 typval_T tv;
21844 if (!writing && (find_viminfo_parameter('!') != NULL))
21846 tab = vim_strchr(virp->vir_line + 1, '\t');
21847 if (tab != NULL)
21849 *tab++ = '\0'; /* isolate the variable name */
21850 if (*tab == 'S') /* string var */
21851 type = VAR_STRING;
21852 #ifdef FEAT_FLOAT
21853 else if (*tab == 'F')
21854 type = VAR_FLOAT;
21855 #endif
21857 tab = vim_strchr(tab, '\t');
21858 if (tab != NULL)
21860 tv.v_type = type;
21861 if (type == VAR_STRING)
21862 tv.vval.v_string = viminfo_readstring(virp,
21863 (int)(tab - virp->vir_line + 1), TRUE);
21864 #ifdef FEAT_FLOAT
21865 else if (type == VAR_FLOAT)
21866 (void)string2float(tab + 1, &tv.vval.v_float);
21867 #endif
21868 else
21869 tv.vval.v_number = atol((char *)tab + 1);
21870 set_var(virp->vir_line + 1, &tv, FALSE);
21871 if (type == VAR_STRING)
21872 vim_free(tv.vval.v_string);
21877 return viminfo_readline(virp);
21881 * Write global vars that start with a capital to the viminfo file
21883 void
21884 write_viminfo_varlist(fp)
21885 FILE *fp;
21887 hashitem_T *hi;
21888 dictitem_T *this_var;
21889 int todo;
21890 char *s;
21891 char_u *p;
21892 char_u *tofree;
21893 char_u numbuf[NUMBUFLEN];
21895 if (find_viminfo_parameter('!') == NULL)
21896 return;
21898 fprintf(fp, _("\n# global variables:\n"));
21900 todo = (int)globvarht.ht_used;
21901 for (hi = globvarht.ht_array; todo > 0; ++hi)
21903 if (!HASHITEM_EMPTY(hi))
21905 --todo;
21906 this_var = HI2DI(hi);
21907 if (var_flavour(this_var->di_key) == VAR_FLAVOUR_VIMINFO)
21909 switch (this_var->di_tv.v_type)
21911 case VAR_STRING: s = "STR"; break;
21912 case VAR_NUMBER: s = "NUM"; break;
21913 #ifdef FEAT_FLOAT
21914 case VAR_FLOAT: s = "FLO"; break;
21915 #endif
21916 default: continue;
21918 fprintf(fp, "!%s\t%s\t", this_var->di_key, s);
21919 p = echo_string(&this_var->di_tv, &tofree, numbuf, 0);
21920 if (p != NULL)
21921 viminfo_writestring(fp, p);
21922 vim_free(tofree);
21927 #endif
21929 #if defined(FEAT_SESSION) || defined(PROTO)
21931 store_session_globals(fd)
21932 FILE *fd;
21934 hashitem_T *hi;
21935 dictitem_T *this_var;
21936 int todo;
21937 char_u *p, *t;
21939 todo = (int)globvarht.ht_used;
21940 for (hi = globvarht.ht_array; todo > 0; ++hi)
21942 if (!HASHITEM_EMPTY(hi))
21944 --todo;
21945 this_var = HI2DI(hi);
21946 if ((this_var->di_tv.v_type == VAR_NUMBER
21947 || this_var->di_tv.v_type == VAR_STRING)
21948 && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
21950 /* Escape special characters with a backslash. Turn a LF and
21951 * CR into \n and \r. */
21952 p = vim_strsave_escaped(get_tv_string(&this_var->di_tv),
21953 (char_u *)"\\\"\n\r");
21954 if (p == NULL) /* out of memory */
21955 break;
21956 for (t = p; *t != NUL; ++t)
21957 if (*t == '\n')
21958 *t = 'n';
21959 else if (*t == '\r')
21960 *t = 'r';
21961 if ((fprintf(fd, "let %s = %c%s%c",
21962 this_var->di_key,
21963 (this_var->di_tv.v_type == VAR_STRING) ? '"'
21964 : ' ',
21966 (this_var->di_tv.v_type == VAR_STRING) ? '"'
21967 : ' ') < 0)
21968 || put_eol(fd) == FAIL)
21970 vim_free(p);
21971 return FAIL;
21973 vim_free(p);
21975 #ifdef FEAT_FLOAT
21976 else if (this_var->di_tv.v_type == VAR_FLOAT
21977 && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
21979 float_T f = this_var->di_tv.vval.v_float;
21980 int sign = ' ';
21982 if (f < 0)
21984 f = -f;
21985 sign = '-';
21987 if ((fprintf(fd, "let %s = %c&%f",
21988 this_var->di_key, sign, f) < 0)
21989 || put_eol(fd) == FAIL)
21990 return FAIL;
21992 #endif
21995 return OK;
21997 #endif
22000 * Display script name where an item was last set.
22001 * Should only be invoked when 'verbose' is non-zero.
22003 void
22004 last_set_msg(scriptID)
22005 scid_T scriptID;
22007 char_u *p;
22009 if (scriptID != 0)
22011 p = home_replace_save(NULL, get_scriptname(scriptID));
22012 if (p != NULL)
22014 verbose_enter();
22015 MSG_PUTS(_("\n\tLast set from "));
22016 MSG_PUTS(p);
22017 vim_free(p);
22018 verbose_leave();
22024 * List v:oldfiles in a nice way.
22026 /*ARGSUSED*/
22027 void
22028 ex_oldfiles(eap)
22029 exarg_T *eap;
22031 list_T *l = vimvars[VV_OLDFILES].vv_list;
22032 listitem_T *li;
22033 int nr = 0;
22035 if (l == NULL)
22036 msg((char_u *)_("No old files"));
22037 else
22039 msg_start();
22040 msg_scroll = TRUE;
22041 for (li = l->lv_first; li != NULL && !got_int; li = li->li_next)
22043 msg_outnum((long)++nr);
22044 MSG_PUTS(": ");
22045 msg_outtrans(get_tv_string(&li->li_tv));
22046 msg_putchar('\n');
22047 out_flush(); /* output one line at a time */
22048 ui_breakcheck();
22050 /* Assume "got_int" was set to truncate the listing. */
22051 got_int = FALSE;
22053 #ifdef FEAT_BROWSE_CMD
22054 if (cmdmod.browse)
22056 quit_more = FALSE;
22057 nr = prompt_for_number(FALSE);
22058 msg_starthere();
22059 if (nr > 0)
22061 char_u *p = list_find_str(get_vim_var_list(VV_OLDFILES),
22062 (long)nr);
22064 if (p != NULL)
22066 p = expand_env_save(p);
22067 eap->arg = p;
22068 eap->cmdidx = CMD_edit;
22069 cmdmod.browse = FALSE;
22070 do_exedit(eap, NULL);
22071 vim_free(p);
22075 #endif
22079 #endif /* FEAT_EVAL */
22082 #if defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) || defined(PROTO)
22084 #ifdef WIN3264
22086 * Functions for ":8" filename modifier: get 8.3 version of a filename.
22088 static int get_short_pathname __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
22089 static int shortpath_for_invalid_fname __ARGS((char_u **fname, char_u **bufp, int *fnamelen));
22090 static int shortpath_for_partial __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
22093 * Get the short path (8.3) for the filename in "fnamep".
22094 * Only works for a valid file name.
22095 * When the path gets longer "fnamep" is changed and the allocated buffer
22096 * is put in "bufp".
22097 * *fnamelen is the length of "fnamep" and set to 0 for a nonexistent path.
22098 * Returns OK on success, FAIL on failure.
22100 static int
22101 get_short_pathname(fnamep, bufp, fnamelen)
22102 char_u **fnamep;
22103 char_u **bufp;
22104 int *fnamelen;
22106 int l, len;
22107 char_u *newbuf;
22109 len = *fnamelen;
22110 l = GetShortPathName(*fnamep, *fnamep, len);
22111 if (l > len - 1)
22113 /* If that doesn't work (not enough space), then save the string
22114 * and try again with a new buffer big enough. */
22115 newbuf = vim_strnsave(*fnamep, l);
22116 if (newbuf == NULL)
22117 return FAIL;
22119 vim_free(*bufp);
22120 *fnamep = *bufp = newbuf;
22122 /* Really should always succeed, as the buffer is big enough. */
22123 l = GetShortPathName(*fnamep, *fnamep, l+1);
22126 *fnamelen = l;
22127 return OK;
22131 * Get the short path (8.3) for the filename in "fname". The converted
22132 * path is returned in "bufp".
22134 * Some of the directories specified in "fname" may not exist. This function
22135 * will shorten the existing directories at the beginning of the path and then
22136 * append the remaining non-existing path.
22138 * fname - Pointer to the filename to shorten. On return, contains the
22139 * pointer to the shortened pathname
22140 * bufp - Pointer to an allocated buffer for the filename.
22141 * fnamelen - Length of the filename pointed to by fname
22143 * Returns OK on success (or nothing done) and FAIL on failure (out of memory).
22145 static int
22146 shortpath_for_invalid_fname(fname, bufp, fnamelen)
22147 char_u **fname;
22148 char_u **bufp;
22149 int *fnamelen;
22151 char_u *short_fname, *save_fname, *pbuf_unused;
22152 char_u *endp, *save_endp;
22153 char_u ch;
22154 int old_len, len;
22155 int new_len, sfx_len;
22156 int retval = OK;
22158 /* Make a copy */
22159 old_len = *fnamelen;
22160 save_fname = vim_strnsave(*fname, old_len);
22161 pbuf_unused = NULL;
22162 short_fname = NULL;
22164 endp = save_fname + old_len - 1; /* Find the end of the copy */
22165 save_endp = endp;
22168 * Try shortening the supplied path till it succeeds by removing one
22169 * directory at a time from the tail of the path.
22171 len = 0;
22172 for (;;)
22174 /* go back one path-separator */
22175 while (endp > save_fname && !after_pathsep(save_fname, endp + 1))
22176 --endp;
22177 if (endp <= save_fname)
22178 break; /* processed the complete path */
22181 * Replace the path separator with a NUL and try to shorten the
22182 * resulting path.
22184 ch = *endp;
22185 *endp = 0;
22186 short_fname = save_fname;
22187 len = (int)STRLEN(short_fname) + 1;
22188 if (get_short_pathname(&short_fname, &pbuf_unused, &len) == FAIL)
22190 retval = FAIL;
22191 goto theend;
22193 *endp = ch; /* preserve the string */
22195 if (len > 0)
22196 break; /* successfully shortened the path */
22198 /* failed to shorten the path. Skip the path separator */
22199 --endp;
22202 if (len > 0)
22205 * Succeeded in shortening the path. Now concatenate the shortened
22206 * path with the remaining path at the tail.
22209 /* Compute the length of the new path. */
22210 sfx_len = (int)(save_endp - endp) + 1;
22211 new_len = len + sfx_len;
22213 *fnamelen = new_len;
22214 vim_free(*bufp);
22215 if (new_len > old_len)
22217 /* There is not enough space in the currently allocated string,
22218 * copy it to a buffer big enough. */
22219 *fname = *bufp = vim_strnsave(short_fname, new_len);
22220 if (*fname == NULL)
22222 retval = FAIL;
22223 goto theend;
22226 else
22228 /* Transfer short_fname to the main buffer (it's big enough),
22229 * unless get_short_pathname() did its work in-place. */
22230 *fname = *bufp = save_fname;
22231 if (short_fname != save_fname)
22232 vim_strncpy(save_fname, short_fname, len);
22233 save_fname = NULL;
22236 /* concat the not-shortened part of the path */
22237 vim_strncpy(*fname + len, endp, sfx_len);
22238 (*fname)[new_len] = NUL;
22241 theend:
22242 vim_free(pbuf_unused);
22243 vim_free(save_fname);
22245 return retval;
22249 * Get a pathname for a partial path.
22250 * Returns OK for success, FAIL for failure.
22252 static int
22253 shortpath_for_partial(fnamep, bufp, fnamelen)
22254 char_u **fnamep;
22255 char_u **bufp;
22256 int *fnamelen;
22258 int sepcount, len, tflen;
22259 char_u *p;
22260 char_u *pbuf, *tfname;
22261 int hasTilde;
22263 /* Count up the path separators from the RHS.. so we know which part
22264 * of the path to return. */
22265 sepcount = 0;
22266 for (p = *fnamep; p < *fnamep + *fnamelen; mb_ptr_adv(p))
22267 if (vim_ispathsep(*p))
22268 ++sepcount;
22270 /* Need full path first (use expand_env() to remove a "~/") */
22271 hasTilde = (**fnamep == '~');
22272 if (hasTilde)
22273 pbuf = tfname = expand_env_save(*fnamep);
22274 else
22275 pbuf = tfname = FullName_save(*fnamep, FALSE);
22277 len = tflen = (int)STRLEN(tfname);
22279 if (get_short_pathname(&tfname, &pbuf, &len) == FAIL)
22280 return FAIL;
22282 if (len == 0)
22284 /* Don't have a valid filename, so shorten the rest of the
22285 * path if we can. This CAN give us invalid 8.3 filenames, but
22286 * there's not a lot of point in guessing what it might be.
22288 len = tflen;
22289 if (shortpath_for_invalid_fname(&tfname, &pbuf, &len) == FAIL)
22290 return FAIL;
22293 /* Count the paths backward to find the beginning of the desired string. */
22294 for (p = tfname + len - 1; p >= tfname; --p)
22296 #ifdef FEAT_MBYTE
22297 if (has_mbyte)
22298 p -= mb_head_off(tfname, p);
22299 #endif
22300 if (vim_ispathsep(*p))
22302 if (sepcount == 0 || (hasTilde && sepcount == 1))
22303 break;
22304 else
22305 sepcount --;
22308 if (hasTilde)
22310 --p;
22311 if (p >= tfname)
22312 *p = '~';
22313 else
22314 return FAIL;
22316 else
22317 ++p;
22319 /* Copy in the string - p indexes into tfname - allocated at pbuf */
22320 vim_free(*bufp);
22321 *fnamelen = (int)STRLEN(p);
22322 *bufp = pbuf;
22323 *fnamep = p;
22325 return OK;
22327 #endif /* WIN3264 */
22330 * Adjust a filename, according to a string of modifiers.
22331 * *fnamep must be NUL terminated when called. When returning, the length is
22332 * determined by *fnamelen.
22333 * Returns VALID_ flags or -1 for failure.
22334 * When there is an error, *fnamep is set to NULL.
22337 modify_fname(src, usedlen, fnamep, bufp, fnamelen)
22338 char_u *src; /* string with modifiers */
22339 int *usedlen; /* characters after src that are used */
22340 char_u **fnamep; /* file name so far */
22341 char_u **bufp; /* buffer for allocated file name or NULL */
22342 int *fnamelen; /* length of fnamep */
22344 int valid = 0;
22345 char_u *tail;
22346 char_u *s, *p, *pbuf;
22347 char_u dirname[MAXPATHL];
22348 int c;
22349 int has_fullname = 0;
22350 #ifdef WIN3264
22351 int has_shortname = 0;
22352 #endif
22354 repeat:
22355 /* ":p" - full path/file_name */
22356 if (src[*usedlen] == ':' && src[*usedlen + 1] == 'p')
22358 has_fullname = 1;
22360 valid |= VALID_PATH;
22361 *usedlen += 2;
22363 /* Expand "~/path" for all systems and "~user/path" for Unix and VMS */
22364 if ((*fnamep)[0] == '~'
22365 #if !defined(UNIX) && !(defined(VMS) && defined(USER_HOME))
22366 && ((*fnamep)[1] == '/'
22367 # ifdef BACKSLASH_IN_FILENAME
22368 || (*fnamep)[1] == '\\'
22369 # endif
22370 || (*fnamep)[1] == NUL)
22372 #endif
22375 *fnamep = expand_env_save(*fnamep);
22376 vim_free(*bufp); /* free any allocated file name */
22377 *bufp = *fnamep;
22378 if (*fnamep == NULL)
22379 return -1;
22382 /* When "/." or "/.." is used: force expansion to get rid of it. */
22383 for (p = *fnamep; *p != NUL; mb_ptr_adv(p))
22385 if (vim_ispathsep(*p)
22386 && p[1] == '.'
22387 && (p[2] == NUL
22388 || vim_ispathsep(p[2])
22389 || (p[2] == '.'
22390 && (p[3] == NUL || vim_ispathsep(p[3])))))
22391 break;
22394 /* FullName_save() is slow, don't use it when not needed. */
22395 if (*p != NUL || !vim_isAbsName(*fnamep))
22397 *fnamep = FullName_save(*fnamep, *p != NUL);
22398 vim_free(*bufp); /* free any allocated file name */
22399 *bufp = *fnamep;
22400 if (*fnamep == NULL)
22401 return -1;
22404 /* Append a path separator to a directory. */
22405 if (mch_isdir(*fnamep))
22407 /* Make room for one or two extra characters. */
22408 *fnamep = vim_strnsave(*fnamep, (int)STRLEN(*fnamep) + 2);
22409 vim_free(*bufp); /* free any allocated file name */
22410 *bufp = *fnamep;
22411 if (*fnamep == NULL)
22412 return -1;
22413 add_pathsep(*fnamep);
22417 /* ":." - path relative to the current directory */
22418 /* ":~" - path relative to the home directory */
22419 /* ":8" - shortname path - postponed till after */
22420 while (src[*usedlen] == ':'
22421 && ((c = src[*usedlen + 1]) == '.' || c == '~' || c == '8'))
22423 *usedlen += 2;
22424 if (c == '8')
22426 #ifdef WIN3264
22427 has_shortname = 1; /* Postpone this. */
22428 #endif
22429 continue;
22431 pbuf = NULL;
22432 /* Need full path first (use expand_env() to remove a "~/") */
22433 if (!has_fullname)
22435 if (c == '.' && **fnamep == '~')
22436 p = pbuf = expand_env_save(*fnamep);
22437 else
22438 p = pbuf = FullName_save(*fnamep, FALSE);
22440 else
22441 p = *fnamep;
22443 has_fullname = 0;
22445 if (p != NULL)
22447 if (c == '.')
22449 mch_dirname(dirname, MAXPATHL);
22450 s = shorten_fname(p, dirname);
22451 if (s != NULL)
22453 *fnamep = s;
22454 if (pbuf != NULL)
22456 vim_free(*bufp); /* free any allocated file name */
22457 *bufp = pbuf;
22458 pbuf = NULL;
22462 else
22464 home_replace(NULL, p, dirname, MAXPATHL, TRUE);
22465 /* Only replace it when it starts with '~' */
22466 if (*dirname == '~')
22468 s = vim_strsave(dirname);
22469 if (s != NULL)
22471 *fnamep = s;
22472 vim_free(*bufp);
22473 *bufp = s;
22477 vim_free(pbuf);
22481 tail = gettail(*fnamep);
22482 *fnamelen = (int)STRLEN(*fnamep);
22484 /* ":h" - head, remove "/file_name", can be repeated */
22485 /* Don't remove the first "/" or "c:\" */
22486 while (src[*usedlen] == ':' && src[*usedlen + 1] == 'h')
22488 valid |= VALID_HEAD;
22489 *usedlen += 2;
22490 s = get_past_head(*fnamep);
22491 while (tail > s && after_pathsep(s, tail))
22492 mb_ptr_back(*fnamep, tail);
22493 *fnamelen = (int)(tail - *fnamep);
22494 #ifdef VMS
22495 if (*fnamelen > 0)
22496 *fnamelen += 1; /* the path separator is part of the path */
22497 #endif
22498 if (*fnamelen == 0)
22500 /* Result is empty. Turn it into "." to make ":cd %:h" work. */
22501 p = vim_strsave((char_u *)".");
22502 if (p == NULL)
22503 return -1;
22504 vim_free(*bufp);
22505 *bufp = *fnamep = tail = p;
22506 *fnamelen = 1;
22508 else
22510 while (tail > s && !after_pathsep(s, tail))
22511 mb_ptr_back(*fnamep, tail);
22515 /* ":8" - shortname */
22516 if (src[*usedlen] == ':' && src[*usedlen + 1] == '8')
22518 *usedlen += 2;
22519 #ifdef WIN3264
22520 has_shortname = 1;
22521 #endif
22524 #ifdef WIN3264
22525 /* Check shortname after we have done 'heads' and before we do 'tails'
22527 if (has_shortname)
22529 pbuf = NULL;
22530 /* Copy the string if it is shortened by :h */
22531 if (*fnamelen < (int)STRLEN(*fnamep))
22533 p = vim_strnsave(*fnamep, *fnamelen);
22534 if (p == 0)
22535 return -1;
22536 vim_free(*bufp);
22537 *bufp = *fnamep = p;
22540 /* Split into two implementations - makes it easier. First is where
22541 * there isn't a full name already, second is where there is.
22543 if (!has_fullname && !vim_isAbsName(*fnamep))
22545 if (shortpath_for_partial(fnamep, bufp, fnamelen) == FAIL)
22546 return -1;
22548 else
22550 int l;
22552 /* Simple case, already have the full-name
22553 * Nearly always shorter, so try first time. */
22554 l = *fnamelen;
22555 if (get_short_pathname(fnamep, bufp, &l) == FAIL)
22556 return -1;
22558 if (l == 0)
22560 /* Couldn't find the filename.. search the paths.
22562 l = *fnamelen;
22563 if (shortpath_for_invalid_fname(fnamep, bufp, &l) == FAIL)
22564 return -1;
22566 *fnamelen = l;
22569 #endif /* WIN3264 */
22571 /* ":t" - tail, just the basename */
22572 if (src[*usedlen] == ':' && src[*usedlen + 1] == 't')
22574 *usedlen += 2;
22575 *fnamelen -= (int)(tail - *fnamep);
22576 *fnamep = tail;
22579 /* ":e" - extension, can be repeated */
22580 /* ":r" - root, without extension, can be repeated */
22581 while (src[*usedlen] == ':'
22582 && (src[*usedlen + 1] == 'e' || src[*usedlen + 1] == 'r'))
22584 /* find a '.' in the tail:
22585 * - for second :e: before the current fname
22586 * - otherwise: The last '.'
22588 if (src[*usedlen + 1] == 'e' && *fnamep > tail)
22589 s = *fnamep - 2;
22590 else
22591 s = *fnamep + *fnamelen - 1;
22592 for ( ; s > tail; --s)
22593 if (s[0] == '.')
22594 break;
22595 if (src[*usedlen + 1] == 'e') /* :e */
22597 if (s > tail)
22599 *fnamelen += (int)(*fnamep - (s + 1));
22600 *fnamep = s + 1;
22601 #ifdef VMS
22602 /* cut version from the extension */
22603 s = *fnamep + *fnamelen - 1;
22604 for ( ; s > *fnamep; --s)
22605 if (s[0] == ';')
22606 break;
22607 if (s > *fnamep)
22608 *fnamelen = s - *fnamep;
22609 #endif
22611 else if (*fnamep <= tail)
22612 *fnamelen = 0;
22614 else /* :r */
22616 if (s > tail) /* remove one extension */
22617 *fnamelen = (int)(s - *fnamep);
22619 *usedlen += 2;
22622 /* ":s?pat?foo?" - substitute */
22623 /* ":gs?pat?foo?" - global substitute */
22624 if (src[*usedlen] == ':'
22625 && (src[*usedlen + 1] == 's'
22626 || (src[*usedlen + 1] == 'g' && src[*usedlen + 2] == 's')))
22628 char_u *str;
22629 char_u *pat;
22630 char_u *sub;
22631 int sep;
22632 char_u *flags;
22633 int didit = FALSE;
22635 flags = (char_u *)"";
22636 s = src + *usedlen + 2;
22637 if (src[*usedlen + 1] == 'g')
22639 flags = (char_u *)"g";
22640 ++s;
22643 sep = *s++;
22644 if (sep)
22646 /* find end of pattern */
22647 p = vim_strchr(s, sep);
22648 if (p != NULL)
22650 pat = vim_strnsave(s, (int)(p - s));
22651 if (pat != NULL)
22653 s = p + 1;
22654 /* find end of substitution */
22655 p = vim_strchr(s, sep);
22656 if (p != NULL)
22658 sub = vim_strnsave(s, (int)(p - s));
22659 str = vim_strnsave(*fnamep, *fnamelen);
22660 if (sub != NULL && str != NULL)
22662 *usedlen = (int)(p + 1 - src);
22663 s = do_string_sub(str, pat, sub, flags);
22664 if (s != NULL)
22666 *fnamep = s;
22667 *fnamelen = (int)STRLEN(s);
22668 vim_free(*bufp);
22669 *bufp = s;
22670 didit = TRUE;
22673 vim_free(sub);
22674 vim_free(str);
22676 vim_free(pat);
22679 /* after using ":s", repeat all the modifiers */
22680 if (didit)
22681 goto repeat;
22685 return valid;
22689 * Perform a substitution on "str" with pattern "pat" and substitute "sub".
22690 * "flags" can be "g" to do a global substitute.
22691 * Returns an allocated string, NULL for error.
22693 char_u *
22694 do_string_sub(str, pat, sub, flags)
22695 char_u *str;
22696 char_u *pat;
22697 char_u *sub;
22698 char_u *flags;
22700 int sublen;
22701 regmatch_T regmatch;
22702 int i;
22703 int do_all;
22704 char_u *tail;
22705 garray_T ga;
22706 char_u *ret;
22707 char_u *save_cpo;
22709 /* Make 'cpoptions' empty, so that the 'l' flag doesn't work here */
22710 save_cpo = p_cpo;
22711 p_cpo = empty_option;
22713 ga_init2(&ga, 1, 200);
22715 do_all = (flags[0] == 'g');
22717 regmatch.rm_ic = p_ic;
22718 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
22719 if (regmatch.regprog != NULL)
22721 tail = str;
22722 while (vim_regexec_nl(&regmatch, str, (colnr_T)(tail - str)))
22725 * Get some space for a temporary buffer to do the substitution
22726 * into. It will contain:
22727 * - The text up to where the match is.
22728 * - The substituted text.
22729 * - The text after the match.
22731 sublen = vim_regsub(&regmatch, sub, tail, FALSE, TRUE, FALSE);
22732 if (ga_grow(&ga, (int)(STRLEN(tail) + sublen -
22733 (regmatch.endp[0] - regmatch.startp[0]))) == FAIL)
22735 ga_clear(&ga);
22736 break;
22739 /* copy the text up to where the match is */
22740 i = (int)(regmatch.startp[0] - tail);
22741 mch_memmove((char_u *)ga.ga_data + ga.ga_len, tail, (size_t)i);
22742 /* add the substituted text */
22743 (void)vim_regsub(&regmatch, sub, (char_u *)ga.ga_data
22744 + ga.ga_len + i, TRUE, TRUE, FALSE);
22745 ga.ga_len += i + sublen - 1;
22746 /* avoid getting stuck on a match with an empty string */
22747 if (tail == regmatch.endp[0])
22749 if (*tail == NUL)
22750 break;
22751 *((char_u *)ga.ga_data + ga.ga_len) = *tail++;
22752 ++ga.ga_len;
22754 else
22756 tail = regmatch.endp[0];
22757 if (*tail == NUL)
22758 break;
22760 if (!do_all)
22761 break;
22764 if (ga.ga_data != NULL)
22765 STRCPY((char *)ga.ga_data + ga.ga_len, tail);
22767 vim_free(regmatch.regprog);
22770 ret = vim_strsave(ga.ga_data == NULL ? str : (char_u *)ga.ga_data);
22771 ga_clear(&ga);
22772 if (p_cpo == empty_option)
22773 p_cpo = save_cpo;
22774 else
22775 /* Darn, evaluating {sub} expression changed the value. */
22776 free_string_option(save_cpo);
22778 return ret;
22781 #endif /* defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) */