Merge branch 'feat/tagfunc'
[vim_extended.git] / src / eval.c
blob3e8df3697fe54fefdab00dd7815899656ee7114e
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.
132 * The last bit is used for previous_funccal, ignored when comparing.
134 static int current_copyID = 0;
135 #define COPYID_INC 2
136 #define COPYID_MASK (~0x1)
139 * Array to hold the hashtab with variables local to each sourced script.
140 * Each item holds a variable (nameless) that points to the dict_T.
142 typedef struct
144 dictitem_T sv_var;
145 dict_T sv_dict;
146 } scriptvar_T;
148 static garray_T ga_scripts = {0, 0, sizeof(scriptvar_T *), 4, NULL};
149 #define SCRIPT_SV(id) (((scriptvar_T **)ga_scripts.ga_data)[(id) - 1])
150 #define SCRIPT_VARS(id) (SCRIPT_SV(id)->sv_dict.dv_hashtab)
152 static int echo_attr = 0; /* attributes used for ":echo" */
154 /* Values for trans_function_name() argument: */
155 #define TFN_INT 1 /* internal function name OK */
156 #define TFN_QUIET 2 /* no error messages */
159 * Structure to hold info for a user function.
161 typedef struct ufunc ufunc_T;
163 struct ufunc
165 int uf_varargs; /* variable nr of arguments */
166 int uf_flags;
167 int uf_calls; /* nr of active calls */
168 garray_T uf_args; /* arguments */
169 garray_T uf_lines; /* function lines */
170 #ifdef FEAT_PROFILE
171 int uf_profiling; /* TRUE when func is being profiled */
172 /* profiling the function as a whole */
173 int uf_tm_count; /* nr of calls */
174 proftime_T uf_tm_total; /* time spent in function + children */
175 proftime_T uf_tm_self; /* time spent in function itself */
176 proftime_T uf_tm_children; /* time spent in children this call */
177 /* profiling the function per line */
178 int *uf_tml_count; /* nr of times line was executed */
179 proftime_T *uf_tml_total; /* time spent in a line + children */
180 proftime_T *uf_tml_self; /* time spent in a line itself */
181 proftime_T uf_tml_start; /* start time for current line */
182 proftime_T uf_tml_children; /* time spent in children for this line */
183 proftime_T uf_tml_wait; /* start wait time for current line */
184 int uf_tml_idx; /* index of line being timed; -1 if none */
185 int uf_tml_execed; /* line being timed was executed */
186 #endif
187 scid_T uf_script_ID; /* ID of script where function was defined,
188 used for s: variables */
189 int uf_refcount; /* for numbered function: reference count */
190 char_u uf_name[1]; /* name of function (actually longer); can
191 start with <SNR>123_ (<SNR> is K_SPECIAL
192 KS_EXTRA KE_SNR) */
195 /* function flags */
196 #define FC_ABORT 1 /* abort function on error */
197 #define FC_RANGE 2 /* function accepts range */
198 #define FC_DICT 4 /* Dict function, uses "self" */
201 * All user-defined functions are found in this hashtable.
203 static hashtab_T func_hashtab;
205 /* The names of packages that once were loaded are remembered. */
206 static garray_T ga_loaded = {0, 0, sizeof(char_u *), 4, NULL};
208 /* list heads for garbage collection */
209 static dict_T *first_dict = NULL; /* list of all dicts */
210 static list_T *first_list = NULL; /* list of all lists */
212 /* From user function to hashitem and back. */
213 static ufunc_T dumuf;
214 #define UF2HIKEY(fp) ((fp)->uf_name)
215 #define HIKEY2UF(p) ((ufunc_T *)(p - (dumuf.uf_name - (char_u *)&dumuf)))
216 #define HI2UF(hi) HIKEY2UF((hi)->hi_key)
218 #define FUNCARG(fp, j) ((char_u **)(fp->uf_args.ga_data))[j]
219 #define FUNCLINE(fp, j) ((char_u **)(fp->uf_lines.ga_data))[j]
221 #define MAX_FUNC_ARGS 20 /* maximum number of function arguments */
222 #define VAR_SHORT_LEN 20 /* short variable name length */
223 #define FIXVAR_CNT 12 /* number of fixed variables */
225 /* structure to hold info for a function that is currently being executed. */
226 typedef struct funccall_S funccall_T;
228 struct funccall_S
230 ufunc_T *func; /* function being called */
231 int linenr; /* next line to be executed */
232 int returned; /* ":return" used */
233 struct /* fixed variables for arguments */
235 dictitem_T var; /* variable (without room for name) */
236 char_u room[VAR_SHORT_LEN]; /* room for the name */
237 } fixvar[FIXVAR_CNT];
238 dict_T l_vars; /* l: local function variables */
239 dictitem_T l_vars_var; /* variable for l: scope */
240 dict_T l_avars; /* a: argument variables */
241 dictitem_T l_avars_var; /* variable for a: scope */
242 list_T l_varlist; /* list for a:000 */
243 listitem_T l_listitems[MAX_FUNC_ARGS]; /* listitems for a:000 */
244 typval_T *rettv; /* return value */
245 linenr_T breakpoint; /* next line with breakpoint or zero */
246 int dbg_tick; /* debug_tick when breakpoint was set */
247 int level; /* top nesting level of executed function */
248 #ifdef FEAT_PROFILE
249 proftime_T prof_child; /* time spent in a child */
250 #endif
251 funccall_T *caller; /* calling function or NULL */
255 * Info used by a ":for" loop.
257 typedef struct
259 int fi_semicolon; /* TRUE if ending in '; var]' */
260 int fi_varcount; /* nr of variables in the list */
261 listwatch_T fi_lw; /* keep an eye on the item used. */
262 list_T *fi_list; /* list being used */
263 } forinfo_T;
266 * Struct used by trans_function_name()
268 typedef struct
270 dict_T *fd_dict; /* Dictionary used */
271 char_u *fd_newkey; /* new key in "dict" in allocated memory */
272 dictitem_T *fd_di; /* Dictionary item used */
273 } funcdict_T;
277 * Array to hold the value of v: variables.
278 * The value is in a dictitem, so that it can also be used in the v: scope.
279 * The reason to use this table anyway is for very quick access to the
280 * variables with the VV_ defines.
282 #include "version.h"
284 /* values for vv_flags: */
285 #define VV_COMPAT 1 /* compatible, also used without "v:" */
286 #define VV_RO 2 /* read-only */
287 #define VV_RO_SBX 4 /* read-only in the sandbox */
289 #define VV_NAME(s, t) s, {{t, 0, {0}}, 0, {0}}, {0}
291 static struct vimvar
293 char *vv_name; /* name of variable, without v: */
294 dictitem_T vv_di; /* value and name for key */
295 char vv_filler[16]; /* space for LONGEST name below!!! */
296 char vv_flags; /* VV_COMPAT, VV_RO, VV_RO_SBX */
297 } vimvars[VV_LEN] =
300 * The order here must match the VV_ defines in vim.h!
301 * Initializing a union does not work, leave tv.vval empty to get zero's.
303 {VV_NAME("count", VAR_NUMBER), VV_COMPAT+VV_RO},
304 {VV_NAME("count1", VAR_NUMBER), VV_RO},
305 {VV_NAME("prevcount", VAR_NUMBER), VV_RO},
306 {VV_NAME("errmsg", VAR_STRING), VV_COMPAT},
307 {VV_NAME("warningmsg", VAR_STRING), 0},
308 {VV_NAME("statusmsg", VAR_STRING), 0},
309 {VV_NAME("shell_error", VAR_NUMBER), VV_COMPAT+VV_RO},
310 {VV_NAME("this_session", VAR_STRING), VV_COMPAT},
311 {VV_NAME("version", VAR_NUMBER), VV_COMPAT+VV_RO},
312 {VV_NAME("lnum", VAR_NUMBER), VV_RO_SBX},
313 {VV_NAME("termresponse", VAR_STRING), VV_RO},
314 {VV_NAME("fname", VAR_STRING), VV_RO},
315 {VV_NAME("lang", VAR_STRING), VV_RO},
316 {VV_NAME("lc_time", VAR_STRING), VV_RO},
317 {VV_NAME("ctype", VAR_STRING), VV_RO},
318 {VV_NAME("charconvert_from", VAR_STRING), VV_RO},
319 {VV_NAME("charconvert_to", VAR_STRING), VV_RO},
320 {VV_NAME("fname_in", VAR_STRING), VV_RO},
321 {VV_NAME("fname_out", VAR_STRING), VV_RO},
322 {VV_NAME("fname_new", VAR_STRING), VV_RO},
323 {VV_NAME("fname_diff", VAR_STRING), VV_RO},
324 {VV_NAME("cmdarg", VAR_STRING), VV_RO},
325 {VV_NAME("foldstart", VAR_NUMBER), VV_RO_SBX},
326 {VV_NAME("foldend", VAR_NUMBER), VV_RO_SBX},
327 {VV_NAME("folddashes", VAR_STRING), VV_RO_SBX},
328 {VV_NAME("foldlevel", VAR_NUMBER), VV_RO_SBX},
329 {VV_NAME("progname", VAR_STRING), VV_RO},
330 {VV_NAME("servername", VAR_STRING), VV_RO},
331 {VV_NAME("dying", VAR_NUMBER), VV_RO},
332 {VV_NAME("exception", VAR_STRING), VV_RO},
333 {VV_NAME("throwpoint", VAR_STRING), VV_RO},
334 {VV_NAME("register", VAR_STRING), VV_RO},
335 {VV_NAME("cmdbang", VAR_NUMBER), VV_RO},
336 {VV_NAME("insertmode", VAR_STRING), VV_RO},
337 {VV_NAME("val", VAR_UNKNOWN), VV_RO},
338 {VV_NAME("key", VAR_UNKNOWN), VV_RO},
339 {VV_NAME("profiling", VAR_NUMBER), VV_RO},
340 {VV_NAME("fcs_reason", VAR_STRING), VV_RO},
341 {VV_NAME("fcs_choice", VAR_STRING), 0},
342 {VV_NAME("beval_bufnr", VAR_NUMBER), VV_RO},
343 {VV_NAME("beval_winnr", VAR_NUMBER), VV_RO},
344 {VV_NAME("beval_lnum", VAR_NUMBER), VV_RO},
345 {VV_NAME("beval_col", VAR_NUMBER), VV_RO},
346 {VV_NAME("beval_text", VAR_STRING), VV_RO},
347 {VV_NAME("scrollstart", VAR_STRING), 0},
348 {VV_NAME("swapname", VAR_STRING), VV_RO},
349 {VV_NAME("swapchoice", VAR_STRING), 0},
350 {VV_NAME("swapcommand", VAR_STRING), VV_RO},
351 {VV_NAME("char", VAR_STRING), VV_RO},
352 {VV_NAME("mouse_win", VAR_NUMBER), 0},
353 {VV_NAME("mouse_lnum", VAR_NUMBER), 0},
354 {VV_NAME("mouse_col", VAR_NUMBER), 0},
355 {VV_NAME("operator", VAR_STRING), VV_RO},
356 {VV_NAME("searchforward", VAR_NUMBER), 0},
357 {VV_NAME("oldfiles", VAR_LIST), 0},
360 /* shorthand */
361 #define vv_type vv_di.di_tv.v_type
362 #define vv_nr vv_di.di_tv.vval.v_number
363 #define vv_float vv_di.di_tv.vval.v_float
364 #define vv_str vv_di.di_tv.vval.v_string
365 #define vv_list vv_di.di_tv.vval.v_list
366 #define vv_tv vv_di.di_tv
369 * The v: variables are stored in dictionary "vimvardict".
370 * "vimvars_var" is the variable that is used for the "l:" scope.
372 static dict_T vimvardict;
373 static dictitem_T vimvars_var;
374 #define vimvarht vimvardict.dv_hashtab
376 static void prepare_vimvar __ARGS((int idx, typval_T *save_tv));
377 static void restore_vimvar __ARGS((int idx, typval_T *save_tv));
378 #if defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)
379 static int call_vim_function __ARGS((char_u *func, int argc, char_u **argv, int safe, typval_T *rettv));
380 #endif
381 static int ex_let_vars __ARGS((char_u *arg, typval_T *tv, int copy, int semicolon, int var_count, char_u *nextchars));
382 static char_u *skip_var_list __ARGS((char_u *arg, int *var_count, int *semicolon));
383 static char_u *skip_var_one __ARGS((char_u *arg));
384 static void list_hashtable_vars __ARGS((hashtab_T *ht, char_u *prefix, int empty, int *first));
385 static void list_glob_vars __ARGS((int *first));
386 static void list_buf_vars __ARGS((int *first));
387 static void list_win_vars __ARGS((int *first));
388 #ifdef FEAT_WINDOWS
389 static void list_tab_vars __ARGS((int *first));
390 #endif
391 static void list_vim_vars __ARGS((int *first));
392 static void list_script_vars __ARGS((int *first));
393 static void list_func_vars __ARGS((int *first));
394 static char_u *list_arg_vars __ARGS((exarg_T *eap, char_u *arg, int *first));
395 static char_u *ex_let_one __ARGS((char_u *arg, typval_T *tv, int copy, char_u *endchars, char_u *op));
396 static int check_changedtick __ARGS((char_u *arg));
397 static char_u *get_lval __ARGS((char_u *name, typval_T *rettv, lval_T *lp, int unlet, int skip, int quiet, int fne_flags));
398 static void clear_lval __ARGS((lval_T *lp));
399 static void set_var_lval __ARGS((lval_T *lp, char_u *endp, typval_T *rettv, int copy, char_u *op));
400 static int tv_op __ARGS((typval_T *tv1, typval_T *tv2, char_u *op));
401 static void list_add_watch __ARGS((list_T *l, listwatch_T *lw));
402 static void list_rem_watch __ARGS((list_T *l, listwatch_T *lwrem));
403 static void list_fix_watch __ARGS((list_T *l, listitem_T *item));
404 static void ex_unletlock __ARGS((exarg_T *eap, char_u *argstart, int deep));
405 static int do_unlet_var __ARGS((lval_T *lp, char_u *name_end, int forceit));
406 static int do_lock_var __ARGS((lval_T *lp, char_u *name_end, int deep, int lock));
407 static void item_lock __ARGS((typval_T *tv, int deep, int lock));
408 static int tv_islocked __ARGS((typval_T *tv));
410 static int eval0 __ARGS((char_u *arg, typval_T *rettv, char_u **nextcmd, int evaluate));
411 static int eval1 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
412 static int eval2 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
413 static int eval3 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
414 static int eval4 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
415 static int eval5 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
416 static int eval6 __ARGS((char_u **arg, typval_T *rettv, int evaluate, int want_string));
417 static int eval7 __ARGS((char_u **arg, typval_T *rettv, int evaluate, int want_string));
419 static int eval_index __ARGS((char_u **arg, typval_T *rettv, int evaluate, int verbose));
420 static int get_option_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
421 static int get_string_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
422 static int get_lit_string_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
423 static int get_list_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
424 static int rettv_list_alloc __ARGS((typval_T *rettv));
425 static listitem_T *listitem_alloc __ARGS((void));
426 static void listitem_free __ARGS((listitem_T *item));
427 static void listitem_remove __ARGS((list_T *l, listitem_T *item));
428 static long list_len __ARGS((list_T *l));
429 static int list_equal __ARGS((list_T *l1, list_T *l2, int ic));
430 static int dict_equal __ARGS((dict_T *d1, dict_T *d2, int ic));
431 static int tv_equal __ARGS((typval_T *tv1, typval_T *tv2, int ic));
432 static listitem_T *list_find __ARGS((list_T *l, long n));
433 static long list_find_nr __ARGS((list_T *l, long idx, int *errorp));
434 static long list_idx_of_item __ARGS((list_T *l, listitem_T *item));
435 static void list_append __ARGS((list_T *l, listitem_T *item));
436 static int list_append_number __ARGS((list_T *l, varnumber_T n));
437 static int list_insert_tv __ARGS((list_T *l, typval_T *tv, listitem_T *item));
438 static int list_extend __ARGS((list_T *l1, list_T *l2, listitem_T *bef));
439 static int list_concat __ARGS((list_T *l1, list_T *l2, typval_T *tv));
440 static list_T *list_copy __ARGS((list_T *orig, int deep, int copyID));
441 static void list_remove __ARGS((list_T *l, listitem_T *item, listitem_T *item2));
442 static char_u *list2string __ARGS((typval_T *tv, int copyID));
443 static int list_join __ARGS((garray_T *gap, list_T *l, char_u *sep, int echo, int copyID));
444 static int free_unref_items __ARGS((int copyID));
445 static void set_ref_in_ht __ARGS((hashtab_T *ht, int copyID));
446 static void set_ref_in_list __ARGS((list_T *l, int copyID));
447 static void set_ref_in_item __ARGS((typval_T *tv, int copyID));
448 static void dict_unref __ARGS((dict_T *d));
449 static void dict_free __ARGS((dict_T *d, int recurse));
450 static dictitem_T *dictitem_copy __ARGS((dictitem_T *org));
451 static void dictitem_remove __ARGS((dict_T *dict, dictitem_T *item));
452 static dict_T *dict_copy __ARGS((dict_T *orig, int deep, int copyID));
453 static long dict_len __ARGS((dict_T *d));
454 static char_u *dict2string __ARGS((typval_T *tv, int copyID));
455 static int get_dict_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
456 static char_u *echo_string __ARGS((typval_T *tv, char_u **tofree, char_u *numbuf, int copyID));
457 static char_u *tv2string __ARGS((typval_T *tv, char_u **tofree, char_u *numbuf, int copyID));
458 static char_u *string_quote __ARGS((char_u *str, int function));
459 #ifdef FEAT_FLOAT
460 static int string2float __ARGS((char_u *text, float_T *value));
461 #endif
462 static int get_env_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
463 static int find_internal_func __ARGS((char_u *name));
464 static char_u *deref_func_name __ARGS((char_u *name, int *lenp));
465 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));
466 static int call_func __ARGS((char_u *func_name, int len, typval_T *rettv, int argcount, typval_T *argvars, linenr_T firstline, linenr_T lastline, int *doesrange, int evaluate, dict_T *selfdict));
467 static void emsg_funcname __ARGS((char *ermsg, char_u *name));
468 static int non_zero_arg __ARGS((typval_T *argvars));
470 #ifdef FEAT_FLOAT
471 static void f_abs __ARGS((typval_T *argvars, typval_T *rettv));
473 /* Below are the 10 added FP functions - I've kept them together */
474 /* here and in their definitions later on. Because the functions[] */
475 /* table must be in ASCII order, they are scattered there - WJMc */
477 static void f_acos __ARGS((typval_T *argvars, typval_T *rettv));
478 static void f_asin __ARGS((typval_T *argvars, typval_T *rettv));
479 static void f_atan2 __ARGS((typval_T *argvars, typval_T *rettv)); /* 2 args */
480 static void f_cosh __ARGS((typval_T *argvars, typval_T *rettv));
481 static void f_exp __ARGS((typval_T *argvars, typval_T *rettv));
482 static void f_fmod __ARGS((typval_T *argvars, typval_T *rettv)); /* 2 args */
483 static void f_log __ARGS((typval_T *argvars, typval_T *rettv));
484 static void f_sinh __ARGS((typval_T *argvars, typval_T *rettv));
485 static void f_tan __ARGS((typval_T *argvars, typval_T *rettv));
486 static void f_tanh __ARGS((typval_T *argvars, typval_T *rettv));
487 #endif
488 static void f_add __ARGS((typval_T *argvars, typval_T *rettv));
489 static void f_append __ARGS((typval_T *argvars, typval_T *rettv));
490 static void f_argc __ARGS((typval_T *argvars, typval_T *rettv));
491 static void f_argidx __ARGS((typval_T *argvars, typval_T *rettv));
492 static void f_argv __ARGS((typval_T *argvars, typval_T *rettv));
493 #ifdef FEAT_FLOAT
494 static void f_atan __ARGS((typval_T *argvars, typval_T *rettv));
495 #endif
496 static void f_browse __ARGS((typval_T *argvars, typval_T *rettv));
497 static void f_browsedir __ARGS((typval_T *argvars, typval_T *rettv));
498 static void f_bufexists __ARGS((typval_T *argvars, typval_T *rettv));
499 static void f_buflisted __ARGS((typval_T *argvars, typval_T *rettv));
500 static void f_bufloaded __ARGS((typval_T *argvars, typval_T *rettv));
501 static void f_bufname __ARGS((typval_T *argvars, typval_T *rettv));
502 static void f_bufnr __ARGS((typval_T *argvars, typval_T *rettv));
503 static void f_bufwinnr __ARGS((typval_T *argvars, typval_T *rettv));
504 static void f_byte2line __ARGS((typval_T *argvars, typval_T *rettv));
505 static void f_byteidx __ARGS((typval_T *argvars, typval_T *rettv));
506 static void f_call __ARGS((typval_T *argvars, typval_T *rettv));
507 #ifdef FEAT_FLOAT
508 static void f_ceil __ARGS((typval_T *argvars, typval_T *rettv));
509 #endif
510 static void f_changenr __ARGS((typval_T *argvars, typval_T *rettv));
511 static void f_char2nr __ARGS((typval_T *argvars, typval_T *rettv));
512 static void f_cindent __ARGS((typval_T *argvars, typval_T *rettv));
513 static void f_clearmatches __ARGS((typval_T *argvars, typval_T *rettv));
514 static void f_col __ARGS((typval_T *argvars, typval_T *rettv));
515 #if defined(FEAT_INS_EXPAND)
516 static void f_complete __ARGS((typval_T *argvars, typval_T *rettv));
517 static void f_complete_add __ARGS((typval_T *argvars, typval_T *rettv));
518 static void f_complete_check __ARGS((typval_T *argvars, typval_T *rettv));
519 #endif
520 static void f_confirm __ARGS((typval_T *argvars, typval_T *rettv));
521 static void f_copy __ARGS((typval_T *argvars, typval_T *rettv));
522 #ifdef FEAT_FLOAT
523 static void f_cos __ARGS((typval_T *argvars, typval_T *rettv));
524 #endif
525 static void f_count __ARGS((typval_T *argvars, typval_T *rettv));
526 static void f_cscope_connection __ARGS((typval_T *argvars, typval_T *rettv));
527 static void f_cursor __ARGS((typval_T *argsvars, typval_T *rettv));
528 static void f_deepcopy __ARGS((typval_T *argvars, typval_T *rettv));
529 static void f_delete __ARGS((typval_T *argvars, typval_T *rettv));
530 static void f_did_filetype __ARGS((typval_T *argvars, typval_T *rettv));
531 static void f_diff_filler __ARGS((typval_T *argvars, typval_T *rettv));
532 static void f_diff_hlID __ARGS((typval_T *argvars, typval_T *rettv));
533 static void f_empty __ARGS((typval_T *argvars, typval_T *rettv));
534 static void f_escape __ARGS((typval_T *argvars, typval_T *rettv));
535 static void f_eval __ARGS((typval_T *argvars, typval_T *rettv));
536 static void f_eventhandler __ARGS((typval_T *argvars, typval_T *rettv));
537 static void f_executable __ARGS((typval_T *argvars, typval_T *rettv));
538 static void f_exists __ARGS((typval_T *argvars, typval_T *rettv));
539 static void f_expand __ARGS((typval_T *argvars, typval_T *rettv));
540 static void f_extend __ARGS((typval_T *argvars, typval_T *rettv));
541 static void f_feedkeys __ARGS((typval_T *argvars, typval_T *rettv));
542 static void f_filereadable __ARGS((typval_T *argvars, typval_T *rettv));
543 static void f_filewritable __ARGS((typval_T *argvars, typval_T *rettv));
544 static void f_filter __ARGS((typval_T *argvars, typval_T *rettv));
545 static void f_finddir __ARGS((typval_T *argvars, typval_T *rettv));
546 static void f_findfile __ARGS((typval_T *argvars, typval_T *rettv));
547 #ifdef FEAT_FLOAT
548 static void f_float2nr __ARGS((typval_T *argvars, typval_T *rettv));
549 static void f_floor __ARGS((typval_T *argvars, typval_T *rettv));
550 #endif
551 static void f_fnameescape __ARGS((typval_T *argvars, typval_T *rettv));
552 static void f_fnamemodify __ARGS((typval_T *argvars, typval_T *rettv));
553 static void f_foldclosed __ARGS((typval_T *argvars, typval_T *rettv));
554 static void f_foldclosedend __ARGS((typval_T *argvars, typval_T *rettv));
555 static void f_foldlevel __ARGS((typval_T *argvars, typval_T *rettv));
556 static void f_foldtext __ARGS((typval_T *argvars, typval_T *rettv));
557 static void f_foldtextresult __ARGS((typval_T *argvars, typval_T *rettv));
558 static void f_foreground __ARGS((typval_T *argvars, typval_T *rettv));
559 static void f_function __ARGS((typval_T *argvars, typval_T *rettv));
560 static void f_garbagecollect __ARGS((typval_T *argvars, typval_T *rettv));
561 static void f_get __ARGS((typval_T *argvars, typval_T *rettv));
562 static void f_getbufline __ARGS((typval_T *argvars, typval_T *rettv));
563 static void f_getbufvar __ARGS((typval_T *argvars, typval_T *rettv));
564 static void f_getchar __ARGS((typval_T *argvars, typval_T *rettv));
565 static void f_getcharmod __ARGS((typval_T *argvars, typval_T *rettv));
566 static void f_getcmdline __ARGS((typval_T *argvars, typval_T *rettv));
567 static void f_getcmdpos __ARGS((typval_T *argvars, typval_T *rettv));
568 static void f_getcmdtype __ARGS((typval_T *argvars, typval_T *rettv));
569 static void f_getcwd __ARGS((typval_T *argvars, typval_T *rettv));
570 static void f_getfontname __ARGS((typval_T *argvars, typval_T *rettv));
571 static void f_getfperm __ARGS((typval_T *argvars, typval_T *rettv));
572 static void f_getfsize __ARGS((typval_T *argvars, typval_T *rettv));
573 static void f_getftime __ARGS((typval_T *argvars, typval_T *rettv));
574 static void f_getftype __ARGS((typval_T *argvars, typval_T *rettv));
575 static void f_getline __ARGS((typval_T *argvars, typval_T *rettv));
576 static void f_getmatches __ARGS((typval_T *argvars, typval_T *rettv));
577 static void f_getpid __ARGS((typval_T *argvars, typval_T *rettv));
578 static void f_getpos __ARGS((typval_T *argvars, typval_T *rettv));
579 static void f_getqflist __ARGS((typval_T *argvars, typval_T *rettv));
580 static void f_getreg __ARGS((typval_T *argvars, typval_T *rettv));
581 static void f_getregtype __ARGS((typval_T *argvars, typval_T *rettv));
582 static void f_gettabwinvar __ARGS((typval_T *argvars, typval_T *rettv));
583 static void f_getwinposx __ARGS((typval_T *argvars, typval_T *rettv));
584 static void f_getwinposy __ARGS((typval_T *argvars, typval_T *rettv));
585 static void f_getwinvar __ARGS((typval_T *argvars, typval_T *rettv));
586 static void f_glob __ARGS((typval_T *argvars, typval_T *rettv));
587 static void f_globpath __ARGS((typval_T *argvars, typval_T *rettv));
588 static void f_has __ARGS((typval_T *argvars, typval_T *rettv));
589 static void f_has_key __ARGS((typval_T *argvars, typval_T *rettv));
590 static void f_haslocaldir __ARGS((typval_T *argvars, typval_T *rettv));
591 static void f_hasmapto __ARGS((typval_T *argvars, typval_T *rettv));
592 static void f_histadd __ARGS((typval_T *argvars, typval_T *rettv));
593 static void f_histdel __ARGS((typval_T *argvars, typval_T *rettv));
594 static void f_histget __ARGS((typval_T *argvars, typval_T *rettv));
595 static void f_histnr __ARGS((typval_T *argvars, typval_T *rettv));
596 static void f_hlID __ARGS((typval_T *argvars, typval_T *rettv));
597 static void f_hlexists __ARGS((typval_T *argvars, typval_T *rettv));
598 static void f_hostname __ARGS((typval_T *argvars, typval_T *rettv));
599 static void f_iconv __ARGS((typval_T *argvars, typval_T *rettv));
600 static void f_indent __ARGS((typval_T *argvars, typval_T *rettv));
601 static void f_index __ARGS((typval_T *argvars, typval_T *rettv));
602 static void f_input __ARGS((typval_T *argvars, typval_T *rettv));
603 static void f_inputdialog __ARGS((typval_T *argvars, typval_T *rettv));
604 static void f_inputlist __ARGS((typval_T *argvars, typval_T *rettv));
605 static void f_inputrestore __ARGS((typval_T *argvars, typval_T *rettv));
606 static void f_inputsave __ARGS((typval_T *argvars, typval_T *rettv));
607 static void f_inputsecret __ARGS((typval_T *argvars, typval_T *rettv));
608 static void f_insert __ARGS((typval_T *argvars, typval_T *rettv));
609 static void f_isdirectory __ARGS((typval_T *argvars, typval_T *rettv));
610 static void f_islocked __ARGS((typval_T *argvars, typval_T *rettv));
611 static void f_items __ARGS((typval_T *argvars, typval_T *rettv));
612 static void f_join __ARGS((typval_T *argvars, typval_T *rettv));
613 static void f_keys __ARGS((typval_T *argvars, typval_T *rettv));
614 static void f_last_buffer_nr __ARGS((typval_T *argvars, typval_T *rettv));
615 static void f_len __ARGS((typval_T *argvars, typval_T *rettv));
616 static void f_libcall __ARGS((typval_T *argvars, typval_T *rettv));
617 static void f_libcallnr __ARGS((typval_T *argvars, typval_T *rettv));
618 static void f_line __ARGS((typval_T *argvars, typval_T *rettv));
619 static void f_line2byte __ARGS((typval_T *argvars, typval_T *rettv));
620 static void f_lispindent __ARGS((typval_T *argvars, typval_T *rettv));
621 static void f_localtime __ARGS((typval_T *argvars, typval_T *rettv));
622 #ifdef FEAT_FLOAT
623 static void f_log10 __ARGS((typval_T *argvars, typval_T *rettv));
624 #endif
625 static void f_map __ARGS((typval_T *argvars, typval_T *rettv));
626 static void f_maparg __ARGS((typval_T *argvars, typval_T *rettv));
627 static void f_mapcheck __ARGS((typval_T *argvars, typval_T *rettv));
628 static void f_match __ARGS((typval_T *argvars, typval_T *rettv));
629 static void f_matchadd __ARGS((typval_T *argvars, typval_T *rettv));
630 static void f_matcharg __ARGS((typval_T *argvars, typval_T *rettv));
631 static void f_matchdelete __ARGS((typval_T *argvars, typval_T *rettv));
632 static void f_matchend __ARGS((typval_T *argvars, typval_T *rettv));
633 static void f_matchlist __ARGS((typval_T *argvars, typval_T *rettv));
634 static void f_matchstr __ARGS((typval_T *argvars, typval_T *rettv));
635 static void f_max __ARGS((typval_T *argvars, typval_T *rettv));
636 static void f_min __ARGS((typval_T *argvars, typval_T *rettv));
637 #ifdef vim_mkdir
638 static void f_mkdir __ARGS((typval_T *argvars, typval_T *rettv));
639 #endif
640 static void f_mode __ARGS((typval_T *argvars, typval_T *rettv));
641 #ifdef FEAT_MZSCHEME
642 static void f_mzeval __ARGS((typval_T *argvars, typval_T *rettv));
643 #endif
644 static void f_nextnonblank __ARGS((typval_T *argvars, typval_T *rettv));
645 static void f_nr2char __ARGS((typval_T *argvars, typval_T *rettv));
646 static void f_pathshorten __ARGS((typval_T *argvars, typval_T *rettv));
647 #ifdef FEAT_FLOAT
648 static void f_pow __ARGS((typval_T *argvars, typval_T *rettv));
649 #endif
650 static void f_prevnonblank __ARGS((typval_T *argvars, typval_T *rettv));
651 static void f_printf __ARGS((typval_T *argvars, typval_T *rettv));
652 static void f_pumvisible __ARGS((typval_T *argvars, typval_T *rettv));
653 static void f_range __ARGS((typval_T *argvars, typval_T *rettv));
654 static void f_readfile __ARGS((typval_T *argvars, typval_T *rettv));
655 static void f_reltime __ARGS((typval_T *argvars, typval_T *rettv));
656 static void f_reltimestr __ARGS((typval_T *argvars, typval_T *rettv));
657 static void f_remote_expr __ARGS((typval_T *argvars, typval_T *rettv));
658 static void f_remote_foreground __ARGS((typval_T *argvars, typval_T *rettv));
659 static void f_remote_peek __ARGS((typval_T *argvars, typval_T *rettv));
660 static void f_remote_read __ARGS((typval_T *argvars, typval_T *rettv));
661 static void f_remote_send __ARGS((typval_T *argvars, typval_T *rettv));
662 static void f_remove __ARGS((typval_T *argvars, typval_T *rettv));
663 static void f_rename __ARGS((typval_T *argvars, typval_T *rettv));
664 static void f_repeat __ARGS((typval_T *argvars, typval_T *rettv));
665 static void f_resolve __ARGS((typval_T *argvars, typval_T *rettv));
666 static void f_reverse __ARGS((typval_T *argvars, typval_T *rettv));
667 #ifdef FEAT_FLOAT
668 static void f_round __ARGS((typval_T *argvars, typval_T *rettv));
669 #endif
670 static void f_search __ARGS((typval_T *argvars, typval_T *rettv));
671 static void f_searchdecl __ARGS((typval_T *argvars, typval_T *rettv));
672 static void f_searchpair __ARGS((typval_T *argvars, typval_T *rettv));
673 static void f_searchpairpos __ARGS((typval_T *argvars, typval_T *rettv));
674 static void f_searchpos __ARGS((typval_T *argvars, typval_T *rettv));
675 static void f_server2client __ARGS((typval_T *argvars, typval_T *rettv));
676 static void f_serverlist __ARGS((typval_T *argvars, typval_T *rettv));
677 static void f_setbufvar __ARGS((typval_T *argvars, typval_T *rettv));
678 static void f_setcmdpos __ARGS((typval_T *argvars, typval_T *rettv));
679 static void f_setline __ARGS((typval_T *argvars, typval_T *rettv));
680 static void f_setloclist __ARGS((typval_T *argvars, typval_T *rettv));
681 static void f_setmatches __ARGS((typval_T *argvars, typval_T *rettv));
682 static void f_setpos __ARGS((typval_T *argvars, typval_T *rettv));
683 static void f_setqflist __ARGS((typval_T *argvars, typval_T *rettv));
684 static void f_setreg __ARGS((typval_T *argvars, typval_T *rettv));
685 static void f_settabwinvar __ARGS((typval_T *argvars, typval_T *rettv));
686 static void f_setwinvar __ARGS((typval_T *argvars, typval_T *rettv));
687 static void f_shellescape __ARGS((typval_T *argvars, typval_T *rettv));
688 static void f_simplify __ARGS((typval_T *argvars, typval_T *rettv));
689 #ifdef FEAT_FLOAT
690 static void f_sin __ARGS((typval_T *argvars, typval_T *rettv));
691 #endif
692 static void f_sort __ARGS((typval_T *argvars, typval_T *rettv));
693 static void f_soundfold __ARGS((typval_T *argvars, typval_T *rettv));
694 static void f_spellbadword __ARGS((typval_T *argvars, typval_T *rettv));
695 static void f_spellsuggest __ARGS((typval_T *argvars, typval_T *rettv));
696 static void f_split __ARGS((typval_T *argvars, typval_T *rettv));
697 #ifdef FEAT_FLOAT
698 static void f_sqrt __ARGS((typval_T *argvars, typval_T *rettv));
699 static void f_str2float __ARGS((typval_T *argvars, typval_T *rettv));
700 #endif
701 static void f_str2nr __ARGS((typval_T *argvars, typval_T *rettv));
702 #ifdef HAVE_STRFTIME
703 static void f_strftime __ARGS((typval_T *argvars, typval_T *rettv));
704 #endif
705 static void f_stridx __ARGS((typval_T *argvars, typval_T *rettv));
706 static void f_string __ARGS((typval_T *argvars, typval_T *rettv));
707 static void f_strlen __ARGS((typval_T *argvars, typval_T *rettv));
708 static void f_strpart __ARGS((typval_T *argvars, typval_T *rettv));
709 static void f_strridx __ARGS((typval_T *argvars, typval_T *rettv));
710 static void f_strtrans __ARGS((typval_T *argvars, typval_T *rettv));
711 static void f_submatch __ARGS((typval_T *argvars, typval_T *rettv));
712 static void f_substitute __ARGS((typval_T *argvars, typval_T *rettv));
713 static void f_synID __ARGS((typval_T *argvars, typval_T *rettv));
714 static void f_synIDattr __ARGS((typval_T *argvars, typval_T *rettv));
715 static void f_synIDtrans __ARGS((typval_T *argvars, typval_T *rettv));
716 static void f_synstack __ARGS((typval_T *argvars, typval_T *rettv));
717 static void f_system __ARGS((typval_T *argvars, typval_T *rettv));
718 static void f_tabpagebuflist __ARGS((typval_T *argvars, typval_T *rettv));
719 static void f_tabpagenr __ARGS((typval_T *argvars, typval_T *rettv));
720 static void f_tabpagewinnr __ARGS((typval_T *argvars, typval_T *rettv));
721 static void f_taglist __ARGS((typval_T *argvars, typval_T *rettv));
722 static void f_tagfiles __ARGS((typval_T *argvars, typval_T *rettv));
723 static void f_tempname __ARGS((typval_T *argvars, typval_T *rettv));
724 static void f_test __ARGS((typval_T *argvars, typval_T *rettv));
725 static void f_tolower __ARGS((typval_T *argvars, typval_T *rettv));
726 static void f_toupper __ARGS((typval_T *argvars, typval_T *rettv));
727 static void f_tr __ARGS((typval_T *argvars, typval_T *rettv));
728 #ifdef FEAT_FLOAT
729 static void f_trunc __ARGS((typval_T *argvars, typval_T *rettv));
730 #endif
731 static void f_type __ARGS((typval_T *argvars, typval_T *rettv));
732 static void f_values __ARGS((typval_T *argvars, typval_T *rettv));
733 static void f_virtcol __ARGS((typval_T *argvars, typval_T *rettv));
734 static void f_visualmode __ARGS((typval_T *argvars, typval_T *rettv));
735 static void f_winbufnr __ARGS((typval_T *argvars, typval_T *rettv));
736 static void f_wincol __ARGS((typval_T *argvars, typval_T *rettv));
737 static void f_winheight __ARGS((typval_T *argvars, typval_T *rettv));
738 static void f_winline __ARGS((typval_T *argvars, typval_T *rettv));
739 static void f_winnr __ARGS((typval_T *argvars, typval_T *rettv));
740 static void f_winrestcmd __ARGS((typval_T *argvars, typval_T *rettv));
741 static void f_winrestview __ARGS((typval_T *argvars, typval_T *rettv));
742 static void f_winsaveview __ARGS((typval_T *argvars, typval_T *rettv));
743 static void f_winwidth __ARGS((typval_T *argvars, typval_T *rettv));
744 static void f_writefile __ARGS((typval_T *argvars, typval_T *rettv));
746 static int list2fpos __ARGS((typval_T *arg, pos_T *posp, int *fnump));
747 static pos_T *var2fpos __ARGS((typval_T *varp, int dollar_lnum, int *fnum));
748 static int get_env_len __ARGS((char_u **arg));
749 static int get_id_len __ARGS((char_u **arg));
750 static int get_name_len __ARGS((char_u **arg, char_u **alias, int evaluate, int verbose));
751 static char_u *find_name_end __ARGS((char_u *arg, char_u **expr_start, char_u **expr_end, int flags));
752 #define FNE_INCL_BR 1 /* find_name_end(): include [] in name */
753 #define FNE_CHECK_START 2 /* find_name_end(): check name starts with
754 valid character */
755 static char_u * make_expanded_name __ARGS((char_u *in_start, char_u *expr_start, char_u *expr_end, char_u *in_end));
756 static int eval_isnamec __ARGS((int c));
757 static int eval_isnamec1 __ARGS((int c));
758 static int get_var_tv __ARGS((char_u *name, int len, typval_T *rettv, int verbose));
759 static int handle_subscript __ARGS((char_u **arg, typval_T *rettv, int evaluate, int verbose));
760 static typval_T *alloc_tv __ARGS((void));
761 static typval_T *alloc_string_tv __ARGS((char_u *string));
762 static void init_tv __ARGS((typval_T *varp));
763 static long get_tv_number __ARGS((typval_T *varp));
764 static linenr_T get_tv_lnum __ARGS((typval_T *argvars));
765 static linenr_T get_tv_lnum_buf __ARGS((typval_T *argvars, buf_T *buf));
766 static char_u *get_tv_string __ARGS((typval_T *varp));
767 static char_u *get_tv_string_buf __ARGS((typval_T *varp, char_u *buf));
768 static char_u *get_tv_string_buf_chk __ARGS((typval_T *varp, char_u *buf));
769 static dictitem_T *find_var __ARGS((char_u *name, hashtab_T **htp));
770 static dictitem_T *find_var_in_ht __ARGS((hashtab_T *ht, char_u *varname, int writing));
771 static hashtab_T *find_var_ht __ARGS((char_u *name, char_u **varname));
772 static void vars_clear_ext __ARGS((hashtab_T *ht, int free_val));
773 static void delete_var __ARGS((hashtab_T *ht, hashitem_T *hi));
774 static void list_one_var __ARGS((dictitem_T *v, char_u *prefix, int *first));
775 static void list_one_var_a __ARGS((char_u *prefix, char_u *name, int type, char_u *string, int *first));
776 static void set_var __ARGS((char_u *name, typval_T *varp, int copy));
777 static int var_check_ro __ARGS((int flags, char_u *name));
778 static int var_check_fixed __ARGS((int flags, char_u *name));
779 static int tv_check_lock __ARGS((int lock, char_u *name));
780 static int item_copy __ARGS((typval_T *from, typval_T *to, int deep, int copyID));
781 static char_u *find_option_end __ARGS((char_u **arg, int *opt_flags));
782 static char_u *trans_function_name __ARGS((char_u **pp, int skip, int flags, funcdict_T *fd));
783 static int eval_fname_script __ARGS((char_u *p));
784 static int eval_fname_sid __ARGS((char_u *p));
785 static void list_func_head __ARGS((ufunc_T *fp, int indent));
786 static ufunc_T *find_func __ARGS((char_u *name));
787 static int function_exists __ARGS((char_u *name));
788 static int builtin_function __ARGS((char_u *name));
789 #ifdef FEAT_PROFILE
790 static void func_do_profile __ARGS((ufunc_T *fp));
791 static void prof_sort_list __ARGS((FILE *fd, ufunc_T **sorttab, int st_len, char *title, int prefer_self));
792 static void prof_func_line __ARGS((FILE *fd, int count, proftime_T *total, proftime_T *self, int prefer_self));
793 static int
794 # ifdef __BORLANDC__
795 _RTLENTRYF
796 # endif
797 prof_total_cmp __ARGS((const void *s1, const void *s2));
798 static int
799 # ifdef __BORLANDC__
800 _RTLENTRYF
801 # endif
802 prof_self_cmp __ARGS((const void *s1, const void *s2));
803 #endif
804 static int script_autoload __ARGS((char_u *name, int reload));
805 static char_u *autoload_name __ARGS((char_u *name));
806 static void cat_func_name __ARGS((char_u *buf, ufunc_T *fp));
807 static void func_free __ARGS((ufunc_T *fp));
808 static void func_unref __ARGS((char_u *name));
809 static void func_ref __ARGS((char_u *name));
810 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));
811 static int can_free_funccal __ARGS((funccall_T *fc, int copyID)) ;
812 static void free_funccal __ARGS((funccall_T *fc, int free_val));
813 static void add_nr_var __ARGS((dict_T *dp, dictitem_T *v, char *name, varnumber_T nr));
814 static win_T *find_win_by_nr __ARGS((typval_T *vp, tabpage_T *tp));
815 static void getwinvar __ARGS((typval_T *argvars, typval_T *rettv, int off));
816 static int searchpair_cmn __ARGS((typval_T *argvars, pos_T *match_pos));
817 static int search_cmn __ARGS((typval_T *argvars, pos_T *match_pos, int *flagsp));
818 static void setwinvar __ARGS((typval_T *argvars, typval_T *rettv, int off));
820 /* Character used as separated in autoload function/variable names. */
821 #define AUTOLOAD_CHAR '#'
824 * Initialize the global and v: variables.
826 void
827 eval_init()
829 int i;
830 struct vimvar *p;
832 init_var_dict(&globvardict, &globvars_var);
833 init_var_dict(&vimvardict, &vimvars_var);
834 hash_init(&compat_hashtab);
835 hash_init(&func_hashtab);
837 for (i = 0; i < VV_LEN; ++i)
839 p = &vimvars[i];
840 STRCPY(p->vv_di.di_key, p->vv_name);
841 if (p->vv_flags & VV_RO)
842 p->vv_di.di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
843 else if (p->vv_flags & VV_RO_SBX)
844 p->vv_di.di_flags = DI_FLAGS_RO_SBX | DI_FLAGS_FIX;
845 else
846 p->vv_di.di_flags = DI_FLAGS_FIX;
848 /* add to v: scope dict, unless the value is not always available */
849 if (p->vv_type != VAR_UNKNOWN)
850 hash_add(&vimvarht, p->vv_di.di_key);
851 if (p->vv_flags & VV_COMPAT)
852 /* add to compat scope dict */
853 hash_add(&compat_hashtab, p->vv_di.di_key);
855 set_vim_var_nr(VV_SEARCHFORWARD, 1L);
858 #if defined(EXITFREE) || defined(PROTO)
859 void
860 eval_clear()
862 int i;
863 struct vimvar *p;
865 for (i = 0; i < VV_LEN; ++i)
867 p = &vimvars[i];
868 if (p->vv_di.di_tv.v_type == VAR_STRING)
870 vim_free(p->vv_str);
871 p->vv_str = NULL;
873 else if (p->vv_di.di_tv.v_type == VAR_LIST)
875 list_unref(p->vv_list);
876 p->vv_list = NULL;
879 hash_clear(&vimvarht);
880 hash_init(&vimvarht); /* garbage_collect() will access it */
881 hash_clear(&compat_hashtab);
883 free_scriptnames();
885 /* global variables */
886 vars_clear(&globvarht);
888 /* autoloaded script names */
889 ga_clear_strings(&ga_loaded);
891 /* script-local variables */
892 for (i = 1; i <= ga_scripts.ga_len; ++i)
894 vars_clear(&SCRIPT_VARS(i));
895 vim_free(SCRIPT_SV(i));
897 ga_clear(&ga_scripts);
899 /* unreferenced lists and dicts */
900 (void)garbage_collect();
902 /* functions */
903 free_all_functions();
904 hash_clear(&func_hashtab);
906 #endif
909 * Return the name of the executed function.
911 char_u *
912 func_name(cookie)
913 void *cookie;
915 return ((funccall_T *)cookie)->func->uf_name;
919 * Return the address holding the next breakpoint line for a funccall cookie.
921 linenr_T *
922 func_breakpoint(cookie)
923 void *cookie;
925 return &((funccall_T *)cookie)->breakpoint;
929 * Return the address holding the debug tick for a funccall cookie.
931 int *
932 func_dbg_tick(cookie)
933 void *cookie;
935 return &((funccall_T *)cookie)->dbg_tick;
939 * Return the nesting level for a funccall cookie.
942 func_level(cookie)
943 void *cookie;
945 return ((funccall_T *)cookie)->level;
948 /* pointer to funccal for currently active function */
949 funccall_T *current_funccal = NULL;
951 /* pointer to list of previously used funccal, still around because some
952 * item in it is still being used. */
953 funccall_T *previous_funccal = NULL;
956 * Return TRUE when a function was ended by a ":return" command.
959 current_func_returned()
961 return current_funccal->returned;
966 * Set an internal variable to a string value. Creates the variable if it does
967 * not already exist.
969 void
970 set_internal_string_var(name, value)
971 char_u *name;
972 char_u *value;
974 char_u *val;
975 typval_T *tvp;
977 val = vim_strsave(value);
978 if (val != NULL)
980 tvp = alloc_string_tv(val);
981 if (tvp != NULL)
983 set_var(name, tvp, FALSE);
984 free_tv(tvp);
989 static lval_T *redir_lval = NULL;
990 static garray_T redir_ga; /* only valid when redir_lval is not NULL */
991 static char_u *redir_endp = NULL;
992 static char_u *redir_varname = NULL;
995 * Start recording command output to a variable
996 * Returns OK if successfully completed the setup. FAIL otherwise.
999 var_redir_start(name, append)
1000 char_u *name;
1001 int append; /* append to an existing variable */
1003 int save_emsg;
1004 int err;
1005 typval_T tv;
1007 /* Catch a bad name early. */
1008 if (!eval_isnamec1(*name))
1010 EMSG(_(e_invarg));
1011 return FAIL;
1014 /* Make a copy of the name, it is used in redir_lval until redir ends. */
1015 redir_varname = vim_strsave(name);
1016 if (redir_varname == NULL)
1017 return FAIL;
1019 redir_lval = (lval_T *)alloc_clear((unsigned)sizeof(lval_T));
1020 if (redir_lval == NULL)
1022 var_redir_stop();
1023 return FAIL;
1026 /* The output is stored in growarray "redir_ga" until redirection ends. */
1027 ga_init2(&redir_ga, (int)sizeof(char), 500);
1029 /* Parse the variable name (can be a dict or list entry). */
1030 redir_endp = get_lval(redir_varname, NULL, redir_lval, FALSE, FALSE, FALSE,
1031 FNE_CHECK_START);
1032 if (redir_endp == NULL || redir_lval->ll_name == NULL || *redir_endp != NUL)
1034 if (redir_endp != NULL && *redir_endp != NUL)
1035 /* Trailing characters are present after the variable name */
1036 EMSG(_(e_trailing));
1037 else
1038 EMSG(_(e_invarg));
1039 redir_endp = NULL; /* don't store a value, only cleanup */
1040 var_redir_stop();
1041 return FAIL;
1044 /* check if we can write to the variable: set it to or append an empty
1045 * string */
1046 save_emsg = did_emsg;
1047 did_emsg = FALSE;
1048 tv.v_type = VAR_STRING;
1049 tv.vval.v_string = (char_u *)"";
1050 if (append)
1051 set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)".");
1052 else
1053 set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)"=");
1054 err = did_emsg;
1055 did_emsg |= save_emsg;
1056 if (err)
1058 redir_endp = NULL; /* don't store a value, only cleanup */
1059 var_redir_stop();
1060 return FAIL;
1062 if (redir_lval->ll_newkey != NULL)
1064 /* Dictionary item was created, don't do it again. */
1065 vim_free(redir_lval->ll_newkey);
1066 redir_lval->ll_newkey = NULL;
1069 return OK;
1073 * Append "value[value_len]" to the variable set by var_redir_start().
1074 * The actual appending is postponed until redirection ends, because the value
1075 * appended may in fact be the string we write to, changing it may cause freed
1076 * memory to be used:
1077 * :redir => foo
1078 * :let foo
1079 * :redir END
1081 void
1082 var_redir_str(value, value_len)
1083 char_u *value;
1084 int value_len;
1086 int len;
1088 if (redir_lval == NULL)
1089 return;
1091 if (value_len == -1)
1092 len = (int)STRLEN(value); /* Append the entire string */
1093 else
1094 len = value_len; /* Append only "value_len" characters */
1096 if (ga_grow(&redir_ga, len) == OK)
1098 mch_memmove((char *)redir_ga.ga_data + redir_ga.ga_len, value, len);
1099 redir_ga.ga_len += len;
1101 else
1102 var_redir_stop();
1106 * Stop redirecting command output to a variable.
1107 * Frees the allocated memory.
1109 void
1110 var_redir_stop()
1112 typval_T tv;
1114 if (redir_lval != NULL)
1116 /* If there was no error: assign the text to the variable. */
1117 if (redir_endp != NULL)
1119 ga_append(&redir_ga, NUL); /* Append the trailing NUL. */
1120 tv.v_type = VAR_STRING;
1121 tv.vval.v_string = redir_ga.ga_data;
1122 set_var_lval(redir_lval, redir_endp, &tv, FALSE, (char_u *)".");
1125 /* free the collected output */
1126 vim_free(redir_ga.ga_data);
1127 redir_ga.ga_data = NULL;
1129 clear_lval(redir_lval);
1130 vim_free(redir_lval);
1131 redir_lval = NULL;
1133 vim_free(redir_varname);
1134 redir_varname = NULL;
1137 # if defined(FEAT_MBYTE) || defined(PROTO)
1139 eval_charconvert(enc_from, enc_to, fname_from, fname_to)
1140 char_u *enc_from;
1141 char_u *enc_to;
1142 char_u *fname_from;
1143 char_u *fname_to;
1145 int err = FALSE;
1147 set_vim_var_string(VV_CC_FROM, enc_from, -1);
1148 set_vim_var_string(VV_CC_TO, enc_to, -1);
1149 set_vim_var_string(VV_FNAME_IN, fname_from, -1);
1150 set_vim_var_string(VV_FNAME_OUT, fname_to, -1);
1151 if (eval_to_bool(p_ccv, &err, NULL, FALSE))
1152 err = TRUE;
1153 set_vim_var_string(VV_CC_FROM, NULL, -1);
1154 set_vim_var_string(VV_CC_TO, NULL, -1);
1155 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1156 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1158 if (err)
1159 return FAIL;
1160 return OK;
1162 # endif
1164 # if defined(FEAT_POSTSCRIPT) || defined(PROTO)
1166 eval_printexpr(fname, args)
1167 char_u *fname;
1168 char_u *args;
1170 int err = FALSE;
1172 set_vim_var_string(VV_FNAME_IN, fname, -1);
1173 set_vim_var_string(VV_CMDARG, args, -1);
1174 if (eval_to_bool(p_pexpr, &err, NULL, FALSE))
1175 err = TRUE;
1176 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1177 set_vim_var_string(VV_CMDARG, NULL, -1);
1179 if (err)
1181 mch_remove(fname);
1182 return FAIL;
1184 return OK;
1186 # endif
1188 # if defined(FEAT_DIFF) || defined(PROTO)
1189 void
1190 eval_diff(origfile, newfile, outfile)
1191 char_u *origfile;
1192 char_u *newfile;
1193 char_u *outfile;
1195 int err = FALSE;
1197 set_vim_var_string(VV_FNAME_IN, origfile, -1);
1198 set_vim_var_string(VV_FNAME_NEW, newfile, -1);
1199 set_vim_var_string(VV_FNAME_OUT, outfile, -1);
1200 (void)eval_to_bool(p_dex, &err, NULL, FALSE);
1201 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1202 set_vim_var_string(VV_FNAME_NEW, NULL, -1);
1203 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1206 void
1207 eval_patch(origfile, difffile, outfile)
1208 char_u *origfile;
1209 char_u *difffile;
1210 char_u *outfile;
1212 int err;
1214 set_vim_var_string(VV_FNAME_IN, origfile, -1);
1215 set_vim_var_string(VV_FNAME_DIFF, difffile, -1);
1216 set_vim_var_string(VV_FNAME_OUT, outfile, -1);
1217 (void)eval_to_bool(p_pex, &err, NULL, FALSE);
1218 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1219 set_vim_var_string(VV_FNAME_DIFF, NULL, -1);
1220 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1222 # endif
1225 * Top level evaluation function, returning a boolean.
1226 * Sets "error" to TRUE if there was an error.
1227 * Return TRUE or FALSE.
1230 eval_to_bool(arg, error, nextcmd, skip)
1231 char_u *arg;
1232 int *error;
1233 char_u **nextcmd;
1234 int skip; /* only parse, don't execute */
1236 typval_T tv;
1237 int retval = FALSE;
1239 if (skip)
1240 ++emsg_skip;
1241 if (eval0(arg, &tv, nextcmd, !skip) == FAIL)
1242 *error = TRUE;
1243 else
1245 *error = FALSE;
1246 if (!skip)
1248 retval = (get_tv_number_chk(&tv, error) != 0);
1249 clear_tv(&tv);
1252 if (skip)
1253 --emsg_skip;
1255 return retval;
1259 * Top level evaluation function, returning a string. If "skip" is TRUE,
1260 * only parsing to "nextcmd" is done, without reporting errors. Return
1261 * pointer to allocated memory, or NULL for failure or when "skip" is TRUE.
1263 char_u *
1264 eval_to_string_skip(arg, nextcmd, skip)
1265 char_u *arg;
1266 char_u **nextcmd;
1267 int skip; /* only parse, don't execute */
1269 typval_T tv;
1270 char_u *retval;
1272 if (skip)
1273 ++emsg_skip;
1274 if (eval0(arg, &tv, nextcmd, !skip) == FAIL || skip)
1275 retval = NULL;
1276 else
1278 retval = vim_strsave(get_tv_string(&tv));
1279 clear_tv(&tv);
1281 if (skip)
1282 --emsg_skip;
1284 return retval;
1288 * Skip over an expression at "*pp".
1289 * Return FAIL for an error, OK otherwise.
1292 skip_expr(pp)
1293 char_u **pp;
1295 typval_T rettv;
1297 *pp = skipwhite(*pp);
1298 return eval1(pp, &rettv, FALSE);
1302 * Top level evaluation function, returning a string.
1303 * When "convert" is TRUE convert a List into a sequence of lines and convert
1304 * a Float to a String.
1305 * Return pointer to allocated memory, or NULL for failure.
1307 char_u *
1308 eval_to_string(arg, nextcmd, convert)
1309 char_u *arg;
1310 char_u **nextcmd;
1311 int convert;
1313 typval_T tv;
1314 char_u *retval;
1315 garray_T ga;
1316 #ifdef FEAT_FLOAT
1317 char_u numbuf[NUMBUFLEN];
1318 #endif
1320 if (eval0(arg, &tv, nextcmd, TRUE) == FAIL)
1321 retval = NULL;
1322 else
1324 if (convert && tv.v_type == VAR_LIST)
1326 ga_init2(&ga, (int)sizeof(char), 80);
1327 if (tv.vval.v_list != NULL)
1328 list_join(&ga, tv.vval.v_list, (char_u *)"\n", TRUE, 0);
1329 ga_append(&ga, NUL);
1330 retval = (char_u *)ga.ga_data;
1332 #ifdef FEAT_FLOAT
1333 else if (convert && tv.v_type == VAR_FLOAT)
1335 vim_snprintf((char *)numbuf, NUMBUFLEN, "%g", tv.vval.v_float);
1336 retval = vim_strsave(numbuf);
1338 #endif
1339 else
1340 retval = vim_strsave(get_tv_string(&tv));
1341 clear_tv(&tv);
1344 return retval;
1348 * Call eval_to_string() without using current local variables and using
1349 * textlock. When "use_sandbox" is TRUE use the sandbox.
1351 char_u *
1352 eval_to_string_safe(arg, nextcmd, use_sandbox)
1353 char_u *arg;
1354 char_u **nextcmd;
1355 int use_sandbox;
1357 char_u *retval;
1358 void *save_funccalp;
1360 save_funccalp = save_funccal();
1361 if (use_sandbox)
1362 ++sandbox;
1363 ++textlock;
1364 retval = eval_to_string(arg, nextcmd, FALSE);
1365 if (use_sandbox)
1366 --sandbox;
1367 --textlock;
1368 restore_funccal(save_funccalp);
1369 return retval;
1373 * Top level evaluation function, returning a number.
1374 * Evaluates "expr" silently.
1375 * Returns -1 for an error.
1378 eval_to_number(expr)
1379 char_u *expr;
1381 typval_T rettv;
1382 int retval;
1383 char_u *p = skipwhite(expr);
1385 ++emsg_off;
1387 if (eval1(&p, &rettv, TRUE) == FAIL)
1388 retval = -1;
1389 else
1391 retval = get_tv_number_chk(&rettv, NULL);
1392 clear_tv(&rettv);
1394 --emsg_off;
1396 return retval;
1400 * Prepare v: variable "idx" to be used.
1401 * Save the current typeval in "save_tv".
1402 * When not used yet add the variable to the v: hashtable.
1404 static void
1405 prepare_vimvar(idx, save_tv)
1406 int idx;
1407 typval_T *save_tv;
1409 *save_tv = vimvars[idx].vv_tv;
1410 if (vimvars[idx].vv_type == VAR_UNKNOWN)
1411 hash_add(&vimvarht, vimvars[idx].vv_di.di_key);
1415 * Restore v: variable "idx" to typeval "save_tv".
1416 * When no longer defined, remove the variable from the v: hashtable.
1418 static void
1419 restore_vimvar(idx, save_tv)
1420 int idx;
1421 typval_T *save_tv;
1423 hashitem_T *hi;
1425 vimvars[idx].vv_tv = *save_tv;
1426 if (vimvars[idx].vv_type == VAR_UNKNOWN)
1428 hi = hash_find(&vimvarht, vimvars[idx].vv_di.di_key);
1429 if (HASHITEM_EMPTY(hi))
1430 EMSG2(_(e_intern2), "restore_vimvar()");
1431 else
1432 hash_remove(&vimvarht, hi);
1436 #if defined(FEAT_SPELL) || defined(PROTO)
1438 * Evaluate an expression to a list with suggestions.
1439 * For the "expr:" part of 'spellsuggest'.
1440 * Returns NULL when there is an error.
1442 list_T *
1443 eval_spell_expr(badword, expr)
1444 char_u *badword;
1445 char_u *expr;
1447 typval_T save_val;
1448 typval_T rettv;
1449 list_T *list = NULL;
1450 char_u *p = skipwhite(expr);
1452 /* Set "v:val" to the bad word. */
1453 prepare_vimvar(VV_VAL, &save_val);
1454 vimvars[VV_VAL].vv_type = VAR_STRING;
1455 vimvars[VV_VAL].vv_str = badword;
1456 if (p_verbose == 0)
1457 ++emsg_off;
1459 if (eval1(&p, &rettv, TRUE) == OK)
1461 if (rettv.v_type != VAR_LIST)
1462 clear_tv(&rettv);
1463 else
1464 list = rettv.vval.v_list;
1467 if (p_verbose == 0)
1468 --emsg_off;
1469 restore_vimvar(VV_VAL, &save_val);
1471 return list;
1475 * "list" is supposed to contain two items: a word and a number. Return the
1476 * word in "pp" and the number as the return value.
1477 * Return -1 if anything isn't right.
1478 * Used to get the good word and score from the eval_spell_expr() result.
1481 get_spellword(list, pp)
1482 list_T *list;
1483 char_u **pp;
1485 listitem_T *li;
1487 li = list->lv_first;
1488 if (li == NULL)
1489 return -1;
1490 *pp = get_tv_string(&li->li_tv);
1492 li = li->li_next;
1493 if (li == NULL)
1494 return -1;
1495 return get_tv_number(&li->li_tv);
1497 #endif
1500 * Top level evaluation function.
1501 * Returns an allocated typval_T with the result.
1502 * Returns NULL when there is an error.
1504 typval_T *
1505 eval_expr(arg, nextcmd)
1506 char_u *arg;
1507 char_u **nextcmd;
1509 typval_T *tv;
1511 tv = (typval_T *)alloc(sizeof(typval_T));
1512 if (tv != NULL && eval0(arg, tv, nextcmd, TRUE) == FAIL)
1514 vim_free(tv);
1515 tv = NULL;
1518 return tv;
1522 #if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) \
1523 || defined(FEAT_COMPL_FUNC) || defined(PROTO)
1525 * Call some vimL function and return the result in "*rettv".
1526 * Uses argv[argc] for the function arguments. Only Number and String
1527 * arguments are currently supported.
1528 * Returns OK or FAIL.
1530 static int
1531 call_vim_function(func, argc, argv, safe, rettv)
1532 char_u *func;
1533 int argc;
1534 char_u **argv;
1535 int safe; /* use the sandbox */
1536 typval_T *rettv;
1538 typval_T *argvars;
1539 long n;
1540 int len;
1541 int i;
1542 int doesrange;
1543 void *save_funccalp = NULL;
1544 int ret;
1546 argvars = (typval_T *)alloc((unsigned)((argc + 1) * sizeof(typval_T)));
1547 if (argvars == NULL)
1548 return FAIL;
1550 for (i = 0; i < argc; i++)
1552 /* Pass a NULL or empty argument as an empty string */
1553 if (argv[i] == NULL || *argv[i] == NUL)
1555 argvars[i].v_type = VAR_STRING;
1556 argvars[i].vval.v_string = (char_u *)"";
1557 continue;
1560 /* Recognize a number argument, the others must be strings. */
1561 vim_str2nr(argv[i], NULL, &len, TRUE, TRUE, &n, NULL);
1562 if (len != 0 && len == (int)STRLEN(argv[i]))
1564 argvars[i].v_type = VAR_NUMBER;
1565 argvars[i].vval.v_number = n;
1567 else
1569 argvars[i].v_type = VAR_STRING;
1570 argvars[i].vval.v_string = argv[i];
1574 if (safe)
1576 save_funccalp = save_funccal();
1577 ++sandbox;
1580 rettv->v_type = VAR_UNKNOWN; /* clear_tv() uses this */
1581 ret = call_func(func, (int)STRLEN(func), rettv, argc, argvars,
1582 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
1583 &doesrange, TRUE, NULL);
1584 if (safe)
1586 --sandbox;
1587 restore_funccal(save_funccalp);
1589 vim_free(argvars);
1591 if (ret == FAIL)
1592 clear_tv(rettv);
1594 return ret;
1597 # if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) || defined(PROTO)
1599 * Call vimL function "func" and return the result as a string.
1600 * Returns NULL when calling the function fails.
1601 * Uses argv[argc] for the function arguments.
1603 void *
1604 call_func_retstr(func, argc, argv, safe)
1605 char_u *func;
1606 int argc;
1607 char_u **argv;
1608 int safe; /* use the sandbox */
1610 typval_T rettv;
1611 char_u *retval;
1613 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1614 return NULL;
1616 retval = vim_strsave(get_tv_string(&rettv));
1617 clear_tv(&rettv);
1618 return retval;
1620 # endif
1622 # if defined(FEAT_COMPL_FUNC) || defined(PROTO)
1624 * Call vimL function "func" and return the result as a number.
1625 * Returns -1 when calling the function fails.
1626 * Uses argv[argc] for the function arguments.
1628 long
1629 call_func_retnr(func, argc, argv, safe)
1630 char_u *func;
1631 int argc;
1632 char_u **argv;
1633 int safe; /* use the sandbox */
1635 typval_T rettv;
1636 long retval;
1638 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1639 return -1;
1641 retval = get_tv_number_chk(&rettv, NULL);
1642 clear_tv(&rettv);
1643 return retval;
1645 # endif
1648 * Call vimL function "func" and return the result as a List.
1649 * Uses argv[argc] for the function arguments.
1650 * Returns NULL when there is something wrong.
1652 void *
1653 call_func_retlist(func, argc, argv, safe)
1654 char_u *func;
1655 int argc;
1656 char_u **argv;
1657 int safe; /* use the sandbox */
1659 typval_T rettv;
1661 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1662 return NULL;
1664 if (rettv.v_type != VAR_LIST)
1666 clear_tv(&rettv);
1667 return NULL;
1670 return rettv.vval.v_list;
1672 #endif
1676 * Save the current function call pointer, and set it to NULL.
1677 * Used when executing autocommands and for ":source".
1679 void *
1680 save_funccal()
1682 funccall_T *fc = current_funccal;
1684 current_funccal = NULL;
1685 return (void *)fc;
1688 void
1689 restore_funccal(vfc)
1690 void *vfc;
1692 funccall_T *fc = (funccall_T *)vfc;
1694 current_funccal = fc;
1697 #if defined(FEAT_PROFILE) || defined(PROTO)
1699 * Prepare profiling for entering a child or something else that is not
1700 * counted for the script/function itself.
1701 * Should always be called in pair with prof_child_exit().
1703 void
1704 prof_child_enter(tm)
1705 proftime_T *tm; /* place to store waittime */
1707 funccall_T *fc = current_funccal;
1709 if (fc != NULL && fc->func->uf_profiling)
1710 profile_start(&fc->prof_child);
1711 script_prof_save(tm);
1715 * Take care of time spent in a child.
1716 * Should always be called after prof_child_enter().
1718 void
1719 prof_child_exit(tm)
1720 proftime_T *tm; /* where waittime was stored */
1722 funccall_T *fc = current_funccal;
1724 if (fc != NULL && fc->func->uf_profiling)
1726 profile_end(&fc->prof_child);
1727 profile_sub_wait(tm, &fc->prof_child); /* don't count waiting time */
1728 profile_add(&fc->func->uf_tm_children, &fc->prof_child);
1729 profile_add(&fc->func->uf_tml_children, &fc->prof_child);
1731 script_prof_restore(tm);
1733 #endif
1736 #ifdef FEAT_FOLDING
1738 * Evaluate 'foldexpr'. Returns the foldlevel, and any character preceding
1739 * it in "*cp". Doesn't give error messages.
1742 eval_foldexpr(arg, cp)
1743 char_u *arg;
1744 int *cp;
1746 typval_T tv;
1747 int retval;
1748 char_u *s;
1749 int use_sandbox = was_set_insecurely((char_u *)"foldexpr",
1750 OPT_LOCAL);
1752 ++emsg_off;
1753 if (use_sandbox)
1754 ++sandbox;
1755 ++textlock;
1756 *cp = NUL;
1757 if (eval0(arg, &tv, NULL, TRUE) == FAIL)
1758 retval = 0;
1759 else
1761 /* If the result is a number, just return the number. */
1762 if (tv.v_type == VAR_NUMBER)
1763 retval = tv.vval.v_number;
1764 else if (tv.v_type != VAR_STRING || tv.vval.v_string == NULL)
1765 retval = 0;
1766 else
1768 /* If the result is a string, check if there is a non-digit before
1769 * the number. */
1770 s = tv.vval.v_string;
1771 if (!VIM_ISDIGIT(*s) && *s != '-')
1772 *cp = *s++;
1773 retval = atol((char *)s);
1775 clear_tv(&tv);
1777 --emsg_off;
1778 if (use_sandbox)
1779 --sandbox;
1780 --textlock;
1782 return retval;
1784 #endif
1787 * ":let" list all variable values
1788 * ":let var1 var2" list variable values
1789 * ":let var = expr" assignment command.
1790 * ":let var += expr" assignment command.
1791 * ":let var -= expr" assignment command.
1792 * ":let var .= expr" assignment command.
1793 * ":let [var1, var2] = expr" unpack list.
1795 void
1796 ex_let(eap)
1797 exarg_T *eap;
1799 char_u *arg = eap->arg;
1800 char_u *expr = NULL;
1801 typval_T rettv;
1802 int i;
1803 int var_count = 0;
1804 int semicolon = 0;
1805 char_u op[2];
1806 char_u *argend;
1807 int first = TRUE;
1809 argend = skip_var_list(arg, &var_count, &semicolon);
1810 if (argend == NULL)
1811 return;
1812 if (argend > arg && argend[-1] == '.') /* for var.='str' */
1813 --argend;
1814 expr = vim_strchr(argend, '=');
1815 if (expr == NULL)
1818 * ":let" without "=": list variables
1820 if (*arg == '[')
1821 EMSG(_(e_invarg));
1822 else if (!ends_excmd(*arg))
1823 /* ":let var1 var2" */
1824 arg = list_arg_vars(eap, arg, &first);
1825 else if (!eap->skip)
1827 /* ":let" */
1828 list_glob_vars(&first);
1829 list_buf_vars(&first);
1830 list_win_vars(&first);
1831 #ifdef FEAT_WINDOWS
1832 list_tab_vars(&first);
1833 #endif
1834 list_script_vars(&first);
1835 list_func_vars(&first);
1836 list_vim_vars(&first);
1838 eap->nextcmd = check_nextcmd(arg);
1840 else
1842 op[0] = '=';
1843 op[1] = NUL;
1844 if (expr > argend)
1846 if (vim_strchr((char_u *)"+-.", expr[-1]) != NULL)
1847 op[0] = expr[-1]; /* +=, -= or .= */
1849 expr = skipwhite(expr + 1);
1851 if (eap->skip)
1852 ++emsg_skip;
1853 i = eval0(expr, &rettv, &eap->nextcmd, !eap->skip);
1854 if (eap->skip)
1856 if (i != FAIL)
1857 clear_tv(&rettv);
1858 --emsg_skip;
1860 else if (i != FAIL)
1862 (void)ex_let_vars(eap->arg, &rettv, FALSE, semicolon, var_count,
1863 op);
1864 clear_tv(&rettv);
1870 * Assign the typevalue "tv" to the variable or variables at "arg_start".
1871 * Handles both "var" with any type and "[var, var; var]" with a list type.
1872 * When "nextchars" is not NULL it points to a string with characters that
1873 * must appear after the variable(s). Use "+", "-" or "." for add, subtract
1874 * or concatenate.
1875 * Returns OK or FAIL;
1877 static int
1878 ex_let_vars(arg_start, tv, copy, semicolon, var_count, nextchars)
1879 char_u *arg_start;
1880 typval_T *tv;
1881 int copy; /* copy values from "tv", don't move */
1882 int semicolon; /* from skip_var_list() */
1883 int var_count; /* from skip_var_list() */
1884 char_u *nextchars;
1886 char_u *arg = arg_start;
1887 list_T *l;
1888 int i;
1889 listitem_T *item;
1890 typval_T ltv;
1892 if (*arg != '[')
1895 * ":let var = expr" or ":for var in list"
1897 if (ex_let_one(arg, tv, copy, nextchars, nextchars) == NULL)
1898 return FAIL;
1899 return OK;
1903 * ":let [v1, v2] = list" or ":for [v1, v2] in listlist"
1905 if (tv->v_type != VAR_LIST || (l = tv->vval.v_list) == NULL)
1907 EMSG(_(e_listreq));
1908 return FAIL;
1911 i = list_len(l);
1912 if (semicolon == 0 && var_count < i)
1914 EMSG(_("E687: Less targets than List items"));
1915 return FAIL;
1917 if (var_count - semicolon > i)
1919 EMSG(_("E688: More targets than List items"));
1920 return FAIL;
1923 item = l->lv_first;
1924 while (*arg != ']')
1926 arg = skipwhite(arg + 1);
1927 arg = ex_let_one(arg, &item->li_tv, TRUE, (char_u *)",;]", nextchars);
1928 item = item->li_next;
1929 if (arg == NULL)
1930 return FAIL;
1932 arg = skipwhite(arg);
1933 if (*arg == ';')
1935 /* Put the rest of the list (may be empty) in the var after ';'.
1936 * Create a new list for this. */
1937 l = list_alloc();
1938 if (l == NULL)
1939 return FAIL;
1940 while (item != NULL)
1942 list_append_tv(l, &item->li_tv);
1943 item = item->li_next;
1946 ltv.v_type = VAR_LIST;
1947 ltv.v_lock = 0;
1948 ltv.vval.v_list = l;
1949 l->lv_refcount = 1;
1951 arg = ex_let_one(skipwhite(arg + 1), &ltv, FALSE,
1952 (char_u *)"]", nextchars);
1953 clear_tv(&ltv);
1954 if (arg == NULL)
1955 return FAIL;
1956 break;
1958 else if (*arg != ',' && *arg != ']')
1960 EMSG2(_(e_intern2), "ex_let_vars()");
1961 return FAIL;
1965 return OK;
1969 * Skip over assignable variable "var" or list of variables "[var, var]".
1970 * Used for ":let varvar = expr" and ":for varvar in expr".
1971 * For "[var, var]" increment "*var_count" for each variable.
1972 * for "[var, var; var]" set "semicolon".
1973 * Return NULL for an error.
1975 static char_u *
1976 skip_var_list(arg, var_count, semicolon)
1977 char_u *arg;
1978 int *var_count;
1979 int *semicolon;
1981 char_u *p, *s;
1983 if (*arg == '[')
1985 /* "[var, var]": find the matching ']'. */
1986 p = arg;
1987 for (;;)
1989 p = skipwhite(p + 1); /* skip whites after '[', ';' or ',' */
1990 s = skip_var_one(p);
1991 if (s == p)
1993 EMSG2(_(e_invarg2), p);
1994 return NULL;
1996 ++*var_count;
1998 p = skipwhite(s);
1999 if (*p == ']')
2000 break;
2001 else if (*p == ';')
2003 if (*semicolon == 1)
2005 EMSG(_("Double ; in list of variables"));
2006 return NULL;
2008 *semicolon = 1;
2010 else if (*p != ',')
2012 EMSG2(_(e_invarg2), p);
2013 return NULL;
2016 return p + 1;
2018 else
2019 return skip_var_one(arg);
2023 * Skip one (assignable) variable name, including @r, $VAR, &option, d.key,
2024 * l[idx].
2026 static char_u *
2027 skip_var_one(arg)
2028 char_u *arg;
2030 if (*arg == '@' && arg[1] != NUL)
2031 return arg + 2;
2032 return find_name_end(*arg == '$' || *arg == '&' ? arg + 1 : arg,
2033 NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
2037 * List variables for hashtab "ht" with prefix "prefix".
2038 * If "empty" is TRUE also list NULL strings as empty strings.
2040 static void
2041 list_hashtable_vars(ht, prefix, empty, first)
2042 hashtab_T *ht;
2043 char_u *prefix;
2044 int empty;
2045 int *first;
2047 hashitem_T *hi;
2048 dictitem_T *di;
2049 int todo;
2051 todo = (int)ht->ht_used;
2052 for (hi = ht->ht_array; todo > 0 && !got_int; ++hi)
2054 if (!HASHITEM_EMPTY(hi))
2056 --todo;
2057 di = HI2DI(hi);
2058 if (empty || di->di_tv.v_type != VAR_STRING
2059 || di->di_tv.vval.v_string != NULL)
2060 list_one_var(di, prefix, first);
2066 * List global variables.
2068 static void
2069 list_glob_vars(first)
2070 int *first;
2072 list_hashtable_vars(&globvarht, (char_u *)"", TRUE, first);
2076 * List buffer variables.
2078 static void
2079 list_buf_vars(first)
2080 int *first;
2082 char_u numbuf[NUMBUFLEN];
2084 list_hashtable_vars(&curbuf->b_vars.dv_hashtab, (char_u *)"b:",
2085 TRUE, first);
2087 sprintf((char *)numbuf, "%ld", (long)curbuf->b_changedtick);
2088 list_one_var_a((char_u *)"b:", (char_u *)"changedtick", VAR_NUMBER,
2089 numbuf, first);
2093 * List window variables.
2095 static void
2096 list_win_vars(first)
2097 int *first;
2099 list_hashtable_vars(&curwin->w_vars.dv_hashtab,
2100 (char_u *)"w:", TRUE, first);
2103 #ifdef FEAT_WINDOWS
2105 * List tab page variables.
2107 static void
2108 list_tab_vars(first)
2109 int *first;
2111 list_hashtable_vars(&curtab->tp_vars.dv_hashtab,
2112 (char_u *)"t:", TRUE, first);
2114 #endif
2117 * List Vim variables.
2119 static void
2120 list_vim_vars(first)
2121 int *first;
2123 list_hashtable_vars(&vimvarht, (char_u *)"v:", FALSE, first);
2127 * List script-local variables, if there is a script.
2129 static void
2130 list_script_vars(first)
2131 int *first;
2133 if (current_SID > 0 && current_SID <= ga_scripts.ga_len)
2134 list_hashtable_vars(&SCRIPT_VARS(current_SID),
2135 (char_u *)"s:", FALSE, first);
2139 * List function variables, if there is a function.
2141 static void
2142 list_func_vars(first)
2143 int *first;
2145 if (current_funccal != NULL)
2146 list_hashtable_vars(&current_funccal->l_vars.dv_hashtab,
2147 (char_u *)"l:", FALSE, first);
2151 * List variables in "arg".
2153 static char_u *
2154 list_arg_vars(eap, arg, first)
2155 exarg_T *eap;
2156 char_u *arg;
2157 int *first;
2159 int error = FALSE;
2160 int len;
2161 char_u *name;
2162 char_u *name_start;
2163 char_u *arg_subsc;
2164 char_u *tofree;
2165 typval_T tv;
2167 while (!ends_excmd(*arg) && !got_int)
2169 if (error || eap->skip)
2171 arg = find_name_end(arg, NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
2172 if (!vim_iswhite(*arg) && !ends_excmd(*arg))
2174 emsg_severe = TRUE;
2175 EMSG(_(e_trailing));
2176 break;
2179 else
2181 /* get_name_len() takes care of expanding curly braces */
2182 name_start = name = arg;
2183 len = get_name_len(&arg, &tofree, TRUE, TRUE);
2184 if (len <= 0)
2186 /* This is mainly to keep test 49 working: when expanding
2187 * curly braces fails overrule the exception error message. */
2188 if (len < 0 && !aborting())
2190 emsg_severe = TRUE;
2191 EMSG2(_(e_invarg2), arg);
2192 break;
2194 error = TRUE;
2196 else
2198 if (tofree != NULL)
2199 name = tofree;
2200 if (get_var_tv(name, len, &tv, TRUE) == FAIL)
2201 error = TRUE;
2202 else
2204 /* handle d.key, l[idx], f(expr) */
2205 arg_subsc = arg;
2206 if (handle_subscript(&arg, &tv, TRUE, TRUE) == FAIL)
2207 error = TRUE;
2208 else
2210 if (arg == arg_subsc && len == 2 && name[1] == ':')
2212 switch (*name)
2214 case 'g': list_glob_vars(first); break;
2215 case 'b': list_buf_vars(first); break;
2216 case 'w': list_win_vars(first); break;
2217 #ifdef FEAT_WINDOWS
2218 case 't': list_tab_vars(first); break;
2219 #endif
2220 case 'v': list_vim_vars(first); break;
2221 case 's': list_script_vars(first); break;
2222 case 'l': list_func_vars(first); break;
2223 default:
2224 EMSG2(_("E738: Can't list variables for %s"), name);
2227 else
2229 char_u numbuf[NUMBUFLEN];
2230 char_u *tf;
2231 int c;
2232 char_u *s;
2234 s = echo_string(&tv, &tf, numbuf, 0);
2235 c = *arg;
2236 *arg = NUL;
2237 list_one_var_a((char_u *)"",
2238 arg == arg_subsc ? name : name_start,
2239 tv.v_type,
2240 s == NULL ? (char_u *)"" : s,
2241 first);
2242 *arg = c;
2243 vim_free(tf);
2245 clear_tv(&tv);
2250 vim_free(tofree);
2253 arg = skipwhite(arg);
2256 return arg;
2260 * Set one item of ":let var = expr" or ":let [v1, v2] = list" to its value.
2261 * Returns a pointer to the char just after the var name.
2262 * Returns NULL if there is an error.
2264 static char_u *
2265 ex_let_one(arg, tv, copy, endchars, op)
2266 char_u *arg; /* points to variable name */
2267 typval_T *tv; /* value to assign to variable */
2268 int copy; /* copy value from "tv" */
2269 char_u *endchars; /* valid chars after variable name or NULL */
2270 char_u *op; /* "+", "-", "." or NULL*/
2272 int c1;
2273 char_u *name;
2274 char_u *p;
2275 char_u *arg_end = NULL;
2276 int len;
2277 int opt_flags;
2278 char_u *tofree = NULL;
2281 * ":let $VAR = expr": Set environment variable.
2283 if (*arg == '$')
2285 /* Find the end of the name. */
2286 ++arg;
2287 name = arg;
2288 len = get_env_len(&arg);
2289 if (len == 0)
2290 EMSG2(_(e_invarg2), name - 1);
2291 else
2293 if (op != NULL && (*op == '+' || *op == '-'))
2294 EMSG2(_(e_letwrong), op);
2295 else if (endchars != NULL
2296 && vim_strchr(endchars, *skipwhite(arg)) == NULL)
2297 EMSG(_(e_letunexp));
2298 else
2300 c1 = name[len];
2301 name[len] = NUL;
2302 p = get_tv_string_chk(tv);
2303 if (p != NULL && op != NULL && *op == '.')
2305 int mustfree = FALSE;
2306 char_u *s = vim_getenv(name, &mustfree);
2308 if (s != NULL)
2310 p = tofree = concat_str(s, p);
2311 if (mustfree)
2312 vim_free(s);
2315 if (p != NULL)
2317 vim_setenv(name, p);
2318 if (STRICMP(name, "HOME") == 0)
2319 init_homedir();
2320 else if (didset_vim && STRICMP(name, "VIM") == 0)
2321 didset_vim = FALSE;
2322 else if (didset_vimruntime
2323 && STRICMP(name, "VIMRUNTIME") == 0)
2324 didset_vimruntime = FALSE;
2325 arg_end = arg;
2327 name[len] = c1;
2328 vim_free(tofree);
2334 * ":let &option = expr": Set option value.
2335 * ":let &l:option = expr": Set local option value.
2336 * ":let &g:option = expr": Set global option value.
2338 else if (*arg == '&')
2340 /* Find the end of the name. */
2341 p = find_option_end(&arg, &opt_flags);
2342 if (p == NULL || (endchars != NULL
2343 && vim_strchr(endchars, *skipwhite(p)) == NULL))
2344 EMSG(_(e_letunexp));
2345 else
2347 long n;
2348 int opt_type;
2349 long numval;
2350 char_u *stringval = NULL;
2351 char_u *s;
2353 c1 = *p;
2354 *p = NUL;
2356 n = get_tv_number(tv);
2357 s = get_tv_string_chk(tv); /* != NULL if number or string */
2358 if (s != NULL && op != NULL && *op != '=')
2360 opt_type = get_option_value(arg, &numval,
2361 &stringval, opt_flags);
2362 if ((opt_type == 1 && *op == '.')
2363 || (opt_type == 0 && *op != '.'))
2364 EMSG2(_(e_letwrong), op);
2365 else
2367 if (opt_type == 1) /* number */
2369 if (*op == '+')
2370 n = numval + n;
2371 else
2372 n = numval - n;
2374 else if (opt_type == 0 && stringval != NULL) /* string */
2376 s = concat_str(stringval, s);
2377 vim_free(stringval);
2378 stringval = s;
2382 if (s != NULL)
2384 set_option_value(arg, n, s, opt_flags);
2385 arg_end = p;
2387 *p = c1;
2388 vim_free(stringval);
2393 * ":let @r = expr": Set register contents.
2395 else if (*arg == '@')
2397 ++arg;
2398 if (op != NULL && (*op == '+' || *op == '-'))
2399 EMSG2(_(e_letwrong), op);
2400 else if (endchars != NULL
2401 && vim_strchr(endchars, *skipwhite(arg + 1)) == NULL)
2402 EMSG(_(e_letunexp));
2403 else
2405 char_u *ptofree = NULL;
2406 char_u *s;
2408 p = get_tv_string_chk(tv);
2409 if (p != NULL && op != NULL && *op == '.')
2411 s = get_reg_contents(*arg == '@' ? '"' : *arg, TRUE, TRUE);
2412 if (s != NULL)
2414 p = ptofree = concat_str(s, p);
2415 vim_free(s);
2418 if (p != NULL)
2420 write_reg_contents(*arg == '@' ? '"' : *arg, p, -1, FALSE);
2421 arg_end = arg + 1;
2423 vim_free(ptofree);
2428 * ":let var = expr": Set internal variable.
2429 * ":let {expr} = expr": Idem, name made with curly braces
2431 else if (eval_isnamec1(*arg) || *arg == '{')
2433 lval_T lv;
2435 p = get_lval(arg, tv, &lv, FALSE, FALSE, FALSE, FNE_CHECK_START);
2436 if (p != NULL && lv.ll_name != NULL)
2438 if (endchars != NULL && vim_strchr(endchars, *skipwhite(p)) == NULL)
2439 EMSG(_(e_letunexp));
2440 else
2442 set_var_lval(&lv, p, tv, copy, op);
2443 arg_end = p;
2446 clear_lval(&lv);
2449 else
2450 EMSG2(_(e_invarg2), arg);
2452 return arg_end;
2456 * If "arg" is equal to "b:changedtick" give an error and return TRUE.
2458 static int
2459 check_changedtick(arg)
2460 char_u *arg;
2462 if (STRNCMP(arg, "b:changedtick", 13) == 0 && !eval_isnamec(arg[13]))
2464 EMSG2(_(e_readonlyvar), arg);
2465 return TRUE;
2467 return FALSE;
2471 * Get an lval: variable, Dict item or List item that can be assigned a value
2472 * to: "name", "na{me}", "name[expr]", "name[expr:expr]", "name[expr][expr]",
2473 * "name.key", "name.key[expr]" etc.
2474 * Indexing only works if "name" is an existing List or Dictionary.
2475 * "name" points to the start of the name.
2476 * If "rettv" is not NULL it points to the value to be assigned.
2477 * "unlet" is TRUE for ":unlet": slightly different behavior when something is
2478 * wrong; must end in space or cmd separator.
2480 * Returns a pointer to just after the name, including indexes.
2481 * When an evaluation error occurs "lp->ll_name" is NULL;
2482 * Returns NULL for a parsing error. Still need to free items in "lp"!
2484 static char_u *
2485 get_lval(name, rettv, lp, unlet, skip, quiet, fne_flags)
2486 char_u *name;
2487 typval_T *rettv;
2488 lval_T *lp;
2489 int unlet;
2490 int skip;
2491 int quiet; /* don't give error messages */
2492 int fne_flags; /* flags for find_name_end() */
2494 char_u *p;
2495 char_u *expr_start, *expr_end;
2496 int cc;
2497 dictitem_T *v;
2498 typval_T var1;
2499 typval_T var2;
2500 int empty1 = FALSE;
2501 listitem_T *ni;
2502 char_u *key = NULL;
2503 int len;
2504 hashtab_T *ht;
2506 /* Clear everything in "lp". */
2507 vim_memset(lp, 0, sizeof(lval_T));
2509 if (skip)
2511 /* When skipping just find the end of the name. */
2512 lp->ll_name = name;
2513 return find_name_end(name, NULL, NULL, FNE_INCL_BR | fne_flags);
2516 /* Find the end of the name. */
2517 p = find_name_end(name, &expr_start, &expr_end, fne_flags);
2518 if (expr_start != NULL)
2520 /* Don't expand the name when we already know there is an error. */
2521 if (unlet && !vim_iswhite(*p) && !ends_excmd(*p)
2522 && *p != '[' && *p != '.')
2524 EMSG(_(e_trailing));
2525 return NULL;
2528 lp->ll_exp_name = make_expanded_name(name, expr_start, expr_end, p);
2529 if (lp->ll_exp_name == NULL)
2531 /* Report an invalid expression in braces, unless the
2532 * expression evaluation has been cancelled due to an
2533 * aborting error, an interrupt, or an exception. */
2534 if (!aborting() && !quiet)
2536 emsg_severe = TRUE;
2537 EMSG2(_(e_invarg2), name);
2538 return NULL;
2541 lp->ll_name = lp->ll_exp_name;
2543 else
2544 lp->ll_name = name;
2546 /* Without [idx] or .key we are done. */
2547 if ((*p != '[' && *p != '.') || lp->ll_name == NULL)
2548 return p;
2550 cc = *p;
2551 *p = NUL;
2552 v = find_var(lp->ll_name, &ht);
2553 if (v == NULL && !quiet)
2554 EMSG2(_(e_undefvar), lp->ll_name);
2555 *p = cc;
2556 if (v == NULL)
2557 return NULL;
2560 * Loop until no more [idx] or .key is following.
2562 lp->ll_tv = &v->di_tv;
2563 while (*p == '[' || (*p == '.' && lp->ll_tv->v_type == VAR_DICT))
2565 if (!(lp->ll_tv->v_type == VAR_LIST && lp->ll_tv->vval.v_list != NULL)
2566 && !(lp->ll_tv->v_type == VAR_DICT
2567 && lp->ll_tv->vval.v_dict != NULL))
2569 if (!quiet)
2570 EMSG(_("E689: Can only index a List or Dictionary"));
2571 return NULL;
2573 if (lp->ll_range)
2575 if (!quiet)
2576 EMSG(_("E708: [:] must come last"));
2577 return NULL;
2580 len = -1;
2581 if (*p == '.')
2583 key = p + 1;
2584 for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
2586 if (len == 0)
2588 if (!quiet)
2589 EMSG(_(e_emptykey));
2590 return NULL;
2592 p = key + len;
2594 else
2596 /* Get the index [expr] or the first index [expr: ]. */
2597 p = skipwhite(p + 1);
2598 if (*p == ':')
2599 empty1 = TRUE;
2600 else
2602 empty1 = FALSE;
2603 if (eval1(&p, &var1, TRUE) == FAIL) /* recursive! */
2604 return NULL;
2605 if (get_tv_string_chk(&var1) == NULL)
2607 /* not a number or string */
2608 clear_tv(&var1);
2609 return NULL;
2613 /* Optionally get the second index [ :expr]. */
2614 if (*p == ':')
2616 if (lp->ll_tv->v_type == VAR_DICT)
2618 if (!quiet)
2619 EMSG(_(e_dictrange));
2620 if (!empty1)
2621 clear_tv(&var1);
2622 return NULL;
2624 if (rettv != NULL && (rettv->v_type != VAR_LIST
2625 || rettv->vval.v_list == NULL))
2627 if (!quiet)
2628 EMSG(_("E709: [:] requires a List value"));
2629 if (!empty1)
2630 clear_tv(&var1);
2631 return NULL;
2633 p = skipwhite(p + 1);
2634 if (*p == ']')
2635 lp->ll_empty2 = TRUE;
2636 else
2638 lp->ll_empty2 = FALSE;
2639 if (eval1(&p, &var2, TRUE) == FAIL) /* recursive! */
2641 if (!empty1)
2642 clear_tv(&var1);
2643 return NULL;
2645 if (get_tv_string_chk(&var2) == NULL)
2647 /* not a number or string */
2648 if (!empty1)
2649 clear_tv(&var1);
2650 clear_tv(&var2);
2651 return NULL;
2654 lp->ll_range = TRUE;
2656 else
2657 lp->ll_range = FALSE;
2659 if (*p != ']')
2661 if (!quiet)
2662 EMSG(_(e_missbrac));
2663 if (!empty1)
2664 clear_tv(&var1);
2665 if (lp->ll_range && !lp->ll_empty2)
2666 clear_tv(&var2);
2667 return NULL;
2670 /* Skip to past ']'. */
2671 ++p;
2674 if (lp->ll_tv->v_type == VAR_DICT)
2676 if (len == -1)
2678 /* "[key]": get key from "var1" */
2679 key = get_tv_string(&var1); /* is number or string */
2680 if (*key == NUL)
2682 if (!quiet)
2683 EMSG(_(e_emptykey));
2684 clear_tv(&var1);
2685 return NULL;
2688 lp->ll_list = NULL;
2689 lp->ll_dict = lp->ll_tv->vval.v_dict;
2690 lp->ll_di = dict_find(lp->ll_dict, key, len);
2691 if (lp->ll_di == NULL)
2693 /* Key does not exist in dict: may need to add it. */
2694 if (*p == '[' || *p == '.' || unlet)
2696 if (!quiet)
2697 EMSG2(_(e_dictkey), key);
2698 if (len == -1)
2699 clear_tv(&var1);
2700 return NULL;
2702 if (len == -1)
2703 lp->ll_newkey = vim_strsave(key);
2704 else
2705 lp->ll_newkey = vim_strnsave(key, len);
2706 if (len == -1)
2707 clear_tv(&var1);
2708 if (lp->ll_newkey == NULL)
2709 p = NULL;
2710 break;
2712 if (len == -1)
2713 clear_tv(&var1);
2714 lp->ll_tv = &lp->ll_di->di_tv;
2716 else
2719 * Get the number and item for the only or first index of the List.
2721 if (empty1)
2722 lp->ll_n1 = 0;
2723 else
2725 lp->ll_n1 = get_tv_number(&var1); /* is number or string */
2726 clear_tv(&var1);
2728 lp->ll_dict = NULL;
2729 lp->ll_list = lp->ll_tv->vval.v_list;
2730 lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2731 if (lp->ll_li == NULL)
2733 if (lp->ll_n1 < 0)
2735 lp->ll_n1 = 0;
2736 lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2739 if (lp->ll_li == NULL)
2741 if (lp->ll_range && !lp->ll_empty2)
2742 clear_tv(&var2);
2743 return NULL;
2747 * May need to find the item or absolute index for the second
2748 * index of a range.
2749 * When no index given: "lp->ll_empty2" is TRUE.
2750 * Otherwise "lp->ll_n2" is set to the second index.
2752 if (lp->ll_range && !lp->ll_empty2)
2754 lp->ll_n2 = get_tv_number(&var2); /* is number or string */
2755 clear_tv(&var2);
2756 if (lp->ll_n2 < 0)
2758 ni = list_find(lp->ll_list, lp->ll_n2);
2759 if (ni == NULL)
2760 return NULL;
2761 lp->ll_n2 = list_idx_of_item(lp->ll_list, ni);
2764 /* Check that lp->ll_n2 isn't before lp->ll_n1. */
2765 if (lp->ll_n1 < 0)
2766 lp->ll_n1 = list_idx_of_item(lp->ll_list, lp->ll_li);
2767 if (lp->ll_n2 < lp->ll_n1)
2768 return NULL;
2771 lp->ll_tv = &lp->ll_li->li_tv;
2775 return p;
2779 * Clear lval "lp" that was filled by get_lval().
2781 static void
2782 clear_lval(lp)
2783 lval_T *lp;
2785 vim_free(lp->ll_exp_name);
2786 vim_free(lp->ll_newkey);
2790 * Set a variable that was parsed by get_lval() to "rettv".
2791 * "endp" points to just after the parsed name.
2792 * "op" is NULL, "+" for "+=", "-" for "-=", "." for ".=" or "=" for "=".
2794 static void
2795 set_var_lval(lp, endp, rettv, copy, op)
2796 lval_T *lp;
2797 char_u *endp;
2798 typval_T *rettv;
2799 int copy;
2800 char_u *op;
2802 int cc;
2803 listitem_T *ri;
2804 dictitem_T *di;
2806 if (lp->ll_tv == NULL)
2808 if (!check_changedtick(lp->ll_name))
2810 cc = *endp;
2811 *endp = NUL;
2812 if (op != NULL && *op != '=')
2814 typval_T tv;
2816 /* handle +=, -= and .= */
2817 if (get_var_tv(lp->ll_name, (int)STRLEN(lp->ll_name),
2818 &tv, TRUE) == OK)
2820 if (tv_op(&tv, rettv, op) == OK)
2821 set_var(lp->ll_name, &tv, FALSE);
2822 clear_tv(&tv);
2825 else
2826 set_var(lp->ll_name, rettv, copy);
2827 *endp = cc;
2830 else if (tv_check_lock(lp->ll_newkey == NULL
2831 ? lp->ll_tv->v_lock
2832 : lp->ll_tv->vval.v_dict->dv_lock, lp->ll_name))
2834 else if (lp->ll_range)
2837 * Assign the List values to the list items.
2839 for (ri = rettv->vval.v_list->lv_first; ri != NULL; )
2841 if (op != NULL && *op != '=')
2842 tv_op(&lp->ll_li->li_tv, &ri->li_tv, op);
2843 else
2845 clear_tv(&lp->ll_li->li_tv);
2846 copy_tv(&ri->li_tv, &lp->ll_li->li_tv);
2848 ri = ri->li_next;
2849 if (ri == NULL || (!lp->ll_empty2 && lp->ll_n2 == lp->ll_n1))
2850 break;
2851 if (lp->ll_li->li_next == NULL)
2853 /* Need to add an empty item. */
2854 if (list_append_number(lp->ll_list, 0) == FAIL)
2856 ri = NULL;
2857 break;
2860 lp->ll_li = lp->ll_li->li_next;
2861 ++lp->ll_n1;
2863 if (ri != NULL)
2864 EMSG(_("E710: List value has more items than target"));
2865 else if (lp->ll_empty2
2866 ? (lp->ll_li != NULL && lp->ll_li->li_next != NULL)
2867 : lp->ll_n1 != lp->ll_n2)
2868 EMSG(_("E711: List value has not enough items"));
2870 else
2873 * Assign to a List or Dictionary item.
2875 if (lp->ll_newkey != NULL)
2877 if (op != NULL && *op != '=')
2879 EMSG2(_(e_letwrong), op);
2880 return;
2883 /* Need to add an item to the Dictionary. */
2884 di = dictitem_alloc(lp->ll_newkey);
2885 if (di == NULL)
2886 return;
2887 if (dict_add(lp->ll_tv->vval.v_dict, di) == FAIL)
2889 vim_free(di);
2890 return;
2892 lp->ll_tv = &di->di_tv;
2894 else if (op != NULL && *op != '=')
2896 tv_op(lp->ll_tv, rettv, op);
2897 return;
2899 else
2900 clear_tv(lp->ll_tv);
2903 * Assign the value to the variable or list item.
2905 if (copy)
2906 copy_tv(rettv, lp->ll_tv);
2907 else
2909 *lp->ll_tv = *rettv;
2910 lp->ll_tv->v_lock = 0;
2911 init_tv(rettv);
2917 * Handle "tv1 += tv2", "tv1 -= tv2" and "tv1 .= tv2"
2918 * Returns OK or FAIL.
2920 static int
2921 tv_op(tv1, tv2, op)
2922 typval_T *tv1;
2923 typval_T *tv2;
2924 char_u *op;
2926 long n;
2927 char_u numbuf[NUMBUFLEN];
2928 char_u *s;
2930 /* Can't do anything with a Funcref or a Dict on the right. */
2931 if (tv2->v_type != VAR_FUNC && tv2->v_type != VAR_DICT)
2933 switch (tv1->v_type)
2935 case VAR_DICT:
2936 case VAR_FUNC:
2937 break;
2939 case VAR_LIST:
2940 if (*op != '+' || tv2->v_type != VAR_LIST)
2941 break;
2942 /* List += List */
2943 if (tv1->vval.v_list != NULL && tv2->vval.v_list != NULL)
2944 list_extend(tv1->vval.v_list, tv2->vval.v_list, NULL);
2945 return OK;
2947 case VAR_NUMBER:
2948 case VAR_STRING:
2949 if (tv2->v_type == VAR_LIST)
2950 break;
2951 if (*op == '+' || *op == '-')
2953 /* nr += nr or nr -= nr*/
2954 n = get_tv_number(tv1);
2955 #ifdef FEAT_FLOAT
2956 if (tv2->v_type == VAR_FLOAT)
2958 float_T f = n;
2960 if (*op == '+')
2961 f += tv2->vval.v_float;
2962 else
2963 f -= tv2->vval.v_float;
2964 clear_tv(tv1);
2965 tv1->v_type = VAR_FLOAT;
2966 tv1->vval.v_float = f;
2968 else
2969 #endif
2971 if (*op == '+')
2972 n += get_tv_number(tv2);
2973 else
2974 n -= get_tv_number(tv2);
2975 clear_tv(tv1);
2976 tv1->v_type = VAR_NUMBER;
2977 tv1->vval.v_number = n;
2980 else
2982 if (tv2->v_type == VAR_FLOAT)
2983 break;
2985 /* str .= str */
2986 s = get_tv_string(tv1);
2987 s = concat_str(s, get_tv_string_buf(tv2, numbuf));
2988 clear_tv(tv1);
2989 tv1->v_type = VAR_STRING;
2990 tv1->vval.v_string = s;
2992 return OK;
2994 #ifdef FEAT_FLOAT
2995 case VAR_FLOAT:
2997 float_T f;
2999 if (*op == '.' || (tv2->v_type != VAR_FLOAT
3000 && tv2->v_type != VAR_NUMBER
3001 && tv2->v_type != VAR_STRING))
3002 break;
3003 if (tv2->v_type == VAR_FLOAT)
3004 f = tv2->vval.v_float;
3005 else
3006 f = get_tv_number(tv2);
3007 if (*op == '+')
3008 tv1->vval.v_float += f;
3009 else
3010 tv1->vval.v_float -= f;
3012 return OK;
3013 #endif
3017 EMSG2(_(e_letwrong), op);
3018 return FAIL;
3022 * Add a watcher to a list.
3024 static void
3025 list_add_watch(l, lw)
3026 list_T *l;
3027 listwatch_T *lw;
3029 lw->lw_next = l->lv_watch;
3030 l->lv_watch = lw;
3034 * Remove a watcher from a list.
3035 * No warning when it isn't found...
3037 static void
3038 list_rem_watch(l, lwrem)
3039 list_T *l;
3040 listwatch_T *lwrem;
3042 listwatch_T *lw, **lwp;
3044 lwp = &l->lv_watch;
3045 for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
3047 if (lw == lwrem)
3049 *lwp = lw->lw_next;
3050 break;
3052 lwp = &lw->lw_next;
3057 * Just before removing an item from a list: advance watchers to the next
3058 * item.
3060 static void
3061 list_fix_watch(l, item)
3062 list_T *l;
3063 listitem_T *item;
3065 listwatch_T *lw;
3067 for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
3068 if (lw->lw_item == item)
3069 lw->lw_item = item->li_next;
3073 * Evaluate the expression used in a ":for var in expr" command.
3074 * "arg" points to "var".
3075 * Set "*errp" to TRUE for an error, FALSE otherwise;
3076 * Return a pointer that holds the info. Null when there is an error.
3078 void *
3079 eval_for_line(arg, errp, nextcmdp, skip)
3080 char_u *arg;
3081 int *errp;
3082 char_u **nextcmdp;
3083 int skip;
3085 forinfo_T *fi;
3086 char_u *expr;
3087 typval_T tv;
3088 list_T *l;
3090 *errp = TRUE; /* default: there is an error */
3092 fi = (forinfo_T *)alloc_clear(sizeof(forinfo_T));
3093 if (fi == NULL)
3094 return NULL;
3096 expr = skip_var_list(arg, &fi->fi_varcount, &fi->fi_semicolon);
3097 if (expr == NULL)
3098 return fi;
3100 expr = skipwhite(expr);
3101 if (expr[0] != 'i' || expr[1] != 'n' || !vim_iswhite(expr[2]))
3103 EMSG(_("E690: Missing \"in\" after :for"));
3104 return fi;
3107 if (skip)
3108 ++emsg_skip;
3109 if (eval0(skipwhite(expr + 2), &tv, nextcmdp, !skip) == OK)
3111 *errp = FALSE;
3112 if (!skip)
3114 l = tv.vval.v_list;
3115 if (tv.v_type != VAR_LIST || l == NULL)
3117 EMSG(_(e_listreq));
3118 clear_tv(&tv);
3120 else
3122 /* No need to increment the refcount, it's already set for the
3123 * list being used in "tv". */
3124 fi->fi_list = l;
3125 list_add_watch(l, &fi->fi_lw);
3126 fi->fi_lw.lw_item = l->lv_first;
3130 if (skip)
3131 --emsg_skip;
3133 return fi;
3137 * Use the first item in a ":for" list. Advance to the next.
3138 * Assign the values to the variable (list). "arg" points to the first one.
3139 * Return TRUE when a valid item was found, FALSE when at end of list or
3140 * something wrong.
3143 next_for_item(fi_void, arg)
3144 void *fi_void;
3145 char_u *arg;
3147 forinfo_T *fi = (forinfo_T *)fi_void;
3148 int result;
3149 listitem_T *item;
3151 item = fi->fi_lw.lw_item;
3152 if (item == NULL)
3153 result = FALSE;
3154 else
3156 fi->fi_lw.lw_item = item->li_next;
3157 result = (ex_let_vars(arg, &item->li_tv, TRUE,
3158 fi->fi_semicolon, fi->fi_varcount, NULL) == OK);
3160 return result;
3164 * Free the structure used to store info used by ":for".
3166 void
3167 free_for_info(fi_void)
3168 void *fi_void;
3170 forinfo_T *fi = (forinfo_T *)fi_void;
3172 if (fi != NULL && fi->fi_list != NULL)
3174 list_rem_watch(fi->fi_list, &fi->fi_lw);
3175 list_unref(fi->fi_list);
3177 vim_free(fi);
3180 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3182 void
3183 set_context_for_expression(xp, arg, cmdidx)
3184 expand_T *xp;
3185 char_u *arg;
3186 cmdidx_T cmdidx;
3188 int got_eq = FALSE;
3189 int c;
3190 char_u *p;
3192 if (cmdidx == CMD_let)
3194 xp->xp_context = EXPAND_USER_VARS;
3195 if (vim_strpbrk(arg, (char_u *)"\"'+-*/%.=!?~|&$([<>,#") == NULL)
3197 /* ":let var1 var2 ...": find last space. */
3198 for (p = arg + STRLEN(arg); p >= arg; )
3200 xp->xp_pattern = p;
3201 mb_ptr_back(arg, p);
3202 if (vim_iswhite(*p))
3203 break;
3205 return;
3208 else
3209 xp->xp_context = cmdidx == CMD_call ? EXPAND_FUNCTIONS
3210 : EXPAND_EXPRESSION;
3211 while ((xp->xp_pattern = vim_strpbrk(arg,
3212 (char_u *)"\"'+-*/%.=!?~|&$([<>,#")) != NULL)
3214 c = *xp->xp_pattern;
3215 if (c == '&')
3217 c = xp->xp_pattern[1];
3218 if (c == '&')
3220 ++xp->xp_pattern;
3221 xp->xp_context = cmdidx != CMD_let || got_eq
3222 ? EXPAND_EXPRESSION : EXPAND_NOTHING;
3224 else if (c != ' ')
3226 xp->xp_context = EXPAND_SETTINGS;
3227 if ((c == 'l' || c == 'g') && xp->xp_pattern[2] == ':')
3228 xp->xp_pattern += 2;
3232 else if (c == '$')
3234 /* environment variable */
3235 xp->xp_context = EXPAND_ENV_VARS;
3237 else if (c == '=')
3239 got_eq = TRUE;
3240 xp->xp_context = EXPAND_EXPRESSION;
3242 else if (c == '<'
3243 && xp->xp_context == EXPAND_FUNCTIONS
3244 && vim_strchr(xp->xp_pattern, '(') == NULL)
3246 /* Function name can start with "<SNR>" */
3247 break;
3249 else if (cmdidx != CMD_let || got_eq)
3251 if (c == '"') /* string */
3253 while ((c = *++xp->xp_pattern) != NUL && c != '"')
3254 if (c == '\\' && xp->xp_pattern[1] != NUL)
3255 ++xp->xp_pattern;
3256 xp->xp_context = EXPAND_NOTHING;
3258 else if (c == '\'') /* literal string */
3260 /* Trick: '' is like stopping and starting a literal string. */
3261 while ((c = *++xp->xp_pattern) != NUL && c != '\'')
3262 /* skip */ ;
3263 xp->xp_context = EXPAND_NOTHING;
3265 else if (c == '|')
3267 if (xp->xp_pattern[1] == '|')
3269 ++xp->xp_pattern;
3270 xp->xp_context = EXPAND_EXPRESSION;
3272 else
3273 xp->xp_context = EXPAND_COMMANDS;
3275 else
3276 xp->xp_context = EXPAND_EXPRESSION;
3278 else
3279 /* Doesn't look like something valid, expand as an expression
3280 * anyway. */
3281 xp->xp_context = EXPAND_EXPRESSION;
3282 arg = xp->xp_pattern;
3283 if (*arg != NUL)
3284 while ((c = *++arg) != NUL && (c == ' ' || c == '\t'))
3285 /* skip */ ;
3287 xp->xp_pattern = arg;
3290 #endif /* FEAT_CMDL_COMPL */
3293 * ":1,25call func(arg1, arg2)" function call.
3295 void
3296 ex_call(eap)
3297 exarg_T *eap;
3299 char_u *arg = eap->arg;
3300 char_u *startarg;
3301 char_u *name;
3302 char_u *tofree;
3303 int len;
3304 typval_T rettv;
3305 linenr_T lnum;
3306 int doesrange;
3307 int failed = FALSE;
3308 funcdict_T fudi;
3310 tofree = trans_function_name(&arg, eap->skip, TFN_INT, &fudi);
3311 if (fudi.fd_newkey != NULL)
3313 /* Still need to give an error message for missing key. */
3314 EMSG2(_(e_dictkey), fudi.fd_newkey);
3315 vim_free(fudi.fd_newkey);
3317 if (tofree == NULL)
3318 return;
3320 /* Increase refcount on dictionary, it could get deleted when evaluating
3321 * the arguments. */
3322 if (fudi.fd_dict != NULL)
3323 ++fudi.fd_dict->dv_refcount;
3325 /* If it is the name of a variable of type VAR_FUNC use its contents. */
3326 len = (int)STRLEN(tofree);
3327 name = deref_func_name(tofree, &len);
3329 /* Skip white space to allow ":call func ()". Not good, but required for
3330 * backward compatibility. */
3331 startarg = skipwhite(arg);
3332 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
3334 if (*startarg != '(')
3336 EMSG2(_("E107: Missing parentheses: %s"), eap->arg);
3337 goto end;
3341 * When skipping, evaluate the function once, to find the end of the
3342 * arguments.
3343 * When the function takes a range, this is discovered after the first
3344 * call, and the loop is broken.
3346 if (eap->skip)
3348 ++emsg_skip;
3349 lnum = eap->line2; /* do it once, also with an invalid range */
3351 else
3352 lnum = eap->line1;
3353 for ( ; lnum <= eap->line2; ++lnum)
3355 if (!eap->skip && eap->addr_count > 0)
3357 curwin->w_cursor.lnum = lnum;
3358 curwin->w_cursor.col = 0;
3360 arg = startarg;
3361 if (get_func_tv(name, (int)STRLEN(name), &rettv, &arg,
3362 eap->line1, eap->line2, &doesrange,
3363 !eap->skip, fudi.fd_dict) == FAIL)
3365 failed = TRUE;
3366 break;
3369 /* Handle a function returning a Funcref, Dictionary or List. */
3370 if (handle_subscript(&arg, &rettv, !eap->skip, TRUE) == FAIL)
3372 failed = TRUE;
3373 break;
3376 clear_tv(&rettv);
3377 if (doesrange || eap->skip)
3378 break;
3380 /* Stop when immediately aborting on error, or when an interrupt
3381 * occurred or an exception was thrown but not caught.
3382 * get_func_tv() returned OK, so that the check for trailing
3383 * characters below is executed. */
3384 if (aborting())
3385 break;
3387 if (eap->skip)
3388 --emsg_skip;
3390 if (!failed)
3392 /* Check for trailing illegal characters and a following command. */
3393 if (!ends_excmd(*arg))
3395 emsg_severe = TRUE;
3396 EMSG(_(e_trailing));
3398 else
3399 eap->nextcmd = check_nextcmd(arg);
3402 end:
3403 dict_unref(fudi.fd_dict);
3404 vim_free(tofree);
3408 * ":unlet[!] var1 ... " command.
3410 void
3411 ex_unlet(eap)
3412 exarg_T *eap;
3414 ex_unletlock(eap, eap->arg, 0);
3418 * ":lockvar" and ":unlockvar" commands
3420 void
3421 ex_lockvar(eap)
3422 exarg_T *eap;
3424 char_u *arg = eap->arg;
3425 int deep = 2;
3427 if (eap->forceit)
3428 deep = -1;
3429 else if (vim_isdigit(*arg))
3431 deep = getdigits(&arg);
3432 arg = skipwhite(arg);
3435 ex_unletlock(eap, arg, deep);
3439 * ":unlet", ":lockvar" and ":unlockvar" are quite similar.
3441 static void
3442 ex_unletlock(eap, argstart, deep)
3443 exarg_T *eap;
3444 char_u *argstart;
3445 int deep;
3447 char_u *arg = argstart;
3448 char_u *name_end;
3449 int error = FALSE;
3450 lval_T lv;
3454 /* Parse the name and find the end. */
3455 name_end = get_lval(arg, NULL, &lv, TRUE, eap->skip || error, FALSE,
3456 FNE_CHECK_START);
3457 if (lv.ll_name == NULL)
3458 error = TRUE; /* error but continue parsing */
3459 if (name_end == NULL || (!vim_iswhite(*name_end)
3460 && !ends_excmd(*name_end)))
3462 if (name_end != NULL)
3464 emsg_severe = TRUE;
3465 EMSG(_(e_trailing));
3467 if (!(eap->skip || error))
3468 clear_lval(&lv);
3469 break;
3472 if (!error && !eap->skip)
3474 if (eap->cmdidx == CMD_unlet)
3476 if (do_unlet_var(&lv, name_end, eap->forceit) == FAIL)
3477 error = TRUE;
3479 else
3481 if (do_lock_var(&lv, name_end, deep,
3482 eap->cmdidx == CMD_lockvar) == FAIL)
3483 error = TRUE;
3487 if (!eap->skip)
3488 clear_lval(&lv);
3490 arg = skipwhite(name_end);
3491 } while (!ends_excmd(*arg));
3493 eap->nextcmd = check_nextcmd(arg);
3496 static int
3497 do_unlet_var(lp, name_end, forceit)
3498 lval_T *lp;
3499 char_u *name_end;
3500 int forceit;
3502 int ret = OK;
3503 int cc;
3505 if (lp->ll_tv == NULL)
3507 cc = *name_end;
3508 *name_end = NUL;
3510 /* Normal name or expanded name. */
3511 if (check_changedtick(lp->ll_name))
3512 ret = FAIL;
3513 else if (do_unlet(lp->ll_name, forceit) == FAIL)
3514 ret = FAIL;
3515 *name_end = cc;
3517 else if (tv_check_lock(lp->ll_tv->v_lock, lp->ll_name))
3518 return FAIL;
3519 else if (lp->ll_range)
3521 listitem_T *li;
3523 /* Delete a range of List items. */
3524 while (lp->ll_li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3526 li = lp->ll_li->li_next;
3527 listitem_remove(lp->ll_list, lp->ll_li);
3528 lp->ll_li = li;
3529 ++lp->ll_n1;
3532 else
3534 if (lp->ll_list != NULL)
3535 /* unlet a List item. */
3536 listitem_remove(lp->ll_list, lp->ll_li);
3537 else
3538 /* unlet a Dictionary item. */
3539 dictitem_remove(lp->ll_dict, lp->ll_di);
3542 return ret;
3546 * "unlet" a variable. Return OK if it existed, FAIL if not.
3547 * When "forceit" is TRUE don't complain if the variable doesn't exist.
3550 do_unlet(name, forceit)
3551 char_u *name;
3552 int forceit;
3554 hashtab_T *ht;
3555 hashitem_T *hi;
3556 char_u *varname;
3557 dictitem_T *di;
3559 ht = find_var_ht(name, &varname);
3560 if (ht != NULL && *varname != NUL)
3562 hi = hash_find(ht, varname);
3563 if (!HASHITEM_EMPTY(hi))
3565 di = HI2DI(hi);
3566 if (var_check_fixed(di->di_flags, name)
3567 || var_check_ro(di->di_flags, name))
3568 return FAIL;
3569 delete_var(ht, hi);
3570 return OK;
3573 if (forceit)
3574 return OK;
3575 EMSG2(_("E108: No such variable: \"%s\""), name);
3576 return FAIL;
3580 * Lock or unlock variable indicated by "lp".
3581 * "deep" is the levels to go (-1 for unlimited);
3582 * "lock" is TRUE for ":lockvar", FALSE for ":unlockvar".
3584 static int
3585 do_lock_var(lp, name_end, deep, lock)
3586 lval_T *lp;
3587 char_u *name_end;
3588 int deep;
3589 int lock;
3591 int ret = OK;
3592 int cc;
3593 dictitem_T *di;
3595 if (deep == 0) /* nothing to do */
3596 return OK;
3598 if (lp->ll_tv == NULL)
3600 cc = *name_end;
3601 *name_end = NUL;
3603 /* Normal name or expanded name. */
3604 if (check_changedtick(lp->ll_name))
3605 ret = FAIL;
3606 else
3608 di = find_var(lp->ll_name, NULL);
3609 if (di == NULL)
3610 ret = FAIL;
3611 else
3613 if (lock)
3614 di->di_flags |= DI_FLAGS_LOCK;
3615 else
3616 di->di_flags &= ~DI_FLAGS_LOCK;
3617 item_lock(&di->di_tv, deep, lock);
3620 *name_end = cc;
3622 else if (lp->ll_range)
3624 listitem_T *li = lp->ll_li;
3626 /* (un)lock a range of List items. */
3627 while (li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3629 item_lock(&li->li_tv, deep, lock);
3630 li = li->li_next;
3631 ++lp->ll_n1;
3634 else if (lp->ll_list != NULL)
3635 /* (un)lock a List item. */
3636 item_lock(&lp->ll_li->li_tv, deep, lock);
3637 else
3638 /* un(lock) a Dictionary item. */
3639 item_lock(&lp->ll_di->di_tv, deep, lock);
3641 return ret;
3645 * Lock or unlock an item. "deep" is nr of levels to go.
3647 static void
3648 item_lock(tv, deep, lock)
3649 typval_T *tv;
3650 int deep;
3651 int lock;
3653 static int recurse = 0;
3654 list_T *l;
3655 listitem_T *li;
3656 dict_T *d;
3657 hashitem_T *hi;
3658 int todo;
3660 if (recurse >= DICT_MAXNEST)
3662 EMSG(_("E743: variable nested too deep for (un)lock"));
3663 return;
3665 if (deep == 0)
3666 return;
3667 ++recurse;
3669 /* lock/unlock the item itself */
3670 if (lock)
3671 tv->v_lock |= VAR_LOCKED;
3672 else
3673 tv->v_lock &= ~VAR_LOCKED;
3675 switch (tv->v_type)
3677 case VAR_LIST:
3678 if ((l = tv->vval.v_list) != NULL)
3680 if (lock)
3681 l->lv_lock |= VAR_LOCKED;
3682 else
3683 l->lv_lock &= ~VAR_LOCKED;
3684 if (deep < 0 || deep > 1)
3685 /* recursive: lock/unlock the items the List contains */
3686 for (li = l->lv_first; li != NULL; li = li->li_next)
3687 item_lock(&li->li_tv, deep - 1, lock);
3689 break;
3690 case VAR_DICT:
3691 if ((d = tv->vval.v_dict) != NULL)
3693 if (lock)
3694 d->dv_lock |= VAR_LOCKED;
3695 else
3696 d->dv_lock &= ~VAR_LOCKED;
3697 if (deep < 0 || deep > 1)
3699 /* recursive: lock/unlock the items the List contains */
3700 todo = (int)d->dv_hashtab.ht_used;
3701 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
3703 if (!HASHITEM_EMPTY(hi))
3705 --todo;
3706 item_lock(&HI2DI(hi)->di_tv, deep - 1, lock);
3712 --recurse;
3716 * Return TRUE if typeval "tv" is locked: Either that value is locked itself
3717 * or it refers to a List or Dictionary that is locked.
3719 static int
3720 tv_islocked(tv)
3721 typval_T *tv;
3723 return (tv->v_lock & VAR_LOCKED)
3724 || (tv->v_type == VAR_LIST
3725 && tv->vval.v_list != NULL
3726 && (tv->vval.v_list->lv_lock & VAR_LOCKED))
3727 || (tv->v_type == VAR_DICT
3728 && tv->vval.v_dict != NULL
3729 && (tv->vval.v_dict->dv_lock & VAR_LOCKED));
3732 #if (defined(FEAT_MENU) && defined(FEAT_MULTI_LANG)) || defined(PROTO)
3734 * Delete all "menutrans_" variables.
3736 void
3737 del_menutrans_vars()
3739 hashitem_T *hi;
3740 int todo;
3742 hash_lock(&globvarht);
3743 todo = (int)globvarht.ht_used;
3744 for (hi = globvarht.ht_array; todo > 0 && !got_int; ++hi)
3746 if (!HASHITEM_EMPTY(hi))
3748 --todo;
3749 if (STRNCMP(HI2DI(hi)->di_key, "menutrans_", 10) == 0)
3750 delete_var(&globvarht, hi);
3753 hash_unlock(&globvarht);
3755 #endif
3757 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3760 * Local string buffer for the next two functions to store a variable name
3761 * with its prefix. Allocated in cat_prefix_varname(), freed later in
3762 * get_user_var_name().
3765 static char_u *cat_prefix_varname __ARGS((int prefix, char_u *name));
3767 static char_u *varnamebuf = NULL;
3768 static int varnamebuflen = 0;
3771 * Function to concatenate a prefix and a variable name.
3773 static char_u *
3774 cat_prefix_varname(prefix, name)
3775 int prefix;
3776 char_u *name;
3778 int len;
3780 len = (int)STRLEN(name) + 3;
3781 if (len > varnamebuflen)
3783 vim_free(varnamebuf);
3784 len += 10; /* some additional space */
3785 varnamebuf = alloc(len);
3786 if (varnamebuf == NULL)
3788 varnamebuflen = 0;
3789 return NULL;
3791 varnamebuflen = len;
3793 *varnamebuf = prefix;
3794 varnamebuf[1] = ':';
3795 STRCPY(varnamebuf + 2, name);
3796 return varnamebuf;
3800 * Function given to ExpandGeneric() to obtain the list of user defined
3801 * (global/buffer/window/built-in) variable names.
3803 char_u *
3804 get_user_var_name(xp, idx)
3805 expand_T *xp;
3806 int idx;
3808 static long_u gdone;
3809 static long_u bdone;
3810 static long_u wdone;
3811 #ifdef FEAT_WINDOWS
3812 static long_u tdone;
3813 #endif
3814 static int vidx;
3815 static hashitem_T *hi;
3816 hashtab_T *ht;
3818 if (idx == 0)
3820 gdone = bdone = wdone = vidx = 0;
3821 #ifdef FEAT_WINDOWS
3822 tdone = 0;
3823 #endif
3826 /* Global variables */
3827 if (gdone < globvarht.ht_used)
3829 if (gdone++ == 0)
3830 hi = globvarht.ht_array;
3831 else
3832 ++hi;
3833 while (HASHITEM_EMPTY(hi))
3834 ++hi;
3835 if (STRNCMP("g:", xp->xp_pattern, 2) == 0)
3836 return cat_prefix_varname('g', hi->hi_key);
3837 return hi->hi_key;
3840 /* b: variables */
3841 ht = &curbuf->b_vars.dv_hashtab;
3842 if (bdone < ht->ht_used)
3844 if (bdone++ == 0)
3845 hi = ht->ht_array;
3846 else
3847 ++hi;
3848 while (HASHITEM_EMPTY(hi))
3849 ++hi;
3850 return cat_prefix_varname('b', hi->hi_key);
3852 if (bdone == ht->ht_used)
3854 ++bdone;
3855 return (char_u *)"b:changedtick";
3858 /* w: variables */
3859 ht = &curwin->w_vars.dv_hashtab;
3860 if (wdone < ht->ht_used)
3862 if (wdone++ == 0)
3863 hi = ht->ht_array;
3864 else
3865 ++hi;
3866 while (HASHITEM_EMPTY(hi))
3867 ++hi;
3868 return cat_prefix_varname('w', hi->hi_key);
3871 #ifdef FEAT_WINDOWS
3872 /* t: variables */
3873 ht = &curtab->tp_vars.dv_hashtab;
3874 if (tdone < ht->ht_used)
3876 if (tdone++ == 0)
3877 hi = ht->ht_array;
3878 else
3879 ++hi;
3880 while (HASHITEM_EMPTY(hi))
3881 ++hi;
3882 return cat_prefix_varname('t', hi->hi_key);
3884 #endif
3886 /* v: variables */
3887 if (vidx < VV_LEN)
3888 return cat_prefix_varname('v', (char_u *)vimvars[vidx++].vv_name);
3890 vim_free(varnamebuf);
3891 varnamebuf = NULL;
3892 varnamebuflen = 0;
3893 return NULL;
3896 #endif /* FEAT_CMDL_COMPL */
3899 * types for expressions.
3901 typedef enum
3903 TYPE_UNKNOWN = 0
3904 , TYPE_EQUAL /* == */
3905 , TYPE_NEQUAL /* != */
3906 , TYPE_GREATER /* > */
3907 , TYPE_GEQUAL /* >= */
3908 , TYPE_SMALLER /* < */
3909 , TYPE_SEQUAL /* <= */
3910 , TYPE_MATCH /* =~ */
3911 , TYPE_NOMATCH /* !~ */
3912 } exptype_T;
3915 * The "evaluate" argument: When FALSE, the argument is only parsed but not
3916 * executed. The function may return OK, but the rettv will be of type
3917 * VAR_UNKNOWN. The function still returns FAIL for a syntax error.
3921 * Handle zero level expression.
3922 * This calls eval1() and handles error message and nextcmd.
3923 * Put the result in "rettv" when returning OK and "evaluate" is TRUE.
3924 * Note: "rettv.v_lock" is not set.
3925 * Return OK or FAIL.
3927 static int
3928 eval0(arg, rettv, nextcmd, evaluate)
3929 char_u *arg;
3930 typval_T *rettv;
3931 char_u **nextcmd;
3932 int evaluate;
3934 int ret;
3935 char_u *p;
3937 p = skipwhite(arg);
3938 ret = eval1(&p, rettv, evaluate);
3939 if (ret == FAIL || !ends_excmd(*p))
3941 if (ret != FAIL)
3942 clear_tv(rettv);
3944 * Report the invalid expression unless the expression evaluation has
3945 * been cancelled due to an aborting error, an interrupt, or an
3946 * exception.
3948 if (!aborting())
3949 EMSG2(_(e_invexpr2), arg);
3950 ret = FAIL;
3952 if (nextcmd != NULL)
3953 *nextcmd = check_nextcmd(p);
3955 return ret;
3959 * Handle top level expression:
3960 * expr2 ? expr1 : expr1
3962 * "arg" must point to the first non-white of the expression.
3963 * "arg" is advanced to the next non-white after the recognized expression.
3965 * Note: "rettv.v_lock" is not set.
3967 * Return OK or FAIL.
3969 static int
3970 eval1(arg, rettv, evaluate)
3971 char_u **arg;
3972 typval_T *rettv;
3973 int evaluate;
3975 int result;
3976 typval_T var2;
3979 * Get the first variable.
3981 if (eval2(arg, rettv, evaluate) == FAIL)
3982 return FAIL;
3984 if ((*arg)[0] == '?')
3986 result = FALSE;
3987 if (evaluate)
3989 int error = FALSE;
3991 if (get_tv_number_chk(rettv, &error) != 0)
3992 result = TRUE;
3993 clear_tv(rettv);
3994 if (error)
3995 return FAIL;
3999 * Get the second variable.
4001 *arg = skipwhite(*arg + 1);
4002 if (eval1(arg, rettv, evaluate && result) == FAIL) /* recursive! */
4003 return FAIL;
4006 * Check for the ":".
4008 if ((*arg)[0] != ':')
4010 EMSG(_("E109: Missing ':' after '?'"));
4011 if (evaluate && result)
4012 clear_tv(rettv);
4013 return FAIL;
4017 * Get the third variable.
4019 *arg = skipwhite(*arg + 1);
4020 if (eval1(arg, &var2, evaluate && !result) == FAIL) /* recursive! */
4022 if (evaluate && result)
4023 clear_tv(rettv);
4024 return FAIL;
4026 if (evaluate && !result)
4027 *rettv = var2;
4030 return OK;
4034 * Handle first level expression:
4035 * expr2 || expr2 || expr2 logical OR
4037 * "arg" must point to the first non-white of the expression.
4038 * "arg" is advanced to the next non-white after the recognized expression.
4040 * Return OK or FAIL.
4042 static int
4043 eval2(arg, rettv, evaluate)
4044 char_u **arg;
4045 typval_T *rettv;
4046 int evaluate;
4048 typval_T var2;
4049 long result;
4050 int first;
4051 int error = FALSE;
4054 * Get the first variable.
4056 if (eval3(arg, rettv, evaluate) == FAIL)
4057 return FAIL;
4060 * Repeat until there is no following "||".
4062 first = TRUE;
4063 result = FALSE;
4064 while ((*arg)[0] == '|' && (*arg)[1] == '|')
4066 if (evaluate && first)
4068 if (get_tv_number_chk(rettv, &error) != 0)
4069 result = TRUE;
4070 clear_tv(rettv);
4071 if (error)
4072 return FAIL;
4073 first = FALSE;
4077 * Get the second variable.
4079 *arg = skipwhite(*arg + 2);
4080 if (eval3(arg, &var2, evaluate && !result) == FAIL)
4081 return FAIL;
4084 * Compute the result.
4086 if (evaluate && !result)
4088 if (get_tv_number_chk(&var2, &error) != 0)
4089 result = TRUE;
4090 clear_tv(&var2);
4091 if (error)
4092 return FAIL;
4094 if (evaluate)
4096 rettv->v_type = VAR_NUMBER;
4097 rettv->vval.v_number = result;
4101 return OK;
4105 * Handle second level expression:
4106 * expr3 && expr3 && expr3 logical AND
4108 * "arg" must point to the first non-white of the expression.
4109 * "arg" is advanced to the next non-white after the recognized expression.
4111 * Return OK or FAIL.
4113 static int
4114 eval3(arg, rettv, evaluate)
4115 char_u **arg;
4116 typval_T *rettv;
4117 int evaluate;
4119 typval_T var2;
4120 long result;
4121 int first;
4122 int error = FALSE;
4125 * Get the first variable.
4127 if (eval4(arg, rettv, evaluate) == FAIL)
4128 return FAIL;
4131 * Repeat until there is no following "&&".
4133 first = TRUE;
4134 result = TRUE;
4135 while ((*arg)[0] == '&' && (*arg)[1] == '&')
4137 if (evaluate && first)
4139 if (get_tv_number_chk(rettv, &error) == 0)
4140 result = FALSE;
4141 clear_tv(rettv);
4142 if (error)
4143 return FAIL;
4144 first = FALSE;
4148 * Get the second variable.
4150 *arg = skipwhite(*arg + 2);
4151 if (eval4(arg, &var2, evaluate && result) == FAIL)
4152 return FAIL;
4155 * Compute the result.
4157 if (evaluate && result)
4159 if (get_tv_number_chk(&var2, &error) == 0)
4160 result = FALSE;
4161 clear_tv(&var2);
4162 if (error)
4163 return FAIL;
4165 if (evaluate)
4167 rettv->v_type = VAR_NUMBER;
4168 rettv->vval.v_number = result;
4172 return OK;
4176 * Handle third level expression:
4177 * var1 == var2
4178 * var1 =~ var2
4179 * var1 != var2
4180 * var1 !~ var2
4181 * var1 > var2
4182 * var1 >= var2
4183 * var1 < var2
4184 * var1 <= var2
4185 * var1 is var2
4186 * var1 isnot var2
4188 * "arg" must point to the first non-white of the expression.
4189 * "arg" is advanced to the next non-white after the recognized expression.
4191 * Return OK or FAIL.
4193 static int
4194 eval4(arg, rettv, evaluate)
4195 char_u **arg;
4196 typval_T *rettv;
4197 int evaluate;
4199 typval_T var2;
4200 char_u *p;
4201 int i;
4202 exptype_T type = TYPE_UNKNOWN;
4203 int type_is = FALSE; /* TRUE for "is" and "isnot" */
4204 int len = 2;
4205 long n1, n2;
4206 char_u *s1, *s2;
4207 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
4208 regmatch_T regmatch;
4209 int ic;
4210 char_u *save_cpo;
4213 * Get the first variable.
4215 if (eval5(arg, rettv, evaluate) == FAIL)
4216 return FAIL;
4218 p = *arg;
4219 switch (p[0])
4221 case '=': if (p[1] == '=')
4222 type = TYPE_EQUAL;
4223 else if (p[1] == '~')
4224 type = TYPE_MATCH;
4225 break;
4226 case '!': if (p[1] == '=')
4227 type = TYPE_NEQUAL;
4228 else if (p[1] == '~')
4229 type = TYPE_NOMATCH;
4230 break;
4231 case '>': if (p[1] != '=')
4233 type = TYPE_GREATER;
4234 len = 1;
4236 else
4237 type = TYPE_GEQUAL;
4238 break;
4239 case '<': if (p[1] != '=')
4241 type = TYPE_SMALLER;
4242 len = 1;
4244 else
4245 type = TYPE_SEQUAL;
4246 break;
4247 case 'i': if (p[1] == 's')
4249 if (p[2] == 'n' && p[3] == 'o' && p[4] == 't')
4250 len = 5;
4251 if (!vim_isIDc(p[len]))
4253 type = len == 2 ? TYPE_EQUAL : TYPE_NEQUAL;
4254 type_is = TRUE;
4257 break;
4261 * If there is a comparative operator, use it.
4263 if (type != TYPE_UNKNOWN)
4265 /* extra question mark appended: ignore case */
4266 if (p[len] == '?')
4268 ic = TRUE;
4269 ++len;
4271 /* extra '#' appended: match case */
4272 else if (p[len] == '#')
4274 ic = FALSE;
4275 ++len;
4277 /* nothing appended: use 'ignorecase' */
4278 else
4279 ic = p_ic;
4282 * Get the second variable.
4284 *arg = skipwhite(p + len);
4285 if (eval5(arg, &var2, evaluate) == FAIL)
4287 clear_tv(rettv);
4288 return FAIL;
4291 if (evaluate)
4293 if (type_is && rettv->v_type != var2.v_type)
4295 /* For "is" a different type always means FALSE, for "notis"
4296 * it means TRUE. */
4297 n1 = (type == TYPE_NEQUAL);
4299 else if (rettv->v_type == VAR_LIST || var2.v_type == VAR_LIST)
4301 if (type_is)
4303 n1 = (rettv->v_type == var2.v_type
4304 && rettv->vval.v_list == var2.vval.v_list);
4305 if (type == TYPE_NEQUAL)
4306 n1 = !n1;
4308 else if (rettv->v_type != var2.v_type
4309 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4311 if (rettv->v_type != var2.v_type)
4312 EMSG(_("E691: Can only compare List with List"));
4313 else
4314 EMSG(_("E692: Invalid operation for Lists"));
4315 clear_tv(rettv);
4316 clear_tv(&var2);
4317 return FAIL;
4319 else
4321 /* Compare two Lists for being equal or unequal. */
4322 n1 = list_equal(rettv->vval.v_list, var2.vval.v_list, ic);
4323 if (type == TYPE_NEQUAL)
4324 n1 = !n1;
4328 else if (rettv->v_type == VAR_DICT || var2.v_type == VAR_DICT)
4330 if (type_is)
4332 n1 = (rettv->v_type == var2.v_type
4333 && rettv->vval.v_dict == var2.vval.v_dict);
4334 if (type == TYPE_NEQUAL)
4335 n1 = !n1;
4337 else if (rettv->v_type != var2.v_type
4338 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4340 if (rettv->v_type != var2.v_type)
4341 EMSG(_("E735: Can only compare Dictionary with Dictionary"));
4342 else
4343 EMSG(_("E736: Invalid operation for Dictionary"));
4344 clear_tv(rettv);
4345 clear_tv(&var2);
4346 return FAIL;
4348 else
4350 /* Compare two Dictionaries for being equal or unequal. */
4351 n1 = dict_equal(rettv->vval.v_dict, var2.vval.v_dict, ic);
4352 if (type == TYPE_NEQUAL)
4353 n1 = !n1;
4357 else if (rettv->v_type == VAR_FUNC || var2.v_type == VAR_FUNC)
4359 if (rettv->v_type != var2.v_type
4360 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4362 if (rettv->v_type != var2.v_type)
4363 EMSG(_("E693: Can only compare Funcref with Funcref"));
4364 else
4365 EMSG(_("E694: Invalid operation for Funcrefs"));
4366 clear_tv(rettv);
4367 clear_tv(&var2);
4368 return FAIL;
4370 else
4372 /* Compare two Funcrefs for being equal or unequal. */
4373 if (rettv->vval.v_string == NULL
4374 || var2.vval.v_string == NULL)
4375 n1 = FALSE;
4376 else
4377 n1 = STRCMP(rettv->vval.v_string,
4378 var2.vval.v_string) == 0;
4379 if (type == TYPE_NEQUAL)
4380 n1 = !n1;
4384 #ifdef FEAT_FLOAT
4386 * If one of the two variables is a float, compare as a float.
4387 * When using "=~" or "!~", always compare as string.
4389 else if ((rettv->v_type == VAR_FLOAT || var2.v_type == VAR_FLOAT)
4390 && type != TYPE_MATCH && type != TYPE_NOMATCH)
4392 float_T f1, f2;
4394 if (rettv->v_type == VAR_FLOAT)
4395 f1 = rettv->vval.v_float;
4396 else
4397 f1 = get_tv_number(rettv);
4398 if (var2.v_type == VAR_FLOAT)
4399 f2 = var2.vval.v_float;
4400 else
4401 f2 = get_tv_number(&var2);
4402 n1 = FALSE;
4403 switch (type)
4405 case TYPE_EQUAL: n1 = (f1 == f2); break;
4406 case TYPE_NEQUAL: n1 = (f1 != f2); break;
4407 case TYPE_GREATER: n1 = (f1 > f2); break;
4408 case TYPE_GEQUAL: n1 = (f1 >= f2); break;
4409 case TYPE_SMALLER: n1 = (f1 < f2); break;
4410 case TYPE_SEQUAL: n1 = (f1 <= f2); break;
4411 case TYPE_UNKNOWN:
4412 case TYPE_MATCH:
4413 case TYPE_NOMATCH: break; /* avoid gcc warning */
4416 #endif
4419 * If one of the two variables is a number, compare as a number.
4420 * When using "=~" or "!~", always compare as string.
4422 else if ((rettv->v_type == VAR_NUMBER || var2.v_type == VAR_NUMBER)
4423 && type != TYPE_MATCH && type != TYPE_NOMATCH)
4425 n1 = get_tv_number(rettv);
4426 n2 = get_tv_number(&var2);
4427 switch (type)
4429 case TYPE_EQUAL: n1 = (n1 == n2); break;
4430 case TYPE_NEQUAL: n1 = (n1 != n2); break;
4431 case TYPE_GREATER: n1 = (n1 > n2); break;
4432 case TYPE_GEQUAL: n1 = (n1 >= n2); break;
4433 case TYPE_SMALLER: n1 = (n1 < n2); break;
4434 case TYPE_SEQUAL: n1 = (n1 <= n2); break;
4435 case TYPE_UNKNOWN:
4436 case TYPE_MATCH:
4437 case TYPE_NOMATCH: break; /* avoid gcc warning */
4440 else
4442 s1 = get_tv_string_buf(rettv, buf1);
4443 s2 = get_tv_string_buf(&var2, buf2);
4444 if (type != TYPE_MATCH && type != TYPE_NOMATCH)
4445 i = ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2);
4446 else
4447 i = 0;
4448 n1 = FALSE;
4449 switch (type)
4451 case TYPE_EQUAL: n1 = (i == 0); break;
4452 case TYPE_NEQUAL: n1 = (i != 0); break;
4453 case TYPE_GREATER: n1 = (i > 0); break;
4454 case TYPE_GEQUAL: n1 = (i >= 0); break;
4455 case TYPE_SMALLER: n1 = (i < 0); break;
4456 case TYPE_SEQUAL: n1 = (i <= 0); break;
4458 case TYPE_MATCH:
4459 case TYPE_NOMATCH:
4460 /* avoid 'l' flag in 'cpoptions' */
4461 save_cpo = p_cpo;
4462 p_cpo = (char_u *)"";
4463 regmatch.regprog = vim_regcomp(s2,
4464 RE_MAGIC + RE_STRING);
4465 regmatch.rm_ic = ic;
4466 if (regmatch.regprog != NULL)
4468 n1 = vim_regexec_nl(&regmatch, s1, (colnr_T)0);
4469 vim_free(regmatch.regprog);
4470 if (type == TYPE_NOMATCH)
4471 n1 = !n1;
4473 p_cpo = save_cpo;
4474 break;
4476 case TYPE_UNKNOWN: break; /* avoid gcc warning */
4479 clear_tv(rettv);
4480 clear_tv(&var2);
4481 rettv->v_type = VAR_NUMBER;
4482 rettv->vval.v_number = n1;
4486 return OK;
4490 * Handle fourth level expression:
4491 * + number addition
4492 * - number subtraction
4493 * . string concatenation
4495 * "arg" must point to the first non-white of the expression.
4496 * "arg" is advanced to the next non-white after the recognized expression.
4498 * Return OK or FAIL.
4500 static int
4501 eval5(arg, rettv, evaluate)
4502 char_u **arg;
4503 typval_T *rettv;
4504 int evaluate;
4506 typval_T var2;
4507 typval_T var3;
4508 int op;
4509 long n1, n2;
4510 #ifdef FEAT_FLOAT
4511 float_T f1 = 0, f2 = 0;
4512 #endif
4513 char_u *s1, *s2;
4514 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
4515 char_u *p;
4518 * Get the first variable.
4520 if (eval6(arg, rettv, evaluate, FALSE) == FAIL)
4521 return FAIL;
4524 * Repeat computing, until no '+', '-' or '.' is following.
4526 for (;;)
4528 op = **arg;
4529 if (op != '+' && op != '-' && op != '.')
4530 break;
4532 if ((op != '+' || rettv->v_type != VAR_LIST)
4533 #ifdef FEAT_FLOAT
4534 && (op == '.' || rettv->v_type != VAR_FLOAT)
4535 #endif
4538 /* For "list + ...", an illegal use of the first operand as
4539 * a number cannot be determined before evaluating the 2nd
4540 * operand: if this is also a list, all is ok.
4541 * For "something . ...", "something - ..." or "non-list + ...",
4542 * we know that the first operand needs to be a string or number
4543 * without evaluating the 2nd operand. So check before to avoid
4544 * side effects after an error. */
4545 if (evaluate && get_tv_string_chk(rettv) == NULL)
4547 clear_tv(rettv);
4548 return FAIL;
4553 * Get the second variable.
4555 *arg = skipwhite(*arg + 1);
4556 if (eval6(arg, &var2, evaluate, op == '.') == FAIL)
4558 clear_tv(rettv);
4559 return FAIL;
4562 if (evaluate)
4565 * Compute the result.
4567 if (op == '.')
4569 s1 = get_tv_string_buf(rettv, buf1); /* already checked */
4570 s2 = get_tv_string_buf_chk(&var2, buf2);
4571 if (s2 == NULL) /* type error ? */
4573 clear_tv(rettv);
4574 clear_tv(&var2);
4575 return FAIL;
4577 p = concat_str(s1, s2);
4578 clear_tv(rettv);
4579 rettv->v_type = VAR_STRING;
4580 rettv->vval.v_string = p;
4582 else if (op == '+' && rettv->v_type == VAR_LIST
4583 && var2.v_type == VAR_LIST)
4585 /* concatenate Lists */
4586 if (list_concat(rettv->vval.v_list, var2.vval.v_list,
4587 &var3) == FAIL)
4589 clear_tv(rettv);
4590 clear_tv(&var2);
4591 return FAIL;
4593 clear_tv(rettv);
4594 *rettv = var3;
4596 else
4598 int error = FALSE;
4600 #ifdef FEAT_FLOAT
4601 if (rettv->v_type == VAR_FLOAT)
4603 f1 = rettv->vval.v_float;
4604 n1 = 0;
4606 else
4607 #endif
4609 n1 = get_tv_number_chk(rettv, &error);
4610 if (error)
4612 /* This can only happen for "list + non-list". For
4613 * "non-list + ..." or "something - ...", we returned
4614 * before evaluating the 2nd operand. */
4615 clear_tv(rettv);
4616 return FAIL;
4618 #ifdef FEAT_FLOAT
4619 if (var2.v_type == VAR_FLOAT)
4620 f1 = n1;
4621 #endif
4623 #ifdef FEAT_FLOAT
4624 if (var2.v_type == VAR_FLOAT)
4626 f2 = var2.vval.v_float;
4627 n2 = 0;
4629 else
4630 #endif
4632 n2 = get_tv_number_chk(&var2, &error);
4633 if (error)
4635 clear_tv(rettv);
4636 clear_tv(&var2);
4637 return FAIL;
4639 #ifdef FEAT_FLOAT
4640 if (rettv->v_type == VAR_FLOAT)
4641 f2 = n2;
4642 #endif
4644 clear_tv(rettv);
4646 #ifdef FEAT_FLOAT
4647 /* If there is a float on either side the result is a float. */
4648 if (rettv->v_type == VAR_FLOAT || var2.v_type == VAR_FLOAT)
4650 if (op == '+')
4651 f1 = f1 + f2;
4652 else
4653 f1 = f1 - f2;
4654 rettv->v_type = VAR_FLOAT;
4655 rettv->vval.v_float = f1;
4657 else
4658 #endif
4660 if (op == '+')
4661 n1 = n1 + n2;
4662 else
4663 n1 = n1 - n2;
4664 rettv->v_type = VAR_NUMBER;
4665 rettv->vval.v_number = n1;
4668 clear_tv(&var2);
4671 return OK;
4675 * Handle fifth level expression:
4676 * * number multiplication
4677 * / number division
4678 * % number modulo
4680 * "arg" must point to the first non-white of the expression.
4681 * "arg" is advanced to the next non-white after the recognized expression.
4683 * Return OK or FAIL.
4685 static int
4686 eval6(arg, rettv, evaluate, want_string)
4687 char_u **arg;
4688 typval_T *rettv;
4689 int evaluate;
4690 int want_string; /* after "." operator */
4692 typval_T var2;
4693 int op;
4694 long n1, n2;
4695 #ifdef FEAT_FLOAT
4696 int use_float = FALSE;
4697 float_T f1 = 0, f2;
4698 #endif
4699 int error = FALSE;
4702 * Get the first variable.
4704 if (eval7(arg, rettv, evaluate, want_string) == FAIL)
4705 return FAIL;
4708 * Repeat computing, until no '*', '/' or '%' is following.
4710 for (;;)
4712 op = **arg;
4713 if (op != '*' && op != '/' && op != '%')
4714 break;
4716 if (evaluate)
4718 #ifdef FEAT_FLOAT
4719 if (rettv->v_type == VAR_FLOAT)
4721 f1 = rettv->vval.v_float;
4722 use_float = TRUE;
4723 n1 = 0;
4725 else
4726 #endif
4727 n1 = get_tv_number_chk(rettv, &error);
4728 clear_tv(rettv);
4729 if (error)
4730 return FAIL;
4732 else
4733 n1 = 0;
4736 * Get the second variable.
4738 *arg = skipwhite(*arg + 1);
4739 if (eval7(arg, &var2, evaluate, FALSE) == FAIL)
4740 return FAIL;
4742 if (evaluate)
4744 #ifdef FEAT_FLOAT
4745 if (var2.v_type == VAR_FLOAT)
4747 if (!use_float)
4749 f1 = n1;
4750 use_float = TRUE;
4752 f2 = var2.vval.v_float;
4753 n2 = 0;
4755 else
4756 #endif
4758 n2 = get_tv_number_chk(&var2, &error);
4759 clear_tv(&var2);
4760 if (error)
4761 return FAIL;
4762 #ifdef FEAT_FLOAT
4763 if (use_float)
4764 f2 = n2;
4765 #endif
4769 * Compute the result.
4770 * When either side is a float the result is a float.
4772 #ifdef FEAT_FLOAT
4773 if (use_float)
4775 if (op == '*')
4776 f1 = f1 * f2;
4777 else if (op == '/')
4779 /* We rely on the floating point library to handle divide
4780 * by zero to result in "inf" and not a crash. */
4781 f1 = f1 / f2;
4783 else
4785 EMSG(_("E804: Cannot use '%' with Float"));
4786 return FAIL;
4788 rettv->v_type = VAR_FLOAT;
4789 rettv->vval.v_float = f1;
4791 else
4792 #endif
4794 if (op == '*')
4795 n1 = n1 * n2;
4796 else if (op == '/')
4798 if (n2 == 0) /* give an error message? */
4800 if (n1 == 0)
4801 n1 = -0x7fffffffL - 1L; /* similar to NaN */
4802 else if (n1 < 0)
4803 n1 = -0x7fffffffL;
4804 else
4805 n1 = 0x7fffffffL;
4807 else
4808 n1 = n1 / n2;
4810 else
4812 if (n2 == 0) /* give an error message? */
4813 n1 = 0;
4814 else
4815 n1 = n1 % n2;
4817 rettv->v_type = VAR_NUMBER;
4818 rettv->vval.v_number = n1;
4823 return OK;
4827 * Handle sixth level expression:
4828 * number number constant
4829 * "string" string constant
4830 * 'string' literal string constant
4831 * &option-name option value
4832 * @r register contents
4833 * identifier variable value
4834 * function() function call
4835 * $VAR environment variable
4836 * (expression) nested expression
4837 * [expr, expr] List
4838 * {key: val, key: val} Dictionary
4840 * Also handle:
4841 * ! in front logical NOT
4842 * - in front unary minus
4843 * + in front unary plus (ignored)
4844 * trailing [] subscript in String or List
4845 * trailing .name entry in Dictionary
4847 * "arg" must point to the first non-white of the expression.
4848 * "arg" is advanced to the next non-white after the recognized expression.
4850 * Return OK or FAIL.
4852 static int
4853 eval7(arg, rettv, evaluate, want_string)
4854 char_u **arg;
4855 typval_T *rettv;
4856 int evaluate;
4857 int want_string; /* after "." operator */
4859 long n;
4860 int len;
4861 char_u *s;
4862 char_u *start_leader, *end_leader;
4863 int ret = OK;
4864 char_u *alias;
4867 * Initialise variable so that clear_tv() can't mistake this for a
4868 * string and free a string that isn't there.
4870 rettv->v_type = VAR_UNKNOWN;
4873 * Skip '!' and '-' characters. They are handled later.
4875 start_leader = *arg;
4876 while (**arg == '!' || **arg == '-' || **arg == '+')
4877 *arg = skipwhite(*arg + 1);
4878 end_leader = *arg;
4880 switch (**arg)
4883 * Number constant.
4885 case '0':
4886 case '1':
4887 case '2':
4888 case '3':
4889 case '4':
4890 case '5':
4891 case '6':
4892 case '7':
4893 case '8':
4894 case '9':
4896 #ifdef FEAT_FLOAT
4897 char_u *p = skipdigits(*arg + 1);
4898 int get_float = FALSE;
4900 /* We accept a float when the format matches
4901 * "[0-9]\+\.[0-9]\+\([eE][+-]\?[0-9]\+\)\?". This is very
4902 * strict to avoid backwards compatibility problems.
4903 * Don't look for a float after the "." operator, so that
4904 * ":let vers = 1.2.3" doesn't fail. */
4905 if (!want_string && p[0] == '.' && vim_isdigit(p[1]))
4907 get_float = TRUE;
4908 p = skipdigits(p + 2);
4909 if (*p == 'e' || *p == 'E')
4911 ++p;
4912 if (*p == '-' || *p == '+')
4913 ++p;
4914 if (!vim_isdigit(*p))
4915 get_float = FALSE;
4916 else
4917 p = skipdigits(p + 1);
4919 if (ASCII_ISALPHA(*p) || *p == '.')
4920 get_float = FALSE;
4922 if (get_float)
4924 float_T f;
4926 *arg += string2float(*arg, &f);
4927 if (evaluate)
4929 rettv->v_type = VAR_FLOAT;
4930 rettv->vval.v_float = f;
4933 else
4934 #endif
4936 vim_str2nr(*arg, NULL, &len, TRUE, TRUE, &n, NULL);
4937 *arg += len;
4938 if (evaluate)
4940 rettv->v_type = VAR_NUMBER;
4941 rettv->vval.v_number = n;
4944 break;
4948 * String constant: "string".
4950 case '"': ret = get_string_tv(arg, rettv, evaluate);
4951 break;
4954 * Literal string constant: 'str''ing'.
4956 case '\'': ret = get_lit_string_tv(arg, rettv, evaluate);
4957 break;
4960 * List: [expr, expr]
4962 case '[': ret = get_list_tv(arg, rettv, evaluate);
4963 break;
4966 * Dictionary: {key: val, key: val}
4968 case '{': ret = get_dict_tv(arg, rettv, evaluate);
4969 break;
4972 * Option value: &name
4974 case '&': ret = get_option_tv(arg, rettv, evaluate);
4975 break;
4978 * Environment variable: $VAR.
4980 case '$': ret = get_env_tv(arg, rettv, evaluate);
4981 break;
4984 * Register contents: @r.
4986 case '@': ++*arg;
4987 if (evaluate)
4989 rettv->v_type = VAR_STRING;
4990 rettv->vval.v_string = get_reg_contents(**arg, TRUE, TRUE);
4992 if (**arg != NUL)
4993 ++*arg;
4994 break;
4997 * nested expression: (expression).
4999 case '(': *arg = skipwhite(*arg + 1);
5000 ret = eval1(arg, rettv, evaluate); /* recursive! */
5001 if (**arg == ')')
5002 ++*arg;
5003 else if (ret == OK)
5005 EMSG(_("E110: Missing ')'"));
5006 clear_tv(rettv);
5007 ret = FAIL;
5009 break;
5011 default: ret = NOTDONE;
5012 break;
5015 if (ret == NOTDONE)
5018 * Must be a variable or function name.
5019 * Can also be a curly-braces kind of name: {expr}.
5021 s = *arg;
5022 len = get_name_len(arg, &alias, evaluate, TRUE);
5023 if (alias != NULL)
5024 s = alias;
5026 if (len <= 0)
5027 ret = FAIL;
5028 else
5030 if (**arg == '(') /* recursive! */
5032 /* If "s" is the name of a variable of type VAR_FUNC
5033 * use its contents. */
5034 s = deref_func_name(s, &len);
5036 /* Invoke the function. */
5037 ret = get_func_tv(s, len, rettv, arg,
5038 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
5039 &len, evaluate, NULL);
5040 /* Stop the expression evaluation when immediately
5041 * aborting on error, or when an interrupt occurred or
5042 * an exception was thrown but not caught. */
5043 if (aborting())
5045 if (ret == OK)
5046 clear_tv(rettv);
5047 ret = FAIL;
5050 else if (evaluate)
5051 ret = get_var_tv(s, len, rettv, TRUE);
5052 else
5053 ret = OK;
5056 if (alias != NULL)
5057 vim_free(alias);
5060 *arg = skipwhite(*arg);
5062 /* Handle following '[', '(' and '.' for expr[expr], expr.name,
5063 * expr(expr). */
5064 if (ret == OK)
5065 ret = handle_subscript(arg, rettv, evaluate, TRUE);
5068 * Apply logical NOT and unary '-', from right to left, ignore '+'.
5070 if (ret == OK && evaluate && end_leader > start_leader)
5072 int error = FALSE;
5073 int val = 0;
5074 #ifdef FEAT_FLOAT
5075 float_T f = 0.0;
5077 if (rettv->v_type == VAR_FLOAT)
5078 f = rettv->vval.v_float;
5079 else
5080 #endif
5081 val = get_tv_number_chk(rettv, &error);
5082 if (error)
5084 clear_tv(rettv);
5085 ret = FAIL;
5087 else
5089 while (end_leader > start_leader)
5091 --end_leader;
5092 if (*end_leader == '!')
5094 #ifdef FEAT_FLOAT
5095 if (rettv->v_type == VAR_FLOAT)
5096 f = !f;
5097 else
5098 #endif
5099 val = !val;
5101 else if (*end_leader == '-')
5103 #ifdef FEAT_FLOAT
5104 if (rettv->v_type == VAR_FLOAT)
5105 f = -f;
5106 else
5107 #endif
5108 val = -val;
5111 #ifdef FEAT_FLOAT
5112 if (rettv->v_type == VAR_FLOAT)
5114 clear_tv(rettv);
5115 rettv->vval.v_float = f;
5117 else
5118 #endif
5120 clear_tv(rettv);
5121 rettv->v_type = VAR_NUMBER;
5122 rettv->vval.v_number = val;
5127 return ret;
5131 * Evaluate an "[expr]" or "[expr:expr]" index. Also "dict.key".
5132 * "*arg" points to the '[' or '.'.
5133 * Returns FAIL or OK. "*arg" is advanced to after the ']'.
5135 static int
5136 eval_index(arg, rettv, evaluate, verbose)
5137 char_u **arg;
5138 typval_T *rettv;
5139 int evaluate;
5140 int verbose; /* give error messages */
5142 int empty1 = FALSE, empty2 = FALSE;
5143 typval_T var1, var2;
5144 long n1, n2 = 0;
5145 long len = -1;
5146 int range = FALSE;
5147 char_u *s;
5148 char_u *key = NULL;
5150 if (rettv->v_type == VAR_FUNC
5151 #ifdef FEAT_FLOAT
5152 || rettv->v_type == VAR_FLOAT
5153 #endif
5156 if (verbose)
5157 EMSG(_("E695: Cannot index a Funcref"));
5158 return FAIL;
5161 if (**arg == '.')
5164 * dict.name
5166 key = *arg + 1;
5167 for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
5169 if (len == 0)
5170 return FAIL;
5171 *arg = skipwhite(key + len);
5173 else
5176 * something[idx]
5178 * Get the (first) variable from inside the [].
5180 *arg = skipwhite(*arg + 1);
5181 if (**arg == ':')
5182 empty1 = TRUE;
5183 else if (eval1(arg, &var1, evaluate) == FAIL) /* recursive! */
5184 return FAIL;
5185 else if (evaluate && get_tv_string_chk(&var1) == NULL)
5187 /* not a number or string */
5188 clear_tv(&var1);
5189 return FAIL;
5193 * Get the second variable from inside the [:].
5195 if (**arg == ':')
5197 range = TRUE;
5198 *arg = skipwhite(*arg + 1);
5199 if (**arg == ']')
5200 empty2 = TRUE;
5201 else if (eval1(arg, &var2, evaluate) == FAIL) /* recursive! */
5203 if (!empty1)
5204 clear_tv(&var1);
5205 return FAIL;
5207 else if (evaluate && get_tv_string_chk(&var2) == NULL)
5209 /* not a number or string */
5210 if (!empty1)
5211 clear_tv(&var1);
5212 clear_tv(&var2);
5213 return FAIL;
5217 /* Check for the ']'. */
5218 if (**arg != ']')
5220 if (verbose)
5221 EMSG(_(e_missbrac));
5222 clear_tv(&var1);
5223 if (range)
5224 clear_tv(&var2);
5225 return FAIL;
5227 *arg = skipwhite(*arg + 1); /* skip the ']' */
5230 if (evaluate)
5232 n1 = 0;
5233 if (!empty1 && rettv->v_type != VAR_DICT)
5235 n1 = get_tv_number(&var1);
5236 clear_tv(&var1);
5238 if (range)
5240 if (empty2)
5241 n2 = -1;
5242 else
5244 n2 = get_tv_number(&var2);
5245 clear_tv(&var2);
5249 switch (rettv->v_type)
5251 case VAR_NUMBER:
5252 case VAR_STRING:
5253 s = get_tv_string(rettv);
5254 len = (long)STRLEN(s);
5255 if (range)
5257 /* The resulting variable is a substring. If the indexes
5258 * are out of range the result is empty. */
5259 if (n1 < 0)
5261 n1 = len + n1;
5262 if (n1 < 0)
5263 n1 = 0;
5265 if (n2 < 0)
5266 n2 = len + n2;
5267 else if (n2 >= len)
5268 n2 = len;
5269 if (n1 >= len || n2 < 0 || n1 > n2)
5270 s = NULL;
5271 else
5272 s = vim_strnsave(s + n1, (int)(n2 - n1 + 1));
5274 else
5276 /* The resulting variable is a string of a single
5277 * character. If the index is too big or negative the
5278 * result is empty. */
5279 if (n1 >= len || n1 < 0)
5280 s = NULL;
5281 else
5282 s = vim_strnsave(s + n1, 1);
5284 clear_tv(rettv);
5285 rettv->v_type = VAR_STRING;
5286 rettv->vval.v_string = s;
5287 break;
5289 case VAR_LIST:
5290 len = list_len(rettv->vval.v_list);
5291 if (n1 < 0)
5292 n1 = len + n1;
5293 if (!empty1 && (n1 < 0 || n1 >= len))
5295 /* For a range we allow invalid values and return an empty
5296 * list. A list index out of range is an error. */
5297 if (!range)
5299 if (verbose)
5300 EMSGN(_(e_listidx), n1);
5301 return FAIL;
5303 n1 = len;
5305 if (range)
5307 list_T *l;
5308 listitem_T *item;
5310 if (n2 < 0)
5311 n2 = len + n2;
5312 else if (n2 >= len)
5313 n2 = len - 1;
5314 if (!empty2 && (n2 < 0 || n2 + 1 < n1))
5315 n2 = -1;
5316 l = list_alloc();
5317 if (l == NULL)
5318 return FAIL;
5319 for (item = list_find(rettv->vval.v_list, n1);
5320 n1 <= n2; ++n1)
5322 if (list_append_tv(l, &item->li_tv) == FAIL)
5324 list_free(l, TRUE);
5325 return FAIL;
5327 item = item->li_next;
5329 clear_tv(rettv);
5330 rettv->v_type = VAR_LIST;
5331 rettv->vval.v_list = l;
5332 ++l->lv_refcount;
5334 else
5336 copy_tv(&list_find(rettv->vval.v_list, n1)->li_tv, &var1);
5337 clear_tv(rettv);
5338 *rettv = var1;
5340 break;
5342 case VAR_DICT:
5343 if (range)
5345 if (verbose)
5346 EMSG(_(e_dictrange));
5347 if (len == -1)
5348 clear_tv(&var1);
5349 return FAIL;
5352 dictitem_T *item;
5354 if (len == -1)
5356 key = get_tv_string(&var1);
5357 if (*key == NUL)
5359 if (verbose)
5360 EMSG(_(e_emptykey));
5361 clear_tv(&var1);
5362 return FAIL;
5366 item = dict_find(rettv->vval.v_dict, key, (int)len);
5368 if (item == NULL && verbose)
5369 EMSG2(_(e_dictkey), key);
5370 if (len == -1)
5371 clear_tv(&var1);
5372 if (item == NULL)
5373 return FAIL;
5375 copy_tv(&item->di_tv, &var1);
5376 clear_tv(rettv);
5377 *rettv = var1;
5379 break;
5383 return OK;
5387 * Get an option value.
5388 * "arg" points to the '&' or '+' before the option name.
5389 * "arg" is advanced to character after the option name.
5390 * Return OK or FAIL.
5392 static int
5393 get_option_tv(arg, rettv, evaluate)
5394 char_u **arg;
5395 typval_T *rettv; /* when NULL, only check if option exists */
5396 int evaluate;
5398 char_u *option_end;
5399 long numval;
5400 char_u *stringval;
5401 int opt_type;
5402 int c;
5403 int working = (**arg == '+'); /* has("+option") */
5404 int ret = OK;
5405 int opt_flags;
5408 * Isolate the option name and find its value.
5410 option_end = find_option_end(arg, &opt_flags);
5411 if (option_end == NULL)
5413 if (rettv != NULL)
5414 EMSG2(_("E112: Option name missing: %s"), *arg);
5415 return FAIL;
5418 if (!evaluate)
5420 *arg = option_end;
5421 return OK;
5424 c = *option_end;
5425 *option_end = NUL;
5426 opt_type = get_option_value(*arg, &numval,
5427 rettv == NULL ? NULL : &stringval, opt_flags);
5429 if (opt_type == -3) /* invalid name */
5431 if (rettv != NULL)
5432 EMSG2(_("E113: Unknown option: %s"), *arg);
5433 ret = FAIL;
5435 else if (rettv != NULL)
5437 if (opt_type == -2) /* hidden string option */
5439 rettv->v_type = VAR_STRING;
5440 rettv->vval.v_string = NULL;
5442 else if (opt_type == -1) /* hidden number option */
5444 rettv->v_type = VAR_NUMBER;
5445 rettv->vval.v_number = 0;
5447 else if (opt_type == 1) /* number option */
5449 rettv->v_type = VAR_NUMBER;
5450 rettv->vval.v_number = numval;
5452 else /* string option */
5454 rettv->v_type = VAR_STRING;
5455 rettv->vval.v_string = stringval;
5458 else if (working && (opt_type == -2 || opt_type == -1))
5459 ret = FAIL;
5461 *option_end = c; /* put back for error messages */
5462 *arg = option_end;
5464 return ret;
5468 * Allocate a variable for a string constant.
5469 * Return OK or FAIL.
5471 static int
5472 get_string_tv(arg, rettv, evaluate)
5473 char_u **arg;
5474 typval_T *rettv;
5475 int evaluate;
5477 char_u *p;
5478 char_u *name;
5479 int extra = 0;
5482 * Find the end of the string, skipping backslashed characters.
5484 for (p = *arg + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
5486 if (*p == '\\' && p[1] != NUL)
5488 ++p;
5489 /* A "\<x>" form occupies at least 4 characters, and produces up
5490 * to 6 characters: reserve space for 2 extra */
5491 if (*p == '<')
5492 extra += 2;
5496 if (*p != '"')
5498 EMSG2(_("E114: Missing quote: %s"), *arg);
5499 return FAIL;
5502 /* If only parsing, set *arg and return here */
5503 if (!evaluate)
5505 *arg = p + 1;
5506 return OK;
5510 * Copy the string into allocated memory, handling backslashed
5511 * characters.
5513 name = alloc((unsigned)(p - *arg + extra));
5514 if (name == NULL)
5515 return FAIL;
5516 rettv->v_type = VAR_STRING;
5517 rettv->vval.v_string = name;
5519 for (p = *arg + 1; *p != NUL && *p != '"'; )
5521 if (*p == '\\')
5523 switch (*++p)
5525 case 'b': *name++ = BS; ++p; break;
5526 case 'e': *name++ = ESC; ++p; break;
5527 case 'f': *name++ = FF; ++p; break;
5528 case 'n': *name++ = NL; ++p; break;
5529 case 'r': *name++ = CAR; ++p; break;
5530 case 't': *name++ = TAB; ++p; break;
5532 case 'X': /* hex: "\x1", "\x12" */
5533 case 'x':
5534 case 'u': /* Unicode: "\u0023" */
5535 case 'U':
5536 if (vim_isxdigit(p[1]))
5538 int n, nr;
5539 int c = toupper(*p);
5541 if (c == 'X')
5542 n = 2;
5543 else
5544 n = 4;
5545 nr = 0;
5546 while (--n >= 0 && vim_isxdigit(p[1]))
5548 ++p;
5549 nr = (nr << 4) + hex2nr(*p);
5551 ++p;
5552 #ifdef FEAT_MBYTE
5553 /* For "\u" store the number according to
5554 * 'encoding'. */
5555 if (c != 'X')
5556 name += (*mb_char2bytes)(nr, name);
5557 else
5558 #endif
5559 *name++ = nr;
5561 break;
5563 /* octal: "\1", "\12", "\123" */
5564 case '0':
5565 case '1':
5566 case '2':
5567 case '3':
5568 case '4':
5569 case '5':
5570 case '6':
5571 case '7': *name = *p++ - '0';
5572 if (*p >= '0' && *p <= '7')
5574 *name = (*name << 3) + *p++ - '0';
5575 if (*p >= '0' && *p <= '7')
5576 *name = (*name << 3) + *p++ - '0';
5578 ++name;
5579 break;
5581 /* Special key, e.g.: "\<C-W>" */
5582 case '<': extra = trans_special(&p, name, TRUE);
5583 if (extra != 0)
5585 name += extra;
5586 break;
5588 /* FALLTHROUGH */
5590 default: MB_COPY_CHAR(p, name);
5591 break;
5594 else
5595 MB_COPY_CHAR(p, name);
5598 *name = NUL;
5599 *arg = p + 1;
5601 return OK;
5605 * Allocate a variable for a 'str''ing' constant.
5606 * Return OK or FAIL.
5608 static int
5609 get_lit_string_tv(arg, rettv, evaluate)
5610 char_u **arg;
5611 typval_T *rettv;
5612 int evaluate;
5614 char_u *p;
5615 char_u *str;
5616 int reduce = 0;
5619 * Find the end of the string, skipping ''.
5621 for (p = *arg + 1; *p != NUL; mb_ptr_adv(p))
5623 if (*p == '\'')
5625 if (p[1] != '\'')
5626 break;
5627 ++reduce;
5628 ++p;
5632 if (*p != '\'')
5634 EMSG2(_("E115: Missing quote: %s"), *arg);
5635 return FAIL;
5638 /* If only parsing return after setting "*arg" */
5639 if (!evaluate)
5641 *arg = p + 1;
5642 return OK;
5646 * Copy the string into allocated memory, handling '' to ' reduction.
5648 str = alloc((unsigned)((p - *arg) - reduce));
5649 if (str == NULL)
5650 return FAIL;
5651 rettv->v_type = VAR_STRING;
5652 rettv->vval.v_string = str;
5654 for (p = *arg + 1; *p != NUL; )
5656 if (*p == '\'')
5658 if (p[1] != '\'')
5659 break;
5660 ++p;
5662 MB_COPY_CHAR(p, str);
5664 *str = NUL;
5665 *arg = p + 1;
5667 return OK;
5671 * Allocate a variable for a List and fill it from "*arg".
5672 * Return OK or FAIL.
5674 static int
5675 get_list_tv(arg, rettv, evaluate)
5676 char_u **arg;
5677 typval_T *rettv;
5678 int evaluate;
5680 list_T *l = NULL;
5681 typval_T tv;
5682 listitem_T *item;
5684 if (evaluate)
5686 l = list_alloc();
5687 if (l == NULL)
5688 return FAIL;
5691 *arg = skipwhite(*arg + 1);
5692 while (**arg != ']' && **arg != NUL)
5694 if (eval1(arg, &tv, evaluate) == FAIL) /* recursive! */
5695 goto failret;
5696 if (evaluate)
5698 item = listitem_alloc();
5699 if (item != NULL)
5701 item->li_tv = tv;
5702 item->li_tv.v_lock = 0;
5703 list_append(l, item);
5705 else
5706 clear_tv(&tv);
5709 if (**arg == ']')
5710 break;
5711 if (**arg != ',')
5713 EMSG2(_("E696: Missing comma in List: %s"), *arg);
5714 goto failret;
5716 *arg = skipwhite(*arg + 1);
5719 if (**arg != ']')
5721 EMSG2(_("E697: Missing end of List ']': %s"), *arg);
5722 failret:
5723 if (evaluate)
5724 list_free(l, TRUE);
5725 return FAIL;
5728 *arg = skipwhite(*arg + 1);
5729 if (evaluate)
5731 rettv->v_type = VAR_LIST;
5732 rettv->vval.v_list = l;
5733 ++l->lv_refcount;
5736 return OK;
5740 * Allocate an empty header for a list.
5741 * Caller should take care of the reference count.
5743 list_T *
5744 list_alloc()
5746 list_T *l;
5748 l = (list_T *)alloc_clear(sizeof(list_T));
5749 if (l != NULL)
5751 /* Prepend the list to the list of lists for garbage collection. */
5752 if (first_list != NULL)
5753 first_list->lv_used_prev = l;
5754 l->lv_used_prev = NULL;
5755 l->lv_used_next = first_list;
5756 first_list = l;
5758 return l;
5762 * Allocate an empty list for a return value.
5763 * Returns OK or FAIL.
5765 static int
5766 rettv_list_alloc(rettv)
5767 typval_T *rettv;
5769 list_T *l = list_alloc();
5771 if (l == NULL)
5772 return FAIL;
5774 rettv->vval.v_list = l;
5775 rettv->v_type = VAR_LIST;
5776 ++l->lv_refcount;
5777 return OK;
5781 * Unreference a list: decrement the reference count and free it when it
5782 * becomes zero.
5784 void
5785 list_unref(l)
5786 list_T *l;
5788 if (l != NULL && --l->lv_refcount <= 0)
5789 list_free(l, TRUE);
5793 * Free a list, including all items it points to.
5794 * Ignores the reference count.
5796 void
5797 list_free(l, recurse)
5798 list_T *l;
5799 int recurse; /* Free Lists and Dictionaries recursively. */
5801 listitem_T *item;
5803 /* Remove the list from the list of lists for garbage collection. */
5804 if (l->lv_used_prev == NULL)
5805 first_list = l->lv_used_next;
5806 else
5807 l->lv_used_prev->lv_used_next = l->lv_used_next;
5808 if (l->lv_used_next != NULL)
5809 l->lv_used_next->lv_used_prev = l->lv_used_prev;
5811 for (item = l->lv_first; item != NULL; item = l->lv_first)
5813 /* Remove the item before deleting it. */
5814 l->lv_first = item->li_next;
5815 if (recurse || (item->li_tv.v_type != VAR_LIST
5816 && item->li_tv.v_type != VAR_DICT))
5817 clear_tv(&item->li_tv);
5818 vim_free(item);
5820 vim_free(l);
5824 * Allocate a list item.
5826 static listitem_T *
5827 listitem_alloc()
5829 return (listitem_T *)alloc(sizeof(listitem_T));
5833 * Free a list item. Also clears the value. Does not notify watchers.
5835 static void
5836 listitem_free(item)
5837 listitem_T *item;
5839 clear_tv(&item->li_tv);
5840 vim_free(item);
5844 * Remove a list item from a List and free it. Also clears the value.
5846 static void
5847 listitem_remove(l, item)
5848 list_T *l;
5849 listitem_T *item;
5851 list_remove(l, item, item);
5852 listitem_free(item);
5856 * Get the number of items in a list.
5858 static long
5859 list_len(l)
5860 list_T *l;
5862 if (l == NULL)
5863 return 0L;
5864 return l->lv_len;
5868 * Return TRUE when two lists have exactly the same values.
5870 static int
5871 list_equal(l1, l2, ic)
5872 list_T *l1;
5873 list_T *l2;
5874 int ic; /* ignore case for strings */
5876 listitem_T *item1, *item2;
5878 if (l1 == NULL || l2 == NULL)
5879 return FALSE;
5880 if (l1 == l2)
5881 return TRUE;
5882 if (list_len(l1) != list_len(l2))
5883 return FALSE;
5885 for (item1 = l1->lv_first, item2 = l2->lv_first;
5886 item1 != NULL && item2 != NULL;
5887 item1 = item1->li_next, item2 = item2->li_next)
5888 if (!tv_equal(&item1->li_tv, &item2->li_tv, ic))
5889 return FALSE;
5890 return item1 == NULL && item2 == NULL;
5893 #if defined(FEAT_RUBY) || defined(FEAT_PYTHON) || defined(FEAT_MZSCHEME) \
5894 || defined(FEAT_LUA) || defined(PROTO)
5896 * Return the dictitem that an entry in a hashtable points to.
5898 dictitem_T *
5899 dict_lookup(hi)
5900 hashitem_T *hi;
5902 return HI2DI(hi);
5904 #endif
5907 * Return TRUE when two dictionaries have exactly the same key/values.
5909 static int
5910 dict_equal(d1, d2, ic)
5911 dict_T *d1;
5912 dict_T *d2;
5913 int ic; /* ignore case for strings */
5915 hashitem_T *hi;
5916 dictitem_T *item2;
5917 int todo;
5919 if (d1 == NULL || d2 == NULL)
5920 return FALSE;
5921 if (d1 == d2)
5922 return TRUE;
5923 if (dict_len(d1) != dict_len(d2))
5924 return FALSE;
5926 todo = (int)d1->dv_hashtab.ht_used;
5927 for (hi = d1->dv_hashtab.ht_array; todo > 0; ++hi)
5929 if (!HASHITEM_EMPTY(hi))
5931 item2 = dict_find(d2, hi->hi_key, -1);
5932 if (item2 == NULL)
5933 return FALSE;
5934 if (!tv_equal(&HI2DI(hi)->di_tv, &item2->di_tv, ic))
5935 return FALSE;
5936 --todo;
5939 return TRUE;
5943 * Return TRUE if "tv1" and "tv2" have the same value.
5944 * Compares the items just like "==" would compare them, but strings and
5945 * numbers are different. Floats and numbers are also different.
5947 static int
5948 tv_equal(tv1, tv2, ic)
5949 typval_T *tv1;
5950 typval_T *tv2;
5951 int ic; /* ignore case */
5953 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
5954 char_u *s1, *s2;
5955 static int recursive = 0; /* cach recursive loops */
5956 int r;
5958 if (tv1->v_type != tv2->v_type)
5959 return FALSE;
5960 /* Catch lists and dicts that have an endless loop by limiting
5961 * recursiveness to 1000. We guess they are equal then. */
5962 if (recursive >= 1000)
5963 return TRUE;
5965 switch (tv1->v_type)
5967 case VAR_LIST:
5968 ++recursive;
5969 r = list_equal(tv1->vval.v_list, tv2->vval.v_list, ic);
5970 --recursive;
5971 return r;
5973 case VAR_DICT:
5974 ++recursive;
5975 r = dict_equal(tv1->vval.v_dict, tv2->vval.v_dict, ic);
5976 --recursive;
5977 return r;
5979 case VAR_FUNC:
5980 return (tv1->vval.v_string != NULL
5981 && tv2->vval.v_string != NULL
5982 && STRCMP(tv1->vval.v_string, tv2->vval.v_string) == 0);
5984 case VAR_NUMBER:
5985 return tv1->vval.v_number == tv2->vval.v_number;
5987 #ifdef FEAT_FLOAT
5988 case VAR_FLOAT:
5989 return tv1->vval.v_float == tv2->vval.v_float;
5990 #endif
5992 case VAR_STRING:
5993 s1 = get_tv_string_buf(tv1, buf1);
5994 s2 = get_tv_string_buf(tv2, buf2);
5995 return ((ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2)) == 0);
5998 EMSG2(_(e_intern2), "tv_equal()");
5999 return TRUE;
6003 * Locate item with index "n" in list "l" and return it.
6004 * A negative index is counted from the end; -1 is the last item.
6005 * Returns NULL when "n" is out of range.
6007 static listitem_T *
6008 list_find(l, n)
6009 list_T *l;
6010 long n;
6012 listitem_T *item;
6013 long idx;
6015 if (l == NULL)
6016 return NULL;
6018 /* Negative index is relative to the end. */
6019 if (n < 0)
6020 n = l->lv_len + n;
6022 /* Check for index out of range. */
6023 if (n < 0 || n >= l->lv_len)
6024 return NULL;
6026 /* When there is a cached index may start search from there. */
6027 if (l->lv_idx_item != NULL)
6029 if (n < l->lv_idx / 2)
6031 /* closest to the start of the list */
6032 item = l->lv_first;
6033 idx = 0;
6035 else if (n > (l->lv_idx + l->lv_len) / 2)
6037 /* closest to the end of the list */
6038 item = l->lv_last;
6039 idx = l->lv_len - 1;
6041 else
6043 /* closest to the cached index */
6044 item = l->lv_idx_item;
6045 idx = l->lv_idx;
6048 else
6050 if (n < l->lv_len / 2)
6052 /* closest to the start of the list */
6053 item = l->lv_first;
6054 idx = 0;
6056 else
6058 /* closest to the end of the list */
6059 item = l->lv_last;
6060 idx = l->lv_len - 1;
6064 while (n > idx)
6066 /* search forward */
6067 item = item->li_next;
6068 ++idx;
6070 while (n < idx)
6072 /* search backward */
6073 item = item->li_prev;
6074 --idx;
6077 /* cache the used index */
6078 l->lv_idx = idx;
6079 l->lv_idx_item = item;
6081 return item;
6085 * Get list item "l[idx]" as a number.
6087 static long
6088 list_find_nr(l, idx, errorp)
6089 list_T *l;
6090 long idx;
6091 int *errorp; /* set to TRUE when something wrong */
6093 listitem_T *li;
6095 li = list_find(l, idx);
6096 if (li == NULL)
6098 if (errorp != NULL)
6099 *errorp = TRUE;
6100 return -1L;
6102 return get_tv_number_chk(&li->li_tv, errorp);
6106 * Get list item "l[idx - 1]" as a string. Returns NULL for failure.
6108 char_u *
6109 list_find_str(l, idx)
6110 list_T *l;
6111 long idx;
6113 listitem_T *li;
6115 li = list_find(l, idx - 1);
6116 if (li == NULL)
6118 EMSGN(_(e_listidx), idx);
6119 return NULL;
6121 return get_tv_string(&li->li_tv);
6125 * Locate "item" list "l" and return its index.
6126 * Returns -1 when "item" is not in the list.
6128 static long
6129 list_idx_of_item(l, item)
6130 list_T *l;
6131 listitem_T *item;
6133 long idx = 0;
6134 listitem_T *li;
6136 if (l == NULL)
6137 return -1;
6138 idx = 0;
6139 for (li = l->lv_first; li != NULL && li != item; li = li->li_next)
6140 ++idx;
6141 if (li == NULL)
6142 return -1;
6143 return idx;
6147 * Append item "item" to the end of list "l".
6149 static void
6150 list_append(l, item)
6151 list_T *l;
6152 listitem_T *item;
6154 if (l->lv_last == NULL)
6156 /* empty list */
6157 l->lv_first = item;
6158 l->lv_last = item;
6159 item->li_prev = NULL;
6161 else
6163 l->lv_last->li_next = item;
6164 item->li_prev = l->lv_last;
6165 l->lv_last = item;
6167 ++l->lv_len;
6168 item->li_next = NULL;
6172 * Append typval_T "tv" to the end of list "l".
6173 * Return FAIL when out of memory.
6176 list_append_tv(l, tv)
6177 list_T *l;
6178 typval_T *tv;
6180 listitem_T *li = listitem_alloc();
6182 if (li == NULL)
6183 return FAIL;
6184 copy_tv(tv, &li->li_tv);
6185 list_append(l, li);
6186 return OK;
6190 * Add a dictionary to a list. Used by getqflist().
6191 * Return FAIL when out of memory.
6194 list_append_dict(list, dict)
6195 list_T *list;
6196 dict_T *dict;
6198 listitem_T *li = listitem_alloc();
6200 if (li == NULL)
6201 return FAIL;
6202 li->li_tv.v_type = VAR_DICT;
6203 li->li_tv.v_lock = 0;
6204 li->li_tv.vval.v_dict = dict;
6205 list_append(list, li);
6206 ++dict->dv_refcount;
6207 return OK;
6211 * Make a copy of "str" and append it as an item to list "l".
6212 * When "len" >= 0 use "str[len]".
6213 * Returns FAIL when out of memory.
6216 list_append_string(l, str, len)
6217 list_T *l;
6218 char_u *str;
6219 int len;
6221 listitem_T *li = listitem_alloc();
6223 if (li == NULL)
6224 return FAIL;
6225 list_append(l, li);
6226 li->li_tv.v_type = VAR_STRING;
6227 li->li_tv.v_lock = 0;
6228 if (str == NULL)
6229 li->li_tv.vval.v_string = NULL;
6230 else if ((li->li_tv.vval.v_string = (len >= 0 ? vim_strnsave(str, len)
6231 : vim_strsave(str))) == NULL)
6232 return FAIL;
6233 return OK;
6237 * Append "n" to list "l".
6238 * Returns FAIL when out of memory.
6240 static int
6241 list_append_number(l, n)
6242 list_T *l;
6243 varnumber_T n;
6245 listitem_T *li;
6247 li = listitem_alloc();
6248 if (li == NULL)
6249 return FAIL;
6250 li->li_tv.v_type = VAR_NUMBER;
6251 li->li_tv.v_lock = 0;
6252 li->li_tv.vval.v_number = n;
6253 list_append(l, li);
6254 return OK;
6258 * Insert typval_T "tv" in list "l" before "item".
6259 * If "item" is NULL append at the end.
6260 * Return FAIL when out of memory.
6262 static int
6263 list_insert_tv(l, tv, item)
6264 list_T *l;
6265 typval_T *tv;
6266 listitem_T *item;
6268 listitem_T *ni = listitem_alloc();
6270 if (ni == NULL)
6271 return FAIL;
6272 copy_tv(tv, &ni->li_tv);
6273 if (item == NULL)
6274 /* Append new item at end of list. */
6275 list_append(l, ni);
6276 else
6278 /* Insert new item before existing item. */
6279 ni->li_prev = item->li_prev;
6280 ni->li_next = item;
6281 if (item->li_prev == NULL)
6283 l->lv_first = ni;
6284 ++l->lv_idx;
6286 else
6288 item->li_prev->li_next = ni;
6289 l->lv_idx_item = NULL;
6291 item->li_prev = ni;
6292 ++l->lv_len;
6294 return OK;
6298 * Extend "l1" with "l2".
6299 * If "bef" is NULL append at the end, otherwise insert before this item.
6300 * Returns FAIL when out of memory.
6302 static int
6303 list_extend(l1, l2, bef)
6304 list_T *l1;
6305 list_T *l2;
6306 listitem_T *bef;
6308 listitem_T *item;
6309 int todo = l2->lv_len;
6311 /* We also quit the loop when we have inserted the original item count of
6312 * the list, avoid a hang when we extend a list with itself. */
6313 for (item = l2->lv_first; item != NULL && --todo >= 0; item = item->li_next)
6314 if (list_insert_tv(l1, &item->li_tv, bef) == FAIL)
6315 return FAIL;
6316 return OK;
6320 * Concatenate lists "l1" and "l2" into a new list, stored in "tv".
6321 * Return FAIL when out of memory.
6323 static int
6324 list_concat(l1, l2, tv)
6325 list_T *l1;
6326 list_T *l2;
6327 typval_T *tv;
6329 list_T *l;
6331 if (l1 == NULL || l2 == NULL)
6332 return FAIL;
6334 /* make a copy of the first list. */
6335 l = list_copy(l1, FALSE, 0);
6336 if (l == NULL)
6337 return FAIL;
6338 tv->v_type = VAR_LIST;
6339 tv->vval.v_list = l;
6341 /* append all items from the second list */
6342 return list_extend(l, l2, NULL);
6346 * Make a copy of list "orig". Shallow if "deep" is FALSE.
6347 * The refcount of the new list is set to 1.
6348 * See item_copy() for "copyID".
6349 * Returns NULL when out of memory.
6351 static list_T *
6352 list_copy(orig, deep, copyID)
6353 list_T *orig;
6354 int deep;
6355 int copyID;
6357 list_T *copy;
6358 listitem_T *item;
6359 listitem_T *ni;
6361 if (orig == NULL)
6362 return NULL;
6364 copy = list_alloc();
6365 if (copy != NULL)
6367 if (copyID != 0)
6369 /* Do this before adding the items, because one of the items may
6370 * refer back to this list. */
6371 orig->lv_copyID = copyID;
6372 orig->lv_copylist = copy;
6374 for (item = orig->lv_first; item != NULL && !got_int;
6375 item = item->li_next)
6377 ni = listitem_alloc();
6378 if (ni == NULL)
6379 break;
6380 if (deep)
6382 if (item_copy(&item->li_tv, &ni->li_tv, deep, copyID) == FAIL)
6384 vim_free(ni);
6385 break;
6388 else
6389 copy_tv(&item->li_tv, &ni->li_tv);
6390 list_append(copy, ni);
6392 ++copy->lv_refcount;
6393 if (item != NULL)
6395 list_unref(copy);
6396 copy = NULL;
6400 return copy;
6404 * Remove items "item" to "item2" from list "l".
6405 * Does not free the listitem or the value!
6407 static void
6408 list_remove(l, item, item2)
6409 list_T *l;
6410 listitem_T *item;
6411 listitem_T *item2;
6413 listitem_T *ip;
6415 /* notify watchers */
6416 for (ip = item; ip != NULL; ip = ip->li_next)
6418 --l->lv_len;
6419 list_fix_watch(l, ip);
6420 if (ip == item2)
6421 break;
6424 if (item2->li_next == NULL)
6425 l->lv_last = item->li_prev;
6426 else
6427 item2->li_next->li_prev = item->li_prev;
6428 if (item->li_prev == NULL)
6429 l->lv_first = item2->li_next;
6430 else
6431 item->li_prev->li_next = item2->li_next;
6432 l->lv_idx_item = NULL;
6436 * Return an allocated string with the string representation of a list.
6437 * May return NULL.
6439 static char_u *
6440 list2string(tv, copyID)
6441 typval_T *tv;
6442 int copyID;
6444 garray_T ga;
6446 if (tv->vval.v_list == NULL)
6447 return NULL;
6448 ga_init2(&ga, (int)sizeof(char), 80);
6449 ga_append(&ga, '[');
6450 if (list_join(&ga, tv->vval.v_list, (char_u *)", ", FALSE, copyID) == FAIL)
6452 vim_free(ga.ga_data);
6453 return NULL;
6455 ga_append(&ga, ']');
6456 ga_append(&ga, NUL);
6457 return (char_u *)ga.ga_data;
6461 * Join list "l" into a string in "*gap", using separator "sep".
6462 * When "echo" is TRUE use String as echoed, otherwise as inside a List.
6463 * Return FAIL or OK.
6465 static int
6466 list_join(gap, l, sep, echo, copyID)
6467 garray_T *gap;
6468 list_T *l;
6469 char_u *sep;
6470 int echo;
6471 int copyID;
6473 int first = TRUE;
6474 char_u *tofree;
6475 char_u numbuf[NUMBUFLEN];
6476 listitem_T *item;
6477 char_u *s;
6479 for (item = l->lv_first; item != NULL && !got_int; item = item->li_next)
6481 if (first)
6482 first = FALSE;
6483 else
6484 ga_concat(gap, sep);
6486 if (echo)
6487 s = echo_string(&item->li_tv, &tofree, numbuf, copyID);
6488 else
6489 s = tv2string(&item->li_tv, &tofree, numbuf, copyID);
6490 if (s != NULL)
6491 ga_concat(gap, s);
6492 vim_free(tofree);
6493 if (s == NULL)
6494 return FAIL;
6495 line_breakcheck();
6497 return OK;
6501 * Garbage collection for lists and dictionaries.
6503 * We use reference counts to be able to free most items right away when they
6504 * are no longer used. But for composite items it's possible that it becomes
6505 * unused while the reference count is > 0: When there is a recursive
6506 * reference. Example:
6507 * :let l = [1, 2, 3]
6508 * :let d = {9: l}
6509 * :let l[1] = d
6511 * Since this is quite unusual we handle this with garbage collection: every
6512 * once in a while find out which lists and dicts are not referenced from any
6513 * variable.
6515 * Here is a good reference text about garbage collection (refers to Python
6516 * but it applies to all reference-counting mechanisms):
6517 * http://python.ca/nas/python/gc/
6521 * Do garbage collection for lists and dicts.
6522 * Return TRUE if some memory was freed.
6525 garbage_collect()
6527 int copyID;
6528 buf_T *buf;
6529 win_T *wp;
6530 int i;
6531 funccall_T *fc, **pfc;
6532 int did_free;
6533 int did_free_funccal = FALSE;
6534 #ifdef FEAT_WINDOWS
6535 tabpage_T *tp;
6536 #endif
6538 /* Only do this once. */
6539 want_garbage_collect = FALSE;
6540 may_garbage_collect = FALSE;
6541 garbage_collect_at_exit = FALSE;
6543 /* We advance by two because we add one for items referenced through
6544 * previous_funccal. */
6545 current_copyID += COPYID_INC;
6546 copyID = current_copyID;
6549 * 1. Go through all accessible variables and mark all lists and dicts
6550 * with copyID.
6553 /* Don't free variables in the previous_funccal list unless they are only
6554 * referenced through previous_funccal. This must be first, because if
6555 * the item is referenced elsewhere the funccal must not be freed. */
6556 for (fc = previous_funccal; fc != NULL; fc = fc->caller)
6558 set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID + 1);
6559 set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID + 1);
6562 /* script-local variables */
6563 for (i = 1; i <= ga_scripts.ga_len; ++i)
6564 set_ref_in_ht(&SCRIPT_VARS(i), copyID);
6566 /* buffer-local variables */
6567 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
6568 set_ref_in_ht(&buf->b_vars.dv_hashtab, copyID);
6570 /* window-local variables */
6571 FOR_ALL_TAB_WINDOWS(tp, wp)
6572 set_ref_in_ht(&wp->w_vars.dv_hashtab, copyID);
6574 #ifdef FEAT_WINDOWS
6575 /* tabpage-local variables */
6576 for (tp = first_tabpage; tp != NULL; tp = tp->tp_next)
6577 set_ref_in_ht(&tp->tp_vars.dv_hashtab, copyID);
6578 #endif
6580 /* global variables */
6581 set_ref_in_ht(&globvarht, copyID);
6583 /* function-local variables */
6584 for (fc = current_funccal; fc != NULL; fc = fc->caller)
6586 set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID);
6587 set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID);
6590 /* v: vars */
6591 set_ref_in_ht(&vimvarht, copyID);
6594 * 2. Free lists and dictionaries that are not referenced.
6596 did_free = free_unref_items(copyID);
6599 * 3. Check if any funccal can be freed now.
6601 for (pfc = &previous_funccal; *pfc != NULL; )
6603 if (can_free_funccal(*pfc, copyID))
6605 fc = *pfc;
6606 *pfc = fc->caller;
6607 free_funccal(fc, TRUE);
6608 did_free = TRUE;
6609 did_free_funccal = TRUE;
6611 else
6612 pfc = &(*pfc)->caller;
6614 if (did_free_funccal)
6615 /* When a funccal was freed some more items might be garbage
6616 * collected, so run again. */
6617 (void)garbage_collect();
6619 return did_free;
6623 * Free lists and dictionaries that are no longer referenced.
6625 static int
6626 free_unref_items(copyID)
6627 int copyID;
6629 dict_T *dd;
6630 list_T *ll;
6631 int did_free = FALSE;
6634 * Go through the list of dicts and free items without the copyID.
6636 for (dd = first_dict; dd != NULL; )
6637 if ((dd->dv_copyID & COPYID_MASK) != (copyID & COPYID_MASK))
6639 /* Free the Dictionary and ordinary items it contains, but don't
6640 * recurse into Lists and Dictionaries, they will be in the list
6641 * of dicts or list of lists. */
6642 dict_free(dd, FALSE);
6643 did_free = TRUE;
6645 /* restart, next dict may also have been freed */
6646 dd = first_dict;
6648 else
6649 dd = dd->dv_used_next;
6652 * Go through the list of lists and free items without the copyID.
6653 * But don't free a list that has a watcher (used in a for loop), these
6654 * are not referenced anywhere.
6656 for (ll = first_list; ll != NULL; )
6657 if ((ll->lv_copyID & COPYID_MASK) != (copyID & COPYID_MASK)
6658 && ll->lv_watch == NULL)
6660 /* Free the List and ordinary items it contains, but don't recurse
6661 * into Lists and Dictionaries, they will be in the list of dicts
6662 * or list of lists. */
6663 list_free(ll, FALSE);
6664 did_free = TRUE;
6666 /* restart, next list may also have been freed */
6667 ll = first_list;
6669 else
6670 ll = ll->lv_used_next;
6672 return did_free;
6676 * Mark all lists and dicts referenced through hashtab "ht" with "copyID".
6678 static void
6679 set_ref_in_ht(ht, copyID)
6680 hashtab_T *ht;
6681 int copyID;
6683 int todo;
6684 hashitem_T *hi;
6686 todo = (int)ht->ht_used;
6687 for (hi = ht->ht_array; todo > 0; ++hi)
6688 if (!HASHITEM_EMPTY(hi))
6690 --todo;
6691 set_ref_in_item(&HI2DI(hi)->di_tv, copyID);
6696 * Mark all lists and dicts referenced through list "l" with "copyID".
6698 static void
6699 set_ref_in_list(l, copyID)
6700 list_T *l;
6701 int copyID;
6703 listitem_T *li;
6705 for (li = l->lv_first; li != NULL; li = li->li_next)
6706 set_ref_in_item(&li->li_tv, copyID);
6710 * Mark all lists and dicts referenced through typval "tv" with "copyID".
6712 static void
6713 set_ref_in_item(tv, copyID)
6714 typval_T *tv;
6715 int copyID;
6717 dict_T *dd;
6718 list_T *ll;
6720 switch (tv->v_type)
6722 case VAR_DICT:
6723 dd = tv->vval.v_dict;
6724 if (dd != NULL && dd->dv_copyID != copyID)
6726 /* Didn't see this dict yet. */
6727 dd->dv_copyID = copyID;
6728 set_ref_in_ht(&dd->dv_hashtab, copyID);
6730 break;
6732 case VAR_LIST:
6733 ll = tv->vval.v_list;
6734 if (ll != NULL && ll->lv_copyID != copyID)
6736 /* Didn't see this list yet. */
6737 ll->lv_copyID = copyID;
6738 set_ref_in_list(ll, copyID);
6740 break;
6742 return;
6746 * Allocate an empty header for a dictionary.
6748 dict_T *
6749 dict_alloc()
6751 dict_T *d;
6753 d = (dict_T *)alloc(sizeof(dict_T));
6754 if (d != NULL)
6756 /* Add the list to the list of dicts for garbage collection. */
6757 if (first_dict != NULL)
6758 first_dict->dv_used_prev = d;
6759 d->dv_used_next = first_dict;
6760 d->dv_used_prev = NULL;
6761 first_dict = d;
6763 hash_init(&d->dv_hashtab);
6764 d->dv_lock = 0;
6765 d->dv_refcount = 0;
6766 d->dv_copyID = 0;
6768 return d;
6772 * Unreference a Dictionary: decrement the reference count and free it when it
6773 * becomes zero.
6775 static void
6776 dict_unref(d)
6777 dict_T *d;
6779 if (d != NULL && --d->dv_refcount <= 0)
6780 dict_free(d, TRUE);
6784 * Free a Dictionary, including all items it contains.
6785 * Ignores the reference count.
6787 static void
6788 dict_free(d, recurse)
6789 dict_T *d;
6790 int recurse; /* Free Lists and Dictionaries recursively. */
6792 int todo;
6793 hashitem_T *hi;
6794 dictitem_T *di;
6796 /* Remove the dict from the list of dicts for garbage collection. */
6797 if (d->dv_used_prev == NULL)
6798 first_dict = d->dv_used_next;
6799 else
6800 d->dv_used_prev->dv_used_next = d->dv_used_next;
6801 if (d->dv_used_next != NULL)
6802 d->dv_used_next->dv_used_prev = d->dv_used_prev;
6804 /* Lock the hashtab, we don't want it to resize while freeing items. */
6805 hash_lock(&d->dv_hashtab);
6806 todo = (int)d->dv_hashtab.ht_used;
6807 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
6809 if (!HASHITEM_EMPTY(hi))
6811 /* Remove the item before deleting it, just in case there is
6812 * something recursive causing trouble. */
6813 di = HI2DI(hi);
6814 hash_remove(&d->dv_hashtab, hi);
6815 if (recurse || (di->di_tv.v_type != VAR_LIST
6816 && di->di_tv.v_type != VAR_DICT))
6817 clear_tv(&di->di_tv);
6818 vim_free(di);
6819 --todo;
6822 hash_clear(&d->dv_hashtab);
6823 vim_free(d);
6827 * Allocate a Dictionary item.
6828 * The "key" is copied to the new item.
6829 * Note that the value of the item "di_tv" still needs to be initialized!
6830 * Returns NULL when out of memory.
6832 dictitem_T *
6833 dictitem_alloc(key)
6834 char_u *key;
6836 dictitem_T *di;
6838 di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T) + STRLEN(key)));
6839 if (di != NULL)
6841 STRCPY(di->di_key, key);
6842 di->di_flags = 0;
6844 return di;
6848 * Make a copy of a Dictionary item.
6850 static dictitem_T *
6851 dictitem_copy(org)
6852 dictitem_T *org;
6854 dictitem_T *di;
6856 di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
6857 + STRLEN(org->di_key)));
6858 if (di != NULL)
6860 STRCPY(di->di_key, org->di_key);
6861 di->di_flags = 0;
6862 copy_tv(&org->di_tv, &di->di_tv);
6864 return di;
6868 * Remove item "item" from Dictionary "dict" and free it.
6870 static void
6871 dictitem_remove(dict, item)
6872 dict_T *dict;
6873 dictitem_T *item;
6875 hashitem_T *hi;
6877 hi = hash_find(&dict->dv_hashtab, item->di_key);
6878 if (HASHITEM_EMPTY(hi))
6879 EMSG2(_(e_intern2), "dictitem_remove()");
6880 else
6881 hash_remove(&dict->dv_hashtab, hi);
6882 dictitem_free(item);
6886 * Free a dict item. Also clears the value.
6888 void
6889 dictitem_free(item)
6890 dictitem_T *item;
6892 clear_tv(&item->di_tv);
6893 vim_free(item);
6897 * Make a copy of dict "d". Shallow if "deep" is FALSE.
6898 * The refcount of the new dict is set to 1.
6899 * See item_copy() for "copyID".
6900 * Returns NULL when out of memory.
6902 static dict_T *
6903 dict_copy(orig, deep, copyID)
6904 dict_T *orig;
6905 int deep;
6906 int copyID;
6908 dict_T *copy;
6909 dictitem_T *di;
6910 int todo;
6911 hashitem_T *hi;
6913 if (orig == NULL)
6914 return NULL;
6916 copy = dict_alloc();
6917 if (copy != NULL)
6919 if (copyID != 0)
6921 orig->dv_copyID = copyID;
6922 orig->dv_copydict = copy;
6924 todo = (int)orig->dv_hashtab.ht_used;
6925 for (hi = orig->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
6927 if (!HASHITEM_EMPTY(hi))
6929 --todo;
6931 di = dictitem_alloc(hi->hi_key);
6932 if (di == NULL)
6933 break;
6934 if (deep)
6936 if (item_copy(&HI2DI(hi)->di_tv, &di->di_tv, deep,
6937 copyID) == FAIL)
6939 vim_free(di);
6940 break;
6943 else
6944 copy_tv(&HI2DI(hi)->di_tv, &di->di_tv);
6945 if (dict_add(copy, di) == FAIL)
6947 dictitem_free(di);
6948 break;
6953 ++copy->dv_refcount;
6954 if (todo > 0)
6956 dict_unref(copy);
6957 copy = NULL;
6961 return copy;
6965 * Add item "item" to Dictionary "d".
6966 * Returns FAIL when out of memory and when key already existed.
6969 dict_add(d, item)
6970 dict_T *d;
6971 dictitem_T *item;
6973 return hash_add(&d->dv_hashtab, item->di_key);
6977 * Add a number or string entry to dictionary "d".
6978 * When "str" is NULL use number "nr", otherwise use "str".
6979 * Returns FAIL when out of memory and when key already exists.
6982 dict_add_nr_str(d, key, nr, str)
6983 dict_T *d;
6984 char *key;
6985 long nr;
6986 char_u *str;
6988 dictitem_T *item;
6990 item = dictitem_alloc((char_u *)key);
6991 if (item == NULL)
6992 return FAIL;
6993 item->di_tv.v_lock = 0;
6994 if (str == NULL)
6996 item->di_tv.v_type = VAR_NUMBER;
6997 item->di_tv.vval.v_number = nr;
6999 else
7001 item->di_tv.v_type = VAR_STRING;
7002 item->di_tv.vval.v_string = vim_strsave(str);
7004 if (dict_add(d, item) == FAIL)
7006 dictitem_free(item);
7007 return FAIL;
7009 return OK;
7012 /* Initializes a data structure used for iterating over dictionary items in
7013 * dict_iterate_next().
7015 void
7016 dict_iterate_start(argvars, iter)
7017 typval_T *argvars;
7018 struct dict_iterator_S *iter;
7020 dict_T *d;
7022 if (argvars[0].v_type != VAR_DICT)
7024 iter->items = 0;
7025 return;
7028 if ((d = argvars[0].vval.v_dict) == NULL)
7030 iter->items = 0;
7031 return;
7034 iter->items = (int)d->dv_hashtab.ht_used;
7035 iter->hi = d->dv_hashtab.ht_array;
7038 /* Allows iterating over the items stored in a dictionary.
7039 * Returns the pointer to the key, *tv_result is set to point to the value
7040 * for that key.
7041 * If there are no more items, NULL is returned.
7042 * iter should be initialized with dict_iterate_start() before calling this
7043 * function for the first time.
7045 char_u*
7046 dict_iterate_next(iter, tv_result)
7047 struct dict_iterator_S *iter;
7048 typval_T **tv_result;
7050 dictitem_T *di;
7051 char_u *result;
7053 if (iter->items <= 0)
7054 return NULL;
7056 while (HASHITEM_EMPTY(iter->hi))
7057 ++iter->hi;
7059 di = HI2DI(iter->hi);
7060 result = di->di_key;
7061 *tv_result = &di->di_tv;
7063 --iter->items;
7064 ++iter->hi;
7065 return result;
7069 * Get the number of items in a Dictionary.
7071 static long
7072 dict_len(d)
7073 dict_T *d;
7075 if (d == NULL)
7076 return 0L;
7077 return (long)d->dv_hashtab.ht_used;
7081 * Find item "key[len]" in Dictionary "d".
7082 * If "len" is negative use strlen(key).
7083 * Returns NULL when not found.
7085 dictitem_T *
7086 dict_find(d, key, len)
7087 dict_T *d;
7088 char_u *key;
7089 int len;
7091 #define AKEYLEN 200
7092 char_u buf[AKEYLEN];
7093 char_u *akey;
7094 char_u *tofree = NULL;
7095 hashitem_T *hi;
7097 if (len < 0)
7098 akey = key;
7099 else if (len >= AKEYLEN)
7101 tofree = akey = vim_strnsave(key, len);
7102 if (akey == NULL)
7103 return NULL;
7105 else
7107 /* Avoid a malloc/free by using buf[]. */
7108 vim_strncpy(buf, key, len);
7109 akey = buf;
7112 hi = hash_find(&d->dv_hashtab, akey);
7113 vim_free(tofree);
7114 if (HASHITEM_EMPTY(hi))
7115 return NULL;
7116 return HI2DI(hi);
7120 * Get a string item from a dictionary.
7121 * When "save" is TRUE allocate memory for it.
7122 * Returns NULL if the entry doesn't exist or out of memory.
7124 char_u *
7125 get_dict_string(d, key, save)
7126 dict_T *d;
7127 char_u *key;
7128 int save;
7130 dictitem_T *di;
7131 char_u *s;
7133 di = dict_find(d, key, -1);
7134 if (di == NULL)
7135 return NULL;
7136 s = get_tv_string(&di->di_tv);
7137 if (save && s != NULL)
7138 s = vim_strsave(s);
7139 return s;
7143 * Get a number item from a dictionary.
7144 * Returns 0 if the entry doesn't exist or out of memory.
7146 long
7147 get_dict_number(d, key)
7148 dict_T *d;
7149 char_u *key;
7151 dictitem_T *di;
7153 di = dict_find(d, key, -1);
7154 if (di == NULL)
7155 return 0;
7156 return get_tv_number(&di->di_tv);
7160 * Return an allocated string with the string representation of a Dictionary.
7161 * May return NULL.
7163 static char_u *
7164 dict2string(tv, copyID)
7165 typval_T *tv;
7166 int copyID;
7168 garray_T ga;
7169 int first = TRUE;
7170 char_u *tofree;
7171 char_u numbuf[NUMBUFLEN];
7172 hashitem_T *hi;
7173 char_u *s;
7174 dict_T *d;
7175 int todo;
7177 if ((d = tv->vval.v_dict) == NULL)
7178 return NULL;
7179 ga_init2(&ga, (int)sizeof(char), 80);
7180 ga_append(&ga, '{');
7182 todo = (int)d->dv_hashtab.ht_used;
7183 for (hi = d->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
7185 if (!HASHITEM_EMPTY(hi))
7187 --todo;
7189 if (first)
7190 first = FALSE;
7191 else
7192 ga_concat(&ga, (char_u *)", ");
7194 tofree = string_quote(hi->hi_key, FALSE);
7195 if (tofree != NULL)
7197 ga_concat(&ga, tofree);
7198 vim_free(tofree);
7200 ga_concat(&ga, (char_u *)": ");
7201 s = tv2string(&HI2DI(hi)->di_tv, &tofree, numbuf, copyID);
7202 if (s != NULL)
7203 ga_concat(&ga, s);
7204 vim_free(tofree);
7205 if (s == NULL)
7206 break;
7209 if (todo > 0)
7211 vim_free(ga.ga_data);
7212 return NULL;
7215 ga_append(&ga, '}');
7216 ga_append(&ga, NUL);
7217 return (char_u *)ga.ga_data;
7221 * Allocate a variable for a Dictionary and fill it from "*arg".
7222 * Return OK or FAIL. Returns NOTDONE for {expr}.
7224 static int
7225 get_dict_tv(arg, rettv, evaluate)
7226 char_u **arg;
7227 typval_T *rettv;
7228 int evaluate;
7230 dict_T *d = NULL;
7231 typval_T tvkey;
7232 typval_T tv;
7233 char_u *key = NULL;
7234 dictitem_T *item;
7235 char_u *start = skipwhite(*arg + 1);
7236 char_u buf[NUMBUFLEN];
7239 * First check if it's not a curly-braces thing: {expr}.
7240 * Must do this without evaluating, otherwise a function may be called
7241 * twice. Unfortunately this means we need to call eval1() twice for the
7242 * first item.
7243 * But {} is an empty Dictionary.
7245 if (*start != '}')
7247 if (eval1(&start, &tv, FALSE) == FAIL) /* recursive! */
7248 return FAIL;
7249 if (*start == '}')
7250 return NOTDONE;
7253 if (evaluate)
7255 d = dict_alloc();
7256 if (d == NULL)
7257 return FAIL;
7259 tvkey.v_type = VAR_UNKNOWN;
7260 tv.v_type = VAR_UNKNOWN;
7262 *arg = skipwhite(*arg + 1);
7263 while (**arg != '}' && **arg != NUL)
7265 if (eval1(arg, &tvkey, evaluate) == FAIL) /* recursive! */
7266 goto failret;
7267 if (**arg != ':')
7269 EMSG2(_("E720: Missing colon in Dictionary: %s"), *arg);
7270 clear_tv(&tvkey);
7271 goto failret;
7273 if (evaluate)
7275 key = get_tv_string_buf_chk(&tvkey, buf);
7276 if (key == NULL || *key == NUL)
7278 /* "key" is NULL when get_tv_string_buf_chk() gave an errmsg */
7279 if (key != NULL)
7280 EMSG(_(e_emptykey));
7281 clear_tv(&tvkey);
7282 goto failret;
7286 *arg = skipwhite(*arg + 1);
7287 if (eval1(arg, &tv, evaluate) == FAIL) /* recursive! */
7289 if (evaluate)
7290 clear_tv(&tvkey);
7291 goto failret;
7293 if (evaluate)
7295 item = dict_find(d, key, -1);
7296 if (item != NULL)
7298 EMSG2(_("E721: Duplicate key in Dictionary: \"%s\""), key);
7299 clear_tv(&tvkey);
7300 clear_tv(&tv);
7301 goto failret;
7303 item = dictitem_alloc(key);
7304 clear_tv(&tvkey);
7305 if (item != NULL)
7307 item->di_tv = tv;
7308 item->di_tv.v_lock = 0;
7309 if (dict_add(d, item) == FAIL)
7310 dictitem_free(item);
7314 if (**arg == '}')
7315 break;
7316 if (**arg != ',')
7318 EMSG2(_("E722: Missing comma in Dictionary: %s"), *arg);
7319 goto failret;
7321 *arg = skipwhite(*arg + 1);
7324 if (**arg != '}')
7326 EMSG2(_("E723: Missing end of Dictionary '}': %s"), *arg);
7327 failret:
7328 if (evaluate)
7329 dict_free(d, TRUE);
7330 return FAIL;
7333 *arg = skipwhite(*arg + 1);
7334 if (evaluate)
7336 rettv->v_type = VAR_DICT;
7337 rettv->vval.v_dict = d;
7338 ++d->dv_refcount;
7341 return OK;
7345 * Return a string with the string representation of a variable.
7346 * If the memory is allocated "tofree" is set to it, otherwise NULL.
7347 * "numbuf" is used for a number.
7348 * Does not put quotes around strings, as ":echo" displays values.
7349 * When "copyID" is not NULL replace recursive lists and dicts with "...".
7350 * May return NULL.
7352 static char_u *
7353 echo_string(tv, tofree, numbuf, copyID)
7354 typval_T *tv;
7355 char_u **tofree;
7356 char_u *numbuf;
7357 int copyID;
7359 static int recurse = 0;
7360 char_u *r = NULL;
7362 if (recurse >= DICT_MAXNEST)
7364 EMSG(_("E724: variable nested too deep for displaying"));
7365 *tofree = NULL;
7366 return NULL;
7368 ++recurse;
7370 switch (tv->v_type)
7372 case VAR_FUNC:
7373 *tofree = NULL;
7374 r = tv->vval.v_string;
7375 break;
7377 case VAR_LIST:
7378 if (tv->vval.v_list == NULL)
7380 *tofree = NULL;
7381 r = NULL;
7383 else if (copyID != 0 && tv->vval.v_list->lv_copyID == copyID)
7385 *tofree = NULL;
7386 r = (char_u *)"[...]";
7388 else
7390 tv->vval.v_list->lv_copyID = copyID;
7391 *tofree = list2string(tv, copyID);
7392 r = *tofree;
7394 break;
7396 case VAR_DICT:
7397 if (tv->vval.v_dict == NULL)
7399 *tofree = NULL;
7400 r = NULL;
7402 else if (copyID != 0 && tv->vval.v_dict->dv_copyID == copyID)
7404 *tofree = NULL;
7405 r = (char_u *)"{...}";
7407 else
7409 tv->vval.v_dict->dv_copyID = copyID;
7410 *tofree = dict2string(tv, copyID);
7411 r = *tofree;
7413 break;
7415 case VAR_STRING:
7416 case VAR_NUMBER:
7417 *tofree = NULL;
7418 r = get_tv_string_buf(tv, numbuf);
7419 break;
7421 #ifdef FEAT_FLOAT
7422 case VAR_FLOAT:
7423 *tofree = NULL;
7424 vim_snprintf((char *)numbuf, NUMBUFLEN, "%g", tv->vval.v_float);
7425 r = numbuf;
7426 break;
7427 #endif
7429 default:
7430 EMSG2(_(e_intern2), "echo_string()");
7431 *tofree = NULL;
7434 --recurse;
7435 return r;
7439 * Return a string with the string representation of a variable.
7440 * If the memory is allocated "tofree" is set to it, otherwise NULL.
7441 * "numbuf" is used for a number.
7442 * Puts quotes around strings, so that they can be parsed back by eval().
7443 * May return NULL.
7445 static char_u *
7446 tv2string(tv, tofree, numbuf, copyID)
7447 typval_T *tv;
7448 char_u **tofree;
7449 char_u *numbuf;
7450 int copyID;
7452 switch (tv->v_type)
7454 case VAR_FUNC:
7455 *tofree = string_quote(tv->vval.v_string, TRUE);
7456 return *tofree;
7457 case VAR_STRING:
7458 *tofree = string_quote(tv->vval.v_string, FALSE);
7459 return *tofree;
7460 #ifdef FEAT_FLOAT
7461 case VAR_FLOAT:
7462 *tofree = NULL;
7463 vim_snprintf((char *)numbuf, NUMBUFLEN - 1, "%g", tv->vval.v_float);
7464 return numbuf;
7465 #endif
7466 case VAR_NUMBER:
7467 case VAR_LIST:
7468 case VAR_DICT:
7469 break;
7470 default:
7471 EMSG2(_(e_intern2), "tv2string()");
7473 return echo_string(tv, tofree, numbuf, copyID);
7477 * Return string "str" in ' quotes, doubling ' characters.
7478 * If "str" is NULL an empty string is assumed.
7479 * If "function" is TRUE make it function('string').
7481 static char_u *
7482 string_quote(str, function)
7483 char_u *str;
7484 int function;
7486 unsigned len;
7487 char_u *p, *r, *s;
7489 len = (function ? 13 : 3);
7490 if (str != NULL)
7492 len += (unsigned)STRLEN(str);
7493 for (p = str; *p != NUL; mb_ptr_adv(p))
7494 if (*p == '\'')
7495 ++len;
7497 s = r = alloc(len);
7498 if (r != NULL)
7500 if (function)
7502 STRCPY(r, "function('");
7503 r += 10;
7505 else
7506 *r++ = '\'';
7507 if (str != NULL)
7508 for (p = str; *p != NUL; )
7510 if (*p == '\'')
7511 *r++ = '\'';
7512 MB_COPY_CHAR(p, r);
7514 *r++ = '\'';
7515 if (function)
7516 *r++ = ')';
7517 *r++ = NUL;
7519 return s;
7522 #ifdef FEAT_FLOAT
7524 * Convert the string "text" to a floating point number.
7525 * This uses strtod(). setlocale(LC_NUMERIC, "C") has been used to make sure
7526 * this always uses a decimal point.
7527 * Returns the length of the text that was consumed.
7529 static int
7530 string2float(text, value)
7531 char_u *text;
7532 float_T *value; /* result stored here */
7534 char *s = (char *)text;
7535 float_T f;
7537 f = strtod(s, &s);
7538 *value = f;
7539 return (int)((char_u *)s - text);
7541 #endif
7544 * Get the value of an environment variable.
7545 * "arg" is pointing to the '$'. It is advanced to after the name.
7546 * If the environment variable was not set, silently assume it is empty.
7547 * Always return OK.
7549 static int
7550 get_env_tv(arg, rettv, evaluate)
7551 char_u **arg;
7552 typval_T *rettv;
7553 int evaluate;
7555 char_u *string = NULL;
7556 int len;
7557 int cc;
7558 char_u *name;
7559 int mustfree = FALSE;
7561 ++*arg;
7562 name = *arg;
7563 len = get_env_len(arg);
7564 if (evaluate)
7566 if (len != 0)
7568 cc = name[len];
7569 name[len] = NUL;
7570 /* first try vim_getenv(), fast for normal environment vars */
7571 string = vim_getenv(name, &mustfree);
7572 if (string != NULL && *string != NUL)
7574 if (!mustfree)
7575 string = vim_strsave(string);
7577 else
7579 if (mustfree)
7580 vim_free(string);
7582 /* next try expanding things like $VIM and ${HOME} */
7583 string = expand_env_save(name - 1);
7584 if (string != NULL && *string == '$')
7586 vim_free(string);
7587 string = NULL;
7590 name[len] = cc;
7592 rettv->v_type = VAR_STRING;
7593 rettv->vval.v_string = string;
7596 return OK;
7600 * Array with names and number of arguments of all internal functions
7601 * MUST BE KEPT SORTED IN strcmp() ORDER FOR BINARY SEARCH!
7603 static struct fst
7605 char *f_name; /* function name */
7606 char f_min_argc; /* minimal number of arguments */
7607 char f_max_argc; /* maximal number of arguments */
7608 void (*f_func) __ARGS((typval_T *args, typval_T *rvar));
7609 /* implementation of function */
7610 } functions[] =
7612 #ifdef FEAT_FLOAT
7613 {"abs", 1, 1, f_abs},
7614 {"acos", 1, 1, f_acos}, /* WJMc */
7615 #endif
7616 {"add", 2, 2, f_add},
7617 {"append", 2, 2, f_append},
7618 {"argc", 0, 0, f_argc},
7619 {"argidx", 0, 0, f_argidx},
7620 {"argv", 0, 1, f_argv},
7621 #ifdef FEAT_FLOAT
7622 {"asin", 1, 1, f_asin}, /* WJMc */
7623 {"atan", 1, 1, f_atan},
7624 {"atan2", 2, 2, f_atan2}, /* WJMc */
7625 #endif
7626 {"browse", 4, 4, f_browse},
7627 {"browsedir", 2, 2, f_browsedir},
7628 {"bufexists", 1, 1, f_bufexists},
7629 {"buffer_exists", 1, 1, f_bufexists}, /* obsolete */
7630 {"buffer_name", 1, 1, f_bufname}, /* obsolete */
7631 {"buffer_number", 1, 1, f_bufnr}, /* obsolete */
7632 {"buflisted", 1, 1, f_buflisted},
7633 {"bufloaded", 1, 1, f_bufloaded},
7634 {"bufname", 1, 1, f_bufname},
7635 {"bufnr", 1, 2, f_bufnr},
7636 {"bufwinnr", 1, 1, f_bufwinnr},
7637 {"byte2line", 1, 1, f_byte2line},
7638 {"byteidx", 2, 2, f_byteidx},
7639 {"call", 2, 3, f_call},
7640 #ifdef FEAT_FLOAT
7641 {"ceil", 1, 1, f_ceil},
7642 #endif
7643 {"changenr", 0, 0, f_changenr},
7644 {"char2nr", 1, 1, f_char2nr},
7645 {"cindent", 1, 1, f_cindent},
7646 {"clearmatches", 0, 0, f_clearmatches},
7647 {"col", 1, 1, f_col},
7648 #if defined(FEAT_INS_EXPAND)
7649 {"complete", 2, 2, f_complete},
7650 {"complete_add", 1, 1, f_complete_add},
7651 {"complete_check", 0, 0, f_complete_check},
7652 #endif
7653 {"confirm", 1, 4, f_confirm},
7654 {"copy", 1, 1, f_copy},
7655 #ifdef FEAT_FLOAT
7656 {"cos", 1, 1, f_cos},
7657 {"cosh", 1, 1, f_cosh}, /* WJMc */
7658 #endif
7659 {"count", 2, 4, f_count},
7660 {"cscope_connection",0,3, f_cscope_connection},
7661 {"cursor", 1, 3, f_cursor},
7662 {"deepcopy", 1, 2, f_deepcopy},
7663 {"delete", 1, 1, f_delete},
7664 {"did_filetype", 0, 0, f_did_filetype},
7665 {"diff_filler", 1, 1, f_diff_filler},
7666 {"diff_hlID", 2, 2, f_diff_hlID},
7667 {"empty", 1, 1, f_empty},
7668 {"escape", 2, 2, f_escape},
7669 {"eval", 1, 1, f_eval},
7670 {"eventhandler", 0, 0, f_eventhandler},
7671 {"executable", 1, 1, f_executable},
7672 {"exists", 1, 1, f_exists},
7673 #ifdef FEAT_FLOAT
7674 {"exp", 1, 1, f_exp}, /* WJMc */
7675 #endif
7676 {"expand", 1, 2, f_expand},
7677 {"extend", 2, 3, f_extend},
7678 {"feedkeys", 1, 2, f_feedkeys},
7679 {"file_readable", 1, 1, f_filereadable}, /* obsolete */
7680 {"filereadable", 1, 1, f_filereadable},
7681 {"filewritable", 1, 1, f_filewritable},
7682 {"filter", 2, 2, f_filter},
7683 {"finddir", 1, 3, f_finddir},
7684 {"findfile", 1, 3, f_findfile},
7685 #ifdef FEAT_FLOAT
7686 {"float2nr", 1, 1, f_float2nr},
7687 {"floor", 1, 1, f_floor},
7688 {"fmod", 2, 2, f_fmod}, /* WJMc */
7689 #endif
7690 {"fnameescape", 1, 1, f_fnameescape},
7691 {"fnamemodify", 2, 2, f_fnamemodify},
7692 {"foldclosed", 1, 1, f_foldclosed},
7693 {"foldclosedend", 1, 1, f_foldclosedend},
7694 {"foldlevel", 1, 1, f_foldlevel},
7695 {"foldtext", 0, 0, f_foldtext},
7696 {"foldtextresult", 1, 1, f_foldtextresult},
7697 {"foreground", 0, 0, f_foreground},
7698 {"function", 1, 1, f_function},
7699 {"garbagecollect", 0, 1, f_garbagecollect},
7700 {"get", 2, 3, f_get},
7701 {"getbufline", 2, 3, f_getbufline},
7702 {"getbufvar", 2, 2, f_getbufvar},
7703 {"getchar", 0, 1, f_getchar},
7704 {"getcharmod", 0, 0, f_getcharmod},
7705 {"getcmdline", 0, 0, f_getcmdline},
7706 {"getcmdpos", 0, 0, f_getcmdpos},
7707 {"getcmdtype", 0, 0, f_getcmdtype},
7708 {"getcwd", 0, 0, f_getcwd},
7709 {"getfontname", 0, 1, f_getfontname},
7710 {"getfperm", 1, 1, f_getfperm},
7711 {"getfsize", 1, 1, f_getfsize},
7712 {"getftime", 1, 1, f_getftime},
7713 {"getftype", 1, 1, f_getftype},
7714 {"getline", 1, 2, f_getline},
7715 {"getloclist", 1, 1, f_getqflist},
7716 {"getmatches", 0, 0, f_getmatches},
7717 {"getpid", 0, 0, f_getpid},
7718 {"getpos", 1, 1, f_getpos},
7719 {"getqflist", 0, 0, f_getqflist},
7720 {"getreg", 0, 2, f_getreg},
7721 {"getregtype", 0, 1, f_getregtype},
7722 {"gettabwinvar", 3, 3, f_gettabwinvar},
7723 {"getwinposx", 0, 0, f_getwinposx},
7724 {"getwinposy", 0, 0, f_getwinposy},
7725 {"getwinvar", 2, 2, f_getwinvar},
7726 {"glob", 1, 2, f_glob},
7727 {"globpath", 2, 3, f_globpath},
7728 {"has", 1, 1, f_has},
7729 {"has_key", 2, 2, f_has_key},
7730 {"haslocaldir", 0, 0, f_haslocaldir},
7731 {"hasmapto", 1, 3, f_hasmapto},
7732 {"highlightID", 1, 1, f_hlID}, /* obsolete */
7733 {"highlight_exists",1, 1, f_hlexists}, /* obsolete */
7734 {"histadd", 2, 2, f_histadd},
7735 {"histdel", 1, 2, f_histdel},
7736 {"histget", 1, 2, f_histget},
7737 {"histnr", 1, 1, f_histnr},
7738 {"hlID", 1, 1, f_hlID},
7739 {"hlexists", 1, 1, f_hlexists},
7740 {"hostname", 0, 0, f_hostname},
7741 {"iconv", 3, 3, f_iconv},
7742 {"indent", 1, 1, f_indent},
7743 {"index", 2, 4, f_index},
7744 {"input", 1, 3, f_input},
7745 {"inputdialog", 1, 3, f_inputdialog},
7746 {"inputlist", 1, 1, f_inputlist},
7747 {"inputrestore", 0, 0, f_inputrestore},
7748 {"inputsave", 0, 0, f_inputsave},
7749 {"inputsecret", 1, 2, f_inputsecret},
7750 {"insert", 2, 3, f_insert},
7751 {"isdirectory", 1, 1, f_isdirectory},
7752 {"islocked", 1, 1, f_islocked},
7753 {"items", 1, 1, f_items},
7754 {"join", 1, 2, f_join},
7755 {"keys", 1, 1, f_keys},
7756 {"last_buffer_nr", 0, 0, f_last_buffer_nr},/* obsolete */
7757 {"len", 1, 1, f_len},
7758 {"libcall", 3, 3, f_libcall},
7759 {"libcallnr", 3, 3, f_libcallnr},
7760 {"line", 1, 1, f_line},
7761 {"line2byte", 1, 1, f_line2byte},
7762 {"lispindent", 1, 1, f_lispindent},
7763 {"localtime", 0, 0, f_localtime},
7764 #ifdef FEAT_FLOAT
7765 {"log", 1, 1, f_log}, /* WJMc */
7766 {"log10", 1, 1, f_log10},
7767 #endif
7768 {"map", 2, 2, f_map},
7769 {"maparg", 1, 3, f_maparg},
7770 {"mapcheck", 1, 3, f_mapcheck},
7771 {"match", 2, 4, f_match},
7772 {"matchadd", 2, 4, f_matchadd},
7773 {"matcharg", 1, 1, f_matcharg},
7774 {"matchdelete", 1, 1, f_matchdelete},
7775 {"matchend", 2, 4, f_matchend},
7776 {"matchlist", 2, 4, f_matchlist},
7777 {"matchstr", 2, 4, f_matchstr},
7778 {"max", 1, 1, f_max},
7779 {"min", 1, 1, f_min},
7780 #ifdef vim_mkdir
7781 {"mkdir", 1, 3, f_mkdir},
7782 #endif
7783 {"mode", 0, 1, f_mode},
7784 #ifdef FEAT_MZSCHEME
7785 {"mzeval", 1, 1, f_mzeval},
7786 #endif
7787 {"nextnonblank", 1, 1, f_nextnonblank},
7788 {"nr2char", 1, 1, f_nr2char},
7789 {"pathshorten", 1, 1, f_pathshorten},
7790 #ifdef FEAT_FLOAT
7791 {"pow", 2, 2, f_pow},
7792 #endif
7793 {"prevnonblank", 1, 1, f_prevnonblank},
7794 {"printf", 2, 19, f_printf},
7795 {"pumvisible", 0, 0, f_pumvisible},
7796 {"range", 1, 3, f_range},
7797 {"readfile", 1, 3, f_readfile},
7798 {"reltime", 0, 2, f_reltime},
7799 {"reltimestr", 1, 1, f_reltimestr},
7800 {"remote_expr", 2, 3, f_remote_expr},
7801 {"remote_foreground", 1, 1, f_remote_foreground},
7802 {"remote_peek", 1, 2, f_remote_peek},
7803 {"remote_read", 1, 1, f_remote_read},
7804 {"remote_send", 2, 3, f_remote_send},
7805 {"remove", 2, 3, f_remove},
7806 {"rename", 2, 2, f_rename},
7807 {"repeat", 2, 2, f_repeat},
7808 {"resolve", 1, 1, f_resolve},
7809 {"reverse", 1, 1, f_reverse},
7810 #ifdef FEAT_FLOAT
7811 {"round", 1, 1, f_round},
7812 #endif
7813 {"search", 1, 4, f_search},
7814 {"searchdecl", 1, 3, f_searchdecl},
7815 {"searchpair", 3, 7, f_searchpair},
7816 {"searchpairpos", 3, 7, f_searchpairpos},
7817 {"searchpos", 1, 4, f_searchpos},
7818 {"server2client", 2, 2, f_server2client},
7819 {"serverlist", 0, 0, f_serverlist},
7820 {"setbufvar", 3, 3, f_setbufvar},
7821 {"setcmdpos", 1, 1, f_setcmdpos},
7822 {"setline", 2, 2, f_setline},
7823 {"setloclist", 2, 3, f_setloclist},
7824 {"setmatches", 1, 1, f_setmatches},
7825 {"setpos", 2, 2, f_setpos},
7826 {"setqflist", 1, 2, f_setqflist},
7827 {"setreg", 2, 3, f_setreg},
7828 {"settabwinvar", 4, 4, f_settabwinvar},
7829 {"setwinvar", 3, 3, f_setwinvar},
7830 {"shellescape", 1, 2, f_shellescape},
7831 {"simplify", 1, 1, f_simplify},
7832 #ifdef FEAT_FLOAT
7833 {"sin", 1, 1, f_sin},
7834 {"sinh", 1, 1, f_sinh}, /* WJMc */
7835 #endif
7836 {"sort", 1, 2, f_sort},
7837 {"soundfold", 1, 1, f_soundfold},
7838 {"spellbadword", 0, 1, f_spellbadword},
7839 {"spellsuggest", 1, 3, f_spellsuggest},
7840 {"split", 1, 3, f_split},
7841 #ifdef FEAT_FLOAT
7842 {"sqrt", 1, 1, f_sqrt},
7843 {"str2float", 1, 1, f_str2float},
7844 #endif
7845 {"str2nr", 1, 2, f_str2nr},
7846 #ifdef HAVE_STRFTIME
7847 {"strftime", 1, 2, f_strftime},
7848 #endif
7849 {"stridx", 2, 3, f_stridx},
7850 {"string", 1, 1, f_string},
7851 {"strlen", 1, 1, f_strlen},
7852 {"strpart", 2, 3, f_strpart},
7853 {"strridx", 2, 3, f_strridx},
7854 {"strtrans", 1, 1, f_strtrans},
7855 {"submatch", 1, 1, f_submatch},
7856 {"substitute", 4, 4, f_substitute},
7857 {"synID", 3, 3, f_synID},
7858 {"synIDattr", 2, 3, f_synIDattr},
7859 {"synIDtrans", 1, 1, f_synIDtrans},
7860 {"synstack", 2, 2, f_synstack},
7861 {"system", 1, 2, f_system},
7862 {"tabpagebuflist", 0, 1, f_tabpagebuflist},
7863 {"tabpagenr", 0, 1, f_tabpagenr},
7864 {"tabpagewinnr", 1, 2, f_tabpagewinnr},
7865 {"tagfiles", 0, 0, f_tagfiles},
7866 {"taglist", 1, 1, f_taglist},
7867 {"tan", 1, 1, f_tan}, /* WJMc */
7868 {"tanh", 1, 1, f_tanh}, /* WJMc */
7869 {"tempname", 0, 0, f_tempname},
7870 {"test", 1, 1, f_test},
7871 {"tolower", 1, 1, f_tolower},
7872 {"toupper", 1, 1, f_toupper},
7873 {"tr", 3, 3, f_tr},
7874 #ifdef FEAT_FLOAT
7875 {"trunc", 1, 1, f_trunc},
7876 #endif
7877 {"type", 1, 1, f_type},
7878 {"values", 1, 1, f_values},
7879 {"virtcol", 1, 1, f_virtcol},
7880 {"visualmode", 0, 1, f_visualmode},
7881 {"winbufnr", 1, 1, f_winbufnr},
7882 {"wincol", 0, 0, f_wincol},
7883 {"winheight", 1, 1, f_winheight},
7884 {"winline", 0, 0, f_winline},
7885 {"winnr", 0, 1, f_winnr},
7886 {"winrestcmd", 0, 0, f_winrestcmd},
7887 {"winrestview", 1, 1, f_winrestview},
7888 {"winsaveview", 0, 0, f_winsaveview},
7889 {"winwidth", 1, 1, f_winwidth},
7890 {"writefile", 2, 3, f_writefile},
7893 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
7896 * Function given to ExpandGeneric() to obtain the list of internal
7897 * or user defined function names.
7899 char_u *
7900 get_function_name(xp, idx)
7901 expand_T *xp;
7902 int idx;
7904 static int intidx = -1;
7905 char_u *name;
7907 if (idx == 0)
7908 intidx = -1;
7909 if (intidx < 0)
7911 name = get_user_func_name(xp, idx);
7912 if (name != NULL)
7913 return name;
7915 if (++intidx < (int)(sizeof(functions) / sizeof(struct fst)))
7917 STRCPY(IObuff, functions[intidx].f_name);
7918 STRCAT(IObuff, "(");
7919 if (functions[intidx].f_max_argc == 0)
7920 STRCAT(IObuff, ")");
7921 return IObuff;
7924 return NULL;
7928 * Function given to ExpandGeneric() to obtain the list of internal or
7929 * user defined variable or function names.
7931 char_u *
7932 get_expr_name(xp, idx)
7933 expand_T *xp;
7934 int idx;
7936 static int intidx = -1;
7937 char_u *name;
7939 if (idx == 0)
7940 intidx = -1;
7941 if (intidx < 0)
7943 name = get_function_name(xp, idx);
7944 if (name != NULL)
7945 return name;
7947 return get_user_var_name(xp, ++intidx);
7950 #endif /* FEAT_CMDL_COMPL */
7953 * Find internal function in table above.
7954 * Return index, or -1 if not found
7956 static int
7957 find_internal_func(name)
7958 char_u *name; /* name of the function */
7960 int first = 0;
7961 int last = (int)(sizeof(functions) / sizeof(struct fst)) - 1;
7962 int cmp;
7963 int x;
7966 * Find the function name in the table. Binary search.
7968 while (first <= last)
7970 x = first + ((unsigned)(last - first) >> 1);
7971 cmp = STRCMP(name, functions[x].f_name);
7972 if (cmp < 0)
7973 last = x - 1;
7974 else if (cmp > 0)
7975 first = x + 1;
7976 else
7977 return x;
7979 return -1;
7983 * Check if "name" is a variable of type VAR_FUNC. If so, return the function
7984 * name it contains, otherwise return "name".
7986 static char_u *
7987 deref_func_name(name, lenp)
7988 char_u *name;
7989 int *lenp;
7991 dictitem_T *v;
7992 int cc;
7994 cc = name[*lenp];
7995 name[*lenp] = NUL;
7996 v = find_var(name, NULL);
7997 name[*lenp] = cc;
7998 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
8000 if (v->di_tv.vval.v_string == NULL)
8002 *lenp = 0;
8003 return (char_u *)""; /* just in case */
8005 *lenp = (int)STRLEN(v->di_tv.vval.v_string);
8006 return v->di_tv.vval.v_string;
8009 return name;
8013 * Allocate a variable for the result of a function.
8014 * Return OK or FAIL.
8016 static int
8017 get_func_tv(name, len, rettv, arg, firstline, lastline, doesrange,
8018 evaluate, selfdict)
8019 char_u *name; /* name of the function */
8020 int len; /* length of "name" */
8021 typval_T *rettv;
8022 char_u **arg; /* argument, pointing to the '(' */
8023 linenr_T firstline; /* first line of range */
8024 linenr_T lastline; /* last line of range */
8025 int *doesrange; /* return: function handled range */
8026 int evaluate;
8027 dict_T *selfdict; /* Dictionary for "self" */
8029 char_u *argp;
8030 int ret = OK;
8031 typval_T argvars[MAX_FUNC_ARGS + 1]; /* vars for arguments */
8032 int argcount = 0; /* number of arguments found */
8035 * Get the arguments.
8037 argp = *arg;
8038 while (argcount < MAX_FUNC_ARGS)
8040 argp = skipwhite(argp + 1); /* skip the '(' or ',' */
8041 if (*argp == ')' || *argp == ',' || *argp == NUL)
8042 break;
8043 if (eval1(&argp, &argvars[argcount], evaluate) == FAIL)
8045 ret = FAIL;
8046 break;
8048 ++argcount;
8049 if (*argp != ',')
8050 break;
8052 if (*argp == ')')
8053 ++argp;
8054 else
8055 ret = FAIL;
8057 if (ret == OK)
8058 ret = call_func(name, len, rettv, argcount, argvars,
8059 firstline, lastline, doesrange, evaluate, selfdict);
8060 else if (!aborting())
8062 if (argcount == MAX_FUNC_ARGS)
8063 emsg_funcname(N_("E740: Too many arguments for function %s"), name);
8064 else
8065 emsg_funcname(N_("E116: Invalid arguments for function %s"), name);
8068 while (--argcount >= 0)
8069 clear_tv(&argvars[argcount]);
8071 *arg = skipwhite(argp);
8072 return ret;
8077 * Call a function with its resolved parameters
8078 * Return OK when the function can't be called, FAIL otherwise.
8079 * Also returns OK when an error was encountered while executing the function.
8081 static int
8082 call_func(func_name, len, rettv, argcount, argvars, firstline, lastline,
8083 doesrange, evaluate, selfdict)
8084 char_u *func_name; /* name of the function */
8085 int len; /* length of "name" */
8086 typval_T *rettv; /* return value goes here */
8087 int argcount; /* number of "argvars" */
8088 typval_T *argvars; /* vars for arguments, must have "argcount"
8089 PLUS ONE elements! */
8090 linenr_T firstline; /* first line of range */
8091 linenr_T lastline; /* last line of range */
8092 int *doesrange; /* return: function handled range */
8093 int evaluate;
8094 dict_T *selfdict; /* Dictionary for "self" */
8096 int ret = FAIL;
8097 #define ERROR_UNKNOWN 0
8098 #define ERROR_TOOMANY 1
8099 #define ERROR_TOOFEW 2
8100 #define ERROR_SCRIPT 3
8101 #define ERROR_DICT 4
8102 #define ERROR_NONE 5
8103 #define ERROR_OTHER 6
8104 int error = ERROR_NONE;
8105 int i;
8106 int llen;
8107 ufunc_T *fp;
8108 #define FLEN_FIXED 40
8109 char_u fname_buf[FLEN_FIXED + 1];
8110 char_u *fname;
8111 char_u *name;
8113 /* Make a copy of the name, if it comes from a funcref variable it could
8114 * be changed or deleted in the called function. */
8115 name = vim_strnsave(func_name, len);
8116 if (name == NULL)
8117 return ret;
8120 * In a script change <SID>name() and s:name() to K_SNR 123_name().
8121 * Change <SNR>123_name() to K_SNR 123_name().
8122 * Use fname_buf[] when it fits, otherwise allocate memory (slow).
8124 llen = eval_fname_script(name);
8125 if (llen > 0)
8127 fname_buf[0] = K_SPECIAL;
8128 fname_buf[1] = KS_EXTRA;
8129 fname_buf[2] = (int)KE_SNR;
8130 i = 3;
8131 if (eval_fname_sid(name)) /* "<SID>" or "s:" */
8133 if (current_SID <= 0)
8134 error = ERROR_SCRIPT;
8135 else
8137 sprintf((char *)fname_buf + 3, "%ld_", (long)current_SID);
8138 i = (int)STRLEN(fname_buf);
8141 if (i + STRLEN(name + llen) < FLEN_FIXED)
8143 STRCPY(fname_buf + i, name + llen);
8144 fname = fname_buf;
8146 else
8148 fname = alloc((unsigned)(i + STRLEN(name + llen) + 1));
8149 if (fname == NULL)
8150 error = ERROR_OTHER;
8151 else
8153 mch_memmove(fname, fname_buf, (size_t)i);
8154 STRCPY(fname + i, name + llen);
8158 else
8159 fname = name;
8161 *doesrange = FALSE;
8164 /* execute the function if no errors detected and executing */
8165 if (evaluate && error == ERROR_NONE)
8167 rettv->v_type = VAR_NUMBER; /* default rettv is number zero */
8168 rettv->vval.v_number = 0;
8169 error = ERROR_UNKNOWN;
8171 if (!builtin_function(fname))
8174 * User defined function.
8176 fp = find_func(fname);
8178 #ifdef FEAT_AUTOCMD
8179 /* Trigger FuncUndefined event, may load the function. */
8180 if (fp == NULL
8181 && apply_autocmds(EVENT_FUNCUNDEFINED,
8182 fname, fname, TRUE, NULL)
8183 && !aborting())
8185 /* executed an autocommand, search for the function again */
8186 fp = find_func(fname);
8188 #endif
8189 /* Try loading a package. */
8190 if (fp == NULL && script_autoload(fname, TRUE) && !aborting())
8192 /* loaded a package, search for the function again */
8193 fp = find_func(fname);
8196 if (fp != NULL)
8198 if (fp->uf_flags & FC_RANGE)
8199 *doesrange = TRUE;
8200 if (argcount < fp->uf_args.ga_len)
8201 error = ERROR_TOOFEW;
8202 else if (!fp->uf_varargs && argcount > fp->uf_args.ga_len)
8203 error = ERROR_TOOMANY;
8204 else if ((fp->uf_flags & FC_DICT) && selfdict == NULL)
8205 error = ERROR_DICT;
8206 else
8209 * Call the user function.
8210 * Save and restore search patterns, script variables and
8211 * redo buffer.
8213 save_search_patterns();
8214 saveRedobuff();
8215 ++fp->uf_calls;
8216 call_user_func(fp, argcount, argvars, rettv,
8217 firstline, lastline,
8218 (fp->uf_flags & FC_DICT) ? selfdict : NULL);
8219 if (--fp->uf_calls <= 0 && isdigit(*fp->uf_name)
8220 && fp->uf_refcount <= 0)
8221 /* Function was unreferenced while being used, free it
8222 * now. */
8223 func_free(fp);
8224 restoreRedobuff();
8225 restore_search_patterns();
8226 error = ERROR_NONE;
8230 else
8233 * Find the function name in the table, call its implementation.
8235 i = find_internal_func(fname);
8236 if (i >= 0)
8238 if (argcount < functions[i].f_min_argc)
8239 error = ERROR_TOOFEW;
8240 else if (argcount > functions[i].f_max_argc)
8241 error = ERROR_TOOMANY;
8242 else
8244 argvars[argcount].v_type = VAR_UNKNOWN;
8245 functions[i].f_func(argvars, rettv);
8246 error = ERROR_NONE;
8251 * The function call (or "FuncUndefined" autocommand sequence) might
8252 * have been aborted by an error, an interrupt, or an explicitly thrown
8253 * exception that has not been caught so far. This situation can be
8254 * tested for by calling aborting(). For an error in an internal
8255 * function or for the "E132" error in call_user_func(), however, the
8256 * throw point at which the "force_abort" flag (temporarily reset by
8257 * emsg()) is normally updated has not been reached yet. We need to
8258 * update that flag first to make aborting() reliable.
8260 update_force_abort();
8262 if (error == ERROR_NONE)
8263 ret = OK;
8266 * Report an error unless the argument evaluation or function call has been
8267 * cancelled due to an aborting error, an interrupt, or an exception.
8269 if (!aborting())
8271 switch (error)
8273 case ERROR_UNKNOWN:
8274 emsg_funcname(N_("E117: Unknown function: %s"), name);
8275 break;
8276 case ERROR_TOOMANY:
8277 emsg_funcname(e_toomanyarg, name);
8278 break;
8279 case ERROR_TOOFEW:
8280 emsg_funcname(N_("E119: Not enough arguments for function: %s"),
8281 name);
8282 break;
8283 case ERROR_SCRIPT:
8284 emsg_funcname(N_("E120: Using <SID> not in a script context: %s"),
8285 name);
8286 break;
8287 case ERROR_DICT:
8288 emsg_funcname(N_("E725: Calling dict function without Dictionary: %s"),
8289 name);
8290 break;
8294 if (fname != name && fname != fname_buf)
8295 vim_free(fname);
8296 vim_free(name);
8298 return ret;
8302 * Give an error message with a function name. Handle <SNR> things.
8303 * "ermsg" is to be passed without translation, use N_() instead of _().
8305 static void
8306 emsg_funcname(ermsg, name)
8307 char *ermsg;
8308 char_u *name;
8310 char_u *p;
8312 if (*name == K_SPECIAL)
8313 p = concat_str((char_u *)"<SNR>", name + 3);
8314 else
8315 p = name;
8316 EMSG2(_(ermsg), p);
8317 if (p != name)
8318 vim_free(p);
8322 * Return TRUE for a non-zero Number and a non-empty String.
8324 static int
8325 non_zero_arg(argvars)
8326 typval_T *argvars;
8328 return ((argvars[0].v_type == VAR_NUMBER
8329 && argvars[0].vval.v_number != 0)
8330 || (argvars[0].v_type == VAR_STRING
8331 && argvars[0].vval.v_string != NULL
8332 && *argvars[0].vval.v_string != NUL));
8335 /*********************************************
8336 * Implementation of the built-in functions
8339 #ifdef FEAT_FLOAT
8341 * "abs(expr)" function
8343 static void
8344 f_abs(argvars, rettv)
8345 typval_T *argvars;
8346 typval_T *rettv;
8348 if (argvars[0].v_type == VAR_FLOAT)
8350 rettv->v_type = VAR_FLOAT;
8351 rettv->vval.v_float = fabs(argvars[0].vval.v_float);
8353 else
8355 varnumber_T n;
8356 int error = FALSE;
8358 n = get_tv_number_chk(&argvars[0], &error);
8359 if (error)
8360 rettv->vval.v_number = -1;
8361 else if (n > 0)
8362 rettv->vval.v_number = n;
8363 else
8364 rettv->vval.v_number = -n;
8367 #endif
8370 * "add(list, item)" function
8372 static void
8373 f_add(argvars, rettv)
8374 typval_T *argvars;
8375 typval_T *rettv;
8377 list_T *l;
8379 rettv->vval.v_number = 1; /* Default: Failed */
8380 if (argvars[0].v_type == VAR_LIST)
8382 if ((l = argvars[0].vval.v_list) != NULL
8383 && !tv_check_lock(l->lv_lock, (char_u *)"add()")
8384 && list_append_tv(l, &argvars[1]) == OK)
8385 copy_tv(&argvars[0], rettv);
8387 else
8388 EMSG(_(e_listreq));
8392 * "append(lnum, string/list)" function
8394 static void
8395 f_append(argvars, rettv)
8396 typval_T *argvars;
8397 typval_T *rettv;
8399 long lnum;
8400 char_u *line;
8401 list_T *l = NULL;
8402 listitem_T *li = NULL;
8403 typval_T *tv;
8404 long added = 0;
8406 lnum = get_tv_lnum(argvars);
8407 if (lnum >= 0
8408 && lnum <= curbuf->b_ml.ml_line_count
8409 && u_save(lnum, lnum + 1) == OK)
8411 if (argvars[1].v_type == VAR_LIST)
8413 l = argvars[1].vval.v_list;
8414 if (l == NULL)
8415 return;
8416 li = l->lv_first;
8418 for (;;)
8420 if (l == NULL)
8421 tv = &argvars[1]; /* append a string */
8422 else if (li == NULL)
8423 break; /* end of list */
8424 else
8425 tv = &li->li_tv; /* append item from list */
8426 line = get_tv_string_chk(tv);
8427 if (line == NULL) /* type error */
8429 rettv->vval.v_number = 1; /* Failed */
8430 break;
8432 ml_append(lnum + added, line, (colnr_T)0, FALSE);
8433 ++added;
8434 if (l == NULL)
8435 break;
8436 li = li->li_next;
8439 appended_lines_mark(lnum, added);
8440 if (curwin->w_cursor.lnum > lnum)
8441 curwin->w_cursor.lnum += added;
8443 else
8444 rettv->vval.v_number = 1; /* Failed */
8448 * "argc()" function
8450 static void
8451 f_argc(argvars, rettv)
8452 typval_T *argvars UNUSED;
8453 typval_T *rettv;
8455 rettv->vval.v_number = ARGCOUNT;
8459 * "argidx()" function
8461 static void
8462 f_argidx(argvars, rettv)
8463 typval_T *argvars UNUSED;
8464 typval_T *rettv;
8466 rettv->vval.v_number = curwin->w_arg_idx;
8470 * "argv(nr)" function
8472 static void
8473 f_argv(argvars, rettv)
8474 typval_T *argvars;
8475 typval_T *rettv;
8477 int idx;
8479 if (argvars[0].v_type != VAR_UNKNOWN)
8481 idx = get_tv_number_chk(&argvars[0], NULL);
8482 if (idx >= 0 && idx < ARGCOUNT)
8483 rettv->vval.v_string = vim_strsave(alist_name(&ARGLIST[idx]));
8484 else
8485 rettv->vval.v_string = NULL;
8486 rettv->v_type = VAR_STRING;
8488 else if (rettv_list_alloc(rettv) == OK)
8489 for (idx = 0; idx < ARGCOUNT; ++idx)
8490 list_append_string(rettv->vval.v_list,
8491 alist_name(&ARGLIST[idx]), -1);
8494 #ifdef FEAT_FLOAT
8495 static int get_float_arg __ARGS((typval_T *argvars, float_T *f));
8498 * Get the float value of "argvars[0]" into "f".
8499 * Returns FAIL when the argument is not a Number or Float.
8501 static int
8502 get_float_arg(argvars, f)
8503 typval_T *argvars;
8504 float_T *f;
8506 if (argvars[0].v_type == VAR_FLOAT)
8508 *f = argvars[0].vval.v_float;
8509 return OK;
8511 if (argvars[0].v_type == VAR_NUMBER)
8513 *f = (float_T)argvars[0].vval.v_number;
8514 return OK;
8516 EMSG(_("E808: Number or Float required"));
8517 return FAIL;
8520 /* The 10 added FP functions are defined immediately before atan() - WJMc */
8523 * "acos()" function
8525 static void
8526 f_acos(argvars, rettv)
8527 typval_T *argvars;
8528 typval_T *rettv;
8530 float_T f;
8532 rettv->v_type = VAR_FLOAT;
8533 if (get_float_arg(argvars, &f) == OK)
8534 rettv->vval.v_float = acos(f);
8535 else
8536 rettv->vval.v_float = 0.0;
8540 * "asin()" function
8542 static void
8543 f_asin(argvars, rettv)
8544 typval_T *argvars;
8545 typval_T *rettv;
8547 float_T f;
8549 rettv->v_type = VAR_FLOAT;
8550 if (get_float_arg(argvars, &f) == OK)
8551 rettv->vval.v_float = asin(f);
8552 else
8553 rettv->vval.v_float = 0.0;
8557 * "atan2()" function
8559 static void
8560 f_atan2(argvars, rettv)
8561 typval_T *argvars;
8562 typval_T *rettv;
8564 float_T fx, fy;
8566 rettv->v_type = VAR_FLOAT;
8567 if (get_float_arg(argvars, &fx) == OK
8568 && get_float_arg(&argvars[1], &fy) == OK)
8569 rettv->vval.v_float = atan2(fx, fy);
8570 else
8571 rettv->vval.v_float = 0.0;
8575 * "cosh()" function
8577 static void
8578 f_cosh(argvars, rettv)
8579 typval_T *argvars;
8580 typval_T *rettv;
8582 float_T f;
8584 rettv->v_type = VAR_FLOAT;
8585 if (get_float_arg(argvars, &f) == OK)
8586 rettv->vval.v_float = cosh(f);
8587 else
8588 rettv->vval.v_float = 0.0;
8592 * "exp()" function
8594 static void
8595 f_exp(argvars, rettv)
8596 typval_T *argvars;
8597 typval_T *rettv;
8599 float_T f;
8601 rettv->v_type = VAR_FLOAT;
8602 if (get_float_arg(argvars, &f) == OK)
8603 rettv->vval.v_float = exp(f);
8604 else
8605 rettv->vval.v_float = 0.0;
8609 * "fmod()" function
8611 static void
8612 f_fmod(argvars, rettv)
8613 typval_T *argvars;
8614 typval_T *rettv;
8616 float_T fx, fy;
8618 rettv->v_type = VAR_FLOAT;
8619 if (get_float_arg(argvars, &fx) == OK
8620 && get_float_arg(&argvars[1], &fy) == OK)
8621 rettv->vval.v_float = fmod(fx, fy);
8622 else
8623 rettv->vval.v_float = 0.0;
8627 * "log()" function
8629 static void
8630 f_log(argvars, rettv)
8631 typval_T *argvars;
8632 typval_T *rettv;
8634 float_T f;
8636 rettv->v_type = VAR_FLOAT;
8637 if (get_float_arg(argvars, &f) == OK)
8638 rettv->vval.v_float = log(f);
8639 else
8640 rettv->vval.v_float = 0.0;
8644 * "sinh()" function
8646 static void
8647 f_sinh(argvars, rettv)
8648 typval_T *argvars;
8649 typval_T *rettv;
8651 float_T f;
8653 rettv->v_type = VAR_FLOAT;
8654 if (get_float_arg(argvars, &f) == OK)
8655 rettv->vval.v_float = sinh(f);
8656 else
8657 rettv->vval.v_float = 0.0;
8661 * "tan()" function
8663 static void
8664 f_tan(argvars, rettv)
8665 typval_T *argvars;
8666 typval_T *rettv;
8668 float_T f;
8670 rettv->v_type = VAR_FLOAT;
8671 if (get_float_arg(argvars, &f) == OK)
8672 rettv->vval.v_float = tan(f);
8673 else
8674 rettv->vval.v_float = 0.0;
8678 * "tanh()" function
8680 static void
8681 f_tanh(argvars, rettv)
8682 typval_T *argvars;
8683 typval_T *rettv;
8685 float_T f;
8687 rettv->v_type = VAR_FLOAT;
8688 if (get_float_arg(argvars, &f) == OK)
8689 rettv->vval.v_float = tanh(f);
8690 else
8691 rettv->vval.v_float = 0.0;
8694 /* End of the 10 added FP functions - WJMc */
8697 * "atan()" function
8699 static void
8700 f_atan(argvars, rettv)
8701 typval_T *argvars;
8702 typval_T *rettv;
8704 float_T f;
8706 rettv->v_type = VAR_FLOAT;
8707 if (get_float_arg(argvars, &f) == OK)
8708 rettv->vval.v_float = atan(f);
8709 else
8710 rettv->vval.v_float = 0.0;
8712 #endif
8715 * "browse(save, title, initdir, default)" function
8717 static void
8718 f_browse(argvars, rettv)
8719 typval_T *argvars UNUSED;
8720 typval_T *rettv;
8722 #ifdef FEAT_BROWSE
8723 int save;
8724 char_u *title;
8725 char_u *initdir;
8726 char_u *defname;
8727 char_u buf[NUMBUFLEN];
8728 char_u buf2[NUMBUFLEN];
8729 int error = FALSE;
8731 save = get_tv_number_chk(&argvars[0], &error);
8732 title = get_tv_string_chk(&argvars[1]);
8733 initdir = get_tv_string_buf_chk(&argvars[2], buf);
8734 defname = get_tv_string_buf_chk(&argvars[3], buf2);
8736 if (error || title == NULL || initdir == NULL || defname == NULL)
8737 rettv->vval.v_string = NULL;
8738 else
8739 rettv->vval.v_string =
8740 do_browse(save ? BROWSE_SAVE : 0,
8741 title, defname, NULL, initdir, NULL, curbuf);
8742 #else
8743 rettv->vval.v_string = NULL;
8744 #endif
8745 rettv->v_type = VAR_STRING;
8749 * "browsedir(title, initdir)" function
8751 static void
8752 f_browsedir(argvars, rettv)
8753 typval_T *argvars UNUSED;
8754 typval_T *rettv;
8756 #ifdef FEAT_BROWSE
8757 char_u *title;
8758 char_u *initdir;
8759 char_u buf[NUMBUFLEN];
8761 title = get_tv_string_chk(&argvars[0]);
8762 initdir = get_tv_string_buf_chk(&argvars[1], buf);
8764 if (title == NULL || initdir == NULL)
8765 rettv->vval.v_string = NULL;
8766 else
8767 rettv->vval.v_string = do_browse(BROWSE_DIR,
8768 title, NULL, NULL, initdir, NULL, curbuf);
8769 #else
8770 rettv->vval.v_string = NULL;
8771 #endif
8772 rettv->v_type = VAR_STRING;
8775 static buf_T *find_buffer __ARGS((typval_T *avar));
8778 * Find a buffer by number or exact name.
8780 static buf_T *
8781 find_buffer(avar)
8782 typval_T *avar;
8784 buf_T *buf = NULL;
8786 if (avar->v_type == VAR_NUMBER)
8787 buf = buflist_findnr((int)avar->vval.v_number);
8788 else if (avar->v_type == VAR_STRING && avar->vval.v_string != NULL)
8790 buf = buflist_findname_exp(avar->vval.v_string);
8791 if (buf == NULL)
8793 /* No full path name match, try a match with a URL or a "nofile"
8794 * buffer, these don't use the full path. */
8795 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8796 if (buf->b_fname != NULL
8797 && (path_with_url(buf->b_fname)
8798 #ifdef FEAT_QUICKFIX
8799 || bt_nofile(buf)
8800 #endif
8802 && STRCMP(buf->b_fname, avar->vval.v_string) == 0)
8803 break;
8806 return buf;
8810 * "bufexists(expr)" function
8812 static void
8813 f_bufexists(argvars, rettv)
8814 typval_T *argvars;
8815 typval_T *rettv;
8817 rettv->vval.v_number = (find_buffer(&argvars[0]) != NULL);
8821 * "buflisted(expr)" function
8823 static void
8824 f_buflisted(argvars, rettv)
8825 typval_T *argvars;
8826 typval_T *rettv;
8828 buf_T *buf;
8830 buf = find_buffer(&argvars[0]);
8831 rettv->vval.v_number = (buf != NULL && buf->b_p_bl);
8835 * "bufloaded(expr)" function
8837 static void
8838 f_bufloaded(argvars, rettv)
8839 typval_T *argvars;
8840 typval_T *rettv;
8842 buf_T *buf;
8844 buf = find_buffer(&argvars[0]);
8845 rettv->vval.v_number = (buf != NULL && buf->b_ml.ml_mfp != NULL);
8848 static buf_T *get_buf_tv __ARGS((typval_T *tv));
8851 * Get buffer by number or pattern.
8853 static buf_T *
8854 get_buf_tv(tv)
8855 typval_T *tv;
8857 char_u *name = tv->vval.v_string;
8858 int save_magic;
8859 char_u *save_cpo;
8860 buf_T *buf;
8862 if (tv->v_type == VAR_NUMBER)
8863 return buflist_findnr((int)tv->vval.v_number);
8864 if (tv->v_type != VAR_STRING)
8865 return NULL;
8866 if (name == NULL || *name == NUL)
8867 return curbuf;
8868 if (name[0] == '$' && name[1] == NUL)
8869 return lastbuf;
8871 /* Ignore 'magic' and 'cpoptions' here to make scripts portable */
8872 save_magic = p_magic;
8873 p_magic = TRUE;
8874 save_cpo = p_cpo;
8875 p_cpo = (char_u *)"";
8877 buf = buflist_findnr(buflist_findpat(name, name + STRLEN(name),
8878 TRUE, FALSE));
8880 p_magic = save_magic;
8881 p_cpo = save_cpo;
8883 /* If not found, try expanding the name, like done for bufexists(). */
8884 if (buf == NULL)
8885 buf = find_buffer(tv);
8887 return buf;
8891 * "bufname(expr)" function
8893 static void
8894 f_bufname(argvars, rettv)
8895 typval_T *argvars;
8896 typval_T *rettv;
8898 buf_T *buf;
8900 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8901 ++emsg_off;
8902 buf = get_buf_tv(&argvars[0]);
8903 rettv->v_type = VAR_STRING;
8904 if (buf != NULL && buf->b_fname != NULL)
8905 rettv->vval.v_string = vim_strsave(buf->b_fname);
8906 else
8907 rettv->vval.v_string = NULL;
8908 --emsg_off;
8912 * "bufnr(expr)" function
8914 static void
8915 f_bufnr(argvars, rettv)
8916 typval_T *argvars;
8917 typval_T *rettv;
8919 buf_T *buf;
8920 int error = FALSE;
8921 char_u *name;
8923 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8924 ++emsg_off;
8925 buf = get_buf_tv(&argvars[0]);
8926 --emsg_off;
8928 /* If the buffer isn't found and the second argument is not zero create a
8929 * new buffer. */
8930 if (buf == NULL
8931 && argvars[1].v_type != VAR_UNKNOWN
8932 && get_tv_number_chk(&argvars[1], &error) != 0
8933 && !error
8934 && (name = get_tv_string_chk(&argvars[0])) != NULL
8935 && !error)
8936 buf = buflist_new(name, NULL, (linenr_T)1, 0);
8938 if (buf != NULL)
8939 rettv->vval.v_number = buf->b_fnum;
8940 else
8941 rettv->vval.v_number = -1;
8945 * "bufwinnr(nr)" function
8947 static void
8948 f_bufwinnr(argvars, rettv)
8949 typval_T *argvars;
8950 typval_T *rettv;
8952 #ifdef FEAT_WINDOWS
8953 win_T *wp;
8954 int winnr = 0;
8955 #endif
8956 buf_T *buf;
8958 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8959 ++emsg_off;
8960 buf = get_buf_tv(&argvars[0]);
8961 #ifdef FEAT_WINDOWS
8962 for (wp = firstwin; wp; wp = wp->w_next)
8964 ++winnr;
8965 if (wp->w_buffer == buf)
8966 break;
8968 rettv->vval.v_number = (wp != NULL ? winnr : -1);
8969 #else
8970 rettv->vval.v_number = (curwin->w_buffer == buf ? 1 : -1);
8971 #endif
8972 --emsg_off;
8976 * "byte2line(byte)" function
8978 static void
8979 f_byte2line(argvars, rettv)
8980 typval_T *argvars UNUSED;
8981 typval_T *rettv;
8983 #ifndef FEAT_BYTEOFF
8984 rettv->vval.v_number = -1;
8985 #else
8986 long boff = 0;
8988 boff = get_tv_number(&argvars[0]) - 1; /* boff gets -1 on type error */
8989 if (boff < 0)
8990 rettv->vval.v_number = -1;
8991 else
8992 rettv->vval.v_number = ml_find_line_or_offset(curbuf,
8993 (linenr_T)0, &boff);
8994 #endif
8998 * "byteidx()" function
9000 static void
9001 f_byteidx(argvars, rettv)
9002 typval_T *argvars;
9003 typval_T *rettv;
9005 #ifdef FEAT_MBYTE
9006 char_u *t;
9007 #endif
9008 char_u *str;
9009 long idx;
9011 str = get_tv_string_chk(&argvars[0]);
9012 idx = get_tv_number_chk(&argvars[1], NULL);
9013 rettv->vval.v_number = -1;
9014 if (str == NULL || idx < 0)
9015 return;
9017 #ifdef FEAT_MBYTE
9018 t = str;
9019 for ( ; idx > 0; idx--)
9021 if (*t == NUL) /* EOL reached */
9022 return;
9023 t += (*mb_ptr2len)(t);
9025 rettv->vval.v_number = (varnumber_T)(t - str);
9026 #else
9027 if ((size_t)idx <= STRLEN(str))
9028 rettv->vval.v_number = idx;
9029 #endif
9033 * "call(func, arglist)" function
9035 static void
9036 f_call(argvars, rettv)
9037 typval_T *argvars;
9038 typval_T *rettv;
9040 char_u *func;
9041 typval_T argv[MAX_FUNC_ARGS + 1];
9042 int argc = 0;
9043 listitem_T *item;
9044 int dummy;
9045 dict_T *selfdict = NULL;
9047 if (argvars[1].v_type != VAR_LIST)
9049 EMSG(_(e_listreq));
9050 return;
9052 if (argvars[1].vval.v_list == NULL)
9053 return;
9055 if (argvars[0].v_type == VAR_FUNC)
9056 func = argvars[0].vval.v_string;
9057 else
9058 func = get_tv_string(&argvars[0]);
9059 if (*func == NUL)
9060 return; /* type error or empty name */
9062 if (argvars[2].v_type != VAR_UNKNOWN)
9064 if (argvars[2].v_type != VAR_DICT)
9066 EMSG(_(e_dictreq));
9067 return;
9069 selfdict = argvars[2].vval.v_dict;
9072 for (item = argvars[1].vval.v_list->lv_first; item != NULL;
9073 item = item->li_next)
9075 if (argc == MAX_FUNC_ARGS)
9077 EMSG(_("E699: Too many arguments"));
9078 break;
9080 /* Make a copy of each argument. This is needed to be able to set
9081 * v_lock to VAR_FIXED in the copy without changing the original list.
9083 copy_tv(&item->li_tv, &argv[argc++]);
9086 if (item == NULL)
9087 (void)call_func(func, (int)STRLEN(func), rettv, argc, argv,
9088 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
9089 &dummy, TRUE, selfdict);
9091 /* Free the arguments. */
9092 while (argc > 0)
9093 clear_tv(&argv[--argc]);
9096 #ifdef FEAT_FLOAT
9098 * "ceil({float})" function
9100 static void
9101 f_ceil(argvars, rettv)
9102 typval_T *argvars;
9103 typval_T *rettv;
9105 float_T f;
9107 rettv->v_type = VAR_FLOAT;
9108 if (get_float_arg(argvars, &f) == OK)
9109 rettv->vval.v_float = ceil(f);
9110 else
9111 rettv->vval.v_float = 0.0;
9113 #endif
9116 * "changenr()" function
9118 static void
9119 f_changenr(argvars, rettv)
9120 typval_T *argvars UNUSED;
9121 typval_T *rettv;
9123 rettv->vval.v_number = curbuf->b_u_seq_cur;
9127 * "char2nr(string)" function
9129 static void
9130 f_char2nr(argvars, rettv)
9131 typval_T *argvars;
9132 typval_T *rettv;
9134 #ifdef FEAT_MBYTE
9135 if (has_mbyte)
9136 rettv->vval.v_number = (*mb_ptr2char)(get_tv_string(&argvars[0]));
9137 else
9138 #endif
9139 rettv->vval.v_number = get_tv_string(&argvars[0])[0];
9143 * "cindent(lnum)" function
9145 static void
9146 f_cindent(argvars, rettv)
9147 typval_T *argvars;
9148 typval_T *rettv;
9150 #ifdef FEAT_CINDENT
9151 pos_T pos;
9152 linenr_T lnum;
9154 pos = curwin->w_cursor;
9155 lnum = get_tv_lnum(argvars);
9156 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
9158 curwin->w_cursor.lnum = lnum;
9159 rettv->vval.v_number = get_c_indent();
9160 curwin->w_cursor = pos;
9162 else
9163 #endif
9164 rettv->vval.v_number = -1;
9168 * "clearmatches()" function
9170 static void
9171 f_clearmatches(argvars, rettv)
9172 typval_T *argvars UNUSED;
9173 typval_T *rettv UNUSED;
9175 #ifdef FEAT_SEARCH_EXTRA
9176 clear_matches(curwin);
9177 #endif
9181 * "col(string)" function
9183 static void
9184 f_col(argvars, rettv)
9185 typval_T *argvars;
9186 typval_T *rettv;
9188 colnr_T col = 0;
9189 pos_T *fp;
9190 int fnum = curbuf->b_fnum;
9192 fp = var2fpos(&argvars[0], FALSE, &fnum);
9193 if (fp != NULL && fnum == curbuf->b_fnum)
9195 if (fp->col == MAXCOL)
9197 /* '> can be MAXCOL, get the length of the line then */
9198 if (fp->lnum <= curbuf->b_ml.ml_line_count)
9199 col = (colnr_T)STRLEN(ml_get(fp->lnum)) + 1;
9200 else
9201 col = MAXCOL;
9203 else
9205 col = fp->col + 1;
9206 #ifdef FEAT_VIRTUALEDIT
9207 /* col(".") when the cursor is on the NUL at the end of the line
9208 * because of "coladd" can be seen as an extra column. */
9209 if (virtual_active() && fp == &curwin->w_cursor)
9211 char_u *p = ml_get_cursor();
9213 if (curwin->w_cursor.coladd >= (colnr_T)chartabsize(p,
9214 curwin->w_virtcol - curwin->w_cursor.coladd))
9216 # ifdef FEAT_MBYTE
9217 int l;
9219 if (*p != NUL && p[(l = (*mb_ptr2len)(p))] == NUL)
9220 col += l;
9221 # else
9222 if (*p != NUL && p[1] == NUL)
9223 ++col;
9224 # endif
9227 #endif
9230 rettv->vval.v_number = col;
9233 #if defined(FEAT_INS_EXPAND)
9235 * "complete()" function
9237 static void
9238 f_complete(argvars, rettv)
9239 typval_T *argvars;
9240 typval_T *rettv UNUSED;
9242 int startcol;
9244 if ((State & INSERT) == 0)
9246 EMSG(_("E785: complete() can only be used in Insert mode"));
9247 return;
9250 /* Check for undo allowed here, because if something was already inserted
9251 * the line was already saved for undo and this check isn't done. */
9252 if (!undo_allowed())
9253 return;
9255 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
9257 EMSG(_(e_invarg));
9258 return;
9261 startcol = get_tv_number_chk(&argvars[0], NULL);
9262 if (startcol <= 0)
9263 return;
9265 set_completion(startcol - 1, argvars[1].vval.v_list);
9269 * "complete_add()" function
9271 static void
9272 f_complete_add(argvars, rettv)
9273 typval_T *argvars;
9274 typval_T *rettv;
9276 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0);
9280 * "complete_check()" function
9282 static void
9283 f_complete_check(argvars, rettv)
9284 typval_T *argvars UNUSED;
9285 typval_T *rettv;
9287 int saved = RedrawingDisabled;
9289 RedrawingDisabled = 0;
9290 ins_compl_check_keys(0);
9291 rettv->vval.v_number = compl_interrupted;
9292 RedrawingDisabled = saved;
9294 #endif
9297 * "confirm(message, buttons[, default [, type]])" function
9299 static void
9300 f_confirm(argvars, rettv)
9301 typval_T *argvars UNUSED;
9302 typval_T *rettv UNUSED;
9304 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
9305 char_u *message;
9306 char_u *buttons = NULL;
9307 char_u buf[NUMBUFLEN];
9308 char_u buf2[NUMBUFLEN];
9309 int def = 1;
9310 int type = VIM_GENERIC;
9311 char_u *typestr;
9312 int error = FALSE;
9314 message = get_tv_string_chk(&argvars[0]);
9315 if (message == NULL)
9316 error = TRUE;
9317 if (argvars[1].v_type != VAR_UNKNOWN)
9319 buttons = get_tv_string_buf_chk(&argvars[1], buf);
9320 if (buttons == NULL)
9321 error = TRUE;
9322 if (argvars[2].v_type != VAR_UNKNOWN)
9324 def = get_tv_number_chk(&argvars[2], &error);
9325 if (argvars[3].v_type != VAR_UNKNOWN)
9327 typestr = get_tv_string_buf_chk(&argvars[3], buf2);
9328 if (typestr == NULL)
9329 error = TRUE;
9330 else
9332 switch (TOUPPER_ASC(*typestr))
9334 case 'E': type = VIM_ERROR; break;
9335 case 'Q': type = VIM_QUESTION; break;
9336 case 'I': type = VIM_INFO; break;
9337 case 'W': type = VIM_WARNING; break;
9338 case 'G': type = VIM_GENERIC; break;
9345 if (buttons == NULL || *buttons == NUL)
9346 buttons = (char_u *)_("&Ok");
9348 if (!error)
9349 rettv->vval.v_number = do_dialog(type, NULL, message, buttons,
9350 def, NULL);
9351 #endif
9355 * "copy()" function
9357 static void
9358 f_copy(argvars, rettv)
9359 typval_T *argvars;
9360 typval_T *rettv;
9362 item_copy(&argvars[0], rettv, FALSE, 0);
9365 #ifdef FEAT_FLOAT
9367 * "cos()" function
9369 static void
9370 f_cos(argvars, rettv)
9371 typval_T *argvars;
9372 typval_T *rettv;
9374 float_T f;
9376 rettv->v_type = VAR_FLOAT;
9377 if (get_float_arg(argvars, &f) == OK)
9378 rettv->vval.v_float = cos(f);
9379 else
9380 rettv->vval.v_float = 0.0;
9382 #endif
9385 * "count()" function
9387 static void
9388 f_count(argvars, rettv)
9389 typval_T *argvars;
9390 typval_T *rettv;
9392 long n = 0;
9393 int ic = FALSE;
9395 if (argvars[0].v_type == VAR_LIST)
9397 listitem_T *li;
9398 list_T *l;
9399 long idx;
9401 if ((l = argvars[0].vval.v_list) != NULL)
9403 li = l->lv_first;
9404 if (argvars[2].v_type != VAR_UNKNOWN)
9406 int error = FALSE;
9408 ic = get_tv_number_chk(&argvars[2], &error);
9409 if (argvars[3].v_type != VAR_UNKNOWN)
9411 idx = get_tv_number_chk(&argvars[3], &error);
9412 if (!error)
9414 li = list_find(l, idx);
9415 if (li == NULL)
9416 EMSGN(_(e_listidx), idx);
9419 if (error)
9420 li = NULL;
9423 for ( ; li != NULL; li = li->li_next)
9424 if (tv_equal(&li->li_tv, &argvars[1], ic))
9425 ++n;
9428 else if (argvars[0].v_type == VAR_DICT)
9430 int todo;
9431 dict_T *d;
9432 hashitem_T *hi;
9434 if ((d = argvars[0].vval.v_dict) != NULL)
9436 int error = FALSE;
9438 if (argvars[2].v_type != VAR_UNKNOWN)
9440 ic = get_tv_number_chk(&argvars[2], &error);
9441 if (argvars[3].v_type != VAR_UNKNOWN)
9442 EMSG(_(e_invarg));
9445 todo = error ? 0 : (int)d->dv_hashtab.ht_used;
9446 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
9448 if (!HASHITEM_EMPTY(hi))
9450 --todo;
9451 if (tv_equal(&HI2DI(hi)->di_tv, &argvars[1], ic))
9452 ++n;
9457 else
9458 EMSG2(_(e_listdictarg), "count()");
9459 rettv->vval.v_number = n;
9463 * "cscope_connection([{num} , {dbpath} [, {prepend}]])" function
9465 * Checks the existence of a cscope connection.
9467 static void
9468 f_cscope_connection(argvars, rettv)
9469 typval_T *argvars UNUSED;
9470 typval_T *rettv UNUSED;
9472 #ifdef FEAT_CSCOPE
9473 int num = 0;
9474 char_u *dbpath = NULL;
9475 char_u *prepend = NULL;
9476 char_u buf[NUMBUFLEN];
9478 if (argvars[0].v_type != VAR_UNKNOWN
9479 && argvars[1].v_type != VAR_UNKNOWN)
9481 num = (int)get_tv_number(&argvars[0]);
9482 dbpath = get_tv_string(&argvars[1]);
9483 if (argvars[2].v_type != VAR_UNKNOWN)
9484 prepend = get_tv_string_buf(&argvars[2], buf);
9487 rettv->vval.v_number = cs_connection(num, dbpath, prepend);
9488 #endif
9492 * "cursor(lnum, col)" function
9494 * Moves the cursor to the specified line and column.
9495 * Returns 0 when the position could be set, -1 otherwise.
9497 static void
9498 f_cursor(argvars, rettv)
9499 typval_T *argvars;
9500 typval_T *rettv;
9502 long line, col;
9503 #ifdef FEAT_VIRTUALEDIT
9504 long coladd = 0;
9505 #endif
9507 rettv->vval.v_number = -1;
9508 if (argvars[1].v_type == VAR_UNKNOWN)
9510 pos_T pos;
9512 if (list2fpos(argvars, &pos, NULL) == FAIL)
9513 return;
9514 line = pos.lnum;
9515 col = pos.col;
9516 #ifdef FEAT_VIRTUALEDIT
9517 coladd = pos.coladd;
9518 #endif
9520 else
9522 line = get_tv_lnum(argvars);
9523 col = get_tv_number_chk(&argvars[1], NULL);
9524 #ifdef FEAT_VIRTUALEDIT
9525 if (argvars[2].v_type != VAR_UNKNOWN)
9526 coladd = get_tv_number_chk(&argvars[2], NULL);
9527 #endif
9529 if (line < 0 || col < 0
9530 #ifdef FEAT_VIRTUALEDIT
9531 || coladd < 0
9532 #endif
9534 return; /* type error; errmsg already given */
9535 if (line > 0)
9536 curwin->w_cursor.lnum = line;
9537 if (col > 0)
9538 curwin->w_cursor.col = col - 1;
9539 #ifdef FEAT_VIRTUALEDIT
9540 curwin->w_cursor.coladd = coladd;
9541 #endif
9543 /* Make sure the cursor is in a valid position. */
9544 check_cursor();
9545 #ifdef FEAT_MBYTE
9546 /* Correct cursor for multi-byte character. */
9547 if (has_mbyte)
9548 mb_adjust_cursor();
9549 #endif
9551 curwin->w_set_curswant = TRUE;
9552 rettv->vval.v_number = 0;
9556 * "deepcopy()" function
9558 static void
9559 f_deepcopy(argvars, rettv)
9560 typval_T *argvars;
9561 typval_T *rettv;
9563 int noref = 0;
9565 if (argvars[1].v_type != VAR_UNKNOWN)
9566 noref = get_tv_number_chk(&argvars[1], NULL);
9567 if (noref < 0 || noref > 1)
9568 EMSG(_(e_invarg));
9569 else
9571 current_copyID += COPYID_INC;
9572 item_copy(&argvars[0], rettv, TRUE, noref == 0 ? current_copyID : 0);
9577 * "delete()" function
9579 static void
9580 f_delete(argvars, rettv)
9581 typval_T *argvars;
9582 typval_T *rettv;
9584 if (check_restricted() || check_secure())
9585 rettv->vval.v_number = -1;
9586 else
9587 rettv->vval.v_number = mch_remove(get_tv_string(&argvars[0]));
9591 * "did_filetype()" function
9593 static void
9594 f_did_filetype(argvars, rettv)
9595 typval_T *argvars UNUSED;
9596 typval_T *rettv UNUSED;
9598 #ifdef FEAT_AUTOCMD
9599 rettv->vval.v_number = did_filetype;
9600 #endif
9604 * "diff_filler()" function
9606 static void
9607 f_diff_filler(argvars, rettv)
9608 typval_T *argvars UNUSED;
9609 typval_T *rettv UNUSED;
9611 #ifdef FEAT_DIFF
9612 rettv->vval.v_number = diff_check_fill(curwin, get_tv_lnum(argvars));
9613 #endif
9617 * "diff_hlID()" function
9619 static void
9620 f_diff_hlID(argvars, rettv)
9621 typval_T *argvars UNUSED;
9622 typval_T *rettv UNUSED;
9624 #ifdef FEAT_DIFF
9625 linenr_T lnum = get_tv_lnum(argvars);
9626 static linenr_T prev_lnum = 0;
9627 static int changedtick = 0;
9628 static int fnum = 0;
9629 static int change_start = 0;
9630 static int change_end = 0;
9631 static hlf_T hlID = (hlf_T)0;
9632 int filler_lines;
9633 int col;
9635 if (lnum < 0) /* ignore type error in {lnum} arg */
9636 lnum = 0;
9637 if (lnum != prev_lnum
9638 || changedtick != curbuf->b_changedtick
9639 || fnum != curbuf->b_fnum)
9641 /* New line, buffer, change: need to get the values. */
9642 filler_lines = diff_check(curwin, lnum);
9643 if (filler_lines < 0)
9645 if (filler_lines == -1)
9647 change_start = MAXCOL;
9648 change_end = -1;
9649 if (diff_find_change(curwin, lnum, &change_start, &change_end))
9650 hlID = HLF_ADD; /* added line */
9651 else
9652 hlID = HLF_CHD; /* changed line */
9654 else
9655 hlID = HLF_ADD; /* added line */
9657 else
9658 hlID = (hlf_T)0;
9659 prev_lnum = lnum;
9660 changedtick = curbuf->b_changedtick;
9661 fnum = curbuf->b_fnum;
9664 if (hlID == HLF_CHD || hlID == HLF_TXD)
9666 col = get_tv_number(&argvars[1]) - 1; /* ignore type error in {col} */
9667 if (col >= change_start && col <= change_end)
9668 hlID = HLF_TXD; /* changed text */
9669 else
9670 hlID = HLF_CHD; /* changed line */
9672 rettv->vval.v_number = hlID == (hlf_T)0 ? 0 : (int)hlID;
9673 #endif
9677 * "empty({expr})" function
9679 static void
9680 f_empty(argvars, rettv)
9681 typval_T *argvars;
9682 typval_T *rettv;
9684 int n;
9686 switch (argvars[0].v_type)
9688 case VAR_STRING:
9689 case VAR_FUNC:
9690 n = argvars[0].vval.v_string == NULL
9691 || *argvars[0].vval.v_string == NUL;
9692 break;
9693 case VAR_NUMBER:
9694 n = argvars[0].vval.v_number == 0;
9695 break;
9696 #ifdef FEAT_FLOAT
9697 case VAR_FLOAT:
9698 n = argvars[0].vval.v_float == 0.0;
9699 break;
9700 #endif
9701 case VAR_LIST:
9702 n = argvars[0].vval.v_list == NULL
9703 || argvars[0].vval.v_list->lv_first == NULL;
9704 break;
9705 case VAR_DICT:
9706 n = argvars[0].vval.v_dict == NULL
9707 || argvars[0].vval.v_dict->dv_hashtab.ht_used == 0;
9708 break;
9709 default:
9710 EMSG2(_(e_intern2), "f_empty()");
9711 n = 0;
9714 rettv->vval.v_number = n;
9718 * "escape({string}, {chars})" function
9720 static void
9721 f_escape(argvars, rettv)
9722 typval_T *argvars;
9723 typval_T *rettv;
9725 char_u buf[NUMBUFLEN];
9727 rettv->vval.v_string = vim_strsave_escaped(get_tv_string(&argvars[0]),
9728 get_tv_string_buf(&argvars[1], buf));
9729 rettv->v_type = VAR_STRING;
9733 * "eval()" function
9735 static void
9736 f_eval(argvars, rettv)
9737 typval_T *argvars;
9738 typval_T *rettv;
9740 char_u *s;
9742 s = get_tv_string_chk(&argvars[0]);
9743 if (s != NULL)
9744 s = skipwhite(s);
9746 if (s == NULL || eval1(&s, rettv, TRUE) == FAIL)
9748 rettv->v_type = VAR_NUMBER;
9749 rettv->vval.v_number = 0;
9751 else if (*s != NUL)
9752 EMSG(_(e_trailing));
9756 * "eventhandler()" function
9758 static void
9759 f_eventhandler(argvars, rettv)
9760 typval_T *argvars UNUSED;
9761 typval_T *rettv;
9763 rettv->vval.v_number = vgetc_busy;
9767 * "executable()" function
9769 static void
9770 f_executable(argvars, rettv)
9771 typval_T *argvars;
9772 typval_T *rettv;
9774 rettv->vval.v_number = mch_can_exe(get_tv_string(&argvars[0]));
9778 * "exists()" function
9780 static void
9781 f_exists(argvars, rettv)
9782 typval_T *argvars;
9783 typval_T *rettv;
9785 char_u *p;
9786 char_u *name;
9787 int n = FALSE;
9788 int len = 0;
9790 p = get_tv_string(&argvars[0]);
9791 if (*p == '$') /* environment variable */
9793 /* first try "normal" environment variables (fast) */
9794 if (mch_getenv(p + 1) != NULL)
9795 n = TRUE;
9796 else
9798 /* try expanding things like $VIM and ${HOME} */
9799 p = expand_env_save(p);
9800 if (p != NULL && *p != '$')
9801 n = TRUE;
9802 vim_free(p);
9805 else if (*p == '&' || *p == '+') /* option */
9807 n = (get_option_tv(&p, NULL, TRUE) == OK);
9808 if (*skipwhite(p) != NUL)
9809 n = FALSE; /* trailing garbage */
9811 else if (*p == '*') /* internal or user defined function */
9813 n = function_exists(p + 1);
9815 else if (*p == ':')
9817 n = cmd_exists(p + 1);
9819 else if (*p == '#')
9821 #ifdef FEAT_AUTOCMD
9822 if (p[1] == '#')
9823 n = autocmd_supported(p + 2);
9824 else
9825 n = au_exists(p + 1);
9826 #endif
9828 else /* internal variable */
9830 char_u *tofree;
9831 typval_T tv;
9833 /* get_name_len() takes care of expanding curly braces */
9834 name = p;
9835 len = get_name_len(&p, &tofree, TRUE, FALSE);
9836 if (len > 0)
9838 if (tofree != NULL)
9839 name = tofree;
9840 n = (get_var_tv(name, len, &tv, FALSE) == OK);
9841 if (n)
9843 /* handle d.key, l[idx], f(expr) */
9844 n = (handle_subscript(&p, &tv, TRUE, FALSE) == OK);
9845 if (n)
9846 clear_tv(&tv);
9849 if (*p != NUL)
9850 n = FALSE;
9852 vim_free(tofree);
9855 rettv->vval.v_number = n;
9859 * "expand()" function
9861 static void
9862 f_expand(argvars, rettv)
9863 typval_T *argvars;
9864 typval_T *rettv;
9866 char_u *s;
9867 int len;
9868 char_u *errormsg;
9869 int flags = WILD_SILENT|WILD_USE_NL|WILD_LIST_NOTFOUND;
9870 expand_T xpc;
9871 int error = FALSE;
9873 rettv->v_type = VAR_STRING;
9874 s = get_tv_string(&argvars[0]);
9875 if (*s == '%' || *s == '#' || *s == '<')
9877 ++emsg_off;
9878 rettv->vval.v_string = eval_vars(s, s, &len, NULL, &errormsg, NULL);
9879 --emsg_off;
9881 else
9883 /* When the optional second argument is non-zero, don't remove matches
9884 * for 'wildignore' and don't put matches for 'suffixes' at the end. */
9885 if (argvars[1].v_type != VAR_UNKNOWN
9886 && get_tv_number_chk(&argvars[1], &error))
9887 flags |= WILD_KEEP_ALL;
9888 if (!error)
9890 ExpandInit(&xpc);
9891 xpc.xp_context = EXPAND_FILES;
9892 rettv->vval.v_string = ExpandOne(&xpc, s, NULL, flags, WILD_ALL);
9894 else
9895 rettv->vval.v_string = NULL;
9900 * "extend(list, list [, idx])" function
9901 * "extend(dict, dict [, action])" function
9903 static void
9904 f_extend(argvars, rettv)
9905 typval_T *argvars;
9906 typval_T *rettv;
9908 if (argvars[0].v_type == VAR_LIST && argvars[1].v_type == VAR_LIST)
9910 list_T *l1, *l2;
9911 listitem_T *item;
9912 long before;
9913 int error = FALSE;
9915 l1 = argvars[0].vval.v_list;
9916 l2 = argvars[1].vval.v_list;
9917 if (l1 != NULL && !tv_check_lock(l1->lv_lock, (char_u *)"extend()")
9918 && l2 != NULL)
9920 if (argvars[2].v_type != VAR_UNKNOWN)
9922 before = get_tv_number_chk(&argvars[2], &error);
9923 if (error)
9924 return; /* type error; errmsg already given */
9926 if (before == l1->lv_len)
9927 item = NULL;
9928 else
9930 item = list_find(l1, before);
9931 if (item == NULL)
9933 EMSGN(_(e_listidx), before);
9934 return;
9938 else
9939 item = NULL;
9940 list_extend(l1, l2, item);
9942 copy_tv(&argvars[0], rettv);
9945 else if (argvars[0].v_type == VAR_DICT && argvars[1].v_type == VAR_DICT)
9947 dict_T *d1, *d2;
9948 dictitem_T *di1;
9949 char_u *action;
9950 int i;
9951 hashitem_T *hi2;
9952 int todo;
9954 d1 = argvars[0].vval.v_dict;
9955 d2 = argvars[1].vval.v_dict;
9956 if (d1 != NULL && !tv_check_lock(d1->dv_lock, (char_u *)"extend()")
9957 && d2 != NULL)
9959 /* Check the third argument. */
9960 if (argvars[2].v_type != VAR_UNKNOWN)
9962 static char *(av[]) = {"keep", "force", "error"};
9964 action = get_tv_string_chk(&argvars[2]);
9965 if (action == NULL)
9966 return; /* type error; errmsg already given */
9967 for (i = 0; i < 3; ++i)
9968 if (STRCMP(action, av[i]) == 0)
9969 break;
9970 if (i == 3)
9972 EMSG2(_(e_invarg2), action);
9973 return;
9976 else
9977 action = (char_u *)"force";
9979 /* Go over all entries in the second dict and add them to the
9980 * first dict. */
9981 todo = (int)d2->dv_hashtab.ht_used;
9982 for (hi2 = d2->dv_hashtab.ht_array; todo > 0; ++hi2)
9984 if (!HASHITEM_EMPTY(hi2))
9986 --todo;
9987 di1 = dict_find(d1, hi2->hi_key, -1);
9988 if (di1 == NULL)
9990 di1 = dictitem_copy(HI2DI(hi2));
9991 if (di1 != NULL && dict_add(d1, di1) == FAIL)
9992 dictitem_free(di1);
9994 else if (*action == 'e')
9996 EMSG2(_("E737: Key already exists: %s"), hi2->hi_key);
9997 break;
9999 else if (*action == 'f')
10001 clear_tv(&di1->di_tv);
10002 copy_tv(&HI2DI(hi2)->di_tv, &di1->di_tv);
10007 copy_tv(&argvars[0], rettv);
10010 else
10011 EMSG2(_(e_listdictarg), "extend()");
10015 * "feedkeys()" function
10017 static void
10018 f_feedkeys(argvars, rettv)
10019 typval_T *argvars;
10020 typval_T *rettv UNUSED;
10022 int remap = TRUE;
10023 char_u *keys, *flags;
10024 char_u nbuf[NUMBUFLEN];
10025 int typed = FALSE;
10026 char_u *keys_esc;
10028 /* This is not allowed in the sandbox. If the commands would still be
10029 * executed in the sandbox it would be OK, but it probably happens later,
10030 * when "sandbox" is no longer set. */
10031 if (check_secure())
10032 return;
10034 keys = get_tv_string(&argvars[0]);
10035 if (*keys != NUL)
10037 if (argvars[1].v_type != VAR_UNKNOWN)
10039 flags = get_tv_string_buf(&argvars[1], nbuf);
10040 for ( ; *flags != NUL; ++flags)
10042 switch (*flags)
10044 case 'n': remap = FALSE; break;
10045 case 'm': remap = TRUE; break;
10046 case 't': typed = TRUE; break;
10051 /* Need to escape K_SPECIAL and CSI before putting the string in the
10052 * typeahead buffer. */
10053 keys_esc = vim_strsave_escape_csi(keys);
10054 if (keys_esc != NULL)
10056 ins_typebuf(keys_esc, (remap ? REMAP_YES : REMAP_NONE),
10057 typebuf.tb_len, !typed, FALSE);
10058 vim_free(keys_esc);
10059 if (vgetc_busy)
10060 typebuf_was_filled = TRUE;
10066 * "filereadable()" function
10068 static void
10069 f_filereadable(argvars, rettv)
10070 typval_T *argvars;
10071 typval_T *rettv;
10073 int fd;
10074 char_u *p;
10075 int n;
10077 #ifndef O_NONBLOCK
10078 # define O_NONBLOCK 0
10079 #endif
10080 p = get_tv_string(&argvars[0]);
10081 if (*p && !mch_isdir(p) && (fd = mch_open((char *)p,
10082 O_RDONLY | O_NONBLOCK, 0)) >= 0)
10084 n = TRUE;
10085 close(fd);
10087 else
10088 n = FALSE;
10090 rettv->vval.v_number = n;
10094 * Return 0 for not writable, 1 for writable file, 2 for a dir which we have
10095 * rights to write into.
10097 static void
10098 f_filewritable(argvars, rettv)
10099 typval_T *argvars;
10100 typval_T *rettv;
10102 rettv->vval.v_number = filewritable(get_tv_string(&argvars[0]));
10105 static void findfilendir __ARGS((typval_T *argvars, typval_T *rettv, int find_what));
10107 static void
10108 findfilendir(argvars, rettv, find_what)
10109 typval_T *argvars;
10110 typval_T *rettv;
10111 int find_what;
10113 #ifdef FEAT_SEARCHPATH
10114 char_u *fname;
10115 char_u *fresult = NULL;
10116 char_u *path = *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path;
10117 char_u *p;
10118 char_u pathbuf[NUMBUFLEN];
10119 int count = 1;
10120 int first = TRUE;
10121 int error = FALSE;
10122 #endif
10124 rettv->vval.v_string = NULL;
10125 rettv->v_type = VAR_STRING;
10127 #ifdef FEAT_SEARCHPATH
10128 fname = get_tv_string(&argvars[0]);
10130 if (argvars[1].v_type != VAR_UNKNOWN)
10132 p = get_tv_string_buf_chk(&argvars[1], pathbuf);
10133 if (p == NULL)
10134 error = TRUE;
10135 else
10137 if (*p != NUL)
10138 path = p;
10140 if (argvars[2].v_type != VAR_UNKNOWN)
10141 count = get_tv_number_chk(&argvars[2], &error);
10145 if (count < 0 && rettv_list_alloc(rettv) == FAIL)
10146 error = TRUE;
10148 if (*fname != NUL && !error)
10152 if (rettv->v_type == VAR_STRING)
10153 vim_free(fresult);
10154 fresult = find_file_in_path_option(first ? fname : NULL,
10155 first ? (int)STRLEN(fname) : 0,
10156 0, first, path,
10157 find_what,
10158 curbuf->b_ffname,
10159 find_what == FINDFILE_DIR
10160 ? (char_u *)"" : curbuf->b_p_sua);
10161 first = FALSE;
10163 if (fresult != NULL && rettv->v_type == VAR_LIST)
10164 list_append_string(rettv->vval.v_list, fresult, -1);
10166 } while ((rettv->v_type == VAR_LIST || --count > 0) && fresult != NULL);
10169 if (rettv->v_type == VAR_STRING)
10170 rettv->vval.v_string = fresult;
10171 #endif
10174 static void filter_map __ARGS((typval_T *argvars, typval_T *rettv, int map));
10175 static int filter_map_one __ARGS((typval_T *tv, char_u *expr, int map, int *remp));
10178 * Implementation of map() and filter().
10180 static void
10181 filter_map(argvars, rettv, map)
10182 typval_T *argvars;
10183 typval_T *rettv;
10184 int map;
10186 char_u buf[NUMBUFLEN];
10187 char_u *expr;
10188 listitem_T *li, *nli;
10189 list_T *l = NULL;
10190 dictitem_T *di;
10191 hashtab_T *ht;
10192 hashitem_T *hi;
10193 dict_T *d = NULL;
10194 typval_T save_val;
10195 typval_T save_key;
10196 int rem;
10197 int todo;
10198 char_u *ermsg = map ? (char_u *)"map()" : (char_u *)"filter()";
10199 int save_did_emsg;
10200 int index = 0;
10202 if (argvars[0].v_type == VAR_LIST)
10204 if ((l = argvars[0].vval.v_list) == NULL
10205 || (map && tv_check_lock(l->lv_lock, ermsg)))
10206 return;
10208 else if (argvars[0].v_type == VAR_DICT)
10210 if ((d = argvars[0].vval.v_dict) == NULL
10211 || (map && tv_check_lock(d->dv_lock, ermsg)))
10212 return;
10214 else
10216 EMSG2(_(e_listdictarg), ermsg);
10217 return;
10220 expr = get_tv_string_buf_chk(&argvars[1], buf);
10221 /* On type errors, the preceding call has already displayed an error
10222 * message. Avoid a misleading error message for an empty string that
10223 * was not passed as argument. */
10224 if (expr != NULL)
10226 prepare_vimvar(VV_VAL, &save_val);
10227 expr = skipwhite(expr);
10229 /* We reset "did_emsg" to be able to detect whether an error
10230 * occurred during evaluation of the expression. */
10231 save_did_emsg = did_emsg;
10232 did_emsg = FALSE;
10234 prepare_vimvar(VV_KEY, &save_key);
10235 if (argvars[0].v_type == VAR_DICT)
10237 vimvars[VV_KEY].vv_type = VAR_STRING;
10239 ht = &d->dv_hashtab;
10240 hash_lock(ht);
10241 todo = (int)ht->ht_used;
10242 for (hi = ht->ht_array; todo > 0; ++hi)
10244 if (!HASHITEM_EMPTY(hi))
10246 --todo;
10247 di = HI2DI(hi);
10248 if (tv_check_lock(di->di_tv.v_lock, ermsg))
10249 break;
10250 vimvars[VV_KEY].vv_str = vim_strsave(di->di_key);
10251 if (filter_map_one(&di->di_tv, expr, map, &rem) == FAIL
10252 || did_emsg)
10253 break;
10254 if (!map && rem)
10255 dictitem_remove(d, di);
10256 clear_tv(&vimvars[VV_KEY].vv_tv);
10259 hash_unlock(ht);
10261 else
10263 vimvars[VV_KEY].vv_type = VAR_NUMBER;
10265 for (li = l->lv_first; li != NULL; li = nli)
10267 if (tv_check_lock(li->li_tv.v_lock, ermsg))
10268 break;
10269 nli = li->li_next;
10270 vimvars[VV_KEY].vv_nr = index;
10271 if (filter_map_one(&li->li_tv, expr, map, &rem) == FAIL
10272 || did_emsg)
10273 break;
10274 if (!map && rem)
10275 listitem_remove(l, li);
10276 ++index;
10280 restore_vimvar(VV_KEY, &save_key);
10281 restore_vimvar(VV_VAL, &save_val);
10283 did_emsg |= save_did_emsg;
10286 copy_tv(&argvars[0], rettv);
10289 static int
10290 filter_map_one(tv, expr, map, remp)
10291 typval_T *tv;
10292 char_u *expr;
10293 int map;
10294 int *remp;
10296 typval_T rettv;
10297 char_u *s;
10298 int retval = FAIL;
10300 copy_tv(tv, &vimvars[VV_VAL].vv_tv);
10301 s = expr;
10302 if (eval1(&s, &rettv, TRUE) == FAIL)
10303 goto theend;
10304 if (*s != NUL) /* check for trailing chars after expr */
10306 EMSG2(_(e_invexpr2), s);
10307 goto theend;
10309 if (map)
10311 /* map(): replace the list item value */
10312 clear_tv(tv);
10313 rettv.v_lock = 0;
10314 *tv = rettv;
10316 else
10318 int error = FALSE;
10320 /* filter(): when expr is zero remove the item */
10321 *remp = (get_tv_number_chk(&rettv, &error) == 0);
10322 clear_tv(&rettv);
10323 /* On type error, nothing has been removed; return FAIL to stop the
10324 * loop. The error message was given by get_tv_number_chk(). */
10325 if (error)
10326 goto theend;
10328 retval = OK;
10329 theend:
10330 clear_tv(&vimvars[VV_VAL].vv_tv);
10331 return retval;
10335 * "filter()" function
10337 static void
10338 f_filter(argvars, rettv)
10339 typval_T *argvars;
10340 typval_T *rettv;
10342 filter_map(argvars, rettv, FALSE);
10346 * "finddir({fname}[, {path}[, {count}]])" function
10348 static void
10349 f_finddir(argvars, rettv)
10350 typval_T *argvars;
10351 typval_T *rettv;
10353 findfilendir(argvars, rettv, FINDFILE_DIR);
10357 * "findfile({fname}[, {path}[, {count}]])" function
10359 static void
10360 f_findfile(argvars, rettv)
10361 typval_T *argvars;
10362 typval_T *rettv;
10364 findfilendir(argvars, rettv, FINDFILE_FILE);
10367 #ifdef FEAT_FLOAT
10369 * "float2nr({float})" function
10371 static void
10372 f_float2nr(argvars, rettv)
10373 typval_T *argvars;
10374 typval_T *rettv;
10376 float_T f;
10378 if (get_float_arg(argvars, &f) == OK)
10380 if (f < -0x7fffffff)
10381 rettv->vval.v_number = -0x7fffffff;
10382 else if (f > 0x7fffffff)
10383 rettv->vval.v_number = 0x7fffffff;
10384 else
10385 rettv->vval.v_number = (varnumber_T)f;
10390 * "floor({float})" function
10392 static void
10393 f_floor(argvars, rettv)
10394 typval_T *argvars;
10395 typval_T *rettv;
10397 float_T f;
10399 rettv->v_type = VAR_FLOAT;
10400 if (get_float_arg(argvars, &f) == OK)
10401 rettv->vval.v_float = floor(f);
10402 else
10403 rettv->vval.v_float = 0.0;
10405 #endif
10408 * "fnameescape({string})" function
10410 static void
10411 f_fnameescape(argvars, rettv)
10412 typval_T *argvars;
10413 typval_T *rettv;
10415 rettv->vval.v_string = vim_strsave_fnameescape(
10416 get_tv_string(&argvars[0]), FALSE);
10417 rettv->v_type = VAR_STRING;
10421 * "fnamemodify({fname}, {mods})" function
10423 static void
10424 f_fnamemodify(argvars, rettv)
10425 typval_T *argvars;
10426 typval_T *rettv;
10428 char_u *fname;
10429 char_u *mods;
10430 int usedlen = 0;
10431 int len;
10432 char_u *fbuf = NULL;
10433 char_u buf[NUMBUFLEN];
10435 fname = get_tv_string_chk(&argvars[0]);
10436 mods = get_tv_string_buf_chk(&argvars[1], buf);
10437 if (fname == NULL || mods == NULL)
10438 fname = NULL;
10439 else
10441 len = (int)STRLEN(fname);
10442 (void)modify_fname(mods, &usedlen, &fname, &fbuf, &len);
10445 rettv->v_type = VAR_STRING;
10446 if (fname == NULL)
10447 rettv->vval.v_string = NULL;
10448 else
10449 rettv->vval.v_string = vim_strnsave(fname, len);
10450 vim_free(fbuf);
10453 static void foldclosed_both __ARGS((typval_T *argvars, typval_T *rettv, int end));
10456 * "foldclosed()" function
10458 static void
10459 foldclosed_both(argvars, rettv, end)
10460 typval_T *argvars;
10461 typval_T *rettv;
10462 int end;
10464 #ifdef FEAT_FOLDING
10465 linenr_T lnum;
10466 linenr_T first, last;
10468 lnum = get_tv_lnum(argvars);
10469 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
10471 if (hasFoldingWin(curwin, lnum, &first, &last, FALSE, NULL))
10473 if (end)
10474 rettv->vval.v_number = (varnumber_T)last;
10475 else
10476 rettv->vval.v_number = (varnumber_T)first;
10477 return;
10480 #endif
10481 rettv->vval.v_number = -1;
10485 * "foldclosed()" function
10487 static void
10488 f_foldclosed(argvars, rettv)
10489 typval_T *argvars;
10490 typval_T *rettv;
10492 foldclosed_both(argvars, rettv, FALSE);
10496 * "foldclosedend()" function
10498 static void
10499 f_foldclosedend(argvars, rettv)
10500 typval_T *argvars;
10501 typval_T *rettv;
10503 foldclosed_both(argvars, rettv, TRUE);
10507 * "foldlevel()" function
10509 static void
10510 f_foldlevel(argvars, rettv)
10511 typval_T *argvars;
10512 typval_T *rettv;
10514 #ifdef FEAT_FOLDING
10515 linenr_T lnum;
10517 lnum = get_tv_lnum(argvars);
10518 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
10519 rettv->vval.v_number = foldLevel(lnum);
10520 #endif
10524 * "foldtext()" function
10526 static void
10527 f_foldtext(argvars, rettv)
10528 typval_T *argvars UNUSED;
10529 typval_T *rettv;
10531 #ifdef FEAT_FOLDING
10532 linenr_T lnum;
10533 char_u *s;
10534 char_u *r;
10535 int len;
10536 char *txt;
10537 #endif
10539 rettv->v_type = VAR_STRING;
10540 rettv->vval.v_string = NULL;
10541 #ifdef FEAT_FOLDING
10542 if ((linenr_T)vimvars[VV_FOLDSTART].vv_nr > 0
10543 && (linenr_T)vimvars[VV_FOLDEND].vv_nr
10544 <= curbuf->b_ml.ml_line_count
10545 && vimvars[VV_FOLDDASHES].vv_str != NULL)
10547 /* Find first non-empty line in the fold. */
10548 lnum = (linenr_T)vimvars[VV_FOLDSTART].vv_nr;
10549 while (lnum < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
10551 if (!linewhite(lnum))
10552 break;
10553 ++lnum;
10556 /* Find interesting text in this line. */
10557 s = skipwhite(ml_get(lnum));
10558 /* skip C comment-start */
10559 if (s[0] == '/' && (s[1] == '*' || s[1] == '/'))
10561 s = skipwhite(s + 2);
10562 if (*skipwhite(s) == NUL
10563 && lnum + 1 < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
10565 s = skipwhite(ml_get(lnum + 1));
10566 if (*s == '*')
10567 s = skipwhite(s + 1);
10570 txt = _("+-%s%3ld lines: ");
10571 r = alloc((unsigned)(STRLEN(txt)
10572 + STRLEN(vimvars[VV_FOLDDASHES].vv_str) /* for %s */
10573 + 20 /* for %3ld */
10574 + STRLEN(s))); /* concatenated */
10575 if (r != NULL)
10577 sprintf((char *)r, txt, vimvars[VV_FOLDDASHES].vv_str,
10578 (long)((linenr_T)vimvars[VV_FOLDEND].vv_nr
10579 - (linenr_T)vimvars[VV_FOLDSTART].vv_nr + 1));
10580 len = (int)STRLEN(r);
10581 STRCAT(r, s);
10582 /* remove 'foldmarker' and 'commentstring' */
10583 foldtext_cleanup(r + len);
10584 rettv->vval.v_string = r;
10587 #endif
10591 * "foldtextresult(lnum)" function
10593 static void
10594 f_foldtextresult(argvars, rettv)
10595 typval_T *argvars UNUSED;
10596 typval_T *rettv;
10598 #ifdef FEAT_FOLDING
10599 linenr_T lnum;
10600 char_u *text;
10601 char_u buf[51];
10602 foldinfo_T foldinfo;
10603 int fold_count;
10604 #endif
10606 rettv->v_type = VAR_STRING;
10607 rettv->vval.v_string = NULL;
10608 #ifdef FEAT_FOLDING
10609 lnum = get_tv_lnum(argvars);
10610 /* treat illegal types and illegal string values for {lnum} the same */
10611 if (lnum < 0)
10612 lnum = 0;
10613 fold_count = foldedCount(curwin, lnum, &foldinfo);
10614 if (fold_count > 0)
10616 text = get_foldtext(curwin, lnum, lnum + fold_count - 1,
10617 &foldinfo, buf);
10618 if (text == buf)
10619 text = vim_strsave(text);
10620 rettv->vval.v_string = text;
10622 #endif
10626 * "foreground()" function
10628 static void
10629 f_foreground(argvars, rettv)
10630 typval_T *argvars UNUSED;
10631 typval_T *rettv UNUSED;
10633 #ifdef FEAT_GUI
10634 if (gui.in_use)
10635 gui_mch_set_foreground();
10636 #else
10637 # ifdef WIN32
10638 win32_set_foreground();
10639 # endif
10640 #endif
10644 * "function()" function
10646 static void
10647 f_function(argvars, rettv)
10648 typval_T *argvars;
10649 typval_T *rettv;
10651 char_u *s;
10653 s = get_tv_string(&argvars[0]);
10654 if (s == NULL || *s == NUL || VIM_ISDIGIT(*s))
10655 EMSG2(_(e_invarg2), s);
10656 /* Don't check an autoload name for existence here. */
10657 else if (vim_strchr(s, AUTOLOAD_CHAR) == NULL && !function_exists(s))
10658 EMSG2(_("E700: Unknown function: %s"), s);
10659 else
10661 rettv->vval.v_string = vim_strsave(s);
10662 rettv->v_type = VAR_FUNC;
10667 * "garbagecollect()" function
10669 static void
10670 f_garbagecollect(argvars, rettv)
10671 typval_T *argvars;
10672 typval_T *rettv UNUSED;
10674 /* This is postponed until we are back at the toplevel, because we may be
10675 * using Lists and Dicts internally. E.g.: ":echo [garbagecollect()]". */
10676 want_garbage_collect = TRUE;
10678 if (argvars[0].v_type != VAR_UNKNOWN && get_tv_number(&argvars[0]) == 1)
10679 garbage_collect_at_exit = TRUE;
10683 * "get()" function
10685 static void
10686 f_get(argvars, rettv)
10687 typval_T *argvars;
10688 typval_T *rettv;
10690 listitem_T *li;
10691 list_T *l;
10692 dictitem_T *di;
10693 dict_T *d;
10694 typval_T *tv = NULL;
10696 if (argvars[0].v_type == VAR_LIST)
10698 if ((l = argvars[0].vval.v_list) != NULL)
10700 int error = FALSE;
10702 li = list_find(l, get_tv_number_chk(&argvars[1], &error));
10703 if (!error && li != NULL)
10704 tv = &li->li_tv;
10707 else if (argvars[0].v_type == VAR_DICT)
10709 if ((d = argvars[0].vval.v_dict) != NULL)
10711 di = dict_find(d, get_tv_string(&argvars[1]), -1);
10712 if (di != NULL)
10713 tv = &di->di_tv;
10716 else
10717 EMSG2(_(e_listdictarg), "get()");
10719 if (tv == NULL)
10721 if (argvars[2].v_type != VAR_UNKNOWN)
10722 copy_tv(&argvars[2], rettv);
10724 else
10725 copy_tv(tv, rettv);
10728 static void get_buffer_lines __ARGS((buf_T *buf, linenr_T start, linenr_T end, int retlist, typval_T *rettv));
10731 * Get line or list of lines from buffer "buf" into "rettv".
10732 * Return a range (from start to end) of lines in rettv from the specified
10733 * buffer.
10734 * If 'retlist' is TRUE, then the lines are returned as a Vim List.
10736 static void
10737 get_buffer_lines(buf, start, end, retlist, rettv)
10738 buf_T *buf;
10739 linenr_T start;
10740 linenr_T end;
10741 int retlist;
10742 typval_T *rettv;
10744 char_u *p;
10746 if (retlist && rettv_list_alloc(rettv) == FAIL)
10747 return;
10749 if (buf == NULL || buf->b_ml.ml_mfp == NULL || start < 0)
10750 return;
10752 if (!retlist)
10754 if (start >= 1 && start <= buf->b_ml.ml_line_count)
10755 p = ml_get_buf(buf, start, FALSE);
10756 else
10757 p = (char_u *)"";
10759 rettv->v_type = VAR_STRING;
10760 rettv->vval.v_string = vim_strsave(p);
10762 else
10764 if (end < start)
10765 return;
10767 if (start < 1)
10768 start = 1;
10769 if (end > buf->b_ml.ml_line_count)
10770 end = buf->b_ml.ml_line_count;
10771 while (start <= end)
10772 if (list_append_string(rettv->vval.v_list,
10773 ml_get_buf(buf, start++, FALSE), -1) == FAIL)
10774 break;
10779 * "getbufline()" function
10781 static void
10782 f_getbufline(argvars, rettv)
10783 typval_T *argvars;
10784 typval_T *rettv;
10786 linenr_T lnum;
10787 linenr_T end;
10788 buf_T *buf;
10790 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
10791 ++emsg_off;
10792 buf = get_buf_tv(&argvars[0]);
10793 --emsg_off;
10795 lnum = get_tv_lnum_buf(&argvars[1], buf);
10796 if (argvars[2].v_type == VAR_UNKNOWN)
10797 end = lnum;
10798 else
10799 end = get_tv_lnum_buf(&argvars[2], buf);
10801 get_buffer_lines(buf, lnum, end, TRUE, rettv);
10805 * "getbufvar()" function
10807 static void
10808 f_getbufvar(argvars, rettv)
10809 typval_T *argvars;
10810 typval_T *rettv;
10812 buf_T *buf;
10813 buf_T *save_curbuf;
10814 char_u *varname;
10815 dictitem_T *v;
10817 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
10818 varname = get_tv_string_chk(&argvars[1]);
10819 ++emsg_off;
10820 buf = get_buf_tv(&argvars[0]);
10822 rettv->v_type = VAR_STRING;
10823 rettv->vval.v_string = NULL;
10825 if (buf != NULL && varname != NULL)
10827 /* set curbuf to be our buf, temporarily */
10828 save_curbuf = curbuf;
10829 curbuf = buf;
10831 if (*varname == '&') /* buffer-local-option */
10832 get_option_tv(&varname, rettv, TRUE);
10833 else
10835 if (*varname == NUL)
10836 /* let getbufvar({nr}, "") return the "b:" dictionary. The
10837 * scope prefix before the NUL byte is required by
10838 * find_var_in_ht(). */
10839 varname = (char_u *)"b:" + 2;
10840 /* look up the variable */
10841 v = find_var_in_ht(&curbuf->b_vars.dv_hashtab, varname, FALSE);
10842 if (v != NULL)
10843 copy_tv(&v->di_tv, rettv);
10846 /* restore previous notion of curbuf */
10847 curbuf = save_curbuf;
10850 --emsg_off;
10854 * "getchar()" function
10856 static void
10857 f_getchar(argvars, rettv)
10858 typval_T *argvars;
10859 typval_T *rettv;
10861 varnumber_T n;
10862 int error = FALSE;
10864 /* Position the cursor. Needed after a message that ends in a space. */
10865 windgoto(msg_row, msg_col);
10867 ++no_mapping;
10868 ++allow_keys;
10869 for (;;)
10871 if (argvars[0].v_type == VAR_UNKNOWN)
10872 /* getchar(): blocking wait. */
10873 n = safe_vgetc();
10874 else if (get_tv_number_chk(&argvars[0], &error) == 1)
10875 /* getchar(1): only check if char avail */
10876 n = vpeekc();
10877 else if (error || vpeekc() == NUL)
10878 /* illegal argument or getchar(0) and no char avail: return zero */
10879 n = 0;
10880 else
10881 /* getchar(0) and char avail: return char */
10882 n = safe_vgetc();
10883 if (n == K_IGNORE)
10884 continue;
10885 break;
10887 --no_mapping;
10888 --allow_keys;
10890 vimvars[VV_MOUSE_WIN].vv_nr = 0;
10891 vimvars[VV_MOUSE_LNUM].vv_nr = 0;
10892 vimvars[VV_MOUSE_COL].vv_nr = 0;
10894 rettv->vval.v_number = n;
10895 if (IS_SPECIAL(n) || mod_mask != 0)
10897 char_u temp[10]; /* modifier: 3, mbyte-char: 6, NUL: 1 */
10898 int i = 0;
10900 /* Turn a special key into three bytes, plus modifier. */
10901 if (mod_mask != 0)
10903 temp[i++] = K_SPECIAL;
10904 temp[i++] = KS_MODIFIER;
10905 temp[i++] = mod_mask;
10907 if (IS_SPECIAL(n))
10909 temp[i++] = K_SPECIAL;
10910 temp[i++] = K_SECOND(n);
10911 temp[i++] = K_THIRD(n);
10913 #ifdef FEAT_MBYTE
10914 else if (has_mbyte)
10915 i += (*mb_char2bytes)(n, temp + i);
10916 #endif
10917 else
10918 temp[i++] = n;
10919 temp[i++] = NUL;
10920 rettv->v_type = VAR_STRING;
10921 rettv->vval.v_string = vim_strsave(temp);
10923 #ifdef FEAT_MOUSE
10924 if (n == K_LEFTMOUSE
10925 || n == K_LEFTMOUSE_NM
10926 || n == K_LEFTDRAG
10927 || n == K_LEFTRELEASE
10928 || n == K_LEFTRELEASE_NM
10929 || n == K_MIDDLEMOUSE
10930 || n == K_MIDDLEDRAG
10931 || n == K_MIDDLERELEASE
10932 || n == K_RIGHTMOUSE
10933 || n == K_RIGHTDRAG
10934 || n == K_RIGHTRELEASE
10935 || n == K_X1MOUSE
10936 || n == K_X1DRAG
10937 || n == K_X1RELEASE
10938 || n == K_X2MOUSE
10939 || n == K_X2DRAG
10940 || n == K_X2RELEASE
10941 || n == K_MOUSEDOWN
10942 || n == K_MOUSEUP)
10944 int row = mouse_row;
10945 int col = mouse_col;
10946 win_T *win;
10947 linenr_T lnum;
10948 # ifdef FEAT_WINDOWS
10949 win_T *wp;
10950 # endif
10951 int winnr = 1;
10953 if (row >= 0 && col >= 0)
10955 /* Find the window at the mouse coordinates and compute the
10956 * text position. */
10957 win = mouse_find_win(&row, &col);
10958 (void)mouse_comp_pos(win, &row, &col, &lnum);
10959 # ifdef FEAT_WINDOWS
10960 for (wp = firstwin; wp != win; wp = wp->w_next)
10961 ++winnr;
10962 # endif
10963 vimvars[VV_MOUSE_WIN].vv_nr = winnr;
10964 vimvars[VV_MOUSE_LNUM].vv_nr = lnum;
10965 vimvars[VV_MOUSE_COL].vv_nr = col + 1;
10968 #endif
10973 * "getcharmod()" function
10975 static void
10976 f_getcharmod(argvars, rettv)
10977 typval_T *argvars UNUSED;
10978 typval_T *rettv;
10980 rettv->vval.v_number = mod_mask;
10984 * "getcmdline()" function
10986 static void
10987 f_getcmdline(argvars, rettv)
10988 typval_T *argvars UNUSED;
10989 typval_T *rettv;
10991 rettv->v_type = VAR_STRING;
10992 rettv->vval.v_string = get_cmdline_str();
10996 * "getcmdpos()" function
10998 static void
10999 f_getcmdpos(argvars, rettv)
11000 typval_T *argvars UNUSED;
11001 typval_T *rettv;
11003 rettv->vval.v_number = get_cmdline_pos() + 1;
11007 * "getcmdtype()" function
11009 static void
11010 f_getcmdtype(argvars, rettv)
11011 typval_T *argvars UNUSED;
11012 typval_T *rettv;
11014 rettv->v_type = VAR_STRING;
11015 rettv->vval.v_string = alloc(2);
11016 if (rettv->vval.v_string != NULL)
11018 rettv->vval.v_string[0] = get_cmdline_type();
11019 rettv->vval.v_string[1] = NUL;
11024 * "getcwd()" function
11026 static void
11027 f_getcwd(argvars, rettv)
11028 typval_T *argvars UNUSED;
11029 typval_T *rettv;
11031 char_u cwd[MAXPATHL];
11033 rettv->v_type = VAR_STRING;
11034 if (mch_dirname(cwd, MAXPATHL) == FAIL)
11035 rettv->vval.v_string = NULL;
11036 else
11038 rettv->vval.v_string = vim_strsave(cwd);
11039 #ifdef BACKSLASH_IN_FILENAME
11040 if (rettv->vval.v_string != NULL)
11041 slash_adjust(rettv->vval.v_string);
11042 #endif
11047 * "getfontname()" function
11049 static void
11050 f_getfontname(argvars, rettv)
11051 typval_T *argvars UNUSED;
11052 typval_T *rettv;
11054 rettv->v_type = VAR_STRING;
11055 rettv->vval.v_string = NULL;
11056 #ifdef FEAT_GUI
11057 if (gui.in_use)
11059 GuiFont font;
11060 char_u *name = NULL;
11062 if (argvars[0].v_type == VAR_UNKNOWN)
11064 /* Get the "Normal" font. Either the name saved by
11065 * hl_set_font_name() or from the font ID. */
11066 font = gui.norm_font;
11067 name = hl_get_font_name();
11069 else
11071 name = get_tv_string(&argvars[0]);
11072 if (STRCMP(name, "*") == 0) /* don't use font dialog */
11073 return;
11074 font = gui_mch_get_font(name, FALSE);
11075 if (font == NOFONT)
11076 return; /* Invalid font name, return empty string. */
11078 rettv->vval.v_string = gui_mch_get_fontname(font, name);
11079 if (argvars[0].v_type != VAR_UNKNOWN)
11080 gui_mch_free_font(font);
11082 #endif
11086 * "getfperm({fname})" function
11088 static void
11089 f_getfperm(argvars, rettv)
11090 typval_T *argvars;
11091 typval_T *rettv;
11093 char_u *fname;
11094 struct stat st;
11095 char_u *perm = NULL;
11096 char_u flags[] = "rwx";
11097 int i;
11099 fname = get_tv_string(&argvars[0]);
11101 rettv->v_type = VAR_STRING;
11102 if (mch_stat((char *)fname, &st) >= 0)
11104 perm = vim_strsave((char_u *)"---------");
11105 if (perm != NULL)
11107 for (i = 0; i < 9; i++)
11109 if (st.st_mode & (1 << (8 - i)))
11110 perm[i] = flags[i % 3];
11114 rettv->vval.v_string = perm;
11118 * "getfsize({fname})" function
11120 static void
11121 f_getfsize(argvars, rettv)
11122 typval_T *argvars;
11123 typval_T *rettv;
11125 char_u *fname;
11126 struct stat st;
11128 fname = get_tv_string(&argvars[0]);
11130 rettv->v_type = VAR_NUMBER;
11132 if (mch_stat((char *)fname, &st) >= 0)
11134 if (mch_isdir(fname))
11135 rettv->vval.v_number = 0;
11136 else
11138 rettv->vval.v_number = (varnumber_T)st.st_size;
11140 /* non-perfect check for overflow */
11141 if ((off_t)rettv->vval.v_number != (off_t)st.st_size)
11142 rettv->vval.v_number = -2;
11145 else
11146 rettv->vval.v_number = -1;
11150 * "getftime({fname})" function
11152 static void
11153 f_getftime(argvars, rettv)
11154 typval_T *argvars;
11155 typval_T *rettv;
11157 char_u *fname;
11158 struct stat st;
11160 fname = get_tv_string(&argvars[0]);
11162 if (mch_stat((char *)fname, &st) >= 0)
11163 rettv->vval.v_number = (varnumber_T)st.st_mtime;
11164 else
11165 rettv->vval.v_number = -1;
11169 * "getftype({fname})" function
11171 static void
11172 f_getftype(argvars, rettv)
11173 typval_T *argvars;
11174 typval_T *rettv;
11176 char_u *fname;
11177 struct stat st;
11178 char_u *type = NULL;
11179 char *t;
11181 fname = get_tv_string(&argvars[0]);
11183 rettv->v_type = VAR_STRING;
11184 if (mch_lstat((char *)fname, &st) >= 0)
11186 #ifdef S_ISREG
11187 if (S_ISREG(st.st_mode))
11188 t = "file";
11189 else if (S_ISDIR(st.st_mode))
11190 t = "dir";
11191 # ifdef S_ISLNK
11192 else if (S_ISLNK(st.st_mode))
11193 t = "link";
11194 # endif
11195 # ifdef S_ISBLK
11196 else if (S_ISBLK(st.st_mode))
11197 t = "bdev";
11198 # endif
11199 # ifdef S_ISCHR
11200 else if (S_ISCHR(st.st_mode))
11201 t = "cdev";
11202 # endif
11203 # ifdef S_ISFIFO
11204 else if (S_ISFIFO(st.st_mode))
11205 t = "fifo";
11206 # endif
11207 # ifdef S_ISSOCK
11208 else if (S_ISSOCK(st.st_mode))
11209 t = "fifo";
11210 # endif
11211 else
11212 t = "other";
11213 #else
11214 # ifdef S_IFMT
11215 switch (st.st_mode & S_IFMT)
11217 case S_IFREG: t = "file"; break;
11218 case S_IFDIR: t = "dir"; break;
11219 # ifdef S_IFLNK
11220 case S_IFLNK: t = "link"; break;
11221 # endif
11222 # ifdef S_IFBLK
11223 case S_IFBLK: t = "bdev"; break;
11224 # endif
11225 # ifdef S_IFCHR
11226 case S_IFCHR: t = "cdev"; break;
11227 # endif
11228 # ifdef S_IFIFO
11229 case S_IFIFO: t = "fifo"; break;
11230 # endif
11231 # ifdef S_IFSOCK
11232 case S_IFSOCK: t = "socket"; break;
11233 # endif
11234 default: t = "other";
11236 # else
11237 if (mch_isdir(fname))
11238 t = "dir";
11239 else
11240 t = "file";
11241 # endif
11242 #endif
11243 type = vim_strsave((char_u *)t);
11245 rettv->vval.v_string = type;
11249 * "getline(lnum, [end])" function
11251 static void
11252 f_getline(argvars, rettv)
11253 typval_T *argvars;
11254 typval_T *rettv;
11256 linenr_T lnum;
11257 linenr_T end;
11258 int retlist;
11260 lnum = get_tv_lnum(argvars);
11261 if (argvars[1].v_type == VAR_UNKNOWN)
11263 end = 0;
11264 retlist = FALSE;
11266 else
11268 end = get_tv_lnum(&argvars[1]);
11269 retlist = TRUE;
11272 get_buffer_lines(curbuf, lnum, end, retlist, rettv);
11276 * "getmatches()" function
11278 static void
11279 f_getmatches(argvars, rettv)
11280 typval_T *argvars UNUSED;
11281 typval_T *rettv;
11283 #ifdef FEAT_SEARCH_EXTRA
11284 dict_T *dict;
11285 matchitem_T *cur = curwin->w_match_head;
11287 if (rettv_list_alloc(rettv) == OK)
11289 while (cur != NULL)
11291 dict = dict_alloc();
11292 if (dict == NULL)
11293 return;
11294 dict_add_nr_str(dict, "group", 0L, syn_id2name(cur->hlg_id));
11295 dict_add_nr_str(dict, "pattern", 0L, cur->pattern);
11296 dict_add_nr_str(dict, "priority", (long)cur->priority, NULL);
11297 dict_add_nr_str(dict, "id", (long)cur->id, NULL);
11298 list_append_dict(rettv->vval.v_list, dict);
11299 cur = cur->next;
11302 #endif
11306 * "getpid()" function
11308 static void
11309 f_getpid(argvars, rettv)
11310 typval_T *argvars UNUSED;
11311 typval_T *rettv;
11313 rettv->vval.v_number = mch_get_pid();
11317 * "getpos(string)" function
11319 static void
11320 f_getpos(argvars, rettv)
11321 typval_T *argvars;
11322 typval_T *rettv;
11324 pos_T *fp;
11325 list_T *l;
11326 int fnum = -1;
11328 if (rettv_list_alloc(rettv) == OK)
11330 l = rettv->vval.v_list;
11331 fp = var2fpos(&argvars[0], TRUE, &fnum);
11332 if (fnum != -1)
11333 list_append_number(l, (varnumber_T)fnum);
11334 else
11335 list_append_number(l, (varnumber_T)0);
11336 list_append_number(l, (fp != NULL) ? (varnumber_T)fp->lnum
11337 : (varnumber_T)0);
11338 list_append_number(l, (fp != NULL)
11339 ? (varnumber_T)(fp->col == MAXCOL ? MAXCOL : fp->col + 1)
11340 : (varnumber_T)0);
11341 list_append_number(l,
11342 #ifdef FEAT_VIRTUALEDIT
11343 (fp != NULL) ? (varnumber_T)fp->coladd :
11344 #endif
11345 (varnumber_T)0);
11347 else
11348 rettv->vval.v_number = FALSE;
11352 * "getqflist()" and "getloclist()" functions
11354 static void
11355 f_getqflist(argvars, rettv)
11356 typval_T *argvars UNUSED;
11357 typval_T *rettv UNUSED;
11359 #ifdef FEAT_QUICKFIX
11360 win_T *wp;
11361 #endif
11363 #ifdef FEAT_QUICKFIX
11364 if (rettv_list_alloc(rettv) == OK)
11366 wp = NULL;
11367 if (argvars[0].v_type != VAR_UNKNOWN) /* getloclist() */
11369 wp = find_win_by_nr(&argvars[0], NULL);
11370 if (wp == NULL)
11371 return;
11374 (void)get_errorlist(wp, rettv->vval.v_list);
11376 #endif
11380 * "getreg()" function
11382 static void
11383 f_getreg(argvars, rettv)
11384 typval_T *argvars;
11385 typval_T *rettv;
11387 char_u *strregname;
11388 int regname;
11389 int arg2 = FALSE;
11390 int error = FALSE;
11392 if (argvars[0].v_type != VAR_UNKNOWN)
11394 strregname = get_tv_string_chk(&argvars[0]);
11395 error = strregname == NULL;
11396 if (argvars[1].v_type != VAR_UNKNOWN)
11397 arg2 = get_tv_number_chk(&argvars[1], &error);
11399 else
11400 strregname = vimvars[VV_REG].vv_str;
11401 regname = (strregname == NULL ? '"' : *strregname);
11402 if (regname == 0)
11403 regname = '"';
11405 rettv->v_type = VAR_STRING;
11406 rettv->vval.v_string = error ? NULL :
11407 get_reg_contents(regname, TRUE, arg2);
11411 * "getregtype()" function
11413 static void
11414 f_getregtype(argvars, rettv)
11415 typval_T *argvars;
11416 typval_T *rettv;
11418 char_u *strregname;
11419 int regname;
11420 char_u buf[NUMBUFLEN + 2];
11421 long reglen = 0;
11423 if (argvars[0].v_type != VAR_UNKNOWN)
11425 strregname = get_tv_string_chk(&argvars[0]);
11426 if (strregname == NULL) /* type error; errmsg already given */
11428 rettv->v_type = VAR_STRING;
11429 rettv->vval.v_string = NULL;
11430 return;
11433 else
11434 /* Default to v:register */
11435 strregname = vimvars[VV_REG].vv_str;
11437 regname = (strregname == NULL ? '"' : *strregname);
11438 if (regname == 0)
11439 regname = '"';
11441 buf[0] = NUL;
11442 buf[1] = NUL;
11443 switch (get_reg_type(regname, &reglen))
11445 case MLINE: buf[0] = 'V'; break;
11446 case MCHAR: buf[0] = 'v'; break;
11447 #ifdef FEAT_VISUAL
11448 case MBLOCK:
11449 buf[0] = Ctrl_V;
11450 sprintf((char *)buf + 1, "%ld", reglen + 1);
11451 break;
11452 #endif
11454 rettv->v_type = VAR_STRING;
11455 rettv->vval.v_string = vim_strsave(buf);
11459 * "gettabwinvar()" function
11461 static void
11462 f_gettabwinvar(argvars, rettv)
11463 typval_T *argvars;
11464 typval_T *rettv;
11466 getwinvar(argvars, rettv, 1);
11470 * "getwinposx()" function
11472 static void
11473 f_getwinposx(argvars, rettv)
11474 typval_T *argvars UNUSED;
11475 typval_T *rettv;
11477 rettv->vval.v_number = -1;
11478 #ifdef FEAT_GUI
11479 if (gui.in_use)
11481 int x, y;
11483 if (gui_mch_get_winpos(&x, &y) == OK)
11484 rettv->vval.v_number = x;
11486 #endif
11490 * "getwinposy()" function
11492 static void
11493 f_getwinposy(argvars, rettv)
11494 typval_T *argvars UNUSED;
11495 typval_T *rettv;
11497 rettv->vval.v_number = -1;
11498 #ifdef FEAT_GUI
11499 if (gui.in_use)
11501 int x, y;
11503 if (gui_mch_get_winpos(&x, &y) == OK)
11504 rettv->vval.v_number = y;
11506 #endif
11510 * Find window specified by "vp" in tabpage "tp".
11512 static win_T *
11513 find_win_by_nr(vp, tp)
11514 typval_T *vp;
11515 tabpage_T *tp; /* NULL for current tab page */
11517 #ifdef FEAT_WINDOWS
11518 win_T *wp;
11519 #endif
11520 int nr;
11522 nr = get_tv_number_chk(vp, NULL);
11524 #ifdef FEAT_WINDOWS
11525 if (nr < 0)
11526 return NULL;
11527 if (nr == 0)
11528 return curwin;
11530 for (wp = (tp == NULL || tp == curtab) ? firstwin : tp->tp_firstwin;
11531 wp != NULL; wp = wp->w_next)
11532 if (--nr <= 0)
11533 break;
11534 return wp;
11535 #else
11536 if (nr == 0 || nr == 1)
11537 return curwin;
11538 return NULL;
11539 #endif
11543 * "getwinvar()" function
11545 static void
11546 f_getwinvar(argvars, rettv)
11547 typval_T *argvars;
11548 typval_T *rettv;
11550 getwinvar(argvars, rettv, 0);
11554 * getwinvar() and gettabwinvar()
11556 static void
11557 getwinvar(argvars, rettv, off)
11558 typval_T *argvars;
11559 typval_T *rettv;
11560 int off; /* 1 for gettabwinvar() */
11562 win_T *win, *oldcurwin;
11563 char_u *varname;
11564 dictitem_T *v;
11565 tabpage_T *tp;
11567 #ifdef FEAT_WINDOWS
11568 if (off == 1)
11569 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
11570 else
11571 tp = curtab;
11572 #endif
11573 win = find_win_by_nr(&argvars[off], tp);
11574 varname = get_tv_string_chk(&argvars[off + 1]);
11575 ++emsg_off;
11577 rettv->v_type = VAR_STRING;
11578 rettv->vval.v_string = NULL;
11580 if (win != NULL && varname != NULL)
11582 /* Set curwin to be our win, temporarily. Also set curbuf, so
11583 * that we can get buffer-local options. */
11584 oldcurwin = curwin;
11585 curwin = win;
11586 curbuf = win->w_buffer;
11588 if (*varname == '&') /* window-local-option */
11589 get_option_tv(&varname, rettv, 1);
11590 else
11592 if (*varname == NUL)
11593 /* let getwinvar({nr}, "") return the "w:" dictionary. The
11594 * scope prefix before the NUL byte is required by
11595 * find_var_in_ht(). */
11596 varname = (char_u *)"w:" + 2;
11597 /* look up the variable */
11598 v = find_var_in_ht(&win->w_vars.dv_hashtab, varname, FALSE);
11599 if (v != NULL)
11600 copy_tv(&v->di_tv, rettv);
11603 /* restore previous notion of curwin */
11604 curwin = oldcurwin;
11605 curbuf = curwin->w_buffer;
11608 --emsg_off;
11612 * "glob()" function
11614 static void
11615 f_glob(argvars, rettv)
11616 typval_T *argvars;
11617 typval_T *rettv;
11619 int flags = WILD_SILENT|WILD_USE_NL;
11620 expand_T xpc;
11621 int error = FALSE;
11623 /* When the optional second argument is non-zero, don't remove matches
11624 * for 'wildignore' and don't put matches for 'suffixes' at the end. */
11625 if (argvars[1].v_type != VAR_UNKNOWN
11626 && get_tv_number_chk(&argvars[1], &error))
11627 flags |= WILD_KEEP_ALL;
11628 rettv->v_type = VAR_STRING;
11629 if (!error)
11631 ExpandInit(&xpc);
11632 xpc.xp_context = EXPAND_FILES;
11633 rettv->vval.v_string = ExpandOne(&xpc, get_tv_string(&argvars[0]),
11634 NULL, flags, WILD_ALL);
11636 else
11637 rettv->vval.v_string = NULL;
11641 * "globpath()" function
11643 static void
11644 f_globpath(argvars, rettv)
11645 typval_T *argvars;
11646 typval_T *rettv;
11648 int flags = 0;
11649 char_u buf1[NUMBUFLEN];
11650 char_u *file = get_tv_string_buf_chk(&argvars[1], buf1);
11651 int error = FALSE;
11653 /* When the optional second argument is non-zero, don't remove matches
11654 * for 'wildignore' and don't put matches for 'suffixes' at the end. */
11655 if (argvars[2].v_type != VAR_UNKNOWN
11656 && get_tv_number_chk(&argvars[2], &error))
11657 flags |= WILD_KEEP_ALL;
11658 rettv->v_type = VAR_STRING;
11659 if (file == NULL || error)
11660 rettv->vval.v_string = NULL;
11661 else
11662 rettv->vval.v_string = globpath(get_tv_string(&argvars[0]), file,
11663 flags);
11667 * "has()" function
11669 static void
11670 f_has(argvars, rettv)
11671 typval_T *argvars;
11672 typval_T *rettv;
11674 int i;
11675 char_u *name;
11676 int n = FALSE;
11677 static char *(has_list[]) =
11679 #ifdef AMIGA
11680 "amiga",
11681 # ifdef FEAT_ARP
11682 "arp",
11683 # endif
11684 #endif
11685 #ifdef __BEOS__
11686 "beos",
11687 #endif
11688 #ifdef MSDOS
11689 # ifdef DJGPP
11690 "dos32",
11691 # else
11692 "dos16",
11693 # endif
11694 #endif
11695 #ifdef MACOS
11696 "mac",
11697 #endif
11698 #if defined(MACOS_X_UNIX)
11699 "macunix",
11700 #endif
11701 #ifdef OS2
11702 "os2",
11703 #endif
11704 #ifdef __QNX__
11705 "qnx",
11706 #endif
11707 #ifdef RISCOS
11708 "riscos",
11709 #endif
11710 #ifdef UNIX
11711 "unix",
11712 #endif
11713 #ifdef VMS
11714 "vms",
11715 #endif
11716 #ifdef WIN16
11717 "win16",
11718 #endif
11719 #ifdef WIN32
11720 "win32",
11721 #endif
11722 #if defined(UNIX) && (defined(__CYGWIN32__) || defined(__CYGWIN__))
11723 "win32unix",
11724 #endif
11725 #if defined(WIN64) || defined(_WIN64)
11726 "win64",
11727 #endif
11728 #ifdef EBCDIC
11729 "ebcdic",
11730 #endif
11731 #ifndef CASE_INSENSITIVE_FILENAME
11732 "fname_case",
11733 #endif
11734 #ifdef FEAT_ARABIC
11735 "arabic",
11736 #endif
11737 #ifdef FEAT_AUTOCMD
11738 "autocmd",
11739 #endif
11740 #ifdef FEAT_BEVAL
11741 "balloon_eval",
11742 # ifndef FEAT_GUI_W32 /* other GUIs always have multiline balloons */
11743 "balloon_multiline",
11744 # endif
11745 #endif
11746 #if defined(SOME_BUILTIN_TCAPS) || defined(ALL_BUILTIN_TCAPS)
11747 "builtin_terms",
11748 # ifdef ALL_BUILTIN_TCAPS
11749 "all_builtin_terms",
11750 # endif
11751 #endif
11752 #ifdef FEAT_BYTEOFF
11753 "byte_offset",
11754 #endif
11755 #ifdef FEAT_CINDENT
11756 "cindent",
11757 #endif
11758 #ifdef FEAT_CLIENTSERVER
11759 "clientserver",
11760 #endif
11761 #ifdef FEAT_CLIPBOARD
11762 "clipboard",
11763 #endif
11764 #ifdef FEAT_CMDL_COMPL
11765 "cmdline_compl",
11766 #endif
11767 #ifdef FEAT_CMDHIST
11768 "cmdline_hist",
11769 #endif
11770 #ifdef FEAT_COMMENTS
11771 "comments",
11772 #endif
11773 #ifdef FEAT_CRYPT
11774 "cryptv",
11775 #endif
11776 #ifdef FEAT_CSCOPE
11777 "cscope",
11778 #endif
11779 #ifdef CURSOR_SHAPE
11780 "cursorshape",
11781 #endif
11782 #ifdef DEBUG
11783 "debug",
11784 #endif
11785 #ifdef FEAT_CON_DIALOG
11786 "dialog_con",
11787 #endif
11788 #ifdef FEAT_GUI_DIALOG
11789 "dialog_gui",
11790 #endif
11791 #ifdef FEAT_DIFF
11792 "diff",
11793 #endif
11794 #ifdef FEAT_DIGRAPHS
11795 "digraphs",
11796 #endif
11797 #ifdef FEAT_DND
11798 "dnd",
11799 #endif
11800 #ifdef FEAT_EMACS_TAGS
11801 "emacs_tags",
11802 #endif
11803 "eval", /* always present, of course! */
11804 #ifdef FEAT_EX_EXTRA
11805 "ex_extra",
11806 #endif
11807 #ifdef FEAT_SEARCH_EXTRA
11808 "extra_search",
11809 #endif
11810 #ifdef FEAT_FKMAP
11811 "farsi",
11812 #endif
11813 #ifdef FEAT_SEARCHPATH
11814 "file_in_path",
11815 #endif
11816 #if defined(UNIX) && !defined(USE_SYSTEM)
11817 "filterpipe",
11818 #endif
11819 #ifdef FEAT_FIND_ID
11820 "find_in_path",
11821 #endif
11822 #ifdef FEAT_FLOAT
11823 "float",
11824 #endif
11825 #ifdef FEAT_FOLDING
11826 "folding",
11827 #endif
11828 #ifdef FEAT_FOOTER
11829 "footer",
11830 #endif
11831 #if !defined(USE_SYSTEM) && defined(UNIX)
11832 "fork",
11833 #endif
11834 #ifdef FEAT_GETTEXT
11835 "gettext",
11836 #endif
11837 #ifdef FEAT_GUI
11838 "gui",
11839 #endif
11840 #ifdef FEAT_GUI_ATHENA
11841 # ifdef FEAT_GUI_NEXTAW
11842 "gui_neXtaw",
11843 # else
11844 "gui_athena",
11845 # endif
11846 #endif
11847 #ifdef FEAT_GUI_GTK
11848 "gui_gtk",
11849 # ifdef HAVE_GTK2
11850 "gui_gtk2",
11851 # endif
11852 #endif
11853 #ifdef FEAT_GUI_GNOME
11854 "gui_gnome",
11855 #endif
11856 #ifdef FEAT_GUI_MAC
11857 "gui_mac",
11858 #endif
11859 #ifdef FEAT_GUI_MOTIF
11860 "gui_motif",
11861 #endif
11862 #ifdef FEAT_GUI_PHOTON
11863 "gui_photon",
11864 #endif
11865 #ifdef FEAT_GUI_W16
11866 "gui_win16",
11867 #endif
11868 #ifdef FEAT_GUI_W32
11869 "gui_win32",
11870 #endif
11871 #ifdef FEAT_HANGULIN
11872 "hangul_input",
11873 #endif
11874 #if defined(HAVE_ICONV_H) && defined(USE_ICONV)
11875 "iconv",
11876 #endif
11877 #ifdef FEAT_INS_EXPAND
11878 "insert_expand",
11879 #endif
11880 #ifdef FEAT_JUMPLIST
11881 "jumplist",
11882 #endif
11883 #ifdef FEAT_KEYMAP
11884 "keymap",
11885 #endif
11886 #ifdef FEAT_LANGMAP
11887 "langmap",
11888 #endif
11889 #ifdef FEAT_LIBCALL
11890 "libcall",
11891 #endif
11892 #ifdef FEAT_LINEBREAK
11893 "linebreak",
11894 #endif
11895 #ifdef FEAT_LISP
11896 "lispindent",
11897 #endif
11898 #ifdef FEAT_LISTCMDS
11899 "listcmds",
11900 #endif
11901 #ifdef FEAT_LOCALMAP
11902 "localmap",
11903 #endif
11904 #ifdef FEAT_LUA
11905 # ifndef DYNAMIC_LUA
11906 "lua",
11907 # endif
11908 #endif
11909 #ifdef FEAT_MENU
11910 "menu",
11911 #endif
11912 #ifdef FEAT_SESSION
11913 "mksession",
11914 #endif
11915 #ifdef FEAT_MODIFY_FNAME
11916 "modify_fname",
11917 #endif
11918 #ifdef FEAT_MOUSE
11919 "mouse",
11920 #endif
11921 #ifdef FEAT_MOUSESHAPE
11922 "mouseshape",
11923 #endif
11924 #if defined(UNIX) || defined(VMS)
11925 # ifdef FEAT_MOUSE_DEC
11926 "mouse_dec",
11927 # endif
11928 # ifdef FEAT_MOUSE_GPM
11929 "mouse_gpm",
11930 # endif
11931 # ifdef FEAT_MOUSE_JSB
11932 "mouse_jsbterm",
11933 # endif
11934 # ifdef FEAT_MOUSE_NET
11935 "mouse_netterm",
11936 # endif
11937 # ifdef FEAT_MOUSE_PTERM
11938 "mouse_pterm",
11939 # endif
11940 # ifdef FEAT_SYSMOUSE
11941 "mouse_sysmouse",
11942 # endif
11943 # ifdef FEAT_MOUSE_XTERM
11944 "mouse_xterm",
11945 # endif
11946 #endif
11947 #ifdef FEAT_MBYTE
11948 "multi_byte",
11949 #endif
11950 #ifdef FEAT_MBYTE_IME
11951 "multi_byte_ime",
11952 #endif
11953 #ifdef FEAT_MULTI_LANG
11954 "multi_lang",
11955 #endif
11956 #ifdef FEAT_MZSCHEME
11957 #ifndef DYNAMIC_MZSCHEME
11958 "mzscheme",
11959 #endif
11960 #endif
11961 #ifdef FEAT_OLE
11962 "ole",
11963 #endif
11964 #ifdef FEAT_OSFILETYPE
11965 "osfiletype",
11966 #endif
11967 #ifdef FEAT_PATH_EXTRA
11968 "path_extra",
11969 #endif
11970 #ifdef FEAT_PERL
11971 #ifndef DYNAMIC_PERL
11972 "perl",
11973 #endif
11974 #endif
11975 #ifdef FEAT_PERSISTENT_UNDO
11976 "persistent_undo",
11977 #endif
11978 #ifdef FEAT_PYTHON
11979 #ifndef DYNAMIC_PYTHON
11980 "python",
11981 #endif
11982 #endif
11983 #ifdef FEAT_POSTSCRIPT
11984 "postscript",
11985 #endif
11986 #ifdef FEAT_PRINTER
11987 "printer",
11988 #endif
11989 #ifdef FEAT_PROFILE
11990 "profile",
11991 #endif
11992 #ifdef FEAT_RELTIME
11993 "reltime",
11994 #endif
11995 #ifdef FEAT_QUICKFIX
11996 "quickfix",
11997 #endif
11998 #ifdef FEAT_RIGHTLEFT
11999 "rightleft",
12000 #endif
12001 #if defined(FEAT_RUBY) && !defined(DYNAMIC_RUBY)
12002 "ruby",
12003 #endif
12004 #ifdef FEAT_SCROLLBIND
12005 "scrollbind",
12006 #endif
12007 #ifdef FEAT_CMDL_INFO
12008 "showcmd",
12009 "cmdline_info",
12010 #endif
12011 #ifdef FEAT_SIGNS
12012 "signs",
12013 #endif
12014 #ifdef FEAT_SMARTINDENT
12015 "smartindent",
12016 #endif
12017 #ifdef FEAT_SNIFF
12018 "sniff",
12019 #endif
12020 #ifdef STARTUPTIME
12021 "startuptime",
12022 #endif
12023 #ifdef FEAT_STL_OPT
12024 "statusline",
12025 #endif
12026 #ifdef FEAT_SUN_WORKSHOP
12027 "sun_workshop",
12028 #endif
12029 #ifdef FEAT_NETBEANS_INTG
12030 "netbeans_intg",
12031 #endif
12032 #ifdef FEAT_SPELL
12033 "spell",
12034 #endif
12035 #ifdef FEAT_SYN_HL
12036 "syntax",
12037 #endif
12038 #if defined(USE_SYSTEM) || !defined(UNIX)
12039 "system",
12040 #endif
12041 #ifdef FEAT_TAG_BINS
12042 "tag_binary",
12043 #endif
12044 #ifdef FEAT_TAG_OLDSTATIC
12045 "tag_old_static",
12046 #endif
12047 #ifdef FEAT_TAG_ANYWHITE
12048 "tag_any_white",
12049 #endif
12050 #ifdef FEAT_TCL
12051 # ifndef DYNAMIC_TCL
12052 "tcl",
12053 # endif
12054 #endif
12055 #ifdef TERMINFO
12056 "terminfo",
12057 #endif
12058 #ifdef FEAT_TERMRESPONSE
12059 "termresponse",
12060 #endif
12061 #ifdef FEAT_TEXTOBJ
12062 "textobjects",
12063 #endif
12064 #ifdef HAVE_TGETENT
12065 "tgetent",
12066 #endif
12067 #ifdef FEAT_TITLE
12068 "title",
12069 #endif
12070 #ifdef FEAT_TOOLBAR
12071 "toolbar",
12072 #endif
12073 #ifdef FEAT_USR_CMDS
12074 "user-commands", /* was accidentally included in 5.4 */
12075 "user_commands",
12076 #endif
12077 #ifdef FEAT_VIMINFO
12078 "viminfo",
12079 #endif
12080 #ifdef FEAT_VARTABS
12081 "vartabs",
12082 #endif
12083 #ifdef FEAT_VERTSPLIT
12084 "vertsplit",
12085 #endif
12086 #ifdef FEAT_VIRTUALEDIT
12087 "virtualedit",
12088 #endif
12089 #ifdef FEAT_VISUAL
12090 "visual",
12091 #endif
12092 #ifdef FEAT_VISUALEXTRA
12093 "visualextra",
12094 #endif
12095 #ifdef FEAT_VREPLACE
12096 "vreplace",
12097 #endif
12098 #ifdef FEAT_WILDIGN
12099 "wildignore",
12100 #endif
12101 #ifdef FEAT_WILDMENU
12102 "wildmenu",
12103 #endif
12104 #ifdef FEAT_WINDOWS
12105 "windows",
12106 #endif
12107 #ifdef FEAT_WAK
12108 "winaltkeys",
12109 #endif
12110 #ifdef FEAT_WRITEBACKUP
12111 "writebackup",
12112 #endif
12113 #ifdef FEAT_XIM
12114 "xim",
12115 #endif
12116 #ifdef FEAT_XFONTSET
12117 "xfontset",
12118 #endif
12119 #ifdef USE_XSMP
12120 "xsmp",
12121 #endif
12122 #ifdef USE_XSMP_INTERACT
12123 "xsmp_interact",
12124 #endif
12125 #ifdef FEAT_XCLIPBOARD
12126 "xterm_clipboard",
12127 #endif
12128 #ifdef FEAT_XTERM_SAVE
12129 "xterm_save",
12130 #endif
12131 #if defined(UNIX) && defined(FEAT_X11)
12132 "X11",
12133 #endif
12134 NULL
12137 name = get_tv_string(&argvars[0]);
12138 for (i = 0; has_list[i] != NULL; ++i)
12139 if (STRICMP(name, has_list[i]) == 0)
12141 n = TRUE;
12142 break;
12145 if (n == FALSE)
12147 if (STRNICMP(name, "patch", 5) == 0)
12148 n = has_patch(atoi((char *)name + 5));
12149 else if (STRICMP(name, "vim_starting") == 0)
12150 n = (starting != 0);
12151 #ifdef FEAT_MBYTE
12152 else if (STRICMP(name, "multi_byte_encoding") == 0)
12153 n = has_mbyte;
12154 #endif
12155 #if defined(FEAT_BEVAL) && defined(FEAT_GUI_W32)
12156 else if (STRICMP(name, "balloon_multiline") == 0)
12157 n = multiline_balloon_available();
12158 #endif
12159 #ifdef DYNAMIC_TCL
12160 else if (STRICMP(name, "tcl") == 0)
12161 n = tcl_enabled(FALSE);
12162 #endif
12163 #if defined(USE_ICONV) && defined(DYNAMIC_ICONV)
12164 else if (STRICMP(name, "iconv") == 0)
12165 n = iconv_enabled(FALSE);
12166 #endif
12167 #ifdef DYNAMIC_LUA
12168 else if (STRICMP(name, "lua") == 0)
12169 n = lua_enabled(FALSE);
12170 #endif
12171 #ifdef DYNAMIC_MZSCHEME
12172 else if (STRICMP(name, "mzscheme") == 0)
12173 n = mzscheme_enabled(FALSE);
12174 #endif
12175 #ifdef DYNAMIC_RUBY
12176 else if (STRICMP(name, "ruby") == 0)
12177 n = ruby_enabled(FALSE);
12178 #endif
12179 #ifdef DYNAMIC_PYTHON
12180 else if (STRICMP(name, "python") == 0)
12181 n = python_enabled(FALSE);
12182 #endif
12183 #ifdef DYNAMIC_PERL
12184 else if (STRICMP(name, "perl") == 0)
12185 n = perl_enabled(FALSE);
12186 #endif
12187 #ifdef FEAT_GUI
12188 else if (STRICMP(name, "gui_running") == 0)
12189 n = (gui.in_use || gui.starting);
12190 # ifdef FEAT_GUI_W32
12191 else if (STRICMP(name, "gui_win32s") == 0)
12192 n = gui_is_win32s();
12193 # endif
12194 # ifdef FEAT_BROWSE
12195 else if (STRICMP(name, "browse") == 0)
12196 n = gui.in_use; /* gui_mch_browse() works when GUI is running */
12197 # endif
12198 #endif
12199 #ifdef FEAT_SYN_HL
12200 else if (STRICMP(name, "syntax_items") == 0)
12201 n = syntax_present(curbuf);
12202 #endif
12203 #if defined(WIN3264)
12204 else if (STRICMP(name, "win95") == 0)
12205 n = mch_windows95();
12206 #endif
12207 #ifdef FEAT_NETBEANS_INTG
12208 else if (STRICMP(name, "netbeans_enabled") == 0)
12209 n = usingNetbeans;
12210 #endif
12213 rettv->vval.v_number = n;
12217 * "has_key()" function
12219 static void
12220 f_has_key(argvars, rettv)
12221 typval_T *argvars;
12222 typval_T *rettv;
12224 if (argvars[0].v_type != VAR_DICT)
12226 EMSG(_(e_dictreq));
12227 return;
12229 if (argvars[0].vval.v_dict == NULL)
12230 return;
12232 rettv->vval.v_number = dict_find(argvars[0].vval.v_dict,
12233 get_tv_string(&argvars[1]), -1) != NULL;
12237 * "haslocaldir()" function
12239 static void
12240 f_haslocaldir(argvars, rettv)
12241 typval_T *argvars UNUSED;
12242 typval_T *rettv;
12244 rettv->vval.v_number = (curwin->w_localdir != NULL);
12248 * "hasmapto()" function
12250 static void
12251 f_hasmapto(argvars, rettv)
12252 typval_T *argvars;
12253 typval_T *rettv;
12255 char_u *name;
12256 char_u *mode;
12257 char_u buf[NUMBUFLEN];
12258 int abbr = FALSE;
12260 name = get_tv_string(&argvars[0]);
12261 if (argvars[1].v_type == VAR_UNKNOWN)
12262 mode = (char_u *)"nvo";
12263 else
12265 mode = get_tv_string_buf(&argvars[1], buf);
12266 if (argvars[2].v_type != VAR_UNKNOWN)
12267 abbr = get_tv_number(&argvars[2]);
12270 if (map_to_exists(name, mode, abbr))
12271 rettv->vval.v_number = TRUE;
12272 else
12273 rettv->vval.v_number = FALSE;
12277 * "histadd()" function
12279 static void
12280 f_histadd(argvars, rettv)
12281 typval_T *argvars UNUSED;
12282 typval_T *rettv;
12284 #ifdef FEAT_CMDHIST
12285 int histype;
12286 char_u *str;
12287 char_u buf[NUMBUFLEN];
12288 #endif
12290 rettv->vval.v_number = FALSE;
12291 if (check_restricted() || check_secure())
12292 return;
12293 #ifdef FEAT_CMDHIST
12294 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
12295 histype = str != NULL ? get_histtype(str) : -1;
12296 if (histype >= 0)
12298 str = get_tv_string_buf(&argvars[1], buf);
12299 if (*str != NUL)
12301 init_history();
12302 add_to_history(histype, str, FALSE, NUL);
12303 rettv->vval.v_number = TRUE;
12304 return;
12307 #endif
12311 * "histdel()" function
12313 static void
12314 f_histdel(argvars, rettv)
12315 typval_T *argvars UNUSED;
12316 typval_T *rettv UNUSED;
12318 #ifdef FEAT_CMDHIST
12319 int n;
12320 char_u buf[NUMBUFLEN];
12321 char_u *str;
12323 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
12324 if (str == NULL)
12325 n = 0;
12326 else if (argvars[1].v_type == VAR_UNKNOWN)
12327 /* only one argument: clear entire history */
12328 n = clr_history(get_histtype(str));
12329 else if (argvars[1].v_type == VAR_NUMBER)
12330 /* index given: remove that entry */
12331 n = del_history_idx(get_histtype(str),
12332 (int)get_tv_number(&argvars[1]));
12333 else
12334 /* string given: remove all matching entries */
12335 n = del_history_entry(get_histtype(str),
12336 get_tv_string_buf(&argvars[1], buf));
12337 rettv->vval.v_number = n;
12338 #endif
12342 * "histget()" function
12344 static void
12345 f_histget(argvars, rettv)
12346 typval_T *argvars UNUSED;
12347 typval_T *rettv;
12349 #ifdef FEAT_CMDHIST
12350 int type;
12351 int idx;
12352 char_u *str;
12354 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
12355 if (str == NULL)
12356 rettv->vval.v_string = NULL;
12357 else
12359 type = get_histtype(str);
12360 if (argvars[1].v_type == VAR_UNKNOWN)
12361 idx = get_history_idx(type);
12362 else
12363 idx = (int)get_tv_number_chk(&argvars[1], NULL);
12364 /* -1 on type error */
12365 rettv->vval.v_string = vim_strsave(get_history_entry(type, idx));
12367 #else
12368 rettv->vval.v_string = NULL;
12369 #endif
12370 rettv->v_type = VAR_STRING;
12374 * "histnr()" function
12376 static void
12377 f_histnr(argvars, rettv)
12378 typval_T *argvars UNUSED;
12379 typval_T *rettv;
12381 int i;
12383 #ifdef FEAT_CMDHIST
12384 char_u *history = get_tv_string_chk(&argvars[0]);
12386 i = history == NULL ? HIST_CMD - 1 : get_histtype(history);
12387 if (i >= HIST_CMD && i < HIST_COUNT)
12388 i = get_history_idx(i);
12389 else
12390 #endif
12391 i = -1;
12392 rettv->vval.v_number = i;
12396 * "highlightID(name)" function
12398 static void
12399 f_hlID(argvars, rettv)
12400 typval_T *argvars;
12401 typval_T *rettv;
12403 rettv->vval.v_number = syn_name2id(get_tv_string(&argvars[0]));
12407 * "highlight_exists()" function
12409 static void
12410 f_hlexists(argvars, rettv)
12411 typval_T *argvars;
12412 typval_T *rettv;
12414 rettv->vval.v_number = highlight_exists(get_tv_string(&argvars[0]));
12418 * "hostname()" function
12420 static void
12421 f_hostname(argvars, rettv)
12422 typval_T *argvars UNUSED;
12423 typval_T *rettv;
12425 char_u hostname[256];
12427 mch_get_host_name(hostname, 256);
12428 rettv->v_type = VAR_STRING;
12429 rettv->vval.v_string = vim_strsave(hostname);
12433 * iconv() function
12435 static void
12436 f_iconv(argvars, rettv)
12437 typval_T *argvars UNUSED;
12438 typval_T *rettv;
12440 #ifdef FEAT_MBYTE
12441 char_u buf1[NUMBUFLEN];
12442 char_u buf2[NUMBUFLEN];
12443 char_u *from, *to, *str;
12444 vimconv_T vimconv;
12445 #endif
12447 rettv->v_type = VAR_STRING;
12448 rettv->vval.v_string = NULL;
12450 #ifdef FEAT_MBYTE
12451 str = get_tv_string(&argvars[0]);
12452 from = enc_canonize(enc_skip(get_tv_string_buf(&argvars[1], buf1)));
12453 to = enc_canonize(enc_skip(get_tv_string_buf(&argvars[2], buf2)));
12454 vimconv.vc_type = CONV_NONE;
12455 convert_setup(&vimconv, from, to);
12457 /* If the encodings are equal, no conversion needed. */
12458 if (vimconv.vc_type == CONV_NONE)
12459 rettv->vval.v_string = vim_strsave(str);
12460 else
12461 rettv->vval.v_string = string_convert(&vimconv, str, NULL);
12463 convert_setup(&vimconv, NULL, NULL);
12464 vim_free(from);
12465 vim_free(to);
12466 #endif
12470 * "indent()" function
12472 static void
12473 f_indent(argvars, rettv)
12474 typval_T *argvars;
12475 typval_T *rettv;
12477 linenr_T lnum;
12479 lnum = get_tv_lnum(argvars);
12480 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
12481 rettv->vval.v_number = get_indent_lnum(lnum);
12482 else
12483 rettv->vval.v_number = -1;
12487 * "index()" function
12489 static void
12490 f_index(argvars, rettv)
12491 typval_T *argvars;
12492 typval_T *rettv;
12494 list_T *l;
12495 listitem_T *item;
12496 long idx = 0;
12497 int ic = FALSE;
12499 rettv->vval.v_number = -1;
12500 if (argvars[0].v_type != VAR_LIST)
12502 EMSG(_(e_listreq));
12503 return;
12505 l = argvars[0].vval.v_list;
12506 if (l != NULL)
12508 item = l->lv_first;
12509 if (argvars[2].v_type != VAR_UNKNOWN)
12511 int error = FALSE;
12513 /* Start at specified item. Use the cached index that list_find()
12514 * sets, so that a negative number also works. */
12515 item = list_find(l, get_tv_number_chk(&argvars[2], &error));
12516 idx = l->lv_idx;
12517 if (argvars[3].v_type != VAR_UNKNOWN)
12518 ic = get_tv_number_chk(&argvars[3], &error);
12519 if (error)
12520 item = NULL;
12523 for ( ; item != NULL; item = item->li_next, ++idx)
12524 if (tv_equal(&item->li_tv, &argvars[1], ic))
12526 rettv->vval.v_number = idx;
12527 break;
12532 static int inputsecret_flag = 0;
12534 static void get_user_input __ARGS((typval_T *argvars, typval_T *rettv, int inputdialog));
12537 * This function is used by f_input() and f_inputdialog() functions. The third
12538 * argument to f_input() specifies the type of completion to use at the
12539 * prompt. The third argument to f_inputdialog() specifies the value to return
12540 * when the user cancels the prompt.
12542 static void
12543 get_user_input(argvars, rettv, inputdialog)
12544 typval_T *argvars;
12545 typval_T *rettv;
12546 int inputdialog;
12548 char_u *prompt = get_tv_string_chk(&argvars[0]);
12549 char_u *p = NULL;
12550 int c;
12551 char_u buf[NUMBUFLEN];
12552 int cmd_silent_save = cmd_silent;
12553 char_u *defstr = (char_u *)"";
12554 int xp_type = EXPAND_NOTHING;
12555 char_u *xp_arg = NULL;
12557 rettv->v_type = VAR_STRING;
12558 rettv->vval.v_string = NULL;
12560 #ifdef NO_CONSOLE_INPUT
12561 /* While starting up, there is no place to enter text. */
12562 if (no_console_input())
12563 return;
12564 #endif
12566 cmd_silent = FALSE; /* Want to see the prompt. */
12567 if (prompt != NULL)
12569 /* Only the part of the message after the last NL is considered as
12570 * prompt for the command line */
12571 p = vim_strrchr(prompt, '\n');
12572 if (p == NULL)
12573 p = prompt;
12574 else
12576 ++p;
12577 c = *p;
12578 *p = NUL;
12579 msg_start();
12580 msg_clr_eos();
12581 msg_puts_attr(prompt, echo_attr);
12582 msg_didout = FALSE;
12583 msg_starthere();
12584 *p = c;
12586 cmdline_row = msg_row;
12588 if (argvars[1].v_type != VAR_UNKNOWN)
12590 defstr = get_tv_string_buf_chk(&argvars[1], buf);
12591 if (defstr != NULL)
12592 stuffReadbuffSpec(defstr);
12594 if (!inputdialog && argvars[2].v_type != VAR_UNKNOWN)
12596 char_u *xp_name;
12597 int xp_namelen;
12598 long argt;
12600 rettv->vval.v_string = NULL;
12602 xp_name = get_tv_string_buf_chk(&argvars[2], buf);
12603 if (xp_name == NULL)
12604 return;
12606 xp_namelen = (int)STRLEN(xp_name);
12608 if (parse_compl_arg(xp_name, xp_namelen, &xp_type, &argt,
12609 &xp_arg) == FAIL)
12610 return;
12614 if (defstr != NULL)
12615 rettv->vval.v_string =
12616 getcmdline_prompt(inputsecret_flag ? NUL : '@', p, echo_attr,
12617 xp_type, xp_arg);
12619 vim_free(xp_arg);
12621 /* since the user typed this, no need to wait for return */
12622 need_wait_return = FALSE;
12623 msg_didout = FALSE;
12625 cmd_silent = cmd_silent_save;
12629 * "input()" function
12630 * Also handles inputsecret() when inputsecret is set.
12632 static void
12633 f_input(argvars, rettv)
12634 typval_T *argvars;
12635 typval_T *rettv;
12637 get_user_input(argvars, rettv, FALSE);
12641 * "inputdialog()" function
12643 static void
12644 f_inputdialog(argvars, rettv)
12645 typval_T *argvars;
12646 typval_T *rettv;
12648 #if defined(FEAT_GUI_TEXTDIALOG)
12649 /* Use a GUI dialog if the GUI is running and 'c' is not in 'guioptions' */
12650 if (gui.in_use && vim_strchr(p_go, GO_CONDIALOG) == NULL)
12652 char_u *message;
12653 char_u buf[NUMBUFLEN];
12654 char_u *defstr = (char_u *)"";
12656 message = get_tv_string_chk(&argvars[0]);
12657 if (argvars[1].v_type != VAR_UNKNOWN
12658 && (defstr = get_tv_string_buf_chk(&argvars[1], buf)) != NULL)
12659 vim_strncpy(IObuff, defstr, IOSIZE - 1);
12660 else
12661 IObuff[0] = NUL;
12662 if (message != NULL && defstr != NULL
12663 && do_dialog(VIM_QUESTION, NULL, message,
12664 (char_u *)_("&OK\n&Cancel"), 1, IObuff) == 1)
12665 rettv->vval.v_string = vim_strsave(IObuff);
12666 else
12668 if (message != NULL && defstr != NULL
12669 && argvars[1].v_type != VAR_UNKNOWN
12670 && argvars[2].v_type != VAR_UNKNOWN)
12671 rettv->vval.v_string = vim_strsave(
12672 get_tv_string_buf(&argvars[2], buf));
12673 else
12674 rettv->vval.v_string = NULL;
12676 rettv->v_type = VAR_STRING;
12678 else
12679 #endif
12680 get_user_input(argvars, rettv, TRUE);
12684 * "inputlist()" function
12686 static void
12687 f_inputlist(argvars, rettv)
12688 typval_T *argvars;
12689 typval_T *rettv;
12691 listitem_T *li;
12692 int selected;
12693 int mouse_used;
12695 #ifdef NO_CONSOLE_INPUT
12696 /* While starting up, there is no place to enter text. */
12697 if (no_console_input())
12698 return;
12699 #endif
12700 if (argvars[0].v_type != VAR_LIST || argvars[0].vval.v_list == NULL)
12702 EMSG2(_(e_listarg), "inputlist()");
12703 return;
12706 msg_start();
12707 msg_row = Rows - 1; /* for when 'cmdheight' > 1 */
12708 lines_left = Rows; /* avoid more prompt */
12709 msg_scroll = TRUE;
12710 msg_clr_eos();
12712 for (li = argvars[0].vval.v_list->lv_first; li != NULL; li = li->li_next)
12714 msg_puts(get_tv_string(&li->li_tv));
12715 msg_putchar('\n');
12718 /* Ask for choice. */
12719 selected = prompt_for_number(&mouse_used);
12720 if (mouse_used)
12721 selected -= lines_left;
12723 rettv->vval.v_number = selected;
12727 static garray_T ga_userinput = {0, 0, sizeof(tasave_T), 4, NULL};
12730 * "inputrestore()" function
12732 static void
12733 f_inputrestore(argvars, rettv)
12734 typval_T *argvars UNUSED;
12735 typval_T *rettv;
12737 if (ga_userinput.ga_len > 0)
12739 --ga_userinput.ga_len;
12740 restore_typeahead((tasave_T *)(ga_userinput.ga_data)
12741 + ga_userinput.ga_len);
12742 /* default return is zero == OK */
12744 else if (p_verbose > 1)
12746 verb_msg((char_u *)_("called inputrestore() more often than inputsave()"));
12747 rettv->vval.v_number = 1; /* Failed */
12752 * "inputsave()" function
12754 static void
12755 f_inputsave(argvars, rettv)
12756 typval_T *argvars UNUSED;
12757 typval_T *rettv;
12759 /* Add an entry to the stack of typeahead storage. */
12760 if (ga_grow(&ga_userinput, 1) == OK)
12762 save_typeahead((tasave_T *)(ga_userinput.ga_data)
12763 + ga_userinput.ga_len);
12764 ++ga_userinput.ga_len;
12765 /* default return is zero == OK */
12767 else
12768 rettv->vval.v_number = 1; /* Failed */
12772 * "inputsecret()" function
12774 static void
12775 f_inputsecret(argvars, rettv)
12776 typval_T *argvars;
12777 typval_T *rettv;
12779 ++cmdline_star;
12780 ++inputsecret_flag;
12781 f_input(argvars, rettv);
12782 --cmdline_star;
12783 --inputsecret_flag;
12787 * "insert()" function
12789 static void
12790 f_insert(argvars, rettv)
12791 typval_T *argvars;
12792 typval_T *rettv;
12794 long before = 0;
12795 listitem_T *item;
12796 list_T *l;
12797 int error = FALSE;
12799 if (argvars[0].v_type != VAR_LIST)
12800 EMSG2(_(e_listarg), "insert()");
12801 else if ((l = argvars[0].vval.v_list) != NULL
12802 && !tv_check_lock(l->lv_lock, (char_u *)"insert()"))
12804 if (argvars[2].v_type != VAR_UNKNOWN)
12805 before = get_tv_number_chk(&argvars[2], &error);
12806 if (error)
12807 return; /* type error; errmsg already given */
12809 if (before == l->lv_len)
12810 item = NULL;
12811 else
12813 item = list_find(l, before);
12814 if (item == NULL)
12816 EMSGN(_(e_listidx), before);
12817 l = NULL;
12820 if (l != NULL)
12822 list_insert_tv(l, &argvars[1], item);
12823 copy_tv(&argvars[0], rettv);
12829 * "isdirectory()" function
12831 static void
12832 f_isdirectory(argvars, rettv)
12833 typval_T *argvars;
12834 typval_T *rettv;
12836 rettv->vval.v_number = mch_isdir(get_tv_string(&argvars[0]));
12840 * "islocked()" function
12842 static void
12843 f_islocked(argvars, rettv)
12844 typval_T *argvars;
12845 typval_T *rettv;
12847 lval_T lv;
12848 char_u *end;
12849 dictitem_T *di;
12851 rettv->vval.v_number = -1;
12852 end = get_lval(get_tv_string(&argvars[0]), NULL, &lv, FALSE, FALSE, FALSE,
12853 FNE_CHECK_START);
12854 if (end != NULL && lv.ll_name != NULL)
12856 if (*end != NUL)
12857 EMSG(_(e_trailing));
12858 else
12860 if (lv.ll_tv == NULL)
12862 if (check_changedtick(lv.ll_name))
12863 rettv->vval.v_number = 1; /* always locked */
12864 else
12866 di = find_var(lv.ll_name, NULL);
12867 if (di != NULL)
12869 /* Consider a variable locked when:
12870 * 1. the variable itself is locked
12871 * 2. the value of the variable is locked.
12872 * 3. the List or Dict value is locked.
12874 rettv->vval.v_number = ((di->di_flags & DI_FLAGS_LOCK)
12875 || tv_islocked(&di->di_tv));
12879 else if (lv.ll_range)
12880 EMSG(_("E786: Range not allowed"));
12881 else if (lv.ll_newkey != NULL)
12882 EMSG2(_(e_dictkey), lv.ll_newkey);
12883 else if (lv.ll_list != NULL)
12884 /* List item. */
12885 rettv->vval.v_number = tv_islocked(&lv.ll_li->li_tv);
12886 else
12887 /* Dictionary item. */
12888 rettv->vval.v_number = tv_islocked(&lv.ll_di->di_tv);
12892 clear_lval(&lv);
12895 static void dict_list __ARGS((typval_T *argvars, typval_T *rettv, int what));
12898 * Turn a dict into a list:
12899 * "what" == 0: list of keys
12900 * "what" == 1: list of values
12901 * "what" == 2: list of items
12903 static void
12904 dict_list(argvars, rettv, what)
12905 typval_T *argvars;
12906 typval_T *rettv;
12907 int what;
12909 list_T *l2;
12910 dictitem_T *di;
12911 hashitem_T *hi;
12912 listitem_T *li;
12913 listitem_T *li2;
12914 dict_T *d;
12915 int todo;
12917 if (argvars[0].v_type != VAR_DICT)
12919 EMSG(_(e_dictreq));
12920 return;
12922 if ((d = argvars[0].vval.v_dict) == NULL)
12923 return;
12925 if (rettv_list_alloc(rettv) == FAIL)
12926 return;
12928 todo = (int)d->dv_hashtab.ht_used;
12929 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
12931 if (!HASHITEM_EMPTY(hi))
12933 --todo;
12934 di = HI2DI(hi);
12936 li = listitem_alloc();
12937 if (li == NULL)
12938 break;
12939 list_append(rettv->vval.v_list, li);
12941 if (what == 0)
12943 /* keys() */
12944 li->li_tv.v_type = VAR_STRING;
12945 li->li_tv.v_lock = 0;
12946 li->li_tv.vval.v_string = vim_strsave(di->di_key);
12948 else if (what == 1)
12950 /* values() */
12951 copy_tv(&di->di_tv, &li->li_tv);
12953 else
12955 /* items() */
12956 l2 = list_alloc();
12957 li->li_tv.v_type = VAR_LIST;
12958 li->li_tv.v_lock = 0;
12959 li->li_tv.vval.v_list = l2;
12960 if (l2 == NULL)
12961 break;
12962 ++l2->lv_refcount;
12964 li2 = listitem_alloc();
12965 if (li2 == NULL)
12966 break;
12967 list_append(l2, li2);
12968 li2->li_tv.v_type = VAR_STRING;
12969 li2->li_tv.v_lock = 0;
12970 li2->li_tv.vval.v_string = vim_strsave(di->di_key);
12972 li2 = listitem_alloc();
12973 if (li2 == NULL)
12974 break;
12975 list_append(l2, li2);
12976 copy_tv(&di->di_tv, &li2->li_tv);
12983 * "items(dict)" function
12985 static void
12986 f_items(argvars, rettv)
12987 typval_T *argvars;
12988 typval_T *rettv;
12990 dict_list(argvars, rettv, 2);
12994 * "join()" function
12996 static void
12997 f_join(argvars, rettv)
12998 typval_T *argvars;
12999 typval_T *rettv;
13001 garray_T ga;
13002 char_u *sep;
13004 if (argvars[0].v_type != VAR_LIST)
13006 EMSG(_(e_listreq));
13007 return;
13009 if (argvars[0].vval.v_list == NULL)
13010 return;
13011 if (argvars[1].v_type == VAR_UNKNOWN)
13012 sep = (char_u *)" ";
13013 else
13014 sep = get_tv_string_chk(&argvars[1]);
13016 rettv->v_type = VAR_STRING;
13018 if (sep != NULL)
13020 ga_init2(&ga, (int)sizeof(char), 80);
13021 list_join(&ga, argvars[0].vval.v_list, sep, TRUE, 0);
13022 ga_append(&ga, NUL);
13023 rettv->vval.v_string = (char_u *)ga.ga_data;
13025 else
13026 rettv->vval.v_string = NULL;
13030 * "keys()" function
13032 static void
13033 f_keys(argvars, rettv)
13034 typval_T *argvars;
13035 typval_T *rettv;
13037 dict_list(argvars, rettv, 0);
13041 * "last_buffer_nr()" function.
13043 static void
13044 f_last_buffer_nr(argvars, rettv)
13045 typval_T *argvars UNUSED;
13046 typval_T *rettv;
13048 int n = 0;
13049 buf_T *buf;
13051 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
13052 if (n < buf->b_fnum)
13053 n = buf->b_fnum;
13055 rettv->vval.v_number = n;
13059 * "len()" function
13061 static void
13062 f_len(argvars, rettv)
13063 typval_T *argvars;
13064 typval_T *rettv;
13066 switch (argvars[0].v_type)
13068 case VAR_STRING:
13069 case VAR_NUMBER:
13070 rettv->vval.v_number = (varnumber_T)STRLEN(
13071 get_tv_string(&argvars[0]));
13072 break;
13073 case VAR_LIST:
13074 rettv->vval.v_number = list_len(argvars[0].vval.v_list);
13075 break;
13076 case VAR_DICT:
13077 rettv->vval.v_number = dict_len(argvars[0].vval.v_dict);
13078 break;
13079 default:
13080 EMSG(_("E701: Invalid type for len()"));
13081 break;
13085 static void libcall_common __ARGS((typval_T *argvars, typval_T *rettv, int type));
13087 static void
13088 libcall_common(argvars, rettv, type)
13089 typval_T *argvars;
13090 typval_T *rettv;
13091 int type;
13093 #ifdef FEAT_LIBCALL
13094 char_u *string_in;
13095 char_u **string_result;
13096 int nr_result;
13097 #endif
13099 rettv->v_type = type;
13100 if (type != VAR_NUMBER)
13101 rettv->vval.v_string = NULL;
13103 if (check_restricted() || check_secure())
13104 return;
13106 #ifdef FEAT_LIBCALL
13107 /* The first two args must be strings, otherwise its meaningless */
13108 if (argvars[0].v_type == VAR_STRING && argvars[1].v_type == VAR_STRING)
13110 string_in = NULL;
13111 if (argvars[2].v_type == VAR_STRING)
13112 string_in = argvars[2].vval.v_string;
13113 if (type == VAR_NUMBER)
13114 string_result = NULL;
13115 else
13116 string_result = &rettv->vval.v_string;
13117 if (mch_libcall(argvars[0].vval.v_string,
13118 argvars[1].vval.v_string,
13119 string_in,
13120 argvars[2].vval.v_number,
13121 string_result,
13122 &nr_result) == OK
13123 && type == VAR_NUMBER)
13124 rettv->vval.v_number = nr_result;
13126 #endif
13130 * "libcall()" function
13132 static void
13133 f_libcall(argvars, rettv)
13134 typval_T *argvars;
13135 typval_T *rettv;
13137 libcall_common(argvars, rettv, VAR_STRING);
13141 * "libcallnr()" function
13143 static void
13144 f_libcallnr(argvars, rettv)
13145 typval_T *argvars;
13146 typval_T *rettv;
13148 libcall_common(argvars, rettv, VAR_NUMBER);
13152 * "line(string)" function
13154 static void
13155 f_line(argvars, rettv)
13156 typval_T *argvars;
13157 typval_T *rettv;
13159 linenr_T lnum = 0;
13160 pos_T *fp;
13161 int fnum;
13163 fp = var2fpos(&argvars[0], TRUE, &fnum);
13164 if (fp != NULL)
13165 lnum = fp->lnum;
13166 rettv->vval.v_number = lnum;
13170 * "line2byte(lnum)" function
13172 static void
13173 f_line2byte(argvars, rettv)
13174 typval_T *argvars UNUSED;
13175 typval_T *rettv;
13177 #ifndef FEAT_BYTEOFF
13178 rettv->vval.v_number = -1;
13179 #else
13180 linenr_T lnum;
13182 lnum = get_tv_lnum(argvars);
13183 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
13184 rettv->vval.v_number = -1;
13185 else
13186 rettv->vval.v_number = ml_find_line_or_offset(curbuf, lnum, NULL);
13187 if (rettv->vval.v_number >= 0)
13188 ++rettv->vval.v_number;
13189 #endif
13193 * "lispindent(lnum)" function
13195 static void
13196 f_lispindent(argvars, rettv)
13197 typval_T *argvars;
13198 typval_T *rettv;
13200 #ifdef FEAT_LISP
13201 pos_T pos;
13202 linenr_T lnum;
13204 pos = curwin->w_cursor;
13205 lnum = get_tv_lnum(argvars);
13206 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
13208 curwin->w_cursor.lnum = lnum;
13209 rettv->vval.v_number = get_lisp_indent();
13210 curwin->w_cursor = pos;
13212 else
13213 #endif
13214 rettv->vval.v_number = -1;
13218 * "localtime()" function
13220 static void
13221 f_localtime(argvars, rettv)
13222 typval_T *argvars UNUSED;
13223 typval_T *rettv;
13225 rettv->vval.v_number = (varnumber_T)time(NULL);
13228 static void get_maparg __ARGS((typval_T *argvars, typval_T *rettv, int exact));
13230 static void
13231 get_maparg(argvars, rettv, exact)
13232 typval_T *argvars;
13233 typval_T *rettv;
13234 int exact;
13236 char_u *keys;
13237 char_u *which;
13238 char_u buf[NUMBUFLEN];
13239 char_u *keys_buf = NULL;
13240 char_u *rhs;
13241 int mode;
13242 garray_T ga;
13243 int abbr = FALSE;
13245 /* return empty string for failure */
13246 rettv->v_type = VAR_STRING;
13247 rettv->vval.v_string = NULL;
13249 keys = get_tv_string(&argvars[0]);
13250 if (*keys == NUL)
13251 return;
13253 if (argvars[1].v_type != VAR_UNKNOWN)
13255 which = get_tv_string_buf_chk(&argvars[1], buf);
13256 if (argvars[2].v_type != VAR_UNKNOWN)
13257 abbr = get_tv_number(&argvars[2]);
13259 else
13260 which = (char_u *)"";
13261 if (which == NULL)
13262 return;
13264 mode = get_map_mode(&which, 0);
13266 keys = replace_termcodes(keys, &keys_buf, TRUE, TRUE, FALSE);
13267 rhs = check_map(keys, mode, exact, FALSE, abbr);
13268 vim_free(keys_buf);
13269 if (rhs != NULL)
13271 ga_init(&ga);
13272 ga.ga_itemsize = 1;
13273 ga.ga_growsize = 40;
13275 while (*rhs != NUL)
13276 ga_concat(&ga, str2special(&rhs, FALSE));
13278 ga_append(&ga, NUL);
13279 rettv->vval.v_string = (char_u *)ga.ga_data;
13283 #ifdef FEAT_FLOAT
13285 * "log10()" function
13287 static void
13288 f_log10(argvars, rettv)
13289 typval_T *argvars;
13290 typval_T *rettv;
13292 float_T f;
13294 rettv->v_type = VAR_FLOAT;
13295 if (get_float_arg(argvars, &f) == OK)
13296 rettv->vval.v_float = log10(f);
13297 else
13298 rettv->vval.v_float = 0.0;
13300 #endif
13303 * "map()" function
13305 static void
13306 f_map(argvars, rettv)
13307 typval_T *argvars;
13308 typval_T *rettv;
13310 filter_map(argvars, rettv, TRUE);
13314 * "maparg()" function
13316 static void
13317 f_maparg(argvars, rettv)
13318 typval_T *argvars;
13319 typval_T *rettv;
13321 get_maparg(argvars, rettv, TRUE);
13325 * "mapcheck()" function
13327 static void
13328 f_mapcheck(argvars, rettv)
13329 typval_T *argvars;
13330 typval_T *rettv;
13332 get_maparg(argvars, rettv, FALSE);
13335 static void find_some_match __ARGS((typval_T *argvars, typval_T *rettv, int start));
13337 static void
13338 find_some_match(argvars, rettv, type)
13339 typval_T *argvars;
13340 typval_T *rettv;
13341 int type;
13343 char_u *str = NULL;
13344 char_u *expr = NULL;
13345 char_u *pat;
13346 regmatch_T regmatch;
13347 char_u patbuf[NUMBUFLEN];
13348 char_u strbuf[NUMBUFLEN];
13349 char_u *save_cpo;
13350 long start = 0;
13351 long nth = 1;
13352 colnr_T startcol = 0;
13353 int match = 0;
13354 list_T *l = NULL;
13355 listitem_T *li = NULL;
13356 long idx = 0;
13357 char_u *tofree = NULL;
13359 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
13360 save_cpo = p_cpo;
13361 p_cpo = (char_u *)"";
13363 rettv->vval.v_number = -1;
13364 if (type == 3)
13366 /* return empty list when there are no matches */
13367 if (rettv_list_alloc(rettv) == FAIL)
13368 goto theend;
13370 else if (type == 2)
13372 rettv->v_type = VAR_STRING;
13373 rettv->vval.v_string = NULL;
13376 if (argvars[0].v_type == VAR_LIST)
13378 if ((l = argvars[0].vval.v_list) == NULL)
13379 goto theend;
13380 li = l->lv_first;
13382 else
13383 expr = str = get_tv_string(&argvars[0]);
13385 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
13386 if (pat == NULL)
13387 goto theend;
13389 if (argvars[2].v_type != VAR_UNKNOWN)
13391 int error = FALSE;
13393 start = get_tv_number_chk(&argvars[2], &error);
13394 if (error)
13395 goto theend;
13396 if (l != NULL)
13398 li = list_find(l, start);
13399 if (li == NULL)
13400 goto theend;
13401 idx = l->lv_idx; /* use the cached index */
13403 else
13405 if (start < 0)
13406 start = 0;
13407 if (start > (long)STRLEN(str))
13408 goto theend;
13409 /* When "count" argument is there ignore matches before "start",
13410 * otherwise skip part of the string. Differs when pattern is "^"
13411 * or "\<". */
13412 if (argvars[3].v_type != VAR_UNKNOWN)
13413 startcol = start;
13414 else
13415 str += start;
13418 if (argvars[3].v_type != VAR_UNKNOWN)
13419 nth = get_tv_number_chk(&argvars[3], &error);
13420 if (error)
13421 goto theend;
13424 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
13425 if (regmatch.regprog != NULL)
13427 regmatch.rm_ic = p_ic;
13429 for (;;)
13431 if (l != NULL)
13433 if (li == NULL)
13435 match = FALSE;
13436 break;
13438 vim_free(tofree);
13439 str = echo_string(&li->li_tv, &tofree, strbuf, 0);
13440 if (str == NULL)
13441 break;
13444 match = vim_regexec_nl(&regmatch, str, (colnr_T)startcol);
13446 if (match && --nth <= 0)
13447 break;
13448 if (l == NULL && !match)
13449 break;
13451 /* Advance to just after the match. */
13452 if (l != NULL)
13454 li = li->li_next;
13455 ++idx;
13457 else
13459 #ifdef FEAT_MBYTE
13460 startcol = (colnr_T)(regmatch.startp[0]
13461 + (*mb_ptr2len)(regmatch.startp[0]) - str);
13462 #else
13463 startcol = regmatch.startp[0] + 1 - str;
13464 #endif
13468 if (match)
13470 if (type == 3)
13472 int i;
13474 /* return list with matched string and submatches */
13475 for (i = 0; i < NSUBEXP; ++i)
13477 if (regmatch.endp[i] == NULL)
13479 if (list_append_string(rettv->vval.v_list,
13480 (char_u *)"", 0) == FAIL)
13481 break;
13483 else if (list_append_string(rettv->vval.v_list,
13484 regmatch.startp[i],
13485 (int)(regmatch.endp[i] - regmatch.startp[i]))
13486 == FAIL)
13487 break;
13490 else if (type == 2)
13492 /* return matched string */
13493 if (l != NULL)
13494 copy_tv(&li->li_tv, rettv);
13495 else
13496 rettv->vval.v_string = vim_strnsave(regmatch.startp[0],
13497 (int)(regmatch.endp[0] - regmatch.startp[0]));
13499 else if (l != NULL)
13500 rettv->vval.v_number = idx;
13501 else
13503 if (type != 0)
13504 rettv->vval.v_number =
13505 (varnumber_T)(regmatch.startp[0] - str);
13506 else
13507 rettv->vval.v_number =
13508 (varnumber_T)(regmatch.endp[0] - str);
13509 rettv->vval.v_number += (varnumber_T)(str - expr);
13512 vim_free(regmatch.regprog);
13515 theend:
13516 vim_free(tofree);
13517 p_cpo = save_cpo;
13521 * "match()" function
13523 static void
13524 f_match(argvars, rettv)
13525 typval_T *argvars;
13526 typval_T *rettv;
13528 find_some_match(argvars, rettv, 1);
13532 * "matchadd()" function
13534 static void
13535 f_matchadd(argvars, rettv)
13536 typval_T *argvars;
13537 typval_T *rettv;
13539 #ifdef FEAT_SEARCH_EXTRA
13540 char_u buf[NUMBUFLEN];
13541 char_u *grp = get_tv_string_buf_chk(&argvars[0], buf); /* group */
13542 char_u *pat = get_tv_string_buf_chk(&argvars[1], buf); /* pattern */
13543 int prio = 10; /* default priority */
13544 int id = -1;
13545 int error = FALSE;
13547 rettv->vval.v_number = -1;
13549 if (grp == NULL || pat == NULL)
13550 return;
13551 if (argvars[2].v_type != VAR_UNKNOWN)
13553 prio = get_tv_number_chk(&argvars[2], &error);
13554 if (argvars[3].v_type != VAR_UNKNOWN)
13555 id = get_tv_number_chk(&argvars[3], &error);
13557 if (error == TRUE)
13558 return;
13559 if (id >= 1 && id <= 3)
13561 EMSGN("E798: ID is reserved for \":match\": %ld", id);
13562 return;
13565 rettv->vval.v_number = match_add(curwin, grp, pat, prio, id);
13566 #endif
13570 * "matcharg()" function
13572 static void
13573 f_matcharg(argvars, rettv)
13574 typval_T *argvars;
13575 typval_T *rettv;
13577 if (rettv_list_alloc(rettv) == OK)
13579 #ifdef FEAT_SEARCH_EXTRA
13580 int id = get_tv_number(&argvars[0]);
13581 matchitem_T *m;
13583 if (id >= 1 && id <= 3)
13585 if ((m = (matchitem_T *)get_match(curwin, id)) != NULL)
13587 list_append_string(rettv->vval.v_list,
13588 syn_id2name(m->hlg_id), -1);
13589 list_append_string(rettv->vval.v_list, m->pattern, -1);
13591 else
13593 list_append_string(rettv->vval.v_list, NUL, -1);
13594 list_append_string(rettv->vval.v_list, NUL, -1);
13597 #endif
13602 * "matchdelete()" function
13604 static void
13605 f_matchdelete(argvars, rettv)
13606 typval_T *argvars;
13607 typval_T *rettv;
13609 #ifdef FEAT_SEARCH_EXTRA
13610 rettv->vval.v_number = match_delete(curwin,
13611 (int)get_tv_number(&argvars[0]), TRUE);
13612 #endif
13616 * "matchend()" function
13618 static void
13619 f_matchend(argvars, rettv)
13620 typval_T *argvars;
13621 typval_T *rettv;
13623 find_some_match(argvars, rettv, 0);
13627 * "matchlist()" function
13629 static void
13630 f_matchlist(argvars, rettv)
13631 typval_T *argvars;
13632 typval_T *rettv;
13634 find_some_match(argvars, rettv, 3);
13638 * "matchstr()" function
13640 static void
13641 f_matchstr(argvars, rettv)
13642 typval_T *argvars;
13643 typval_T *rettv;
13645 find_some_match(argvars, rettv, 2);
13648 static void max_min __ARGS((typval_T *argvars, typval_T *rettv, int domax));
13650 static void
13651 max_min(argvars, rettv, domax)
13652 typval_T *argvars;
13653 typval_T *rettv;
13654 int domax;
13656 long n = 0;
13657 long i;
13658 int error = FALSE;
13660 if (argvars[0].v_type == VAR_LIST)
13662 list_T *l;
13663 listitem_T *li;
13665 l = argvars[0].vval.v_list;
13666 if (l != NULL)
13668 li = l->lv_first;
13669 if (li != NULL)
13671 n = get_tv_number_chk(&li->li_tv, &error);
13672 for (;;)
13674 li = li->li_next;
13675 if (li == NULL)
13676 break;
13677 i = get_tv_number_chk(&li->li_tv, &error);
13678 if (domax ? i > n : i < n)
13679 n = i;
13684 else if (argvars[0].v_type == VAR_DICT)
13686 dict_T *d;
13687 int first = TRUE;
13688 hashitem_T *hi;
13689 int todo;
13691 d = argvars[0].vval.v_dict;
13692 if (d != NULL)
13694 todo = (int)d->dv_hashtab.ht_used;
13695 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
13697 if (!HASHITEM_EMPTY(hi))
13699 --todo;
13700 i = get_tv_number_chk(&HI2DI(hi)->di_tv, &error);
13701 if (first)
13703 n = i;
13704 first = FALSE;
13706 else if (domax ? i > n : i < n)
13707 n = i;
13712 else
13713 EMSG(_(e_listdictarg));
13714 rettv->vval.v_number = error ? 0 : n;
13718 * "max()" function
13720 static void
13721 f_max(argvars, rettv)
13722 typval_T *argvars;
13723 typval_T *rettv;
13725 max_min(argvars, rettv, TRUE);
13729 * "min()" function
13731 static void
13732 f_min(argvars, rettv)
13733 typval_T *argvars;
13734 typval_T *rettv;
13736 max_min(argvars, rettv, FALSE);
13739 static int mkdir_recurse __ARGS((char_u *dir, int prot));
13742 * Create the directory in which "dir" is located, and higher levels when
13743 * needed.
13745 static int
13746 mkdir_recurse(dir, prot)
13747 char_u *dir;
13748 int prot;
13750 char_u *p;
13751 char_u *updir;
13752 int r = FAIL;
13754 /* Get end of directory name in "dir".
13755 * We're done when it's "/" or "c:/". */
13756 p = gettail_sep(dir);
13757 if (p <= get_past_head(dir))
13758 return OK;
13760 /* If the directory exists we're done. Otherwise: create it.*/
13761 updir = vim_strnsave(dir, (int)(p - dir));
13762 if (updir == NULL)
13763 return FAIL;
13764 if (mch_isdir(updir))
13765 r = OK;
13766 else if (mkdir_recurse(updir, prot) == OK)
13767 r = vim_mkdir_emsg(updir, prot);
13768 vim_free(updir);
13769 return r;
13772 #ifdef vim_mkdir
13774 * "mkdir()" function
13776 static void
13777 f_mkdir(argvars, rettv)
13778 typval_T *argvars;
13779 typval_T *rettv;
13781 char_u *dir;
13782 char_u buf[NUMBUFLEN];
13783 int prot = 0755;
13785 rettv->vval.v_number = FAIL;
13786 if (check_restricted() || check_secure())
13787 return;
13789 dir = get_tv_string_buf(&argvars[0], buf);
13790 if (argvars[1].v_type != VAR_UNKNOWN)
13792 if (argvars[2].v_type != VAR_UNKNOWN)
13793 prot = get_tv_number_chk(&argvars[2], NULL);
13794 if (prot != -1 && STRCMP(get_tv_string(&argvars[1]), "p") == 0)
13795 mkdir_recurse(dir, prot);
13797 rettv->vval.v_number = prot != -1 ? vim_mkdir_emsg(dir, prot) : 0;
13799 #endif
13802 * "mode()" function
13804 static void
13805 f_mode(argvars, rettv)
13806 typval_T *argvars;
13807 typval_T *rettv;
13809 char_u buf[3];
13811 buf[1] = NUL;
13812 buf[2] = NUL;
13814 #ifdef FEAT_VISUAL
13815 if (VIsual_active)
13817 if (VIsual_select)
13818 buf[0] = VIsual_mode + 's' - 'v';
13819 else
13820 buf[0] = VIsual_mode;
13822 else
13823 #endif
13824 if (State == HITRETURN || State == ASKMORE || State == SETWSIZE
13825 || State == CONFIRM)
13827 buf[0] = 'r';
13828 if (State == ASKMORE)
13829 buf[1] = 'm';
13830 else if (State == CONFIRM)
13831 buf[1] = '?';
13833 else if (State == EXTERNCMD)
13834 buf[0] = '!';
13835 else if (State & INSERT)
13837 #ifdef FEAT_VREPLACE
13838 if (State & VREPLACE_FLAG)
13840 buf[0] = 'R';
13841 buf[1] = 'v';
13843 else
13844 #endif
13845 if (State & REPLACE_FLAG)
13846 buf[0] = 'R';
13847 else
13848 buf[0] = 'i';
13850 else if (State & CMDLINE)
13852 buf[0] = 'c';
13853 if (exmode_active)
13854 buf[1] = 'v';
13856 else if (exmode_active)
13858 buf[0] = 'c';
13859 buf[1] = 'e';
13861 else
13863 buf[0] = 'n';
13864 if (finish_op)
13865 buf[1] = 'o';
13868 /* Clear out the minor mode when the argument is not a non-zero number or
13869 * non-empty string. */
13870 if (!non_zero_arg(&argvars[0]))
13871 buf[1] = NUL;
13873 rettv->vval.v_string = vim_strsave(buf);
13874 rettv->v_type = VAR_STRING;
13877 #ifdef FEAT_MZSCHEME
13879 * "mzeval()" function
13881 static void
13882 f_mzeval(argvars, rettv)
13883 typval_T *argvars;
13884 typval_T *rettv;
13886 char_u *str;
13887 char_u buf[NUMBUFLEN];
13889 str = get_tv_string_buf(&argvars[0], buf);
13890 do_mzeval(str, rettv);
13892 #endif
13895 * "nextnonblank()" function
13897 static void
13898 f_nextnonblank(argvars, rettv)
13899 typval_T *argvars;
13900 typval_T *rettv;
13902 linenr_T lnum;
13904 for (lnum = get_tv_lnum(argvars); ; ++lnum)
13906 if (lnum < 0 || lnum > curbuf->b_ml.ml_line_count)
13908 lnum = 0;
13909 break;
13911 if (*skipwhite(ml_get(lnum)) != NUL)
13912 break;
13914 rettv->vval.v_number = lnum;
13918 * "nr2char()" function
13920 static void
13921 f_nr2char(argvars, rettv)
13922 typval_T *argvars;
13923 typval_T *rettv;
13925 char_u buf[NUMBUFLEN];
13927 #ifdef FEAT_MBYTE
13928 if (has_mbyte)
13929 buf[(*mb_char2bytes)((int)get_tv_number(&argvars[0]), buf)] = NUL;
13930 else
13931 #endif
13933 buf[0] = (char_u)get_tv_number(&argvars[0]);
13934 buf[1] = NUL;
13936 rettv->v_type = VAR_STRING;
13937 rettv->vval.v_string = vim_strsave(buf);
13941 * "pathshorten()" function
13943 static void
13944 f_pathshorten(argvars, rettv)
13945 typval_T *argvars;
13946 typval_T *rettv;
13948 char_u *p;
13950 rettv->v_type = VAR_STRING;
13951 p = get_tv_string_chk(&argvars[0]);
13952 if (p == NULL)
13953 rettv->vval.v_string = NULL;
13954 else
13956 p = vim_strsave(p);
13957 rettv->vval.v_string = p;
13958 if (p != NULL)
13959 shorten_dir(p);
13963 #ifdef FEAT_FLOAT
13965 * "pow()" function
13967 static void
13968 f_pow(argvars, rettv)
13969 typval_T *argvars;
13970 typval_T *rettv;
13972 float_T fx, fy;
13974 rettv->v_type = VAR_FLOAT;
13975 if (get_float_arg(argvars, &fx) == OK
13976 && get_float_arg(&argvars[1], &fy) == OK)
13977 rettv->vval.v_float = pow(fx, fy);
13978 else
13979 rettv->vval.v_float = 0.0;
13981 #endif
13984 * "prevnonblank()" function
13986 static void
13987 f_prevnonblank(argvars, rettv)
13988 typval_T *argvars;
13989 typval_T *rettv;
13991 linenr_T lnum;
13993 lnum = get_tv_lnum(argvars);
13994 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
13995 lnum = 0;
13996 else
13997 while (lnum >= 1 && *skipwhite(ml_get(lnum)) == NUL)
13998 --lnum;
13999 rettv->vval.v_number = lnum;
14002 #ifdef HAVE_STDARG_H
14003 /* This dummy va_list is here because:
14004 * - passing a NULL pointer doesn't work when va_list isn't a pointer
14005 * - locally in the function results in a "used before set" warning
14006 * - using va_start() to initialize it gives "function with fixed args" error */
14007 static va_list ap;
14008 #endif
14011 * "printf()" function
14013 static void
14014 f_printf(argvars, rettv)
14015 typval_T *argvars;
14016 typval_T *rettv;
14018 rettv->v_type = VAR_STRING;
14019 rettv->vval.v_string = NULL;
14020 #ifdef HAVE_STDARG_H /* only very old compilers can't do this */
14022 char_u buf[NUMBUFLEN];
14023 int len;
14024 char_u *s;
14025 int saved_did_emsg = did_emsg;
14026 char *fmt;
14028 /* Get the required length, allocate the buffer and do it for real. */
14029 did_emsg = FALSE;
14030 fmt = (char *)get_tv_string_buf(&argvars[0], buf);
14031 len = vim_vsnprintf(NULL, 0, fmt, ap, argvars + 1);
14032 if (!did_emsg)
14034 s = alloc(len + 1);
14035 if (s != NULL)
14037 rettv->vval.v_string = s;
14038 (void)vim_vsnprintf((char *)s, len + 1, fmt, ap, argvars + 1);
14041 did_emsg |= saved_did_emsg;
14043 #endif
14047 * "pumvisible()" function
14049 static void
14050 f_pumvisible(argvars, rettv)
14051 typval_T *argvars UNUSED;
14052 typval_T *rettv UNUSED;
14054 #ifdef FEAT_INS_EXPAND
14055 if (pum_visible())
14056 rettv->vval.v_number = 1;
14057 #endif
14061 * "range()" function
14063 static void
14064 f_range(argvars, rettv)
14065 typval_T *argvars;
14066 typval_T *rettv;
14068 long start;
14069 long end;
14070 long stride = 1;
14071 long i;
14072 int error = FALSE;
14074 start = get_tv_number_chk(&argvars[0], &error);
14075 if (argvars[1].v_type == VAR_UNKNOWN)
14077 end = start - 1;
14078 start = 0;
14080 else
14082 end = get_tv_number_chk(&argvars[1], &error);
14083 if (argvars[2].v_type != VAR_UNKNOWN)
14084 stride = get_tv_number_chk(&argvars[2], &error);
14087 if (error)
14088 return; /* type error; errmsg already given */
14089 if (stride == 0)
14090 EMSG(_("E726: Stride is zero"));
14091 else if (stride > 0 ? end + 1 < start : end - 1 > start)
14092 EMSG(_("E727: Start past end"));
14093 else
14095 if (rettv_list_alloc(rettv) == OK)
14096 for (i = start; stride > 0 ? i <= end : i >= end; i += stride)
14097 if (list_append_number(rettv->vval.v_list,
14098 (varnumber_T)i) == FAIL)
14099 break;
14104 * "readfile()" function
14106 static void
14107 f_readfile(argvars, rettv)
14108 typval_T *argvars;
14109 typval_T *rettv;
14111 int binary = FALSE;
14112 char_u *fname;
14113 FILE *fd;
14114 listitem_T *li;
14115 #define FREAD_SIZE 200 /* optimized for text lines */
14116 char_u buf[FREAD_SIZE];
14117 int readlen; /* size of last fread() */
14118 int buflen; /* nr of valid chars in buf[] */
14119 int filtd; /* how much in buf[] was NUL -> '\n' filtered */
14120 int tolist; /* first byte in buf[] still to be put in list */
14121 int chop; /* how many CR to chop off */
14122 char_u *prev = NULL; /* previously read bytes, if any */
14123 int prevlen = 0; /* length of "prev" if not NULL */
14124 char_u *s;
14125 int len;
14126 long maxline = MAXLNUM;
14127 long cnt = 0;
14129 if (argvars[1].v_type != VAR_UNKNOWN)
14131 if (STRCMP(get_tv_string(&argvars[1]), "b") == 0)
14132 binary = TRUE;
14133 if (argvars[2].v_type != VAR_UNKNOWN)
14134 maxline = get_tv_number(&argvars[2]);
14137 if (rettv_list_alloc(rettv) == FAIL)
14138 return;
14140 /* Always open the file in binary mode, library functions have a mind of
14141 * their own about CR-LF conversion. */
14142 fname = get_tv_string(&argvars[0]);
14143 if (*fname == NUL || (fd = mch_fopen((char *)fname, READBIN)) == NULL)
14145 EMSG2(_(e_notopen), *fname == NUL ? (char_u *)_("<empty>") : fname);
14146 return;
14149 filtd = 0;
14150 while (cnt < maxline || maxline < 0)
14152 readlen = (int)fread(buf + filtd, 1, FREAD_SIZE - filtd, fd);
14153 buflen = filtd + readlen;
14154 tolist = 0;
14155 for ( ; filtd < buflen || readlen <= 0; ++filtd)
14157 if (buf[filtd] == '\n' || readlen <= 0)
14159 /* Only when in binary mode add an empty list item when the
14160 * last line ends in a '\n'. */
14161 if (!binary && readlen == 0 && filtd == 0)
14162 break;
14164 /* Found end-of-line or end-of-file: add a text line to the
14165 * list. */
14166 chop = 0;
14167 if (!binary)
14168 while (filtd - chop - 1 >= tolist
14169 && buf[filtd - chop - 1] == '\r')
14170 ++chop;
14171 len = filtd - tolist - chop;
14172 if (prev == NULL)
14173 s = vim_strnsave(buf + tolist, len);
14174 else
14176 s = alloc((unsigned)(prevlen + len + 1));
14177 if (s != NULL)
14179 mch_memmove(s, prev, prevlen);
14180 vim_free(prev);
14181 prev = NULL;
14182 mch_memmove(s + prevlen, buf + tolist, len);
14183 s[prevlen + len] = NUL;
14186 tolist = filtd + 1;
14188 li = listitem_alloc();
14189 if (li == NULL)
14191 vim_free(s);
14192 break;
14194 li->li_tv.v_type = VAR_STRING;
14195 li->li_tv.v_lock = 0;
14196 li->li_tv.vval.v_string = s;
14197 list_append(rettv->vval.v_list, li);
14199 if (++cnt >= maxline && maxline >= 0)
14200 break;
14201 if (readlen <= 0)
14202 break;
14204 else if (buf[filtd] == NUL)
14205 buf[filtd] = '\n';
14207 if (readlen <= 0)
14208 break;
14210 if (tolist == 0)
14212 /* "buf" is full, need to move text to an allocated buffer */
14213 if (prev == NULL)
14215 prev = vim_strnsave(buf, buflen);
14216 prevlen = buflen;
14218 else
14220 s = alloc((unsigned)(prevlen + buflen));
14221 if (s != NULL)
14223 mch_memmove(s, prev, prevlen);
14224 mch_memmove(s + prevlen, buf, buflen);
14225 vim_free(prev);
14226 prev = s;
14227 prevlen += buflen;
14230 filtd = 0;
14232 else
14234 mch_memmove(buf, buf + tolist, buflen - tolist);
14235 filtd -= tolist;
14240 * For a negative line count use only the lines at the end of the file,
14241 * free the rest.
14243 if (maxline < 0)
14244 while (cnt > -maxline)
14246 listitem_remove(rettv->vval.v_list, rettv->vval.v_list->lv_first);
14247 --cnt;
14250 vim_free(prev);
14251 fclose(fd);
14254 #if defined(FEAT_RELTIME)
14255 static int list2proftime __ARGS((typval_T *arg, proftime_T *tm));
14258 * Convert a List to proftime_T.
14259 * Return FAIL when there is something wrong.
14261 static int
14262 list2proftime(arg, tm)
14263 typval_T *arg;
14264 proftime_T *tm;
14266 long n1, n2;
14267 int error = FALSE;
14269 if (arg->v_type != VAR_LIST || arg->vval.v_list == NULL
14270 || arg->vval.v_list->lv_len != 2)
14271 return FAIL;
14272 n1 = list_find_nr(arg->vval.v_list, 0L, &error);
14273 n2 = list_find_nr(arg->vval.v_list, 1L, &error);
14274 # ifdef WIN3264
14275 tm->HighPart = n1;
14276 tm->LowPart = n2;
14277 # else
14278 tm->tv_sec = n1;
14279 tm->tv_usec = n2;
14280 # endif
14281 return error ? FAIL : OK;
14283 #endif /* FEAT_RELTIME */
14286 * "reltime()" function
14288 static void
14289 f_reltime(argvars, rettv)
14290 typval_T *argvars;
14291 typval_T *rettv;
14293 #ifdef FEAT_RELTIME
14294 proftime_T res;
14295 proftime_T start;
14297 if (argvars[0].v_type == VAR_UNKNOWN)
14299 /* No arguments: get current time. */
14300 profile_start(&res);
14302 else if (argvars[1].v_type == VAR_UNKNOWN)
14304 if (list2proftime(&argvars[0], &res) == FAIL)
14305 return;
14306 profile_end(&res);
14308 else
14310 /* Two arguments: compute the difference. */
14311 if (list2proftime(&argvars[0], &start) == FAIL
14312 || list2proftime(&argvars[1], &res) == FAIL)
14313 return;
14314 profile_sub(&res, &start);
14317 if (rettv_list_alloc(rettv) == OK)
14319 long n1, n2;
14321 # ifdef WIN3264
14322 n1 = res.HighPart;
14323 n2 = res.LowPart;
14324 # else
14325 n1 = res.tv_sec;
14326 n2 = res.tv_usec;
14327 # endif
14328 list_append_number(rettv->vval.v_list, (varnumber_T)n1);
14329 list_append_number(rettv->vval.v_list, (varnumber_T)n2);
14331 #endif
14335 * "reltimestr()" function
14337 static void
14338 f_reltimestr(argvars, rettv)
14339 typval_T *argvars;
14340 typval_T *rettv;
14342 #ifdef FEAT_RELTIME
14343 proftime_T tm;
14344 #endif
14346 rettv->v_type = VAR_STRING;
14347 rettv->vval.v_string = NULL;
14348 #ifdef FEAT_RELTIME
14349 if (list2proftime(&argvars[0], &tm) == OK)
14350 rettv->vval.v_string = vim_strsave((char_u *)profile_msg(&tm));
14351 #endif
14354 #if defined(FEAT_CLIENTSERVER) && defined(FEAT_X11)
14355 static void make_connection __ARGS((void));
14356 static int check_connection __ARGS((void));
14358 static void
14359 make_connection()
14361 if (X_DISPLAY == NULL
14362 # ifdef FEAT_GUI
14363 && !gui.in_use
14364 # endif
14367 x_force_connect = TRUE;
14368 setup_term_clip();
14369 x_force_connect = FALSE;
14373 static int
14374 check_connection()
14376 make_connection();
14377 if (X_DISPLAY == NULL)
14379 EMSG(_("E240: No connection to Vim server"));
14380 return FAIL;
14382 return OK;
14384 #endif
14386 #ifdef FEAT_CLIENTSERVER
14387 static void remote_common __ARGS((typval_T *argvars, typval_T *rettv, int expr));
14389 static void
14390 remote_common(argvars, rettv, expr)
14391 typval_T *argvars;
14392 typval_T *rettv;
14393 int expr;
14395 char_u *server_name;
14396 char_u *keys;
14397 char_u *r = NULL;
14398 char_u buf[NUMBUFLEN];
14399 # ifdef WIN32
14400 HWND w;
14401 # else
14402 Window w;
14403 # endif
14405 if (check_restricted() || check_secure())
14406 return;
14408 # ifdef FEAT_X11
14409 if (check_connection() == FAIL)
14410 return;
14411 # endif
14413 server_name = get_tv_string_chk(&argvars[0]);
14414 if (server_name == NULL)
14415 return; /* type error; errmsg already given */
14416 keys = get_tv_string_buf(&argvars[1], buf);
14417 # ifdef WIN32
14418 if (serverSendToVim(server_name, keys, &r, &w, expr, TRUE) < 0)
14419 # else
14420 if (serverSendToVim(X_DISPLAY, server_name, keys, &r, &w, expr, 0, TRUE)
14421 < 0)
14422 # endif
14424 if (r != NULL)
14425 EMSG(r); /* sending worked but evaluation failed */
14426 else
14427 EMSG2(_("E241: Unable to send to %s"), server_name);
14428 return;
14431 rettv->vval.v_string = r;
14433 if (argvars[2].v_type != VAR_UNKNOWN)
14435 dictitem_T v;
14436 char_u str[30];
14437 char_u *idvar;
14439 sprintf((char *)str, PRINTF_HEX_LONG_U, (long_u)w);
14440 v.di_tv.v_type = VAR_STRING;
14441 v.di_tv.vval.v_string = vim_strsave(str);
14442 idvar = get_tv_string_chk(&argvars[2]);
14443 if (idvar != NULL)
14444 set_var(idvar, &v.di_tv, FALSE);
14445 vim_free(v.di_tv.vval.v_string);
14448 #endif
14451 * "remote_expr()" function
14453 static void
14454 f_remote_expr(argvars, rettv)
14455 typval_T *argvars UNUSED;
14456 typval_T *rettv;
14458 rettv->v_type = VAR_STRING;
14459 rettv->vval.v_string = NULL;
14460 #ifdef FEAT_CLIENTSERVER
14461 remote_common(argvars, rettv, TRUE);
14462 #endif
14466 * "remote_foreground()" function
14468 static void
14469 f_remote_foreground(argvars, rettv)
14470 typval_T *argvars UNUSED;
14471 typval_T *rettv UNUSED;
14473 #ifdef FEAT_CLIENTSERVER
14474 # ifdef WIN32
14475 /* On Win32 it's done in this application. */
14477 char_u *server_name = get_tv_string_chk(&argvars[0]);
14479 if (server_name != NULL)
14480 serverForeground(server_name);
14482 # else
14483 /* Send a foreground() expression to the server. */
14484 argvars[1].v_type = VAR_STRING;
14485 argvars[1].vval.v_string = vim_strsave((char_u *)"foreground()");
14486 argvars[2].v_type = VAR_UNKNOWN;
14487 remote_common(argvars, rettv, TRUE);
14488 vim_free(argvars[1].vval.v_string);
14489 # endif
14490 #endif
14493 static void
14494 f_remote_peek(argvars, rettv)
14495 typval_T *argvars UNUSED;
14496 typval_T *rettv;
14498 #ifdef FEAT_CLIENTSERVER
14499 dictitem_T v;
14500 char_u *s = NULL;
14501 # ifdef WIN32
14502 long_u n = 0;
14503 # endif
14504 char_u *serverid;
14506 if (check_restricted() || check_secure())
14508 rettv->vval.v_number = -1;
14509 return;
14511 serverid = get_tv_string_chk(&argvars[0]);
14512 if (serverid == NULL)
14514 rettv->vval.v_number = -1;
14515 return; /* type error; errmsg already given */
14517 # ifdef WIN32
14518 sscanf(serverid, SCANF_HEX_LONG_U, &n);
14519 if (n == 0)
14520 rettv->vval.v_number = -1;
14521 else
14523 s = serverGetReply((HWND)n, FALSE, FALSE, FALSE);
14524 rettv->vval.v_number = (s != NULL);
14526 # else
14527 if (check_connection() == FAIL)
14528 return;
14530 rettv->vval.v_number = serverPeekReply(X_DISPLAY,
14531 serverStrToWin(serverid), &s);
14532 # endif
14534 if (argvars[1].v_type != VAR_UNKNOWN && rettv->vval.v_number > 0)
14536 char_u *retvar;
14538 v.di_tv.v_type = VAR_STRING;
14539 v.di_tv.vval.v_string = vim_strsave(s);
14540 retvar = get_tv_string_chk(&argvars[1]);
14541 if (retvar != NULL)
14542 set_var(retvar, &v.di_tv, FALSE);
14543 vim_free(v.di_tv.vval.v_string);
14545 #else
14546 rettv->vval.v_number = -1;
14547 #endif
14550 static void
14551 f_remote_read(argvars, rettv)
14552 typval_T *argvars UNUSED;
14553 typval_T *rettv;
14555 char_u *r = NULL;
14557 #ifdef FEAT_CLIENTSERVER
14558 char_u *serverid = get_tv_string_chk(&argvars[0]);
14560 if (serverid != NULL && !check_restricted() && !check_secure())
14562 # ifdef WIN32
14563 /* The server's HWND is encoded in the 'id' parameter */
14564 long_u n = 0;
14566 sscanf(serverid, SCANF_HEX_LONG_U, &n);
14567 if (n != 0)
14568 r = serverGetReply((HWND)n, FALSE, TRUE, TRUE);
14569 if (r == NULL)
14570 # else
14571 if (check_connection() == FAIL || serverReadReply(X_DISPLAY,
14572 serverStrToWin(serverid), &r, FALSE) < 0)
14573 # endif
14574 EMSG(_("E277: Unable to read a server reply"));
14576 #endif
14577 rettv->v_type = VAR_STRING;
14578 rettv->vval.v_string = r;
14582 * "remote_send()" function
14584 static void
14585 f_remote_send(argvars, rettv)
14586 typval_T *argvars UNUSED;
14587 typval_T *rettv;
14589 rettv->v_type = VAR_STRING;
14590 rettv->vval.v_string = NULL;
14591 #ifdef FEAT_CLIENTSERVER
14592 remote_common(argvars, rettv, FALSE);
14593 #endif
14597 * "remove()" function
14599 static void
14600 f_remove(argvars, rettv)
14601 typval_T *argvars;
14602 typval_T *rettv;
14604 list_T *l;
14605 listitem_T *item, *item2;
14606 listitem_T *li;
14607 long idx;
14608 long end;
14609 char_u *key;
14610 dict_T *d;
14611 dictitem_T *di;
14613 if (argvars[0].v_type == VAR_DICT)
14615 if (argvars[2].v_type != VAR_UNKNOWN)
14616 EMSG2(_(e_toomanyarg), "remove()");
14617 else if ((d = argvars[0].vval.v_dict) != NULL
14618 && !tv_check_lock(d->dv_lock, (char_u *)"remove() argument"))
14620 key = get_tv_string_chk(&argvars[1]);
14621 if (key != NULL)
14623 di = dict_find(d, key, -1);
14624 if (di == NULL)
14625 EMSG2(_(e_dictkey), key);
14626 else
14628 *rettv = di->di_tv;
14629 init_tv(&di->di_tv);
14630 dictitem_remove(d, di);
14635 else if (argvars[0].v_type != VAR_LIST)
14636 EMSG2(_(e_listdictarg), "remove()");
14637 else if ((l = argvars[0].vval.v_list) != NULL
14638 && !tv_check_lock(l->lv_lock, (char_u *)"remove() argument"))
14640 int error = FALSE;
14642 idx = get_tv_number_chk(&argvars[1], &error);
14643 if (error)
14644 ; /* type error: do nothing, errmsg already given */
14645 else if ((item = list_find(l, idx)) == NULL)
14646 EMSGN(_(e_listidx), idx);
14647 else
14649 if (argvars[2].v_type == VAR_UNKNOWN)
14651 /* Remove one item, return its value. */
14652 list_remove(l, item, item);
14653 *rettv = item->li_tv;
14654 vim_free(item);
14656 else
14658 /* Remove range of items, return list with values. */
14659 end = get_tv_number_chk(&argvars[2], &error);
14660 if (error)
14661 ; /* type error: do nothing */
14662 else if ((item2 = list_find(l, end)) == NULL)
14663 EMSGN(_(e_listidx), end);
14664 else
14666 int cnt = 0;
14668 for (li = item; li != NULL; li = li->li_next)
14670 ++cnt;
14671 if (li == item2)
14672 break;
14674 if (li == NULL) /* didn't find "item2" after "item" */
14675 EMSG(_(e_invrange));
14676 else
14678 list_remove(l, item, item2);
14679 if (rettv_list_alloc(rettv) == OK)
14681 l = rettv->vval.v_list;
14682 l->lv_first = item;
14683 l->lv_last = item2;
14684 item->li_prev = NULL;
14685 item2->li_next = NULL;
14686 l->lv_len = cnt;
14696 * "rename({from}, {to})" function
14698 static void
14699 f_rename(argvars, rettv)
14700 typval_T *argvars;
14701 typval_T *rettv;
14703 char_u buf[NUMBUFLEN];
14705 if (check_restricted() || check_secure())
14706 rettv->vval.v_number = -1;
14707 else
14708 rettv->vval.v_number = vim_rename(get_tv_string(&argvars[0]),
14709 get_tv_string_buf(&argvars[1], buf));
14713 * "repeat()" function
14715 static void
14716 f_repeat(argvars, rettv)
14717 typval_T *argvars;
14718 typval_T *rettv;
14720 char_u *p;
14721 int n;
14722 int slen;
14723 int len;
14724 char_u *r;
14725 int i;
14727 n = get_tv_number(&argvars[1]);
14728 if (argvars[0].v_type == VAR_LIST)
14730 if (rettv_list_alloc(rettv) == OK && argvars[0].vval.v_list != NULL)
14731 while (n-- > 0)
14732 if (list_extend(rettv->vval.v_list,
14733 argvars[0].vval.v_list, NULL) == FAIL)
14734 break;
14736 else
14738 p = get_tv_string(&argvars[0]);
14739 rettv->v_type = VAR_STRING;
14740 rettv->vval.v_string = NULL;
14742 slen = (int)STRLEN(p);
14743 len = slen * n;
14744 if (len <= 0)
14745 return;
14747 r = alloc(len + 1);
14748 if (r != NULL)
14750 for (i = 0; i < n; i++)
14751 mch_memmove(r + i * slen, p, (size_t)slen);
14752 r[len] = NUL;
14755 rettv->vval.v_string = r;
14760 * "resolve()" function
14762 static void
14763 f_resolve(argvars, rettv)
14764 typval_T *argvars;
14765 typval_T *rettv;
14767 char_u *p;
14769 p = get_tv_string(&argvars[0]);
14770 #ifdef FEAT_SHORTCUT
14772 char_u *v = NULL;
14774 v = mch_resolve_shortcut(p);
14775 if (v != NULL)
14776 rettv->vval.v_string = v;
14777 else
14778 rettv->vval.v_string = vim_strsave(p);
14780 #else
14781 # ifdef HAVE_READLINK
14783 char_u buf[MAXPATHL + 1];
14784 char_u *cpy;
14785 int len;
14786 char_u *remain = NULL;
14787 char_u *q;
14788 int is_relative_to_current = FALSE;
14789 int has_trailing_pathsep = FALSE;
14790 int limit = 100;
14792 p = vim_strsave(p);
14794 if (p[0] == '.' && (vim_ispathsep(p[1])
14795 || (p[1] == '.' && (vim_ispathsep(p[2])))))
14796 is_relative_to_current = TRUE;
14798 len = STRLEN(p);
14799 if (len > 0 && after_pathsep(p, p + len))
14800 has_trailing_pathsep = TRUE;
14802 q = getnextcomp(p);
14803 if (*q != NUL)
14805 /* Separate the first path component in "p", and keep the
14806 * remainder (beginning with the path separator). */
14807 remain = vim_strsave(q - 1);
14808 q[-1] = NUL;
14811 for (;;)
14813 for (;;)
14815 len = readlink((char *)p, (char *)buf, MAXPATHL);
14816 if (len <= 0)
14817 break;
14818 buf[len] = NUL;
14820 if (limit-- == 0)
14822 vim_free(p);
14823 vim_free(remain);
14824 EMSG(_("E655: Too many symbolic links (cycle?)"));
14825 rettv->vval.v_string = NULL;
14826 goto fail;
14829 /* Ensure that the result will have a trailing path separator
14830 * if the argument has one. */
14831 if (remain == NULL && has_trailing_pathsep)
14832 add_pathsep(buf);
14834 /* Separate the first path component in the link value and
14835 * concatenate the remainders. */
14836 q = getnextcomp(vim_ispathsep(*buf) ? buf + 1 : buf);
14837 if (*q != NUL)
14839 if (remain == NULL)
14840 remain = vim_strsave(q - 1);
14841 else
14843 cpy = concat_str(q - 1, remain);
14844 if (cpy != NULL)
14846 vim_free(remain);
14847 remain = cpy;
14850 q[-1] = NUL;
14853 q = gettail(p);
14854 if (q > p && *q == NUL)
14856 /* Ignore trailing path separator. */
14857 q[-1] = NUL;
14858 q = gettail(p);
14860 if (q > p && !mch_isFullName(buf))
14862 /* symlink is relative to directory of argument */
14863 cpy = alloc((unsigned)(STRLEN(p) + STRLEN(buf) + 1));
14864 if (cpy != NULL)
14866 STRCPY(cpy, p);
14867 STRCPY(gettail(cpy), buf);
14868 vim_free(p);
14869 p = cpy;
14872 else
14874 vim_free(p);
14875 p = vim_strsave(buf);
14879 if (remain == NULL)
14880 break;
14882 /* Append the first path component of "remain" to "p". */
14883 q = getnextcomp(remain + 1);
14884 len = q - remain - (*q != NUL);
14885 cpy = vim_strnsave(p, STRLEN(p) + len);
14886 if (cpy != NULL)
14888 STRNCAT(cpy, remain, len);
14889 vim_free(p);
14890 p = cpy;
14892 /* Shorten "remain". */
14893 if (*q != NUL)
14894 STRMOVE(remain, q - 1);
14895 else
14897 vim_free(remain);
14898 remain = NULL;
14902 /* If the result is a relative path name, make it explicitly relative to
14903 * the current directory if and only if the argument had this form. */
14904 if (!vim_ispathsep(*p))
14906 if (is_relative_to_current
14907 && *p != NUL
14908 && !(p[0] == '.'
14909 && (p[1] == NUL
14910 || vim_ispathsep(p[1])
14911 || (p[1] == '.'
14912 && (p[2] == NUL
14913 || vim_ispathsep(p[2]))))))
14915 /* Prepend "./". */
14916 cpy = concat_str((char_u *)"./", p);
14917 if (cpy != NULL)
14919 vim_free(p);
14920 p = cpy;
14923 else if (!is_relative_to_current)
14925 /* Strip leading "./". */
14926 q = p;
14927 while (q[0] == '.' && vim_ispathsep(q[1]))
14928 q += 2;
14929 if (q > p)
14930 STRMOVE(p, p + 2);
14934 /* Ensure that the result will have no trailing path separator
14935 * if the argument had none. But keep "/" or "//". */
14936 if (!has_trailing_pathsep)
14938 q = p + STRLEN(p);
14939 if (after_pathsep(p, q))
14940 *gettail_sep(p) = NUL;
14943 rettv->vval.v_string = p;
14945 # else
14946 rettv->vval.v_string = vim_strsave(p);
14947 # endif
14948 #endif
14950 simplify_filename(rettv->vval.v_string);
14952 #ifdef HAVE_READLINK
14953 fail:
14954 #endif
14955 rettv->v_type = VAR_STRING;
14959 * "reverse({list})" function
14961 static void
14962 f_reverse(argvars, rettv)
14963 typval_T *argvars;
14964 typval_T *rettv;
14966 list_T *l;
14967 listitem_T *li, *ni;
14969 if (argvars[0].v_type != VAR_LIST)
14970 EMSG2(_(e_listarg), "reverse()");
14971 else if ((l = argvars[0].vval.v_list) != NULL
14972 && !tv_check_lock(l->lv_lock, (char_u *)"reverse()"))
14974 li = l->lv_last;
14975 l->lv_first = l->lv_last = NULL;
14976 l->lv_len = 0;
14977 while (li != NULL)
14979 ni = li->li_prev;
14980 list_append(l, li);
14981 li = ni;
14983 rettv->vval.v_list = l;
14984 rettv->v_type = VAR_LIST;
14985 ++l->lv_refcount;
14986 l->lv_idx = l->lv_len - l->lv_idx - 1;
14990 #define SP_NOMOVE 0x01 /* don't move cursor */
14991 #define SP_REPEAT 0x02 /* repeat to find outer pair */
14992 #define SP_RETCOUNT 0x04 /* return matchcount */
14993 #define SP_SETPCMARK 0x08 /* set previous context mark */
14994 #define SP_START 0x10 /* accept match at start position */
14995 #define SP_SUBPAT 0x20 /* return nr of matching sub-pattern */
14996 #define SP_END 0x40 /* leave cursor at end of match */
14998 static int get_search_arg __ARGS((typval_T *varp, int *flagsp));
15001 * Get flags for a search function.
15002 * Possibly sets "p_ws".
15003 * Returns BACKWARD, FORWARD or zero (for an error).
15005 static int
15006 get_search_arg(varp, flagsp)
15007 typval_T *varp;
15008 int *flagsp;
15010 int dir = FORWARD;
15011 char_u *flags;
15012 char_u nbuf[NUMBUFLEN];
15013 int mask;
15015 if (varp->v_type != VAR_UNKNOWN)
15017 flags = get_tv_string_buf_chk(varp, nbuf);
15018 if (flags == NULL)
15019 return 0; /* type error; errmsg already given */
15020 while (*flags != NUL)
15022 switch (*flags)
15024 case 'b': dir = BACKWARD; break;
15025 case 'w': p_ws = TRUE; break;
15026 case 'W': p_ws = FALSE; break;
15027 default: mask = 0;
15028 if (flagsp != NULL)
15029 switch (*flags)
15031 case 'c': mask = SP_START; break;
15032 case 'e': mask = SP_END; break;
15033 case 'm': mask = SP_RETCOUNT; break;
15034 case 'n': mask = SP_NOMOVE; break;
15035 case 'p': mask = SP_SUBPAT; break;
15036 case 'r': mask = SP_REPEAT; break;
15037 case 's': mask = SP_SETPCMARK; break;
15039 if (mask == 0)
15041 EMSG2(_(e_invarg2), flags);
15042 dir = 0;
15044 else
15045 *flagsp |= mask;
15047 if (dir == 0)
15048 break;
15049 ++flags;
15052 return dir;
15056 * Shared by search() and searchpos() functions
15058 static int
15059 search_cmn(argvars, match_pos, flagsp)
15060 typval_T *argvars;
15061 pos_T *match_pos;
15062 int *flagsp;
15064 int flags;
15065 char_u *pat;
15066 pos_T pos;
15067 pos_T save_cursor;
15068 int save_p_ws = p_ws;
15069 int dir;
15070 int retval = 0; /* default: FAIL */
15071 long lnum_stop = 0;
15072 proftime_T tm;
15073 #ifdef FEAT_RELTIME
15074 long time_limit = 0;
15075 #endif
15076 int options = SEARCH_KEEP;
15077 int subpatnum;
15079 pat = get_tv_string(&argvars[0]);
15080 dir = get_search_arg(&argvars[1], flagsp); /* may set p_ws */
15081 if (dir == 0)
15082 goto theend;
15083 flags = *flagsp;
15084 if (flags & SP_START)
15085 options |= SEARCH_START;
15086 if (flags & SP_END)
15087 options |= SEARCH_END;
15089 /* Optional arguments: line number to stop searching and timeout. */
15090 if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN)
15092 lnum_stop = get_tv_number_chk(&argvars[2], NULL);
15093 if (lnum_stop < 0)
15094 goto theend;
15095 #ifdef FEAT_RELTIME
15096 if (argvars[3].v_type != VAR_UNKNOWN)
15098 time_limit = get_tv_number_chk(&argvars[3], NULL);
15099 if (time_limit < 0)
15100 goto theend;
15102 #endif
15105 #ifdef FEAT_RELTIME
15106 /* Set the time limit, if there is one. */
15107 profile_setlimit(time_limit, &tm);
15108 #endif
15111 * This function does not accept SP_REPEAT and SP_RETCOUNT flags.
15112 * Check to make sure only those flags are set.
15113 * Also, Only the SP_NOMOVE or the SP_SETPCMARK flag can be set. Both
15114 * flags cannot be set. Check for that condition also.
15116 if (((flags & (SP_REPEAT | SP_RETCOUNT)) != 0)
15117 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
15119 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
15120 goto theend;
15123 pos = save_cursor = curwin->w_cursor;
15124 subpatnum = searchit(curwin, curbuf, &pos, dir, pat, 1L,
15125 options, RE_SEARCH, (linenr_T)lnum_stop, &tm);
15126 if (subpatnum != FAIL)
15128 if (flags & SP_SUBPAT)
15129 retval = subpatnum;
15130 else
15131 retval = pos.lnum;
15132 if (flags & SP_SETPCMARK)
15133 setpcmark();
15134 curwin->w_cursor = pos;
15135 if (match_pos != NULL)
15137 /* Store the match cursor position */
15138 match_pos->lnum = pos.lnum;
15139 match_pos->col = pos.col + 1;
15141 /* "/$" will put the cursor after the end of the line, may need to
15142 * correct that here */
15143 check_cursor();
15146 /* If 'n' flag is used: restore cursor position. */
15147 if (flags & SP_NOMOVE)
15148 curwin->w_cursor = save_cursor;
15149 else
15150 curwin->w_set_curswant = TRUE;
15151 theend:
15152 p_ws = save_p_ws;
15154 return retval;
15157 #ifdef FEAT_FLOAT
15159 * "round({float})" function
15161 static void
15162 f_round(argvars, rettv)
15163 typval_T *argvars;
15164 typval_T *rettv;
15166 float_T f;
15168 rettv->v_type = VAR_FLOAT;
15169 if (get_float_arg(argvars, &f) == OK)
15170 /* round() is not in C90, use ceil() or floor() instead. */
15171 rettv->vval.v_float = f > 0 ? floor(f + 0.5) : ceil(f - 0.5);
15172 else
15173 rettv->vval.v_float = 0.0;
15175 #endif
15178 * "search()" function
15180 static void
15181 f_search(argvars, rettv)
15182 typval_T *argvars;
15183 typval_T *rettv;
15185 int flags = 0;
15187 rettv->vval.v_number = search_cmn(argvars, NULL, &flags);
15191 * "searchdecl()" function
15193 static void
15194 f_searchdecl(argvars, rettv)
15195 typval_T *argvars;
15196 typval_T *rettv;
15198 int locally = 1;
15199 int thisblock = 0;
15200 int error = FALSE;
15201 char_u *name;
15203 rettv->vval.v_number = 1; /* default: FAIL */
15205 name = get_tv_string_chk(&argvars[0]);
15206 if (argvars[1].v_type != VAR_UNKNOWN)
15208 locally = get_tv_number_chk(&argvars[1], &error) == 0;
15209 if (!error && argvars[2].v_type != VAR_UNKNOWN)
15210 thisblock = get_tv_number_chk(&argvars[2], &error) != 0;
15212 if (!error && name != NULL)
15213 rettv->vval.v_number = find_decl(name, (int)STRLEN(name),
15214 locally, thisblock, SEARCH_KEEP) == FAIL;
15218 * Used by searchpair() and searchpairpos()
15220 static int
15221 searchpair_cmn(argvars, match_pos)
15222 typval_T *argvars;
15223 pos_T *match_pos;
15225 char_u *spat, *mpat, *epat;
15226 char_u *skip;
15227 int save_p_ws = p_ws;
15228 int dir;
15229 int flags = 0;
15230 char_u nbuf1[NUMBUFLEN];
15231 char_u nbuf2[NUMBUFLEN];
15232 char_u nbuf3[NUMBUFLEN];
15233 int retval = 0; /* default: FAIL */
15234 long lnum_stop = 0;
15235 long time_limit = 0;
15237 /* Get the three pattern arguments: start, middle, end. */
15238 spat = get_tv_string_chk(&argvars[0]);
15239 mpat = get_tv_string_buf_chk(&argvars[1], nbuf1);
15240 epat = get_tv_string_buf_chk(&argvars[2], nbuf2);
15241 if (spat == NULL || mpat == NULL || epat == NULL)
15242 goto theend; /* type error */
15244 /* Handle the optional fourth argument: flags */
15245 dir = get_search_arg(&argvars[3], &flags); /* may set p_ws */
15246 if (dir == 0)
15247 goto theend;
15249 /* Don't accept SP_END or SP_SUBPAT.
15250 * Only one of the SP_NOMOVE or SP_SETPCMARK flags can be set.
15252 if ((flags & (SP_END | SP_SUBPAT)) != 0
15253 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
15255 EMSG2(_(e_invarg2), get_tv_string(&argvars[3]));
15256 goto theend;
15259 /* Using 'r' implies 'W', otherwise it doesn't work. */
15260 if (flags & SP_REPEAT)
15261 p_ws = FALSE;
15263 /* Optional fifth argument: skip expression */
15264 if (argvars[3].v_type == VAR_UNKNOWN
15265 || argvars[4].v_type == VAR_UNKNOWN)
15266 skip = (char_u *)"";
15267 else
15269 skip = get_tv_string_buf_chk(&argvars[4], nbuf3);
15270 if (argvars[5].v_type != VAR_UNKNOWN)
15272 lnum_stop = get_tv_number_chk(&argvars[5], NULL);
15273 if (lnum_stop < 0)
15274 goto theend;
15275 #ifdef FEAT_RELTIME
15276 if (argvars[6].v_type != VAR_UNKNOWN)
15278 time_limit = get_tv_number_chk(&argvars[6], NULL);
15279 if (time_limit < 0)
15280 goto theend;
15282 #endif
15285 if (skip == NULL)
15286 goto theend; /* type error */
15288 retval = do_searchpair(spat, mpat, epat, dir, skip, flags,
15289 match_pos, lnum_stop, time_limit);
15291 theend:
15292 p_ws = save_p_ws;
15294 return retval;
15298 * "searchpair()" function
15300 static void
15301 f_searchpair(argvars, rettv)
15302 typval_T *argvars;
15303 typval_T *rettv;
15305 rettv->vval.v_number = searchpair_cmn(argvars, NULL);
15309 * "searchpairpos()" function
15311 static void
15312 f_searchpairpos(argvars, rettv)
15313 typval_T *argvars;
15314 typval_T *rettv;
15316 pos_T match_pos;
15317 int lnum = 0;
15318 int col = 0;
15320 if (rettv_list_alloc(rettv) == FAIL)
15321 return;
15323 if (searchpair_cmn(argvars, &match_pos) > 0)
15325 lnum = match_pos.lnum;
15326 col = match_pos.col;
15329 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
15330 list_append_number(rettv->vval.v_list, (varnumber_T)col);
15334 * Search for a start/middle/end thing.
15335 * Used by searchpair(), see its documentation for the details.
15336 * Returns 0 or -1 for no match,
15338 long
15339 do_searchpair(spat, mpat, epat, dir, skip, flags, match_pos,
15340 lnum_stop, time_limit)
15341 char_u *spat; /* start pattern */
15342 char_u *mpat; /* middle pattern */
15343 char_u *epat; /* end pattern */
15344 int dir; /* BACKWARD or FORWARD */
15345 char_u *skip; /* skip expression */
15346 int flags; /* SP_SETPCMARK and other SP_ values */
15347 pos_T *match_pos;
15348 linenr_T lnum_stop; /* stop at this line if not zero */
15349 long time_limit; /* stop after this many msec */
15351 char_u *save_cpo;
15352 char_u *pat, *pat2 = NULL, *pat3 = NULL;
15353 long retval = 0;
15354 pos_T pos;
15355 pos_T firstpos;
15356 pos_T foundpos;
15357 pos_T save_cursor;
15358 pos_T save_pos;
15359 int n;
15360 int r;
15361 int nest = 1;
15362 int err;
15363 int options = SEARCH_KEEP;
15364 proftime_T tm;
15366 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
15367 save_cpo = p_cpo;
15368 p_cpo = empty_option;
15370 #ifdef FEAT_RELTIME
15371 /* Set the time limit, if there is one. */
15372 profile_setlimit(time_limit, &tm);
15373 #endif
15375 /* Make two search patterns: start/end (pat2, for in nested pairs) and
15376 * start/middle/end (pat3, for the top pair). */
15377 pat2 = alloc((unsigned)(STRLEN(spat) + STRLEN(epat) + 15));
15378 pat3 = alloc((unsigned)(STRLEN(spat) + STRLEN(mpat) + STRLEN(epat) + 23));
15379 if (pat2 == NULL || pat3 == NULL)
15380 goto theend;
15381 sprintf((char *)pat2, "\\(%s\\m\\)\\|\\(%s\\m\\)", spat, epat);
15382 if (*mpat == NUL)
15383 STRCPY(pat3, pat2);
15384 else
15385 sprintf((char *)pat3, "\\(%s\\m\\)\\|\\(%s\\m\\)\\|\\(%s\\m\\)",
15386 spat, epat, mpat);
15387 if (flags & SP_START)
15388 options |= SEARCH_START;
15390 save_cursor = curwin->w_cursor;
15391 pos = curwin->w_cursor;
15392 clearpos(&firstpos);
15393 clearpos(&foundpos);
15394 pat = pat3;
15395 for (;;)
15397 n = searchit(curwin, curbuf, &pos, dir, pat, 1L,
15398 options, RE_SEARCH, lnum_stop, &tm);
15399 if (n == FAIL || (firstpos.lnum != 0 && equalpos(pos, firstpos)))
15400 /* didn't find it or found the first match again: FAIL */
15401 break;
15403 if (firstpos.lnum == 0)
15404 firstpos = pos;
15405 if (equalpos(pos, foundpos))
15407 /* Found the same position again. Can happen with a pattern that
15408 * has "\zs" at the end and searching backwards. Advance one
15409 * character and try again. */
15410 if (dir == BACKWARD)
15411 decl(&pos);
15412 else
15413 incl(&pos);
15415 foundpos = pos;
15417 /* clear the start flag to avoid getting stuck here */
15418 options &= ~SEARCH_START;
15420 /* If the skip pattern matches, ignore this match. */
15421 if (*skip != NUL)
15423 save_pos = curwin->w_cursor;
15424 curwin->w_cursor = pos;
15425 r = eval_to_bool(skip, &err, NULL, FALSE);
15426 curwin->w_cursor = save_pos;
15427 if (err)
15429 /* Evaluating {skip} caused an error, break here. */
15430 curwin->w_cursor = save_cursor;
15431 retval = -1;
15432 break;
15434 if (r)
15435 continue;
15438 if ((dir == BACKWARD && n == 3) || (dir == FORWARD && n == 2))
15440 /* Found end when searching backwards or start when searching
15441 * forward: nested pair. */
15442 ++nest;
15443 pat = pat2; /* nested, don't search for middle */
15445 else
15447 /* Found end when searching forward or start when searching
15448 * backward: end of (nested) pair; or found middle in outer pair. */
15449 if (--nest == 1)
15450 pat = pat3; /* outer level, search for middle */
15453 if (nest == 0)
15455 /* Found the match: return matchcount or line number. */
15456 if (flags & SP_RETCOUNT)
15457 ++retval;
15458 else
15459 retval = pos.lnum;
15460 if (flags & SP_SETPCMARK)
15461 setpcmark();
15462 curwin->w_cursor = pos;
15463 if (!(flags & SP_REPEAT))
15464 break;
15465 nest = 1; /* search for next unmatched */
15469 if (match_pos != NULL)
15471 /* Store the match cursor position */
15472 match_pos->lnum = curwin->w_cursor.lnum;
15473 match_pos->col = curwin->w_cursor.col + 1;
15476 /* If 'n' flag is used or search failed: restore cursor position. */
15477 if ((flags & SP_NOMOVE) || retval == 0)
15478 curwin->w_cursor = save_cursor;
15480 theend:
15481 vim_free(pat2);
15482 vim_free(pat3);
15483 if (p_cpo == empty_option)
15484 p_cpo = save_cpo;
15485 else
15486 /* Darn, evaluating the {skip} expression changed the value. */
15487 free_string_option(save_cpo);
15489 return retval;
15493 * "searchpos()" function
15495 static void
15496 f_searchpos(argvars, rettv)
15497 typval_T *argvars;
15498 typval_T *rettv;
15500 pos_T match_pos;
15501 int lnum = 0;
15502 int col = 0;
15503 int n;
15504 int flags = 0;
15506 if (rettv_list_alloc(rettv) == FAIL)
15507 return;
15509 n = search_cmn(argvars, &match_pos, &flags);
15510 if (n > 0)
15512 lnum = match_pos.lnum;
15513 col = match_pos.col;
15516 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
15517 list_append_number(rettv->vval.v_list, (varnumber_T)col);
15518 if (flags & SP_SUBPAT)
15519 list_append_number(rettv->vval.v_list, (varnumber_T)n);
15523 static void
15524 f_server2client(argvars, rettv)
15525 typval_T *argvars UNUSED;
15526 typval_T *rettv;
15528 #ifdef FEAT_CLIENTSERVER
15529 char_u buf[NUMBUFLEN];
15530 char_u *server = get_tv_string_chk(&argvars[0]);
15531 char_u *reply = get_tv_string_buf_chk(&argvars[1], buf);
15533 rettv->vval.v_number = -1;
15534 if (server == NULL || reply == NULL)
15535 return;
15536 if (check_restricted() || check_secure())
15537 return;
15538 # ifdef FEAT_X11
15539 if (check_connection() == FAIL)
15540 return;
15541 # endif
15543 if (serverSendReply(server, reply) < 0)
15545 EMSG(_("E258: Unable to send to client"));
15546 return;
15548 rettv->vval.v_number = 0;
15549 #else
15550 rettv->vval.v_number = -1;
15551 #endif
15554 static void
15555 f_serverlist(argvars, rettv)
15556 typval_T *argvars UNUSED;
15557 typval_T *rettv;
15559 char_u *r = NULL;
15561 #ifdef FEAT_CLIENTSERVER
15562 # ifdef WIN32
15563 r = serverGetVimNames();
15564 # else
15565 make_connection();
15566 if (X_DISPLAY != NULL)
15567 r = serverGetVimNames(X_DISPLAY);
15568 # endif
15569 #endif
15570 rettv->v_type = VAR_STRING;
15571 rettv->vval.v_string = r;
15575 * "setbufvar()" function
15577 static void
15578 f_setbufvar(argvars, rettv)
15579 typval_T *argvars;
15580 typval_T *rettv UNUSED;
15582 buf_T *buf;
15583 aco_save_T aco;
15584 char_u *varname, *bufvarname;
15585 typval_T *varp;
15586 char_u nbuf[NUMBUFLEN];
15588 if (check_restricted() || check_secure())
15589 return;
15590 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
15591 varname = get_tv_string_chk(&argvars[1]);
15592 buf = get_buf_tv(&argvars[0]);
15593 varp = &argvars[2];
15595 if (buf != NULL && varname != NULL && varp != NULL)
15597 /* set curbuf to be our buf, temporarily */
15598 aucmd_prepbuf(&aco, buf);
15600 if (*varname == '&')
15602 long numval;
15603 char_u *strval;
15604 int error = FALSE;
15606 ++varname;
15607 numval = get_tv_number_chk(varp, &error);
15608 strval = get_tv_string_buf_chk(varp, nbuf);
15609 if (!error && strval != NULL)
15610 set_option_value(varname, numval, strval, OPT_LOCAL);
15612 else
15614 bufvarname = alloc((unsigned)STRLEN(varname) + 3);
15615 if (bufvarname != NULL)
15617 STRCPY(bufvarname, "b:");
15618 STRCPY(bufvarname + 2, varname);
15619 set_var(bufvarname, varp, TRUE);
15620 vim_free(bufvarname);
15624 /* reset notion of buffer */
15625 aucmd_restbuf(&aco);
15630 * "setcmdpos()" function
15632 static void
15633 f_setcmdpos(argvars, rettv)
15634 typval_T *argvars;
15635 typval_T *rettv;
15637 int pos = (int)get_tv_number(&argvars[0]) - 1;
15639 if (pos >= 0)
15640 rettv->vval.v_number = set_cmdline_pos(pos);
15644 * "setline()" function
15646 static void
15647 f_setline(argvars, rettv)
15648 typval_T *argvars;
15649 typval_T *rettv;
15651 linenr_T lnum;
15652 char_u *line = NULL;
15653 list_T *l = NULL;
15654 listitem_T *li = NULL;
15655 long added = 0;
15656 linenr_T lcount = curbuf->b_ml.ml_line_count;
15658 lnum = get_tv_lnum(&argvars[0]);
15659 if (argvars[1].v_type == VAR_LIST)
15661 l = argvars[1].vval.v_list;
15662 li = l->lv_first;
15664 else
15665 line = get_tv_string_chk(&argvars[1]);
15667 /* default result is zero == OK */
15668 for (;;)
15670 if (l != NULL)
15672 /* list argument, get next string */
15673 if (li == NULL)
15674 break;
15675 line = get_tv_string_chk(&li->li_tv);
15676 li = li->li_next;
15679 rettv->vval.v_number = 1; /* FAIL */
15680 if (line == NULL || lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
15681 break;
15682 if (lnum <= curbuf->b_ml.ml_line_count)
15684 /* existing line, replace it */
15685 if (u_savesub(lnum) == OK && ml_replace(lnum, line, TRUE) == OK)
15687 changed_bytes(lnum, 0);
15688 if (lnum == curwin->w_cursor.lnum)
15689 check_cursor_col();
15690 rettv->vval.v_number = 0; /* OK */
15693 else if (added > 0 || u_save(lnum - 1, lnum) == OK)
15695 /* lnum is one past the last line, append the line */
15696 ++added;
15697 if (ml_append(lnum - 1, line, (colnr_T)0, FALSE) == OK)
15698 rettv->vval.v_number = 0; /* OK */
15701 if (l == NULL) /* only one string argument */
15702 break;
15703 ++lnum;
15706 if (added > 0)
15707 appended_lines_mark(lcount, added);
15710 static void set_qf_ll_list __ARGS((win_T *wp, typval_T *list_arg, typval_T *action_arg, typval_T *rettv));
15713 * Used by "setqflist()" and "setloclist()" functions
15715 static void
15716 set_qf_ll_list(wp, list_arg, action_arg, rettv)
15717 win_T *wp UNUSED;
15718 typval_T *list_arg UNUSED;
15719 typval_T *action_arg UNUSED;
15720 typval_T *rettv;
15722 #ifdef FEAT_QUICKFIX
15723 char_u *act;
15724 int action = ' ';
15725 #endif
15727 rettv->vval.v_number = -1;
15729 #ifdef FEAT_QUICKFIX
15730 if (list_arg->v_type != VAR_LIST)
15731 EMSG(_(e_listreq));
15732 else
15734 list_T *l = list_arg->vval.v_list;
15736 if (action_arg->v_type == VAR_STRING)
15738 act = get_tv_string_chk(action_arg);
15739 if (act == NULL)
15740 return; /* type error; errmsg already given */
15741 if (*act == 'a' || *act == 'r')
15742 action = *act;
15745 if (l != NULL && set_errorlist(wp, l, action) == OK)
15746 rettv->vval.v_number = 0;
15748 #endif
15752 * "setloclist()" function
15754 static void
15755 f_setloclist(argvars, rettv)
15756 typval_T *argvars;
15757 typval_T *rettv;
15759 win_T *win;
15761 rettv->vval.v_number = -1;
15763 win = find_win_by_nr(&argvars[0], NULL);
15764 if (win != NULL)
15765 set_qf_ll_list(win, &argvars[1], &argvars[2], rettv);
15769 * "setmatches()" function
15771 static void
15772 f_setmatches(argvars, rettv)
15773 typval_T *argvars;
15774 typval_T *rettv;
15776 #ifdef FEAT_SEARCH_EXTRA
15777 list_T *l;
15778 listitem_T *li;
15779 dict_T *d;
15781 rettv->vval.v_number = -1;
15782 if (argvars[0].v_type != VAR_LIST)
15784 EMSG(_(e_listreq));
15785 return;
15787 if ((l = argvars[0].vval.v_list) != NULL)
15790 /* To some extent make sure that we are dealing with a list from
15791 * "getmatches()". */
15792 li = l->lv_first;
15793 while (li != NULL)
15795 if (li->li_tv.v_type != VAR_DICT
15796 || (d = li->li_tv.vval.v_dict) == NULL)
15798 EMSG(_(e_invarg));
15799 return;
15801 if (!(dict_find(d, (char_u *)"group", -1) != NULL
15802 && dict_find(d, (char_u *)"pattern", -1) != NULL
15803 && dict_find(d, (char_u *)"priority", -1) != NULL
15804 && dict_find(d, (char_u *)"id", -1) != NULL))
15806 EMSG(_(e_invarg));
15807 return;
15809 li = li->li_next;
15812 clear_matches(curwin);
15813 li = l->lv_first;
15814 while (li != NULL)
15816 d = li->li_tv.vval.v_dict;
15817 match_add(curwin, get_dict_string(d, (char_u *)"group", FALSE),
15818 get_dict_string(d, (char_u *)"pattern", FALSE),
15819 (int)get_dict_number(d, (char_u *)"priority"),
15820 (int)get_dict_number(d, (char_u *)"id"));
15821 li = li->li_next;
15823 rettv->vval.v_number = 0;
15825 #endif
15829 * "setpos()" function
15831 static void
15832 f_setpos(argvars, rettv)
15833 typval_T *argvars;
15834 typval_T *rettv;
15836 pos_T pos;
15837 int fnum;
15838 char_u *name;
15840 rettv->vval.v_number = -1;
15841 name = get_tv_string_chk(argvars);
15842 if (name != NULL)
15844 if (list2fpos(&argvars[1], &pos, &fnum) == OK)
15846 if (--pos.col < 0)
15847 pos.col = 0;
15848 if (name[0] == '.' && name[1] == NUL)
15850 /* set cursor */
15851 if (fnum == curbuf->b_fnum)
15853 curwin->w_cursor = pos;
15854 check_cursor();
15855 rettv->vval.v_number = 0;
15857 else
15858 EMSG(_(e_invarg));
15860 else if (name[0] == '\'' && name[1] != NUL && name[2] == NUL)
15862 /* set mark */
15863 if (setmark_pos(name[1], &pos, fnum) == OK)
15864 rettv->vval.v_number = 0;
15866 else
15867 EMSG(_(e_invarg));
15873 * "setqflist()" function
15875 static void
15876 f_setqflist(argvars, rettv)
15877 typval_T *argvars;
15878 typval_T *rettv;
15880 set_qf_ll_list(NULL, &argvars[0], &argvars[1], rettv);
15884 * "setreg()" function
15886 static void
15887 f_setreg(argvars, rettv)
15888 typval_T *argvars;
15889 typval_T *rettv;
15891 int regname;
15892 char_u *strregname;
15893 char_u *stropt;
15894 char_u *strval;
15895 int append;
15896 char_u yank_type;
15897 long block_len;
15899 block_len = -1;
15900 yank_type = MAUTO;
15901 append = FALSE;
15903 strregname = get_tv_string_chk(argvars);
15904 rettv->vval.v_number = 1; /* FAIL is default */
15906 if (strregname == NULL)
15907 return; /* type error; errmsg already given */
15908 regname = *strregname;
15909 if (regname == 0 || regname == '@')
15910 regname = '"';
15911 else if (regname == '=')
15912 return;
15914 if (argvars[2].v_type != VAR_UNKNOWN)
15916 stropt = get_tv_string_chk(&argvars[2]);
15917 if (stropt == NULL)
15918 return; /* type error */
15919 for (; *stropt != NUL; ++stropt)
15920 switch (*stropt)
15922 case 'a': case 'A': /* append */
15923 append = TRUE;
15924 break;
15925 case 'v': case 'c': /* character-wise selection */
15926 yank_type = MCHAR;
15927 break;
15928 case 'V': case 'l': /* line-wise selection */
15929 yank_type = MLINE;
15930 break;
15931 #ifdef FEAT_VISUAL
15932 case 'b': case Ctrl_V: /* block-wise selection */
15933 yank_type = MBLOCK;
15934 if (VIM_ISDIGIT(stropt[1]))
15936 ++stropt;
15937 block_len = getdigits(&stropt) - 1;
15938 --stropt;
15940 break;
15941 #endif
15945 strval = get_tv_string_chk(&argvars[1]);
15946 if (strval != NULL)
15947 write_reg_contents_ex(regname, strval, -1,
15948 append, yank_type, block_len);
15949 rettv->vval.v_number = 0;
15953 * "settabwinvar()" function
15955 static void
15956 f_settabwinvar(argvars, rettv)
15957 typval_T *argvars;
15958 typval_T *rettv;
15960 setwinvar(argvars, rettv, 1);
15964 * "setwinvar()" function
15966 static void
15967 f_setwinvar(argvars, rettv)
15968 typval_T *argvars;
15969 typval_T *rettv;
15971 setwinvar(argvars, rettv, 0);
15975 * "setwinvar()" and "settabwinvar()" functions
15977 static void
15978 setwinvar(argvars, rettv, off)
15979 typval_T *argvars;
15980 typval_T *rettv UNUSED;
15981 int off;
15983 win_T *win;
15984 #ifdef FEAT_WINDOWS
15985 win_T *save_curwin;
15986 tabpage_T *save_curtab;
15987 #endif
15988 char_u *varname, *winvarname;
15989 typval_T *varp;
15990 char_u nbuf[NUMBUFLEN];
15991 tabpage_T *tp;
15993 if (check_restricted() || check_secure())
15994 return;
15996 #ifdef FEAT_WINDOWS
15997 if (off == 1)
15998 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
15999 else
16000 tp = curtab;
16001 #endif
16002 win = find_win_by_nr(&argvars[off], tp);
16003 varname = get_tv_string_chk(&argvars[off + 1]);
16004 varp = &argvars[off + 2];
16006 if (win != NULL && varname != NULL && varp != NULL)
16008 #ifdef FEAT_WINDOWS
16009 /* set curwin to be our win, temporarily */
16010 save_curwin = curwin;
16011 save_curtab = curtab;
16012 goto_tabpage_tp(tp);
16013 if (!win_valid(win))
16014 return;
16015 curwin = win;
16016 curbuf = curwin->w_buffer;
16017 #endif
16019 if (*varname == '&')
16021 long numval;
16022 char_u *strval;
16023 int error = FALSE;
16025 ++varname;
16026 numval = get_tv_number_chk(varp, &error);
16027 strval = get_tv_string_buf_chk(varp, nbuf);
16028 if (!error && strval != NULL)
16029 set_option_value(varname, numval, strval, OPT_LOCAL);
16031 else
16033 winvarname = alloc((unsigned)STRLEN(varname) + 3);
16034 if (winvarname != NULL)
16036 STRCPY(winvarname, "w:");
16037 STRCPY(winvarname + 2, varname);
16038 set_var(winvarname, varp, TRUE);
16039 vim_free(winvarname);
16043 #ifdef FEAT_WINDOWS
16044 /* Restore current tabpage and window, if still valid (autocomands can
16045 * make them invalid). */
16046 if (valid_tabpage(save_curtab))
16047 goto_tabpage_tp(save_curtab);
16048 if (win_valid(save_curwin))
16050 curwin = save_curwin;
16051 curbuf = curwin->w_buffer;
16053 #endif
16058 * "shellescape({string})" function
16060 static void
16061 f_shellescape(argvars, rettv)
16062 typval_T *argvars;
16063 typval_T *rettv;
16065 rettv->vval.v_string = vim_strsave_shellescape(
16066 get_tv_string(&argvars[0]), non_zero_arg(&argvars[1]));
16067 rettv->v_type = VAR_STRING;
16071 * "simplify()" function
16073 static void
16074 f_simplify(argvars, rettv)
16075 typval_T *argvars;
16076 typval_T *rettv;
16078 char_u *p;
16080 p = get_tv_string(&argvars[0]);
16081 rettv->vval.v_string = vim_strsave(p);
16082 simplify_filename(rettv->vval.v_string); /* simplify in place */
16083 rettv->v_type = VAR_STRING;
16086 #ifdef FEAT_FLOAT
16088 * "sin()" function
16090 static void
16091 f_sin(argvars, rettv)
16092 typval_T *argvars;
16093 typval_T *rettv;
16095 float_T f;
16097 rettv->v_type = VAR_FLOAT;
16098 if (get_float_arg(argvars, &f) == OK)
16099 rettv->vval.v_float = sin(f);
16100 else
16101 rettv->vval.v_float = 0.0;
16103 #endif
16105 static int
16106 #ifdef __BORLANDC__
16107 _RTLENTRYF
16108 #endif
16109 item_compare __ARGS((const void *s1, const void *s2));
16110 static int
16111 #ifdef __BORLANDC__
16112 _RTLENTRYF
16113 #endif
16114 item_compare2 __ARGS((const void *s1, const void *s2));
16116 static int item_compare_ic;
16117 static char_u *item_compare_func;
16118 static int item_compare_func_err;
16119 #define ITEM_COMPARE_FAIL 999
16122 * Compare functions for f_sort() below.
16124 static int
16125 #ifdef __BORLANDC__
16126 _RTLENTRYF
16127 #endif
16128 item_compare(s1, s2)
16129 const void *s1;
16130 const void *s2;
16132 char_u *p1, *p2;
16133 char_u *tofree1, *tofree2;
16134 int res;
16135 char_u numbuf1[NUMBUFLEN];
16136 char_u numbuf2[NUMBUFLEN];
16138 p1 = tv2string(&(*(listitem_T **)s1)->li_tv, &tofree1, numbuf1, 0);
16139 p2 = tv2string(&(*(listitem_T **)s2)->li_tv, &tofree2, numbuf2, 0);
16140 if (p1 == NULL)
16141 p1 = (char_u *)"";
16142 if (p2 == NULL)
16143 p2 = (char_u *)"";
16144 if (item_compare_ic)
16145 res = STRICMP(p1, p2);
16146 else
16147 res = STRCMP(p1, p2);
16148 vim_free(tofree1);
16149 vim_free(tofree2);
16150 return res;
16153 static int
16154 #ifdef __BORLANDC__
16155 _RTLENTRYF
16156 #endif
16157 item_compare2(s1, s2)
16158 const void *s1;
16159 const void *s2;
16161 int res;
16162 typval_T rettv;
16163 typval_T argv[3];
16164 int dummy;
16166 /* shortcut after failure in previous call; compare all items equal */
16167 if (item_compare_func_err)
16168 return 0;
16170 /* copy the values. This is needed to be able to set v_lock to VAR_FIXED
16171 * in the copy without changing the original list items. */
16172 copy_tv(&(*(listitem_T **)s1)->li_tv, &argv[0]);
16173 copy_tv(&(*(listitem_T **)s2)->li_tv, &argv[1]);
16175 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
16176 res = call_func(item_compare_func, (int)STRLEN(item_compare_func),
16177 &rettv, 2, argv, 0L, 0L, &dummy, TRUE, NULL);
16178 clear_tv(&argv[0]);
16179 clear_tv(&argv[1]);
16181 if (res == FAIL)
16182 res = ITEM_COMPARE_FAIL;
16183 else
16184 res = get_tv_number_chk(&rettv, &item_compare_func_err);
16185 if (item_compare_func_err)
16186 res = ITEM_COMPARE_FAIL; /* return value has wrong type */
16187 clear_tv(&rettv);
16188 return res;
16192 * "sort({list})" function
16194 static void
16195 f_sort(argvars, rettv)
16196 typval_T *argvars;
16197 typval_T *rettv;
16199 list_T *l;
16200 listitem_T *li;
16201 listitem_T **ptrs;
16202 long len;
16203 long i;
16205 if (argvars[0].v_type != VAR_LIST)
16206 EMSG2(_(e_listarg), "sort()");
16207 else
16209 l = argvars[0].vval.v_list;
16210 if (l == NULL || tv_check_lock(l->lv_lock, (char_u *)"sort()"))
16211 return;
16212 rettv->vval.v_list = l;
16213 rettv->v_type = VAR_LIST;
16214 ++l->lv_refcount;
16216 len = list_len(l);
16217 if (len <= 1)
16218 return; /* short list sorts pretty quickly */
16220 item_compare_ic = FALSE;
16221 item_compare_func = NULL;
16222 if (argvars[1].v_type != VAR_UNKNOWN)
16224 if (argvars[1].v_type == VAR_FUNC)
16225 item_compare_func = argvars[1].vval.v_string;
16226 else
16228 int error = FALSE;
16230 i = get_tv_number_chk(&argvars[1], &error);
16231 if (error)
16232 return; /* type error; errmsg already given */
16233 if (i == 1)
16234 item_compare_ic = TRUE;
16235 else
16236 item_compare_func = get_tv_string(&argvars[1]);
16240 /* Make an array with each entry pointing to an item in the List. */
16241 ptrs = (listitem_T **)alloc((int)(len * sizeof(listitem_T *)));
16242 if (ptrs == NULL)
16243 return;
16244 i = 0;
16245 for (li = l->lv_first; li != NULL; li = li->li_next)
16246 ptrs[i++] = li;
16248 item_compare_func_err = FALSE;
16249 /* test the compare function */
16250 if (item_compare_func != NULL
16251 && item_compare2((void *)&ptrs[0], (void *)&ptrs[1])
16252 == ITEM_COMPARE_FAIL)
16253 EMSG(_("E702: Sort compare function failed"));
16254 else
16256 /* Sort the array with item pointers. */
16257 qsort((void *)ptrs, (size_t)len, sizeof(listitem_T *),
16258 item_compare_func == NULL ? item_compare : item_compare2);
16260 if (!item_compare_func_err)
16262 /* Clear the List and append the items in the sorted order. */
16263 l->lv_first = l->lv_last = l->lv_idx_item = NULL;
16264 l->lv_len = 0;
16265 for (i = 0; i < len; ++i)
16266 list_append(l, ptrs[i]);
16270 vim_free(ptrs);
16275 * "soundfold({word})" function
16277 static void
16278 f_soundfold(argvars, rettv)
16279 typval_T *argvars;
16280 typval_T *rettv;
16282 char_u *s;
16284 rettv->v_type = VAR_STRING;
16285 s = get_tv_string(&argvars[0]);
16286 #ifdef FEAT_SPELL
16287 rettv->vval.v_string = eval_soundfold(s);
16288 #else
16289 rettv->vval.v_string = vim_strsave(s);
16290 #endif
16294 * "spellbadword()" function
16296 static void
16297 f_spellbadword(argvars, rettv)
16298 typval_T *argvars UNUSED;
16299 typval_T *rettv;
16301 char_u *word = (char_u *)"";
16302 hlf_T attr = HLF_COUNT;
16303 int len = 0;
16305 if (rettv_list_alloc(rettv) == FAIL)
16306 return;
16308 #ifdef FEAT_SPELL
16309 if (argvars[0].v_type == VAR_UNKNOWN)
16311 /* Find the start and length of the badly spelled word. */
16312 len = spell_move_to(curwin, FORWARD, TRUE, TRUE, &attr);
16313 if (len != 0)
16314 word = ml_get_cursor();
16316 else if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
16318 char_u *str = get_tv_string_chk(&argvars[0]);
16319 int capcol = -1;
16321 if (str != NULL)
16323 /* Check the argument for spelling. */
16324 while (*str != NUL)
16326 len = spell_check(curwin, str, &attr, &capcol, FALSE);
16327 if (attr != HLF_COUNT)
16329 word = str;
16330 break;
16332 str += len;
16336 #endif
16338 list_append_string(rettv->vval.v_list, word, len);
16339 list_append_string(rettv->vval.v_list, (char_u *)(
16340 attr == HLF_SPB ? "bad" :
16341 attr == HLF_SPR ? "rare" :
16342 attr == HLF_SPL ? "local" :
16343 attr == HLF_SPC ? "caps" :
16344 ""), -1);
16348 * "spellsuggest()" function
16350 static void
16351 f_spellsuggest(argvars, rettv)
16352 typval_T *argvars UNUSED;
16353 typval_T *rettv;
16355 #ifdef FEAT_SPELL
16356 char_u *str;
16357 int typeerr = FALSE;
16358 int maxcount;
16359 garray_T ga;
16360 int i;
16361 listitem_T *li;
16362 int need_capital = FALSE;
16363 #endif
16365 if (rettv_list_alloc(rettv) == FAIL)
16366 return;
16368 #ifdef FEAT_SPELL
16369 if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
16371 str = get_tv_string(&argvars[0]);
16372 if (argvars[1].v_type != VAR_UNKNOWN)
16374 maxcount = get_tv_number_chk(&argvars[1], &typeerr);
16375 if (maxcount <= 0)
16376 return;
16377 if (argvars[2].v_type != VAR_UNKNOWN)
16379 need_capital = get_tv_number_chk(&argvars[2], &typeerr);
16380 if (typeerr)
16381 return;
16384 else
16385 maxcount = 25;
16387 spell_suggest_list(&ga, str, maxcount, need_capital, FALSE);
16389 for (i = 0; i < ga.ga_len; ++i)
16391 str = ((char_u **)ga.ga_data)[i];
16393 li = listitem_alloc();
16394 if (li == NULL)
16395 vim_free(str);
16396 else
16398 li->li_tv.v_type = VAR_STRING;
16399 li->li_tv.v_lock = 0;
16400 li->li_tv.vval.v_string = str;
16401 list_append(rettv->vval.v_list, li);
16404 ga_clear(&ga);
16406 #endif
16409 static void
16410 f_split(argvars, rettv)
16411 typval_T *argvars;
16412 typval_T *rettv;
16414 char_u *str;
16415 char_u *end;
16416 char_u *pat = NULL;
16417 regmatch_T regmatch;
16418 char_u patbuf[NUMBUFLEN];
16419 char_u *save_cpo;
16420 int match;
16421 colnr_T col = 0;
16422 int keepempty = FALSE;
16423 int typeerr = FALSE;
16425 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
16426 save_cpo = p_cpo;
16427 p_cpo = (char_u *)"";
16429 str = get_tv_string(&argvars[0]);
16430 if (argvars[1].v_type != VAR_UNKNOWN)
16432 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
16433 if (pat == NULL)
16434 typeerr = TRUE;
16435 if (argvars[2].v_type != VAR_UNKNOWN)
16436 keepempty = get_tv_number_chk(&argvars[2], &typeerr);
16438 if (pat == NULL || *pat == NUL)
16439 pat = (char_u *)"[\\x01- ]\\+";
16441 if (rettv_list_alloc(rettv) == FAIL)
16442 return;
16443 if (typeerr)
16444 return;
16446 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
16447 if (regmatch.regprog != NULL)
16449 regmatch.rm_ic = FALSE;
16450 while (*str != NUL || keepempty)
16452 if (*str == NUL)
16453 match = FALSE; /* empty item at the end */
16454 else
16455 match = vim_regexec_nl(&regmatch, str, col);
16456 if (match)
16457 end = regmatch.startp[0];
16458 else
16459 end = str + STRLEN(str);
16460 if (keepempty || end > str || (rettv->vval.v_list->lv_len > 0
16461 && *str != NUL && match && end < regmatch.endp[0]))
16463 if (list_append_string(rettv->vval.v_list, str,
16464 (int)(end - str)) == FAIL)
16465 break;
16467 if (!match)
16468 break;
16469 /* Advance to just after the match. */
16470 if (regmatch.endp[0] > str)
16471 col = 0;
16472 else
16474 /* Don't get stuck at the same match. */
16475 #ifdef FEAT_MBYTE
16476 col = (*mb_ptr2len)(regmatch.endp[0]);
16477 #else
16478 col = 1;
16479 #endif
16481 str = regmatch.endp[0];
16484 vim_free(regmatch.regprog);
16487 p_cpo = save_cpo;
16490 #ifdef FEAT_FLOAT
16492 * "sqrt()" function
16494 static void
16495 f_sqrt(argvars, rettv)
16496 typval_T *argvars;
16497 typval_T *rettv;
16499 float_T f;
16501 rettv->v_type = VAR_FLOAT;
16502 if (get_float_arg(argvars, &f) == OK)
16503 rettv->vval.v_float = sqrt(f);
16504 else
16505 rettv->vval.v_float = 0.0;
16509 * "str2float()" function
16511 static void
16512 f_str2float(argvars, rettv)
16513 typval_T *argvars;
16514 typval_T *rettv;
16516 char_u *p = skipwhite(get_tv_string(&argvars[0]));
16518 if (*p == '+')
16519 p = skipwhite(p + 1);
16520 (void)string2float(p, &rettv->vval.v_float);
16521 rettv->v_type = VAR_FLOAT;
16523 #endif
16526 * "str2nr()" function
16528 static void
16529 f_str2nr(argvars, rettv)
16530 typval_T *argvars;
16531 typval_T *rettv;
16533 int base = 10;
16534 char_u *p;
16535 long n;
16537 if (argvars[1].v_type != VAR_UNKNOWN)
16539 base = get_tv_number(&argvars[1]);
16540 if (base != 8 && base != 10 && base != 16)
16542 EMSG(_(e_invarg));
16543 return;
16547 p = skipwhite(get_tv_string(&argvars[0]));
16548 if (*p == '+')
16549 p = skipwhite(p + 1);
16550 vim_str2nr(p, NULL, NULL, base == 8 ? 2 : 0, base == 16 ? 2 : 0, &n, NULL);
16551 rettv->vval.v_number = n;
16554 #ifdef HAVE_STRFTIME
16556 * "strftime({format}[, {time}])" function
16558 static void
16559 f_strftime(argvars, rettv)
16560 typval_T *argvars;
16561 typval_T *rettv;
16563 char_u result_buf[256];
16564 struct tm *curtime;
16565 time_t seconds;
16566 char_u *p;
16568 rettv->v_type = VAR_STRING;
16570 p = get_tv_string(&argvars[0]);
16571 if (argvars[1].v_type == VAR_UNKNOWN)
16572 seconds = time(NULL);
16573 else
16574 seconds = (time_t)get_tv_number(&argvars[1]);
16575 curtime = localtime(&seconds);
16576 /* MSVC returns NULL for an invalid value of seconds. */
16577 if (curtime == NULL)
16578 rettv->vval.v_string = vim_strsave((char_u *)_("(Invalid)"));
16579 else
16581 # ifdef FEAT_MBYTE
16582 vimconv_T conv;
16583 char_u *enc;
16585 conv.vc_type = CONV_NONE;
16586 enc = enc_locale();
16587 convert_setup(&conv, p_enc, enc);
16588 if (conv.vc_type != CONV_NONE)
16589 p = string_convert(&conv, p, NULL);
16590 # endif
16591 if (p != NULL)
16592 (void)strftime((char *)result_buf, sizeof(result_buf),
16593 (char *)p, curtime);
16594 else
16595 result_buf[0] = NUL;
16597 # ifdef FEAT_MBYTE
16598 if (conv.vc_type != CONV_NONE)
16599 vim_free(p);
16600 convert_setup(&conv, enc, p_enc);
16601 if (conv.vc_type != CONV_NONE)
16602 rettv->vval.v_string = string_convert(&conv, result_buf, NULL);
16603 else
16604 # endif
16605 rettv->vval.v_string = vim_strsave(result_buf);
16607 # ifdef FEAT_MBYTE
16608 /* Release conversion descriptors */
16609 convert_setup(&conv, NULL, NULL);
16610 vim_free(enc);
16611 # endif
16614 #endif
16617 * "stridx()" function
16619 static void
16620 f_stridx(argvars, rettv)
16621 typval_T *argvars;
16622 typval_T *rettv;
16624 char_u buf[NUMBUFLEN];
16625 char_u *needle;
16626 char_u *haystack;
16627 char_u *save_haystack;
16628 char_u *pos;
16629 int start_idx;
16631 needle = get_tv_string_chk(&argvars[1]);
16632 save_haystack = haystack = get_tv_string_buf_chk(&argvars[0], buf);
16633 rettv->vval.v_number = -1;
16634 if (needle == NULL || haystack == NULL)
16635 return; /* type error; errmsg already given */
16637 if (argvars[2].v_type != VAR_UNKNOWN)
16639 int error = FALSE;
16641 start_idx = get_tv_number_chk(&argvars[2], &error);
16642 if (error || start_idx >= (int)STRLEN(haystack))
16643 return;
16644 if (start_idx >= 0)
16645 haystack += start_idx;
16648 pos = (char_u *)strstr((char *)haystack, (char *)needle);
16649 if (pos != NULL)
16650 rettv->vval.v_number = (varnumber_T)(pos - save_haystack);
16654 * "string()" function
16656 static void
16657 f_string(argvars, rettv)
16658 typval_T *argvars;
16659 typval_T *rettv;
16661 char_u *tofree;
16662 char_u numbuf[NUMBUFLEN];
16664 rettv->v_type = VAR_STRING;
16665 rettv->vval.v_string = tv2string(&argvars[0], &tofree, numbuf, 0);
16666 /* Make a copy if we have a value but it's not in allocated memory. */
16667 if (rettv->vval.v_string != NULL && tofree == NULL)
16668 rettv->vval.v_string = vim_strsave(rettv->vval.v_string);
16672 * "strlen()" function
16674 static void
16675 f_strlen(argvars, rettv)
16676 typval_T *argvars;
16677 typval_T *rettv;
16679 rettv->vval.v_number = (varnumber_T)(STRLEN(
16680 get_tv_string(&argvars[0])));
16684 * "strpart()" function
16686 static void
16687 f_strpart(argvars, rettv)
16688 typval_T *argvars;
16689 typval_T *rettv;
16691 char_u *p;
16692 int n;
16693 int len;
16694 int slen;
16695 int error = FALSE;
16697 p = get_tv_string(&argvars[0]);
16698 slen = (int)STRLEN(p);
16700 n = get_tv_number_chk(&argvars[1], &error);
16701 if (error)
16702 len = 0;
16703 else if (argvars[2].v_type != VAR_UNKNOWN)
16704 len = get_tv_number(&argvars[2]);
16705 else
16706 len = slen - n; /* default len: all bytes that are available. */
16709 * Only return the overlap between the specified part and the actual
16710 * string.
16712 if (n < 0)
16714 len += n;
16715 n = 0;
16717 else if (n > slen)
16718 n = slen;
16719 if (len < 0)
16720 len = 0;
16721 else if (n + len > slen)
16722 len = slen - n;
16724 rettv->v_type = VAR_STRING;
16725 rettv->vval.v_string = vim_strnsave(p + n, len);
16729 * "strridx()" function
16731 static void
16732 f_strridx(argvars, rettv)
16733 typval_T *argvars;
16734 typval_T *rettv;
16736 char_u buf[NUMBUFLEN];
16737 char_u *needle;
16738 char_u *haystack;
16739 char_u *rest;
16740 char_u *lastmatch = NULL;
16741 int haystack_len, end_idx;
16743 needle = get_tv_string_chk(&argvars[1]);
16744 haystack = get_tv_string_buf_chk(&argvars[0], buf);
16746 rettv->vval.v_number = -1;
16747 if (needle == NULL || haystack == NULL)
16748 return; /* type error; errmsg already given */
16750 haystack_len = (int)STRLEN(haystack);
16751 if (argvars[2].v_type != VAR_UNKNOWN)
16753 /* Third argument: upper limit for index */
16754 end_idx = get_tv_number_chk(&argvars[2], NULL);
16755 if (end_idx < 0)
16756 return; /* can never find a match */
16758 else
16759 end_idx = haystack_len;
16761 if (*needle == NUL)
16763 /* Empty string matches past the end. */
16764 lastmatch = haystack + end_idx;
16766 else
16768 for (rest = haystack; *rest != '\0'; ++rest)
16770 rest = (char_u *)strstr((char *)rest, (char *)needle);
16771 if (rest == NULL || rest > haystack + end_idx)
16772 break;
16773 lastmatch = rest;
16777 if (lastmatch == NULL)
16778 rettv->vval.v_number = -1;
16779 else
16780 rettv->vval.v_number = (varnumber_T)(lastmatch - haystack);
16784 * "strtrans()" function
16786 static void
16787 f_strtrans(argvars, rettv)
16788 typval_T *argvars;
16789 typval_T *rettv;
16791 rettv->v_type = VAR_STRING;
16792 rettv->vval.v_string = transstr(get_tv_string(&argvars[0]));
16796 * "submatch()" function
16798 static void
16799 f_submatch(argvars, rettv)
16800 typval_T *argvars;
16801 typval_T *rettv;
16803 rettv->v_type = VAR_STRING;
16804 rettv->vval.v_string =
16805 reg_submatch((int)get_tv_number_chk(&argvars[0], NULL));
16809 * "substitute()" function
16811 static void
16812 f_substitute(argvars, rettv)
16813 typval_T *argvars;
16814 typval_T *rettv;
16816 char_u patbuf[NUMBUFLEN];
16817 char_u subbuf[NUMBUFLEN];
16818 char_u flagsbuf[NUMBUFLEN];
16820 char_u *str = get_tv_string_chk(&argvars[0]);
16821 char_u *pat = get_tv_string_buf_chk(&argvars[1], patbuf);
16822 char_u *sub = get_tv_string_buf_chk(&argvars[2], subbuf);
16823 char_u *flg = get_tv_string_buf_chk(&argvars[3], flagsbuf);
16825 rettv->v_type = VAR_STRING;
16826 if (str == NULL || pat == NULL || sub == NULL || flg == NULL)
16827 rettv->vval.v_string = NULL;
16828 else
16829 rettv->vval.v_string = do_string_sub(str, pat, sub, flg);
16833 * "synID(lnum, col, trans)" function
16835 static void
16836 f_synID(argvars, rettv)
16837 typval_T *argvars UNUSED;
16838 typval_T *rettv;
16840 int id = 0;
16841 #ifdef FEAT_SYN_HL
16842 long lnum;
16843 long col;
16844 int trans;
16845 int transerr = FALSE;
16847 lnum = get_tv_lnum(argvars); /* -1 on type error */
16848 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
16849 trans = get_tv_number_chk(&argvars[2], &transerr);
16851 if (!transerr && lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
16852 && col >= 0 && col < (long)STRLEN(ml_get(lnum)))
16853 id = syn_get_id(curwin, lnum, (colnr_T)col, trans, NULL, FALSE);
16854 #endif
16856 rettv->vval.v_number = id;
16860 * "synIDattr(id, what [, mode])" function
16862 static void
16863 f_synIDattr(argvars, rettv)
16864 typval_T *argvars UNUSED;
16865 typval_T *rettv;
16867 char_u *p = NULL;
16868 #ifdef FEAT_SYN_HL
16869 int id;
16870 char_u *what;
16871 char_u *mode;
16872 char_u modebuf[NUMBUFLEN];
16873 int modec;
16875 id = get_tv_number(&argvars[0]);
16876 what = get_tv_string(&argvars[1]);
16877 if (argvars[2].v_type != VAR_UNKNOWN)
16879 mode = get_tv_string_buf(&argvars[2], modebuf);
16880 modec = TOLOWER_ASC(mode[0]);
16881 if (modec != 't' && modec != 'c'
16882 #ifdef FEAT_GUI
16883 && modec != 'g'
16884 #endif
16886 modec = 0; /* replace invalid with current */
16888 else
16890 #ifdef FEAT_GUI
16891 if (gui.in_use)
16892 modec = 'g';
16893 else
16894 #endif
16895 if (t_colors > 1)
16896 modec = 'c';
16897 else
16898 modec = 't';
16902 switch (TOLOWER_ASC(what[0]))
16904 case 'b':
16905 if (TOLOWER_ASC(what[1]) == 'g') /* bg[#] */
16906 p = highlight_color(id, what, modec);
16907 else /* bold */
16908 p = highlight_has_attr(id, HL_BOLD, modec);
16909 break;
16911 case 'f': /* fg[#] or font */
16912 p = highlight_color(id, what, modec);
16913 break;
16915 case 'i':
16916 if (TOLOWER_ASC(what[1]) == 'n') /* inverse */
16917 p = highlight_has_attr(id, HL_INVERSE, modec);
16918 else /* italic */
16919 p = highlight_has_attr(id, HL_ITALIC, modec);
16920 break;
16922 case 'n': /* name */
16923 p = get_highlight_name(NULL, id - 1);
16924 break;
16926 case 'r': /* reverse */
16927 p = highlight_has_attr(id, HL_INVERSE, modec);
16928 break;
16930 case 's':
16931 if (TOLOWER_ASC(what[1]) == 'p') /* sp[#] */
16932 p = highlight_color(id, what, modec);
16933 else /* standout */
16934 p = highlight_has_attr(id, HL_STANDOUT, modec);
16935 break;
16937 case 'u':
16938 if (STRLEN(what) <= 5 || TOLOWER_ASC(what[5]) != 'c')
16939 /* underline */
16940 p = highlight_has_attr(id, HL_UNDERLINE, modec);
16941 else
16942 /* undercurl */
16943 p = highlight_has_attr(id, HL_UNDERCURL, modec);
16944 break;
16947 if (p != NULL)
16948 p = vim_strsave(p);
16949 #endif
16950 rettv->v_type = VAR_STRING;
16951 rettv->vval.v_string = p;
16955 * "synIDtrans(id)" function
16957 static void
16958 f_synIDtrans(argvars, rettv)
16959 typval_T *argvars UNUSED;
16960 typval_T *rettv;
16962 int id;
16964 #ifdef FEAT_SYN_HL
16965 id = get_tv_number(&argvars[0]);
16967 if (id > 0)
16968 id = syn_get_final_id(id);
16969 else
16970 #endif
16971 id = 0;
16973 rettv->vval.v_number = id;
16977 * "synstack(lnum, col)" function
16979 static void
16980 f_synstack(argvars, rettv)
16981 typval_T *argvars UNUSED;
16982 typval_T *rettv;
16984 #ifdef FEAT_SYN_HL
16985 long lnum;
16986 long col;
16987 int i;
16988 int id;
16989 #endif
16991 rettv->v_type = VAR_LIST;
16992 rettv->vval.v_list = NULL;
16994 #ifdef FEAT_SYN_HL
16995 lnum = get_tv_lnum(argvars); /* -1 on type error */
16996 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
16998 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
16999 && col >= 0 && (col == 0 || col < (long)STRLEN(ml_get(lnum)))
17000 && rettv_list_alloc(rettv) != FAIL)
17002 (void)syn_get_id(curwin, lnum, (colnr_T)col, FALSE, NULL, TRUE);
17003 for (i = 0; ; ++i)
17005 id = syn_get_stack_item(i);
17006 if (id < 0)
17007 break;
17008 if (list_append_number(rettv->vval.v_list, id) == FAIL)
17009 break;
17012 #endif
17016 * "system()" function
17018 static void
17019 f_system(argvars, rettv)
17020 typval_T *argvars;
17021 typval_T *rettv;
17023 char_u *res = NULL;
17024 char_u *p;
17025 char_u *infile = NULL;
17026 char_u buf[NUMBUFLEN];
17027 int err = FALSE;
17028 FILE *fd;
17030 if (check_restricted() || check_secure())
17031 goto done;
17033 if (argvars[1].v_type != VAR_UNKNOWN)
17036 * Write the string to a temp file, to be used for input of the shell
17037 * command.
17039 if ((infile = vim_tempname('i')) == NULL)
17041 EMSG(_(e_notmp));
17042 goto done;
17045 fd = mch_fopen((char *)infile, WRITEBIN);
17046 if (fd == NULL)
17048 EMSG2(_(e_notopen), infile);
17049 goto done;
17051 p = get_tv_string_buf_chk(&argvars[1], buf);
17052 if (p == NULL)
17054 fclose(fd);
17055 goto done; /* type error; errmsg already given */
17057 if (fwrite(p, STRLEN(p), 1, fd) != 1)
17058 err = TRUE;
17059 if (fclose(fd) != 0)
17060 err = TRUE;
17061 if (err)
17063 EMSG(_("E677: Error writing temp file"));
17064 goto done;
17068 res = get_cmd_output(get_tv_string(&argvars[0]), infile,
17069 SHELL_SILENT | SHELL_COOKED);
17071 #ifdef USE_CR
17072 /* translate <CR> into <NL> */
17073 if (res != NULL)
17075 char_u *s;
17077 for (s = res; *s; ++s)
17079 if (*s == CAR)
17080 *s = NL;
17083 #else
17084 # ifdef USE_CRNL
17085 /* translate <CR><NL> into <NL> */
17086 if (res != NULL)
17088 char_u *s, *d;
17090 d = res;
17091 for (s = res; *s; ++s)
17093 if (s[0] == CAR && s[1] == NL)
17094 ++s;
17095 *d++ = *s;
17097 *d = NUL;
17099 # endif
17100 #endif
17102 done:
17103 if (infile != NULL)
17105 mch_remove(infile);
17106 vim_free(infile);
17108 rettv->v_type = VAR_STRING;
17109 rettv->vval.v_string = res;
17113 * "tabpagebuflist()" function
17115 static void
17116 f_tabpagebuflist(argvars, rettv)
17117 typval_T *argvars UNUSED;
17118 typval_T *rettv UNUSED;
17120 #ifdef FEAT_WINDOWS
17121 tabpage_T *tp;
17122 win_T *wp = NULL;
17124 if (argvars[0].v_type == VAR_UNKNOWN)
17125 wp = firstwin;
17126 else
17128 tp = find_tabpage((int)get_tv_number(&argvars[0]));
17129 if (tp != NULL)
17130 wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
17132 if (wp != NULL && rettv_list_alloc(rettv) != FAIL)
17134 for (; wp != NULL; wp = wp->w_next)
17135 if (list_append_number(rettv->vval.v_list,
17136 wp->w_buffer->b_fnum) == FAIL)
17137 break;
17139 #endif
17144 * "tabpagenr()" function
17146 static void
17147 f_tabpagenr(argvars, rettv)
17148 typval_T *argvars UNUSED;
17149 typval_T *rettv;
17151 int nr = 1;
17152 #ifdef FEAT_WINDOWS
17153 char_u *arg;
17155 if (argvars[0].v_type != VAR_UNKNOWN)
17157 arg = get_tv_string_chk(&argvars[0]);
17158 nr = 0;
17159 if (arg != NULL)
17161 if (STRCMP(arg, "$") == 0)
17162 nr = tabpage_index(NULL) - 1;
17163 else
17164 EMSG2(_(e_invexpr2), arg);
17167 else
17168 nr = tabpage_index(curtab);
17169 #endif
17170 rettv->vval.v_number = nr;
17174 #ifdef FEAT_WINDOWS
17175 static int get_winnr __ARGS((tabpage_T *tp, typval_T *argvar));
17178 * Common code for tabpagewinnr() and winnr().
17180 static int
17181 get_winnr(tp, argvar)
17182 tabpage_T *tp;
17183 typval_T *argvar;
17185 win_T *twin;
17186 int nr = 1;
17187 win_T *wp;
17188 char_u *arg;
17190 twin = (tp == curtab) ? curwin : tp->tp_curwin;
17191 if (argvar->v_type != VAR_UNKNOWN)
17193 arg = get_tv_string_chk(argvar);
17194 if (arg == NULL)
17195 nr = 0; /* type error; errmsg already given */
17196 else if (STRCMP(arg, "$") == 0)
17197 twin = (tp == curtab) ? lastwin : tp->tp_lastwin;
17198 else if (STRCMP(arg, "#") == 0)
17200 twin = (tp == curtab) ? prevwin : tp->tp_prevwin;
17201 if (twin == NULL)
17202 nr = 0;
17204 else
17206 EMSG2(_(e_invexpr2), arg);
17207 nr = 0;
17211 if (nr > 0)
17212 for (wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
17213 wp != twin; wp = wp->w_next)
17215 if (wp == NULL)
17217 /* didn't find it in this tabpage */
17218 nr = 0;
17219 break;
17221 ++nr;
17223 return nr;
17225 #endif
17228 * "tabpagewinnr()" function
17230 static void
17231 f_tabpagewinnr(argvars, rettv)
17232 typval_T *argvars UNUSED;
17233 typval_T *rettv;
17235 int nr = 1;
17236 #ifdef FEAT_WINDOWS
17237 tabpage_T *tp;
17239 tp = find_tabpage((int)get_tv_number(&argvars[0]));
17240 if (tp == NULL)
17241 nr = 0;
17242 else
17243 nr = get_winnr(tp, &argvars[1]);
17244 #endif
17245 rettv->vval.v_number = nr;
17250 * "tagfiles()" function
17252 static void
17253 f_tagfiles(argvars, rettv)
17254 typval_T *argvars UNUSED;
17255 typval_T *rettv;
17257 char_u fname[MAXPATHL + 1];
17258 tagname_T tn;
17259 int first;
17261 if (rettv_list_alloc(rettv) == FAIL)
17262 return;
17264 for (first = TRUE; ; first = FALSE)
17265 if (get_tagfname(&tn, first, fname) == FAIL
17266 || list_append_string(rettv->vval.v_list, fname, -1) == FAIL)
17267 break;
17268 tagname_free(&tn);
17272 * "taglist()" function
17274 static void
17275 f_taglist(argvars, rettv)
17276 typval_T *argvars;
17277 typval_T *rettv;
17279 char_u *tag_pattern;
17281 tag_pattern = get_tv_string(&argvars[0]);
17283 rettv->vval.v_number = FALSE;
17284 if (*tag_pattern == NUL)
17285 return;
17287 if (rettv_list_alloc(rettv) == OK)
17288 (void)get_tags(rettv->vval.v_list, tag_pattern);
17292 * "tempname()" function
17294 static void
17295 f_tempname(argvars, rettv)
17296 typval_T *argvars UNUSED;
17297 typval_T *rettv;
17299 static int x = 'A';
17301 rettv->v_type = VAR_STRING;
17302 rettv->vval.v_string = vim_tempname(x);
17304 /* Advance 'x' to use A-Z and 0-9, so that there are at least 34 different
17305 * names. Skip 'I' and 'O', they are used for shell redirection. */
17308 if (x == 'Z')
17309 x = '0';
17310 else if (x == '9')
17311 x = 'A';
17312 else
17314 #ifdef EBCDIC
17315 if (x == 'I')
17316 x = 'J';
17317 else if (x == 'R')
17318 x = 'S';
17319 else
17320 #endif
17321 ++x;
17323 } while (x == 'I' || x == 'O');
17327 * "test(list)" function: Just checking the walls...
17329 static void
17330 f_test(argvars, rettv)
17331 typval_T *argvars UNUSED;
17332 typval_T *rettv UNUSED;
17334 /* Used for unit testing. Change the code below to your liking. */
17335 #if 0
17336 listitem_T *li;
17337 list_T *l;
17338 char_u *bad, *good;
17340 if (argvars[0].v_type != VAR_LIST)
17341 return;
17342 l = argvars[0].vval.v_list;
17343 if (l == NULL)
17344 return;
17345 li = l->lv_first;
17346 if (li == NULL)
17347 return;
17348 bad = get_tv_string(&li->li_tv);
17349 li = li->li_next;
17350 if (li == NULL)
17351 return;
17352 good = get_tv_string(&li->li_tv);
17353 rettv->vval.v_number = test_edit_score(bad, good);
17354 #endif
17358 * "tolower(string)" function
17360 static void
17361 f_tolower(argvars, rettv)
17362 typval_T *argvars;
17363 typval_T *rettv;
17365 char_u *p;
17367 p = vim_strsave(get_tv_string(&argvars[0]));
17368 rettv->v_type = VAR_STRING;
17369 rettv->vval.v_string = p;
17371 if (p != NULL)
17372 while (*p != NUL)
17374 #ifdef FEAT_MBYTE
17375 int l;
17377 if (enc_utf8)
17379 int c, lc;
17381 c = utf_ptr2char(p);
17382 lc = utf_tolower(c);
17383 l = utf_ptr2len(p);
17384 /* TODO: reallocate string when byte count changes. */
17385 if (utf_char2len(lc) == l)
17386 utf_char2bytes(lc, p);
17387 p += l;
17389 else if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
17390 p += l; /* skip multi-byte character */
17391 else
17392 #endif
17394 *p = TOLOWER_LOC(*p); /* note that tolower() can be a macro */
17395 ++p;
17401 * "toupper(string)" function
17403 static void
17404 f_toupper(argvars, rettv)
17405 typval_T *argvars;
17406 typval_T *rettv;
17408 rettv->v_type = VAR_STRING;
17409 rettv->vval.v_string = strup_save(get_tv_string(&argvars[0]));
17413 * "tr(string, fromstr, tostr)" function
17415 static void
17416 f_tr(argvars, rettv)
17417 typval_T *argvars;
17418 typval_T *rettv;
17420 char_u *instr;
17421 char_u *fromstr;
17422 char_u *tostr;
17423 char_u *p;
17424 #ifdef FEAT_MBYTE
17425 int inlen;
17426 int fromlen;
17427 int tolen;
17428 int idx;
17429 char_u *cpstr;
17430 int cplen;
17431 int first = TRUE;
17432 #endif
17433 char_u buf[NUMBUFLEN];
17434 char_u buf2[NUMBUFLEN];
17435 garray_T ga;
17437 instr = get_tv_string(&argvars[0]);
17438 fromstr = get_tv_string_buf_chk(&argvars[1], buf);
17439 tostr = get_tv_string_buf_chk(&argvars[2], buf2);
17441 /* Default return value: empty string. */
17442 rettv->v_type = VAR_STRING;
17443 rettv->vval.v_string = NULL;
17444 if (fromstr == NULL || tostr == NULL)
17445 return; /* type error; errmsg already given */
17446 ga_init2(&ga, (int)sizeof(char), 80);
17448 #ifdef FEAT_MBYTE
17449 if (!has_mbyte)
17450 #endif
17451 /* not multi-byte: fromstr and tostr must be the same length */
17452 if (STRLEN(fromstr) != STRLEN(tostr))
17454 #ifdef FEAT_MBYTE
17455 error:
17456 #endif
17457 EMSG2(_(e_invarg2), fromstr);
17458 ga_clear(&ga);
17459 return;
17462 /* fromstr and tostr have to contain the same number of chars */
17463 while (*instr != NUL)
17465 #ifdef FEAT_MBYTE
17466 if (has_mbyte)
17468 inlen = (*mb_ptr2len)(instr);
17469 cpstr = instr;
17470 cplen = inlen;
17471 idx = 0;
17472 for (p = fromstr; *p != NUL; p += fromlen)
17474 fromlen = (*mb_ptr2len)(p);
17475 if (fromlen == inlen && STRNCMP(instr, p, inlen) == 0)
17477 for (p = tostr; *p != NUL; p += tolen)
17479 tolen = (*mb_ptr2len)(p);
17480 if (idx-- == 0)
17482 cplen = tolen;
17483 cpstr = p;
17484 break;
17487 if (*p == NUL) /* tostr is shorter than fromstr */
17488 goto error;
17489 break;
17491 ++idx;
17494 if (first && cpstr == instr)
17496 /* Check that fromstr and tostr have the same number of
17497 * (multi-byte) characters. Done only once when a character
17498 * of instr doesn't appear in fromstr. */
17499 first = FALSE;
17500 for (p = tostr; *p != NUL; p += tolen)
17502 tolen = (*mb_ptr2len)(p);
17503 --idx;
17505 if (idx != 0)
17506 goto error;
17509 ga_grow(&ga, cplen);
17510 mch_memmove((char *)ga.ga_data + ga.ga_len, cpstr, (size_t)cplen);
17511 ga.ga_len += cplen;
17513 instr += inlen;
17515 else
17516 #endif
17518 /* When not using multi-byte chars we can do it faster. */
17519 p = vim_strchr(fromstr, *instr);
17520 if (p != NULL)
17521 ga_append(&ga, tostr[p - fromstr]);
17522 else
17523 ga_append(&ga, *instr);
17524 ++instr;
17528 /* add a terminating NUL */
17529 ga_grow(&ga, 1);
17530 ga_append(&ga, NUL);
17532 rettv->vval.v_string = ga.ga_data;
17535 #ifdef FEAT_FLOAT
17537 * "trunc({float})" function
17539 static void
17540 f_trunc(argvars, rettv)
17541 typval_T *argvars;
17542 typval_T *rettv;
17544 float_T f;
17546 rettv->v_type = VAR_FLOAT;
17547 if (get_float_arg(argvars, &f) == OK)
17548 /* trunc() is not in C90, use floor() or ceil() instead. */
17549 rettv->vval.v_float = f > 0 ? floor(f) : ceil(f);
17550 else
17551 rettv->vval.v_float = 0.0;
17553 #endif
17556 * "type(expr)" function
17558 static void
17559 f_type(argvars, rettv)
17560 typval_T *argvars;
17561 typval_T *rettv;
17563 int n;
17565 switch (argvars[0].v_type)
17567 case VAR_NUMBER: n = 0; break;
17568 case VAR_STRING: n = 1; break;
17569 case VAR_FUNC: n = 2; break;
17570 case VAR_LIST: n = 3; break;
17571 case VAR_DICT: n = 4; break;
17572 #ifdef FEAT_FLOAT
17573 case VAR_FLOAT: n = 5; break;
17574 #endif
17575 default: EMSG2(_(e_intern2), "f_type()"); n = 0; break;
17577 rettv->vval.v_number = n;
17581 * "values(dict)" function
17583 static void
17584 f_values(argvars, rettv)
17585 typval_T *argvars;
17586 typval_T *rettv;
17588 dict_list(argvars, rettv, 1);
17592 * "virtcol(string)" function
17594 static void
17595 f_virtcol(argvars, rettv)
17596 typval_T *argvars;
17597 typval_T *rettv;
17599 colnr_T vcol = 0;
17600 pos_T *fp;
17601 int fnum = curbuf->b_fnum;
17603 fp = var2fpos(&argvars[0], FALSE, &fnum);
17604 if (fp != NULL && fp->lnum <= curbuf->b_ml.ml_line_count
17605 && fnum == curbuf->b_fnum)
17607 getvvcol(curwin, fp, NULL, NULL, &vcol);
17608 ++vcol;
17611 rettv->vval.v_number = vcol;
17615 * "visualmode()" function
17617 static void
17618 f_visualmode(argvars, rettv)
17619 typval_T *argvars UNUSED;
17620 typval_T *rettv UNUSED;
17622 #ifdef FEAT_VISUAL
17623 char_u str[2];
17625 rettv->v_type = VAR_STRING;
17626 str[0] = curbuf->b_visual_mode_eval;
17627 str[1] = NUL;
17628 rettv->vval.v_string = vim_strsave(str);
17630 /* A non-zero number or non-empty string argument: reset mode. */
17631 if (non_zero_arg(&argvars[0]))
17632 curbuf->b_visual_mode_eval = NUL;
17633 #endif
17637 * "winbufnr(nr)" function
17639 static void
17640 f_winbufnr(argvars, rettv)
17641 typval_T *argvars;
17642 typval_T *rettv;
17644 win_T *wp;
17646 wp = find_win_by_nr(&argvars[0], NULL);
17647 if (wp == NULL)
17648 rettv->vval.v_number = -1;
17649 else
17650 rettv->vval.v_number = wp->w_buffer->b_fnum;
17654 * "wincol()" function
17656 static void
17657 f_wincol(argvars, rettv)
17658 typval_T *argvars UNUSED;
17659 typval_T *rettv;
17661 validate_cursor();
17662 rettv->vval.v_number = curwin->w_wcol + 1;
17666 * "winheight(nr)" function
17668 static void
17669 f_winheight(argvars, rettv)
17670 typval_T *argvars;
17671 typval_T *rettv;
17673 win_T *wp;
17675 wp = find_win_by_nr(&argvars[0], NULL);
17676 if (wp == NULL)
17677 rettv->vval.v_number = -1;
17678 else
17679 rettv->vval.v_number = wp->w_height;
17683 * "winline()" function
17685 static void
17686 f_winline(argvars, rettv)
17687 typval_T *argvars UNUSED;
17688 typval_T *rettv;
17690 validate_cursor();
17691 rettv->vval.v_number = curwin->w_wrow + 1;
17695 * "winnr()" function
17697 static void
17698 f_winnr(argvars, rettv)
17699 typval_T *argvars UNUSED;
17700 typval_T *rettv;
17702 int nr = 1;
17704 #ifdef FEAT_WINDOWS
17705 nr = get_winnr(curtab, &argvars[0]);
17706 #endif
17707 rettv->vval.v_number = nr;
17711 * "winrestcmd()" function
17713 static void
17714 f_winrestcmd(argvars, rettv)
17715 typval_T *argvars UNUSED;
17716 typval_T *rettv;
17718 #ifdef FEAT_WINDOWS
17719 win_T *wp;
17720 int winnr = 1;
17721 garray_T ga;
17722 char_u buf[50];
17724 ga_init2(&ga, (int)sizeof(char), 70);
17725 for (wp = firstwin; wp != NULL; wp = wp->w_next)
17727 sprintf((char *)buf, "%dresize %d|", winnr, wp->w_height);
17728 ga_concat(&ga, buf);
17729 # ifdef FEAT_VERTSPLIT
17730 sprintf((char *)buf, "vert %dresize %d|", winnr, wp->w_width);
17731 ga_concat(&ga, buf);
17732 # endif
17733 ++winnr;
17735 ga_append(&ga, NUL);
17737 rettv->vval.v_string = ga.ga_data;
17738 #else
17739 rettv->vval.v_string = NULL;
17740 #endif
17741 rettv->v_type = VAR_STRING;
17745 * "winrestview()" function
17747 static void
17748 f_winrestview(argvars, rettv)
17749 typval_T *argvars;
17750 typval_T *rettv UNUSED;
17752 dict_T *dict;
17754 if (argvars[0].v_type != VAR_DICT
17755 || (dict = argvars[0].vval.v_dict) == NULL)
17756 EMSG(_(e_invarg));
17757 else
17759 curwin->w_cursor.lnum = get_dict_number(dict, (char_u *)"lnum");
17760 curwin->w_cursor.col = get_dict_number(dict, (char_u *)"col");
17761 #ifdef FEAT_VIRTUALEDIT
17762 curwin->w_cursor.coladd = get_dict_number(dict, (char_u *)"coladd");
17763 #endif
17764 curwin->w_curswant = get_dict_number(dict, (char_u *)"curswant");
17765 curwin->w_set_curswant = FALSE;
17767 set_topline(curwin, get_dict_number(dict, (char_u *)"topline"));
17768 #ifdef FEAT_DIFF
17769 curwin->w_topfill = get_dict_number(dict, (char_u *)"topfill");
17770 #endif
17771 curwin->w_leftcol = get_dict_number(dict, (char_u *)"leftcol");
17772 curwin->w_skipcol = get_dict_number(dict, (char_u *)"skipcol");
17774 check_cursor();
17775 changed_cline_bef_curs();
17776 invalidate_botline();
17777 redraw_later(VALID);
17779 if (curwin->w_topline == 0)
17780 curwin->w_topline = 1;
17781 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
17782 curwin->w_topline = curbuf->b_ml.ml_line_count;
17783 #ifdef FEAT_DIFF
17784 check_topfill(curwin, TRUE);
17785 #endif
17790 * "winsaveview()" function
17792 static void
17793 f_winsaveview(argvars, rettv)
17794 typval_T *argvars UNUSED;
17795 typval_T *rettv;
17797 dict_T *dict;
17799 dict = dict_alloc();
17800 if (dict == NULL)
17801 return;
17802 rettv->v_type = VAR_DICT;
17803 rettv->vval.v_dict = dict;
17804 ++dict->dv_refcount;
17806 dict_add_nr_str(dict, "lnum", (long)curwin->w_cursor.lnum, NULL);
17807 dict_add_nr_str(dict, "col", (long)curwin->w_cursor.col, NULL);
17808 #ifdef FEAT_VIRTUALEDIT
17809 dict_add_nr_str(dict, "coladd", (long)curwin->w_cursor.coladd, NULL);
17810 #endif
17811 update_curswant();
17812 dict_add_nr_str(dict, "curswant", (long)curwin->w_curswant, NULL);
17814 dict_add_nr_str(dict, "topline", (long)curwin->w_topline, NULL);
17815 #ifdef FEAT_DIFF
17816 dict_add_nr_str(dict, "topfill", (long)curwin->w_topfill, NULL);
17817 #endif
17818 dict_add_nr_str(dict, "leftcol", (long)curwin->w_leftcol, NULL);
17819 dict_add_nr_str(dict, "skipcol", (long)curwin->w_skipcol, NULL);
17823 * "winwidth(nr)" function
17825 static void
17826 f_winwidth(argvars, rettv)
17827 typval_T *argvars;
17828 typval_T *rettv;
17830 win_T *wp;
17832 wp = find_win_by_nr(&argvars[0], NULL);
17833 if (wp == NULL)
17834 rettv->vval.v_number = -1;
17835 else
17836 #ifdef FEAT_VERTSPLIT
17837 rettv->vval.v_number = wp->w_width;
17838 #else
17839 rettv->vval.v_number = Columns;
17840 #endif
17844 * "writefile()" function
17846 static void
17847 f_writefile(argvars, rettv)
17848 typval_T *argvars;
17849 typval_T *rettv;
17851 int binary = FALSE;
17852 char_u *fname;
17853 FILE *fd;
17854 listitem_T *li;
17855 char_u *s;
17856 int ret = 0;
17857 int c;
17859 if (check_restricted() || check_secure())
17860 return;
17862 if (argvars[0].v_type != VAR_LIST)
17864 EMSG2(_(e_listarg), "writefile()");
17865 return;
17867 if (argvars[0].vval.v_list == NULL)
17868 return;
17870 if (argvars[2].v_type != VAR_UNKNOWN
17871 && STRCMP(get_tv_string(&argvars[2]), "b") == 0)
17872 binary = TRUE;
17874 /* Always open the file in binary mode, library functions have a mind of
17875 * their own about CR-LF conversion. */
17876 fname = get_tv_string(&argvars[1]);
17877 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
17879 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
17880 ret = -1;
17882 else
17884 for (li = argvars[0].vval.v_list->lv_first; li != NULL;
17885 li = li->li_next)
17887 for (s = get_tv_string(&li->li_tv); *s != NUL; ++s)
17889 if (*s == '\n')
17890 c = putc(NUL, fd);
17891 else
17892 c = putc(*s, fd);
17893 if (c == EOF)
17895 ret = -1;
17896 break;
17899 if (!binary || li->li_next != NULL)
17900 if (putc('\n', fd) == EOF)
17902 ret = -1;
17903 break;
17905 if (ret < 0)
17907 EMSG(_(e_write));
17908 break;
17911 fclose(fd);
17914 rettv->vval.v_number = ret;
17918 * Translate a String variable into a position.
17919 * Returns NULL when there is an error.
17921 static pos_T *
17922 var2fpos(varp, dollar_lnum, fnum)
17923 typval_T *varp;
17924 int dollar_lnum; /* TRUE when $ is last line */
17925 int *fnum; /* set to fnum for '0, 'A, etc. */
17927 char_u *name;
17928 static pos_T pos;
17929 pos_T *pp;
17931 /* Argument can be [lnum, col, coladd]. */
17932 if (varp->v_type == VAR_LIST)
17934 list_T *l;
17935 int len;
17936 int error = FALSE;
17937 listitem_T *li;
17939 l = varp->vval.v_list;
17940 if (l == NULL)
17941 return NULL;
17943 /* Get the line number */
17944 pos.lnum = list_find_nr(l, 0L, &error);
17945 if (error || pos.lnum <= 0 || pos.lnum > curbuf->b_ml.ml_line_count)
17946 return NULL; /* invalid line number */
17948 /* Get the column number */
17949 pos.col = list_find_nr(l, 1L, &error);
17950 if (error)
17951 return NULL;
17952 len = (long)STRLEN(ml_get(pos.lnum));
17954 /* We accept "$" for the column number: last column. */
17955 li = list_find(l, 1L);
17956 if (li != NULL && li->li_tv.v_type == VAR_STRING
17957 && li->li_tv.vval.v_string != NULL
17958 && STRCMP(li->li_tv.vval.v_string, "$") == 0)
17959 pos.col = len + 1;
17961 /* Accept a position up to the NUL after the line. */
17962 if (pos.col == 0 || (int)pos.col > len + 1)
17963 return NULL; /* invalid column number */
17964 --pos.col;
17966 #ifdef FEAT_VIRTUALEDIT
17967 /* Get the virtual offset. Defaults to zero. */
17968 pos.coladd = list_find_nr(l, 2L, &error);
17969 if (error)
17970 pos.coladd = 0;
17971 #endif
17973 return &pos;
17976 name = get_tv_string_chk(varp);
17977 if (name == NULL)
17978 return NULL;
17979 if (name[0] == '.') /* cursor */
17980 return &curwin->w_cursor;
17981 #ifdef FEAT_VISUAL
17982 if (name[0] == 'v' && name[1] == NUL) /* Visual start */
17984 if (VIsual_active)
17985 return &VIsual;
17986 return &curwin->w_cursor;
17988 #endif
17989 if (name[0] == '\'') /* mark */
17991 pp = getmark_fnum(name[1], FALSE, fnum);
17992 if (pp == NULL || pp == (pos_T *)-1 || pp->lnum <= 0)
17993 return NULL;
17994 return pp;
17997 #ifdef FEAT_VIRTUALEDIT
17998 pos.coladd = 0;
17999 #endif
18001 if (name[0] == 'w' && dollar_lnum)
18003 pos.col = 0;
18004 if (name[1] == '0') /* "w0": first visible line */
18006 update_topline();
18007 pos.lnum = curwin->w_topline;
18008 return &pos;
18010 else if (name[1] == '$') /* "w$": last visible line */
18012 validate_botline();
18013 pos.lnum = curwin->w_botline - 1;
18014 return &pos;
18017 else if (name[0] == '$') /* last column or line */
18019 if (dollar_lnum)
18021 pos.lnum = curbuf->b_ml.ml_line_count;
18022 pos.col = 0;
18024 else
18026 pos.lnum = curwin->w_cursor.lnum;
18027 pos.col = (colnr_T)STRLEN(ml_get_curline());
18029 return &pos;
18031 return NULL;
18035 * Convert list in "arg" into a position and optional file number.
18036 * When "fnump" is NULL there is no file number, only 3 items.
18037 * Note that the column is passed on as-is, the caller may want to decrement
18038 * it to use 1 for the first column.
18039 * Return FAIL when conversion is not possible, doesn't check the position for
18040 * validity.
18042 static int
18043 list2fpos(arg, posp, fnump)
18044 typval_T *arg;
18045 pos_T *posp;
18046 int *fnump;
18048 list_T *l = arg->vval.v_list;
18049 long i = 0;
18050 long n;
18052 /* List must be: [fnum, lnum, col, coladd], where "fnum" is only there
18053 * when "fnump" isn't NULL and "coladd" is optional. */
18054 if (arg->v_type != VAR_LIST
18055 || l == NULL
18056 || l->lv_len < (fnump == NULL ? 2 : 3)
18057 || l->lv_len > (fnump == NULL ? 3 : 4))
18058 return FAIL;
18060 if (fnump != NULL)
18062 n = list_find_nr(l, i++, NULL); /* fnum */
18063 if (n < 0)
18064 return FAIL;
18065 if (n == 0)
18066 n = curbuf->b_fnum; /* current buffer */
18067 *fnump = n;
18070 n = list_find_nr(l, i++, NULL); /* lnum */
18071 if (n < 0)
18072 return FAIL;
18073 posp->lnum = n;
18075 n = list_find_nr(l, i++, NULL); /* col */
18076 if (n < 0)
18077 return FAIL;
18078 posp->col = n;
18080 #ifdef FEAT_VIRTUALEDIT
18081 n = list_find_nr(l, i, NULL);
18082 if (n < 0)
18083 posp->coladd = 0;
18084 else
18085 posp->coladd = n;
18086 #endif
18088 return OK;
18092 * Get the length of an environment variable name.
18093 * Advance "arg" to the first character after the name.
18094 * Return 0 for error.
18096 static int
18097 get_env_len(arg)
18098 char_u **arg;
18100 char_u *p;
18101 int len;
18103 for (p = *arg; vim_isIDc(*p); ++p)
18105 if (p == *arg) /* no name found */
18106 return 0;
18108 len = (int)(p - *arg);
18109 *arg = p;
18110 return len;
18114 * Get the length of the name of a function or internal variable.
18115 * "arg" is advanced to the first non-white character after the name.
18116 * Return 0 if something is wrong.
18118 static int
18119 get_id_len(arg)
18120 char_u **arg;
18122 char_u *p;
18123 int len;
18125 /* Find the end of the name. */
18126 for (p = *arg; eval_isnamec(*p); ++p)
18128 if (p == *arg) /* no name found */
18129 return 0;
18131 len = (int)(p - *arg);
18132 *arg = skipwhite(p);
18134 return len;
18138 * Get the length of the name of a variable or function.
18139 * Only the name is recognized, does not handle ".key" or "[idx]".
18140 * "arg" is advanced to the first non-white character after the name.
18141 * Return -1 if curly braces expansion failed.
18142 * Return 0 if something else is wrong.
18143 * If the name contains 'magic' {}'s, expand them and return the
18144 * expanded name in an allocated string via 'alias' - caller must free.
18146 static int
18147 get_name_len(arg, alias, evaluate, verbose)
18148 char_u **arg;
18149 char_u **alias;
18150 int evaluate;
18151 int verbose;
18153 int len;
18154 char_u *p;
18155 char_u *expr_start;
18156 char_u *expr_end;
18158 *alias = NULL; /* default to no alias */
18160 if ((*arg)[0] == K_SPECIAL && (*arg)[1] == KS_EXTRA
18161 && (*arg)[2] == (int)KE_SNR)
18163 /* hard coded <SNR>, already translated */
18164 *arg += 3;
18165 return get_id_len(arg) + 3;
18167 len = eval_fname_script(*arg);
18168 if (len > 0)
18170 /* literal "<SID>", "s:" or "<SNR>" */
18171 *arg += len;
18175 * Find the end of the name; check for {} construction.
18177 p = find_name_end(*arg, &expr_start, &expr_end,
18178 len > 0 ? 0 : FNE_CHECK_START);
18179 if (expr_start != NULL)
18181 char_u *temp_string;
18183 if (!evaluate)
18185 len += (int)(p - *arg);
18186 *arg = skipwhite(p);
18187 return len;
18191 * Include any <SID> etc in the expanded string:
18192 * Thus the -len here.
18194 temp_string = make_expanded_name(*arg - len, expr_start, expr_end, p);
18195 if (temp_string == NULL)
18196 return -1;
18197 *alias = temp_string;
18198 *arg = skipwhite(p);
18199 return (int)STRLEN(temp_string);
18202 len += get_id_len(arg);
18203 if (len == 0 && verbose)
18204 EMSG2(_(e_invexpr2), *arg);
18206 return len;
18210 * Find the end of a variable or function name, taking care of magic braces.
18211 * If "expr_start" is not NULL then "expr_start" and "expr_end" are set to the
18212 * start and end of the first magic braces item.
18213 * "flags" can have FNE_INCL_BR and FNE_CHECK_START.
18214 * Return a pointer to just after the name. Equal to "arg" if there is no
18215 * valid name.
18217 static char_u *
18218 find_name_end(arg, expr_start, expr_end, flags)
18219 char_u *arg;
18220 char_u **expr_start;
18221 char_u **expr_end;
18222 int flags;
18224 int mb_nest = 0;
18225 int br_nest = 0;
18226 char_u *p;
18228 if (expr_start != NULL)
18230 *expr_start = NULL;
18231 *expr_end = NULL;
18234 /* Quick check for valid starting character. */
18235 if ((flags & FNE_CHECK_START) && !eval_isnamec1(*arg) && *arg != '{')
18236 return arg;
18238 for (p = arg; *p != NUL
18239 && (eval_isnamec(*p)
18240 || *p == '{'
18241 || ((flags & FNE_INCL_BR) && (*p == '[' || *p == '.'))
18242 || mb_nest != 0
18243 || br_nest != 0); mb_ptr_adv(p))
18245 if (*p == '\'')
18247 /* skip over 'string' to avoid counting [ and ] inside it. */
18248 for (p = p + 1; *p != NUL && *p != '\''; mb_ptr_adv(p))
18250 if (*p == NUL)
18251 break;
18253 else if (*p == '"')
18255 /* skip over "str\"ing" to avoid counting [ and ] inside it. */
18256 for (p = p + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
18257 if (*p == '\\' && p[1] != NUL)
18258 ++p;
18259 if (*p == NUL)
18260 break;
18263 if (mb_nest == 0)
18265 if (*p == '[')
18266 ++br_nest;
18267 else if (*p == ']')
18268 --br_nest;
18271 if (br_nest == 0)
18273 if (*p == '{')
18275 mb_nest++;
18276 if (expr_start != NULL && *expr_start == NULL)
18277 *expr_start = p;
18279 else if (*p == '}')
18281 mb_nest--;
18282 if (expr_start != NULL && mb_nest == 0 && *expr_end == NULL)
18283 *expr_end = p;
18288 return p;
18292 * Expands out the 'magic' {}'s in a variable/function name.
18293 * Note that this can call itself recursively, to deal with
18294 * constructs like foo{bar}{baz}{bam}
18295 * The four pointer arguments point to "foo{expre}ss{ion}bar"
18296 * "in_start" ^
18297 * "expr_start" ^
18298 * "expr_end" ^
18299 * "in_end" ^
18301 * Returns a new allocated string, which the caller must free.
18302 * Returns NULL for failure.
18304 static char_u *
18305 make_expanded_name(in_start, expr_start, expr_end, in_end)
18306 char_u *in_start;
18307 char_u *expr_start;
18308 char_u *expr_end;
18309 char_u *in_end;
18311 char_u c1;
18312 char_u *retval = NULL;
18313 char_u *temp_result;
18314 char_u *nextcmd = NULL;
18316 if (expr_end == NULL || in_end == NULL)
18317 return NULL;
18318 *expr_start = NUL;
18319 *expr_end = NUL;
18320 c1 = *in_end;
18321 *in_end = NUL;
18323 temp_result = eval_to_string(expr_start + 1, &nextcmd, FALSE);
18324 if (temp_result != NULL && nextcmd == NULL)
18326 retval = alloc((unsigned)(STRLEN(temp_result) + (expr_start - in_start)
18327 + (in_end - expr_end) + 1));
18328 if (retval != NULL)
18330 STRCPY(retval, in_start);
18331 STRCAT(retval, temp_result);
18332 STRCAT(retval, expr_end + 1);
18335 vim_free(temp_result);
18337 *in_end = c1; /* put char back for error messages */
18338 *expr_start = '{';
18339 *expr_end = '}';
18341 if (retval != NULL)
18343 temp_result = find_name_end(retval, &expr_start, &expr_end, 0);
18344 if (expr_start != NULL)
18346 /* Further expansion! */
18347 temp_result = make_expanded_name(retval, expr_start,
18348 expr_end, temp_result);
18349 vim_free(retval);
18350 retval = temp_result;
18354 return retval;
18358 * Return TRUE if character "c" can be used in a variable or function name.
18359 * Does not include '{' or '}' for magic braces.
18361 static int
18362 eval_isnamec(c)
18363 int c;
18365 return (ASCII_ISALNUM(c) || c == '_' || c == ':' || c == AUTOLOAD_CHAR);
18369 * Return TRUE if character "c" can be used as the first character in a
18370 * variable or function name (excluding '{' and '}').
18372 static int
18373 eval_isnamec1(c)
18374 int c;
18376 return (ASCII_ISALPHA(c) || c == '_');
18380 * Set number v: variable to "val".
18382 void
18383 set_vim_var_nr(idx, val)
18384 int idx;
18385 long val;
18387 vimvars[idx].vv_nr = val;
18391 * Get number v: variable value.
18393 long
18394 get_vim_var_nr(idx)
18395 int idx;
18397 return vimvars[idx].vv_nr;
18401 * Get string v: variable value. Uses a static buffer, can only be used once.
18403 char_u *
18404 get_vim_var_str(idx)
18405 int idx;
18407 return get_tv_string(&vimvars[idx].vv_tv);
18411 * Get List v: variable value. Caller must take care of reference count when
18412 * needed.
18414 list_T *
18415 get_vim_var_list(idx)
18416 int idx;
18418 return vimvars[idx].vv_list;
18422 * Set v:char to character "c".
18424 void
18425 set_vim_var_char(c)
18426 int c;
18428 #ifdef FEAT_MBYTE
18429 char_u buf[MB_MAXBYTES];
18430 #else
18431 char_u buf[2];
18432 #endif
18434 #ifdef FEAT_MBYTE
18435 if (has_mbyte)
18436 buf[(*mb_char2bytes)(c, buf)] = NUL;
18437 else
18438 #endif
18440 buf[0] = c;
18441 buf[1] = NUL;
18443 set_vim_var_string(VV_CHAR, buf, -1);
18447 * Set v:count to "count" and v:count1 to "count1".
18448 * When "set_prevcount" is TRUE first set v:prevcount from v:count.
18450 void
18451 set_vcount(count, count1, set_prevcount)
18452 long count;
18453 long count1;
18454 int set_prevcount;
18456 if (set_prevcount)
18457 vimvars[VV_PREVCOUNT].vv_nr = vimvars[VV_COUNT].vv_nr;
18458 vimvars[VV_COUNT].vv_nr = count;
18459 vimvars[VV_COUNT1].vv_nr = count1;
18463 * Set string v: variable to a copy of "val".
18465 void
18466 set_vim_var_string(idx, val, len)
18467 int idx;
18468 char_u *val;
18469 int len; /* length of "val" to use or -1 (whole string) */
18471 /* Need to do this (at least) once, since we can't initialize a union.
18472 * Will always be invoked when "v:progname" is set. */
18473 vimvars[VV_VERSION].vv_nr = VIM_VERSION_100;
18475 vim_free(vimvars[idx].vv_str);
18476 if (val == NULL)
18477 vimvars[idx].vv_str = NULL;
18478 else if (len == -1)
18479 vimvars[idx].vv_str = vim_strsave(val);
18480 else
18481 vimvars[idx].vv_str = vim_strnsave(val, len);
18485 * Set List v: variable to "val".
18487 void
18488 set_vim_var_list(idx, val)
18489 int idx;
18490 list_T *val;
18492 list_unref(vimvars[idx].vv_list);
18493 vimvars[idx].vv_list = val;
18494 if (val != NULL)
18495 ++val->lv_refcount;
18499 * Set v:register if needed.
18501 void
18502 set_reg_var(c)
18503 int c;
18505 char_u regname;
18507 if (c == 0 || c == ' ')
18508 regname = '"';
18509 else
18510 regname = c;
18511 /* Avoid free/alloc when the value is already right. */
18512 if (vimvars[VV_REG].vv_str == NULL || vimvars[VV_REG].vv_str[0] != c)
18513 set_vim_var_string(VV_REG, &regname, 1);
18517 * Get or set v:exception. If "oldval" == NULL, return the current value.
18518 * Otherwise, restore the value to "oldval" and return NULL.
18519 * Must always be called in pairs to save and restore v:exception! Does not
18520 * take care of memory allocations.
18522 char_u *
18523 v_exception(oldval)
18524 char_u *oldval;
18526 if (oldval == NULL)
18527 return vimvars[VV_EXCEPTION].vv_str;
18529 vimvars[VV_EXCEPTION].vv_str = oldval;
18530 return NULL;
18534 * Get or set v:throwpoint. If "oldval" == NULL, return the current value.
18535 * Otherwise, restore the value to "oldval" and return NULL.
18536 * Must always be called in pairs to save and restore v:throwpoint! Does not
18537 * take care of memory allocations.
18539 char_u *
18540 v_throwpoint(oldval)
18541 char_u *oldval;
18543 if (oldval == NULL)
18544 return vimvars[VV_THROWPOINT].vv_str;
18546 vimvars[VV_THROWPOINT].vv_str = oldval;
18547 return NULL;
18550 #if defined(FEAT_AUTOCMD) || defined(PROTO)
18552 * Set v:cmdarg.
18553 * If "eap" != NULL, use "eap" to generate the value and return the old value.
18554 * If "oldarg" != NULL, restore the value to "oldarg" and return NULL.
18555 * Must always be called in pairs!
18557 char_u *
18558 set_cmdarg(eap, oldarg)
18559 exarg_T *eap;
18560 char_u *oldarg;
18562 char_u *oldval;
18563 char_u *newval;
18564 unsigned len;
18566 oldval = vimvars[VV_CMDARG].vv_str;
18567 if (eap == NULL)
18569 vim_free(oldval);
18570 vimvars[VV_CMDARG].vv_str = oldarg;
18571 return NULL;
18574 if (eap->force_bin == FORCE_BIN)
18575 len = 6;
18576 else if (eap->force_bin == FORCE_NOBIN)
18577 len = 8;
18578 else
18579 len = 0;
18581 if (eap->read_edit)
18582 len += 7;
18584 if (eap->force_ff != 0)
18585 len += (unsigned)STRLEN(eap->cmd + eap->force_ff) + 6;
18586 # ifdef FEAT_MBYTE
18587 if (eap->force_enc != 0)
18588 len += (unsigned)STRLEN(eap->cmd + eap->force_enc) + 7;
18589 if (eap->bad_char != 0)
18590 len += 7 + 4; /* " ++bad=" + "keep" or "drop" */
18591 # endif
18593 newval = alloc(len + 1);
18594 if (newval == NULL)
18595 return NULL;
18597 if (eap->force_bin == FORCE_BIN)
18598 sprintf((char *)newval, " ++bin");
18599 else if (eap->force_bin == FORCE_NOBIN)
18600 sprintf((char *)newval, " ++nobin");
18601 else
18602 *newval = NUL;
18604 if (eap->read_edit)
18605 STRCAT(newval, " ++edit");
18607 if (eap->force_ff != 0)
18608 sprintf((char *)newval + STRLEN(newval), " ++ff=%s",
18609 eap->cmd + eap->force_ff);
18610 # ifdef FEAT_MBYTE
18611 if (eap->force_enc != 0)
18612 sprintf((char *)newval + STRLEN(newval), " ++enc=%s",
18613 eap->cmd + eap->force_enc);
18614 if (eap->bad_char == BAD_KEEP)
18615 STRCPY(newval + STRLEN(newval), " ++bad=keep");
18616 else if (eap->bad_char == BAD_DROP)
18617 STRCPY(newval + STRLEN(newval), " ++bad=drop");
18618 else if (eap->bad_char != 0)
18619 sprintf((char *)newval + STRLEN(newval), " ++bad=%c", eap->bad_char);
18620 # endif
18621 vimvars[VV_CMDARG].vv_str = newval;
18622 return oldval;
18624 #endif
18627 * Get the value of internal variable "name".
18628 * Return OK or FAIL.
18630 static int
18631 get_var_tv(name, len, rettv, verbose)
18632 char_u *name;
18633 int len; /* length of "name" */
18634 typval_T *rettv; /* NULL when only checking existence */
18635 int verbose; /* may give error message */
18637 int ret = OK;
18638 typval_T *tv = NULL;
18639 typval_T atv;
18640 dictitem_T *v;
18641 int cc;
18643 /* truncate the name, so that we can use strcmp() */
18644 cc = name[len];
18645 name[len] = NUL;
18648 * Check for "b:changedtick".
18650 if (STRCMP(name, "b:changedtick") == 0)
18652 atv.v_type = VAR_NUMBER;
18653 atv.vval.v_number = curbuf->b_changedtick;
18654 tv = &atv;
18658 * Check for user-defined variables.
18660 else
18662 v = find_var(name, NULL);
18663 if (v != NULL)
18664 tv = &v->di_tv;
18667 if (tv == NULL)
18669 if (rettv != NULL && verbose)
18670 EMSG2(_(e_undefvar), name);
18671 ret = FAIL;
18673 else if (rettv != NULL)
18674 copy_tv(tv, rettv);
18676 name[len] = cc;
18678 return ret;
18682 * Handle expr[expr], expr[expr:expr] subscript and .name lookup.
18683 * Also handle function call with Funcref variable: func(expr)
18684 * Can all be combined: dict.func(expr)[idx]['func'](expr)
18686 static int
18687 handle_subscript(arg, rettv, evaluate, verbose)
18688 char_u **arg;
18689 typval_T *rettv;
18690 int evaluate; /* do more than finding the end */
18691 int verbose; /* give error messages */
18693 int ret = OK;
18694 dict_T *selfdict = NULL;
18695 char_u *s;
18696 int len;
18697 typval_T functv;
18699 while (ret == OK
18700 && (**arg == '['
18701 || (**arg == '.' && rettv->v_type == VAR_DICT)
18702 || (**arg == '(' && rettv->v_type == VAR_FUNC))
18703 && !vim_iswhite(*(*arg - 1)))
18705 if (**arg == '(')
18707 /* need to copy the funcref so that we can clear rettv */
18708 functv = *rettv;
18709 rettv->v_type = VAR_UNKNOWN;
18711 /* Invoke the function. Recursive! */
18712 s = functv.vval.v_string;
18713 ret = get_func_tv(s, (int)STRLEN(s), rettv, arg,
18714 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
18715 &len, evaluate, selfdict);
18717 /* Clear the funcref afterwards, so that deleting it while
18718 * evaluating the arguments is possible (see test55). */
18719 clear_tv(&functv);
18721 /* Stop the expression evaluation when immediately aborting on
18722 * error, or when an interrupt occurred or an exception was thrown
18723 * but not caught. */
18724 if (aborting())
18726 if (ret == OK)
18727 clear_tv(rettv);
18728 ret = FAIL;
18730 dict_unref(selfdict);
18731 selfdict = NULL;
18733 else /* **arg == '[' || **arg == '.' */
18735 dict_unref(selfdict);
18736 if (rettv->v_type == VAR_DICT)
18738 selfdict = rettv->vval.v_dict;
18739 if (selfdict != NULL)
18740 ++selfdict->dv_refcount;
18742 else
18743 selfdict = NULL;
18744 if (eval_index(arg, rettv, evaluate, verbose) == FAIL)
18746 clear_tv(rettv);
18747 ret = FAIL;
18751 dict_unref(selfdict);
18752 return ret;
18756 * Allocate memory for a variable type-value, and make it empty (0 or NULL
18757 * value).
18759 static typval_T *
18760 alloc_tv()
18762 return (typval_T *)alloc_clear((unsigned)sizeof(typval_T));
18766 * Allocate memory for a variable type-value, and assign a string to it.
18767 * The string "s" must have been allocated, it is consumed.
18768 * Return NULL for out of memory, the variable otherwise.
18770 static typval_T *
18771 alloc_string_tv(s)
18772 char_u *s;
18774 typval_T *rettv;
18776 rettv = alloc_tv();
18777 if (rettv != NULL)
18779 rettv->v_type = VAR_STRING;
18780 rettv->vval.v_string = s;
18782 else
18783 vim_free(s);
18784 return rettv;
18788 * Free the memory for a variable type-value.
18790 void
18791 free_tv(varp)
18792 typval_T *varp;
18794 if (varp != NULL)
18796 switch (varp->v_type)
18798 case VAR_FUNC:
18799 func_unref(varp->vval.v_string);
18800 /*FALLTHROUGH*/
18801 case VAR_STRING:
18802 vim_free(varp->vval.v_string);
18803 break;
18804 case VAR_LIST:
18805 list_unref(varp->vval.v_list);
18806 break;
18807 case VAR_DICT:
18808 dict_unref(varp->vval.v_dict);
18809 break;
18810 case VAR_NUMBER:
18811 #ifdef FEAT_FLOAT
18812 case VAR_FLOAT:
18813 #endif
18814 case VAR_UNKNOWN:
18815 break;
18816 default:
18817 EMSG2(_(e_intern2), "free_tv()");
18818 break;
18820 vim_free(varp);
18825 * Free the memory for a variable value and set the value to NULL or 0.
18827 void
18828 clear_tv(varp)
18829 typval_T *varp;
18831 if (varp != NULL)
18833 switch (varp->v_type)
18835 case VAR_FUNC:
18836 func_unref(varp->vval.v_string);
18837 /*FALLTHROUGH*/
18838 case VAR_STRING:
18839 vim_free(varp->vval.v_string);
18840 varp->vval.v_string = NULL;
18841 break;
18842 case VAR_LIST:
18843 list_unref(varp->vval.v_list);
18844 varp->vval.v_list = NULL;
18845 break;
18846 case VAR_DICT:
18847 dict_unref(varp->vval.v_dict);
18848 varp->vval.v_dict = NULL;
18849 break;
18850 case VAR_NUMBER:
18851 varp->vval.v_number = 0;
18852 break;
18853 #ifdef FEAT_FLOAT
18854 case VAR_FLOAT:
18855 varp->vval.v_float = 0.0;
18856 break;
18857 #endif
18858 case VAR_UNKNOWN:
18859 break;
18860 default:
18861 EMSG2(_(e_intern2), "clear_tv()");
18863 varp->v_lock = 0;
18868 * Set the value of a variable to NULL without freeing items.
18870 static void
18871 init_tv(varp)
18872 typval_T *varp;
18874 if (varp != NULL)
18875 vim_memset(varp, 0, sizeof(typval_T));
18879 * Get the number value of a variable.
18880 * If it is a String variable, uses vim_str2nr().
18881 * For incompatible types, return 0.
18882 * get_tv_number_chk() is similar to get_tv_number(), but informs the
18883 * caller of incompatible types: it sets *denote to TRUE if "denote"
18884 * is not NULL or returns -1 otherwise.
18886 static long
18887 get_tv_number(varp)
18888 typval_T *varp;
18890 int error = FALSE;
18892 return get_tv_number_chk(varp, &error); /* return 0L on error */
18895 long
18896 get_tv_number_chk(varp, denote)
18897 typval_T *varp;
18898 int *denote;
18900 long n = 0L;
18902 switch (varp->v_type)
18904 case VAR_NUMBER:
18905 return (long)(varp->vval.v_number);
18906 #ifdef FEAT_FLOAT
18907 case VAR_FLOAT:
18908 EMSG(_("E805: Using a Float as a Number"));
18909 break;
18910 #endif
18911 case VAR_FUNC:
18912 EMSG(_("E703: Using a Funcref as a Number"));
18913 break;
18914 case VAR_STRING:
18915 if (varp->vval.v_string != NULL)
18916 vim_str2nr(varp->vval.v_string, NULL, NULL,
18917 TRUE, TRUE, &n, NULL);
18918 return n;
18919 case VAR_LIST:
18920 EMSG(_("E745: Using a List as a Number"));
18921 break;
18922 case VAR_DICT:
18923 EMSG(_("E728: Using a Dictionary as a Number"));
18924 break;
18925 default:
18926 EMSG2(_(e_intern2), "get_tv_number()");
18927 break;
18929 if (denote == NULL) /* useful for values that must be unsigned */
18930 n = -1;
18931 else
18932 *denote = TRUE;
18933 return n;
18937 * Get the lnum from the first argument.
18938 * Also accepts ".", "$", etc., but that only works for the current buffer.
18939 * Returns -1 on error.
18941 static linenr_T
18942 get_tv_lnum(argvars)
18943 typval_T *argvars;
18945 typval_T rettv;
18946 linenr_T lnum;
18948 lnum = get_tv_number_chk(&argvars[0], NULL);
18949 if (lnum == 0) /* no valid number, try using line() */
18951 rettv.v_type = VAR_NUMBER;
18952 f_line(argvars, &rettv);
18953 lnum = rettv.vval.v_number;
18954 clear_tv(&rettv);
18956 return lnum;
18960 * Get the lnum from the first argument.
18961 * Also accepts "$", then "buf" is used.
18962 * Returns 0 on error.
18964 static linenr_T
18965 get_tv_lnum_buf(argvars, buf)
18966 typval_T *argvars;
18967 buf_T *buf;
18969 if (argvars[0].v_type == VAR_STRING
18970 && argvars[0].vval.v_string != NULL
18971 && argvars[0].vval.v_string[0] == '$'
18972 && buf != NULL)
18973 return buf->b_ml.ml_line_count;
18974 return get_tv_number_chk(&argvars[0], NULL);
18978 * Get the string value of a variable.
18979 * If it is a Number variable, the number is converted into a string.
18980 * get_tv_string() uses a single, static buffer. YOU CAN ONLY USE IT ONCE!
18981 * get_tv_string_buf() uses a given buffer.
18982 * If the String variable has never been set, return an empty string.
18983 * Never returns NULL;
18984 * get_tv_string_chk() and get_tv_string_buf_chk() are similar, but return
18985 * NULL on error.
18987 static char_u *
18988 get_tv_string(varp)
18989 typval_T *varp;
18991 static char_u mybuf[NUMBUFLEN];
18993 return get_tv_string_buf(varp, mybuf);
18996 static char_u *
18997 get_tv_string_buf(varp, buf)
18998 typval_T *varp;
18999 char_u *buf;
19001 char_u *res = get_tv_string_buf_chk(varp, buf);
19003 return res != NULL ? res : (char_u *)"";
19006 char_u *
19007 get_tv_string_chk(varp)
19008 typval_T *varp;
19010 static char_u mybuf[NUMBUFLEN];
19012 return get_tv_string_buf_chk(varp, mybuf);
19015 static char_u *
19016 get_tv_string_buf_chk(varp, buf)
19017 typval_T *varp;
19018 char_u *buf;
19020 switch (varp->v_type)
19022 case VAR_NUMBER:
19023 sprintf((char *)buf, "%ld", (long)varp->vval.v_number);
19024 return buf;
19025 case VAR_FUNC:
19026 EMSG(_("E729: using Funcref as a String"));
19027 break;
19028 case VAR_LIST:
19029 EMSG(_("E730: using List as a String"));
19030 break;
19031 case VAR_DICT:
19032 EMSG(_("E731: using Dictionary as a String"));
19033 break;
19034 #ifdef FEAT_FLOAT
19035 case VAR_FLOAT:
19036 EMSG(_("E806: using Float as a String"));
19037 break;
19038 #endif
19039 case VAR_STRING:
19040 if (varp->vval.v_string != NULL)
19041 return varp->vval.v_string;
19042 return (char_u *)"";
19043 default:
19044 EMSG2(_(e_intern2), "get_tv_string_buf()");
19045 break;
19047 return NULL;
19051 * Find variable "name" in the list of variables.
19052 * Return a pointer to it if found, NULL if not found.
19053 * Careful: "a:0" variables don't have a name.
19054 * When "htp" is not NULL we are writing to the variable, set "htp" to the
19055 * hashtab_T used.
19057 static dictitem_T *
19058 find_var(name, htp)
19059 char_u *name;
19060 hashtab_T **htp;
19062 char_u *varname;
19063 hashtab_T *ht;
19065 ht = find_var_ht(name, &varname);
19066 if (htp != NULL)
19067 *htp = ht;
19068 if (ht == NULL)
19069 return NULL;
19070 return find_var_in_ht(ht, varname, htp != NULL);
19074 * Find variable "varname" in hashtab "ht".
19075 * Returns NULL if not found.
19077 static dictitem_T *
19078 find_var_in_ht(ht, varname, writing)
19079 hashtab_T *ht;
19080 char_u *varname;
19081 int writing;
19083 hashitem_T *hi;
19085 if (*varname == NUL)
19087 /* Must be something like "s:", otherwise "ht" would be NULL. */
19088 switch (varname[-2])
19090 case 's': return &SCRIPT_SV(current_SID)->sv_var;
19091 case 'g': return &globvars_var;
19092 case 'v': return &vimvars_var;
19093 case 'b': return &curbuf->b_bufvar;
19094 case 'w': return &curwin->w_winvar;
19095 #ifdef FEAT_WINDOWS
19096 case 't': return &curtab->tp_winvar;
19097 #endif
19098 case 'l': return current_funccal == NULL
19099 ? NULL : &current_funccal->l_vars_var;
19100 case 'a': return current_funccal == NULL
19101 ? NULL : &current_funccal->l_avars_var;
19103 return NULL;
19106 hi = hash_find(ht, varname);
19107 if (HASHITEM_EMPTY(hi))
19109 /* For global variables we may try auto-loading the script. If it
19110 * worked find the variable again. Don't auto-load a script if it was
19111 * loaded already, otherwise it would be loaded every time when
19112 * checking if a function name is a Funcref variable. */
19113 if (ht == &globvarht && !writing
19114 && script_autoload(varname, FALSE) && !aborting())
19115 hi = hash_find(ht, varname);
19116 if (HASHITEM_EMPTY(hi))
19117 return NULL;
19119 return HI2DI(hi);
19123 * Find the hashtab used for a variable name.
19124 * Set "varname" to the start of name without ':'.
19126 static hashtab_T *
19127 find_var_ht(name, varname)
19128 char_u *name;
19129 char_u **varname;
19131 hashitem_T *hi;
19133 if (name[1] != ':')
19135 /* The name must not start with a colon or #. */
19136 if (name[0] == ':' || name[0] == AUTOLOAD_CHAR)
19137 return NULL;
19138 *varname = name;
19140 /* "version" is "v:version" in all scopes */
19141 hi = hash_find(&compat_hashtab, name);
19142 if (!HASHITEM_EMPTY(hi))
19143 return &compat_hashtab;
19145 if (current_funccal == NULL)
19146 return &globvarht; /* global variable */
19147 return &current_funccal->l_vars.dv_hashtab; /* l: variable */
19149 *varname = name + 2;
19150 if (*name == 'g') /* global variable */
19151 return &globvarht;
19152 /* There must be no ':' or '#' in the rest of the name, unless g: is used
19154 if (vim_strchr(name + 2, ':') != NULL
19155 || vim_strchr(name + 2, AUTOLOAD_CHAR) != NULL)
19156 return NULL;
19157 if (*name == 'b') /* buffer variable */
19158 return &curbuf->b_vars.dv_hashtab;
19159 if (*name == 'w') /* window variable */
19160 return &curwin->w_vars.dv_hashtab;
19161 #ifdef FEAT_WINDOWS
19162 if (*name == 't') /* tab page variable */
19163 return &curtab->tp_vars.dv_hashtab;
19164 #endif
19165 if (*name == 'v') /* v: variable */
19166 return &vimvarht;
19167 if (*name == 'a' && current_funccal != NULL) /* function argument */
19168 return &current_funccal->l_avars.dv_hashtab;
19169 if (*name == 'l' && current_funccal != NULL) /* local function variable */
19170 return &current_funccal->l_vars.dv_hashtab;
19171 if (*name == 's' /* script variable */
19172 && current_SID > 0 && current_SID <= ga_scripts.ga_len)
19173 return &SCRIPT_VARS(current_SID);
19174 return NULL;
19178 * Get the string value of a (global/local) variable.
19179 * Returns NULL when it doesn't exist.
19181 char_u *
19182 get_var_value(name)
19183 char_u *name;
19185 dictitem_T *v;
19187 v = find_var(name, NULL);
19188 if (v == NULL)
19189 return NULL;
19190 return get_tv_string(&v->di_tv);
19194 * Allocate a new hashtab for a sourced script. It will be used while
19195 * sourcing this script and when executing functions defined in the script.
19197 void
19198 new_script_vars(id)
19199 scid_T id;
19201 int i;
19202 hashtab_T *ht;
19203 scriptvar_T *sv;
19205 if (ga_grow(&ga_scripts, (int)(id - ga_scripts.ga_len)) == OK)
19207 /* Re-allocating ga_data means that an ht_array pointing to
19208 * ht_smallarray becomes invalid. We can recognize this: ht_mask is
19209 * at its init value. Also reset "v_dict", it's always the same. */
19210 for (i = 1; i <= ga_scripts.ga_len; ++i)
19212 ht = &SCRIPT_VARS(i);
19213 if (ht->ht_mask == HT_INIT_SIZE - 1)
19214 ht->ht_array = ht->ht_smallarray;
19215 sv = SCRIPT_SV(i);
19216 sv->sv_var.di_tv.vval.v_dict = &sv->sv_dict;
19219 while (ga_scripts.ga_len < id)
19221 sv = SCRIPT_SV(ga_scripts.ga_len + 1) =
19222 (scriptvar_T *)alloc_clear(sizeof(scriptvar_T));
19223 init_var_dict(&sv->sv_dict, &sv->sv_var);
19224 ++ga_scripts.ga_len;
19230 * Initialize dictionary "dict" as a scope and set variable "dict_var" to
19231 * point to it.
19233 void
19234 init_var_dict(dict, dict_var)
19235 dict_T *dict;
19236 dictitem_T *dict_var;
19238 hash_init(&dict->dv_hashtab);
19239 dict->dv_refcount = DO_NOT_FREE_CNT;
19240 dict->dv_copyID = 0;
19241 dict_var->di_tv.vval.v_dict = dict;
19242 dict_var->di_tv.v_type = VAR_DICT;
19243 dict_var->di_tv.v_lock = VAR_FIXED;
19244 dict_var->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
19245 dict_var->di_key[0] = NUL;
19249 * Clean up a list of internal variables.
19250 * Frees all allocated variables and the value they contain.
19251 * Clears hashtab "ht", does not free it.
19253 void
19254 vars_clear(ht)
19255 hashtab_T *ht;
19257 vars_clear_ext(ht, TRUE);
19261 * Like vars_clear(), but only free the value if "free_val" is TRUE.
19263 static void
19264 vars_clear_ext(ht, free_val)
19265 hashtab_T *ht;
19266 int free_val;
19268 int todo;
19269 hashitem_T *hi;
19270 dictitem_T *v;
19272 hash_lock(ht);
19273 todo = (int)ht->ht_used;
19274 for (hi = ht->ht_array; todo > 0; ++hi)
19276 if (!HASHITEM_EMPTY(hi))
19278 --todo;
19280 /* Free the variable. Don't remove it from the hashtab,
19281 * ht_array might change then. hash_clear() takes care of it
19282 * later. */
19283 v = HI2DI(hi);
19284 if (free_val)
19285 clear_tv(&v->di_tv);
19286 if ((v->di_flags & DI_FLAGS_FIX) == 0)
19287 vim_free(v);
19290 hash_clear(ht);
19291 ht->ht_used = 0;
19295 * Delete a variable from hashtab "ht" at item "hi".
19296 * Clear the variable value and free the dictitem.
19298 static void
19299 delete_var(ht, hi)
19300 hashtab_T *ht;
19301 hashitem_T *hi;
19303 dictitem_T *di = HI2DI(hi);
19305 hash_remove(ht, hi);
19306 clear_tv(&di->di_tv);
19307 vim_free(di);
19311 * List the value of one internal variable.
19313 static void
19314 list_one_var(v, prefix, first)
19315 dictitem_T *v;
19316 char_u *prefix;
19317 int *first;
19319 char_u *tofree;
19320 char_u *s;
19321 char_u numbuf[NUMBUFLEN];
19323 current_copyID += COPYID_INC;
19324 s = echo_string(&v->di_tv, &tofree, numbuf, current_copyID);
19325 list_one_var_a(prefix, v->di_key, v->di_tv.v_type,
19326 s == NULL ? (char_u *)"" : s, first);
19327 vim_free(tofree);
19330 static void
19331 list_one_var_a(prefix, name, type, string, first)
19332 char_u *prefix;
19333 char_u *name;
19334 int type;
19335 char_u *string;
19336 int *first; /* when TRUE clear rest of screen and set to FALSE */
19338 /* don't use msg() or msg_attr() to avoid overwriting "v:statusmsg" */
19339 msg_start();
19340 msg_puts(prefix);
19341 if (name != NULL) /* "a:" vars don't have a name stored */
19342 msg_puts(name);
19343 msg_putchar(' ');
19344 msg_advance(22);
19345 if (type == VAR_NUMBER)
19346 msg_putchar('#');
19347 else if (type == VAR_FUNC)
19348 msg_putchar('*');
19349 else if (type == VAR_LIST)
19351 msg_putchar('[');
19352 if (*string == '[')
19353 ++string;
19355 else if (type == VAR_DICT)
19357 msg_putchar('{');
19358 if (*string == '{')
19359 ++string;
19361 else
19362 msg_putchar(' ');
19364 msg_outtrans(string);
19366 if (type == VAR_FUNC)
19367 msg_puts((char_u *)"()");
19368 if (*first)
19370 msg_clr_eos();
19371 *first = FALSE;
19376 * Set variable "name" to value in "tv".
19377 * If the variable already exists, the value is updated.
19378 * Otherwise the variable is created.
19380 static void
19381 set_var(name, tv, copy)
19382 char_u *name;
19383 typval_T *tv;
19384 int copy; /* make copy of value in "tv" */
19386 dictitem_T *v;
19387 char_u *varname;
19388 hashtab_T *ht;
19389 char_u *p;
19391 ht = find_var_ht(name, &varname);
19392 if (ht == NULL || *varname == NUL)
19394 EMSG2(_(e_illvar), name);
19395 return;
19397 v = find_var_in_ht(ht, varname, TRUE);
19399 if (tv->v_type == VAR_FUNC)
19401 if (!(vim_strchr((char_u *)"wbs", name[0]) != NULL && name[1] == ':')
19402 && !ASCII_ISUPPER((name[0] != NUL && name[1] == ':')
19403 ? name[2] : name[0]))
19405 EMSG2(_("E704: Funcref variable name must start with a capital: %s"), name);
19406 return;
19408 /* Don't allow hiding a function. When "v" is not NULL we migth be
19409 * assigning another function to the same var, the type is checked
19410 * below. */
19411 if (v == NULL && function_exists(name))
19413 EMSG2(_("E705: Variable name conflicts with existing function: %s"),
19414 name);
19415 return;
19419 if (v != NULL)
19421 /* existing variable, need to clear the value */
19422 if (var_check_ro(v->di_flags, name)
19423 || tv_check_lock(v->di_tv.v_lock, name))
19424 return;
19425 if (v->di_tv.v_type != tv->v_type
19426 && !((v->di_tv.v_type == VAR_STRING
19427 || v->di_tv.v_type == VAR_NUMBER)
19428 && (tv->v_type == VAR_STRING
19429 || tv->v_type == VAR_NUMBER))
19430 #ifdef FEAT_FLOAT
19431 && !((v->di_tv.v_type == VAR_NUMBER
19432 || v->di_tv.v_type == VAR_FLOAT)
19433 && (tv->v_type == VAR_NUMBER
19434 || tv->v_type == VAR_FLOAT))
19435 #endif
19438 EMSG2(_("E706: Variable type mismatch for: %s"), name);
19439 return;
19443 * Handle setting internal v: variables separately: we don't change
19444 * the type.
19446 if (ht == &vimvarht)
19448 if (v->di_tv.v_type == VAR_STRING)
19450 vim_free(v->di_tv.vval.v_string);
19451 if (copy || tv->v_type != VAR_STRING)
19452 v->di_tv.vval.v_string = vim_strsave(get_tv_string(tv));
19453 else
19455 /* Take over the string to avoid an extra alloc/free. */
19456 v->di_tv.vval.v_string = tv->vval.v_string;
19457 tv->vval.v_string = NULL;
19460 else if (v->di_tv.v_type != VAR_NUMBER)
19461 EMSG2(_(e_intern2), "set_var()");
19462 else
19464 v->di_tv.vval.v_number = get_tv_number(tv);
19465 if (STRCMP(varname, "searchforward") == 0)
19466 set_search_direction(v->di_tv.vval.v_number ? '/' : '?');
19468 return;
19471 clear_tv(&v->di_tv);
19473 else /* add a new variable */
19475 /* Can't add "v:" variable. */
19476 if (ht == &vimvarht)
19478 EMSG2(_(e_illvar), name);
19479 return;
19482 /* Make sure the variable name is valid. */
19483 for (p = varname; *p != NUL; ++p)
19484 if (!eval_isnamec1(*p) && (p == varname || !VIM_ISDIGIT(*p))
19485 && *p != AUTOLOAD_CHAR)
19487 EMSG2(_(e_illvar), varname);
19488 return;
19491 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
19492 + STRLEN(varname)));
19493 if (v == NULL)
19494 return;
19495 STRCPY(v->di_key, varname);
19496 if (hash_add(ht, DI2HIKEY(v)) == FAIL)
19498 vim_free(v);
19499 return;
19501 v->di_flags = 0;
19504 if (copy || tv->v_type == VAR_NUMBER || tv->v_type == VAR_FLOAT)
19505 copy_tv(tv, &v->di_tv);
19506 else
19508 v->di_tv = *tv;
19509 v->di_tv.v_lock = 0;
19510 init_tv(tv);
19515 * Return TRUE if di_flags "flags" indicates variable "name" is read-only.
19516 * Also give an error message.
19518 static int
19519 var_check_ro(flags, name)
19520 int flags;
19521 char_u *name;
19523 if (flags & DI_FLAGS_RO)
19525 EMSG2(_(e_readonlyvar), name);
19526 return TRUE;
19528 if ((flags & DI_FLAGS_RO_SBX) && sandbox)
19530 EMSG2(_(e_readonlysbx), name);
19531 return TRUE;
19533 return FALSE;
19537 * Return TRUE if di_flags "flags" indicates variable "name" is fixed.
19538 * Also give an error message.
19540 static int
19541 var_check_fixed(flags, name)
19542 int flags;
19543 char_u *name;
19545 if (flags & DI_FLAGS_FIX)
19547 EMSG2(_("E795: Cannot delete variable %s"), name);
19548 return TRUE;
19550 return FALSE;
19554 * Return TRUE if typeval "tv" is set to be locked (immutable).
19555 * Also give an error message, using "name".
19557 static int
19558 tv_check_lock(lock, name)
19559 int lock;
19560 char_u *name;
19562 if (lock & VAR_LOCKED)
19564 EMSG2(_("E741: Value is locked: %s"),
19565 name == NULL ? (char_u *)_("Unknown") : name);
19566 return TRUE;
19568 if (lock & VAR_FIXED)
19570 EMSG2(_("E742: Cannot change value of %s"),
19571 name == NULL ? (char_u *)_("Unknown") : name);
19572 return TRUE;
19574 return FALSE;
19578 * Copy the values from typval_T "from" to typval_T "to".
19579 * When needed allocates string or increases reference count.
19580 * Does not make a copy of a list or dict but copies the reference!
19581 * It is OK for "from" and "to" to point to the same item. This is used to
19582 * make a copy later.
19584 void
19585 copy_tv(from, to)
19586 typval_T *from;
19587 typval_T *to;
19589 to->v_type = from->v_type;
19590 to->v_lock = 0;
19591 switch (from->v_type)
19593 case VAR_NUMBER:
19594 to->vval.v_number = from->vval.v_number;
19595 break;
19596 #ifdef FEAT_FLOAT
19597 case VAR_FLOAT:
19598 to->vval.v_float = from->vval.v_float;
19599 break;
19600 #endif
19601 case VAR_STRING:
19602 case VAR_FUNC:
19603 if (from->vval.v_string == NULL)
19604 to->vval.v_string = NULL;
19605 else
19607 to->vval.v_string = vim_strsave(from->vval.v_string);
19608 if (from->v_type == VAR_FUNC)
19609 func_ref(to->vval.v_string);
19611 break;
19612 case VAR_LIST:
19613 if (from->vval.v_list == NULL)
19614 to->vval.v_list = NULL;
19615 else
19617 to->vval.v_list = from->vval.v_list;
19618 ++to->vval.v_list->lv_refcount;
19620 break;
19621 case VAR_DICT:
19622 if (from->vval.v_dict == NULL)
19623 to->vval.v_dict = NULL;
19624 else
19626 to->vval.v_dict = from->vval.v_dict;
19627 ++to->vval.v_dict->dv_refcount;
19629 break;
19630 default:
19631 EMSG2(_(e_intern2), "copy_tv()");
19632 break;
19637 * Make a copy of an item.
19638 * Lists and Dictionaries are also copied. A deep copy if "deep" is set.
19639 * For deepcopy() "copyID" is zero for a full copy or the ID for when a
19640 * reference to an already copied list/dict can be used.
19641 * Returns FAIL or OK.
19643 static int
19644 item_copy(from, to, deep, copyID)
19645 typval_T *from;
19646 typval_T *to;
19647 int deep;
19648 int copyID;
19650 static int recurse = 0;
19651 int ret = OK;
19653 if (recurse >= DICT_MAXNEST)
19655 EMSG(_("E698: variable nested too deep for making a copy"));
19656 return FAIL;
19658 ++recurse;
19660 switch (from->v_type)
19662 case VAR_NUMBER:
19663 #ifdef FEAT_FLOAT
19664 case VAR_FLOAT:
19665 #endif
19666 case VAR_STRING:
19667 case VAR_FUNC:
19668 copy_tv(from, to);
19669 break;
19670 case VAR_LIST:
19671 to->v_type = VAR_LIST;
19672 to->v_lock = 0;
19673 if (from->vval.v_list == NULL)
19674 to->vval.v_list = NULL;
19675 else if (copyID != 0 && from->vval.v_list->lv_copyID == copyID)
19677 /* use the copy made earlier */
19678 to->vval.v_list = from->vval.v_list->lv_copylist;
19679 ++to->vval.v_list->lv_refcount;
19681 else
19682 to->vval.v_list = list_copy(from->vval.v_list, deep, copyID);
19683 if (to->vval.v_list == NULL)
19684 ret = FAIL;
19685 break;
19686 case VAR_DICT:
19687 to->v_type = VAR_DICT;
19688 to->v_lock = 0;
19689 if (from->vval.v_dict == NULL)
19690 to->vval.v_dict = NULL;
19691 else if (copyID != 0 && from->vval.v_dict->dv_copyID == copyID)
19693 /* use the copy made earlier */
19694 to->vval.v_dict = from->vval.v_dict->dv_copydict;
19695 ++to->vval.v_dict->dv_refcount;
19697 else
19698 to->vval.v_dict = dict_copy(from->vval.v_dict, deep, copyID);
19699 if (to->vval.v_dict == NULL)
19700 ret = FAIL;
19701 break;
19702 default:
19703 EMSG2(_(e_intern2), "item_copy()");
19704 ret = FAIL;
19706 --recurse;
19707 return ret;
19711 * ":echo expr1 ..." print each argument separated with a space, add a
19712 * newline at the end.
19713 * ":echon expr1 ..." print each argument plain.
19715 void
19716 ex_echo(eap)
19717 exarg_T *eap;
19719 char_u *arg = eap->arg;
19720 typval_T rettv;
19721 char_u *tofree;
19722 char_u *p;
19723 int needclr = TRUE;
19724 int atstart = TRUE;
19725 char_u numbuf[NUMBUFLEN];
19727 if (eap->skip)
19728 ++emsg_skip;
19729 while (*arg != NUL && *arg != '|' && *arg != '\n' && !got_int)
19731 /* If eval1() causes an error message the text from the command may
19732 * still need to be cleared. E.g., "echo 22,44". */
19733 need_clr_eos = needclr;
19735 p = arg;
19736 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
19739 * Report the invalid expression unless the expression evaluation
19740 * has been cancelled due to an aborting error, an interrupt, or an
19741 * exception.
19743 if (!aborting())
19744 EMSG2(_(e_invexpr2), p);
19745 need_clr_eos = FALSE;
19746 break;
19748 need_clr_eos = FALSE;
19750 if (!eap->skip)
19752 if (atstart)
19754 atstart = FALSE;
19755 /* Call msg_start() after eval1(), evaluating the expression
19756 * may cause a message to appear. */
19757 if (eap->cmdidx == CMD_echo)
19758 msg_start();
19760 else if (eap->cmdidx == CMD_echo)
19761 msg_puts_attr((char_u *)" ", echo_attr);
19762 current_copyID += COPYID_INC;
19763 p = echo_string(&rettv, &tofree, numbuf, current_copyID);
19764 if (p != NULL)
19765 for ( ; *p != NUL && !got_int; ++p)
19767 if (*p == '\n' || *p == '\r' || *p == TAB)
19769 if (*p != TAB && needclr)
19771 /* remove any text still there from the command */
19772 msg_clr_eos();
19773 needclr = FALSE;
19775 msg_putchar_attr(*p, echo_attr);
19777 else
19779 #ifdef FEAT_MBYTE
19780 if (has_mbyte)
19782 int i = (*mb_ptr2len)(p);
19784 (void)msg_outtrans_len_attr(p, i, echo_attr);
19785 p += i - 1;
19787 else
19788 #endif
19789 (void)msg_outtrans_len_attr(p, 1, echo_attr);
19792 vim_free(tofree);
19794 clear_tv(&rettv);
19795 arg = skipwhite(arg);
19797 eap->nextcmd = check_nextcmd(arg);
19799 if (eap->skip)
19800 --emsg_skip;
19801 else
19803 /* remove text that may still be there from the command */
19804 if (needclr)
19805 msg_clr_eos();
19806 if (eap->cmdidx == CMD_echo)
19807 msg_end();
19812 * ":echohl {name}".
19814 void
19815 ex_echohl(eap)
19816 exarg_T *eap;
19818 int id;
19820 id = syn_name2id(eap->arg);
19821 if (id == 0)
19822 echo_attr = 0;
19823 else
19824 echo_attr = syn_id2attr(id);
19828 * ":execute expr1 ..." execute the result of an expression.
19829 * ":echomsg expr1 ..." Print a message
19830 * ":echoerr expr1 ..." Print an error
19831 * Each gets spaces around each argument and a newline at the end for
19832 * echo commands
19834 void
19835 ex_execute(eap)
19836 exarg_T *eap;
19838 char_u *arg = eap->arg;
19839 typval_T rettv;
19840 int ret = OK;
19841 char_u *p;
19842 garray_T ga;
19843 int len;
19844 int save_did_emsg;
19846 ga_init2(&ga, 1, 80);
19848 if (eap->skip)
19849 ++emsg_skip;
19850 while (*arg != NUL && *arg != '|' && *arg != '\n')
19852 p = arg;
19853 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
19856 * Report the invalid expression unless the expression evaluation
19857 * has been cancelled due to an aborting error, an interrupt, or an
19858 * exception.
19860 if (!aborting())
19861 EMSG2(_(e_invexpr2), p);
19862 ret = FAIL;
19863 break;
19866 if (!eap->skip)
19868 p = get_tv_string(&rettv);
19869 len = (int)STRLEN(p);
19870 if (ga_grow(&ga, len + 2) == FAIL)
19872 clear_tv(&rettv);
19873 ret = FAIL;
19874 break;
19876 if (ga.ga_len)
19877 ((char_u *)(ga.ga_data))[ga.ga_len++] = ' ';
19878 STRCPY((char_u *)(ga.ga_data) + ga.ga_len, p);
19879 ga.ga_len += len;
19882 clear_tv(&rettv);
19883 arg = skipwhite(arg);
19886 if (ret != FAIL && ga.ga_data != NULL)
19888 if (eap->cmdidx == CMD_echomsg)
19890 MSG_ATTR(ga.ga_data, echo_attr);
19891 out_flush();
19893 else if (eap->cmdidx == CMD_echoerr)
19895 /* We don't want to abort following commands, restore did_emsg. */
19896 save_did_emsg = did_emsg;
19897 EMSG((char_u *)ga.ga_data);
19898 if (!force_abort)
19899 did_emsg = save_did_emsg;
19901 else if (eap->cmdidx == CMD_execute)
19902 do_cmdline((char_u *)ga.ga_data,
19903 eap->getline, eap->cookie, DOCMD_NOWAIT|DOCMD_VERBOSE);
19906 ga_clear(&ga);
19908 if (eap->skip)
19909 --emsg_skip;
19911 eap->nextcmd = check_nextcmd(arg);
19915 * Skip over the name of an option: "&option", "&g:option" or "&l:option".
19916 * "arg" points to the "&" or '+' when called, to "option" when returning.
19917 * Returns NULL when no option name found. Otherwise pointer to the char
19918 * after the option name.
19920 static char_u *
19921 find_option_end(arg, opt_flags)
19922 char_u **arg;
19923 int *opt_flags;
19925 char_u *p = *arg;
19927 ++p;
19928 if (*p == 'g' && p[1] == ':')
19930 *opt_flags = OPT_GLOBAL;
19931 p += 2;
19933 else if (*p == 'l' && p[1] == ':')
19935 *opt_flags = OPT_LOCAL;
19936 p += 2;
19938 else
19939 *opt_flags = 0;
19941 if (!ASCII_ISALPHA(*p))
19942 return NULL;
19943 *arg = p;
19945 if (p[0] == 't' && p[1] == '_' && p[2] != NUL && p[3] != NUL)
19946 p += 4; /* termcap option */
19947 else
19948 while (ASCII_ISALPHA(*p))
19949 ++p;
19950 return p;
19954 * ":function"
19956 void
19957 ex_function(eap)
19958 exarg_T *eap;
19960 char_u *theline;
19961 int j;
19962 int c;
19963 int saved_did_emsg;
19964 char_u *name = NULL;
19965 char_u *p;
19966 char_u *arg;
19967 char_u *line_arg = NULL;
19968 garray_T newargs;
19969 garray_T newlines;
19970 int varargs = FALSE;
19971 int mustend = FALSE;
19972 int flags = 0;
19973 ufunc_T *fp;
19974 int indent;
19975 int nesting;
19976 char_u *skip_until = NULL;
19977 dictitem_T *v;
19978 funcdict_T fudi;
19979 static int func_nr = 0; /* number for nameless function */
19980 int paren;
19981 hashtab_T *ht;
19982 int todo;
19983 hashitem_T *hi;
19984 int sourcing_lnum_off;
19987 * ":function" without argument: list functions.
19989 if (ends_excmd(*eap->arg))
19991 if (!eap->skip)
19993 todo = (int)func_hashtab.ht_used;
19994 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
19996 if (!HASHITEM_EMPTY(hi))
19998 --todo;
19999 fp = HI2UF(hi);
20000 if (!isdigit(*fp->uf_name))
20001 list_func_head(fp, FALSE);
20005 eap->nextcmd = check_nextcmd(eap->arg);
20006 return;
20010 * ":function /pat": list functions matching pattern.
20012 if (*eap->arg == '/')
20014 p = skip_regexp(eap->arg + 1, '/', TRUE, NULL);
20015 if (!eap->skip)
20017 regmatch_T regmatch;
20019 c = *p;
20020 *p = NUL;
20021 regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC);
20022 *p = c;
20023 if (regmatch.regprog != NULL)
20025 regmatch.rm_ic = p_ic;
20027 todo = (int)func_hashtab.ht_used;
20028 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
20030 if (!HASHITEM_EMPTY(hi))
20032 --todo;
20033 fp = HI2UF(hi);
20034 if (!isdigit(*fp->uf_name)
20035 && vim_regexec(&regmatch, fp->uf_name, 0))
20036 list_func_head(fp, FALSE);
20039 vim_free(regmatch.regprog);
20042 if (*p == '/')
20043 ++p;
20044 eap->nextcmd = check_nextcmd(p);
20045 return;
20049 * Get the function name. There are these situations:
20050 * func normal function name
20051 * "name" == func, "fudi.fd_dict" == NULL
20052 * dict.func new dictionary entry
20053 * "name" == NULL, "fudi.fd_dict" set,
20054 * "fudi.fd_di" == NULL, "fudi.fd_newkey" == func
20055 * dict.func existing dict entry with a Funcref
20056 * "name" == func, "fudi.fd_dict" set,
20057 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
20058 * dict.func existing dict entry that's not a Funcref
20059 * "name" == NULL, "fudi.fd_dict" set,
20060 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
20062 p = eap->arg;
20063 name = trans_function_name(&p, eap->skip, 0, &fudi);
20064 paren = (vim_strchr(p, '(') != NULL);
20065 if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip)
20068 * Return on an invalid expression in braces, unless the expression
20069 * evaluation has been cancelled due to an aborting error, an
20070 * interrupt, or an exception.
20072 if (!aborting())
20074 if (!eap->skip && fudi.fd_newkey != NULL)
20075 EMSG2(_(e_dictkey), fudi.fd_newkey);
20076 vim_free(fudi.fd_newkey);
20077 return;
20079 else
20080 eap->skip = TRUE;
20083 /* An error in a function call during evaluation of an expression in magic
20084 * braces should not cause the function not to be defined. */
20085 saved_did_emsg = did_emsg;
20086 did_emsg = FALSE;
20089 * ":function func" with only function name: list function.
20091 if (!paren)
20093 if (!ends_excmd(*skipwhite(p)))
20095 EMSG(_(e_trailing));
20096 goto ret_free;
20098 eap->nextcmd = check_nextcmd(p);
20099 if (eap->nextcmd != NULL)
20100 *p = NUL;
20101 if (!eap->skip && !got_int)
20103 fp = find_func(name);
20104 if (fp != NULL)
20106 list_func_head(fp, TRUE);
20107 for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j)
20109 if (FUNCLINE(fp, j) == NULL)
20110 continue;
20111 msg_putchar('\n');
20112 msg_outnum((long)(j + 1));
20113 if (j < 9)
20114 msg_putchar(' ');
20115 if (j < 99)
20116 msg_putchar(' ');
20117 msg_prt_line(FUNCLINE(fp, j), FALSE);
20118 out_flush(); /* show a line at a time */
20119 ui_breakcheck();
20121 if (!got_int)
20123 msg_putchar('\n');
20124 msg_puts((char_u *)" endfunction");
20127 else
20128 emsg_funcname(N_("E123: Undefined function: %s"), name);
20130 goto ret_free;
20134 * ":function name(arg1, arg2)" Define function.
20136 p = skipwhite(p);
20137 if (*p != '(')
20139 if (!eap->skip)
20141 EMSG2(_("E124: Missing '(': %s"), eap->arg);
20142 goto ret_free;
20144 /* attempt to continue by skipping some text */
20145 if (vim_strchr(p, '(') != NULL)
20146 p = vim_strchr(p, '(');
20148 p = skipwhite(p + 1);
20150 ga_init2(&newargs, (int)sizeof(char_u *), 3);
20151 ga_init2(&newlines, (int)sizeof(char_u *), 3);
20153 if (!eap->skip)
20155 /* Check the name of the function. Unless it's a dictionary function
20156 * (that we are overwriting). */
20157 if (name != NULL)
20158 arg = name;
20159 else
20160 arg = fudi.fd_newkey;
20161 if (arg != NULL && (fudi.fd_di == NULL
20162 || fudi.fd_di->di_tv.v_type != VAR_FUNC))
20164 if (*arg == K_SPECIAL)
20165 j = 3;
20166 else
20167 j = 0;
20168 while (arg[j] != NUL && (j == 0 ? eval_isnamec1(arg[j])
20169 : eval_isnamec(arg[j])))
20170 ++j;
20171 if (arg[j] != NUL)
20172 emsg_funcname((char *)e_invarg2, arg);
20177 * Isolate the arguments: "arg1, arg2, ...)"
20179 while (*p != ')')
20181 if (p[0] == '.' && p[1] == '.' && p[2] == '.')
20183 varargs = TRUE;
20184 p += 3;
20185 mustend = TRUE;
20187 else
20189 arg = p;
20190 while (ASCII_ISALNUM(*p) || *p == '_')
20191 ++p;
20192 if (arg == p || isdigit(*arg)
20193 || (p - arg == 9 && STRNCMP(arg, "firstline", 9) == 0)
20194 || (p - arg == 8 && STRNCMP(arg, "lastline", 8) == 0))
20196 if (!eap->skip)
20197 EMSG2(_("E125: Illegal argument: %s"), arg);
20198 break;
20200 if (ga_grow(&newargs, 1) == FAIL)
20201 goto erret;
20202 c = *p;
20203 *p = NUL;
20204 arg = vim_strsave(arg);
20205 if (arg == NULL)
20206 goto erret;
20207 ((char_u **)(newargs.ga_data))[newargs.ga_len] = arg;
20208 *p = c;
20209 newargs.ga_len++;
20210 if (*p == ',')
20211 ++p;
20212 else
20213 mustend = TRUE;
20215 p = skipwhite(p);
20216 if (mustend && *p != ')')
20218 if (!eap->skip)
20219 EMSG2(_(e_invarg2), eap->arg);
20220 break;
20223 ++p; /* skip the ')' */
20225 /* find extra arguments "range", "dict" and "abort" */
20226 for (;;)
20228 p = skipwhite(p);
20229 if (STRNCMP(p, "range", 5) == 0)
20231 flags |= FC_RANGE;
20232 p += 5;
20234 else if (STRNCMP(p, "dict", 4) == 0)
20236 flags |= FC_DICT;
20237 p += 4;
20239 else if (STRNCMP(p, "abort", 5) == 0)
20241 flags |= FC_ABORT;
20242 p += 5;
20244 else
20245 break;
20248 /* When there is a line break use what follows for the function body.
20249 * Makes 'exe "func Test()\n...\nendfunc"' work. */
20250 if (*p == '\n')
20251 line_arg = p + 1;
20252 else if (*p != NUL && *p != '"' && !eap->skip && !did_emsg)
20253 EMSG(_(e_trailing));
20256 * Read the body of the function, until ":endfunction" is found.
20258 if (KeyTyped)
20260 /* Check if the function already exists, don't let the user type the
20261 * whole function before telling him it doesn't work! For a script we
20262 * need to skip the body to be able to find what follows. */
20263 if (!eap->skip && !eap->forceit)
20265 if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL)
20266 EMSG(_(e_funcdict));
20267 else if (name != NULL && find_func(name) != NULL)
20268 emsg_funcname(e_funcexts, name);
20271 if (!eap->skip && did_emsg)
20272 goto erret;
20274 msg_putchar('\n'); /* don't overwrite the function name */
20275 cmdline_row = msg_row;
20278 indent = 2;
20279 nesting = 0;
20280 for (;;)
20282 msg_scroll = TRUE;
20283 need_wait_return = FALSE;
20284 sourcing_lnum_off = sourcing_lnum;
20286 if (line_arg != NULL)
20288 /* Use eap->arg, split up in parts by line breaks. */
20289 theline = line_arg;
20290 p = vim_strchr(theline, '\n');
20291 if (p == NULL)
20292 line_arg += STRLEN(line_arg);
20293 else
20295 *p = NUL;
20296 line_arg = p + 1;
20299 else if (eap->getline == NULL)
20300 theline = getcmdline(':', 0L, indent);
20301 else
20302 theline = eap->getline(':', eap->cookie, indent);
20303 if (KeyTyped)
20304 lines_left = Rows - 1;
20305 if (theline == NULL)
20307 EMSG(_("E126: Missing :endfunction"));
20308 goto erret;
20311 /* Detect line continuation: sourcing_lnum increased more than one. */
20312 if (sourcing_lnum > sourcing_lnum_off + 1)
20313 sourcing_lnum_off = sourcing_lnum - sourcing_lnum_off - 1;
20314 else
20315 sourcing_lnum_off = 0;
20317 if (skip_until != NULL)
20319 /* between ":append" and "." and between ":python <<EOF" and "EOF"
20320 * don't check for ":endfunc". */
20321 if (STRCMP(theline, skip_until) == 0)
20323 vim_free(skip_until);
20324 skip_until = NULL;
20327 else
20329 /* skip ':' and blanks*/
20330 for (p = theline; vim_iswhite(*p) || *p == ':'; ++p)
20333 /* Check for "endfunction". */
20334 if (checkforcmd(&p, "endfunction", 4) && nesting-- == 0)
20336 if (line_arg == NULL)
20337 vim_free(theline);
20338 break;
20341 /* Increase indent inside "if", "while", "for" and "try", decrease
20342 * at "end". */
20343 if (indent > 2 && STRNCMP(p, "end", 3) == 0)
20344 indent -= 2;
20345 else if (STRNCMP(p, "if", 2) == 0
20346 || STRNCMP(p, "wh", 2) == 0
20347 || STRNCMP(p, "for", 3) == 0
20348 || STRNCMP(p, "try", 3) == 0)
20349 indent += 2;
20351 /* Check for defining a function inside this function. */
20352 if (checkforcmd(&p, "function", 2))
20354 if (*p == '!')
20355 p = skipwhite(p + 1);
20356 p += eval_fname_script(p);
20357 if (ASCII_ISALPHA(*p))
20359 vim_free(trans_function_name(&p, TRUE, 0, NULL));
20360 if (*skipwhite(p) == '(')
20362 ++nesting;
20363 indent += 2;
20368 /* Check for ":append" or ":insert". */
20369 p = skip_range(p, NULL);
20370 if ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p'))
20371 || (p[0] == 'i'
20372 && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n'
20373 && (!ASCII_ISALPHA(p[2]) || (p[2] == 's'))))))
20374 skip_until = vim_strsave((char_u *)".");
20376 /* Check for ":python <<EOF", ":tcl <<EOF", etc. */
20377 arg = skipwhite(skiptowhite(p));
20378 if (arg[0] == '<' && arg[1] =='<'
20379 && ((p[0] == 'p' && p[1] == 'y'
20380 && (!ASCII_ISALPHA(p[2]) || p[2] == 't'))
20381 || (p[0] == 'p' && p[1] == 'e'
20382 && (!ASCII_ISALPHA(p[2]) || p[2] == 'r'))
20383 || (p[0] == 't' && p[1] == 'c'
20384 && (!ASCII_ISALPHA(p[2]) || p[2] == 'l'))
20385 || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b'
20386 && (!ASCII_ISALPHA(p[3]) || p[3] == 'y'))
20387 || (p[0] == 'm' && p[1] == 'z'
20388 && (!ASCII_ISALPHA(p[2]) || p[2] == 's'))
20391 /* ":python <<" continues until a dot, like ":append" */
20392 p = skipwhite(arg + 2);
20393 if (*p == NUL)
20394 skip_until = vim_strsave((char_u *)".");
20395 else
20396 skip_until = vim_strsave(p);
20400 /* Add the line to the function. */
20401 if (ga_grow(&newlines, 1 + sourcing_lnum_off) == FAIL)
20403 if (line_arg == NULL)
20404 vim_free(theline);
20405 goto erret;
20408 /* Copy the line to newly allocated memory. get_one_sourceline()
20409 * allocates 250 bytes per line, this saves 80% on average. The cost
20410 * is an extra alloc/free. */
20411 p = vim_strsave(theline);
20412 if (p != NULL)
20414 if (line_arg == NULL)
20415 vim_free(theline);
20416 theline = p;
20419 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = theline;
20421 /* Add NULL lines for continuation lines, so that the line count is
20422 * equal to the index in the growarray. */
20423 while (sourcing_lnum_off-- > 0)
20424 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = NULL;
20426 /* Check for end of eap->arg. */
20427 if (line_arg != NULL && *line_arg == NUL)
20428 line_arg = NULL;
20431 /* Don't define the function when skipping commands or when an error was
20432 * detected. */
20433 if (eap->skip || did_emsg)
20434 goto erret;
20437 * If there are no errors, add the function
20439 if (fudi.fd_dict == NULL)
20441 v = find_var(name, &ht);
20442 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
20444 emsg_funcname(N_("E707: Function name conflicts with variable: %s"),
20445 name);
20446 goto erret;
20449 fp = find_func(name);
20450 if (fp != NULL)
20452 if (!eap->forceit)
20454 emsg_funcname(e_funcexts, name);
20455 goto erret;
20457 if (fp->uf_calls > 0)
20459 emsg_funcname(N_("E127: Cannot redefine function %s: It is in use"),
20460 name);
20461 goto erret;
20463 /* redefine existing function */
20464 ga_clear_strings(&(fp->uf_args));
20465 ga_clear_strings(&(fp->uf_lines));
20466 vim_free(name);
20467 name = NULL;
20470 else
20472 char numbuf[20];
20474 fp = NULL;
20475 if (fudi.fd_newkey == NULL && !eap->forceit)
20477 EMSG(_(e_funcdict));
20478 goto erret;
20480 if (fudi.fd_di == NULL)
20482 /* Can't add a function to a locked dictionary */
20483 if (tv_check_lock(fudi.fd_dict->dv_lock, eap->arg))
20484 goto erret;
20486 /* Can't change an existing function if it is locked */
20487 else if (tv_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg))
20488 goto erret;
20490 /* Give the function a sequential number. Can only be used with a
20491 * Funcref! */
20492 vim_free(name);
20493 sprintf(numbuf, "%d", ++func_nr);
20494 name = vim_strsave((char_u *)numbuf);
20495 if (name == NULL)
20496 goto erret;
20499 if (fp == NULL)
20501 if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL)
20503 int slen, plen;
20504 char_u *scriptname;
20506 /* Check that the autoload name matches the script name. */
20507 j = FAIL;
20508 if (sourcing_name != NULL)
20510 scriptname = autoload_name(name);
20511 if (scriptname != NULL)
20513 p = vim_strchr(scriptname, '/');
20514 plen = (int)STRLEN(p);
20515 slen = (int)STRLEN(sourcing_name);
20516 if (slen > plen && fnamecmp(p,
20517 sourcing_name + slen - plen) == 0)
20518 j = OK;
20519 vim_free(scriptname);
20522 if (j == FAIL)
20524 EMSG2(_("E746: Function name does not match script file name: %s"), name);
20525 goto erret;
20529 fp = (ufunc_T *)alloc((unsigned)(sizeof(ufunc_T) + STRLEN(name)));
20530 if (fp == NULL)
20531 goto erret;
20533 if (fudi.fd_dict != NULL)
20535 if (fudi.fd_di == NULL)
20537 /* add new dict entry */
20538 fudi.fd_di = dictitem_alloc(fudi.fd_newkey);
20539 if (fudi.fd_di == NULL)
20541 vim_free(fp);
20542 goto erret;
20544 if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL)
20546 vim_free(fudi.fd_di);
20547 vim_free(fp);
20548 goto erret;
20551 else
20552 /* overwrite existing dict entry */
20553 clear_tv(&fudi.fd_di->di_tv);
20554 fudi.fd_di->di_tv.v_type = VAR_FUNC;
20555 fudi.fd_di->di_tv.v_lock = 0;
20556 fudi.fd_di->di_tv.vval.v_string = vim_strsave(name);
20557 fp->uf_refcount = 1;
20559 /* behave like "dict" was used */
20560 flags |= FC_DICT;
20563 /* insert the new function in the function list */
20564 STRCPY(fp->uf_name, name);
20565 hash_add(&func_hashtab, UF2HIKEY(fp));
20567 fp->uf_args = newargs;
20568 fp->uf_lines = newlines;
20569 #ifdef FEAT_PROFILE
20570 fp->uf_tml_count = NULL;
20571 fp->uf_tml_total = NULL;
20572 fp->uf_tml_self = NULL;
20573 fp->uf_profiling = FALSE;
20574 if (prof_def_func())
20575 func_do_profile(fp);
20576 #endif
20577 fp->uf_varargs = varargs;
20578 fp->uf_flags = flags;
20579 fp->uf_calls = 0;
20580 fp->uf_script_ID = current_SID;
20581 goto ret_free;
20583 erret:
20584 ga_clear_strings(&newargs);
20585 ga_clear_strings(&newlines);
20586 ret_free:
20587 vim_free(skip_until);
20588 vim_free(fudi.fd_newkey);
20589 vim_free(name);
20590 did_emsg |= saved_did_emsg;
20594 * Get a function name, translating "<SID>" and "<SNR>".
20595 * Also handles a Funcref in a List or Dictionary.
20596 * Returns the function name in allocated memory, or NULL for failure.
20597 * flags:
20598 * TFN_INT: internal function name OK
20599 * TFN_QUIET: be quiet
20600 * Advances "pp" to just after the function name (if no error).
20602 static char_u *
20603 trans_function_name(pp, skip, flags, fdp)
20604 char_u **pp;
20605 int skip; /* only find the end, don't evaluate */
20606 int flags;
20607 funcdict_T *fdp; /* return: info about dictionary used */
20609 char_u *name = NULL;
20610 char_u *start;
20611 char_u *end;
20612 int lead;
20613 char_u sid_buf[20];
20614 int len;
20615 lval_T lv;
20617 if (fdp != NULL)
20618 vim_memset(fdp, 0, sizeof(funcdict_T));
20619 start = *pp;
20621 /* Check for hard coded <SNR>: already translated function ID (from a user
20622 * command). */
20623 if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA
20624 && (*pp)[2] == (int)KE_SNR)
20626 *pp += 3;
20627 len = get_id_len(pp) + 3;
20628 return vim_strnsave(start, len);
20631 /* A name starting with "<SID>" or "<SNR>" is local to a script. But
20632 * don't skip over "s:", get_lval() needs it for "s:dict.func". */
20633 lead = eval_fname_script(start);
20634 if (lead > 2)
20635 start += lead;
20637 end = get_lval(start, NULL, &lv, FALSE, skip, flags & TFN_QUIET,
20638 lead > 2 ? 0 : FNE_CHECK_START);
20639 if (end == start)
20641 if (!skip)
20642 EMSG(_("E129: Function name required"));
20643 goto theend;
20645 if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range)))
20648 * Report an invalid expression in braces, unless the expression
20649 * evaluation has been cancelled due to an aborting error, an
20650 * interrupt, or an exception.
20652 if (!aborting())
20654 if (end != NULL)
20655 EMSG2(_(e_invarg2), start);
20657 else
20658 *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR);
20659 goto theend;
20662 if (lv.ll_tv != NULL)
20664 if (fdp != NULL)
20666 fdp->fd_dict = lv.ll_dict;
20667 fdp->fd_newkey = lv.ll_newkey;
20668 lv.ll_newkey = NULL;
20669 fdp->fd_di = lv.ll_di;
20671 if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL)
20673 name = vim_strsave(lv.ll_tv->vval.v_string);
20674 *pp = end;
20676 else
20678 if (!skip && !(flags & TFN_QUIET) && (fdp == NULL
20679 || lv.ll_dict == NULL || fdp->fd_newkey == NULL))
20680 EMSG(_(e_funcref));
20681 else
20682 *pp = end;
20683 name = NULL;
20685 goto theend;
20688 if (lv.ll_name == NULL)
20690 /* Error found, but continue after the function name. */
20691 *pp = end;
20692 goto theend;
20695 /* Check if the name is a Funcref. If so, use the value. */
20696 if (lv.ll_exp_name != NULL)
20698 len = (int)STRLEN(lv.ll_exp_name);
20699 name = deref_func_name(lv.ll_exp_name, &len);
20700 if (name == lv.ll_exp_name)
20701 name = NULL;
20703 else
20705 len = (int)(end - *pp);
20706 name = deref_func_name(*pp, &len);
20707 if (name == *pp)
20708 name = NULL;
20710 if (name != NULL)
20712 name = vim_strsave(name);
20713 *pp = end;
20714 goto theend;
20717 if (lv.ll_exp_name != NULL)
20719 len = (int)STRLEN(lv.ll_exp_name);
20720 if (lead <= 2 && lv.ll_name == lv.ll_exp_name
20721 && STRNCMP(lv.ll_name, "s:", 2) == 0)
20723 /* When there was "s:" already or the name expanded to get a
20724 * leading "s:" then remove it. */
20725 lv.ll_name += 2;
20726 len -= 2;
20727 lead = 2;
20730 else
20732 if (lead == 2) /* skip over "s:" */
20733 lv.ll_name += 2;
20734 len = (int)(end - lv.ll_name);
20738 * Copy the function name to allocated memory.
20739 * Accept <SID>name() inside a script, translate into <SNR>123_name().
20740 * Accept <SNR>123_name() outside a script.
20742 if (skip)
20743 lead = 0; /* do nothing */
20744 else if (lead > 0)
20746 lead = 3;
20747 if ((lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name))
20748 || eval_fname_sid(*pp))
20750 /* It's "s:" or "<SID>" */
20751 if (current_SID <= 0)
20753 EMSG(_(e_usingsid));
20754 goto theend;
20756 sprintf((char *)sid_buf, "%ld_", (long)current_SID);
20757 lead += (int)STRLEN(sid_buf);
20760 else if (!(flags & TFN_INT) && builtin_function(lv.ll_name))
20762 EMSG2(_("E128: Function name must start with a capital or contain a colon: %s"), lv.ll_name);
20763 goto theend;
20765 name = alloc((unsigned)(len + lead + 1));
20766 if (name != NULL)
20768 if (lead > 0)
20770 name[0] = K_SPECIAL;
20771 name[1] = KS_EXTRA;
20772 name[2] = (int)KE_SNR;
20773 if (lead > 3) /* If it's "<SID>" */
20774 STRCPY(name + 3, sid_buf);
20776 mch_memmove(name + lead, lv.ll_name, (size_t)len);
20777 name[len + lead] = NUL;
20779 *pp = end;
20781 theend:
20782 clear_lval(&lv);
20783 return name;
20787 * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case).
20788 * Return 2 if "p" starts with "s:".
20789 * Return 0 otherwise.
20791 static int
20792 eval_fname_script(p)
20793 char_u *p;
20795 if (p[0] == '<' && (STRNICMP(p + 1, "SID>", 4) == 0
20796 || STRNICMP(p + 1, "SNR>", 4) == 0))
20797 return 5;
20798 if (p[0] == 's' && p[1] == ':')
20799 return 2;
20800 return 0;
20804 * Return TRUE if "p" starts with "<SID>" or "s:".
20805 * Only works if eval_fname_script() returned non-zero for "p"!
20807 static int
20808 eval_fname_sid(p)
20809 char_u *p;
20811 return (*p == 's' || TOUPPER_ASC(p[2]) == 'I');
20815 * List the head of the function: "name(arg1, arg2)".
20817 static void
20818 list_func_head(fp, indent)
20819 ufunc_T *fp;
20820 int indent;
20822 int j;
20824 msg_start();
20825 if (indent)
20826 MSG_PUTS(" ");
20827 MSG_PUTS("function ");
20828 if (fp->uf_name[0] == K_SPECIAL)
20830 MSG_PUTS_ATTR("<SNR>", hl_attr(HLF_8));
20831 msg_puts(fp->uf_name + 3);
20833 else
20834 msg_puts(fp->uf_name);
20835 msg_putchar('(');
20836 for (j = 0; j < fp->uf_args.ga_len; ++j)
20838 if (j)
20839 MSG_PUTS(", ");
20840 msg_puts(FUNCARG(fp, j));
20842 if (fp->uf_varargs)
20844 if (j)
20845 MSG_PUTS(", ");
20846 MSG_PUTS("...");
20848 msg_putchar(')');
20849 msg_clr_eos();
20850 if (p_verbose > 0)
20851 last_set_msg(fp->uf_script_ID);
20855 * Find a function by name, return pointer to it in ufuncs.
20856 * Return NULL for unknown function.
20858 static ufunc_T *
20859 find_func(name)
20860 char_u *name;
20862 hashitem_T *hi;
20864 hi = hash_find(&func_hashtab, name);
20865 if (!HASHITEM_EMPTY(hi))
20866 return HI2UF(hi);
20867 return NULL;
20870 #if defined(EXITFREE) || defined(PROTO)
20871 void
20872 free_all_functions()
20874 hashitem_T *hi;
20876 /* Need to start all over every time, because func_free() may change the
20877 * hash table. */
20878 while (func_hashtab.ht_used > 0)
20879 for (hi = func_hashtab.ht_array; ; ++hi)
20880 if (!HASHITEM_EMPTY(hi))
20882 func_free(HI2UF(hi));
20883 break;
20886 #endif
20889 * Return TRUE if a function "name" exists.
20891 static int
20892 function_exists(name)
20893 char_u *name;
20895 char_u *nm = name;
20896 char_u *p;
20897 int n = FALSE;
20899 p = trans_function_name(&nm, FALSE, TFN_INT|TFN_QUIET, NULL);
20900 nm = skipwhite(nm);
20902 /* Only accept "funcname", "funcname ", "funcname (..." and
20903 * "funcname(...", not "funcname!...". */
20904 if (p != NULL && (*nm == NUL || *nm == '('))
20906 if (builtin_function(p))
20907 n = (find_internal_func(p) >= 0);
20908 else
20909 n = (find_func(p) != NULL);
20911 vim_free(p);
20912 return n;
20916 * Return TRUE if "name" looks like a builtin function name: starts with a
20917 * lower case letter and doesn't contain a ':' or AUTOLOAD_CHAR.
20919 static int
20920 builtin_function(name)
20921 char_u *name;
20923 return ASCII_ISLOWER(name[0]) && vim_strchr(name, ':') == NULL
20924 && vim_strchr(name, AUTOLOAD_CHAR) == NULL;
20927 #if defined(FEAT_PROFILE) || defined(PROTO)
20929 * Start profiling function "fp".
20931 static void
20932 func_do_profile(fp)
20933 ufunc_T *fp;
20935 fp->uf_tm_count = 0;
20936 profile_zero(&fp->uf_tm_self);
20937 profile_zero(&fp->uf_tm_total);
20938 if (fp->uf_tml_count == NULL)
20939 fp->uf_tml_count = (int *)alloc_clear((unsigned)
20940 (sizeof(int) * fp->uf_lines.ga_len));
20941 if (fp->uf_tml_total == NULL)
20942 fp->uf_tml_total = (proftime_T *)alloc_clear((unsigned)
20943 (sizeof(proftime_T) * fp->uf_lines.ga_len));
20944 if (fp->uf_tml_self == NULL)
20945 fp->uf_tml_self = (proftime_T *)alloc_clear((unsigned)
20946 (sizeof(proftime_T) * fp->uf_lines.ga_len));
20947 fp->uf_tml_idx = -1;
20948 if (fp->uf_tml_count == NULL || fp->uf_tml_total == NULL
20949 || fp->uf_tml_self == NULL)
20950 return; /* out of memory */
20952 fp->uf_profiling = TRUE;
20956 * Dump the profiling results for all functions in file "fd".
20958 void
20959 func_dump_profile(fd)
20960 FILE *fd;
20962 hashitem_T *hi;
20963 int todo;
20964 ufunc_T *fp;
20965 int i;
20966 ufunc_T **sorttab;
20967 int st_len = 0;
20969 todo = (int)func_hashtab.ht_used;
20970 if (todo == 0)
20971 return; /* nothing to dump */
20973 sorttab = (ufunc_T **)alloc((unsigned)(sizeof(ufunc_T) * todo));
20975 for (hi = func_hashtab.ht_array; todo > 0; ++hi)
20977 if (!HASHITEM_EMPTY(hi))
20979 --todo;
20980 fp = HI2UF(hi);
20981 if (fp->uf_profiling)
20983 if (sorttab != NULL)
20984 sorttab[st_len++] = fp;
20986 if (fp->uf_name[0] == K_SPECIAL)
20987 fprintf(fd, "FUNCTION <SNR>%s()\n", fp->uf_name + 3);
20988 else
20989 fprintf(fd, "FUNCTION %s()\n", fp->uf_name);
20990 if (fp->uf_tm_count == 1)
20991 fprintf(fd, "Called 1 time\n");
20992 else
20993 fprintf(fd, "Called %d times\n", fp->uf_tm_count);
20994 fprintf(fd, "Total time: %s\n", profile_msg(&fp->uf_tm_total));
20995 fprintf(fd, " Self time: %s\n", profile_msg(&fp->uf_tm_self));
20996 fprintf(fd, "\n");
20997 fprintf(fd, "count total (s) self (s)\n");
20999 for (i = 0; i < fp->uf_lines.ga_len; ++i)
21001 if (FUNCLINE(fp, i) == NULL)
21002 continue;
21003 prof_func_line(fd, fp->uf_tml_count[i],
21004 &fp->uf_tml_total[i], &fp->uf_tml_self[i], TRUE);
21005 fprintf(fd, "%s\n", FUNCLINE(fp, i));
21007 fprintf(fd, "\n");
21012 if (sorttab != NULL && st_len > 0)
21014 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
21015 prof_total_cmp);
21016 prof_sort_list(fd, sorttab, st_len, "TOTAL", FALSE);
21017 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
21018 prof_self_cmp);
21019 prof_sort_list(fd, sorttab, st_len, "SELF", TRUE);
21022 vim_free(sorttab);
21025 static void
21026 prof_sort_list(fd, sorttab, st_len, title, prefer_self)
21027 FILE *fd;
21028 ufunc_T **sorttab;
21029 int st_len;
21030 char *title;
21031 int prefer_self; /* when equal print only self time */
21033 int i;
21034 ufunc_T *fp;
21036 fprintf(fd, "FUNCTIONS SORTED ON %s TIME\n", title);
21037 fprintf(fd, "count total (s) self (s) function\n");
21038 for (i = 0; i < 20 && i < st_len; ++i)
21040 fp = sorttab[i];
21041 prof_func_line(fd, fp->uf_tm_count, &fp->uf_tm_total, &fp->uf_tm_self,
21042 prefer_self);
21043 if (fp->uf_name[0] == K_SPECIAL)
21044 fprintf(fd, " <SNR>%s()\n", fp->uf_name + 3);
21045 else
21046 fprintf(fd, " %s()\n", fp->uf_name);
21048 fprintf(fd, "\n");
21052 * Print the count and times for one function or function line.
21054 static void
21055 prof_func_line(fd, count, total, self, prefer_self)
21056 FILE *fd;
21057 int count;
21058 proftime_T *total;
21059 proftime_T *self;
21060 int prefer_self; /* when equal print only self time */
21062 if (count > 0)
21064 fprintf(fd, "%5d ", count);
21065 if (prefer_self && profile_equal(total, self))
21066 fprintf(fd, " ");
21067 else
21068 fprintf(fd, "%s ", profile_msg(total));
21069 if (!prefer_self && profile_equal(total, self))
21070 fprintf(fd, " ");
21071 else
21072 fprintf(fd, "%s ", profile_msg(self));
21074 else
21075 fprintf(fd, " ");
21079 * Compare function for total time sorting.
21081 static int
21082 #ifdef __BORLANDC__
21083 _RTLENTRYF
21084 #endif
21085 prof_total_cmp(s1, s2)
21086 const void *s1;
21087 const void *s2;
21089 ufunc_T *p1, *p2;
21091 p1 = *(ufunc_T **)s1;
21092 p2 = *(ufunc_T **)s2;
21093 return profile_cmp(&p1->uf_tm_total, &p2->uf_tm_total);
21097 * Compare function for self time sorting.
21099 static int
21100 #ifdef __BORLANDC__
21101 _RTLENTRYF
21102 #endif
21103 prof_self_cmp(s1, s2)
21104 const void *s1;
21105 const void *s2;
21107 ufunc_T *p1, *p2;
21109 p1 = *(ufunc_T **)s1;
21110 p2 = *(ufunc_T **)s2;
21111 return profile_cmp(&p1->uf_tm_self, &p2->uf_tm_self);
21114 #endif
21117 * If "name" has a package name try autoloading the script for it.
21118 * Return TRUE if a package was loaded.
21120 static int
21121 script_autoload(name, reload)
21122 char_u *name;
21123 int reload; /* load script again when already loaded */
21125 char_u *p;
21126 char_u *scriptname, *tofree;
21127 int ret = FALSE;
21128 int i;
21130 /* If there is no '#' after name[0] there is no package name. */
21131 p = vim_strchr(name, AUTOLOAD_CHAR);
21132 if (p == NULL || p == name)
21133 return FALSE;
21135 tofree = scriptname = autoload_name(name);
21137 /* Find the name in the list of previously loaded package names. Skip
21138 * "autoload/", it's always the same. */
21139 for (i = 0; i < ga_loaded.ga_len; ++i)
21140 if (STRCMP(((char_u **)ga_loaded.ga_data)[i] + 9, scriptname + 9) == 0)
21141 break;
21142 if (!reload && i < ga_loaded.ga_len)
21143 ret = FALSE; /* was loaded already */
21144 else
21146 /* Remember the name if it wasn't loaded already. */
21147 if (i == ga_loaded.ga_len && ga_grow(&ga_loaded, 1) == OK)
21149 ((char_u **)ga_loaded.ga_data)[ga_loaded.ga_len++] = scriptname;
21150 tofree = NULL;
21153 /* Try loading the package from $VIMRUNTIME/autoload/<name>.vim */
21154 if (source_runtime(scriptname, FALSE) == OK)
21155 ret = TRUE;
21158 vim_free(tofree);
21159 return ret;
21163 * Return the autoload script name for a function or variable name.
21164 * Returns NULL when out of memory.
21166 static char_u *
21167 autoload_name(name)
21168 char_u *name;
21170 char_u *p;
21171 char_u *scriptname;
21173 /* Get the script file name: replace '#' with '/', append ".vim". */
21174 scriptname = alloc((unsigned)(STRLEN(name) + 14));
21175 if (scriptname == NULL)
21176 return FALSE;
21177 STRCPY(scriptname, "autoload/");
21178 STRCAT(scriptname, name);
21179 *vim_strrchr(scriptname, AUTOLOAD_CHAR) = NUL;
21180 STRCAT(scriptname, ".vim");
21181 while ((p = vim_strchr(scriptname, AUTOLOAD_CHAR)) != NULL)
21182 *p = '/';
21183 return scriptname;
21186 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
21189 * Function given to ExpandGeneric() to obtain the list of user defined
21190 * function names.
21192 char_u *
21193 get_user_func_name(xp, idx)
21194 expand_T *xp;
21195 int idx;
21197 static long_u done;
21198 static hashitem_T *hi;
21199 ufunc_T *fp;
21201 if (idx == 0)
21203 done = 0;
21204 hi = func_hashtab.ht_array;
21206 if (done < func_hashtab.ht_used)
21208 if (done++ > 0)
21209 ++hi;
21210 while (HASHITEM_EMPTY(hi))
21211 ++hi;
21212 fp = HI2UF(hi);
21214 if (STRLEN(fp->uf_name) + 4 >= IOSIZE)
21215 return fp->uf_name; /* prevents overflow */
21217 cat_func_name(IObuff, fp);
21218 if (xp->xp_context != EXPAND_USER_FUNC)
21220 STRCAT(IObuff, "(");
21221 if (!fp->uf_varargs && fp->uf_args.ga_len == 0)
21222 STRCAT(IObuff, ")");
21224 return IObuff;
21226 return NULL;
21229 #endif /* FEAT_CMDL_COMPL */
21232 * Copy the function name of "fp" to buffer "buf".
21233 * "buf" must be able to hold the function name plus three bytes.
21234 * Takes care of script-local function names.
21236 static void
21237 cat_func_name(buf, fp)
21238 char_u *buf;
21239 ufunc_T *fp;
21241 if (fp->uf_name[0] == K_SPECIAL)
21243 STRCPY(buf, "<SNR>");
21244 STRCAT(buf, fp->uf_name + 3);
21246 else
21247 STRCPY(buf, fp->uf_name);
21251 * ":delfunction {name}"
21253 void
21254 ex_delfunction(eap)
21255 exarg_T *eap;
21257 ufunc_T *fp = NULL;
21258 char_u *p;
21259 char_u *name;
21260 funcdict_T fudi;
21262 p = eap->arg;
21263 name = trans_function_name(&p, eap->skip, 0, &fudi);
21264 vim_free(fudi.fd_newkey);
21265 if (name == NULL)
21267 if (fudi.fd_dict != NULL && !eap->skip)
21268 EMSG(_(e_funcref));
21269 return;
21271 if (!ends_excmd(*skipwhite(p)))
21273 vim_free(name);
21274 EMSG(_(e_trailing));
21275 return;
21277 eap->nextcmd = check_nextcmd(p);
21278 if (eap->nextcmd != NULL)
21279 *p = NUL;
21281 if (!eap->skip)
21282 fp = find_func(name);
21283 vim_free(name);
21285 if (!eap->skip)
21287 if (fp == NULL)
21289 EMSG2(_(e_nofunc), eap->arg);
21290 return;
21292 if (fp->uf_calls > 0)
21294 EMSG2(_("E131: Cannot delete function %s: It is in use"), eap->arg);
21295 return;
21298 if (fudi.fd_dict != NULL)
21300 /* Delete the dict item that refers to the function, it will
21301 * invoke func_unref() and possibly delete the function. */
21302 dictitem_remove(fudi.fd_dict, fudi.fd_di);
21304 else
21305 func_free(fp);
21310 * Free a function and remove it from the list of functions.
21312 static void
21313 func_free(fp)
21314 ufunc_T *fp;
21316 hashitem_T *hi;
21318 /* clear this function */
21319 ga_clear_strings(&(fp->uf_args));
21320 ga_clear_strings(&(fp->uf_lines));
21321 #ifdef FEAT_PROFILE
21322 vim_free(fp->uf_tml_count);
21323 vim_free(fp->uf_tml_total);
21324 vim_free(fp->uf_tml_self);
21325 #endif
21327 /* remove the function from the function hashtable */
21328 hi = hash_find(&func_hashtab, UF2HIKEY(fp));
21329 if (HASHITEM_EMPTY(hi))
21330 EMSG2(_(e_intern2), "func_free()");
21331 else
21332 hash_remove(&func_hashtab, hi);
21334 vim_free(fp);
21338 * Unreference a Function: decrement the reference count and free it when it
21339 * becomes zero. Only for numbered functions.
21341 static void
21342 func_unref(name)
21343 char_u *name;
21345 ufunc_T *fp;
21347 if (name != NULL && isdigit(*name))
21349 fp = find_func(name);
21350 if (fp == NULL)
21351 EMSG2(_(e_intern2), "func_unref()");
21352 else if (--fp->uf_refcount <= 0)
21354 /* Only delete it when it's not being used. Otherwise it's done
21355 * when "uf_calls" becomes zero. */
21356 if (fp->uf_calls == 0)
21357 func_free(fp);
21363 * Count a reference to a Function.
21365 static void
21366 func_ref(name)
21367 char_u *name;
21369 ufunc_T *fp;
21371 if (name != NULL && isdigit(*name))
21373 fp = find_func(name);
21374 if (fp == NULL)
21375 EMSG2(_(e_intern2), "func_ref()");
21376 else
21377 ++fp->uf_refcount;
21382 * Call a user function.
21384 static void
21385 call_user_func(fp, argcount, argvars, rettv, firstline, lastline, selfdict)
21386 ufunc_T *fp; /* pointer to function */
21387 int argcount; /* nr of args */
21388 typval_T *argvars; /* arguments */
21389 typval_T *rettv; /* return value */
21390 linenr_T firstline; /* first line of range */
21391 linenr_T lastline; /* last line of range */
21392 dict_T *selfdict; /* Dictionary for "self" */
21394 char_u *save_sourcing_name;
21395 linenr_T save_sourcing_lnum;
21396 scid_T save_current_SID;
21397 funccall_T *fc;
21398 int save_did_emsg;
21399 static int depth = 0;
21400 dictitem_T *v;
21401 int fixvar_idx = 0; /* index in fixvar[] */
21402 int i;
21403 int ai;
21404 char_u numbuf[NUMBUFLEN];
21405 char_u *name;
21406 #ifdef FEAT_PROFILE
21407 proftime_T wait_start;
21408 proftime_T call_start;
21409 #endif
21411 /* If depth of calling is getting too high, don't execute the function */
21412 if (depth >= p_mfd)
21414 EMSG(_("E132: Function call depth is higher than 'maxfuncdepth'"));
21415 rettv->v_type = VAR_NUMBER;
21416 rettv->vval.v_number = -1;
21417 return;
21419 ++depth;
21421 line_breakcheck(); /* check for CTRL-C hit */
21423 fc = (funccall_T *)alloc(sizeof(funccall_T));
21424 fc->caller = current_funccal;
21425 current_funccal = fc;
21426 fc->func = fp;
21427 fc->rettv = rettv;
21428 rettv->vval.v_number = 0;
21429 fc->linenr = 0;
21430 fc->returned = FALSE;
21431 fc->level = ex_nesting_level;
21432 /* Check if this function has a breakpoint. */
21433 fc->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, (linenr_T)0);
21434 fc->dbg_tick = debug_tick;
21437 * Note about using fc->fixvar[]: This is an array of FIXVAR_CNT variables
21438 * with names up to VAR_SHORT_LEN long. This avoids having to alloc/free
21439 * each argument variable and saves a lot of time.
21442 * Init l: variables.
21444 init_var_dict(&fc->l_vars, &fc->l_vars_var);
21445 if (selfdict != NULL)
21447 /* Set l:self to "selfdict". Use "name" to avoid a warning from
21448 * some compiler that checks the destination size. */
21449 v = &fc->fixvar[fixvar_idx++].var;
21450 name = v->di_key;
21451 STRCPY(name, "self");
21452 v->di_flags = DI_FLAGS_RO + DI_FLAGS_FIX;
21453 hash_add(&fc->l_vars.dv_hashtab, DI2HIKEY(v));
21454 v->di_tv.v_type = VAR_DICT;
21455 v->di_tv.v_lock = 0;
21456 v->di_tv.vval.v_dict = selfdict;
21457 ++selfdict->dv_refcount;
21461 * Init a: variables.
21462 * Set a:0 to "argcount".
21463 * Set a:000 to a list with room for the "..." arguments.
21465 init_var_dict(&fc->l_avars, &fc->l_avars_var);
21466 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "0",
21467 (varnumber_T)(argcount - fp->uf_args.ga_len));
21468 /* Use "name" to avoid a warning from some compiler that checks the
21469 * destination size. */
21470 v = &fc->fixvar[fixvar_idx++].var;
21471 name = v->di_key;
21472 STRCPY(name, "000");
21473 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21474 hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v));
21475 v->di_tv.v_type = VAR_LIST;
21476 v->di_tv.v_lock = VAR_FIXED;
21477 v->di_tv.vval.v_list = &fc->l_varlist;
21478 vim_memset(&fc->l_varlist, 0, sizeof(list_T));
21479 fc->l_varlist.lv_refcount = DO_NOT_FREE_CNT;
21480 fc->l_varlist.lv_lock = VAR_FIXED;
21483 * Set a:firstline to "firstline" and a:lastline to "lastline".
21484 * Set a:name to named arguments.
21485 * Set a:N to the "..." arguments.
21487 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "firstline",
21488 (varnumber_T)firstline);
21489 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "lastline",
21490 (varnumber_T)lastline);
21491 for (i = 0; i < argcount; ++i)
21493 ai = i - fp->uf_args.ga_len;
21494 if (ai < 0)
21495 /* named argument a:name */
21496 name = FUNCARG(fp, i);
21497 else
21499 /* "..." argument a:1, a:2, etc. */
21500 sprintf((char *)numbuf, "%d", ai + 1);
21501 name = numbuf;
21503 if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN)
21505 v = &fc->fixvar[fixvar_idx++].var;
21506 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21508 else
21510 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
21511 + STRLEN(name)));
21512 if (v == NULL)
21513 break;
21514 v->di_flags = DI_FLAGS_RO;
21516 STRCPY(v->di_key, name);
21517 hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v));
21519 /* Note: the values are copied directly to avoid alloc/free.
21520 * "argvars" must have VAR_FIXED for v_lock. */
21521 v->di_tv = argvars[i];
21522 v->di_tv.v_lock = VAR_FIXED;
21524 if (ai >= 0 && ai < MAX_FUNC_ARGS)
21526 list_append(&fc->l_varlist, &fc->l_listitems[ai]);
21527 fc->l_listitems[ai].li_tv = argvars[i];
21528 fc->l_listitems[ai].li_tv.v_lock = VAR_FIXED;
21532 /* Don't redraw while executing the function. */
21533 ++RedrawingDisabled;
21534 save_sourcing_name = sourcing_name;
21535 save_sourcing_lnum = sourcing_lnum;
21536 sourcing_lnum = 1;
21537 sourcing_name = alloc((unsigned)((save_sourcing_name == NULL ? 0
21538 : STRLEN(save_sourcing_name)) + STRLEN(fp->uf_name) + 13));
21539 if (sourcing_name != NULL)
21541 if (save_sourcing_name != NULL
21542 && STRNCMP(save_sourcing_name, "function ", 9) == 0)
21543 sprintf((char *)sourcing_name, "%s..", save_sourcing_name);
21544 else
21545 STRCPY(sourcing_name, "function ");
21546 cat_func_name(sourcing_name + STRLEN(sourcing_name), fp);
21548 if (p_verbose >= 12)
21550 ++no_wait_return;
21551 verbose_enter_scroll();
21553 smsg((char_u *)_("calling %s"), sourcing_name);
21554 if (p_verbose >= 14)
21556 char_u buf[MSG_BUF_LEN];
21557 char_u numbuf2[NUMBUFLEN];
21558 char_u *tofree;
21559 char_u *s;
21561 msg_puts((char_u *)"(");
21562 for (i = 0; i < argcount; ++i)
21564 if (i > 0)
21565 msg_puts((char_u *)", ");
21566 if (argvars[i].v_type == VAR_NUMBER)
21567 msg_outnum((long)argvars[i].vval.v_number);
21568 else
21570 s = tv2string(&argvars[i], &tofree, numbuf2, 0);
21571 if (s != NULL)
21573 trunc_string(s, buf, MSG_BUF_CLEN);
21574 msg_puts(buf);
21575 vim_free(tofree);
21579 msg_puts((char_u *)")");
21581 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21583 verbose_leave_scroll();
21584 --no_wait_return;
21587 #ifdef FEAT_PROFILE
21588 if (do_profiling == PROF_YES)
21590 if (!fp->uf_profiling && has_profiling(FALSE, fp->uf_name, NULL))
21591 func_do_profile(fp);
21592 if (fp->uf_profiling
21593 || (fc->caller != NULL && fc->caller->func->uf_profiling))
21595 ++fp->uf_tm_count;
21596 profile_start(&call_start);
21597 profile_zero(&fp->uf_tm_children);
21599 script_prof_save(&wait_start);
21601 #endif
21603 save_current_SID = current_SID;
21604 current_SID = fp->uf_script_ID;
21605 save_did_emsg = did_emsg;
21606 did_emsg = FALSE;
21608 /* call do_cmdline() to execute the lines */
21609 do_cmdline(NULL, get_func_line, (void *)fc,
21610 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
21612 --RedrawingDisabled;
21614 /* when the function was aborted because of an error, return -1 */
21615 if ((did_emsg && (fp->uf_flags & FC_ABORT)) || rettv->v_type == VAR_UNKNOWN)
21617 clear_tv(rettv);
21618 rettv->v_type = VAR_NUMBER;
21619 rettv->vval.v_number = -1;
21622 #ifdef FEAT_PROFILE
21623 if (do_profiling == PROF_YES && (fp->uf_profiling
21624 || (fc->caller != NULL && fc->caller->func->uf_profiling)))
21626 profile_end(&call_start);
21627 profile_sub_wait(&wait_start, &call_start);
21628 profile_add(&fp->uf_tm_total, &call_start);
21629 profile_self(&fp->uf_tm_self, &call_start, &fp->uf_tm_children);
21630 if (fc->caller != NULL && fc->caller->func->uf_profiling)
21632 profile_add(&fc->caller->func->uf_tm_children, &call_start);
21633 profile_add(&fc->caller->func->uf_tml_children, &call_start);
21636 #endif
21638 /* when being verbose, mention the return value */
21639 if (p_verbose >= 12)
21641 ++no_wait_return;
21642 verbose_enter_scroll();
21644 if (aborting())
21645 smsg((char_u *)_("%s aborted"), sourcing_name);
21646 else if (fc->rettv->v_type == VAR_NUMBER)
21647 smsg((char_u *)_("%s returning #%ld"), sourcing_name,
21648 (long)fc->rettv->vval.v_number);
21649 else
21651 char_u buf[MSG_BUF_LEN];
21652 char_u numbuf2[NUMBUFLEN];
21653 char_u *tofree;
21654 char_u *s;
21656 /* The value may be very long. Skip the middle part, so that we
21657 * have some idea how it starts and ends. smsg() would always
21658 * truncate it at the end. */
21659 s = tv2string(fc->rettv, &tofree, numbuf2, 0);
21660 if (s != NULL)
21662 trunc_string(s, buf, MSG_BUF_CLEN);
21663 smsg((char_u *)_("%s returning %s"), sourcing_name, buf);
21664 vim_free(tofree);
21667 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21669 verbose_leave_scroll();
21670 --no_wait_return;
21673 vim_free(sourcing_name);
21674 sourcing_name = save_sourcing_name;
21675 sourcing_lnum = save_sourcing_lnum;
21676 current_SID = save_current_SID;
21677 #ifdef FEAT_PROFILE
21678 if (do_profiling == PROF_YES)
21679 script_prof_restore(&wait_start);
21680 #endif
21682 if (p_verbose >= 12 && sourcing_name != NULL)
21684 ++no_wait_return;
21685 verbose_enter_scroll();
21687 smsg((char_u *)_("continuing in %s"), sourcing_name);
21688 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21690 verbose_leave_scroll();
21691 --no_wait_return;
21694 did_emsg |= save_did_emsg;
21695 current_funccal = fc->caller;
21696 --depth;
21698 /* If the a:000 list and the l: and a: dicts are not referenced we can
21699 * free the funccall_T and what's in it. */
21700 if (fc->l_varlist.lv_refcount == DO_NOT_FREE_CNT
21701 && fc->l_vars.dv_refcount == DO_NOT_FREE_CNT
21702 && fc->l_avars.dv_refcount == DO_NOT_FREE_CNT)
21704 free_funccal(fc, FALSE);
21706 else
21708 hashitem_T *hi;
21709 listitem_T *li;
21710 int todo;
21712 /* "fc" is still in use. This can happen when returning "a:000" or
21713 * assigning "l:" to a global variable.
21714 * Link "fc" in the list for garbage collection later. */
21715 fc->caller = previous_funccal;
21716 previous_funccal = fc;
21718 /* Make a copy of the a: variables, since we didn't do that above. */
21719 todo = (int)fc->l_avars.dv_hashtab.ht_used;
21720 for (hi = fc->l_avars.dv_hashtab.ht_array; todo > 0; ++hi)
21722 if (!HASHITEM_EMPTY(hi))
21724 --todo;
21725 v = HI2DI(hi);
21726 copy_tv(&v->di_tv, &v->di_tv);
21730 /* Make a copy of the a:000 items, since we didn't do that above. */
21731 for (li = fc->l_varlist.lv_first; li != NULL; li = li->li_next)
21732 copy_tv(&li->li_tv, &li->li_tv);
21737 * Return TRUE if items in "fc" do not have "copyID". That means they are not
21738 * referenced from anywhere that is in use.
21740 static int
21741 can_free_funccal(fc, copyID)
21742 funccall_T *fc;
21743 int copyID;
21745 return (fc->l_varlist.lv_copyID != copyID
21746 && fc->l_vars.dv_copyID != copyID
21747 && fc->l_avars.dv_copyID != copyID);
21751 * Free "fc" and what it contains.
21753 static void
21754 free_funccal(fc, free_val)
21755 funccall_T *fc;
21756 int free_val; /* a: vars were allocated */
21758 listitem_T *li;
21760 /* The a: variables typevals may not have been allocated, only free the
21761 * allocated variables. */
21762 vars_clear_ext(&fc->l_avars.dv_hashtab, free_val);
21764 /* free all l: variables */
21765 vars_clear(&fc->l_vars.dv_hashtab);
21767 /* Free the a:000 variables if they were allocated. */
21768 if (free_val)
21769 for (li = fc->l_varlist.lv_first; li != NULL; li = li->li_next)
21770 clear_tv(&li->li_tv);
21772 vim_free(fc);
21776 * Add a number variable "name" to dict "dp" with value "nr".
21778 static void
21779 add_nr_var(dp, v, name, nr)
21780 dict_T *dp;
21781 dictitem_T *v;
21782 char *name;
21783 varnumber_T nr;
21785 STRCPY(v->di_key, name);
21786 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21787 hash_add(&dp->dv_hashtab, DI2HIKEY(v));
21788 v->di_tv.v_type = VAR_NUMBER;
21789 v->di_tv.v_lock = VAR_FIXED;
21790 v->di_tv.vval.v_number = nr;
21794 * ":return [expr]"
21796 void
21797 ex_return(eap)
21798 exarg_T *eap;
21800 char_u *arg = eap->arg;
21801 typval_T rettv;
21802 int returning = FALSE;
21804 if (current_funccal == NULL)
21806 EMSG(_("E133: :return not inside a function"));
21807 return;
21810 if (eap->skip)
21811 ++emsg_skip;
21813 eap->nextcmd = NULL;
21814 if ((*arg != NUL && *arg != '|' && *arg != '\n')
21815 && eval0(arg, &rettv, &eap->nextcmd, !eap->skip) != FAIL)
21817 if (!eap->skip)
21818 returning = do_return(eap, FALSE, TRUE, &rettv);
21819 else
21820 clear_tv(&rettv);
21822 /* It's safer to return also on error. */
21823 else if (!eap->skip)
21826 * Return unless the expression evaluation has been cancelled due to an
21827 * aborting error, an interrupt, or an exception.
21829 if (!aborting())
21830 returning = do_return(eap, FALSE, TRUE, NULL);
21833 /* When skipping or the return gets pending, advance to the next command
21834 * in this line (!returning). Otherwise, ignore the rest of the line.
21835 * Following lines will be ignored by get_func_line(). */
21836 if (returning)
21837 eap->nextcmd = NULL;
21838 else if (eap->nextcmd == NULL) /* no argument */
21839 eap->nextcmd = check_nextcmd(arg);
21841 if (eap->skip)
21842 --emsg_skip;
21846 * Return from a function. Possibly makes the return pending. Also called
21847 * for a pending return at the ":endtry" or after returning from an extra
21848 * do_cmdline(). "reanimate" is used in the latter case. "is_cmd" is set
21849 * when called due to a ":return" command. "rettv" may point to a typval_T
21850 * with the return rettv. Returns TRUE when the return can be carried out,
21851 * FALSE when the return gets pending.
21854 do_return(eap, reanimate, is_cmd, rettv)
21855 exarg_T *eap;
21856 int reanimate;
21857 int is_cmd;
21858 void *rettv;
21860 int idx;
21861 struct condstack *cstack = eap->cstack;
21863 if (reanimate)
21864 /* Undo the return. */
21865 current_funccal->returned = FALSE;
21868 * Cleanup (and inactivate) conditionals, but stop when a try conditional
21869 * not in its finally clause (which then is to be executed next) is found.
21870 * In this case, make the ":return" pending for execution at the ":endtry".
21871 * Otherwise, return normally.
21873 idx = cleanup_conditionals(eap->cstack, 0, TRUE);
21874 if (idx >= 0)
21876 cstack->cs_pending[idx] = CSTP_RETURN;
21878 if (!is_cmd && !reanimate)
21879 /* A pending return again gets pending. "rettv" points to an
21880 * allocated variable with the rettv of the original ":return"'s
21881 * argument if present or is NULL else. */
21882 cstack->cs_rettv[idx] = rettv;
21883 else
21885 /* When undoing a return in order to make it pending, get the stored
21886 * return rettv. */
21887 if (reanimate)
21888 rettv = current_funccal->rettv;
21890 if (rettv != NULL)
21892 /* Store the value of the pending return. */
21893 if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL)
21894 *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv;
21895 else
21896 EMSG(_(e_outofmem));
21898 else
21899 cstack->cs_rettv[idx] = NULL;
21901 if (reanimate)
21903 /* The pending return value could be overwritten by a ":return"
21904 * without argument in a finally clause; reset the default
21905 * return value. */
21906 current_funccal->rettv->v_type = VAR_NUMBER;
21907 current_funccal->rettv->vval.v_number = 0;
21910 report_make_pending(CSTP_RETURN, rettv);
21912 else
21914 current_funccal->returned = TRUE;
21916 /* If the return is carried out now, store the return value. For
21917 * a return immediately after reanimation, the value is already
21918 * there. */
21919 if (!reanimate && rettv != NULL)
21921 clear_tv(current_funccal->rettv);
21922 *current_funccal->rettv = *(typval_T *)rettv;
21923 if (!is_cmd)
21924 vim_free(rettv);
21928 return idx < 0;
21932 * Free the variable with a pending return value.
21934 void
21935 discard_pending_return(rettv)
21936 void *rettv;
21938 free_tv((typval_T *)rettv);
21942 * Generate a return command for producing the value of "rettv". The result
21943 * is an allocated string. Used by report_pending() for verbose messages.
21945 char_u *
21946 get_return_cmd(rettv)
21947 void *rettv;
21949 char_u *s = NULL;
21950 char_u *tofree = NULL;
21951 char_u numbuf[NUMBUFLEN];
21953 if (rettv != NULL)
21954 s = echo_string((typval_T *)rettv, &tofree, numbuf, 0);
21955 if (s == NULL)
21956 s = (char_u *)"";
21958 STRCPY(IObuff, ":return ");
21959 STRNCPY(IObuff + 8, s, IOSIZE - 8);
21960 if (STRLEN(s) + 8 >= IOSIZE)
21961 STRCPY(IObuff + IOSIZE - 4, "...");
21962 vim_free(tofree);
21963 return vim_strsave(IObuff);
21967 * Get next function line.
21968 * Called by do_cmdline() to get the next line.
21969 * Returns allocated string, or NULL for end of function.
21971 char_u *
21972 get_func_line(c, cookie, indent)
21973 int c UNUSED;
21974 void *cookie;
21975 int indent UNUSED;
21977 funccall_T *fcp = (funccall_T *)cookie;
21978 ufunc_T *fp = fcp->func;
21979 char_u *retval;
21980 garray_T *gap; /* growarray with function lines */
21982 /* If breakpoints have been added/deleted need to check for it. */
21983 if (fcp->dbg_tick != debug_tick)
21985 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
21986 sourcing_lnum);
21987 fcp->dbg_tick = debug_tick;
21989 #ifdef FEAT_PROFILE
21990 if (do_profiling == PROF_YES)
21991 func_line_end(cookie);
21992 #endif
21994 gap = &fp->uf_lines;
21995 if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
21996 || fcp->returned)
21997 retval = NULL;
21998 else
22000 /* Skip NULL lines (continuation lines). */
22001 while (fcp->linenr < gap->ga_len
22002 && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL)
22003 ++fcp->linenr;
22004 if (fcp->linenr >= gap->ga_len)
22005 retval = NULL;
22006 else
22008 retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]);
22009 sourcing_lnum = fcp->linenr;
22010 #ifdef FEAT_PROFILE
22011 if (do_profiling == PROF_YES)
22012 func_line_start(cookie);
22013 #endif
22017 /* Did we encounter a breakpoint? */
22018 if (fcp->breakpoint != 0 && fcp->breakpoint <= sourcing_lnum)
22020 dbg_breakpoint(fp->uf_name, sourcing_lnum);
22021 /* Find next breakpoint. */
22022 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
22023 sourcing_lnum);
22024 fcp->dbg_tick = debug_tick;
22027 return retval;
22030 #if defined(FEAT_PROFILE) || defined(PROTO)
22032 * Called when starting to read a function line.
22033 * "sourcing_lnum" must be correct!
22034 * When skipping lines it may not actually be executed, but we won't find out
22035 * until later and we need to store the time now.
22037 void
22038 func_line_start(cookie)
22039 void *cookie;
22041 funccall_T *fcp = (funccall_T *)cookie;
22042 ufunc_T *fp = fcp->func;
22044 if (fp->uf_profiling && sourcing_lnum >= 1
22045 && sourcing_lnum <= fp->uf_lines.ga_len)
22047 fp->uf_tml_idx = sourcing_lnum - 1;
22048 /* Skip continuation lines. */
22049 while (fp->uf_tml_idx > 0 && FUNCLINE(fp, fp->uf_tml_idx) == NULL)
22050 --fp->uf_tml_idx;
22051 fp->uf_tml_execed = FALSE;
22052 profile_start(&fp->uf_tml_start);
22053 profile_zero(&fp->uf_tml_children);
22054 profile_get_wait(&fp->uf_tml_wait);
22059 * Called when actually executing a function line.
22061 void
22062 func_line_exec(cookie)
22063 void *cookie;
22065 funccall_T *fcp = (funccall_T *)cookie;
22066 ufunc_T *fp = fcp->func;
22068 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
22069 fp->uf_tml_execed = TRUE;
22073 * Called when done with a function line.
22075 void
22076 func_line_end(cookie)
22077 void *cookie;
22079 funccall_T *fcp = (funccall_T *)cookie;
22080 ufunc_T *fp = fcp->func;
22082 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
22084 if (fp->uf_tml_execed)
22086 ++fp->uf_tml_count[fp->uf_tml_idx];
22087 profile_end(&fp->uf_tml_start);
22088 profile_sub_wait(&fp->uf_tml_wait, &fp->uf_tml_start);
22089 profile_add(&fp->uf_tml_total[fp->uf_tml_idx], &fp->uf_tml_start);
22090 profile_self(&fp->uf_tml_self[fp->uf_tml_idx], &fp->uf_tml_start,
22091 &fp->uf_tml_children);
22093 fp->uf_tml_idx = -1;
22096 #endif
22099 * Return TRUE if the currently active function should be ended, because a
22100 * return was encountered or an error occurred. Used inside a ":while".
22103 func_has_ended(cookie)
22104 void *cookie;
22106 funccall_T *fcp = (funccall_T *)cookie;
22108 /* Ignore the "abort" flag if the abortion behavior has been changed due to
22109 * an error inside a try conditional. */
22110 return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
22111 || fcp->returned);
22115 * return TRUE if cookie indicates a function which "abort"s on errors.
22118 func_has_abort(cookie)
22119 void *cookie;
22121 return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT;
22124 #if defined(FEAT_VIMINFO) || defined(FEAT_SESSION)
22125 typedef enum
22127 VAR_FLAVOUR_DEFAULT, /* doesn't start with uppercase */
22128 VAR_FLAVOUR_SESSION, /* starts with uppercase, some lower */
22129 VAR_FLAVOUR_VIMINFO /* all uppercase */
22130 } var_flavour_T;
22132 static var_flavour_T var_flavour __ARGS((char_u *varname));
22134 static var_flavour_T
22135 var_flavour(varname)
22136 char_u *varname;
22138 char_u *p = varname;
22140 if (ASCII_ISUPPER(*p))
22142 while (*(++p))
22143 if (ASCII_ISLOWER(*p))
22144 return VAR_FLAVOUR_SESSION;
22145 return VAR_FLAVOUR_VIMINFO;
22147 else
22148 return VAR_FLAVOUR_DEFAULT;
22150 #endif
22152 #if defined(FEAT_VIMINFO) || defined(PROTO)
22154 * Restore global vars that start with a capital from the viminfo file
22157 read_viminfo_varlist(virp, writing)
22158 vir_T *virp;
22159 int writing;
22161 char_u *tab;
22162 int type = VAR_NUMBER;
22163 typval_T tv;
22165 if (!writing && (find_viminfo_parameter('!') != NULL))
22167 tab = vim_strchr(virp->vir_line + 1, '\t');
22168 if (tab != NULL)
22170 *tab++ = '\0'; /* isolate the variable name */
22171 if (*tab == 'S') /* string var */
22172 type = VAR_STRING;
22173 #ifdef FEAT_FLOAT
22174 else if (*tab == 'F')
22175 type = VAR_FLOAT;
22176 #endif
22178 tab = vim_strchr(tab, '\t');
22179 if (tab != NULL)
22181 tv.v_type = type;
22182 if (type == VAR_STRING)
22183 tv.vval.v_string = viminfo_readstring(virp,
22184 (int)(tab - virp->vir_line + 1), TRUE);
22185 #ifdef FEAT_FLOAT
22186 else if (type == VAR_FLOAT)
22187 (void)string2float(tab + 1, &tv.vval.v_float);
22188 #endif
22189 else
22190 tv.vval.v_number = atol((char *)tab + 1);
22191 set_var(virp->vir_line + 1, &tv, FALSE);
22192 if (type == VAR_STRING)
22193 vim_free(tv.vval.v_string);
22198 return viminfo_readline(virp);
22202 * Write global vars that start with a capital to the viminfo file
22204 void
22205 write_viminfo_varlist(fp)
22206 FILE *fp;
22208 hashitem_T *hi;
22209 dictitem_T *this_var;
22210 int todo;
22211 char *s;
22212 char_u *p;
22213 char_u *tofree;
22214 char_u numbuf[NUMBUFLEN];
22216 if (find_viminfo_parameter('!') == NULL)
22217 return;
22219 fputs(_("\n# global variables:\n"), fp);
22221 todo = (int)globvarht.ht_used;
22222 for (hi = globvarht.ht_array; todo > 0; ++hi)
22224 if (!HASHITEM_EMPTY(hi))
22226 --todo;
22227 this_var = HI2DI(hi);
22228 if (var_flavour(this_var->di_key) == VAR_FLAVOUR_VIMINFO)
22230 switch (this_var->di_tv.v_type)
22232 case VAR_STRING: s = "STR"; break;
22233 case VAR_NUMBER: s = "NUM"; break;
22234 #ifdef FEAT_FLOAT
22235 case VAR_FLOAT: s = "FLO"; break;
22236 #endif
22237 default: continue;
22239 fprintf(fp, "!%s\t%s\t", this_var->di_key, s);
22240 p = echo_string(&this_var->di_tv, &tofree, numbuf, 0);
22241 if (p != NULL)
22242 viminfo_writestring(fp, p);
22243 vim_free(tofree);
22248 #endif
22250 #if defined(FEAT_SESSION) || defined(PROTO)
22252 store_session_globals(fd)
22253 FILE *fd;
22255 hashitem_T *hi;
22256 dictitem_T *this_var;
22257 int todo;
22258 char_u *p, *t;
22260 todo = (int)globvarht.ht_used;
22261 for (hi = globvarht.ht_array; todo > 0; ++hi)
22263 if (!HASHITEM_EMPTY(hi))
22265 --todo;
22266 this_var = HI2DI(hi);
22267 if ((this_var->di_tv.v_type == VAR_NUMBER
22268 || this_var->di_tv.v_type == VAR_STRING)
22269 && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
22271 /* Escape special characters with a backslash. Turn a LF and
22272 * CR into \n and \r. */
22273 p = vim_strsave_escaped(get_tv_string(&this_var->di_tv),
22274 (char_u *)"\\\"\n\r");
22275 if (p == NULL) /* out of memory */
22276 break;
22277 for (t = p; *t != NUL; ++t)
22278 if (*t == '\n')
22279 *t = 'n';
22280 else if (*t == '\r')
22281 *t = 'r';
22282 if ((fprintf(fd, "let %s = %c%s%c",
22283 this_var->di_key,
22284 (this_var->di_tv.v_type == VAR_STRING) ? '"'
22285 : ' ',
22287 (this_var->di_tv.v_type == VAR_STRING) ? '"'
22288 : ' ') < 0)
22289 || put_eol(fd) == FAIL)
22291 vim_free(p);
22292 return FAIL;
22294 vim_free(p);
22296 #ifdef FEAT_FLOAT
22297 else if (this_var->di_tv.v_type == VAR_FLOAT
22298 && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
22300 float_T f = this_var->di_tv.vval.v_float;
22301 int sign = ' ';
22303 if (f < 0)
22305 f = -f;
22306 sign = '-';
22308 if ((fprintf(fd, "let %s = %c&%f",
22309 this_var->di_key, sign, f) < 0)
22310 || put_eol(fd) == FAIL)
22311 return FAIL;
22313 #endif
22316 return OK;
22318 #endif
22321 * Display script name where an item was last set.
22322 * Should only be invoked when 'verbose' is non-zero.
22324 void
22325 last_set_msg(scriptID)
22326 scid_T scriptID;
22328 char_u *p;
22330 if (scriptID != 0)
22332 p = home_replace_save(NULL, get_scriptname(scriptID));
22333 if (p != NULL)
22335 verbose_enter();
22336 MSG_PUTS(_("\n\tLast set from "));
22337 MSG_PUTS(p);
22338 vim_free(p);
22339 verbose_leave();
22345 * List v:oldfiles in a nice way.
22347 void
22348 ex_oldfiles(eap)
22349 exarg_T *eap UNUSED;
22351 list_T *l = vimvars[VV_OLDFILES].vv_list;
22352 listitem_T *li;
22353 int nr = 0;
22355 if (l == NULL)
22356 msg((char_u *)_("No old files"));
22357 else
22359 msg_start();
22360 msg_scroll = TRUE;
22361 for (li = l->lv_first; li != NULL && !got_int; li = li->li_next)
22363 msg_outnum((long)++nr);
22364 MSG_PUTS(": ");
22365 msg_outtrans(get_tv_string(&li->li_tv));
22366 msg_putchar('\n');
22367 out_flush(); /* output one line at a time */
22368 ui_breakcheck();
22370 /* Assume "got_int" was set to truncate the listing. */
22371 got_int = FALSE;
22373 #ifdef FEAT_BROWSE_CMD
22374 if (cmdmod.browse)
22376 quit_more = FALSE;
22377 nr = prompt_for_number(FALSE);
22378 msg_starthere();
22379 if (nr > 0)
22381 char_u *p = list_find_str(get_vim_var_list(VV_OLDFILES),
22382 (long)nr);
22384 if (p != NULL)
22386 p = expand_env_save(p);
22387 eap->arg = p;
22388 eap->cmdidx = CMD_edit;
22389 cmdmod.browse = FALSE;
22390 do_exedit(eap, NULL);
22391 vim_free(p);
22395 #endif
22399 #endif /* FEAT_EVAL */
22402 #if defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) || defined(PROTO)
22404 #ifdef WIN3264
22406 * Functions for ":8" filename modifier: get 8.3 version of a filename.
22408 static int get_short_pathname __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
22409 static int shortpath_for_invalid_fname __ARGS((char_u **fname, char_u **bufp, int *fnamelen));
22410 static int shortpath_for_partial __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
22413 * Get the short path (8.3) for the filename in "fnamep".
22414 * Only works for a valid file name.
22415 * When the path gets longer "fnamep" is changed and the allocated buffer
22416 * is put in "bufp".
22417 * *fnamelen is the length of "fnamep" and set to 0 for a nonexistent path.
22418 * Returns OK on success, FAIL on failure.
22420 static int
22421 get_short_pathname(fnamep, bufp, fnamelen)
22422 char_u **fnamep;
22423 char_u **bufp;
22424 int *fnamelen;
22426 int l, len;
22427 char_u *newbuf;
22429 len = *fnamelen;
22430 l = GetShortPathName(*fnamep, *fnamep, len);
22431 if (l > len - 1)
22433 /* If that doesn't work (not enough space), then save the string
22434 * and try again with a new buffer big enough. */
22435 newbuf = vim_strnsave(*fnamep, l);
22436 if (newbuf == NULL)
22437 return FAIL;
22439 vim_free(*bufp);
22440 *fnamep = *bufp = newbuf;
22442 /* Really should always succeed, as the buffer is big enough. */
22443 l = GetShortPathName(*fnamep, *fnamep, l+1);
22446 *fnamelen = l;
22447 return OK;
22451 * Get the short path (8.3) for the filename in "fname". The converted
22452 * path is returned in "bufp".
22454 * Some of the directories specified in "fname" may not exist. This function
22455 * will shorten the existing directories at the beginning of the path and then
22456 * append the remaining non-existing path.
22458 * fname - Pointer to the filename to shorten. On return, contains the
22459 * pointer to the shortened pathname
22460 * bufp - Pointer to an allocated buffer for the filename.
22461 * fnamelen - Length of the filename pointed to by fname
22463 * Returns OK on success (or nothing done) and FAIL on failure (out of memory).
22465 static int
22466 shortpath_for_invalid_fname(fname, bufp, fnamelen)
22467 char_u **fname;
22468 char_u **bufp;
22469 int *fnamelen;
22471 char_u *short_fname, *save_fname, *pbuf_unused;
22472 char_u *endp, *save_endp;
22473 char_u ch;
22474 int old_len, len;
22475 int new_len, sfx_len;
22476 int retval = OK;
22478 /* Make a copy */
22479 old_len = *fnamelen;
22480 save_fname = vim_strnsave(*fname, old_len);
22481 pbuf_unused = NULL;
22482 short_fname = NULL;
22484 endp = save_fname + old_len - 1; /* Find the end of the copy */
22485 save_endp = endp;
22488 * Try shortening the supplied path till it succeeds by removing one
22489 * directory at a time from the tail of the path.
22491 len = 0;
22492 for (;;)
22494 /* go back one path-separator */
22495 while (endp > save_fname && !after_pathsep(save_fname, endp + 1))
22496 --endp;
22497 if (endp <= save_fname)
22498 break; /* processed the complete path */
22501 * Replace the path separator with a NUL and try to shorten the
22502 * resulting path.
22504 ch = *endp;
22505 *endp = 0;
22506 short_fname = save_fname;
22507 len = (int)STRLEN(short_fname) + 1;
22508 if (get_short_pathname(&short_fname, &pbuf_unused, &len) == FAIL)
22510 retval = FAIL;
22511 goto theend;
22513 *endp = ch; /* preserve the string */
22515 if (len > 0)
22516 break; /* successfully shortened the path */
22518 /* failed to shorten the path. Skip the path separator */
22519 --endp;
22522 if (len > 0)
22525 * Succeeded in shortening the path. Now concatenate the shortened
22526 * path with the remaining path at the tail.
22529 /* Compute the length of the new path. */
22530 sfx_len = (int)(save_endp - endp) + 1;
22531 new_len = len + sfx_len;
22533 *fnamelen = new_len;
22534 vim_free(*bufp);
22535 if (new_len > old_len)
22537 /* There is not enough space in the currently allocated string,
22538 * copy it to a buffer big enough. */
22539 *fname = *bufp = vim_strnsave(short_fname, new_len);
22540 if (*fname == NULL)
22542 retval = FAIL;
22543 goto theend;
22546 else
22548 /* Transfer short_fname to the main buffer (it's big enough),
22549 * unless get_short_pathname() did its work in-place. */
22550 *fname = *bufp = save_fname;
22551 if (short_fname != save_fname)
22552 vim_strncpy(save_fname, short_fname, len);
22553 save_fname = NULL;
22556 /* concat the not-shortened part of the path */
22557 vim_strncpy(*fname + len, endp, sfx_len);
22558 (*fname)[new_len] = NUL;
22561 theend:
22562 vim_free(pbuf_unused);
22563 vim_free(save_fname);
22565 return retval;
22569 * Get a pathname for a partial path.
22570 * Returns OK for success, FAIL for failure.
22572 static int
22573 shortpath_for_partial(fnamep, bufp, fnamelen)
22574 char_u **fnamep;
22575 char_u **bufp;
22576 int *fnamelen;
22578 int sepcount, len, tflen;
22579 char_u *p;
22580 char_u *pbuf, *tfname;
22581 int hasTilde;
22583 /* Count up the path separators from the RHS.. so we know which part
22584 * of the path to return. */
22585 sepcount = 0;
22586 for (p = *fnamep; p < *fnamep + *fnamelen; mb_ptr_adv(p))
22587 if (vim_ispathsep(*p))
22588 ++sepcount;
22590 /* Need full path first (use expand_env() to remove a "~/") */
22591 hasTilde = (**fnamep == '~');
22592 if (hasTilde)
22593 pbuf = tfname = expand_env_save(*fnamep);
22594 else
22595 pbuf = tfname = FullName_save(*fnamep, FALSE);
22597 len = tflen = (int)STRLEN(tfname);
22599 if (get_short_pathname(&tfname, &pbuf, &len) == FAIL)
22600 return FAIL;
22602 if (len == 0)
22604 /* Don't have a valid filename, so shorten the rest of the
22605 * path if we can. This CAN give us invalid 8.3 filenames, but
22606 * there's not a lot of point in guessing what it might be.
22608 len = tflen;
22609 if (shortpath_for_invalid_fname(&tfname, &pbuf, &len) == FAIL)
22610 return FAIL;
22613 /* Count the paths backward to find the beginning of the desired string. */
22614 for (p = tfname + len - 1; p >= tfname; --p)
22616 #ifdef FEAT_MBYTE
22617 if (has_mbyte)
22618 p -= mb_head_off(tfname, p);
22619 #endif
22620 if (vim_ispathsep(*p))
22622 if (sepcount == 0 || (hasTilde && sepcount == 1))
22623 break;
22624 else
22625 sepcount --;
22628 if (hasTilde)
22630 --p;
22631 if (p >= tfname)
22632 *p = '~';
22633 else
22634 return FAIL;
22636 else
22637 ++p;
22639 /* Copy in the string - p indexes into tfname - allocated at pbuf */
22640 vim_free(*bufp);
22641 *fnamelen = (int)STRLEN(p);
22642 *bufp = pbuf;
22643 *fnamep = p;
22645 return OK;
22647 #endif /* WIN3264 */
22650 * Adjust a filename, according to a string of modifiers.
22651 * *fnamep must be NUL terminated when called. When returning, the length is
22652 * determined by *fnamelen.
22653 * Returns VALID_ flags or -1 for failure.
22654 * When there is an error, *fnamep is set to NULL.
22657 modify_fname(src, usedlen, fnamep, bufp, fnamelen)
22658 char_u *src; /* string with modifiers */
22659 int *usedlen; /* characters after src that are used */
22660 char_u **fnamep; /* file name so far */
22661 char_u **bufp; /* buffer for allocated file name or NULL */
22662 int *fnamelen; /* length of fnamep */
22664 int valid = 0;
22665 char_u *tail;
22666 char_u *s, *p, *pbuf;
22667 char_u dirname[MAXPATHL];
22668 int c;
22669 int has_fullname = 0;
22670 #ifdef WIN3264
22671 int has_shortname = 0;
22672 #endif
22674 repeat:
22675 /* ":p" - full path/file_name */
22676 if (src[*usedlen] == ':' && src[*usedlen + 1] == 'p')
22678 has_fullname = 1;
22680 valid |= VALID_PATH;
22681 *usedlen += 2;
22683 /* Expand "~/path" for all systems and "~user/path" for Unix and VMS */
22684 if ((*fnamep)[0] == '~'
22685 #if !defined(UNIX) && !(defined(VMS) && defined(USER_HOME))
22686 && ((*fnamep)[1] == '/'
22687 # ifdef BACKSLASH_IN_FILENAME
22688 || (*fnamep)[1] == '\\'
22689 # endif
22690 || (*fnamep)[1] == NUL)
22692 #endif
22695 *fnamep = expand_env_save(*fnamep);
22696 vim_free(*bufp); /* free any allocated file name */
22697 *bufp = *fnamep;
22698 if (*fnamep == NULL)
22699 return -1;
22702 /* When "/." or "/.." is used: force expansion to get rid of it. */
22703 for (p = *fnamep; *p != NUL; mb_ptr_adv(p))
22705 if (vim_ispathsep(*p)
22706 && p[1] == '.'
22707 && (p[2] == NUL
22708 || vim_ispathsep(p[2])
22709 || (p[2] == '.'
22710 && (p[3] == NUL || vim_ispathsep(p[3])))))
22711 break;
22714 /* FullName_save() is slow, don't use it when not needed. */
22715 if (*p != NUL || !vim_isAbsName(*fnamep))
22717 *fnamep = FullName_save(*fnamep, *p != NUL);
22718 vim_free(*bufp); /* free any allocated file name */
22719 *bufp = *fnamep;
22720 if (*fnamep == NULL)
22721 return -1;
22724 /* Append a path separator to a directory. */
22725 if (mch_isdir(*fnamep))
22727 /* Make room for one or two extra characters. */
22728 *fnamep = vim_strnsave(*fnamep, (int)STRLEN(*fnamep) + 2);
22729 vim_free(*bufp); /* free any allocated file name */
22730 *bufp = *fnamep;
22731 if (*fnamep == NULL)
22732 return -1;
22733 add_pathsep(*fnamep);
22737 /* ":." - path relative to the current directory */
22738 /* ":~" - path relative to the home directory */
22739 /* ":8" - shortname path - postponed till after */
22740 while (src[*usedlen] == ':'
22741 && ((c = src[*usedlen + 1]) == '.' || c == '~' || c == '8'))
22743 *usedlen += 2;
22744 if (c == '8')
22746 #ifdef WIN3264
22747 has_shortname = 1; /* Postpone this. */
22748 #endif
22749 continue;
22751 pbuf = NULL;
22752 /* Need full path first (use expand_env() to remove a "~/") */
22753 if (!has_fullname)
22755 if (c == '.' && **fnamep == '~')
22756 p = pbuf = expand_env_save(*fnamep);
22757 else
22758 p = pbuf = FullName_save(*fnamep, FALSE);
22760 else
22761 p = *fnamep;
22763 has_fullname = 0;
22765 if (p != NULL)
22767 if (c == '.')
22769 mch_dirname(dirname, MAXPATHL);
22770 s = shorten_fname(p, dirname);
22771 if (s != NULL)
22773 *fnamep = s;
22774 if (pbuf != NULL)
22776 vim_free(*bufp); /* free any allocated file name */
22777 *bufp = pbuf;
22778 pbuf = NULL;
22782 else
22784 home_replace(NULL, p, dirname, MAXPATHL, TRUE);
22785 /* Only replace it when it starts with '~' */
22786 if (*dirname == '~')
22788 s = vim_strsave(dirname);
22789 if (s != NULL)
22791 *fnamep = s;
22792 vim_free(*bufp);
22793 *bufp = s;
22797 vim_free(pbuf);
22801 tail = gettail(*fnamep);
22802 *fnamelen = (int)STRLEN(*fnamep);
22804 /* ":h" - head, remove "/file_name", can be repeated */
22805 /* Don't remove the first "/" or "c:\" */
22806 while (src[*usedlen] == ':' && src[*usedlen + 1] == 'h')
22808 valid |= VALID_HEAD;
22809 *usedlen += 2;
22810 s = get_past_head(*fnamep);
22811 while (tail > s && after_pathsep(s, tail))
22812 mb_ptr_back(*fnamep, tail);
22813 *fnamelen = (int)(tail - *fnamep);
22814 #ifdef VMS
22815 if (*fnamelen > 0)
22816 *fnamelen += 1; /* the path separator is part of the path */
22817 #endif
22818 if (*fnamelen == 0)
22820 /* Result is empty. Turn it into "." to make ":cd %:h" work. */
22821 p = vim_strsave((char_u *)".");
22822 if (p == NULL)
22823 return -1;
22824 vim_free(*bufp);
22825 *bufp = *fnamep = tail = p;
22826 *fnamelen = 1;
22828 else
22830 while (tail > s && !after_pathsep(s, tail))
22831 mb_ptr_back(*fnamep, tail);
22835 /* ":8" - shortname */
22836 if (src[*usedlen] == ':' && src[*usedlen + 1] == '8')
22838 *usedlen += 2;
22839 #ifdef WIN3264
22840 has_shortname = 1;
22841 #endif
22844 #ifdef WIN3264
22845 /* Check shortname after we have done 'heads' and before we do 'tails'
22847 if (has_shortname)
22849 pbuf = NULL;
22850 /* Copy the string if it is shortened by :h */
22851 if (*fnamelen < (int)STRLEN(*fnamep))
22853 p = vim_strnsave(*fnamep, *fnamelen);
22854 if (p == 0)
22855 return -1;
22856 vim_free(*bufp);
22857 *bufp = *fnamep = p;
22860 /* Split into two implementations - makes it easier. First is where
22861 * there isn't a full name already, second is where there is.
22863 if (!has_fullname && !vim_isAbsName(*fnamep))
22865 if (shortpath_for_partial(fnamep, bufp, fnamelen) == FAIL)
22866 return -1;
22868 else
22870 int l;
22872 /* Simple case, already have the full-name
22873 * Nearly always shorter, so try first time. */
22874 l = *fnamelen;
22875 if (get_short_pathname(fnamep, bufp, &l) == FAIL)
22876 return -1;
22878 if (l == 0)
22880 /* Couldn't find the filename.. search the paths.
22882 l = *fnamelen;
22883 if (shortpath_for_invalid_fname(fnamep, bufp, &l) == FAIL)
22884 return -1;
22886 *fnamelen = l;
22889 #endif /* WIN3264 */
22891 /* ":t" - tail, just the basename */
22892 if (src[*usedlen] == ':' && src[*usedlen + 1] == 't')
22894 *usedlen += 2;
22895 *fnamelen -= (int)(tail - *fnamep);
22896 *fnamep = tail;
22899 /* ":e" - extension, can be repeated */
22900 /* ":r" - root, without extension, can be repeated */
22901 while (src[*usedlen] == ':'
22902 && (src[*usedlen + 1] == 'e' || src[*usedlen + 1] == 'r'))
22904 /* find a '.' in the tail:
22905 * - for second :e: before the current fname
22906 * - otherwise: The last '.'
22908 if (src[*usedlen + 1] == 'e' && *fnamep > tail)
22909 s = *fnamep - 2;
22910 else
22911 s = *fnamep + *fnamelen - 1;
22912 for ( ; s > tail; --s)
22913 if (s[0] == '.')
22914 break;
22915 if (src[*usedlen + 1] == 'e') /* :e */
22917 if (s > tail)
22919 *fnamelen += (int)(*fnamep - (s + 1));
22920 *fnamep = s + 1;
22921 #ifdef VMS
22922 /* cut version from the extension */
22923 s = *fnamep + *fnamelen - 1;
22924 for ( ; s > *fnamep; --s)
22925 if (s[0] == ';')
22926 break;
22927 if (s > *fnamep)
22928 *fnamelen = s - *fnamep;
22929 #endif
22931 else if (*fnamep <= tail)
22932 *fnamelen = 0;
22934 else /* :r */
22936 if (s > tail) /* remove one extension */
22937 *fnamelen = (int)(s - *fnamep);
22939 *usedlen += 2;
22942 /* ":s?pat?foo?" - substitute */
22943 /* ":gs?pat?foo?" - global substitute */
22944 if (src[*usedlen] == ':'
22945 && (src[*usedlen + 1] == 's'
22946 || (src[*usedlen + 1] == 'g' && src[*usedlen + 2] == 's')))
22948 char_u *str;
22949 char_u *pat;
22950 char_u *sub;
22951 int sep;
22952 char_u *flags;
22953 int didit = FALSE;
22955 flags = (char_u *)"";
22956 s = src + *usedlen + 2;
22957 if (src[*usedlen + 1] == 'g')
22959 flags = (char_u *)"g";
22960 ++s;
22963 sep = *s++;
22964 if (sep)
22966 /* find end of pattern */
22967 p = vim_strchr(s, sep);
22968 if (p != NULL)
22970 pat = vim_strnsave(s, (int)(p - s));
22971 if (pat != NULL)
22973 s = p + 1;
22974 /* find end of substitution */
22975 p = vim_strchr(s, sep);
22976 if (p != NULL)
22978 sub = vim_strnsave(s, (int)(p - s));
22979 str = vim_strnsave(*fnamep, *fnamelen);
22980 if (sub != NULL && str != NULL)
22982 *usedlen = (int)(p + 1 - src);
22983 s = do_string_sub(str, pat, sub, flags);
22984 if (s != NULL)
22986 *fnamep = s;
22987 *fnamelen = (int)STRLEN(s);
22988 vim_free(*bufp);
22989 *bufp = s;
22990 didit = TRUE;
22993 vim_free(sub);
22994 vim_free(str);
22996 vim_free(pat);
22999 /* after using ":s", repeat all the modifiers */
23000 if (didit)
23001 goto repeat;
23005 return valid;
23009 * Perform a substitution on "str" with pattern "pat" and substitute "sub".
23010 * "flags" can be "g" to do a global substitute.
23011 * Returns an allocated string, NULL for error.
23013 char_u *
23014 do_string_sub(str, pat, sub, flags)
23015 char_u *str;
23016 char_u *pat;
23017 char_u *sub;
23018 char_u *flags;
23020 int sublen;
23021 regmatch_T regmatch;
23022 int i;
23023 int do_all;
23024 char_u *tail;
23025 garray_T ga;
23026 char_u *ret;
23027 char_u *save_cpo;
23029 /* Make 'cpoptions' empty, so that the 'l' flag doesn't work here */
23030 save_cpo = p_cpo;
23031 p_cpo = empty_option;
23033 ga_init2(&ga, 1, 200);
23035 do_all = (flags[0] == 'g');
23037 regmatch.rm_ic = p_ic;
23038 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
23039 if (regmatch.regprog != NULL)
23041 tail = str;
23042 while (vim_regexec_nl(&regmatch, str, (colnr_T)(tail - str)))
23045 * Get some space for a temporary buffer to do the substitution
23046 * into. It will contain:
23047 * - The text up to where the match is.
23048 * - The substituted text.
23049 * - The text after the match.
23051 sublen = vim_regsub(&regmatch, sub, tail, FALSE, TRUE, FALSE);
23052 if (ga_grow(&ga, (int)(STRLEN(tail) + sublen -
23053 (regmatch.endp[0] - regmatch.startp[0]))) == FAIL)
23055 ga_clear(&ga);
23056 break;
23059 /* copy the text up to where the match is */
23060 i = (int)(regmatch.startp[0] - tail);
23061 mch_memmove((char_u *)ga.ga_data + ga.ga_len, tail, (size_t)i);
23062 /* add the substituted text */
23063 (void)vim_regsub(&regmatch, sub, (char_u *)ga.ga_data
23064 + ga.ga_len + i, TRUE, TRUE, FALSE);
23065 ga.ga_len += i + sublen - 1;
23066 /* avoid getting stuck on a match with an empty string */
23067 if (tail == regmatch.endp[0])
23069 if (*tail == NUL)
23070 break;
23071 *((char_u *)ga.ga_data + ga.ga_len) = *tail++;
23072 ++ga.ga_len;
23074 else
23076 tail = regmatch.endp[0];
23077 if (*tail == NUL)
23078 break;
23080 if (!do_all)
23081 break;
23084 if (ga.ga_data != NULL)
23085 STRCPY((char *)ga.ga_data + ga.ga_len, tail);
23087 vim_free(regmatch.regprog);
23090 ret = vim_strsave(ga.ga_data == NULL ? str : (char_u *)ga.ga_data);
23091 ga_clear(&ga);
23092 if (p_cpo == empty_option)
23093 p_cpo = save_cpo;
23094 else
23095 /* Darn, evaluating {sub} expression changed the value. */
23096 free_string_option(save_cpo);
23098 return ret;
23101 #endif /* defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) */