Merge branch 'vim-with-runtime' into feat/float-point-ext
[vim_extended.git] / src / eval.c
blobfa2ff61ebe40c363961169310dfa5d37d3cfccc4
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(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;
7013 * Get the number of items in a Dictionary.
7015 static long
7016 dict_len(d)
7017 dict_T *d;
7019 if (d == NULL)
7020 return 0L;
7021 return (long)d->dv_hashtab.ht_used;
7025 * Find item "key[len]" in Dictionary "d".
7026 * If "len" is negative use strlen(key).
7027 * Returns NULL when not found.
7029 dictitem_T *
7030 dict_find(d, key, len)
7031 dict_T *d;
7032 char_u *key;
7033 int len;
7035 #define AKEYLEN 200
7036 char_u buf[AKEYLEN];
7037 char_u *akey;
7038 char_u *tofree = NULL;
7039 hashitem_T *hi;
7041 if (len < 0)
7042 akey = key;
7043 else if (len >= AKEYLEN)
7045 tofree = akey = vim_strnsave(key, len);
7046 if (akey == NULL)
7047 return NULL;
7049 else
7051 /* Avoid a malloc/free by using buf[]. */
7052 vim_strncpy(buf, key, len);
7053 akey = buf;
7056 hi = hash_find(&d->dv_hashtab, akey);
7057 vim_free(tofree);
7058 if (HASHITEM_EMPTY(hi))
7059 return NULL;
7060 return HI2DI(hi);
7064 * Get a string item from a dictionary.
7065 * When "save" is TRUE allocate memory for it.
7066 * Returns NULL if the entry doesn't exist or out of memory.
7068 char_u *
7069 get_dict_string(d, key, save)
7070 dict_T *d;
7071 char_u *key;
7072 int save;
7074 dictitem_T *di;
7075 char_u *s;
7077 di = dict_find(d, key, -1);
7078 if (di == NULL)
7079 return NULL;
7080 s = get_tv_string(&di->di_tv);
7081 if (save && s != NULL)
7082 s = vim_strsave(s);
7083 return s;
7087 * Get a number item from a dictionary.
7088 * Returns 0 if the entry doesn't exist or out of memory.
7090 long
7091 get_dict_number(d, key)
7092 dict_T *d;
7093 char_u *key;
7095 dictitem_T *di;
7097 di = dict_find(d, key, -1);
7098 if (di == NULL)
7099 return 0;
7100 return get_tv_number(&di->di_tv);
7104 * Return an allocated string with the string representation of a Dictionary.
7105 * May return NULL.
7107 static char_u *
7108 dict2string(tv, copyID)
7109 typval_T *tv;
7110 int copyID;
7112 garray_T ga;
7113 int first = TRUE;
7114 char_u *tofree;
7115 char_u numbuf[NUMBUFLEN];
7116 hashitem_T *hi;
7117 char_u *s;
7118 dict_T *d;
7119 int todo;
7121 if ((d = tv->vval.v_dict) == NULL)
7122 return NULL;
7123 ga_init2(&ga, (int)sizeof(char), 80);
7124 ga_append(&ga, '{');
7126 todo = (int)d->dv_hashtab.ht_used;
7127 for (hi = d->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
7129 if (!HASHITEM_EMPTY(hi))
7131 --todo;
7133 if (first)
7134 first = FALSE;
7135 else
7136 ga_concat(&ga, (char_u *)", ");
7138 tofree = string_quote(hi->hi_key, FALSE);
7139 if (tofree != NULL)
7141 ga_concat(&ga, tofree);
7142 vim_free(tofree);
7144 ga_concat(&ga, (char_u *)": ");
7145 s = tv2string(&HI2DI(hi)->di_tv, &tofree, numbuf, copyID);
7146 if (s != NULL)
7147 ga_concat(&ga, s);
7148 vim_free(tofree);
7149 if (s == NULL)
7150 break;
7153 if (todo > 0)
7155 vim_free(ga.ga_data);
7156 return NULL;
7159 ga_append(&ga, '}');
7160 ga_append(&ga, NUL);
7161 return (char_u *)ga.ga_data;
7165 * Allocate a variable for a Dictionary and fill it from "*arg".
7166 * Return OK or FAIL. Returns NOTDONE for {expr}.
7168 static int
7169 get_dict_tv(arg, rettv, evaluate)
7170 char_u **arg;
7171 typval_T *rettv;
7172 int evaluate;
7174 dict_T *d = NULL;
7175 typval_T tvkey;
7176 typval_T tv;
7177 char_u *key = NULL;
7178 dictitem_T *item;
7179 char_u *start = skipwhite(*arg + 1);
7180 char_u buf[NUMBUFLEN];
7183 * First check if it's not a curly-braces thing: {expr}.
7184 * Must do this without evaluating, otherwise a function may be called
7185 * twice. Unfortunately this means we need to call eval1() twice for the
7186 * first item.
7187 * But {} is an empty Dictionary.
7189 if (*start != '}')
7191 if (eval1(&start, &tv, FALSE) == FAIL) /* recursive! */
7192 return FAIL;
7193 if (*start == '}')
7194 return NOTDONE;
7197 if (evaluate)
7199 d = dict_alloc();
7200 if (d == NULL)
7201 return FAIL;
7203 tvkey.v_type = VAR_UNKNOWN;
7204 tv.v_type = VAR_UNKNOWN;
7206 *arg = skipwhite(*arg + 1);
7207 while (**arg != '}' && **arg != NUL)
7209 if (eval1(arg, &tvkey, evaluate) == FAIL) /* recursive! */
7210 goto failret;
7211 if (**arg != ':')
7213 EMSG2(_("E720: Missing colon in Dictionary: %s"), *arg);
7214 clear_tv(&tvkey);
7215 goto failret;
7217 if (evaluate)
7219 key = get_tv_string_buf_chk(&tvkey, buf);
7220 if (key == NULL || *key == NUL)
7222 /* "key" is NULL when get_tv_string_buf_chk() gave an errmsg */
7223 if (key != NULL)
7224 EMSG(_(e_emptykey));
7225 clear_tv(&tvkey);
7226 goto failret;
7230 *arg = skipwhite(*arg + 1);
7231 if (eval1(arg, &tv, evaluate) == FAIL) /* recursive! */
7233 if (evaluate)
7234 clear_tv(&tvkey);
7235 goto failret;
7237 if (evaluate)
7239 item = dict_find(d, key, -1);
7240 if (item != NULL)
7242 EMSG2(_("E721: Duplicate key in Dictionary: \"%s\""), key);
7243 clear_tv(&tvkey);
7244 clear_tv(&tv);
7245 goto failret;
7247 item = dictitem_alloc(key);
7248 clear_tv(&tvkey);
7249 if (item != NULL)
7251 item->di_tv = tv;
7252 item->di_tv.v_lock = 0;
7253 if (dict_add(d, item) == FAIL)
7254 dictitem_free(item);
7258 if (**arg == '}')
7259 break;
7260 if (**arg != ',')
7262 EMSG2(_("E722: Missing comma in Dictionary: %s"), *arg);
7263 goto failret;
7265 *arg = skipwhite(*arg + 1);
7268 if (**arg != '}')
7270 EMSG2(_("E723: Missing end of Dictionary '}': %s"), *arg);
7271 failret:
7272 if (evaluate)
7273 dict_free(d, TRUE);
7274 return FAIL;
7277 *arg = skipwhite(*arg + 1);
7278 if (evaluate)
7280 rettv->v_type = VAR_DICT;
7281 rettv->vval.v_dict = d;
7282 ++d->dv_refcount;
7285 return OK;
7289 * Return a string with the string representation of a variable.
7290 * If the memory is allocated "tofree" is set to it, otherwise NULL.
7291 * "numbuf" is used for a number.
7292 * Does not put quotes around strings, as ":echo" displays values.
7293 * When "copyID" is not NULL replace recursive lists and dicts with "...".
7294 * May return NULL.
7296 static char_u *
7297 echo_string(tv, tofree, numbuf, copyID)
7298 typval_T *tv;
7299 char_u **tofree;
7300 char_u *numbuf;
7301 int copyID;
7303 static int recurse = 0;
7304 char_u *r = NULL;
7306 if (recurse >= DICT_MAXNEST)
7308 EMSG(_("E724: variable nested too deep for displaying"));
7309 *tofree = NULL;
7310 return NULL;
7312 ++recurse;
7314 switch (tv->v_type)
7316 case VAR_FUNC:
7317 *tofree = NULL;
7318 r = tv->vval.v_string;
7319 break;
7321 case VAR_LIST:
7322 if (tv->vval.v_list == NULL)
7324 *tofree = NULL;
7325 r = NULL;
7327 else if (copyID != 0 && tv->vval.v_list->lv_copyID == copyID)
7329 *tofree = NULL;
7330 r = (char_u *)"[...]";
7332 else
7334 tv->vval.v_list->lv_copyID = copyID;
7335 *tofree = list2string(tv, copyID);
7336 r = *tofree;
7338 break;
7340 case VAR_DICT:
7341 if (tv->vval.v_dict == NULL)
7343 *tofree = NULL;
7344 r = NULL;
7346 else if (copyID != 0 && tv->vval.v_dict->dv_copyID == copyID)
7348 *tofree = NULL;
7349 r = (char_u *)"{...}";
7351 else
7353 tv->vval.v_dict->dv_copyID = copyID;
7354 *tofree = dict2string(tv, copyID);
7355 r = *tofree;
7357 break;
7359 case VAR_STRING:
7360 case VAR_NUMBER:
7361 *tofree = NULL;
7362 r = get_tv_string_buf(tv, numbuf);
7363 break;
7365 #ifdef FEAT_FLOAT
7366 case VAR_FLOAT:
7367 *tofree = NULL;
7368 vim_snprintf((char *)numbuf, NUMBUFLEN, "%g", tv->vval.v_float);
7369 r = numbuf;
7370 break;
7371 #endif
7373 default:
7374 EMSG2(_(e_intern2), "echo_string()");
7375 *tofree = NULL;
7378 --recurse;
7379 return r;
7383 * Return a string with the string representation of a variable.
7384 * If the memory is allocated "tofree" is set to it, otherwise NULL.
7385 * "numbuf" is used for a number.
7386 * Puts quotes around strings, so that they can be parsed back by eval().
7387 * May return NULL.
7389 static char_u *
7390 tv2string(tv, tofree, numbuf, copyID)
7391 typval_T *tv;
7392 char_u **tofree;
7393 char_u *numbuf;
7394 int copyID;
7396 switch (tv->v_type)
7398 case VAR_FUNC:
7399 *tofree = string_quote(tv->vval.v_string, TRUE);
7400 return *tofree;
7401 case VAR_STRING:
7402 *tofree = string_quote(tv->vval.v_string, FALSE);
7403 return *tofree;
7404 #ifdef FEAT_FLOAT
7405 case VAR_FLOAT:
7406 *tofree = NULL;
7407 vim_snprintf((char *)numbuf, NUMBUFLEN - 1, "%g", tv->vval.v_float);
7408 return numbuf;
7409 #endif
7410 case VAR_NUMBER:
7411 case VAR_LIST:
7412 case VAR_DICT:
7413 break;
7414 default:
7415 EMSG2(_(e_intern2), "tv2string()");
7417 return echo_string(tv, tofree, numbuf, copyID);
7421 * Return string "str" in ' quotes, doubling ' characters.
7422 * If "str" is NULL an empty string is assumed.
7423 * If "function" is TRUE make it function('string').
7425 static char_u *
7426 string_quote(str, function)
7427 char_u *str;
7428 int function;
7430 unsigned len;
7431 char_u *p, *r, *s;
7433 len = (function ? 13 : 3);
7434 if (str != NULL)
7436 len += (unsigned)STRLEN(str);
7437 for (p = str; *p != NUL; mb_ptr_adv(p))
7438 if (*p == '\'')
7439 ++len;
7441 s = r = alloc(len);
7442 if (r != NULL)
7444 if (function)
7446 STRCPY(r, "function('");
7447 r += 10;
7449 else
7450 *r++ = '\'';
7451 if (str != NULL)
7452 for (p = str; *p != NUL; )
7454 if (*p == '\'')
7455 *r++ = '\'';
7456 MB_COPY_CHAR(p, r);
7458 *r++ = '\'';
7459 if (function)
7460 *r++ = ')';
7461 *r++ = NUL;
7463 return s;
7466 #ifdef FEAT_FLOAT
7468 * Convert the string "text" to a floating point number.
7469 * This uses strtod(). setlocale(LC_NUMERIC, "C") has been used to make sure
7470 * this always uses a decimal point.
7471 * Returns the length of the text that was consumed.
7473 static int
7474 string2float(text, value)
7475 char_u *text;
7476 float_T *value; /* result stored here */
7478 char *s = (char *)text;
7479 float_T f;
7481 f = strtod(s, &s);
7482 *value = f;
7483 return (int)((char_u *)s - text);
7485 #endif
7488 * Get the value of an environment variable.
7489 * "arg" is pointing to the '$'. It is advanced to after the name.
7490 * If the environment variable was not set, silently assume it is empty.
7491 * Always return OK.
7493 static int
7494 get_env_tv(arg, rettv, evaluate)
7495 char_u **arg;
7496 typval_T *rettv;
7497 int evaluate;
7499 char_u *string = NULL;
7500 int len;
7501 int cc;
7502 char_u *name;
7503 int mustfree = FALSE;
7505 ++*arg;
7506 name = *arg;
7507 len = get_env_len(arg);
7508 if (evaluate)
7510 if (len != 0)
7512 cc = name[len];
7513 name[len] = NUL;
7514 /* first try vim_getenv(), fast for normal environment vars */
7515 string = vim_getenv(name, &mustfree);
7516 if (string != NULL && *string != NUL)
7518 if (!mustfree)
7519 string = vim_strsave(string);
7521 else
7523 if (mustfree)
7524 vim_free(string);
7526 /* next try expanding things like $VIM and ${HOME} */
7527 string = expand_env_save(name - 1);
7528 if (string != NULL && *string == '$')
7530 vim_free(string);
7531 string = NULL;
7534 name[len] = cc;
7536 rettv->v_type = VAR_STRING;
7537 rettv->vval.v_string = string;
7540 return OK;
7544 * Array with names and number of arguments of all internal functions
7545 * MUST BE KEPT SORTED IN strcmp() ORDER FOR BINARY SEARCH!
7547 static struct fst
7549 char *f_name; /* function name */
7550 char f_min_argc; /* minimal number of arguments */
7551 char f_max_argc; /* maximal number of arguments */
7552 void (*f_func) __ARGS((typval_T *args, typval_T *rvar));
7553 /* implementation of function */
7554 } functions[] =
7556 #ifdef FEAT_FLOAT
7557 {"abs", 1, 1, f_abs},
7558 {"acos", 1, 1, f_acos}, /* WJMc */
7559 #endif
7560 {"add", 2, 2, f_add},
7561 {"append", 2, 2, f_append},
7562 {"argc", 0, 0, f_argc},
7563 {"argidx", 0, 0, f_argidx},
7564 {"argv", 0, 1, f_argv},
7565 #ifdef FEAT_FLOAT
7566 {"asin", 1, 1, f_asin}, /* WJMc */
7567 {"atan", 1, 1, f_atan},
7568 {"atan2", 2, 2, f_atan2}, /* WJMc */
7569 #endif
7570 {"browse", 4, 4, f_browse},
7571 {"browsedir", 2, 2, f_browsedir},
7572 {"bufexists", 1, 1, f_bufexists},
7573 {"buffer_exists", 1, 1, f_bufexists}, /* obsolete */
7574 {"buffer_name", 1, 1, f_bufname}, /* obsolete */
7575 {"buffer_number", 1, 1, f_bufnr}, /* obsolete */
7576 {"buflisted", 1, 1, f_buflisted},
7577 {"bufloaded", 1, 1, f_bufloaded},
7578 {"bufname", 1, 1, f_bufname},
7579 {"bufnr", 1, 2, f_bufnr},
7580 {"bufwinnr", 1, 1, f_bufwinnr},
7581 {"byte2line", 1, 1, f_byte2line},
7582 {"byteidx", 2, 2, f_byteidx},
7583 {"call", 2, 3, f_call},
7584 #ifdef FEAT_FLOAT
7585 {"ceil", 1, 1, f_ceil},
7586 #endif
7587 {"changenr", 0, 0, f_changenr},
7588 {"char2nr", 1, 1, f_char2nr},
7589 {"cindent", 1, 1, f_cindent},
7590 {"clearmatches", 0, 0, f_clearmatches},
7591 {"col", 1, 1, f_col},
7592 #if defined(FEAT_INS_EXPAND)
7593 {"complete", 2, 2, f_complete},
7594 {"complete_add", 1, 1, f_complete_add},
7595 {"complete_check", 0, 0, f_complete_check},
7596 #endif
7597 {"confirm", 1, 4, f_confirm},
7598 {"copy", 1, 1, f_copy},
7599 #ifdef FEAT_FLOAT
7600 {"cos", 1, 1, f_cos},
7601 {"cosh", 1, 1, f_cosh}, /* WJMc */
7602 #endif
7603 {"count", 2, 4, f_count},
7604 {"cscope_connection",0,3, f_cscope_connection},
7605 {"cursor", 1, 3, f_cursor},
7606 {"deepcopy", 1, 2, f_deepcopy},
7607 {"delete", 1, 1, f_delete},
7608 {"did_filetype", 0, 0, f_did_filetype},
7609 {"diff_filler", 1, 1, f_diff_filler},
7610 {"diff_hlID", 2, 2, f_diff_hlID},
7611 {"empty", 1, 1, f_empty},
7612 {"escape", 2, 2, f_escape},
7613 {"eval", 1, 1, f_eval},
7614 {"eventhandler", 0, 0, f_eventhandler},
7615 {"executable", 1, 1, f_executable},
7616 {"exists", 1, 1, f_exists},
7617 #ifdef FEAT_FLOAT
7618 {"exp", 1, 1, f_exp}, /* WJMc */
7619 #endif
7620 {"expand", 1, 2, f_expand},
7621 {"extend", 2, 3, f_extend},
7622 {"feedkeys", 1, 2, f_feedkeys},
7623 {"file_readable", 1, 1, f_filereadable}, /* obsolete */
7624 {"filereadable", 1, 1, f_filereadable},
7625 {"filewritable", 1, 1, f_filewritable},
7626 {"filter", 2, 2, f_filter},
7627 {"finddir", 1, 3, f_finddir},
7628 {"findfile", 1, 3, f_findfile},
7629 #ifdef FEAT_FLOAT
7630 {"float2nr", 1, 1, f_float2nr},
7631 {"floor", 1, 1, f_floor},
7632 {"fmod", 2, 2, f_fmod}, /* WJMc */
7633 #endif
7634 {"fnameescape", 1, 1, f_fnameescape},
7635 {"fnamemodify", 2, 2, f_fnamemodify},
7636 {"foldclosed", 1, 1, f_foldclosed},
7637 {"foldclosedend", 1, 1, f_foldclosedend},
7638 {"foldlevel", 1, 1, f_foldlevel},
7639 {"foldtext", 0, 0, f_foldtext},
7640 {"foldtextresult", 1, 1, f_foldtextresult},
7641 {"foreground", 0, 0, f_foreground},
7642 {"function", 1, 1, f_function},
7643 {"garbagecollect", 0, 1, f_garbagecollect},
7644 {"get", 2, 3, f_get},
7645 {"getbufline", 2, 3, f_getbufline},
7646 {"getbufvar", 2, 2, f_getbufvar},
7647 {"getchar", 0, 1, f_getchar},
7648 {"getcharmod", 0, 0, f_getcharmod},
7649 {"getcmdline", 0, 0, f_getcmdline},
7650 {"getcmdpos", 0, 0, f_getcmdpos},
7651 {"getcmdtype", 0, 0, f_getcmdtype},
7652 {"getcwd", 0, 0, f_getcwd},
7653 {"getfontname", 0, 1, f_getfontname},
7654 {"getfperm", 1, 1, f_getfperm},
7655 {"getfsize", 1, 1, f_getfsize},
7656 {"getftime", 1, 1, f_getftime},
7657 {"getftype", 1, 1, f_getftype},
7658 {"getline", 1, 2, f_getline},
7659 {"getloclist", 1, 1, f_getqflist},
7660 {"getmatches", 0, 0, f_getmatches},
7661 {"getpid", 0, 0, f_getpid},
7662 {"getpos", 1, 1, f_getpos},
7663 {"getqflist", 0, 0, f_getqflist},
7664 {"getreg", 0, 2, f_getreg},
7665 {"getregtype", 0, 1, f_getregtype},
7666 {"gettabwinvar", 3, 3, f_gettabwinvar},
7667 {"getwinposx", 0, 0, f_getwinposx},
7668 {"getwinposy", 0, 0, f_getwinposy},
7669 {"getwinvar", 2, 2, f_getwinvar},
7670 {"glob", 1, 2, f_glob},
7671 {"globpath", 2, 3, f_globpath},
7672 {"has", 1, 1, f_has},
7673 {"has_key", 2, 2, f_has_key},
7674 {"haslocaldir", 0, 0, f_haslocaldir},
7675 {"hasmapto", 1, 3, f_hasmapto},
7676 {"highlightID", 1, 1, f_hlID}, /* obsolete */
7677 {"highlight_exists",1, 1, f_hlexists}, /* obsolete */
7678 {"histadd", 2, 2, f_histadd},
7679 {"histdel", 1, 2, f_histdel},
7680 {"histget", 1, 2, f_histget},
7681 {"histnr", 1, 1, f_histnr},
7682 {"hlID", 1, 1, f_hlID},
7683 {"hlexists", 1, 1, f_hlexists},
7684 {"hostname", 0, 0, f_hostname},
7685 {"iconv", 3, 3, f_iconv},
7686 {"indent", 1, 1, f_indent},
7687 {"index", 2, 4, f_index},
7688 {"input", 1, 3, f_input},
7689 {"inputdialog", 1, 3, f_inputdialog},
7690 {"inputlist", 1, 1, f_inputlist},
7691 {"inputrestore", 0, 0, f_inputrestore},
7692 {"inputsave", 0, 0, f_inputsave},
7693 {"inputsecret", 1, 2, f_inputsecret},
7694 {"insert", 2, 3, f_insert},
7695 {"isdirectory", 1, 1, f_isdirectory},
7696 {"islocked", 1, 1, f_islocked},
7697 {"items", 1, 1, f_items},
7698 {"join", 1, 2, f_join},
7699 {"keys", 1, 1, f_keys},
7700 {"last_buffer_nr", 0, 0, f_last_buffer_nr},/* obsolete */
7701 {"len", 1, 1, f_len},
7702 {"libcall", 3, 3, f_libcall},
7703 {"libcallnr", 3, 3, f_libcallnr},
7704 {"line", 1, 1, f_line},
7705 {"line2byte", 1, 1, f_line2byte},
7706 {"lispindent", 1, 1, f_lispindent},
7707 {"localtime", 0, 0, f_localtime},
7708 #ifdef FEAT_FLOAT
7709 {"log", 1, 1, f_log}, /* WJMc */
7710 {"log10", 1, 1, f_log10},
7711 #endif
7712 {"map", 2, 2, f_map},
7713 {"maparg", 1, 3, f_maparg},
7714 {"mapcheck", 1, 3, f_mapcheck},
7715 {"match", 2, 4, f_match},
7716 {"matchadd", 2, 4, f_matchadd},
7717 {"matcharg", 1, 1, f_matcharg},
7718 {"matchdelete", 1, 1, f_matchdelete},
7719 {"matchend", 2, 4, f_matchend},
7720 {"matchlist", 2, 4, f_matchlist},
7721 {"matchstr", 2, 4, f_matchstr},
7722 {"max", 1, 1, f_max},
7723 {"min", 1, 1, f_min},
7724 #ifdef vim_mkdir
7725 {"mkdir", 1, 3, f_mkdir},
7726 #endif
7727 {"mode", 0, 1, f_mode},
7728 #ifdef FEAT_MZSCHEME
7729 {"mzeval", 1, 1, f_mzeval},
7730 #endif
7731 {"nextnonblank", 1, 1, f_nextnonblank},
7732 {"nr2char", 1, 1, f_nr2char},
7733 {"pathshorten", 1, 1, f_pathshorten},
7734 #ifdef FEAT_FLOAT
7735 {"pow", 2, 2, f_pow},
7736 #endif
7737 {"prevnonblank", 1, 1, f_prevnonblank},
7738 {"printf", 2, 19, f_printf},
7739 {"pumvisible", 0, 0, f_pumvisible},
7740 {"range", 1, 3, f_range},
7741 {"readfile", 1, 3, f_readfile},
7742 {"reltime", 0, 2, f_reltime},
7743 {"reltimestr", 1, 1, f_reltimestr},
7744 {"remote_expr", 2, 3, f_remote_expr},
7745 {"remote_foreground", 1, 1, f_remote_foreground},
7746 {"remote_peek", 1, 2, f_remote_peek},
7747 {"remote_read", 1, 1, f_remote_read},
7748 {"remote_send", 2, 3, f_remote_send},
7749 {"remove", 2, 3, f_remove},
7750 {"rename", 2, 2, f_rename},
7751 {"repeat", 2, 2, f_repeat},
7752 {"resolve", 1, 1, f_resolve},
7753 {"reverse", 1, 1, f_reverse},
7754 #ifdef FEAT_FLOAT
7755 {"round", 1, 1, f_round},
7756 #endif
7757 {"search", 1, 4, f_search},
7758 {"searchdecl", 1, 3, f_searchdecl},
7759 {"searchpair", 3, 7, f_searchpair},
7760 {"searchpairpos", 3, 7, f_searchpairpos},
7761 {"searchpos", 1, 4, f_searchpos},
7762 {"server2client", 2, 2, f_server2client},
7763 {"serverlist", 0, 0, f_serverlist},
7764 {"setbufvar", 3, 3, f_setbufvar},
7765 {"setcmdpos", 1, 1, f_setcmdpos},
7766 {"setline", 2, 2, f_setline},
7767 {"setloclist", 2, 3, f_setloclist},
7768 {"setmatches", 1, 1, f_setmatches},
7769 {"setpos", 2, 2, f_setpos},
7770 {"setqflist", 1, 2, f_setqflist},
7771 {"setreg", 2, 3, f_setreg},
7772 {"settabwinvar", 4, 4, f_settabwinvar},
7773 {"setwinvar", 3, 3, f_setwinvar},
7774 {"shellescape", 1, 2, f_shellescape},
7775 {"simplify", 1, 1, f_simplify},
7776 #ifdef FEAT_FLOAT
7777 {"sin", 1, 1, f_sin},
7778 {"sinh", 1, 1, f_sinh}, /* WJMc */
7779 #endif
7780 {"sort", 1, 2, f_sort},
7781 {"soundfold", 1, 1, f_soundfold},
7782 {"spellbadword", 0, 1, f_spellbadword},
7783 {"spellsuggest", 1, 3, f_spellsuggest},
7784 {"split", 1, 3, f_split},
7785 #ifdef FEAT_FLOAT
7786 {"sqrt", 1, 1, f_sqrt},
7787 {"str2float", 1, 1, f_str2float},
7788 #endif
7789 {"str2nr", 1, 2, f_str2nr},
7790 #ifdef HAVE_STRFTIME
7791 {"strftime", 1, 2, f_strftime},
7792 #endif
7793 {"stridx", 2, 3, f_stridx},
7794 {"string", 1, 1, f_string},
7795 {"strlen", 1, 1, f_strlen},
7796 {"strpart", 2, 3, f_strpart},
7797 {"strridx", 2, 3, f_strridx},
7798 {"strtrans", 1, 1, f_strtrans},
7799 {"submatch", 1, 1, f_submatch},
7800 {"substitute", 4, 4, f_substitute},
7801 {"synID", 3, 3, f_synID},
7802 {"synIDattr", 2, 3, f_synIDattr},
7803 {"synIDtrans", 1, 1, f_synIDtrans},
7804 {"synstack", 2, 2, f_synstack},
7805 {"system", 1, 2, f_system},
7806 {"tabpagebuflist", 0, 1, f_tabpagebuflist},
7807 {"tabpagenr", 0, 1, f_tabpagenr},
7808 {"tabpagewinnr", 1, 2, f_tabpagewinnr},
7809 {"tagfiles", 0, 0, f_tagfiles},
7810 {"taglist", 1, 1, f_taglist},
7811 {"tan", 1, 1, f_tan}, /* WJMc */
7812 {"tanh", 1, 1, f_tanh}, /* WJMc */
7813 {"tempname", 0, 0, f_tempname},
7814 {"test", 1, 1, f_test},
7815 {"tolower", 1, 1, f_tolower},
7816 {"toupper", 1, 1, f_toupper},
7817 {"tr", 3, 3, f_tr},
7818 #ifdef FEAT_FLOAT
7819 {"trunc", 1, 1, f_trunc},
7820 #endif
7821 {"type", 1, 1, f_type},
7822 {"values", 1, 1, f_values},
7823 {"virtcol", 1, 1, f_virtcol},
7824 {"visualmode", 0, 1, f_visualmode},
7825 {"winbufnr", 1, 1, f_winbufnr},
7826 {"wincol", 0, 0, f_wincol},
7827 {"winheight", 1, 1, f_winheight},
7828 {"winline", 0, 0, f_winline},
7829 {"winnr", 0, 1, f_winnr},
7830 {"winrestcmd", 0, 0, f_winrestcmd},
7831 {"winrestview", 1, 1, f_winrestview},
7832 {"winsaveview", 0, 0, f_winsaveview},
7833 {"winwidth", 1, 1, f_winwidth},
7834 {"writefile", 2, 3, f_writefile},
7837 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
7840 * Function given to ExpandGeneric() to obtain the list of internal
7841 * or user defined function names.
7843 char_u *
7844 get_function_name(xp, idx)
7845 expand_T *xp;
7846 int idx;
7848 static int intidx = -1;
7849 char_u *name;
7851 if (idx == 0)
7852 intidx = -1;
7853 if (intidx < 0)
7855 name = get_user_func_name(xp, idx);
7856 if (name != NULL)
7857 return name;
7859 if (++intidx < (int)(sizeof(functions) / sizeof(struct fst)))
7861 STRCPY(IObuff, functions[intidx].f_name);
7862 STRCAT(IObuff, "(");
7863 if (functions[intidx].f_max_argc == 0)
7864 STRCAT(IObuff, ")");
7865 return IObuff;
7868 return NULL;
7872 * Function given to ExpandGeneric() to obtain the list of internal or
7873 * user defined variable or function names.
7875 char_u *
7876 get_expr_name(xp, idx)
7877 expand_T *xp;
7878 int idx;
7880 static int intidx = -1;
7881 char_u *name;
7883 if (idx == 0)
7884 intidx = -1;
7885 if (intidx < 0)
7887 name = get_function_name(xp, idx);
7888 if (name != NULL)
7889 return name;
7891 return get_user_var_name(xp, ++intidx);
7894 #endif /* FEAT_CMDL_COMPL */
7897 * Find internal function in table above.
7898 * Return index, or -1 if not found
7900 static int
7901 find_internal_func(name)
7902 char_u *name; /* name of the function */
7904 int first = 0;
7905 int last = (int)(sizeof(functions) / sizeof(struct fst)) - 1;
7906 int cmp;
7907 int x;
7910 * Find the function name in the table. Binary search.
7912 while (first <= last)
7914 x = first + ((unsigned)(last - first) >> 1);
7915 cmp = STRCMP(name, functions[x].f_name);
7916 if (cmp < 0)
7917 last = x - 1;
7918 else if (cmp > 0)
7919 first = x + 1;
7920 else
7921 return x;
7923 return -1;
7927 * Check if "name" is a variable of type VAR_FUNC. If so, return the function
7928 * name it contains, otherwise return "name".
7930 static char_u *
7931 deref_func_name(name, lenp)
7932 char_u *name;
7933 int *lenp;
7935 dictitem_T *v;
7936 int cc;
7938 cc = name[*lenp];
7939 name[*lenp] = NUL;
7940 v = find_var(name, NULL);
7941 name[*lenp] = cc;
7942 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
7944 if (v->di_tv.vval.v_string == NULL)
7946 *lenp = 0;
7947 return (char_u *)""; /* just in case */
7949 *lenp = (int)STRLEN(v->di_tv.vval.v_string);
7950 return v->di_tv.vval.v_string;
7953 return name;
7957 * Allocate a variable for the result of a function.
7958 * Return OK or FAIL.
7960 static int
7961 get_func_tv(name, len, rettv, arg, firstline, lastline, doesrange,
7962 evaluate, selfdict)
7963 char_u *name; /* name of the function */
7964 int len; /* length of "name" */
7965 typval_T *rettv;
7966 char_u **arg; /* argument, pointing to the '(' */
7967 linenr_T firstline; /* first line of range */
7968 linenr_T lastline; /* last line of range */
7969 int *doesrange; /* return: function handled range */
7970 int evaluate;
7971 dict_T *selfdict; /* Dictionary for "self" */
7973 char_u *argp;
7974 int ret = OK;
7975 typval_T argvars[MAX_FUNC_ARGS + 1]; /* vars for arguments */
7976 int argcount = 0; /* number of arguments found */
7979 * Get the arguments.
7981 argp = *arg;
7982 while (argcount < MAX_FUNC_ARGS)
7984 argp = skipwhite(argp + 1); /* skip the '(' or ',' */
7985 if (*argp == ')' || *argp == ',' || *argp == NUL)
7986 break;
7987 if (eval1(&argp, &argvars[argcount], evaluate) == FAIL)
7989 ret = FAIL;
7990 break;
7992 ++argcount;
7993 if (*argp != ',')
7994 break;
7996 if (*argp == ')')
7997 ++argp;
7998 else
7999 ret = FAIL;
8001 if (ret == OK)
8002 ret = call_func(name, len, rettv, argcount, argvars,
8003 firstline, lastline, doesrange, evaluate, selfdict);
8004 else if (!aborting())
8006 if (argcount == MAX_FUNC_ARGS)
8007 emsg_funcname(N_("E740: Too many arguments for function %s"), name);
8008 else
8009 emsg_funcname(N_("E116: Invalid arguments for function %s"), name);
8012 while (--argcount >= 0)
8013 clear_tv(&argvars[argcount]);
8015 *arg = skipwhite(argp);
8016 return ret;
8021 * Call a function with its resolved parameters
8022 * Return OK when the function can't be called, FAIL otherwise.
8023 * Also returns OK when an error was encountered while executing the function.
8025 static int
8026 call_func(func_name, len, rettv, argcount, argvars, firstline, lastline,
8027 doesrange, evaluate, selfdict)
8028 char_u *func_name; /* name of the function */
8029 int len; /* length of "name" */
8030 typval_T *rettv; /* return value goes here */
8031 int argcount; /* number of "argvars" */
8032 typval_T *argvars; /* vars for arguments, must have "argcount"
8033 PLUS ONE elements! */
8034 linenr_T firstline; /* first line of range */
8035 linenr_T lastline; /* last line of range */
8036 int *doesrange; /* return: function handled range */
8037 int evaluate;
8038 dict_T *selfdict; /* Dictionary for "self" */
8040 int ret = FAIL;
8041 #define ERROR_UNKNOWN 0
8042 #define ERROR_TOOMANY 1
8043 #define ERROR_TOOFEW 2
8044 #define ERROR_SCRIPT 3
8045 #define ERROR_DICT 4
8046 #define ERROR_NONE 5
8047 #define ERROR_OTHER 6
8048 int error = ERROR_NONE;
8049 int i;
8050 int llen;
8051 ufunc_T *fp;
8052 #define FLEN_FIXED 40
8053 char_u fname_buf[FLEN_FIXED + 1];
8054 char_u *fname;
8055 char_u *name;
8057 /* Make a copy of the name, if it comes from a funcref variable it could
8058 * be changed or deleted in the called function. */
8059 name = vim_strnsave(func_name, len);
8060 if (name == NULL)
8061 return ret;
8064 * In a script change <SID>name() and s:name() to K_SNR 123_name().
8065 * Change <SNR>123_name() to K_SNR 123_name().
8066 * Use fname_buf[] when it fits, otherwise allocate memory (slow).
8068 llen = eval_fname_script(name);
8069 if (llen > 0)
8071 fname_buf[0] = K_SPECIAL;
8072 fname_buf[1] = KS_EXTRA;
8073 fname_buf[2] = (int)KE_SNR;
8074 i = 3;
8075 if (eval_fname_sid(name)) /* "<SID>" or "s:" */
8077 if (current_SID <= 0)
8078 error = ERROR_SCRIPT;
8079 else
8081 sprintf((char *)fname_buf + 3, "%ld_", (long)current_SID);
8082 i = (int)STRLEN(fname_buf);
8085 if (i + STRLEN(name + llen) < FLEN_FIXED)
8087 STRCPY(fname_buf + i, name + llen);
8088 fname = fname_buf;
8090 else
8092 fname = alloc((unsigned)(i + STRLEN(name + llen) + 1));
8093 if (fname == NULL)
8094 error = ERROR_OTHER;
8095 else
8097 mch_memmove(fname, fname_buf, (size_t)i);
8098 STRCPY(fname + i, name + llen);
8102 else
8103 fname = name;
8105 *doesrange = FALSE;
8108 /* execute the function if no errors detected and executing */
8109 if (evaluate && error == ERROR_NONE)
8111 rettv->v_type = VAR_NUMBER; /* default rettv is number zero */
8112 rettv->vval.v_number = 0;
8113 error = ERROR_UNKNOWN;
8115 if (!builtin_function(fname))
8118 * User defined function.
8120 fp = find_func(fname);
8122 #ifdef FEAT_AUTOCMD
8123 /* Trigger FuncUndefined event, may load the function. */
8124 if (fp == NULL
8125 && apply_autocmds(EVENT_FUNCUNDEFINED,
8126 fname, fname, TRUE, NULL)
8127 && !aborting())
8129 /* executed an autocommand, search for the function again */
8130 fp = find_func(fname);
8132 #endif
8133 /* Try loading a package. */
8134 if (fp == NULL && script_autoload(fname, TRUE) && !aborting())
8136 /* loaded a package, search for the function again */
8137 fp = find_func(fname);
8140 if (fp != NULL)
8142 if (fp->uf_flags & FC_RANGE)
8143 *doesrange = TRUE;
8144 if (argcount < fp->uf_args.ga_len)
8145 error = ERROR_TOOFEW;
8146 else if (!fp->uf_varargs && argcount > fp->uf_args.ga_len)
8147 error = ERROR_TOOMANY;
8148 else if ((fp->uf_flags & FC_DICT) && selfdict == NULL)
8149 error = ERROR_DICT;
8150 else
8153 * Call the user function.
8154 * Save and restore search patterns, script variables and
8155 * redo buffer.
8157 save_search_patterns();
8158 saveRedobuff();
8159 ++fp->uf_calls;
8160 call_user_func(fp, argcount, argvars, rettv,
8161 firstline, lastline,
8162 (fp->uf_flags & FC_DICT) ? selfdict : NULL);
8163 if (--fp->uf_calls <= 0 && isdigit(*fp->uf_name)
8164 && fp->uf_refcount <= 0)
8165 /* Function was unreferenced while being used, free it
8166 * now. */
8167 func_free(fp);
8168 restoreRedobuff();
8169 restore_search_patterns();
8170 error = ERROR_NONE;
8174 else
8177 * Find the function name in the table, call its implementation.
8179 i = find_internal_func(fname);
8180 if (i >= 0)
8182 if (argcount < functions[i].f_min_argc)
8183 error = ERROR_TOOFEW;
8184 else if (argcount > functions[i].f_max_argc)
8185 error = ERROR_TOOMANY;
8186 else
8188 argvars[argcount].v_type = VAR_UNKNOWN;
8189 functions[i].f_func(argvars, rettv);
8190 error = ERROR_NONE;
8195 * The function call (or "FuncUndefined" autocommand sequence) might
8196 * have been aborted by an error, an interrupt, or an explicitly thrown
8197 * exception that has not been caught so far. This situation can be
8198 * tested for by calling aborting(). For an error in an internal
8199 * function or for the "E132" error in call_user_func(), however, the
8200 * throw point at which the "force_abort" flag (temporarily reset by
8201 * emsg()) is normally updated has not been reached yet. We need to
8202 * update that flag first to make aborting() reliable.
8204 update_force_abort();
8206 if (error == ERROR_NONE)
8207 ret = OK;
8210 * Report an error unless the argument evaluation or function call has been
8211 * cancelled due to an aborting error, an interrupt, or an exception.
8213 if (!aborting())
8215 switch (error)
8217 case ERROR_UNKNOWN:
8218 emsg_funcname(N_("E117: Unknown function: %s"), name);
8219 break;
8220 case ERROR_TOOMANY:
8221 emsg_funcname(e_toomanyarg, name);
8222 break;
8223 case ERROR_TOOFEW:
8224 emsg_funcname(N_("E119: Not enough arguments for function: %s"),
8225 name);
8226 break;
8227 case ERROR_SCRIPT:
8228 emsg_funcname(N_("E120: Using <SID> not in a script context: %s"),
8229 name);
8230 break;
8231 case ERROR_DICT:
8232 emsg_funcname(N_("E725: Calling dict function without Dictionary: %s"),
8233 name);
8234 break;
8238 if (fname != name && fname != fname_buf)
8239 vim_free(fname);
8240 vim_free(name);
8242 return ret;
8246 * Give an error message with a function name. Handle <SNR> things.
8247 * "ermsg" is to be passed without translation, use N_() instead of _().
8249 static void
8250 emsg_funcname(ermsg, name)
8251 char *ermsg;
8252 char_u *name;
8254 char_u *p;
8256 if (*name == K_SPECIAL)
8257 p = concat_str((char_u *)"<SNR>", name + 3);
8258 else
8259 p = name;
8260 EMSG2(_(ermsg), p);
8261 if (p != name)
8262 vim_free(p);
8266 * Return TRUE for a non-zero Number and a non-empty String.
8268 static int
8269 non_zero_arg(argvars)
8270 typval_T *argvars;
8272 return ((argvars[0].v_type == VAR_NUMBER
8273 && argvars[0].vval.v_number != 0)
8274 || (argvars[0].v_type == VAR_STRING
8275 && argvars[0].vval.v_string != NULL
8276 && *argvars[0].vval.v_string != NUL));
8279 /*********************************************
8280 * Implementation of the built-in functions
8283 #ifdef FEAT_FLOAT
8285 * "abs(expr)" function
8287 static void
8288 f_abs(argvars, rettv)
8289 typval_T *argvars;
8290 typval_T *rettv;
8292 if (argvars[0].v_type == VAR_FLOAT)
8294 rettv->v_type = VAR_FLOAT;
8295 rettv->vval.v_float = fabs(argvars[0].vval.v_float);
8297 else
8299 varnumber_T n;
8300 int error = FALSE;
8302 n = get_tv_number_chk(&argvars[0], &error);
8303 if (error)
8304 rettv->vval.v_number = -1;
8305 else if (n > 0)
8306 rettv->vval.v_number = n;
8307 else
8308 rettv->vval.v_number = -n;
8311 #endif
8314 * "add(list, item)" function
8316 static void
8317 f_add(argvars, rettv)
8318 typval_T *argvars;
8319 typval_T *rettv;
8321 list_T *l;
8323 rettv->vval.v_number = 1; /* Default: Failed */
8324 if (argvars[0].v_type == VAR_LIST)
8326 if ((l = argvars[0].vval.v_list) != NULL
8327 && !tv_check_lock(l->lv_lock, (char_u *)"add()")
8328 && list_append_tv(l, &argvars[1]) == OK)
8329 copy_tv(&argvars[0], rettv);
8331 else
8332 EMSG(_(e_listreq));
8336 * "append(lnum, string/list)" function
8338 static void
8339 f_append(argvars, rettv)
8340 typval_T *argvars;
8341 typval_T *rettv;
8343 long lnum;
8344 char_u *line;
8345 list_T *l = NULL;
8346 listitem_T *li = NULL;
8347 typval_T *tv;
8348 long added = 0;
8350 lnum = get_tv_lnum(argvars);
8351 if (lnum >= 0
8352 && lnum <= curbuf->b_ml.ml_line_count
8353 && u_save(lnum, lnum + 1) == OK)
8355 if (argvars[1].v_type == VAR_LIST)
8357 l = argvars[1].vval.v_list;
8358 if (l == NULL)
8359 return;
8360 li = l->lv_first;
8362 for (;;)
8364 if (l == NULL)
8365 tv = &argvars[1]; /* append a string */
8366 else if (li == NULL)
8367 break; /* end of list */
8368 else
8369 tv = &li->li_tv; /* append item from list */
8370 line = get_tv_string_chk(tv);
8371 if (line == NULL) /* type error */
8373 rettv->vval.v_number = 1; /* Failed */
8374 break;
8376 ml_append(lnum + added, line, (colnr_T)0, FALSE);
8377 ++added;
8378 if (l == NULL)
8379 break;
8380 li = li->li_next;
8383 appended_lines_mark(lnum, added);
8384 if (curwin->w_cursor.lnum > lnum)
8385 curwin->w_cursor.lnum += added;
8387 else
8388 rettv->vval.v_number = 1; /* Failed */
8392 * "argc()" function
8394 static void
8395 f_argc(argvars, rettv)
8396 typval_T *argvars UNUSED;
8397 typval_T *rettv;
8399 rettv->vval.v_number = ARGCOUNT;
8403 * "argidx()" function
8405 static void
8406 f_argidx(argvars, rettv)
8407 typval_T *argvars UNUSED;
8408 typval_T *rettv;
8410 rettv->vval.v_number = curwin->w_arg_idx;
8414 * "argv(nr)" function
8416 static void
8417 f_argv(argvars, rettv)
8418 typval_T *argvars;
8419 typval_T *rettv;
8421 int idx;
8423 if (argvars[0].v_type != VAR_UNKNOWN)
8425 idx = get_tv_number_chk(&argvars[0], NULL);
8426 if (idx >= 0 && idx < ARGCOUNT)
8427 rettv->vval.v_string = vim_strsave(alist_name(&ARGLIST[idx]));
8428 else
8429 rettv->vval.v_string = NULL;
8430 rettv->v_type = VAR_STRING;
8432 else if (rettv_list_alloc(rettv) == OK)
8433 for (idx = 0; idx < ARGCOUNT; ++idx)
8434 list_append_string(rettv->vval.v_list,
8435 alist_name(&ARGLIST[idx]), -1);
8438 #ifdef FEAT_FLOAT
8439 static int get_float_arg __ARGS((typval_T *argvars, float_T *f));
8442 * Get the float value of "argvars[0]" into "f".
8443 * Returns FAIL when the argument is not a Number or Float.
8445 static int
8446 get_float_arg(argvars, f)
8447 typval_T *argvars;
8448 float_T *f;
8450 if (argvars[0].v_type == VAR_FLOAT)
8452 *f = argvars[0].vval.v_float;
8453 return OK;
8455 if (argvars[0].v_type == VAR_NUMBER)
8457 *f = (float_T)argvars[0].vval.v_number;
8458 return OK;
8460 EMSG(_("E808: Number or Float required"));
8461 return FAIL;
8464 /* The 10 added FP functions are defined immediately before atan() - WJMc */
8467 * "acos()" function
8469 static void
8470 f_acos(argvars, rettv)
8471 typval_T *argvars;
8472 typval_T *rettv;
8474 float_T f;
8476 rettv->v_type = VAR_FLOAT;
8477 if (get_float_arg(argvars, &f) == OK)
8478 rettv->vval.v_float = acos(f);
8479 else
8480 rettv->vval.v_float = 0.0;
8484 * "asin()" function
8486 static void
8487 f_asin(argvars, rettv)
8488 typval_T *argvars;
8489 typval_T *rettv;
8491 float_T f;
8493 rettv->v_type = VAR_FLOAT;
8494 if (get_float_arg(argvars, &f) == OK)
8495 rettv->vval.v_float = asin(f);
8496 else
8497 rettv->vval.v_float = 0.0;
8501 * "atan2()" function
8503 static void
8504 f_atan2(argvars, rettv)
8505 typval_T *argvars;
8506 typval_T *rettv;
8508 float_T fx, fy;
8510 rettv->v_type = VAR_FLOAT;
8511 if (get_float_arg(argvars, &fx) == OK
8512 && get_float_arg(&argvars[1], &fy) == OK)
8513 rettv->vval.v_float = atan2(fx, fy);
8514 else
8515 rettv->vval.v_float = 0.0;
8519 * "cosh()" function
8521 static void
8522 f_cosh(argvars, rettv)
8523 typval_T *argvars;
8524 typval_T *rettv;
8526 float_T f;
8528 rettv->v_type = VAR_FLOAT;
8529 if (get_float_arg(argvars, &f) == OK)
8530 rettv->vval.v_float = cosh(f);
8531 else
8532 rettv->vval.v_float = 0.0;
8536 * "exp()" function
8538 static void
8539 f_exp(argvars, rettv)
8540 typval_T *argvars;
8541 typval_T *rettv;
8543 float_T f;
8545 rettv->v_type = VAR_FLOAT;
8546 if (get_float_arg(argvars, &f) == OK)
8547 rettv->vval.v_float = exp(f);
8548 else
8549 rettv->vval.v_float = 0.0;
8553 * "fmod()" function
8555 static void
8556 f_fmod(argvars, rettv)
8557 typval_T *argvars;
8558 typval_T *rettv;
8560 float_T fx, fy;
8562 rettv->v_type = VAR_FLOAT;
8563 if (get_float_arg(argvars, &fx) == OK
8564 && get_float_arg(&argvars[1], &fy) == OK)
8565 rettv->vval.v_float = fmod(fx, fy);
8566 else
8567 rettv->vval.v_float = 0.0;
8571 * "log()" function
8573 static void
8574 f_log(argvars, rettv)
8575 typval_T *argvars;
8576 typval_T *rettv;
8578 float_T f;
8580 rettv->v_type = VAR_FLOAT;
8581 if (get_float_arg(argvars, &f) == OK)
8582 rettv->vval.v_float = log(f);
8583 else
8584 rettv->vval.v_float = 0.0;
8588 * "sinh()" function
8590 static void
8591 f_sinh(argvars, rettv)
8592 typval_T *argvars;
8593 typval_T *rettv;
8595 float_T f;
8597 rettv->v_type = VAR_FLOAT;
8598 if (get_float_arg(argvars, &f) == OK)
8599 rettv->vval.v_float = sinh(f);
8600 else
8601 rettv->vval.v_float = 0.0;
8605 * "tan()" function
8607 static void
8608 f_tan(argvars, rettv)
8609 typval_T *argvars;
8610 typval_T *rettv;
8612 float_T f;
8614 rettv->v_type = VAR_FLOAT;
8615 if (get_float_arg(argvars, &f) == OK)
8616 rettv->vval.v_float = tan(f);
8617 else
8618 rettv->vval.v_float = 0.0;
8622 * "tanh()" function
8624 static void
8625 f_tanh(argvars, rettv)
8626 typval_T *argvars;
8627 typval_T *rettv;
8629 float_T f;
8631 rettv->v_type = VAR_FLOAT;
8632 if (get_float_arg(argvars, &f) == OK)
8633 rettv->vval.v_float = tanh(f);
8634 else
8635 rettv->vval.v_float = 0.0;
8638 /* End of the 10 added FP functions - WJMc */
8641 * "atan()" function
8643 static void
8644 f_atan(argvars, rettv)
8645 typval_T *argvars;
8646 typval_T *rettv;
8648 float_T f;
8650 rettv->v_type = VAR_FLOAT;
8651 if (get_float_arg(argvars, &f) == OK)
8652 rettv->vval.v_float = atan(f);
8653 else
8654 rettv->vval.v_float = 0.0;
8656 #endif
8659 * "browse(save, title, initdir, default)" function
8661 static void
8662 f_browse(argvars, rettv)
8663 typval_T *argvars UNUSED;
8664 typval_T *rettv;
8666 #ifdef FEAT_BROWSE
8667 int save;
8668 char_u *title;
8669 char_u *initdir;
8670 char_u *defname;
8671 char_u buf[NUMBUFLEN];
8672 char_u buf2[NUMBUFLEN];
8673 int error = FALSE;
8675 save = get_tv_number_chk(&argvars[0], &error);
8676 title = get_tv_string_chk(&argvars[1]);
8677 initdir = get_tv_string_buf_chk(&argvars[2], buf);
8678 defname = get_tv_string_buf_chk(&argvars[3], buf2);
8680 if (error || title == NULL || initdir == NULL || defname == NULL)
8681 rettv->vval.v_string = NULL;
8682 else
8683 rettv->vval.v_string =
8684 do_browse(save ? BROWSE_SAVE : 0,
8685 title, defname, NULL, initdir, NULL, curbuf);
8686 #else
8687 rettv->vval.v_string = NULL;
8688 #endif
8689 rettv->v_type = VAR_STRING;
8693 * "browsedir(title, initdir)" function
8695 static void
8696 f_browsedir(argvars, rettv)
8697 typval_T *argvars UNUSED;
8698 typval_T *rettv;
8700 #ifdef FEAT_BROWSE
8701 char_u *title;
8702 char_u *initdir;
8703 char_u buf[NUMBUFLEN];
8705 title = get_tv_string_chk(&argvars[0]);
8706 initdir = get_tv_string_buf_chk(&argvars[1], buf);
8708 if (title == NULL || initdir == NULL)
8709 rettv->vval.v_string = NULL;
8710 else
8711 rettv->vval.v_string = do_browse(BROWSE_DIR,
8712 title, NULL, NULL, initdir, NULL, curbuf);
8713 #else
8714 rettv->vval.v_string = NULL;
8715 #endif
8716 rettv->v_type = VAR_STRING;
8719 static buf_T *find_buffer __ARGS((typval_T *avar));
8722 * Find a buffer by number or exact name.
8724 static buf_T *
8725 find_buffer(avar)
8726 typval_T *avar;
8728 buf_T *buf = NULL;
8730 if (avar->v_type == VAR_NUMBER)
8731 buf = buflist_findnr((int)avar->vval.v_number);
8732 else if (avar->v_type == VAR_STRING && avar->vval.v_string != NULL)
8734 buf = buflist_findname_exp(avar->vval.v_string);
8735 if (buf == NULL)
8737 /* No full path name match, try a match with a URL or a "nofile"
8738 * buffer, these don't use the full path. */
8739 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8740 if (buf->b_fname != NULL
8741 && (path_with_url(buf->b_fname)
8742 #ifdef FEAT_QUICKFIX
8743 || bt_nofile(buf)
8744 #endif
8746 && STRCMP(buf->b_fname, avar->vval.v_string) == 0)
8747 break;
8750 return buf;
8754 * "bufexists(expr)" function
8756 static void
8757 f_bufexists(argvars, rettv)
8758 typval_T *argvars;
8759 typval_T *rettv;
8761 rettv->vval.v_number = (find_buffer(&argvars[0]) != NULL);
8765 * "buflisted(expr)" function
8767 static void
8768 f_buflisted(argvars, rettv)
8769 typval_T *argvars;
8770 typval_T *rettv;
8772 buf_T *buf;
8774 buf = find_buffer(&argvars[0]);
8775 rettv->vval.v_number = (buf != NULL && buf->b_p_bl);
8779 * "bufloaded(expr)" function
8781 static void
8782 f_bufloaded(argvars, rettv)
8783 typval_T *argvars;
8784 typval_T *rettv;
8786 buf_T *buf;
8788 buf = find_buffer(&argvars[0]);
8789 rettv->vval.v_number = (buf != NULL && buf->b_ml.ml_mfp != NULL);
8792 static buf_T *get_buf_tv __ARGS((typval_T *tv));
8795 * Get buffer by number or pattern.
8797 static buf_T *
8798 get_buf_tv(tv)
8799 typval_T *tv;
8801 char_u *name = tv->vval.v_string;
8802 int save_magic;
8803 char_u *save_cpo;
8804 buf_T *buf;
8806 if (tv->v_type == VAR_NUMBER)
8807 return buflist_findnr((int)tv->vval.v_number);
8808 if (tv->v_type != VAR_STRING)
8809 return NULL;
8810 if (name == NULL || *name == NUL)
8811 return curbuf;
8812 if (name[0] == '$' && name[1] == NUL)
8813 return lastbuf;
8815 /* Ignore 'magic' and 'cpoptions' here to make scripts portable */
8816 save_magic = p_magic;
8817 p_magic = TRUE;
8818 save_cpo = p_cpo;
8819 p_cpo = (char_u *)"";
8821 buf = buflist_findnr(buflist_findpat(name, name + STRLEN(name),
8822 TRUE, FALSE));
8824 p_magic = save_magic;
8825 p_cpo = save_cpo;
8827 /* If not found, try expanding the name, like done for bufexists(). */
8828 if (buf == NULL)
8829 buf = find_buffer(tv);
8831 return buf;
8835 * "bufname(expr)" function
8837 static void
8838 f_bufname(argvars, rettv)
8839 typval_T *argvars;
8840 typval_T *rettv;
8842 buf_T *buf;
8844 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8845 ++emsg_off;
8846 buf = get_buf_tv(&argvars[0]);
8847 rettv->v_type = VAR_STRING;
8848 if (buf != NULL && buf->b_fname != NULL)
8849 rettv->vval.v_string = vim_strsave(buf->b_fname);
8850 else
8851 rettv->vval.v_string = NULL;
8852 --emsg_off;
8856 * "bufnr(expr)" function
8858 static void
8859 f_bufnr(argvars, rettv)
8860 typval_T *argvars;
8861 typval_T *rettv;
8863 buf_T *buf;
8864 int error = FALSE;
8865 char_u *name;
8867 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8868 ++emsg_off;
8869 buf = get_buf_tv(&argvars[0]);
8870 --emsg_off;
8872 /* If the buffer isn't found and the second argument is not zero create a
8873 * new buffer. */
8874 if (buf == NULL
8875 && argvars[1].v_type != VAR_UNKNOWN
8876 && get_tv_number_chk(&argvars[1], &error) != 0
8877 && !error
8878 && (name = get_tv_string_chk(&argvars[0])) != NULL
8879 && !error)
8880 buf = buflist_new(name, NULL, (linenr_T)1, 0);
8882 if (buf != NULL)
8883 rettv->vval.v_number = buf->b_fnum;
8884 else
8885 rettv->vval.v_number = -1;
8889 * "bufwinnr(nr)" function
8891 static void
8892 f_bufwinnr(argvars, rettv)
8893 typval_T *argvars;
8894 typval_T *rettv;
8896 #ifdef FEAT_WINDOWS
8897 win_T *wp;
8898 int winnr = 0;
8899 #endif
8900 buf_T *buf;
8902 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8903 ++emsg_off;
8904 buf = get_buf_tv(&argvars[0]);
8905 #ifdef FEAT_WINDOWS
8906 for (wp = firstwin; wp; wp = wp->w_next)
8908 ++winnr;
8909 if (wp->w_buffer == buf)
8910 break;
8912 rettv->vval.v_number = (wp != NULL ? winnr : -1);
8913 #else
8914 rettv->vval.v_number = (curwin->w_buffer == buf ? 1 : -1);
8915 #endif
8916 --emsg_off;
8920 * "byte2line(byte)" function
8922 static void
8923 f_byte2line(argvars, rettv)
8924 typval_T *argvars UNUSED;
8925 typval_T *rettv;
8927 #ifndef FEAT_BYTEOFF
8928 rettv->vval.v_number = -1;
8929 #else
8930 long boff = 0;
8932 boff = get_tv_number(&argvars[0]) - 1; /* boff gets -1 on type error */
8933 if (boff < 0)
8934 rettv->vval.v_number = -1;
8935 else
8936 rettv->vval.v_number = ml_find_line_or_offset(curbuf,
8937 (linenr_T)0, &boff);
8938 #endif
8942 * "byteidx()" function
8944 static void
8945 f_byteidx(argvars, rettv)
8946 typval_T *argvars;
8947 typval_T *rettv;
8949 #ifdef FEAT_MBYTE
8950 char_u *t;
8951 #endif
8952 char_u *str;
8953 long idx;
8955 str = get_tv_string_chk(&argvars[0]);
8956 idx = get_tv_number_chk(&argvars[1], NULL);
8957 rettv->vval.v_number = -1;
8958 if (str == NULL || idx < 0)
8959 return;
8961 #ifdef FEAT_MBYTE
8962 t = str;
8963 for ( ; idx > 0; idx--)
8965 if (*t == NUL) /* EOL reached */
8966 return;
8967 t += (*mb_ptr2len)(t);
8969 rettv->vval.v_number = (varnumber_T)(t - str);
8970 #else
8971 if ((size_t)idx <= STRLEN(str))
8972 rettv->vval.v_number = idx;
8973 #endif
8977 * "call(func, arglist)" function
8979 static void
8980 f_call(argvars, rettv)
8981 typval_T *argvars;
8982 typval_T *rettv;
8984 char_u *func;
8985 typval_T argv[MAX_FUNC_ARGS + 1];
8986 int argc = 0;
8987 listitem_T *item;
8988 int dummy;
8989 dict_T *selfdict = NULL;
8991 if (argvars[1].v_type != VAR_LIST)
8993 EMSG(_(e_listreq));
8994 return;
8996 if (argvars[1].vval.v_list == NULL)
8997 return;
8999 if (argvars[0].v_type == VAR_FUNC)
9000 func = argvars[0].vval.v_string;
9001 else
9002 func = get_tv_string(&argvars[0]);
9003 if (*func == NUL)
9004 return; /* type error or empty name */
9006 if (argvars[2].v_type != VAR_UNKNOWN)
9008 if (argvars[2].v_type != VAR_DICT)
9010 EMSG(_(e_dictreq));
9011 return;
9013 selfdict = argvars[2].vval.v_dict;
9016 for (item = argvars[1].vval.v_list->lv_first; item != NULL;
9017 item = item->li_next)
9019 if (argc == MAX_FUNC_ARGS)
9021 EMSG(_("E699: Too many arguments"));
9022 break;
9024 /* Make a copy of each argument. This is needed to be able to set
9025 * v_lock to VAR_FIXED in the copy without changing the original list.
9027 copy_tv(&item->li_tv, &argv[argc++]);
9030 if (item == NULL)
9031 (void)call_func(func, (int)STRLEN(func), rettv, argc, argv,
9032 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
9033 &dummy, TRUE, selfdict);
9035 /* Free the arguments. */
9036 while (argc > 0)
9037 clear_tv(&argv[--argc]);
9040 #ifdef FEAT_FLOAT
9042 * "ceil({float})" function
9044 static void
9045 f_ceil(argvars, rettv)
9046 typval_T *argvars;
9047 typval_T *rettv;
9049 float_T f;
9051 rettv->v_type = VAR_FLOAT;
9052 if (get_float_arg(argvars, &f) == OK)
9053 rettv->vval.v_float = ceil(f);
9054 else
9055 rettv->vval.v_float = 0.0;
9057 #endif
9060 * "changenr()" function
9062 static void
9063 f_changenr(argvars, rettv)
9064 typval_T *argvars UNUSED;
9065 typval_T *rettv;
9067 rettv->vval.v_number = curbuf->b_u_seq_cur;
9071 * "char2nr(string)" function
9073 static void
9074 f_char2nr(argvars, rettv)
9075 typval_T *argvars;
9076 typval_T *rettv;
9078 #ifdef FEAT_MBYTE
9079 if (has_mbyte)
9080 rettv->vval.v_number = (*mb_ptr2char)(get_tv_string(&argvars[0]));
9081 else
9082 #endif
9083 rettv->vval.v_number = get_tv_string(&argvars[0])[0];
9087 * "cindent(lnum)" function
9089 static void
9090 f_cindent(argvars, rettv)
9091 typval_T *argvars;
9092 typval_T *rettv;
9094 #ifdef FEAT_CINDENT
9095 pos_T pos;
9096 linenr_T lnum;
9098 pos = curwin->w_cursor;
9099 lnum = get_tv_lnum(argvars);
9100 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
9102 curwin->w_cursor.lnum = lnum;
9103 rettv->vval.v_number = get_c_indent();
9104 curwin->w_cursor = pos;
9106 else
9107 #endif
9108 rettv->vval.v_number = -1;
9112 * "clearmatches()" function
9114 static void
9115 f_clearmatches(argvars, rettv)
9116 typval_T *argvars UNUSED;
9117 typval_T *rettv UNUSED;
9119 #ifdef FEAT_SEARCH_EXTRA
9120 clear_matches(curwin);
9121 #endif
9125 * "col(string)" function
9127 static void
9128 f_col(argvars, rettv)
9129 typval_T *argvars;
9130 typval_T *rettv;
9132 colnr_T col = 0;
9133 pos_T *fp;
9134 int fnum = curbuf->b_fnum;
9136 fp = var2fpos(&argvars[0], FALSE, &fnum);
9137 if (fp != NULL && fnum == curbuf->b_fnum)
9139 if (fp->col == MAXCOL)
9141 /* '> can be MAXCOL, get the length of the line then */
9142 if (fp->lnum <= curbuf->b_ml.ml_line_count)
9143 col = (colnr_T)STRLEN(ml_get(fp->lnum)) + 1;
9144 else
9145 col = MAXCOL;
9147 else
9149 col = fp->col + 1;
9150 #ifdef FEAT_VIRTUALEDIT
9151 /* col(".") when the cursor is on the NUL at the end of the line
9152 * because of "coladd" can be seen as an extra column. */
9153 if (virtual_active() && fp == &curwin->w_cursor)
9155 char_u *p = ml_get_cursor();
9157 if (curwin->w_cursor.coladd >= (colnr_T)chartabsize(p,
9158 curwin->w_virtcol - curwin->w_cursor.coladd))
9160 # ifdef FEAT_MBYTE
9161 int l;
9163 if (*p != NUL && p[(l = (*mb_ptr2len)(p))] == NUL)
9164 col += l;
9165 # else
9166 if (*p != NUL && p[1] == NUL)
9167 ++col;
9168 # endif
9171 #endif
9174 rettv->vval.v_number = col;
9177 #if defined(FEAT_INS_EXPAND)
9179 * "complete()" function
9181 static void
9182 f_complete(argvars, rettv)
9183 typval_T *argvars;
9184 typval_T *rettv UNUSED;
9186 int startcol;
9188 if ((State & INSERT) == 0)
9190 EMSG(_("E785: complete() can only be used in Insert mode"));
9191 return;
9194 /* Check for undo allowed here, because if something was already inserted
9195 * the line was already saved for undo and this check isn't done. */
9196 if (!undo_allowed())
9197 return;
9199 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
9201 EMSG(_(e_invarg));
9202 return;
9205 startcol = get_tv_number_chk(&argvars[0], NULL);
9206 if (startcol <= 0)
9207 return;
9209 set_completion(startcol - 1, argvars[1].vval.v_list);
9213 * "complete_add()" function
9215 static void
9216 f_complete_add(argvars, rettv)
9217 typval_T *argvars;
9218 typval_T *rettv;
9220 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0);
9224 * "complete_check()" function
9226 static void
9227 f_complete_check(argvars, rettv)
9228 typval_T *argvars UNUSED;
9229 typval_T *rettv;
9231 int saved = RedrawingDisabled;
9233 RedrawingDisabled = 0;
9234 ins_compl_check_keys(0);
9235 rettv->vval.v_number = compl_interrupted;
9236 RedrawingDisabled = saved;
9238 #endif
9241 * "confirm(message, buttons[, default [, type]])" function
9243 static void
9244 f_confirm(argvars, rettv)
9245 typval_T *argvars UNUSED;
9246 typval_T *rettv UNUSED;
9248 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
9249 char_u *message;
9250 char_u *buttons = NULL;
9251 char_u buf[NUMBUFLEN];
9252 char_u buf2[NUMBUFLEN];
9253 int def = 1;
9254 int type = VIM_GENERIC;
9255 char_u *typestr;
9256 int error = FALSE;
9258 message = get_tv_string_chk(&argvars[0]);
9259 if (message == NULL)
9260 error = TRUE;
9261 if (argvars[1].v_type != VAR_UNKNOWN)
9263 buttons = get_tv_string_buf_chk(&argvars[1], buf);
9264 if (buttons == NULL)
9265 error = TRUE;
9266 if (argvars[2].v_type != VAR_UNKNOWN)
9268 def = get_tv_number_chk(&argvars[2], &error);
9269 if (argvars[3].v_type != VAR_UNKNOWN)
9271 typestr = get_tv_string_buf_chk(&argvars[3], buf2);
9272 if (typestr == NULL)
9273 error = TRUE;
9274 else
9276 switch (TOUPPER_ASC(*typestr))
9278 case 'E': type = VIM_ERROR; break;
9279 case 'Q': type = VIM_QUESTION; break;
9280 case 'I': type = VIM_INFO; break;
9281 case 'W': type = VIM_WARNING; break;
9282 case 'G': type = VIM_GENERIC; break;
9289 if (buttons == NULL || *buttons == NUL)
9290 buttons = (char_u *)_("&Ok");
9292 if (!error)
9293 rettv->vval.v_number = do_dialog(type, NULL, message, buttons,
9294 def, NULL);
9295 #endif
9299 * "copy()" function
9301 static void
9302 f_copy(argvars, rettv)
9303 typval_T *argvars;
9304 typval_T *rettv;
9306 item_copy(&argvars[0], rettv, FALSE, 0);
9309 #ifdef FEAT_FLOAT
9311 * "cos()" function
9313 static void
9314 f_cos(argvars, rettv)
9315 typval_T *argvars;
9316 typval_T *rettv;
9318 float_T f;
9320 rettv->v_type = VAR_FLOAT;
9321 if (get_float_arg(argvars, &f) == OK)
9322 rettv->vval.v_float = cos(f);
9323 else
9324 rettv->vval.v_float = 0.0;
9326 #endif
9329 * "count()" function
9331 static void
9332 f_count(argvars, rettv)
9333 typval_T *argvars;
9334 typval_T *rettv;
9336 long n = 0;
9337 int ic = FALSE;
9339 if (argvars[0].v_type == VAR_LIST)
9341 listitem_T *li;
9342 list_T *l;
9343 long idx;
9345 if ((l = argvars[0].vval.v_list) != NULL)
9347 li = l->lv_first;
9348 if (argvars[2].v_type != VAR_UNKNOWN)
9350 int error = FALSE;
9352 ic = get_tv_number_chk(&argvars[2], &error);
9353 if (argvars[3].v_type != VAR_UNKNOWN)
9355 idx = get_tv_number_chk(&argvars[3], &error);
9356 if (!error)
9358 li = list_find(l, idx);
9359 if (li == NULL)
9360 EMSGN(_(e_listidx), idx);
9363 if (error)
9364 li = NULL;
9367 for ( ; li != NULL; li = li->li_next)
9368 if (tv_equal(&li->li_tv, &argvars[1], ic))
9369 ++n;
9372 else if (argvars[0].v_type == VAR_DICT)
9374 int todo;
9375 dict_T *d;
9376 hashitem_T *hi;
9378 if ((d = argvars[0].vval.v_dict) != NULL)
9380 int error = FALSE;
9382 if (argvars[2].v_type != VAR_UNKNOWN)
9384 ic = get_tv_number_chk(&argvars[2], &error);
9385 if (argvars[3].v_type != VAR_UNKNOWN)
9386 EMSG(_(e_invarg));
9389 todo = error ? 0 : (int)d->dv_hashtab.ht_used;
9390 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
9392 if (!HASHITEM_EMPTY(hi))
9394 --todo;
9395 if (tv_equal(&HI2DI(hi)->di_tv, &argvars[1], ic))
9396 ++n;
9401 else
9402 EMSG2(_(e_listdictarg), "count()");
9403 rettv->vval.v_number = n;
9407 * "cscope_connection([{num} , {dbpath} [, {prepend}]])" function
9409 * Checks the existence of a cscope connection.
9411 static void
9412 f_cscope_connection(argvars, rettv)
9413 typval_T *argvars UNUSED;
9414 typval_T *rettv UNUSED;
9416 #ifdef FEAT_CSCOPE
9417 int num = 0;
9418 char_u *dbpath = NULL;
9419 char_u *prepend = NULL;
9420 char_u buf[NUMBUFLEN];
9422 if (argvars[0].v_type != VAR_UNKNOWN
9423 && argvars[1].v_type != VAR_UNKNOWN)
9425 num = (int)get_tv_number(&argvars[0]);
9426 dbpath = get_tv_string(&argvars[1]);
9427 if (argvars[2].v_type != VAR_UNKNOWN)
9428 prepend = get_tv_string_buf(&argvars[2], buf);
9431 rettv->vval.v_number = cs_connection(num, dbpath, prepend);
9432 #endif
9436 * "cursor(lnum, col)" function
9438 * Moves the cursor to the specified line and column.
9439 * Returns 0 when the position could be set, -1 otherwise.
9441 static void
9442 f_cursor(argvars, rettv)
9443 typval_T *argvars;
9444 typval_T *rettv;
9446 long line, col;
9447 #ifdef FEAT_VIRTUALEDIT
9448 long coladd = 0;
9449 #endif
9451 rettv->vval.v_number = -1;
9452 if (argvars[1].v_type == VAR_UNKNOWN)
9454 pos_T pos;
9456 if (list2fpos(argvars, &pos, NULL) == FAIL)
9457 return;
9458 line = pos.lnum;
9459 col = pos.col;
9460 #ifdef FEAT_VIRTUALEDIT
9461 coladd = pos.coladd;
9462 #endif
9464 else
9466 line = get_tv_lnum(argvars);
9467 col = get_tv_number_chk(&argvars[1], NULL);
9468 #ifdef FEAT_VIRTUALEDIT
9469 if (argvars[2].v_type != VAR_UNKNOWN)
9470 coladd = get_tv_number_chk(&argvars[2], NULL);
9471 #endif
9473 if (line < 0 || col < 0
9474 #ifdef FEAT_VIRTUALEDIT
9475 || coladd < 0
9476 #endif
9478 return; /* type error; errmsg already given */
9479 if (line > 0)
9480 curwin->w_cursor.lnum = line;
9481 if (col > 0)
9482 curwin->w_cursor.col = col - 1;
9483 #ifdef FEAT_VIRTUALEDIT
9484 curwin->w_cursor.coladd = coladd;
9485 #endif
9487 /* Make sure the cursor is in a valid position. */
9488 check_cursor();
9489 #ifdef FEAT_MBYTE
9490 /* Correct cursor for multi-byte character. */
9491 if (has_mbyte)
9492 mb_adjust_cursor();
9493 #endif
9495 curwin->w_set_curswant = TRUE;
9496 rettv->vval.v_number = 0;
9500 * "deepcopy()" function
9502 static void
9503 f_deepcopy(argvars, rettv)
9504 typval_T *argvars;
9505 typval_T *rettv;
9507 int noref = 0;
9509 if (argvars[1].v_type != VAR_UNKNOWN)
9510 noref = get_tv_number_chk(&argvars[1], NULL);
9511 if (noref < 0 || noref > 1)
9512 EMSG(_(e_invarg));
9513 else
9515 current_copyID += COPYID_INC;
9516 item_copy(&argvars[0], rettv, TRUE, noref == 0 ? current_copyID : 0);
9521 * "delete()" function
9523 static void
9524 f_delete(argvars, rettv)
9525 typval_T *argvars;
9526 typval_T *rettv;
9528 if (check_restricted() || check_secure())
9529 rettv->vval.v_number = -1;
9530 else
9531 rettv->vval.v_number = mch_remove(get_tv_string(&argvars[0]));
9535 * "did_filetype()" function
9537 static void
9538 f_did_filetype(argvars, rettv)
9539 typval_T *argvars UNUSED;
9540 typval_T *rettv UNUSED;
9542 #ifdef FEAT_AUTOCMD
9543 rettv->vval.v_number = did_filetype;
9544 #endif
9548 * "diff_filler()" function
9550 static void
9551 f_diff_filler(argvars, rettv)
9552 typval_T *argvars UNUSED;
9553 typval_T *rettv UNUSED;
9555 #ifdef FEAT_DIFF
9556 rettv->vval.v_number = diff_check_fill(curwin, get_tv_lnum(argvars));
9557 #endif
9561 * "diff_hlID()" function
9563 static void
9564 f_diff_hlID(argvars, rettv)
9565 typval_T *argvars UNUSED;
9566 typval_T *rettv UNUSED;
9568 #ifdef FEAT_DIFF
9569 linenr_T lnum = get_tv_lnum(argvars);
9570 static linenr_T prev_lnum = 0;
9571 static int changedtick = 0;
9572 static int fnum = 0;
9573 static int change_start = 0;
9574 static int change_end = 0;
9575 static hlf_T hlID = (hlf_T)0;
9576 int filler_lines;
9577 int col;
9579 if (lnum < 0) /* ignore type error in {lnum} arg */
9580 lnum = 0;
9581 if (lnum != prev_lnum
9582 || changedtick != curbuf->b_changedtick
9583 || fnum != curbuf->b_fnum)
9585 /* New line, buffer, change: need to get the values. */
9586 filler_lines = diff_check(curwin, lnum);
9587 if (filler_lines < 0)
9589 if (filler_lines == -1)
9591 change_start = MAXCOL;
9592 change_end = -1;
9593 if (diff_find_change(curwin, lnum, &change_start, &change_end))
9594 hlID = HLF_ADD; /* added line */
9595 else
9596 hlID = HLF_CHD; /* changed line */
9598 else
9599 hlID = HLF_ADD; /* added line */
9601 else
9602 hlID = (hlf_T)0;
9603 prev_lnum = lnum;
9604 changedtick = curbuf->b_changedtick;
9605 fnum = curbuf->b_fnum;
9608 if (hlID == HLF_CHD || hlID == HLF_TXD)
9610 col = get_tv_number(&argvars[1]) - 1; /* ignore type error in {col} */
9611 if (col >= change_start && col <= change_end)
9612 hlID = HLF_TXD; /* changed text */
9613 else
9614 hlID = HLF_CHD; /* changed line */
9616 rettv->vval.v_number = hlID == (hlf_T)0 ? 0 : (int)hlID;
9617 #endif
9621 * "empty({expr})" function
9623 static void
9624 f_empty(argvars, rettv)
9625 typval_T *argvars;
9626 typval_T *rettv;
9628 int n;
9630 switch (argvars[0].v_type)
9632 case VAR_STRING:
9633 case VAR_FUNC:
9634 n = argvars[0].vval.v_string == NULL
9635 || *argvars[0].vval.v_string == NUL;
9636 break;
9637 case VAR_NUMBER:
9638 n = argvars[0].vval.v_number == 0;
9639 break;
9640 #ifdef FEAT_FLOAT
9641 case VAR_FLOAT:
9642 n = argvars[0].vval.v_float == 0.0;
9643 break;
9644 #endif
9645 case VAR_LIST:
9646 n = argvars[0].vval.v_list == NULL
9647 || argvars[0].vval.v_list->lv_first == NULL;
9648 break;
9649 case VAR_DICT:
9650 n = argvars[0].vval.v_dict == NULL
9651 || argvars[0].vval.v_dict->dv_hashtab.ht_used == 0;
9652 break;
9653 default:
9654 EMSG2(_(e_intern2), "f_empty()");
9655 n = 0;
9658 rettv->vval.v_number = n;
9662 * "escape({string}, {chars})" function
9664 static void
9665 f_escape(argvars, rettv)
9666 typval_T *argvars;
9667 typval_T *rettv;
9669 char_u buf[NUMBUFLEN];
9671 rettv->vval.v_string = vim_strsave_escaped(get_tv_string(&argvars[0]),
9672 get_tv_string_buf(&argvars[1], buf));
9673 rettv->v_type = VAR_STRING;
9677 * "eval()" function
9679 static void
9680 f_eval(argvars, rettv)
9681 typval_T *argvars;
9682 typval_T *rettv;
9684 char_u *s;
9686 s = get_tv_string_chk(&argvars[0]);
9687 if (s != NULL)
9688 s = skipwhite(s);
9690 if (s == NULL || eval1(&s, rettv, TRUE) == FAIL)
9692 rettv->v_type = VAR_NUMBER;
9693 rettv->vval.v_number = 0;
9695 else if (*s != NUL)
9696 EMSG(_(e_trailing));
9700 * "eventhandler()" function
9702 static void
9703 f_eventhandler(argvars, rettv)
9704 typval_T *argvars UNUSED;
9705 typval_T *rettv;
9707 rettv->vval.v_number = vgetc_busy;
9711 * "executable()" function
9713 static void
9714 f_executable(argvars, rettv)
9715 typval_T *argvars;
9716 typval_T *rettv;
9718 rettv->vval.v_number = mch_can_exe(get_tv_string(&argvars[0]));
9722 * "exists()" function
9724 static void
9725 f_exists(argvars, rettv)
9726 typval_T *argvars;
9727 typval_T *rettv;
9729 char_u *p;
9730 char_u *name;
9731 int n = FALSE;
9732 int len = 0;
9734 p = get_tv_string(&argvars[0]);
9735 if (*p == '$') /* environment variable */
9737 /* first try "normal" environment variables (fast) */
9738 if (mch_getenv(p + 1) != NULL)
9739 n = TRUE;
9740 else
9742 /* try expanding things like $VIM and ${HOME} */
9743 p = expand_env_save(p);
9744 if (p != NULL && *p != '$')
9745 n = TRUE;
9746 vim_free(p);
9749 else if (*p == '&' || *p == '+') /* option */
9751 n = (get_option_tv(&p, NULL, TRUE) == OK);
9752 if (*skipwhite(p) != NUL)
9753 n = FALSE; /* trailing garbage */
9755 else if (*p == '*') /* internal or user defined function */
9757 n = function_exists(p + 1);
9759 else if (*p == ':')
9761 n = cmd_exists(p + 1);
9763 else if (*p == '#')
9765 #ifdef FEAT_AUTOCMD
9766 if (p[1] == '#')
9767 n = autocmd_supported(p + 2);
9768 else
9769 n = au_exists(p + 1);
9770 #endif
9772 else /* internal variable */
9774 char_u *tofree;
9775 typval_T tv;
9777 /* get_name_len() takes care of expanding curly braces */
9778 name = p;
9779 len = get_name_len(&p, &tofree, TRUE, FALSE);
9780 if (len > 0)
9782 if (tofree != NULL)
9783 name = tofree;
9784 n = (get_var_tv(name, len, &tv, FALSE) == OK);
9785 if (n)
9787 /* handle d.key, l[idx], f(expr) */
9788 n = (handle_subscript(&p, &tv, TRUE, FALSE) == OK);
9789 if (n)
9790 clear_tv(&tv);
9793 if (*p != NUL)
9794 n = FALSE;
9796 vim_free(tofree);
9799 rettv->vval.v_number = n;
9803 * "expand()" function
9805 static void
9806 f_expand(argvars, rettv)
9807 typval_T *argvars;
9808 typval_T *rettv;
9810 char_u *s;
9811 int len;
9812 char_u *errormsg;
9813 int flags = WILD_SILENT|WILD_USE_NL|WILD_LIST_NOTFOUND;
9814 expand_T xpc;
9815 int error = FALSE;
9817 rettv->v_type = VAR_STRING;
9818 s = get_tv_string(&argvars[0]);
9819 if (*s == '%' || *s == '#' || *s == '<')
9821 ++emsg_off;
9822 rettv->vval.v_string = eval_vars(s, s, &len, NULL, &errormsg, NULL);
9823 --emsg_off;
9825 else
9827 /* When the optional second argument is non-zero, don't remove matches
9828 * for 'wildignore' and don't put matches for 'suffixes' at the end. */
9829 if (argvars[1].v_type != VAR_UNKNOWN
9830 && get_tv_number_chk(&argvars[1], &error))
9831 flags |= WILD_KEEP_ALL;
9832 if (!error)
9834 ExpandInit(&xpc);
9835 xpc.xp_context = EXPAND_FILES;
9836 rettv->vval.v_string = ExpandOne(&xpc, s, NULL, flags, WILD_ALL);
9838 else
9839 rettv->vval.v_string = NULL;
9844 * "extend(list, list [, idx])" function
9845 * "extend(dict, dict [, action])" function
9847 static void
9848 f_extend(argvars, rettv)
9849 typval_T *argvars;
9850 typval_T *rettv;
9852 if (argvars[0].v_type == VAR_LIST && argvars[1].v_type == VAR_LIST)
9854 list_T *l1, *l2;
9855 listitem_T *item;
9856 long before;
9857 int error = FALSE;
9859 l1 = argvars[0].vval.v_list;
9860 l2 = argvars[1].vval.v_list;
9861 if (l1 != NULL && !tv_check_lock(l1->lv_lock, (char_u *)"extend()")
9862 && l2 != NULL)
9864 if (argvars[2].v_type != VAR_UNKNOWN)
9866 before = get_tv_number_chk(&argvars[2], &error);
9867 if (error)
9868 return; /* type error; errmsg already given */
9870 if (before == l1->lv_len)
9871 item = NULL;
9872 else
9874 item = list_find(l1, before);
9875 if (item == NULL)
9877 EMSGN(_(e_listidx), before);
9878 return;
9882 else
9883 item = NULL;
9884 list_extend(l1, l2, item);
9886 copy_tv(&argvars[0], rettv);
9889 else if (argvars[0].v_type == VAR_DICT && argvars[1].v_type == VAR_DICT)
9891 dict_T *d1, *d2;
9892 dictitem_T *di1;
9893 char_u *action;
9894 int i;
9895 hashitem_T *hi2;
9896 int todo;
9898 d1 = argvars[0].vval.v_dict;
9899 d2 = argvars[1].vval.v_dict;
9900 if (d1 != NULL && !tv_check_lock(d1->dv_lock, (char_u *)"extend()")
9901 && d2 != NULL)
9903 /* Check the third argument. */
9904 if (argvars[2].v_type != VAR_UNKNOWN)
9906 static char *(av[]) = {"keep", "force", "error"};
9908 action = get_tv_string_chk(&argvars[2]);
9909 if (action == NULL)
9910 return; /* type error; errmsg already given */
9911 for (i = 0; i < 3; ++i)
9912 if (STRCMP(action, av[i]) == 0)
9913 break;
9914 if (i == 3)
9916 EMSG2(_(e_invarg2), action);
9917 return;
9920 else
9921 action = (char_u *)"force";
9923 /* Go over all entries in the second dict and add them to the
9924 * first dict. */
9925 todo = (int)d2->dv_hashtab.ht_used;
9926 for (hi2 = d2->dv_hashtab.ht_array; todo > 0; ++hi2)
9928 if (!HASHITEM_EMPTY(hi2))
9930 --todo;
9931 di1 = dict_find(d1, hi2->hi_key, -1);
9932 if (di1 == NULL)
9934 di1 = dictitem_copy(HI2DI(hi2));
9935 if (di1 != NULL && dict_add(d1, di1) == FAIL)
9936 dictitem_free(di1);
9938 else if (*action == 'e')
9940 EMSG2(_("E737: Key already exists: %s"), hi2->hi_key);
9941 break;
9943 else if (*action == 'f')
9945 clear_tv(&di1->di_tv);
9946 copy_tv(&HI2DI(hi2)->di_tv, &di1->di_tv);
9951 copy_tv(&argvars[0], rettv);
9954 else
9955 EMSG2(_(e_listdictarg), "extend()");
9959 * "feedkeys()" function
9961 static void
9962 f_feedkeys(argvars, rettv)
9963 typval_T *argvars;
9964 typval_T *rettv UNUSED;
9966 int remap = TRUE;
9967 char_u *keys, *flags;
9968 char_u nbuf[NUMBUFLEN];
9969 int typed = FALSE;
9970 char_u *keys_esc;
9972 /* This is not allowed in the sandbox. If the commands would still be
9973 * executed in the sandbox it would be OK, but it probably happens later,
9974 * when "sandbox" is no longer set. */
9975 if (check_secure())
9976 return;
9978 keys = get_tv_string(&argvars[0]);
9979 if (*keys != NUL)
9981 if (argvars[1].v_type != VAR_UNKNOWN)
9983 flags = get_tv_string_buf(&argvars[1], nbuf);
9984 for ( ; *flags != NUL; ++flags)
9986 switch (*flags)
9988 case 'n': remap = FALSE; break;
9989 case 'm': remap = TRUE; break;
9990 case 't': typed = TRUE; break;
9995 /* Need to escape K_SPECIAL and CSI before putting the string in the
9996 * typeahead buffer. */
9997 keys_esc = vim_strsave_escape_csi(keys);
9998 if (keys_esc != NULL)
10000 ins_typebuf(keys_esc, (remap ? REMAP_YES : REMAP_NONE),
10001 typebuf.tb_len, !typed, FALSE);
10002 vim_free(keys_esc);
10003 if (vgetc_busy)
10004 typebuf_was_filled = TRUE;
10010 * "filereadable()" function
10012 static void
10013 f_filereadable(argvars, rettv)
10014 typval_T *argvars;
10015 typval_T *rettv;
10017 int fd;
10018 char_u *p;
10019 int n;
10021 #ifndef O_NONBLOCK
10022 # define O_NONBLOCK 0
10023 #endif
10024 p = get_tv_string(&argvars[0]);
10025 if (*p && !mch_isdir(p) && (fd = mch_open((char *)p,
10026 O_RDONLY | O_NONBLOCK, 0)) >= 0)
10028 n = TRUE;
10029 close(fd);
10031 else
10032 n = FALSE;
10034 rettv->vval.v_number = n;
10038 * Return 0 for not writable, 1 for writable file, 2 for a dir which we have
10039 * rights to write into.
10041 static void
10042 f_filewritable(argvars, rettv)
10043 typval_T *argvars;
10044 typval_T *rettv;
10046 rettv->vval.v_number = filewritable(get_tv_string(&argvars[0]));
10049 static void findfilendir __ARGS((typval_T *argvars, typval_T *rettv, int find_what));
10051 static void
10052 findfilendir(argvars, rettv, find_what)
10053 typval_T *argvars;
10054 typval_T *rettv;
10055 int find_what;
10057 #ifdef FEAT_SEARCHPATH
10058 char_u *fname;
10059 char_u *fresult = NULL;
10060 char_u *path = *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path;
10061 char_u *p;
10062 char_u pathbuf[NUMBUFLEN];
10063 int count = 1;
10064 int first = TRUE;
10065 int error = FALSE;
10066 #endif
10068 rettv->vval.v_string = NULL;
10069 rettv->v_type = VAR_STRING;
10071 #ifdef FEAT_SEARCHPATH
10072 fname = get_tv_string(&argvars[0]);
10074 if (argvars[1].v_type != VAR_UNKNOWN)
10076 p = get_tv_string_buf_chk(&argvars[1], pathbuf);
10077 if (p == NULL)
10078 error = TRUE;
10079 else
10081 if (*p != NUL)
10082 path = p;
10084 if (argvars[2].v_type != VAR_UNKNOWN)
10085 count = get_tv_number_chk(&argvars[2], &error);
10089 if (count < 0 && rettv_list_alloc(rettv) == FAIL)
10090 error = TRUE;
10092 if (*fname != NUL && !error)
10096 if (rettv->v_type == VAR_STRING)
10097 vim_free(fresult);
10098 fresult = find_file_in_path_option(first ? fname : NULL,
10099 first ? (int)STRLEN(fname) : 0,
10100 0, first, path,
10101 find_what,
10102 curbuf->b_ffname,
10103 find_what == FINDFILE_DIR
10104 ? (char_u *)"" : curbuf->b_p_sua);
10105 first = FALSE;
10107 if (fresult != NULL && rettv->v_type == VAR_LIST)
10108 list_append_string(rettv->vval.v_list, fresult, -1);
10110 } while ((rettv->v_type == VAR_LIST || --count > 0) && fresult != NULL);
10113 if (rettv->v_type == VAR_STRING)
10114 rettv->vval.v_string = fresult;
10115 #endif
10118 static void filter_map __ARGS((typval_T *argvars, typval_T *rettv, int map));
10119 static int filter_map_one __ARGS((typval_T *tv, char_u *expr, int map, int *remp));
10122 * Implementation of map() and filter().
10124 static void
10125 filter_map(argvars, rettv, map)
10126 typval_T *argvars;
10127 typval_T *rettv;
10128 int map;
10130 char_u buf[NUMBUFLEN];
10131 char_u *expr;
10132 listitem_T *li, *nli;
10133 list_T *l = NULL;
10134 dictitem_T *di;
10135 hashtab_T *ht;
10136 hashitem_T *hi;
10137 dict_T *d = NULL;
10138 typval_T save_val;
10139 typval_T save_key;
10140 int rem;
10141 int todo;
10142 char_u *ermsg = map ? (char_u *)"map()" : (char_u *)"filter()";
10143 int save_did_emsg;
10144 int index = 0;
10146 if (argvars[0].v_type == VAR_LIST)
10148 if ((l = argvars[0].vval.v_list) == NULL
10149 || (map && tv_check_lock(l->lv_lock, ermsg)))
10150 return;
10152 else if (argvars[0].v_type == VAR_DICT)
10154 if ((d = argvars[0].vval.v_dict) == NULL
10155 || (map && tv_check_lock(d->dv_lock, ermsg)))
10156 return;
10158 else
10160 EMSG2(_(e_listdictarg), ermsg);
10161 return;
10164 expr = get_tv_string_buf_chk(&argvars[1], buf);
10165 /* On type errors, the preceding call has already displayed an error
10166 * message. Avoid a misleading error message for an empty string that
10167 * was not passed as argument. */
10168 if (expr != NULL)
10170 prepare_vimvar(VV_VAL, &save_val);
10171 expr = skipwhite(expr);
10173 /* We reset "did_emsg" to be able to detect whether an error
10174 * occurred during evaluation of the expression. */
10175 save_did_emsg = did_emsg;
10176 did_emsg = FALSE;
10178 prepare_vimvar(VV_KEY, &save_key);
10179 if (argvars[0].v_type == VAR_DICT)
10181 vimvars[VV_KEY].vv_type = VAR_STRING;
10183 ht = &d->dv_hashtab;
10184 hash_lock(ht);
10185 todo = (int)ht->ht_used;
10186 for (hi = ht->ht_array; todo > 0; ++hi)
10188 if (!HASHITEM_EMPTY(hi))
10190 --todo;
10191 di = HI2DI(hi);
10192 if (tv_check_lock(di->di_tv.v_lock, ermsg))
10193 break;
10194 vimvars[VV_KEY].vv_str = vim_strsave(di->di_key);
10195 if (filter_map_one(&di->di_tv, expr, map, &rem) == FAIL
10196 || did_emsg)
10197 break;
10198 if (!map && rem)
10199 dictitem_remove(d, di);
10200 clear_tv(&vimvars[VV_KEY].vv_tv);
10203 hash_unlock(ht);
10205 else
10207 vimvars[VV_KEY].vv_type = VAR_NUMBER;
10209 for (li = l->lv_first; li != NULL; li = nli)
10211 if (tv_check_lock(li->li_tv.v_lock, ermsg))
10212 break;
10213 nli = li->li_next;
10214 vimvars[VV_KEY].vv_nr = index;
10215 if (filter_map_one(&li->li_tv, expr, map, &rem) == FAIL
10216 || did_emsg)
10217 break;
10218 if (!map && rem)
10219 listitem_remove(l, li);
10220 ++index;
10224 restore_vimvar(VV_KEY, &save_key);
10225 restore_vimvar(VV_VAL, &save_val);
10227 did_emsg |= save_did_emsg;
10230 copy_tv(&argvars[0], rettv);
10233 static int
10234 filter_map_one(tv, expr, map, remp)
10235 typval_T *tv;
10236 char_u *expr;
10237 int map;
10238 int *remp;
10240 typval_T rettv;
10241 char_u *s;
10242 int retval = FAIL;
10244 copy_tv(tv, &vimvars[VV_VAL].vv_tv);
10245 s = expr;
10246 if (eval1(&s, &rettv, TRUE) == FAIL)
10247 goto theend;
10248 if (*s != NUL) /* check for trailing chars after expr */
10250 EMSG2(_(e_invexpr2), s);
10251 goto theend;
10253 if (map)
10255 /* map(): replace the list item value */
10256 clear_tv(tv);
10257 rettv.v_lock = 0;
10258 *tv = rettv;
10260 else
10262 int error = FALSE;
10264 /* filter(): when expr is zero remove the item */
10265 *remp = (get_tv_number_chk(&rettv, &error) == 0);
10266 clear_tv(&rettv);
10267 /* On type error, nothing has been removed; return FAIL to stop the
10268 * loop. The error message was given by get_tv_number_chk(). */
10269 if (error)
10270 goto theend;
10272 retval = OK;
10273 theend:
10274 clear_tv(&vimvars[VV_VAL].vv_tv);
10275 return retval;
10279 * "filter()" function
10281 static void
10282 f_filter(argvars, rettv)
10283 typval_T *argvars;
10284 typval_T *rettv;
10286 filter_map(argvars, rettv, FALSE);
10290 * "finddir({fname}[, {path}[, {count}]])" function
10292 static void
10293 f_finddir(argvars, rettv)
10294 typval_T *argvars;
10295 typval_T *rettv;
10297 findfilendir(argvars, rettv, FINDFILE_DIR);
10301 * "findfile({fname}[, {path}[, {count}]])" function
10303 static void
10304 f_findfile(argvars, rettv)
10305 typval_T *argvars;
10306 typval_T *rettv;
10308 findfilendir(argvars, rettv, FINDFILE_FILE);
10311 #ifdef FEAT_FLOAT
10313 * "float2nr({float})" function
10315 static void
10316 f_float2nr(argvars, rettv)
10317 typval_T *argvars;
10318 typval_T *rettv;
10320 float_T f;
10322 if (get_float_arg(argvars, &f) == OK)
10324 if (f < -0x7fffffff)
10325 rettv->vval.v_number = -0x7fffffff;
10326 else if (f > 0x7fffffff)
10327 rettv->vval.v_number = 0x7fffffff;
10328 else
10329 rettv->vval.v_number = (varnumber_T)f;
10334 * "floor({float})" function
10336 static void
10337 f_floor(argvars, rettv)
10338 typval_T *argvars;
10339 typval_T *rettv;
10341 float_T f;
10343 rettv->v_type = VAR_FLOAT;
10344 if (get_float_arg(argvars, &f) == OK)
10345 rettv->vval.v_float = floor(f);
10346 else
10347 rettv->vval.v_float = 0.0;
10349 #endif
10352 * "fnameescape({string})" function
10354 static void
10355 f_fnameescape(argvars, rettv)
10356 typval_T *argvars;
10357 typval_T *rettv;
10359 rettv->vval.v_string = vim_strsave_fnameescape(
10360 get_tv_string(&argvars[0]), FALSE);
10361 rettv->v_type = VAR_STRING;
10365 * "fnamemodify({fname}, {mods})" function
10367 static void
10368 f_fnamemodify(argvars, rettv)
10369 typval_T *argvars;
10370 typval_T *rettv;
10372 char_u *fname;
10373 char_u *mods;
10374 int usedlen = 0;
10375 int len;
10376 char_u *fbuf = NULL;
10377 char_u buf[NUMBUFLEN];
10379 fname = get_tv_string_chk(&argvars[0]);
10380 mods = get_tv_string_buf_chk(&argvars[1], buf);
10381 if (fname == NULL || mods == NULL)
10382 fname = NULL;
10383 else
10385 len = (int)STRLEN(fname);
10386 (void)modify_fname(mods, &usedlen, &fname, &fbuf, &len);
10389 rettv->v_type = VAR_STRING;
10390 if (fname == NULL)
10391 rettv->vval.v_string = NULL;
10392 else
10393 rettv->vval.v_string = vim_strnsave(fname, len);
10394 vim_free(fbuf);
10397 static void foldclosed_both __ARGS((typval_T *argvars, typval_T *rettv, int end));
10400 * "foldclosed()" function
10402 static void
10403 foldclosed_both(argvars, rettv, end)
10404 typval_T *argvars;
10405 typval_T *rettv;
10406 int end;
10408 #ifdef FEAT_FOLDING
10409 linenr_T lnum;
10410 linenr_T first, last;
10412 lnum = get_tv_lnum(argvars);
10413 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
10415 if (hasFoldingWin(curwin, lnum, &first, &last, FALSE, NULL))
10417 if (end)
10418 rettv->vval.v_number = (varnumber_T)last;
10419 else
10420 rettv->vval.v_number = (varnumber_T)first;
10421 return;
10424 #endif
10425 rettv->vval.v_number = -1;
10429 * "foldclosed()" function
10431 static void
10432 f_foldclosed(argvars, rettv)
10433 typval_T *argvars;
10434 typval_T *rettv;
10436 foldclosed_both(argvars, rettv, FALSE);
10440 * "foldclosedend()" function
10442 static void
10443 f_foldclosedend(argvars, rettv)
10444 typval_T *argvars;
10445 typval_T *rettv;
10447 foldclosed_both(argvars, rettv, TRUE);
10451 * "foldlevel()" function
10453 static void
10454 f_foldlevel(argvars, rettv)
10455 typval_T *argvars;
10456 typval_T *rettv;
10458 #ifdef FEAT_FOLDING
10459 linenr_T lnum;
10461 lnum = get_tv_lnum(argvars);
10462 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
10463 rettv->vval.v_number = foldLevel(lnum);
10464 #endif
10468 * "foldtext()" function
10470 static void
10471 f_foldtext(argvars, rettv)
10472 typval_T *argvars UNUSED;
10473 typval_T *rettv;
10475 #ifdef FEAT_FOLDING
10476 linenr_T lnum;
10477 char_u *s;
10478 char_u *r;
10479 int len;
10480 char *txt;
10481 #endif
10483 rettv->v_type = VAR_STRING;
10484 rettv->vval.v_string = NULL;
10485 #ifdef FEAT_FOLDING
10486 if ((linenr_T)vimvars[VV_FOLDSTART].vv_nr > 0
10487 && (linenr_T)vimvars[VV_FOLDEND].vv_nr
10488 <= curbuf->b_ml.ml_line_count
10489 && vimvars[VV_FOLDDASHES].vv_str != NULL)
10491 /* Find first non-empty line in the fold. */
10492 lnum = (linenr_T)vimvars[VV_FOLDSTART].vv_nr;
10493 while (lnum < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
10495 if (!linewhite(lnum))
10496 break;
10497 ++lnum;
10500 /* Find interesting text in this line. */
10501 s = skipwhite(ml_get(lnum));
10502 /* skip C comment-start */
10503 if (s[0] == '/' && (s[1] == '*' || s[1] == '/'))
10505 s = skipwhite(s + 2);
10506 if (*skipwhite(s) == NUL
10507 && lnum + 1 < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
10509 s = skipwhite(ml_get(lnum + 1));
10510 if (*s == '*')
10511 s = skipwhite(s + 1);
10514 txt = _("+-%s%3ld lines: ");
10515 r = alloc((unsigned)(STRLEN(txt)
10516 + STRLEN(vimvars[VV_FOLDDASHES].vv_str) /* for %s */
10517 + 20 /* for %3ld */
10518 + STRLEN(s))); /* concatenated */
10519 if (r != NULL)
10521 sprintf((char *)r, txt, vimvars[VV_FOLDDASHES].vv_str,
10522 (long)((linenr_T)vimvars[VV_FOLDEND].vv_nr
10523 - (linenr_T)vimvars[VV_FOLDSTART].vv_nr + 1));
10524 len = (int)STRLEN(r);
10525 STRCAT(r, s);
10526 /* remove 'foldmarker' and 'commentstring' */
10527 foldtext_cleanup(r + len);
10528 rettv->vval.v_string = r;
10531 #endif
10535 * "foldtextresult(lnum)" function
10537 static void
10538 f_foldtextresult(argvars, rettv)
10539 typval_T *argvars UNUSED;
10540 typval_T *rettv;
10542 #ifdef FEAT_FOLDING
10543 linenr_T lnum;
10544 char_u *text;
10545 char_u buf[51];
10546 foldinfo_T foldinfo;
10547 int fold_count;
10548 #endif
10550 rettv->v_type = VAR_STRING;
10551 rettv->vval.v_string = NULL;
10552 #ifdef FEAT_FOLDING
10553 lnum = get_tv_lnum(argvars);
10554 /* treat illegal types and illegal string values for {lnum} the same */
10555 if (lnum < 0)
10556 lnum = 0;
10557 fold_count = foldedCount(curwin, lnum, &foldinfo);
10558 if (fold_count > 0)
10560 text = get_foldtext(curwin, lnum, lnum + fold_count - 1,
10561 &foldinfo, buf);
10562 if (text == buf)
10563 text = vim_strsave(text);
10564 rettv->vval.v_string = text;
10566 #endif
10570 * "foreground()" function
10572 static void
10573 f_foreground(argvars, rettv)
10574 typval_T *argvars UNUSED;
10575 typval_T *rettv UNUSED;
10577 #ifdef FEAT_GUI
10578 if (gui.in_use)
10579 gui_mch_set_foreground();
10580 #else
10581 # ifdef WIN32
10582 win32_set_foreground();
10583 # endif
10584 #endif
10588 * "function()" function
10590 static void
10591 f_function(argvars, rettv)
10592 typval_T *argvars;
10593 typval_T *rettv;
10595 char_u *s;
10597 s = get_tv_string(&argvars[0]);
10598 if (s == NULL || *s == NUL || VIM_ISDIGIT(*s))
10599 EMSG2(_(e_invarg2), s);
10600 /* Don't check an autoload name for existence here. */
10601 else if (vim_strchr(s, AUTOLOAD_CHAR) == NULL && !function_exists(s))
10602 EMSG2(_("E700: Unknown function: %s"), s);
10603 else
10605 rettv->vval.v_string = vim_strsave(s);
10606 rettv->v_type = VAR_FUNC;
10611 * "garbagecollect()" function
10613 static void
10614 f_garbagecollect(argvars, rettv)
10615 typval_T *argvars;
10616 typval_T *rettv UNUSED;
10618 /* This is postponed until we are back at the toplevel, because we may be
10619 * using Lists and Dicts internally. E.g.: ":echo [garbagecollect()]". */
10620 want_garbage_collect = TRUE;
10622 if (argvars[0].v_type != VAR_UNKNOWN && get_tv_number(&argvars[0]) == 1)
10623 garbage_collect_at_exit = TRUE;
10627 * "get()" function
10629 static void
10630 f_get(argvars, rettv)
10631 typval_T *argvars;
10632 typval_T *rettv;
10634 listitem_T *li;
10635 list_T *l;
10636 dictitem_T *di;
10637 dict_T *d;
10638 typval_T *tv = NULL;
10640 if (argvars[0].v_type == VAR_LIST)
10642 if ((l = argvars[0].vval.v_list) != NULL)
10644 int error = FALSE;
10646 li = list_find(l, get_tv_number_chk(&argvars[1], &error));
10647 if (!error && li != NULL)
10648 tv = &li->li_tv;
10651 else if (argvars[0].v_type == VAR_DICT)
10653 if ((d = argvars[0].vval.v_dict) != NULL)
10655 di = dict_find(d, get_tv_string(&argvars[1]), -1);
10656 if (di != NULL)
10657 tv = &di->di_tv;
10660 else
10661 EMSG2(_(e_listdictarg), "get()");
10663 if (tv == NULL)
10665 if (argvars[2].v_type != VAR_UNKNOWN)
10666 copy_tv(&argvars[2], rettv);
10668 else
10669 copy_tv(tv, rettv);
10672 static void get_buffer_lines __ARGS((buf_T *buf, linenr_T start, linenr_T end, int retlist, typval_T *rettv));
10675 * Get line or list of lines from buffer "buf" into "rettv".
10676 * Return a range (from start to end) of lines in rettv from the specified
10677 * buffer.
10678 * If 'retlist' is TRUE, then the lines are returned as a Vim List.
10680 static void
10681 get_buffer_lines(buf, start, end, retlist, rettv)
10682 buf_T *buf;
10683 linenr_T start;
10684 linenr_T end;
10685 int retlist;
10686 typval_T *rettv;
10688 char_u *p;
10690 if (retlist && rettv_list_alloc(rettv) == FAIL)
10691 return;
10693 if (buf == NULL || buf->b_ml.ml_mfp == NULL || start < 0)
10694 return;
10696 if (!retlist)
10698 if (start >= 1 && start <= buf->b_ml.ml_line_count)
10699 p = ml_get_buf(buf, start, FALSE);
10700 else
10701 p = (char_u *)"";
10703 rettv->v_type = VAR_STRING;
10704 rettv->vval.v_string = vim_strsave(p);
10706 else
10708 if (end < start)
10709 return;
10711 if (start < 1)
10712 start = 1;
10713 if (end > buf->b_ml.ml_line_count)
10714 end = buf->b_ml.ml_line_count;
10715 while (start <= end)
10716 if (list_append_string(rettv->vval.v_list,
10717 ml_get_buf(buf, start++, FALSE), -1) == FAIL)
10718 break;
10723 * "getbufline()" function
10725 static void
10726 f_getbufline(argvars, rettv)
10727 typval_T *argvars;
10728 typval_T *rettv;
10730 linenr_T lnum;
10731 linenr_T end;
10732 buf_T *buf;
10734 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
10735 ++emsg_off;
10736 buf = get_buf_tv(&argvars[0]);
10737 --emsg_off;
10739 lnum = get_tv_lnum_buf(&argvars[1], buf);
10740 if (argvars[2].v_type == VAR_UNKNOWN)
10741 end = lnum;
10742 else
10743 end = get_tv_lnum_buf(&argvars[2], buf);
10745 get_buffer_lines(buf, lnum, end, TRUE, rettv);
10749 * "getbufvar()" function
10751 static void
10752 f_getbufvar(argvars, rettv)
10753 typval_T *argvars;
10754 typval_T *rettv;
10756 buf_T *buf;
10757 buf_T *save_curbuf;
10758 char_u *varname;
10759 dictitem_T *v;
10761 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
10762 varname = get_tv_string_chk(&argvars[1]);
10763 ++emsg_off;
10764 buf = get_buf_tv(&argvars[0]);
10766 rettv->v_type = VAR_STRING;
10767 rettv->vval.v_string = NULL;
10769 if (buf != NULL && varname != NULL)
10771 /* set curbuf to be our buf, temporarily */
10772 save_curbuf = curbuf;
10773 curbuf = buf;
10775 if (*varname == '&') /* buffer-local-option */
10776 get_option_tv(&varname, rettv, TRUE);
10777 else
10779 if (*varname == NUL)
10780 /* let getbufvar({nr}, "") return the "b:" dictionary. The
10781 * scope prefix before the NUL byte is required by
10782 * find_var_in_ht(). */
10783 varname = (char_u *)"b:" + 2;
10784 /* look up the variable */
10785 v = find_var_in_ht(&curbuf->b_vars.dv_hashtab, varname, FALSE);
10786 if (v != NULL)
10787 copy_tv(&v->di_tv, rettv);
10790 /* restore previous notion of curbuf */
10791 curbuf = save_curbuf;
10794 --emsg_off;
10798 * "getchar()" function
10800 static void
10801 f_getchar(argvars, rettv)
10802 typval_T *argvars;
10803 typval_T *rettv;
10805 varnumber_T n;
10806 int error = FALSE;
10808 /* Position the cursor. Needed after a message that ends in a space. */
10809 windgoto(msg_row, msg_col);
10811 ++no_mapping;
10812 ++allow_keys;
10813 for (;;)
10815 if (argvars[0].v_type == VAR_UNKNOWN)
10816 /* getchar(): blocking wait. */
10817 n = safe_vgetc();
10818 else if (get_tv_number_chk(&argvars[0], &error) == 1)
10819 /* getchar(1): only check if char avail */
10820 n = vpeekc();
10821 else if (error || vpeekc() == NUL)
10822 /* illegal argument or getchar(0) and no char avail: return zero */
10823 n = 0;
10824 else
10825 /* getchar(0) and char avail: return char */
10826 n = safe_vgetc();
10827 if (n == K_IGNORE)
10828 continue;
10829 break;
10831 --no_mapping;
10832 --allow_keys;
10834 vimvars[VV_MOUSE_WIN].vv_nr = 0;
10835 vimvars[VV_MOUSE_LNUM].vv_nr = 0;
10836 vimvars[VV_MOUSE_COL].vv_nr = 0;
10838 rettv->vval.v_number = n;
10839 if (IS_SPECIAL(n) || mod_mask != 0)
10841 char_u temp[10]; /* modifier: 3, mbyte-char: 6, NUL: 1 */
10842 int i = 0;
10844 /* Turn a special key into three bytes, plus modifier. */
10845 if (mod_mask != 0)
10847 temp[i++] = K_SPECIAL;
10848 temp[i++] = KS_MODIFIER;
10849 temp[i++] = mod_mask;
10851 if (IS_SPECIAL(n))
10853 temp[i++] = K_SPECIAL;
10854 temp[i++] = K_SECOND(n);
10855 temp[i++] = K_THIRD(n);
10857 #ifdef FEAT_MBYTE
10858 else if (has_mbyte)
10859 i += (*mb_char2bytes)(n, temp + i);
10860 #endif
10861 else
10862 temp[i++] = n;
10863 temp[i++] = NUL;
10864 rettv->v_type = VAR_STRING;
10865 rettv->vval.v_string = vim_strsave(temp);
10867 #ifdef FEAT_MOUSE
10868 if (n == K_LEFTMOUSE
10869 || n == K_LEFTMOUSE_NM
10870 || n == K_LEFTDRAG
10871 || n == K_LEFTRELEASE
10872 || n == K_LEFTRELEASE_NM
10873 || n == K_MIDDLEMOUSE
10874 || n == K_MIDDLEDRAG
10875 || n == K_MIDDLERELEASE
10876 || n == K_RIGHTMOUSE
10877 || n == K_RIGHTDRAG
10878 || n == K_RIGHTRELEASE
10879 || n == K_X1MOUSE
10880 || n == K_X1DRAG
10881 || n == K_X1RELEASE
10882 || n == K_X2MOUSE
10883 || n == K_X2DRAG
10884 || n == K_X2RELEASE
10885 || n == K_MOUSEDOWN
10886 || n == K_MOUSEUP)
10888 int row = mouse_row;
10889 int col = mouse_col;
10890 win_T *win;
10891 linenr_T lnum;
10892 # ifdef FEAT_WINDOWS
10893 win_T *wp;
10894 # endif
10895 int winnr = 1;
10897 if (row >= 0 && col >= 0)
10899 /* Find the window at the mouse coordinates and compute the
10900 * text position. */
10901 win = mouse_find_win(&row, &col);
10902 (void)mouse_comp_pos(win, &row, &col, &lnum);
10903 # ifdef FEAT_WINDOWS
10904 for (wp = firstwin; wp != win; wp = wp->w_next)
10905 ++winnr;
10906 # endif
10907 vimvars[VV_MOUSE_WIN].vv_nr = winnr;
10908 vimvars[VV_MOUSE_LNUM].vv_nr = lnum;
10909 vimvars[VV_MOUSE_COL].vv_nr = col + 1;
10912 #endif
10917 * "getcharmod()" function
10919 static void
10920 f_getcharmod(argvars, rettv)
10921 typval_T *argvars UNUSED;
10922 typval_T *rettv;
10924 rettv->vval.v_number = mod_mask;
10928 * "getcmdline()" function
10930 static void
10931 f_getcmdline(argvars, rettv)
10932 typval_T *argvars UNUSED;
10933 typval_T *rettv;
10935 rettv->v_type = VAR_STRING;
10936 rettv->vval.v_string = get_cmdline_str();
10940 * "getcmdpos()" function
10942 static void
10943 f_getcmdpos(argvars, rettv)
10944 typval_T *argvars UNUSED;
10945 typval_T *rettv;
10947 rettv->vval.v_number = get_cmdline_pos() + 1;
10951 * "getcmdtype()" function
10953 static void
10954 f_getcmdtype(argvars, rettv)
10955 typval_T *argvars UNUSED;
10956 typval_T *rettv;
10958 rettv->v_type = VAR_STRING;
10959 rettv->vval.v_string = alloc(2);
10960 if (rettv->vval.v_string != NULL)
10962 rettv->vval.v_string[0] = get_cmdline_type();
10963 rettv->vval.v_string[1] = NUL;
10968 * "getcwd()" function
10970 static void
10971 f_getcwd(argvars, rettv)
10972 typval_T *argvars UNUSED;
10973 typval_T *rettv;
10975 char_u cwd[MAXPATHL];
10977 rettv->v_type = VAR_STRING;
10978 if (mch_dirname(cwd, MAXPATHL) == FAIL)
10979 rettv->vval.v_string = NULL;
10980 else
10982 rettv->vval.v_string = vim_strsave(cwd);
10983 #ifdef BACKSLASH_IN_FILENAME
10984 if (rettv->vval.v_string != NULL)
10985 slash_adjust(rettv->vval.v_string);
10986 #endif
10991 * "getfontname()" function
10993 static void
10994 f_getfontname(argvars, rettv)
10995 typval_T *argvars UNUSED;
10996 typval_T *rettv;
10998 rettv->v_type = VAR_STRING;
10999 rettv->vval.v_string = NULL;
11000 #ifdef FEAT_GUI
11001 if (gui.in_use)
11003 GuiFont font;
11004 char_u *name = NULL;
11006 if (argvars[0].v_type == VAR_UNKNOWN)
11008 /* Get the "Normal" font. Either the name saved by
11009 * hl_set_font_name() or from the font ID. */
11010 font = gui.norm_font;
11011 name = hl_get_font_name();
11013 else
11015 name = get_tv_string(&argvars[0]);
11016 if (STRCMP(name, "*") == 0) /* don't use font dialog */
11017 return;
11018 font = gui_mch_get_font(name, FALSE);
11019 if (font == NOFONT)
11020 return; /* Invalid font name, return empty string. */
11022 rettv->vval.v_string = gui_mch_get_fontname(font, name);
11023 if (argvars[0].v_type != VAR_UNKNOWN)
11024 gui_mch_free_font(font);
11026 #endif
11030 * "getfperm({fname})" function
11032 static void
11033 f_getfperm(argvars, rettv)
11034 typval_T *argvars;
11035 typval_T *rettv;
11037 char_u *fname;
11038 struct stat st;
11039 char_u *perm = NULL;
11040 char_u flags[] = "rwx";
11041 int i;
11043 fname = get_tv_string(&argvars[0]);
11045 rettv->v_type = VAR_STRING;
11046 if (mch_stat((char *)fname, &st) >= 0)
11048 perm = vim_strsave((char_u *)"---------");
11049 if (perm != NULL)
11051 for (i = 0; i < 9; i++)
11053 if (st.st_mode & (1 << (8 - i)))
11054 perm[i] = flags[i % 3];
11058 rettv->vval.v_string = perm;
11062 * "getfsize({fname})" function
11064 static void
11065 f_getfsize(argvars, rettv)
11066 typval_T *argvars;
11067 typval_T *rettv;
11069 char_u *fname;
11070 struct stat st;
11072 fname = get_tv_string(&argvars[0]);
11074 rettv->v_type = VAR_NUMBER;
11076 if (mch_stat((char *)fname, &st) >= 0)
11078 if (mch_isdir(fname))
11079 rettv->vval.v_number = 0;
11080 else
11082 rettv->vval.v_number = (varnumber_T)st.st_size;
11084 /* non-perfect check for overflow */
11085 if ((off_t)rettv->vval.v_number != (off_t)st.st_size)
11086 rettv->vval.v_number = -2;
11089 else
11090 rettv->vval.v_number = -1;
11094 * "getftime({fname})" function
11096 static void
11097 f_getftime(argvars, rettv)
11098 typval_T *argvars;
11099 typval_T *rettv;
11101 char_u *fname;
11102 struct stat st;
11104 fname = get_tv_string(&argvars[0]);
11106 if (mch_stat((char *)fname, &st) >= 0)
11107 rettv->vval.v_number = (varnumber_T)st.st_mtime;
11108 else
11109 rettv->vval.v_number = -1;
11113 * "getftype({fname})" function
11115 static void
11116 f_getftype(argvars, rettv)
11117 typval_T *argvars;
11118 typval_T *rettv;
11120 char_u *fname;
11121 struct stat st;
11122 char_u *type = NULL;
11123 char *t;
11125 fname = get_tv_string(&argvars[0]);
11127 rettv->v_type = VAR_STRING;
11128 if (mch_lstat((char *)fname, &st) >= 0)
11130 #ifdef S_ISREG
11131 if (S_ISREG(st.st_mode))
11132 t = "file";
11133 else if (S_ISDIR(st.st_mode))
11134 t = "dir";
11135 # ifdef S_ISLNK
11136 else if (S_ISLNK(st.st_mode))
11137 t = "link";
11138 # endif
11139 # ifdef S_ISBLK
11140 else if (S_ISBLK(st.st_mode))
11141 t = "bdev";
11142 # endif
11143 # ifdef S_ISCHR
11144 else if (S_ISCHR(st.st_mode))
11145 t = "cdev";
11146 # endif
11147 # ifdef S_ISFIFO
11148 else if (S_ISFIFO(st.st_mode))
11149 t = "fifo";
11150 # endif
11151 # ifdef S_ISSOCK
11152 else if (S_ISSOCK(st.st_mode))
11153 t = "fifo";
11154 # endif
11155 else
11156 t = "other";
11157 #else
11158 # ifdef S_IFMT
11159 switch (st.st_mode & S_IFMT)
11161 case S_IFREG: t = "file"; break;
11162 case S_IFDIR: t = "dir"; break;
11163 # ifdef S_IFLNK
11164 case S_IFLNK: t = "link"; break;
11165 # endif
11166 # ifdef S_IFBLK
11167 case S_IFBLK: t = "bdev"; break;
11168 # endif
11169 # ifdef S_IFCHR
11170 case S_IFCHR: t = "cdev"; break;
11171 # endif
11172 # ifdef S_IFIFO
11173 case S_IFIFO: t = "fifo"; break;
11174 # endif
11175 # ifdef S_IFSOCK
11176 case S_IFSOCK: t = "socket"; break;
11177 # endif
11178 default: t = "other";
11180 # else
11181 if (mch_isdir(fname))
11182 t = "dir";
11183 else
11184 t = "file";
11185 # endif
11186 #endif
11187 type = vim_strsave((char_u *)t);
11189 rettv->vval.v_string = type;
11193 * "getline(lnum, [end])" function
11195 static void
11196 f_getline(argvars, rettv)
11197 typval_T *argvars;
11198 typval_T *rettv;
11200 linenr_T lnum;
11201 linenr_T end;
11202 int retlist;
11204 lnum = get_tv_lnum(argvars);
11205 if (argvars[1].v_type == VAR_UNKNOWN)
11207 end = 0;
11208 retlist = FALSE;
11210 else
11212 end = get_tv_lnum(&argvars[1]);
11213 retlist = TRUE;
11216 get_buffer_lines(curbuf, lnum, end, retlist, rettv);
11220 * "getmatches()" function
11222 static void
11223 f_getmatches(argvars, rettv)
11224 typval_T *argvars UNUSED;
11225 typval_T *rettv;
11227 #ifdef FEAT_SEARCH_EXTRA
11228 dict_T *dict;
11229 matchitem_T *cur = curwin->w_match_head;
11231 if (rettv_list_alloc(rettv) == OK)
11233 while (cur != NULL)
11235 dict = dict_alloc();
11236 if (dict == NULL)
11237 return;
11238 dict_add_nr_str(dict, "group", 0L, syn_id2name(cur->hlg_id));
11239 dict_add_nr_str(dict, "pattern", 0L, cur->pattern);
11240 dict_add_nr_str(dict, "priority", (long)cur->priority, NULL);
11241 dict_add_nr_str(dict, "id", (long)cur->id, NULL);
11242 list_append_dict(rettv->vval.v_list, dict);
11243 cur = cur->next;
11246 #endif
11250 * "getpid()" function
11252 static void
11253 f_getpid(argvars, rettv)
11254 typval_T *argvars UNUSED;
11255 typval_T *rettv;
11257 rettv->vval.v_number = mch_get_pid();
11261 * "getpos(string)" function
11263 static void
11264 f_getpos(argvars, rettv)
11265 typval_T *argvars;
11266 typval_T *rettv;
11268 pos_T *fp;
11269 list_T *l;
11270 int fnum = -1;
11272 if (rettv_list_alloc(rettv) == OK)
11274 l = rettv->vval.v_list;
11275 fp = var2fpos(&argvars[0], TRUE, &fnum);
11276 if (fnum != -1)
11277 list_append_number(l, (varnumber_T)fnum);
11278 else
11279 list_append_number(l, (varnumber_T)0);
11280 list_append_number(l, (fp != NULL) ? (varnumber_T)fp->lnum
11281 : (varnumber_T)0);
11282 list_append_number(l, (fp != NULL)
11283 ? (varnumber_T)(fp->col == MAXCOL ? MAXCOL : fp->col + 1)
11284 : (varnumber_T)0);
11285 list_append_number(l,
11286 #ifdef FEAT_VIRTUALEDIT
11287 (fp != NULL) ? (varnumber_T)fp->coladd :
11288 #endif
11289 (varnumber_T)0);
11291 else
11292 rettv->vval.v_number = FALSE;
11296 * "getqflist()" and "getloclist()" functions
11298 static void
11299 f_getqflist(argvars, rettv)
11300 typval_T *argvars UNUSED;
11301 typval_T *rettv UNUSED;
11303 #ifdef FEAT_QUICKFIX
11304 win_T *wp;
11305 #endif
11307 #ifdef FEAT_QUICKFIX
11308 if (rettv_list_alloc(rettv) == OK)
11310 wp = NULL;
11311 if (argvars[0].v_type != VAR_UNKNOWN) /* getloclist() */
11313 wp = find_win_by_nr(&argvars[0], NULL);
11314 if (wp == NULL)
11315 return;
11318 (void)get_errorlist(wp, rettv->vval.v_list);
11320 #endif
11324 * "getreg()" function
11326 static void
11327 f_getreg(argvars, rettv)
11328 typval_T *argvars;
11329 typval_T *rettv;
11331 char_u *strregname;
11332 int regname;
11333 int arg2 = FALSE;
11334 int error = FALSE;
11336 if (argvars[0].v_type != VAR_UNKNOWN)
11338 strregname = get_tv_string_chk(&argvars[0]);
11339 error = strregname == NULL;
11340 if (argvars[1].v_type != VAR_UNKNOWN)
11341 arg2 = get_tv_number_chk(&argvars[1], &error);
11343 else
11344 strregname = vimvars[VV_REG].vv_str;
11345 regname = (strregname == NULL ? '"' : *strregname);
11346 if (regname == 0)
11347 regname = '"';
11349 rettv->v_type = VAR_STRING;
11350 rettv->vval.v_string = error ? NULL :
11351 get_reg_contents(regname, TRUE, arg2);
11355 * "getregtype()" function
11357 static void
11358 f_getregtype(argvars, rettv)
11359 typval_T *argvars;
11360 typval_T *rettv;
11362 char_u *strregname;
11363 int regname;
11364 char_u buf[NUMBUFLEN + 2];
11365 long reglen = 0;
11367 if (argvars[0].v_type != VAR_UNKNOWN)
11369 strregname = get_tv_string_chk(&argvars[0]);
11370 if (strregname == NULL) /* type error; errmsg already given */
11372 rettv->v_type = VAR_STRING;
11373 rettv->vval.v_string = NULL;
11374 return;
11377 else
11378 /* Default to v:register */
11379 strregname = vimvars[VV_REG].vv_str;
11381 regname = (strregname == NULL ? '"' : *strregname);
11382 if (regname == 0)
11383 regname = '"';
11385 buf[0] = NUL;
11386 buf[1] = NUL;
11387 switch (get_reg_type(regname, &reglen))
11389 case MLINE: buf[0] = 'V'; break;
11390 case MCHAR: buf[0] = 'v'; break;
11391 #ifdef FEAT_VISUAL
11392 case MBLOCK:
11393 buf[0] = Ctrl_V;
11394 sprintf((char *)buf + 1, "%ld", reglen + 1);
11395 break;
11396 #endif
11398 rettv->v_type = VAR_STRING;
11399 rettv->vval.v_string = vim_strsave(buf);
11403 * "gettabwinvar()" function
11405 static void
11406 f_gettabwinvar(argvars, rettv)
11407 typval_T *argvars;
11408 typval_T *rettv;
11410 getwinvar(argvars, rettv, 1);
11414 * "getwinposx()" function
11416 static void
11417 f_getwinposx(argvars, rettv)
11418 typval_T *argvars UNUSED;
11419 typval_T *rettv;
11421 rettv->vval.v_number = -1;
11422 #ifdef FEAT_GUI
11423 if (gui.in_use)
11425 int x, y;
11427 if (gui_mch_get_winpos(&x, &y) == OK)
11428 rettv->vval.v_number = x;
11430 #endif
11434 * "getwinposy()" function
11436 static void
11437 f_getwinposy(argvars, rettv)
11438 typval_T *argvars UNUSED;
11439 typval_T *rettv;
11441 rettv->vval.v_number = -1;
11442 #ifdef FEAT_GUI
11443 if (gui.in_use)
11445 int x, y;
11447 if (gui_mch_get_winpos(&x, &y) == OK)
11448 rettv->vval.v_number = y;
11450 #endif
11454 * Find window specified by "vp" in tabpage "tp".
11456 static win_T *
11457 find_win_by_nr(vp, tp)
11458 typval_T *vp;
11459 tabpage_T *tp; /* NULL for current tab page */
11461 #ifdef FEAT_WINDOWS
11462 win_T *wp;
11463 #endif
11464 int nr;
11466 nr = get_tv_number_chk(vp, NULL);
11468 #ifdef FEAT_WINDOWS
11469 if (nr < 0)
11470 return NULL;
11471 if (nr == 0)
11472 return curwin;
11474 for (wp = (tp == NULL || tp == curtab) ? firstwin : tp->tp_firstwin;
11475 wp != NULL; wp = wp->w_next)
11476 if (--nr <= 0)
11477 break;
11478 return wp;
11479 #else
11480 if (nr == 0 || nr == 1)
11481 return curwin;
11482 return NULL;
11483 #endif
11487 * "getwinvar()" function
11489 static void
11490 f_getwinvar(argvars, rettv)
11491 typval_T *argvars;
11492 typval_T *rettv;
11494 getwinvar(argvars, rettv, 0);
11498 * getwinvar() and gettabwinvar()
11500 static void
11501 getwinvar(argvars, rettv, off)
11502 typval_T *argvars;
11503 typval_T *rettv;
11504 int off; /* 1 for gettabwinvar() */
11506 win_T *win, *oldcurwin;
11507 char_u *varname;
11508 dictitem_T *v;
11509 tabpage_T *tp;
11511 #ifdef FEAT_WINDOWS
11512 if (off == 1)
11513 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
11514 else
11515 tp = curtab;
11516 #endif
11517 win = find_win_by_nr(&argvars[off], tp);
11518 varname = get_tv_string_chk(&argvars[off + 1]);
11519 ++emsg_off;
11521 rettv->v_type = VAR_STRING;
11522 rettv->vval.v_string = NULL;
11524 if (win != NULL && varname != NULL)
11526 /* Set curwin to be our win, temporarily. Also set curbuf, so
11527 * that we can get buffer-local options. */
11528 oldcurwin = curwin;
11529 curwin = win;
11530 curbuf = win->w_buffer;
11532 if (*varname == '&') /* window-local-option */
11533 get_option_tv(&varname, rettv, 1);
11534 else
11536 if (*varname == NUL)
11537 /* let getwinvar({nr}, "") return the "w:" dictionary. The
11538 * scope prefix before the NUL byte is required by
11539 * find_var_in_ht(). */
11540 varname = (char_u *)"w:" + 2;
11541 /* look up the variable */
11542 v = find_var_in_ht(&win->w_vars.dv_hashtab, varname, FALSE);
11543 if (v != NULL)
11544 copy_tv(&v->di_tv, rettv);
11547 /* restore previous notion of curwin */
11548 curwin = oldcurwin;
11549 curbuf = curwin->w_buffer;
11552 --emsg_off;
11556 * "glob()" function
11558 static void
11559 f_glob(argvars, rettv)
11560 typval_T *argvars;
11561 typval_T *rettv;
11563 int flags = WILD_SILENT|WILD_USE_NL;
11564 expand_T xpc;
11565 int error = FALSE;
11567 /* When the optional second argument is non-zero, don't remove matches
11568 * for 'wildignore' and don't put matches for 'suffixes' at the end. */
11569 if (argvars[1].v_type != VAR_UNKNOWN
11570 && get_tv_number_chk(&argvars[1], &error))
11571 flags |= WILD_KEEP_ALL;
11572 rettv->v_type = VAR_STRING;
11573 if (!error)
11575 ExpandInit(&xpc);
11576 xpc.xp_context = EXPAND_FILES;
11577 rettv->vval.v_string = ExpandOne(&xpc, get_tv_string(&argvars[0]),
11578 NULL, flags, WILD_ALL);
11580 else
11581 rettv->vval.v_string = NULL;
11585 * "globpath()" function
11587 static void
11588 f_globpath(argvars, rettv)
11589 typval_T *argvars;
11590 typval_T *rettv;
11592 int flags = 0;
11593 char_u buf1[NUMBUFLEN];
11594 char_u *file = get_tv_string_buf_chk(&argvars[1], buf1);
11595 int error = FALSE;
11597 /* When the optional second argument is non-zero, don't remove matches
11598 * for 'wildignore' and don't put matches for 'suffixes' at the end. */
11599 if (argvars[2].v_type != VAR_UNKNOWN
11600 && get_tv_number_chk(&argvars[2], &error))
11601 flags |= WILD_KEEP_ALL;
11602 rettv->v_type = VAR_STRING;
11603 if (file == NULL || error)
11604 rettv->vval.v_string = NULL;
11605 else
11606 rettv->vval.v_string = globpath(get_tv_string(&argvars[0]), file,
11607 flags);
11611 * "has()" function
11613 static void
11614 f_has(argvars, rettv)
11615 typval_T *argvars;
11616 typval_T *rettv;
11618 int i;
11619 char_u *name;
11620 int n = FALSE;
11621 static char *(has_list[]) =
11623 #ifdef AMIGA
11624 "amiga",
11625 # ifdef FEAT_ARP
11626 "arp",
11627 # endif
11628 #endif
11629 #ifdef __BEOS__
11630 "beos",
11631 #endif
11632 #ifdef MSDOS
11633 # ifdef DJGPP
11634 "dos32",
11635 # else
11636 "dos16",
11637 # endif
11638 #endif
11639 #ifdef MACOS
11640 "mac",
11641 #endif
11642 #if defined(MACOS_X_UNIX)
11643 "macunix",
11644 #endif
11645 #ifdef OS2
11646 "os2",
11647 #endif
11648 #ifdef __QNX__
11649 "qnx",
11650 #endif
11651 #ifdef RISCOS
11652 "riscos",
11653 #endif
11654 #ifdef UNIX
11655 "unix",
11656 #endif
11657 #ifdef VMS
11658 "vms",
11659 #endif
11660 #ifdef WIN16
11661 "win16",
11662 #endif
11663 #ifdef WIN32
11664 "win32",
11665 #endif
11666 #if defined(UNIX) && (defined(__CYGWIN32__) || defined(__CYGWIN__))
11667 "win32unix",
11668 #endif
11669 #if defined(WIN64) || defined(_WIN64)
11670 "win64",
11671 #endif
11672 #ifdef EBCDIC
11673 "ebcdic",
11674 #endif
11675 #ifndef CASE_INSENSITIVE_FILENAME
11676 "fname_case",
11677 #endif
11678 #ifdef FEAT_ARABIC
11679 "arabic",
11680 #endif
11681 #ifdef FEAT_AUTOCMD
11682 "autocmd",
11683 #endif
11684 #ifdef FEAT_BEVAL
11685 "balloon_eval",
11686 # ifndef FEAT_GUI_W32 /* other GUIs always have multiline balloons */
11687 "balloon_multiline",
11688 # endif
11689 #endif
11690 #if defined(SOME_BUILTIN_TCAPS) || defined(ALL_BUILTIN_TCAPS)
11691 "builtin_terms",
11692 # ifdef ALL_BUILTIN_TCAPS
11693 "all_builtin_terms",
11694 # endif
11695 #endif
11696 #ifdef FEAT_BYTEOFF
11697 "byte_offset",
11698 #endif
11699 #ifdef FEAT_CINDENT
11700 "cindent",
11701 #endif
11702 #ifdef FEAT_CLIENTSERVER
11703 "clientserver",
11704 #endif
11705 #ifdef FEAT_CLIPBOARD
11706 "clipboard",
11707 #endif
11708 #ifdef FEAT_CMDL_COMPL
11709 "cmdline_compl",
11710 #endif
11711 #ifdef FEAT_CMDHIST
11712 "cmdline_hist",
11713 #endif
11714 #ifdef FEAT_COMMENTS
11715 "comments",
11716 #endif
11717 #ifdef FEAT_CRYPT
11718 "cryptv",
11719 #endif
11720 #ifdef FEAT_CSCOPE
11721 "cscope",
11722 #endif
11723 #ifdef CURSOR_SHAPE
11724 "cursorshape",
11725 #endif
11726 #ifdef DEBUG
11727 "debug",
11728 #endif
11729 #ifdef FEAT_CON_DIALOG
11730 "dialog_con",
11731 #endif
11732 #ifdef FEAT_GUI_DIALOG
11733 "dialog_gui",
11734 #endif
11735 #ifdef FEAT_DIFF
11736 "diff",
11737 #endif
11738 #ifdef FEAT_DIGRAPHS
11739 "digraphs",
11740 #endif
11741 #ifdef FEAT_DND
11742 "dnd",
11743 #endif
11744 #ifdef FEAT_EMACS_TAGS
11745 "emacs_tags",
11746 #endif
11747 "eval", /* always present, of course! */
11748 #ifdef FEAT_EX_EXTRA
11749 "ex_extra",
11750 #endif
11751 #ifdef FEAT_SEARCH_EXTRA
11752 "extra_search",
11753 #endif
11754 #ifdef FEAT_FKMAP
11755 "farsi",
11756 #endif
11757 #ifdef FEAT_SEARCHPATH
11758 "file_in_path",
11759 #endif
11760 #if defined(UNIX) && !defined(USE_SYSTEM)
11761 "filterpipe",
11762 #endif
11763 #ifdef FEAT_FIND_ID
11764 "find_in_path",
11765 #endif
11766 #ifdef FEAT_FLOAT
11767 "float",
11768 #endif
11769 #ifdef FEAT_FOLDING
11770 "folding",
11771 #endif
11772 #ifdef FEAT_FOOTER
11773 "footer",
11774 #endif
11775 #if !defined(USE_SYSTEM) && defined(UNIX)
11776 "fork",
11777 #endif
11778 #ifdef FEAT_GETTEXT
11779 "gettext",
11780 #endif
11781 #ifdef FEAT_GUI
11782 "gui",
11783 #endif
11784 #ifdef FEAT_GUI_ATHENA
11785 # ifdef FEAT_GUI_NEXTAW
11786 "gui_neXtaw",
11787 # else
11788 "gui_athena",
11789 # endif
11790 #endif
11791 #ifdef FEAT_GUI_GTK
11792 "gui_gtk",
11793 # ifdef HAVE_GTK2
11794 "gui_gtk2",
11795 # endif
11796 #endif
11797 #ifdef FEAT_GUI_GNOME
11798 "gui_gnome",
11799 #endif
11800 #ifdef FEAT_GUI_MAC
11801 "gui_mac",
11802 #endif
11803 #ifdef FEAT_GUI_MOTIF
11804 "gui_motif",
11805 #endif
11806 #ifdef FEAT_GUI_PHOTON
11807 "gui_photon",
11808 #endif
11809 #ifdef FEAT_GUI_W16
11810 "gui_win16",
11811 #endif
11812 #ifdef FEAT_GUI_W32
11813 "gui_win32",
11814 #endif
11815 #ifdef FEAT_HANGULIN
11816 "hangul_input",
11817 #endif
11818 #if defined(HAVE_ICONV_H) && defined(USE_ICONV)
11819 "iconv",
11820 #endif
11821 #ifdef FEAT_INS_EXPAND
11822 "insert_expand",
11823 #endif
11824 #ifdef FEAT_JUMPLIST
11825 "jumplist",
11826 #endif
11827 #ifdef FEAT_KEYMAP
11828 "keymap",
11829 #endif
11830 #ifdef FEAT_LANGMAP
11831 "langmap",
11832 #endif
11833 #ifdef FEAT_LIBCALL
11834 "libcall",
11835 #endif
11836 #ifdef FEAT_LINEBREAK
11837 "linebreak",
11838 #endif
11839 #ifdef FEAT_LISP
11840 "lispindent",
11841 #endif
11842 #ifdef FEAT_LISTCMDS
11843 "listcmds",
11844 #endif
11845 #ifdef FEAT_LOCALMAP
11846 "localmap",
11847 #endif
11848 #ifdef FEAT_MENU
11849 "menu",
11850 #endif
11851 #ifdef FEAT_SESSION
11852 "mksession",
11853 #endif
11854 #ifdef FEAT_MODIFY_FNAME
11855 "modify_fname",
11856 #endif
11857 #ifdef FEAT_MOUSE
11858 "mouse",
11859 #endif
11860 #ifdef FEAT_MOUSESHAPE
11861 "mouseshape",
11862 #endif
11863 #if defined(UNIX) || defined(VMS)
11864 # ifdef FEAT_MOUSE_DEC
11865 "mouse_dec",
11866 # endif
11867 # ifdef FEAT_MOUSE_GPM
11868 "mouse_gpm",
11869 # endif
11870 # ifdef FEAT_MOUSE_JSB
11871 "mouse_jsbterm",
11872 # endif
11873 # ifdef FEAT_MOUSE_NET
11874 "mouse_netterm",
11875 # endif
11876 # ifdef FEAT_MOUSE_PTERM
11877 "mouse_pterm",
11878 # endif
11879 # ifdef FEAT_SYSMOUSE
11880 "mouse_sysmouse",
11881 # endif
11882 # ifdef FEAT_MOUSE_XTERM
11883 "mouse_xterm",
11884 # endif
11885 #endif
11886 #ifdef FEAT_MBYTE
11887 "multi_byte",
11888 #endif
11889 #ifdef FEAT_MBYTE_IME
11890 "multi_byte_ime",
11891 #endif
11892 #ifdef FEAT_MULTI_LANG
11893 "multi_lang",
11894 #endif
11895 #ifdef FEAT_MZSCHEME
11896 #ifndef DYNAMIC_MZSCHEME
11897 "mzscheme",
11898 #endif
11899 #endif
11900 #ifdef FEAT_OLE
11901 "ole",
11902 #endif
11903 #ifdef FEAT_OSFILETYPE
11904 "osfiletype",
11905 #endif
11906 #ifdef FEAT_PATH_EXTRA
11907 "path_extra",
11908 #endif
11909 #ifdef FEAT_PERL
11910 #ifndef DYNAMIC_PERL
11911 "perl",
11912 #endif
11913 #endif
11914 #ifdef FEAT_PYTHON
11915 #ifndef DYNAMIC_PYTHON
11916 "python",
11917 #endif
11918 #endif
11919 #ifdef FEAT_POSTSCRIPT
11920 "postscript",
11921 #endif
11922 #ifdef FEAT_PRINTER
11923 "printer",
11924 #endif
11925 #ifdef FEAT_PROFILE
11926 "profile",
11927 #endif
11928 #ifdef FEAT_RELTIME
11929 "reltime",
11930 #endif
11931 #ifdef FEAT_QUICKFIX
11932 "quickfix",
11933 #endif
11934 #ifdef FEAT_RIGHTLEFT
11935 "rightleft",
11936 #endif
11937 #if defined(FEAT_RUBY) && !defined(DYNAMIC_RUBY)
11938 "ruby",
11939 #endif
11940 #ifdef FEAT_SCROLLBIND
11941 "scrollbind",
11942 #endif
11943 #ifdef FEAT_CMDL_INFO
11944 "showcmd",
11945 "cmdline_info",
11946 #endif
11947 #ifdef FEAT_SIGNS
11948 "signs",
11949 #endif
11950 #ifdef FEAT_SMARTINDENT
11951 "smartindent",
11952 #endif
11953 #ifdef FEAT_SNIFF
11954 "sniff",
11955 #endif
11956 #ifdef STARTUPTIME
11957 "startuptime",
11958 #endif
11959 #ifdef FEAT_STL_OPT
11960 "statusline",
11961 #endif
11962 #ifdef FEAT_SUN_WORKSHOP
11963 "sun_workshop",
11964 #endif
11965 #ifdef FEAT_NETBEANS_INTG
11966 "netbeans_intg",
11967 #endif
11968 #ifdef FEAT_SPELL
11969 "spell",
11970 #endif
11971 #ifdef FEAT_SYN_HL
11972 "syntax",
11973 #endif
11974 #if defined(USE_SYSTEM) || !defined(UNIX)
11975 "system",
11976 #endif
11977 #ifdef FEAT_TAG_BINS
11978 "tag_binary",
11979 #endif
11980 #ifdef FEAT_TAG_OLDSTATIC
11981 "tag_old_static",
11982 #endif
11983 #ifdef FEAT_TAG_ANYWHITE
11984 "tag_any_white",
11985 #endif
11986 #ifdef FEAT_TCL
11987 # ifndef DYNAMIC_TCL
11988 "tcl",
11989 # endif
11990 #endif
11991 #ifdef TERMINFO
11992 "terminfo",
11993 #endif
11994 #ifdef FEAT_TERMRESPONSE
11995 "termresponse",
11996 #endif
11997 #ifdef FEAT_TEXTOBJ
11998 "textobjects",
11999 #endif
12000 #ifdef HAVE_TGETENT
12001 "tgetent",
12002 #endif
12003 #ifdef FEAT_TITLE
12004 "title",
12005 #endif
12006 #ifdef FEAT_TOOLBAR
12007 "toolbar",
12008 #endif
12009 #ifdef FEAT_USR_CMDS
12010 "user-commands", /* was accidentally included in 5.4 */
12011 "user_commands",
12012 #endif
12013 #ifdef FEAT_VIMINFO
12014 "viminfo",
12015 #endif
12016 #ifdef FEAT_VERTSPLIT
12017 "vertsplit",
12018 #endif
12019 #ifdef FEAT_VIRTUALEDIT
12020 "virtualedit",
12021 #endif
12022 #ifdef FEAT_VISUAL
12023 "visual",
12024 #endif
12025 #ifdef FEAT_VISUALEXTRA
12026 "visualextra",
12027 #endif
12028 #ifdef FEAT_VREPLACE
12029 "vreplace",
12030 #endif
12031 #ifdef FEAT_WILDIGN
12032 "wildignore",
12033 #endif
12034 #ifdef FEAT_WILDMENU
12035 "wildmenu",
12036 #endif
12037 #ifdef FEAT_WINDOWS
12038 "windows",
12039 #endif
12040 #ifdef FEAT_WAK
12041 "winaltkeys",
12042 #endif
12043 #ifdef FEAT_WRITEBACKUP
12044 "writebackup",
12045 #endif
12046 #ifdef FEAT_XIM
12047 "xim",
12048 #endif
12049 #ifdef FEAT_XFONTSET
12050 "xfontset",
12051 #endif
12052 #ifdef USE_XSMP
12053 "xsmp",
12054 #endif
12055 #ifdef USE_XSMP_INTERACT
12056 "xsmp_interact",
12057 #endif
12058 #ifdef FEAT_XCLIPBOARD
12059 "xterm_clipboard",
12060 #endif
12061 #ifdef FEAT_XTERM_SAVE
12062 "xterm_save",
12063 #endif
12064 #if defined(UNIX) && defined(FEAT_X11)
12065 "X11",
12066 #endif
12067 NULL
12070 name = get_tv_string(&argvars[0]);
12071 for (i = 0; has_list[i] != NULL; ++i)
12072 if (STRICMP(name, has_list[i]) == 0)
12074 n = TRUE;
12075 break;
12078 if (n == FALSE)
12080 if (STRNICMP(name, "patch", 5) == 0)
12081 n = has_patch(atoi((char *)name + 5));
12082 else if (STRICMP(name, "vim_starting") == 0)
12083 n = (starting != 0);
12084 #ifdef FEAT_MBYTE
12085 else if (STRICMP(name, "multi_byte_encoding") == 0)
12086 n = has_mbyte;
12087 #endif
12088 #if defined(FEAT_BEVAL) && defined(FEAT_GUI_W32)
12089 else if (STRICMP(name, "balloon_multiline") == 0)
12090 n = multiline_balloon_available();
12091 #endif
12092 #ifdef DYNAMIC_TCL
12093 else if (STRICMP(name, "tcl") == 0)
12094 n = tcl_enabled(FALSE);
12095 #endif
12096 #if defined(USE_ICONV) && defined(DYNAMIC_ICONV)
12097 else if (STRICMP(name, "iconv") == 0)
12098 n = iconv_enabled(FALSE);
12099 #endif
12100 #ifdef DYNAMIC_MZSCHEME
12101 else if (STRICMP(name, "mzscheme") == 0)
12102 n = mzscheme_enabled(FALSE);
12103 #endif
12104 #ifdef DYNAMIC_RUBY
12105 else if (STRICMP(name, "ruby") == 0)
12106 n = ruby_enabled(FALSE);
12107 #endif
12108 #ifdef DYNAMIC_PYTHON
12109 else if (STRICMP(name, "python") == 0)
12110 n = python_enabled(FALSE);
12111 #endif
12112 #ifdef DYNAMIC_PERL
12113 else if (STRICMP(name, "perl") == 0)
12114 n = perl_enabled(FALSE);
12115 #endif
12116 #ifdef FEAT_GUI
12117 else if (STRICMP(name, "gui_running") == 0)
12118 n = (gui.in_use || gui.starting);
12119 # ifdef FEAT_GUI_W32
12120 else if (STRICMP(name, "gui_win32s") == 0)
12121 n = gui_is_win32s();
12122 # endif
12123 # ifdef FEAT_BROWSE
12124 else if (STRICMP(name, "browse") == 0)
12125 n = gui.in_use; /* gui_mch_browse() works when GUI is running */
12126 # endif
12127 #endif
12128 #ifdef FEAT_SYN_HL
12129 else if (STRICMP(name, "syntax_items") == 0)
12130 n = syntax_present(curbuf);
12131 #endif
12132 #if defined(WIN3264)
12133 else if (STRICMP(name, "win95") == 0)
12134 n = mch_windows95();
12135 #endif
12136 #ifdef FEAT_NETBEANS_INTG
12137 else if (STRICMP(name, "netbeans_enabled") == 0)
12138 n = usingNetbeans;
12139 #endif
12142 rettv->vval.v_number = n;
12146 * "has_key()" function
12148 static void
12149 f_has_key(argvars, rettv)
12150 typval_T *argvars;
12151 typval_T *rettv;
12153 if (argvars[0].v_type != VAR_DICT)
12155 EMSG(_(e_dictreq));
12156 return;
12158 if (argvars[0].vval.v_dict == NULL)
12159 return;
12161 rettv->vval.v_number = dict_find(argvars[0].vval.v_dict,
12162 get_tv_string(&argvars[1]), -1) != NULL;
12166 * "haslocaldir()" function
12168 static void
12169 f_haslocaldir(argvars, rettv)
12170 typval_T *argvars UNUSED;
12171 typval_T *rettv;
12173 rettv->vval.v_number = (curwin->w_localdir != NULL);
12177 * "hasmapto()" function
12179 static void
12180 f_hasmapto(argvars, rettv)
12181 typval_T *argvars;
12182 typval_T *rettv;
12184 char_u *name;
12185 char_u *mode;
12186 char_u buf[NUMBUFLEN];
12187 int abbr = FALSE;
12189 name = get_tv_string(&argvars[0]);
12190 if (argvars[1].v_type == VAR_UNKNOWN)
12191 mode = (char_u *)"nvo";
12192 else
12194 mode = get_tv_string_buf(&argvars[1], buf);
12195 if (argvars[2].v_type != VAR_UNKNOWN)
12196 abbr = get_tv_number(&argvars[2]);
12199 if (map_to_exists(name, mode, abbr))
12200 rettv->vval.v_number = TRUE;
12201 else
12202 rettv->vval.v_number = FALSE;
12206 * "histadd()" function
12208 static void
12209 f_histadd(argvars, rettv)
12210 typval_T *argvars UNUSED;
12211 typval_T *rettv;
12213 #ifdef FEAT_CMDHIST
12214 int histype;
12215 char_u *str;
12216 char_u buf[NUMBUFLEN];
12217 #endif
12219 rettv->vval.v_number = FALSE;
12220 if (check_restricted() || check_secure())
12221 return;
12222 #ifdef FEAT_CMDHIST
12223 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
12224 histype = str != NULL ? get_histtype(str) : -1;
12225 if (histype >= 0)
12227 str = get_tv_string_buf(&argvars[1], buf);
12228 if (*str != NUL)
12230 init_history();
12231 add_to_history(histype, str, FALSE, NUL);
12232 rettv->vval.v_number = TRUE;
12233 return;
12236 #endif
12240 * "histdel()" function
12242 static void
12243 f_histdel(argvars, rettv)
12244 typval_T *argvars UNUSED;
12245 typval_T *rettv UNUSED;
12247 #ifdef FEAT_CMDHIST
12248 int n;
12249 char_u buf[NUMBUFLEN];
12250 char_u *str;
12252 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
12253 if (str == NULL)
12254 n = 0;
12255 else if (argvars[1].v_type == VAR_UNKNOWN)
12256 /* only one argument: clear entire history */
12257 n = clr_history(get_histtype(str));
12258 else if (argvars[1].v_type == VAR_NUMBER)
12259 /* index given: remove that entry */
12260 n = del_history_idx(get_histtype(str),
12261 (int)get_tv_number(&argvars[1]));
12262 else
12263 /* string given: remove all matching entries */
12264 n = del_history_entry(get_histtype(str),
12265 get_tv_string_buf(&argvars[1], buf));
12266 rettv->vval.v_number = n;
12267 #endif
12271 * "histget()" function
12273 static void
12274 f_histget(argvars, rettv)
12275 typval_T *argvars UNUSED;
12276 typval_T *rettv;
12278 #ifdef FEAT_CMDHIST
12279 int type;
12280 int idx;
12281 char_u *str;
12283 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
12284 if (str == NULL)
12285 rettv->vval.v_string = NULL;
12286 else
12288 type = get_histtype(str);
12289 if (argvars[1].v_type == VAR_UNKNOWN)
12290 idx = get_history_idx(type);
12291 else
12292 idx = (int)get_tv_number_chk(&argvars[1], NULL);
12293 /* -1 on type error */
12294 rettv->vval.v_string = vim_strsave(get_history_entry(type, idx));
12296 #else
12297 rettv->vval.v_string = NULL;
12298 #endif
12299 rettv->v_type = VAR_STRING;
12303 * "histnr()" function
12305 static void
12306 f_histnr(argvars, rettv)
12307 typval_T *argvars UNUSED;
12308 typval_T *rettv;
12310 int i;
12312 #ifdef FEAT_CMDHIST
12313 char_u *history = get_tv_string_chk(&argvars[0]);
12315 i = history == NULL ? HIST_CMD - 1 : get_histtype(history);
12316 if (i >= HIST_CMD && i < HIST_COUNT)
12317 i = get_history_idx(i);
12318 else
12319 #endif
12320 i = -1;
12321 rettv->vval.v_number = i;
12325 * "highlightID(name)" function
12327 static void
12328 f_hlID(argvars, rettv)
12329 typval_T *argvars;
12330 typval_T *rettv;
12332 rettv->vval.v_number = syn_name2id(get_tv_string(&argvars[0]));
12336 * "highlight_exists()" function
12338 static void
12339 f_hlexists(argvars, rettv)
12340 typval_T *argvars;
12341 typval_T *rettv;
12343 rettv->vval.v_number = highlight_exists(get_tv_string(&argvars[0]));
12347 * "hostname()" function
12349 static void
12350 f_hostname(argvars, rettv)
12351 typval_T *argvars UNUSED;
12352 typval_T *rettv;
12354 char_u hostname[256];
12356 mch_get_host_name(hostname, 256);
12357 rettv->v_type = VAR_STRING;
12358 rettv->vval.v_string = vim_strsave(hostname);
12362 * iconv() function
12364 static void
12365 f_iconv(argvars, rettv)
12366 typval_T *argvars UNUSED;
12367 typval_T *rettv;
12369 #ifdef FEAT_MBYTE
12370 char_u buf1[NUMBUFLEN];
12371 char_u buf2[NUMBUFLEN];
12372 char_u *from, *to, *str;
12373 vimconv_T vimconv;
12374 #endif
12376 rettv->v_type = VAR_STRING;
12377 rettv->vval.v_string = NULL;
12379 #ifdef FEAT_MBYTE
12380 str = get_tv_string(&argvars[0]);
12381 from = enc_canonize(enc_skip(get_tv_string_buf(&argvars[1], buf1)));
12382 to = enc_canonize(enc_skip(get_tv_string_buf(&argvars[2], buf2)));
12383 vimconv.vc_type = CONV_NONE;
12384 convert_setup(&vimconv, from, to);
12386 /* If the encodings are equal, no conversion needed. */
12387 if (vimconv.vc_type == CONV_NONE)
12388 rettv->vval.v_string = vim_strsave(str);
12389 else
12390 rettv->vval.v_string = string_convert(&vimconv, str, NULL);
12392 convert_setup(&vimconv, NULL, NULL);
12393 vim_free(from);
12394 vim_free(to);
12395 #endif
12399 * "indent()" function
12401 static void
12402 f_indent(argvars, rettv)
12403 typval_T *argvars;
12404 typval_T *rettv;
12406 linenr_T lnum;
12408 lnum = get_tv_lnum(argvars);
12409 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
12410 rettv->vval.v_number = get_indent_lnum(lnum);
12411 else
12412 rettv->vval.v_number = -1;
12416 * "index()" function
12418 static void
12419 f_index(argvars, rettv)
12420 typval_T *argvars;
12421 typval_T *rettv;
12423 list_T *l;
12424 listitem_T *item;
12425 long idx = 0;
12426 int ic = FALSE;
12428 rettv->vval.v_number = -1;
12429 if (argvars[0].v_type != VAR_LIST)
12431 EMSG(_(e_listreq));
12432 return;
12434 l = argvars[0].vval.v_list;
12435 if (l != NULL)
12437 item = l->lv_first;
12438 if (argvars[2].v_type != VAR_UNKNOWN)
12440 int error = FALSE;
12442 /* Start at specified item. Use the cached index that list_find()
12443 * sets, so that a negative number also works. */
12444 item = list_find(l, get_tv_number_chk(&argvars[2], &error));
12445 idx = l->lv_idx;
12446 if (argvars[3].v_type != VAR_UNKNOWN)
12447 ic = get_tv_number_chk(&argvars[3], &error);
12448 if (error)
12449 item = NULL;
12452 for ( ; item != NULL; item = item->li_next, ++idx)
12453 if (tv_equal(&item->li_tv, &argvars[1], ic))
12455 rettv->vval.v_number = idx;
12456 break;
12461 static int inputsecret_flag = 0;
12463 static void get_user_input __ARGS((typval_T *argvars, typval_T *rettv, int inputdialog));
12466 * This function is used by f_input() and f_inputdialog() functions. The third
12467 * argument to f_input() specifies the type of completion to use at the
12468 * prompt. The third argument to f_inputdialog() specifies the value to return
12469 * when the user cancels the prompt.
12471 static void
12472 get_user_input(argvars, rettv, inputdialog)
12473 typval_T *argvars;
12474 typval_T *rettv;
12475 int inputdialog;
12477 char_u *prompt = get_tv_string_chk(&argvars[0]);
12478 char_u *p = NULL;
12479 int c;
12480 char_u buf[NUMBUFLEN];
12481 int cmd_silent_save = cmd_silent;
12482 char_u *defstr = (char_u *)"";
12483 int xp_type = EXPAND_NOTHING;
12484 char_u *xp_arg = NULL;
12486 rettv->v_type = VAR_STRING;
12487 rettv->vval.v_string = NULL;
12489 #ifdef NO_CONSOLE_INPUT
12490 /* While starting up, there is no place to enter text. */
12491 if (no_console_input())
12492 return;
12493 #endif
12495 cmd_silent = FALSE; /* Want to see the prompt. */
12496 if (prompt != NULL)
12498 /* Only the part of the message after the last NL is considered as
12499 * prompt for the command line */
12500 p = vim_strrchr(prompt, '\n');
12501 if (p == NULL)
12502 p = prompt;
12503 else
12505 ++p;
12506 c = *p;
12507 *p = NUL;
12508 msg_start();
12509 msg_clr_eos();
12510 msg_puts_attr(prompt, echo_attr);
12511 msg_didout = FALSE;
12512 msg_starthere();
12513 *p = c;
12515 cmdline_row = msg_row;
12517 if (argvars[1].v_type != VAR_UNKNOWN)
12519 defstr = get_tv_string_buf_chk(&argvars[1], buf);
12520 if (defstr != NULL)
12521 stuffReadbuffSpec(defstr);
12523 if (!inputdialog && argvars[2].v_type != VAR_UNKNOWN)
12525 char_u *xp_name;
12526 int xp_namelen;
12527 long argt;
12529 rettv->vval.v_string = NULL;
12531 xp_name = get_tv_string_buf_chk(&argvars[2], buf);
12532 if (xp_name == NULL)
12533 return;
12535 xp_namelen = (int)STRLEN(xp_name);
12537 if (parse_compl_arg(xp_name, xp_namelen, &xp_type, &argt,
12538 &xp_arg) == FAIL)
12539 return;
12543 if (defstr != NULL)
12544 rettv->vval.v_string =
12545 getcmdline_prompt(inputsecret_flag ? NUL : '@', p, echo_attr,
12546 xp_type, xp_arg);
12548 vim_free(xp_arg);
12550 /* since the user typed this, no need to wait for return */
12551 need_wait_return = FALSE;
12552 msg_didout = FALSE;
12554 cmd_silent = cmd_silent_save;
12558 * "input()" function
12559 * Also handles inputsecret() when inputsecret is set.
12561 static void
12562 f_input(argvars, rettv)
12563 typval_T *argvars;
12564 typval_T *rettv;
12566 get_user_input(argvars, rettv, FALSE);
12570 * "inputdialog()" function
12572 static void
12573 f_inputdialog(argvars, rettv)
12574 typval_T *argvars;
12575 typval_T *rettv;
12577 #if defined(FEAT_GUI_TEXTDIALOG)
12578 /* Use a GUI dialog if the GUI is running and 'c' is not in 'guioptions' */
12579 if (gui.in_use && vim_strchr(p_go, GO_CONDIALOG) == NULL)
12581 char_u *message;
12582 char_u buf[NUMBUFLEN];
12583 char_u *defstr = (char_u *)"";
12585 message = get_tv_string_chk(&argvars[0]);
12586 if (argvars[1].v_type != VAR_UNKNOWN
12587 && (defstr = get_tv_string_buf_chk(&argvars[1], buf)) != NULL)
12588 vim_strncpy(IObuff, defstr, IOSIZE - 1);
12589 else
12590 IObuff[0] = NUL;
12591 if (message != NULL && defstr != NULL
12592 && do_dialog(VIM_QUESTION, NULL, message,
12593 (char_u *)_("&OK\n&Cancel"), 1, IObuff) == 1)
12594 rettv->vval.v_string = vim_strsave(IObuff);
12595 else
12597 if (message != NULL && defstr != NULL
12598 && argvars[1].v_type != VAR_UNKNOWN
12599 && argvars[2].v_type != VAR_UNKNOWN)
12600 rettv->vval.v_string = vim_strsave(
12601 get_tv_string_buf(&argvars[2], buf));
12602 else
12603 rettv->vval.v_string = NULL;
12605 rettv->v_type = VAR_STRING;
12607 else
12608 #endif
12609 get_user_input(argvars, rettv, TRUE);
12613 * "inputlist()" function
12615 static void
12616 f_inputlist(argvars, rettv)
12617 typval_T *argvars;
12618 typval_T *rettv;
12620 listitem_T *li;
12621 int selected;
12622 int mouse_used;
12624 #ifdef NO_CONSOLE_INPUT
12625 /* While starting up, there is no place to enter text. */
12626 if (no_console_input())
12627 return;
12628 #endif
12629 if (argvars[0].v_type != VAR_LIST || argvars[0].vval.v_list == NULL)
12631 EMSG2(_(e_listarg), "inputlist()");
12632 return;
12635 msg_start();
12636 msg_row = Rows - 1; /* for when 'cmdheight' > 1 */
12637 lines_left = Rows; /* avoid more prompt */
12638 msg_scroll = TRUE;
12639 msg_clr_eos();
12641 for (li = argvars[0].vval.v_list->lv_first; li != NULL; li = li->li_next)
12643 msg_puts(get_tv_string(&li->li_tv));
12644 msg_putchar('\n');
12647 /* Ask for choice. */
12648 selected = prompt_for_number(&mouse_used);
12649 if (mouse_used)
12650 selected -= lines_left;
12652 rettv->vval.v_number = selected;
12656 static garray_T ga_userinput = {0, 0, sizeof(tasave_T), 4, NULL};
12659 * "inputrestore()" function
12661 static void
12662 f_inputrestore(argvars, rettv)
12663 typval_T *argvars UNUSED;
12664 typval_T *rettv;
12666 if (ga_userinput.ga_len > 0)
12668 --ga_userinput.ga_len;
12669 restore_typeahead((tasave_T *)(ga_userinput.ga_data)
12670 + ga_userinput.ga_len);
12671 /* default return is zero == OK */
12673 else if (p_verbose > 1)
12675 verb_msg((char_u *)_("called inputrestore() more often than inputsave()"));
12676 rettv->vval.v_number = 1; /* Failed */
12681 * "inputsave()" function
12683 static void
12684 f_inputsave(argvars, rettv)
12685 typval_T *argvars UNUSED;
12686 typval_T *rettv;
12688 /* Add an entry to the stack of typeahead storage. */
12689 if (ga_grow(&ga_userinput, 1) == OK)
12691 save_typeahead((tasave_T *)(ga_userinput.ga_data)
12692 + ga_userinput.ga_len);
12693 ++ga_userinput.ga_len;
12694 /* default return is zero == OK */
12696 else
12697 rettv->vval.v_number = 1; /* Failed */
12701 * "inputsecret()" function
12703 static void
12704 f_inputsecret(argvars, rettv)
12705 typval_T *argvars;
12706 typval_T *rettv;
12708 ++cmdline_star;
12709 ++inputsecret_flag;
12710 f_input(argvars, rettv);
12711 --cmdline_star;
12712 --inputsecret_flag;
12716 * "insert()" function
12718 static void
12719 f_insert(argvars, rettv)
12720 typval_T *argvars;
12721 typval_T *rettv;
12723 long before = 0;
12724 listitem_T *item;
12725 list_T *l;
12726 int error = FALSE;
12728 if (argvars[0].v_type != VAR_LIST)
12729 EMSG2(_(e_listarg), "insert()");
12730 else if ((l = argvars[0].vval.v_list) != NULL
12731 && !tv_check_lock(l->lv_lock, (char_u *)"insert()"))
12733 if (argvars[2].v_type != VAR_UNKNOWN)
12734 before = get_tv_number_chk(&argvars[2], &error);
12735 if (error)
12736 return; /* type error; errmsg already given */
12738 if (before == l->lv_len)
12739 item = NULL;
12740 else
12742 item = list_find(l, before);
12743 if (item == NULL)
12745 EMSGN(_(e_listidx), before);
12746 l = NULL;
12749 if (l != NULL)
12751 list_insert_tv(l, &argvars[1], item);
12752 copy_tv(&argvars[0], rettv);
12758 * "isdirectory()" function
12760 static void
12761 f_isdirectory(argvars, rettv)
12762 typval_T *argvars;
12763 typval_T *rettv;
12765 rettv->vval.v_number = mch_isdir(get_tv_string(&argvars[0]));
12769 * "islocked()" function
12771 static void
12772 f_islocked(argvars, rettv)
12773 typval_T *argvars;
12774 typval_T *rettv;
12776 lval_T lv;
12777 char_u *end;
12778 dictitem_T *di;
12780 rettv->vval.v_number = -1;
12781 end = get_lval(get_tv_string(&argvars[0]), NULL, &lv, FALSE, FALSE, FALSE,
12782 FNE_CHECK_START);
12783 if (end != NULL && lv.ll_name != NULL)
12785 if (*end != NUL)
12786 EMSG(_(e_trailing));
12787 else
12789 if (lv.ll_tv == NULL)
12791 if (check_changedtick(lv.ll_name))
12792 rettv->vval.v_number = 1; /* always locked */
12793 else
12795 di = find_var(lv.ll_name, NULL);
12796 if (di != NULL)
12798 /* Consider a variable locked when:
12799 * 1. the variable itself is locked
12800 * 2. the value of the variable is locked.
12801 * 3. the List or Dict value is locked.
12803 rettv->vval.v_number = ((di->di_flags & DI_FLAGS_LOCK)
12804 || tv_islocked(&di->di_tv));
12808 else if (lv.ll_range)
12809 EMSG(_("E786: Range not allowed"));
12810 else if (lv.ll_newkey != NULL)
12811 EMSG2(_(e_dictkey), lv.ll_newkey);
12812 else if (lv.ll_list != NULL)
12813 /* List item. */
12814 rettv->vval.v_number = tv_islocked(&lv.ll_li->li_tv);
12815 else
12816 /* Dictionary item. */
12817 rettv->vval.v_number = tv_islocked(&lv.ll_di->di_tv);
12821 clear_lval(&lv);
12824 static void dict_list __ARGS((typval_T *argvars, typval_T *rettv, int what));
12827 * Turn a dict into a list:
12828 * "what" == 0: list of keys
12829 * "what" == 1: list of values
12830 * "what" == 2: list of items
12832 static void
12833 dict_list(argvars, rettv, what)
12834 typval_T *argvars;
12835 typval_T *rettv;
12836 int what;
12838 list_T *l2;
12839 dictitem_T *di;
12840 hashitem_T *hi;
12841 listitem_T *li;
12842 listitem_T *li2;
12843 dict_T *d;
12844 int todo;
12846 if (argvars[0].v_type != VAR_DICT)
12848 EMSG(_(e_dictreq));
12849 return;
12851 if ((d = argvars[0].vval.v_dict) == NULL)
12852 return;
12854 if (rettv_list_alloc(rettv) == FAIL)
12855 return;
12857 todo = (int)d->dv_hashtab.ht_used;
12858 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
12860 if (!HASHITEM_EMPTY(hi))
12862 --todo;
12863 di = HI2DI(hi);
12865 li = listitem_alloc();
12866 if (li == NULL)
12867 break;
12868 list_append(rettv->vval.v_list, li);
12870 if (what == 0)
12872 /* keys() */
12873 li->li_tv.v_type = VAR_STRING;
12874 li->li_tv.v_lock = 0;
12875 li->li_tv.vval.v_string = vim_strsave(di->di_key);
12877 else if (what == 1)
12879 /* values() */
12880 copy_tv(&di->di_tv, &li->li_tv);
12882 else
12884 /* items() */
12885 l2 = list_alloc();
12886 li->li_tv.v_type = VAR_LIST;
12887 li->li_tv.v_lock = 0;
12888 li->li_tv.vval.v_list = l2;
12889 if (l2 == NULL)
12890 break;
12891 ++l2->lv_refcount;
12893 li2 = listitem_alloc();
12894 if (li2 == NULL)
12895 break;
12896 list_append(l2, li2);
12897 li2->li_tv.v_type = VAR_STRING;
12898 li2->li_tv.v_lock = 0;
12899 li2->li_tv.vval.v_string = vim_strsave(di->di_key);
12901 li2 = listitem_alloc();
12902 if (li2 == NULL)
12903 break;
12904 list_append(l2, li2);
12905 copy_tv(&di->di_tv, &li2->li_tv);
12912 * "items(dict)" function
12914 static void
12915 f_items(argvars, rettv)
12916 typval_T *argvars;
12917 typval_T *rettv;
12919 dict_list(argvars, rettv, 2);
12923 * "join()" function
12925 static void
12926 f_join(argvars, rettv)
12927 typval_T *argvars;
12928 typval_T *rettv;
12930 garray_T ga;
12931 char_u *sep;
12933 if (argvars[0].v_type != VAR_LIST)
12935 EMSG(_(e_listreq));
12936 return;
12938 if (argvars[0].vval.v_list == NULL)
12939 return;
12940 if (argvars[1].v_type == VAR_UNKNOWN)
12941 sep = (char_u *)" ";
12942 else
12943 sep = get_tv_string_chk(&argvars[1]);
12945 rettv->v_type = VAR_STRING;
12947 if (sep != NULL)
12949 ga_init2(&ga, (int)sizeof(char), 80);
12950 list_join(&ga, argvars[0].vval.v_list, sep, TRUE, 0);
12951 ga_append(&ga, NUL);
12952 rettv->vval.v_string = (char_u *)ga.ga_data;
12954 else
12955 rettv->vval.v_string = NULL;
12959 * "keys()" function
12961 static void
12962 f_keys(argvars, rettv)
12963 typval_T *argvars;
12964 typval_T *rettv;
12966 dict_list(argvars, rettv, 0);
12970 * "last_buffer_nr()" function.
12972 static void
12973 f_last_buffer_nr(argvars, rettv)
12974 typval_T *argvars UNUSED;
12975 typval_T *rettv;
12977 int n = 0;
12978 buf_T *buf;
12980 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
12981 if (n < buf->b_fnum)
12982 n = buf->b_fnum;
12984 rettv->vval.v_number = n;
12988 * "len()" function
12990 static void
12991 f_len(argvars, rettv)
12992 typval_T *argvars;
12993 typval_T *rettv;
12995 switch (argvars[0].v_type)
12997 case VAR_STRING:
12998 case VAR_NUMBER:
12999 rettv->vval.v_number = (varnumber_T)STRLEN(
13000 get_tv_string(&argvars[0]));
13001 break;
13002 case VAR_LIST:
13003 rettv->vval.v_number = list_len(argvars[0].vval.v_list);
13004 break;
13005 case VAR_DICT:
13006 rettv->vval.v_number = dict_len(argvars[0].vval.v_dict);
13007 break;
13008 default:
13009 EMSG(_("E701: Invalid type for len()"));
13010 break;
13014 static void libcall_common __ARGS((typval_T *argvars, typval_T *rettv, int type));
13016 static void
13017 libcall_common(argvars, rettv, type)
13018 typval_T *argvars;
13019 typval_T *rettv;
13020 int type;
13022 #ifdef FEAT_LIBCALL
13023 char_u *string_in;
13024 char_u **string_result;
13025 int nr_result;
13026 #endif
13028 rettv->v_type = type;
13029 if (type != VAR_NUMBER)
13030 rettv->vval.v_string = NULL;
13032 if (check_restricted() || check_secure())
13033 return;
13035 #ifdef FEAT_LIBCALL
13036 /* The first two args must be strings, otherwise its meaningless */
13037 if (argvars[0].v_type == VAR_STRING && argvars[1].v_type == VAR_STRING)
13039 string_in = NULL;
13040 if (argvars[2].v_type == VAR_STRING)
13041 string_in = argvars[2].vval.v_string;
13042 if (type == VAR_NUMBER)
13043 string_result = NULL;
13044 else
13045 string_result = &rettv->vval.v_string;
13046 if (mch_libcall(argvars[0].vval.v_string,
13047 argvars[1].vval.v_string,
13048 string_in,
13049 argvars[2].vval.v_number,
13050 string_result,
13051 &nr_result) == OK
13052 && type == VAR_NUMBER)
13053 rettv->vval.v_number = nr_result;
13055 #endif
13059 * "libcall()" function
13061 static void
13062 f_libcall(argvars, rettv)
13063 typval_T *argvars;
13064 typval_T *rettv;
13066 libcall_common(argvars, rettv, VAR_STRING);
13070 * "libcallnr()" function
13072 static void
13073 f_libcallnr(argvars, rettv)
13074 typval_T *argvars;
13075 typval_T *rettv;
13077 libcall_common(argvars, rettv, VAR_NUMBER);
13081 * "line(string)" function
13083 static void
13084 f_line(argvars, rettv)
13085 typval_T *argvars;
13086 typval_T *rettv;
13088 linenr_T lnum = 0;
13089 pos_T *fp;
13090 int fnum;
13092 fp = var2fpos(&argvars[0], TRUE, &fnum);
13093 if (fp != NULL)
13094 lnum = fp->lnum;
13095 rettv->vval.v_number = lnum;
13099 * "line2byte(lnum)" function
13101 static void
13102 f_line2byte(argvars, rettv)
13103 typval_T *argvars UNUSED;
13104 typval_T *rettv;
13106 #ifndef FEAT_BYTEOFF
13107 rettv->vval.v_number = -1;
13108 #else
13109 linenr_T lnum;
13111 lnum = get_tv_lnum(argvars);
13112 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
13113 rettv->vval.v_number = -1;
13114 else
13115 rettv->vval.v_number = ml_find_line_or_offset(curbuf, lnum, NULL);
13116 if (rettv->vval.v_number >= 0)
13117 ++rettv->vval.v_number;
13118 #endif
13122 * "lispindent(lnum)" function
13124 static void
13125 f_lispindent(argvars, rettv)
13126 typval_T *argvars;
13127 typval_T *rettv;
13129 #ifdef FEAT_LISP
13130 pos_T pos;
13131 linenr_T lnum;
13133 pos = curwin->w_cursor;
13134 lnum = get_tv_lnum(argvars);
13135 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
13137 curwin->w_cursor.lnum = lnum;
13138 rettv->vval.v_number = get_lisp_indent();
13139 curwin->w_cursor = pos;
13141 else
13142 #endif
13143 rettv->vval.v_number = -1;
13147 * "localtime()" function
13149 static void
13150 f_localtime(argvars, rettv)
13151 typval_T *argvars UNUSED;
13152 typval_T *rettv;
13154 rettv->vval.v_number = (varnumber_T)time(NULL);
13157 static void get_maparg __ARGS((typval_T *argvars, typval_T *rettv, int exact));
13159 static void
13160 get_maparg(argvars, rettv, exact)
13161 typval_T *argvars;
13162 typval_T *rettv;
13163 int exact;
13165 char_u *keys;
13166 char_u *which;
13167 char_u buf[NUMBUFLEN];
13168 char_u *keys_buf = NULL;
13169 char_u *rhs;
13170 int mode;
13171 garray_T ga;
13172 int abbr = FALSE;
13174 /* return empty string for failure */
13175 rettv->v_type = VAR_STRING;
13176 rettv->vval.v_string = NULL;
13178 keys = get_tv_string(&argvars[0]);
13179 if (*keys == NUL)
13180 return;
13182 if (argvars[1].v_type != VAR_UNKNOWN)
13184 which = get_tv_string_buf_chk(&argvars[1], buf);
13185 if (argvars[2].v_type != VAR_UNKNOWN)
13186 abbr = get_tv_number(&argvars[2]);
13188 else
13189 which = (char_u *)"";
13190 if (which == NULL)
13191 return;
13193 mode = get_map_mode(&which, 0);
13195 keys = replace_termcodes(keys, &keys_buf, TRUE, TRUE, FALSE);
13196 rhs = check_map(keys, mode, exact, FALSE, abbr);
13197 vim_free(keys_buf);
13198 if (rhs != NULL)
13200 ga_init(&ga);
13201 ga.ga_itemsize = 1;
13202 ga.ga_growsize = 40;
13204 while (*rhs != NUL)
13205 ga_concat(&ga, str2special(&rhs, FALSE));
13207 ga_append(&ga, NUL);
13208 rettv->vval.v_string = (char_u *)ga.ga_data;
13212 #ifdef FEAT_FLOAT
13214 * "log10()" function
13216 static void
13217 f_log10(argvars, rettv)
13218 typval_T *argvars;
13219 typval_T *rettv;
13221 float_T f;
13223 rettv->v_type = VAR_FLOAT;
13224 if (get_float_arg(argvars, &f) == OK)
13225 rettv->vval.v_float = log10(f);
13226 else
13227 rettv->vval.v_float = 0.0;
13229 #endif
13232 * "map()" function
13234 static void
13235 f_map(argvars, rettv)
13236 typval_T *argvars;
13237 typval_T *rettv;
13239 filter_map(argvars, rettv, TRUE);
13243 * "maparg()" function
13245 static void
13246 f_maparg(argvars, rettv)
13247 typval_T *argvars;
13248 typval_T *rettv;
13250 get_maparg(argvars, rettv, TRUE);
13254 * "mapcheck()" function
13256 static void
13257 f_mapcheck(argvars, rettv)
13258 typval_T *argvars;
13259 typval_T *rettv;
13261 get_maparg(argvars, rettv, FALSE);
13264 static void find_some_match __ARGS((typval_T *argvars, typval_T *rettv, int start));
13266 static void
13267 find_some_match(argvars, rettv, type)
13268 typval_T *argvars;
13269 typval_T *rettv;
13270 int type;
13272 char_u *str = NULL;
13273 char_u *expr = NULL;
13274 char_u *pat;
13275 regmatch_T regmatch;
13276 char_u patbuf[NUMBUFLEN];
13277 char_u strbuf[NUMBUFLEN];
13278 char_u *save_cpo;
13279 long start = 0;
13280 long nth = 1;
13281 colnr_T startcol = 0;
13282 int match = 0;
13283 list_T *l = NULL;
13284 listitem_T *li = NULL;
13285 long idx = 0;
13286 char_u *tofree = NULL;
13288 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
13289 save_cpo = p_cpo;
13290 p_cpo = (char_u *)"";
13292 rettv->vval.v_number = -1;
13293 if (type == 3)
13295 /* return empty list when there are no matches */
13296 if (rettv_list_alloc(rettv) == FAIL)
13297 goto theend;
13299 else if (type == 2)
13301 rettv->v_type = VAR_STRING;
13302 rettv->vval.v_string = NULL;
13305 if (argvars[0].v_type == VAR_LIST)
13307 if ((l = argvars[0].vval.v_list) == NULL)
13308 goto theend;
13309 li = l->lv_first;
13311 else
13312 expr = str = get_tv_string(&argvars[0]);
13314 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
13315 if (pat == NULL)
13316 goto theend;
13318 if (argvars[2].v_type != VAR_UNKNOWN)
13320 int error = FALSE;
13322 start = get_tv_number_chk(&argvars[2], &error);
13323 if (error)
13324 goto theend;
13325 if (l != NULL)
13327 li = list_find(l, start);
13328 if (li == NULL)
13329 goto theend;
13330 idx = l->lv_idx; /* use the cached index */
13332 else
13334 if (start < 0)
13335 start = 0;
13336 if (start > (long)STRLEN(str))
13337 goto theend;
13338 /* When "count" argument is there ignore matches before "start",
13339 * otherwise skip part of the string. Differs when pattern is "^"
13340 * or "\<". */
13341 if (argvars[3].v_type != VAR_UNKNOWN)
13342 startcol = start;
13343 else
13344 str += start;
13347 if (argvars[3].v_type != VAR_UNKNOWN)
13348 nth = get_tv_number_chk(&argvars[3], &error);
13349 if (error)
13350 goto theend;
13353 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
13354 if (regmatch.regprog != NULL)
13356 regmatch.rm_ic = p_ic;
13358 for (;;)
13360 if (l != NULL)
13362 if (li == NULL)
13364 match = FALSE;
13365 break;
13367 vim_free(tofree);
13368 str = echo_string(&li->li_tv, &tofree, strbuf, 0);
13369 if (str == NULL)
13370 break;
13373 match = vim_regexec_nl(&regmatch, str, (colnr_T)startcol);
13375 if (match && --nth <= 0)
13376 break;
13377 if (l == NULL && !match)
13378 break;
13380 /* Advance to just after the match. */
13381 if (l != NULL)
13383 li = li->li_next;
13384 ++idx;
13386 else
13388 #ifdef FEAT_MBYTE
13389 startcol = (colnr_T)(regmatch.startp[0]
13390 + (*mb_ptr2len)(regmatch.startp[0]) - str);
13391 #else
13392 startcol = regmatch.startp[0] + 1 - str;
13393 #endif
13397 if (match)
13399 if (type == 3)
13401 int i;
13403 /* return list with matched string and submatches */
13404 for (i = 0; i < NSUBEXP; ++i)
13406 if (regmatch.endp[i] == NULL)
13408 if (list_append_string(rettv->vval.v_list,
13409 (char_u *)"", 0) == FAIL)
13410 break;
13412 else if (list_append_string(rettv->vval.v_list,
13413 regmatch.startp[i],
13414 (int)(regmatch.endp[i] - regmatch.startp[i]))
13415 == FAIL)
13416 break;
13419 else if (type == 2)
13421 /* return matched string */
13422 if (l != NULL)
13423 copy_tv(&li->li_tv, rettv);
13424 else
13425 rettv->vval.v_string = vim_strnsave(regmatch.startp[0],
13426 (int)(regmatch.endp[0] - regmatch.startp[0]));
13428 else if (l != NULL)
13429 rettv->vval.v_number = idx;
13430 else
13432 if (type != 0)
13433 rettv->vval.v_number =
13434 (varnumber_T)(regmatch.startp[0] - str);
13435 else
13436 rettv->vval.v_number =
13437 (varnumber_T)(regmatch.endp[0] - str);
13438 rettv->vval.v_number += (varnumber_T)(str - expr);
13441 vim_free(regmatch.regprog);
13444 theend:
13445 vim_free(tofree);
13446 p_cpo = save_cpo;
13450 * "match()" function
13452 static void
13453 f_match(argvars, rettv)
13454 typval_T *argvars;
13455 typval_T *rettv;
13457 find_some_match(argvars, rettv, 1);
13461 * "matchadd()" function
13463 static void
13464 f_matchadd(argvars, rettv)
13465 typval_T *argvars;
13466 typval_T *rettv;
13468 #ifdef FEAT_SEARCH_EXTRA
13469 char_u buf[NUMBUFLEN];
13470 char_u *grp = get_tv_string_buf_chk(&argvars[0], buf); /* group */
13471 char_u *pat = get_tv_string_buf_chk(&argvars[1], buf); /* pattern */
13472 int prio = 10; /* default priority */
13473 int id = -1;
13474 int error = FALSE;
13476 rettv->vval.v_number = -1;
13478 if (grp == NULL || pat == NULL)
13479 return;
13480 if (argvars[2].v_type != VAR_UNKNOWN)
13482 prio = get_tv_number_chk(&argvars[2], &error);
13483 if (argvars[3].v_type != VAR_UNKNOWN)
13484 id = get_tv_number_chk(&argvars[3], &error);
13486 if (error == TRUE)
13487 return;
13488 if (id >= 1 && id <= 3)
13490 EMSGN("E798: ID is reserved for \":match\": %ld", id);
13491 return;
13494 rettv->vval.v_number = match_add(curwin, grp, pat, prio, id);
13495 #endif
13499 * "matcharg()" function
13501 static void
13502 f_matcharg(argvars, rettv)
13503 typval_T *argvars;
13504 typval_T *rettv;
13506 if (rettv_list_alloc(rettv) == OK)
13508 #ifdef FEAT_SEARCH_EXTRA
13509 int id = get_tv_number(&argvars[0]);
13510 matchitem_T *m;
13512 if (id >= 1 && id <= 3)
13514 if ((m = (matchitem_T *)get_match(curwin, id)) != NULL)
13516 list_append_string(rettv->vval.v_list,
13517 syn_id2name(m->hlg_id), -1);
13518 list_append_string(rettv->vval.v_list, m->pattern, -1);
13520 else
13522 list_append_string(rettv->vval.v_list, NUL, -1);
13523 list_append_string(rettv->vval.v_list, NUL, -1);
13526 #endif
13531 * "matchdelete()" function
13533 static void
13534 f_matchdelete(argvars, rettv)
13535 typval_T *argvars;
13536 typval_T *rettv;
13538 #ifdef FEAT_SEARCH_EXTRA
13539 rettv->vval.v_number = match_delete(curwin,
13540 (int)get_tv_number(&argvars[0]), TRUE);
13541 #endif
13545 * "matchend()" function
13547 static void
13548 f_matchend(argvars, rettv)
13549 typval_T *argvars;
13550 typval_T *rettv;
13552 find_some_match(argvars, rettv, 0);
13556 * "matchlist()" function
13558 static void
13559 f_matchlist(argvars, rettv)
13560 typval_T *argvars;
13561 typval_T *rettv;
13563 find_some_match(argvars, rettv, 3);
13567 * "matchstr()" function
13569 static void
13570 f_matchstr(argvars, rettv)
13571 typval_T *argvars;
13572 typval_T *rettv;
13574 find_some_match(argvars, rettv, 2);
13577 static void max_min __ARGS((typval_T *argvars, typval_T *rettv, int domax));
13579 static void
13580 max_min(argvars, rettv, domax)
13581 typval_T *argvars;
13582 typval_T *rettv;
13583 int domax;
13585 long n = 0;
13586 long i;
13587 int error = FALSE;
13589 if (argvars[0].v_type == VAR_LIST)
13591 list_T *l;
13592 listitem_T *li;
13594 l = argvars[0].vval.v_list;
13595 if (l != NULL)
13597 li = l->lv_first;
13598 if (li != NULL)
13600 n = get_tv_number_chk(&li->li_tv, &error);
13601 for (;;)
13603 li = li->li_next;
13604 if (li == NULL)
13605 break;
13606 i = get_tv_number_chk(&li->li_tv, &error);
13607 if (domax ? i > n : i < n)
13608 n = i;
13613 else if (argvars[0].v_type == VAR_DICT)
13615 dict_T *d;
13616 int first = TRUE;
13617 hashitem_T *hi;
13618 int todo;
13620 d = argvars[0].vval.v_dict;
13621 if (d != NULL)
13623 todo = (int)d->dv_hashtab.ht_used;
13624 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
13626 if (!HASHITEM_EMPTY(hi))
13628 --todo;
13629 i = get_tv_number_chk(&HI2DI(hi)->di_tv, &error);
13630 if (first)
13632 n = i;
13633 first = FALSE;
13635 else if (domax ? i > n : i < n)
13636 n = i;
13641 else
13642 EMSG(_(e_listdictarg));
13643 rettv->vval.v_number = error ? 0 : n;
13647 * "max()" function
13649 static void
13650 f_max(argvars, rettv)
13651 typval_T *argvars;
13652 typval_T *rettv;
13654 max_min(argvars, rettv, TRUE);
13658 * "min()" function
13660 static void
13661 f_min(argvars, rettv)
13662 typval_T *argvars;
13663 typval_T *rettv;
13665 max_min(argvars, rettv, FALSE);
13668 static int mkdir_recurse __ARGS((char_u *dir, int prot));
13671 * Create the directory in which "dir" is located, and higher levels when
13672 * needed.
13674 static int
13675 mkdir_recurse(dir, prot)
13676 char_u *dir;
13677 int prot;
13679 char_u *p;
13680 char_u *updir;
13681 int r = FAIL;
13683 /* Get end of directory name in "dir".
13684 * We're done when it's "/" or "c:/". */
13685 p = gettail_sep(dir);
13686 if (p <= get_past_head(dir))
13687 return OK;
13689 /* If the directory exists we're done. Otherwise: create it.*/
13690 updir = vim_strnsave(dir, (int)(p - dir));
13691 if (updir == NULL)
13692 return FAIL;
13693 if (mch_isdir(updir))
13694 r = OK;
13695 else if (mkdir_recurse(updir, prot) == OK)
13696 r = vim_mkdir_emsg(updir, prot);
13697 vim_free(updir);
13698 return r;
13701 #ifdef vim_mkdir
13703 * "mkdir()" function
13705 static void
13706 f_mkdir(argvars, rettv)
13707 typval_T *argvars;
13708 typval_T *rettv;
13710 char_u *dir;
13711 char_u buf[NUMBUFLEN];
13712 int prot = 0755;
13714 rettv->vval.v_number = FAIL;
13715 if (check_restricted() || check_secure())
13716 return;
13718 dir = get_tv_string_buf(&argvars[0], buf);
13719 if (argvars[1].v_type != VAR_UNKNOWN)
13721 if (argvars[2].v_type != VAR_UNKNOWN)
13722 prot = get_tv_number_chk(&argvars[2], NULL);
13723 if (prot != -1 && STRCMP(get_tv_string(&argvars[1]), "p") == 0)
13724 mkdir_recurse(dir, prot);
13726 rettv->vval.v_number = prot != -1 ? vim_mkdir_emsg(dir, prot) : 0;
13728 #endif
13731 * "mode()" function
13733 static void
13734 f_mode(argvars, rettv)
13735 typval_T *argvars;
13736 typval_T *rettv;
13738 char_u buf[3];
13740 buf[1] = NUL;
13741 buf[2] = NUL;
13743 #ifdef FEAT_VISUAL
13744 if (VIsual_active)
13746 if (VIsual_select)
13747 buf[0] = VIsual_mode + 's' - 'v';
13748 else
13749 buf[0] = VIsual_mode;
13751 else
13752 #endif
13753 if (State == HITRETURN || State == ASKMORE || State == SETWSIZE
13754 || State == CONFIRM)
13756 buf[0] = 'r';
13757 if (State == ASKMORE)
13758 buf[1] = 'm';
13759 else if (State == CONFIRM)
13760 buf[1] = '?';
13762 else if (State == EXTERNCMD)
13763 buf[0] = '!';
13764 else if (State & INSERT)
13766 #ifdef FEAT_VREPLACE
13767 if (State & VREPLACE_FLAG)
13769 buf[0] = 'R';
13770 buf[1] = 'v';
13772 else
13773 #endif
13774 if (State & REPLACE_FLAG)
13775 buf[0] = 'R';
13776 else
13777 buf[0] = 'i';
13779 else if (State & CMDLINE)
13781 buf[0] = 'c';
13782 if (exmode_active)
13783 buf[1] = 'v';
13785 else if (exmode_active)
13787 buf[0] = 'c';
13788 buf[1] = 'e';
13790 else
13792 buf[0] = 'n';
13793 if (finish_op)
13794 buf[1] = 'o';
13797 /* Clear out the minor mode when the argument is not a non-zero number or
13798 * non-empty string. */
13799 if (!non_zero_arg(&argvars[0]))
13800 buf[1] = NUL;
13802 rettv->vval.v_string = vim_strsave(buf);
13803 rettv->v_type = VAR_STRING;
13806 #ifdef FEAT_MZSCHEME
13808 * "mzeval()" function
13810 static void
13811 f_mzeval(argvars, rettv)
13812 typval_T *argvars;
13813 typval_T *rettv;
13815 char_u *str;
13816 char_u buf[NUMBUFLEN];
13818 str = get_tv_string_buf(&argvars[0], buf);
13819 do_mzeval(str, rettv);
13821 #endif
13824 * "nextnonblank()" function
13826 static void
13827 f_nextnonblank(argvars, rettv)
13828 typval_T *argvars;
13829 typval_T *rettv;
13831 linenr_T lnum;
13833 for (lnum = get_tv_lnum(argvars); ; ++lnum)
13835 if (lnum < 0 || lnum > curbuf->b_ml.ml_line_count)
13837 lnum = 0;
13838 break;
13840 if (*skipwhite(ml_get(lnum)) != NUL)
13841 break;
13843 rettv->vval.v_number = lnum;
13847 * "nr2char()" function
13849 static void
13850 f_nr2char(argvars, rettv)
13851 typval_T *argvars;
13852 typval_T *rettv;
13854 char_u buf[NUMBUFLEN];
13856 #ifdef FEAT_MBYTE
13857 if (has_mbyte)
13858 buf[(*mb_char2bytes)((int)get_tv_number(&argvars[0]), buf)] = NUL;
13859 else
13860 #endif
13862 buf[0] = (char_u)get_tv_number(&argvars[0]);
13863 buf[1] = NUL;
13865 rettv->v_type = VAR_STRING;
13866 rettv->vval.v_string = vim_strsave(buf);
13870 * "pathshorten()" function
13872 static void
13873 f_pathshorten(argvars, rettv)
13874 typval_T *argvars;
13875 typval_T *rettv;
13877 char_u *p;
13879 rettv->v_type = VAR_STRING;
13880 p = get_tv_string_chk(&argvars[0]);
13881 if (p == NULL)
13882 rettv->vval.v_string = NULL;
13883 else
13885 p = vim_strsave(p);
13886 rettv->vval.v_string = p;
13887 if (p != NULL)
13888 shorten_dir(p);
13892 #ifdef FEAT_FLOAT
13894 * "pow()" function
13896 static void
13897 f_pow(argvars, rettv)
13898 typval_T *argvars;
13899 typval_T *rettv;
13901 float_T fx, fy;
13903 rettv->v_type = VAR_FLOAT;
13904 if (get_float_arg(argvars, &fx) == OK
13905 && get_float_arg(&argvars[1], &fy) == OK)
13906 rettv->vval.v_float = pow(fx, fy);
13907 else
13908 rettv->vval.v_float = 0.0;
13910 #endif
13913 * "prevnonblank()" function
13915 static void
13916 f_prevnonblank(argvars, rettv)
13917 typval_T *argvars;
13918 typval_T *rettv;
13920 linenr_T lnum;
13922 lnum = get_tv_lnum(argvars);
13923 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
13924 lnum = 0;
13925 else
13926 while (lnum >= 1 && *skipwhite(ml_get(lnum)) == NUL)
13927 --lnum;
13928 rettv->vval.v_number = lnum;
13931 #ifdef HAVE_STDARG_H
13932 /* This dummy va_list is here because:
13933 * - passing a NULL pointer doesn't work when va_list isn't a pointer
13934 * - locally in the function results in a "used before set" warning
13935 * - using va_start() to initialize it gives "function with fixed args" error */
13936 static va_list ap;
13937 #endif
13940 * "printf()" function
13942 static void
13943 f_printf(argvars, rettv)
13944 typval_T *argvars;
13945 typval_T *rettv;
13947 rettv->v_type = VAR_STRING;
13948 rettv->vval.v_string = NULL;
13949 #ifdef HAVE_STDARG_H /* only very old compilers can't do this */
13951 char_u buf[NUMBUFLEN];
13952 int len;
13953 char_u *s;
13954 int saved_did_emsg = did_emsg;
13955 char *fmt;
13957 /* Get the required length, allocate the buffer and do it for real. */
13958 did_emsg = FALSE;
13959 fmt = (char *)get_tv_string_buf(&argvars[0], buf);
13960 len = vim_vsnprintf(NULL, 0, fmt, ap, argvars + 1);
13961 if (!did_emsg)
13963 s = alloc(len + 1);
13964 if (s != NULL)
13966 rettv->vval.v_string = s;
13967 (void)vim_vsnprintf((char *)s, len + 1, fmt, ap, argvars + 1);
13970 did_emsg |= saved_did_emsg;
13972 #endif
13976 * "pumvisible()" function
13978 static void
13979 f_pumvisible(argvars, rettv)
13980 typval_T *argvars UNUSED;
13981 typval_T *rettv UNUSED;
13983 #ifdef FEAT_INS_EXPAND
13984 if (pum_visible())
13985 rettv->vval.v_number = 1;
13986 #endif
13990 * "range()" function
13992 static void
13993 f_range(argvars, rettv)
13994 typval_T *argvars;
13995 typval_T *rettv;
13997 long start;
13998 long end;
13999 long stride = 1;
14000 long i;
14001 int error = FALSE;
14003 start = get_tv_number_chk(&argvars[0], &error);
14004 if (argvars[1].v_type == VAR_UNKNOWN)
14006 end = start - 1;
14007 start = 0;
14009 else
14011 end = get_tv_number_chk(&argvars[1], &error);
14012 if (argvars[2].v_type != VAR_UNKNOWN)
14013 stride = get_tv_number_chk(&argvars[2], &error);
14016 if (error)
14017 return; /* type error; errmsg already given */
14018 if (stride == 0)
14019 EMSG(_("E726: Stride is zero"));
14020 else if (stride > 0 ? end + 1 < start : end - 1 > start)
14021 EMSG(_("E727: Start past end"));
14022 else
14024 if (rettv_list_alloc(rettv) == OK)
14025 for (i = start; stride > 0 ? i <= end : i >= end; i += stride)
14026 if (list_append_number(rettv->vval.v_list,
14027 (varnumber_T)i) == FAIL)
14028 break;
14033 * "readfile()" function
14035 static void
14036 f_readfile(argvars, rettv)
14037 typval_T *argvars;
14038 typval_T *rettv;
14040 int binary = FALSE;
14041 char_u *fname;
14042 FILE *fd;
14043 listitem_T *li;
14044 #define FREAD_SIZE 200 /* optimized for text lines */
14045 char_u buf[FREAD_SIZE];
14046 int readlen; /* size of last fread() */
14047 int buflen; /* nr of valid chars in buf[] */
14048 int filtd; /* how much in buf[] was NUL -> '\n' filtered */
14049 int tolist; /* first byte in buf[] still to be put in list */
14050 int chop; /* how many CR to chop off */
14051 char_u *prev = NULL; /* previously read bytes, if any */
14052 int prevlen = 0; /* length of "prev" if not NULL */
14053 char_u *s;
14054 int len;
14055 long maxline = MAXLNUM;
14056 long cnt = 0;
14058 if (argvars[1].v_type != VAR_UNKNOWN)
14060 if (STRCMP(get_tv_string(&argvars[1]), "b") == 0)
14061 binary = TRUE;
14062 if (argvars[2].v_type != VAR_UNKNOWN)
14063 maxline = get_tv_number(&argvars[2]);
14066 if (rettv_list_alloc(rettv) == FAIL)
14067 return;
14069 /* Always open the file in binary mode, library functions have a mind of
14070 * their own about CR-LF conversion. */
14071 fname = get_tv_string(&argvars[0]);
14072 if (*fname == NUL || (fd = mch_fopen((char *)fname, READBIN)) == NULL)
14074 EMSG2(_(e_notopen), *fname == NUL ? (char_u *)_("<empty>") : fname);
14075 return;
14078 filtd = 0;
14079 while (cnt < maxline || maxline < 0)
14081 readlen = (int)fread(buf + filtd, 1, FREAD_SIZE - filtd, fd);
14082 buflen = filtd + readlen;
14083 tolist = 0;
14084 for ( ; filtd < buflen || readlen <= 0; ++filtd)
14086 if (buf[filtd] == '\n' || readlen <= 0)
14088 /* Only when in binary mode add an empty list item when the
14089 * last line ends in a '\n'. */
14090 if (!binary && readlen == 0 && filtd == 0)
14091 break;
14093 /* Found end-of-line or end-of-file: add a text line to the
14094 * list. */
14095 chop = 0;
14096 if (!binary)
14097 while (filtd - chop - 1 >= tolist
14098 && buf[filtd - chop - 1] == '\r')
14099 ++chop;
14100 len = filtd - tolist - chop;
14101 if (prev == NULL)
14102 s = vim_strnsave(buf + tolist, len);
14103 else
14105 s = alloc((unsigned)(prevlen + len + 1));
14106 if (s != NULL)
14108 mch_memmove(s, prev, prevlen);
14109 vim_free(prev);
14110 prev = NULL;
14111 mch_memmove(s + prevlen, buf + tolist, len);
14112 s[prevlen + len] = NUL;
14115 tolist = filtd + 1;
14117 li = listitem_alloc();
14118 if (li == NULL)
14120 vim_free(s);
14121 break;
14123 li->li_tv.v_type = VAR_STRING;
14124 li->li_tv.v_lock = 0;
14125 li->li_tv.vval.v_string = s;
14126 list_append(rettv->vval.v_list, li);
14128 if (++cnt >= maxline && maxline >= 0)
14129 break;
14130 if (readlen <= 0)
14131 break;
14133 else if (buf[filtd] == NUL)
14134 buf[filtd] = '\n';
14136 if (readlen <= 0)
14137 break;
14139 if (tolist == 0)
14141 /* "buf" is full, need to move text to an allocated buffer */
14142 if (prev == NULL)
14144 prev = vim_strnsave(buf, buflen);
14145 prevlen = buflen;
14147 else
14149 s = alloc((unsigned)(prevlen + buflen));
14150 if (s != NULL)
14152 mch_memmove(s, prev, prevlen);
14153 mch_memmove(s + prevlen, buf, buflen);
14154 vim_free(prev);
14155 prev = s;
14156 prevlen += buflen;
14159 filtd = 0;
14161 else
14163 mch_memmove(buf, buf + tolist, buflen - tolist);
14164 filtd -= tolist;
14169 * For a negative line count use only the lines at the end of the file,
14170 * free the rest.
14172 if (maxline < 0)
14173 while (cnt > -maxline)
14175 listitem_remove(rettv->vval.v_list, rettv->vval.v_list->lv_first);
14176 --cnt;
14179 vim_free(prev);
14180 fclose(fd);
14183 #if defined(FEAT_RELTIME)
14184 static int list2proftime __ARGS((typval_T *arg, proftime_T *tm));
14187 * Convert a List to proftime_T.
14188 * Return FAIL when there is something wrong.
14190 static int
14191 list2proftime(arg, tm)
14192 typval_T *arg;
14193 proftime_T *tm;
14195 long n1, n2;
14196 int error = FALSE;
14198 if (arg->v_type != VAR_LIST || arg->vval.v_list == NULL
14199 || arg->vval.v_list->lv_len != 2)
14200 return FAIL;
14201 n1 = list_find_nr(arg->vval.v_list, 0L, &error);
14202 n2 = list_find_nr(arg->vval.v_list, 1L, &error);
14203 # ifdef WIN3264
14204 tm->HighPart = n1;
14205 tm->LowPart = n2;
14206 # else
14207 tm->tv_sec = n1;
14208 tm->tv_usec = n2;
14209 # endif
14210 return error ? FAIL : OK;
14212 #endif /* FEAT_RELTIME */
14215 * "reltime()" function
14217 static void
14218 f_reltime(argvars, rettv)
14219 typval_T *argvars;
14220 typval_T *rettv;
14222 #ifdef FEAT_RELTIME
14223 proftime_T res;
14224 proftime_T start;
14226 if (argvars[0].v_type == VAR_UNKNOWN)
14228 /* No arguments: get current time. */
14229 profile_start(&res);
14231 else if (argvars[1].v_type == VAR_UNKNOWN)
14233 if (list2proftime(&argvars[0], &res) == FAIL)
14234 return;
14235 profile_end(&res);
14237 else
14239 /* Two arguments: compute the difference. */
14240 if (list2proftime(&argvars[0], &start) == FAIL
14241 || list2proftime(&argvars[1], &res) == FAIL)
14242 return;
14243 profile_sub(&res, &start);
14246 if (rettv_list_alloc(rettv) == OK)
14248 long n1, n2;
14250 # ifdef WIN3264
14251 n1 = res.HighPart;
14252 n2 = res.LowPart;
14253 # else
14254 n1 = res.tv_sec;
14255 n2 = res.tv_usec;
14256 # endif
14257 list_append_number(rettv->vval.v_list, (varnumber_T)n1);
14258 list_append_number(rettv->vval.v_list, (varnumber_T)n2);
14260 #endif
14264 * "reltimestr()" function
14266 static void
14267 f_reltimestr(argvars, rettv)
14268 typval_T *argvars;
14269 typval_T *rettv;
14271 #ifdef FEAT_RELTIME
14272 proftime_T tm;
14273 #endif
14275 rettv->v_type = VAR_STRING;
14276 rettv->vval.v_string = NULL;
14277 #ifdef FEAT_RELTIME
14278 if (list2proftime(&argvars[0], &tm) == OK)
14279 rettv->vval.v_string = vim_strsave((char_u *)profile_msg(&tm));
14280 #endif
14283 #if defined(FEAT_CLIENTSERVER) && defined(FEAT_X11)
14284 static void make_connection __ARGS((void));
14285 static int check_connection __ARGS((void));
14287 static void
14288 make_connection()
14290 if (X_DISPLAY == NULL
14291 # ifdef FEAT_GUI
14292 && !gui.in_use
14293 # endif
14296 x_force_connect = TRUE;
14297 setup_term_clip();
14298 x_force_connect = FALSE;
14302 static int
14303 check_connection()
14305 make_connection();
14306 if (X_DISPLAY == NULL)
14308 EMSG(_("E240: No connection to Vim server"));
14309 return FAIL;
14311 return OK;
14313 #endif
14315 #ifdef FEAT_CLIENTSERVER
14316 static void remote_common __ARGS((typval_T *argvars, typval_T *rettv, int expr));
14318 static void
14319 remote_common(argvars, rettv, expr)
14320 typval_T *argvars;
14321 typval_T *rettv;
14322 int expr;
14324 char_u *server_name;
14325 char_u *keys;
14326 char_u *r = NULL;
14327 char_u buf[NUMBUFLEN];
14328 # ifdef WIN32
14329 HWND w;
14330 # else
14331 Window w;
14332 # endif
14334 if (check_restricted() || check_secure())
14335 return;
14337 # ifdef FEAT_X11
14338 if (check_connection() == FAIL)
14339 return;
14340 # endif
14342 server_name = get_tv_string_chk(&argvars[0]);
14343 if (server_name == NULL)
14344 return; /* type error; errmsg already given */
14345 keys = get_tv_string_buf(&argvars[1], buf);
14346 # ifdef WIN32
14347 if (serverSendToVim(server_name, keys, &r, &w, expr, TRUE) < 0)
14348 # else
14349 if (serverSendToVim(X_DISPLAY, server_name, keys, &r, &w, expr, 0, TRUE)
14350 < 0)
14351 # endif
14353 if (r != NULL)
14354 EMSG(r); /* sending worked but evaluation failed */
14355 else
14356 EMSG2(_("E241: Unable to send to %s"), server_name);
14357 return;
14360 rettv->vval.v_string = r;
14362 if (argvars[2].v_type != VAR_UNKNOWN)
14364 dictitem_T v;
14365 char_u str[30];
14366 char_u *idvar;
14368 sprintf((char *)str, PRINTF_HEX_LONG_U, (long_u)w);
14369 v.di_tv.v_type = VAR_STRING;
14370 v.di_tv.vval.v_string = vim_strsave(str);
14371 idvar = get_tv_string_chk(&argvars[2]);
14372 if (idvar != NULL)
14373 set_var(idvar, &v.di_tv, FALSE);
14374 vim_free(v.di_tv.vval.v_string);
14377 #endif
14380 * "remote_expr()" function
14382 static void
14383 f_remote_expr(argvars, rettv)
14384 typval_T *argvars UNUSED;
14385 typval_T *rettv;
14387 rettv->v_type = VAR_STRING;
14388 rettv->vval.v_string = NULL;
14389 #ifdef FEAT_CLIENTSERVER
14390 remote_common(argvars, rettv, TRUE);
14391 #endif
14395 * "remote_foreground()" function
14397 static void
14398 f_remote_foreground(argvars, rettv)
14399 typval_T *argvars UNUSED;
14400 typval_T *rettv UNUSED;
14402 #ifdef FEAT_CLIENTSERVER
14403 # ifdef WIN32
14404 /* On Win32 it's done in this application. */
14406 char_u *server_name = get_tv_string_chk(&argvars[0]);
14408 if (server_name != NULL)
14409 serverForeground(server_name);
14411 # else
14412 /* Send a foreground() expression to the server. */
14413 argvars[1].v_type = VAR_STRING;
14414 argvars[1].vval.v_string = vim_strsave((char_u *)"foreground()");
14415 argvars[2].v_type = VAR_UNKNOWN;
14416 remote_common(argvars, rettv, TRUE);
14417 vim_free(argvars[1].vval.v_string);
14418 # endif
14419 #endif
14422 static void
14423 f_remote_peek(argvars, rettv)
14424 typval_T *argvars UNUSED;
14425 typval_T *rettv;
14427 #ifdef FEAT_CLIENTSERVER
14428 dictitem_T v;
14429 char_u *s = NULL;
14430 # ifdef WIN32
14431 long_u n = 0;
14432 # endif
14433 char_u *serverid;
14435 if (check_restricted() || check_secure())
14437 rettv->vval.v_number = -1;
14438 return;
14440 serverid = get_tv_string_chk(&argvars[0]);
14441 if (serverid == NULL)
14443 rettv->vval.v_number = -1;
14444 return; /* type error; errmsg already given */
14446 # ifdef WIN32
14447 sscanf(serverid, SCANF_HEX_LONG_U, &n);
14448 if (n == 0)
14449 rettv->vval.v_number = -1;
14450 else
14452 s = serverGetReply((HWND)n, FALSE, FALSE, FALSE);
14453 rettv->vval.v_number = (s != NULL);
14455 # else
14456 if (check_connection() == FAIL)
14457 return;
14459 rettv->vval.v_number = serverPeekReply(X_DISPLAY,
14460 serverStrToWin(serverid), &s);
14461 # endif
14463 if (argvars[1].v_type != VAR_UNKNOWN && rettv->vval.v_number > 0)
14465 char_u *retvar;
14467 v.di_tv.v_type = VAR_STRING;
14468 v.di_tv.vval.v_string = vim_strsave(s);
14469 retvar = get_tv_string_chk(&argvars[1]);
14470 if (retvar != NULL)
14471 set_var(retvar, &v.di_tv, FALSE);
14472 vim_free(v.di_tv.vval.v_string);
14474 #else
14475 rettv->vval.v_number = -1;
14476 #endif
14479 static void
14480 f_remote_read(argvars, rettv)
14481 typval_T *argvars UNUSED;
14482 typval_T *rettv;
14484 char_u *r = NULL;
14486 #ifdef FEAT_CLIENTSERVER
14487 char_u *serverid = get_tv_string_chk(&argvars[0]);
14489 if (serverid != NULL && !check_restricted() && !check_secure())
14491 # ifdef WIN32
14492 /* The server's HWND is encoded in the 'id' parameter */
14493 long_u n = 0;
14495 sscanf(serverid, SCANF_HEX_LONG_U, &n);
14496 if (n != 0)
14497 r = serverGetReply((HWND)n, FALSE, TRUE, TRUE);
14498 if (r == NULL)
14499 # else
14500 if (check_connection() == FAIL || serverReadReply(X_DISPLAY,
14501 serverStrToWin(serverid), &r, FALSE) < 0)
14502 # endif
14503 EMSG(_("E277: Unable to read a server reply"));
14505 #endif
14506 rettv->v_type = VAR_STRING;
14507 rettv->vval.v_string = r;
14511 * "remote_send()" function
14513 static void
14514 f_remote_send(argvars, rettv)
14515 typval_T *argvars UNUSED;
14516 typval_T *rettv;
14518 rettv->v_type = VAR_STRING;
14519 rettv->vval.v_string = NULL;
14520 #ifdef FEAT_CLIENTSERVER
14521 remote_common(argvars, rettv, FALSE);
14522 #endif
14526 * "remove()" function
14528 static void
14529 f_remove(argvars, rettv)
14530 typval_T *argvars;
14531 typval_T *rettv;
14533 list_T *l;
14534 listitem_T *item, *item2;
14535 listitem_T *li;
14536 long idx;
14537 long end;
14538 char_u *key;
14539 dict_T *d;
14540 dictitem_T *di;
14542 if (argvars[0].v_type == VAR_DICT)
14544 if (argvars[2].v_type != VAR_UNKNOWN)
14545 EMSG2(_(e_toomanyarg), "remove()");
14546 else if ((d = argvars[0].vval.v_dict) != NULL
14547 && !tv_check_lock(d->dv_lock, (char_u *)"remove() argument"))
14549 key = get_tv_string_chk(&argvars[1]);
14550 if (key != NULL)
14552 di = dict_find(d, key, -1);
14553 if (di == NULL)
14554 EMSG2(_(e_dictkey), key);
14555 else
14557 *rettv = di->di_tv;
14558 init_tv(&di->di_tv);
14559 dictitem_remove(d, di);
14564 else if (argvars[0].v_type != VAR_LIST)
14565 EMSG2(_(e_listdictarg), "remove()");
14566 else if ((l = argvars[0].vval.v_list) != NULL
14567 && !tv_check_lock(l->lv_lock, (char_u *)"remove() argument"))
14569 int error = FALSE;
14571 idx = get_tv_number_chk(&argvars[1], &error);
14572 if (error)
14573 ; /* type error: do nothing, errmsg already given */
14574 else if ((item = list_find(l, idx)) == NULL)
14575 EMSGN(_(e_listidx), idx);
14576 else
14578 if (argvars[2].v_type == VAR_UNKNOWN)
14580 /* Remove one item, return its value. */
14581 list_remove(l, item, item);
14582 *rettv = item->li_tv;
14583 vim_free(item);
14585 else
14587 /* Remove range of items, return list with values. */
14588 end = get_tv_number_chk(&argvars[2], &error);
14589 if (error)
14590 ; /* type error: do nothing */
14591 else if ((item2 = list_find(l, end)) == NULL)
14592 EMSGN(_(e_listidx), end);
14593 else
14595 int cnt = 0;
14597 for (li = item; li != NULL; li = li->li_next)
14599 ++cnt;
14600 if (li == item2)
14601 break;
14603 if (li == NULL) /* didn't find "item2" after "item" */
14604 EMSG(_(e_invrange));
14605 else
14607 list_remove(l, item, item2);
14608 if (rettv_list_alloc(rettv) == OK)
14610 l = rettv->vval.v_list;
14611 l->lv_first = item;
14612 l->lv_last = item2;
14613 item->li_prev = NULL;
14614 item2->li_next = NULL;
14615 l->lv_len = cnt;
14625 * "rename({from}, {to})" function
14627 static void
14628 f_rename(argvars, rettv)
14629 typval_T *argvars;
14630 typval_T *rettv;
14632 char_u buf[NUMBUFLEN];
14634 if (check_restricted() || check_secure())
14635 rettv->vval.v_number = -1;
14636 else
14637 rettv->vval.v_number = vim_rename(get_tv_string(&argvars[0]),
14638 get_tv_string_buf(&argvars[1], buf));
14642 * "repeat()" function
14644 static void
14645 f_repeat(argvars, rettv)
14646 typval_T *argvars;
14647 typval_T *rettv;
14649 char_u *p;
14650 int n;
14651 int slen;
14652 int len;
14653 char_u *r;
14654 int i;
14656 n = get_tv_number(&argvars[1]);
14657 if (argvars[0].v_type == VAR_LIST)
14659 if (rettv_list_alloc(rettv) == OK && argvars[0].vval.v_list != NULL)
14660 while (n-- > 0)
14661 if (list_extend(rettv->vval.v_list,
14662 argvars[0].vval.v_list, NULL) == FAIL)
14663 break;
14665 else
14667 p = get_tv_string(&argvars[0]);
14668 rettv->v_type = VAR_STRING;
14669 rettv->vval.v_string = NULL;
14671 slen = (int)STRLEN(p);
14672 len = slen * n;
14673 if (len <= 0)
14674 return;
14676 r = alloc(len + 1);
14677 if (r != NULL)
14679 for (i = 0; i < n; i++)
14680 mch_memmove(r + i * slen, p, (size_t)slen);
14681 r[len] = NUL;
14684 rettv->vval.v_string = r;
14689 * "resolve()" function
14691 static void
14692 f_resolve(argvars, rettv)
14693 typval_T *argvars;
14694 typval_T *rettv;
14696 char_u *p;
14698 p = get_tv_string(&argvars[0]);
14699 #ifdef FEAT_SHORTCUT
14701 char_u *v = NULL;
14703 v = mch_resolve_shortcut(p);
14704 if (v != NULL)
14705 rettv->vval.v_string = v;
14706 else
14707 rettv->vval.v_string = vim_strsave(p);
14709 #else
14710 # ifdef HAVE_READLINK
14712 char_u buf[MAXPATHL + 1];
14713 char_u *cpy;
14714 int len;
14715 char_u *remain = NULL;
14716 char_u *q;
14717 int is_relative_to_current = FALSE;
14718 int has_trailing_pathsep = FALSE;
14719 int limit = 100;
14721 p = vim_strsave(p);
14723 if (p[0] == '.' && (vim_ispathsep(p[1])
14724 || (p[1] == '.' && (vim_ispathsep(p[2])))))
14725 is_relative_to_current = TRUE;
14727 len = STRLEN(p);
14728 if (len > 0 && after_pathsep(p, p + len))
14729 has_trailing_pathsep = TRUE;
14731 q = getnextcomp(p);
14732 if (*q != NUL)
14734 /* Separate the first path component in "p", and keep the
14735 * remainder (beginning with the path separator). */
14736 remain = vim_strsave(q - 1);
14737 q[-1] = NUL;
14740 for (;;)
14742 for (;;)
14744 len = readlink((char *)p, (char *)buf, MAXPATHL);
14745 if (len <= 0)
14746 break;
14747 buf[len] = NUL;
14749 if (limit-- == 0)
14751 vim_free(p);
14752 vim_free(remain);
14753 EMSG(_("E655: Too many symbolic links (cycle?)"));
14754 rettv->vval.v_string = NULL;
14755 goto fail;
14758 /* Ensure that the result will have a trailing path separator
14759 * if the argument has one. */
14760 if (remain == NULL && has_trailing_pathsep)
14761 add_pathsep(buf);
14763 /* Separate the first path component in the link value and
14764 * concatenate the remainders. */
14765 q = getnextcomp(vim_ispathsep(*buf) ? buf + 1 : buf);
14766 if (*q != NUL)
14768 if (remain == NULL)
14769 remain = vim_strsave(q - 1);
14770 else
14772 cpy = concat_str(q - 1, remain);
14773 if (cpy != NULL)
14775 vim_free(remain);
14776 remain = cpy;
14779 q[-1] = NUL;
14782 q = gettail(p);
14783 if (q > p && *q == NUL)
14785 /* Ignore trailing path separator. */
14786 q[-1] = NUL;
14787 q = gettail(p);
14789 if (q > p && !mch_isFullName(buf))
14791 /* symlink is relative to directory of argument */
14792 cpy = alloc((unsigned)(STRLEN(p) + STRLEN(buf) + 1));
14793 if (cpy != NULL)
14795 STRCPY(cpy, p);
14796 STRCPY(gettail(cpy), buf);
14797 vim_free(p);
14798 p = cpy;
14801 else
14803 vim_free(p);
14804 p = vim_strsave(buf);
14808 if (remain == NULL)
14809 break;
14811 /* Append the first path component of "remain" to "p". */
14812 q = getnextcomp(remain + 1);
14813 len = q - remain - (*q != NUL);
14814 cpy = vim_strnsave(p, STRLEN(p) + len);
14815 if (cpy != NULL)
14817 STRNCAT(cpy, remain, len);
14818 vim_free(p);
14819 p = cpy;
14821 /* Shorten "remain". */
14822 if (*q != NUL)
14823 STRMOVE(remain, q - 1);
14824 else
14826 vim_free(remain);
14827 remain = NULL;
14831 /* If the result is a relative path name, make it explicitly relative to
14832 * the current directory if and only if the argument had this form. */
14833 if (!vim_ispathsep(*p))
14835 if (is_relative_to_current
14836 && *p != NUL
14837 && !(p[0] == '.'
14838 && (p[1] == NUL
14839 || vim_ispathsep(p[1])
14840 || (p[1] == '.'
14841 && (p[2] == NUL
14842 || vim_ispathsep(p[2]))))))
14844 /* Prepend "./". */
14845 cpy = concat_str((char_u *)"./", p);
14846 if (cpy != NULL)
14848 vim_free(p);
14849 p = cpy;
14852 else if (!is_relative_to_current)
14854 /* Strip leading "./". */
14855 q = p;
14856 while (q[0] == '.' && vim_ispathsep(q[1]))
14857 q += 2;
14858 if (q > p)
14859 STRMOVE(p, p + 2);
14863 /* Ensure that the result will have no trailing path separator
14864 * if the argument had none. But keep "/" or "//". */
14865 if (!has_trailing_pathsep)
14867 q = p + STRLEN(p);
14868 if (after_pathsep(p, q))
14869 *gettail_sep(p) = NUL;
14872 rettv->vval.v_string = p;
14874 # else
14875 rettv->vval.v_string = vim_strsave(p);
14876 # endif
14877 #endif
14879 simplify_filename(rettv->vval.v_string);
14881 #ifdef HAVE_READLINK
14882 fail:
14883 #endif
14884 rettv->v_type = VAR_STRING;
14888 * "reverse({list})" function
14890 static void
14891 f_reverse(argvars, rettv)
14892 typval_T *argvars;
14893 typval_T *rettv;
14895 list_T *l;
14896 listitem_T *li, *ni;
14898 if (argvars[0].v_type != VAR_LIST)
14899 EMSG2(_(e_listarg), "reverse()");
14900 else if ((l = argvars[0].vval.v_list) != NULL
14901 && !tv_check_lock(l->lv_lock, (char_u *)"reverse()"))
14903 li = l->lv_last;
14904 l->lv_first = l->lv_last = NULL;
14905 l->lv_len = 0;
14906 while (li != NULL)
14908 ni = li->li_prev;
14909 list_append(l, li);
14910 li = ni;
14912 rettv->vval.v_list = l;
14913 rettv->v_type = VAR_LIST;
14914 ++l->lv_refcount;
14915 l->lv_idx = l->lv_len - l->lv_idx - 1;
14919 #define SP_NOMOVE 0x01 /* don't move cursor */
14920 #define SP_REPEAT 0x02 /* repeat to find outer pair */
14921 #define SP_RETCOUNT 0x04 /* return matchcount */
14922 #define SP_SETPCMARK 0x08 /* set previous context mark */
14923 #define SP_START 0x10 /* accept match at start position */
14924 #define SP_SUBPAT 0x20 /* return nr of matching sub-pattern */
14925 #define SP_END 0x40 /* leave cursor at end of match */
14927 static int get_search_arg __ARGS((typval_T *varp, int *flagsp));
14930 * Get flags for a search function.
14931 * Possibly sets "p_ws".
14932 * Returns BACKWARD, FORWARD or zero (for an error).
14934 static int
14935 get_search_arg(varp, flagsp)
14936 typval_T *varp;
14937 int *flagsp;
14939 int dir = FORWARD;
14940 char_u *flags;
14941 char_u nbuf[NUMBUFLEN];
14942 int mask;
14944 if (varp->v_type != VAR_UNKNOWN)
14946 flags = get_tv_string_buf_chk(varp, nbuf);
14947 if (flags == NULL)
14948 return 0; /* type error; errmsg already given */
14949 while (*flags != NUL)
14951 switch (*flags)
14953 case 'b': dir = BACKWARD; break;
14954 case 'w': p_ws = TRUE; break;
14955 case 'W': p_ws = FALSE; break;
14956 default: mask = 0;
14957 if (flagsp != NULL)
14958 switch (*flags)
14960 case 'c': mask = SP_START; break;
14961 case 'e': mask = SP_END; break;
14962 case 'm': mask = SP_RETCOUNT; break;
14963 case 'n': mask = SP_NOMOVE; break;
14964 case 'p': mask = SP_SUBPAT; break;
14965 case 'r': mask = SP_REPEAT; break;
14966 case 's': mask = SP_SETPCMARK; break;
14968 if (mask == 0)
14970 EMSG2(_(e_invarg2), flags);
14971 dir = 0;
14973 else
14974 *flagsp |= mask;
14976 if (dir == 0)
14977 break;
14978 ++flags;
14981 return dir;
14985 * Shared by search() and searchpos() functions
14987 static int
14988 search_cmn(argvars, match_pos, flagsp)
14989 typval_T *argvars;
14990 pos_T *match_pos;
14991 int *flagsp;
14993 int flags;
14994 char_u *pat;
14995 pos_T pos;
14996 pos_T save_cursor;
14997 int save_p_ws = p_ws;
14998 int dir;
14999 int retval = 0; /* default: FAIL */
15000 long lnum_stop = 0;
15001 proftime_T tm;
15002 #ifdef FEAT_RELTIME
15003 long time_limit = 0;
15004 #endif
15005 int options = SEARCH_KEEP;
15006 int subpatnum;
15008 pat = get_tv_string(&argvars[0]);
15009 dir = get_search_arg(&argvars[1], flagsp); /* may set p_ws */
15010 if (dir == 0)
15011 goto theend;
15012 flags = *flagsp;
15013 if (flags & SP_START)
15014 options |= SEARCH_START;
15015 if (flags & SP_END)
15016 options |= SEARCH_END;
15018 /* Optional arguments: line number to stop searching and timeout. */
15019 if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN)
15021 lnum_stop = get_tv_number_chk(&argvars[2], NULL);
15022 if (lnum_stop < 0)
15023 goto theend;
15024 #ifdef FEAT_RELTIME
15025 if (argvars[3].v_type != VAR_UNKNOWN)
15027 time_limit = get_tv_number_chk(&argvars[3], NULL);
15028 if (time_limit < 0)
15029 goto theend;
15031 #endif
15034 #ifdef FEAT_RELTIME
15035 /* Set the time limit, if there is one. */
15036 profile_setlimit(time_limit, &tm);
15037 #endif
15040 * This function does not accept SP_REPEAT and SP_RETCOUNT flags.
15041 * Check to make sure only those flags are set.
15042 * Also, Only the SP_NOMOVE or the SP_SETPCMARK flag can be set. Both
15043 * flags cannot be set. Check for that condition also.
15045 if (((flags & (SP_REPEAT | SP_RETCOUNT)) != 0)
15046 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
15048 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
15049 goto theend;
15052 pos = save_cursor = curwin->w_cursor;
15053 subpatnum = searchit(curwin, curbuf, &pos, dir, pat, 1L,
15054 options, RE_SEARCH, (linenr_T)lnum_stop, &tm);
15055 if (subpatnum != FAIL)
15057 if (flags & SP_SUBPAT)
15058 retval = subpatnum;
15059 else
15060 retval = pos.lnum;
15061 if (flags & SP_SETPCMARK)
15062 setpcmark();
15063 curwin->w_cursor = pos;
15064 if (match_pos != NULL)
15066 /* Store the match cursor position */
15067 match_pos->lnum = pos.lnum;
15068 match_pos->col = pos.col + 1;
15070 /* "/$" will put the cursor after the end of the line, may need to
15071 * correct that here */
15072 check_cursor();
15075 /* If 'n' flag is used: restore cursor position. */
15076 if (flags & SP_NOMOVE)
15077 curwin->w_cursor = save_cursor;
15078 else
15079 curwin->w_set_curswant = TRUE;
15080 theend:
15081 p_ws = save_p_ws;
15083 return retval;
15086 #ifdef FEAT_FLOAT
15088 * "round({float})" function
15090 static void
15091 f_round(argvars, rettv)
15092 typval_T *argvars;
15093 typval_T *rettv;
15095 float_T f;
15097 rettv->v_type = VAR_FLOAT;
15098 if (get_float_arg(argvars, &f) == OK)
15099 /* round() is not in C90, use ceil() or floor() instead. */
15100 rettv->vval.v_float = f > 0 ? floor(f + 0.5) : ceil(f - 0.5);
15101 else
15102 rettv->vval.v_float = 0.0;
15104 #endif
15107 * "search()" function
15109 static void
15110 f_search(argvars, rettv)
15111 typval_T *argvars;
15112 typval_T *rettv;
15114 int flags = 0;
15116 rettv->vval.v_number = search_cmn(argvars, NULL, &flags);
15120 * "searchdecl()" function
15122 static void
15123 f_searchdecl(argvars, rettv)
15124 typval_T *argvars;
15125 typval_T *rettv;
15127 int locally = 1;
15128 int thisblock = 0;
15129 int error = FALSE;
15130 char_u *name;
15132 rettv->vval.v_number = 1; /* default: FAIL */
15134 name = get_tv_string_chk(&argvars[0]);
15135 if (argvars[1].v_type != VAR_UNKNOWN)
15137 locally = get_tv_number_chk(&argvars[1], &error) == 0;
15138 if (!error && argvars[2].v_type != VAR_UNKNOWN)
15139 thisblock = get_tv_number_chk(&argvars[2], &error) != 0;
15141 if (!error && name != NULL)
15142 rettv->vval.v_number = find_decl(name, (int)STRLEN(name),
15143 locally, thisblock, SEARCH_KEEP) == FAIL;
15147 * Used by searchpair() and searchpairpos()
15149 static int
15150 searchpair_cmn(argvars, match_pos)
15151 typval_T *argvars;
15152 pos_T *match_pos;
15154 char_u *spat, *mpat, *epat;
15155 char_u *skip;
15156 int save_p_ws = p_ws;
15157 int dir;
15158 int flags = 0;
15159 char_u nbuf1[NUMBUFLEN];
15160 char_u nbuf2[NUMBUFLEN];
15161 char_u nbuf3[NUMBUFLEN];
15162 int retval = 0; /* default: FAIL */
15163 long lnum_stop = 0;
15164 long time_limit = 0;
15166 /* Get the three pattern arguments: start, middle, end. */
15167 spat = get_tv_string_chk(&argvars[0]);
15168 mpat = get_tv_string_buf_chk(&argvars[1], nbuf1);
15169 epat = get_tv_string_buf_chk(&argvars[2], nbuf2);
15170 if (spat == NULL || mpat == NULL || epat == NULL)
15171 goto theend; /* type error */
15173 /* Handle the optional fourth argument: flags */
15174 dir = get_search_arg(&argvars[3], &flags); /* may set p_ws */
15175 if (dir == 0)
15176 goto theend;
15178 /* Don't accept SP_END or SP_SUBPAT.
15179 * Only one of the SP_NOMOVE or SP_SETPCMARK flags can be set.
15181 if ((flags & (SP_END | SP_SUBPAT)) != 0
15182 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
15184 EMSG2(_(e_invarg2), get_tv_string(&argvars[3]));
15185 goto theend;
15188 /* Using 'r' implies 'W', otherwise it doesn't work. */
15189 if (flags & SP_REPEAT)
15190 p_ws = FALSE;
15192 /* Optional fifth argument: skip expression */
15193 if (argvars[3].v_type == VAR_UNKNOWN
15194 || argvars[4].v_type == VAR_UNKNOWN)
15195 skip = (char_u *)"";
15196 else
15198 skip = get_tv_string_buf_chk(&argvars[4], nbuf3);
15199 if (argvars[5].v_type != VAR_UNKNOWN)
15201 lnum_stop = get_tv_number_chk(&argvars[5], NULL);
15202 if (lnum_stop < 0)
15203 goto theend;
15204 #ifdef FEAT_RELTIME
15205 if (argvars[6].v_type != VAR_UNKNOWN)
15207 time_limit = get_tv_number_chk(&argvars[6], NULL);
15208 if (time_limit < 0)
15209 goto theend;
15211 #endif
15214 if (skip == NULL)
15215 goto theend; /* type error */
15217 retval = do_searchpair(spat, mpat, epat, dir, skip, flags,
15218 match_pos, lnum_stop, time_limit);
15220 theend:
15221 p_ws = save_p_ws;
15223 return retval;
15227 * "searchpair()" function
15229 static void
15230 f_searchpair(argvars, rettv)
15231 typval_T *argvars;
15232 typval_T *rettv;
15234 rettv->vval.v_number = searchpair_cmn(argvars, NULL);
15238 * "searchpairpos()" function
15240 static void
15241 f_searchpairpos(argvars, rettv)
15242 typval_T *argvars;
15243 typval_T *rettv;
15245 pos_T match_pos;
15246 int lnum = 0;
15247 int col = 0;
15249 if (rettv_list_alloc(rettv) == FAIL)
15250 return;
15252 if (searchpair_cmn(argvars, &match_pos) > 0)
15254 lnum = match_pos.lnum;
15255 col = match_pos.col;
15258 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
15259 list_append_number(rettv->vval.v_list, (varnumber_T)col);
15263 * Search for a start/middle/end thing.
15264 * Used by searchpair(), see its documentation for the details.
15265 * Returns 0 or -1 for no match,
15267 long
15268 do_searchpair(spat, mpat, epat, dir, skip, flags, match_pos,
15269 lnum_stop, time_limit)
15270 char_u *spat; /* start pattern */
15271 char_u *mpat; /* middle pattern */
15272 char_u *epat; /* end pattern */
15273 int dir; /* BACKWARD or FORWARD */
15274 char_u *skip; /* skip expression */
15275 int flags; /* SP_SETPCMARK and other SP_ values */
15276 pos_T *match_pos;
15277 linenr_T lnum_stop; /* stop at this line if not zero */
15278 long time_limit; /* stop after this many msec */
15280 char_u *save_cpo;
15281 char_u *pat, *pat2 = NULL, *pat3 = NULL;
15282 long retval = 0;
15283 pos_T pos;
15284 pos_T firstpos;
15285 pos_T foundpos;
15286 pos_T save_cursor;
15287 pos_T save_pos;
15288 int n;
15289 int r;
15290 int nest = 1;
15291 int err;
15292 int options = SEARCH_KEEP;
15293 proftime_T tm;
15295 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
15296 save_cpo = p_cpo;
15297 p_cpo = empty_option;
15299 #ifdef FEAT_RELTIME
15300 /* Set the time limit, if there is one. */
15301 profile_setlimit(time_limit, &tm);
15302 #endif
15304 /* Make two search patterns: start/end (pat2, for in nested pairs) and
15305 * start/middle/end (pat3, for the top pair). */
15306 pat2 = alloc((unsigned)(STRLEN(spat) + STRLEN(epat) + 15));
15307 pat3 = alloc((unsigned)(STRLEN(spat) + STRLEN(mpat) + STRLEN(epat) + 23));
15308 if (pat2 == NULL || pat3 == NULL)
15309 goto theend;
15310 sprintf((char *)pat2, "\\(%s\\m\\)\\|\\(%s\\m\\)", spat, epat);
15311 if (*mpat == NUL)
15312 STRCPY(pat3, pat2);
15313 else
15314 sprintf((char *)pat3, "\\(%s\\m\\)\\|\\(%s\\m\\)\\|\\(%s\\m\\)",
15315 spat, epat, mpat);
15316 if (flags & SP_START)
15317 options |= SEARCH_START;
15319 save_cursor = curwin->w_cursor;
15320 pos = curwin->w_cursor;
15321 clearpos(&firstpos);
15322 clearpos(&foundpos);
15323 pat = pat3;
15324 for (;;)
15326 n = searchit(curwin, curbuf, &pos, dir, pat, 1L,
15327 options, RE_SEARCH, lnum_stop, &tm);
15328 if (n == FAIL || (firstpos.lnum != 0 && equalpos(pos, firstpos)))
15329 /* didn't find it or found the first match again: FAIL */
15330 break;
15332 if (firstpos.lnum == 0)
15333 firstpos = pos;
15334 if (equalpos(pos, foundpos))
15336 /* Found the same position again. Can happen with a pattern that
15337 * has "\zs" at the end and searching backwards. Advance one
15338 * character and try again. */
15339 if (dir == BACKWARD)
15340 decl(&pos);
15341 else
15342 incl(&pos);
15344 foundpos = pos;
15346 /* clear the start flag to avoid getting stuck here */
15347 options &= ~SEARCH_START;
15349 /* If the skip pattern matches, ignore this match. */
15350 if (*skip != NUL)
15352 save_pos = curwin->w_cursor;
15353 curwin->w_cursor = pos;
15354 r = eval_to_bool(skip, &err, NULL, FALSE);
15355 curwin->w_cursor = save_pos;
15356 if (err)
15358 /* Evaluating {skip} caused an error, break here. */
15359 curwin->w_cursor = save_cursor;
15360 retval = -1;
15361 break;
15363 if (r)
15364 continue;
15367 if ((dir == BACKWARD && n == 3) || (dir == FORWARD && n == 2))
15369 /* Found end when searching backwards or start when searching
15370 * forward: nested pair. */
15371 ++nest;
15372 pat = pat2; /* nested, don't search for middle */
15374 else
15376 /* Found end when searching forward or start when searching
15377 * backward: end of (nested) pair; or found middle in outer pair. */
15378 if (--nest == 1)
15379 pat = pat3; /* outer level, search for middle */
15382 if (nest == 0)
15384 /* Found the match: return matchcount or line number. */
15385 if (flags & SP_RETCOUNT)
15386 ++retval;
15387 else
15388 retval = pos.lnum;
15389 if (flags & SP_SETPCMARK)
15390 setpcmark();
15391 curwin->w_cursor = pos;
15392 if (!(flags & SP_REPEAT))
15393 break;
15394 nest = 1; /* search for next unmatched */
15398 if (match_pos != NULL)
15400 /* Store the match cursor position */
15401 match_pos->lnum = curwin->w_cursor.lnum;
15402 match_pos->col = curwin->w_cursor.col + 1;
15405 /* If 'n' flag is used or search failed: restore cursor position. */
15406 if ((flags & SP_NOMOVE) || retval == 0)
15407 curwin->w_cursor = save_cursor;
15409 theend:
15410 vim_free(pat2);
15411 vim_free(pat3);
15412 if (p_cpo == empty_option)
15413 p_cpo = save_cpo;
15414 else
15415 /* Darn, evaluating the {skip} expression changed the value. */
15416 free_string_option(save_cpo);
15418 return retval;
15422 * "searchpos()" function
15424 static void
15425 f_searchpos(argvars, rettv)
15426 typval_T *argvars;
15427 typval_T *rettv;
15429 pos_T match_pos;
15430 int lnum = 0;
15431 int col = 0;
15432 int n;
15433 int flags = 0;
15435 if (rettv_list_alloc(rettv) == FAIL)
15436 return;
15438 n = search_cmn(argvars, &match_pos, &flags);
15439 if (n > 0)
15441 lnum = match_pos.lnum;
15442 col = match_pos.col;
15445 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
15446 list_append_number(rettv->vval.v_list, (varnumber_T)col);
15447 if (flags & SP_SUBPAT)
15448 list_append_number(rettv->vval.v_list, (varnumber_T)n);
15452 static void
15453 f_server2client(argvars, rettv)
15454 typval_T *argvars UNUSED;
15455 typval_T *rettv;
15457 #ifdef FEAT_CLIENTSERVER
15458 char_u buf[NUMBUFLEN];
15459 char_u *server = get_tv_string_chk(&argvars[0]);
15460 char_u *reply = get_tv_string_buf_chk(&argvars[1], buf);
15462 rettv->vval.v_number = -1;
15463 if (server == NULL || reply == NULL)
15464 return;
15465 if (check_restricted() || check_secure())
15466 return;
15467 # ifdef FEAT_X11
15468 if (check_connection() == FAIL)
15469 return;
15470 # endif
15472 if (serverSendReply(server, reply) < 0)
15474 EMSG(_("E258: Unable to send to client"));
15475 return;
15477 rettv->vval.v_number = 0;
15478 #else
15479 rettv->vval.v_number = -1;
15480 #endif
15483 static void
15484 f_serverlist(argvars, rettv)
15485 typval_T *argvars UNUSED;
15486 typval_T *rettv;
15488 char_u *r = NULL;
15490 #ifdef FEAT_CLIENTSERVER
15491 # ifdef WIN32
15492 r = serverGetVimNames();
15493 # else
15494 make_connection();
15495 if (X_DISPLAY != NULL)
15496 r = serverGetVimNames(X_DISPLAY);
15497 # endif
15498 #endif
15499 rettv->v_type = VAR_STRING;
15500 rettv->vval.v_string = r;
15504 * "setbufvar()" function
15506 static void
15507 f_setbufvar(argvars, rettv)
15508 typval_T *argvars;
15509 typval_T *rettv UNUSED;
15511 buf_T *buf;
15512 aco_save_T aco;
15513 char_u *varname, *bufvarname;
15514 typval_T *varp;
15515 char_u nbuf[NUMBUFLEN];
15517 if (check_restricted() || check_secure())
15518 return;
15519 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
15520 varname = get_tv_string_chk(&argvars[1]);
15521 buf = get_buf_tv(&argvars[0]);
15522 varp = &argvars[2];
15524 if (buf != NULL && varname != NULL && varp != NULL)
15526 /* set curbuf to be our buf, temporarily */
15527 aucmd_prepbuf(&aco, buf);
15529 if (*varname == '&')
15531 long numval;
15532 char_u *strval;
15533 int error = FALSE;
15535 ++varname;
15536 numval = get_tv_number_chk(varp, &error);
15537 strval = get_tv_string_buf_chk(varp, nbuf);
15538 if (!error && strval != NULL)
15539 set_option_value(varname, numval, strval, OPT_LOCAL);
15541 else
15543 bufvarname = alloc((unsigned)STRLEN(varname) + 3);
15544 if (bufvarname != NULL)
15546 STRCPY(bufvarname, "b:");
15547 STRCPY(bufvarname + 2, varname);
15548 set_var(bufvarname, varp, TRUE);
15549 vim_free(bufvarname);
15553 /* reset notion of buffer */
15554 aucmd_restbuf(&aco);
15559 * "setcmdpos()" function
15561 static void
15562 f_setcmdpos(argvars, rettv)
15563 typval_T *argvars;
15564 typval_T *rettv;
15566 int pos = (int)get_tv_number(&argvars[0]) - 1;
15568 if (pos >= 0)
15569 rettv->vval.v_number = set_cmdline_pos(pos);
15573 * "setline()" function
15575 static void
15576 f_setline(argvars, rettv)
15577 typval_T *argvars;
15578 typval_T *rettv;
15580 linenr_T lnum;
15581 char_u *line = NULL;
15582 list_T *l = NULL;
15583 listitem_T *li = NULL;
15584 long added = 0;
15585 linenr_T lcount = curbuf->b_ml.ml_line_count;
15587 lnum = get_tv_lnum(&argvars[0]);
15588 if (argvars[1].v_type == VAR_LIST)
15590 l = argvars[1].vval.v_list;
15591 li = l->lv_first;
15593 else
15594 line = get_tv_string_chk(&argvars[1]);
15596 /* default result is zero == OK */
15597 for (;;)
15599 if (l != NULL)
15601 /* list argument, get next string */
15602 if (li == NULL)
15603 break;
15604 line = get_tv_string_chk(&li->li_tv);
15605 li = li->li_next;
15608 rettv->vval.v_number = 1; /* FAIL */
15609 if (line == NULL || lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
15610 break;
15611 if (lnum <= curbuf->b_ml.ml_line_count)
15613 /* existing line, replace it */
15614 if (u_savesub(lnum) == OK && ml_replace(lnum, line, TRUE) == OK)
15616 changed_bytes(lnum, 0);
15617 if (lnum == curwin->w_cursor.lnum)
15618 check_cursor_col();
15619 rettv->vval.v_number = 0; /* OK */
15622 else if (added > 0 || u_save(lnum - 1, lnum) == OK)
15624 /* lnum is one past the last line, append the line */
15625 ++added;
15626 if (ml_append(lnum - 1, line, (colnr_T)0, FALSE) == OK)
15627 rettv->vval.v_number = 0; /* OK */
15630 if (l == NULL) /* only one string argument */
15631 break;
15632 ++lnum;
15635 if (added > 0)
15636 appended_lines_mark(lcount, added);
15639 static void set_qf_ll_list __ARGS((win_T *wp, typval_T *list_arg, typval_T *action_arg, typval_T *rettv));
15642 * Used by "setqflist()" and "setloclist()" functions
15644 static void
15645 set_qf_ll_list(wp, list_arg, action_arg, rettv)
15646 win_T *wp UNUSED;
15647 typval_T *list_arg UNUSED;
15648 typval_T *action_arg UNUSED;
15649 typval_T *rettv;
15651 #ifdef FEAT_QUICKFIX
15652 char_u *act;
15653 int action = ' ';
15654 #endif
15656 rettv->vval.v_number = -1;
15658 #ifdef FEAT_QUICKFIX
15659 if (list_arg->v_type != VAR_LIST)
15660 EMSG(_(e_listreq));
15661 else
15663 list_T *l = list_arg->vval.v_list;
15665 if (action_arg->v_type == VAR_STRING)
15667 act = get_tv_string_chk(action_arg);
15668 if (act == NULL)
15669 return; /* type error; errmsg already given */
15670 if (*act == 'a' || *act == 'r')
15671 action = *act;
15674 if (l != NULL && set_errorlist(wp, l, action) == OK)
15675 rettv->vval.v_number = 0;
15677 #endif
15681 * "setloclist()" function
15683 static void
15684 f_setloclist(argvars, rettv)
15685 typval_T *argvars;
15686 typval_T *rettv;
15688 win_T *win;
15690 rettv->vval.v_number = -1;
15692 win = find_win_by_nr(&argvars[0], NULL);
15693 if (win != NULL)
15694 set_qf_ll_list(win, &argvars[1], &argvars[2], rettv);
15698 * "setmatches()" function
15700 static void
15701 f_setmatches(argvars, rettv)
15702 typval_T *argvars;
15703 typval_T *rettv;
15705 #ifdef FEAT_SEARCH_EXTRA
15706 list_T *l;
15707 listitem_T *li;
15708 dict_T *d;
15710 rettv->vval.v_number = -1;
15711 if (argvars[0].v_type != VAR_LIST)
15713 EMSG(_(e_listreq));
15714 return;
15716 if ((l = argvars[0].vval.v_list) != NULL)
15719 /* To some extent make sure that we are dealing with a list from
15720 * "getmatches()". */
15721 li = l->lv_first;
15722 while (li != NULL)
15724 if (li->li_tv.v_type != VAR_DICT
15725 || (d = li->li_tv.vval.v_dict) == NULL)
15727 EMSG(_(e_invarg));
15728 return;
15730 if (!(dict_find(d, (char_u *)"group", -1) != NULL
15731 && dict_find(d, (char_u *)"pattern", -1) != NULL
15732 && dict_find(d, (char_u *)"priority", -1) != NULL
15733 && dict_find(d, (char_u *)"id", -1) != NULL))
15735 EMSG(_(e_invarg));
15736 return;
15738 li = li->li_next;
15741 clear_matches(curwin);
15742 li = l->lv_first;
15743 while (li != NULL)
15745 d = li->li_tv.vval.v_dict;
15746 match_add(curwin, get_dict_string(d, (char_u *)"group", FALSE),
15747 get_dict_string(d, (char_u *)"pattern", FALSE),
15748 (int)get_dict_number(d, (char_u *)"priority"),
15749 (int)get_dict_number(d, (char_u *)"id"));
15750 li = li->li_next;
15752 rettv->vval.v_number = 0;
15754 #endif
15758 * "setpos()" function
15760 static void
15761 f_setpos(argvars, rettv)
15762 typval_T *argvars;
15763 typval_T *rettv;
15765 pos_T pos;
15766 int fnum;
15767 char_u *name;
15769 rettv->vval.v_number = -1;
15770 name = get_tv_string_chk(argvars);
15771 if (name != NULL)
15773 if (list2fpos(&argvars[1], &pos, &fnum) == OK)
15775 if (--pos.col < 0)
15776 pos.col = 0;
15777 if (name[0] == '.' && name[1] == NUL)
15779 /* set cursor */
15780 if (fnum == curbuf->b_fnum)
15782 curwin->w_cursor = pos;
15783 check_cursor();
15784 rettv->vval.v_number = 0;
15786 else
15787 EMSG(_(e_invarg));
15789 else if (name[0] == '\'' && name[1] != NUL && name[2] == NUL)
15791 /* set mark */
15792 if (setmark_pos(name[1], &pos, fnum) == OK)
15793 rettv->vval.v_number = 0;
15795 else
15796 EMSG(_(e_invarg));
15802 * "setqflist()" function
15804 static void
15805 f_setqflist(argvars, rettv)
15806 typval_T *argvars;
15807 typval_T *rettv;
15809 set_qf_ll_list(NULL, &argvars[0], &argvars[1], rettv);
15813 * "setreg()" function
15815 static void
15816 f_setreg(argvars, rettv)
15817 typval_T *argvars;
15818 typval_T *rettv;
15820 int regname;
15821 char_u *strregname;
15822 char_u *stropt;
15823 char_u *strval;
15824 int append;
15825 char_u yank_type;
15826 long block_len;
15828 block_len = -1;
15829 yank_type = MAUTO;
15830 append = FALSE;
15832 strregname = get_tv_string_chk(argvars);
15833 rettv->vval.v_number = 1; /* FAIL is default */
15835 if (strregname == NULL)
15836 return; /* type error; errmsg already given */
15837 regname = *strregname;
15838 if (regname == 0 || regname == '@')
15839 regname = '"';
15840 else if (regname == '=')
15841 return;
15843 if (argvars[2].v_type != VAR_UNKNOWN)
15845 stropt = get_tv_string_chk(&argvars[2]);
15846 if (stropt == NULL)
15847 return; /* type error */
15848 for (; *stropt != NUL; ++stropt)
15849 switch (*stropt)
15851 case 'a': case 'A': /* append */
15852 append = TRUE;
15853 break;
15854 case 'v': case 'c': /* character-wise selection */
15855 yank_type = MCHAR;
15856 break;
15857 case 'V': case 'l': /* line-wise selection */
15858 yank_type = MLINE;
15859 break;
15860 #ifdef FEAT_VISUAL
15861 case 'b': case Ctrl_V: /* block-wise selection */
15862 yank_type = MBLOCK;
15863 if (VIM_ISDIGIT(stropt[1]))
15865 ++stropt;
15866 block_len = getdigits(&stropt) - 1;
15867 --stropt;
15869 break;
15870 #endif
15874 strval = get_tv_string_chk(&argvars[1]);
15875 if (strval != NULL)
15876 write_reg_contents_ex(regname, strval, -1,
15877 append, yank_type, block_len);
15878 rettv->vval.v_number = 0;
15882 * "settabwinvar()" function
15884 static void
15885 f_settabwinvar(argvars, rettv)
15886 typval_T *argvars;
15887 typval_T *rettv;
15889 setwinvar(argvars, rettv, 1);
15893 * "setwinvar()" function
15895 static void
15896 f_setwinvar(argvars, rettv)
15897 typval_T *argvars;
15898 typval_T *rettv;
15900 setwinvar(argvars, rettv, 0);
15904 * "setwinvar()" and "settabwinvar()" functions
15906 static void
15907 setwinvar(argvars, rettv, off)
15908 typval_T *argvars;
15909 typval_T *rettv UNUSED;
15910 int off;
15912 win_T *win;
15913 #ifdef FEAT_WINDOWS
15914 win_T *save_curwin;
15915 tabpage_T *save_curtab;
15916 #endif
15917 char_u *varname, *winvarname;
15918 typval_T *varp;
15919 char_u nbuf[NUMBUFLEN];
15920 tabpage_T *tp;
15922 if (check_restricted() || check_secure())
15923 return;
15925 #ifdef FEAT_WINDOWS
15926 if (off == 1)
15927 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
15928 else
15929 tp = curtab;
15930 #endif
15931 win = find_win_by_nr(&argvars[off], tp);
15932 varname = get_tv_string_chk(&argvars[off + 1]);
15933 varp = &argvars[off + 2];
15935 if (win != NULL && varname != NULL && varp != NULL)
15937 #ifdef FEAT_WINDOWS
15938 /* set curwin to be our win, temporarily */
15939 save_curwin = curwin;
15940 save_curtab = curtab;
15941 goto_tabpage_tp(tp);
15942 if (!win_valid(win))
15943 return;
15944 curwin = win;
15945 curbuf = curwin->w_buffer;
15946 #endif
15948 if (*varname == '&')
15950 long numval;
15951 char_u *strval;
15952 int error = FALSE;
15954 ++varname;
15955 numval = get_tv_number_chk(varp, &error);
15956 strval = get_tv_string_buf_chk(varp, nbuf);
15957 if (!error && strval != NULL)
15958 set_option_value(varname, numval, strval, OPT_LOCAL);
15960 else
15962 winvarname = alloc((unsigned)STRLEN(varname) + 3);
15963 if (winvarname != NULL)
15965 STRCPY(winvarname, "w:");
15966 STRCPY(winvarname + 2, varname);
15967 set_var(winvarname, varp, TRUE);
15968 vim_free(winvarname);
15972 #ifdef FEAT_WINDOWS
15973 /* Restore current tabpage and window, if still valid (autocomands can
15974 * make them invalid). */
15975 if (valid_tabpage(save_curtab))
15976 goto_tabpage_tp(save_curtab);
15977 if (win_valid(save_curwin))
15979 curwin = save_curwin;
15980 curbuf = curwin->w_buffer;
15982 #endif
15987 * "shellescape({string})" function
15989 static void
15990 f_shellescape(argvars, rettv)
15991 typval_T *argvars;
15992 typval_T *rettv;
15994 rettv->vval.v_string = vim_strsave_shellescape(
15995 get_tv_string(&argvars[0]), non_zero_arg(&argvars[1]));
15996 rettv->v_type = VAR_STRING;
16000 * "simplify()" function
16002 static void
16003 f_simplify(argvars, rettv)
16004 typval_T *argvars;
16005 typval_T *rettv;
16007 char_u *p;
16009 p = get_tv_string(&argvars[0]);
16010 rettv->vval.v_string = vim_strsave(p);
16011 simplify_filename(rettv->vval.v_string); /* simplify in place */
16012 rettv->v_type = VAR_STRING;
16015 #ifdef FEAT_FLOAT
16017 * "sin()" function
16019 static void
16020 f_sin(argvars, rettv)
16021 typval_T *argvars;
16022 typval_T *rettv;
16024 float_T f;
16026 rettv->v_type = VAR_FLOAT;
16027 if (get_float_arg(argvars, &f) == OK)
16028 rettv->vval.v_float = sin(f);
16029 else
16030 rettv->vval.v_float = 0.0;
16032 #endif
16034 static int
16035 #ifdef __BORLANDC__
16036 _RTLENTRYF
16037 #endif
16038 item_compare __ARGS((const void *s1, const void *s2));
16039 static int
16040 #ifdef __BORLANDC__
16041 _RTLENTRYF
16042 #endif
16043 item_compare2 __ARGS((const void *s1, const void *s2));
16045 static int item_compare_ic;
16046 static char_u *item_compare_func;
16047 static int item_compare_func_err;
16048 #define ITEM_COMPARE_FAIL 999
16051 * Compare functions for f_sort() below.
16053 static int
16054 #ifdef __BORLANDC__
16055 _RTLENTRYF
16056 #endif
16057 item_compare(s1, s2)
16058 const void *s1;
16059 const void *s2;
16061 char_u *p1, *p2;
16062 char_u *tofree1, *tofree2;
16063 int res;
16064 char_u numbuf1[NUMBUFLEN];
16065 char_u numbuf2[NUMBUFLEN];
16067 p1 = tv2string(&(*(listitem_T **)s1)->li_tv, &tofree1, numbuf1, 0);
16068 p2 = tv2string(&(*(listitem_T **)s2)->li_tv, &tofree2, numbuf2, 0);
16069 if (p1 == NULL)
16070 p1 = (char_u *)"";
16071 if (p2 == NULL)
16072 p2 = (char_u *)"";
16073 if (item_compare_ic)
16074 res = STRICMP(p1, p2);
16075 else
16076 res = STRCMP(p1, p2);
16077 vim_free(tofree1);
16078 vim_free(tofree2);
16079 return res;
16082 static int
16083 #ifdef __BORLANDC__
16084 _RTLENTRYF
16085 #endif
16086 item_compare2(s1, s2)
16087 const void *s1;
16088 const void *s2;
16090 int res;
16091 typval_T rettv;
16092 typval_T argv[3];
16093 int dummy;
16095 /* shortcut after failure in previous call; compare all items equal */
16096 if (item_compare_func_err)
16097 return 0;
16099 /* copy the values. This is needed to be able to set v_lock to VAR_FIXED
16100 * in the copy without changing the original list items. */
16101 copy_tv(&(*(listitem_T **)s1)->li_tv, &argv[0]);
16102 copy_tv(&(*(listitem_T **)s2)->li_tv, &argv[1]);
16104 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
16105 res = call_func(item_compare_func, (int)STRLEN(item_compare_func),
16106 &rettv, 2, argv, 0L, 0L, &dummy, TRUE, NULL);
16107 clear_tv(&argv[0]);
16108 clear_tv(&argv[1]);
16110 if (res == FAIL)
16111 res = ITEM_COMPARE_FAIL;
16112 else
16113 res = get_tv_number_chk(&rettv, &item_compare_func_err);
16114 if (item_compare_func_err)
16115 res = ITEM_COMPARE_FAIL; /* return value has wrong type */
16116 clear_tv(&rettv);
16117 return res;
16121 * "sort({list})" function
16123 static void
16124 f_sort(argvars, rettv)
16125 typval_T *argvars;
16126 typval_T *rettv;
16128 list_T *l;
16129 listitem_T *li;
16130 listitem_T **ptrs;
16131 long len;
16132 long i;
16134 if (argvars[0].v_type != VAR_LIST)
16135 EMSG2(_(e_listarg), "sort()");
16136 else
16138 l = argvars[0].vval.v_list;
16139 if (l == NULL || tv_check_lock(l->lv_lock, (char_u *)"sort()"))
16140 return;
16141 rettv->vval.v_list = l;
16142 rettv->v_type = VAR_LIST;
16143 ++l->lv_refcount;
16145 len = list_len(l);
16146 if (len <= 1)
16147 return; /* short list sorts pretty quickly */
16149 item_compare_ic = FALSE;
16150 item_compare_func = NULL;
16151 if (argvars[1].v_type != VAR_UNKNOWN)
16153 if (argvars[1].v_type == VAR_FUNC)
16154 item_compare_func = argvars[1].vval.v_string;
16155 else
16157 int error = FALSE;
16159 i = get_tv_number_chk(&argvars[1], &error);
16160 if (error)
16161 return; /* type error; errmsg already given */
16162 if (i == 1)
16163 item_compare_ic = TRUE;
16164 else
16165 item_compare_func = get_tv_string(&argvars[1]);
16169 /* Make an array with each entry pointing to an item in the List. */
16170 ptrs = (listitem_T **)alloc((int)(len * sizeof(listitem_T *)));
16171 if (ptrs == NULL)
16172 return;
16173 i = 0;
16174 for (li = l->lv_first; li != NULL; li = li->li_next)
16175 ptrs[i++] = li;
16177 item_compare_func_err = FALSE;
16178 /* test the compare function */
16179 if (item_compare_func != NULL
16180 && item_compare2((void *)&ptrs[0], (void *)&ptrs[1])
16181 == ITEM_COMPARE_FAIL)
16182 EMSG(_("E702: Sort compare function failed"));
16183 else
16185 /* Sort the array with item pointers. */
16186 qsort((void *)ptrs, (size_t)len, sizeof(listitem_T *),
16187 item_compare_func == NULL ? item_compare : item_compare2);
16189 if (!item_compare_func_err)
16191 /* Clear the List and append the items in the sorted order. */
16192 l->lv_first = l->lv_last = l->lv_idx_item = NULL;
16193 l->lv_len = 0;
16194 for (i = 0; i < len; ++i)
16195 list_append(l, ptrs[i]);
16199 vim_free(ptrs);
16204 * "soundfold({word})" function
16206 static void
16207 f_soundfold(argvars, rettv)
16208 typval_T *argvars;
16209 typval_T *rettv;
16211 char_u *s;
16213 rettv->v_type = VAR_STRING;
16214 s = get_tv_string(&argvars[0]);
16215 #ifdef FEAT_SPELL
16216 rettv->vval.v_string = eval_soundfold(s);
16217 #else
16218 rettv->vval.v_string = vim_strsave(s);
16219 #endif
16223 * "spellbadword()" function
16225 static void
16226 f_spellbadword(argvars, rettv)
16227 typval_T *argvars UNUSED;
16228 typval_T *rettv;
16230 char_u *word = (char_u *)"";
16231 hlf_T attr = HLF_COUNT;
16232 int len = 0;
16234 if (rettv_list_alloc(rettv) == FAIL)
16235 return;
16237 #ifdef FEAT_SPELL
16238 if (argvars[0].v_type == VAR_UNKNOWN)
16240 /* Find the start and length of the badly spelled word. */
16241 len = spell_move_to(curwin, FORWARD, TRUE, TRUE, &attr);
16242 if (len != 0)
16243 word = ml_get_cursor();
16245 else if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
16247 char_u *str = get_tv_string_chk(&argvars[0]);
16248 int capcol = -1;
16250 if (str != NULL)
16252 /* Check the argument for spelling. */
16253 while (*str != NUL)
16255 len = spell_check(curwin, str, &attr, &capcol, FALSE);
16256 if (attr != HLF_COUNT)
16258 word = str;
16259 break;
16261 str += len;
16265 #endif
16267 list_append_string(rettv->vval.v_list, word, len);
16268 list_append_string(rettv->vval.v_list, (char_u *)(
16269 attr == HLF_SPB ? "bad" :
16270 attr == HLF_SPR ? "rare" :
16271 attr == HLF_SPL ? "local" :
16272 attr == HLF_SPC ? "caps" :
16273 ""), -1);
16277 * "spellsuggest()" function
16279 static void
16280 f_spellsuggest(argvars, rettv)
16281 typval_T *argvars UNUSED;
16282 typval_T *rettv;
16284 #ifdef FEAT_SPELL
16285 char_u *str;
16286 int typeerr = FALSE;
16287 int maxcount;
16288 garray_T ga;
16289 int i;
16290 listitem_T *li;
16291 int need_capital = FALSE;
16292 #endif
16294 if (rettv_list_alloc(rettv) == FAIL)
16295 return;
16297 #ifdef FEAT_SPELL
16298 if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
16300 str = get_tv_string(&argvars[0]);
16301 if (argvars[1].v_type != VAR_UNKNOWN)
16303 maxcount = get_tv_number_chk(&argvars[1], &typeerr);
16304 if (maxcount <= 0)
16305 return;
16306 if (argvars[2].v_type != VAR_UNKNOWN)
16308 need_capital = get_tv_number_chk(&argvars[2], &typeerr);
16309 if (typeerr)
16310 return;
16313 else
16314 maxcount = 25;
16316 spell_suggest_list(&ga, str, maxcount, need_capital, FALSE);
16318 for (i = 0; i < ga.ga_len; ++i)
16320 str = ((char_u **)ga.ga_data)[i];
16322 li = listitem_alloc();
16323 if (li == NULL)
16324 vim_free(str);
16325 else
16327 li->li_tv.v_type = VAR_STRING;
16328 li->li_tv.v_lock = 0;
16329 li->li_tv.vval.v_string = str;
16330 list_append(rettv->vval.v_list, li);
16333 ga_clear(&ga);
16335 #endif
16338 static void
16339 f_split(argvars, rettv)
16340 typval_T *argvars;
16341 typval_T *rettv;
16343 char_u *str;
16344 char_u *end;
16345 char_u *pat = NULL;
16346 regmatch_T regmatch;
16347 char_u patbuf[NUMBUFLEN];
16348 char_u *save_cpo;
16349 int match;
16350 colnr_T col = 0;
16351 int keepempty = FALSE;
16352 int typeerr = FALSE;
16354 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
16355 save_cpo = p_cpo;
16356 p_cpo = (char_u *)"";
16358 str = get_tv_string(&argvars[0]);
16359 if (argvars[1].v_type != VAR_UNKNOWN)
16361 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
16362 if (pat == NULL)
16363 typeerr = TRUE;
16364 if (argvars[2].v_type != VAR_UNKNOWN)
16365 keepempty = get_tv_number_chk(&argvars[2], &typeerr);
16367 if (pat == NULL || *pat == NUL)
16368 pat = (char_u *)"[\\x01- ]\\+";
16370 if (rettv_list_alloc(rettv) == FAIL)
16371 return;
16372 if (typeerr)
16373 return;
16375 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
16376 if (regmatch.regprog != NULL)
16378 regmatch.rm_ic = FALSE;
16379 while (*str != NUL || keepempty)
16381 if (*str == NUL)
16382 match = FALSE; /* empty item at the end */
16383 else
16384 match = vim_regexec_nl(&regmatch, str, col);
16385 if (match)
16386 end = regmatch.startp[0];
16387 else
16388 end = str + STRLEN(str);
16389 if (keepempty || end > str || (rettv->vval.v_list->lv_len > 0
16390 && *str != NUL && match && end < regmatch.endp[0]))
16392 if (list_append_string(rettv->vval.v_list, str,
16393 (int)(end - str)) == FAIL)
16394 break;
16396 if (!match)
16397 break;
16398 /* Advance to just after the match. */
16399 if (regmatch.endp[0] > str)
16400 col = 0;
16401 else
16403 /* Don't get stuck at the same match. */
16404 #ifdef FEAT_MBYTE
16405 col = (*mb_ptr2len)(regmatch.endp[0]);
16406 #else
16407 col = 1;
16408 #endif
16410 str = regmatch.endp[0];
16413 vim_free(regmatch.regprog);
16416 p_cpo = save_cpo;
16419 #ifdef FEAT_FLOAT
16421 * "sqrt()" function
16423 static void
16424 f_sqrt(argvars, rettv)
16425 typval_T *argvars;
16426 typval_T *rettv;
16428 float_T f;
16430 rettv->v_type = VAR_FLOAT;
16431 if (get_float_arg(argvars, &f) == OK)
16432 rettv->vval.v_float = sqrt(f);
16433 else
16434 rettv->vval.v_float = 0.0;
16438 * "str2float()" function
16440 static void
16441 f_str2float(argvars, rettv)
16442 typval_T *argvars;
16443 typval_T *rettv;
16445 char_u *p = skipwhite(get_tv_string(&argvars[0]));
16447 if (*p == '+')
16448 p = skipwhite(p + 1);
16449 (void)string2float(p, &rettv->vval.v_float);
16450 rettv->v_type = VAR_FLOAT;
16452 #endif
16455 * "str2nr()" function
16457 static void
16458 f_str2nr(argvars, rettv)
16459 typval_T *argvars;
16460 typval_T *rettv;
16462 int base = 10;
16463 char_u *p;
16464 long n;
16466 if (argvars[1].v_type != VAR_UNKNOWN)
16468 base = get_tv_number(&argvars[1]);
16469 if (base != 8 && base != 10 && base != 16)
16471 EMSG(_(e_invarg));
16472 return;
16476 p = skipwhite(get_tv_string(&argvars[0]));
16477 if (*p == '+')
16478 p = skipwhite(p + 1);
16479 vim_str2nr(p, NULL, NULL, base == 8 ? 2 : 0, base == 16 ? 2 : 0, &n, NULL);
16480 rettv->vval.v_number = n;
16483 #ifdef HAVE_STRFTIME
16485 * "strftime({format}[, {time}])" function
16487 static void
16488 f_strftime(argvars, rettv)
16489 typval_T *argvars;
16490 typval_T *rettv;
16492 char_u result_buf[256];
16493 struct tm *curtime;
16494 time_t seconds;
16495 char_u *p;
16497 rettv->v_type = VAR_STRING;
16499 p = get_tv_string(&argvars[0]);
16500 if (argvars[1].v_type == VAR_UNKNOWN)
16501 seconds = time(NULL);
16502 else
16503 seconds = (time_t)get_tv_number(&argvars[1]);
16504 curtime = localtime(&seconds);
16505 /* MSVC returns NULL for an invalid value of seconds. */
16506 if (curtime == NULL)
16507 rettv->vval.v_string = vim_strsave((char_u *)_("(Invalid)"));
16508 else
16510 # ifdef FEAT_MBYTE
16511 vimconv_T conv;
16512 char_u *enc;
16514 conv.vc_type = CONV_NONE;
16515 enc = enc_locale();
16516 convert_setup(&conv, p_enc, enc);
16517 if (conv.vc_type != CONV_NONE)
16518 p = string_convert(&conv, p, NULL);
16519 # endif
16520 if (p != NULL)
16521 (void)strftime((char *)result_buf, sizeof(result_buf),
16522 (char *)p, curtime);
16523 else
16524 result_buf[0] = NUL;
16526 # ifdef FEAT_MBYTE
16527 if (conv.vc_type != CONV_NONE)
16528 vim_free(p);
16529 convert_setup(&conv, enc, p_enc);
16530 if (conv.vc_type != CONV_NONE)
16531 rettv->vval.v_string = string_convert(&conv, result_buf, NULL);
16532 else
16533 # endif
16534 rettv->vval.v_string = vim_strsave(result_buf);
16536 # ifdef FEAT_MBYTE
16537 /* Release conversion descriptors */
16538 convert_setup(&conv, NULL, NULL);
16539 vim_free(enc);
16540 # endif
16543 #endif
16546 * "stridx()" function
16548 static void
16549 f_stridx(argvars, rettv)
16550 typval_T *argvars;
16551 typval_T *rettv;
16553 char_u buf[NUMBUFLEN];
16554 char_u *needle;
16555 char_u *haystack;
16556 char_u *save_haystack;
16557 char_u *pos;
16558 int start_idx;
16560 needle = get_tv_string_chk(&argvars[1]);
16561 save_haystack = haystack = get_tv_string_buf_chk(&argvars[0], buf);
16562 rettv->vval.v_number = -1;
16563 if (needle == NULL || haystack == NULL)
16564 return; /* type error; errmsg already given */
16566 if (argvars[2].v_type != VAR_UNKNOWN)
16568 int error = FALSE;
16570 start_idx = get_tv_number_chk(&argvars[2], &error);
16571 if (error || start_idx >= (int)STRLEN(haystack))
16572 return;
16573 if (start_idx >= 0)
16574 haystack += start_idx;
16577 pos = (char_u *)strstr((char *)haystack, (char *)needle);
16578 if (pos != NULL)
16579 rettv->vval.v_number = (varnumber_T)(pos - save_haystack);
16583 * "string()" function
16585 static void
16586 f_string(argvars, rettv)
16587 typval_T *argvars;
16588 typval_T *rettv;
16590 char_u *tofree;
16591 char_u numbuf[NUMBUFLEN];
16593 rettv->v_type = VAR_STRING;
16594 rettv->vval.v_string = tv2string(&argvars[0], &tofree, numbuf, 0);
16595 /* Make a copy if we have a value but it's not in allocated memory. */
16596 if (rettv->vval.v_string != NULL && tofree == NULL)
16597 rettv->vval.v_string = vim_strsave(rettv->vval.v_string);
16601 * "strlen()" function
16603 static void
16604 f_strlen(argvars, rettv)
16605 typval_T *argvars;
16606 typval_T *rettv;
16608 rettv->vval.v_number = (varnumber_T)(STRLEN(
16609 get_tv_string(&argvars[0])));
16613 * "strpart()" function
16615 static void
16616 f_strpart(argvars, rettv)
16617 typval_T *argvars;
16618 typval_T *rettv;
16620 char_u *p;
16621 int n;
16622 int len;
16623 int slen;
16624 int error = FALSE;
16626 p = get_tv_string(&argvars[0]);
16627 slen = (int)STRLEN(p);
16629 n = get_tv_number_chk(&argvars[1], &error);
16630 if (error)
16631 len = 0;
16632 else if (argvars[2].v_type != VAR_UNKNOWN)
16633 len = get_tv_number(&argvars[2]);
16634 else
16635 len = slen - n; /* default len: all bytes that are available. */
16638 * Only return the overlap between the specified part and the actual
16639 * string.
16641 if (n < 0)
16643 len += n;
16644 n = 0;
16646 else if (n > slen)
16647 n = slen;
16648 if (len < 0)
16649 len = 0;
16650 else if (n + len > slen)
16651 len = slen - n;
16653 rettv->v_type = VAR_STRING;
16654 rettv->vval.v_string = vim_strnsave(p + n, len);
16658 * "strridx()" function
16660 static void
16661 f_strridx(argvars, rettv)
16662 typval_T *argvars;
16663 typval_T *rettv;
16665 char_u buf[NUMBUFLEN];
16666 char_u *needle;
16667 char_u *haystack;
16668 char_u *rest;
16669 char_u *lastmatch = NULL;
16670 int haystack_len, end_idx;
16672 needle = get_tv_string_chk(&argvars[1]);
16673 haystack = get_tv_string_buf_chk(&argvars[0], buf);
16675 rettv->vval.v_number = -1;
16676 if (needle == NULL || haystack == NULL)
16677 return; /* type error; errmsg already given */
16679 haystack_len = (int)STRLEN(haystack);
16680 if (argvars[2].v_type != VAR_UNKNOWN)
16682 /* Third argument: upper limit for index */
16683 end_idx = get_tv_number_chk(&argvars[2], NULL);
16684 if (end_idx < 0)
16685 return; /* can never find a match */
16687 else
16688 end_idx = haystack_len;
16690 if (*needle == NUL)
16692 /* Empty string matches past the end. */
16693 lastmatch = haystack + end_idx;
16695 else
16697 for (rest = haystack; *rest != '\0'; ++rest)
16699 rest = (char_u *)strstr((char *)rest, (char *)needle);
16700 if (rest == NULL || rest > haystack + end_idx)
16701 break;
16702 lastmatch = rest;
16706 if (lastmatch == NULL)
16707 rettv->vval.v_number = -1;
16708 else
16709 rettv->vval.v_number = (varnumber_T)(lastmatch - haystack);
16713 * "strtrans()" function
16715 static void
16716 f_strtrans(argvars, rettv)
16717 typval_T *argvars;
16718 typval_T *rettv;
16720 rettv->v_type = VAR_STRING;
16721 rettv->vval.v_string = transstr(get_tv_string(&argvars[0]));
16725 * "submatch()" function
16727 static void
16728 f_submatch(argvars, rettv)
16729 typval_T *argvars;
16730 typval_T *rettv;
16732 rettv->v_type = VAR_STRING;
16733 rettv->vval.v_string =
16734 reg_submatch((int)get_tv_number_chk(&argvars[0], NULL));
16738 * "substitute()" function
16740 static void
16741 f_substitute(argvars, rettv)
16742 typval_T *argvars;
16743 typval_T *rettv;
16745 char_u patbuf[NUMBUFLEN];
16746 char_u subbuf[NUMBUFLEN];
16747 char_u flagsbuf[NUMBUFLEN];
16749 char_u *str = get_tv_string_chk(&argvars[0]);
16750 char_u *pat = get_tv_string_buf_chk(&argvars[1], patbuf);
16751 char_u *sub = get_tv_string_buf_chk(&argvars[2], subbuf);
16752 char_u *flg = get_tv_string_buf_chk(&argvars[3], flagsbuf);
16754 rettv->v_type = VAR_STRING;
16755 if (str == NULL || pat == NULL || sub == NULL || flg == NULL)
16756 rettv->vval.v_string = NULL;
16757 else
16758 rettv->vval.v_string = do_string_sub(str, pat, sub, flg);
16762 * "synID(lnum, col, trans)" function
16764 static void
16765 f_synID(argvars, rettv)
16766 typval_T *argvars UNUSED;
16767 typval_T *rettv;
16769 int id = 0;
16770 #ifdef FEAT_SYN_HL
16771 long lnum;
16772 long col;
16773 int trans;
16774 int transerr = FALSE;
16776 lnum = get_tv_lnum(argvars); /* -1 on type error */
16777 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
16778 trans = get_tv_number_chk(&argvars[2], &transerr);
16780 if (!transerr && lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
16781 && col >= 0 && col < (long)STRLEN(ml_get(lnum)))
16782 id = syn_get_id(curwin, lnum, (colnr_T)col, trans, NULL, FALSE);
16783 #endif
16785 rettv->vval.v_number = id;
16789 * "synIDattr(id, what [, mode])" function
16791 static void
16792 f_synIDattr(argvars, rettv)
16793 typval_T *argvars UNUSED;
16794 typval_T *rettv;
16796 char_u *p = NULL;
16797 #ifdef FEAT_SYN_HL
16798 int id;
16799 char_u *what;
16800 char_u *mode;
16801 char_u modebuf[NUMBUFLEN];
16802 int modec;
16804 id = get_tv_number(&argvars[0]);
16805 what = get_tv_string(&argvars[1]);
16806 if (argvars[2].v_type != VAR_UNKNOWN)
16808 mode = get_tv_string_buf(&argvars[2], modebuf);
16809 modec = TOLOWER_ASC(mode[0]);
16810 if (modec != 't' && modec != 'c'
16811 #ifdef FEAT_GUI
16812 && modec != 'g'
16813 #endif
16815 modec = 0; /* replace invalid with current */
16817 else
16819 #ifdef FEAT_GUI
16820 if (gui.in_use)
16821 modec = 'g';
16822 else
16823 #endif
16824 if (t_colors > 1)
16825 modec = 'c';
16826 else
16827 modec = 't';
16831 switch (TOLOWER_ASC(what[0]))
16833 case 'b':
16834 if (TOLOWER_ASC(what[1]) == 'g') /* bg[#] */
16835 p = highlight_color(id, what, modec);
16836 else /* bold */
16837 p = highlight_has_attr(id, HL_BOLD, modec);
16838 break;
16840 case 'f': /* fg[#] or font */
16841 p = highlight_color(id, what, modec);
16842 break;
16844 case 'i':
16845 if (TOLOWER_ASC(what[1]) == 'n') /* inverse */
16846 p = highlight_has_attr(id, HL_INVERSE, modec);
16847 else /* italic */
16848 p = highlight_has_attr(id, HL_ITALIC, modec);
16849 break;
16851 case 'n': /* name */
16852 p = get_highlight_name(NULL, id - 1);
16853 break;
16855 case 'r': /* reverse */
16856 p = highlight_has_attr(id, HL_INVERSE, modec);
16857 break;
16859 case 's':
16860 if (TOLOWER_ASC(what[1]) == 'p') /* sp[#] */
16861 p = highlight_color(id, what, modec);
16862 else /* standout */
16863 p = highlight_has_attr(id, HL_STANDOUT, modec);
16864 break;
16866 case 'u':
16867 if (STRLEN(what) <= 5 || TOLOWER_ASC(what[5]) != 'c')
16868 /* underline */
16869 p = highlight_has_attr(id, HL_UNDERLINE, modec);
16870 else
16871 /* undercurl */
16872 p = highlight_has_attr(id, HL_UNDERCURL, modec);
16873 break;
16876 if (p != NULL)
16877 p = vim_strsave(p);
16878 #endif
16879 rettv->v_type = VAR_STRING;
16880 rettv->vval.v_string = p;
16884 * "synIDtrans(id)" function
16886 static void
16887 f_synIDtrans(argvars, rettv)
16888 typval_T *argvars UNUSED;
16889 typval_T *rettv;
16891 int id;
16893 #ifdef FEAT_SYN_HL
16894 id = get_tv_number(&argvars[0]);
16896 if (id > 0)
16897 id = syn_get_final_id(id);
16898 else
16899 #endif
16900 id = 0;
16902 rettv->vval.v_number = id;
16906 * "synstack(lnum, col)" function
16908 static void
16909 f_synstack(argvars, rettv)
16910 typval_T *argvars UNUSED;
16911 typval_T *rettv;
16913 #ifdef FEAT_SYN_HL
16914 long lnum;
16915 long col;
16916 int i;
16917 int id;
16918 #endif
16920 rettv->v_type = VAR_LIST;
16921 rettv->vval.v_list = NULL;
16923 #ifdef FEAT_SYN_HL
16924 lnum = get_tv_lnum(argvars); /* -1 on type error */
16925 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
16927 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
16928 && col >= 0 && (col == 0 || col < (long)STRLEN(ml_get(lnum)))
16929 && rettv_list_alloc(rettv) != FAIL)
16931 (void)syn_get_id(curwin, lnum, (colnr_T)col, FALSE, NULL, TRUE);
16932 for (i = 0; ; ++i)
16934 id = syn_get_stack_item(i);
16935 if (id < 0)
16936 break;
16937 if (list_append_number(rettv->vval.v_list, id) == FAIL)
16938 break;
16941 #endif
16945 * "system()" function
16947 static void
16948 f_system(argvars, rettv)
16949 typval_T *argvars;
16950 typval_T *rettv;
16952 char_u *res = NULL;
16953 char_u *p;
16954 char_u *infile = NULL;
16955 char_u buf[NUMBUFLEN];
16956 int err = FALSE;
16957 FILE *fd;
16959 if (check_restricted() || check_secure())
16960 goto done;
16962 if (argvars[1].v_type != VAR_UNKNOWN)
16965 * Write the string to a temp file, to be used for input of the shell
16966 * command.
16968 if ((infile = vim_tempname('i')) == NULL)
16970 EMSG(_(e_notmp));
16971 goto done;
16974 fd = mch_fopen((char *)infile, WRITEBIN);
16975 if (fd == NULL)
16977 EMSG2(_(e_notopen), infile);
16978 goto done;
16980 p = get_tv_string_buf_chk(&argvars[1], buf);
16981 if (p == NULL)
16983 fclose(fd);
16984 goto done; /* type error; errmsg already given */
16986 if (fwrite(p, STRLEN(p), 1, fd) != 1)
16987 err = TRUE;
16988 if (fclose(fd) != 0)
16989 err = TRUE;
16990 if (err)
16992 EMSG(_("E677: Error writing temp file"));
16993 goto done;
16997 res = get_cmd_output(get_tv_string(&argvars[0]), infile,
16998 SHELL_SILENT | SHELL_COOKED);
17000 #ifdef USE_CR
17001 /* translate <CR> into <NL> */
17002 if (res != NULL)
17004 char_u *s;
17006 for (s = res; *s; ++s)
17008 if (*s == CAR)
17009 *s = NL;
17012 #else
17013 # ifdef USE_CRNL
17014 /* translate <CR><NL> into <NL> */
17015 if (res != NULL)
17017 char_u *s, *d;
17019 d = res;
17020 for (s = res; *s; ++s)
17022 if (s[0] == CAR && s[1] == NL)
17023 ++s;
17024 *d++ = *s;
17026 *d = NUL;
17028 # endif
17029 #endif
17031 done:
17032 if (infile != NULL)
17034 mch_remove(infile);
17035 vim_free(infile);
17037 rettv->v_type = VAR_STRING;
17038 rettv->vval.v_string = res;
17042 * "tabpagebuflist()" function
17044 static void
17045 f_tabpagebuflist(argvars, rettv)
17046 typval_T *argvars UNUSED;
17047 typval_T *rettv UNUSED;
17049 #ifdef FEAT_WINDOWS
17050 tabpage_T *tp;
17051 win_T *wp = NULL;
17053 if (argvars[0].v_type == VAR_UNKNOWN)
17054 wp = firstwin;
17055 else
17057 tp = find_tabpage((int)get_tv_number(&argvars[0]));
17058 if (tp != NULL)
17059 wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
17061 if (wp != NULL && rettv_list_alloc(rettv) != FAIL)
17063 for (; wp != NULL; wp = wp->w_next)
17064 if (list_append_number(rettv->vval.v_list,
17065 wp->w_buffer->b_fnum) == FAIL)
17066 break;
17068 #endif
17073 * "tabpagenr()" function
17075 static void
17076 f_tabpagenr(argvars, rettv)
17077 typval_T *argvars UNUSED;
17078 typval_T *rettv;
17080 int nr = 1;
17081 #ifdef FEAT_WINDOWS
17082 char_u *arg;
17084 if (argvars[0].v_type != VAR_UNKNOWN)
17086 arg = get_tv_string_chk(&argvars[0]);
17087 nr = 0;
17088 if (arg != NULL)
17090 if (STRCMP(arg, "$") == 0)
17091 nr = tabpage_index(NULL) - 1;
17092 else
17093 EMSG2(_(e_invexpr2), arg);
17096 else
17097 nr = tabpage_index(curtab);
17098 #endif
17099 rettv->vval.v_number = nr;
17103 #ifdef FEAT_WINDOWS
17104 static int get_winnr __ARGS((tabpage_T *tp, typval_T *argvar));
17107 * Common code for tabpagewinnr() and winnr().
17109 static int
17110 get_winnr(tp, argvar)
17111 tabpage_T *tp;
17112 typval_T *argvar;
17114 win_T *twin;
17115 int nr = 1;
17116 win_T *wp;
17117 char_u *arg;
17119 twin = (tp == curtab) ? curwin : tp->tp_curwin;
17120 if (argvar->v_type != VAR_UNKNOWN)
17122 arg = get_tv_string_chk(argvar);
17123 if (arg == NULL)
17124 nr = 0; /* type error; errmsg already given */
17125 else if (STRCMP(arg, "$") == 0)
17126 twin = (tp == curtab) ? lastwin : tp->tp_lastwin;
17127 else if (STRCMP(arg, "#") == 0)
17129 twin = (tp == curtab) ? prevwin : tp->tp_prevwin;
17130 if (twin == NULL)
17131 nr = 0;
17133 else
17135 EMSG2(_(e_invexpr2), arg);
17136 nr = 0;
17140 if (nr > 0)
17141 for (wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
17142 wp != twin; wp = wp->w_next)
17144 if (wp == NULL)
17146 /* didn't find it in this tabpage */
17147 nr = 0;
17148 break;
17150 ++nr;
17152 return nr;
17154 #endif
17157 * "tabpagewinnr()" function
17159 static void
17160 f_tabpagewinnr(argvars, rettv)
17161 typval_T *argvars UNUSED;
17162 typval_T *rettv;
17164 int nr = 1;
17165 #ifdef FEAT_WINDOWS
17166 tabpage_T *tp;
17168 tp = find_tabpage((int)get_tv_number(&argvars[0]));
17169 if (tp == NULL)
17170 nr = 0;
17171 else
17172 nr = get_winnr(tp, &argvars[1]);
17173 #endif
17174 rettv->vval.v_number = nr;
17179 * "tagfiles()" function
17181 static void
17182 f_tagfiles(argvars, rettv)
17183 typval_T *argvars UNUSED;
17184 typval_T *rettv;
17186 char_u fname[MAXPATHL + 1];
17187 tagname_T tn;
17188 int first;
17190 if (rettv_list_alloc(rettv) == FAIL)
17191 return;
17193 for (first = TRUE; ; first = FALSE)
17194 if (get_tagfname(&tn, first, fname) == FAIL
17195 || list_append_string(rettv->vval.v_list, fname, -1) == FAIL)
17196 break;
17197 tagname_free(&tn);
17201 * "taglist()" function
17203 static void
17204 f_taglist(argvars, rettv)
17205 typval_T *argvars;
17206 typval_T *rettv;
17208 char_u *tag_pattern;
17210 tag_pattern = get_tv_string(&argvars[0]);
17212 rettv->vval.v_number = FALSE;
17213 if (*tag_pattern == NUL)
17214 return;
17216 if (rettv_list_alloc(rettv) == OK)
17217 (void)get_tags(rettv->vval.v_list, tag_pattern);
17221 * "tempname()" function
17223 static void
17224 f_tempname(argvars, rettv)
17225 typval_T *argvars UNUSED;
17226 typval_T *rettv;
17228 static int x = 'A';
17230 rettv->v_type = VAR_STRING;
17231 rettv->vval.v_string = vim_tempname(x);
17233 /* Advance 'x' to use A-Z and 0-9, so that there are at least 34 different
17234 * names. Skip 'I' and 'O', they are used for shell redirection. */
17237 if (x == 'Z')
17238 x = '0';
17239 else if (x == '9')
17240 x = 'A';
17241 else
17243 #ifdef EBCDIC
17244 if (x == 'I')
17245 x = 'J';
17246 else if (x == 'R')
17247 x = 'S';
17248 else
17249 #endif
17250 ++x;
17252 } while (x == 'I' || x == 'O');
17256 * "test(list)" function: Just checking the walls...
17258 static void
17259 f_test(argvars, rettv)
17260 typval_T *argvars UNUSED;
17261 typval_T *rettv UNUSED;
17263 /* Used for unit testing. Change the code below to your liking. */
17264 #if 0
17265 listitem_T *li;
17266 list_T *l;
17267 char_u *bad, *good;
17269 if (argvars[0].v_type != VAR_LIST)
17270 return;
17271 l = argvars[0].vval.v_list;
17272 if (l == NULL)
17273 return;
17274 li = l->lv_first;
17275 if (li == NULL)
17276 return;
17277 bad = get_tv_string(&li->li_tv);
17278 li = li->li_next;
17279 if (li == NULL)
17280 return;
17281 good = get_tv_string(&li->li_tv);
17282 rettv->vval.v_number = test_edit_score(bad, good);
17283 #endif
17287 * "tolower(string)" function
17289 static void
17290 f_tolower(argvars, rettv)
17291 typval_T *argvars;
17292 typval_T *rettv;
17294 char_u *p;
17296 p = vim_strsave(get_tv_string(&argvars[0]));
17297 rettv->v_type = VAR_STRING;
17298 rettv->vval.v_string = p;
17300 if (p != NULL)
17301 while (*p != NUL)
17303 #ifdef FEAT_MBYTE
17304 int l;
17306 if (enc_utf8)
17308 int c, lc;
17310 c = utf_ptr2char(p);
17311 lc = utf_tolower(c);
17312 l = utf_ptr2len(p);
17313 /* TODO: reallocate string when byte count changes. */
17314 if (utf_char2len(lc) == l)
17315 utf_char2bytes(lc, p);
17316 p += l;
17318 else if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
17319 p += l; /* skip multi-byte character */
17320 else
17321 #endif
17323 *p = TOLOWER_LOC(*p); /* note that tolower() can be a macro */
17324 ++p;
17330 * "toupper(string)" function
17332 static void
17333 f_toupper(argvars, rettv)
17334 typval_T *argvars;
17335 typval_T *rettv;
17337 rettv->v_type = VAR_STRING;
17338 rettv->vval.v_string = strup_save(get_tv_string(&argvars[0]));
17342 * "tr(string, fromstr, tostr)" function
17344 static void
17345 f_tr(argvars, rettv)
17346 typval_T *argvars;
17347 typval_T *rettv;
17349 char_u *instr;
17350 char_u *fromstr;
17351 char_u *tostr;
17352 char_u *p;
17353 #ifdef FEAT_MBYTE
17354 int inlen;
17355 int fromlen;
17356 int tolen;
17357 int idx;
17358 char_u *cpstr;
17359 int cplen;
17360 int first = TRUE;
17361 #endif
17362 char_u buf[NUMBUFLEN];
17363 char_u buf2[NUMBUFLEN];
17364 garray_T ga;
17366 instr = get_tv_string(&argvars[0]);
17367 fromstr = get_tv_string_buf_chk(&argvars[1], buf);
17368 tostr = get_tv_string_buf_chk(&argvars[2], buf2);
17370 /* Default return value: empty string. */
17371 rettv->v_type = VAR_STRING;
17372 rettv->vval.v_string = NULL;
17373 if (fromstr == NULL || tostr == NULL)
17374 return; /* type error; errmsg already given */
17375 ga_init2(&ga, (int)sizeof(char), 80);
17377 #ifdef FEAT_MBYTE
17378 if (!has_mbyte)
17379 #endif
17380 /* not multi-byte: fromstr and tostr must be the same length */
17381 if (STRLEN(fromstr) != STRLEN(tostr))
17383 #ifdef FEAT_MBYTE
17384 error:
17385 #endif
17386 EMSG2(_(e_invarg2), fromstr);
17387 ga_clear(&ga);
17388 return;
17391 /* fromstr and tostr have to contain the same number of chars */
17392 while (*instr != NUL)
17394 #ifdef FEAT_MBYTE
17395 if (has_mbyte)
17397 inlen = (*mb_ptr2len)(instr);
17398 cpstr = instr;
17399 cplen = inlen;
17400 idx = 0;
17401 for (p = fromstr; *p != NUL; p += fromlen)
17403 fromlen = (*mb_ptr2len)(p);
17404 if (fromlen == inlen && STRNCMP(instr, p, inlen) == 0)
17406 for (p = tostr; *p != NUL; p += tolen)
17408 tolen = (*mb_ptr2len)(p);
17409 if (idx-- == 0)
17411 cplen = tolen;
17412 cpstr = p;
17413 break;
17416 if (*p == NUL) /* tostr is shorter than fromstr */
17417 goto error;
17418 break;
17420 ++idx;
17423 if (first && cpstr == instr)
17425 /* Check that fromstr and tostr have the same number of
17426 * (multi-byte) characters. Done only once when a character
17427 * of instr doesn't appear in fromstr. */
17428 first = FALSE;
17429 for (p = tostr; *p != NUL; p += tolen)
17431 tolen = (*mb_ptr2len)(p);
17432 --idx;
17434 if (idx != 0)
17435 goto error;
17438 ga_grow(&ga, cplen);
17439 mch_memmove((char *)ga.ga_data + ga.ga_len, cpstr, (size_t)cplen);
17440 ga.ga_len += cplen;
17442 instr += inlen;
17444 else
17445 #endif
17447 /* When not using multi-byte chars we can do it faster. */
17448 p = vim_strchr(fromstr, *instr);
17449 if (p != NULL)
17450 ga_append(&ga, tostr[p - fromstr]);
17451 else
17452 ga_append(&ga, *instr);
17453 ++instr;
17457 /* add a terminating NUL */
17458 ga_grow(&ga, 1);
17459 ga_append(&ga, NUL);
17461 rettv->vval.v_string = ga.ga_data;
17464 #ifdef FEAT_FLOAT
17466 * "trunc({float})" function
17468 static void
17469 f_trunc(argvars, rettv)
17470 typval_T *argvars;
17471 typval_T *rettv;
17473 float_T f;
17475 rettv->v_type = VAR_FLOAT;
17476 if (get_float_arg(argvars, &f) == OK)
17477 /* trunc() is not in C90, use floor() or ceil() instead. */
17478 rettv->vval.v_float = f > 0 ? floor(f) : ceil(f);
17479 else
17480 rettv->vval.v_float = 0.0;
17482 #endif
17485 * "type(expr)" function
17487 static void
17488 f_type(argvars, rettv)
17489 typval_T *argvars;
17490 typval_T *rettv;
17492 int n;
17494 switch (argvars[0].v_type)
17496 case VAR_NUMBER: n = 0; break;
17497 case VAR_STRING: n = 1; break;
17498 case VAR_FUNC: n = 2; break;
17499 case VAR_LIST: n = 3; break;
17500 case VAR_DICT: n = 4; break;
17501 #ifdef FEAT_FLOAT
17502 case VAR_FLOAT: n = 5; break;
17503 #endif
17504 default: EMSG2(_(e_intern2), "f_type()"); n = 0; break;
17506 rettv->vval.v_number = n;
17510 * "values(dict)" function
17512 static void
17513 f_values(argvars, rettv)
17514 typval_T *argvars;
17515 typval_T *rettv;
17517 dict_list(argvars, rettv, 1);
17521 * "virtcol(string)" function
17523 static void
17524 f_virtcol(argvars, rettv)
17525 typval_T *argvars;
17526 typval_T *rettv;
17528 colnr_T vcol = 0;
17529 pos_T *fp;
17530 int fnum = curbuf->b_fnum;
17532 fp = var2fpos(&argvars[0], FALSE, &fnum);
17533 if (fp != NULL && fp->lnum <= curbuf->b_ml.ml_line_count
17534 && fnum == curbuf->b_fnum)
17536 getvvcol(curwin, fp, NULL, NULL, &vcol);
17537 ++vcol;
17540 rettv->vval.v_number = vcol;
17544 * "visualmode()" function
17546 static void
17547 f_visualmode(argvars, rettv)
17548 typval_T *argvars UNUSED;
17549 typval_T *rettv UNUSED;
17551 #ifdef FEAT_VISUAL
17552 char_u str[2];
17554 rettv->v_type = VAR_STRING;
17555 str[0] = curbuf->b_visual_mode_eval;
17556 str[1] = NUL;
17557 rettv->vval.v_string = vim_strsave(str);
17559 /* A non-zero number or non-empty string argument: reset mode. */
17560 if (non_zero_arg(&argvars[0]))
17561 curbuf->b_visual_mode_eval = NUL;
17562 #endif
17566 * "winbufnr(nr)" function
17568 static void
17569 f_winbufnr(argvars, rettv)
17570 typval_T *argvars;
17571 typval_T *rettv;
17573 win_T *wp;
17575 wp = find_win_by_nr(&argvars[0], NULL);
17576 if (wp == NULL)
17577 rettv->vval.v_number = -1;
17578 else
17579 rettv->vval.v_number = wp->w_buffer->b_fnum;
17583 * "wincol()" function
17585 static void
17586 f_wincol(argvars, rettv)
17587 typval_T *argvars UNUSED;
17588 typval_T *rettv;
17590 validate_cursor();
17591 rettv->vval.v_number = curwin->w_wcol + 1;
17595 * "winheight(nr)" function
17597 static void
17598 f_winheight(argvars, rettv)
17599 typval_T *argvars;
17600 typval_T *rettv;
17602 win_T *wp;
17604 wp = find_win_by_nr(&argvars[0], NULL);
17605 if (wp == NULL)
17606 rettv->vval.v_number = -1;
17607 else
17608 rettv->vval.v_number = wp->w_height;
17612 * "winline()" function
17614 static void
17615 f_winline(argvars, rettv)
17616 typval_T *argvars UNUSED;
17617 typval_T *rettv;
17619 validate_cursor();
17620 rettv->vval.v_number = curwin->w_wrow + 1;
17624 * "winnr()" function
17626 static void
17627 f_winnr(argvars, rettv)
17628 typval_T *argvars UNUSED;
17629 typval_T *rettv;
17631 int nr = 1;
17633 #ifdef FEAT_WINDOWS
17634 nr = get_winnr(curtab, &argvars[0]);
17635 #endif
17636 rettv->vval.v_number = nr;
17640 * "winrestcmd()" function
17642 static void
17643 f_winrestcmd(argvars, rettv)
17644 typval_T *argvars UNUSED;
17645 typval_T *rettv;
17647 #ifdef FEAT_WINDOWS
17648 win_T *wp;
17649 int winnr = 1;
17650 garray_T ga;
17651 char_u buf[50];
17653 ga_init2(&ga, (int)sizeof(char), 70);
17654 for (wp = firstwin; wp != NULL; wp = wp->w_next)
17656 sprintf((char *)buf, "%dresize %d|", winnr, wp->w_height);
17657 ga_concat(&ga, buf);
17658 # ifdef FEAT_VERTSPLIT
17659 sprintf((char *)buf, "vert %dresize %d|", winnr, wp->w_width);
17660 ga_concat(&ga, buf);
17661 # endif
17662 ++winnr;
17664 ga_append(&ga, NUL);
17666 rettv->vval.v_string = ga.ga_data;
17667 #else
17668 rettv->vval.v_string = NULL;
17669 #endif
17670 rettv->v_type = VAR_STRING;
17674 * "winrestview()" function
17676 static void
17677 f_winrestview(argvars, rettv)
17678 typval_T *argvars;
17679 typval_T *rettv UNUSED;
17681 dict_T *dict;
17683 if (argvars[0].v_type != VAR_DICT
17684 || (dict = argvars[0].vval.v_dict) == NULL)
17685 EMSG(_(e_invarg));
17686 else
17688 curwin->w_cursor.lnum = get_dict_number(dict, (char_u *)"lnum");
17689 curwin->w_cursor.col = get_dict_number(dict, (char_u *)"col");
17690 #ifdef FEAT_VIRTUALEDIT
17691 curwin->w_cursor.coladd = get_dict_number(dict, (char_u *)"coladd");
17692 #endif
17693 curwin->w_curswant = get_dict_number(dict, (char_u *)"curswant");
17694 curwin->w_set_curswant = FALSE;
17696 set_topline(curwin, get_dict_number(dict, (char_u *)"topline"));
17697 #ifdef FEAT_DIFF
17698 curwin->w_topfill = get_dict_number(dict, (char_u *)"topfill");
17699 #endif
17700 curwin->w_leftcol = get_dict_number(dict, (char_u *)"leftcol");
17701 curwin->w_skipcol = get_dict_number(dict, (char_u *)"skipcol");
17703 check_cursor();
17704 changed_cline_bef_curs();
17705 invalidate_botline();
17706 redraw_later(VALID);
17708 if (curwin->w_topline == 0)
17709 curwin->w_topline = 1;
17710 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
17711 curwin->w_topline = curbuf->b_ml.ml_line_count;
17712 #ifdef FEAT_DIFF
17713 check_topfill(curwin, TRUE);
17714 #endif
17719 * "winsaveview()" function
17721 static void
17722 f_winsaveview(argvars, rettv)
17723 typval_T *argvars UNUSED;
17724 typval_T *rettv;
17726 dict_T *dict;
17728 dict = dict_alloc();
17729 if (dict == NULL)
17730 return;
17731 rettv->v_type = VAR_DICT;
17732 rettv->vval.v_dict = dict;
17733 ++dict->dv_refcount;
17735 dict_add_nr_str(dict, "lnum", (long)curwin->w_cursor.lnum, NULL);
17736 dict_add_nr_str(dict, "col", (long)curwin->w_cursor.col, NULL);
17737 #ifdef FEAT_VIRTUALEDIT
17738 dict_add_nr_str(dict, "coladd", (long)curwin->w_cursor.coladd, NULL);
17739 #endif
17740 update_curswant();
17741 dict_add_nr_str(dict, "curswant", (long)curwin->w_curswant, NULL);
17743 dict_add_nr_str(dict, "topline", (long)curwin->w_topline, NULL);
17744 #ifdef FEAT_DIFF
17745 dict_add_nr_str(dict, "topfill", (long)curwin->w_topfill, NULL);
17746 #endif
17747 dict_add_nr_str(dict, "leftcol", (long)curwin->w_leftcol, NULL);
17748 dict_add_nr_str(dict, "skipcol", (long)curwin->w_skipcol, NULL);
17752 * "winwidth(nr)" function
17754 static void
17755 f_winwidth(argvars, rettv)
17756 typval_T *argvars;
17757 typval_T *rettv;
17759 win_T *wp;
17761 wp = find_win_by_nr(&argvars[0], NULL);
17762 if (wp == NULL)
17763 rettv->vval.v_number = -1;
17764 else
17765 #ifdef FEAT_VERTSPLIT
17766 rettv->vval.v_number = wp->w_width;
17767 #else
17768 rettv->vval.v_number = Columns;
17769 #endif
17773 * "writefile()" function
17775 static void
17776 f_writefile(argvars, rettv)
17777 typval_T *argvars;
17778 typval_T *rettv;
17780 int binary = FALSE;
17781 char_u *fname;
17782 FILE *fd;
17783 listitem_T *li;
17784 char_u *s;
17785 int ret = 0;
17786 int c;
17788 if (check_restricted() || check_secure())
17789 return;
17791 if (argvars[0].v_type != VAR_LIST)
17793 EMSG2(_(e_listarg), "writefile()");
17794 return;
17796 if (argvars[0].vval.v_list == NULL)
17797 return;
17799 if (argvars[2].v_type != VAR_UNKNOWN
17800 && STRCMP(get_tv_string(&argvars[2]), "b") == 0)
17801 binary = TRUE;
17803 /* Always open the file in binary mode, library functions have a mind of
17804 * their own about CR-LF conversion. */
17805 fname = get_tv_string(&argvars[1]);
17806 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
17808 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
17809 ret = -1;
17811 else
17813 for (li = argvars[0].vval.v_list->lv_first; li != NULL;
17814 li = li->li_next)
17816 for (s = get_tv_string(&li->li_tv); *s != NUL; ++s)
17818 if (*s == '\n')
17819 c = putc(NUL, fd);
17820 else
17821 c = putc(*s, fd);
17822 if (c == EOF)
17824 ret = -1;
17825 break;
17828 if (!binary || li->li_next != NULL)
17829 if (putc('\n', fd) == EOF)
17831 ret = -1;
17832 break;
17834 if (ret < 0)
17836 EMSG(_(e_write));
17837 break;
17840 fclose(fd);
17843 rettv->vval.v_number = ret;
17847 * Translate a String variable into a position.
17848 * Returns NULL when there is an error.
17850 static pos_T *
17851 var2fpos(varp, dollar_lnum, fnum)
17852 typval_T *varp;
17853 int dollar_lnum; /* TRUE when $ is last line */
17854 int *fnum; /* set to fnum for '0, 'A, etc. */
17856 char_u *name;
17857 static pos_T pos;
17858 pos_T *pp;
17860 /* Argument can be [lnum, col, coladd]. */
17861 if (varp->v_type == VAR_LIST)
17863 list_T *l;
17864 int len;
17865 int error = FALSE;
17866 listitem_T *li;
17868 l = varp->vval.v_list;
17869 if (l == NULL)
17870 return NULL;
17872 /* Get the line number */
17873 pos.lnum = list_find_nr(l, 0L, &error);
17874 if (error || pos.lnum <= 0 || pos.lnum > curbuf->b_ml.ml_line_count)
17875 return NULL; /* invalid line number */
17877 /* Get the column number */
17878 pos.col = list_find_nr(l, 1L, &error);
17879 if (error)
17880 return NULL;
17881 len = (long)STRLEN(ml_get(pos.lnum));
17883 /* We accept "$" for the column number: last column. */
17884 li = list_find(l, 1L);
17885 if (li != NULL && li->li_tv.v_type == VAR_STRING
17886 && li->li_tv.vval.v_string != NULL
17887 && STRCMP(li->li_tv.vval.v_string, "$") == 0)
17888 pos.col = len + 1;
17890 /* Accept a position up to the NUL after the line. */
17891 if (pos.col == 0 || (int)pos.col > len + 1)
17892 return NULL; /* invalid column number */
17893 --pos.col;
17895 #ifdef FEAT_VIRTUALEDIT
17896 /* Get the virtual offset. Defaults to zero. */
17897 pos.coladd = list_find_nr(l, 2L, &error);
17898 if (error)
17899 pos.coladd = 0;
17900 #endif
17902 return &pos;
17905 name = get_tv_string_chk(varp);
17906 if (name == NULL)
17907 return NULL;
17908 if (name[0] == '.') /* cursor */
17909 return &curwin->w_cursor;
17910 #ifdef FEAT_VISUAL
17911 if (name[0] == 'v' && name[1] == NUL) /* Visual start */
17913 if (VIsual_active)
17914 return &VIsual;
17915 return &curwin->w_cursor;
17917 #endif
17918 if (name[0] == '\'') /* mark */
17920 pp = getmark_fnum(name[1], FALSE, fnum);
17921 if (pp == NULL || pp == (pos_T *)-1 || pp->lnum <= 0)
17922 return NULL;
17923 return pp;
17926 #ifdef FEAT_VIRTUALEDIT
17927 pos.coladd = 0;
17928 #endif
17930 if (name[0] == 'w' && dollar_lnum)
17932 pos.col = 0;
17933 if (name[1] == '0') /* "w0": first visible line */
17935 update_topline();
17936 pos.lnum = curwin->w_topline;
17937 return &pos;
17939 else if (name[1] == '$') /* "w$": last visible line */
17941 validate_botline();
17942 pos.lnum = curwin->w_botline - 1;
17943 return &pos;
17946 else if (name[0] == '$') /* last column or line */
17948 if (dollar_lnum)
17950 pos.lnum = curbuf->b_ml.ml_line_count;
17951 pos.col = 0;
17953 else
17955 pos.lnum = curwin->w_cursor.lnum;
17956 pos.col = (colnr_T)STRLEN(ml_get_curline());
17958 return &pos;
17960 return NULL;
17964 * Convert list in "arg" into a position and optional file number.
17965 * When "fnump" is NULL there is no file number, only 3 items.
17966 * Note that the column is passed on as-is, the caller may want to decrement
17967 * it to use 1 for the first column.
17968 * Return FAIL when conversion is not possible, doesn't check the position for
17969 * validity.
17971 static int
17972 list2fpos(arg, posp, fnump)
17973 typval_T *arg;
17974 pos_T *posp;
17975 int *fnump;
17977 list_T *l = arg->vval.v_list;
17978 long i = 0;
17979 long n;
17981 /* List must be: [fnum, lnum, col, coladd], where "fnum" is only there
17982 * when "fnump" isn't NULL and "coladd" is optional. */
17983 if (arg->v_type != VAR_LIST
17984 || l == NULL
17985 || l->lv_len < (fnump == NULL ? 2 : 3)
17986 || l->lv_len > (fnump == NULL ? 3 : 4))
17987 return FAIL;
17989 if (fnump != NULL)
17991 n = list_find_nr(l, i++, NULL); /* fnum */
17992 if (n < 0)
17993 return FAIL;
17994 if (n == 0)
17995 n = curbuf->b_fnum; /* current buffer */
17996 *fnump = n;
17999 n = list_find_nr(l, i++, NULL); /* lnum */
18000 if (n < 0)
18001 return FAIL;
18002 posp->lnum = n;
18004 n = list_find_nr(l, i++, NULL); /* col */
18005 if (n < 0)
18006 return FAIL;
18007 posp->col = n;
18009 #ifdef FEAT_VIRTUALEDIT
18010 n = list_find_nr(l, i, NULL);
18011 if (n < 0)
18012 posp->coladd = 0;
18013 else
18014 posp->coladd = n;
18015 #endif
18017 return OK;
18021 * Get the length of an environment variable name.
18022 * Advance "arg" to the first character after the name.
18023 * Return 0 for error.
18025 static int
18026 get_env_len(arg)
18027 char_u **arg;
18029 char_u *p;
18030 int len;
18032 for (p = *arg; vim_isIDc(*p); ++p)
18034 if (p == *arg) /* no name found */
18035 return 0;
18037 len = (int)(p - *arg);
18038 *arg = p;
18039 return len;
18043 * Get the length of the name of a function or internal variable.
18044 * "arg" is advanced to the first non-white character after the name.
18045 * Return 0 if something is wrong.
18047 static int
18048 get_id_len(arg)
18049 char_u **arg;
18051 char_u *p;
18052 int len;
18054 /* Find the end of the name. */
18055 for (p = *arg; eval_isnamec(*p); ++p)
18057 if (p == *arg) /* no name found */
18058 return 0;
18060 len = (int)(p - *arg);
18061 *arg = skipwhite(p);
18063 return len;
18067 * Get the length of the name of a variable or function.
18068 * Only the name is recognized, does not handle ".key" or "[idx]".
18069 * "arg" is advanced to the first non-white character after the name.
18070 * Return -1 if curly braces expansion failed.
18071 * Return 0 if something else is wrong.
18072 * If the name contains 'magic' {}'s, expand them and return the
18073 * expanded name in an allocated string via 'alias' - caller must free.
18075 static int
18076 get_name_len(arg, alias, evaluate, verbose)
18077 char_u **arg;
18078 char_u **alias;
18079 int evaluate;
18080 int verbose;
18082 int len;
18083 char_u *p;
18084 char_u *expr_start;
18085 char_u *expr_end;
18087 *alias = NULL; /* default to no alias */
18089 if ((*arg)[0] == K_SPECIAL && (*arg)[1] == KS_EXTRA
18090 && (*arg)[2] == (int)KE_SNR)
18092 /* hard coded <SNR>, already translated */
18093 *arg += 3;
18094 return get_id_len(arg) + 3;
18096 len = eval_fname_script(*arg);
18097 if (len > 0)
18099 /* literal "<SID>", "s:" or "<SNR>" */
18100 *arg += len;
18104 * Find the end of the name; check for {} construction.
18106 p = find_name_end(*arg, &expr_start, &expr_end,
18107 len > 0 ? 0 : FNE_CHECK_START);
18108 if (expr_start != NULL)
18110 char_u *temp_string;
18112 if (!evaluate)
18114 len += (int)(p - *arg);
18115 *arg = skipwhite(p);
18116 return len;
18120 * Include any <SID> etc in the expanded string:
18121 * Thus the -len here.
18123 temp_string = make_expanded_name(*arg - len, expr_start, expr_end, p);
18124 if (temp_string == NULL)
18125 return -1;
18126 *alias = temp_string;
18127 *arg = skipwhite(p);
18128 return (int)STRLEN(temp_string);
18131 len += get_id_len(arg);
18132 if (len == 0 && verbose)
18133 EMSG2(_(e_invexpr2), *arg);
18135 return len;
18139 * Find the end of a variable or function name, taking care of magic braces.
18140 * If "expr_start" is not NULL then "expr_start" and "expr_end" are set to the
18141 * start and end of the first magic braces item.
18142 * "flags" can have FNE_INCL_BR and FNE_CHECK_START.
18143 * Return a pointer to just after the name. Equal to "arg" if there is no
18144 * valid name.
18146 static char_u *
18147 find_name_end(arg, expr_start, expr_end, flags)
18148 char_u *arg;
18149 char_u **expr_start;
18150 char_u **expr_end;
18151 int flags;
18153 int mb_nest = 0;
18154 int br_nest = 0;
18155 char_u *p;
18157 if (expr_start != NULL)
18159 *expr_start = NULL;
18160 *expr_end = NULL;
18163 /* Quick check for valid starting character. */
18164 if ((flags & FNE_CHECK_START) && !eval_isnamec1(*arg) && *arg != '{')
18165 return arg;
18167 for (p = arg; *p != NUL
18168 && (eval_isnamec(*p)
18169 || *p == '{'
18170 || ((flags & FNE_INCL_BR) && (*p == '[' || *p == '.'))
18171 || mb_nest != 0
18172 || br_nest != 0); mb_ptr_adv(p))
18174 if (*p == '\'')
18176 /* skip over 'string' to avoid counting [ and ] inside it. */
18177 for (p = p + 1; *p != NUL && *p != '\''; mb_ptr_adv(p))
18179 if (*p == NUL)
18180 break;
18182 else if (*p == '"')
18184 /* skip over "str\"ing" to avoid counting [ and ] inside it. */
18185 for (p = p + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
18186 if (*p == '\\' && p[1] != NUL)
18187 ++p;
18188 if (*p == NUL)
18189 break;
18192 if (mb_nest == 0)
18194 if (*p == '[')
18195 ++br_nest;
18196 else if (*p == ']')
18197 --br_nest;
18200 if (br_nest == 0)
18202 if (*p == '{')
18204 mb_nest++;
18205 if (expr_start != NULL && *expr_start == NULL)
18206 *expr_start = p;
18208 else if (*p == '}')
18210 mb_nest--;
18211 if (expr_start != NULL && mb_nest == 0 && *expr_end == NULL)
18212 *expr_end = p;
18217 return p;
18221 * Expands out the 'magic' {}'s in a variable/function name.
18222 * Note that this can call itself recursively, to deal with
18223 * constructs like foo{bar}{baz}{bam}
18224 * The four pointer arguments point to "foo{expre}ss{ion}bar"
18225 * "in_start" ^
18226 * "expr_start" ^
18227 * "expr_end" ^
18228 * "in_end" ^
18230 * Returns a new allocated string, which the caller must free.
18231 * Returns NULL for failure.
18233 static char_u *
18234 make_expanded_name(in_start, expr_start, expr_end, in_end)
18235 char_u *in_start;
18236 char_u *expr_start;
18237 char_u *expr_end;
18238 char_u *in_end;
18240 char_u c1;
18241 char_u *retval = NULL;
18242 char_u *temp_result;
18243 char_u *nextcmd = NULL;
18245 if (expr_end == NULL || in_end == NULL)
18246 return NULL;
18247 *expr_start = NUL;
18248 *expr_end = NUL;
18249 c1 = *in_end;
18250 *in_end = NUL;
18252 temp_result = eval_to_string(expr_start + 1, &nextcmd, FALSE);
18253 if (temp_result != NULL && nextcmd == NULL)
18255 retval = alloc((unsigned)(STRLEN(temp_result) + (expr_start - in_start)
18256 + (in_end - expr_end) + 1));
18257 if (retval != NULL)
18259 STRCPY(retval, in_start);
18260 STRCAT(retval, temp_result);
18261 STRCAT(retval, expr_end + 1);
18264 vim_free(temp_result);
18266 *in_end = c1; /* put char back for error messages */
18267 *expr_start = '{';
18268 *expr_end = '}';
18270 if (retval != NULL)
18272 temp_result = find_name_end(retval, &expr_start, &expr_end, 0);
18273 if (expr_start != NULL)
18275 /* Further expansion! */
18276 temp_result = make_expanded_name(retval, expr_start,
18277 expr_end, temp_result);
18278 vim_free(retval);
18279 retval = temp_result;
18283 return retval;
18287 * Return TRUE if character "c" can be used in a variable or function name.
18288 * Does not include '{' or '}' for magic braces.
18290 static int
18291 eval_isnamec(c)
18292 int c;
18294 return (ASCII_ISALNUM(c) || c == '_' || c == ':' || c == AUTOLOAD_CHAR);
18298 * Return TRUE if character "c" can be used as the first character in a
18299 * variable or function name (excluding '{' and '}').
18301 static int
18302 eval_isnamec1(c)
18303 int c;
18305 return (ASCII_ISALPHA(c) || c == '_');
18309 * Set number v: variable to "val".
18311 void
18312 set_vim_var_nr(idx, val)
18313 int idx;
18314 long val;
18316 vimvars[idx].vv_nr = val;
18320 * Get number v: variable value.
18322 long
18323 get_vim_var_nr(idx)
18324 int idx;
18326 return vimvars[idx].vv_nr;
18330 * Get string v: variable value. Uses a static buffer, can only be used once.
18332 char_u *
18333 get_vim_var_str(idx)
18334 int idx;
18336 return get_tv_string(&vimvars[idx].vv_tv);
18340 * Get List v: variable value. Caller must take care of reference count when
18341 * needed.
18343 list_T *
18344 get_vim_var_list(idx)
18345 int idx;
18347 return vimvars[idx].vv_list;
18351 * Set v:char to character "c".
18353 void
18354 set_vim_var_char(c)
18355 int c;
18357 #ifdef FEAT_MBYTE
18358 char_u buf[MB_MAXBYTES];
18359 #else
18360 char_u buf[2];
18361 #endif
18363 #ifdef FEAT_MBYTE
18364 if (has_mbyte)
18365 buf[(*mb_char2bytes)(c, buf)] = NUL;
18366 else
18367 #endif
18369 buf[0] = c;
18370 buf[1] = NUL;
18372 set_vim_var_string(VV_CHAR, buf, -1);
18376 * Set v:count to "count" and v:count1 to "count1".
18377 * When "set_prevcount" is TRUE first set v:prevcount from v:count.
18379 void
18380 set_vcount(count, count1, set_prevcount)
18381 long count;
18382 long count1;
18383 int set_prevcount;
18385 if (set_prevcount)
18386 vimvars[VV_PREVCOUNT].vv_nr = vimvars[VV_COUNT].vv_nr;
18387 vimvars[VV_COUNT].vv_nr = count;
18388 vimvars[VV_COUNT1].vv_nr = count1;
18392 * Set string v: variable to a copy of "val".
18394 void
18395 set_vim_var_string(idx, val, len)
18396 int idx;
18397 char_u *val;
18398 int len; /* length of "val" to use or -1 (whole string) */
18400 /* Need to do this (at least) once, since we can't initialize a union.
18401 * Will always be invoked when "v:progname" is set. */
18402 vimvars[VV_VERSION].vv_nr = VIM_VERSION_100;
18404 vim_free(vimvars[idx].vv_str);
18405 if (val == NULL)
18406 vimvars[idx].vv_str = NULL;
18407 else if (len == -1)
18408 vimvars[idx].vv_str = vim_strsave(val);
18409 else
18410 vimvars[idx].vv_str = vim_strnsave(val, len);
18414 * Set List v: variable to "val".
18416 void
18417 set_vim_var_list(idx, val)
18418 int idx;
18419 list_T *val;
18421 list_unref(vimvars[idx].vv_list);
18422 vimvars[idx].vv_list = val;
18423 if (val != NULL)
18424 ++val->lv_refcount;
18428 * Set v:register if needed.
18430 void
18431 set_reg_var(c)
18432 int c;
18434 char_u regname;
18436 if (c == 0 || c == ' ')
18437 regname = '"';
18438 else
18439 regname = c;
18440 /* Avoid free/alloc when the value is already right. */
18441 if (vimvars[VV_REG].vv_str == NULL || vimvars[VV_REG].vv_str[0] != c)
18442 set_vim_var_string(VV_REG, &regname, 1);
18446 * Get or set v:exception. If "oldval" == NULL, return the current value.
18447 * Otherwise, restore the value to "oldval" and return NULL.
18448 * Must always be called in pairs to save and restore v:exception! Does not
18449 * take care of memory allocations.
18451 char_u *
18452 v_exception(oldval)
18453 char_u *oldval;
18455 if (oldval == NULL)
18456 return vimvars[VV_EXCEPTION].vv_str;
18458 vimvars[VV_EXCEPTION].vv_str = oldval;
18459 return NULL;
18463 * Get or set v:throwpoint. If "oldval" == NULL, return the current value.
18464 * Otherwise, restore the value to "oldval" and return NULL.
18465 * Must always be called in pairs to save and restore v:throwpoint! Does not
18466 * take care of memory allocations.
18468 char_u *
18469 v_throwpoint(oldval)
18470 char_u *oldval;
18472 if (oldval == NULL)
18473 return vimvars[VV_THROWPOINT].vv_str;
18475 vimvars[VV_THROWPOINT].vv_str = oldval;
18476 return NULL;
18479 #if defined(FEAT_AUTOCMD) || defined(PROTO)
18481 * Set v:cmdarg.
18482 * If "eap" != NULL, use "eap" to generate the value and return the old value.
18483 * If "oldarg" != NULL, restore the value to "oldarg" and return NULL.
18484 * Must always be called in pairs!
18486 char_u *
18487 set_cmdarg(eap, oldarg)
18488 exarg_T *eap;
18489 char_u *oldarg;
18491 char_u *oldval;
18492 char_u *newval;
18493 unsigned len;
18495 oldval = vimvars[VV_CMDARG].vv_str;
18496 if (eap == NULL)
18498 vim_free(oldval);
18499 vimvars[VV_CMDARG].vv_str = oldarg;
18500 return NULL;
18503 if (eap->force_bin == FORCE_BIN)
18504 len = 6;
18505 else if (eap->force_bin == FORCE_NOBIN)
18506 len = 8;
18507 else
18508 len = 0;
18510 if (eap->read_edit)
18511 len += 7;
18513 if (eap->force_ff != 0)
18514 len += (unsigned)STRLEN(eap->cmd + eap->force_ff) + 6;
18515 # ifdef FEAT_MBYTE
18516 if (eap->force_enc != 0)
18517 len += (unsigned)STRLEN(eap->cmd + eap->force_enc) + 7;
18518 if (eap->bad_char != 0)
18519 len += 7 + 4; /* " ++bad=" + "keep" or "drop" */
18520 # endif
18522 newval = alloc(len + 1);
18523 if (newval == NULL)
18524 return NULL;
18526 if (eap->force_bin == FORCE_BIN)
18527 sprintf((char *)newval, " ++bin");
18528 else if (eap->force_bin == FORCE_NOBIN)
18529 sprintf((char *)newval, " ++nobin");
18530 else
18531 *newval = NUL;
18533 if (eap->read_edit)
18534 STRCAT(newval, " ++edit");
18536 if (eap->force_ff != 0)
18537 sprintf((char *)newval + STRLEN(newval), " ++ff=%s",
18538 eap->cmd + eap->force_ff);
18539 # ifdef FEAT_MBYTE
18540 if (eap->force_enc != 0)
18541 sprintf((char *)newval + STRLEN(newval), " ++enc=%s",
18542 eap->cmd + eap->force_enc);
18543 if (eap->bad_char == BAD_KEEP)
18544 STRCPY(newval + STRLEN(newval), " ++bad=keep");
18545 else if (eap->bad_char == BAD_DROP)
18546 STRCPY(newval + STRLEN(newval), " ++bad=drop");
18547 else if (eap->bad_char != 0)
18548 sprintf((char *)newval + STRLEN(newval), " ++bad=%c", eap->bad_char);
18549 # endif
18550 vimvars[VV_CMDARG].vv_str = newval;
18551 return oldval;
18553 #endif
18556 * Get the value of internal variable "name".
18557 * Return OK or FAIL.
18559 static int
18560 get_var_tv(name, len, rettv, verbose)
18561 char_u *name;
18562 int len; /* length of "name" */
18563 typval_T *rettv; /* NULL when only checking existence */
18564 int verbose; /* may give error message */
18566 int ret = OK;
18567 typval_T *tv = NULL;
18568 typval_T atv;
18569 dictitem_T *v;
18570 int cc;
18572 /* truncate the name, so that we can use strcmp() */
18573 cc = name[len];
18574 name[len] = NUL;
18577 * Check for "b:changedtick".
18579 if (STRCMP(name, "b:changedtick") == 0)
18581 atv.v_type = VAR_NUMBER;
18582 atv.vval.v_number = curbuf->b_changedtick;
18583 tv = &atv;
18587 * Check for user-defined variables.
18589 else
18591 v = find_var(name, NULL);
18592 if (v != NULL)
18593 tv = &v->di_tv;
18596 if (tv == NULL)
18598 if (rettv != NULL && verbose)
18599 EMSG2(_(e_undefvar), name);
18600 ret = FAIL;
18602 else if (rettv != NULL)
18603 copy_tv(tv, rettv);
18605 name[len] = cc;
18607 return ret;
18611 * Handle expr[expr], expr[expr:expr] subscript and .name lookup.
18612 * Also handle function call with Funcref variable: func(expr)
18613 * Can all be combined: dict.func(expr)[idx]['func'](expr)
18615 static int
18616 handle_subscript(arg, rettv, evaluate, verbose)
18617 char_u **arg;
18618 typval_T *rettv;
18619 int evaluate; /* do more than finding the end */
18620 int verbose; /* give error messages */
18622 int ret = OK;
18623 dict_T *selfdict = NULL;
18624 char_u *s;
18625 int len;
18626 typval_T functv;
18628 while (ret == OK
18629 && (**arg == '['
18630 || (**arg == '.' && rettv->v_type == VAR_DICT)
18631 || (**arg == '(' && rettv->v_type == VAR_FUNC))
18632 && !vim_iswhite(*(*arg - 1)))
18634 if (**arg == '(')
18636 /* need to copy the funcref so that we can clear rettv */
18637 functv = *rettv;
18638 rettv->v_type = VAR_UNKNOWN;
18640 /* Invoke the function. Recursive! */
18641 s = functv.vval.v_string;
18642 ret = get_func_tv(s, (int)STRLEN(s), rettv, arg,
18643 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
18644 &len, evaluate, selfdict);
18646 /* Clear the funcref afterwards, so that deleting it while
18647 * evaluating the arguments is possible (see test55). */
18648 clear_tv(&functv);
18650 /* Stop the expression evaluation when immediately aborting on
18651 * error, or when an interrupt occurred or an exception was thrown
18652 * but not caught. */
18653 if (aborting())
18655 if (ret == OK)
18656 clear_tv(rettv);
18657 ret = FAIL;
18659 dict_unref(selfdict);
18660 selfdict = NULL;
18662 else /* **arg == '[' || **arg == '.' */
18664 dict_unref(selfdict);
18665 if (rettv->v_type == VAR_DICT)
18667 selfdict = rettv->vval.v_dict;
18668 if (selfdict != NULL)
18669 ++selfdict->dv_refcount;
18671 else
18672 selfdict = NULL;
18673 if (eval_index(arg, rettv, evaluate, verbose) == FAIL)
18675 clear_tv(rettv);
18676 ret = FAIL;
18680 dict_unref(selfdict);
18681 return ret;
18685 * Allocate memory for a variable type-value, and make it empty (0 or NULL
18686 * value).
18688 static typval_T *
18689 alloc_tv()
18691 return (typval_T *)alloc_clear((unsigned)sizeof(typval_T));
18695 * Allocate memory for a variable type-value, and assign a string to it.
18696 * The string "s" must have been allocated, it is consumed.
18697 * Return NULL for out of memory, the variable otherwise.
18699 static typval_T *
18700 alloc_string_tv(s)
18701 char_u *s;
18703 typval_T *rettv;
18705 rettv = alloc_tv();
18706 if (rettv != NULL)
18708 rettv->v_type = VAR_STRING;
18709 rettv->vval.v_string = s;
18711 else
18712 vim_free(s);
18713 return rettv;
18717 * Free the memory for a variable type-value.
18719 void
18720 free_tv(varp)
18721 typval_T *varp;
18723 if (varp != NULL)
18725 switch (varp->v_type)
18727 case VAR_FUNC:
18728 func_unref(varp->vval.v_string);
18729 /*FALLTHROUGH*/
18730 case VAR_STRING:
18731 vim_free(varp->vval.v_string);
18732 break;
18733 case VAR_LIST:
18734 list_unref(varp->vval.v_list);
18735 break;
18736 case VAR_DICT:
18737 dict_unref(varp->vval.v_dict);
18738 break;
18739 case VAR_NUMBER:
18740 #ifdef FEAT_FLOAT
18741 case VAR_FLOAT:
18742 #endif
18743 case VAR_UNKNOWN:
18744 break;
18745 default:
18746 EMSG2(_(e_intern2), "free_tv()");
18747 break;
18749 vim_free(varp);
18754 * Free the memory for a variable value and set the value to NULL or 0.
18756 void
18757 clear_tv(varp)
18758 typval_T *varp;
18760 if (varp != NULL)
18762 switch (varp->v_type)
18764 case VAR_FUNC:
18765 func_unref(varp->vval.v_string);
18766 /*FALLTHROUGH*/
18767 case VAR_STRING:
18768 vim_free(varp->vval.v_string);
18769 varp->vval.v_string = NULL;
18770 break;
18771 case VAR_LIST:
18772 list_unref(varp->vval.v_list);
18773 varp->vval.v_list = NULL;
18774 break;
18775 case VAR_DICT:
18776 dict_unref(varp->vval.v_dict);
18777 varp->vval.v_dict = NULL;
18778 break;
18779 case VAR_NUMBER:
18780 varp->vval.v_number = 0;
18781 break;
18782 #ifdef FEAT_FLOAT
18783 case VAR_FLOAT:
18784 varp->vval.v_float = 0.0;
18785 break;
18786 #endif
18787 case VAR_UNKNOWN:
18788 break;
18789 default:
18790 EMSG2(_(e_intern2), "clear_tv()");
18792 varp->v_lock = 0;
18797 * Set the value of a variable to NULL without freeing items.
18799 static void
18800 init_tv(varp)
18801 typval_T *varp;
18803 if (varp != NULL)
18804 vim_memset(varp, 0, sizeof(typval_T));
18808 * Get the number value of a variable.
18809 * If it is a String variable, uses vim_str2nr().
18810 * For incompatible types, return 0.
18811 * get_tv_number_chk() is similar to get_tv_number(), but informs the
18812 * caller of incompatible types: it sets *denote to TRUE if "denote"
18813 * is not NULL or returns -1 otherwise.
18815 static long
18816 get_tv_number(varp)
18817 typval_T *varp;
18819 int error = FALSE;
18821 return get_tv_number_chk(varp, &error); /* return 0L on error */
18824 long
18825 get_tv_number_chk(varp, denote)
18826 typval_T *varp;
18827 int *denote;
18829 long n = 0L;
18831 switch (varp->v_type)
18833 case VAR_NUMBER:
18834 return (long)(varp->vval.v_number);
18835 #ifdef FEAT_FLOAT
18836 case VAR_FLOAT:
18837 EMSG(_("E805: Using a Float as a Number"));
18838 break;
18839 #endif
18840 case VAR_FUNC:
18841 EMSG(_("E703: Using a Funcref as a Number"));
18842 break;
18843 case VAR_STRING:
18844 if (varp->vval.v_string != NULL)
18845 vim_str2nr(varp->vval.v_string, NULL, NULL,
18846 TRUE, TRUE, &n, NULL);
18847 return n;
18848 case VAR_LIST:
18849 EMSG(_("E745: Using a List as a Number"));
18850 break;
18851 case VAR_DICT:
18852 EMSG(_("E728: Using a Dictionary as a Number"));
18853 break;
18854 default:
18855 EMSG2(_(e_intern2), "get_tv_number()");
18856 break;
18858 if (denote == NULL) /* useful for values that must be unsigned */
18859 n = -1;
18860 else
18861 *denote = TRUE;
18862 return n;
18866 * Get the lnum from the first argument.
18867 * Also accepts ".", "$", etc., but that only works for the current buffer.
18868 * Returns -1 on error.
18870 static linenr_T
18871 get_tv_lnum(argvars)
18872 typval_T *argvars;
18874 typval_T rettv;
18875 linenr_T lnum;
18877 lnum = get_tv_number_chk(&argvars[0], NULL);
18878 if (lnum == 0) /* no valid number, try using line() */
18880 rettv.v_type = VAR_NUMBER;
18881 f_line(argvars, &rettv);
18882 lnum = rettv.vval.v_number;
18883 clear_tv(&rettv);
18885 return lnum;
18889 * Get the lnum from the first argument.
18890 * Also accepts "$", then "buf" is used.
18891 * Returns 0 on error.
18893 static linenr_T
18894 get_tv_lnum_buf(argvars, buf)
18895 typval_T *argvars;
18896 buf_T *buf;
18898 if (argvars[0].v_type == VAR_STRING
18899 && argvars[0].vval.v_string != NULL
18900 && argvars[0].vval.v_string[0] == '$'
18901 && buf != NULL)
18902 return buf->b_ml.ml_line_count;
18903 return get_tv_number_chk(&argvars[0], NULL);
18907 * Get the string value of a variable.
18908 * If it is a Number variable, the number is converted into a string.
18909 * get_tv_string() uses a single, static buffer. YOU CAN ONLY USE IT ONCE!
18910 * get_tv_string_buf() uses a given buffer.
18911 * If the String variable has never been set, return an empty string.
18912 * Never returns NULL;
18913 * get_tv_string_chk() and get_tv_string_buf_chk() are similar, but return
18914 * NULL on error.
18916 static char_u *
18917 get_tv_string(varp)
18918 typval_T *varp;
18920 static char_u mybuf[NUMBUFLEN];
18922 return get_tv_string_buf(varp, mybuf);
18925 static char_u *
18926 get_tv_string_buf(varp, buf)
18927 typval_T *varp;
18928 char_u *buf;
18930 char_u *res = get_tv_string_buf_chk(varp, buf);
18932 return res != NULL ? res : (char_u *)"";
18935 char_u *
18936 get_tv_string_chk(varp)
18937 typval_T *varp;
18939 static char_u mybuf[NUMBUFLEN];
18941 return get_tv_string_buf_chk(varp, mybuf);
18944 static char_u *
18945 get_tv_string_buf_chk(varp, buf)
18946 typval_T *varp;
18947 char_u *buf;
18949 switch (varp->v_type)
18951 case VAR_NUMBER:
18952 sprintf((char *)buf, "%ld", (long)varp->vval.v_number);
18953 return buf;
18954 case VAR_FUNC:
18955 EMSG(_("E729: using Funcref as a String"));
18956 break;
18957 case VAR_LIST:
18958 EMSG(_("E730: using List as a String"));
18959 break;
18960 case VAR_DICT:
18961 EMSG(_("E731: using Dictionary as a String"));
18962 break;
18963 #ifdef FEAT_FLOAT
18964 case VAR_FLOAT:
18965 EMSG(_("E806: using Float as a String"));
18966 break;
18967 #endif
18968 case VAR_STRING:
18969 if (varp->vval.v_string != NULL)
18970 return varp->vval.v_string;
18971 return (char_u *)"";
18972 default:
18973 EMSG2(_(e_intern2), "get_tv_string_buf()");
18974 break;
18976 return NULL;
18980 * Find variable "name" in the list of variables.
18981 * Return a pointer to it if found, NULL if not found.
18982 * Careful: "a:0" variables don't have a name.
18983 * When "htp" is not NULL we are writing to the variable, set "htp" to the
18984 * hashtab_T used.
18986 static dictitem_T *
18987 find_var(name, htp)
18988 char_u *name;
18989 hashtab_T **htp;
18991 char_u *varname;
18992 hashtab_T *ht;
18994 ht = find_var_ht(name, &varname);
18995 if (htp != NULL)
18996 *htp = ht;
18997 if (ht == NULL)
18998 return NULL;
18999 return find_var_in_ht(ht, varname, htp != NULL);
19003 * Find variable "varname" in hashtab "ht".
19004 * Returns NULL if not found.
19006 static dictitem_T *
19007 find_var_in_ht(ht, varname, writing)
19008 hashtab_T *ht;
19009 char_u *varname;
19010 int writing;
19012 hashitem_T *hi;
19014 if (*varname == NUL)
19016 /* Must be something like "s:", otherwise "ht" would be NULL. */
19017 switch (varname[-2])
19019 case 's': return &SCRIPT_SV(current_SID)->sv_var;
19020 case 'g': return &globvars_var;
19021 case 'v': return &vimvars_var;
19022 case 'b': return &curbuf->b_bufvar;
19023 case 'w': return &curwin->w_winvar;
19024 #ifdef FEAT_WINDOWS
19025 case 't': return &curtab->tp_winvar;
19026 #endif
19027 case 'l': return current_funccal == NULL
19028 ? NULL : &current_funccal->l_vars_var;
19029 case 'a': return current_funccal == NULL
19030 ? NULL : &current_funccal->l_avars_var;
19032 return NULL;
19035 hi = hash_find(ht, varname);
19036 if (HASHITEM_EMPTY(hi))
19038 /* For global variables we may try auto-loading the script. If it
19039 * worked find the variable again. Don't auto-load a script if it was
19040 * loaded already, otherwise it would be loaded every time when
19041 * checking if a function name is a Funcref variable. */
19042 if (ht == &globvarht && !writing
19043 && script_autoload(varname, FALSE) && !aborting())
19044 hi = hash_find(ht, varname);
19045 if (HASHITEM_EMPTY(hi))
19046 return NULL;
19048 return HI2DI(hi);
19052 * Find the hashtab used for a variable name.
19053 * Set "varname" to the start of name without ':'.
19055 static hashtab_T *
19056 find_var_ht(name, varname)
19057 char_u *name;
19058 char_u **varname;
19060 hashitem_T *hi;
19062 if (name[1] != ':')
19064 /* The name must not start with a colon or #. */
19065 if (name[0] == ':' || name[0] == AUTOLOAD_CHAR)
19066 return NULL;
19067 *varname = name;
19069 /* "version" is "v:version" in all scopes */
19070 hi = hash_find(&compat_hashtab, name);
19071 if (!HASHITEM_EMPTY(hi))
19072 return &compat_hashtab;
19074 if (current_funccal == NULL)
19075 return &globvarht; /* global variable */
19076 return &current_funccal->l_vars.dv_hashtab; /* l: variable */
19078 *varname = name + 2;
19079 if (*name == 'g') /* global variable */
19080 return &globvarht;
19081 /* There must be no ':' or '#' in the rest of the name, unless g: is used
19083 if (vim_strchr(name + 2, ':') != NULL
19084 || vim_strchr(name + 2, AUTOLOAD_CHAR) != NULL)
19085 return NULL;
19086 if (*name == 'b') /* buffer variable */
19087 return &curbuf->b_vars.dv_hashtab;
19088 if (*name == 'w') /* window variable */
19089 return &curwin->w_vars.dv_hashtab;
19090 #ifdef FEAT_WINDOWS
19091 if (*name == 't') /* tab page variable */
19092 return &curtab->tp_vars.dv_hashtab;
19093 #endif
19094 if (*name == 'v') /* v: variable */
19095 return &vimvarht;
19096 if (*name == 'a' && current_funccal != NULL) /* function argument */
19097 return &current_funccal->l_avars.dv_hashtab;
19098 if (*name == 'l' && current_funccal != NULL) /* local function variable */
19099 return &current_funccal->l_vars.dv_hashtab;
19100 if (*name == 's' /* script variable */
19101 && current_SID > 0 && current_SID <= ga_scripts.ga_len)
19102 return &SCRIPT_VARS(current_SID);
19103 return NULL;
19107 * Get the string value of a (global/local) variable.
19108 * Returns NULL when it doesn't exist.
19110 char_u *
19111 get_var_value(name)
19112 char_u *name;
19114 dictitem_T *v;
19116 v = find_var(name, NULL);
19117 if (v == NULL)
19118 return NULL;
19119 return get_tv_string(&v->di_tv);
19123 * Allocate a new hashtab for a sourced script. It will be used while
19124 * sourcing this script and when executing functions defined in the script.
19126 void
19127 new_script_vars(id)
19128 scid_T id;
19130 int i;
19131 hashtab_T *ht;
19132 scriptvar_T *sv;
19134 if (ga_grow(&ga_scripts, (int)(id - ga_scripts.ga_len)) == OK)
19136 /* Re-allocating ga_data means that an ht_array pointing to
19137 * ht_smallarray becomes invalid. We can recognize this: ht_mask is
19138 * at its init value. Also reset "v_dict", it's always the same. */
19139 for (i = 1; i <= ga_scripts.ga_len; ++i)
19141 ht = &SCRIPT_VARS(i);
19142 if (ht->ht_mask == HT_INIT_SIZE - 1)
19143 ht->ht_array = ht->ht_smallarray;
19144 sv = SCRIPT_SV(i);
19145 sv->sv_var.di_tv.vval.v_dict = &sv->sv_dict;
19148 while (ga_scripts.ga_len < id)
19150 sv = SCRIPT_SV(ga_scripts.ga_len + 1) =
19151 (scriptvar_T *)alloc_clear(sizeof(scriptvar_T));
19152 init_var_dict(&sv->sv_dict, &sv->sv_var);
19153 ++ga_scripts.ga_len;
19159 * Initialize dictionary "dict" as a scope and set variable "dict_var" to
19160 * point to it.
19162 void
19163 init_var_dict(dict, dict_var)
19164 dict_T *dict;
19165 dictitem_T *dict_var;
19167 hash_init(&dict->dv_hashtab);
19168 dict->dv_refcount = DO_NOT_FREE_CNT;
19169 dict->dv_copyID = 0;
19170 dict_var->di_tv.vval.v_dict = dict;
19171 dict_var->di_tv.v_type = VAR_DICT;
19172 dict_var->di_tv.v_lock = VAR_FIXED;
19173 dict_var->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
19174 dict_var->di_key[0] = NUL;
19178 * Clean up a list of internal variables.
19179 * Frees all allocated variables and the value they contain.
19180 * Clears hashtab "ht", does not free it.
19182 void
19183 vars_clear(ht)
19184 hashtab_T *ht;
19186 vars_clear_ext(ht, TRUE);
19190 * Like vars_clear(), but only free the value if "free_val" is TRUE.
19192 static void
19193 vars_clear_ext(ht, free_val)
19194 hashtab_T *ht;
19195 int free_val;
19197 int todo;
19198 hashitem_T *hi;
19199 dictitem_T *v;
19201 hash_lock(ht);
19202 todo = (int)ht->ht_used;
19203 for (hi = ht->ht_array; todo > 0; ++hi)
19205 if (!HASHITEM_EMPTY(hi))
19207 --todo;
19209 /* Free the variable. Don't remove it from the hashtab,
19210 * ht_array might change then. hash_clear() takes care of it
19211 * later. */
19212 v = HI2DI(hi);
19213 if (free_val)
19214 clear_tv(&v->di_tv);
19215 if ((v->di_flags & DI_FLAGS_FIX) == 0)
19216 vim_free(v);
19219 hash_clear(ht);
19220 ht->ht_used = 0;
19224 * Delete a variable from hashtab "ht" at item "hi".
19225 * Clear the variable value and free the dictitem.
19227 static void
19228 delete_var(ht, hi)
19229 hashtab_T *ht;
19230 hashitem_T *hi;
19232 dictitem_T *di = HI2DI(hi);
19234 hash_remove(ht, hi);
19235 clear_tv(&di->di_tv);
19236 vim_free(di);
19240 * List the value of one internal variable.
19242 static void
19243 list_one_var(v, prefix, first)
19244 dictitem_T *v;
19245 char_u *prefix;
19246 int *first;
19248 char_u *tofree;
19249 char_u *s;
19250 char_u numbuf[NUMBUFLEN];
19252 current_copyID += COPYID_INC;
19253 s = echo_string(&v->di_tv, &tofree, numbuf, current_copyID);
19254 list_one_var_a(prefix, v->di_key, v->di_tv.v_type,
19255 s == NULL ? (char_u *)"" : s, first);
19256 vim_free(tofree);
19259 static void
19260 list_one_var_a(prefix, name, type, string, first)
19261 char_u *prefix;
19262 char_u *name;
19263 int type;
19264 char_u *string;
19265 int *first; /* when TRUE clear rest of screen and set to FALSE */
19267 /* don't use msg() or msg_attr() to avoid overwriting "v:statusmsg" */
19268 msg_start();
19269 msg_puts(prefix);
19270 if (name != NULL) /* "a:" vars don't have a name stored */
19271 msg_puts(name);
19272 msg_putchar(' ');
19273 msg_advance(22);
19274 if (type == VAR_NUMBER)
19275 msg_putchar('#');
19276 else if (type == VAR_FUNC)
19277 msg_putchar('*');
19278 else if (type == VAR_LIST)
19280 msg_putchar('[');
19281 if (*string == '[')
19282 ++string;
19284 else if (type == VAR_DICT)
19286 msg_putchar('{');
19287 if (*string == '{')
19288 ++string;
19290 else
19291 msg_putchar(' ');
19293 msg_outtrans(string);
19295 if (type == VAR_FUNC)
19296 msg_puts((char_u *)"()");
19297 if (*first)
19299 msg_clr_eos();
19300 *first = FALSE;
19305 * Set variable "name" to value in "tv".
19306 * If the variable already exists, the value is updated.
19307 * Otherwise the variable is created.
19309 static void
19310 set_var(name, tv, copy)
19311 char_u *name;
19312 typval_T *tv;
19313 int copy; /* make copy of value in "tv" */
19315 dictitem_T *v;
19316 char_u *varname;
19317 hashtab_T *ht;
19318 char_u *p;
19320 ht = find_var_ht(name, &varname);
19321 if (ht == NULL || *varname == NUL)
19323 EMSG2(_(e_illvar), name);
19324 return;
19326 v = find_var_in_ht(ht, varname, TRUE);
19328 if (tv->v_type == VAR_FUNC)
19330 if (!(vim_strchr((char_u *)"wbs", name[0]) != NULL && name[1] == ':')
19331 && !ASCII_ISUPPER((name[0] != NUL && name[1] == ':')
19332 ? name[2] : name[0]))
19334 EMSG2(_("E704: Funcref variable name must start with a capital: %s"), name);
19335 return;
19337 /* Don't allow hiding a function. When "v" is not NULL we migth be
19338 * assigning another function to the same var, the type is checked
19339 * below. */
19340 if (v == NULL && function_exists(name))
19342 EMSG2(_("E705: Variable name conflicts with existing function: %s"),
19343 name);
19344 return;
19348 if (v != NULL)
19350 /* existing variable, need to clear the value */
19351 if (var_check_ro(v->di_flags, name)
19352 || tv_check_lock(v->di_tv.v_lock, name))
19353 return;
19354 if (v->di_tv.v_type != tv->v_type
19355 && !((v->di_tv.v_type == VAR_STRING
19356 || v->di_tv.v_type == VAR_NUMBER)
19357 && (tv->v_type == VAR_STRING
19358 || tv->v_type == VAR_NUMBER))
19359 #ifdef FEAT_FLOAT
19360 && !((v->di_tv.v_type == VAR_NUMBER
19361 || v->di_tv.v_type == VAR_FLOAT)
19362 && (tv->v_type == VAR_NUMBER
19363 || tv->v_type == VAR_FLOAT))
19364 #endif
19367 EMSG2(_("E706: Variable type mismatch for: %s"), name);
19368 return;
19372 * Handle setting internal v: variables separately: we don't change
19373 * the type.
19375 if (ht == &vimvarht)
19377 if (v->di_tv.v_type == VAR_STRING)
19379 vim_free(v->di_tv.vval.v_string);
19380 if (copy || tv->v_type != VAR_STRING)
19381 v->di_tv.vval.v_string = vim_strsave(get_tv_string(tv));
19382 else
19384 /* Take over the string to avoid an extra alloc/free. */
19385 v->di_tv.vval.v_string = tv->vval.v_string;
19386 tv->vval.v_string = NULL;
19389 else if (v->di_tv.v_type != VAR_NUMBER)
19390 EMSG2(_(e_intern2), "set_var()");
19391 else
19393 v->di_tv.vval.v_number = get_tv_number(tv);
19394 if (STRCMP(varname, "searchforward") == 0)
19395 set_search_direction(v->di_tv.vval.v_number ? '/' : '?');
19397 return;
19400 clear_tv(&v->di_tv);
19402 else /* add a new variable */
19404 /* Can't add "v:" variable. */
19405 if (ht == &vimvarht)
19407 EMSG2(_(e_illvar), name);
19408 return;
19411 /* Make sure the variable name is valid. */
19412 for (p = varname; *p != NUL; ++p)
19413 if (!eval_isnamec1(*p) && (p == varname || !VIM_ISDIGIT(*p))
19414 && *p != AUTOLOAD_CHAR)
19416 EMSG2(_(e_illvar), varname);
19417 return;
19420 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
19421 + STRLEN(varname)));
19422 if (v == NULL)
19423 return;
19424 STRCPY(v->di_key, varname);
19425 if (hash_add(ht, DI2HIKEY(v)) == FAIL)
19427 vim_free(v);
19428 return;
19430 v->di_flags = 0;
19433 if (copy || tv->v_type == VAR_NUMBER || tv->v_type == VAR_FLOAT)
19434 copy_tv(tv, &v->di_tv);
19435 else
19437 v->di_tv = *tv;
19438 v->di_tv.v_lock = 0;
19439 init_tv(tv);
19444 * Return TRUE if di_flags "flags" indicates variable "name" is read-only.
19445 * Also give an error message.
19447 static int
19448 var_check_ro(flags, name)
19449 int flags;
19450 char_u *name;
19452 if (flags & DI_FLAGS_RO)
19454 EMSG2(_(e_readonlyvar), name);
19455 return TRUE;
19457 if ((flags & DI_FLAGS_RO_SBX) && sandbox)
19459 EMSG2(_(e_readonlysbx), name);
19460 return TRUE;
19462 return FALSE;
19466 * Return TRUE if di_flags "flags" indicates variable "name" is fixed.
19467 * Also give an error message.
19469 static int
19470 var_check_fixed(flags, name)
19471 int flags;
19472 char_u *name;
19474 if (flags & DI_FLAGS_FIX)
19476 EMSG2(_("E795: Cannot delete variable %s"), name);
19477 return TRUE;
19479 return FALSE;
19483 * Return TRUE if typeval "tv" is set to be locked (immutable).
19484 * Also give an error message, using "name".
19486 static int
19487 tv_check_lock(lock, name)
19488 int lock;
19489 char_u *name;
19491 if (lock & VAR_LOCKED)
19493 EMSG2(_("E741: Value is locked: %s"),
19494 name == NULL ? (char_u *)_("Unknown") : name);
19495 return TRUE;
19497 if (lock & VAR_FIXED)
19499 EMSG2(_("E742: Cannot change value of %s"),
19500 name == NULL ? (char_u *)_("Unknown") : name);
19501 return TRUE;
19503 return FALSE;
19507 * Copy the values from typval_T "from" to typval_T "to".
19508 * When needed allocates string or increases reference count.
19509 * Does not make a copy of a list or dict but copies the reference!
19510 * It is OK for "from" and "to" to point to the same item. This is used to
19511 * make a copy later.
19513 void
19514 copy_tv(from, to)
19515 typval_T *from;
19516 typval_T *to;
19518 to->v_type = from->v_type;
19519 to->v_lock = 0;
19520 switch (from->v_type)
19522 case VAR_NUMBER:
19523 to->vval.v_number = from->vval.v_number;
19524 break;
19525 #ifdef FEAT_FLOAT
19526 case VAR_FLOAT:
19527 to->vval.v_float = from->vval.v_float;
19528 break;
19529 #endif
19530 case VAR_STRING:
19531 case VAR_FUNC:
19532 if (from->vval.v_string == NULL)
19533 to->vval.v_string = NULL;
19534 else
19536 to->vval.v_string = vim_strsave(from->vval.v_string);
19537 if (from->v_type == VAR_FUNC)
19538 func_ref(to->vval.v_string);
19540 break;
19541 case VAR_LIST:
19542 if (from->vval.v_list == NULL)
19543 to->vval.v_list = NULL;
19544 else
19546 to->vval.v_list = from->vval.v_list;
19547 ++to->vval.v_list->lv_refcount;
19549 break;
19550 case VAR_DICT:
19551 if (from->vval.v_dict == NULL)
19552 to->vval.v_dict = NULL;
19553 else
19555 to->vval.v_dict = from->vval.v_dict;
19556 ++to->vval.v_dict->dv_refcount;
19558 break;
19559 default:
19560 EMSG2(_(e_intern2), "copy_tv()");
19561 break;
19566 * Make a copy of an item.
19567 * Lists and Dictionaries are also copied. A deep copy if "deep" is set.
19568 * For deepcopy() "copyID" is zero for a full copy or the ID for when a
19569 * reference to an already copied list/dict can be used.
19570 * Returns FAIL or OK.
19572 static int
19573 item_copy(from, to, deep, copyID)
19574 typval_T *from;
19575 typval_T *to;
19576 int deep;
19577 int copyID;
19579 static int recurse = 0;
19580 int ret = OK;
19582 if (recurse >= DICT_MAXNEST)
19584 EMSG(_("E698: variable nested too deep for making a copy"));
19585 return FAIL;
19587 ++recurse;
19589 switch (from->v_type)
19591 case VAR_NUMBER:
19592 #ifdef FEAT_FLOAT
19593 case VAR_FLOAT:
19594 #endif
19595 case VAR_STRING:
19596 case VAR_FUNC:
19597 copy_tv(from, to);
19598 break;
19599 case VAR_LIST:
19600 to->v_type = VAR_LIST;
19601 to->v_lock = 0;
19602 if (from->vval.v_list == NULL)
19603 to->vval.v_list = NULL;
19604 else if (copyID != 0 && from->vval.v_list->lv_copyID == copyID)
19606 /* use the copy made earlier */
19607 to->vval.v_list = from->vval.v_list->lv_copylist;
19608 ++to->vval.v_list->lv_refcount;
19610 else
19611 to->vval.v_list = list_copy(from->vval.v_list, deep, copyID);
19612 if (to->vval.v_list == NULL)
19613 ret = FAIL;
19614 break;
19615 case VAR_DICT:
19616 to->v_type = VAR_DICT;
19617 to->v_lock = 0;
19618 if (from->vval.v_dict == NULL)
19619 to->vval.v_dict = NULL;
19620 else if (copyID != 0 && from->vval.v_dict->dv_copyID == copyID)
19622 /* use the copy made earlier */
19623 to->vval.v_dict = from->vval.v_dict->dv_copydict;
19624 ++to->vval.v_dict->dv_refcount;
19626 else
19627 to->vval.v_dict = dict_copy(from->vval.v_dict, deep, copyID);
19628 if (to->vval.v_dict == NULL)
19629 ret = FAIL;
19630 break;
19631 default:
19632 EMSG2(_(e_intern2), "item_copy()");
19633 ret = FAIL;
19635 --recurse;
19636 return ret;
19640 * ":echo expr1 ..." print each argument separated with a space, add a
19641 * newline at the end.
19642 * ":echon expr1 ..." print each argument plain.
19644 void
19645 ex_echo(eap)
19646 exarg_T *eap;
19648 char_u *arg = eap->arg;
19649 typval_T rettv;
19650 char_u *tofree;
19651 char_u *p;
19652 int needclr = TRUE;
19653 int atstart = TRUE;
19654 char_u numbuf[NUMBUFLEN];
19656 if (eap->skip)
19657 ++emsg_skip;
19658 while (*arg != NUL && *arg != '|' && *arg != '\n' && !got_int)
19660 /* If eval1() causes an error message the text from the command may
19661 * still need to be cleared. E.g., "echo 22,44". */
19662 need_clr_eos = needclr;
19664 p = arg;
19665 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
19668 * Report the invalid expression unless the expression evaluation
19669 * has been cancelled due to an aborting error, an interrupt, or an
19670 * exception.
19672 if (!aborting())
19673 EMSG2(_(e_invexpr2), p);
19674 need_clr_eos = FALSE;
19675 break;
19677 need_clr_eos = FALSE;
19679 if (!eap->skip)
19681 if (atstart)
19683 atstart = FALSE;
19684 /* Call msg_start() after eval1(), evaluating the expression
19685 * may cause a message to appear. */
19686 if (eap->cmdidx == CMD_echo)
19687 msg_start();
19689 else if (eap->cmdidx == CMD_echo)
19690 msg_puts_attr((char_u *)" ", echo_attr);
19691 current_copyID += COPYID_INC;
19692 p = echo_string(&rettv, &tofree, numbuf, current_copyID);
19693 if (p != NULL)
19694 for ( ; *p != NUL && !got_int; ++p)
19696 if (*p == '\n' || *p == '\r' || *p == TAB)
19698 if (*p != TAB && needclr)
19700 /* remove any text still there from the command */
19701 msg_clr_eos();
19702 needclr = FALSE;
19704 msg_putchar_attr(*p, echo_attr);
19706 else
19708 #ifdef FEAT_MBYTE
19709 if (has_mbyte)
19711 int i = (*mb_ptr2len)(p);
19713 (void)msg_outtrans_len_attr(p, i, echo_attr);
19714 p += i - 1;
19716 else
19717 #endif
19718 (void)msg_outtrans_len_attr(p, 1, echo_attr);
19721 vim_free(tofree);
19723 clear_tv(&rettv);
19724 arg = skipwhite(arg);
19726 eap->nextcmd = check_nextcmd(arg);
19728 if (eap->skip)
19729 --emsg_skip;
19730 else
19732 /* remove text that may still be there from the command */
19733 if (needclr)
19734 msg_clr_eos();
19735 if (eap->cmdidx == CMD_echo)
19736 msg_end();
19741 * ":echohl {name}".
19743 void
19744 ex_echohl(eap)
19745 exarg_T *eap;
19747 int id;
19749 id = syn_name2id(eap->arg);
19750 if (id == 0)
19751 echo_attr = 0;
19752 else
19753 echo_attr = syn_id2attr(id);
19757 * ":execute expr1 ..." execute the result of an expression.
19758 * ":echomsg expr1 ..." Print a message
19759 * ":echoerr expr1 ..." Print an error
19760 * Each gets spaces around each argument and a newline at the end for
19761 * echo commands
19763 void
19764 ex_execute(eap)
19765 exarg_T *eap;
19767 char_u *arg = eap->arg;
19768 typval_T rettv;
19769 int ret = OK;
19770 char_u *p;
19771 garray_T ga;
19772 int len;
19773 int save_did_emsg;
19775 ga_init2(&ga, 1, 80);
19777 if (eap->skip)
19778 ++emsg_skip;
19779 while (*arg != NUL && *arg != '|' && *arg != '\n')
19781 p = arg;
19782 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
19785 * Report the invalid expression unless the expression evaluation
19786 * has been cancelled due to an aborting error, an interrupt, or an
19787 * exception.
19789 if (!aborting())
19790 EMSG2(_(e_invexpr2), p);
19791 ret = FAIL;
19792 break;
19795 if (!eap->skip)
19797 p = get_tv_string(&rettv);
19798 len = (int)STRLEN(p);
19799 if (ga_grow(&ga, len + 2) == FAIL)
19801 clear_tv(&rettv);
19802 ret = FAIL;
19803 break;
19805 if (ga.ga_len)
19806 ((char_u *)(ga.ga_data))[ga.ga_len++] = ' ';
19807 STRCPY((char_u *)(ga.ga_data) + ga.ga_len, p);
19808 ga.ga_len += len;
19811 clear_tv(&rettv);
19812 arg = skipwhite(arg);
19815 if (ret != FAIL && ga.ga_data != NULL)
19817 if (eap->cmdidx == CMD_echomsg)
19819 MSG_ATTR(ga.ga_data, echo_attr);
19820 out_flush();
19822 else if (eap->cmdidx == CMD_echoerr)
19824 /* We don't want to abort following commands, restore did_emsg. */
19825 save_did_emsg = did_emsg;
19826 EMSG((char_u *)ga.ga_data);
19827 if (!force_abort)
19828 did_emsg = save_did_emsg;
19830 else if (eap->cmdidx == CMD_execute)
19831 do_cmdline((char_u *)ga.ga_data,
19832 eap->getline, eap->cookie, DOCMD_NOWAIT|DOCMD_VERBOSE);
19835 ga_clear(&ga);
19837 if (eap->skip)
19838 --emsg_skip;
19840 eap->nextcmd = check_nextcmd(arg);
19844 * Skip over the name of an option: "&option", "&g:option" or "&l:option".
19845 * "arg" points to the "&" or '+' when called, to "option" when returning.
19846 * Returns NULL when no option name found. Otherwise pointer to the char
19847 * after the option name.
19849 static char_u *
19850 find_option_end(arg, opt_flags)
19851 char_u **arg;
19852 int *opt_flags;
19854 char_u *p = *arg;
19856 ++p;
19857 if (*p == 'g' && p[1] == ':')
19859 *opt_flags = OPT_GLOBAL;
19860 p += 2;
19862 else if (*p == 'l' && p[1] == ':')
19864 *opt_flags = OPT_LOCAL;
19865 p += 2;
19867 else
19868 *opt_flags = 0;
19870 if (!ASCII_ISALPHA(*p))
19871 return NULL;
19872 *arg = p;
19874 if (p[0] == 't' && p[1] == '_' && p[2] != NUL && p[3] != NUL)
19875 p += 4; /* termcap option */
19876 else
19877 while (ASCII_ISALPHA(*p))
19878 ++p;
19879 return p;
19883 * ":function"
19885 void
19886 ex_function(eap)
19887 exarg_T *eap;
19889 char_u *theline;
19890 int j;
19891 int c;
19892 int saved_did_emsg;
19893 char_u *name = NULL;
19894 char_u *p;
19895 char_u *arg;
19896 char_u *line_arg = NULL;
19897 garray_T newargs;
19898 garray_T newlines;
19899 int varargs = FALSE;
19900 int mustend = FALSE;
19901 int flags = 0;
19902 ufunc_T *fp;
19903 int indent;
19904 int nesting;
19905 char_u *skip_until = NULL;
19906 dictitem_T *v;
19907 funcdict_T fudi;
19908 static int func_nr = 0; /* number for nameless function */
19909 int paren;
19910 hashtab_T *ht;
19911 int todo;
19912 hashitem_T *hi;
19913 int sourcing_lnum_off;
19916 * ":function" without argument: list functions.
19918 if (ends_excmd(*eap->arg))
19920 if (!eap->skip)
19922 todo = (int)func_hashtab.ht_used;
19923 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
19925 if (!HASHITEM_EMPTY(hi))
19927 --todo;
19928 fp = HI2UF(hi);
19929 if (!isdigit(*fp->uf_name))
19930 list_func_head(fp, FALSE);
19934 eap->nextcmd = check_nextcmd(eap->arg);
19935 return;
19939 * ":function /pat": list functions matching pattern.
19941 if (*eap->arg == '/')
19943 p = skip_regexp(eap->arg + 1, '/', TRUE, NULL);
19944 if (!eap->skip)
19946 regmatch_T regmatch;
19948 c = *p;
19949 *p = NUL;
19950 regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC);
19951 *p = c;
19952 if (regmatch.regprog != NULL)
19954 regmatch.rm_ic = p_ic;
19956 todo = (int)func_hashtab.ht_used;
19957 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
19959 if (!HASHITEM_EMPTY(hi))
19961 --todo;
19962 fp = HI2UF(hi);
19963 if (!isdigit(*fp->uf_name)
19964 && vim_regexec(&regmatch, fp->uf_name, 0))
19965 list_func_head(fp, FALSE);
19968 vim_free(regmatch.regprog);
19971 if (*p == '/')
19972 ++p;
19973 eap->nextcmd = check_nextcmd(p);
19974 return;
19978 * Get the function name. There are these situations:
19979 * func normal function name
19980 * "name" == func, "fudi.fd_dict" == NULL
19981 * dict.func new dictionary entry
19982 * "name" == NULL, "fudi.fd_dict" set,
19983 * "fudi.fd_di" == NULL, "fudi.fd_newkey" == func
19984 * dict.func existing dict entry with a Funcref
19985 * "name" == func, "fudi.fd_dict" set,
19986 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
19987 * dict.func existing dict entry that's not a Funcref
19988 * "name" == NULL, "fudi.fd_dict" set,
19989 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
19991 p = eap->arg;
19992 name = trans_function_name(&p, eap->skip, 0, &fudi);
19993 paren = (vim_strchr(p, '(') != NULL);
19994 if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip)
19997 * Return on an invalid expression in braces, unless the expression
19998 * evaluation has been cancelled due to an aborting error, an
19999 * interrupt, or an exception.
20001 if (!aborting())
20003 if (!eap->skip && fudi.fd_newkey != NULL)
20004 EMSG2(_(e_dictkey), fudi.fd_newkey);
20005 vim_free(fudi.fd_newkey);
20006 return;
20008 else
20009 eap->skip = TRUE;
20012 /* An error in a function call during evaluation of an expression in magic
20013 * braces should not cause the function not to be defined. */
20014 saved_did_emsg = did_emsg;
20015 did_emsg = FALSE;
20018 * ":function func" with only function name: list function.
20020 if (!paren)
20022 if (!ends_excmd(*skipwhite(p)))
20024 EMSG(_(e_trailing));
20025 goto ret_free;
20027 eap->nextcmd = check_nextcmd(p);
20028 if (eap->nextcmd != NULL)
20029 *p = NUL;
20030 if (!eap->skip && !got_int)
20032 fp = find_func(name);
20033 if (fp != NULL)
20035 list_func_head(fp, TRUE);
20036 for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j)
20038 if (FUNCLINE(fp, j) == NULL)
20039 continue;
20040 msg_putchar('\n');
20041 msg_outnum((long)(j + 1));
20042 if (j < 9)
20043 msg_putchar(' ');
20044 if (j < 99)
20045 msg_putchar(' ');
20046 msg_prt_line(FUNCLINE(fp, j), FALSE);
20047 out_flush(); /* show a line at a time */
20048 ui_breakcheck();
20050 if (!got_int)
20052 msg_putchar('\n');
20053 msg_puts((char_u *)" endfunction");
20056 else
20057 emsg_funcname(N_("E123: Undefined function: %s"), name);
20059 goto ret_free;
20063 * ":function name(arg1, arg2)" Define function.
20065 p = skipwhite(p);
20066 if (*p != '(')
20068 if (!eap->skip)
20070 EMSG2(_("E124: Missing '(': %s"), eap->arg);
20071 goto ret_free;
20073 /* attempt to continue by skipping some text */
20074 if (vim_strchr(p, '(') != NULL)
20075 p = vim_strchr(p, '(');
20077 p = skipwhite(p + 1);
20079 ga_init2(&newargs, (int)sizeof(char_u *), 3);
20080 ga_init2(&newlines, (int)sizeof(char_u *), 3);
20082 if (!eap->skip)
20084 /* Check the name of the function. Unless it's a dictionary function
20085 * (that we are overwriting). */
20086 if (name != NULL)
20087 arg = name;
20088 else
20089 arg = fudi.fd_newkey;
20090 if (arg != NULL && (fudi.fd_di == NULL
20091 || fudi.fd_di->di_tv.v_type != VAR_FUNC))
20093 if (*arg == K_SPECIAL)
20094 j = 3;
20095 else
20096 j = 0;
20097 while (arg[j] != NUL && (j == 0 ? eval_isnamec1(arg[j])
20098 : eval_isnamec(arg[j])))
20099 ++j;
20100 if (arg[j] != NUL)
20101 emsg_funcname((char *)e_invarg2, arg);
20106 * Isolate the arguments: "arg1, arg2, ...)"
20108 while (*p != ')')
20110 if (p[0] == '.' && p[1] == '.' && p[2] == '.')
20112 varargs = TRUE;
20113 p += 3;
20114 mustend = TRUE;
20116 else
20118 arg = p;
20119 while (ASCII_ISALNUM(*p) || *p == '_')
20120 ++p;
20121 if (arg == p || isdigit(*arg)
20122 || (p - arg == 9 && STRNCMP(arg, "firstline", 9) == 0)
20123 || (p - arg == 8 && STRNCMP(arg, "lastline", 8) == 0))
20125 if (!eap->skip)
20126 EMSG2(_("E125: Illegal argument: %s"), arg);
20127 break;
20129 if (ga_grow(&newargs, 1) == FAIL)
20130 goto erret;
20131 c = *p;
20132 *p = NUL;
20133 arg = vim_strsave(arg);
20134 if (arg == NULL)
20135 goto erret;
20136 ((char_u **)(newargs.ga_data))[newargs.ga_len] = arg;
20137 *p = c;
20138 newargs.ga_len++;
20139 if (*p == ',')
20140 ++p;
20141 else
20142 mustend = TRUE;
20144 p = skipwhite(p);
20145 if (mustend && *p != ')')
20147 if (!eap->skip)
20148 EMSG2(_(e_invarg2), eap->arg);
20149 break;
20152 ++p; /* skip the ')' */
20154 /* find extra arguments "range", "dict" and "abort" */
20155 for (;;)
20157 p = skipwhite(p);
20158 if (STRNCMP(p, "range", 5) == 0)
20160 flags |= FC_RANGE;
20161 p += 5;
20163 else if (STRNCMP(p, "dict", 4) == 0)
20165 flags |= FC_DICT;
20166 p += 4;
20168 else if (STRNCMP(p, "abort", 5) == 0)
20170 flags |= FC_ABORT;
20171 p += 5;
20173 else
20174 break;
20177 /* When there is a line break use what follows for the function body.
20178 * Makes 'exe "func Test()\n...\nendfunc"' work. */
20179 if (*p == '\n')
20180 line_arg = p + 1;
20181 else if (*p != NUL && *p != '"' && !eap->skip && !did_emsg)
20182 EMSG(_(e_trailing));
20185 * Read the body of the function, until ":endfunction" is found.
20187 if (KeyTyped)
20189 /* Check if the function already exists, don't let the user type the
20190 * whole function before telling him it doesn't work! For a script we
20191 * need to skip the body to be able to find what follows. */
20192 if (!eap->skip && !eap->forceit)
20194 if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL)
20195 EMSG(_(e_funcdict));
20196 else if (name != NULL && find_func(name) != NULL)
20197 emsg_funcname(e_funcexts, name);
20200 if (!eap->skip && did_emsg)
20201 goto erret;
20203 msg_putchar('\n'); /* don't overwrite the function name */
20204 cmdline_row = msg_row;
20207 indent = 2;
20208 nesting = 0;
20209 for (;;)
20211 msg_scroll = TRUE;
20212 need_wait_return = FALSE;
20213 sourcing_lnum_off = sourcing_lnum;
20215 if (line_arg != NULL)
20217 /* Use eap->arg, split up in parts by line breaks. */
20218 theline = line_arg;
20219 p = vim_strchr(theline, '\n');
20220 if (p == NULL)
20221 line_arg += STRLEN(line_arg);
20222 else
20224 *p = NUL;
20225 line_arg = p + 1;
20228 else if (eap->getline == NULL)
20229 theline = getcmdline(':', 0L, indent);
20230 else
20231 theline = eap->getline(':', eap->cookie, indent);
20232 if (KeyTyped)
20233 lines_left = Rows - 1;
20234 if (theline == NULL)
20236 EMSG(_("E126: Missing :endfunction"));
20237 goto erret;
20240 /* Detect line continuation: sourcing_lnum increased more than one. */
20241 if (sourcing_lnum > sourcing_lnum_off + 1)
20242 sourcing_lnum_off = sourcing_lnum - sourcing_lnum_off - 1;
20243 else
20244 sourcing_lnum_off = 0;
20246 if (skip_until != NULL)
20248 /* between ":append" and "." and between ":python <<EOF" and "EOF"
20249 * don't check for ":endfunc". */
20250 if (STRCMP(theline, skip_until) == 0)
20252 vim_free(skip_until);
20253 skip_until = NULL;
20256 else
20258 /* skip ':' and blanks*/
20259 for (p = theline; vim_iswhite(*p) || *p == ':'; ++p)
20262 /* Check for "endfunction". */
20263 if (checkforcmd(&p, "endfunction", 4) && nesting-- == 0)
20265 if (line_arg == NULL)
20266 vim_free(theline);
20267 break;
20270 /* Increase indent inside "if", "while", "for" and "try", decrease
20271 * at "end". */
20272 if (indent > 2 && STRNCMP(p, "end", 3) == 0)
20273 indent -= 2;
20274 else if (STRNCMP(p, "if", 2) == 0
20275 || STRNCMP(p, "wh", 2) == 0
20276 || STRNCMP(p, "for", 3) == 0
20277 || STRNCMP(p, "try", 3) == 0)
20278 indent += 2;
20280 /* Check for defining a function inside this function. */
20281 if (checkforcmd(&p, "function", 2))
20283 if (*p == '!')
20284 p = skipwhite(p + 1);
20285 p += eval_fname_script(p);
20286 if (ASCII_ISALPHA(*p))
20288 vim_free(trans_function_name(&p, TRUE, 0, NULL));
20289 if (*skipwhite(p) == '(')
20291 ++nesting;
20292 indent += 2;
20297 /* Check for ":append" or ":insert". */
20298 p = skip_range(p, NULL);
20299 if ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p'))
20300 || (p[0] == 'i'
20301 && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n'
20302 && (!ASCII_ISALPHA(p[2]) || (p[2] == 's'))))))
20303 skip_until = vim_strsave((char_u *)".");
20305 /* Check for ":python <<EOF", ":tcl <<EOF", etc. */
20306 arg = skipwhite(skiptowhite(p));
20307 if (arg[0] == '<' && arg[1] =='<'
20308 && ((p[0] == 'p' && p[1] == 'y'
20309 && (!ASCII_ISALPHA(p[2]) || p[2] == 't'))
20310 || (p[0] == 'p' && p[1] == 'e'
20311 && (!ASCII_ISALPHA(p[2]) || p[2] == 'r'))
20312 || (p[0] == 't' && p[1] == 'c'
20313 && (!ASCII_ISALPHA(p[2]) || p[2] == 'l'))
20314 || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b'
20315 && (!ASCII_ISALPHA(p[3]) || p[3] == 'y'))
20316 || (p[0] == 'm' && p[1] == 'z'
20317 && (!ASCII_ISALPHA(p[2]) || p[2] == 's'))
20320 /* ":python <<" continues until a dot, like ":append" */
20321 p = skipwhite(arg + 2);
20322 if (*p == NUL)
20323 skip_until = vim_strsave((char_u *)".");
20324 else
20325 skip_until = vim_strsave(p);
20329 /* Add the line to the function. */
20330 if (ga_grow(&newlines, 1 + sourcing_lnum_off) == FAIL)
20332 if (line_arg == NULL)
20333 vim_free(theline);
20334 goto erret;
20337 /* Copy the line to newly allocated memory. get_one_sourceline()
20338 * allocates 250 bytes per line, this saves 80% on average. The cost
20339 * is an extra alloc/free. */
20340 p = vim_strsave(theline);
20341 if (p != NULL)
20343 if (line_arg == NULL)
20344 vim_free(theline);
20345 theline = p;
20348 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = theline;
20350 /* Add NULL lines for continuation lines, so that the line count is
20351 * equal to the index in the growarray. */
20352 while (sourcing_lnum_off-- > 0)
20353 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = NULL;
20355 /* Check for end of eap->arg. */
20356 if (line_arg != NULL && *line_arg == NUL)
20357 line_arg = NULL;
20360 /* Don't define the function when skipping commands or when an error was
20361 * detected. */
20362 if (eap->skip || did_emsg)
20363 goto erret;
20366 * If there are no errors, add the function
20368 if (fudi.fd_dict == NULL)
20370 v = find_var(name, &ht);
20371 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
20373 emsg_funcname(N_("E707: Function name conflicts with variable: %s"),
20374 name);
20375 goto erret;
20378 fp = find_func(name);
20379 if (fp != NULL)
20381 if (!eap->forceit)
20383 emsg_funcname(e_funcexts, name);
20384 goto erret;
20386 if (fp->uf_calls > 0)
20388 emsg_funcname(N_("E127: Cannot redefine function %s: It is in use"),
20389 name);
20390 goto erret;
20392 /* redefine existing function */
20393 ga_clear_strings(&(fp->uf_args));
20394 ga_clear_strings(&(fp->uf_lines));
20395 vim_free(name);
20396 name = NULL;
20399 else
20401 char numbuf[20];
20403 fp = NULL;
20404 if (fudi.fd_newkey == NULL && !eap->forceit)
20406 EMSG(_(e_funcdict));
20407 goto erret;
20409 if (fudi.fd_di == NULL)
20411 /* Can't add a function to a locked dictionary */
20412 if (tv_check_lock(fudi.fd_dict->dv_lock, eap->arg))
20413 goto erret;
20415 /* Can't change an existing function if it is locked */
20416 else if (tv_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg))
20417 goto erret;
20419 /* Give the function a sequential number. Can only be used with a
20420 * Funcref! */
20421 vim_free(name);
20422 sprintf(numbuf, "%d", ++func_nr);
20423 name = vim_strsave((char_u *)numbuf);
20424 if (name == NULL)
20425 goto erret;
20428 if (fp == NULL)
20430 if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL)
20432 int slen, plen;
20433 char_u *scriptname;
20435 /* Check that the autoload name matches the script name. */
20436 j = FAIL;
20437 if (sourcing_name != NULL)
20439 scriptname = autoload_name(name);
20440 if (scriptname != NULL)
20442 p = vim_strchr(scriptname, '/');
20443 plen = (int)STRLEN(p);
20444 slen = (int)STRLEN(sourcing_name);
20445 if (slen > plen && fnamecmp(p,
20446 sourcing_name + slen - plen) == 0)
20447 j = OK;
20448 vim_free(scriptname);
20451 if (j == FAIL)
20453 EMSG2(_("E746: Function name does not match script file name: %s"), name);
20454 goto erret;
20458 fp = (ufunc_T *)alloc((unsigned)(sizeof(ufunc_T) + STRLEN(name)));
20459 if (fp == NULL)
20460 goto erret;
20462 if (fudi.fd_dict != NULL)
20464 if (fudi.fd_di == NULL)
20466 /* add new dict entry */
20467 fudi.fd_di = dictitem_alloc(fudi.fd_newkey);
20468 if (fudi.fd_di == NULL)
20470 vim_free(fp);
20471 goto erret;
20473 if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL)
20475 vim_free(fudi.fd_di);
20476 vim_free(fp);
20477 goto erret;
20480 else
20481 /* overwrite existing dict entry */
20482 clear_tv(&fudi.fd_di->di_tv);
20483 fudi.fd_di->di_tv.v_type = VAR_FUNC;
20484 fudi.fd_di->di_tv.v_lock = 0;
20485 fudi.fd_di->di_tv.vval.v_string = vim_strsave(name);
20486 fp->uf_refcount = 1;
20488 /* behave like "dict" was used */
20489 flags |= FC_DICT;
20492 /* insert the new function in the function list */
20493 STRCPY(fp->uf_name, name);
20494 hash_add(&func_hashtab, UF2HIKEY(fp));
20496 fp->uf_args = newargs;
20497 fp->uf_lines = newlines;
20498 #ifdef FEAT_PROFILE
20499 fp->uf_tml_count = NULL;
20500 fp->uf_tml_total = NULL;
20501 fp->uf_tml_self = NULL;
20502 fp->uf_profiling = FALSE;
20503 if (prof_def_func())
20504 func_do_profile(fp);
20505 #endif
20506 fp->uf_varargs = varargs;
20507 fp->uf_flags = flags;
20508 fp->uf_calls = 0;
20509 fp->uf_script_ID = current_SID;
20510 goto ret_free;
20512 erret:
20513 ga_clear_strings(&newargs);
20514 ga_clear_strings(&newlines);
20515 ret_free:
20516 vim_free(skip_until);
20517 vim_free(fudi.fd_newkey);
20518 vim_free(name);
20519 did_emsg |= saved_did_emsg;
20523 * Get a function name, translating "<SID>" and "<SNR>".
20524 * Also handles a Funcref in a List or Dictionary.
20525 * Returns the function name in allocated memory, or NULL for failure.
20526 * flags:
20527 * TFN_INT: internal function name OK
20528 * TFN_QUIET: be quiet
20529 * Advances "pp" to just after the function name (if no error).
20531 static char_u *
20532 trans_function_name(pp, skip, flags, fdp)
20533 char_u **pp;
20534 int skip; /* only find the end, don't evaluate */
20535 int flags;
20536 funcdict_T *fdp; /* return: info about dictionary used */
20538 char_u *name = NULL;
20539 char_u *start;
20540 char_u *end;
20541 int lead;
20542 char_u sid_buf[20];
20543 int len;
20544 lval_T lv;
20546 if (fdp != NULL)
20547 vim_memset(fdp, 0, sizeof(funcdict_T));
20548 start = *pp;
20550 /* Check for hard coded <SNR>: already translated function ID (from a user
20551 * command). */
20552 if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA
20553 && (*pp)[2] == (int)KE_SNR)
20555 *pp += 3;
20556 len = get_id_len(pp) + 3;
20557 return vim_strnsave(start, len);
20560 /* A name starting with "<SID>" or "<SNR>" is local to a script. But
20561 * don't skip over "s:", get_lval() needs it for "s:dict.func". */
20562 lead = eval_fname_script(start);
20563 if (lead > 2)
20564 start += lead;
20566 end = get_lval(start, NULL, &lv, FALSE, skip, flags & TFN_QUIET,
20567 lead > 2 ? 0 : FNE_CHECK_START);
20568 if (end == start)
20570 if (!skip)
20571 EMSG(_("E129: Function name required"));
20572 goto theend;
20574 if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range)))
20577 * Report an invalid expression in braces, unless the expression
20578 * evaluation has been cancelled due to an aborting error, an
20579 * interrupt, or an exception.
20581 if (!aborting())
20583 if (end != NULL)
20584 EMSG2(_(e_invarg2), start);
20586 else
20587 *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR);
20588 goto theend;
20591 if (lv.ll_tv != NULL)
20593 if (fdp != NULL)
20595 fdp->fd_dict = lv.ll_dict;
20596 fdp->fd_newkey = lv.ll_newkey;
20597 lv.ll_newkey = NULL;
20598 fdp->fd_di = lv.ll_di;
20600 if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL)
20602 name = vim_strsave(lv.ll_tv->vval.v_string);
20603 *pp = end;
20605 else
20607 if (!skip && !(flags & TFN_QUIET) && (fdp == NULL
20608 || lv.ll_dict == NULL || fdp->fd_newkey == NULL))
20609 EMSG(_(e_funcref));
20610 else
20611 *pp = end;
20612 name = NULL;
20614 goto theend;
20617 if (lv.ll_name == NULL)
20619 /* Error found, but continue after the function name. */
20620 *pp = end;
20621 goto theend;
20624 /* Check if the name is a Funcref. If so, use the value. */
20625 if (lv.ll_exp_name != NULL)
20627 len = (int)STRLEN(lv.ll_exp_name);
20628 name = deref_func_name(lv.ll_exp_name, &len);
20629 if (name == lv.ll_exp_name)
20630 name = NULL;
20632 else
20634 len = (int)(end - *pp);
20635 name = deref_func_name(*pp, &len);
20636 if (name == *pp)
20637 name = NULL;
20639 if (name != NULL)
20641 name = vim_strsave(name);
20642 *pp = end;
20643 goto theend;
20646 if (lv.ll_exp_name != NULL)
20648 len = (int)STRLEN(lv.ll_exp_name);
20649 if (lead <= 2 && lv.ll_name == lv.ll_exp_name
20650 && STRNCMP(lv.ll_name, "s:", 2) == 0)
20652 /* When there was "s:" already or the name expanded to get a
20653 * leading "s:" then remove it. */
20654 lv.ll_name += 2;
20655 len -= 2;
20656 lead = 2;
20659 else
20661 if (lead == 2) /* skip over "s:" */
20662 lv.ll_name += 2;
20663 len = (int)(end - lv.ll_name);
20667 * Copy the function name to allocated memory.
20668 * Accept <SID>name() inside a script, translate into <SNR>123_name().
20669 * Accept <SNR>123_name() outside a script.
20671 if (skip)
20672 lead = 0; /* do nothing */
20673 else if (lead > 0)
20675 lead = 3;
20676 if ((lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name))
20677 || eval_fname_sid(*pp))
20679 /* It's "s:" or "<SID>" */
20680 if (current_SID <= 0)
20682 EMSG(_(e_usingsid));
20683 goto theend;
20685 sprintf((char *)sid_buf, "%ld_", (long)current_SID);
20686 lead += (int)STRLEN(sid_buf);
20689 else if (!(flags & TFN_INT) && builtin_function(lv.ll_name))
20691 EMSG2(_("E128: Function name must start with a capital or contain a colon: %s"), lv.ll_name);
20692 goto theend;
20694 name = alloc((unsigned)(len + lead + 1));
20695 if (name != NULL)
20697 if (lead > 0)
20699 name[0] = K_SPECIAL;
20700 name[1] = KS_EXTRA;
20701 name[2] = (int)KE_SNR;
20702 if (lead > 3) /* If it's "<SID>" */
20703 STRCPY(name + 3, sid_buf);
20705 mch_memmove(name + lead, lv.ll_name, (size_t)len);
20706 name[len + lead] = NUL;
20708 *pp = end;
20710 theend:
20711 clear_lval(&lv);
20712 return name;
20716 * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case).
20717 * Return 2 if "p" starts with "s:".
20718 * Return 0 otherwise.
20720 static int
20721 eval_fname_script(p)
20722 char_u *p;
20724 if (p[0] == '<' && (STRNICMP(p + 1, "SID>", 4) == 0
20725 || STRNICMP(p + 1, "SNR>", 4) == 0))
20726 return 5;
20727 if (p[0] == 's' && p[1] == ':')
20728 return 2;
20729 return 0;
20733 * Return TRUE if "p" starts with "<SID>" or "s:".
20734 * Only works if eval_fname_script() returned non-zero for "p"!
20736 static int
20737 eval_fname_sid(p)
20738 char_u *p;
20740 return (*p == 's' || TOUPPER_ASC(p[2]) == 'I');
20744 * List the head of the function: "name(arg1, arg2)".
20746 static void
20747 list_func_head(fp, indent)
20748 ufunc_T *fp;
20749 int indent;
20751 int j;
20753 msg_start();
20754 if (indent)
20755 MSG_PUTS(" ");
20756 MSG_PUTS("function ");
20757 if (fp->uf_name[0] == K_SPECIAL)
20759 MSG_PUTS_ATTR("<SNR>", hl_attr(HLF_8));
20760 msg_puts(fp->uf_name + 3);
20762 else
20763 msg_puts(fp->uf_name);
20764 msg_putchar('(');
20765 for (j = 0; j < fp->uf_args.ga_len; ++j)
20767 if (j)
20768 MSG_PUTS(", ");
20769 msg_puts(FUNCARG(fp, j));
20771 if (fp->uf_varargs)
20773 if (j)
20774 MSG_PUTS(", ");
20775 MSG_PUTS("...");
20777 msg_putchar(')');
20778 msg_clr_eos();
20779 if (p_verbose > 0)
20780 last_set_msg(fp->uf_script_ID);
20784 * Find a function by name, return pointer to it in ufuncs.
20785 * Return NULL for unknown function.
20787 static ufunc_T *
20788 find_func(name)
20789 char_u *name;
20791 hashitem_T *hi;
20793 hi = hash_find(&func_hashtab, name);
20794 if (!HASHITEM_EMPTY(hi))
20795 return HI2UF(hi);
20796 return NULL;
20799 #if defined(EXITFREE) || defined(PROTO)
20800 void
20801 free_all_functions()
20803 hashitem_T *hi;
20805 /* Need to start all over every time, because func_free() may change the
20806 * hash table. */
20807 while (func_hashtab.ht_used > 0)
20808 for (hi = func_hashtab.ht_array; ; ++hi)
20809 if (!HASHITEM_EMPTY(hi))
20811 func_free(HI2UF(hi));
20812 break;
20815 #endif
20818 * Return TRUE if a function "name" exists.
20820 static int
20821 function_exists(name)
20822 char_u *name;
20824 char_u *nm = name;
20825 char_u *p;
20826 int n = FALSE;
20828 p = trans_function_name(&nm, FALSE, TFN_INT|TFN_QUIET, NULL);
20829 nm = skipwhite(nm);
20831 /* Only accept "funcname", "funcname ", "funcname (..." and
20832 * "funcname(...", not "funcname!...". */
20833 if (p != NULL && (*nm == NUL || *nm == '('))
20835 if (builtin_function(p))
20836 n = (find_internal_func(p) >= 0);
20837 else
20838 n = (find_func(p) != NULL);
20840 vim_free(p);
20841 return n;
20845 * Return TRUE if "name" looks like a builtin function name: starts with a
20846 * lower case letter and doesn't contain a ':' or AUTOLOAD_CHAR.
20848 static int
20849 builtin_function(name)
20850 char_u *name;
20852 return ASCII_ISLOWER(name[0]) && vim_strchr(name, ':') == NULL
20853 && vim_strchr(name, AUTOLOAD_CHAR) == NULL;
20856 #if defined(FEAT_PROFILE) || defined(PROTO)
20858 * Start profiling function "fp".
20860 static void
20861 func_do_profile(fp)
20862 ufunc_T *fp;
20864 fp->uf_tm_count = 0;
20865 profile_zero(&fp->uf_tm_self);
20866 profile_zero(&fp->uf_tm_total);
20867 if (fp->uf_tml_count == NULL)
20868 fp->uf_tml_count = (int *)alloc_clear((unsigned)
20869 (sizeof(int) * fp->uf_lines.ga_len));
20870 if (fp->uf_tml_total == NULL)
20871 fp->uf_tml_total = (proftime_T *)alloc_clear((unsigned)
20872 (sizeof(proftime_T) * fp->uf_lines.ga_len));
20873 if (fp->uf_tml_self == NULL)
20874 fp->uf_tml_self = (proftime_T *)alloc_clear((unsigned)
20875 (sizeof(proftime_T) * fp->uf_lines.ga_len));
20876 fp->uf_tml_idx = -1;
20877 if (fp->uf_tml_count == NULL || fp->uf_tml_total == NULL
20878 || fp->uf_tml_self == NULL)
20879 return; /* out of memory */
20881 fp->uf_profiling = TRUE;
20885 * Dump the profiling results for all functions in file "fd".
20887 void
20888 func_dump_profile(fd)
20889 FILE *fd;
20891 hashitem_T *hi;
20892 int todo;
20893 ufunc_T *fp;
20894 int i;
20895 ufunc_T **sorttab;
20896 int st_len = 0;
20898 todo = (int)func_hashtab.ht_used;
20899 if (todo == 0)
20900 return; /* nothing to dump */
20902 sorttab = (ufunc_T **)alloc((unsigned)(sizeof(ufunc_T) * todo));
20904 for (hi = func_hashtab.ht_array; todo > 0; ++hi)
20906 if (!HASHITEM_EMPTY(hi))
20908 --todo;
20909 fp = HI2UF(hi);
20910 if (fp->uf_profiling)
20912 if (sorttab != NULL)
20913 sorttab[st_len++] = fp;
20915 if (fp->uf_name[0] == K_SPECIAL)
20916 fprintf(fd, "FUNCTION <SNR>%s()\n", fp->uf_name + 3);
20917 else
20918 fprintf(fd, "FUNCTION %s()\n", fp->uf_name);
20919 if (fp->uf_tm_count == 1)
20920 fprintf(fd, "Called 1 time\n");
20921 else
20922 fprintf(fd, "Called %d times\n", fp->uf_tm_count);
20923 fprintf(fd, "Total time: %s\n", profile_msg(&fp->uf_tm_total));
20924 fprintf(fd, " Self time: %s\n", profile_msg(&fp->uf_tm_self));
20925 fprintf(fd, "\n");
20926 fprintf(fd, "count total (s) self (s)\n");
20928 for (i = 0; i < fp->uf_lines.ga_len; ++i)
20930 if (FUNCLINE(fp, i) == NULL)
20931 continue;
20932 prof_func_line(fd, fp->uf_tml_count[i],
20933 &fp->uf_tml_total[i], &fp->uf_tml_self[i], TRUE);
20934 fprintf(fd, "%s\n", FUNCLINE(fp, i));
20936 fprintf(fd, "\n");
20941 if (sorttab != NULL && st_len > 0)
20943 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
20944 prof_total_cmp);
20945 prof_sort_list(fd, sorttab, st_len, "TOTAL", FALSE);
20946 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
20947 prof_self_cmp);
20948 prof_sort_list(fd, sorttab, st_len, "SELF", TRUE);
20951 vim_free(sorttab);
20954 static void
20955 prof_sort_list(fd, sorttab, st_len, title, prefer_self)
20956 FILE *fd;
20957 ufunc_T **sorttab;
20958 int st_len;
20959 char *title;
20960 int prefer_self; /* when equal print only self time */
20962 int i;
20963 ufunc_T *fp;
20965 fprintf(fd, "FUNCTIONS SORTED ON %s TIME\n", title);
20966 fprintf(fd, "count total (s) self (s) function\n");
20967 for (i = 0; i < 20 && i < st_len; ++i)
20969 fp = sorttab[i];
20970 prof_func_line(fd, fp->uf_tm_count, &fp->uf_tm_total, &fp->uf_tm_self,
20971 prefer_self);
20972 if (fp->uf_name[0] == K_SPECIAL)
20973 fprintf(fd, " <SNR>%s()\n", fp->uf_name + 3);
20974 else
20975 fprintf(fd, " %s()\n", fp->uf_name);
20977 fprintf(fd, "\n");
20981 * Print the count and times for one function or function line.
20983 static void
20984 prof_func_line(fd, count, total, self, prefer_self)
20985 FILE *fd;
20986 int count;
20987 proftime_T *total;
20988 proftime_T *self;
20989 int prefer_self; /* when equal print only self time */
20991 if (count > 0)
20993 fprintf(fd, "%5d ", count);
20994 if (prefer_self && profile_equal(total, self))
20995 fprintf(fd, " ");
20996 else
20997 fprintf(fd, "%s ", profile_msg(total));
20998 if (!prefer_self && profile_equal(total, self))
20999 fprintf(fd, " ");
21000 else
21001 fprintf(fd, "%s ", profile_msg(self));
21003 else
21004 fprintf(fd, " ");
21008 * Compare function for total time sorting.
21010 static int
21011 #ifdef __BORLANDC__
21012 _RTLENTRYF
21013 #endif
21014 prof_total_cmp(s1, s2)
21015 const void *s1;
21016 const void *s2;
21018 ufunc_T *p1, *p2;
21020 p1 = *(ufunc_T **)s1;
21021 p2 = *(ufunc_T **)s2;
21022 return profile_cmp(&p1->uf_tm_total, &p2->uf_tm_total);
21026 * Compare function for self time sorting.
21028 static int
21029 #ifdef __BORLANDC__
21030 _RTLENTRYF
21031 #endif
21032 prof_self_cmp(s1, s2)
21033 const void *s1;
21034 const void *s2;
21036 ufunc_T *p1, *p2;
21038 p1 = *(ufunc_T **)s1;
21039 p2 = *(ufunc_T **)s2;
21040 return profile_cmp(&p1->uf_tm_self, &p2->uf_tm_self);
21043 #endif
21046 * If "name" has a package name try autoloading the script for it.
21047 * Return TRUE if a package was loaded.
21049 static int
21050 script_autoload(name, reload)
21051 char_u *name;
21052 int reload; /* load script again when already loaded */
21054 char_u *p;
21055 char_u *scriptname, *tofree;
21056 int ret = FALSE;
21057 int i;
21059 /* If there is no '#' after name[0] there is no package name. */
21060 p = vim_strchr(name, AUTOLOAD_CHAR);
21061 if (p == NULL || p == name)
21062 return FALSE;
21064 tofree = scriptname = autoload_name(name);
21066 /* Find the name in the list of previously loaded package names. Skip
21067 * "autoload/", it's always the same. */
21068 for (i = 0; i < ga_loaded.ga_len; ++i)
21069 if (STRCMP(((char_u **)ga_loaded.ga_data)[i] + 9, scriptname + 9) == 0)
21070 break;
21071 if (!reload && i < ga_loaded.ga_len)
21072 ret = FALSE; /* was loaded already */
21073 else
21075 /* Remember the name if it wasn't loaded already. */
21076 if (i == ga_loaded.ga_len && ga_grow(&ga_loaded, 1) == OK)
21078 ((char_u **)ga_loaded.ga_data)[ga_loaded.ga_len++] = scriptname;
21079 tofree = NULL;
21082 /* Try loading the package from $VIMRUNTIME/autoload/<name>.vim */
21083 if (source_runtime(scriptname, FALSE) == OK)
21084 ret = TRUE;
21087 vim_free(tofree);
21088 return ret;
21092 * Return the autoload script name for a function or variable name.
21093 * Returns NULL when out of memory.
21095 static char_u *
21096 autoload_name(name)
21097 char_u *name;
21099 char_u *p;
21100 char_u *scriptname;
21102 /* Get the script file name: replace '#' with '/', append ".vim". */
21103 scriptname = alloc((unsigned)(STRLEN(name) + 14));
21104 if (scriptname == NULL)
21105 return FALSE;
21106 STRCPY(scriptname, "autoload/");
21107 STRCAT(scriptname, name);
21108 *vim_strrchr(scriptname, AUTOLOAD_CHAR) = NUL;
21109 STRCAT(scriptname, ".vim");
21110 while ((p = vim_strchr(scriptname, AUTOLOAD_CHAR)) != NULL)
21111 *p = '/';
21112 return scriptname;
21115 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
21118 * Function given to ExpandGeneric() to obtain the list of user defined
21119 * function names.
21121 char_u *
21122 get_user_func_name(xp, idx)
21123 expand_T *xp;
21124 int idx;
21126 static long_u done;
21127 static hashitem_T *hi;
21128 ufunc_T *fp;
21130 if (idx == 0)
21132 done = 0;
21133 hi = func_hashtab.ht_array;
21135 if (done < func_hashtab.ht_used)
21137 if (done++ > 0)
21138 ++hi;
21139 while (HASHITEM_EMPTY(hi))
21140 ++hi;
21141 fp = HI2UF(hi);
21143 if (STRLEN(fp->uf_name) + 4 >= IOSIZE)
21144 return fp->uf_name; /* prevents overflow */
21146 cat_func_name(IObuff, fp);
21147 if (xp->xp_context != EXPAND_USER_FUNC)
21149 STRCAT(IObuff, "(");
21150 if (!fp->uf_varargs && fp->uf_args.ga_len == 0)
21151 STRCAT(IObuff, ")");
21153 return IObuff;
21155 return NULL;
21158 #endif /* FEAT_CMDL_COMPL */
21161 * Copy the function name of "fp" to buffer "buf".
21162 * "buf" must be able to hold the function name plus three bytes.
21163 * Takes care of script-local function names.
21165 static void
21166 cat_func_name(buf, fp)
21167 char_u *buf;
21168 ufunc_T *fp;
21170 if (fp->uf_name[0] == K_SPECIAL)
21172 STRCPY(buf, "<SNR>");
21173 STRCAT(buf, fp->uf_name + 3);
21175 else
21176 STRCPY(buf, fp->uf_name);
21180 * ":delfunction {name}"
21182 void
21183 ex_delfunction(eap)
21184 exarg_T *eap;
21186 ufunc_T *fp = NULL;
21187 char_u *p;
21188 char_u *name;
21189 funcdict_T fudi;
21191 p = eap->arg;
21192 name = trans_function_name(&p, eap->skip, 0, &fudi);
21193 vim_free(fudi.fd_newkey);
21194 if (name == NULL)
21196 if (fudi.fd_dict != NULL && !eap->skip)
21197 EMSG(_(e_funcref));
21198 return;
21200 if (!ends_excmd(*skipwhite(p)))
21202 vim_free(name);
21203 EMSG(_(e_trailing));
21204 return;
21206 eap->nextcmd = check_nextcmd(p);
21207 if (eap->nextcmd != NULL)
21208 *p = NUL;
21210 if (!eap->skip)
21211 fp = find_func(name);
21212 vim_free(name);
21214 if (!eap->skip)
21216 if (fp == NULL)
21218 EMSG2(_(e_nofunc), eap->arg);
21219 return;
21221 if (fp->uf_calls > 0)
21223 EMSG2(_("E131: Cannot delete function %s: It is in use"), eap->arg);
21224 return;
21227 if (fudi.fd_dict != NULL)
21229 /* Delete the dict item that refers to the function, it will
21230 * invoke func_unref() and possibly delete the function. */
21231 dictitem_remove(fudi.fd_dict, fudi.fd_di);
21233 else
21234 func_free(fp);
21239 * Free a function and remove it from the list of functions.
21241 static void
21242 func_free(fp)
21243 ufunc_T *fp;
21245 hashitem_T *hi;
21247 /* clear this function */
21248 ga_clear_strings(&(fp->uf_args));
21249 ga_clear_strings(&(fp->uf_lines));
21250 #ifdef FEAT_PROFILE
21251 vim_free(fp->uf_tml_count);
21252 vim_free(fp->uf_tml_total);
21253 vim_free(fp->uf_tml_self);
21254 #endif
21256 /* remove the function from the function hashtable */
21257 hi = hash_find(&func_hashtab, UF2HIKEY(fp));
21258 if (HASHITEM_EMPTY(hi))
21259 EMSG2(_(e_intern2), "func_free()");
21260 else
21261 hash_remove(&func_hashtab, hi);
21263 vim_free(fp);
21267 * Unreference a Function: decrement the reference count and free it when it
21268 * becomes zero. Only for numbered functions.
21270 static void
21271 func_unref(name)
21272 char_u *name;
21274 ufunc_T *fp;
21276 if (name != NULL && isdigit(*name))
21278 fp = find_func(name);
21279 if (fp == NULL)
21280 EMSG2(_(e_intern2), "func_unref()");
21281 else if (--fp->uf_refcount <= 0)
21283 /* Only delete it when it's not being used. Otherwise it's done
21284 * when "uf_calls" becomes zero. */
21285 if (fp->uf_calls == 0)
21286 func_free(fp);
21292 * Count a reference to a Function.
21294 static void
21295 func_ref(name)
21296 char_u *name;
21298 ufunc_T *fp;
21300 if (name != NULL && isdigit(*name))
21302 fp = find_func(name);
21303 if (fp == NULL)
21304 EMSG2(_(e_intern2), "func_ref()");
21305 else
21306 ++fp->uf_refcount;
21311 * Call a user function.
21313 static void
21314 call_user_func(fp, argcount, argvars, rettv, firstline, lastline, selfdict)
21315 ufunc_T *fp; /* pointer to function */
21316 int argcount; /* nr of args */
21317 typval_T *argvars; /* arguments */
21318 typval_T *rettv; /* return value */
21319 linenr_T firstline; /* first line of range */
21320 linenr_T lastline; /* last line of range */
21321 dict_T *selfdict; /* Dictionary for "self" */
21323 char_u *save_sourcing_name;
21324 linenr_T save_sourcing_lnum;
21325 scid_T save_current_SID;
21326 funccall_T *fc;
21327 int save_did_emsg;
21328 static int depth = 0;
21329 dictitem_T *v;
21330 int fixvar_idx = 0; /* index in fixvar[] */
21331 int i;
21332 int ai;
21333 char_u numbuf[NUMBUFLEN];
21334 char_u *name;
21335 #ifdef FEAT_PROFILE
21336 proftime_T wait_start;
21337 proftime_T call_start;
21338 #endif
21340 /* If depth of calling is getting too high, don't execute the function */
21341 if (depth >= p_mfd)
21343 EMSG(_("E132: Function call depth is higher than 'maxfuncdepth'"));
21344 rettv->v_type = VAR_NUMBER;
21345 rettv->vval.v_number = -1;
21346 return;
21348 ++depth;
21350 line_breakcheck(); /* check for CTRL-C hit */
21352 fc = (funccall_T *)alloc(sizeof(funccall_T));
21353 fc->caller = current_funccal;
21354 current_funccal = fc;
21355 fc->func = fp;
21356 fc->rettv = rettv;
21357 rettv->vval.v_number = 0;
21358 fc->linenr = 0;
21359 fc->returned = FALSE;
21360 fc->level = ex_nesting_level;
21361 /* Check if this function has a breakpoint. */
21362 fc->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, (linenr_T)0);
21363 fc->dbg_tick = debug_tick;
21366 * Note about using fc->fixvar[]: This is an array of FIXVAR_CNT variables
21367 * with names up to VAR_SHORT_LEN long. This avoids having to alloc/free
21368 * each argument variable and saves a lot of time.
21371 * Init l: variables.
21373 init_var_dict(&fc->l_vars, &fc->l_vars_var);
21374 if (selfdict != NULL)
21376 /* Set l:self to "selfdict". Use "name" to avoid a warning from
21377 * some compiler that checks the destination size. */
21378 v = &fc->fixvar[fixvar_idx++].var;
21379 name = v->di_key;
21380 STRCPY(name, "self");
21381 v->di_flags = DI_FLAGS_RO + DI_FLAGS_FIX;
21382 hash_add(&fc->l_vars.dv_hashtab, DI2HIKEY(v));
21383 v->di_tv.v_type = VAR_DICT;
21384 v->di_tv.v_lock = 0;
21385 v->di_tv.vval.v_dict = selfdict;
21386 ++selfdict->dv_refcount;
21390 * Init a: variables.
21391 * Set a:0 to "argcount".
21392 * Set a:000 to a list with room for the "..." arguments.
21394 init_var_dict(&fc->l_avars, &fc->l_avars_var);
21395 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "0",
21396 (varnumber_T)(argcount - fp->uf_args.ga_len));
21397 /* Use "name" to avoid a warning from some compiler that checks the
21398 * destination size. */
21399 v = &fc->fixvar[fixvar_idx++].var;
21400 name = v->di_key;
21401 STRCPY(name, "000");
21402 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21403 hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v));
21404 v->di_tv.v_type = VAR_LIST;
21405 v->di_tv.v_lock = VAR_FIXED;
21406 v->di_tv.vval.v_list = &fc->l_varlist;
21407 vim_memset(&fc->l_varlist, 0, sizeof(list_T));
21408 fc->l_varlist.lv_refcount = DO_NOT_FREE_CNT;
21409 fc->l_varlist.lv_lock = VAR_FIXED;
21412 * Set a:firstline to "firstline" and a:lastline to "lastline".
21413 * Set a:name to named arguments.
21414 * Set a:N to the "..." arguments.
21416 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "firstline",
21417 (varnumber_T)firstline);
21418 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "lastline",
21419 (varnumber_T)lastline);
21420 for (i = 0; i < argcount; ++i)
21422 ai = i - fp->uf_args.ga_len;
21423 if (ai < 0)
21424 /* named argument a:name */
21425 name = FUNCARG(fp, i);
21426 else
21428 /* "..." argument a:1, a:2, etc. */
21429 sprintf((char *)numbuf, "%d", ai + 1);
21430 name = numbuf;
21432 if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN)
21434 v = &fc->fixvar[fixvar_idx++].var;
21435 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21437 else
21439 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
21440 + STRLEN(name)));
21441 if (v == NULL)
21442 break;
21443 v->di_flags = DI_FLAGS_RO;
21445 STRCPY(v->di_key, name);
21446 hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v));
21448 /* Note: the values are copied directly to avoid alloc/free.
21449 * "argvars" must have VAR_FIXED for v_lock. */
21450 v->di_tv = argvars[i];
21451 v->di_tv.v_lock = VAR_FIXED;
21453 if (ai >= 0 && ai < MAX_FUNC_ARGS)
21455 list_append(&fc->l_varlist, &fc->l_listitems[ai]);
21456 fc->l_listitems[ai].li_tv = argvars[i];
21457 fc->l_listitems[ai].li_tv.v_lock = VAR_FIXED;
21461 /* Don't redraw while executing the function. */
21462 ++RedrawingDisabled;
21463 save_sourcing_name = sourcing_name;
21464 save_sourcing_lnum = sourcing_lnum;
21465 sourcing_lnum = 1;
21466 sourcing_name = alloc((unsigned)((save_sourcing_name == NULL ? 0
21467 : STRLEN(save_sourcing_name)) + STRLEN(fp->uf_name) + 13));
21468 if (sourcing_name != NULL)
21470 if (save_sourcing_name != NULL
21471 && STRNCMP(save_sourcing_name, "function ", 9) == 0)
21472 sprintf((char *)sourcing_name, "%s..", save_sourcing_name);
21473 else
21474 STRCPY(sourcing_name, "function ");
21475 cat_func_name(sourcing_name + STRLEN(sourcing_name), fp);
21477 if (p_verbose >= 12)
21479 ++no_wait_return;
21480 verbose_enter_scroll();
21482 smsg((char_u *)_("calling %s"), sourcing_name);
21483 if (p_verbose >= 14)
21485 char_u buf[MSG_BUF_LEN];
21486 char_u numbuf2[NUMBUFLEN];
21487 char_u *tofree;
21488 char_u *s;
21490 msg_puts((char_u *)"(");
21491 for (i = 0; i < argcount; ++i)
21493 if (i > 0)
21494 msg_puts((char_u *)", ");
21495 if (argvars[i].v_type == VAR_NUMBER)
21496 msg_outnum((long)argvars[i].vval.v_number);
21497 else
21499 s = tv2string(&argvars[i], &tofree, numbuf2, 0);
21500 if (s != NULL)
21502 trunc_string(s, buf, MSG_BUF_CLEN);
21503 msg_puts(buf);
21504 vim_free(tofree);
21508 msg_puts((char_u *)")");
21510 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21512 verbose_leave_scroll();
21513 --no_wait_return;
21516 #ifdef FEAT_PROFILE
21517 if (do_profiling == PROF_YES)
21519 if (!fp->uf_profiling && has_profiling(FALSE, fp->uf_name, NULL))
21520 func_do_profile(fp);
21521 if (fp->uf_profiling
21522 || (fc->caller != NULL && fc->caller->func->uf_profiling))
21524 ++fp->uf_tm_count;
21525 profile_start(&call_start);
21526 profile_zero(&fp->uf_tm_children);
21528 script_prof_save(&wait_start);
21530 #endif
21532 save_current_SID = current_SID;
21533 current_SID = fp->uf_script_ID;
21534 save_did_emsg = did_emsg;
21535 did_emsg = FALSE;
21537 /* call do_cmdline() to execute the lines */
21538 do_cmdline(NULL, get_func_line, (void *)fc,
21539 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
21541 --RedrawingDisabled;
21543 /* when the function was aborted because of an error, return -1 */
21544 if ((did_emsg && (fp->uf_flags & FC_ABORT)) || rettv->v_type == VAR_UNKNOWN)
21546 clear_tv(rettv);
21547 rettv->v_type = VAR_NUMBER;
21548 rettv->vval.v_number = -1;
21551 #ifdef FEAT_PROFILE
21552 if (do_profiling == PROF_YES && (fp->uf_profiling
21553 || (fc->caller != NULL && fc->caller->func->uf_profiling)))
21555 profile_end(&call_start);
21556 profile_sub_wait(&wait_start, &call_start);
21557 profile_add(&fp->uf_tm_total, &call_start);
21558 profile_self(&fp->uf_tm_self, &call_start, &fp->uf_tm_children);
21559 if (fc->caller != NULL && fc->caller->func->uf_profiling)
21561 profile_add(&fc->caller->func->uf_tm_children, &call_start);
21562 profile_add(&fc->caller->func->uf_tml_children, &call_start);
21565 #endif
21567 /* when being verbose, mention the return value */
21568 if (p_verbose >= 12)
21570 ++no_wait_return;
21571 verbose_enter_scroll();
21573 if (aborting())
21574 smsg((char_u *)_("%s aborted"), sourcing_name);
21575 else if (fc->rettv->v_type == VAR_NUMBER)
21576 smsg((char_u *)_("%s returning #%ld"), sourcing_name,
21577 (long)fc->rettv->vval.v_number);
21578 else
21580 char_u buf[MSG_BUF_LEN];
21581 char_u numbuf2[NUMBUFLEN];
21582 char_u *tofree;
21583 char_u *s;
21585 /* The value may be very long. Skip the middle part, so that we
21586 * have some idea how it starts and ends. smsg() would always
21587 * truncate it at the end. */
21588 s = tv2string(fc->rettv, &tofree, numbuf2, 0);
21589 if (s != NULL)
21591 trunc_string(s, buf, MSG_BUF_CLEN);
21592 smsg((char_u *)_("%s returning %s"), sourcing_name, buf);
21593 vim_free(tofree);
21596 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21598 verbose_leave_scroll();
21599 --no_wait_return;
21602 vim_free(sourcing_name);
21603 sourcing_name = save_sourcing_name;
21604 sourcing_lnum = save_sourcing_lnum;
21605 current_SID = save_current_SID;
21606 #ifdef FEAT_PROFILE
21607 if (do_profiling == PROF_YES)
21608 script_prof_restore(&wait_start);
21609 #endif
21611 if (p_verbose >= 12 && sourcing_name != NULL)
21613 ++no_wait_return;
21614 verbose_enter_scroll();
21616 smsg((char_u *)_("continuing in %s"), sourcing_name);
21617 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21619 verbose_leave_scroll();
21620 --no_wait_return;
21623 did_emsg |= save_did_emsg;
21624 current_funccal = fc->caller;
21625 --depth;
21627 /* If the a:000 list and the l: and a: dicts are not referenced we can
21628 * free the funccall_T and what's in it. */
21629 if (fc->l_varlist.lv_refcount == DO_NOT_FREE_CNT
21630 && fc->l_vars.dv_refcount == DO_NOT_FREE_CNT
21631 && fc->l_avars.dv_refcount == DO_NOT_FREE_CNT)
21633 free_funccal(fc, FALSE);
21635 else
21637 hashitem_T *hi;
21638 listitem_T *li;
21639 int todo;
21641 /* "fc" is still in use. This can happen when returning "a:000" or
21642 * assigning "l:" to a global variable.
21643 * Link "fc" in the list for garbage collection later. */
21644 fc->caller = previous_funccal;
21645 previous_funccal = fc;
21647 /* Make a copy of the a: variables, since we didn't do that above. */
21648 todo = (int)fc->l_avars.dv_hashtab.ht_used;
21649 for (hi = fc->l_avars.dv_hashtab.ht_array; todo > 0; ++hi)
21651 if (!HASHITEM_EMPTY(hi))
21653 --todo;
21654 v = HI2DI(hi);
21655 copy_tv(&v->di_tv, &v->di_tv);
21659 /* Make a copy of the a:000 items, since we didn't do that above. */
21660 for (li = fc->l_varlist.lv_first; li != NULL; li = li->li_next)
21661 copy_tv(&li->li_tv, &li->li_tv);
21666 * Return TRUE if items in "fc" do not have "copyID". That means they are not
21667 * referenced from anywhere that is in use.
21669 static int
21670 can_free_funccal(fc, copyID)
21671 funccall_T *fc;
21672 int copyID;
21674 return (fc->l_varlist.lv_copyID != copyID
21675 && fc->l_vars.dv_copyID != copyID
21676 && fc->l_avars.dv_copyID != copyID);
21680 * Free "fc" and what it contains.
21682 static void
21683 free_funccal(fc, free_val)
21684 funccall_T *fc;
21685 int free_val; /* a: vars were allocated */
21687 listitem_T *li;
21689 /* The a: variables typevals may not have been allocated, only free the
21690 * allocated variables. */
21691 vars_clear_ext(&fc->l_avars.dv_hashtab, free_val);
21693 /* free all l: variables */
21694 vars_clear(&fc->l_vars.dv_hashtab);
21696 /* Free the a:000 variables if they were allocated. */
21697 if (free_val)
21698 for (li = fc->l_varlist.lv_first; li != NULL; li = li->li_next)
21699 clear_tv(&li->li_tv);
21701 vim_free(fc);
21705 * Add a number variable "name" to dict "dp" with value "nr".
21707 static void
21708 add_nr_var(dp, v, name, nr)
21709 dict_T *dp;
21710 dictitem_T *v;
21711 char *name;
21712 varnumber_T nr;
21714 STRCPY(v->di_key, name);
21715 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21716 hash_add(&dp->dv_hashtab, DI2HIKEY(v));
21717 v->di_tv.v_type = VAR_NUMBER;
21718 v->di_tv.v_lock = VAR_FIXED;
21719 v->di_tv.vval.v_number = nr;
21723 * ":return [expr]"
21725 void
21726 ex_return(eap)
21727 exarg_T *eap;
21729 char_u *arg = eap->arg;
21730 typval_T rettv;
21731 int returning = FALSE;
21733 if (current_funccal == NULL)
21735 EMSG(_("E133: :return not inside a function"));
21736 return;
21739 if (eap->skip)
21740 ++emsg_skip;
21742 eap->nextcmd = NULL;
21743 if ((*arg != NUL && *arg != '|' && *arg != '\n')
21744 && eval0(arg, &rettv, &eap->nextcmd, !eap->skip) != FAIL)
21746 if (!eap->skip)
21747 returning = do_return(eap, FALSE, TRUE, &rettv);
21748 else
21749 clear_tv(&rettv);
21751 /* It's safer to return also on error. */
21752 else if (!eap->skip)
21755 * Return unless the expression evaluation has been cancelled due to an
21756 * aborting error, an interrupt, or an exception.
21758 if (!aborting())
21759 returning = do_return(eap, FALSE, TRUE, NULL);
21762 /* When skipping or the return gets pending, advance to the next command
21763 * in this line (!returning). Otherwise, ignore the rest of the line.
21764 * Following lines will be ignored by get_func_line(). */
21765 if (returning)
21766 eap->nextcmd = NULL;
21767 else if (eap->nextcmd == NULL) /* no argument */
21768 eap->nextcmd = check_nextcmd(arg);
21770 if (eap->skip)
21771 --emsg_skip;
21775 * Return from a function. Possibly makes the return pending. Also called
21776 * for a pending return at the ":endtry" or after returning from an extra
21777 * do_cmdline(). "reanimate" is used in the latter case. "is_cmd" is set
21778 * when called due to a ":return" command. "rettv" may point to a typval_T
21779 * with the return rettv. Returns TRUE when the return can be carried out,
21780 * FALSE when the return gets pending.
21783 do_return(eap, reanimate, is_cmd, rettv)
21784 exarg_T *eap;
21785 int reanimate;
21786 int is_cmd;
21787 void *rettv;
21789 int idx;
21790 struct condstack *cstack = eap->cstack;
21792 if (reanimate)
21793 /* Undo the return. */
21794 current_funccal->returned = FALSE;
21797 * Cleanup (and inactivate) conditionals, but stop when a try conditional
21798 * not in its finally clause (which then is to be executed next) is found.
21799 * In this case, make the ":return" pending for execution at the ":endtry".
21800 * Otherwise, return normally.
21802 idx = cleanup_conditionals(eap->cstack, 0, TRUE);
21803 if (idx >= 0)
21805 cstack->cs_pending[idx] = CSTP_RETURN;
21807 if (!is_cmd && !reanimate)
21808 /* A pending return again gets pending. "rettv" points to an
21809 * allocated variable with the rettv of the original ":return"'s
21810 * argument if present or is NULL else. */
21811 cstack->cs_rettv[idx] = rettv;
21812 else
21814 /* When undoing a return in order to make it pending, get the stored
21815 * return rettv. */
21816 if (reanimate)
21817 rettv = current_funccal->rettv;
21819 if (rettv != NULL)
21821 /* Store the value of the pending return. */
21822 if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL)
21823 *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv;
21824 else
21825 EMSG(_(e_outofmem));
21827 else
21828 cstack->cs_rettv[idx] = NULL;
21830 if (reanimate)
21832 /* The pending return value could be overwritten by a ":return"
21833 * without argument in a finally clause; reset the default
21834 * return value. */
21835 current_funccal->rettv->v_type = VAR_NUMBER;
21836 current_funccal->rettv->vval.v_number = 0;
21839 report_make_pending(CSTP_RETURN, rettv);
21841 else
21843 current_funccal->returned = TRUE;
21845 /* If the return is carried out now, store the return value. For
21846 * a return immediately after reanimation, the value is already
21847 * there. */
21848 if (!reanimate && rettv != NULL)
21850 clear_tv(current_funccal->rettv);
21851 *current_funccal->rettv = *(typval_T *)rettv;
21852 if (!is_cmd)
21853 vim_free(rettv);
21857 return idx < 0;
21861 * Free the variable with a pending return value.
21863 void
21864 discard_pending_return(rettv)
21865 void *rettv;
21867 free_tv((typval_T *)rettv);
21871 * Generate a return command for producing the value of "rettv". The result
21872 * is an allocated string. Used by report_pending() for verbose messages.
21874 char_u *
21875 get_return_cmd(rettv)
21876 void *rettv;
21878 char_u *s = NULL;
21879 char_u *tofree = NULL;
21880 char_u numbuf[NUMBUFLEN];
21882 if (rettv != NULL)
21883 s = echo_string((typval_T *)rettv, &tofree, numbuf, 0);
21884 if (s == NULL)
21885 s = (char_u *)"";
21887 STRCPY(IObuff, ":return ");
21888 STRNCPY(IObuff + 8, s, IOSIZE - 8);
21889 if (STRLEN(s) + 8 >= IOSIZE)
21890 STRCPY(IObuff + IOSIZE - 4, "...");
21891 vim_free(tofree);
21892 return vim_strsave(IObuff);
21896 * Get next function line.
21897 * Called by do_cmdline() to get the next line.
21898 * Returns allocated string, or NULL for end of function.
21900 char_u *
21901 get_func_line(c, cookie, indent)
21902 int c UNUSED;
21903 void *cookie;
21904 int indent UNUSED;
21906 funccall_T *fcp = (funccall_T *)cookie;
21907 ufunc_T *fp = fcp->func;
21908 char_u *retval;
21909 garray_T *gap; /* growarray with function lines */
21911 /* If breakpoints have been added/deleted need to check for it. */
21912 if (fcp->dbg_tick != debug_tick)
21914 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
21915 sourcing_lnum);
21916 fcp->dbg_tick = debug_tick;
21918 #ifdef FEAT_PROFILE
21919 if (do_profiling == PROF_YES)
21920 func_line_end(cookie);
21921 #endif
21923 gap = &fp->uf_lines;
21924 if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
21925 || fcp->returned)
21926 retval = NULL;
21927 else
21929 /* Skip NULL lines (continuation lines). */
21930 while (fcp->linenr < gap->ga_len
21931 && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL)
21932 ++fcp->linenr;
21933 if (fcp->linenr >= gap->ga_len)
21934 retval = NULL;
21935 else
21937 retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]);
21938 sourcing_lnum = fcp->linenr;
21939 #ifdef FEAT_PROFILE
21940 if (do_profiling == PROF_YES)
21941 func_line_start(cookie);
21942 #endif
21946 /* Did we encounter a breakpoint? */
21947 if (fcp->breakpoint != 0 && fcp->breakpoint <= sourcing_lnum)
21949 dbg_breakpoint(fp->uf_name, sourcing_lnum);
21950 /* Find next breakpoint. */
21951 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
21952 sourcing_lnum);
21953 fcp->dbg_tick = debug_tick;
21956 return retval;
21959 #if defined(FEAT_PROFILE) || defined(PROTO)
21961 * Called when starting to read a function line.
21962 * "sourcing_lnum" must be correct!
21963 * When skipping lines it may not actually be executed, but we won't find out
21964 * until later and we need to store the time now.
21966 void
21967 func_line_start(cookie)
21968 void *cookie;
21970 funccall_T *fcp = (funccall_T *)cookie;
21971 ufunc_T *fp = fcp->func;
21973 if (fp->uf_profiling && sourcing_lnum >= 1
21974 && sourcing_lnum <= fp->uf_lines.ga_len)
21976 fp->uf_tml_idx = sourcing_lnum - 1;
21977 /* Skip continuation lines. */
21978 while (fp->uf_tml_idx > 0 && FUNCLINE(fp, fp->uf_tml_idx) == NULL)
21979 --fp->uf_tml_idx;
21980 fp->uf_tml_execed = FALSE;
21981 profile_start(&fp->uf_tml_start);
21982 profile_zero(&fp->uf_tml_children);
21983 profile_get_wait(&fp->uf_tml_wait);
21988 * Called when actually executing a function line.
21990 void
21991 func_line_exec(cookie)
21992 void *cookie;
21994 funccall_T *fcp = (funccall_T *)cookie;
21995 ufunc_T *fp = fcp->func;
21997 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
21998 fp->uf_tml_execed = TRUE;
22002 * Called when done with a function line.
22004 void
22005 func_line_end(cookie)
22006 void *cookie;
22008 funccall_T *fcp = (funccall_T *)cookie;
22009 ufunc_T *fp = fcp->func;
22011 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
22013 if (fp->uf_tml_execed)
22015 ++fp->uf_tml_count[fp->uf_tml_idx];
22016 profile_end(&fp->uf_tml_start);
22017 profile_sub_wait(&fp->uf_tml_wait, &fp->uf_tml_start);
22018 profile_add(&fp->uf_tml_total[fp->uf_tml_idx], &fp->uf_tml_start);
22019 profile_self(&fp->uf_tml_self[fp->uf_tml_idx], &fp->uf_tml_start,
22020 &fp->uf_tml_children);
22022 fp->uf_tml_idx = -1;
22025 #endif
22028 * Return TRUE if the currently active function should be ended, because a
22029 * return was encountered or an error occurred. Used inside a ":while".
22032 func_has_ended(cookie)
22033 void *cookie;
22035 funccall_T *fcp = (funccall_T *)cookie;
22037 /* Ignore the "abort" flag if the abortion behavior has been changed due to
22038 * an error inside a try conditional. */
22039 return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
22040 || fcp->returned);
22044 * return TRUE if cookie indicates a function which "abort"s on errors.
22047 func_has_abort(cookie)
22048 void *cookie;
22050 return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT;
22053 #if defined(FEAT_VIMINFO) || defined(FEAT_SESSION)
22054 typedef enum
22056 VAR_FLAVOUR_DEFAULT, /* doesn't start with uppercase */
22057 VAR_FLAVOUR_SESSION, /* starts with uppercase, some lower */
22058 VAR_FLAVOUR_VIMINFO /* all uppercase */
22059 } var_flavour_T;
22061 static var_flavour_T var_flavour __ARGS((char_u *varname));
22063 static var_flavour_T
22064 var_flavour(varname)
22065 char_u *varname;
22067 char_u *p = varname;
22069 if (ASCII_ISUPPER(*p))
22071 while (*(++p))
22072 if (ASCII_ISLOWER(*p))
22073 return VAR_FLAVOUR_SESSION;
22074 return VAR_FLAVOUR_VIMINFO;
22076 else
22077 return VAR_FLAVOUR_DEFAULT;
22079 #endif
22081 #if defined(FEAT_VIMINFO) || defined(PROTO)
22083 * Restore global vars that start with a capital from the viminfo file
22086 read_viminfo_varlist(virp, writing)
22087 vir_T *virp;
22088 int writing;
22090 char_u *tab;
22091 int type = VAR_NUMBER;
22092 typval_T tv;
22094 if (!writing && (find_viminfo_parameter('!') != NULL))
22096 tab = vim_strchr(virp->vir_line + 1, '\t');
22097 if (tab != NULL)
22099 *tab++ = '\0'; /* isolate the variable name */
22100 if (*tab == 'S') /* string var */
22101 type = VAR_STRING;
22102 #ifdef FEAT_FLOAT
22103 else if (*tab == 'F')
22104 type = VAR_FLOAT;
22105 #endif
22107 tab = vim_strchr(tab, '\t');
22108 if (tab != NULL)
22110 tv.v_type = type;
22111 if (type == VAR_STRING)
22112 tv.vval.v_string = viminfo_readstring(virp,
22113 (int)(tab - virp->vir_line + 1), TRUE);
22114 #ifdef FEAT_FLOAT
22115 else if (type == VAR_FLOAT)
22116 (void)string2float(tab + 1, &tv.vval.v_float);
22117 #endif
22118 else
22119 tv.vval.v_number = atol((char *)tab + 1);
22120 set_var(virp->vir_line + 1, &tv, FALSE);
22121 if (type == VAR_STRING)
22122 vim_free(tv.vval.v_string);
22127 return viminfo_readline(virp);
22131 * Write global vars that start with a capital to the viminfo file
22133 void
22134 write_viminfo_varlist(fp)
22135 FILE *fp;
22137 hashitem_T *hi;
22138 dictitem_T *this_var;
22139 int todo;
22140 char *s;
22141 char_u *p;
22142 char_u *tofree;
22143 char_u numbuf[NUMBUFLEN];
22145 if (find_viminfo_parameter('!') == NULL)
22146 return;
22148 fputs(_("\n# global variables:\n"), fp);
22150 todo = (int)globvarht.ht_used;
22151 for (hi = globvarht.ht_array; todo > 0; ++hi)
22153 if (!HASHITEM_EMPTY(hi))
22155 --todo;
22156 this_var = HI2DI(hi);
22157 if (var_flavour(this_var->di_key) == VAR_FLAVOUR_VIMINFO)
22159 switch (this_var->di_tv.v_type)
22161 case VAR_STRING: s = "STR"; break;
22162 case VAR_NUMBER: s = "NUM"; break;
22163 #ifdef FEAT_FLOAT
22164 case VAR_FLOAT: s = "FLO"; break;
22165 #endif
22166 default: continue;
22168 fprintf(fp, "!%s\t%s\t", this_var->di_key, s);
22169 p = echo_string(&this_var->di_tv, &tofree, numbuf, 0);
22170 if (p != NULL)
22171 viminfo_writestring(fp, p);
22172 vim_free(tofree);
22177 #endif
22179 #if defined(FEAT_SESSION) || defined(PROTO)
22181 store_session_globals(fd)
22182 FILE *fd;
22184 hashitem_T *hi;
22185 dictitem_T *this_var;
22186 int todo;
22187 char_u *p, *t;
22189 todo = (int)globvarht.ht_used;
22190 for (hi = globvarht.ht_array; todo > 0; ++hi)
22192 if (!HASHITEM_EMPTY(hi))
22194 --todo;
22195 this_var = HI2DI(hi);
22196 if ((this_var->di_tv.v_type == VAR_NUMBER
22197 || this_var->di_tv.v_type == VAR_STRING)
22198 && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
22200 /* Escape special characters with a backslash. Turn a LF and
22201 * CR into \n and \r. */
22202 p = vim_strsave_escaped(get_tv_string(&this_var->di_tv),
22203 (char_u *)"\\\"\n\r");
22204 if (p == NULL) /* out of memory */
22205 break;
22206 for (t = p; *t != NUL; ++t)
22207 if (*t == '\n')
22208 *t = 'n';
22209 else if (*t == '\r')
22210 *t = 'r';
22211 if ((fprintf(fd, "let %s = %c%s%c",
22212 this_var->di_key,
22213 (this_var->di_tv.v_type == VAR_STRING) ? '"'
22214 : ' ',
22216 (this_var->di_tv.v_type == VAR_STRING) ? '"'
22217 : ' ') < 0)
22218 || put_eol(fd) == FAIL)
22220 vim_free(p);
22221 return FAIL;
22223 vim_free(p);
22225 #ifdef FEAT_FLOAT
22226 else if (this_var->di_tv.v_type == VAR_FLOAT
22227 && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
22229 float_T f = this_var->di_tv.vval.v_float;
22230 int sign = ' ';
22232 if (f < 0)
22234 f = -f;
22235 sign = '-';
22237 if ((fprintf(fd, "let %s = %c&%f",
22238 this_var->di_key, sign, f) < 0)
22239 || put_eol(fd) == FAIL)
22240 return FAIL;
22242 #endif
22245 return OK;
22247 #endif
22250 * Display script name where an item was last set.
22251 * Should only be invoked when 'verbose' is non-zero.
22253 void
22254 last_set_msg(scriptID)
22255 scid_T scriptID;
22257 char_u *p;
22259 if (scriptID != 0)
22261 p = home_replace_save(NULL, get_scriptname(scriptID));
22262 if (p != NULL)
22264 verbose_enter();
22265 MSG_PUTS(_("\n\tLast set from "));
22266 MSG_PUTS(p);
22267 vim_free(p);
22268 verbose_leave();
22274 * List v:oldfiles in a nice way.
22276 void
22277 ex_oldfiles(eap)
22278 exarg_T *eap UNUSED;
22280 list_T *l = vimvars[VV_OLDFILES].vv_list;
22281 listitem_T *li;
22282 int nr = 0;
22284 if (l == NULL)
22285 msg((char_u *)_("No old files"));
22286 else
22288 msg_start();
22289 msg_scroll = TRUE;
22290 for (li = l->lv_first; li != NULL && !got_int; li = li->li_next)
22292 msg_outnum((long)++nr);
22293 MSG_PUTS(": ");
22294 msg_outtrans(get_tv_string(&li->li_tv));
22295 msg_putchar('\n');
22296 out_flush(); /* output one line at a time */
22297 ui_breakcheck();
22299 /* Assume "got_int" was set to truncate the listing. */
22300 got_int = FALSE;
22302 #ifdef FEAT_BROWSE_CMD
22303 if (cmdmod.browse)
22305 quit_more = FALSE;
22306 nr = prompt_for_number(FALSE);
22307 msg_starthere();
22308 if (nr > 0)
22310 char_u *p = list_find_str(get_vim_var_list(VV_OLDFILES),
22311 (long)nr);
22313 if (p != NULL)
22315 p = expand_env_save(p);
22316 eap->arg = p;
22317 eap->cmdidx = CMD_edit;
22318 cmdmod.browse = FALSE;
22319 do_exedit(eap, NULL);
22320 vim_free(p);
22324 #endif
22328 #endif /* FEAT_EVAL */
22331 #if defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) || defined(PROTO)
22333 #ifdef WIN3264
22335 * Functions for ":8" filename modifier: get 8.3 version of a filename.
22337 static int get_short_pathname __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
22338 static int shortpath_for_invalid_fname __ARGS((char_u **fname, char_u **bufp, int *fnamelen));
22339 static int shortpath_for_partial __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
22342 * Get the short path (8.3) for the filename in "fnamep".
22343 * Only works for a valid file name.
22344 * When the path gets longer "fnamep" is changed and the allocated buffer
22345 * is put in "bufp".
22346 * *fnamelen is the length of "fnamep" and set to 0 for a nonexistent path.
22347 * Returns OK on success, FAIL on failure.
22349 static int
22350 get_short_pathname(fnamep, bufp, fnamelen)
22351 char_u **fnamep;
22352 char_u **bufp;
22353 int *fnamelen;
22355 int l, len;
22356 char_u *newbuf;
22358 len = *fnamelen;
22359 l = GetShortPathName(*fnamep, *fnamep, len);
22360 if (l > len - 1)
22362 /* If that doesn't work (not enough space), then save the string
22363 * and try again with a new buffer big enough. */
22364 newbuf = vim_strnsave(*fnamep, l);
22365 if (newbuf == NULL)
22366 return FAIL;
22368 vim_free(*bufp);
22369 *fnamep = *bufp = newbuf;
22371 /* Really should always succeed, as the buffer is big enough. */
22372 l = GetShortPathName(*fnamep, *fnamep, l+1);
22375 *fnamelen = l;
22376 return OK;
22380 * Get the short path (8.3) for the filename in "fname". The converted
22381 * path is returned in "bufp".
22383 * Some of the directories specified in "fname" may not exist. This function
22384 * will shorten the existing directories at the beginning of the path and then
22385 * append the remaining non-existing path.
22387 * fname - Pointer to the filename to shorten. On return, contains the
22388 * pointer to the shortened pathname
22389 * bufp - Pointer to an allocated buffer for the filename.
22390 * fnamelen - Length of the filename pointed to by fname
22392 * Returns OK on success (or nothing done) and FAIL on failure (out of memory).
22394 static int
22395 shortpath_for_invalid_fname(fname, bufp, fnamelen)
22396 char_u **fname;
22397 char_u **bufp;
22398 int *fnamelen;
22400 char_u *short_fname, *save_fname, *pbuf_unused;
22401 char_u *endp, *save_endp;
22402 char_u ch;
22403 int old_len, len;
22404 int new_len, sfx_len;
22405 int retval = OK;
22407 /* Make a copy */
22408 old_len = *fnamelen;
22409 save_fname = vim_strnsave(*fname, old_len);
22410 pbuf_unused = NULL;
22411 short_fname = NULL;
22413 endp = save_fname + old_len - 1; /* Find the end of the copy */
22414 save_endp = endp;
22417 * Try shortening the supplied path till it succeeds by removing one
22418 * directory at a time from the tail of the path.
22420 len = 0;
22421 for (;;)
22423 /* go back one path-separator */
22424 while (endp > save_fname && !after_pathsep(save_fname, endp + 1))
22425 --endp;
22426 if (endp <= save_fname)
22427 break; /* processed the complete path */
22430 * Replace the path separator with a NUL and try to shorten the
22431 * resulting path.
22433 ch = *endp;
22434 *endp = 0;
22435 short_fname = save_fname;
22436 len = (int)STRLEN(short_fname) + 1;
22437 if (get_short_pathname(&short_fname, &pbuf_unused, &len) == FAIL)
22439 retval = FAIL;
22440 goto theend;
22442 *endp = ch; /* preserve the string */
22444 if (len > 0)
22445 break; /* successfully shortened the path */
22447 /* failed to shorten the path. Skip the path separator */
22448 --endp;
22451 if (len > 0)
22454 * Succeeded in shortening the path. Now concatenate the shortened
22455 * path with the remaining path at the tail.
22458 /* Compute the length of the new path. */
22459 sfx_len = (int)(save_endp - endp) + 1;
22460 new_len = len + sfx_len;
22462 *fnamelen = new_len;
22463 vim_free(*bufp);
22464 if (new_len > old_len)
22466 /* There is not enough space in the currently allocated string,
22467 * copy it to a buffer big enough. */
22468 *fname = *bufp = vim_strnsave(short_fname, new_len);
22469 if (*fname == NULL)
22471 retval = FAIL;
22472 goto theend;
22475 else
22477 /* Transfer short_fname to the main buffer (it's big enough),
22478 * unless get_short_pathname() did its work in-place. */
22479 *fname = *bufp = save_fname;
22480 if (short_fname != save_fname)
22481 vim_strncpy(save_fname, short_fname, len);
22482 save_fname = NULL;
22485 /* concat the not-shortened part of the path */
22486 vim_strncpy(*fname + len, endp, sfx_len);
22487 (*fname)[new_len] = NUL;
22490 theend:
22491 vim_free(pbuf_unused);
22492 vim_free(save_fname);
22494 return retval;
22498 * Get a pathname for a partial path.
22499 * Returns OK for success, FAIL for failure.
22501 static int
22502 shortpath_for_partial(fnamep, bufp, fnamelen)
22503 char_u **fnamep;
22504 char_u **bufp;
22505 int *fnamelen;
22507 int sepcount, len, tflen;
22508 char_u *p;
22509 char_u *pbuf, *tfname;
22510 int hasTilde;
22512 /* Count up the path separators from the RHS.. so we know which part
22513 * of the path to return. */
22514 sepcount = 0;
22515 for (p = *fnamep; p < *fnamep + *fnamelen; mb_ptr_adv(p))
22516 if (vim_ispathsep(*p))
22517 ++sepcount;
22519 /* Need full path first (use expand_env() to remove a "~/") */
22520 hasTilde = (**fnamep == '~');
22521 if (hasTilde)
22522 pbuf = tfname = expand_env_save(*fnamep);
22523 else
22524 pbuf = tfname = FullName_save(*fnamep, FALSE);
22526 len = tflen = (int)STRLEN(tfname);
22528 if (get_short_pathname(&tfname, &pbuf, &len) == FAIL)
22529 return FAIL;
22531 if (len == 0)
22533 /* Don't have a valid filename, so shorten the rest of the
22534 * path if we can. This CAN give us invalid 8.3 filenames, but
22535 * there's not a lot of point in guessing what it might be.
22537 len = tflen;
22538 if (shortpath_for_invalid_fname(&tfname, &pbuf, &len) == FAIL)
22539 return FAIL;
22542 /* Count the paths backward to find the beginning of the desired string. */
22543 for (p = tfname + len - 1; p >= tfname; --p)
22545 #ifdef FEAT_MBYTE
22546 if (has_mbyte)
22547 p -= mb_head_off(tfname, p);
22548 #endif
22549 if (vim_ispathsep(*p))
22551 if (sepcount == 0 || (hasTilde && sepcount == 1))
22552 break;
22553 else
22554 sepcount --;
22557 if (hasTilde)
22559 --p;
22560 if (p >= tfname)
22561 *p = '~';
22562 else
22563 return FAIL;
22565 else
22566 ++p;
22568 /* Copy in the string - p indexes into tfname - allocated at pbuf */
22569 vim_free(*bufp);
22570 *fnamelen = (int)STRLEN(p);
22571 *bufp = pbuf;
22572 *fnamep = p;
22574 return OK;
22576 #endif /* WIN3264 */
22579 * Adjust a filename, according to a string of modifiers.
22580 * *fnamep must be NUL terminated when called. When returning, the length is
22581 * determined by *fnamelen.
22582 * Returns VALID_ flags or -1 for failure.
22583 * When there is an error, *fnamep is set to NULL.
22586 modify_fname(src, usedlen, fnamep, bufp, fnamelen)
22587 char_u *src; /* string with modifiers */
22588 int *usedlen; /* characters after src that are used */
22589 char_u **fnamep; /* file name so far */
22590 char_u **bufp; /* buffer for allocated file name or NULL */
22591 int *fnamelen; /* length of fnamep */
22593 int valid = 0;
22594 char_u *tail;
22595 char_u *s, *p, *pbuf;
22596 char_u dirname[MAXPATHL];
22597 int c;
22598 int has_fullname = 0;
22599 #ifdef WIN3264
22600 int has_shortname = 0;
22601 #endif
22603 repeat:
22604 /* ":p" - full path/file_name */
22605 if (src[*usedlen] == ':' && src[*usedlen + 1] == 'p')
22607 has_fullname = 1;
22609 valid |= VALID_PATH;
22610 *usedlen += 2;
22612 /* Expand "~/path" for all systems and "~user/path" for Unix and VMS */
22613 if ((*fnamep)[0] == '~'
22614 #if !defined(UNIX) && !(defined(VMS) && defined(USER_HOME))
22615 && ((*fnamep)[1] == '/'
22616 # ifdef BACKSLASH_IN_FILENAME
22617 || (*fnamep)[1] == '\\'
22618 # endif
22619 || (*fnamep)[1] == NUL)
22621 #endif
22624 *fnamep = expand_env_save(*fnamep);
22625 vim_free(*bufp); /* free any allocated file name */
22626 *bufp = *fnamep;
22627 if (*fnamep == NULL)
22628 return -1;
22631 /* When "/." or "/.." is used: force expansion to get rid of it. */
22632 for (p = *fnamep; *p != NUL; mb_ptr_adv(p))
22634 if (vim_ispathsep(*p)
22635 && p[1] == '.'
22636 && (p[2] == NUL
22637 || vim_ispathsep(p[2])
22638 || (p[2] == '.'
22639 && (p[3] == NUL || vim_ispathsep(p[3])))))
22640 break;
22643 /* FullName_save() is slow, don't use it when not needed. */
22644 if (*p != NUL || !vim_isAbsName(*fnamep))
22646 *fnamep = FullName_save(*fnamep, *p != NUL);
22647 vim_free(*bufp); /* free any allocated file name */
22648 *bufp = *fnamep;
22649 if (*fnamep == NULL)
22650 return -1;
22653 /* Append a path separator to a directory. */
22654 if (mch_isdir(*fnamep))
22656 /* Make room for one or two extra characters. */
22657 *fnamep = vim_strnsave(*fnamep, (int)STRLEN(*fnamep) + 2);
22658 vim_free(*bufp); /* free any allocated file name */
22659 *bufp = *fnamep;
22660 if (*fnamep == NULL)
22661 return -1;
22662 add_pathsep(*fnamep);
22666 /* ":." - path relative to the current directory */
22667 /* ":~" - path relative to the home directory */
22668 /* ":8" - shortname path - postponed till after */
22669 while (src[*usedlen] == ':'
22670 && ((c = src[*usedlen + 1]) == '.' || c == '~' || c == '8'))
22672 *usedlen += 2;
22673 if (c == '8')
22675 #ifdef WIN3264
22676 has_shortname = 1; /* Postpone this. */
22677 #endif
22678 continue;
22680 pbuf = NULL;
22681 /* Need full path first (use expand_env() to remove a "~/") */
22682 if (!has_fullname)
22684 if (c == '.' && **fnamep == '~')
22685 p = pbuf = expand_env_save(*fnamep);
22686 else
22687 p = pbuf = FullName_save(*fnamep, FALSE);
22689 else
22690 p = *fnamep;
22692 has_fullname = 0;
22694 if (p != NULL)
22696 if (c == '.')
22698 mch_dirname(dirname, MAXPATHL);
22699 s = shorten_fname(p, dirname);
22700 if (s != NULL)
22702 *fnamep = s;
22703 if (pbuf != NULL)
22705 vim_free(*bufp); /* free any allocated file name */
22706 *bufp = pbuf;
22707 pbuf = NULL;
22711 else
22713 home_replace(NULL, p, dirname, MAXPATHL, TRUE);
22714 /* Only replace it when it starts with '~' */
22715 if (*dirname == '~')
22717 s = vim_strsave(dirname);
22718 if (s != NULL)
22720 *fnamep = s;
22721 vim_free(*bufp);
22722 *bufp = s;
22726 vim_free(pbuf);
22730 tail = gettail(*fnamep);
22731 *fnamelen = (int)STRLEN(*fnamep);
22733 /* ":h" - head, remove "/file_name", can be repeated */
22734 /* Don't remove the first "/" or "c:\" */
22735 while (src[*usedlen] == ':' && src[*usedlen + 1] == 'h')
22737 valid |= VALID_HEAD;
22738 *usedlen += 2;
22739 s = get_past_head(*fnamep);
22740 while (tail > s && after_pathsep(s, tail))
22741 mb_ptr_back(*fnamep, tail);
22742 *fnamelen = (int)(tail - *fnamep);
22743 #ifdef VMS
22744 if (*fnamelen > 0)
22745 *fnamelen += 1; /* the path separator is part of the path */
22746 #endif
22747 if (*fnamelen == 0)
22749 /* Result is empty. Turn it into "." to make ":cd %:h" work. */
22750 p = vim_strsave((char_u *)".");
22751 if (p == NULL)
22752 return -1;
22753 vim_free(*bufp);
22754 *bufp = *fnamep = tail = p;
22755 *fnamelen = 1;
22757 else
22759 while (tail > s && !after_pathsep(s, tail))
22760 mb_ptr_back(*fnamep, tail);
22764 /* ":8" - shortname */
22765 if (src[*usedlen] == ':' && src[*usedlen + 1] == '8')
22767 *usedlen += 2;
22768 #ifdef WIN3264
22769 has_shortname = 1;
22770 #endif
22773 #ifdef WIN3264
22774 /* Check shortname after we have done 'heads' and before we do 'tails'
22776 if (has_shortname)
22778 pbuf = NULL;
22779 /* Copy the string if it is shortened by :h */
22780 if (*fnamelen < (int)STRLEN(*fnamep))
22782 p = vim_strnsave(*fnamep, *fnamelen);
22783 if (p == 0)
22784 return -1;
22785 vim_free(*bufp);
22786 *bufp = *fnamep = p;
22789 /* Split into two implementations - makes it easier. First is where
22790 * there isn't a full name already, second is where there is.
22792 if (!has_fullname && !vim_isAbsName(*fnamep))
22794 if (shortpath_for_partial(fnamep, bufp, fnamelen) == FAIL)
22795 return -1;
22797 else
22799 int l;
22801 /* Simple case, already have the full-name
22802 * Nearly always shorter, so try first time. */
22803 l = *fnamelen;
22804 if (get_short_pathname(fnamep, bufp, &l) == FAIL)
22805 return -1;
22807 if (l == 0)
22809 /* Couldn't find the filename.. search the paths.
22811 l = *fnamelen;
22812 if (shortpath_for_invalid_fname(fnamep, bufp, &l) == FAIL)
22813 return -1;
22815 *fnamelen = l;
22818 #endif /* WIN3264 */
22820 /* ":t" - tail, just the basename */
22821 if (src[*usedlen] == ':' && src[*usedlen + 1] == 't')
22823 *usedlen += 2;
22824 *fnamelen -= (int)(tail - *fnamep);
22825 *fnamep = tail;
22828 /* ":e" - extension, can be repeated */
22829 /* ":r" - root, without extension, can be repeated */
22830 while (src[*usedlen] == ':'
22831 && (src[*usedlen + 1] == 'e' || src[*usedlen + 1] == 'r'))
22833 /* find a '.' in the tail:
22834 * - for second :e: before the current fname
22835 * - otherwise: The last '.'
22837 if (src[*usedlen + 1] == 'e' && *fnamep > tail)
22838 s = *fnamep - 2;
22839 else
22840 s = *fnamep + *fnamelen - 1;
22841 for ( ; s > tail; --s)
22842 if (s[0] == '.')
22843 break;
22844 if (src[*usedlen + 1] == 'e') /* :e */
22846 if (s > tail)
22848 *fnamelen += (int)(*fnamep - (s + 1));
22849 *fnamep = s + 1;
22850 #ifdef VMS
22851 /* cut version from the extension */
22852 s = *fnamep + *fnamelen - 1;
22853 for ( ; s > *fnamep; --s)
22854 if (s[0] == ';')
22855 break;
22856 if (s > *fnamep)
22857 *fnamelen = s - *fnamep;
22858 #endif
22860 else if (*fnamep <= tail)
22861 *fnamelen = 0;
22863 else /* :r */
22865 if (s > tail) /* remove one extension */
22866 *fnamelen = (int)(s - *fnamep);
22868 *usedlen += 2;
22871 /* ":s?pat?foo?" - substitute */
22872 /* ":gs?pat?foo?" - global substitute */
22873 if (src[*usedlen] == ':'
22874 && (src[*usedlen + 1] == 's'
22875 || (src[*usedlen + 1] == 'g' && src[*usedlen + 2] == 's')))
22877 char_u *str;
22878 char_u *pat;
22879 char_u *sub;
22880 int sep;
22881 char_u *flags;
22882 int didit = FALSE;
22884 flags = (char_u *)"";
22885 s = src + *usedlen + 2;
22886 if (src[*usedlen + 1] == 'g')
22888 flags = (char_u *)"g";
22889 ++s;
22892 sep = *s++;
22893 if (sep)
22895 /* find end of pattern */
22896 p = vim_strchr(s, sep);
22897 if (p != NULL)
22899 pat = vim_strnsave(s, (int)(p - s));
22900 if (pat != NULL)
22902 s = p + 1;
22903 /* find end of substitution */
22904 p = vim_strchr(s, sep);
22905 if (p != NULL)
22907 sub = vim_strnsave(s, (int)(p - s));
22908 str = vim_strnsave(*fnamep, *fnamelen);
22909 if (sub != NULL && str != NULL)
22911 *usedlen = (int)(p + 1 - src);
22912 s = do_string_sub(str, pat, sub, flags);
22913 if (s != NULL)
22915 *fnamep = s;
22916 *fnamelen = (int)STRLEN(s);
22917 vim_free(*bufp);
22918 *bufp = s;
22919 didit = TRUE;
22922 vim_free(sub);
22923 vim_free(str);
22925 vim_free(pat);
22928 /* after using ":s", repeat all the modifiers */
22929 if (didit)
22930 goto repeat;
22934 return valid;
22938 * Perform a substitution on "str" with pattern "pat" and substitute "sub".
22939 * "flags" can be "g" to do a global substitute.
22940 * Returns an allocated string, NULL for error.
22942 char_u *
22943 do_string_sub(str, pat, sub, flags)
22944 char_u *str;
22945 char_u *pat;
22946 char_u *sub;
22947 char_u *flags;
22949 int sublen;
22950 regmatch_T regmatch;
22951 int i;
22952 int do_all;
22953 char_u *tail;
22954 garray_T ga;
22955 char_u *ret;
22956 char_u *save_cpo;
22958 /* Make 'cpoptions' empty, so that the 'l' flag doesn't work here */
22959 save_cpo = p_cpo;
22960 p_cpo = empty_option;
22962 ga_init2(&ga, 1, 200);
22964 do_all = (flags[0] == 'g');
22966 regmatch.rm_ic = p_ic;
22967 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
22968 if (regmatch.regprog != NULL)
22970 tail = str;
22971 while (vim_regexec_nl(&regmatch, str, (colnr_T)(tail - str)))
22974 * Get some space for a temporary buffer to do the substitution
22975 * into. It will contain:
22976 * - The text up to where the match is.
22977 * - The substituted text.
22978 * - The text after the match.
22980 sublen = vim_regsub(&regmatch, sub, tail, FALSE, TRUE, FALSE);
22981 if (ga_grow(&ga, (int)(STRLEN(tail) + sublen -
22982 (regmatch.endp[0] - regmatch.startp[0]))) == FAIL)
22984 ga_clear(&ga);
22985 break;
22988 /* copy the text up to where the match is */
22989 i = (int)(regmatch.startp[0] - tail);
22990 mch_memmove((char_u *)ga.ga_data + ga.ga_len, tail, (size_t)i);
22991 /* add the substituted text */
22992 (void)vim_regsub(&regmatch, sub, (char_u *)ga.ga_data
22993 + ga.ga_len + i, TRUE, TRUE, FALSE);
22994 ga.ga_len += i + sublen - 1;
22995 /* avoid getting stuck on a match with an empty string */
22996 if (tail == regmatch.endp[0])
22998 if (*tail == NUL)
22999 break;
23000 *((char_u *)ga.ga_data + ga.ga_len) = *tail++;
23001 ++ga.ga_len;
23003 else
23005 tail = regmatch.endp[0];
23006 if (*tail == NUL)
23007 break;
23009 if (!do_all)
23010 break;
23013 if (ga.ga_data != NULL)
23014 STRCPY((char *)ga.ga_data + ga.ga_len, tail);
23016 vim_free(regmatch.regprog);
23019 ret = vim_strsave(ga.ga_data == NULL ? str : (char_u *)ga.ga_data);
23020 ga_clear(&ga);
23021 if (p_cpo == empty_option)
23022 p_cpo = save_cpo;
23023 else
23024 /* Darn, evaluating {sub} expression changed the value. */
23025 free_string_option(save_cpo);
23027 return ret;
23030 #endif /* defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) */