Patch 7.0.070
[MacVim/jjgod.git] / src / eval.c
blob76a3ff4ff602df684b419f2cc8ea23df75d9b5e0
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(MSWIN)
14 # include "vimio.h" /* for mch_open(), must be before vim.h */
15 #endif
17 #include "vim.h"
19 #ifdef AMIGA
20 # include <time.h> /* for strftime() */
21 #endif
23 #ifdef MACOS
24 # include <time.h> /* for time_t */
25 #endif
27 #ifdef HAVE_FCNTL_H
28 # include <fcntl.h>
29 #endif
31 #if defined(FEAT_EVAL) || defined(PROTO)
33 #define DICT_MAXNEST 100 /* maximum nesting of lists and dicts */
36 * In a hashtab item "hi_key" points to "di_key" in a dictitem.
37 * This avoids adding a pointer to the hashtab item.
38 * DI2HIKEY() converts a dictitem pointer to a hashitem key pointer.
39 * HIKEY2DI() converts a hashitem key pointer to a dictitem pointer.
40 * HI2DI() converts a hashitem pointer to a dictitem pointer.
42 static dictitem_T dumdi;
43 #define DI2HIKEY(di) ((di)->di_key)
44 #define HIKEY2DI(p) ((dictitem_T *)(p - (dumdi.di_key - (char_u *)&dumdi)))
45 #define HI2DI(hi) HIKEY2DI((hi)->hi_key)
48 * Structure returned by get_lval() and used by set_var_lval().
49 * For a plain name:
50 * "name" points to the variable name.
51 * "exp_name" is NULL.
52 * "tv" is NULL
53 * For a magic braces name:
54 * "name" points to the expanded variable name.
55 * "exp_name" is non-NULL, to be freed later.
56 * "tv" is NULL
57 * For an index in a list:
58 * "name" points to the (expanded) variable name.
59 * "exp_name" NULL or non-NULL, to be freed later.
60 * "tv" points to the (first) list item value
61 * "li" points to the (first) list item
62 * "range", "n1", "n2" and "empty2" indicate what items are used.
63 * For an existing Dict item:
64 * "name" points to the (expanded) variable name.
65 * "exp_name" NULL or non-NULL, to be freed later.
66 * "tv" points to the dict item value
67 * "newkey" is NULL
68 * For a non-existing Dict item:
69 * "name" points to the (expanded) variable name.
70 * "exp_name" NULL or non-NULL, to be freed later.
71 * "tv" points to the Dictionary typval_T
72 * "newkey" is the key for the new item.
74 typedef struct lval_S
76 char_u *ll_name; /* start of variable name (can be NULL) */
77 char_u *ll_exp_name; /* NULL or expanded name in allocated memory. */
78 typval_T *ll_tv; /* Typeval of item being used. If "newkey"
79 isn't NULL it's the Dict to which to add
80 the item. */
81 listitem_T *ll_li; /* The list item or NULL. */
82 list_T *ll_list; /* The list or NULL. */
83 int ll_range; /* TRUE when a [i:j] range was used */
84 long ll_n1; /* First index for list */
85 long ll_n2; /* Second index for list range */
86 int ll_empty2; /* Second index is empty: [i:] */
87 dict_T *ll_dict; /* The Dictionary or NULL */
88 dictitem_T *ll_di; /* The dictitem or NULL */
89 char_u *ll_newkey; /* New key for Dict in alloc. mem or NULL. */
90 } lval_T;
93 static char *e_letunexp = N_("E18: Unexpected characters in :let");
94 static char *e_listidx = N_("E684: list index out of range: %ld");
95 static char *e_undefvar = N_("E121: Undefined variable: %s");
96 static char *e_missbrac = N_("E111: Missing ']'");
97 static char *e_listarg = N_("E686: Argument of %s must be a List");
98 static char *e_listdictarg = N_("E712: Argument of %s must be a List or Dictionary");
99 static char *e_emptykey = N_("E713: Cannot use empty key for Dictionary");
100 static char *e_listreq = N_("E714: List required");
101 static char *e_dictreq = N_("E715: Dictionary required");
102 static char *e_toomanyarg = N_("E118: Too many arguments for function: %s");
103 static char *e_dictkey = N_("E716: Key not present in Dictionary: %s");
104 static char *e_funcexts = N_("E122: Function %s already exists, add ! to replace it");
105 static char *e_funcdict = N_("E717: Dictionary entry already exists");
106 static char *e_funcref = N_("E718: Funcref required");
107 static char *e_dictrange = N_("E719: Cannot use [:] with a Dictionary");
108 static char *e_letwrong = N_("E734: Wrong variable type for %s=");
109 static char *e_nofunc = N_("E130: Unknown function: %s");
110 static char *e_illvar = N_("E461: Illegal variable name: %s");
112 * All user-defined global variables are stored in dictionary "globvardict".
113 * "globvars_var" is the variable that is used for "g:".
115 static dict_T globvardict;
116 static dictitem_T globvars_var;
117 #define globvarht globvardict.dv_hashtab
120 * Old Vim variables such as "v:version" are also available without the "v:".
121 * Also in functions. We need a special hashtable for them.
123 static hashtab_T compat_hashtab;
126 * When recursively copying lists and dicts we need to remember which ones we
127 * have done to avoid endless recursiveness. This unique ID is used for that.
129 static int current_copyID = 0;
132 * Array to hold the hashtab with variables local to each sourced script.
133 * Each item holds a variable (nameless) that points to the dict_T.
135 typedef struct
137 dictitem_T sv_var;
138 dict_T sv_dict;
139 } scriptvar_T;
141 static garray_T ga_scripts = {0, 0, sizeof(scriptvar_T), 4, NULL};
142 #define SCRIPT_SV(id) (((scriptvar_T *)ga_scripts.ga_data)[(id) - 1])
143 #define SCRIPT_VARS(id) (SCRIPT_SV(id).sv_dict.dv_hashtab)
145 static int echo_attr = 0; /* attributes used for ":echo" */
147 /* Values for trans_function_name() argument: */
148 #define TFN_INT 1 /* internal function name OK */
149 #define TFN_QUIET 2 /* no error messages */
152 * Structure to hold info for a user function.
154 typedef struct ufunc ufunc_T;
156 struct ufunc
158 int uf_varargs; /* variable nr of arguments */
159 int uf_flags;
160 int uf_calls; /* nr of active calls */
161 garray_T uf_args; /* arguments */
162 garray_T uf_lines; /* function lines */
163 #ifdef FEAT_PROFILE
164 int uf_profiling; /* TRUE when func is being profiled */
165 /* profiling the function as a whole */
166 int uf_tm_count; /* nr of calls */
167 proftime_T uf_tm_total; /* time spend in function + children */
168 proftime_T uf_tm_self; /* time spend in function itself */
169 proftime_T uf_tm_start; /* time at function call */
170 proftime_T uf_tm_children; /* time spent in children this call */
171 /* profiling the function per line */
172 int *uf_tml_count; /* nr of times line was executed */
173 proftime_T *uf_tml_total; /* time spend in a line + children */
174 proftime_T *uf_tml_self; /* time spend in a line itself */
175 proftime_T uf_tml_start; /* start time for current line */
176 proftime_T uf_tml_children; /* time spent in children for this line */
177 proftime_T uf_tml_wait; /* start wait time for current line */
178 int uf_tml_idx; /* index of line being timed; -1 if none */
179 int uf_tml_execed; /* line being timed was executed */
180 #endif
181 scid_T uf_script_ID; /* ID of script where function was defined,
182 used for s: variables */
183 int uf_refcount; /* for numbered function: reference count */
184 char_u uf_name[1]; /* name of function (actually longer); can
185 start with <SNR>123_ (<SNR> is K_SPECIAL
186 KS_EXTRA KE_SNR) */
189 /* function flags */
190 #define FC_ABORT 1 /* abort function on error */
191 #define FC_RANGE 2 /* function accepts range */
192 #define FC_DICT 4 /* Dict function, uses "self" */
194 #define DEL_REFCOUNT 999999 /* list/dict is being deleted */
197 * All user-defined functions are found in this hashtable.
199 static hashtab_T func_hashtab;
201 /* The names of packages that once were loaded are remembered. */
202 static garray_T ga_loaded = {0, 0, sizeof(char_u *), 4, NULL};
204 /* list heads for garbage collection */
205 static dict_T *first_dict = NULL; /* list of all dicts */
206 static list_T *first_list = NULL; /* list of all lists */
208 /* From user function to hashitem and back. */
209 static ufunc_T dumuf;
210 #define UF2HIKEY(fp) ((fp)->uf_name)
211 #define HIKEY2UF(p) ((ufunc_T *)(p - (dumuf.uf_name - (char_u *)&dumuf)))
212 #define HI2UF(hi) HIKEY2UF((hi)->hi_key)
214 #define FUNCARG(fp, j) ((char_u **)(fp->uf_args.ga_data))[j]
215 #define FUNCLINE(fp, j) ((char_u **)(fp->uf_lines.ga_data))[j]
217 #define MAX_FUNC_ARGS 20 /* maximum number of function arguments */
218 #define VAR_SHORT_LEN 20 /* short variable name length */
219 #define FIXVAR_CNT 12 /* number of fixed variables */
221 /* structure to hold info for a function that is currently being executed. */
222 typedef struct funccall_S funccall_T;
224 struct funccall_S
226 ufunc_T *func; /* function being called */
227 int linenr; /* next line to be executed */
228 int returned; /* ":return" used */
229 struct /* fixed variables for arguments */
231 dictitem_T var; /* variable (without room for name) */
232 char_u room[VAR_SHORT_LEN]; /* room for the name */
233 } fixvar[FIXVAR_CNT];
234 dict_T l_vars; /* l: local function variables */
235 dictitem_T l_vars_var; /* variable for l: scope */
236 dict_T l_avars; /* a: argument variables */
237 dictitem_T l_avars_var; /* variable for a: scope */
238 list_T l_varlist; /* list for a:000 */
239 listitem_T l_listitems[MAX_FUNC_ARGS]; /* listitems for a:000 */
240 typval_T *rettv; /* return value */
241 linenr_T breakpoint; /* next line with breakpoint or zero */
242 int dbg_tick; /* debug_tick when breakpoint was set */
243 int level; /* top nesting level of executed function */
244 #ifdef FEAT_PROFILE
245 proftime_T prof_child; /* time spent in a child */
246 #endif
247 funccall_T *caller; /* calling function or NULL */
251 * Info used by a ":for" loop.
253 typedef struct
255 int fi_semicolon; /* TRUE if ending in '; var]' */
256 int fi_varcount; /* nr of variables in the list */
257 listwatch_T fi_lw; /* keep an eye on the item used. */
258 list_T *fi_list; /* list being used */
259 } forinfo_T;
262 * Struct used by trans_function_name()
264 typedef struct
266 dict_T *fd_dict; /* Dictionary used */
267 char_u *fd_newkey; /* new key in "dict" in allocated memory */
268 dictitem_T *fd_di; /* Dictionary item used */
269 } funcdict_T;
273 * Array to hold the value of v: variables.
274 * The value is in a dictitem, so that it can also be used in the v: scope.
275 * The reason to use this table anyway is for very quick access to the
276 * variables with the VV_ defines.
278 #include "version.h"
280 /* values for vv_flags: */
281 #define VV_COMPAT 1 /* compatible, also used without "v:" */
282 #define VV_RO 2 /* read-only */
283 #define VV_RO_SBX 4 /* read-only in the sandbox */
285 #define VV_NAME(s, t) s, {{t}}, {0}
287 static struct vimvar
289 char *vv_name; /* name of variable, without v: */
290 dictitem_T vv_di; /* value and name for key */
291 char vv_filler[16]; /* space for LONGEST name below!!! */
292 char vv_flags; /* VV_COMPAT, VV_RO, VV_RO_SBX */
293 } vimvars[VV_LEN] =
296 * The order here must match the VV_ defines in vim.h!
297 * Initializing a union does not work, leave tv.vval empty to get zero's.
299 {VV_NAME("count", VAR_NUMBER), VV_COMPAT+VV_RO},
300 {VV_NAME("count1", VAR_NUMBER), VV_RO},
301 {VV_NAME("prevcount", VAR_NUMBER), VV_RO},
302 {VV_NAME("errmsg", VAR_STRING), VV_COMPAT},
303 {VV_NAME("warningmsg", VAR_STRING), 0},
304 {VV_NAME("statusmsg", VAR_STRING), 0},
305 {VV_NAME("shell_error", VAR_NUMBER), VV_COMPAT+VV_RO},
306 {VV_NAME("this_session", VAR_STRING), VV_COMPAT},
307 {VV_NAME("version", VAR_NUMBER), VV_COMPAT+VV_RO},
308 {VV_NAME("lnum", VAR_NUMBER), VV_RO_SBX},
309 {VV_NAME("termresponse", VAR_STRING), VV_RO},
310 {VV_NAME("fname", VAR_STRING), VV_RO},
311 {VV_NAME("lang", VAR_STRING), VV_RO},
312 {VV_NAME("lc_time", VAR_STRING), VV_RO},
313 {VV_NAME("ctype", VAR_STRING), VV_RO},
314 {VV_NAME("charconvert_from", VAR_STRING), VV_RO},
315 {VV_NAME("charconvert_to", VAR_STRING), VV_RO},
316 {VV_NAME("fname_in", VAR_STRING), VV_RO},
317 {VV_NAME("fname_out", VAR_STRING), VV_RO},
318 {VV_NAME("fname_new", VAR_STRING), VV_RO},
319 {VV_NAME("fname_diff", VAR_STRING), VV_RO},
320 {VV_NAME("cmdarg", VAR_STRING), VV_RO},
321 {VV_NAME("foldstart", VAR_NUMBER), VV_RO_SBX},
322 {VV_NAME("foldend", VAR_NUMBER), VV_RO_SBX},
323 {VV_NAME("folddashes", VAR_STRING), VV_RO_SBX},
324 {VV_NAME("foldlevel", VAR_NUMBER), VV_RO_SBX},
325 {VV_NAME("progname", VAR_STRING), VV_RO},
326 {VV_NAME("servername", VAR_STRING), VV_RO},
327 {VV_NAME("dying", VAR_NUMBER), VV_RO},
328 {VV_NAME("exception", VAR_STRING), VV_RO},
329 {VV_NAME("throwpoint", VAR_STRING), VV_RO},
330 {VV_NAME("register", VAR_STRING), VV_RO},
331 {VV_NAME("cmdbang", VAR_NUMBER), VV_RO},
332 {VV_NAME("insertmode", VAR_STRING), VV_RO},
333 {VV_NAME("val", VAR_UNKNOWN), VV_RO},
334 {VV_NAME("key", VAR_UNKNOWN), VV_RO},
335 {VV_NAME("profiling", VAR_NUMBER), VV_RO},
336 {VV_NAME("fcs_reason", VAR_STRING), VV_RO},
337 {VV_NAME("fcs_choice", VAR_STRING), 0},
338 {VV_NAME("beval_bufnr", VAR_NUMBER), VV_RO},
339 {VV_NAME("beval_winnr", VAR_NUMBER), VV_RO},
340 {VV_NAME("beval_lnum", VAR_NUMBER), VV_RO},
341 {VV_NAME("beval_col", VAR_NUMBER), VV_RO},
342 {VV_NAME("beval_text", VAR_STRING), VV_RO},
343 {VV_NAME("scrollstart", VAR_STRING), 0},
344 {VV_NAME("swapname", VAR_STRING), VV_RO},
345 {VV_NAME("swapchoice", VAR_STRING), 0},
346 {VV_NAME("swapcommand", VAR_STRING), VV_RO},
347 {VV_NAME("char", VAR_STRING), VV_RO},
350 /* shorthand */
351 #define vv_type vv_di.di_tv.v_type
352 #define vv_nr vv_di.di_tv.vval.v_number
353 #define vv_str vv_di.di_tv.vval.v_string
354 #define vv_tv vv_di.di_tv
357 * The v: variables are stored in dictionary "vimvardict".
358 * "vimvars_var" is the variable that is used for the "l:" scope.
360 static dict_T vimvardict;
361 static dictitem_T vimvars_var;
362 #define vimvarht vimvardict.dv_hashtab
364 static void prepare_vimvar __ARGS((int idx, typval_T *save_tv));
365 static void restore_vimvar __ARGS((int idx, typval_T *save_tv));
366 #if defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)
367 static int call_vim_function __ARGS((char_u *func, int argc, char_u **argv, int safe, typval_T *rettv));
368 #endif
369 static int ex_let_vars __ARGS((char_u *arg, typval_T *tv, int copy, int semicolon, int var_count, char_u *nextchars));
370 static char_u *skip_var_list __ARGS((char_u *arg, int *var_count, int *semicolon));
371 static char_u *skip_var_one __ARGS((char_u *arg));
372 static void list_hashtable_vars __ARGS((hashtab_T *ht, char_u *prefix, int empty));
373 static void list_glob_vars __ARGS((void));
374 static void list_buf_vars __ARGS((void));
375 static void list_win_vars __ARGS((void));
376 #ifdef FEAT_WINDOWS
377 static void list_tab_vars __ARGS((void));
378 #endif
379 static void list_vim_vars __ARGS((void));
380 static void list_script_vars __ARGS((void));
381 static void list_func_vars __ARGS((void));
382 static char_u *list_arg_vars __ARGS((exarg_T *eap, char_u *arg));
383 static char_u *ex_let_one __ARGS((char_u *arg, typval_T *tv, int copy, char_u *endchars, char_u *op));
384 static int check_changedtick __ARGS((char_u *arg));
385 static char_u *get_lval __ARGS((char_u *name, typval_T *rettv, lval_T *lp, int unlet, int skip, int quiet, int fne_flags));
386 static void clear_lval __ARGS((lval_T *lp));
387 static void set_var_lval __ARGS((lval_T *lp, char_u *endp, typval_T *rettv, int copy, char_u *op));
388 static int tv_op __ARGS((typval_T *tv1, typval_T *tv2, char_u *op));
389 static void list_add_watch __ARGS((list_T *l, listwatch_T *lw));
390 static void list_rem_watch __ARGS((list_T *l, listwatch_T *lwrem));
391 static void list_fix_watch __ARGS((list_T *l, listitem_T *item));
392 static void ex_unletlock __ARGS((exarg_T *eap, char_u *argstart, int deep));
393 static int do_unlet_var __ARGS((lval_T *lp, char_u *name_end, int forceit));
394 static int do_lock_var __ARGS((lval_T *lp, char_u *name_end, int deep, int lock));
395 static void item_lock __ARGS((typval_T *tv, int deep, int lock));
396 static int tv_islocked __ARGS((typval_T *tv));
398 static int eval0 __ARGS((char_u *arg, typval_T *rettv, char_u **nextcmd, int evaluate));
399 static int eval1 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
400 static int eval2 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
401 static int eval3 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
402 static int eval4 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
403 static int eval5 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
404 static int eval6 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
405 static int eval7 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
407 static int eval_index __ARGS((char_u **arg, typval_T *rettv, int evaluate, int verbose));
408 static int get_option_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
409 static int get_string_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
410 static int get_lit_string_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
411 static int get_list_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
412 static int rettv_list_alloc __ARGS((typval_T *rettv));
413 static listitem_T *listitem_alloc __ARGS((void));
414 static void listitem_free __ARGS((listitem_T *item));
415 static void listitem_remove __ARGS((list_T *l, listitem_T *item));
416 static long list_len __ARGS((list_T *l));
417 static int list_equal __ARGS((list_T *l1, list_T *l2, int ic));
418 static int dict_equal __ARGS((dict_T *d1, dict_T *d2, int ic));
419 static int tv_equal __ARGS((typval_T *tv1, typval_T *tv2, int ic));
420 static listitem_T *list_find __ARGS((list_T *l, long n));
421 static long list_find_nr __ARGS((list_T *l, long idx, int *errorp));
422 static long list_idx_of_item __ARGS((list_T *l, listitem_T *item));
423 static void list_append __ARGS((list_T *l, listitem_T *item));
424 static int list_append_tv __ARGS((list_T *l, typval_T *tv));
425 static int list_append_string __ARGS((list_T *l, char_u *str, int len));
426 static int list_append_number __ARGS((list_T *l, varnumber_T n));
427 static int list_insert_tv __ARGS((list_T *l, typval_T *tv, listitem_T *item));
428 static int list_extend __ARGS((list_T *l1, list_T *l2, listitem_T *bef));
429 static int list_concat __ARGS((list_T *l1, list_T *l2, typval_T *tv));
430 static list_T *list_copy __ARGS((list_T *orig, int deep, int copyID));
431 static void list_remove __ARGS((list_T *l, listitem_T *item, listitem_T *item2));
432 static char_u *list2string __ARGS((typval_T *tv, int copyID));
433 static int list_join __ARGS((garray_T *gap, list_T *l, char_u *sep, int echo, int copyID));
434 static void set_ref_in_ht __ARGS((hashtab_T *ht, int copyID));
435 static void set_ref_in_list __ARGS((list_T *l, int copyID));
436 static void set_ref_in_item __ARGS((typval_T *tv, int copyID));
437 static void dict_unref __ARGS((dict_T *d));
438 static void dict_free __ARGS((dict_T *d));
439 static dictitem_T *dictitem_alloc __ARGS((char_u *key));
440 static dictitem_T *dictitem_copy __ARGS((dictitem_T *org));
441 static void dictitem_remove __ARGS((dict_T *dict, dictitem_T *item));
442 static void dictitem_free __ARGS((dictitem_T *item));
443 static dict_T *dict_copy __ARGS((dict_T *orig, int deep, int copyID));
444 static int dict_add __ARGS((dict_T *d, dictitem_T *item));
445 static long dict_len __ARGS((dict_T *d));
446 static dictitem_T *dict_find __ARGS((dict_T *d, char_u *key, int len));
447 static char_u *dict2string __ARGS((typval_T *tv, int copyID));
448 static int get_dict_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
449 static char_u *echo_string __ARGS((typval_T *tv, char_u **tofree, char_u *numbuf, int copyID));
450 static char_u *tv2string __ARGS((typval_T *tv, char_u **tofree, char_u *numbuf, int copyID));
451 static char_u *string_quote __ARGS((char_u *str, int function));
452 static int get_env_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
453 static int find_internal_func __ARGS((char_u *name));
454 static char_u *deref_func_name __ARGS((char_u *name, int *lenp));
455 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));
456 static int call_func __ARGS((char_u *name, int len, typval_T *rettv, int argcount, typval_T *argvars, linenr_T firstline, linenr_T lastline, int *doesrange, int evaluate, dict_T *selfdict));
457 static void emsg_funcname __ARGS((char *ermsg, char_u *name));
459 static void f_add __ARGS((typval_T *argvars, typval_T *rettv));
460 static void f_append __ARGS((typval_T *argvars, typval_T *rettv));
461 static void f_argc __ARGS((typval_T *argvars, typval_T *rettv));
462 static void f_argidx __ARGS((typval_T *argvars, typval_T *rettv));
463 static void f_argv __ARGS((typval_T *argvars, typval_T *rettv));
464 static void f_browse __ARGS((typval_T *argvars, typval_T *rettv));
465 static void f_browsedir __ARGS((typval_T *argvars, typval_T *rettv));
466 static void f_bufexists __ARGS((typval_T *argvars, typval_T *rettv));
467 static void f_buflisted __ARGS((typval_T *argvars, typval_T *rettv));
468 static void f_bufloaded __ARGS((typval_T *argvars, typval_T *rettv));
469 static void f_bufname __ARGS((typval_T *argvars, typval_T *rettv));
470 static void f_bufnr __ARGS((typval_T *argvars, typval_T *rettv));
471 static void f_bufwinnr __ARGS((typval_T *argvars, typval_T *rettv));
472 static void f_byte2line __ARGS((typval_T *argvars, typval_T *rettv));
473 static void f_byteidx __ARGS((typval_T *argvars, typval_T *rettv));
474 static void f_call __ARGS((typval_T *argvars, typval_T *rettv));
475 static void f_changenr __ARGS((typval_T *argvars, typval_T *rettv));
476 static void f_char2nr __ARGS((typval_T *argvars, typval_T *rettv));
477 static void f_cindent __ARGS((typval_T *argvars, typval_T *rettv));
478 static void f_col __ARGS((typval_T *argvars, typval_T *rettv));
479 #if defined(FEAT_INS_EXPAND)
480 static void f_complete __ARGS((typval_T *argvars, typval_T *rettv));
481 static void f_complete_add __ARGS((typval_T *argvars, typval_T *rettv));
482 static void f_complete_check __ARGS((typval_T *argvars, typval_T *rettv));
483 #endif
484 static void f_confirm __ARGS((typval_T *argvars, typval_T *rettv));
485 static void f_copy __ARGS((typval_T *argvars, typval_T *rettv));
486 static void f_count __ARGS((typval_T *argvars, typval_T *rettv));
487 static void f_cscope_connection __ARGS((typval_T *argvars, typval_T *rettv));
488 static void f_cursor __ARGS((typval_T *argsvars, typval_T *rettv));
489 static void f_deepcopy __ARGS((typval_T *argvars, typval_T *rettv));
490 static void f_delete __ARGS((typval_T *argvars, typval_T *rettv));
491 static void f_did_filetype __ARGS((typval_T *argvars, typval_T *rettv));
492 static void f_diff_filler __ARGS((typval_T *argvars, typval_T *rettv));
493 static void f_diff_hlID __ARGS((typval_T *argvars, typval_T *rettv));
494 static void f_empty __ARGS((typval_T *argvars, typval_T *rettv));
495 static void f_escape __ARGS((typval_T *argvars, typval_T *rettv));
496 static void f_eval __ARGS((typval_T *argvars, typval_T *rettv));
497 static void f_eventhandler __ARGS((typval_T *argvars, typval_T *rettv));
498 static void f_executable __ARGS((typval_T *argvars, typval_T *rettv));
499 static void f_exists __ARGS((typval_T *argvars, typval_T *rettv));
500 static void f_expand __ARGS((typval_T *argvars, typval_T *rettv));
501 static void f_extend __ARGS((typval_T *argvars, typval_T *rettv));
502 static void f_feedkeys __ARGS((typval_T *argvars, typval_T *rettv));
503 static void f_filereadable __ARGS((typval_T *argvars, typval_T *rettv));
504 static void f_filewritable __ARGS((typval_T *argvars, typval_T *rettv));
505 static void f_filter __ARGS((typval_T *argvars, typval_T *rettv));
506 static void f_finddir __ARGS((typval_T *argvars, typval_T *rettv));
507 static void f_findfile __ARGS((typval_T *argvars, typval_T *rettv));
508 static void f_fnamemodify __ARGS((typval_T *argvars, typval_T *rettv));
509 static void f_foldclosed __ARGS((typval_T *argvars, typval_T *rettv));
510 static void f_foldclosedend __ARGS((typval_T *argvars, typval_T *rettv));
511 static void f_foldlevel __ARGS((typval_T *argvars, typval_T *rettv));
512 static void f_foldtext __ARGS((typval_T *argvars, typval_T *rettv));
513 static void f_foldtextresult __ARGS((typval_T *argvars, typval_T *rettv));
514 static void f_foreground __ARGS((typval_T *argvars, typval_T *rettv));
515 static void f_function __ARGS((typval_T *argvars, typval_T *rettv));
516 static void f_garbagecollect __ARGS((typval_T *argvars, typval_T *rettv));
517 static void f_get __ARGS((typval_T *argvars, typval_T *rettv));
518 static void f_getbufline __ARGS((typval_T *argvars, typval_T *rettv));
519 static void f_getbufvar __ARGS((typval_T *argvars, typval_T *rettv));
520 static void f_getchar __ARGS((typval_T *argvars, typval_T *rettv));
521 static void f_getcharmod __ARGS((typval_T *argvars, typval_T *rettv));
522 static void f_getcmdline __ARGS((typval_T *argvars, typval_T *rettv));
523 static void f_getcmdpos __ARGS((typval_T *argvars, typval_T *rettv));
524 static void f_getcmdtype __ARGS((typval_T *argvars, typval_T *rettv));
525 static void f_getcwd __ARGS((typval_T *argvars, typval_T *rettv));
526 static void f_getfontname __ARGS((typval_T *argvars, typval_T *rettv));
527 static void f_getfperm __ARGS((typval_T *argvars, typval_T *rettv));
528 static void f_getfsize __ARGS((typval_T *argvars, typval_T *rettv));
529 static void f_getftime __ARGS((typval_T *argvars, typval_T *rettv));
530 static void f_getftype __ARGS((typval_T *argvars, typval_T *rettv));
531 static void f_getline __ARGS((typval_T *argvars, typval_T *rettv));
532 static void f_getpos __ARGS((typval_T *argvars, typval_T *rettv));
533 static void f_getqflist __ARGS((typval_T *argvars, typval_T *rettv));
534 static void f_getreg __ARGS((typval_T *argvars, typval_T *rettv));
535 static void f_getregtype __ARGS((typval_T *argvars, typval_T *rettv));
536 static void f_gettabwinvar __ARGS((typval_T *argvars, typval_T *rettv));
537 static void f_getwinposx __ARGS((typval_T *argvars, typval_T *rettv));
538 static void f_getwinposy __ARGS((typval_T *argvars, typval_T *rettv));
539 static void f_getwinvar __ARGS((typval_T *argvars, typval_T *rettv));
540 static void f_glob __ARGS((typval_T *argvars, typval_T *rettv));
541 static void f_globpath __ARGS((typval_T *argvars, typval_T *rettv));
542 static void f_has __ARGS((typval_T *argvars, typval_T *rettv));
543 static void f_has_key __ARGS((typval_T *argvars, typval_T *rettv));
544 static void f_hasmapto __ARGS((typval_T *argvars, typval_T *rettv));
545 static void f_histadd __ARGS((typval_T *argvars, typval_T *rettv));
546 static void f_histdel __ARGS((typval_T *argvars, typval_T *rettv));
547 static void f_histget __ARGS((typval_T *argvars, typval_T *rettv));
548 static void f_histnr __ARGS((typval_T *argvars, typval_T *rettv));
549 static void f_hlID __ARGS((typval_T *argvars, typval_T *rettv));
550 static void f_hlexists __ARGS((typval_T *argvars, typval_T *rettv));
551 static void f_hostname __ARGS((typval_T *argvars, typval_T *rettv));
552 static void f_iconv __ARGS((typval_T *argvars, typval_T *rettv));
553 static void f_indent __ARGS((typval_T *argvars, typval_T *rettv));
554 static void f_index __ARGS((typval_T *argvars, typval_T *rettv));
555 static void f_input __ARGS((typval_T *argvars, typval_T *rettv));
556 static void f_inputdialog __ARGS((typval_T *argvars, typval_T *rettv));
557 static void f_inputlist __ARGS((typval_T *argvars, typval_T *rettv));
558 static void f_inputrestore __ARGS((typval_T *argvars, typval_T *rettv));
559 static void f_inputsave __ARGS((typval_T *argvars, typval_T *rettv));
560 static void f_inputsecret __ARGS((typval_T *argvars, typval_T *rettv));
561 static void f_insert __ARGS((typval_T *argvars, typval_T *rettv));
562 static void f_isdirectory __ARGS((typval_T *argvars, typval_T *rettv));
563 static void f_islocked __ARGS((typval_T *argvars, typval_T *rettv));
564 static void f_items __ARGS((typval_T *argvars, typval_T *rettv));
565 static void f_join __ARGS((typval_T *argvars, typval_T *rettv));
566 static void f_keys __ARGS((typval_T *argvars, typval_T *rettv));
567 static void f_last_buffer_nr __ARGS((typval_T *argvars, typval_T *rettv));
568 static void f_len __ARGS((typval_T *argvars, typval_T *rettv));
569 static void f_libcall __ARGS((typval_T *argvars, typval_T *rettv));
570 static void f_libcallnr __ARGS((typval_T *argvars, typval_T *rettv));
571 static void f_line __ARGS((typval_T *argvars, typval_T *rettv));
572 static void f_line2byte __ARGS((typval_T *argvars, typval_T *rettv));
573 static void f_lispindent __ARGS((typval_T *argvars, typval_T *rettv));
574 static void f_localtime __ARGS((typval_T *argvars, typval_T *rettv));
575 static void f_map __ARGS((typval_T *argvars, typval_T *rettv));
576 static void f_maparg __ARGS((typval_T *argvars, typval_T *rettv));
577 static void f_mapcheck __ARGS((typval_T *argvars, typval_T *rettv));
578 static void f_match __ARGS((typval_T *argvars, typval_T *rettv));
579 static void f_matcharg __ARGS((typval_T *argvars, typval_T *rettv));
580 static void f_matchend __ARGS((typval_T *argvars, typval_T *rettv));
581 static void f_matchlist __ARGS((typval_T *argvars, typval_T *rettv));
582 static void f_matchstr __ARGS((typval_T *argvars, typval_T *rettv));
583 static void f_max __ARGS((typval_T *argvars, typval_T *rettv));
584 static void f_min __ARGS((typval_T *argvars, typval_T *rettv));
585 #ifdef vim_mkdir
586 static void f_mkdir __ARGS((typval_T *argvars, typval_T *rettv));
587 #endif
588 static void f_mode __ARGS((typval_T *argvars, typval_T *rettv));
589 static void f_nextnonblank __ARGS((typval_T *argvars, typval_T *rettv));
590 static void f_nr2char __ARGS((typval_T *argvars, typval_T *rettv));
591 static void f_pathshorten __ARGS((typval_T *argvars, typval_T *rettv));
592 static void f_prevnonblank __ARGS((typval_T *argvars, typval_T *rettv));
593 static void f_printf __ARGS((typval_T *argvars, typval_T *rettv));
594 static void f_pumvisible __ARGS((typval_T *argvars, typval_T *rettv));
595 static void f_range __ARGS((typval_T *argvars, typval_T *rettv));
596 static void f_readfile __ARGS((typval_T *argvars, typval_T *rettv));
597 static void f_reltime __ARGS((typval_T *argvars, typval_T *rettv));
598 static void f_reltimestr __ARGS((typval_T *argvars, typval_T *rettv));
599 static void f_remote_expr __ARGS((typval_T *argvars, typval_T *rettv));
600 static void f_remote_foreground __ARGS((typval_T *argvars, typval_T *rettv));
601 static void f_remote_peek __ARGS((typval_T *argvars, typval_T *rettv));
602 static void f_remote_read __ARGS((typval_T *argvars, typval_T *rettv));
603 static void f_remote_send __ARGS((typval_T *argvars, typval_T *rettv));
604 static void f_remove __ARGS((typval_T *argvars, typval_T *rettv));
605 static void f_rename __ARGS((typval_T *argvars, typval_T *rettv));
606 static void f_repeat __ARGS((typval_T *argvars, typval_T *rettv));
607 static void f_resolve __ARGS((typval_T *argvars, typval_T *rettv));
608 static void f_reverse __ARGS((typval_T *argvars, typval_T *rettv));
609 static void f_search __ARGS((typval_T *argvars, typval_T *rettv));
610 static void f_searchdecl __ARGS((typval_T *argvars, typval_T *rettv));
611 static void f_searchpair __ARGS((typval_T *argvars, typval_T *rettv));
612 static void f_searchpairpos __ARGS((typval_T *argvars, typval_T *rettv));
613 static void f_searchpos __ARGS((typval_T *argvars, typval_T *rettv));
614 static void f_server2client __ARGS((typval_T *argvars, typval_T *rettv));
615 static void f_serverlist __ARGS((typval_T *argvars, typval_T *rettv));
616 static void f_setbufvar __ARGS((typval_T *argvars, typval_T *rettv));
617 static void f_setcmdpos __ARGS((typval_T *argvars, typval_T *rettv));
618 static void f_setline __ARGS((typval_T *argvars, typval_T *rettv));
619 static void f_setloclist __ARGS((typval_T *argvars, typval_T *rettv));
620 static void f_setpos __ARGS((typval_T *argvars, typval_T *rettv));
621 static void f_setqflist __ARGS((typval_T *argvars, typval_T *rettv));
622 static void f_setreg __ARGS((typval_T *argvars, typval_T *rettv));
623 static void f_settabwinvar __ARGS((typval_T *argvars, typval_T *rettv));
624 static void f_setwinvar __ARGS((typval_T *argvars, typval_T *rettv));
625 static void f_simplify __ARGS((typval_T *argvars, typval_T *rettv));
626 static void f_sort __ARGS((typval_T *argvars, typval_T *rettv));
627 static void f_soundfold __ARGS((typval_T *argvars, typval_T *rettv));
628 static void f_spellbadword __ARGS((typval_T *argvars, typval_T *rettv));
629 static void f_spellsuggest __ARGS((typval_T *argvars, typval_T *rettv));
630 static void f_split __ARGS((typval_T *argvars, typval_T *rettv));
631 static void f_str2nr __ARGS((typval_T *argvars, typval_T *rettv));
632 #ifdef HAVE_STRFTIME
633 static void f_strftime __ARGS((typval_T *argvars, typval_T *rettv));
634 #endif
635 static void f_stridx __ARGS((typval_T *argvars, typval_T *rettv));
636 static void f_string __ARGS((typval_T *argvars, typval_T *rettv));
637 static void f_strlen __ARGS((typval_T *argvars, typval_T *rettv));
638 static void f_strpart __ARGS((typval_T *argvars, typval_T *rettv));
639 static void f_strridx __ARGS((typval_T *argvars, typval_T *rettv));
640 static void f_strtrans __ARGS((typval_T *argvars, typval_T *rettv));
641 static void f_submatch __ARGS((typval_T *argvars, typval_T *rettv));
642 static void f_substitute __ARGS((typval_T *argvars, typval_T *rettv));
643 static void f_synID __ARGS((typval_T *argvars, typval_T *rettv));
644 static void f_synIDattr __ARGS((typval_T *argvars, typval_T *rettv));
645 static void f_synIDtrans __ARGS((typval_T *argvars, typval_T *rettv));
646 static void f_system __ARGS((typval_T *argvars, typval_T *rettv));
647 static void f_tabpagebuflist __ARGS((typval_T *argvars, typval_T *rettv));
648 static void f_tabpagenr __ARGS((typval_T *argvars, typval_T *rettv));
649 static void f_tabpagewinnr __ARGS((typval_T *argvars, typval_T *rettv));
650 static void f_taglist __ARGS((typval_T *argvars, typval_T *rettv));
651 static void f_tagfiles __ARGS((typval_T *argvars, typval_T *rettv));
652 static void f_tempname __ARGS((typval_T *argvars, typval_T *rettv));
653 static void f_test __ARGS((typval_T *argvars, typval_T *rettv));
654 static void f_tolower __ARGS((typval_T *argvars, typval_T *rettv));
655 static void f_toupper __ARGS((typval_T *argvars, typval_T *rettv));
656 static void f_tr __ARGS((typval_T *argvars, typval_T *rettv));
657 static void f_type __ARGS((typval_T *argvars, typval_T *rettv));
658 static void f_values __ARGS((typval_T *argvars, typval_T *rettv));
659 static void f_virtcol __ARGS((typval_T *argvars, typval_T *rettv));
660 static void f_visualmode __ARGS((typval_T *argvars, typval_T *rettv));
661 static void f_winbufnr __ARGS((typval_T *argvars, typval_T *rettv));
662 static void f_wincol __ARGS((typval_T *argvars, typval_T *rettv));
663 static void f_winheight __ARGS((typval_T *argvars, typval_T *rettv));
664 static void f_winline __ARGS((typval_T *argvars, typval_T *rettv));
665 static void f_winnr __ARGS((typval_T *argvars, typval_T *rettv));
666 static void f_winrestcmd __ARGS((typval_T *argvars, typval_T *rettv));
667 static void f_winrestview __ARGS((typval_T *argvars, typval_T *rettv));
668 static void f_winsaveview __ARGS((typval_T *argvars, typval_T *rettv));
669 static void f_winwidth __ARGS((typval_T *argvars, typval_T *rettv));
670 static void f_writefile __ARGS((typval_T *argvars, typval_T *rettv));
672 static int list2fpos __ARGS((typval_T *arg, pos_T *posp, int *fnump));
673 static pos_T *var2fpos __ARGS((typval_T *varp, int lnum, int *fnum));
674 static int get_env_len __ARGS((char_u **arg));
675 static int get_id_len __ARGS((char_u **arg));
676 static int get_name_len __ARGS((char_u **arg, char_u **alias, int evaluate, int verbose));
677 static char_u *find_name_end __ARGS((char_u *arg, char_u **expr_start, char_u **expr_end, int flags));
678 #define FNE_INCL_BR 1 /* find_name_end(): include [] in name */
679 #define FNE_CHECK_START 2 /* find_name_end(): check name starts with
680 valid character */
681 static char_u * make_expanded_name __ARGS((char_u *in_start, char_u *expr_start, char_u *expr_end, char_u *in_end));
682 static int eval_isnamec __ARGS((int c));
683 static int eval_isnamec1 __ARGS((int c));
684 static int get_var_tv __ARGS((char_u *name, int len, typval_T *rettv, int verbose));
685 static int handle_subscript __ARGS((char_u **arg, typval_T *rettv, int evaluate, int verbose));
686 static typval_T *alloc_tv __ARGS((void));
687 static typval_T *alloc_string_tv __ARGS((char_u *string));
688 static void init_tv __ARGS((typval_T *varp));
689 static long get_tv_number __ARGS((typval_T *varp));
690 static linenr_T get_tv_lnum __ARGS((typval_T *argvars));
691 static linenr_T get_tv_lnum_buf __ARGS((typval_T *argvars, buf_T *buf));
692 static char_u *get_tv_string __ARGS((typval_T *varp));
693 static char_u *get_tv_string_buf __ARGS((typval_T *varp, char_u *buf));
694 static char_u *get_tv_string_buf_chk __ARGS((typval_T *varp, char_u *buf));
695 static dictitem_T *find_var __ARGS((char_u *name, hashtab_T **htp));
696 static dictitem_T *find_var_in_ht __ARGS((hashtab_T *ht, char_u *varname, int writing));
697 static hashtab_T *find_var_ht __ARGS((char_u *name, char_u **varname));
698 static void vars_clear_ext __ARGS((hashtab_T *ht, int free_val));
699 static void delete_var __ARGS((hashtab_T *ht, hashitem_T *hi));
700 static void list_one_var __ARGS((dictitem_T *v, char_u *prefix));
701 static void list_one_var_a __ARGS((char_u *prefix, char_u *name, int type, char_u *string));
702 static void set_var __ARGS((char_u *name, typval_T *varp, int copy));
703 static int var_check_ro __ARGS((int flags, char_u *name));
704 static int tv_check_lock __ARGS((int lock, char_u *name));
705 static void copy_tv __ARGS((typval_T *from, typval_T *to));
706 static int item_copy __ARGS((typval_T *from, typval_T *to, int deep, int copyID));
707 static char_u *find_option_end __ARGS((char_u **arg, int *opt_flags));
708 static char_u *trans_function_name __ARGS((char_u **pp, int skip, int flags, funcdict_T *fd));
709 static int eval_fname_script __ARGS((char_u *p));
710 static int eval_fname_sid __ARGS((char_u *p));
711 static void list_func_head __ARGS((ufunc_T *fp, int indent));
712 static ufunc_T *find_func __ARGS((char_u *name));
713 static int function_exists __ARGS((char_u *name));
714 static int builtin_function __ARGS((char_u *name));
715 #ifdef FEAT_PROFILE
716 static void func_do_profile __ARGS((ufunc_T *fp));
717 static void prof_sort_list __ARGS((FILE *fd, ufunc_T **sorttab, int st_len, char *title, int prefer_self));
718 static void prof_func_line __ARGS((FILE *fd, int count, proftime_T *total, proftime_T *self, int prefer_self));
719 static int
720 # ifdef __BORLANDC__
721 _RTLENTRYF
722 # endif
723 prof_total_cmp __ARGS((const void *s1, const void *s2));
724 static int
725 # ifdef __BORLANDC__
726 _RTLENTRYF
727 # endif
728 prof_self_cmp __ARGS((const void *s1, const void *s2));
729 #endif
730 static int script_autoload __ARGS((char_u *name, int reload));
731 static char_u *autoload_name __ARGS((char_u *name));
732 static void cat_func_name __ARGS((char_u *buf, ufunc_T *fp));
733 static void func_free __ARGS((ufunc_T *fp));
734 static void func_unref __ARGS((char_u *name));
735 static void func_ref __ARGS((char_u *name));
736 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));
737 static void add_nr_var __ARGS((dict_T *dp, dictitem_T *v, char *name, varnumber_T nr));
738 static win_T *find_win_by_nr __ARGS((typval_T *vp, tabpage_T *tp));
739 static void getwinvar __ARGS((typval_T *argvars, typval_T *rettv, int off));
740 static int searchpair_cmn __ARGS((typval_T *argvars, pos_T *match_pos));
741 static int search_cmn __ARGS((typval_T *argvars, pos_T *match_pos, int *flagsp));
742 static void setwinvar __ARGS((typval_T *argvars, typval_T *rettv, int off));
744 /* Character used as separated in autoload function/variable names. */
745 #define AUTOLOAD_CHAR '#'
748 * Initialize the global and v: variables.
750 void
751 eval_init()
753 int i;
754 struct vimvar *p;
756 init_var_dict(&globvardict, &globvars_var);
757 init_var_dict(&vimvardict, &vimvars_var);
758 hash_init(&compat_hashtab);
759 hash_init(&func_hashtab);
761 for (i = 0; i < VV_LEN; ++i)
763 p = &vimvars[i];
764 STRCPY(p->vv_di.di_key, p->vv_name);
765 if (p->vv_flags & VV_RO)
766 p->vv_di.di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
767 else if (p->vv_flags & VV_RO_SBX)
768 p->vv_di.di_flags = DI_FLAGS_RO_SBX | DI_FLAGS_FIX;
769 else
770 p->vv_di.di_flags = DI_FLAGS_FIX;
772 /* add to v: scope dict, unless the value is not always available */
773 if (p->vv_type != VAR_UNKNOWN)
774 hash_add(&vimvarht, p->vv_di.di_key);
775 if (p->vv_flags & VV_COMPAT)
776 /* add to compat scope dict */
777 hash_add(&compat_hashtab, p->vv_di.di_key);
781 #if defined(EXITFREE) || defined(PROTO)
782 void
783 eval_clear()
785 int i;
786 struct vimvar *p;
788 for (i = 0; i < VV_LEN; ++i)
790 p = &vimvars[i];
791 if (p->vv_di.di_tv.v_type == VAR_STRING)
793 vim_free(p->vv_di.di_tv.vval.v_string);
794 p->vv_di.di_tv.vval.v_string = NULL;
797 hash_clear(&vimvarht);
798 hash_clear(&compat_hashtab);
800 /* script-local variables */
801 for (i = 1; i <= ga_scripts.ga_len; ++i)
802 vars_clear(&SCRIPT_VARS(i));
803 ga_clear(&ga_scripts);
804 free_scriptnames();
806 /* global variables */
807 vars_clear(&globvarht);
809 /* functions */
810 free_all_functions();
811 hash_clear(&func_hashtab);
813 /* autoloaded script names */
814 ga_clear_strings(&ga_loaded);
816 /* unreferenced lists and dicts */
817 (void)garbage_collect();
819 #endif
822 * Return the name of the executed function.
824 char_u *
825 func_name(cookie)
826 void *cookie;
828 return ((funccall_T *)cookie)->func->uf_name;
832 * Return the address holding the next breakpoint line for a funccall cookie.
834 linenr_T *
835 func_breakpoint(cookie)
836 void *cookie;
838 return &((funccall_T *)cookie)->breakpoint;
842 * Return the address holding the debug tick for a funccall cookie.
844 int *
845 func_dbg_tick(cookie)
846 void *cookie;
848 return &((funccall_T *)cookie)->dbg_tick;
852 * Return the nesting level for a funccall cookie.
855 func_level(cookie)
856 void *cookie;
858 return ((funccall_T *)cookie)->level;
861 /* pointer to funccal for currently active function */
862 funccall_T *current_funccal = NULL;
865 * Return TRUE when a function was ended by a ":return" command.
868 current_func_returned()
870 return current_funccal->returned;
875 * Set an internal variable to a string value. Creates the variable if it does
876 * not already exist.
878 void
879 set_internal_string_var(name, value)
880 char_u *name;
881 char_u *value;
883 char_u *val;
884 typval_T *tvp;
886 val = vim_strsave(value);
887 if (val != NULL)
889 tvp = alloc_string_tv(val);
890 if (tvp != NULL)
892 set_var(name, tvp, FALSE);
893 free_tv(tvp);
898 static lval_T *redir_lval = NULL;
899 static char_u *redir_endp = NULL;
900 static char_u *redir_varname = NULL;
903 * Start recording command output to a variable
904 * Returns OK if successfully completed the setup. FAIL otherwise.
907 var_redir_start(name, append)
908 char_u *name;
909 int append; /* append to an existing variable */
911 int save_emsg;
912 int err;
913 typval_T tv;
915 /* Make sure a valid variable name is specified */
916 if (!eval_isnamec1(*name))
918 EMSG(_(e_invarg));
919 return FAIL;
922 redir_varname = vim_strsave(name);
923 if (redir_varname == NULL)
924 return FAIL;
926 redir_lval = (lval_T *)alloc_clear((unsigned)sizeof(lval_T));
927 if (redir_lval == NULL)
929 var_redir_stop();
930 return FAIL;
933 /* Parse the variable name (can be a dict or list entry). */
934 redir_endp = get_lval(redir_varname, NULL, redir_lval, FALSE, FALSE, FALSE,
935 FNE_CHECK_START);
936 if (redir_endp == NULL || redir_lval->ll_name == NULL || *redir_endp != NUL)
938 if (redir_endp != NULL && *redir_endp != NUL)
939 /* Trailing characters are present after the variable name */
940 EMSG(_(e_trailing));
941 else
942 EMSG(_(e_invarg));
943 var_redir_stop();
944 return FAIL;
947 /* check if we can write to the variable: set it to or append an empty
948 * string */
949 save_emsg = did_emsg;
950 did_emsg = FALSE;
951 tv.v_type = VAR_STRING;
952 tv.vval.v_string = (char_u *)"";
953 if (append)
954 set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)".");
955 else
956 set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)"=");
957 err = did_emsg;
958 did_emsg |= save_emsg;
959 if (err)
961 var_redir_stop();
962 return FAIL;
964 if (redir_lval->ll_newkey != NULL)
966 /* Dictionary item was created, don't do it again. */
967 vim_free(redir_lval->ll_newkey);
968 redir_lval->ll_newkey = NULL;
971 return OK;
975 * Append "value[len]" to the variable set by var_redir_start().
977 void
978 var_redir_str(value, len)
979 char_u *value;
980 int len;
982 char_u *val;
983 typval_T tv;
984 int save_emsg;
985 int err;
987 if (redir_lval == NULL)
988 return;
990 if (len == -1)
991 /* Append the entire string */
992 val = vim_strsave(value);
993 else
994 /* Append only the specified number of characters */
995 val = vim_strnsave(value, len);
996 if (val == NULL)
997 return;
999 tv.v_type = VAR_STRING;
1000 tv.vval.v_string = val;
1002 save_emsg = did_emsg;
1003 did_emsg = FALSE;
1004 set_var_lval(redir_lval, redir_endp, &tv, FALSE, (char_u *)".");
1005 err = did_emsg;
1006 did_emsg |= save_emsg;
1007 if (err)
1008 var_redir_stop();
1010 vim_free(tv.vval.v_string);
1014 * Stop redirecting command output to a variable.
1016 void
1017 var_redir_stop()
1019 if (redir_lval != NULL)
1021 clear_lval(redir_lval);
1022 vim_free(redir_lval);
1023 redir_lval = NULL;
1025 vim_free(redir_varname);
1026 redir_varname = NULL;
1029 # if defined(FEAT_MBYTE) || defined(PROTO)
1031 eval_charconvert(enc_from, enc_to, fname_from, fname_to)
1032 char_u *enc_from;
1033 char_u *enc_to;
1034 char_u *fname_from;
1035 char_u *fname_to;
1037 int err = FALSE;
1039 set_vim_var_string(VV_CC_FROM, enc_from, -1);
1040 set_vim_var_string(VV_CC_TO, enc_to, -1);
1041 set_vim_var_string(VV_FNAME_IN, fname_from, -1);
1042 set_vim_var_string(VV_FNAME_OUT, fname_to, -1);
1043 if (eval_to_bool(p_ccv, &err, NULL, FALSE))
1044 err = TRUE;
1045 set_vim_var_string(VV_CC_FROM, NULL, -1);
1046 set_vim_var_string(VV_CC_TO, NULL, -1);
1047 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1048 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1050 if (err)
1051 return FAIL;
1052 return OK;
1054 # endif
1056 # if defined(FEAT_POSTSCRIPT) || defined(PROTO)
1058 eval_printexpr(fname, args)
1059 char_u *fname;
1060 char_u *args;
1062 int err = FALSE;
1064 set_vim_var_string(VV_FNAME_IN, fname, -1);
1065 set_vim_var_string(VV_CMDARG, args, -1);
1066 if (eval_to_bool(p_pexpr, &err, NULL, FALSE))
1067 err = TRUE;
1068 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1069 set_vim_var_string(VV_CMDARG, NULL, -1);
1071 if (err)
1073 mch_remove(fname);
1074 return FAIL;
1076 return OK;
1078 # endif
1080 # if defined(FEAT_DIFF) || defined(PROTO)
1081 void
1082 eval_diff(origfile, newfile, outfile)
1083 char_u *origfile;
1084 char_u *newfile;
1085 char_u *outfile;
1087 int err = FALSE;
1089 set_vim_var_string(VV_FNAME_IN, origfile, -1);
1090 set_vim_var_string(VV_FNAME_NEW, newfile, -1);
1091 set_vim_var_string(VV_FNAME_OUT, outfile, -1);
1092 (void)eval_to_bool(p_dex, &err, NULL, FALSE);
1093 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1094 set_vim_var_string(VV_FNAME_NEW, NULL, -1);
1095 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1098 void
1099 eval_patch(origfile, difffile, outfile)
1100 char_u *origfile;
1101 char_u *difffile;
1102 char_u *outfile;
1104 int err;
1106 set_vim_var_string(VV_FNAME_IN, origfile, -1);
1107 set_vim_var_string(VV_FNAME_DIFF, difffile, -1);
1108 set_vim_var_string(VV_FNAME_OUT, outfile, -1);
1109 (void)eval_to_bool(p_pex, &err, NULL, FALSE);
1110 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1111 set_vim_var_string(VV_FNAME_DIFF, NULL, -1);
1112 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1114 # endif
1117 * Top level evaluation function, returning a boolean.
1118 * Sets "error" to TRUE if there was an error.
1119 * Return TRUE or FALSE.
1122 eval_to_bool(arg, error, nextcmd, skip)
1123 char_u *arg;
1124 int *error;
1125 char_u **nextcmd;
1126 int skip; /* only parse, don't execute */
1128 typval_T tv;
1129 int retval = FALSE;
1131 if (skip)
1132 ++emsg_skip;
1133 if (eval0(arg, &tv, nextcmd, !skip) == FAIL)
1134 *error = TRUE;
1135 else
1137 *error = FALSE;
1138 if (!skip)
1140 retval = (get_tv_number_chk(&tv, error) != 0);
1141 clear_tv(&tv);
1144 if (skip)
1145 --emsg_skip;
1147 return retval;
1151 * Top level evaluation function, returning a string. If "skip" is TRUE,
1152 * only parsing to "nextcmd" is done, without reporting errors. Return
1153 * pointer to allocated memory, or NULL for failure or when "skip" is TRUE.
1155 char_u *
1156 eval_to_string_skip(arg, nextcmd, skip)
1157 char_u *arg;
1158 char_u **nextcmd;
1159 int skip; /* only parse, don't execute */
1161 typval_T tv;
1162 char_u *retval;
1164 if (skip)
1165 ++emsg_skip;
1166 if (eval0(arg, &tv, nextcmd, !skip) == FAIL || skip)
1167 retval = NULL;
1168 else
1170 retval = vim_strsave(get_tv_string(&tv));
1171 clear_tv(&tv);
1173 if (skip)
1174 --emsg_skip;
1176 return retval;
1180 * Skip over an expression at "*pp".
1181 * Return FAIL for an error, OK otherwise.
1184 skip_expr(pp)
1185 char_u **pp;
1187 typval_T rettv;
1189 *pp = skipwhite(*pp);
1190 return eval1(pp, &rettv, FALSE);
1194 * Top level evaluation function, returning a string.
1195 * Return pointer to allocated memory, or NULL for failure.
1197 char_u *
1198 eval_to_string(arg, nextcmd, dolist)
1199 char_u *arg;
1200 char_u **nextcmd;
1201 int dolist; /* turn List into sequence of lines */
1203 typval_T tv;
1204 char_u *retval;
1205 garray_T ga;
1207 if (eval0(arg, &tv, nextcmd, TRUE) == FAIL)
1208 retval = NULL;
1209 else
1211 if (dolist && tv.v_type == VAR_LIST)
1213 ga_init2(&ga, (int)sizeof(char), 80);
1214 list_join(&ga, tv.vval.v_list, (char_u *)"\n", TRUE, 0);
1215 ga_append(&ga, NUL);
1216 retval = (char_u *)ga.ga_data;
1218 else
1219 retval = vim_strsave(get_tv_string(&tv));
1220 clear_tv(&tv);
1223 return retval;
1227 * Call eval_to_string() without using current local variables and using
1228 * textlock. When "use_sandbox" is TRUE use the sandbox.
1230 char_u *
1231 eval_to_string_safe(arg, nextcmd, use_sandbox)
1232 char_u *arg;
1233 char_u **nextcmd;
1234 int use_sandbox;
1236 char_u *retval;
1237 void *save_funccalp;
1239 save_funccalp = save_funccal();
1240 if (use_sandbox)
1241 ++sandbox;
1242 ++textlock;
1243 retval = eval_to_string(arg, nextcmd, FALSE);
1244 if (use_sandbox)
1245 --sandbox;
1246 --textlock;
1247 restore_funccal(save_funccalp);
1248 return retval;
1252 * Top level evaluation function, returning a number.
1253 * Evaluates "expr" silently.
1254 * Returns -1 for an error.
1257 eval_to_number(expr)
1258 char_u *expr;
1260 typval_T rettv;
1261 int retval;
1262 char_u *p = skipwhite(expr);
1264 ++emsg_off;
1266 if (eval1(&p, &rettv, TRUE) == FAIL)
1267 retval = -1;
1268 else
1270 retval = get_tv_number_chk(&rettv, NULL);
1271 clear_tv(&rettv);
1273 --emsg_off;
1275 return retval;
1279 * Prepare v: variable "idx" to be used.
1280 * Save the current typeval in "save_tv".
1281 * When not used yet add the variable to the v: hashtable.
1283 static void
1284 prepare_vimvar(idx, save_tv)
1285 int idx;
1286 typval_T *save_tv;
1288 *save_tv = vimvars[idx].vv_tv;
1289 if (vimvars[idx].vv_type == VAR_UNKNOWN)
1290 hash_add(&vimvarht, vimvars[idx].vv_di.di_key);
1294 * Restore v: variable "idx" to typeval "save_tv".
1295 * When no longer defined, remove the variable from the v: hashtable.
1297 static void
1298 restore_vimvar(idx, save_tv)
1299 int idx;
1300 typval_T *save_tv;
1302 hashitem_T *hi;
1304 clear_tv(&vimvars[idx].vv_tv);
1305 vimvars[idx].vv_tv = *save_tv;
1306 if (vimvars[idx].vv_type == VAR_UNKNOWN)
1308 hi = hash_find(&vimvarht, vimvars[idx].vv_di.di_key);
1309 if (HASHITEM_EMPTY(hi))
1310 EMSG2(_(e_intern2), "restore_vimvar()");
1311 else
1312 hash_remove(&vimvarht, hi);
1316 #if defined(FEAT_SPELL) || defined(PROTO)
1318 * Evaluate an expression to a list with suggestions.
1319 * For the "expr:" part of 'spellsuggest'.
1321 list_T *
1322 eval_spell_expr(badword, expr)
1323 char_u *badword;
1324 char_u *expr;
1326 typval_T save_val;
1327 typval_T rettv;
1328 list_T *list = NULL;
1329 char_u *p = skipwhite(expr);
1331 /* Set "v:val" to the bad word. */
1332 prepare_vimvar(VV_VAL, &save_val);
1333 vimvars[VV_VAL].vv_type = VAR_STRING;
1334 vimvars[VV_VAL].vv_str = badword;
1335 if (p_verbose == 0)
1336 ++emsg_off;
1338 if (eval1(&p, &rettv, TRUE) == OK)
1340 if (rettv.v_type != VAR_LIST)
1341 clear_tv(&rettv);
1342 else
1343 list = rettv.vval.v_list;
1346 if (p_verbose == 0)
1347 --emsg_off;
1348 vimvars[VV_VAL].vv_str = NULL;
1349 restore_vimvar(VV_VAL, &save_val);
1351 return list;
1355 * "list" is supposed to contain two items: a word and a number. Return the
1356 * word in "pp" and the number as the return value.
1357 * Return -1 if anything isn't right.
1358 * Used to get the good word and score from the eval_spell_expr() result.
1361 get_spellword(list, pp)
1362 list_T *list;
1363 char_u **pp;
1365 listitem_T *li;
1367 li = list->lv_first;
1368 if (li == NULL)
1369 return -1;
1370 *pp = get_tv_string(&li->li_tv);
1372 li = li->li_next;
1373 if (li == NULL)
1374 return -1;
1375 return get_tv_number(&li->li_tv);
1377 #endif
1380 * Top level evaluation function.
1381 * Returns an allocated typval_T with the result.
1382 * Returns NULL when there is an error.
1384 typval_T *
1385 eval_expr(arg, nextcmd)
1386 char_u *arg;
1387 char_u **nextcmd;
1389 typval_T *tv;
1391 tv = (typval_T *)alloc(sizeof(typval_T));
1392 if (tv != NULL && eval0(arg, tv, nextcmd, TRUE) == FAIL)
1394 vim_free(tv);
1395 tv = NULL;
1398 return tv;
1402 #if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) || defined(PROTO)
1404 * Call some vimL function and return the result in "*rettv".
1405 * Uses argv[argc] for the function arguments.
1406 * Returns OK or FAIL.
1408 static int
1409 call_vim_function(func, argc, argv, safe, rettv)
1410 char_u *func;
1411 int argc;
1412 char_u **argv;
1413 int safe; /* use the sandbox */
1414 typval_T *rettv;
1416 typval_T *argvars;
1417 long n;
1418 int len;
1419 int i;
1420 int doesrange;
1421 void *save_funccalp = NULL;
1422 int ret;
1424 argvars = (typval_T *)alloc((unsigned)((argc + 1) * sizeof(typval_T)));
1425 if (argvars == NULL)
1426 return FAIL;
1428 for (i = 0; i < argc; i++)
1430 /* Pass a NULL or empty argument as an empty string */
1431 if (argv[i] == NULL || *argv[i] == NUL)
1433 argvars[i].v_type = VAR_STRING;
1434 argvars[i].vval.v_string = (char_u *)"";
1435 continue;
1438 /* Recognize a number argument, the others must be strings. */
1439 vim_str2nr(argv[i], NULL, &len, TRUE, TRUE, &n, NULL);
1440 if (len != 0 && len == (int)STRLEN(argv[i]))
1442 argvars[i].v_type = VAR_NUMBER;
1443 argvars[i].vval.v_number = n;
1445 else
1447 argvars[i].v_type = VAR_STRING;
1448 argvars[i].vval.v_string = argv[i];
1452 if (safe)
1454 save_funccalp = save_funccal();
1455 ++sandbox;
1458 rettv->v_type = VAR_UNKNOWN; /* clear_tv() uses this */
1459 ret = call_func(func, (int)STRLEN(func), rettv, argc, argvars,
1460 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
1461 &doesrange, TRUE, NULL);
1462 if (safe)
1464 --sandbox;
1465 restore_funccal(save_funccalp);
1467 vim_free(argvars);
1469 if (ret == FAIL)
1470 clear_tv(rettv);
1472 return ret;
1476 * Call vimL function "func" and return the result as a string.
1477 * Returns NULL when calling the function fails.
1478 * Uses argv[argc] for the function arguments.
1480 void *
1481 call_func_retstr(func, argc, argv, safe)
1482 char_u *func;
1483 int argc;
1484 char_u **argv;
1485 int safe; /* use the sandbox */
1487 typval_T rettv;
1488 char_u *retval;
1490 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1491 return NULL;
1493 retval = vim_strsave(get_tv_string(&rettv));
1494 clear_tv(&rettv);
1495 return retval;
1498 #if defined(FEAT_COMPL_FUNC) || defined(PROTO)
1500 * Call vimL function "func" and return the result as a number.
1501 * Returns -1 when calling the function fails.
1502 * Uses argv[argc] for the function arguments.
1504 long
1505 call_func_retnr(func, argc, argv, safe)
1506 char_u *func;
1507 int argc;
1508 char_u **argv;
1509 int safe; /* use the sandbox */
1511 typval_T rettv;
1512 long retval;
1514 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1515 return -1;
1517 retval = get_tv_number_chk(&rettv, NULL);
1518 clear_tv(&rettv);
1519 return retval;
1521 #endif
1524 * Call vimL function "func" and return the result as a list
1525 * Uses argv[argc] for the function arguments.
1527 void *
1528 call_func_retlist(func, argc, argv, safe)
1529 char_u *func;
1530 int argc;
1531 char_u **argv;
1532 int safe; /* use the sandbox */
1534 typval_T rettv;
1536 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1537 return NULL;
1539 if (rettv.v_type != VAR_LIST)
1541 clear_tv(&rettv);
1542 return NULL;
1545 return rettv.vval.v_list;
1548 #endif
1551 * Save the current function call pointer, and set it to NULL.
1552 * Used when executing autocommands and for ":source".
1554 void *
1555 save_funccal()
1557 funccall_T *fc = current_funccal;
1559 current_funccal = NULL;
1560 return (void *)fc;
1563 void
1564 restore_funccal(vfc)
1565 void *vfc;
1567 funccall_T *fc = (funccall_T *)vfc;
1569 current_funccal = fc;
1572 #if defined(FEAT_PROFILE) || defined(PROTO)
1574 * Prepare profiling for entering a child or something else that is not
1575 * counted for the script/function itself.
1576 * Should always be called in pair with prof_child_exit().
1578 void
1579 prof_child_enter(tm)
1580 proftime_T *tm; /* place to store waittime */
1582 funccall_T *fc = current_funccal;
1584 if (fc != NULL && fc->func->uf_profiling)
1585 profile_start(&fc->prof_child);
1586 script_prof_save(tm);
1590 * Take care of time spent in a child.
1591 * Should always be called after prof_child_enter().
1593 void
1594 prof_child_exit(tm)
1595 proftime_T *tm; /* where waittime was stored */
1597 funccall_T *fc = current_funccal;
1599 if (fc != NULL && fc->func->uf_profiling)
1601 profile_end(&fc->prof_child);
1602 profile_sub_wait(tm, &fc->prof_child); /* don't count waiting time */
1603 profile_add(&fc->func->uf_tm_children, &fc->prof_child);
1604 profile_add(&fc->func->uf_tml_children, &fc->prof_child);
1606 script_prof_restore(tm);
1608 #endif
1611 #ifdef FEAT_FOLDING
1613 * Evaluate 'foldexpr'. Returns the foldlevel, and any character preceding
1614 * it in "*cp". Doesn't give error messages.
1617 eval_foldexpr(arg, cp)
1618 char_u *arg;
1619 int *cp;
1621 typval_T tv;
1622 int retval;
1623 char_u *s;
1624 int use_sandbox = was_set_insecurely((char_u *)"foldexpr",
1625 OPT_LOCAL);
1627 ++emsg_off;
1628 if (use_sandbox)
1629 ++sandbox;
1630 ++textlock;
1631 *cp = NUL;
1632 if (eval0(arg, &tv, NULL, TRUE) == FAIL)
1633 retval = 0;
1634 else
1636 /* If the result is a number, just return the number. */
1637 if (tv.v_type == VAR_NUMBER)
1638 retval = tv.vval.v_number;
1639 else if (tv.v_type != VAR_STRING || tv.vval.v_string == NULL)
1640 retval = 0;
1641 else
1643 /* If the result is a string, check if there is a non-digit before
1644 * the number. */
1645 s = tv.vval.v_string;
1646 if (!VIM_ISDIGIT(*s) && *s != '-')
1647 *cp = *s++;
1648 retval = atol((char *)s);
1650 clear_tv(&tv);
1652 --emsg_off;
1653 if (use_sandbox)
1654 --sandbox;
1655 --textlock;
1657 return retval;
1659 #endif
1662 * ":let" list all variable values
1663 * ":let var1 var2" list variable values
1664 * ":let var = expr" assignment command.
1665 * ":let var += expr" assignment command.
1666 * ":let var -= expr" assignment command.
1667 * ":let var .= expr" assignment command.
1668 * ":let [var1, var2] = expr" unpack list.
1670 void
1671 ex_let(eap)
1672 exarg_T *eap;
1674 char_u *arg = eap->arg;
1675 char_u *expr = NULL;
1676 typval_T rettv;
1677 int i;
1678 int var_count = 0;
1679 int semicolon = 0;
1680 char_u op[2];
1681 char_u *argend;
1683 argend = skip_var_list(arg, &var_count, &semicolon);
1684 if (argend == NULL)
1685 return;
1686 if (argend > arg && argend[-1] == '.') /* for var.='str' */
1687 --argend;
1688 expr = vim_strchr(argend, '=');
1689 if (expr == NULL)
1692 * ":let" without "=": list variables
1694 if (*arg == '[')
1695 EMSG(_(e_invarg));
1696 else if (!ends_excmd(*arg))
1697 /* ":let var1 var2" */
1698 arg = list_arg_vars(eap, arg);
1699 else if (!eap->skip)
1701 /* ":let" */
1702 list_glob_vars();
1703 list_buf_vars();
1704 list_win_vars();
1705 #ifdef FEAT_WINDOWS
1706 list_tab_vars();
1707 #endif
1708 list_script_vars();
1709 list_func_vars();
1710 list_vim_vars();
1712 eap->nextcmd = check_nextcmd(arg);
1714 else
1716 op[0] = '=';
1717 op[1] = NUL;
1718 if (expr > argend)
1720 if (vim_strchr((char_u *)"+-.", expr[-1]) != NULL)
1721 op[0] = expr[-1]; /* +=, -= or .= */
1723 expr = skipwhite(expr + 1);
1725 if (eap->skip)
1726 ++emsg_skip;
1727 i = eval0(expr, &rettv, &eap->nextcmd, !eap->skip);
1728 if (eap->skip)
1730 if (i != FAIL)
1731 clear_tv(&rettv);
1732 --emsg_skip;
1734 else if (i != FAIL)
1736 (void)ex_let_vars(eap->arg, &rettv, FALSE, semicolon, var_count,
1737 op);
1738 clear_tv(&rettv);
1744 * Assign the typevalue "tv" to the variable or variables at "arg_start".
1745 * Handles both "var" with any type and "[var, var; var]" with a list type.
1746 * When "nextchars" is not NULL it points to a string with characters that
1747 * must appear after the variable(s). Use "+", "-" or "." for add, subtract
1748 * or concatenate.
1749 * Returns OK or FAIL;
1751 static int
1752 ex_let_vars(arg_start, tv, copy, semicolon, var_count, nextchars)
1753 char_u *arg_start;
1754 typval_T *tv;
1755 int copy; /* copy values from "tv", don't move */
1756 int semicolon; /* from skip_var_list() */
1757 int var_count; /* from skip_var_list() */
1758 char_u *nextchars;
1760 char_u *arg = arg_start;
1761 list_T *l;
1762 int i;
1763 listitem_T *item;
1764 typval_T ltv;
1766 if (*arg != '[')
1769 * ":let var = expr" or ":for var in list"
1771 if (ex_let_one(arg, tv, copy, nextchars, nextchars) == NULL)
1772 return FAIL;
1773 return OK;
1777 * ":let [v1, v2] = list" or ":for [v1, v2] in listlist"
1779 if (tv->v_type != VAR_LIST || (l = tv->vval.v_list) == NULL)
1781 EMSG(_(e_listreq));
1782 return FAIL;
1785 i = list_len(l);
1786 if (semicolon == 0 && var_count < i)
1788 EMSG(_("E687: Less targets than List items"));
1789 return FAIL;
1791 if (var_count - semicolon > i)
1793 EMSG(_("E688: More targets than List items"));
1794 return FAIL;
1797 item = l->lv_first;
1798 while (*arg != ']')
1800 arg = skipwhite(arg + 1);
1801 arg = ex_let_one(arg, &item->li_tv, TRUE, (char_u *)",;]", nextchars);
1802 item = item->li_next;
1803 if (arg == NULL)
1804 return FAIL;
1806 arg = skipwhite(arg);
1807 if (*arg == ';')
1809 /* Put the rest of the list (may be empty) in the var after ';'.
1810 * Create a new list for this. */
1811 l = list_alloc();
1812 if (l == NULL)
1813 return FAIL;
1814 while (item != NULL)
1816 list_append_tv(l, &item->li_tv);
1817 item = item->li_next;
1820 ltv.v_type = VAR_LIST;
1821 ltv.v_lock = 0;
1822 ltv.vval.v_list = l;
1823 l->lv_refcount = 1;
1825 arg = ex_let_one(skipwhite(arg + 1), &ltv, FALSE,
1826 (char_u *)"]", nextchars);
1827 clear_tv(&ltv);
1828 if (arg == NULL)
1829 return FAIL;
1830 break;
1832 else if (*arg != ',' && *arg != ']')
1834 EMSG2(_(e_intern2), "ex_let_vars()");
1835 return FAIL;
1839 return OK;
1843 * Skip over assignable variable "var" or list of variables "[var, var]".
1844 * Used for ":let varvar = expr" and ":for varvar in expr".
1845 * For "[var, var]" increment "*var_count" for each variable.
1846 * for "[var, var; var]" set "semicolon".
1847 * Return NULL for an error.
1849 static char_u *
1850 skip_var_list(arg, var_count, semicolon)
1851 char_u *arg;
1852 int *var_count;
1853 int *semicolon;
1855 char_u *p, *s;
1857 if (*arg == '[')
1859 /* "[var, var]": find the matching ']'. */
1860 p = arg;
1861 for (;;)
1863 p = skipwhite(p + 1); /* skip whites after '[', ';' or ',' */
1864 s = skip_var_one(p);
1865 if (s == p)
1867 EMSG2(_(e_invarg2), p);
1868 return NULL;
1870 ++*var_count;
1872 p = skipwhite(s);
1873 if (*p == ']')
1874 break;
1875 else if (*p == ';')
1877 if (*semicolon == 1)
1879 EMSG(_("Double ; in list of variables"));
1880 return NULL;
1882 *semicolon = 1;
1884 else if (*p != ',')
1886 EMSG2(_(e_invarg2), p);
1887 return NULL;
1890 return p + 1;
1892 else
1893 return skip_var_one(arg);
1897 * Skip one (assignable) variable name, includig @r, $VAR, &option, d.key,
1898 * l[idx].
1900 static char_u *
1901 skip_var_one(arg)
1902 char_u *arg;
1904 if (*arg == '@' && arg[1] != NUL)
1905 return arg + 2;
1906 return find_name_end(*arg == '$' || *arg == '&' ? arg + 1 : arg,
1907 NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
1911 * List variables for hashtab "ht" with prefix "prefix".
1912 * If "empty" is TRUE also list NULL strings as empty strings.
1914 static void
1915 list_hashtable_vars(ht, prefix, empty)
1916 hashtab_T *ht;
1917 char_u *prefix;
1918 int empty;
1920 hashitem_T *hi;
1921 dictitem_T *di;
1922 int todo;
1924 todo = (int)ht->ht_used;
1925 for (hi = ht->ht_array; todo > 0 && !got_int; ++hi)
1927 if (!HASHITEM_EMPTY(hi))
1929 --todo;
1930 di = HI2DI(hi);
1931 if (empty || di->di_tv.v_type != VAR_STRING
1932 || di->di_tv.vval.v_string != NULL)
1933 list_one_var(di, prefix);
1939 * List global variables.
1941 static void
1942 list_glob_vars()
1944 list_hashtable_vars(&globvarht, (char_u *)"", TRUE);
1948 * List buffer variables.
1950 static void
1951 list_buf_vars()
1953 char_u numbuf[NUMBUFLEN];
1955 list_hashtable_vars(&curbuf->b_vars.dv_hashtab, (char_u *)"b:", TRUE);
1957 sprintf((char *)numbuf, "%ld", (long)curbuf->b_changedtick);
1958 list_one_var_a((char_u *)"b:", (char_u *)"changedtick", VAR_NUMBER, numbuf);
1962 * List window variables.
1964 static void
1965 list_win_vars()
1967 list_hashtable_vars(&curwin->w_vars.dv_hashtab, (char_u *)"w:", TRUE);
1970 #ifdef FEAT_WINDOWS
1972 * List tab page variables.
1974 static void
1975 list_tab_vars()
1977 list_hashtable_vars(&curtab->tp_vars.dv_hashtab, (char_u *)"t:", TRUE);
1979 #endif
1982 * List Vim variables.
1984 static void
1985 list_vim_vars()
1987 list_hashtable_vars(&vimvarht, (char_u *)"v:", FALSE);
1991 * List script-local variables, if there is a script.
1993 static void
1994 list_script_vars()
1996 if (current_SID > 0 && current_SID <= ga_scripts.ga_len)
1997 list_hashtable_vars(&SCRIPT_VARS(current_SID), (char_u *)"s:", FALSE);
2001 * List function variables, if there is a function.
2003 static void
2004 list_func_vars()
2006 if (current_funccal != NULL)
2007 list_hashtable_vars(&current_funccal->l_vars.dv_hashtab,
2008 (char_u *)"l:", FALSE);
2012 * List variables in "arg".
2014 static char_u *
2015 list_arg_vars(eap, arg)
2016 exarg_T *eap;
2017 char_u *arg;
2019 int error = FALSE;
2020 int len;
2021 char_u *name;
2022 char_u *name_start;
2023 char_u *arg_subsc;
2024 char_u *tofree;
2025 typval_T tv;
2027 while (!ends_excmd(*arg) && !got_int)
2029 if (error || eap->skip)
2031 arg = find_name_end(arg, NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
2032 if (!vim_iswhite(*arg) && !ends_excmd(*arg))
2034 emsg_severe = TRUE;
2035 EMSG(_(e_trailing));
2036 break;
2039 else
2041 /* get_name_len() takes care of expanding curly braces */
2042 name_start = name = arg;
2043 len = get_name_len(&arg, &tofree, TRUE, TRUE);
2044 if (len <= 0)
2046 /* This is mainly to keep test 49 working: when expanding
2047 * curly braces fails overrule the exception error message. */
2048 if (len < 0 && !aborting())
2050 emsg_severe = TRUE;
2051 EMSG2(_(e_invarg2), arg);
2052 break;
2054 error = TRUE;
2056 else
2058 if (tofree != NULL)
2059 name = tofree;
2060 if (get_var_tv(name, len, &tv, TRUE) == FAIL)
2061 error = TRUE;
2062 else
2064 /* handle d.key, l[idx], f(expr) */
2065 arg_subsc = arg;
2066 if (handle_subscript(&arg, &tv, TRUE, TRUE) == FAIL)
2067 error = TRUE;
2068 else
2070 if (arg == arg_subsc && len == 2 && name[1] == ':')
2072 switch (*name)
2074 case 'g': list_glob_vars(); break;
2075 case 'b': list_buf_vars(); break;
2076 case 'w': list_win_vars(); break;
2077 #ifdef FEAT_WINDOWS
2078 case 't': list_tab_vars(); break;
2079 #endif
2080 case 'v': list_vim_vars(); break;
2081 case 's': list_script_vars(); break;
2082 case 'l': list_func_vars(); break;
2083 default:
2084 EMSG2(_("E738: Can't list variables for %s"), name);
2087 else
2089 char_u numbuf[NUMBUFLEN];
2090 char_u *tf;
2091 int c;
2092 char_u *s;
2094 s = echo_string(&tv, &tf, numbuf, 0);
2095 c = *arg;
2096 *arg = NUL;
2097 list_one_var_a((char_u *)"",
2098 arg == arg_subsc ? name : name_start,
2099 tv.v_type, s == NULL ? (char_u *)"" : s);
2100 *arg = c;
2101 vim_free(tf);
2103 clear_tv(&tv);
2108 vim_free(tofree);
2111 arg = skipwhite(arg);
2114 return arg;
2118 * Set one item of ":let var = expr" or ":let [v1, v2] = list" to its value.
2119 * Returns a pointer to the char just after the var name.
2120 * Returns NULL if there is an error.
2122 static char_u *
2123 ex_let_one(arg, tv, copy, endchars, op)
2124 char_u *arg; /* points to variable name */
2125 typval_T *tv; /* value to assign to variable */
2126 int copy; /* copy value from "tv" */
2127 char_u *endchars; /* valid chars after variable name or NULL */
2128 char_u *op; /* "+", "-", "." or NULL*/
2130 int c1;
2131 char_u *name;
2132 char_u *p;
2133 char_u *arg_end = NULL;
2134 int len;
2135 int opt_flags;
2136 char_u *tofree = NULL;
2139 * ":let $VAR = expr": Set environment variable.
2141 if (*arg == '$')
2143 /* Find the end of the name. */
2144 ++arg;
2145 name = arg;
2146 len = get_env_len(&arg);
2147 if (len == 0)
2148 EMSG2(_(e_invarg2), name - 1);
2149 else
2151 if (op != NULL && (*op == '+' || *op == '-'))
2152 EMSG2(_(e_letwrong), op);
2153 else if (endchars != NULL
2154 && vim_strchr(endchars, *skipwhite(arg)) == NULL)
2155 EMSG(_(e_letunexp));
2156 else
2158 c1 = name[len];
2159 name[len] = NUL;
2160 p = get_tv_string_chk(tv);
2161 if (p != NULL && op != NULL && *op == '.')
2163 int mustfree = FALSE;
2164 char_u *s = vim_getenv(name, &mustfree);
2166 if (s != NULL)
2168 p = tofree = concat_str(s, p);
2169 if (mustfree)
2170 vim_free(s);
2173 if (p != NULL)
2175 vim_setenv(name, p);
2176 if (STRICMP(name, "HOME") == 0)
2177 init_homedir();
2178 else if (didset_vim && STRICMP(name, "VIM") == 0)
2179 didset_vim = FALSE;
2180 else if (didset_vimruntime
2181 && STRICMP(name, "VIMRUNTIME") == 0)
2182 didset_vimruntime = FALSE;
2183 arg_end = arg;
2185 name[len] = c1;
2186 vim_free(tofree);
2192 * ":let &option = expr": Set option value.
2193 * ":let &l:option = expr": Set local option value.
2194 * ":let &g:option = expr": Set global option value.
2196 else if (*arg == '&')
2198 /* Find the end of the name. */
2199 p = find_option_end(&arg, &opt_flags);
2200 if (p == NULL || (endchars != NULL
2201 && vim_strchr(endchars, *skipwhite(p)) == NULL))
2202 EMSG(_(e_letunexp));
2203 else
2205 long n;
2206 int opt_type;
2207 long numval;
2208 char_u *stringval = NULL;
2209 char_u *s;
2211 c1 = *p;
2212 *p = NUL;
2214 n = get_tv_number(tv);
2215 s = get_tv_string_chk(tv); /* != NULL if number or string */
2216 if (s != NULL && op != NULL && *op != '=')
2218 opt_type = get_option_value(arg, &numval,
2219 &stringval, opt_flags);
2220 if ((opt_type == 1 && *op == '.')
2221 || (opt_type == 0 && *op != '.'))
2222 EMSG2(_(e_letwrong), op);
2223 else
2225 if (opt_type == 1) /* number */
2227 if (*op == '+')
2228 n = numval + n;
2229 else
2230 n = numval - n;
2232 else if (opt_type == 0 && stringval != NULL) /* string */
2234 s = concat_str(stringval, s);
2235 vim_free(stringval);
2236 stringval = s;
2240 if (s != NULL)
2242 set_option_value(arg, n, s, opt_flags);
2243 arg_end = p;
2245 *p = c1;
2246 vim_free(stringval);
2251 * ":let @r = expr": Set register contents.
2253 else if (*arg == '@')
2255 ++arg;
2256 if (op != NULL && (*op == '+' || *op == '-'))
2257 EMSG2(_(e_letwrong), op);
2258 else if (endchars != NULL
2259 && vim_strchr(endchars, *skipwhite(arg + 1)) == NULL)
2260 EMSG(_(e_letunexp));
2261 else
2263 char_u *ptofree = NULL;
2264 char_u *s;
2266 p = get_tv_string_chk(tv);
2267 if (p != NULL && op != NULL && *op == '.')
2269 s = get_reg_contents(*arg == '@' ? '"' : *arg, TRUE, TRUE);
2270 if (s != NULL)
2272 p = ptofree = concat_str(s, p);
2273 vim_free(s);
2276 if (p != NULL)
2278 write_reg_contents(*arg == '@' ? '"' : *arg, p, -1, FALSE);
2279 arg_end = arg + 1;
2281 vim_free(ptofree);
2286 * ":let var = expr": Set internal variable.
2287 * ":let {expr} = expr": Idem, name made with curly braces
2289 else if (eval_isnamec1(*arg) || *arg == '{')
2291 lval_T lv;
2293 p = get_lval(arg, tv, &lv, FALSE, FALSE, FALSE, FNE_CHECK_START);
2294 if (p != NULL && lv.ll_name != NULL)
2296 if (endchars != NULL && vim_strchr(endchars, *skipwhite(p)) == NULL)
2297 EMSG(_(e_letunexp));
2298 else
2300 set_var_lval(&lv, p, tv, copy, op);
2301 arg_end = p;
2304 clear_lval(&lv);
2307 else
2308 EMSG2(_(e_invarg2), arg);
2310 return arg_end;
2314 * If "arg" is equal to "b:changedtick" give an error and return TRUE.
2316 static int
2317 check_changedtick(arg)
2318 char_u *arg;
2320 if (STRNCMP(arg, "b:changedtick", 13) == 0 && !eval_isnamec(arg[13]))
2322 EMSG2(_(e_readonlyvar), arg);
2323 return TRUE;
2325 return FALSE;
2329 * Get an lval: variable, Dict item or List item that can be assigned a value
2330 * to: "name", "na{me}", "name[expr]", "name[expr:expr]", "name[expr][expr]",
2331 * "name.key", "name.key[expr]" etc.
2332 * Indexing only works if "name" is an existing List or Dictionary.
2333 * "name" points to the start of the name.
2334 * If "rettv" is not NULL it points to the value to be assigned.
2335 * "unlet" is TRUE for ":unlet": slightly different behavior when something is
2336 * wrong; must end in space or cmd separator.
2338 * Returns a pointer to just after the name, including indexes.
2339 * When an evaluation error occurs "lp->ll_name" is NULL;
2340 * Returns NULL for a parsing error. Still need to free items in "lp"!
2342 static char_u *
2343 get_lval(name, rettv, lp, unlet, skip, quiet, fne_flags)
2344 char_u *name;
2345 typval_T *rettv;
2346 lval_T *lp;
2347 int unlet;
2348 int skip;
2349 int quiet; /* don't give error messages */
2350 int fne_flags; /* flags for find_name_end() */
2352 char_u *p;
2353 char_u *expr_start, *expr_end;
2354 int cc;
2355 dictitem_T *v;
2356 typval_T var1;
2357 typval_T var2;
2358 int empty1 = FALSE;
2359 listitem_T *ni;
2360 char_u *key = NULL;
2361 int len;
2362 hashtab_T *ht;
2364 /* Clear everything in "lp". */
2365 vim_memset(lp, 0, sizeof(lval_T));
2367 if (skip)
2369 /* When skipping just find the end of the name. */
2370 lp->ll_name = name;
2371 return find_name_end(name, NULL, NULL, FNE_INCL_BR | fne_flags);
2374 /* Find the end of the name. */
2375 p = find_name_end(name, &expr_start, &expr_end, fne_flags);
2376 if (expr_start != NULL)
2378 /* Don't expand the name when we already know there is an error. */
2379 if (unlet && !vim_iswhite(*p) && !ends_excmd(*p)
2380 && *p != '[' && *p != '.')
2382 EMSG(_(e_trailing));
2383 return NULL;
2386 lp->ll_exp_name = make_expanded_name(name, expr_start, expr_end, p);
2387 if (lp->ll_exp_name == NULL)
2389 /* Report an invalid expression in braces, unless the
2390 * expression evaluation has been cancelled due to an
2391 * aborting error, an interrupt, or an exception. */
2392 if (!aborting() && !quiet)
2394 emsg_severe = TRUE;
2395 EMSG2(_(e_invarg2), name);
2396 return NULL;
2399 lp->ll_name = lp->ll_exp_name;
2401 else
2402 lp->ll_name = name;
2404 /* Without [idx] or .key we are done. */
2405 if ((*p != '[' && *p != '.') || lp->ll_name == NULL)
2406 return p;
2408 cc = *p;
2409 *p = NUL;
2410 v = find_var(lp->ll_name, &ht);
2411 if (v == NULL && !quiet)
2412 EMSG2(_(e_undefvar), lp->ll_name);
2413 *p = cc;
2414 if (v == NULL)
2415 return NULL;
2418 * Loop until no more [idx] or .key is following.
2420 lp->ll_tv = &v->di_tv;
2421 while (*p == '[' || (*p == '.' && lp->ll_tv->v_type == VAR_DICT))
2423 if (!(lp->ll_tv->v_type == VAR_LIST && lp->ll_tv->vval.v_list != NULL)
2424 && !(lp->ll_tv->v_type == VAR_DICT
2425 && lp->ll_tv->vval.v_dict != NULL))
2427 if (!quiet)
2428 EMSG(_("E689: Can only index a List or Dictionary"));
2429 return NULL;
2431 if (lp->ll_range)
2433 if (!quiet)
2434 EMSG(_("E708: [:] must come last"));
2435 return NULL;
2438 len = -1;
2439 if (*p == '.')
2441 key = p + 1;
2442 for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
2444 if (len == 0)
2446 if (!quiet)
2447 EMSG(_(e_emptykey));
2448 return NULL;
2450 p = key + len;
2452 else
2454 /* Get the index [expr] or the first index [expr: ]. */
2455 p = skipwhite(p + 1);
2456 if (*p == ':')
2457 empty1 = TRUE;
2458 else
2460 empty1 = FALSE;
2461 if (eval1(&p, &var1, TRUE) == FAIL) /* recursive! */
2462 return NULL;
2463 if (get_tv_string_chk(&var1) == NULL)
2465 /* not a number or string */
2466 clear_tv(&var1);
2467 return NULL;
2471 /* Optionally get the second index [ :expr]. */
2472 if (*p == ':')
2474 if (lp->ll_tv->v_type == VAR_DICT)
2476 if (!quiet)
2477 EMSG(_(e_dictrange));
2478 if (!empty1)
2479 clear_tv(&var1);
2480 return NULL;
2482 if (rettv != NULL && (rettv->v_type != VAR_LIST
2483 || rettv->vval.v_list == NULL))
2485 if (!quiet)
2486 EMSG(_("E709: [:] requires a List value"));
2487 if (!empty1)
2488 clear_tv(&var1);
2489 return NULL;
2491 p = skipwhite(p + 1);
2492 if (*p == ']')
2493 lp->ll_empty2 = TRUE;
2494 else
2496 lp->ll_empty2 = FALSE;
2497 if (eval1(&p, &var2, TRUE) == FAIL) /* recursive! */
2499 if (!empty1)
2500 clear_tv(&var1);
2501 return NULL;
2503 if (get_tv_string_chk(&var2) == NULL)
2505 /* not a number or string */
2506 if (!empty1)
2507 clear_tv(&var1);
2508 clear_tv(&var2);
2509 return NULL;
2512 lp->ll_range = TRUE;
2514 else
2515 lp->ll_range = FALSE;
2517 if (*p != ']')
2519 if (!quiet)
2520 EMSG(_(e_missbrac));
2521 if (!empty1)
2522 clear_tv(&var1);
2523 if (lp->ll_range && !lp->ll_empty2)
2524 clear_tv(&var2);
2525 return NULL;
2528 /* Skip to past ']'. */
2529 ++p;
2532 if (lp->ll_tv->v_type == VAR_DICT)
2534 if (len == -1)
2536 /* "[key]": get key from "var1" */
2537 key = get_tv_string(&var1); /* is number or string */
2538 if (*key == NUL)
2540 if (!quiet)
2541 EMSG(_(e_emptykey));
2542 clear_tv(&var1);
2543 return NULL;
2546 lp->ll_list = NULL;
2547 lp->ll_dict = lp->ll_tv->vval.v_dict;
2548 lp->ll_di = dict_find(lp->ll_dict, key, len);
2549 if (lp->ll_di == NULL)
2551 /* Key does not exist in dict: may need to add it. */
2552 if (*p == '[' || *p == '.' || unlet)
2554 if (!quiet)
2555 EMSG2(_(e_dictkey), key);
2556 if (len == -1)
2557 clear_tv(&var1);
2558 return NULL;
2560 if (len == -1)
2561 lp->ll_newkey = vim_strsave(key);
2562 else
2563 lp->ll_newkey = vim_strnsave(key, len);
2564 if (len == -1)
2565 clear_tv(&var1);
2566 if (lp->ll_newkey == NULL)
2567 p = NULL;
2568 break;
2570 if (len == -1)
2571 clear_tv(&var1);
2572 lp->ll_tv = &lp->ll_di->di_tv;
2574 else
2577 * Get the number and item for the only or first index of the List.
2579 if (empty1)
2580 lp->ll_n1 = 0;
2581 else
2583 lp->ll_n1 = get_tv_number(&var1); /* is number or string */
2584 clear_tv(&var1);
2586 lp->ll_dict = NULL;
2587 lp->ll_list = lp->ll_tv->vval.v_list;
2588 lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2589 if (lp->ll_li == NULL)
2591 if (lp->ll_n1 < 0)
2593 lp->ll_n1 = 0;
2594 lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2597 if (lp->ll_li == NULL)
2599 if (lp->ll_range && !lp->ll_empty2)
2600 clear_tv(&var2);
2601 return NULL;
2605 * May need to find the item or absolute index for the second
2606 * index of a range.
2607 * When no index given: "lp->ll_empty2" is TRUE.
2608 * Otherwise "lp->ll_n2" is set to the second index.
2610 if (lp->ll_range && !lp->ll_empty2)
2612 lp->ll_n2 = get_tv_number(&var2); /* is number or string */
2613 clear_tv(&var2);
2614 if (lp->ll_n2 < 0)
2616 ni = list_find(lp->ll_list, lp->ll_n2);
2617 if (ni == NULL)
2618 return NULL;
2619 lp->ll_n2 = list_idx_of_item(lp->ll_list, ni);
2622 /* Check that lp->ll_n2 isn't before lp->ll_n1. */
2623 if (lp->ll_n1 < 0)
2624 lp->ll_n1 = list_idx_of_item(lp->ll_list, lp->ll_li);
2625 if (lp->ll_n2 < lp->ll_n1)
2626 return NULL;
2629 lp->ll_tv = &lp->ll_li->li_tv;
2633 return p;
2637 * Clear lval "lp" that was filled by get_lval().
2639 static void
2640 clear_lval(lp)
2641 lval_T *lp;
2643 vim_free(lp->ll_exp_name);
2644 vim_free(lp->ll_newkey);
2648 * Set a variable that was parsed by get_lval() to "rettv".
2649 * "endp" points to just after the parsed name.
2650 * "op" is NULL, "+" for "+=", "-" for "-=", "." for ".=" or "=" for "=".
2652 static void
2653 set_var_lval(lp, endp, rettv, copy, op)
2654 lval_T *lp;
2655 char_u *endp;
2656 typval_T *rettv;
2657 int copy;
2658 char_u *op;
2660 int cc;
2661 listitem_T *ri;
2662 dictitem_T *di;
2664 if (lp->ll_tv == NULL)
2666 if (!check_changedtick(lp->ll_name))
2668 cc = *endp;
2669 *endp = NUL;
2670 if (op != NULL && *op != '=')
2672 typval_T tv;
2674 /* handle +=, -= and .= */
2675 if (get_var_tv(lp->ll_name, (int)STRLEN(lp->ll_name),
2676 &tv, TRUE) == OK)
2678 if (tv_op(&tv, rettv, op) == OK)
2679 set_var(lp->ll_name, &tv, FALSE);
2680 clear_tv(&tv);
2683 else
2684 set_var(lp->ll_name, rettv, copy);
2685 *endp = cc;
2688 else if (tv_check_lock(lp->ll_newkey == NULL
2689 ? lp->ll_tv->v_lock
2690 : lp->ll_tv->vval.v_dict->dv_lock, lp->ll_name))
2692 else if (lp->ll_range)
2695 * Assign the List values to the list items.
2697 for (ri = rettv->vval.v_list->lv_first; ri != NULL; )
2699 if (op != NULL && *op != '=')
2700 tv_op(&lp->ll_li->li_tv, &ri->li_tv, op);
2701 else
2703 clear_tv(&lp->ll_li->li_tv);
2704 copy_tv(&ri->li_tv, &lp->ll_li->li_tv);
2706 ri = ri->li_next;
2707 if (ri == NULL || (!lp->ll_empty2 && lp->ll_n2 == lp->ll_n1))
2708 break;
2709 if (lp->ll_li->li_next == NULL)
2711 /* Need to add an empty item. */
2712 if (list_append_number(lp->ll_list, 0) == FAIL)
2714 ri = NULL;
2715 break;
2718 lp->ll_li = lp->ll_li->li_next;
2719 ++lp->ll_n1;
2721 if (ri != NULL)
2722 EMSG(_("E710: List value has more items than target"));
2723 else if (lp->ll_empty2
2724 ? (lp->ll_li != NULL && lp->ll_li->li_next != NULL)
2725 : lp->ll_n1 != lp->ll_n2)
2726 EMSG(_("E711: List value has not enough items"));
2728 else
2731 * Assign to a List or Dictionary item.
2733 if (lp->ll_newkey != NULL)
2735 if (op != NULL && *op != '=')
2737 EMSG2(_(e_letwrong), op);
2738 return;
2741 /* Need to add an item to the Dictionary. */
2742 di = dictitem_alloc(lp->ll_newkey);
2743 if (di == NULL)
2744 return;
2745 if (dict_add(lp->ll_tv->vval.v_dict, di) == FAIL)
2747 vim_free(di);
2748 return;
2750 lp->ll_tv = &di->di_tv;
2752 else if (op != NULL && *op != '=')
2754 tv_op(lp->ll_tv, rettv, op);
2755 return;
2757 else
2758 clear_tv(lp->ll_tv);
2761 * Assign the value to the variable or list item.
2763 if (copy)
2764 copy_tv(rettv, lp->ll_tv);
2765 else
2767 *lp->ll_tv = *rettv;
2768 lp->ll_tv->v_lock = 0;
2769 init_tv(rettv);
2775 * Handle "tv1 += tv2", "tv1 -= tv2" and "tv1 .= tv2"
2776 * Returns OK or FAIL.
2778 static int
2779 tv_op(tv1, tv2, op)
2780 typval_T *tv1;
2781 typval_T *tv2;
2782 char_u *op;
2784 long n;
2785 char_u numbuf[NUMBUFLEN];
2786 char_u *s;
2788 /* Can't do anything with a Funcref or a Dict on the right. */
2789 if (tv2->v_type != VAR_FUNC && tv2->v_type != VAR_DICT)
2791 switch (tv1->v_type)
2793 case VAR_DICT:
2794 case VAR_FUNC:
2795 break;
2797 case VAR_LIST:
2798 if (*op != '+' || tv2->v_type != VAR_LIST)
2799 break;
2800 /* List += List */
2801 if (tv1->vval.v_list != NULL && tv2->vval.v_list != NULL)
2802 list_extend(tv1->vval.v_list, tv2->vval.v_list, NULL);
2803 return OK;
2805 case VAR_NUMBER:
2806 case VAR_STRING:
2807 if (tv2->v_type == VAR_LIST)
2808 break;
2809 if (*op == '+' || *op == '-')
2811 /* nr += nr or nr -= nr*/
2812 n = get_tv_number(tv1);
2813 if (*op == '+')
2814 n += get_tv_number(tv2);
2815 else
2816 n -= get_tv_number(tv2);
2817 clear_tv(tv1);
2818 tv1->v_type = VAR_NUMBER;
2819 tv1->vval.v_number = n;
2821 else
2823 /* str .= str */
2824 s = get_tv_string(tv1);
2825 s = concat_str(s, get_tv_string_buf(tv2, numbuf));
2826 clear_tv(tv1);
2827 tv1->v_type = VAR_STRING;
2828 tv1->vval.v_string = s;
2830 return OK;
2834 EMSG2(_(e_letwrong), op);
2835 return FAIL;
2839 * Add a watcher to a list.
2841 static void
2842 list_add_watch(l, lw)
2843 list_T *l;
2844 listwatch_T *lw;
2846 lw->lw_next = l->lv_watch;
2847 l->lv_watch = lw;
2851 * Remove a watcher from a list.
2852 * No warning when it isn't found...
2854 static void
2855 list_rem_watch(l, lwrem)
2856 list_T *l;
2857 listwatch_T *lwrem;
2859 listwatch_T *lw, **lwp;
2861 lwp = &l->lv_watch;
2862 for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
2864 if (lw == lwrem)
2866 *lwp = lw->lw_next;
2867 break;
2869 lwp = &lw->lw_next;
2874 * Just before removing an item from a list: advance watchers to the next
2875 * item.
2877 static void
2878 list_fix_watch(l, item)
2879 list_T *l;
2880 listitem_T *item;
2882 listwatch_T *lw;
2884 for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
2885 if (lw->lw_item == item)
2886 lw->lw_item = item->li_next;
2890 * Evaluate the expression used in a ":for var in expr" command.
2891 * "arg" points to "var".
2892 * Set "*errp" to TRUE for an error, FALSE otherwise;
2893 * Return a pointer that holds the info. Null when there is an error.
2895 void *
2896 eval_for_line(arg, errp, nextcmdp, skip)
2897 char_u *arg;
2898 int *errp;
2899 char_u **nextcmdp;
2900 int skip;
2902 forinfo_T *fi;
2903 char_u *expr;
2904 typval_T tv;
2905 list_T *l;
2907 *errp = TRUE; /* default: there is an error */
2909 fi = (forinfo_T *)alloc_clear(sizeof(forinfo_T));
2910 if (fi == NULL)
2911 return NULL;
2913 expr = skip_var_list(arg, &fi->fi_varcount, &fi->fi_semicolon);
2914 if (expr == NULL)
2915 return fi;
2917 expr = skipwhite(expr);
2918 if (expr[0] != 'i' || expr[1] != 'n' || !vim_iswhite(expr[2]))
2920 EMSG(_("E690: Missing \"in\" after :for"));
2921 return fi;
2924 if (skip)
2925 ++emsg_skip;
2926 if (eval0(skipwhite(expr + 2), &tv, nextcmdp, !skip) == OK)
2928 *errp = FALSE;
2929 if (!skip)
2931 l = tv.vval.v_list;
2932 if (tv.v_type != VAR_LIST || l == NULL)
2934 EMSG(_(e_listreq));
2935 clear_tv(&tv);
2937 else
2939 /* No need to increment the refcount, it's already set for the
2940 * list being used in "tv". */
2941 fi->fi_list = l;
2942 list_add_watch(l, &fi->fi_lw);
2943 fi->fi_lw.lw_item = l->lv_first;
2947 if (skip)
2948 --emsg_skip;
2950 return fi;
2954 * Use the first item in a ":for" list. Advance to the next.
2955 * Assign the values to the variable (list). "arg" points to the first one.
2956 * Return TRUE when a valid item was found, FALSE when at end of list or
2957 * something wrong.
2960 next_for_item(fi_void, arg)
2961 void *fi_void;
2962 char_u *arg;
2964 forinfo_T *fi = (forinfo_T *)fi_void;
2965 int result;
2966 listitem_T *item;
2968 item = fi->fi_lw.lw_item;
2969 if (item == NULL)
2970 result = FALSE;
2971 else
2973 fi->fi_lw.lw_item = item->li_next;
2974 result = (ex_let_vars(arg, &item->li_tv, TRUE,
2975 fi->fi_semicolon, fi->fi_varcount, NULL) == OK);
2977 return result;
2981 * Free the structure used to store info used by ":for".
2983 void
2984 free_for_info(fi_void)
2985 void *fi_void;
2987 forinfo_T *fi = (forinfo_T *)fi_void;
2989 if (fi != NULL && fi->fi_list != NULL)
2991 list_rem_watch(fi->fi_list, &fi->fi_lw);
2992 list_unref(fi->fi_list);
2994 vim_free(fi);
2997 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
2999 void
3000 set_context_for_expression(xp, arg, cmdidx)
3001 expand_T *xp;
3002 char_u *arg;
3003 cmdidx_T cmdidx;
3005 int got_eq = FALSE;
3006 int c;
3007 char_u *p;
3009 if (cmdidx == CMD_let)
3011 xp->xp_context = EXPAND_USER_VARS;
3012 if (vim_strpbrk(arg, (char_u *)"\"'+-*/%.=!?~|&$([<>,#") == NULL)
3014 /* ":let var1 var2 ...": find last space. */
3015 for (p = arg + STRLEN(arg); p >= arg; )
3017 xp->xp_pattern = p;
3018 mb_ptr_back(arg, p);
3019 if (vim_iswhite(*p))
3020 break;
3022 return;
3025 else
3026 xp->xp_context = cmdidx == CMD_call ? EXPAND_FUNCTIONS
3027 : EXPAND_EXPRESSION;
3028 while ((xp->xp_pattern = vim_strpbrk(arg,
3029 (char_u *)"\"'+-*/%.=!?~|&$([<>,#")) != NULL)
3031 c = *xp->xp_pattern;
3032 if (c == '&')
3034 c = xp->xp_pattern[1];
3035 if (c == '&')
3037 ++xp->xp_pattern;
3038 xp->xp_context = cmdidx != CMD_let || got_eq
3039 ? EXPAND_EXPRESSION : EXPAND_NOTHING;
3041 else if (c != ' ')
3043 xp->xp_context = EXPAND_SETTINGS;
3044 if ((c == 'l' || c == 'g') && xp->xp_pattern[2] == ':')
3045 xp->xp_pattern += 2;
3049 else if (c == '$')
3051 /* environment variable */
3052 xp->xp_context = EXPAND_ENV_VARS;
3054 else if (c == '=')
3056 got_eq = TRUE;
3057 xp->xp_context = EXPAND_EXPRESSION;
3059 else if (c == '<'
3060 && xp->xp_context == EXPAND_FUNCTIONS
3061 && vim_strchr(xp->xp_pattern, '(') == NULL)
3063 /* Function name can start with "<SNR>" */
3064 break;
3066 else if (cmdidx != CMD_let || got_eq)
3068 if (c == '"') /* string */
3070 while ((c = *++xp->xp_pattern) != NUL && c != '"')
3071 if (c == '\\' && xp->xp_pattern[1] != NUL)
3072 ++xp->xp_pattern;
3073 xp->xp_context = EXPAND_NOTHING;
3075 else if (c == '\'') /* literal string */
3077 /* Trick: '' is like stopping and starting a literal string. */
3078 while ((c = *++xp->xp_pattern) != NUL && c != '\'')
3079 /* skip */ ;
3080 xp->xp_context = EXPAND_NOTHING;
3082 else if (c == '|')
3084 if (xp->xp_pattern[1] == '|')
3086 ++xp->xp_pattern;
3087 xp->xp_context = EXPAND_EXPRESSION;
3089 else
3090 xp->xp_context = EXPAND_COMMANDS;
3092 else
3093 xp->xp_context = EXPAND_EXPRESSION;
3095 else
3096 /* Doesn't look like something valid, expand as an expression
3097 * anyway. */
3098 xp->xp_context = EXPAND_EXPRESSION;
3099 arg = xp->xp_pattern;
3100 if (*arg != NUL)
3101 while ((c = *++arg) != NUL && (c == ' ' || c == '\t'))
3102 /* skip */ ;
3104 xp->xp_pattern = arg;
3107 #endif /* FEAT_CMDL_COMPL */
3110 * ":1,25call func(arg1, arg2)" function call.
3112 void
3113 ex_call(eap)
3114 exarg_T *eap;
3116 char_u *arg = eap->arg;
3117 char_u *startarg;
3118 char_u *name;
3119 char_u *tofree;
3120 int len;
3121 typval_T rettv;
3122 linenr_T lnum;
3123 int doesrange;
3124 int failed = FALSE;
3125 funcdict_T fudi;
3127 tofree = trans_function_name(&arg, eap->skip, TFN_INT, &fudi);
3128 vim_free(fudi.fd_newkey);
3129 if (tofree == NULL)
3130 return;
3132 /* Increase refcount on dictionary, it could get deleted when evaluating
3133 * the arguments. */
3134 if (fudi.fd_dict != NULL)
3135 ++fudi.fd_dict->dv_refcount;
3137 /* If it is the name of a variable of type VAR_FUNC use its contents. */
3138 len = (int)STRLEN(tofree);
3139 name = deref_func_name(tofree, &len);
3141 /* Skip white space to allow ":call func ()". Not good, but required for
3142 * backward compatibility. */
3143 startarg = skipwhite(arg);
3144 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
3146 if (*startarg != '(')
3148 EMSG2(_("E107: Missing braces: %s"), eap->arg);
3149 goto end;
3153 * When skipping, evaluate the function once, to find the end of the
3154 * arguments.
3155 * When the function takes a range, this is discovered after the first
3156 * call, and the loop is broken.
3158 if (eap->skip)
3160 ++emsg_skip;
3161 lnum = eap->line2; /* do it once, also with an invalid range */
3163 else
3164 lnum = eap->line1;
3165 for ( ; lnum <= eap->line2; ++lnum)
3167 if (!eap->skip && eap->addr_count > 0)
3169 curwin->w_cursor.lnum = lnum;
3170 curwin->w_cursor.col = 0;
3172 arg = startarg;
3173 if (get_func_tv(name, (int)STRLEN(name), &rettv, &arg,
3174 eap->line1, eap->line2, &doesrange,
3175 !eap->skip, fudi.fd_dict) == FAIL)
3177 failed = TRUE;
3178 break;
3180 clear_tv(&rettv);
3181 if (doesrange || eap->skip)
3182 break;
3183 /* Stop when immediately aborting on error, or when an interrupt
3184 * occurred or an exception was thrown but not caught.
3185 * get_func_tv() returned OK, so that the check for trailing
3186 * characters below is executed. */
3187 if (aborting())
3188 break;
3190 if (eap->skip)
3191 --emsg_skip;
3193 if (!failed)
3195 /* Check for trailing illegal characters and a following command. */
3196 if (!ends_excmd(*arg))
3198 emsg_severe = TRUE;
3199 EMSG(_(e_trailing));
3201 else
3202 eap->nextcmd = check_nextcmd(arg);
3205 end:
3206 dict_unref(fudi.fd_dict);
3207 vim_free(tofree);
3211 * ":unlet[!] var1 ... " command.
3213 void
3214 ex_unlet(eap)
3215 exarg_T *eap;
3217 ex_unletlock(eap, eap->arg, 0);
3221 * ":lockvar" and ":unlockvar" commands
3223 void
3224 ex_lockvar(eap)
3225 exarg_T *eap;
3227 char_u *arg = eap->arg;
3228 int deep = 2;
3230 if (eap->forceit)
3231 deep = -1;
3232 else if (vim_isdigit(*arg))
3234 deep = getdigits(&arg);
3235 arg = skipwhite(arg);
3238 ex_unletlock(eap, arg, deep);
3242 * ":unlet", ":lockvar" and ":unlockvar" are quite similar.
3244 static void
3245 ex_unletlock(eap, argstart, deep)
3246 exarg_T *eap;
3247 char_u *argstart;
3248 int deep;
3250 char_u *arg = argstart;
3251 char_u *name_end;
3252 int error = FALSE;
3253 lval_T lv;
3257 /* Parse the name and find the end. */
3258 name_end = get_lval(arg, NULL, &lv, TRUE, eap->skip || error, FALSE,
3259 FNE_CHECK_START);
3260 if (lv.ll_name == NULL)
3261 error = TRUE; /* error but continue parsing */
3262 if (name_end == NULL || (!vim_iswhite(*name_end)
3263 && !ends_excmd(*name_end)))
3265 if (name_end != NULL)
3267 emsg_severe = TRUE;
3268 EMSG(_(e_trailing));
3270 if (!(eap->skip || error))
3271 clear_lval(&lv);
3272 break;
3275 if (!error && !eap->skip)
3277 if (eap->cmdidx == CMD_unlet)
3279 if (do_unlet_var(&lv, name_end, eap->forceit) == FAIL)
3280 error = TRUE;
3282 else
3284 if (do_lock_var(&lv, name_end, deep,
3285 eap->cmdidx == CMD_lockvar) == FAIL)
3286 error = TRUE;
3290 if (!eap->skip)
3291 clear_lval(&lv);
3293 arg = skipwhite(name_end);
3294 } while (!ends_excmd(*arg));
3296 eap->nextcmd = check_nextcmd(arg);
3299 static int
3300 do_unlet_var(lp, name_end, forceit)
3301 lval_T *lp;
3302 char_u *name_end;
3303 int forceit;
3305 int ret = OK;
3306 int cc;
3308 if (lp->ll_tv == NULL)
3310 cc = *name_end;
3311 *name_end = NUL;
3313 /* Normal name or expanded name. */
3314 if (check_changedtick(lp->ll_name))
3315 ret = FAIL;
3316 else if (do_unlet(lp->ll_name, forceit) == FAIL)
3317 ret = FAIL;
3318 *name_end = cc;
3320 else if (tv_check_lock(lp->ll_tv->v_lock, lp->ll_name))
3321 return FAIL;
3322 else if (lp->ll_range)
3324 listitem_T *li;
3326 /* Delete a range of List items. */
3327 while (lp->ll_li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3329 li = lp->ll_li->li_next;
3330 listitem_remove(lp->ll_list, lp->ll_li);
3331 lp->ll_li = li;
3332 ++lp->ll_n1;
3335 else
3337 if (lp->ll_list != NULL)
3338 /* unlet a List item. */
3339 listitem_remove(lp->ll_list, lp->ll_li);
3340 else
3341 /* unlet a Dictionary item. */
3342 dictitem_remove(lp->ll_dict, lp->ll_di);
3345 return ret;
3349 * "unlet" a variable. Return OK if it existed, FAIL if not.
3350 * When "forceit" is TRUE don't complain if the variable doesn't exist.
3353 do_unlet(name, forceit)
3354 char_u *name;
3355 int forceit;
3357 hashtab_T *ht;
3358 hashitem_T *hi;
3359 char_u *varname;
3361 ht = find_var_ht(name, &varname);
3362 if (ht != NULL && *varname != NUL)
3364 hi = hash_find(ht, varname);
3365 if (!HASHITEM_EMPTY(hi))
3367 if (var_check_ro(HI2DI(hi)->di_flags, name))
3368 return FAIL;
3369 delete_var(ht, hi);
3370 return OK;
3373 if (forceit)
3374 return OK;
3375 EMSG2(_("E108: No such variable: \"%s\""), name);
3376 return FAIL;
3380 * Lock or unlock variable indicated by "lp".
3381 * "deep" is the levels to go (-1 for unlimited);
3382 * "lock" is TRUE for ":lockvar", FALSE for ":unlockvar".
3384 static int
3385 do_lock_var(lp, name_end, deep, lock)
3386 lval_T *lp;
3387 char_u *name_end;
3388 int deep;
3389 int lock;
3391 int ret = OK;
3392 int cc;
3393 dictitem_T *di;
3395 if (deep == 0) /* nothing to do */
3396 return OK;
3398 if (lp->ll_tv == NULL)
3400 cc = *name_end;
3401 *name_end = NUL;
3403 /* Normal name or expanded name. */
3404 if (check_changedtick(lp->ll_name))
3405 ret = FAIL;
3406 else
3408 di = find_var(lp->ll_name, NULL);
3409 if (di == NULL)
3410 ret = FAIL;
3411 else
3413 if (lock)
3414 di->di_flags |= DI_FLAGS_LOCK;
3415 else
3416 di->di_flags &= ~DI_FLAGS_LOCK;
3417 item_lock(&di->di_tv, deep, lock);
3420 *name_end = cc;
3422 else if (lp->ll_range)
3424 listitem_T *li = lp->ll_li;
3426 /* (un)lock a range of List items. */
3427 while (li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3429 item_lock(&li->li_tv, deep, lock);
3430 li = li->li_next;
3431 ++lp->ll_n1;
3434 else if (lp->ll_list != NULL)
3435 /* (un)lock a List item. */
3436 item_lock(&lp->ll_li->li_tv, deep, lock);
3437 else
3438 /* un(lock) a Dictionary item. */
3439 item_lock(&lp->ll_di->di_tv, deep, lock);
3441 return ret;
3445 * Lock or unlock an item. "deep" is nr of levels to go.
3447 static void
3448 item_lock(tv, deep, lock)
3449 typval_T *tv;
3450 int deep;
3451 int lock;
3453 static int recurse = 0;
3454 list_T *l;
3455 listitem_T *li;
3456 dict_T *d;
3457 hashitem_T *hi;
3458 int todo;
3460 if (recurse >= DICT_MAXNEST)
3462 EMSG(_("E743: variable nested too deep for (un)lock"));
3463 return;
3465 if (deep == 0)
3466 return;
3467 ++recurse;
3469 /* lock/unlock the item itself */
3470 if (lock)
3471 tv->v_lock |= VAR_LOCKED;
3472 else
3473 tv->v_lock &= ~VAR_LOCKED;
3475 switch (tv->v_type)
3477 case VAR_LIST:
3478 if ((l = tv->vval.v_list) != NULL)
3480 if (lock)
3481 l->lv_lock |= VAR_LOCKED;
3482 else
3483 l->lv_lock &= ~VAR_LOCKED;
3484 if (deep < 0 || deep > 1)
3485 /* recursive: lock/unlock the items the List contains */
3486 for (li = l->lv_first; li != NULL; li = li->li_next)
3487 item_lock(&li->li_tv, deep - 1, lock);
3489 break;
3490 case VAR_DICT:
3491 if ((d = tv->vval.v_dict) != NULL)
3493 if (lock)
3494 d->dv_lock |= VAR_LOCKED;
3495 else
3496 d->dv_lock &= ~VAR_LOCKED;
3497 if (deep < 0 || deep > 1)
3499 /* recursive: lock/unlock the items the List contains */
3500 todo = (int)d->dv_hashtab.ht_used;
3501 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
3503 if (!HASHITEM_EMPTY(hi))
3505 --todo;
3506 item_lock(&HI2DI(hi)->di_tv, deep - 1, lock);
3512 --recurse;
3516 * Return TRUE if typeval "tv" is locked: Either tha value is locked itself or
3517 * it refers to a List or Dictionary that is locked.
3519 static int
3520 tv_islocked(tv)
3521 typval_T *tv;
3523 return (tv->v_lock & VAR_LOCKED)
3524 || (tv->v_type == VAR_LIST
3525 && tv->vval.v_list != NULL
3526 && (tv->vval.v_list->lv_lock & VAR_LOCKED))
3527 || (tv->v_type == VAR_DICT
3528 && tv->vval.v_dict != NULL
3529 && (tv->vval.v_dict->dv_lock & VAR_LOCKED));
3532 #if (defined(FEAT_MENU) && defined(FEAT_MULTI_LANG)) || defined(PROTO)
3534 * Delete all "menutrans_" variables.
3536 void
3537 del_menutrans_vars()
3539 hashitem_T *hi;
3540 int todo;
3542 hash_lock(&globvarht);
3543 todo = (int)globvarht.ht_used;
3544 for (hi = globvarht.ht_array; todo > 0 && !got_int; ++hi)
3546 if (!HASHITEM_EMPTY(hi))
3548 --todo;
3549 if (STRNCMP(HI2DI(hi)->di_key, "menutrans_", 10) == 0)
3550 delete_var(&globvarht, hi);
3553 hash_unlock(&globvarht);
3555 #endif
3557 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3560 * Local string buffer for the next two functions to store a variable name
3561 * with its prefix. Allocated in cat_prefix_varname(), freed later in
3562 * get_user_var_name().
3565 static char_u *cat_prefix_varname __ARGS((int prefix, char_u *name));
3567 static char_u *varnamebuf = NULL;
3568 static int varnamebuflen = 0;
3571 * Function to concatenate a prefix and a variable name.
3573 static char_u *
3574 cat_prefix_varname(prefix, name)
3575 int prefix;
3576 char_u *name;
3578 int len;
3580 len = (int)STRLEN(name) + 3;
3581 if (len > varnamebuflen)
3583 vim_free(varnamebuf);
3584 len += 10; /* some additional space */
3585 varnamebuf = alloc(len);
3586 if (varnamebuf == NULL)
3588 varnamebuflen = 0;
3589 return NULL;
3591 varnamebuflen = len;
3593 *varnamebuf = prefix;
3594 varnamebuf[1] = ':';
3595 STRCPY(varnamebuf + 2, name);
3596 return varnamebuf;
3600 * Function given to ExpandGeneric() to obtain the list of user defined
3601 * (global/buffer/window/built-in) variable names.
3603 /*ARGSUSED*/
3604 char_u *
3605 get_user_var_name(xp, idx)
3606 expand_T *xp;
3607 int idx;
3609 static long_u gdone;
3610 static long_u bdone;
3611 static long_u wdone;
3612 #ifdef FEAT_WINDOWS
3613 static long_u tdone;
3614 #endif
3615 static int vidx;
3616 static hashitem_T *hi;
3617 hashtab_T *ht;
3619 if (idx == 0)
3621 gdone = bdone = wdone = vidx = 0;
3622 #ifdef FEAT_WINDOWS
3623 tdone = 0;
3624 #endif
3627 /* Global variables */
3628 if (gdone < globvarht.ht_used)
3630 if (gdone++ == 0)
3631 hi = globvarht.ht_array;
3632 else
3633 ++hi;
3634 while (HASHITEM_EMPTY(hi))
3635 ++hi;
3636 if (STRNCMP("g:", xp->xp_pattern, 2) == 0)
3637 return cat_prefix_varname('g', hi->hi_key);
3638 return hi->hi_key;
3641 /* b: variables */
3642 ht = &curbuf->b_vars.dv_hashtab;
3643 if (bdone < ht->ht_used)
3645 if (bdone++ == 0)
3646 hi = ht->ht_array;
3647 else
3648 ++hi;
3649 while (HASHITEM_EMPTY(hi))
3650 ++hi;
3651 return cat_prefix_varname('b', hi->hi_key);
3653 if (bdone == ht->ht_used)
3655 ++bdone;
3656 return (char_u *)"b:changedtick";
3659 /* w: variables */
3660 ht = &curwin->w_vars.dv_hashtab;
3661 if (wdone < ht->ht_used)
3663 if (wdone++ == 0)
3664 hi = ht->ht_array;
3665 else
3666 ++hi;
3667 while (HASHITEM_EMPTY(hi))
3668 ++hi;
3669 return cat_prefix_varname('w', hi->hi_key);
3672 #ifdef FEAT_WINDOWS
3673 /* t: variables */
3674 ht = &curtab->tp_vars.dv_hashtab;
3675 if (tdone < ht->ht_used)
3677 if (tdone++ == 0)
3678 hi = ht->ht_array;
3679 else
3680 ++hi;
3681 while (HASHITEM_EMPTY(hi))
3682 ++hi;
3683 return cat_prefix_varname('t', hi->hi_key);
3685 #endif
3687 /* v: variables */
3688 if (vidx < VV_LEN)
3689 return cat_prefix_varname('v', (char_u *)vimvars[vidx++].vv_name);
3691 vim_free(varnamebuf);
3692 varnamebuf = NULL;
3693 varnamebuflen = 0;
3694 return NULL;
3697 #endif /* FEAT_CMDL_COMPL */
3700 * types for expressions.
3702 typedef enum
3704 TYPE_UNKNOWN = 0
3705 , TYPE_EQUAL /* == */
3706 , TYPE_NEQUAL /* != */
3707 , TYPE_GREATER /* > */
3708 , TYPE_GEQUAL /* >= */
3709 , TYPE_SMALLER /* < */
3710 , TYPE_SEQUAL /* <= */
3711 , TYPE_MATCH /* =~ */
3712 , TYPE_NOMATCH /* !~ */
3713 } exptype_T;
3716 * The "evaluate" argument: When FALSE, the argument is only parsed but not
3717 * executed. The function may return OK, but the rettv will be of type
3718 * VAR_UNKNOWN. The function still returns FAIL for a syntax error.
3722 * Handle zero level expression.
3723 * This calls eval1() and handles error message and nextcmd.
3724 * Put the result in "rettv" when returning OK and "evaluate" is TRUE.
3725 * Note: "rettv.v_lock" is not set.
3726 * Return OK or FAIL.
3728 static int
3729 eval0(arg, rettv, nextcmd, evaluate)
3730 char_u *arg;
3731 typval_T *rettv;
3732 char_u **nextcmd;
3733 int evaluate;
3735 int ret;
3736 char_u *p;
3738 p = skipwhite(arg);
3739 ret = eval1(&p, rettv, evaluate);
3740 if (ret == FAIL || !ends_excmd(*p))
3742 if (ret != FAIL)
3743 clear_tv(rettv);
3745 * Report the invalid expression unless the expression evaluation has
3746 * been cancelled due to an aborting error, an interrupt, or an
3747 * exception.
3749 if (!aborting())
3750 EMSG2(_(e_invexpr2), arg);
3751 ret = FAIL;
3753 if (nextcmd != NULL)
3754 *nextcmd = check_nextcmd(p);
3756 return ret;
3760 * Handle top level expression:
3761 * expr1 ? expr0 : expr0
3763 * "arg" must point to the first non-white of the expression.
3764 * "arg" is advanced to the next non-white after the recognized expression.
3766 * Note: "rettv.v_lock" is not set.
3768 * Return OK or FAIL.
3770 static int
3771 eval1(arg, rettv, evaluate)
3772 char_u **arg;
3773 typval_T *rettv;
3774 int evaluate;
3776 int result;
3777 typval_T var2;
3780 * Get the first variable.
3782 if (eval2(arg, rettv, evaluate) == FAIL)
3783 return FAIL;
3785 if ((*arg)[0] == '?')
3787 result = FALSE;
3788 if (evaluate)
3790 int error = FALSE;
3792 if (get_tv_number_chk(rettv, &error) != 0)
3793 result = TRUE;
3794 clear_tv(rettv);
3795 if (error)
3796 return FAIL;
3800 * Get the second variable.
3802 *arg = skipwhite(*arg + 1);
3803 if (eval1(arg, rettv, evaluate && result) == FAIL) /* recursive! */
3804 return FAIL;
3807 * Check for the ":".
3809 if ((*arg)[0] != ':')
3811 EMSG(_("E109: Missing ':' after '?'"));
3812 if (evaluate && result)
3813 clear_tv(rettv);
3814 return FAIL;
3818 * Get the third variable.
3820 *arg = skipwhite(*arg + 1);
3821 if (eval1(arg, &var2, evaluate && !result) == FAIL) /* recursive! */
3823 if (evaluate && result)
3824 clear_tv(rettv);
3825 return FAIL;
3827 if (evaluate && !result)
3828 *rettv = var2;
3831 return OK;
3835 * Handle first level expression:
3836 * expr2 || expr2 || expr2 logical OR
3838 * "arg" must point to the first non-white of the expression.
3839 * "arg" is advanced to the next non-white after the recognized expression.
3841 * Return OK or FAIL.
3843 static int
3844 eval2(arg, rettv, evaluate)
3845 char_u **arg;
3846 typval_T *rettv;
3847 int evaluate;
3849 typval_T var2;
3850 long result;
3851 int first;
3852 int error = FALSE;
3855 * Get the first variable.
3857 if (eval3(arg, rettv, evaluate) == FAIL)
3858 return FAIL;
3861 * Repeat until there is no following "||".
3863 first = TRUE;
3864 result = FALSE;
3865 while ((*arg)[0] == '|' && (*arg)[1] == '|')
3867 if (evaluate && first)
3869 if (get_tv_number_chk(rettv, &error) != 0)
3870 result = TRUE;
3871 clear_tv(rettv);
3872 if (error)
3873 return FAIL;
3874 first = FALSE;
3878 * Get the second variable.
3880 *arg = skipwhite(*arg + 2);
3881 if (eval3(arg, &var2, evaluate && !result) == FAIL)
3882 return FAIL;
3885 * Compute the result.
3887 if (evaluate && !result)
3889 if (get_tv_number_chk(&var2, &error) != 0)
3890 result = TRUE;
3891 clear_tv(&var2);
3892 if (error)
3893 return FAIL;
3895 if (evaluate)
3897 rettv->v_type = VAR_NUMBER;
3898 rettv->vval.v_number = result;
3902 return OK;
3906 * Handle second level expression:
3907 * expr3 && expr3 && expr3 logical AND
3909 * "arg" must point to the first non-white of the expression.
3910 * "arg" is advanced to the next non-white after the recognized expression.
3912 * Return OK or FAIL.
3914 static int
3915 eval3(arg, rettv, evaluate)
3916 char_u **arg;
3917 typval_T *rettv;
3918 int evaluate;
3920 typval_T var2;
3921 long result;
3922 int first;
3923 int error = FALSE;
3926 * Get the first variable.
3928 if (eval4(arg, rettv, evaluate) == FAIL)
3929 return FAIL;
3932 * Repeat until there is no following "&&".
3934 first = TRUE;
3935 result = TRUE;
3936 while ((*arg)[0] == '&' && (*arg)[1] == '&')
3938 if (evaluate && first)
3940 if (get_tv_number_chk(rettv, &error) == 0)
3941 result = FALSE;
3942 clear_tv(rettv);
3943 if (error)
3944 return FAIL;
3945 first = FALSE;
3949 * Get the second variable.
3951 *arg = skipwhite(*arg + 2);
3952 if (eval4(arg, &var2, evaluate && result) == FAIL)
3953 return FAIL;
3956 * Compute the result.
3958 if (evaluate && result)
3960 if (get_tv_number_chk(&var2, &error) == 0)
3961 result = FALSE;
3962 clear_tv(&var2);
3963 if (error)
3964 return FAIL;
3966 if (evaluate)
3968 rettv->v_type = VAR_NUMBER;
3969 rettv->vval.v_number = result;
3973 return OK;
3977 * Handle third level expression:
3978 * var1 == var2
3979 * var1 =~ var2
3980 * var1 != var2
3981 * var1 !~ var2
3982 * var1 > var2
3983 * var1 >= var2
3984 * var1 < var2
3985 * var1 <= var2
3986 * var1 is var2
3987 * var1 isnot var2
3989 * "arg" must point to the first non-white of the expression.
3990 * "arg" is advanced to the next non-white after the recognized expression.
3992 * Return OK or FAIL.
3994 static int
3995 eval4(arg, rettv, evaluate)
3996 char_u **arg;
3997 typval_T *rettv;
3998 int evaluate;
4000 typval_T var2;
4001 char_u *p;
4002 int i;
4003 exptype_T type = TYPE_UNKNOWN;
4004 int type_is = FALSE; /* TRUE for "is" and "isnot" */
4005 int len = 2;
4006 long n1, n2;
4007 char_u *s1, *s2;
4008 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
4009 regmatch_T regmatch;
4010 int ic;
4011 char_u *save_cpo;
4014 * Get the first variable.
4016 if (eval5(arg, rettv, evaluate) == FAIL)
4017 return FAIL;
4019 p = *arg;
4020 switch (p[0])
4022 case '=': if (p[1] == '=')
4023 type = TYPE_EQUAL;
4024 else if (p[1] == '~')
4025 type = TYPE_MATCH;
4026 break;
4027 case '!': if (p[1] == '=')
4028 type = TYPE_NEQUAL;
4029 else if (p[1] == '~')
4030 type = TYPE_NOMATCH;
4031 break;
4032 case '>': if (p[1] != '=')
4034 type = TYPE_GREATER;
4035 len = 1;
4037 else
4038 type = TYPE_GEQUAL;
4039 break;
4040 case '<': if (p[1] != '=')
4042 type = TYPE_SMALLER;
4043 len = 1;
4045 else
4046 type = TYPE_SEQUAL;
4047 break;
4048 case 'i': if (p[1] == 's')
4050 if (p[2] == 'n' && p[3] == 'o' && p[4] == 't')
4051 len = 5;
4052 if (!vim_isIDc(p[len]))
4054 type = len == 2 ? TYPE_EQUAL : TYPE_NEQUAL;
4055 type_is = TRUE;
4058 break;
4062 * If there is a comparitive operator, use it.
4064 if (type != TYPE_UNKNOWN)
4066 /* extra question mark appended: ignore case */
4067 if (p[len] == '?')
4069 ic = TRUE;
4070 ++len;
4072 /* extra '#' appended: match case */
4073 else if (p[len] == '#')
4075 ic = FALSE;
4076 ++len;
4078 /* nothing appened: use 'ignorecase' */
4079 else
4080 ic = p_ic;
4083 * Get the second variable.
4085 *arg = skipwhite(p + len);
4086 if (eval5(arg, &var2, evaluate) == FAIL)
4088 clear_tv(rettv);
4089 return FAIL;
4092 if (evaluate)
4094 if (type_is && rettv->v_type != var2.v_type)
4096 /* For "is" a different type always means FALSE, for "notis"
4097 * it means TRUE. */
4098 n1 = (type == TYPE_NEQUAL);
4100 else if (rettv->v_type == VAR_LIST || var2.v_type == VAR_LIST)
4102 if (type_is)
4104 n1 = (rettv->v_type == var2.v_type
4105 && rettv->vval.v_list == var2.vval.v_list);
4106 if (type == TYPE_NEQUAL)
4107 n1 = !n1;
4109 else if (rettv->v_type != var2.v_type
4110 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4112 if (rettv->v_type != var2.v_type)
4113 EMSG(_("E691: Can only compare List with List"));
4114 else
4115 EMSG(_("E692: Invalid operation for Lists"));
4116 clear_tv(rettv);
4117 clear_tv(&var2);
4118 return FAIL;
4120 else
4122 /* Compare two Lists for being equal or unequal. */
4123 n1 = list_equal(rettv->vval.v_list, var2.vval.v_list, ic);
4124 if (type == TYPE_NEQUAL)
4125 n1 = !n1;
4129 else if (rettv->v_type == VAR_DICT || var2.v_type == VAR_DICT)
4131 if (type_is)
4133 n1 = (rettv->v_type == var2.v_type
4134 && rettv->vval.v_dict == var2.vval.v_dict);
4135 if (type == TYPE_NEQUAL)
4136 n1 = !n1;
4138 else if (rettv->v_type != var2.v_type
4139 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4141 if (rettv->v_type != var2.v_type)
4142 EMSG(_("E735: Can only compare Dictionary with Dictionary"));
4143 else
4144 EMSG(_("E736: Invalid operation for Dictionary"));
4145 clear_tv(rettv);
4146 clear_tv(&var2);
4147 return FAIL;
4149 else
4151 /* Compare two Dictionaries for being equal or unequal. */
4152 n1 = dict_equal(rettv->vval.v_dict, var2.vval.v_dict, ic);
4153 if (type == TYPE_NEQUAL)
4154 n1 = !n1;
4158 else if (rettv->v_type == VAR_FUNC || var2.v_type == VAR_FUNC)
4160 if (rettv->v_type != var2.v_type
4161 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4163 if (rettv->v_type != var2.v_type)
4164 EMSG(_("E693: Can only compare Funcref with Funcref"));
4165 else
4166 EMSG(_("E694: Invalid operation for Funcrefs"));
4167 clear_tv(rettv);
4168 clear_tv(&var2);
4169 return FAIL;
4171 else
4173 /* Compare two Funcrefs for being equal or unequal. */
4174 if (rettv->vval.v_string == NULL
4175 || var2.vval.v_string == NULL)
4176 n1 = FALSE;
4177 else
4178 n1 = STRCMP(rettv->vval.v_string,
4179 var2.vval.v_string) == 0;
4180 if (type == TYPE_NEQUAL)
4181 n1 = !n1;
4186 * If one of the two variables is a number, compare as a number.
4187 * When using "=~" or "!~", always compare as string.
4189 else if ((rettv->v_type == VAR_NUMBER || var2.v_type == VAR_NUMBER)
4190 && type != TYPE_MATCH && type != TYPE_NOMATCH)
4192 n1 = get_tv_number(rettv);
4193 n2 = get_tv_number(&var2);
4194 switch (type)
4196 case TYPE_EQUAL: n1 = (n1 == n2); break;
4197 case TYPE_NEQUAL: n1 = (n1 != n2); break;
4198 case TYPE_GREATER: n1 = (n1 > n2); break;
4199 case TYPE_GEQUAL: n1 = (n1 >= n2); break;
4200 case TYPE_SMALLER: n1 = (n1 < n2); break;
4201 case TYPE_SEQUAL: n1 = (n1 <= n2); break;
4202 case TYPE_UNKNOWN:
4203 case TYPE_MATCH:
4204 case TYPE_NOMATCH: break; /* avoid gcc warning */
4207 else
4209 s1 = get_tv_string_buf(rettv, buf1);
4210 s2 = get_tv_string_buf(&var2, buf2);
4211 if (type != TYPE_MATCH && type != TYPE_NOMATCH)
4212 i = ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2);
4213 else
4214 i = 0;
4215 n1 = FALSE;
4216 switch (type)
4218 case TYPE_EQUAL: n1 = (i == 0); break;
4219 case TYPE_NEQUAL: n1 = (i != 0); break;
4220 case TYPE_GREATER: n1 = (i > 0); break;
4221 case TYPE_GEQUAL: n1 = (i >= 0); break;
4222 case TYPE_SMALLER: n1 = (i < 0); break;
4223 case TYPE_SEQUAL: n1 = (i <= 0); break;
4225 case TYPE_MATCH:
4226 case TYPE_NOMATCH:
4227 /* avoid 'l' flag in 'cpoptions' */
4228 save_cpo = p_cpo;
4229 p_cpo = (char_u *)"";
4230 regmatch.regprog = vim_regcomp(s2,
4231 RE_MAGIC + RE_STRING);
4232 regmatch.rm_ic = ic;
4233 if (regmatch.regprog != NULL)
4235 n1 = vim_regexec_nl(&regmatch, s1, (colnr_T)0);
4236 vim_free(regmatch.regprog);
4237 if (type == TYPE_NOMATCH)
4238 n1 = !n1;
4240 p_cpo = save_cpo;
4241 break;
4243 case TYPE_UNKNOWN: break; /* avoid gcc warning */
4246 clear_tv(rettv);
4247 clear_tv(&var2);
4248 rettv->v_type = VAR_NUMBER;
4249 rettv->vval.v_number = n1;
4253 return OK;
4257 * Handle fourth level expression:
4258 * + number addition
4259 * - number subtraction
4260 * . string concatenation
4262 * "arg" must point to the first non-white of the expression.
4263 * "arg" is advanced to the next non-white after the recognized expression.
4265 * Return OK or FAIL.
4267 static int
4268 eval5(arg, rettv, evaluate)
4269 char_u **arg;
4270 typval_T *rettv;
4271 int evaluate;
4273 typval_T var2;
4274 typval_T var3;
4275 int op;
4276 long n1, n2;
4277 char_u *s1, *s2;
4278 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
4279 char_u *p;
4282 * Get the first variable.
4284 if (eval6(arg, rettv, evaluate) == FAIL)
4285 return FAIL;
4288 * Repeat computing, until no '+', '-' or '.' is following.
4290 for (;;)
4292 op = **arg;
4293 if (op != '+' && op != '-' && op != '.')
4294 break;
4296 if (op != '+' || rettv->v_type != VAR_LIST)
4298 /* For "list + ...", an illegal use of the first operand as
4299 * a number cannot be determined before evaluating the 2nd
4300 * operand: if this is also a list, all is ok.
4301 * For "something . ...", "something - ..." or "non-list + ...",
4302 * we know that the first operand needs to be a string or number
4303 * without evaluating the 2nd operand. So check before to avoid
4304 * side effects after an error. */
4305 if (evaluate && get_tv_string_chk(rettv) == NULL)
4307 clear_tv(rettv);
4308 return FAIL;
4313 * Get the second variable.
4315 *arg = skipwhite(*arg + 1);
4316 if (eval6(arg, &var2, evaluate) == FAIL)
4318 clear_tv(rettv);
4319 return FAIL;
4322 if (evaluate)
4325 * Compute the result.
4327 if (op == '.')
4329 s1 = get_tv_string_buf(rettv, buf1); /* already checked */
4330 s2 = get_tv_string_buf_chk(&var2, buf2);
4331 if (s2 == NULL) /* type error ? */
4333 clear_tv(rettv);
4334 clear_tv(&var2);
4335 return FAIL;
4337 p = concat_str(s1, s2);
4338 clear_tv(rettv);
4339 rettv->v_type = VAR_STRING;
4340 rettv->vval.v_string = p;
4342 else if (op == '+' && rettv->v_type == VAR_LIST
4343 && var2.v_type == VAR_LIST)
4345 /* concatenate Lists */
4346 if (list_concat(rettv->vval.v_list, var2.vval.v_list,
4347 &var3) == FAIL)
4349 clear_tv(rettv);
4350 clear_tv(&var2);
4351 return FAIL;
4353 clear_tv(rettv);
4354 *rettv = var3;
4356 else
4358 int error = FALSE;
4360 n1 = get_tv_number_chk(rettv, &error);
4361 if (error)
4363 /* This can only happen for "list + non-list".
4364 * For "non-list + ..." or "something - ...", we returned
4365 * before evaluating the 2nd operand. */
4366 clear_tv(rettv);
4367 return FAIL;
4369 n2 = get_tv_number_chk(&var2, &error);
4370 if (error)
4372 clear_tv(rettv);
4373 clear_tv(&var2);
4374 return FAIL;
4376 clear_tv(rettv);
4377 if (op == '+')
4378 n1 = n1 + n2;
4379 else
4380 n1 = n1 - n2;
4381 rettv->v_type = VAR_NUMBER;
4382 rettv->vval.v_number = n1;
4384 clear_tv(&var2);
4387 return OK;
4391 * Handle fifth level expression:
4392 * * number multiplication
4393 * / number division
4394 * % number modulo
4396 * "arg" must point to the first non-white of the expression.
4397 * "arg" is advanced to the next non-white after the recognized expression.
4399 * Return OK or FAIL.
4401 static int
4402 eval6(arg, rettv, evaluate)
4403 char_u **arg;
4404 typval_T *rettv;
4405 int evaluate;
4407 typval_T var2;
4408 int op;
4409 long n1, n2;
4410 int error = FALSE;
4413 * Get the first variable.
4415 if (eval7(arg, rettv, evaluate) == FAIL)
4416 return FAIL;
4419 * Repeat computing, until no '*', '/' or '%' is following.
4421 for (;;)
4423 op = **arg;
4424 if (op != '*' && op != '/' && op != '%')
4425 break;
4427 if (evaluate)
4429 n1 = get_tv_number_chk(rettv, &error);
4430 clear_tv(rettv);
4431 if (error)
4432 return FAIL;
4434 else
4435 n1 = 0;
4438 * Get the second variable.
4440 *arg = skipwhite(*arg + 1);
4441 if (eval7(arg, &var2, evaluate) == FAIL)
4442 return FAIL;
4444 if (evaluate)
4446 n2 = get_tv_number_chk(&var2, &error);
4447 clear_tv(&var2);
4448 if (error)
4449 return FAIL;
4452 * Compute the result.
4454 if (op == '*')
4455 n1 = n1 * n2;
4456 else if (op == '/')
4458 if (n2 == 0) /* give an error message? */
4459 n1 = 0x7fffffffL;
4460 else
4461 n1 = n1 / n2;
4463 else
4465 if (n2 == 0) /* give an error message? */
4466 n1 = 0;
4467 else
4468 n1 = n1 % n2;
4470 rettv->v_type = VAR_NUMBER;
4471 rettv->vval.v_number = n1;
4475 return OK;
4479 * Handle sixth level expression:
4480 * number number constant
4481 * "string" string contstant
4482 * 'string' literal string contstant
4483 * &option-name option value
4484 * @r register contents
4485 * identifier variable value
4486 * function() function call
4487 * $VAR environment variable
4488 * (expression) nested expression
4489 * [expr, expr] List
4490 * {key: val, key: val} Dictionary
4492 * Also handle:
4493 * ! in front logical NOT
4494 * - in front unary minus
4495 * + in front unary plus (ignored)
4496 * trailing [] subscript in String or List
4497 * trailing .name entry in Dictionary
4499 * "arg" must point to the first non-white of the expression.
4500 * "arg" is advanced to the next non-white after the recognized expression.
4502 * Return OK or FAIL.
4504 static int
4505 eval7(arg, rettv, evaluate)
4506 char_u **arg;
4507 typval_T *rettv;
4508 int evaluate;
4510 long n;
4511 int len;
4512 char_u *s;
4513 int val;
4514 char_u *start_leader, *end_leader;
4515 int ret = OK;
4516 char_u *alias;
4519 * Initialise variable so that clear_tv() can't mistake this for a
4520 * string and free a string that isn't there.
4522 rettv->v_type = VAR_UNKNOWN;
4525 * Skip '!' and '-' characters. They are handled later.
4527 start_leader = *arg;
4528 while (**arg == '!' || **arg == '-' || **arg == '+')
4529 *arg = skipwhite(*arg + 1);
4530 end_leader = *arg;
4532 switch (**arg)
4535 * Number constant.
4537 case '0':
4538 case '1':
4539 case '2':
4540 case '3':
4541 case '4':
4542 case '5':
4543 case '6':
4544 case '7':
4545 case '8':
4546 case '9':
4547 vim_str2nr(*arg, NULL, &len, TRUE, TRUE, &n, NULL);
4548 *arg += len;
4549 if (evaluate)
4551 rettv->v_type = VAR_NUMBER;
4552 rettv->vval.v_number = n;
4554 break;
4557 * String constant: "string".
4559 case '"': ret = get_string_tv(arg, rettv, evaluate);
4560 break;
4563 * Literal string constant: 'str''ing'.
4565 case '\'': ret = get_lit_string_tv(arg, rettv, evaluate);
4566 break;
4569 * List: [expr, expr]
4571 case '[': ret = get_list_tv(arg, rettv, evaluate);
4572 break;
4575 * Dictionary: {key: val, key: val}
4577 case '{': ret = get_dict_tv(arg, rettv, evaluate);
4578 break;
4581 * Option value: &name
4583 case '&': ret = get_option_tv(arg, rettv, evaluate);
4584 break;
4587 * Environment variable: $VAR.
4589 case '$': ret = get_env_tv(arg, rettv, evaluate);
4590 break;
4593 * Register contents: @r.
4595 case '@': ++*arg;
4596 if (evaluate)
4598 rettv->v_type = VAR_STRING;
4599 rettv->vval.v_string = get_reg_contents(**arg, TRUE, TRUE);
4601 if (**arg != NUL)
4602 ++*arg;
4603 break;
4606 * nested expression: (expression).
4608 case '(': *arg = skipwhite(*arg + 1);
4609 ret = eval1(arg, rettv, evaluate); /* recursive! */
4610 if (**arg == ')')
4611 ++*arg;
4612 else if (ret == OK)
4614 EMSG(_("E110: Missing ')'"));
4615 clear_tv(rettv);
4616 ret = FAIL;
4618 break;
4620 default: ret = NOTDONE;
4621 break;
4624 if (ret == NOTDONE)
4627 * Must be a variable or function name.
4628 * Can also be a curly-braces kind of name: {expr}.
4630 s = *arg;
4631 len = get_name_len(arg, &alias, evaluate, TRUE);
4632 if (alias != NULL)
4633 s = alias;
4635 if (len <= 0)
4636 ret = FAIL;
4637 else
4639 if (**arg == '(') /* recursive! */
4641 /* If "s" is the name of a variable of type VAR_FUNC
4642 * use its contents. */
4643 s = deref_func_name(s, &len);
4645 /* Invoke the function. */
4646 ret = get_func_tv(s, len, rettv, arg,
4647 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
4648 &len, evaluate, NULL);
4649 /* Stop the expression evaluation when immediately
4650 * aborting on error, or when an interrupt occurred or
4651 * an exception was thrown but not caught. */
4652 if (aborting())
4654 if (ret == OK)
4655 clear_tv(rettv);
4656 ret = FAIL;
4659 else if (evaluate)
4660 ret = get_var_tv(s, len, rettv, TRUE);
4661 else
4662 ret = OK;
4665 if (alias != NULL)
4666 vim_free(alias);
4669 *arg = skipwhite(*arg);
4671 /* Handle following '[', '(' and '.' for expr[expr], expr.name,
4672 * expr(expr). */
4673 if (ret == OK)
4674 ret = handle_subscript(arg, rettv, evaluate, TRUE);
4677 * Apply logical NOT and unary '-', from right to left, ignore '+'.
4679 if (ret == OK && evaluate && end_leader > start_leader)
4681 int error = FALSE;
4683 val = get_tv_number_chk(rettv, &error);
4684 if (error)
4686 clear_tv(rettv);
4687 ret = FAIL;
4689 else
4691 while (end_leader > start_leader)
4693 --end_leader;
4694 if (*end_leader == '!')
4695 val = !val;
4696 else if (*end_leader == '-')
4697 val = -val;
4699 clear_tv(rettv);
4700 rettv->v_type = VAR_NUMBER;
4701 rettv->vval.v_number = val;
4705 return ret;
4709 * Evaluate an "[expr]" or "[expr:expr]" index. Also "dict.key".
4710 * "*arg" points to the '[' or '.'.
4711 * Returns FAIL or OK. "*arg" is advanced to after the ']'.
4713 static int
4714 eval_index(arg, rettv, evaluate, verbose)
4715 char_u **arg;
4716 typval_T *rettv;
4717 int evaluate;
4718 int verbose; /* give error messages */
4720 int empty1 = FALSE, empty2 = FALSE;
4721 typval_T var1, var2;
4722 long n1, n2 = 0;
4723 long len = -1;
4724 int range = FALSE;
4725 char_u *s;
4726 char_u *key = NULL;
4728 if (rettv->v_type == VAR_FUNC)
4730 if (verbose)
4731 EMSG(_("E695: Cannot index a Funcref"));
4732 return FAIL;
4735 if (**arg == '.')
4738 * dict.name
4740 key = *arg + 1;
4741 for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
4743 if (len == 0)
4744 return FAIL;
4745 *arg = skipwhite(key + len);
4747 else
4750 * something[idx]
4752 * Get the (first) variable from inside the [].
4754 *arg = skipwhite(*arg + 1);
4755 if (**arg == ':')
4756 empty1 = TRUE;
4757 else if (eval1(arg, &var1, evaluate) == FAIL) /* recursive! */
4758 return FAIL;
4759 else if (evaluate && get_tv_string_chk(&var1) == NULL)
4761 /* not a number or string */
4762 clear_tv(&var1);
4763 return FAIL;
4767 * Get the second variable from inside the [:].
4769 if (**arg == ':')
4771 range = TRUE;
4772 *arg = skipwhite(*arg + 1);
4773 if (**arg == ']')
4774 empty2 = TRUE;
4775 else if (eval1(arg, &var2, evaluate) == FAIL) /* recursive! */
4777 if (!empty1)
4778 clear_tv(&var1);
4779 return FAIL;
4781 else if (evaluate && get_tv_string_chk(&var2) == NULL)
4783 /* not a number or string */
4784 if (!empty1)
4785 clear_tv(&var1);
4786 clear_tv(&var2);
4787 return FAIL;
4791 /* Check for the ']'. */
4792 if (**arg != ']')
4794 if (verbose)
4795 EMSG(_(e_missbrac));
4796 clear_tv(&var1);
4797 if (range)
4798 clear_tv(&var2);
4799 return FAIL;
4801 *arg = skipwhite(*arg + 1); /* skip the ']' */
4804 if (evaluate)
4806 n1 = 0;
4807 if (!empty1 && rettv->v_type != VAR_DICT)
4809 n1 = get_tv_number(&var1);
4810 clear_tv(&var1);
4812 if (range)
4814 if (empty2)
4815 n2 = -1;
4816 else
4818 n2 = get_tv_number(&var2);
4819 clear_tv(&var2);
4823 switch (rettv->v_type)
4825 case VAR_NUMBER:
4826 case VAR_STRING:
4827 s = get_tv_string(rettv);
4828 len = (long)STRLEN(s);
4829 if (range)
4831 /* The resulting variable is a substring. If the indexes
4832 * are out of range the result is empty. */
4833 if (n1 < 0)
4835 n1 = len + n1;
4836 if (n1 < 0)
4837 n1 = 0;
4839 if (n2 < 0)
4840 n2 = len + n2;
4841 else if (n2 >= len)
4842 n2 = len;
4843 if (n1 >= len || n2 < 0 || n1 > n2)
4844 s = NULL;
4845 else
4846 s = vim_strnsave(s + n1, (int)(n2 - n1 + 1));
4848 else
4850 /* The resulting variable is a string of a single
4851 * character. If the index is too big or negative the
4852 * result is empty. */
4853 if (n1 >= len || n1 < 0)
4854 s = NULL;
4855 else
4856 s = vim_strnsave(s + n1, 1);
4858 clear_tv(rettv);
4859 rettv->v_type = VAR_STRING;
4860 rettv->vval.v_string = s;
4861 break;
4863 case VAR_LIST:
4864 len = list_len(rettv->vval.v_list);
4865 if (n1 < 0)
4866 n1 = len + n1;
4867 if (!empty1 && (n1 < 0 || n1 >= len))
4869 /* For a range we allow invalid values and return an empty
4870 * list. A list index out of range is an error. */
4871 if (!range)
4873 if (verbose)
4874 EMSGN(_(e_listidx), n1);
4875 return FAIL;
4877 n1 = len;
4879 if (range)
4881 list_T *l;
4882 listitem_T *item;
4884 if (n2 < 0)
4885 n2 = len + n2;
4886 else if (n2 >= len)
4887 n2 = len - 1;
4888 if (!empty2 && (n2 < 0 || n2 + 1 < n1))
4889 n2 = -1;
4890 l = list_alloc();
4891 if (l == NULL)
4892 return FAIL;
4893 for (item = list_find(rettv->vval.v_list, n1);
4894 n1 <= n2; ++n1)
4896 if (list_append_tv(l, &item->li_tv) == FAIL)
4898 list_free(l);
4899 return FAIL;
4901 item = item->li_next;
4903 clear_tv(rettv);
4904 rettv->v_type = VAR_LIST;
4905 rettv->vval.v_list = l;
4906 ++l->lv_refcount;
4908 else
4910 copy_tv(&list_find(rettv->vval.v_list, n1)->li_tv, &var1);
4911 clear_tv(rettv);
4912 *rettv = var1;
4914 break;
4916 case VAR_DICT:
4917 if (range)
4919 if (verbose)
4920 EMSG(_(e_dictrange));
4921 if (len == -1)
4922 clear_tv(&var1);
4923 return FAIL;
4926 dictitem_T *item;
4928 if (len == -1)
4930 key = get_tv_string(&var1);
4931 if (*key == NUL)
4933 if (verbose)
4934 EMSG(_(e_emptykey));
4935 clear_tv(&var1);
4936 return FAIL;
4940 item = dict_find(rettv->vval.v_dict, key, (int)len);
4942 if (item == NULL && verbose)
4943 EMSG2(_(e_dictkey), key);
4944 if (len == -1)
4945 clear_tv(&var1);
4946 if (item == NULL)
4947 return FAIL;
4949 copy_tv(&item->di_tv, &var1);
4950 clear_tv(rettv);
4951 *rettv = var1;
4953 break;
4957 return OK;
4961 * Get an option value.
4962 * "arg" points to the '&' or '+' before the option name.
4963 * "arg" is advanced to character after the option name.
4964 * Return OK or FAIL.
4966 static int
4967 get_option_tv(arg, rettv, evaluate)
4968 char_u **arg;
4969 typval_T *rettv; /* when NULL, only check if option exists */
4970 int evaluate;
4972 char_u *option_end;
4973 long numval;
4974 char_u *stringval;
4975 int opt_type;
4976 int c;
4977 int working = (**arg == '+'); /* has("+option") */
4978 int ret = OK;
4979 int opt_flags;
4982 * Isolate the option name and find its value.
4984 option_end = find_option_end(arg, &opt_flags);
4985 if (option_end == NULL)
4987 if (rettv != NULL)
4988 EMSG2(_("E112: Option name missing: %s"), *arg);
4989 return FAIL;
4992 if (!evaluate)
4994 *arg = option_end;
4995 return OK;
4998 c = *option_end;
4999 *option_end = NUL;
5000 opt_type = get_option_value(*arg, &numval,
5001 rettv == NULL ? NULL : &stringval, opt_flags);
5003 if (opt_type == -3) /* invalid name */
5005 if (rettv != NULL)
5006 EMSG2(_("E113: Unknown option: %s"), *arg);
5007 ret = FAIL;
5009 else if (rettv != NULL)
5011 if (opt_type == -2) /* hidden string option */
5013 rettv->v_type = VAR_STRING;
5014 rettv->vval.v_string = NULL;
5016 else if (opt_type == -1) /* hidden number option */
5018 rettv->v_type = VAR_NUMBER;
5019 rettv->vval.v_number = 0;
5021 else if (opt_type == 1) /* number option */
5023 rettv->v_type = VAR_NUMBER;
5024 rettv->vval.v_number = numval;
5026 else /* string option */
5028 rettv->v_type = VAR_STRING;
5029 rettv->vval.v_string = stringval;
5032 else if (working && (opt_type == -2 || opt_type == -1))
5033 ret = FAIL;
5035 *option_end = c; /* put back for error messages */
5036 *arg = option_end;
5038 return ret;
5042 * Allocate a variable for a string constant.
5043 * Return OK or FAIL.
5045 static int
5046 get_string_tv(arg, rettv, evaluate)
5047 char_u **arg;
5048 typval_T *rettv;
5049 int evaluate;
5051 char_u *p;
5052 char_u *name;
5053 int extra = 0;
5056 * Find the end of the string, skipping backslashed characters.
5058 for (p = *arg + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
5060 if (*p == '\\' && p[1] != NUL)
5062 ++p;
5063 /* A "\<x>" form occupies at least 4 characters, and produces up
5064 * to 6 characters: reserve space for 2 extra */
5065 if (*p == '<')
5066 extra += 2;
5070 if (*p != '"')
5072 EMSG2(_("E114: Missing quote: %s"), *arg);
5073 return FAIL;
5076 /* If only parsing, set *arg and return here */
5077 if (!evaluate)
5079 *arg = p + 1;
5080 return OK;
5084 * Copy the string into allocated memory, handling backslashed
5085 * characters.
5087 name = alloc((unsigned)(p - *arg + extra));
5088 if (name == NULL)
5089 return FAIL;
5090 rettv->v_type = VAR_STRING;
5091 rettv->vval.v_string = name;
5093 for (p = *arg + 1; *p != NUL && *p != '"'; )
5095 if (*p == '\\')
5097 switch (*++p)
5099 case 'b': *name++ = BS; ++p; break;
5100 case 'e': *name++ = ESC; ++p; break;
5101 case 'f': *name++ = FF; ++p; break;
5102 case 'n': *name++ = NL; ++p; break;
5103 case 'r': *name++ = CAR; ++p; break;
5104 case 't': *name++ = TAB; ++p; break;
5106 case 'X': /* hex: "\x1", "\x12" */
5107 case 'x':
5108 case 'u': /* Unicode: "\u0023" */
5109 case 'U':
5110 if (vim_isxdigit(p[1]))
5112 int n, nr;
5113 int c = toupper(*p);
5115 if (c == 'X')
5116 n = 2;
5117 else
5118 n = 4;
5119 nr = 0;
5120 while (--n >= 0 && vim_isxdigit(p[1]))
5122 ++p;
5123 nr = (nr << 4) + hex2nr(*p);
5125 ++p;
5126 #ifdef FEAT_MBYTE
5127 /* For "\u" store the number according to
5128 * 'encoding'. */
5129 if (c != 'X')
5130 name += (*mb_char2bytes)(nr, name);
5131 else
5132 #endif
5133 *name++ = nr;
5135 break;
5137 /* octal: "\1", "\12", "\123" */
5138 case '0':
5139 case '1':
5140 case '2':
5141 case '3':
5142 case '4':
5143 case '5':
5144 case '6':
5145 case '7': *name = *p++ - '0';
5146 if (*p >= '0' && *p <= '7')
5148 *name = (*name << 3) + *p++ - '0';
5149 if (*p >= '0' && *p <= '7')
5150 *name = (*name << 3) + *p++ - '0';
5152 ++name;
5153 break;
5155 /* Special key, e.g.: "\<C-W>" */
5156 case '<': extra = trans_special(&p, name, TRUE);
5157 if (extra != 0)
5159 name += extra;
5160 break;
5162 /* FALLTHROUGH */
5164 default: MB_COPY_CHAR(p, name);
5165 break;
5168 else
5169 MB_COPY_CHAR(p, name);
5172 *name = NUL;
5173 *arg = p + 1;
5175 return OK;
5179 * Allocate a variable for a 'str''ing' constant.
5180 * Return OK or FAIL.
5182 static int
5183 get_lit_string_tv(arg, rettv, evaluate)
5184 char_u **arg;
5185 typval_T *rettv;
5186 int evaluate;
5188 char_u *p;
5189 char_u *str;
5190 int reduce = 0;
5193 * Find the end of the string, skipping ''.
5195 for (p = *arg + 1; *p != NUL; mb_ptr_adv(p))
5197 if (*p == '\'')
5199 if (p[1] != '\'')
5200 break;
5201 ++reduce;
5202 ++p;
5206 if (*p != '\'')
5208 EMSG2(_("E115: Missing quote: %s"), *arg);
5209 return FAIL;
5212 /* If only parsing return after setting "*arg" */
5213 if (!evaluate)
5215 *arg = p + 1;
5216 return OK;
5220 * Copy the string into allocated memory, handling '' to ' reduction.
5222 str = alloc((unsigned)((p - *arg) - reduce));
5223 if (str == NULL)
5224 return FAIL;
5225 rettv->v_type = VAR_STRING;
5226 rettv->vval.v_string = str;
5228 for (p = *arg + 1; *p != NUL; )
5230 if (*p == '\'')
5232 if (p[1] != '\'')
5233 break;
5234 ++p;
5236 MB_COPY_CHAR(p, str);
5238 *str = NUL;
5239 *arg = p + 1;
5241 return OK;
5245 * Allocate a variable for a List and fill it from "*arg".
5246 * Return OK or FAIL.
5248 static int
5249 get_list_tv(arg, rettv, evaluate)
5250 char_u **arg;
5251 typval_T *rettv;
5252 int evaluate;
5254 list_T *l = NULL;
5255 typval_T tv;
5256 listitem_T *item;
5258 if (evaluate)
5260 l = list_alloc();
5261 if (l == NULL)
5262 return FAIL;
5265 *arg = skipwhite(*arg + 1);
5266 while (**arg != ']' && **arg != NUL)
5268 if (eval1(arg, &tv, evaluate) == FAIL) /* recursive! */
5269 goto failret;
5270 if (evaluate)
5272 item = listitem_alloc();
5273 if (item != NULL)
5275 item->li_tv = tv;
5276 item->li_tv.v_lock = 0;
5277 list_append(l, item);
5279 else
5280 clear_tv(&tv);
5283 if (**arg == ']')
5284 break;
5285 if (**arg != ',')
5287 EMSG2(_("E696: Missing comma in List: %s"), *arg);
5288 goto failret;
5290 *arg = skipwhite(*arg + 1);
5293 if (**arg != ']')
5295 EMSG2(_("E697: Missing end of List ']': %s"), *arg);
5296 failret:
5297 if (evaluate)
5298 list_free(l);
5299 return FAIL;
5302 *arg = skipwhite(*arg + 1);
5303 if (evaluate)
5305 rettv->v_type = VAR_LIST;
5306 rettv->vval.v_list = l;
5307 ++l->lv_refcount;
5310 return OK;
5314 * Allocate an empty header for a list.
5315 * Caller should take care of the reference count.
5317 list_T *
5318 list_alloc()
5320 list_T *l;
5322 l = (list_T *)alloc_clear(sizeof(list_T));
5323 if (l != NULL)
5325 /* Prepend the list to the list of lists for garbage collection. */
5326 if (first_list != NULL)
5327 first_list->lv_used_prev = l;
5328 l->lv_used_prev = NULL;
5329 l->lv_used_next = first_list;
5330 first_list = l;
5332 return l;
5336 * Allocate an empty list for a return value.
5337 * Returns OK or FAIL.
5339 static int
5340 rettv_list_alloc(rettv)
5341 typval_T *rettv;
5343 list_T *l = list_alloc();
5345 if (l == NULL)
5346 return FAIL;
5348 rettv->vval.v_list = l;
5349 rettv->v_type = VAR_LIST;
5350 ++l->lv_refcount;
5351 return OK;
5355 * Unreference a list: decrement the reference count and free it when it
5356 * becomes zero.
5358 void
5359 list_unref(l)
5360 list_T *l;
5362 if (l != NULL && l->lv_refcount != DEL_REFCOUNT && --l->lv_refcount <= 0)
5363 list_free(l);
5367 * Free a list, including all items it points to.
5368 * Ignores the reference count.
5370 void
5371 list_free(l)
5372 list_T *l;
5374 listitem_T *item;
5376 /* Avoid that recursive reference to the list frees us again. */
5377 l->lv_refcount = DEL_REFCOUNT;
5379 /* Remove the list from the list of lists for garbage collection. */
5380 if (l->lv_used_prev == NULL)
5381 first_list = l->lv_used_next;
5382 else
5383 l->lv_used_prev->lv_used_next = l->lv_used_next;
5384 if (l->lv_used_next != NULL)
5385 l->lv_used_next->lv_used_prev = l->lv_used_prev;
5387 for (item = l->lv_first; item != NULL; item = l->lv_first)
5389 /* Remove the item before deleting it. */
5390 l->lv_first = item->li_next;
5391 listitem_free(item);
5393 vim_free(l);
5397 * Allocate a list item.
5399 static listitem_T *
5400 listitem_alloc()
5402 return (listitem_T *)alloc(sizeof(listitem_T));
5406 * Free a list item. Also clears the value. Does not notify watchers.
5408 static void
5409 listitem_free(item)
5410 listitem_T *item;
5412 clear_tv(&item->li_tv);
5413 vim_free(item);
5417 * Remove a list item from a List and free it. Also clears the value.
5419 static void
5420 listitem_remove(l, item)
5421 list_T *l;
5422 listitem_T *item;
5424 list_remove(l, item, item);
5425 listitem_free(item);
5429 * Get the number of items in a list.
5431 static long
5432 list_len(l)
5433 list_T *l;
5435 if (l == NULL)
5436 return 0L;
5437 return l->lv_len;
5441 * Return TRUE when two lists have exactly the same values.
5443 static int
5444 list_equal(l1, l2, ic)
5445 list_T *l1;
5446 list_T *l2;
5447 int ic; /* ignore case for strings */
5449 listitem_T *item1, *item2;
5451 if (list_len(l1) != list_len(l2))
5452 return FALSE;
5454 for (item1 = l1->lv_first, item2 = l2->lv_first;
5455 item1 != NULL && item2 != NULL;
5456 item1 = item1->li_next, item2 = item2->li_next)
5457 if (!tv_equal(&item1->li_tv, &item2->li_tv, ic))
5458 return FALSE;
5459 return item1 == NULL && item2 == NULL;
5462 #if defined(FEAT_PYTHON) || defined(PROTO)
5464 * Return the dictitem that an entry in a hashtable points to.
5466 dictitem_T *
5467 dict_lookup(hi)
5468 hashitem_T *hi;
5470 return HI2DI(hi);
5472 #endif
5475 * Return TRUE when two dictionaries have exactly the same key/values.
5477 static int
5478 dict_equal(d1, d2, ic)
5479 dict_T *d1;
5480 dict_T *d2;
5481 int ic; /* ignore case for strings */
5483 hashitem_T *hi;
5484 dictitem_T *item2;
5485 int todo;
5487 if (dict_len(d1) != dict_len(d2))
5488 return FALSE;
5490 todo = (int)d1->dv_hashtab.ht_used;
5491 for (hi = d1->dv_hashtab.ht_array; todo > 0; ++hi)
5493 if (!HASHITEM_EMPTY(hi))
5495 item2 = dict_find(d2, hi->hi_key, -1);
5496 if (item2 == NULL)
5497 return FALSE;
5498 if (!tv_equal(&HI2DI(hi)->di_tv, &item2->di_tv, ic))
5499 return FALSE;
5500 --todo;
5503 return TRUE;
5507 * Return TRUE if "tv1" and "tv2" have the same value.
5508 * Compares the items just like "==" would compare them, but strings and
5509 * numbers are different.
5511 static int
5512 tv_equal(tv1, tv2, ic)
5513 typval_T *tv1;
5514 typval_T *tv2;
5515 int ic; /* ignore case */
5517 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
5518 char_u *s1, *s2;
5520 if (tv1->v_type != tv2->v_type)
5521 return FALSE;
5523 switch (tv1->v_type)
5525 case VAR_LIST:
5526 /* recursive! */
5527 return list_equal(tv1->vval.v_list, tv2->vval.v_list, ic);
5529 case VAR_DICT:
5530 /* recursive! */
5531 return dict_equal(tv1->vval.v_dict, tv2->vval.v_dict, ic);
5533 case VAR_FUNC:
5534 return (tv1->vval.v_string != NULL
5535 && tv2->vval.v_string != NULL
5536 && STRCMP(tv1->vval.v_string, tv2->vval.v_string) == 0);
5538 case VAR_NUMBER:
5539 return tv1->vval.v_number == tv2->vval.v_number;
5541 case VAR_STRING:
5542 s1 = get_tv_string_buf(tv1, buf1);
5543 s2 = get_tv_string_buf(tv2, buf2);
5544 return ((ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2)) == 0);
5547 EMSG2(_(e_intern2), "tv_equal()");
5548 return TRUE;
5552 * Locate item with index "n" in list "l" and return it.
5553 * A negative index is counted from the end; -1 is the last item.
5554 * Returns NULL when "n" is out of range.
5556 static listitem_T *
5557 list_find(l, n)
5558 list_T *l;
5559 long n;
5561 listitem_T *item;
5562 long idx;
5564 if (l == NULL)
5565 return NULL;
5567 /* Negative index is relative to the end. */
5568 if (n < 0)
5569 n = l->lv_len + n;
5571 /* Check for index out of range. */
5572 if (n < 0 || n >= l->lv_len)
5573 return NULL;
5575 /* When there is a cached index may start search from there. */
5576 if (l->lv_idx_item != NULL)
5578 if (n < l->lv_idx / 2)
5580 /* closest to the start of the list */
5581 item = l->lv_first;
5582 idx = 0;
5584 else if (n > (l->lv_idx + l->lv_len) / 2)
5586 /* closest to the end of the list */
5587 item = l->lv_last;
5588 idx = l->lv_len - 1;
5590 else
5592 /* closest to the cached index */
5593 item = l->lv_idx_item;
5594 idx = l->lv_idx;
5597 else
5599 if (n < l->lv_len / 2)
5601 /* closest to the start of the list */
5602 item = l->lv_first;
5603 idx = 0;
5605 else
5607 /* closest to the end of the list */
5608 item = l->lv_last;
5609 idx = l->lv_len - 1;
5613 while (n > idx)
5615 /* search forward */
5616 item = item->li_next;
5617 ++idx;
5619 while (n < idx)
5621 /* search backward */
5622 item = item->li_prev;
5623 --idx;
5626 /* cache the used index */
5627 l->lv_idx = idx;
5628 l->lv_idx_item = item;
5630 return item;
5634 * Get list item "l[idx]" as a number.
5636 static long
5637 list_find_nr(l, idx, errorp)
5638 list_T *l;
5639 long idx;
5640 int *errorp; /* set to TRUE when something wrong */
5642 listitem_T *li;
5644 li = list_find(l, idx);
5645 if (li == NULL)
5647 if (errorp != NULL)
5648 *errorp = TRUE;
5649 return -1L;
5651 return get_tv_number_chk(&li->li_tv, errorp);
5655 * Locate "item" list "l" and return its index.
5656 * Returns -1 when "item" is not in the list.
5658 static long
5659 list_idx_of_item(l, item)
5660 list_T *l;
5661 listitem_T *item;
5663 long idx = 0;
5664 listitem_T *li;
5666 if (l == NULL)
5667 return -1;
5668 idx = 0;
5669 for (li = l->lv_first; li != NULL && li != item; li = li->li_next)
5670 ++idx;
5671 if (li == NULL)
5672 return -1;
5673 return idx;
5677 * Append item "item" to the end of list "l".
5679 static void
5680 list_append(l, item)
5681 list_T *l;
5682 listitem_T *item;
5684 if (l->lv_last == NULL)
5686 /* empty list */
5687 l->lv_first = item;
5688 l->lv_last = item;
5689 item->li_prev = NULL;
5691 else
5693 l->lv_last->li_next = item;
5694 item->li_prev = l->lv_last;
5695 l->lv_last = item;
5697 ++l->lv_len;
5698 item->li_next = NULL;
5702 * Append typval_T "tv" to the end of list "l".
5703 * Return FAIL when out of memory.
5705 static int
5706 list_append_tv(l, tv)
5707 list_T *l;
5708 typval_T *tv;
5710 listitem_T *li = listitem_alloc();
5712 if (li == NULL)
5713 return FAIL;
5714 copy_tv(tv, &li->li_tv);
5715 list_append(l, li);
5716 return OK;
5720 * Add a dictionary to a list. Used by getqflist().
5721 * Return FAIL when out of memory.
5724 list_append_dict(list, dict)
5725 list_T *list;
5726 dict_T *dict;
5728 listitem_T *li = listitem_alloc();
5730 if (li == NULL)
5731 return FAIL;
5732 li->li_tv.v_type = VAR_DICT;
5733 li->li_tv.v_lock = 0;
5734 li->li_tv.vval.v_dict = dict;
5735 list_append(list, li);
5736 ++dict->dv_refcount;
5737 return OK;
5741 * Make a copy of "str" and append it as an item to list "l".
5742 * When "len" >= 0 use "str[len]".
5743 * Returns FAIL when out of memory.
5745 static int
5746 list_append_string(l, str, len)
5747 list_T *l;
5748 char_u *str;
5749 int len;
5751 listitem_T *li = listitem_alloc();
5753 if (li == NULL)
5754 return FAIL;
5755 list_append(l, li);
5756 li->li_tv.v_type = VAR_STRING;
5757 li->li_tv.v_lock = 0;
5758 if (str == NULL)
5759 li->li_tv.vval.v_string = NULL;
5760 else if ((li->li_tv.vval.v_string = (len >= 0 ? vim_strnsave(str, len)
5761 : vim_strsave(str))) == NULL)
5762 return FAIL;
5763 return OK;
5767 * Append "n" to list "l".
5768 * Returns FAIL when out of memory.
5770 static int
5771 list_append_number(l, n)
5772 list_T *l;
5773 varnumber_T n;
5775 listitem_T *li;
5777 li = listitem_alloc();
5778 if (li == NULL)
5779 return FAIL;
5780 li->li_tv.v_type = VAR_NUMBER;
5781 li->li_tv.v_lock = 0;
5782 li->li_tv.vval.v_number = n;
5783 list_append(l, li);
5784 return OK;
5788 * Insert typval_T "tv" in list "l" before "item".
5789 * If "item" is NULL append at the end.
5790 * Return FAIL when out of memory.
5792 static int
5793 list_insert_tv(l, tv, item)
5794 list_T *l;
5795 typval_T *tv;
5796 listitem_T *item;
5798 listitem_T *ni = listitem_alloc();
5800 if (ni == NULL)
5801 return FAIL;
5802 copy_tv(tv, &ni->li_tv);
5803 if (item == NULL)
5804 /* Append new item at end of list. */
5805 list_append(l, ni);
5806 else
5808 /* Insert new item before existing item. */
5809 ni->li_prev = item->li_prev;
5810 ni->li_next = item;
5811 if (item->li_prev == NULL)
5813 l->lv_first = ni;
5814 ++l->lv_idx;
5816 else
5818 item->li_prev->li_next = ni;
5819 l->lv_idx_item = NULL;
5821 item->li_prev = ni;
5822 ++l->lv_len;
5824 return OK;
5828 * Extend "l1" with "l2".
5829 * If "bef" is NULL append at the end, otherwise insert before this item.
5830 * Returns FAIL when out of memory.
5832 static int
5833 list_extend(l1, l2, bef)
5834 list_T *l1;
5835 list_T *l2;
5836 listitem_T *bef;
5838 listitem_T *item;
5840 for (item = l2->lv_first; item != NULL; item = item->li_next)
5841 if (list_insert_tv(l1, &item->li_tv, bef) == FAIL)
5842 return FAIL;
5843 return OK;
5847 * Concatenate lists "l1" and "l2" into a new list, stored in "tv".
5848 * Return FAIL when out of memory.
5850 static int
5851 list_concat(l1, l2, tv)
5852 list_T *l1;
5853 list_T *l2;
5854 typval_T *tv;
5856 list_T *l;
5858 /* make a copy of the first list. */
5859 l = list_copy(l1, FALSE, 0);
5860 if (l == NULL)
5861 return FAIL;
5862 tv->v_type = VAR_LIST;
5863 tv->vval.v_list = l;
5865 /* append all items from the second list */
5866 return list_extend(l, l2, NULL);
5870 * Make a copy of list "orig". Shallow if "deep" is FALSE.
5871 * The refcount of the new list is set to 1.
5872 * See item_copy() for "copyID".
5873 * Returns NULL when out of memory.
5875 static list_T *
5876 list_copy(orig, deep, copyID)
5877 list_T *orig;
5878 int deep;
5879 int copyID;
5881 list_T *copy;
5882 listitem_T *item;
5883 listitem_T *ni;
5885 if (orig == NULL)
5886 return NULL;
5888 copy = list_alloc();
5889 if (copy != NULL)
5891 if (copyID != 0)
5893 /* Do this before adding the items, because one of the items may
5894 * refer back to this list. */
5895 orig->lv_copyID = copyID;
5896 orig->lv_copylist = copy;
5898 for (item = orig->lv_first; item != NULL && !got_int;
5899 item = item->li_next)
5901 ni = listitem_alloc();
5902 if (ni == NULL)
5903 break;
5904 if (deep)
5906 if (item_copy(&item->li_tv, &ni->li_tv, deep, copyID) == FAIL)
5908 vim_free(ni);
5909 break;
5912 else
5913 copy_tv(&item->li_tv, &ni->li_tv);
5914 list_append(copy, ni);
5916 ++copy->lv_refcount;
5917 if (item != NULL)
5919 list_unref(copy);
5920 copy = NULL;
5924 return copy;
5928 * Remove items "item" to "item2" from list "l".
5929 * Does not free the listitem or the value!
5931 static void
5932 list_remove(l, item, item2)
5933 list_T *l;
5934 listitem_T *item;
5935 listitem_T *item2;
5937 listitem_T *ip;
5939 /* notify watchers */
5940 for (ip = item; ip != NULL; ip = ip->li_next)
5942 --l->lv_len;
5943 list_fix_watch(l, ip);
5944 if (ip == item2)
5945 break;
5948 if (item2->li_next == NULL)
5949 l->lv_last = item->li_prev;
5950 else
5951 item2->li_next->li_prev = item->li_prev;
5952 if (item->li_prev == NULL)
5953 l->lv_first = item2->li_next;
5954 else
5955 item->li_prev->li_next = item2->li_next;
5956 l->lv_idx_item = NULL;
5960 * Return an allocated string with the string representation of a list.
5961 * May return NULL.
5963 static char_u *
5964 list2string(tv, copyID)
5965 typval_T *tv;
5966 int copyID;
5968 garray_T ga;
5970 if (tv->vval.v_list == NULL)
5971 return NULL;
5972 ga_init2(&ga, (int)sizeof(char), 80);
5973 ga_append(&ga, '[');
5974 if (list_join(&ga, tv->vval.v_list, (char_u *)", ", FALSE, copyID) == FAIL)
5976 vim_free(ga.ga_data);
5977 return NULL;
5979 ga_append(&ga, ']');
5980 ga_append(&ga, NUL);
5981 return (char_u *)ga.ga_data;
5985 * Join list "l" into a string in "*gap", using separator "sep".
5986 * When "echo" is TRUE use String as echoed, otherwise as inside a List.
5987 * Return FAIL or OK.
5989 static int
5990 list_join(gap, l, sep, echo, copyID)
5991 garray_T *gap;
5992 list_T *l;
5993 char_u *sep;
5994 int echo;
5995 int copyID;
5997 int first = TRUE;
5998 char_u *tofree;
5999 char_u numbuf[NUMBUFLEN];
6000 listitem_T *item;
6001 char_u *s;
6003 for (item = l->lv_first; item != NULL && !got_int; item = item->li_next)
6005 if (first)
6006 first = FALSE;
6007 else
6008 ga_concat(gap, sep);
6010 if (echo)
6011 s = echo_string(&item->li_tv, &tofree, numbuf, copyID);
6012 else
6013 s = tv2string(&item->li_tv, &tofree, numbuf, copyID);
6014 if (s != NULL)
6015 ga_concat(gap, s);
6016 vim_free(tofree);
6017 if (s == NULL)
6018 return FAIL;
6020 return OK;
6024 * Garbage collection for lists and dictionaries.
6026 * We use reference counts to be able to free most items right away when they
6027 * are no longer used. But for composite items it's possible that it becomes
6028 * unused while the reference count is > 0: When there is a recursive
6029 * reference. Example:
6030 * :let l = [1, 2, 3]
6031 * :let d = {9: l}
6032 * :let l[1] = d
6034 * Since this is quite unusual we handle this with garbage collection: every
6035 * once in a while find out which lists and dicts are not referenced from any
6036 * variable.
6038 * Here is a good reference text about garbage collection (refers to Python
6039 * but it applies to all reference-counting mechanisms):
6040 * http://python.ca/nas/python/gc/
6044 * Do garbage collection for lists and dicts.
6045 * Return TRUE if some memory was freed.
6048 garbage_collect()
6050 dict_T *dd;
6051 list_T *ll;
6052 int copyID = ++current_copyID;
6053 buf_T *buf;
6054 win_T *wp;
6055 int i;
6056 funccall_T *fc;
6057 int did_free = FALSE;
6058 #ifdef FEAT_WINDOWS
6059 tabpage_T *tp;
6060 #endif
6063 * 1. Go through all accessible variables and mark all lists and dicts
6064 * with copyID.
6066 /* script-local variables */
6067 for (i = 1; i <= ga_scripts.ga_len; ++i)
6068 set_ref_in_ht(&SCRIPT_VARS(i), copyID);
6070 /* buffer-local variables */
6071 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
6072 set_ref_in_ht(&buf->b_vars.dv_hashtab, copyID);
6074 /* window-local variables */
6075 FOR_ALL_TAB_WINDOWS(tp, wp)
6076 set_ref_in_ht(&wp->w_vars.dv_hashtab, copyID);
6078 #ifdef FEAT_WINDOWS
6079 /* tabpage-local variables */
6080 for (tp = first_tabpage; tp != NULL; tp = tp->tp_next)
6081 set_ref_in_ht(&tp->tp_vars.dv_hashtab, copyID);
6082 #endif
6084 /* global variables */
6085 set_ref_in_ht(&globvarht, copyID);
6087 /* function-local variables */
6088 for (fc = current_funccal; fc != NULL; fc = fc->caller)
6090 set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID);
6091 set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID);
6095 * 2. Go through the list of dicts and free items without the copyID.
6097 for (dd = first_dict; dd != NULL; )
6098 if (dd->dv_copyID != copyID)
6100 dict_free(dd);
6101 did_free = TRUE;
6103 /* restart, next dict may also have been freed */
6104 dd = first_dict;
6106 else
6107 dd = dd->dv_used_next;
6110 * 3. Go through the list of lists and free items without the copyID.
6111 * But don't free a list that has a watcher (used in a for loop), these
6112 * are not referenced anywhere.
6114 for (ll = first_list; ll != NULL; )
6115 if (ll->lv_copyID != copyID && ll->lv_watch == NULL)
6117 list_free(ll);
6118 did_free = TRUE;
6120 /* restart, next list may also have been freed */
6121 ll = first_list;
6123 else
6124 ll = ll->lv_used_next;
6126 return did_free;
6130 * Mark all lists and dicts referenced through hashtab "ht" with "copyID".
6132 static void
6133 set_ref_in_ht(ht, copyID)
6134 hashtab_T *ht;
6135 int copyID;
6137 int todo;
6138 hashitem_T *hi;
6140 todo = (int)ht->ht_used;
6141 for (hi = ht->ht_array; todo > 0; ++hi)
6142 if (!HASHITEM_EMPTY(hi))
6144 --todo;
6145 set_ref_in_item(&HI2DI(hi)->di_tv, copyID);
6150 * Mark all lists and dicts referenced through list "l" with "copyID".
6152 static void
6153 set_ref_in_list(l, copyID)
6154 list_T *l;
6155 int copyID;
6157 listitem_T *li;
6159 for (li = l->lv_first; li != NULL; li = li->li_next)
6160 set_ref_in_item(&li->li_tv, copyID);
6164 * Mark all lists and dicts referenced through typval "tv" with "copyID".
6166 static void
6167 set_ref_in_item(tv, copyID)
6168 typval_T *tv;
6169 int copyID;
6171 dict_T *dd;
6172 list_T *ll;
6174 switch (tv->v_type)
6176 case VAR_DICT:
6177 dd = tv->vval.v_dict;
6178 if (dd->dv_copyID != copyID)
6180 /* Didn't see this dict yet. */
6181 dd->dv_copyID = copyID;
6182 set_ref_in_ht(&dd->dv_hashtab, copyID);
6184 break;
6186 case VAR_LIST:
6187 ll = tv->vval.v_list;
6188 if (ll->lv_copyID != copyID)
6190 /* Didn't see this list yet. */
6191 ll->lv_copyID = copyID;
6192 set_ref_in_list(ll, copyID);
6194 break;
6196 return;
6200 * Allocate an empty header for a dictionary.
6202 dict_T *
6203 dict_alloc()
6205 dict_T *d;
6207 d = (dict_T *)alloc(sizeof(dict_T));
6208 if (d != NULL)
6210 /* Add the list to the hashtable for garbage collection. */
6211 if (first_dict != NULL)
6212 first_dict->dv_used_prev = d;
6213 d->dv_used_next = first_dict;
6214 d->dv_used_prev = NULL;
6216 hash_init(&d->dv_hashtab);
6217 d->dv_lock = 0;
6218 d->dv_refcount = 0;
6219 d->dv_copyID = 0;
6221 return d;
6225 * Unreference a Dictionary: decrement the reference count and free it when it
6226 * becomes zero.
6228 static void
6229 dict_unref(d)
6230 dict_T *d;
6232 if (d != NULL && d->dv_refcount != DEL_REFCOUNT && --d->dv_refcount <= 0)
6233 dict_free(d);
6237 * Free a Dictionary, including all items it contains.
6238 * Ignores the reference count.
6240 static void
6241 dict_free(d)
6242 dict_T *d;
6244 int todo;
6245 hashitem_T *hi;
6246 dictitem_T *di;
6248 /* Avoid that recursive reference to the dict frees us again. */
6249 d->dv_refcount = DEL_REFCOUNT;
6251 /* Remove the dict from the list of dicts for garbage collection. */
6252 if (d->dv_used_prev == NULL)
6253 first_dict = d->dv_used_next;
6254 else
6255 d->dv_used_prev->dv_used_next = d->dv_used_next;
6256 if (d->dv_used_next != NULL)
6257 d->dv_used_next->dv_used_prev = d->dv_used_prev;
6259 /* Lock the hashtab, we don't want it to resize while freeing items. */
6260 hash_lock(&d->dv_hashtab);
6261 todo = (int)d->dv_hashtab.ht_used;
6262 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
6264 if (!HASHITEM_EMPTY(hi))
6266 /* Remove the item before deleting it, just in case there is
6267 * something recursive causing trouble. */
6268 di = HI2DI(hi);
6269 hash_remove(&d->dv_hashtab, hi);
6270 dictitem_free(di);
6271 --todo;
6274 hash_clear(&d->dv_hashtab);
6275 vim_free(d);
6279 * Allocate a Dictionary item.
6280 * The "key" is copied to the new item.
6281 * Note that the value of the item "di_tv" still needs to be initialized!
6282 * Returns NULL when out of memory.
6284 static dictitem_T *
6285 dictitem_alloc(key)
6286 char_u *key;
6288 dictitem_T *di;
6290 di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T) + STRLEN(key)));
6291 if (di != NULL)
6293 STRCPY(di->di_key, key);
6294 di->di_flags = 0;
6296 return di;
6300 * Make a copy of a Dictionary item.
6302 static dictitem_T *
6303 dictitem_copy(org)
6304 dictitem_T *org;
6306 dictitem_T *di;
6308 di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
6309 + STRLEN(org->di_key)));
6310 if (di != NULL)
6312 STRCPY(di->di_key, org->di_key);
6313 di->di_flags = 0;
6314 copy_tv(&org->di_tv, &di->di_tv);
6316 return di;
6320 * Remove item "item" from Dictionary "dict" and free it.
6322 static void
6323 dictitem_remove(dict, item)
6324 dict_T *dict;
6325 dictitem_T *item;
6327 hashitem_T *hi;
6329 hi = hash_find(&dict->dv_hashtab, item->di_key);
6330 if (HASHITEM_EMPTY(hi))
6331 EMSG2(_(e_intern2), "dictitem_remove()");
6332 else
6333 hash_remove(&dict->dv_hashtab, hi);
6334 dictitem_free(item);
6338 * Free a dict item. Also clears the value.
6340 static void
6341 dictitem_free(item)
6342 dictitem_T *item;
6344 clear_tv(&item->di_tv);
6345 vim_free(item);
6349 * Make a copy of dict "d". Shallow if "deep" is FALSE.
6350 * The refcount of the new dict is set to 1.
6351 * See item_copy() for "copyID".
6352 * Returns NULL when out of memory.
6354 static dict_T *
6355 dict_copy(orig, deep, copyID)
6356 dict_T *orig;
6357 int deep;
6358 int copyID;
6360 dict_T *copy;
6361 dictitem_T *di;
6362 int todo;
6363 hashitem_T *hi;
6365 if (orig == NULL)
6366 return NULL;
6368 copy = dict_alloc();
6369 if (copy != NULL)
6371 if (copyID != 0)
6373 orig->dv_copyID = copyID;
6374 orig->dv_copydict = copy;
6376 todo = (int)orig->dv_hashtab.ht_used;
6377 for (hi = orig->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
6379 if (!HASHITEM_EMPTY(hi))
6381 --todo;
6383 di = dictitem_alloc(hi->hi_key);
6384 if (di == NULL)
6385 break;
6386 if (deep)
6388 if (item_copy(&HI2DI(hi)->di_tv, &di->di_tv, deep,
6389 copyID) == FAIL)
6391 vim_free(di);
6392 break;
6395 else
6396 copy_tv(&HI2DI(hi)->di_tv, &di->di_tv);
6397 if (dict_add(copy, di) == FAIL)
6399 dictitem_free(di);
6400 break;
6405 ++copy->dv_refcount;
6406 if (todo > 0)
6408 dict_unref(copy);
6409 copy = NULL;
6413 return copy;
6417 * Add item "item" to Dictionary "d".
6418 * Returns FAIL when out of memory and when key already existed.
6420 static int
6421 dict_add(d, item)
6422 dict_T *d;
6423 dictitem_T *item;
6425 return hash_add(&d->dv_hashtab, item->di_key);
6429 * Add a number or string entry to dictionary "d".
6430 * When "str" is NULL use number "nr", otherwise use "str".
6431 * Returns FAIL when out of memory and when key already exists.
6434 dict_add_nr_str(d, key, nr, str)
6435 dict_T *d;
6436 char *key;
6437 long nr;
6438 char_u *str;
6440 dictitem_T *item;
6442 item = dictitem_alloc((char_u *)key);
6443 if (item == NULL)
6444 return FAIL;
6445 item->di_tv.v_lock = 0;
6446 if (str == NULL)
6448 item->di_tv.v_type = VAR_NUMBER;
6449 item->di_tv.vval.v_number = nr;
6451 else
6453 item->di_tv.v_type = VAR_STRING;
6454 item->di_tv.vval.v_string = vim_strsave(str);
6456 if (dict_add(d, item) == FAIL)
6458 dictitem_free(item);
6459 return FAIL;
6461 return OK;
6465 * Get the number of items in a Dictionary.
6467 static long
6468 dict_len(d)
6469 dict_T *d;
6471 if (d == NULL)
6472 return 0L;
6473 return (long)d->dv_hashtab.ht_used;
6477 * Find item "key[len]" in Dictionary "d".
6478 * If "len" is negative use strlen(key).
6479 * Returns NULL when not found.
6481 static dictitem_T *
6482 dict_find(d, key, len)
6483 dict_T *d;
6484 char_u *key;
6485 int len;
6487 #define AKEYLEN 200
6488 char_u buf[AKEYLEN];
6489 char_u *akey;
6490 char_u *tofree = NULL;
6491 hashitem_T *hi;
6493 if (len < 0)
6494 akey = key;
6495 else if (len >= AKEYLEN)
6497 tofree = akey = vim_strnsave(key, len);
6498 if (akey == NULL)
6499 return NULL;
6501 else
6503 /* Avoid a malloc/free by using buf[]. */
6504 vim_strncpy(buf, key, len);
6505 akey = buf;
6508 hi = hash_find(&d->dv_hashtab, akey);
6509 vim_free(tofree);
6510 if (HASHITEM_EMPTY(hi))
6511 return NULL;
6512 return HI2DI(hi);
6516 * Get a string item from a dictionary.
6517 * When "save" is TRUE allocate memory for it.
6518 * Returns NULL if the entry doesn't exist or out of memory.
6520 char_u *
6521 get_dict_string(d, key, save)
6522 dict_T *d;
6523 char_u *key;
6524 int save;
6526 dictitem_T *di;
6527 char_u *s;
6529 di = dict_find(d, key, -1);
6530 if (di == NULL)
6531 return NULL;
6532 s = get_tv_string(&di->di_tv);
6533 if (save && s != NULL)
6534 s = vim_strsave(s);
6535 return s;
6539 * Get a number item from a dictionary.
6540 * Returns 0 if the entry doesn't exist or out of memory.
6542 long
6543 get_dict_number(d, key)
6544 dict_T *d;
6545 char_u *key;
6547 dictitem_T *di;
6549 di = dict_find(d, key, -1);
6550 if (di == NULL)
6551 return 0;
6552 return get_tv_number(&di->di_tv);
6556 * Return an allocated string with the string representation of a Dictionary.
6557 * May return NULL.
6559 static char_u *
6560 dict2string(tv, copyID)
6561 typval_T *tv;
6562 int copyID;
6564 garray_T ga;
6565 int first = TRUE;
6566 char_u *tofree;
6567 char_u numbuf[NUMBUFLEN];
6568 hashitem_T *hi;
6569 char_u *s;
6570 dict_T *d;
6571 int todo;
6573 if ((d = tv->vval.v_dict) == NULL)
6574 return NULL;
6575 ga_init2(&ga, (int)sizeof(char), 80);
6576 ga_append(&ga, '{');
6578 todo = (int)d->dv_hashtab.ht_used;
6579 for (hi = d->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
6581 if (!HASHITEM_EMPTY(hi))
6583 --todo;
6585 if (first)
6586 first = FALSE;
6587 else
6588 ga_concat(&ga, (char_u *)", ");
6590 tofree = string_quote(hi->hi_key, FALSE);
6591 if (tofree != NULL)
6593 ga_concat(&ga, tofree);
6594 vim_free(tofree);
6596 ga_concat(&ga, (char_u *)": ");
6597 s = tv2string(&HI2DI(hi)->di_tv, &tofree, numbuf, copyID);
6598 if (s != NULL)
6599 ga_concat(&ga, s);
6600 vim_free(tofree);
6601 if (s == NULL)
6602 break;
6605 if (todo > 0)
6607 vim_free(ga.ga_data);
6608 return NULL;
6611 ga_append(&ga, '}');
6612 ga_append(&ga, NUL);
6613 return (char_u *)ga.ga_data;
6617 * Allocate a variable for a Dictionary and fill it from "*arg".
6618 * Return OK or FAIL. Returns NOTDONE for {expr}.
6620 static int
6621 get_dict_tv(arg, rettv, evaluate)
6622 char_u **arg;
6623 typval_T *rettv;
6624 int evaluate;
6626 dict_T *d = NULL;
6627 typval_T tvkey;
6628 typval_T tv;
6629 char_u *key;
6630 dictitem_T *item;
6631 char_u *start = skipwhite(*arg + 1);
6632 char_u buf[NUMBUFLEN];
6635 * First check if it's not a curly-braces thing: {expr}.
6636 * Must do this without evaluating, otherwise a function may be called
6637 * twice. Unfortunately this means we need to call eval1() twice for the
6638 * first item.
6639 * But {} is an empty Dictionary.
6641 if (*start != '}')
6643 if (eval1(&start, &tv, FALSE) == FAIL) /* recursive! */
6644 return FAIL;
6645 if (*start == '}')
6646 return NOTDONE;
6649 if (evaluate)
6651 d = dict_alloc();
6652 if (d == NULL)
6653 return FAIL;
6655 tvkey.v_type = VAR_UNKNOWN;
6656 tv.v_type = VAR_UNKNOWN;
6658 *arg = skipwhite(*arg + 1);
6659 while (**arg != '}' && **arg != NUL)
6661 if (eval1(arg, &tvkey, evaluate) == FAIL) /* recursive! */
6662 goto failret;
6663 if (**arg != ':')
6665 EMSG2(_("E720: Missing colon in Dictionary: %s"), *arg);
6666 clear_tv(&tvkey);
6667 goto failret;
6669 key = get_tv_string_buf_chk(&tvkey, buf);
6670 if (key == NULL || *key == NUL)
6672 /* "key" is NULL when get_tv_string_buf_chk() gave an errmsg */
6673 if (key != NULL)
6674 EMSG(_(e_emptykey));
6675 clear_tv(&tvkey);
6676 goto failret;
6679 *arg = skipwhite(*arg + 1);
6680 if (eval1(arg, &tv, evaluate) == FAIL) /* recursive! */
6682 clear_tv(&tvkey);
6683 goto failret;
6685 if (evaluate)
6687 item = dict_find(d, key, -1);
6688 if (item != NULL)
6690 EMSG2(_("E721: Duplicate key in Dictionary: \"%s\""), key);
6691 clear_tv(&tvkey);
6692 clear_tv(&tv);
6693 goto failret;
6695 item = dictitem_alloc(key);
6696 clear_tv(&tvkey);
6697 if (item != NULL)
6699 item->di_tv = tv;
6700 item->di_tv.v_lock = 0;
6701 if (dict_add(d, item) == FAIL)
6702 dictitem_free(item);
6706 if (**arg == '}')
6707 break;
6708 if (**arg != ',')
6710 EMSG2(_("E722: Missing comma in Dictionary: %s"), *arg);
6711 goto failret;
6713 *arg = skipwhite(*arg + 1);
6716 if (**arg != '}')
6718 EMSG2(_("E723: Missing end of Dictionary '}': %s"), *arg);
6719 failret:
6720 if (evaluate)
6721 dict_free(d);
6722 return FAIL;
6725 *arg = skipwhite(*arg + 1);
6726 if (evaluate)
6728 rettv->v_type = VAR_DICT;
6729 rettv->vval.v_dict = d;
6730 ++d->dv_refcount;
6733 return OK;
6737 * Return a string with the string representation of a variable.
6738 * If the memory is allocated "tofree" is set to it, otherwise NULL.
6739 * "numbuf" is used for a number.
6740 * Does not put quotes around strings, as ":echo" displays values.
6741 * When "copyID" is not NULL replace recursive lists and dicts with "...".
6742 * May return NULL;
6744 static char_u *
6745 echo_string(tv, tofree, numbuf, copyID)
6746 typval_T *tv;
6747 char_u **tofree;
6748 char_u *numbuf;
6749 int copyID;
6751 static int recurse = 0;
6752 char_u *r = NULL;
6754 if (recurse >= DICT_MAXNEST)
6756 EMSG(_("E724: variable nested too deep for displaying"));
6757 *tofree = NULL;
6758 return NULL;
6760 ++recurse;
6762 switch (tv->v_type)
6764 case VAR_FUNC:
6765 *tofree = NULL;
6766 r = tv->vval.v_string;
6767 break;
6769 case VAR_LIST:
6770 if (tv->vval.v_list == NULL)
6772 *tofree = NULL;
6773 r = NULL;
6775 else if (copyID != 0 && tv->vval.v_list->lv_copyID == copyID)
6777 *tofree = NULL;
6778 r = (char_u *)"[...]";
6780 else
6782 tv->vval.v_list->lv_copyID = copyID;
6783 *tofree = list2string(tv, copyID);
6784 r = *tofree;
6786 break;
6788 case VAR_DICT:
6789 if (tv->vval.v_dict == NULL)
6791 *tofree = NULL;
6792 r = NULL;
6794 else if (copyID != 0 && tv->vval.v_dict->dv_copyID == copyID)
6796 *tofree = NULL;
6797 r = (char_u *)"{...}";
6799 else
6801 tv->vval.v_dict->dv_copyID = copyID;
6802 *tofree = dict2string(tv, copyID);
6803 r = *tofree;
6805 break;
6807 case VAR_STRING:
6808 case VAR_NUMBER:
6809 *tofree = NULL;
6810 r = get_tv_string_buf(tv, numbuf);
6811 break;
6813 default:
6814 EMSG2(_(e_intern2), "echo_string()");
6815 *tofree = NULL;
6818 --recurse;
6819 return r;
6823 * Return a string with the string representation of a variable.
6824 * If the memory is allocated "tofree" is set to it, otherwise NULL.
6825 * "numbuf" is used for a number.
6826 * Puts quotes around strings, so that they can be parsed back by eval().
6827 * May return NULL;
6829 static char_u *
6830 tv2string(tv, tofree, numbuf, copyID)
6831 typval_T *tv;
6832 char_u **tofree;
6833 char_u *numbuf;
6834 int copyID;
6836 switch (tv->v_type)
6838 case VAR_FUNC:
6839 *tofree = string_quote(tv->vval.v_string, TRUE);
6840 return *tofree;
6841 case VAR_STRING:
6842 *tofree = string_quote(tv->vval.v_string, FALSE);
6843 return *tofree;
6844 case VAR_NUMBER:
6845 case VAR_LIST:
6846 case VAR_DICT:
6847 break;
6848 default:
6849 EMSG2(_(e_intern2), "tv2string()");
6851 return echo_string(tv, tofree, numbuf, copyID);
6855 * Return string "str" in ' quotes, doubling ' characters.
6856 * If "str" is NULL an empty string is assumed.
6857 * If "function" is TRUE make it function('string').
6859 static char_u *
6860 string_quote(str, function)
6861 char_u *str;
6862 int function;
6864 unsigned len;
6865 char_u *p, *r, *s;
6867 len = (function ? 13 : 3);
6868 if (str != NULL)
6870 len += (unsigned)STRLEN(str);
6871 for (p = str; *p != NUL; mb_ptr_adv(p))
6872 if (*p == '\'')
6873 ++len;
6875 s = r = alloc(len);
6876 if (r != NULL)
6878 if (function)
6880 STRCPY(r, "function('");
6881 r += 10;
6883 else
6884 *r++ = '\'';
6885 if (str != NULL)
6886 for (p = str; *p != NUL; )
6888 if (*p == '\'')
6889 *r++ = '\'';
6890 MB_COPY_CHAR(p, r);
6892 *r++ = '\'';
6893 if (function)
6894 *r++ = ')';
6895 *r++ = NUL;
6897 return s;
6901 * Get the value of an environment variable.
6902 * "arg" is pointing to the '$'. It is advanced to after the name.
6903 * If the environment variable was not set, silently assume it is empty.
6904 * Always return OK.
6906 static int
6907 get_env_tv(arg, rettv, evaluate)
6908 char_u **arg;
6909 typval_T *rettv;
6910 int evaluate;
6912 char_u *string = NULL;
6913 int len;
6914 int cc;
6915 char_u *name;
6916 int mustfree = FALSE;
6918 ++*arg;
6919 name = *arg;
6920 len = get_env_len(arg);
6921 if (evaluate)
6923 if (len != 0)
6925 cc = name[len];
6926 name[len] = NUL;
6927 /* first try vim_getenv(), fast for normal environment vars */
6928 string = vim_getenv(name, &mustfree);
6929 if (string != NULL && *string != NUL)
6931 if (!mustfree)
6932 string = vim_strsave(string);
6934 else
6936 if (mustfree)
6937 vim_free(string);
6939 /* next try expanding things like $VIM and ${HOME} */
6940 string = expand_env_save(name - 1);
6941 if (string != NULL && *string == '$')
6943 vim_free(string);
6944 string = NULL;
6947 name[len] = cc;
6949 rettv->v_type = VAR_STRING;
6950 rettv->vval.v_string = string;
6953 return OK;
6957 * Array with names and number of arguments of all internal functions
6958 * MUST BE KEPT SORTED IN strcmp() ORDER FOR BINARY SEARCH!
6960 static struct fst
6962 char *f_name; /* function name */
6963 char f_min_argc; /* minimal number of arguments */
6964 char f_max_argc; /* maximal number of arguments */
6965 void (*f_func) __ARGS((typval_T *args, typval_T *rvar));
6966 /* implemenation of function */
6967 } functions[] =
6969 {"add", 2, 2, f_add},
6970 {"append", 2, 2, f_append},
6971 {"argc", 0, 0, f_argc},
6972 {"argidx", 0, 0, f_argidx},
6973 {"argv", 0, 1, f_argv},
6974 {"browse", 4, 4, f_browse},
6975 {"browsedir", 2, 2, f_browsedir},
6976 {"bufexists", 1, 1, f_bufexists},
6977 {"buffer_exists", 1, 1, f_bufexists}, /* obsolete */
6978 {"buffer_name", 1, 1, f_bufname}, /* obsolete */
6979 {"buffer_number", 1, 1, f_bufnr}, /* obsolete */
6980 {"buflisted", 1, 1, f_buflisted},
6981 {"bufloaded", 1, 1, f_bufloaded},
6982 {"bufname", 1, 1, f_bufname},
6983 {"bufnr", 1, 2, f_bufnr},
6984 {"bufwinnr", 1, 1, f_bufwinnr},
6985 {"byte2line", 1, 1, f_byte2line},
6986 {"byteidx", 2, 2, f_byteidx},
6987 {"call", 2, 3, f_call},
6988 {"changenr", 0, 0, f_changenr},
6989 {"char2nr", 1, 1, f_char2nr},
6990 {"cindent", 1, 1, f_cindent},
6991 {"col", 1, 1, f_col},
6992 #if defined(FEAT_INS_EXPAND)
6993 {"complete", 2, 2, f_complete},
6994 {"complete_add", 1, 1, f_complete_add},
6995 {"complete_check", 0, 0, f_complete_check},
6996 #endif
6997 {"confirm", 1, 4, f_confirm},
6998 {"copy", 1, 1, f_copy},
6999 {"count", 2, 4, f_count},
7000 {"cscope_connection",0,3, f_cscope_connection},
7001 {"cursor", 1, 3, f_cursor},
7002 {"deepcopy", 1, 2, f_deepcopy},
7003 {"delete", 1, 1, f_delete},
7004 {"did_filetype", 0, 0, f_did_filetype},
7005 {"diff_filler", 1, 1, f_diff_filler},
7006 {"diff_hlID", 2, 2, f_diff_hlID},
7007 {"empty", 1, 1, f_empty},
7008 {"escape", 2, 2, f_escape},
7009 {"eval", 1, 1, f_eval},
7010 {"eventhandler", 0, 0, f_eventhandler},
7011 {"executable", 1, 1, f_executable},
7012 {"exists", 1, 1, f_exists},
7013 {"expand", 1, 2, f_expand},
7014 {"extend", 2, 3, f_extend},
7015 {"feedkeys", 1, 2, f_feedkeys},
7016 {"file_readable", 1, 1, f_filereadable}, /* obsolete */
7017 {"filereadable", 1, 1, f_filereadable},
7018 {"filewritable", 1, 1, f_filewritable},
7019 {"filter", 2, 2, f_filter},
7020 {"finddir", 1, 3, f_finddir},
7021 {"findfile", 1, 3, f_findfile},
7022 {"fnamemodify", 2, 2, f_fnamemodify},
7023 {"foldclosed", 1, 1, f_foldclosed},
7024 {"foldclosedend", 1, 1, f_foldclosedend},
7025 {"foldlevel", 1, 1, f_foldlevel},
7026 {"foldtext", 0, 0, f_foldtext},
7027 {"foldtextresult", 1, 1, f_foldtextresult},
7028 {"foreground", 0, 0, f_foreground},
7029 {"function", 1, 1, f_function},
7030 {"garbagecollect", 0, 0, f_garbagecollect},
7031 {"get", 2, 3, f_get},
7032 {"getbufline", 2, 3, f_getbufline},
7033 {"getbufvar", 2, 2, f_getbufvar},
7034 {"getchar", 0, 1, f_getchar},
7035 {"getcharmod", 0, 0, f_getcharmod},
7036 {"getcmdline", 0, 0, f_getcmdline},
7037 {"getcmdpos", 0, 0, f_getcmdpos},
7038 {"getcmdtype", 0, 0, f_getcmdtype},
7039 {"getcwd", 0, 0, f_getcwd},
7040 {"getfontname", 0, 1, f_getfontname},
7041 {"getfperm", 1, 1, f_getfperm},
7042 {"getfsize", 1, 1, f_getfsize},
7043 {"getftime", 1, 1, f_getftime},
7044 {"getftype", 1, 1, f_getftype},
7045 {"getline", 1, 2, f_getline},
7046 {"getloclist", 1, 1, f_getqflist},
7047 {"getpos", 1, 1, f_getpos},
7048 {"getqflist", 0, 0, f_getqflist},
7049 {"getreg", 0, 2, f_getreg},
7050 {"getregtype", 0, 1, f_getregtype},
7051 {"gettabwinvar", 3, 3, f_gettabwinvar},
7052 {"getwinposx", 0, 0, f_getwinposx},
7053 {"getwinposy", 0, 0, f_getwinposy},
7054 {"getwinvar", 2, 2, f_getwinvar},
7055 {"glob", 1, 1, f_glob},
7056 {"globpath", 2, 2, f_globpath},
7057 {"has", 1, 1, f_has},
7058 {"has_key", 2, 2, f_has_key},
7059 {"hasmapto", 1, 3, f_hasmapto},
7060 {"highlightID", 1, 1, f_hlID}, /* obsolete */
7061 {"highlight_exists",1, 1, f_hlexists}, /* obsolete */
7062 {"histadd", 2, 2, f_histadd},
7063 {"histdel", 1, 2, f_histdel},
7064 {"histget", 1, 2, f_histget},
7065 {"histnr", 1, 1, f_histnr},
7066 {"hlID", 1, 1, f_hlID},
7067 {"hlexists", 1, 1, f_hlexists},
7068 {"hostname", 0, 0, f_hostname},
7069 {"iconv", 3, 3, f_iconv},
7070 {"indent", 1, 1, f_indent},
7071 {"index", 2, 4, f_index},
7072 {"input", 1, 3, f_input},
7073 {"inputdialog", 1, 3, f_inputdialog},
7074 {"inputlist", 1, 1, f_inputlist},
7075 {"inputrestore", 0, 0, f_inputrestore},
7076 {"inputsave", 0, 0, f_inputsave},
7077 {"inputsecret", 1, 2, f_inputsecret},
7078 {"insert", 2, 3, f_insert},
7079 {"isdirectory", 1, 1, f_isdirectory},
7080 {"islocked", 1, 1, f_islocked},
7081 {"items", 1, 1, f_items},
7082 {"join", 1, 2, f_join},
7083 {"keys", 1, 1, f_keys},
7084 {"last_buffer_nr", 0, 0, f_last_buffer_nr},/* obsolete */
7085 {"len", 1, 1, f_len},
7086 {"libcall", 3, 3, f_libcall},
7087 {"libcallnr", 3, 3, f_libcallnr},
7088 {"line", 1, 1, f_line},
7089 {"line2byte", 1, 1, f_line2byte},
7090 {"lispindent", 1, 1, f_lispindent},
7091 {"localtime", 0, 0, f_localtime},
7092 {"map", 2, 2, f_map},
7093 {"maparg", 1, 3, f_maparg},
7094 {"mapcheck", 1, 3, f_mapcheck},
7095 {"match", 2, 4, f_match},
7096 {"matcharg", 1, 1, f_matcharg},
7097 {"matchend", 2, 4, f_matchend},
7098 {"matchlist", 2, 4, f_matchlist},
7099 {"matchstr", 2, 4, f_matchstr},
7100 {"max", 1, 1, f_max},
7101 {"min", 1, 1, f_min},
7102 #ifdef vim_mkdir
7103 {"mkdir", 1, 3, f_mkdir},
7104 #endif
7105 {"mode", 0, 0, f_mode},
7106 {"nextnonblank", 1, 1, f_nextnonblank},
7107 {"nr2char", 1, 1, f_nr2char},
7108 {"pathshorten", 1, 1, f_pathshorten},
7109 {"prevnonblank", 1, 1, f_prevnonblank},
7110 {"printf", 2, 19, f_printf},
7111 {"pumvisible", 0, 0, f_pumvisible},
7112 {"range", 1, 3, f_range},
7113 {"readfile", 1, 3, f_readfile},
7114 {"reltime", 0, 2, f_reltime},
7115 {"reltimestr", 1, 1, f_reltimestr},
7116 {"remote_expr", 2, 3, f_remote_expr},
7117 {"remote_foreground", 1, 1, f_remote_foreground},
7118 {"remote_peek", 1, 2, f_remote_peek},
7119 {"remote_read", 1, 1, f_remote_read},
7120 {"remote_send", 2, 3, f_remote_send},
7121 {"remove", 2, 3, f_remove},
7122 {"rename", 2, 2, f_rename},
7123 {"repeat", 2, 2, f_repeat},
7124 {"resolve", 1, 1, f_resolve},
7125 {"reverse", 1, 1, f_reverse},
7126 {"search", 1, 3, f_search},
7127 {"searchdecl", 1, 3, f_searchdecl},
7128 {"searchpair", 3, 6, f_searchpair},
7129 {"searchpairpos", 3, 6, f_searchpairpos},
7130 {"searchpos", 1, 3, f_searchpos},
7131 {"server2client", 2, 2, f_server2client},
7132 {"serverlist", 0, 0, f_serverlist},
7133 {"setbufvar", 3, 3, f_setbufvar},
7134 {"setcmdpos", 1, 1, f_setcmdpos},
7135 {"setline", 2, 2, f_setline},
7136 {"setloclist", 2, 3, f_setloclist},
7137 {"setpos", 2, 2, f_setpos},
7138 {"setqflist", 1, 2, f_setqflist},
7139 {"setreg", 2, 3, f_setreg},
7140 {"settabwinvar", 4, 4, f_settabwinvar},
7141 {"setwinvar", 3, 3, f_setwinvar},
7142 {"simplify", 1, 1, f_simplify},
7143 {"sort", 1, 2, f_sort},
7144 {"soundfold", 1, 1, f_soundfold},
7145 {"spellbadword", 0, 1, f_spellbadword},
7146 {"spellsuggest", 1, 3, f_spellsuggest},
7147 {"split", 1, 3, f_split},
7148 {"str2nr", 1, 2, f_str2nr},
7149 #ifdef HAVE_STRFTIME
7150 {"strftime", 1, 2, f_strftime},
7151 #endif
7152 {"stridx", 2, 3, f_stridx},
7153 {"string", 1, 1, f_string},
7154 {"strlen", 1, 1, f_strlen},
7155 {"strpart", 2, 3, f_strpart},
7156 {"strridx", 2, 3, f_strridx},
7157 {"strtrans", 1, 1, f_strtrans},
7158 {"submatch", 1, 1, f_submatch},
7159 {"substitute", 4, 4, f_substitute},
7160 {"synID", 3, 3, f_synID},
7161 {"synIDattr", 2, 3, f_synIDattr},
7162 {"synIDtrans", 1, 1, f_synIDtrans},
7163 {"system", 1, 2, f_system},
7164 {"tabpagebuflist", 0, 1, f_tabpagebuflist},
7165 {"tabpagenr", 0, 1, f_tabpagenr},
7166 {"tabpagewinnr", 1, 2, f_tabpagewinnr},
7167 {"tagfiles", 0, 0, f_tagfiles},
7168 {"taglist", 1, 1, f_taglist},
7169 {"tempname", 0, 0, f_tempname},
7170 {"test", 1, 1, f_test},
7171 {"tolower", 1, 1, f_tolower},
7172 {"toupper", 1, 1, f_toupper},
7173 {"tr", 3, 3, f_tr},
7174 {"type", 1, 1, f_type},
7175 {"values", 1, 1, f_values},
7176 {"virtcol", 1, 1, f_virtcol},
7177 {"visualmode", 0, 1, f_visualmode},
7178 {"winbufnr", 1, 1, f_winbufnr},
7179 {"wincol", 0, 0, f_wincol},
7180 {"winheight", 1, 1, f_winheight},
7181 {"winline", 0, 0, f_winline},
7182 {"winnr", 0, 1, f_winnr},
7183 {"winrestcmd", 0, 0, f_winrestcmd},
7184 {"winrestview", 1, 1, f_winrestview},
7185 {"winsaveview", 0, 0, f_winsaveview},
7186 {"winwidth", 1, 1, f_winwidth},
7187 {"writefile", 2, 3, f_writefile},
7190 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
7193 * Function given to ExpandGeneric() to obtain the list of internal
7194 * or user defined function names.
7196 char_u *
7197 get_function_name(xp, idx)
7198 expand_T *xp;
7199 int idx;
7201 static int intidx = -1;
7202 char_u *name;
7204 if (idx == 0)
7205 intidx = -1;
7206 if (intidx < 0)
7208 name = get_user_func_name(xp, idx);
7209 if (name != NULL)
7210 return name;
7212 if (++intidx < (int)(sizeof(functions) / sizeof(struct fst)))
7214 STRCPY(IObuff, functions[intidx].f_name);
7215 STRCAT(IObuff, "(");
7216 if (functions[intidx].f_max_argc == 0)
7217 STRCAT(IObuff, ")");
7218 return IObuff;
7221 return NULL;
7225 * Function given to ExpandGeneric() to obtain the list of internal or
7226 * user defined variable or function names.
7228 /*ARGSUSED*/
7229 char_u *
7230 get_expr_name(xp, idx)
7231 expand_T *xp;
7232 int idx;
7234 static int intidx = -1;
7235 char_u *name;
7237 if (idx == 0)
7238 intidx = -1;
7239 if (intidx < 0)
7241 name = get_function_name(xp, idx);
7242 if (name != NULL)
7243 return name;
7245 return get_user_var_name(xp, ++intidx);
7248 #endif /* FEAT_CMDL_COMPL */
7251 * Find internal function in table above.
7252 * Return index, or -1 if not found
7254 static int
7255 find_internal_func(name)
7256 char_u *name; /* name of the function */
7258 int first = 0;
7259 int last = (int)(sizeof(functions) / sizeof(struct fst)) - 1;
7260 int cmp;
7261 int x;
7264 * Find the function name in the table. Binary search.
7266 while (first <= last)
7268 x = first + ((unsigned)(last - first) >> 1);
7269 cmp = STRCMP(name, functions[x].f_name);
7270 if (cmp < 0)
7271 last = x - 1;
7272 else if (cmp > 0)
7273 first = x + 1;
7274 else
7275 return x;
7277 return -1;
7281 * Check if "name" is a variable of type VAR_FUNC. If so, return the function
7282 * name it contains, otherwise return "name".
7284 static char_u *
7285 deref_func_name(name, lenp)
7286 char_u *name;
7287 int *lenp;
7289 dictitem_T *v;
7290 int cc;
7292 cc = name[*lenp];
7293 name[*lenp] = NUL;
7294 v = find_var(name, NULL);
7295 name[*lenp] = cc;
7296 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
7298 if (v->di_tv.vval.v_string == NULL)
7300 *lenp = 0;
7301 return (char_u *)""; /* just in case */
7303 *lenp = (int)STRLEN(v->di_tv.vval.v_string);
7304 return v->di_tv.vval.v_string;
7307 return name;
7311 * Allocate a variable for the result of a function.
7312 * Return OK or FAIL.
7314 static int
7315 get_func_tv(name, len, rettv, arg, firstline, lastline, doesrange,
7316 evaluate, selfdict)
7317 char_u *name; /* name of the function */
7318 int len; /* length of "name" */
7319 typval_T *rettv;
7320 char_u **arg; /* argument, pointing to the '(' */
7321 linenr_T firstline; /* first line of range */
7322 linenr_T lastline; /* last line of range */
7323 int *doesrange; /* return: function handled range */
7324 int evaluate;
7325 dict_T *selfdict; /* Dictionary for "self" */
7327 char_u *argp;
7328 int ret = OK;
7329 typval_T argvars[MAX_FUNC_ARGS + 1]; /* vars for arguments */
7330 int argcount = 0; /* number of arguments found */
7333 * Get the arguments.
7335 argp = *arg;
7336 while (argcount < MAX_FUNC_ARGS)
7338 argp = skipwhite(argp + 1); /* skip the '(' or ',' */
7339 if (*argp == ')' || *argp == ',' || *argp == NUL)
7340 break;
7341 if (eval1(&argp, &argvars[argcount], evaluate) == FAIL)
7343 ret = FAIL;
7344 break;
7346 ++argcount;
7347 if (*argp != ',')
7348 break;
7350 if (*argp == ')')
7351 ++argp;
7352 else
7353 ret = FAIL;
7355 if (ret == OK)
7356 ret = call_func(name, len, rettv, argcount, argvars,
7357 firstline, lastline, doesrange, evaluate, selfdict);
7358 else if (!aborting())
7360 if (argcount == MAX_FUNC_ARGS)
7361 emsg_funcname("E740: Too many arguments for function %s", name);
7362 else
7363 emsg_funcname("E116: Invalid arguments for function %s", name);
7366 while (--argcount >= 0)
7367 clear_tv(&argvars[argcount]);
7369 *arg = skipwhite(argp);
7370 return ret;
7375 * Call a function with its resolved parameters
7376 * Return OK when the function can't be called, FAIL otherwise.
7377 * Also returns OK when an error was encountered while executing the function.
7379 static int
7380 call_func(name, len, rettv, argcount, argvars, firstline, lastline,
7381 doesrange, evaluate, selfdict)
7382 char_u *name; /* name of the function */
7383 int len; /* length of "name" */
7384 typval_T *rettv; /* return value goes here */
7385 int argcount; /* number of "argvars" */
7386 typval_T *argvars; /* vars for arguments, must have "argcount"
7387 PLUS ONE elements! */
7388 linenr_T firstline; /* first line of range */
7389 linenr_T lastline; /* last line of range */
7390 int *doesrange; /* return: function handled range */
7391 int evaluate;
7392 dict_T *selfdict; /* Dictionary for "self" */
7394 int ret = FAIL;
7395 #define ERROR_UNKNOWN 0
7396 #define ERROR_TOOMANY 1
7397 #define ERROR_TOOFEW 2
7398 #define ERROR_SCRIPT 3
7399 #define ERROR_DICT 4
7400 #define ERROR_NONE 5
7401 #define ERROR_OTHER 6
7402 int error = ERROR_NONE;
7403 int i;
7404 int llen;
7405 ufunc_T *fp;
7406 int cc;
7407 #define FLEN_FIXED 40
7408 char_u fname_buf[FLEN_FIXED + 1];
7409 char_u *fname;
7412 * In a script change <SID>name() and s:name() to K_SNR 123_name().
7413 * Change <SNR>123_name() to K_SNR 123_name().
7414 * Use fname_buf[] when it fits, otherwise allocate memory (slow).
7416 cc = name[len];
7417 name[len] = NUL;
7418 llen = eval_fname_script(name);
7419 if (llen > 0)
7421 fname_buf[0] = K_SPECIAL;
7422 fname_buf[1] = KS_EXTRA;
7423 fname_buf[2] = (int)KE_SNR;
7424 i = 3;
7425 if (eval_fname_sid(name)) /* "<SID>" or "s:" */
7427 if (current_SID <= 0)
7428 error = ERROR_SCRIPT;
7429 else
7431 sprintf((char *)fname_buf + 3, "%ld_", (long)current_SID);
7432 i = (int)STRLEN(fname_buf);
7435 if (i + STRLEN(name + llen) < FLEN_FIXED)
7437 STRCPY(fname_buf + i, name + llen);
7438 fname = fname_buf;
7440 else
7442 fname = alloc((unsigned)(i + STRLEN(name + llen) + 1));
7443 if (fname == NULL)
7444 error = ERROR_OTHER;
7445 else
7447 mch_memmove(fname, fname_buf, (size_t)i);
7448 STRCPY(fname + i, name + llen);
7452 else
7453 fname = name;
7455 *doesrange = FALSE;
7458 /* execute the function if no errors detected and executing */
7459 if (evaluate && error == ERROR_NONE)
7461 rettv->v_type = VAR_NUMBER; /* default is number rettv */
7462 error = ERROR_UNKNOWN;
7464 if (!builtin_function(fname))
7467 * User defined function.
7469 fp = find_func(fname);
7471 #ifdef FEAT_AUTOCMD
7472 /* Trigger FuncUndefined event, may load the function. */
7473 if (fp == NULL
7474 && apply_autocmds(EVENT_FUNCUNDEFINED,
7475 fname, fname, TRUE, NULL)
7476 && !aborting())
7478 /* executed an autocommand, search for the function again */
7479 fp = find_func(fname);
7481 #endif
7482 /* Try loading a package. */
7483 if (fp == NULL && script_autoload(fname, TRUE) && !aborting())
7485 /* loaded a package, search for the function again */
7486 fp = find_func(fname);
7489 if (fp != NULL)
7491 if (fp->uf_flags & FC_RANGE)
7492 *doesrange = TRUE;
7493 if (argcount < fp->uf_args.ga_len)
7494 error = ERROR_TOOFEW;
7495 else if (!fp->uf_varargs && argcount > fp->uf_args.ga_len)
7496 error = ERROR_TOOMANY;
7497 else if ((fp->uf_flags & FC_DICT) && selfdict == NULL)
7498 error = ERROR_DICT;
7499 else
7502 * Call the user function.
7503 * Save and restore search patterns, script variables and
7504 * redo buffer.
7506 save_search_patterns();
7507 saveRedobuff();
7508 ++fp->uf_calls;
7509 call_user_func(fp, argcount, argvars, rettv,
7510 firstline, lastline,
7511 (fp->uf_flags & FC_DICT) ? selfdict : NULL);
7512 if (--fp->uf_calls <= 0 && isdigit(*fp->uf_name)
7513 && fp->uf_refcount <= 0)
7514 /* Function was unreferenced while being used, free it
7515 * now. */
7516 func_free(fp);
7517 restoreRedobuff();
7518 restore_search_patterns();
7519 error = ERROR_NONE;
7523 else
7526 * Find the function name in the table, call its implementation.
7528 i = find_internal_func(fname);
7529 if (i >= 0)
7531 if (argcount < functions[i].f_min_argc)
7532 error = ERROR_TOOFEW;
7533 else if (argcount > functions[i].f_max_argc)
7534 error = ERROR_TOOMANY;
7535 else
7537 argvars[argcount].v_type = VAR_UNKNOWN;
7538 functions[i].f_func(argvars, rettv);
7539 error = ERROR_NONE;
7544 * The function call (or "FuncUndefined" autocommand sequence) might
7545 * have been aborted by an error, an interrupt, or an explicitly thrown
7546 * exception that has not been caught so far. This situation can be
7547 * tested for by calling aborting(). For an error in an internal
7548 * function or for the "E132" error in call_user_func(), however, the
7549 * throw point at which the "force_abort" flag (temporarily reset by
7550 * emsg()) is normally updated has not been reached yet. We need to
7551 * update that flag first to make aborting() reliable.
7553 update_force_abort();
7555 if (error == ERROR_NONE)
7556 ret = OK;
7559 * Report an error unless the argument evaluation or function call has been
7560 * cancelled due to an aborting error, an interrupt, or an exception.
7562 if (!aborting())
7564 switch (error)
7566 case ERROR_UNKNOWN:
7567 emsg_funcname(N_("E117: Unknown function: %s"), name);
7568 break;
7569 case ERROR_TOOMANY:
7570 emsg_funcname(e_toomanyarg, name);
7571 break;
7572 case ERROR_TOOFEW:
7573 emsg_funcname(N_("E119: Not enough arguments for function: %s"),
7574 name);
7575 break;
7576 case ERROR_SCRIPT:
7577 emsg_funcname(N_("E120: Using <SID> not in a script context: %s"),
7578 name);
7579 break;
7580 case ERROR_DICT:
7581 emsg_funcname(N_("E725: Calling dict function without Dictionary: %s"),
7582 name);
7583 break;
7587 name[len] = cc;
7588 if (fname != name && fname != fname_buf)
7589 vim_free(fname);
7591 return ret;
7595 * Give an error message with a function name. Handle <SNR> things.
7597 static void
7598 emsg_funcname(ermsg, name)
7599 char *ermsg;
7600 char_u *name;
7602 char_u *p;
7604 if (*name == K_SPECIAL)
7605 p = concat_str((char_u *)"<SNR>", name + 3);
7606 else
7607 p = name;
7608 EMSG2(_(ermsg), p);
7609 if (p != name)
7610 vim_free(p);
7613 /*********************************************
7614 * Implementation of the built-in functions
7618 * "add(list, item)" function
7620 static void
7621 f_add(argvars, rettv)
7622 typval_T *argvars;
7623 typval_T *rettv;
7625 list_T *l;
7627 rettv->vval.v_number = 1; /* Default: Failed */
7628 if (argvars[0].v_type == VAR_LIST)
7630 if ((l = argvars[0].vval.v_list) != NULL
7631 && !tv_check_lock(l->lv_lock, (char_u *)"add()")
7632 && list_append_tv(l, &argvars[1]) == OK)
7633 copy_tv(&argvars[0], rettv);
7635 else
7636 EMSG(_(e_listreq));
7640 * "append(lnum, string/list)" function
7642 static void
7643 f_append(argvars, rettv)
7644 typval_T *argvars;
7645 typval_T *rettv;
7647 long lnum;
7648 char_u *line;
7649 list_T *l = NULL;
7650 listitem_T *li = NULL;
7651 typval_T *tv;
7652 long added = 0;
7654 lnum = get_tv_lnum(argvars);
7655 if (lnum >= 0
7656 && lnum <= curbuf->b_ml.ml_line_count
7657 && u_save(lnum, lnum + 1) == OK)
7659 if (argvars[1].v_type == VAR_LIST)
7661 l = argvars[1].vval.v_list;
7662 if (l == NULL)
7663 return;
7664 li = l->lv_first;
7666 rettv->vval.v_number = 0; /* Default: Success */
7667 for (;;)
7669 if (l == NULL)
7670 tv = &argvars[1]; /* append a string */
7671 else if (li == NULL)
7672 break; /* end of list */
7673 else
7674 tv = &li->li_tv; /* append item from list */
7675 line = get_tv_string_chk(tv);
7676 if (line == NULL) /* type error */
7678 rettv->vval.v_number = 1; /* Failed */
7679 break;
7681 ml_append(lnum + added, line, (colnr_T)0, FALSE);
7682 ++added;
7683 if (l == NULL)
7684 break;
7685 li = li->li_next;
7688 appended_lines_mark(lnum, added);
7689 if (curwin->w_cursor.lnum > lnum)
7690 curwin->w_cursor.lnum += added;
7692 else
7693 rettv->vval.v_number = 1; /* Failed */
7697 * "argc()" function
7699 /* ARGSUSED */
7700 static void
7701 f_argc(argvars, rettv)
7702 typval_T *argvars;
7703 typval_T *rettv;
7705 rettv->vval.v_number = ARGCOUNT;
7709 * "argidx()" function
7711 /* ARGSUSED */
7712 static void
7713 f_argidx(argvars, rettv)
7714 typval_T *argvars;
7715 typval_T *rettv;
7717 rettv->vval.v_number = curwin->w_arg_idx;
7721 * "argv(nr)" function
7723 static void
7724 f_argv(argvars, rettv)
7725 typval_T *argvars;
7726 typval_T *rettv;
7728 int idx;
7730 if (argvars[0].v_type != VAR_UNKNOWN)
7732 idx = get_tv_number_chk(&argvars[0], NULL);
7733 if (idx >= 0 && idx < ARGCOUNT)
7734 rettv->vval.v_string = vim_strsave(alist_name(&ARGLIST[idx]));
7735 else
7736 rettv->vval.v_string = NULL;
7737 rettv->v_type = VAR_STRING;
7739 else if (rettv_list_alloc(rettv) == OK)
7740 for (idx = 0; idx < ARGCOUNT; ++idx)
7741 list_append_string(rettv->vval.v_list,
7742 alist_name(&ARGLIST[idx]), -1);
7746 * "browse(save, title, initdir, default)" function
7748 /* ARGSUSED */
7749 static void
7750 f_browse(argvars, rettv)
7751 typval_T *argvars;
7752 typval_T *rettv;
7754 #ifdef FEAT_BROWSE
7755 int save;
7756 char_u *title;
7757 char_u *initdir;
7758 char_u *defname;
7759 char_u buf[NUMBUFLEN];
7760 char_u buf2[NUMBUFLEN];
7761 int error = FALSE;
7763 save = get_tv_number_chk(&argvars[0], &error);
7764 title = get_tv_string_chk(&argvars[1]);
7765 initdir = get_tv_string_buf_chk(&argvars[2], buf);
7766 defname = get_tv_string_buf_chk(&argvars[3], buf2);
7768 if (error || title == NULL || initdir == NULL || defname == NULL)
7769 rettv->vval.v_string = NULL;
7770 else
7771 rettv->vval.v_string =
7772 do_browse(save ? BROWSE_SAVE : 0,
7773 title, defname, NULL, initdir, NULL, curbuf);
7774 #else
7775 rettv->vval.v_string = NULL;
7776 #endif
7777 rettv->v_type = VAR_STRING;
7781 * "browsedir(title, initdir)" function
7783 /* ARGSUSED */
7784 static void
7785 f_browsedir(argvars, rettv)
7786 typval_T *argvars;
7787 typval_T *rettv;
7789 #ifdef FEAT_BROWSE
7790 char_u *title;
7791 char_u *initdir;
7792 char_u buf[NUMBUFLEN];
7794 title = get_tv_string_chk(&argvars[0]);
7795 initdir = get_tv_string_buf_chk(&argvars[1], buf);
7797 if (title == NULL || initdir == NULL)
7798 rettv->vval.v_string = NULL;
7799 else
7800 rettv->vval.v_string = do_browse(BROWSE_DIR,
7801 title, NULL, NULL, initdir, NULL, curbuf);
7802 #else
7803 rettv->vval.v_string = NULL;
7804 #endif
7805 rettv->v_type = VAR_STRING;
7808 static buf_T *find_buffer __ARGS((typval_T *avar));
7811 * Find a buffer by number or exact name.
7813 static buf_T *
7814 find_buffer(avar)
7815 typval_T *avar;
7817 buf_T *buf = NULL;
7819 if (avar->v_type == VAR_NUMBER)
7820 buf = buflist_findnr((int)avar->vval.v_number);
7821 else if (avar->v_type == VAR_STRING && avar->vval.v_string != NULL)
7823 buf = buflist_findname_exp(avar->vval.v_string);
7824 if (buf == NULL)
7826 /* No full path name match, try a match with a URL or a "nofile"
7827 * buffer, these don't use the full path. */
7828 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
7829 if (buf->b_fname != NULL
7830 && (path_with_url(buf->b_fname)
7831 #ifdef FEAT_QUICKFIX
7832 || bt_nofile(buf)
7833 #endif
7835 && STRCMP(buf->b_fname, avar->vval.v_string) == 0)
7836 break;
7839 return buf;
7843 * "bufexists(expr)" function
7845 static void
7846 f_bufexists(argvars, rettv)
7847 typval_T *argvars;
7848 typval_T *rettv;
7850 rettv->vval.v_number = (find_buffer(&argvars[0]) != NULL);
7854 * "buflisted(expr)" function
7856 static void
7857 f_buflisted(argvars, rettv)
7858 typval_T *argvars;
7859 typval_T *rettv;
7861 buf_T *buf;
7863 buf = find_buffer(&argvars[0]);
7864 rettv->vval.v_number = (buf != NULL && buf->b_p_bl);
7868 * "bufloaded(expr)" function
7870 static void
7871 f_bufloaded(argvars, rettv)
7872 typval_T *argvars;
7873 typval_T *rettv;
7875 buf_T *buf;
7877 buf = find_buffer(&argvars[0]);
7878 rettv->vval.v_number = (buf != NULL && buf->b_ml.ml_mfp != NULL);
7881 static buf_T *get_buf_tv __ARGS((typval_T *tv));
7884 * Get buffer by number or pattern.
7886 static buf_T *
7887 get_buf_tv(tv)
7888 typval_T *tv;
7890 char_u *name = tv->vval.v_string;
7891 int save_magic;
7892 char_u *save_cpo;
7893 buf_T *buf;
7895 if (tv->v_type == VAR_NUMBER)
7896 return buflist_findnr((int)tv->vval.v_number);
7897 if (tv->v_type != VAR_STRING)
7898 return NULL;
7899 if (name == NULL || *name == NUL)
7900 return curbuf;
7901 if (name[0] == '$' && name[1] == NUL)
7902 return lastbuf;
7904 /* Ignore 'magic' and 'cpoptions' here to make scripts portable */
7905 save_magic = p_magic;
7906 p_magic = TRUE;
7907 save_cpo = p_cpo;
7908 p_cpo = (char_u *)"";
7910 buf = buflist_findnr(buflist_findpat(name, name + STRLEN(name),
7911 TRUE, FALSE));
7913 p_magic = save_magic;
7914 p_cpo = save_cpo;
7916 /* If not found, try expanding the name, like done for bufexists(). */
7917 if (buf == NULL)
7918 buf = find_buffer(tv);
7920 return buf;
7924 * "bufname(expr)" function
7926 static void
7927 f_bufname(argvars, rettv)
7928 typval_T *argvars;
7929 typval_T *rettv;
7931 buf_T *buf;
7933 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
7934 ++emsg_off;
7935 buf = get_buf_tv(&argvars[0]);
7936 rettv->v_type = VAR_STRING;
7937 if (buf != NULL && buf->b_fname != NULL)
7938 rettv->vval.v_string = vim_strsave(buf->b_fname);
7939 else
7940 rettv->vval.v_string = NULL;
7941 --emsg_off;
7945 * "bufnr(expr)" function
7947 static void
7948 f_bufnr(argvars, rettv)
7949 typval_T *argvars;
7950 typval_T *rettv;
7952 buf_T *buf;
7953 int error = FALSE;
7954 char_u *name;
7956 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
7957 ++emsg_off;
7958 buf = get_buf_tv(&argvars[0]);
7959 --emsg_off;
7961 /* If the buffer isn't found and the second argument is not zero create a
7962 * new buffer. */
7963 if (buf == NULL
7964 && argvars[1].v_type != VAR_UNKNOWN
7965 && get_tv_number_chk(&argvars[1], &error) != 0
7966 && !error
7967 && (name = get_tv_string_chk(&argvars[0])) != NULL
7968 && !error)
7969 buf = buflist_new(name, NULL, (linenr_T)1, 0);
7971 if (buf != NULL)
7972 rettv->vval.v_number = buf->b_fnum;
7973 else
7974 rettv->vval.v_number = -1;
7978 * "bufwinnr(nr)" function
7980 static void
7981 f_bufwinnr(argvars, rettv)
7982 typval_T *argvars;
7983 typval_T *rettv;
7985 #ifdef FEAT_WINDOWS
7986 win_T *wp;
7987 int winnr = 0;
7988 #endif
7989 buf_T *buf;
7991 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
7992 ++emsg_off;
7993 buf = get_buf_tv(&argvars[0]);
7994 #ifdef FEAT_WINDOWS
7995 for (wp = firstwin; wp; wp = wp->w_next)
7997 ++winnr;
7998 if (wp->w_buffer == buf)
7999 break;
8001 rettv->vval.v_number = (wp != NULL ? winnr : -1);
8002 #else
8003 rettv->vval.v_number = (curwin->w_buffer == buf ? 1 : -1);
8004 #endif
8005 --emsg_off;
8009 * "byte2line(byte)" function
8011 /*ARGSUSED*/
8012 static void
8013 f_byte2line(argvars, rettv)
8014 typval_T *argvars;
8015 typval_T *rettv;
8017 #ifndef FEAT_BYTEOFF
8018 rettv->vval.v_number = -1;
8019 #else
8020 long boff = 0;
8022 boff = get_tv_number(&argvars[0]) - 1; /* boff gets -1 on type error */
8023 if (boff < 0)
8024 rettv->vval.v_number = -1;
8025 else
8026 rettv->vval.v_number = ml_find_line_or_offset(curbuf,
8027 (linenr_T)0, &boff);
8028 #endif
8032 * "byteidx()" function
8034 /*ARGSUSED*/
8035 static void
8036 f_byteidx(argvars, rettv)
8037 typval_T *argvars;
8038 typval_T *rettv;
8040 #ifdef FEAT_MBYTE
8041 char_u *t;
8042 #endif
8043 char_u *str;
8044 long idx;
8046 str = get_tv_string_chk(&argvars[0]);
8047 idx = get_tv_number_chk(&argvars[1], NULL);
8048 rettv->vval.v_number = -1;
8049 if (str == NULL || idx < 0)
8050 return;
8052 #ifdef FEAT_MBYTE
8053 t = str;
8054 for ( ; idx > 0; idx--)
8056 if (*t == NUL) /* EOL reached */
8057 return;
8058 t += (*mb_ptr2len)(t);
8060 rettv->vval.v_number = (varnumber_T)(t - str);
8061 #else
8062 if (idx <= STRLEN(str))
8063 rettv->vval.v_number = idx;
8064 #endif
8068 * "call(func, arglist)" function
8070 static void
8071 f_call(argvars, rettv)
8072 typval_T *argvars;
8073 typval_T *rettv;
8075 char_u *func;
8076 typval_T argv[MAX_FUNC_ARGS + 1];
8077 int argc = 0;
8078 listitem_T *item;
8079 int dummy;
8080 dict_T *selfdict = NULL;
8082 rettv->vval.v_number = 0;
8083 if (argvars[1].v_type != VAR_LIST)
8085 EMSG(_(e_listreq));
8086 return;
8088 if (argvars[1].vval.v_list == NULL)
8089 return;
8091 if (argvars[0].v_type == VAR_FUNC)
8092 func = argvars[0].vval.v_string;
8093 else
8094 func = get_tv_string(&argvars[0]);
8095 if (*func == NUL)
8096 return; /* type error or empty name */
8098 if (argvars[2].v_type != VAR_UNKNOWN)
8100 if (argvars[2].v_type != VAR_DICT)
8102 EMSG(_(e_dictreq));
8103 return;
8105 selfdict = argvars[2].vval.v_dict;
8108 for (item = argvars[1].vval.v_list->lv_first; item != NULL;
8109 item = item->li_next)
8111 if (argc == MAX_FUNC_ARGS)
8113 EMSG(_("E699: Too many arguments"));
8114 break;
8116 /* Make a copy of each argument. This is needed to be able to set
8117 * v_lock to VAR_FIXED in the copy without changing the original list.
8119 copy_tv(&item->li_tv, &argv[argc++]);
8122 if (item == NULL)
8123 (void)call_func(func, (int)STRLEN(func), rettv, argc, argv,
8124 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
8125 &dummy, TRUE, selfdict);
8127 /* Free the arguments. */
8128 while (argc > 0)
8129 clear_tv(&argv[--argc]);
8133 * "changenr()" function
8135 /*ARGSUSED*/
8136 static void
8137 f_changenr(argvars, rettv)
8138 typval_T *argvars;
8139 typval_T *rettv;
8141 rettv->vval.v_number = curbuf->b_u_seq_cur;
8145 * "char2nr(string)" function
8147 static void
8148 f_char2nr(argvars, rettv)
8149 typval_T *argvars;
8150 typval_T *rettv;
8152 #ifdef FEAT_MBYTE
8153 if (has_mbyte)
8154 rettv->vval.v_number = (*mb_ptr2char)(get_tv_string(&argvars[0]));
8155 else
8156 #endif
8157 rettv->vval.v_number = get_tv_string(&argvars[0])[0];
8161 * "cindent(lnum)" function
8163 static void
8164 f_cindent(argvars, rettv)
8165 typval_T *argvars;
8166 typval_T *rettv;
8168 #ifdef FEAT_CINDENT
8169 pos_T pos;
8170 linenr_T lnum;
8172 pos = curwin->w_cursor;
8173 lnum = get_tv_lnum(argvars);
8174 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
8176 curwin->w_cursor.lnum = lnum;
8177 rettv->vval.v_number = get_c_indent();
8178 curwin->w_cursor = pos;
8180 else
8181 #endif
8182 rettv->vval.v_number = -1;
8186 * "col(string)" function
8188 static void
8189 f_col(argvars, rettv)
8190 typval_T *argvars;
8191 typval_T *rettv;
8193 colnr_T col = 0;
8194 pos_T *fp;
8195 int fnum = curbuf->b_fnum;
8197 fp = var2fpos(&argvars[0], FALSE, &fnum);
8198 if (fp != NULL && fnum == curbuf->b_fnum)
8200 if (fp->col == MAXCOL)
8202 /* '> can be MAXCOL, get the length of the line then */
8203 if (fp->lnum <= curbuf->b_ml.ml_line_count)
8204 col = (colnr_T)STRLEN(ml_get(fp->lnum)) + 1;
8205 else
8206 col = MAXCOL;
8208 else
8210 col = fp->col + 1;
8211 #ifdef FEAT_VIRTUALEDIT
8212 /* col(".") when the cursor is on the NUL at the end of the line
8213 * because of "coladd" can be seen as an extra column. */
8214 if (virtual_active() && fp == &curwin->w_cursor)
8216 char_u *p = ml_get_cursor();
8218 if (curwin->w_cursor.coladd >= (colnr_T)chartabsize(p,
8219 curwin->w_virtcol - curwin->w_cursor.coladd))
8221 # ifdef FEAT_MBYTE
8222 int l;
8224 if (*p != NUL && p[(l = (*mb_ptr2len)(p))] == NUL)
8225 col += l;
8226 # else
8227 if (*p != NUL && p[1] == NUL)
8228 ++col;
8229 # endif
8232 #endif
8235 rettv->vval.v_number = col;
8238 #if defined(FEAT_INS_EXPAND)
8240 * "complete()" function
8242 /*ARGSUSED*/
8243 static void
8244 f_complete(argvars, rettv)
8245 typval_T *argvars;
8246 typval_T *rettv;
8248 int startcol;
8250 if ((State & INSERT) == 0)
8252 EMSG(_("E785: complete() can only be used in Insert mode"));
8253 return;
8256 /* Check for undo allowed here, because if something was already inserted
8257 * the line was already saved for undo and this check isn't done. */
8258 if (!undo_allowed())
8259 return;
8261 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
8263 EMSG(_(e_invarg));
8264 return;
8267 startcol = get_tv_number_chk(&argvars[0], NULL);
8268 if (startcol <= 0)
8269 return;
8271 set_completion(startcol - 1, argvars[1].vval.v_list);
8275 * "complete_add()" function
8277 /*ARGSUSED*/
8278 static void
8279 f_complete_add(argvars, rettv)
8280 typval_T *argvars;
8281 typval_T *rettv;
8283 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0);
8287 * "complete_check()" function
8289 /*ARGSUSED*/
8290 static void
8291 f_complete_check(argvars, rettv)
8292 typval_T *argvars;
8293 typval_T *rettv;
8295 int saved = RedrawingDisabled;
8297 RedrawingDisabled = 0;
8298 ins_compl_check_keys(0);
8299 rettv->vval.v_number = compl_interrupted;
8300 RedrawingDisabled = saved;
8302 #endif
8305 * "confirm(message, buttons[, default [, type]])" function
8307 /*ARGSUSED*/
8308 static void
8309 f_confirm(argvars, rettv)
8310 typval_T *argvars;
8311 typval_T *rettv;
8313 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
8314 char_u *message;
8315 char_u *buttons = NULL;
8316 char_u buf[NUMBUFLEN];
8317 char_u buf2[NUMBUFLEN];
8318 int def = 1;
8319 int type = VIM_GENERIC;
8320 char_u *typestr;
8321 int error = FALSE;
8323 message = get_tv_string_chk(&argvars[0]);
8324 if (message == NULL)
8325 error = TRUE;
8326 if (argvars[1].v_type != VAR_UNKNOWN)
8328 buttons = get_tv_string_buf_chk(&argvars[1], buf);
8329 if (buttons == NULL)
8330 error = TRUE;
8331 if (argvars[2].v_type != VAR_UNKNOWN)
8333 def = get_tv_number_chk(&argvars[2], &error);
8334 if (argvars[3].v_type != VAR_UNKNOWN)
8336 typestr = get_tv_string_buf_chk(&argvars[3], buf2);
8337 if (typestr == NULL)
8338 error = TRUE;
8339 else
8341 switch (TOUPPER_ASC(*typestr))
8343 case 'E': type = VIM_ERROR; break;
8344 case 'Q': type = VIM_QUESTION; break;
8345 case 'I': type = VIM_INFO; break;
8346 case 'W': type = VIM_WARNING; break;
8347 case 'G': type = VIM_GENERIC; break;
8354 if (buttons == NULL || *buttons == NUL)
8355 buttons = (char_u *)_("&Ok");
8357 if (error)
8358 rettv->vval.v_number = 0;
8359 else
8360 rettv->vval.v_number = do_dialog(type, NULL, message, buttons,
8361 def, NULL);
8362 #else
8363 rettv->vval.v_number = 0;
8364 #endif
8368 * "copy()" function
8370 static void
8371 f_copy(argvars, rettv)
8372 typval_T *argvars;
8373 typval_T *rettv;
8375 item_copy(&argvars[0], rettv, FALSE, 0);
8379 * "count()" function
8381 static void
8382 f_count(argvars, rettv)
8383 typval_T *argvars;
8384 typval_T *rettv;
8386 long n = 0;
8387 int ic = FALSE;
8389 if (argvars[0].v_type == VAR_LIST)
8391 listitem_T *li;
8392 list_T *l;
8393 long idx;
8395 if ((l = argvars[0].vval.v_list) != NULL)
8397 li = l->lv_first;
8398 if (argvars[2].v_type != VAR_UNKNOWN)
8400 int error = FALSE;
8402 ic = get_tv_number_chk(&argvars[2], &error);
8403 if (argvars[3].v_type != VAR_UNKNOWN)
8405 idx = get_tv_number_chk(&argvars[3], &error);
8406 if (!error)
8408 li = list_find(l, idx);
8409 if (li == NULL)
8410 EMSGN(_(e_listidx), idx);
8413 if (error)
8414 li = NULL;
8417 for ( ; li != NULL; li = li->li_next)
8418 if (tv_equal(&li->li_tv, &argvars[1], ic))
8419 ++n;
8422 else if (argvars[0].v_type == VAR_DICT)
8424 int todo;
8425 dict_T *d;
8426 hashitem_T *hi;
8428 if ((d = argvars[0].vval.v_dict) != NULL)
8430 int error = FALSE;
8432 if (argvars[2].v_type != VAR_UNKNOWN)
8434 ic = get_tv_number_chk(&argvars[2], &error);
8435 if (argvars[3].v_type != VAR_UNKNOWN)
8436 EMSG(_(e_invarg));
8439 todo = error ? 0 : (int)d->dv_hashtab.ht_used;
8440 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
8442 if (!HASHITEM_EMPTY(hi))
8444 --todo;
8445 if (tv_equal(&HI2DI(hi)->di_tv, &argvars[1], ic))
8446 ++n;
8451 else
8452 EMSG2(_(e_listdictarg), "count()");
8453 rettv->vval.v_number = n;
8457 * "cscope_connection([{num} , {dbpath} [, {prepend}]])" function
8459 * Checks the existence of a cscope connection.
8461 /*ARGSUSED*/
8462 static void
8463 f_cscope_connection(argvars, rettv)
8464 typval_T *argvars;
8465 typval_T *rettv;
8467 #ifdef FEAT_CSCOPE
8468 int num = 0;
8469 char_u *dbpath = NULL;
8470 char_u *prepend = NULL;
8471 char_u buf[NUMBUFLEN];
8473 if (argvars[0].v_type != VAR_UNKNOWN
8474 && argvars[1].v_type != VAR_UNKNOWN)
8476 num = (int)get_tv_number(&argvars[0]);
8477 dbpath = get_tv_string(&argvars[1]);
8478 if (argvars[2].v_type != VAR_UNKNOWN)
8479 prepend = get_tv_string_buf(&argvars[2], buf);
8482 rettv->vval.v_number = cs_connection(num, dbpath, prepend);
8483 #else
8484 rettv->vval.v_number = 0;
8485 #endif
8489 * "cursor(lnum, col)" function
8491 * Moves the cursor to the specified line and column
8493 /*ARGSUSED*/
8494 static void
8495 f_cursor(argvars, rettv)
8496 typval_T *argvars;
8497 typval_T *rettv;
8499 long line, col;
8500 #ifdef FEAT_VIRTUALEDIT
8501 long coladd = 0;
8502 #endif
8504 if (argvars[1].v_type == VAR_UNKNOWN)
8506 pos_T pos;
8508 if (list2fpos(argvars, &pos, NULL) == FAIL)
8509 return;
8510 line = pos.lnum;
8511 col = pos.col;
8512 #ifdef FEAT_VIRTUALEDIT
8513 coladd = pos.coladd;
8514 #endif
8516 else
8518 line = get_tv_lnum(argvars);
8519 col = get_tv_number_chk(&argvars[1], NULL);
8520 #ifdef FEAT_VIRTUALEDIT
8521 if (argvars[2].v_type != VAR_UNKNOWN)
8522 coladd = get_tv_number_chk(&argvars[2], NULL);
8523 #endif
8525 if (line < 0 || col < 0
8526 #ifdef FEAT_VIRTUALEDIT
8527 || coladd < 0
8528 #endif
8530 return; /* type error; errmsg already given */
8531 if (line > 0)
8532 curwin->w_cursor.lnum = line;
8533 if (col > 0)
8534 curwin->w_cursor.col = col - 1;
8535 #ifdef FEAT_VIRTUALEDIT
8536 curwin->w_cursor.coladd = coladd;
8537 #endif
8539 /* Make sure the cursor is in a valid position. */
8540 check_cursor();
8541 #ifdef FEAT_MBYTE
8542 /* Correct cursor for multi-byte character. */
8543 if (has_mbyte)
8544 mb_adjust_cursor();
8545 #endif
8547 curwin->w_set_curswant = TRUE;
8551 * "deepcopy()" function
8553 static void
8554 f_deepcopy(argvars, rettv)
8555 typval_T *argvars;
8556 typval_T *rettv;
8558 int noref = 0;
8560 if (argvars[1].v_type != VAR_UNKNOWN)
8561 noref = get_tv_number_chk(&argvars[1], NULL);
8562 if (noref < 0 || noref > 1)
8563 EMSG(_(e_invarg));
8564 else
8565 item_copy(&argvars[0], rettv, TRUE, noref == 0 ? ++current_copyID : 0);
8569 * "delete()" function
8571 static void
8572 f_delete(argvars, rettv)
8573 typval_T *argvars;
8574 typval_T *rettv;
8576 if (check_restricted() || check_secure())
8577 rettv->vval.v_number = -1;
8578 else
8579 rettv->vval.v_number = mch_remove(get_tv_string(&argvars[0]));
8583 * "did_filetype()" function
8585 /*ARGSUSED*/
8586 static void
8587 f_did_filetype(argvars, rettv)
8588 typval_T *argvars;
8589 typval_T *rettv;
8591 #ifdef FEAT_AUTOCMD
8592 rettv->vval.v_number = did_filetype;
8593 #else
8594 rettv->vval.v_number = 0;
8595 #endif
8599 * "diff_filler()" function
8601 /*ARGSUSED*/
8602 static void
8603 f_diff_filler(argvars, rettv)
8604 typval_T *argvars;
8605 typval_T *rettv;
8607 #ifdef FEAT_DIFF
8608 rettv->vval.v_number = diff_check_fill(curwin, get_tv_lnum(argvars));
8609 #endif
8613 * "diff_hlID()" function
8615 /*ARGSUSED*/
8616 static void
8617 f_diff_hlID(argvars, rettv)
8618 typval_T *argvars;
8619 typval_T *rettv;
8621 #ifdef FEAT_DIFF
8622 linenr_T lnum = get_tv_lnum(argvars);
8623 static linenr_T prev_lnum = 0;
8624 static int changedtick = 0;
8625 static int fnum = 0;
8626 static int change_start = 0;
8627 static int change_end = 0;
8628 static hlf_T hlID = 0;
8629 int filler_lines;
8630 int col;
8632 if (lnum < 0) /* ignore type error in {lnum} arg */
8633 lnum = 0;
8634 if (lnum != prev_lnum
8635 || changedtick != curbuf->b_changedtick
8636 || fnum != curbuf->b_fnum)
8638 /* New line, buffer, change: need to get the values. */
8639 filler_lines = diff_check(curwin, lnum);
8640 if (filler_lines < 0)
8642 if (filler_lines == -1)
8644 change_start = MAXCOL;
8645 change_end = -1;
8646 if (diff_find_change(curwin, lnum, &change_start, &change_end))
8647 hlID = HLF_ADD; /* added line */
8648 else
8649 hlID = HLF_CHD; /* changed line */
8651 else
8652 hlID = HLF_ADD; /* added line */
8654 else
8655 hlID = (hlf_T)0;
8656 prev_lnum = lnum;
8657 changedtick = curbuf->b_changedtick;
8658 fnum = curbuf->b_fnum;
8661 if (hlID == HLF_CHD || hlID == HLF_TXD)
8663 col = get_tv_number(&argvars[1]) - 1; /* ignore type error in {col} */
8664 if (col >= change_start && col <= change_end)
8665 hlID = HLF_TXD; /* changed text */
8666 else
8667 hlID = HLF_CHD; /* changed line */
8669 rettv->vval.v_number = hlID == (hlf_T)0 ? 0 : (int)hlID;
8670 #endif
8674 * "empty({expr})" function
8676 static void
8677 f_empty(argvars, rettv)
8678 typval_T *argvars;
8679 typval_T *rettv;
8681 int n;
8683 switch (argvars[0].v_type)
8685 case VAR_STRING:
8686 case VAR_FUNC:
8687 n = argvars[0].vval.v_string == NULL
8688 || *argvars[0].vval.v_string == NUL;
8689 break;
8690 case VAR_NUMBER:
8691 n = argvars[0].vval.v_number == 0;
8692 break;
8693 case VAR_LIST:
8694 n = argvars[0].vval.v_list == NULL
8695 || argvars[0].vval.v_list->lv_first == NULL;
8696 break;
8697 case VAR_DICT:
8698 n = argvars[0].vval.v_dict == NULL
8699 || argvars[0].vval.v_dict->dv_hashtab.ht_used == 0;
8700 break;
8701 default:
8702 EMSG2(_(e_intern2), "f_empty()");
8703 n = 0;
8706 rettv->vval.v_number = n;
8710 * "escape({string}, {chars})" function
8712 static void
8713 f_escape(argvars, rettv)
8714 typval_T *argvars;
8715 typval_T *rettv;
8717 char_u buf[NUMBUFLEN];
8719 rettv->vval.v_string = vim_strsave_escaped(get_tv_string(&argvars[0]),
8720 get_tv_string_buf(&argvars[1], buf));
8721 rettv->v_type = VAR_STRING;
8725 * "eval()" function
8727 /*ARGSUSED*/
8728 static void
8729 f_eval(argvars, rettv)
8730 typval_T *argvars;
8731 typval_T *rettv;
8733 char_u *s;
8735 s = get_tv_string_chk(&argvars[0]);
8736 if (s != NULL)
8737 s = skipwhite(s);
8739 if (s == NULL || eval1(&s, rettv, TRUE) == FAIL)
8741 rettv->v_type = VAR_NUMBER;
8742 rettv->vval.v_number = 0;
8744 else if (*s != NUL)
8745 EMSG(_(e_trailing));
8749 * "eventhandler()" function
8751 /*ARGSUSED*/
8752 static void
8753 f_eventhandler(argvars, rettv)
8754 typval_T *argvars;
8755 typval_T *rettv;
8757 rettv->vval.v_number = vgetc_busy;
8761 * "executable()" function
8763 static void
8764 f_executable(argvars, rettv)
8765 typval_T *argvars;
8766 typval_T *rettv;
8768 rettv->vval.v_number = mch_can_exe(get_tv_string(&argvars[0]));
8772 * "exists()" function
8774 static void
8775 f_exists(argvars, rettv)
8776 typval_T *argvars;
8777 typval_T *rettv;
8779 char_u *p;
8780 char_u *name;
8781 int n = FALSE;
8782 int len = 0;
8784 p = get_tv_string(&argvars[0]);
8785 if (*p == '$') /* environment variable */
8787 /* first try "normal" environment variables (fast) */
8788 if (mch_getenv(p + 1) != NULL)
8789 n = TRUE;
8790 else
8792 /* try expanding things like $VIM and ${HOME} */
8793 p = expand_env_save(p);
8794 if (p != NULL && *p != '$')
8795 n = TRUE;
8796 vim_free(p);
8799 else if (*p == '&' || *p == '+') /* option */
8801 n = (get_option_tv(&p, NULL, TRUE) == OK);
8802 if (*skipwhite(p) != NUL)
8803 n = FALSE; /* trailing garbage */
8805 else if (*p == '*') /* internal or user defined function */
8807 n = function_exists(p + 1);
8809 else if (*p == ':')
8811 n = cmd_exists(p + 1);
8813 else if (*p == '#')
8815 #ifdef FEAT_AUTOCMD
8816 if (p[1] == '#')
8817 n = autocmd_supported(p + 2);
8818 else
8819 n = au_exists(p + 1);
8820 #endif
8822 else /* internal variable */
8824 char_u *tofree;
8825 typval_T tv;
8827 /* get_name_len() takes care of expanding curly braces */
8828 name = p;
8829 len = get_name_len(&p, &tofree, TRUE, FALSE);
8830 if (len > 0)
8832 if (tofree != NULL)
8833 name = tofree;
8834 n = (get_var_tv(name, len, &tv, FALSE) == OK);
8835 if (n)
8837 /* handle d.key, l[idx], f(expr) */
8838 n = (handle_subscript(&p, &tv, TRUE, FALSE) == OK);
8839 if (n)
8840 clear_tv(&tv);
8843 if (*p != NUL)
8844 n = FALSE;
8846 vim_free(tofree);
8849 rettv->vval.v_number = n;
8853 * "expand()" function
8855 static void
8856 f_expand(argvars, rettv)
8857 typval_T *argvars;
8858 typval_T *rettv;
8860 char_u *s;
8861 int len;
8862 char_u *errormsg;
8863 int flags = WILD_SILENT|WILD_USE_NL|WILD_LIST_NOTFOUND;
8864 expand_T xpc;
8865 int error = FALSE;
8867 rettv->v_type = VAR_STRING;
8868 s = get_tv_string(&argvars[0]);
8869 if (*s == '%' || *s == '#' || *s == '<')
8871 ++emsg_off;
8872 rettv->vval.v_string = eval_vars(s, &len, NULL, &errormsg, s);
8873 --emsg_off;
8875 else
8877 /* When the optional second argument is non-zero, don't remove matches
8878 * for 'suffixes' and 'wildignore' */
8879 if (argvars[1].v_type != VAR_UNKNOWN
8880 && get_tv_number_chk(&argvars[1], &error))
8881 flags |= WILD_KEEP_ALL;
8882 if (!error)
8884 ExpandInit(&xpc);
8885 xpc.xp_context = EXPAND_FILES;
8886 rettv->vval.v_string = ExpandOne(&xpc, s, NULL, flags, WILD_ALL);
8888 else
8889 rettv->vval.v_string = NULL;
8894 * "extend(list, list [, idx])" function
8895 * "extend(dict, dict [, action])" function
8897 static void
8898 f_extend(argvars, rettv)
8899 typval_T *argvars;
8900 typval_T *rettv;
8902 rettv->vval.v_number = 0;
8903 if (argvars[0].v_type == VAR_LIST && argvars[1].v_type == VAR_LIST)
8905 list_T *l1, *l2;
8906 listitem_T *item;
8907 long before;
8908 int error = FALSE;
8910 l1 = argvars[0].vval.v_list;
8911 l2 = argvars[1].vval.v_list;
8912 if (l1 != NULL && !tv_check_lock(l1->lv_lock, (char_u *)"extend()")
8913 && l2 != NULL)
8915 if (argvars[2].v_type != VAR_UNKNOWN)
8917 before = get_tv_number_chk(&argvars[2], &error);
8918 if (error)
8919 return; /* type error; errmsg already given */
8921 if (before == l1->lv_len)
8922 item = NULL;
8923 else
8925 item = list_find(l1, before);
8926 if (item == NULL)
8928 EMSGN(_(e_listidx), before);
8929 return;
8933 else
8934 item = NULL;
8935 list_extend(l1, l2, item);
8937 copy_tv(&argvars[0], rettv);
8940 else if (argvars[0].v_type == VAR_DICT && argvars[1].v_type == VAR_DICT)
8942 dict_T *d1, *d2;
8943 dictitem_T *di1;
8944 char_u *action;
8945 int i;
8946 hashitem_T *hi2;
8947 int todo;
8949 d1 = argvars[0].vval.v_dict;
8950 d2 = argvars[1].vval.v_dict;
8951 if (d1 != NULL && !tv_check_lock(d1->dv_lock, (char_u *)"extend()")
8952 && d2 != NULL)
8954 /* Check the third argument. */
8955 if (argvars[2].v_type != VAR_UNKNOWN)
8957 static char *(av[]) = {"keep", "force", "error"};
8959 action = get_tv_string_chk(&argvars[2]);
8960 if (action == NULL)
8961 return; /* type error; errmsg already given */
8962 for (i = 0; i < 3; ++i)
8963 if (STRCMP(action, av[i]) == 0)
8964 break;
8965 if (i == 3)
8967 EMSG2(_(e_invarg2), action);
8968 return;
8971 else
8972 action = (char_u *)"force";
8974 /* Go over all entries in the second dict and add them to the
8975 * first dict. */
8976 todo = (int)d2->dv_hashtab.ht_used;
8977 for (hi2 = d2->dv_hashtab.ht_array; todo > 0; ++hi2)
8979 if (!HASHITEM_EMPTY(hi2))
8981 --todo;
8982 di1 = dict_find(d1, hi2->hi_key, -1);
8983 if (di1 == NULL)
8985 di1 = dictitem_copy(HI2DI(hi2));
8986 if (di1 != NULL && dict_add(d1, di1) == FAIL)
8987 dictitem_free(di1);
8989 else if (*action == 'e')
8991 EMSG2(_("E737: Key already exists: %s"), hi2->hi_key);
8992 break;
8994 else if (*action == 'f')
8996 clear_tv(&di1->di_tv);
8997 copy_tv(&HI2DI(hi2)->di_tv, &di1->di_tv);
9002 copy_tv(&argvars[0], rettv);
9005 else
9006 EMSG2(_(e_listdictarg), "extend()");
9010 * "feedkeys()" function
9012 /*ARGSUSED*/
9013 static void
9014 f_feedkeys(argvars, rettv)
9015 typval_T *argvars;
9016 typval_T *rettv;
9018 int remap = TRUE;
9019 char_u *keys, *flags;
9020 char_u nbuf[NUMBUFLEN];
9021 int typed = FALSE;
9022 char_u *keys_esc;
9024 rettv->vval.v_number = 0;
9025 keys = get_tv_string(&argvars[0]);
9026 if (*keys != NUL)
9028 if (argvars[1].v_type != VAR_UNKNOWN)
9030 flags = get_tv_string_buf(&argvars[1], nbuf);
9031 for ( ; *flags != NUL; ++flags)
9033 switch (*flags)
9035 case 'n': remap = FALSE; break;
9036 case 'm': remap = TRUE; break;
9037 case 't': typed = TRUE; break;
9042 /* Need to escape K_SPECIAL and CSI before putting the string in the
9043 * typeahead buffer. */
9044 keys_esc = vim_strsave_escape_csi(keys);
9045 if (keys_esc != NULL)
9047 ins_typebuf(keys_esc, (remap ? REMAP_YES : REMAP_NONE),
9048 typebuf.tb_len, !typed, FALSE);
9049 vim_free(keys_esc);
9050 if (vgetc_busy)
9051 typebuf_was_filled = TRUE;
9057 * "filereadable()" function
9059 static void
9060 f_filereadable(argvars, rettv)
9061 typval_T *argvars;
9062 typval_T *rettv;
9064 FILE *fd;
9065 char_u *p;
9066 int n;
9068 p = get_tv_string(&argvars[0]);
9069 if (*p && !mch_isdir(p) && (fd = mch_fopen((char *)p, "r")) != NULL)
9071 n = TRUE;
9072 fclose(fd);
9074 else
9075 n = FALSE;
9077 rettv->vval.v_number = n;
9081 * Return 0 for not writable, 1 for writable file, 2 for a dir which we have
9082 * rights to write into.
9084 static void
9085 f_filewritable(argvars, rettv)
9086 typval_T *argvars;
9087 typval_T *rettv;
9089 rettv->vval.v_number = filewritable(get_tv_string(&argvars[0]));
9092 static void findfilendir __ARGS((typval_T *argvars, typval_T *rettv, int dir));
9094 static void
9095 findfilendir(argvars, rettv, dir)
9096 typval_T *argvars;
9097 typval_T *rettv;
9098 int dir;
9100 #ifdef FEAT_SEARCHPATH
9101 char_u *fname;
9102 char_u *fresult = NULL;
9103 char_u *path = *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path;
9104 char_u *p;
9105 char_u pathbuf[NUMBUFLEN];
9106 int count = 1;
9107 int first = TRUE;
9108 int error = FALSE;
9109 #endif
9111 rettv->vval.v_string = NULL;
9112 rettv->v_type = VAR_STRING;
9114 #ifdef FEAT_SEARCHPATH
9115 fname = get_tv_string(&argvars[0]);
9117 if (argvars[1].v_type != VAR_UNKNOWN)
9119 p = get_tv_string_buf_chk(&argvars[1], pathbuf);
9120 if (p == NULL)
9121 error = TRUE;
9122 else
9124 if (*p != NUL)
9125 path = p;
9127 if (argvars[2].v_type != VAR_UNKNOWN)
9128 count = get_tv_number_chk(&argvars[2], &error);
9132 if (count < 0 && rettv_list_alloc(rettv) == FAIL)
9133 error = TRUE;
9135 if (*fname != NUL && !error)
9139 if (rettv->v_type == VAR_STRING)
9140 vim_free(fresult);
9141 fresult = find_file_in_path_option(first ? fname : NULL,
9142 first ? (int)STRLEN(fname) : 0,
9143 0, first, path, dir, NULL,
9144 dir ? (char_u *)"" : curbuf->b_p_sua);
9145 first = FALSE;
9147 if (fresult != NULL && rettv->v_type == VAR_LIST)
9148 list_append_string(rettv->vval.v_list, fresult, -1);
9150 } while ((rettv->v_type == VAR_LIST || --count > 0) && fresult != NULL);
9153 if (rettv->v_type == VAR_STRING)
9154 rettv->vval.v_string = fresult;
9155 #endif
9158 static void filter_map __ARGS((typval_T *argvars, typval_T *rettv, int map));
9159 static int filter_map_one __ARGS((typval_T *tv, char_u *expr, int map, int *remp));
9162 * Implementation of map() and filter().
9164 static void
9165 filter_map(argvars, rettv, map)
9166 typval_T *argvars;
9167 typval_T *rettv;
9168 int map;
9170 char_u buf[NUMBUFLEN];
9171 char_u *expr;
9172 listitem_T *li, *nli;
9173 list_T *l = NULL;
9174 dictitem_T *di;
9175 hashtab_T *ht;
9176 hashitem_T *hi;
9177 dict_T *d = NULL;
9178 typval_T save_val;
9179 typval_T save_key;
9180 int rem;
9181 int todo;
9182 char_u *ermsg = map ? (char_u *)"map()" : (char_u *)"filter()";
9183 int save_did_emsg;
9185 rettv->vval.v_number = 0;
9186 if (argvars[0].v_type == VAR_LIST)
9188 if ((l = argvars[0].vval.v_list) == NULL
9189 || (map && tv_check_lock(l->lv_lock, ermsg)))
9190 return;
9192 else if (argvars[0].v_type == VAR_DICT)
9194 if ((d = argvars[0].vval.v_dict) == NULL
9195 || (map && tv_check_lock(d->dv_lock, ermsg)))
9196 return;
9198 else
9200 EMSG2(_(e_listdictarg), ermsg);
9201 return;
9204 expr = get_tv_string_buf_chk(&argvars[1], buf);
9205 /* On type errors, the preceding call has already displayed an error
9206 * message. Avoid a misleading error message for an empty string that
9207 * was not passed as argument. */
9208 if (expr != NULL)
9210 prepare_vimvar(VV_VAL, &save_val);
9211 expr = skipwhite(expr);
9213 /* We reset "did_emsg" to be able to detect whether an error
9214 * occurred during evaluation of the expression. */
9215 save_did_emsg = did_emsg;
9216 did_emsg = FALSE;
9218 if (argvars[0].v_type == VAR_DICT)
9220 prepare_vimvar(VV_KEY, &save_key);
9221 vimvars[VV_KEY].vv_type = VAR_STRING;
9223 ht = &d->dv_hashtab;
9224 hash_lock(ht);
9225 todo = (int)ht->ht_used;
9226 for (hi = ht->ht_array; todo > 0; ++hi)
9228 if (!HASHITEM_EMPTY(hi))
9230 --todo;
9231 di = HI2DI(hi);
9232 if (tv_check_lock(di->di_tv.v_lock, ermsg))
9233 break;
9234 vimvars[VV_KEY].vv_str = vim_strsave(di->di_key);
9235 if (filter_map_one(&di->di_tv, expr, map, &rem) == FAIL
9236 || did_emsg)
9237 break;
9238 if (!map && rem)
9239 dictitem_remove(d, di);
9240 clear_tv(&vimvars[VV_KEY].vv_tv);
9243 hash_unlock(ht);
9245 restore_vimvar(VV_KEY, &save_key);
9247 else
9249 for (li = l->lv_first; li != NULL; li = nli)
9251 if (tv_check_lock(li->li_tv.v_lock, ermsg))
9252 break;
9253 nli = li->li_next;
9254 if (filter_map_one(&li->li_tv, expr, map, &rem) == FAIL
9255 || did_emsg)
9256 break;
9257 if (!map && rem)
9258 listitem_remove(l, li);
9262 restore_vimvar(VV_VAL, &save_val);
9264 did_emsg |= save_did_emsg;
9267 copy_tv(&argvars[0], rettv);
9270 static int
9271 filter_map_one(tv, expr, map, remp)
9272 typval_T *tv;
9273 char_u *expr;
9274 int map;
9275 int *remp;
9277 typval_T rettv;
9278 char_u *s;
9280 copy_tv(tv, &vimvars[VV_VAL].vv_tv);
9281 s = expr;
9282 if (eval1(&s, &rettv, TRUE) == FAIL)
9283 return FAIL;
9284 if (*s != NUL) /* check for trailing chars after expr */
9286 EMSG2(_(e_invexpr2), s);
9287 return FAIL;
9289 if (map)
9291 /* map(): replace the list item value */
9292 clear_tv(tv);
9293 rettv.v_lock = 0;
9294 *tv = rettv;
9296 else
9298 int error = FALSE;
9300 /* filter(): when expr is zero remove the item */
9301 *remp = (get_tv_number_chk(&rettv, &error) == 0);
9302 clear_tv(&rettv);
9303 /* On type error, nothing has been removed; return FAIL to stop the
9304 * loop. The error message was given by get_tv_number_chk(). */
9305 if (error)
9306 return FAIL;
9308 clear_tv(&vimvars[VV_VAL].vv_tv);
9309 return OK;
9313 * "filter()" function
9315 static void
9316 f_filter(argvars, rettv)
9317 typval_T *argvars;
9318 typval_T *rettv;
9320 filter_map(argvars, rettv, FALSE);
9324 * "finddir({fname}[, {path}[, {count}]])" function
9326 static void
9327 f_finddir(argvars, rettv)
9328 typval_T *argvars;
9329 typval_T *rettv;
9331 findfilendir(argvars, rettv, TRUE);
9335 * "findfile({fname}[, {path}[, {count}]])" function
9337 static void
9338 f_findfile(argvars, rettv)
9339 typval_T *argvars;
9340 typval_T *rettv;
9342 findfilendir(argvars, rettv, FALSE);
9346 * "fnamemodify({fname}, {mods})" function
9348 static void
9349 f_fnamemodify(argvars, rettv)
9350 typval_T *argvars;
9351 typval_T *rettv;
9353 char_u *fname;
9354 char_u *mods;
9355 int usedlen = 0;
9356 int len;
9357 char_u *fbuf = NULL;
9358 char_u buf[NUMBUFLEN];
9360 fname = get_tv_string_chk(&argvars[0]);
9361 mods = get_tv_string_buf_chk(&argvars[1], buf);
9362 if (fname == NULL || mods == NULL)
9363 fname = NULL;
9364 else
9366 len = (int)STRLEN(fname);
9367 (void)modify_fname(mods, &usedlen, &fname, &fbuf, &len);
9370 rettv->v_type = VAR_STRING;
9371 if (fname == NULL)
9372 rettv->vval.v_string = NULL;
9373 else
9374 rettv->vval.v_string = vim_strnsave(fname, len);
9375 vim_free(fbuf);
9378 static void foldclosed_both __ARGS((typval_T *argvars, typval_T *rettv, int end));
9381 * "foldclosed()" function
9383 static void
9384 foldclosed_both(argvars, rettv, end)
9385 typval_T *argvars;
9386 typval_T *rettv;
9387 int end;
9389 #ifdef FEAT_FOLDING
9390 linenr_T lnum;
9391 linenr_T first, last;
9393 lnum = get_tv_lnum(argvars);
9394 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
9396 if (hasFoldingWin(curwin, lnum, &first, &last, FALSE, NULL))
9398 if (end)
9399 rettv->vval.v_number = (varnumber_T)last;
9400 else
9401 rettv->vval.v_number = (varnumber_T)first;
9402 return;
9405 #endif
9406 rettv->vval.v_number = -1;
9410 * "foldclosed()" function
9412 static void
9413 f_foldclosed(argvars, rettv)
9414 typval_T *argvars;
9415 typval_T *rettv;
9417 foldclosed_both(argvars, rettv, FALSE);
9421 * "foldclosedend()" function
9423 static void
9424 f_foldclosedend(argvars, rettv)
9425 typval_T *argvars;
9426 typval_T *rettv;
9428 foldclosed_both(argvars, rettv, TRUE);
9432 * "foldlevel()" function
9434 static void
9435 f_foldlevel(argvars, rettv)
9436 typval_T *argvars;
9437 typval_T *rettv;
9439 #ifdef FEAT_FOLDING
9440 linenr_T lnum;
9442 lnum = get_tv_lnum(argvars);
9443 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
9444 rettv->vval.v_number = foldLevel(lnum);
9445 else
9446 #endif
9447 rettv->vval.v_number = 0;
9451 * "foldtext()" function
9453 /*ARGSUSED*/
9454 static void
9455 f_foldtext(argvars, rettv)
9456 typval_T *argvars;
9457 typval_T *rettv;
9459 #ifdef FEAT_FOLDING
9460 linenr_T lnum;
9461 char_u *s;
9462 char_u *r;
9463 int len;
9464 char *txt;
9465 #endif
9467 rettv->v_type = VAR_STRING;
9468 rettv->vval.v_string = NULL;
9469 #ifdef FEAT_FOLDING
9470 if ((linenr_T)vimvars[VV_FOLDSTART].vv_nr > 0
9471 && (linenr_T)vimvars[VV_FOLDEND].vv_nr
9472 <= curbuf->b_ml.ml_line_count
9473 && vimvars[VV_FOLDDASHES].vv_str != NULL)
9475 /* Find first non-empty line in the fold. */
9476 lnum = (linenr_T)vimvars[VV_FOLDSTART].vv_nr;
9477 while (lnum < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
9479 if (!linewhite(lnum))
9480 break;
9481 ++lnum;
9484 /* Find interesting text in this line. */
9485 s = skipwhite(ml_get(lnum));
9486 /* skip C comment-start */
9487 if (s[0] == '/' && (s[1] == '*' || s[1] == '/'))
9489 s = skipwhite(s + 2);
9490 if (*skipwhite(s) == NUL
9491 && lnum + 1 < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
9493 s = skipwhite(ml_get(lnum + 1));
9494 if (*s == '*')
9495 s = skipwhite(s + 1);
9498 txt = _("+-%s%3ld lines: ");
9499 r = alloc((unsigned)(STRLEN(txt)
9500 + STRLEN(vimvars[VV_FOLDDASHES].vv_str) /* for %s */
9501 + 20 /* for %3ld */
9502 + STRLEN(s))); /* concatenated */
9503 if (r != NULL)
9505 sprintf((char *)r, txt, vimvars[VV_FOLDDASHES].vv_str,
9506 (long)((linenr_T)vimvars[VV_FOLDEND].vv_nr
9507 - (linenr_T)vimvars[VV_FOLDSTART].vv_nr + 1));
9508 len = (int)STRLEN(r);
9509 STRCAT(r, s);
9510 /* remove 'foldmarker' and 'commentstring' */
9511 foldtext_cleanup(r + len);
9512 rettv->vval.v_string = r;
9515 #endif
9519 * "foldtextresult(lnum)" function
9521 /*ARGSUSED*/
9522 static void
9523 f_foldtextresult(argvars, rettv)
9524 typval_T *argvars;
9525 typval_T *rettv;
9527 #ifdef FEAT_FOLDING
9528 linenr_T lnum;
9529 char_u *text;
9530 char_u buf[51];
9531 foldinfo_T foldinfo;
9532 int fold_count;
9533 #endif
9535 rettv->v_type = VAR_STRING;
9536 rettv->vval.v_string = NULL;
9537 #ifdef FEAT_FOLDING
9538 lnum = get_tv_lnum(argvars);
9539 /* treat illegal types and illegal string values for {lnum} the same */
9540 if (lnum < 0)
9541 lnum = 0;
9542 fold_count = foldedCount(curwin, lnum, &foldinfo);
9543 if (fold_count > 0)
9545 text = get_foldtext(curwin, lnum, lnum + fold_count - 1,
9546 &foldinfo, buf);
9547 if (text == buf)
9548 text = vim_strsave(text);
9549 rettv->vval.v_string = text;
9551 #endif
9555 * "foreground()" function
9557 /*ARGSUSED*/
9558 static void
9559 f_foreground(argvars, rettv)
9560 typval_T *argvars;
9561 typval_T *rettv;
9563 rettv->vval.v_number = 0;
9564 #ifdef FEAT_GUI
9565 if (gui.in_use)
9566 gui_mch_set_foreground();
9567 #else
9568 # ifdef WIN32
9569 win32_set_foreground();
9570 # endif
9571 #endif
9575 * "function()" function
9577 /*ARGSUSED*/
9578 static void
9579 f_function(argvars, rettv)
9580 typval_T *argvars;
9581 typval_T *rettv;
9583 char_u *s;
9585 rettv->vval.v_number = 0;
9586 s = get_tv_string(&argvars[0]);
9587 if (s == NULL || *s == NUL || VIM_ISDIGIT(*s))
9588 EMSG2(_(e_invarg2), s);
9589 else if (!function_exists(s))
9590 EMSG2(_("E700: Unknown function: %s"), s);
9591 else
9593 rettv->vval.v_string = vim_strsave(s);
9594 rettv->v_type = VAR_FUNC;
9599 * "garbagecollect()" function
9601 /*ARGSUSED*/
9602 static void
9603 f_garbagecollect(argvars, rettv)
9604 typval_T *argvars;
9605 typval_T *rettv;
9607 garbage_collect();
9611 * "get()" function
9613 static void
9614 f_get(argvars, rettv)
9615 typval_T *argvars;
9616 typval_T *rettv;
9618 listitem_T *li;
9619 list_T *l;
9620 dictitem_T *di;
9621 dict_T *d;
9622 typval_T *tv = NULL;
9624 if (argvars[0].v_type == VAR_LIST)
9626 if ((l = argvars[0].vval.v_list) != NULL)
9628 int error = FALSE;
9630 li = list_find(l, get_tv_number_chk(&argvars[1], &error));
9631 if (!error && li != NULL)
9632 tv = &li->li_tv;
9635 else if (argvars[0].v_type == VAR_DICT)
9637 if ((d = argvars[0].vval.v_dict) != NULL)
9639 di = dict_find(d, get_tv_string(&argvars[1]), -1);
9640 if (di != NULL)
9641 tv = &di->di_tv;
9644 else
9645 EMSG2(_(e_listdictarg), "get()");
9647 if (tv == NULL)
9649 if (argvars[2].v_type == VAR_UNKNOWN)
9650 rettv->vval.v_number = 0;
9651 else
9652 copy_tv(&argvars[2], rettv);
9654 else
9655 copy_tv(tv, rettv);
9658 static void get_buffer_lines __ARGS((buf_T *buf, linenr_T start, linenr_T end, int retlist, typval_T *rettv));
9661 * Get line or list of lines from buffer "buf" into "rettv".
9662 * Return a range (from start to end) of lines in rettv from the specified
9663 * buffer.
9664 * If 'retlist' is TRUE, then the lines are returned as a Vim List.
9666 static void
9667 get_buffer_lines(buf, start, end, retlist, rettv)
9668 buf_T *buf;
9669 linenr_T start;
9670 linenr_T end;
9671 int retlist;
9672 typval_T *rettv;
9674 char_u *p;
9676 if (retlist)
9678 if (rettv_list_alloc(rettv) == FAIL)
9679 return;
9681 else
9682 rettv->vval.v_number = 0;
9684 if (buf == NULL || buf->b_ml.ml_mfp == NULL || start < 0)
9685 return;
9687 if (!retlist)
9689 if (start >= 1 && start <= buf->b_ml.ml_line_count)
9690 p = ml_get_buf(buf, start, FALSE);
9691 else
9692 p = (char_u *)"";
9694 rettv->v_type = VAR_STRING;
9695 rettv->vval.v_string = vim_strsave(p);
9697 else
9699 if (end < start)
9700 return;
9702 if (start < 1)
9703 start = 1;
9704 if (end > buf->b_ml.ml_line_count)
9705 end = buf->b_ml.ml_line_count;
9706 while (start <= end)
9707 if (list_append_string(rettv->vval.v_list,
9708 ml_get_buf(buf, start++, FALSE), -1) == FAIL)
9709 break;
9714 * "getbufline()" function
9716 static void
9717 f_getbufline(argvars, rettv)
9718 typval_T *argvars;
9719 typval_T *rettv;
9721 linenr_T lnum;
9722 linenr_T end;
9723 buf_T *buf;
9725 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
9726 ++emsg_off;
9727 buf = get_buf_tv(&argvars[0]);
9728 --emsg_off;
9730 lnum = get_tv_lnum_buf(&argvars[1], buf);
9731 if (argvars[2].v_type == VAR_UNKNOWN)
9732 end = lnum;
9733 else
9734 end = get_tv_lnum_buf(&argvars[2], buf);
9736 get_buffer_lines(buf, lnum, end, TRUE, rettv);
9740 * "getbufvar()" function
9742 static void
9743 f_getbufvar(argvars, rettv)
9744 typval_T *argvars;
9745 typval_T *rettv;
9747 buf_T *buf;
9748 buf_T *save_curbuf;
9749 char_u *varname;
9750 dictitem_T *v;
9752 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
9753 varname = get_tv_string_chk(&argvars[1]);
9754 ++emsg_off;
9755 buf = get_buf_tv(&argvars[0]);
9757 rettv->v_type = VAR_STRING;
9758 rettv->vval.v_string = NULL;
9760 if (buf != NULL && varname != NULL)
9762 if (*varname == '&') /* buffer-local-option */
9764 /* set curbuf to be our buf, temporarily */
9765 save_curbuf = curbuf;
9766 curbuf = buf;
9768 get_option_tv(&varname, rettv, TRUE);
9770 /* restore previous notion of curbuf */
9771 curbuf = save_curbuf;
9773 else
9775 if (*varname == NUL)
9776 /* let getbufvar({nr}, "") return the "b:" dictionary. The
9777 * scope prefix before the NUL byte is required by
9778 * find_var_in_ht(). */
9779 varname = (char_u *)"b:" + 2;
9780 /* look up the variable */
9781 v = find_var_in_ht(&buf->b_vars.dv_hashtab, varname, FALSE);
9782 if (v != NULL)
9783 copy_tv(&v->di_tv, rettv);
9787 --emsg_off;
9791 * "getchar()" function
9793 static void
9794 f_getchar(argvars, rettv)
9795 typval_T *argvars;
9796 typval_T *rettv;
9798 varnumber_T n;
9799 int error = FALSE;
9801 /* Position the cursor. Needed after a message that ends in a space. */
9802 windgoto(msg_row, msg_col);
9804 ++no_mapping;
9805 ++allow_keys;
9806 if (argvars[0].v_type == VAR_UNKNOWN)
9807 /* getchar(): blocking wait. */
9808 n = safe_vgetc();
9809 else if (get_tv_number_chk(&argvars[0], &error) == 1)
9810 /* getchar(1): only check if char avail */
9811 n = vpeekc();
9812 else if (error || vpeekc() == NUL)
9813 /* illegal argument or getchar(0) and no char avail: return zero */
9814 n = 0;
9815 else
9816 /* getchar(0) and char avail: return char */
9817 n = safe_vgetc();
9818 --no_mapping;
9819 --allow_keys;
9821 rettv->vval.v_number = n;
9822 if (IS_SPECIAL(n) || mod_mask != 0)
9824 char_u temp[10]; /* modifier: 3, mbyte-char: 6, NUL: 1 */
9825 int i = 0;
9827 /* Turn a special key into three bytes, plus modifier. */
9828 if (mod_mask != 0)
9830 temp[i++] = K_SPECIAL;
9831 temp[i++] = KS_MODIFIER;
9832 temp[i++] = mod_mask;
9834 if (IS_SPECIAL(n))
9836 temp[i++] = K_SPECIAL;
9837 temp[i++] = K_SECOND(n);
9838 temp[i++] = K_THIRD(n);
9840 #ifdef FEAT_MBYTE
9841 else if (has_mbyte)
9842 i += (*mb_char2bytes)(n, temp + i);
9843 #endif
9844 else
9845 temp[i++] = n;
9846 temp[i++] = NUL;
9847 rettv->v_type = VAR_STRING;
9848 rettv->vval.v_string = vim_strsave(temp);
9853 * "getcharmod()" function
9855 /*ARGSUSED*/
9856 static void
9857 f_getcharmod(argvars, rettv)
9858 typval_T *argvars;
9859 typval_T *rettv;
9861 rettv->vval.v_number = mod_mask;
9865 * "getcmdline()" function
9867 /*ARGSUSED*/
9868 static void
9869 f_getcmdline(argvars, rettv)
9870 typval_T *argvars;
9871 typval_T *rettv;
9873 rettv->v_type = VAR_STRING;
9874 rettv->vval.v_string = get_cmdline_str();
9878 * "getcmdpos()" function
9880 /*ARGSUSED*/
9881 static void
9882 f_getcmdpos(argvars, rettv)
9883 typval_T *argvars;
9884 typval_T *rettv;
9886 rettv->vval.v_number = get_cmdline_pos() + 1;
9890 * "getcmdtype()" function
9892 /*ARGSUSED*/
9893 static void
9894 f_getcmdtype(argvars, rettv)
9895 typval_T *argvars;
9896 typval_T *rettv;
9898 rettv->v_type = VAR_STRING;
9899 rettv->vval.v_string = alloc(2);
9900 if (rettv->vval.v_string != NULL)
9902 rettv->vval.v_string[0] = get_cmdline_type();
9903 rettv->vval.v_string[1] = NUL;
9908 * "getcwd()" function
9910 /*ARGSUSED*/
9911 static void
9912 f_getcwd(argvars, rettv)
9913 typval_T *argvars;
9914 typval_T *rettv;
9916 char_u cwd[MAXPATHL];
9918 rettv->v_type = VAR_STRING;
9919 if (mch_dirname(cwd, MAXPATHL) == FAIL)
9920 rettv->vval.v_string = NULL;
9921 else
9923 rettv->vval.v_string = vim_strsave(cwd);
9924 #ifdef BACKSLASH_IN_FILENAME
9925 if (rettv->vval.v_string != NULL)
9926 slash_adjust(rettv->vval.v_string);
9927 #endif
9932 * "getfontname()" function
9934 /*ARGSUSED*/
9935 static void
9936 f_getfontname(argvars, rettv)
9937 typval_T *argvars;
9938 typval_T *rettv;
9940 rettv->v_type = VAR_STRING;
9941 rettv->vval.v_string = NULL;
9942 #ifdef FEAT_GUI
9943 if (gui.in_use)
9945 GuiFont font;
9946 char_u *name = NULL;
9948 if (argvars[0].v_type == VAR_UNKNOWN)
9950 /* Get the "Normal" font. Either the name saved by
9951 * hl_set_font_name() or from the font ID. */
9952 font = gui.norm_font;
9953 name = hl_get_font_name();
9955 else
9957 name = get_tv_string(&argvars[0]);
9958 if (STRCMP(name, "*") == 0) /* don't use font dialog */
9959 return;
9960 font = gui_mch_get_font(name, FALSE);
9961 if (font == NOFONT)
9962 return; /* Invalid font name, return empty string. */
9964 rettv->vval.v_string = gui_mch_get_fontname(font, name);
9965 if (argvars[0].v_type != VAR_UNKNOWN)
9966 gui_mch_free_font(font);
9968 #endif
9972 * "getfperm({fname})" function
9974 static void
9975 f_getfperm(argvars, rettv)
9976 typval_T *argvars;
9977 typval_T *rettv;
9979 char_u *fname;
9980 struct stat st;
9981 char_u *perm = NULL;
9982 char_u flags[] = "rwx";
9983 int i;
9985 fname = get_tv_string(&argvars[0]);
9987 rettv->v_type = VAR_STRING;
9988 if (mch_stat((char *)fname, &st) >= 0)
9990 perm = vim_strsave((char_u *)"---------");
9991 if (perm != NULL)
9993 for (i = 0; i < 9; i++)
9995 if (st.st_mode & (1 << (8 - i)))
9996 perm[i] = flags[i % 3];
10000 rettv->vval.v_string = perm;
10004 * "getfsize({fname})" function
10006 static void
10007 f_getfsize(argvars, rettv)
10008 typval_T *argvars;
10009 typval_T *rettv;
10011 char_u *fname;
10012 struct stat st;
10014 fname = get_tv_string(&argvars[0]);
10016 rettv->v_type = VAR_NUMBER;
10018 if (mch_stat((char *)fname, &st) >= 0)
10020 if (mch_isdir(fname))
10021 rettv->vval.v_number = 0;
10022 else
10023 rettv->vval.v_number = (varnumber_T)st.st_size;
10025 else
10026 rettv->vval.v_number = -1;
10030 * "getftime({fname})" function
10032 static void
10033 f_getftime(argvars, rettv)
10034 typval_T *argvars;
10035 typval_T *rettv;
10037 char_u *fname;
10038 struct stat st;
10040 fname = get_tv_string(&argvars[0]);
10042 if (mch_stat((char *)fname, &st) >= 0)
10043 rettv->vval.v_number = (varnumber_T)st.st_mtime;
10044 else
10045 rettv->vval.v_number = -1;
10049 * "getftype({fname})" function
10051 static void
10052 f_getftype(argvars, rettv)
10053 typval_T *argvars;
10054 typval_T *rettv;
10056 char_u *fname;
10057 struct stat st;
10058 char_u *type = NULL;
10059 char *t;
10061 fname = get_tv_string(&argvars[0]);
10063 rettv->v_type = VAR_STRING;
10064 if (mch_lstat((char *)fname, &st) >= 0)
10066 #ifdef S_ISREG
10067 if (S_ISREG(st.st_mode))
10068 t = "file";
10069 else if (S_ISDIR(st.st_mode))
10070 t = "dir";
10071 # ifdef S_ISLNK
10072 else if (S_ISLNK(st.st_mode))
10073 t = "link";
10074 # endif
10075 # ifdef S_ISBLK
10076 else if (S_ISBLK(st.st_mode))
10077 t = "bdev";
10078 # endif
10079 # ifdef S_ISCHR
10080 else if (S_ISCHR(st.st_mode))
10081 t = "cdev";
10082 # endif
10083 # ifdef S_ISFIFO
10084 else if (S_ISFIFO(st.st_mode))
10085 t = "fifo";
10086 # endif
10087 # ifdef S_ISSOCK
10088 else if (S_ISSOCK(st.st_mode))
10089 t = "fifo";
10090 # endif
10091 else
10092 t = "other";
10093 #else
10094 # ifdef S_IFMT
10095 switch (st.st_mode & S_IFMT)
10097 case S_IFREG: t = "file"; break;
10098 case S_IFDIR: t = "dir"; break;
10099 # ifdef S_IFLNK
10100 case S_IFLNK: t = "link"; break;
10101 # endif
10102 # ifdef S_IFBLK
10103 case S_IFBLK: t = "bdev"; break;
10104 # endif
10105 # ifdef S_IFCHR
10106 case S_IFCHR: t = "cdev"; break;
10107 # endif
10108 # ifdef S_IFIFO
10109 case S_IFIFO: t = "fifo"; break;
10110 # endif
10111 # ifdef S_IFSOCK
10112 case S_IFSOCK: t = "socket"; break;
10113 # endif
10114 default: t = "other";
10116 # else
10117 if (mch_isdir(fname))
10118 t = "dir";
10119 else
10120 t = "file";
10121 # endif
10122 #endif
10123 type = vim_strsave((char_u *)t);
10125 rettv->vval.v_string = type;
10129 * "getline(lnum, [end])" function
10131 static void
10132 f_getline(argvars, rettv)
10133 typval_T *argvars;
10134 typval_T *rettv;
10136 linenr_T lnum;
10137 linenr_T end;
10138 int retlist;
10140 lnum = get_tv_lnum(argvars);
10141 if (argvars[1].v_type == VAR_UNKNOWN)
10143 end = 0;
10144 retlist = FALSE;
10146 else
10148 end = get_tv_lnum(&argvars[1]);
10149 retlist = TRUE;
10152 get_buffer_lines(curbuf, lnum, end, retlist, rettv);
10156 * "getpos(string)" function
10158 static void
10159 f_getpos(argvars, rettv)
10160 typval_T *argvars;
10161 typval_T *rettv;
10163 pos_T *fp;
10164 list_T *l;
10165 int fnum = -1;
10167 if (rettv_list_alloc(rettv) == OK)
10169 l = rettv->vval.v_list;
10170 fp = var2fpos(&argvars[0], TRUE, &fnum);
10171 if (fnum != -1)
10172 list_append_number(l, (varnumber_T)fnum);
10173 else
10174 list_append_number(l, (varnumber_T)0);
10175 list_append_number(l, (fp != NULL) ? (varnumber_T)fp->lnum
10176 : (varnumber_T)0);
10177 list_append_number(l, (fp != NULL) ? (varnumber_T)fp->col + 1
10178 : (varnumber_T)0);
10179 list_append_number(l,
10180 #ifdef FEAT_VIRTUALEDIT
10181 (fp != NULL) ? (varnumber_T)fp->coladd :
10182 #endif
10183 (varnumber_T)0);
10185 else
10186 rettv->vval.v_number = FALSE;
10190 * "getqflist()" and "getloclist()" functions
10192 /*ARGSUSED*/
10193 static void
10194 f_getqflist(argvars, rettv)
10195 typval_T *argvars;
10196 typval_T *rettv;
10198 #ifdef FEAT_QUICKFIX
10199 win_T *wp;
10200 #endif
10202 rettv->vval.v_number = FALSE;
10203 #ifdef FEAT_QUICKFIX
10204 if (rettv_list_alloc(rettv) == OK)
10206 wp = NULL;
10207 if (argvars[0].v_type != VAR_UNKNOWN) /* getloclist() */
10209 wp = find_win_by_nr(&argvars[0], NULL);
10210 if (wp == NULL)
10211 return;
10214 (void)get_errorlist(wp, rettv->vval.v_list);
10216 #endif
10220 * "getreg()" function
10222 static void
10223 f_getreg(argvars, rettv)
10224 typval_T *argvars;
10225 typval_T *rettv;
10227 char_u *strregname;
10228 int regname;
10229 int arg2 = FALSE;
10230 int error = FALSE;
10232 if (argvars[0].v_type != VAR_UNKNOWN)
10234 strregname = get_tv_string_chk(&argvars[0]);
10235 error = strregname == NULL;
10236 if (argvars[1].v_type != VAR_UNKNOWN)
10237 arg2 = get_tv_number_chk(&argvars[1], &error);
10239 else
10240 strregname = vimvars[VV_REG].vv_str;
10241 regname = (strregname == NULL ? '"' : *strregname);
10242 if (regname == 0)
10243 regname = '"';
10245 rettv->v_type = VAR_STRING;
10246 rettv->vval.v_string = error ? NULL :
10247 get_reg_contents(regname, TRUE, arg2);
10251 * "getregtype()" function
10253 static void
10254 f_getregtype(argvars, rettv)
10255 typval_T *argvars;
10256 typval_T *rettv;
10258 char_u *strregname;
10259 int regname;
10260 char_u buf[NUMBUFLEN + 2];
10261 long reglen = 0;
10263 if (argvars[0].v_type != VAR_UNKNOWN)
10265 strregname = get_tv_string_chk(&argvars[0]);
10266 if (strregname == NULL) /* type error; errmsg already given */
10268 rettv->v_type = VAR_STRING;
10269 rettv->vval.v_string = NULL;
10270 return;
10273 else
10274 /* Default to v:register */
10275 strregname = vimvars[VV_REG].vv_str;
10277 regname = (strregname == NULL ? '"' : *strregname);
10278 if (regname == 0)
10279 regname = '"';
10281 buf[0] = NUL;
10282 buf[1] = NUL;
10283 switch (get_reg_type(regname, &reglen))
10285 case MLINE: buf[0] = 'V'; break;
10286 case MCHAR: buf[0] = 'v'; break;
10287 #ifdef FEAT_VISUAL
10288 case MBLOCK:
10289 buf[0] = Ctrl_V;
10290 sprintf((char *)buf + 1, "%ld", reglen + 1);
10291 break;
10292 #endif
10294 rettv->v_type = VAR_STRING;
10295 rettv->vval.v_string = vim_strsave(buf);
10299 * "gettabwinvar()" function
10301 static void
10302 f_gettabwinvar(argvars, rettv)
10303 typval_T *argvars;
10304 typval_T *rettv;
10306 getwinvar(argvars, rettv, 1);
10310 * "getwinposx()" function
10312 /*ARGSUSED*/
10313 static void
10314 f_getwinposx(argvars, rettv)
10315 typval_T *argvars;
10316 typval_T *rettv;
10318 rettv->vval.v_number = -1;
10319 #ifdef FEAT_GUI
10320 if (gui.in_use)
10322 int x, y;
10324 if (gui_mch_get_winpos(&x, &y) == OK)
10325 rettv->vval.v_number = x;
10327 #endif
10331 * "getwinposy()" function
10333 /*ARGSUSED*/
10334 static void
10335 f_getwinposy(argvars, rettv)
10336 typval_T *argvars;
10337 typval_T *rettv;
10339 rettv->vval.v_number = -1;
10340 #ifdef FEAT_GUI
10341 if (gui.in_use)
10343 int x, y;
10345 if (gui_mch_get_winpos(&x, &y) == OK)
10346 rettv->vval.v_number = y;
10348 #endif
10352 * Find window specifed by "vp" in tabpage "tp".
10354 static win_T *
10355 find_win_by_nr(vp, tp)
10356 typval_T *vp;
10357 tabpage_T *tp; /* NULL for current tab page */
10359 #ifdef FEAT_WINDOWS
10360 win_T *wp;
10361 #endif
10362 int nr;
10364 nr = get_tv_number_chk(vp, NULL);
10366 #ifdef FEAT_WINDOWS
10367 if (nr < 0)
10368 return NULL;
10369 if (nr == 0)
10370 return curwin;
10372 for (wp = (tp == NULL || tp == curtab) ? firstwin : tp->tp_firstwin;
10373 wp != NULL; wp = wp->w_next)
10374 if (--nr <= 0)
10375 break;
10376 return wp;
10377 #else
10378 if (nr == 0 || nr == 1)
10379 return curwin;
10380 return NULL;
10381 #endif
10385 * "getwinvar()" function
10387 static void
10388 f_getwinvar(argvars, rettv)
10389 typval_T *argvars;
10390 typval_T *rettv;
10392 getwinvar(argvars, rettv, 0);
10396 * getwinvar() and gettabwinvar()
10398 static void
10399 getwinvar(argvars, rettv, off)
10400 typval_T *argvars;
10401 typval_T *rettv;
10402 int off; /* 1 for gettabwinvar() */
10404 win_T *win, *oldcurwin;
10405 char_u *varname;
10406 dictitem_T *v;
10407 tabpage_T *tp;
10409 #ifdef FEAT_WINDOWS
10410 if (off == 1)
10411 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
10412 else
10413 tp = curtab;
10414 #endif
10415 win = find_win_by_nr(&argvars[off], tp);
10416 varname = get_tv_string_chk(&argvars[off + 1]);
10417 ++emsg_off;
10419 rettv->v_type = VAR_STRING;
10420 rettv->vval.v_string = NULL;
10422 if (win != NULL && varname != NULL)
10424 if (*varname == '&') /* window-local-option */
10426 /* Set curwin to be our win, temporarily. Also set curbuf, so
10427 * that we can get buffer-local options. */
10428 oldcurwin = curwin;
10429 curwin = win;
10430 curbuf = win->w_buffer;
10432 get_option_tv(&varname, rettv, 1);
10434 /* restore previous notion of curwin */
10435 curwin = oldcurwin;
10436 curbuf = curwin->w_buffer;
10438 else
10440 if (*varname == NUL)
10441 /* let getwinvar({nr}, "") return the "w:" dictionary. The
10442 * scope prefix before the NUL byte is required by
10443 * find_var_in_ht(). */
10444 varname = (char_u *)"w:" + 2;
10445 /* look up the variable */
10446 v = find_var_in_ht(&win->w_vars.dv_hashtab, varname, FALSE);
10447 if (v != NULL)
10448 copy_tv(&v->di_tv, rettv);
10452 --emsg_off;
10456 * "glob()" function
10458 static void
10459 f_glob(argvars, rettv)
10460 typval_T *argvars;
10461 typval_T *rettv;
10463 expand_T xpc;
10465 ExpandInit(&xpc);
10466 xpc.xp_context = EXPAND_FILES;
10467 rettv->v_type = VAR_STRING;
10468 rettv->vval.v_string = ExpandOne(&xpc, get_tv_string(&argvars[0]),
10469 NULL, WILD_USE_NL|WILD_SILENT, WILD_ALL);
10473 * "globpath()" function
10475 static void
10476 f_globpath(argvars, rettv)
10477 typval_T *argvars;
10478 typval_T *rettv;
10480 char_u buf1[NUMBUFLEN];
10481 char_u *file = get_tv_string_buf_chk(&argvars[1], buf1);
10483 rettv->v_type = VAR_STRING;
10484 if (file == NULL)
10485 rettv->vval.v_string = NULL;
10486 else
10487 rettv->vval.v_string = globpath(get_tv_string(&argvars[0]), file);
10491 * "has()" function
10493 static void
10494 f_has(argvars, rettv)
10495 typval_T *argvars;
10496 typval_T *rettv;
10498 int i;
10499 char_u *name;
10500 int n = FALSE;
10501 static char *(has_list[]) =
10503 #ifdef AMIGA
10504 "amiga",
10505 # ifdef FEAT_ARP
10506 "arp",
10507 # endif
10508 #endif
10509 #ifdef __BEOS__
10510 "beos",
10511 #endif
10512 #ifdef MSDOS
10513 # ifdef DJGPP
10514 "dos32",
10515 # else
10516 "dos16",
10517 # endif
10518 #endif
10519 #ifdef MACOS
10520 "mac",
10521 #endif
10522 #if defined(MACOS_X_UNIX)
10523 "macunix",
10524 #endif
10525 #ifdef OS2
10526 "os2",
10527 #endif
10528 #ifdef __QNX__
10529 "qnx",
10530 #endif
10531 #ifdef RISCOS
10532 "riscos",
10533 #endif
10534 #ifdef UNIX
10535 "unix",
10536 #endif
10537 #ifdef VMS
10538 "vms",
10539 #endif
10540 #ifdef WIN16
10541 "win16",
10542 #endif
10543 #ifdef WIN32
10544 "win32",
10545 #endif
10546 #if defined(UNIX) && (defined(__CYGWIN32__) || defined(__CYGWIN__))
10547 "win32unix",
10548 #endif
10549 #ifdef WIN64
10550 "win64",
10551 #endif
10552 #ifdef EBCDIC
10553 "ebcdic",
10554 #endif
10555 #ifndef CASE_INSENSITIVE_FILENAME
10556 "fname_case",
10557 #endif
10558 #ifdef FEAT_ARABIC
10559 "arabic",
10560 #endif
10561 #ifdef FEAT_AUTOCMD
10562 "autocmd",
10563 #endif
10564 #ifdef FEAT_BEVAL
10565 "balloon_eval",
10566 # ifndef FEAT_GUI_W32 /* other GUIs always have multiline balloons */
10567 "balloon_multiline",
10568 # endif
10569 #endif
10570 #if defined(SOME_BUILTIN_TCAPS) || defined(ALL_BUILTIN_TCAPS)
10571 "builtin_terms",
10572 # ifdef ALL_BUILTIN_TCAPS
10573 "all_builtin_terms",
10574 # endif
10575 #endif
10576 #ifdef FEAT_BYTEOFF
10577 "byte_offset",
10578 #endif
10579 #ifdef FEAT_CINDENT
10580 "cindent",
10581 #endif
10582 #ifdef FEAT_CLIENTSERVER
10583 "clientserver",
10584 #endif
10585 #ifdef FEAT_CLIPBOARD
10586 "clipboard",
10587 #endif
10588 #ifdef FEAT_CMDL_COMPL
10589 "cmdline_compl",
10590 #endif
10591 #ifdef FEAT_CMDHIST
10592 "cmdline_hist",
10593 #endif
10594 #ifdef FEAT_COMMENTS
10595 "comments",
10596 #endif
10597 #ifdef FEAT_CRYPT
10598 "cryptv",
10599 #endif
10600 #ifdef FEAT_CSCOPE
10601 "cscope",
10602 #endif
10603 #ifdef CURSOR_SHAPE
10604 "cursorshape",
10605 #endif
10606 #ifdef DEBUG
10607 "debug",
10608 #endif
10609 #ifdef FEAT_CON_DIALOG
10610 "dialog_con",
10611 #endif
10612 #ifdef FEAT_GUI_DIALOG
10613 "dialog_gui",
10614 #endif
10615 #ifdef FEAT_DIFF
10616 "diff",
10617 #endif
10618 #ifdef FEAT_DIGRAPHS
10619 "digraphs",
10620 #endif
10621 #ifdef FEAT_DND
10622 "dnd",
10623 #endif
10624 #ifdef FEAT_EMACS_TAGS
10625 "emacs_tags",
10626 #endif
10627 "eval", /* always present, of course! */
10628 #ifdef FEAT_EX_EXTRA
10629 "ex_extra",
10630 #endif
10631 #ifdef FEAT_SEARCH_EXTRA
10632 "extra_search",
10633 #endif
10634 #ifdef FEAT_FKMAP
10635 "farsi",
10636 #endif
10637 #ifdef FEAT_SEARCHPATH
10638 "file_in_path",
10639 #endif
10640 #if defined(UNIX) && !defined(USE_SYSTEM)
10641 "filterpipe",
10642 #endif
10643 #ifdef FEAT_FIND_ID
10644 "find_in_path",
10645 #endif
10646 #ifdef FEAT_FOLDING
10647 "folding",
10648 #endif
10649 #ifdef FEAT_FOOTER
10650 "footer",
10651 #endif
10652 #if !defined(USE_SYSTEM) && defined(UNIX)
10653 "fork",
10654 #endif
10655 #ifdef FEAT_GETTEXT
10656 "gettext",
10657 #endif
10658 #ifdef FEAT_GUI
10659 "gui",
10660 #endif
10661 #ifdef FEAT_GUI_ATHENA
10662 # ifdef FEAT_GUI_NEXTAW
10663 "gui_neXtaw",
10664 # else
10665 "gui_athena",
10666 # endif
10667 #endif
10668 #ifdef FEAT_GUI_GTK
10669 "gui_gtk",
10670 # ifdef HAVE_GTK2
10671 "gui_gtk2",
10672 # endif
10673 #endif
10674 #ifdef FEAT_GUI_MAC
10675 "gui_mac",
10676 #endif
10677 #ifdef FEAT_GUI_MOTIF
10678 "gui_motif",
10679 #endif
10680 #ifdef FEAT_GUI_PHOTON
10681 "gui_photon",
10682 #endif
10683 #ifdef FEAT_GUI_W16
10684 "gui_win16",
10685 #endif
10686 #ifdef FEAT_GUI_W32
10687 "gui_win32",
10688 #endif
10689 #ifdef FEAT_HANGULIN
10690 "hangul_input",
10691 #endif
10692 #if defined(HAVE_ICONV_H) && defined(USE_ICONV)
10693 "iconv",
10694 #endif
10695 #ifdef FEAT_INS_EXPAND
10696 "insert_expand",
10697 #endif
10698 #ifdef FEAT_JUMPLIST
10699 "jumplist",
10700 #endif
10701 #ifdef FEAT_KEYMAP
10702 "keymap",
10703 #endif
10704 #ifdef FEAT_LANGMAP
10705 "langmap",
10706 #endif
10707 #ifdef FEAT_LIBCALL
10708 "libcall",
10709 #endif
10710 #ifdef FEAT_LINEBREAK
10711 "linebreak",
10712 #endif
10713 #ifdef FEAT_LISP
10714 "lispindent",
10715 #endif
10716 #ifdef FEAT_LISTCMDS
10717 "listcmds",
10718 #endif
10719 #ifdef FEAT_LOCALMAP
10720 "localmap",
10721 #endif
10722 #ifdef FEAT_MENU
10723 "menu",
10724 #endif
10725 #ifdef FEAT_SESSION
10726 "mksession",
10727 #endif
10728 #ifdef FEAT_MODIFY_FNAME
10729 "modify_fname",
10730 #endif
10731 #ifdef FEAT_MOUSE
10732 "mouse",
10733 #endif
10734 #ifdef FEAT_MOUSESHAPE
10735 "mouseshape",
10736 #endif
10737 #if defined(UNIX) || defined(VMS)
10738 # ifdef FEAT_MOUSE_DEC
10739 "mouse_dec",
10740 # endif
10741 # ifdef FEAT_MOUSE_GPM
10742 "mouse_gpm",
10743 # endif
10744 # ifdef FEAT_MOUSE_JSB
10745 "mouse_jsbterm",
10746 # endif
10747 # ifdef FEAT_MOUSE_NET
10748 "mouse_netterm",
10749 # endif
10750 # ifdef FEAT_MOUSE_PTERM
10751 "mouse_pterm",
10752 # endif
10753 # ifdef FEAT_MOUSE_XTERM
10754 "mouse_xterm",
10755 # endif
10756 #endif
10757 #ifdef FEAT_MBYTE
10758 "multi_byte",
10759 #endif
10760 #ifdef FEAT_MBYTE_IME
10761 "multi_byte_ime",
10762 #endif
10763 #ifdef FEAT_MULTI_LANG
10764 "multi_lang",
10765 #endif
10766 #ifdef FEAT_MZSCHEME
10767 #ifndef DYNAMIC_MZSCHEME
10768 "mzscheme",
10769 #endif
10770 #endif
10771 #ifdef FEAT_OLE
10772 "ole",
10773 #endif
10774 #ifdef FEAT_OSFILETYPE
10775 "osfiletype",
10776 #endif
10777 #ifdef FEAT_PATH_EXTRA
10778 "path_extra",
10779 #endif
10780 #ifdef FEAT_PERL
10781 #ifndef DYNAMIC_PERL
10782 "perl",
10783 #endif
10784 #endif
10785 #ifdef FEAT_PYTHON
10786 #ifndef DYNAMIC_PYTHON
10787 "python",
10788 #endif
10789 #endif
10790 #ifdef FEAT_POSTSCRIPT
10791 "postscript",
10792 #endif
10793 #ifdef FEAT_PRINTER
10794 "printer",
10795 #endif
10796 #ifdef FEAT_PROFILE
10797 "profile",
10798 #endif
10799 #ifdef FEAT_RELTIME
10800 "reltime",
10801 #endif
10802 #ifdef FEAT_QUICKFIX
10803 "quickfix",
10804 #endif
10805 #ifdef FEAT_RIGHTLEFT
10806 "rightleft",
10807 #endif
10808 #if defined(FEAT_RUBY) && !defined(DYNAMIC_RUBY)
10809 "ruby",
10810 #endif
10811 #ifdef FEAT_SCROLLBIND
10812 "scrollbind",
10813 #endif
10814 #ifdef FEAT_CMDL_INFO
10815 "showcmd",
10816 "cmdline_info",
10817 #endif
10818 #ifdef FEAT_SIGNS
10819 "signs",
10820 #endif
10821 #ifdef FEAT_SMARTINDENT
10822 "smartindent",
10823 #endif
10824 #ifdef FEAT_SNIFF
10825 "sniff",
10826 #endif
10827 #ifdef FEAT_STL_OPT
10828 "statusline",
10829 #endif
10830 #ifdef FEAT_SUN_WORKSHOP
10831 "sun_workshop",
10832 #endif
10833 #ifdef FEAT_NETBEANS_INTG
10834 "netbeans_intg",
10835 #endif
10836 #ifdef FEAT_SPELL
10837 "spell",
10838 #endif
10839 #ifdef FEAT_SYN_HL
10840 "syntax",
10841 #endif
10842 #if defined(USE_SYSTEM) || !defined(UNIX)
10843 "system",
10844 #endif
10845 #ifdef FEAT_TAG_BINS
10846 "tag_binary",
10847 #endif
10848 #ifdef FEAT_TAG_OLDSTATIC
10849 "tag_old_static",
10850 #endif
10851 #ifdef FEAT_TAG_ANYWHITE
10852 "tag_any_white",
10853 #endif
10854 #ifdef FEAT_TCL
10855 # ifndef DYNAMIC_TCL
10856 "tcl",
10857 # endif
10858 #endif
10859 #ifdef TERMINFO
10860 "terminfo",
10861 #endif
10862 #ifdef FEAT_TERMRESPONSE
10863 "termresponse",
10864 #endif
10865 #ifdef FEAT_TEXTOBJ
10866 "textobjects",
10867 #endif
10868 #ifdef HAVE_TGETENT
10869 "tgetent",
10870 #endif
10871 #ifdef FEAT_TITLE
10872 "title",
10873 #endif
10874 #ifdef FEAT_TOOLBAR
10875 "toolbar",
10876 #endif
10877 #ifdef FEAT_USR_CMDS
10878 "user-commands", /* was accidentally included in 5.4 */
10879 "user_commands",
10880 #endif
10881 #ifdef FEAT_VIMINFO
10882 "viminfo",
10883 #endif
10884 #ifdef FEAT_VERTSPLIT
10885 "vertsplit",
10886 #endif
10887 #ifdef FEAT_VIRTUALEDIT
10888 "virtualedit",
10889 #endif
10890 #ifdef FEAT_VISUAL
10891 "visual",
10892 #endif
10893 #ifdef FEAT_VISUALEXTRA
10894 "visualextra",
10895 #endif
10896 #ifdef FEAT_VREPLACE
10897 "vreplace",
10898 #endif
10899 #ifdef FEAT_WILDIGN
10900 "wildignore",
10901 #endif
10902 #ifdef FEAT_WILDMENU
10903 "wildmenu",
10904 #endif
10905 #ifdef FEAT_WINDOWS
10906 "windows",
10907 #endif
10908 #ifdef FEAT_WAK
10909 "winaltkeys",
10910 #endif
10911 #ifdef FEAT_WRITEBACKUP
10912 "writebackup",
10913 #endif
10914 #ifdef FEAT_XIM
10915 "xim",
10916 #endif
10917 #ifdef FEAT_XFONTSET
10918 "xfontset",
10919 #endif
10920 #ifdef USE_XSMP
10921 "xsmp",
10922 #endif
10923 #ifdef USE_XSMP_INTERACT
10924 "xsmp_interact",
10925 #endif
10926 #ifdef FEAT_XCLIPBOARD
10927 "xterm_clipboard",
10928 #endif
10929 #ifdef FEAT_XTERM_SAVE
10930 "xterm_save",
10931 #endif
10932 #if defined(UNIX) && defined(FEAT_X11)
10933 "X11",
10934 #endif
10935 NULL
10938 name = get_tv_string(&argvars[0]);
10939 for (i = 0; has_list[i] != NULL; ++i)
10940 if (STRICMP(name, has_list[i]) == 0)
10942 n = TRUE;
10943 break;
10946 if (n == FALSE)
10948 if (STRNICMP(name, "patch", 5) == 0)
10949 n = has_patch(atoi((char *)name + 5));
10950 else if (STRICMP(name, "vim_starting") == 0)
10951 n = (starting != 0);
10952 #if defined(FEAT_BEVAL) && defined(FEAT_GUI_W32)
10953 else if (STRICMP(name, "balloon_multiline") == 0)
10954 n = multiline_balloon_available();
10955 #endif
10956 #ifdef DYNAMIC_TCL
10957 else if (STRICMP(name, "tcl") == 0)
10958 n = tcl_enabled(FALSE);
10959 #endif
10960 #if defined(USE_ICONV) && defined(DYNAMIC_ICONV)
10961 else if (STRICMP(name, "iconv") == 0)
10962 n = iconv_enabled(FALSE);
10963 #endif
10964 #ifdef DYNAMIC_MZSCHEME
10965 else if (STRICMP(name, "mzscheme") == 0)
10966 n = mzscheme_enabled(FALSE);
10967 #endif
10968 #ifdef DYNAMIC_RUBY
10969 else if (STRICMP(name, "ruby") == 0)
10970 n = ruby_enabled(FALSE);
10971 #endif
10972 #ifdef DYNAMIC_PYTHON
10973 else if (STRICMP(name, "python") == 0)
10974 n = python_enabled(FALSE);
10975 #endif
10976 #ifdef DYNAMIC_PERL
10977 else if (STRICMP(name, "perl") == 0)
10978 n = perl_enabled(FALSE);
10979 #endif
10980 #ifdef FEAT_GUI
10981 else if (STRICMP(name, "gui_running") == 0)
10982 n = (gui.in_use || gui.starting);
10983 # ifdef FEAT_GUI_W32
10984 else if (STRICMP(name, "gui_win32s") == 0)
10985 n = gui_is_win32s();
10986 # endif
10987 # ifdef FEAT_BROWSE
10988 else if (STRICMP(name, "browse") == 0)
10989 n = gui.in_use; /* gui_mch_browse() works when GUI is running */
10990 # endif
10991 #endif
10992 #ifdef FEAT_SYN_HL
10993 else if (STRICMP(name, "syntax_items") == 0)
10994 n = syntax_present(curbuf);
10995 #endif
10996 #if defined(WIN3264)
10997 else if (STRICMP(name, "win95") == 0)
10998 n = mch_windows95();
10999 #endif
11000 #ifdef FEAT_NETBEANS_INTG
11001 else if (STRICMP(name, "netbeans_enabled") == 0)
11002 n = usingNetbeans;
11003 #endif
11006 rettv->vval.v_number = n;
11010 * "has_key()" function
11012 static void
11013 f_has_key(argvars, rettv)
11014 typval_T *argvars;
11015 typval_T *rettv;
11017 rettv->vval.v_number = 0;
11018 if (argvars[0].v_type != VAR_DICT)
11020 EMSG(_(e_dictreq));
11021 return;
11023 if (argvars[0].vval.v_dict == NULL)
11024 return;
11026 rettv->vval.v_number = dict_find(argvars[0].vval.v_dict,
11027 get_tv_string(&argvars[1]), -1) != NULL;
11031 * "hasmapto()" function
11033 static void
11034 f_hasmapto(argvars, rettv)
11035 typval_T *argvars;
11036 typval_T *rettv;
11038 char_u *name;
11039 char_u *mode;
11040 char_u buf[NUMBUFLEN];
11041 int abbr = FALSE;
11043 name = get_tv_string(&argvars[0]);
11044 if (argvars[1].v_type == VAR_UNKNOWN)
11045 mode = (char_u *)"nvo";
11046 else
11048 mode = get_tv_string_buf(&argvars[1], buf);
11049 if (argvars[2].v_type != VAR_UNKNOWN)
11050 abbr = get_tv_number(&argvars[2]);
11053 if (map_to_exists(name, mode, abbr))
11054 rettv->vval.v_number = TRUE;
11055 else
11056 rettv->vval.v_number = FALSE;
11060 * "histadd()" function
11062 /*ARGSUSED*/
11063 static void
11064 f_histadd(argvars, rettv)
11065 typval_T *argvars;
11066 typval_T *rettv;
11068 #ifdef FEAT_CMDHIST
11069 int histype;
11070 char_u *str;
11071 char_u buf[NUMBUFLEN];
11072 #endif
11074 rettv->vval.v_number = FALSE;
11075 if (check_restricted() || check_secure())
11076 return;
11077 #ifdef FEAT_CMDHIST
11078 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
11079 histype = str != NULL ? get_histtype(str) : -1;
11080 if (histype >= 0)
11082 str = get_tv_string_buf(&argvars[1], buf);
11083 if (*str != NUL)
11085 add_to_history(histype, str, FALSE, NUL);
11086 rettv->vval.v_number = TRUE;
11087 return;
11090 #endif
11094 * "histdel()" function
11096 /*ARGSUSED*/
11097 static void
11098 f_histdel(argvars, rettv)
11099 typval_T *argvars;
11100 typval_T *rettv;
11102 #ifdef FEAT_CMDHIST
11103 int n;
11104 char_u buf[NUMBUFLEN];
11105 char_u *str;
11107 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
11108 if (str == NULL)
11109 n = 0;
11110 else if (argvars[1].v_type == VAR_UNKNOWN)
11111 /* only one argument: clear entire history */
11112 n = clr_history(get_histtype(str));
11113 else if (argvars[1].v_type == VAR_NUMBER)
11114 /* index given: remove that entry */
11115 n = del_history_idx(get_histtype(str),
11116 (int)get_tv_number(&argvars[1]));
11117 else
11118 /* string given: remove all matching entries */
11119 n = del_history_entry(get_histtype(str),
11120 get_tv_string_buf(&argvars[1], buf));
11121 rettv->vval.v_number = n;
11122 #else
11123 rettv->vval.v_number = 0;
11124 #endif
11128 * "histget()" function
11130 /*ARGSUSED*/
11131 static void
11132 f_histget(argvars, rettv)
11133 typval_T *argvars;
11134 typval_T *rettv;
11136 #ifdef FEAT_CMDHIST
11137 int type;
11138 int idx;
11139 char_u *str;
11141 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
11142 if (str == NULL)
11143 rettv->vval.v_string = NULL;
11144 else
11146 type = get_histtype(str);
11147 if (argvars[1].v_type == VAR_UNKNOWN)
11148 idx = get_history_idx(type);
11149 else
11150 idx = (int)get_tv_number_chk(&argvars[1], NULL);
11151 /* -1 on type error */
11152 rettv->vval.v_string = vim_strsave(get_history_entry(type, idx));
11154 #else
11155 rettv->vval.v_string = NULL;
11156 #endif
11157 rettv->v_type = VAR_STRING;
11161 * "histnr()" function
11163 /*ARGSUSED*/
11164 static void
11165 f_histnr(argvars, rettv)
11166 typval_T *argvars;
11167 typval_T *rettv;
11169 int i;
11171 #ifdef FEAT_CMDHIST
11172 char_u *history = get_tv_string_chk(&argvars[0]);
11174 i = history == NULL ? HIST_CMD - 1 : get_histtype(history);
11175 if (i >= HIST_CMD && i < HIST_COUNT)
11176 i = get_history_idx(i);
11177 else
11178 #endif
11179 i = -1;
11180 rettv->vval.v_number = i;
11184 * "highlightID(name)" function
11186 static void
11187 f_hlID(argvars, rettv)
11188 typval_T *argvars;
11189 typval_T *rettv;
11191 rettv->vval.v_number = syn_name2id(get_tv_string(&argvars[0]));
11195 * "highlight_exists()" function
11197 static void
11198 f_hlexists(argvars, rettv)
11199 typval_T *argvars;
11200 typval_T *rettv;
11202 rettv->vval.v_number = highlight_exists(get_tv_string(&argvars[0]));
11206 * "hostname()" function
11208 /*ARGSUSED*/
11209 static void
11210 f_hostname(argvars, rettv)
11211 typval_T *argvars;
11212 typval_T *rettv;
11214 char_u hostname[256];
11216 mch_get_host_name(hostname, 256);
11217 rettv->v_type = VAR_STRING;
11218 rettv->vval.v_string = vim_strsave(hostname);
11222 * iconv() function
11224 /*ARGSUSED*/
11225 static void
11226 f_iconv(argvars, rettv)
11227 typval_T *argvars;
11228 typval_T *rettv;
11230 #ifdef FEAT_MBYTE
11231 char_u buf1[NUMBUFLEN];
11232 char_u buf2[NUMBUFLEN];
11233 char_u *from, *to, *str;
11234 vimconv_T vimconv;
11235 #endif
11237 rettv->v_type = VAR_STRING;
11238 rettv->vval.v_string = NULL;
11240 #ifdef FEAT_MBYTE
11241 str = get_tv_string(&argvars[0]);
11242 from = enc_canonize(enc_skip(get_tv_string_buf(&argvars[1], buf1)));
11243 to = enc_canonize(enc_skip(get_tv_string_buf(&argvars[2], buf2)));
11244 vimconv.vc_type = CONV_NONE;
11245 convert_setup(&vimconv, from, to);
11247 /* If the encodings are equal, no conversion needed. */
11248 if (vimconv.vc_type == CONV_NONE)
11249 rettv->vval.v_string = vim_strsave(str);
11250 else
11251 rettv->vval.v_string = string_convert(&vimconv, str, NULL);
11253 convert_setup(&vimconv, NULL, NULL);
11254 vim_free(from);
11255 vim_free(to);
11256 #endif
11260 * "indent()" function
11262 static void
11263 f_indent(argvars, rettv)
11264 typval_T *argvars;
11265 typval_T *rettv;
11267 linenr_T lnum;
11269 lnum = get_tv_lnum(argvars);
11270 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
11271 rettv->vval.v_number = get_indent_lnum(lnum);
11272 else
11273 rettv->vval.v_number = -1;
11277 * "index()" function
11279 static void
11280 f_index(argvars, rettv)
11281 typval_T *argvars;
11282 typval_T *rettv;
11284 list_T *l;
11285 listitem_T *item;
11286 long idx = 0;
11287 int ic = FALSE;
11289 rettv->vval.v_number = -1;
11290 if (argvars[0].v_type != VAR_LIST)
11292 EMSG(_(e_listreq));
11293 return;
11295 l = argvars[0].vval.v_list;
11296 if (l != NULL)
11298 item = l->lv_first;
11299 if (argvars[2].v_type != VAR_UNKNOWN)
11301 int error = FALSE;
11303 /* Start at specified item. Use the cached index that list_find()
11304 * sets, so that a negative number also works. */
11305 item = list_find(l, get_tv_number_chk(&argvars[2], &error));
11306 idx = l->lv_idx;
11307 if (argvars[3].v_type != VAR_UNKNOWN)
11308 ic = get_tv_number_chk(&argvars[3], &error);
11309 if (error)
11310 item = NULL;
11313 for ( ; item != NULL; item = item->li_next, ++idx)
11314 if (tv_equal(&item->li_tv, &argvars[1], ic))
11316 rettv->vval.v_number = idx;
11317 break;
11322 static int inputsecret_flag = 0;
11324 static void get_user_input __ARGS((typval_T *argvars, typval_T *rettv, int inputdialog));
11327 * This function is used by f_input() and f_inputdialog() functions. The third
11328 * argument to f_input() specifies the type of completion to use at the
11329 * prompt. The third argument to f_inputdialog() specifies the value to return
11330 * when the user cancels the prompt.
11332 static void
11333 get_user_input(argvars, rettv, inputdialog)
11334 typval_T *argvars;
11335 typval_T *rettv;
11336 int inputdialog;
11338 char_u *prompt = get_tv_string_chk(&argvars[0]);
11339 char_u *p = NULL;
11340 int c;
11341 char_u buf[NUMBUFLEN];
11342 int cmd_silent_save = cmd_silent;
11343 char_u *defstr = (char_u *)"";
11344 int xp_type = EXPAND_NOTHING;
11345 char_u *xp_arg = NULL;
11347 rettv->v_type = VAR_STRING;
11349 #ifdef NO_CONSOLE_INPUT
11350 /* While starting up, there is no place to enter text. */
11351 if (no_console_input())
11353 rettv->vval.v_string = NULL;
11354 return;
11356 #endif
11358 cmd_silent = FALSE; /* Want to see the prompt. */
11359 if (prompt != NULL)
11361 /* Only the part of the message after the last NL is considered as
11362 * prompt for the command line */
11363 p = vim_strrchr(prompt, '\n');
11364 if (p == NULL)
11365 p = prompt;
11366 else
11368 ++p;
11369 c = *p;
11370 *p = NUL;
11371 msg_start();
11372 msg_clr_eos();
11373 msg_puts_attr(prompt, echo_attr);
11374 msg_didout = FALSE;
11375 msg_starthere();
11376 *p = c;
11378 cmdline_row = msg_row;
11380 if (argvars[1].v_type != VAR_UNKNOWN)
11382 defstr = get_tv_string_buf_chk(&argvars[1], buf);
11383 if (defstr != NULL)
11384 stuffReadbuffSpec(defstr);
11386 if (!inputdialog && argvars[2].v_type != VAR_UNKNOWN)
11388 char_u *xp_name;
11389 int xp_namelen;
11390 long argt;
11392 rettv->vval.v_string = NULL;
11394 xp_name = get_tv_string_buf_chk(&argvars[2], buf);
11395 if (xp_name == NULL)
11396 return;
11398 xp_namelen = (int)STRLEN(xp_name);
11400 if (parse_compl_arg(xp_name, xp_namelen, &xp_type, &argt,
11401 &xp_arg) == FAIL)
11402 return;
11406 if (defstr != NULL)
11407 rettv->vval.v_string =
11408 getcmdline_prompt(inputsecret_flag ? NUL : '@', p, echo_attr,
11409 xp_type, xp_arg);
11411 vim_free(xp_arg);
11413 /* since the user typed this, no need to wait for return */
11414 need_wait_return = FALSE;
11415 msg_didout = FALSE;
11417 cmd_silent = cmd_silent_save;
11421 * "input()" function
11422 * Also handles inputsecret() when inputsecret is set.
11424 static void
11425 f_input(argvars, rettv)
11426 typval_T *argvars;
11427 typval_T *rettv;
11429 get_user_input(argvars, rettv, FALSE);
11433 * "inputdialog()" function
11435 static void
11436 f_inputdialog(argvars, rettv)
11437 typval_T *argvars;
11438 typval_T *rettv;
11440 #if defined(FEAT_GUI_TEXTDIALOG)
11441 /* Use a GUI dialog if the GUI is running and 'c' is not in 'guioptions' */
11442 if (gui.in_use && vim_strchr(p_go, GO_CONDIALOG) == NULL)
11444 char_u *message;
11445 char_u buf[NUMBUFLEN];
11446 char_u *defstr = (char_u *)"";
11448 message = get_tv_string_chk(&argvars[0]);
11449 if (argvars[1].v_type != VAR_UNKNOWN
11450 && (defstr = get_tv_string_buf_chk(&argvars[1], buf)) != NULL)
11451 vim_strncpy(IObuff, defstr, IOSIZE - 1);
11452 else
11453 IObuff[0] = NUL;
11454 if (message != NULL && defstr != NULL
11455 && do_dialog(VIM_QUESTION, NULL, message,
11456 (char_u *)_("&OK\n&Cancel"), 1, IObuff) == 1)
11457 rettv->vval.v_string = vim_strsave(IObuff);
11458 else
11460 if (message != NULL && defstr != NULL
11461 && argvars[1].v_type != VAR_UNKNOWN
11462 && argvars[2].v_type != VAR_UNKNOWN)
11463 rettv->vval.v_string = vim_strsave(
11464 get_tv_string_buf(&argvars[2], buf));
11465 else
11466 rettv->vval.v_string = NULL;
11468 rettv->v_type = VAR_STRING;
11470 else
11471 #endif
11472 get_user_input(argvars, rettv, TRUE);
11476 * "inputlist()" function
11478 static void
11479 f_inputlist(argvars, rettv)
11480 typval_T *argvars;
11481 typval_T *rettv;
11483 listitem_T *li;
11484 int selected;
11485 int mouse_used;
11487 rettv->vval.v_number = 0;
11488 #ifdef NO_CONSOLE_INPUT
11489 /* While starting up, there is no place to enter text. */
11490 if (no_console_input())
11491 return;
11492 #endif
11493 if (argvars[0].v_type != VAR_LIST || argvars[0].vval.v_list == NULL)
11495 EMSG2(_(e_listarg), "inputlist()");
11496 return;
11499 msg_start();
11500 msg_row = Rows - 1; /* for when 'cmdheight' > 1 */
11501 lines_left = Rows; /* avoid more prompt */
11502 msg_scroll = TRUE;
11503 msg_clr_eos();
11505 for (li = argvars[0].vval.v_list->lv_first; li != NULL; li = li->li_next)
11507 msg_puts(get_tv_string(&li->li_tv));
11508 msg_putchar('\n');
11511 /* Ask for choice. */
11512 selected = prompt_for_number(&mouse_used);
11513 if (mouse_used)
11514 selected -= lines_left;
11516 rettv->vval.v_number = selected;
11520 static garray_T ga_userinput = {0, 0, sizeof(tasave_T), 4, NULL};
11523 * "inputrestore()" function
11525 /*ARGSUSED*/
11526 static void
11527 f_inputrestore(argvars, rettv)
11528 typval_T *argvars;
11529 typval_T *rettv;
11531 if (ga_userinput.ga_len > 0)
11533 --ga_userinput.ga_len;
11534 restore_typeahead((tasave_T *)(ga_userinput.ga_data)
11535 + ga_userinput.ga_len);
11536 rettv->vval.v_number = 0; /* OK */
11538 else if (p_verbose > 1)
11540 verb_msg((char_u *)_("called inputrestore() more often than inputsave()"));
11541 rettv->vval.v_number = 1; /* Failed */
11546 * "inputsave()" function
11548 /*ARGSUSED*/
11549 static void
11550 f_inputsave(argvars, rettv)
11551 typval_T *argvars;
11552 typval_T *rettv;
11554 /* Add an entry to the stack of typehead storage. */
11555 if (ga_grow(&ga_userinput, 1) == OK)
11557 save_typeahead((tasave_T *)(ga_userinput.ga_data)
11558 + ga_userinput.ga_len);
11559 ++ga_userinput.ga_len;
11560 rettv->vval.v_number = 0; /* OK */
11562 else
11563 rettv->vval.v_number = 1; /* Failed */
11567 * "inputsecret()" function
11569 static void
11570 f_inputsecret(argvars, rettv)
11571 typval_T *argvars;
11572 typval_T *rettv;
11574 ++cmdline_star;
11575 ++inputsecret_flag;
11576 f_input(argvars, rettv);
11577 --cmdline_star;
11578 --inputsecret_flag;
11582 * "insert()" function
11584 static void
11585 f_insert(argvars, rettv)
11586 typval_T *argvars;
11587 typval_T *rettv;
11589 long before = 0;
11590 listitem_T *item;
11591 list_T *l;
11592 int error = FALSE;
11594 rettv->vval.v_number = 0;
11595 if (argvars[0].v_type != VAR_LIST)
11596 EMSG2(_(e_listarg), "insert()");
11597 else if ((l = argvars[0].vval.v_list) != NULL
11598 && !tv_check_lock(l->lv_lock, (char_u *)"insert()"))
11600 if (argvars[2].v_type != VAR_UNKNOWN)
11601 before = get_tv_number_chk(&argvars[2], &error);
11602 if (error)
11603 return; /* type error; errmsg already given */
11605 if (before == l->lv_len)
11606 item = NULL;
11607 else
11609 item = list_find(l, before);
11610 if (item == NULL)
11612 EMSGN(_(e_listidx), before);
11613 l = NULL;
11616 if (l != NULL)
11618 list_insert_tv(l, &argvars[1], item);
11619 copy_tv(&argvars[0], rettv);
11625 * "isdirectory()" function
11627 static void
11628 f_isdirectory(argvars, rettv)
11629 typval_T *argvars;
11630 typval_T *rettv;
11632 rettv->vval.v_number = mch_isdir(get_tv_string(&argvars[0]));
11636 * "islocked()" function
11638 static void
11639 f_islocked(argvars, rettv)
11640 typval_T *argvars;
11641 typval_T *rettv;
11643 lval_T lv;
11644 char_u *end;
11645 dictitem_T *di;
11647 rettv->vval.v_number = -1;
11648 end = get_lval(get_tv_string(&argvars[0]), NULL, &lv, FALSE, FALSE, FALSE,
11649 FNE_CHECK_START);
11650 if (end != NULL && lv.ll_name != NULL)
11652 if (*end != NUL)
11653 EMSG(_(e_trailing));
11654 else
11656 if (lv.ll_tv == NULL)
11658 if (check_changedtick(lv.ll_name))
11659 rettv->vval.v_number = 1; /* always locked */
11660 else
11662 di = find_var(lv.ll_name, NULL);
11663 if (di != NULL)
11665 /* Consider a variable locked when:
11666 * 1. the variable itself is locked
11667 * 2. the value of the variable is locked.
11668 * 3. the List or Dict value is locked.
11670 rettv->vval.v_number = ((di->di_flags & DI_FLAGS_LOCK)
11671 || tv_islocked(&di->di_tv));
11675 else if (lv.ll_range)
11676 EMSG(_("E786: Range not allowed"));
11677 else if (lv.ll_newkey != NULL)
11678 EMSG2(_(e_dictkey), lv.ll_newkey);
11679 else if (lv.ll_list != NULL)
11680 /* List item. */
11681 rettv->vval.v_number = tv_islocked(&lv.ll_li->li_tv);
11682 else
11683 /* Dictionary item. */
11684 rettv->vval.v_number = tv_islocked(&lv.ll_di->di_tv);
11688 clear_lval(&lv);
11691 static void dict_list __ARGS((typval_T *argvars, typval_T *rettv, int what));
11694 * Turn a dict into a list:
11695 * "what" == 0: list of keys
11696 * "what" == 1: list of values
11697 * "what" == 2: list of items
11699 static void
11700 dict_list(argvars, rettv, what)
11701 typval_T *argvars;
11702 typval_T *rettv;
11703 int what;
11705 list_T *l2;
11706 dictitem_T *di;
11707 hashitem_T *hi;
11708 listitem_T *li;
11709 listitem_T *li2;
11710 dict_T *d;
11711 int todo;
11713 rettv->vval.v_number = 0;
11714 if (argvars[0].v_type != VAR_DICT)
11716 EMSG(_(e_dictreq));
11717 return;
11719 if ((d = argvars[0].vval.v_dict) == NULL)
11720 return;
11722 if (rettv_list_alloc(rettv) == FAIL)
11723 return;
11725 todo = (int)d->dv_hashtab.ht_used;
11726 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
11728 if (!HASHITEM_EMPTY(hi))
11730 --todo;
11731 di = HI2DI(hi);
11733 li = listitem_alloc();
11734 if (li == NULL)
11735 break;
11736 list_append(rettv->vval.v_list, li);
11738 if (what == 0)
11740 /* keys() */
11741 li->li_tv.v_type = VAR_STRING;
11742 li->li_tv.v_lock = 0;
11743 li->li_tv.vval.v_string = vim_strsave(di->di_key);
11745 else if (what == 1)
11747 /* values() */
11748 copy_tv(&di->di_tv, &li->li_tv);
11750 else
11752 /* items() */
11753 l2 = list_alloc();
11754 li->li_tv.v_type = VAR_LIST;
11755 li->li_tv.v_lock = 0;
11756 li->li_tv.vval.v_list = l2;
11757 if (l2 == NULL)
11758 break;
11759 ++l2->lv_refcount;
11761 li2 = listitem_alloc();
11762 if (li2 == NULL)
11763 break;
11764 list_append(l2, li2);
11765 li2->li_tv.v_type = VAR_STRING;
11766 li2->li_tv.v_lock = 0;
11767 li2->li_tv.vval.v_string = vim_strsave(di->di_key);
11769 li2 = listitem_alloc();
11770 if (li2 == NULL)
11771 break;
11772 list_append(l2, li2);
11773 copy_tv(&di->di_tv, &li2->li_tv);
11780 * "items(dict)" function
11782 static void
11783 f_items(argvars, rettv)
11784 typval_T *argvars;
11785 typval_T *rettv;
11787 dict_list(argvars, rettv, 2);
11791 * "join()" function
11793 static void
11794 f_join(argvars, rettv)
11795 typval_T *argvars;
11796 typval_T *rettv;
11798 garray_T ga;
11799 char_u *sep;
11801 rettv->vval.v_number = 0;
11802 if (argvars[0].v_type != VAR_LIST)
11804 EMSG(_(e_listreq));
11805 return;
11807 if (argvars[0].vval.v_list == NULL)
11808 return;
11809 if (argvars[1].v_type == VAR_UNKNOWN)
11810 sep = (char_u *)" ";
11811 else
11812 sep = get_tv_string_chk(&argvars[1]);
11814 rettv->v_type = VAR_STRING;
11816 if (sep != NULL)
11818 ga_init2(&ga, (int)sizeof(char), 80);
11819 list_join(&ga, argvars[0].vval.v_list, sep, TRUE, 0);
11820 ga_append(&ga, NUL);
11821 rettv->vval.v_string = (char_u *)ga.ga_data;
11823 else
11824 rettv->vval.v_string = NULL;
11828 * "keys()" function
11830 static void
11831 f_keys(argvars, rettv)
11832 typval_T *argvars;
11833 typval_T *rettv;
11835 dict_list(argvars, rettv, 0);
11839 * "last_buffer_nr()" function.
11841 /*ARGSUSED*/
11842 static void
11843 f_last_buffer_nr(argvars, rettv)
11844 typval_T *argvars;
11845 typval_T *rettv;
11847 int n = 0;
11848 buf_T *buf;
11850 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
11851 if (n < buf->b_fnum)
11852 n = buf->b_fnum;
11854 rettv->vval.v_number = n;
11858 * "len()" function
11860 static void
11861 f_len(argvars, rettv)
11862 typval_T *argvars;
11863 typval_T *rettv;
11865 switch (argvars[0].v_type)
11867 case VAR_STRING:
11868 case VAR_NUMBER:
11869 rettv->vval.v_number = (varnumber_T)STRLEN(
11870 get_tv_string(&argvars[0]));
11871 break;
11872 case VAR_LIST:
11873 rettv->vval.v_number = list_len(argvars[0].vval.v_list);
11874 break;
11875 case VAR_DICT:
11876 rettv->vval.v_number = dict_len(argvars[0].vval.v_dict);
11877 break;
11878 default:
11879 EMSG(_("E701: Invalid type for len()"));
11880 break;
11884 static void libcall_common __ARGS((typval_T *argvars, typval_T *rettv, int type));
11886 static void
11887 libcall_common(argvars, rettv, type)
11888 typval_T *argvars;
11889 typval_T *rettv;
11890 int type;
11892 #ifdef FEAT_LIBCALL
11893 char_u *string_in;
11894 char_u **string_result;
11895 int nr_result;
11896 #endif
11898 rettv->v_type = type;
11899 if (type == VAR_NUMBER)
11900 rettv->vval.v_number = 0;
11901 else
11902 rettv->vval.v_string = NULL;
11904 if (check_restricted() || check_secure())
11905 return;
11907 #ifdef FEAT_LIBCALL
11908 /* The first two args must be strings, otherwise its meaningless */
11909 if (argvars[0].v_type == VAR_STRING && argvars[1].v_type == VAR_STRING)
11911 string_in = NULL;
11912 if (argvars[2].v_type == VAR_STRING)
11913 string_in = argvars[2].vval.v_string;
11914 if (type == VAR_NUMBER)
11915 string_result = NULL;
11916 else
11917 string_result = &rettv->vval.v_string;
11918 if (mch_libcall(argvars[0].vval.v_string,
11919 argvars[1].vval.v_string,
11920 string_in,
11921 argvars[2].vval.v_number,
11922 string_result,
11923 &nr_result) == OK
11924 && type == VAR_NUMBER)
11925 rettv->vval.v_number = nr_result;
11927 #endif
11931 * "libcall()" function
11933 static void
11934 f_libcall(argvars, rettv)
11935 typval_T *argvars;
11936 typval_T *rettv;
11938 libcall_common(argvars, rettv, VAR_STRING);
11942 * "libcallnr()" function
11944 static void
11945 f_libcallnr(argvars, rettv)
11946 typval_T *argvars;
11947 typval_T *rettv;
11949 libcall_common(argvars, rettv, VAR_NUMBER);
11953 * "line(string)" function
11955 static void
11956 f_line(argvars, rettv)
11957 typval_T *argvars;
11958 typval_T *rettv;
11960 linenr_T lnum = 0;
11961 pos_T *fp;
11962 int fnum;
11964 fp = var2fpos(&argvars[0], TRUE, &fnum);
11965 if (fp != NULL)
11966 lnum = fp->lnum;
11967 rettv->vval.v_number = lnum;
11971 * "line2byte(lnum)" function
11973 /*ARGSUSED*/
11974 static void
11975 f_line2byte(argvars, rettv)
11976 typval_T *argvars;
11977 typval_T *rettv;
11979 #ifndef FEAT_BYTEOFF
11980 rettv->vval.v_number = -1;
11981 #else
11982 linenr_T lnum;
11984 lnum = get_tv_lnum(argvars);
11985 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
11986 rettv->vval.v_number = -1;
11987 else
11988 rettv->vval.v_number = ml_find_line_or_offset(curbuf, lnum, NULL);
11989 if (rettv->vval.v_number >= 0)
11990 ++rettv->vval.v_number;
11991 #endif
11995 * "lispindent(lnum)" function
11997 static void
11998 f_lispindent(argvars, rettv)
11999 typval_T *argvars;
12000 typval_T *rettv;
12002 #ifdef FEAT_LISP
12003 pos_T pos;
12004 linenr_T lnum;
12006 pos = curwin->w_cursor;
12007 lnum = get_tv_lnum(argvars);
12008 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
12010 curwin->w_cursor.lnum = lnum;
12011 rettv->vval.v_number = get_lisp_indent();
12012 curwin->w_cursor = pos;
12014 else
12015 #endif
12016 rettv->vval.v_number = -1;
12020 * "localtime()" function
12022 /*ARGSUSED*/
12023 static void
12024 f_localtime(argvars, rettv)
12025 typval_T *argvars;
12026 typval_T *rettv;
12028 rettv->vval.v_number = (varnumber_T)time(NULL);
12031 static void get_maparg __ARGS((typval_T *argvars, typval_T *rettv, int exact));
12033 static void
12034 get_maparg(argvars, rettv, exact)
12035 typval_T *argvars;
12036 typval_T *rettv;
12037 int exact;
12039 char_u *keys;
12040 char_u *which;
12041 char_u buf[NUMBUFLEN];
12042 char_u *keys_buf = NULL;
12043 char_u *rhs;
12044 int mode;
12045 garray_T ga;
12046 int abbr = FALSE;
12048 /* return empty string for failure */
12049 rettv->v_type = VAR_STRING;
12050 rettv->vval.v_string = NULL;
12052 keys = get_tv_string(&argvars[0]);
12053 if (*keys == NUL)
12054 return;
12056 if (argvars[1].v_type != VAR_UNKNOWN)
12058 which = get_tv_string_buf_chk(&argvars[1], buf);
12059 if (argvars[2].v_type != VAR_UNKNOWN)
12060 abbr = get_tv_number(&argvars[2]);
12062 else
12063 which = (char_u *)"";
12064 if (which == NULL)
12065 return;
12067 mode = get_map_mode(&which, 0);
12069 keys = replace_termcodes(keys, &keys_buf, TRUE, TRUE, FALSE);
12070 rhs = check_map(keys, mode, exact, FALSE, abbr);
12071 vim_free(keys_buf);
12072 if (rhs != NULL)
12074 ga_init(&ga);
12075 ga.ga_itemsize = 1;
12076 ga.ga_growsize = 40;
12078 while (*rhs != NUL)
12079 ga_concat(&ga, str2special(&rhs, FALSE));
12081 ga_append(&ga, NUL);
12082 rettv->vval.v_string = (char_u *)ga.ga_data;
12087 * "map()" function
12089 static void
12090 f_map(argvars, rettv)
12091 typval_T *argvars;
12092 typval_T *rettv;
12094 filter_map(argvars, rettv, TRUE);
12098 * "maparg()" function
12100 static void
12101 f_maparg(argvars, rettv)
12102 typval_T *argvars;
12103 typval_T *rettv;
12105 get_maparg(argvars, rettv, TRUE);
12109 * "mapcheck()" function
12111 static void
12112 f_mapcheck(argvars, rettv)
12113 typval_T *argvars;
12114 typval_T *rettv;
12116 get_maparg(argvars, rettv, FALSE);
12119 static void find_some_match __ARGS((typval_T *argvars, typval_T *rettv, int start));
12121 static void
12122 find_some_match(argvars, rettv, type)
12123 typval_T *argvars;
12124 typval_T *rettv;
12125 int type;
12127 char_u *str = NULL;
12128 char_u *expr = NULL;
12129 char_u *pat;
12130 regmatch_T regmatch;
12131 char_u patbuf[NUMBUFLEN];
12132 char_u strbuf[NUMBUFLEN];
12133 char_u *save_cpo;
12134 long start = 0;
12135 long nth = 1;
12136 colnr_T startcol = 0;
12137 int match = 0;
12138 list_T *l = NULL;
12139 listitem_T *li = NULL;
12140 long idx = 0;
12141 char_u *tofree = NULL;
12143 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
12144 save_cpo = p_cpo;
12145 p_cpo = (char_u *)"";
12147 rettv->vval.v_number = -1;
12148 if (type == 3)
12150 /* return empty list when there are no matches */
12151 if (rettv_list_alloc(rettv) == FAIL)
12152 goto theend;
12154 else if (type == 2)
12156 rettv->v_type = VAR_STRING;
12157 rettv->vval.v_string = NULL;
12160 if (argvars[0].v_type == VAR_LIST)
12162 if ((l = argvars[0].vval.v_list) == NULL)
12163 goto theend;
12164 li = l->lv_first;
12166 else
12167 expr = str = get_tv_string(&argvars[0]);
12169 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
12170 if (pat == NULL)
12171 goto theend;
12173 if (argvars[2].v_type != VAR_UNKNOWN)
12175 int error = FALSE;
12177 start = get_tv_number_chk(&argvars[2], &error);
12178 if (error)
12179 goto theend;
12180 if (l != NULL)
12182 li = list_find(l, start);
12183 if (li == NULL)
12184 goto theend;
12185 idx = l->lv_idx; /* use the cached index */
12187 else
12189 if (start < 0)
12190 start = 0;
12191 if (start > (long)STRLEN(str))
12192 goto theend;
12193 /* When "count" argument is there ignore matches before "start",
12194 * otherwise skip part of the string. Differs when pattern is "^"
12195 * or "\<". */
12196 if (argvars[3].v_type != VAR_UNKNOWN)
12197 startcol = start;
12198 else
12199 str += start;
12202 if (argvars[3].v_type != VAR_UNKNOWN)
12203 nth = get_tv_number_chk(&argvars[3], &error);
12204 if (error)
12205 goto theend;
12208 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
12209 if (regmatch.regprog != NULL)
12211 regmatch.rm_ic = p_ic;
12213 for (;;)
12215 if (l != NULL)
12217 if (li == NULL)
12219 match = FALSE;
12220 break;
12222 vim_free(tofree);
12223 str = echo_string(&li->li_tv, &tofree, strbuf, 0);
12224 if (str == NULL)
12225 break;
12228 match = vim_regexec_nl(&regmatch, str, (colnr_T)startcol);
12230 if (match && --nth <= 0)
12231 break;
12232 if (l == NULL && !match)
12233 break;
12235 /* Advance to just after the match. */
12236 if (l != NULL)
12238 li = li->li_next;
12239 ++idx;
12241 else
12243 #ifdef FEAT_MBYTE
12244 startcol = (colnr_T)(regmatch.startp[0]
12245 + (*mb_ptr2len)(regmatch.startp[0]) - str);
12246 #else
12247 startcol = regmatch.startp[0] + 1 - str;
12248 #endif
12252 if (match)
12254 if (type == 3)
12256 int i;
12258 /* return list with matched string and submatches */
12259 for (i = 0; i < NSUBEXP; ++i)
12261 if (regmatch.endp[i] == NULL)
12263 if (list_append_string(rettv->vval.v_list,
12264 (char_u *)"", 0) == FAIL)
12265 break;
12267 else if (list_append_string(rettv->vval.v_list,
12268 regmatch.startp[i],
12269 (int)(regmatch.endp[i] - regmatch.startp[i]))
12270 == FAIL)
12271 break;
12274 else if (type == 2)
12276 /* return matched string */
12277 if (l != NULL)
12278 copy_tv(&li->li_tv, rettv);
12279 else
12280 rettv->vval.v_string = vim_strnsave(regmatch.startp[0],
12281 (int)(regmatch.endp[0] - regmatch.startp[0]));
12283 else if (l != NULL)
12284 rettv->vval.v_number = idx;
12285 else
12287 if (type != 0)
12288 rettv->vval.v_number =
12289 (varnumber_T)(regmatch.startp[0] - str);
12290 else
12291 rettv->vval.v_number =
12292 (varnumber_T)(regmatch.endp[0] - str);
12293 rettv->vval.v_number += (varnumber_T)(str - expr);
12296 vim_free(regmatch.regprog);
12299 theend:
12300 vim_free(tofree);
12301 p_cpo = save_cpo;
12305 * "match()" function
12307 static void
12308 f_match(argvars, rettv)
12309 typval_T *argvars;
12310 typval_T *rettv;
12312 find_some_match(argvars, rettv, 1);
12316 * "matcharg()" function
12318 static void
12319 f_matcharg(argvars, rettv)
12320 typval_T *argvars;
12321 typval_T *rettv;
12323 if (rettv_list_alloc(rettv) == OK)
12325 #ifdef FEAT_SEARCH_EXTRA
12326 int mi = get_tv_number(&argvars[0]);
12328 if (mi >= 1 && mi <= 3)
12330 list_append_string(rettv->vval.v_list,
12331 syn_id2name(curwin->w_match_id[mi - 1]), -1);
12332 list_append_string(rettv->vval.v_list,
12333 curwin->w_match_pat[mi - 1], -1);
12335 #endif
12340 * "matchend()" function
12342 static void
12343 f_matchend(argvars, rettv)
12344 typval_T *argvars;
12345 typval_T *rettv;
12347 find_some_match(argvars, rettv, 0);
12351 * "matchlist()" function
12353 static void
12354 f_matchlist(argvars, rettv)
12355 typval_T *argvars;
12356 typval_T *rettv;
12358 find_some_match(argvars, rettv, 3);
12362 * "matchstr()" function
12364 static void
12365 f_matchstr(argvars, rettv)
12366 typval_T *argvars;
12367 typval_T *rettv;
12369 find_some_match(argvars, rettv, 2);
12372 static void max_min __ARGS((typval_T *argvars, typval_T *rettv, int domax));
12374 static void
12375 max_min(argvars, rettv, domax)
12376 typval_T *argvars;
12377 typval_T *rettv;
12378 int domax;
12380 long n = 0;
12381 long i;
12382 int error = FALSE;
12384 if (argvars[0].v_type == VAR_LIST)
12386 list_T *l;
12387 listitem_T *li;
12389 l = argvars[0].vval.v_list;
12390 if (l != NULL)
12392 li = l->lv_first;
12393 if (li != NULL)
12395 n = get_tv_number_chk(&li->li_tv, &error);
12396 for (;;)
12398 li = li->li_next;
12399 if (li == NULL)
12400 break;
12401 i = get_tv_number_chk(&li->li_tv, &error);
12402 if (domax ? i > n : i < n)
12403 n = i;
12408 else if (argvars[0].v_type == VAR_DICT)
12410 dict_T *d;
12411 int first = TRUE;
12412 hashitem_T *hi;
12413 int todo;
12415 d = argvars[0].vval.v_dict;
12416 if (d != NULL)
12418 todo = (int)d->dv_hashtab.ht_used;
12419 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
12421 if (!HASHITEM_EMPTY(hi))
12423 --todo;
12424 i = get_tv_number_chk(&HI2DI(hi)->di_tv, &error);
12425 if (first)
12427 n = i;
12428 first = FALSE;
12430 else if (domax ? i > n : i < n)
12431 n = i;
12436 else
12437 EMSG(_(e_listdictarg));
12438 rettv->vval.v_number = error ? 0 : n;
12442 * "max()" function
12444 static void
12445 f_max(argvars, rettv)
12446 typval_T *argvars;
12447 typval_T *rettv;
12449 max_min(argvars, rettv, TRUE);
12453 * "min()" function
12455 static void
12456 f_min(argvars, rettv)
12457 typval_T *argvars;
12458 typval_T *rettv;
12460 max_min(argvars, rettv, FALSE);
12463 static int mkdir_recurse __ARGS((char_u *dir, int prot));
12466 * Create the directory in which "dir" is located, and higher levels when
12467 * needed.
12469 static int
12470 mkdir_recurse(dir, prot)
12471 char_u *dir;
12472 int prot;
12474 char_u *p;
12475 char_u *updir;
12476 int r = FAIL;
12478 /* Get end of directory name in "dir".
12479 * We're done when it's "/" or "c:/". */
12480 p = gettail_sep(dir);
12481 if (p <= get_past_head(dir))
12482 return OK;
12484 /* If the directory exists we're done. Otherwise: create it.*/
12485 updir = vim_strnsave(dir, (int)(p - dir));
12486 if (updir == NULL)
12487 return FAIL;
12488 if (mch_isdir(updir))
12489 r = OK;
12490 else if (mkdir_recurse(updir, prot) == OK)
12491 r = vim_mkdir_emsg(updir, prot);
12492 vim_free(updir);
12493 return r;
12496 #ifdef vim_mkdir
12498 * "mkdir()" function
12500 static void
12501 f_mkdir(argvars, rettv)
12502 typval_T *argvars;
12503 typval_T *rettv;
12505 char_u *dir;
12506 char_u buf[NUMBUFLEN];
12507 int prot = 0755;
12509 rettv->vval.v_number = FAIL;
12510 if (check_restricted() || check_secure())
12511 return;
12513 dir = get_tv_string_buf(&argvars[0], buf);
12514 if (argvars[1].v_type != VAR_UNKNOWN)
12516 if (argvars[2].v_type != VAR_UNKNOWN)
12517 prot = get_tv_number_chk(&argvars[2], NULL);
12518 if (prot != -1 && STRCMP(get_tv_string(&argvars[1]), "p") == 0)
12519 mkdir_recurse(dir, prot);
12521 rettv->vval.v_number = prot != -1 ? vim_mkdir_emsg(dir, prot) : 0;
12523 #endif
12526 * "mode()" function
12528 /*ARGSUSED*/
12529 static void
12530 f_mode(argvars, rettv)
12531 typval_T *argvars;
12532 typval_T *rettv;
12534 char_u buf[2];
12536 #ifdef FEAT_VISUAL
12537 if (VIsual_active)
12539 if (VIsual_select)
12540 buf[0] = VIsual_mode + 's' - 'v';
12541 else
12542 buf[0] = VIsual_mode;
12544 else
12545 #endif
12546 if (State == HITRETURN || State == ASKMORE || State == SETWSIZE)
12547 buf[0] = 'r';
12548 else if (State & INSERT)
12550 if (State & REPLACE_FLAG)
12551 buf[0] = 'R';
12552 else
12553 buf[0] = 'i';
12555 else if (State & CMDLINE)
12556 buf[0] = 'c';
12557 else
12558 buf[0] = 'n';
12560 buf[1] = NUL;
12561 rettv->vval.v_string = vim_strsave(buf);
12562 rettv->v_type = VAR_STRING;
12566 * "nextnonblank()" function
12568 static void
12569 f_nextnonblank(argvars, rettv)
12570 typval_T *argvars;
12571 typval_T *rettv;
12573 linenr_T lnum;
12575 for (lnum = get_tv_lnum(argvars); ; ++lnum)
12577 if (lnum < 0 || lnum > curbuf->b_ml.ml_line_count)
12579 lnum = 0;
12580 break;
12582 if (*skipwhite(ml_get(lnum)) != NUL)
12583 break;
12585 rettv->vval.v_number = lnum;
12589 * "nr2char()" function
12591 static void
12592 f_nr2char(argvars, rettv)
12593 typval_T *argvars;
12594 typval_T *rettv;
12596 char_u buf[NUMBUFLEN];
12598 #ifdef FEAT_MBYTE
12599 if (has_mbyte)
12600 buf[(*mb_char2bytes)((int)get_tv_number(&argvars[0]), buf)] = NUL;
12601 else
12602 #endif
12604 buf[0] = (char_u)get_tv_number(&argvars[0]);
12605 buf[1] = NUL;
12607 rettv->v_type = VAR_STRING;
12608 rettv->vval.v_string = vim_strsave(buf);
12612 * "pathshorten()" function
12614 static void
12615 f_pathshorten(argvars, rettv)
12616 typval_T *argvars;
12617 typval_T *rettv;
12619 char_u *p;
12621 rettv->v_type = VAR_STRING;
12622 p = get_tv_string_chk(&argvars[0]);
12623 if (p == NULL)
12624 rettv->vval.v_string = NULL;
12625 else
12627 p = vim_strsave(p);
12628 rettv->vval.v_string = p;
12629 if (p != NULL)
12630 shorten_dir(p);
12635 * "prevnonblank()" function
12637 static void
12638 f_prevnonblank(argvars, rettv)
12639 typval_T *argvars;
12640 typval_T *rettv;
12642 linenr_T lnum;
12644 lnum = get_tv_lnum(argvars);
12645 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
12646 lnum = 0;
12647 else
12648 while (lnum >= 1 && *skipwhite(ml_get(lnum)) == NUL)
12649 --lnum;
12650 rettv->vval.v_number = lnum;
12653 #ifdef HAVE_STDARG_H
12654 /* This dummy va_list is here because:
12655 * - passing a NULL pointer doesn't work when va_list isn't a pointer
12656 * - locally in the function results in a "used before set" warning
12657 * - using va_start() to initialize it gives "function with fixed args" error */
12658 static va_list ap;
12659 #endif
12662 * "printf()" function
12664 static void
12665 f_printf(argvars, rettv)
12666 typval_T *argvars;
12667 typval_T *rettv;
12669 rettv->v_type = VAR_STRING;
12670 rettv->vval.v_string = NULL;
12671 #ifdef HAVE_STDARG_H /* only very old compilers can't do this */
12673 char_u buf[NUMBUFLEN];
12674 int len;
12675 char_u *s;
12676 int saved_did_emsg = did_emsg;
12677 char *fmt;
12679 /* Get the required length, allocate the buffer and do it for real. */
12680 did_emsg = FALSE;
12681 fmt = (char *)get_tv_string_buf(&argvars[0], buf);
12682 len = vim_vsnprintf(NULL, 0, fmt, ap, argvars + 1);
12683 if (!did_emsg)
12685 s = alloc(len + 1);
12686 if (s != NULL)
12688 rettv->vval.v_string = s;
12689 (void)vim_vsnprintf((char *)s, len + 1, fmt, ap, argvars + 1);
12692 did_emsg |= saved_did_emsg;
12694 #endif
12698 * "pumvisible()" function
12700 /*ARGSUSED*/
12701 static void
12702 f_pumvisible(argvars, rettv)
12703 typval_T *argvars;
12704 typval_T *rettv;
12706 rettv->vval.v_number = 0;
12707 #ifdef FEAT_INS_EXPAND
12708 if (pum_visible())
12709 rettv->vval.v_number = 1;
12710 #endif
12714 * "range()" function
12716 static void
12717 f_range(argvars, rettv)
12718 typval_T *argvars;
12719 typval_T *rettv;
12721 long start;
12722 long end;
12723 long stride = 1;
12724 long i;
12725 int error = FALSE;
12727 start = get_tv_number_chk(&argvars[0], &error);
12728 if (argvars[1].v_type == VAR_UNKNOWN)
12730 end = start - 1;
12731 start = 0;
12733 else
12735 end = get_tv_number_chk(&argvars[1], &error);
12736 if (argvars[2].v_type != VAR_UNKNOWN)
12737 stride = get_tv_number_chk(&argvars[2], &error);
12740 rettv->vval.v_number = 0;
12741 if (error)
12742 return; /* type error; errmsg already given */
12743 if (stride == 0)
12744 EMSG(_("E726: Stride is zero"));
12745 else if (stride > 0 ? end + 1 < start : end - 1 > start)
12746 EMSG(_("E727: Start past end"));
12747 else
12749 if (rettv_list_alloc(rettv) == OK)
12750 for (i = start; stride > 0 ? i <= end : i >= end; i += stride)
12751 if (list_append_number(rettv->vval.v_list,
12752 (varnumber_T)i) == FAIL)
12753 break;
12758 * "readfile()" function
12760 static void
12761 f_readfile(argvars, rettv)
12762 typval_T *argvars;
12763 typval_T *rettv;
12765 int binary = FALSE;
12766 char_u *fname;
12767 FILE *fd;
12768 listitem_T *li;
12769 #define FREAD_SIZE 200 /* optimized for text lines */
12770 char_u buf[FREAD_SIZE];
12771 int readlen; /* size of last fread() */
12772 int buflen; /* nr of valid chars in buf[] */
12773 int filtd; /* how much in buf[] was NUL -> '\n' filtered */
12774 int tolist; /* first byte in buf[] still to be put in list */
12775 int chop; /* how many CR to chop off */
12776 char_u *prev = NULL; /* previously read bytes, if any */
12777 int prevlen = 0; /* length of "prev" if not NULL */
12778 char_u *s;
12779 int len;
12780 long maxline = MAXLNUM;
12781 long cnt = 0;
12783 if (argvars[1].v_type != VAR_UNKNOWN)
12785 if (STRCMP(get_tv_string(&argvars[1]), "b") == 0)
12786 binary = TRUE;
12787 if (argvars[2].v_type != VAR_UNKNOWN)
12788 maxline = get_tv_number(&argvars[2]);
12791 if (rettv_list_alloc(rettv) == FAIL)
12792 return;
12794 /* Always open the file in binary mode, library functions have a mind of
12795 * their own about CR-LF conversion. */
12796 fname = get_tv_string(&argvars[0]);
12797 if (*fname == NUL || (fd = mch_fopen((char *)fname, READBIN)) == NULL)
12799 EMSG2(_(e_notopen), *fname == NUL ? (char_u *)_("<empty>") : fname);
12800 return;
12803 filtd = 0;
12804 while (cnt < maxline || maxline < 0)
12806 readlen = (int)fread(buf + filtd, 1, FREAD_SIZE - filtd, fd);
12807 buflen = filtd + readlen;
12808 tolist = 0;
12809 for ( ; filtd < buflen || readlen <= 0; ++filtd)
12811 if (buf[filtd] == '\n' || readlen <= 0)
12813 /* Only when in binary mode add an empty list item when the
12814 * last line ends in a '\n'. */
12815 if (!binary && readlen == 0 && filtd == 0)
12816 break;
12818 /* Found end-of-line or end-of-file: add a text line to the
12819 * list. */
12820 chop = 0;
12821 if (!binary)
12822 while (filtd - chop - 1 >= tolist
12823 && buf[filtd - chop - 1] == '\r')
12824 ++chop;
12825 len = filtd - tolist - chop;
12826 if (prev == NULL)
12827 s = vim_strnsave(buf + tolist, len);
12828 else
12830 s = alloc((unsigned)(prevlen + len + 1));
12831 if (s != NULL)
12833 mch_memmove(s, prev, prevlen);
12834 vim_free(prev);
12835 prev = NULL;
12836 mch_memmove(s + prevlen, buf + tolist, len);
12837 s[prevlen + len] = NUL;
12840 tolist = filtd + 1;
12842 li = listitem_alloc();
12843 if (li == NULL)
12845 vim_free(s);
12846 break;
12848 li->li_tv.v_type = VAR_STRING;
12849 li->li_tv.v_lock = 0;
12850 li->li_tv.vval.v_string = s;
12851 list_append(rettv->vval.v_list, li);
12853 if (++cnt >= maxline && maxline >= 0)
12854 break;
12855 if (readlen <= 0)
12856 break;
12858 else if (buf[filtd] == NUL)
12859 buf[filtd] = '\n';
12861 if (readlen <= 0)
12862 break;
12864 if (tolist == 0)
12866 /* "buf" is full, need to move text to an allocated buffer */
12867 if (prev == NULL)
12869 prev = vim_strnsave(buf, buflen);
12870 prevlen = buflen;
12872 else
12874 s = alloc((unsigned)(prevlen + buflen));
12875 if (s != NULL)
12877 mch_memmove(s, prev, prevlen);
12878 mch_memmove(s + prevlen, buf, buflen);
12879 vim_free(prev);
12880 prev = s;
12881 prevlen += buflen;
12884 filtd = 0;
12886 else
12888 mch_memmove(buf, buf + tolist, buflen - tolist);
12889 filtd -= tolist;
12894 * For a negative line count use only the lines at the end of the file,
12895 * free the rest.
12897 if (maxline < 0)
12898 while (cnt > -maxline)
12900 listitem_remove(rettv->vval.v_list, rettv->vval.v_list->lv_first);
12901 --cnt;
12904 vim_free(prev);
12905 fclose(fd);
12908 #if defined(FEAT_RELTIME)
12909 static int list2proftime __ARGS((typval_T *arg, proftime_T *tm));
12912 * Convert a List to proftime_T.
12913 * Return FAIL when there is something wrong.
12915 static int
12916 list2proftime(arg, tm)
12917 typval_T *arg;
12918 proftime_T *tm;
12920 long n1, n2;
12921 int error = FALSE;
12923 if (arg->v_type != VAR_LIST || arg->vval.v_list == NULL
12924 || arg->vval.v_list->lv_len != 2)
12925 return FAIL;
12926 n1 = list_find_nr(arg->vval.v_list, 0L, &error);
12927 n2 = list_find_nr(arg->vval.v_list, 1L, &error);
12928 # ifdef WIN3264
12929 tm->HighPart = n1;
12930 tm->LowPart = n2;
12931 # else
12932 tm->tv_sec = n1;
12933 tm->tv_usec = n2;
12934 # endif
12935 return error ? FAIL : OK;
12937 #endif /* FEAT_RELTIME */
12940 * "reltime()" function
12942 static void
12943 f_reltime(argvars, rettv)
12944 typval_T *argvars;
12945 typval_T *rettv;
12947 #ifdef FEAT_RELTIME
12948 proftime_T res;
12949 proftime_T start;
12951 if (argvars[0].v_type == VAR_UNKNOWN)
12953 /* No arguments: get current time. */
12954 profile_start(&res);
12956 else if (argvars[1].v_type == VAR_UNKNOWN)
12958 if (list2proftime(&argvars[0], &res) == FAIL)
12959 return;
12960 profile_end(&res);
12962 else
12964 /* Two arguments: compute the difference. */
12965 if (list2proftime(&argvars[0], &start) == FAIL
12966 || list2proftime(&argvars[1], &res) == FAIL)
12967 return;
12968 profile_sub(&res, &start);
12971 if (rettv_list_alloc(rettv) == OK)
12973 long n1, n2;
12975 # ifdef WIN3264
12976 n1 = res.HighPart;
12977 n2 = res.LowPart;
12978 # else
12979 n1 = res.tv_sec;
12980 n2 = res.tv_usec;
12981 # endif
12982 list_append_number(rettv->vval.v_list, (varnumber_T)n1);
12983 list_append_number(rettv->vval.v_list, (varnumber_T)n2);
12985 #endif
12989 * "reltimestr()" function
12991 static void
12992 f_reltimestr(argvars, rettv)
12993 typval_T *argvars;
12994 typval_T *rettv;
12996 #ifdef FEAT_RELTIME
12997 proftime_T tm;
12998 #endif
13000 rettv->v_type = VAR_STRING;
13001 rettv->vval.v_string = NULL;
13002 #ifdef FEAT_RELTIME
13003 if (list2proftime(&argvars[0], &tm) == OK)
13004 rettv->vval.v_string = vim_strsave((char_u *)profile_msg(&tm));
13005 #endif
13008 #if defined(FEAT_CLIENTSERVER) && defined(FEAT_X11)
13009 static void make_connection __ARGS((void));
13010 static int check_connection __ARGS((void));
13012 static void
13013 make_connection()
13015 if (X_DISPLAY == NULL
13016 # ifdef FEAT_GUI
13017 && !gui.in_use
13018 # endif
13021 x_force_connect = TRUE;
13022 setup_term_clip();
13023 x_force_connect = FALSE;
13027 static int
13028 check_connection()
13030 make_connection();
13031 if (X_DISPLAY == NULL)
13033 EMSG(_("E240: No connection to Vim server"));
13034 return FAIL;
13036 return OK;
13038 #endif
13040 #ifdef FEAT_CLIENTSERVER
13041 static void remote_common __ARGS((typval_T *argvars, typval_T *rettv, int expr));
13043 static void
13044 remote_common(argvars, rettv, expr)
13045 typval_T *argvars;
13046 typval_T *rettv;
13047 int expr;
13049 char_u *server_name;
13050 char_u *keys;
13051 char_u *r = NULL;
13052 char_u buf[NUMBUFLEN];
13053 # ifdef WIN32
13054 HWND w;
13055 # else
13056 Window w;
13057 # endif
13059 if (check_restricted() || check_secure())
13060 return;
13062 # ifdef FEAT_X11
13063 if (check_connection() == FAIL)
13064 return;
13065 # endif
13067 server_name = get_tv_string_chk(&argvars[0]);
13068 if (server_name == NULL)
13069 return; /* type error; errmsg already given */
13070 keys = get_tv_string_buf(&argvars[1], buf);
13071 # ifdef WIN32
13072 if (serverSendToVim(server_name, keys, &r, &w, expr, TRUE) < 0)
13073 # else
13074 if (serverSendToVim(X_DISPLAY, server_name, keys, &r, &w, expr, 0, TRUE)
13075 < 0)
13076 # endif
13078 if (r != NULL)
13079 EMSG(r); /* sending worked but evaluation failed */
13080 else
13081 EMSG2(_("E241: Unable to send to %s"), server_name);
13082 return;
13085 rettv->vval.v_string = r;
13087 if (argvars[2].v_type != VAR_UNKNOWN)
13089 dictitem_T v;
13090 char_u str[30];
13091 char_u *idvar;
13093 sprintf((char *)str, PRINTF_HEX_LONG_U, (long_u)w);
13094 v.di_tv.v_type = VAR_STRING;
13095 v.di_tv.vval.v_string = vim_strsave(str);
13096 idvar = get_tv_string_chk(&argvars[2]);
13097 if (idvar != NULL)
13098 set_var(idvar, &v.di_tv, FALSE);
13099 vim_free(v.di_tv.vval.v_string);
13102 #endif
13105 * "remote_expr()" function
13107 /*ARGSUSED*/
13108 static void
13109 f_remote_expr(argvars, rettv)
13110 typval_T *argvars;
13111 typval_T *rettv;
13113 rettv->v_type = VAR_STRING;
13114 rettv->vval.v_string = NULL;
13115 #ifdef FEAT_CLIENTSERVER
13116 remote_common(argvars, rettv, TRUE);
13117 #endif
13121 * "remote_foreground()" function
13123 /*ARGSUSED*/
13124 static void
13125 f_remote_foreground(argvars, rettv)
13126 typval_T *argvars;
13127 typval_T *rettv;
13129 rettv->vval.v_number = 0;
13130 #ifdef FEAT_CLIENTSERVER
13131 # ifdef WIN32
13132 /* On Win32 it's done in this application. */
13134 char_u *server_name = get_tv_string_chk(&argvars[0]);
13136 if (server_name != NULL)
13137 serverForeground(server_name);
13139 # else
13140 /* Send a foreground() expression to the server. */
13141 argvars[1].v_type = VAR_STRING;
13142 argvars[1].vval.v_string = vim_strsave((char_u *)"foreground()");
13143 argvars[2].v_type = VAR_UNKNOWN;
13144 remote_common(argvars, rettv, TRUE);
13145 vim_free(argvars[1].vval.v_string);
13146 # endif
13147 #endif
13150 /*ARGSUSED*/
13151 static void
13152 f_remote_peek(argvars, rettv)
13153 typval_T *argvars;
13154 typval_T *rettv;
13156 #ifdef FEAT_CLIENTSERVER
13157 dictitem_T v;
13158 char_u *s = NULL;
13159 # ifdef WIN32
13160 long_u n = 0;
13161 # endif
13162 char_u *serverid;
13164 if (check_restricted() || check_secure())
13166 rettv->vval.v_number = -1;
13167 return;
13169 serverid = get_tv_string_chk(&argvars[0]);
13170 if (serverid == NULL)
13172 rettv->vval.v_number = -1;
13173 return; /* type error; errmsg already given */
13175 # ifdef WIN32
13176 sscanf(serverid, SCANF_HEX_LONG_U, &n);
13177 if (n == 0)
13178 rettv->vval.v_number = -1;
13179 else
13181 s = serverGetReply((HWND)n, FALSE, FALSE, FALSE);
13182 rettv->vval.v_number = (s != NULL);
13184 # else
13185 rettv->vval.v_number = 0;
13186 if (check_connection() == FAIL)
13187 return;
13189 rettv->vval.v_number = serverPeekReply(X_DISPLAY,
13190 serverStrToWin(serverid), &s);
13191 # endif
13193 if (argvars[1].v_type != VAR_UNKNOWN && rettv->vval.v_number > 0)
13195 char_u *retvar;
13197 v.di_tv.v_type = VAR_STRING;
13198 v.di_tv.vval.v_string = vim_strsave(s);
13199 retvar = get_tv_string_chk(&argvars[1]);
13200 if (retvar != NULL)
13201 set_var(retvar, &v.di_tv, FALSE);
13202 vim_free(v.di_tv.vval.v_string);
13204 #else
13205 rettv->vval.v_number = -1;
13206 #endif
13209 /*ARGSUSED*/
13210 static void
13211 f_remote_read(argvars, rettv)
13212 typval_T *argvars;
13213 typval_T *rettv;
13215 char_u *r = NULL;
13217 #ifdef FEAT_CLIENTSERVER
13218 char_u *serverid = get_tv_string_chk(&argvars[0]);
13220 if (serverid != NULL && !check_restricted() && !check_secure())
13222 # ifdef WIN32
13223 /* The server's HWND is encoded in the 'id' parameter */
13224 long_u n = 0;
13226 sscanf(serverid, SCANF_HEX_LONG_U, &n);
13227 if (n != 0)
13228 r = serverGetReply((HWND)n, FALSE, TRUE, TRUE);
13229 if (r == NULL)
13230 # else
13231 if (check_connection() == FAIL || serverReadReply(X_DISPLAY,
13232 serverStrToWin(serverid), &r, FALSE) < 0)
13233 # endif
13234 EMSG(_("E277: Unable to read a server reply"));
13236 #endif
13237 rettv->v_type = VAR_STRING;
13238 rettv->vval.v_string = r;
13242 * "remote_send()" function
13244 /*ARGSUSED*/
13245 static void
13246 f_remote_send(argvars, rettv)
13247 typval_T *argvars;
13248 typval_T *rettv;
13250 rettv->v_type = VAR_STRING;
13251 rettv->vval.v_string = NULL;
13252 #ifdef FEAT_CLIENTSERVER
13253 remote_common(argvars, rettv, FALSE);
13254 #endif
13258 * "remove()" function
13260 static void
13261 f_remove(argvars, rettv)
13262 typval_T *argvars;
13263 typval_T *rettv;
13265 list_T *l;
13266 listitem_T *item, *item2;
13267 listitem_T *li;
13268 long idx;
13269 long end;
13270 char_u *key;
13271 dict_T *d;
13272 dictitem_T *di;
13274 rettv->vval.v_number = 0;
13275 if (argvars[0].v_type == VAR_DICT)
13277 if (argvars[2].v_type != VAR_UNKNOWN)
13278 EMSG2(_(e_toomanyarg), "remove()");
13279 else if ((d = argvars[0].vval.v_dict) != NULL
13280 && !tv_check_lock(d->dv_lock, (char_u *)"remove() argument"))
13282 key = get_tv_string_chk(&argvars[1]);
13283 if (key != NULL)
13285 di = dict_find(d, key, -1);
13286 if (di == NULL)
13287 EMSG2(_(e_dictkey), key);
13288 else
13290 *rettv = di->di_tv;
13291 init_tv(&di->di_tv);
13292 dictitem_remove(d, di);
13297 else if (argvars[0].v_type != VAR_LIST)
13298 EMSG2(_(e_listdictarg), "remove()");
13299 else if ((l = argvars[0].vval.v_list) != NULL
13300 && !tv_check_lock(l->lv_lock, (char_u *)"remove() argument"))
13302 int error = FALSE;
13304 idx = get_tv_number_chk(&argvars[1], &error);
13305 if (error)
13306 ; /* type error: do nothing, errmsg already given */
13307 else if ((item = list_find(l, idx)) == NULL)
13308 EMSGN(_(e_listidx), idx);
13309 else
13311 if (argvars[2].v_type == VAR_UNKNOWN)
13313 /* Remove one item, return its value. */
13314 list_remove(l, item, item);
13315 *rettv = item->li_tv;
13316 vim_free(item);
13318 else
13320 /* Remove range of items, return list with values. */
13321 end = get_tv_number_chk(&argvars[2], &error);
13322 if (error)
13323 ; /* type error: do nothing */
13324 else if ((item2 = list_find(l, end)) == NULL)
13325 EMSGN(_(e_listidx), end);
13326 else
13328 int cnt = 0;
13330 for (li = item; li != NULL; li = li->li_next)
13332 ++cnt;
13333 if (li == item2)
13334 break;
13336 if (li == NULL) /* didn't find "item2" after "item" */
13337 EMSG(_(e_invrange));
13338 else
13340 list_remove(l, item, item2);
13341 if (rettv_list_alloc(rettv) == OK)
13343 l = rettv->vval.v_list;
13344 l->lv_first = item;
13345 l->lv_last = item2;
13346 item->li_prev = NULL;
13347 item2->li_next = NULL;
13348 l->lv_len = cnt;
13358 * "rename({from}, {to})" function
13360 static void
13361 f_rename(argvars, rettv)
13362 typval_T *argvars;
13363 typval_T *rettv;
13365 char_u buf[NUMBUFLEN];
13367 if (check_restricted() || check_secure())
13368 rettv->vval.v_number = -1;
13369 else
13370 rettv->vval.v_number = vim_rename(get_tv_string(&argvars[0]),
13371 get_tv_string_buf(&argvars[1], buf));
13375 * "repeat()" function
13377 /*ARGSUSED*/
13378 static void
13379 f_repeat(argvars, rettv)
13380 typval_T *argvars;
13381 typval_T *rettv;
13383 char_u *p;
13384 int n;
13385 int slen;
13386 int len;
13387 char_u *r;
13388 int i;
13390 n = get_tv_number(&argvars[1]);
13391 if (argvars[0].v_type == VAR_LIST)
13393 if (rettv_list_alloc(rettv) == OK && argvars[0].vval.v_list != NULL)
13394 while (n-- > 0)
13395 if (list_extend(rettv->vval.v_list,
13396 argvars[0].vval.v_list, NULL) == FAIL)
13397 break;
13399 else
13401 p = get_tv_string(&argvars[0]);
13402 rettv->v_type = VAR_STRING;
13403 rettv->vval.v_string = NULL;
13405 slen = (int)STRLEN(p);
13406 len = slen * n;
13407 if (len <= 0)
13408 return;
13410 r = alloc(len + 1);
13411 if (r != NULL)
13413 for (i = 0; i < n; i++)
13414 mch_memmove(r + i * slen, p, (size_t)slen);
13415 r[len] = NUL;
13418 rettv->vval.v_string = r;
13423 * "resolve()" function
13425 static void
13426 f_resolve(argvars, rettv)
13427 typval_T *argvars;
13428 typval_T *rettv;
13430 char_u *p;
13432 p = get_tv_string(&argvars[0]);
13433 #ifdef FEAT_SHORTCUT
13435 char_u *v = NULL;
13437 v = mch_resolve_shortcut(p);
13438 if (v != NULL)
13439 rettv->vval.v_string = v;
13440 else
13441 rettv->vval.v_string = vim_strsave(p);
13443 #else
13444 # ifdef HAVE_READLINK
13446 char_u buf[MAXPATHL + 1];
13447 char_u *cpy;
13448 int len;
13449 char_u *remain = NULL;
13450 char_u *q;
13451 int is_relative_to_current = FALSE;
13452 int has_trailing_pathsep = FALSE;
13453 int limit = 100;
13455 p = vim_strsave(p);
13457 if (p[0] == '.' && (vim_ispathsep(p[1])
13458 || (p[1] == '.' && (vim_ispathsep(p[2])))))
13459 is_relative_to_current = TRUE;
13461 len = STRLEN(p);
13462 if (len > 0 && after_pathsep(p, p + len))
13463 has_trailing_pathsep = TRUE;
13465 q = getnextcomp(p);
13466 if (*q != NUL)
13468 /* Separate the first path component in "p", and keep the
13469 * remainder (beginning with the path separator). */
13470 remain = vim_strsave(q - 1);
13471 q[-1] = NUL;
13474 for (;;)
13476 for (;;)
13478 len = readlink((char *)p, (char *)buf, MAXPATHL);
13479 if (len <= 0)
13480 break;
13481 buf[len] = NUL;
13483 if (limit-- == 0)
13485 vim_free(p);
13486 vim_free(remain);
13487 EMSG(_("E655: Too many symbolic links (cycle?)"));
13488 rettv->vval.v_string = NULL;
13489 goto fail;
13492 /* Ensure that the result will have a trailing path separator
13493 * if the argument has one. */
13494 if (remain == NULL && has_trailing_pathsep)
13495 add_pathsep(buf);
13497 /* Separate the first path component in the link value and
13498 * concatenate the remainders. */
13499 q = getnextcomp(vim_ispathsep(*buf) ? buf + 1 : buf);
13500 if (*q != NUL)
13502 if (remain == NULL)
13503 remain = vim_strsave(q - 1);
13504 else
13506 cpy = concat_str(q - 1, remain);
13507 if (cpy != NULL)
13509 vim_free(remain);
13510 remain = cpy;
13513 q[-1] = NUL;
13516 q = gettail(p);
13517 if (q > p && *q == NUL)
13519 /* Ignore trailing path separator. */
13520 q[-1] = NUL;
13521 q = gettail(p);
13523 if (q > p && !mch_isFullName(buf))
13525 /* symlink is relative to directory of argument */
13526 cpy = alloc((unsigned)(STRLEN(p) + STRLEN(buf) + 1));
13527 if (cpy != NULL)
13529 STRCPY(cpy, p);
13530 STRCPY(gettail(cpy), buf);
13531 vim_free(p);
13532 p = cpy;
13535 else
13537 vim_free(p);
13538 p = vim_strsave(buf);
13542 if (remain == NULL)
13543 break;
13545 /* Append the first path component of "remain" to "p". */
13546 q = getnextcomp(remain + 1);
13547 len = q - remain - (*q != NUL);
13548 cpy = vim_strnsave(p, STRLEN(p) + len);
13549 if (cpy != NULL)
13551 STRNCAT(cpy, remain, len);
13552 vim_free(p);
13553 p = cpy;
13555 /* Shorten "remain". */
13556 if (*q != NUL)
13557 STRCPY(remain, q - 1);
13558 else
13560 vim_free(remain);
13561 remain = NULL;
13565 /* If the result is a relative path name, make it explicitly relative to
13566 * the current directory if and only if the argument had this form. */
13567 if (!vim_ispathsep(*p))
13569 if (is_relative_to_current
13570 && *p != NUL
13571 && !(p[0] == '.'
13572 && (p[1] == NUL
13573 || vim_ispathsep(p[1])
13574 || (p[1] == '.'
13575 && (p[2] == NUL
13576 || vim_ispathsep(p[2]))))))
13578 /* Prepend "./". */
13579 cpy = concat_str((char_u *)"./", p);
13580 if (cpy != NULL)
13582 vim_free(p);
13583 p = cpy;
13586 else if (!is_relative_to_current)
13588 /* Strip leading "./". */
13589 q = p;
13590 while (q[0] == '.' && vim_ispathsep(q[1]))
13591 q += 2;
13592 if (q > p)
13593 mch_memmove(p, p + 2, STRLEN(p + 2) + (size_t)1);
13597 /* Ensure that the result will have no trailing path separator
13598 * if the argument had none. But keep "/" or "//". */
13599 if (!has_trailing_pathsep)
13601 q = p + STRLEN(p);
13602 if (after_pathsep(p, q))
13603 *gettail_sep(p) = NUL;
13606 rettv->vval.v_string = p;
13608 # else
13609 rettv->vval.v_string = vim_strsave(p);
13610 # endif
13611 #endif
13613 simplify_filename(rettv->vval.v_string);
13615 #ifdef HAVE_READLINK
13616 fail:
13617 #endif
13618 rettv->v_type = VAR_STRING;
13622 * "reverse({list})" function
13624 static void
13625 f_reverse(argvars, rettv)
13626 typval_T *argvars;
13627 typval_T *rettv;
13629 list_T *l;
13630 listitem_T *li, *ni;
13632 rettv->vval.v_number = 0;
13633 if (argvars[0].v_type != VAR_LIST)
13634 EMSG2(_(e_listarg), "reverse()");
13635 else if ((l = argvars[0].vval.v_list) != NULL
13636 && !tv_check_lock(l->lv_lock, (char_u *)"reverse()"))
13638 li = l->lv_last;
13639 l->lv_first = l->lv_last = NULL;
13640 l->lv_len = 0;
13641 while (li != NULL)
13643 ni = li->li_prev;
13644 list_append(l, li);
13645 li = ni;
13647 rettv->vval.v_list = l;
13648 rettv->v_type = VAR_LIST;
13649 ++l->lv_refcount;
13653 #define SP_NOMOVE 0x01 /* don't move cursor */
13654 #define SP_REPEAT 0x02 /* repeat to find outer pair */
13655 #define SP_RETCOUNT 0x04 /* return matchcount */
13656 #define SP_SETPCMARK 0x08 /* set previous context mark */
13657 #define SP_START 0x10 /* accept match at start position */
13658 #define SP_SUBPAT 0x20 /* return nr of matching sub-pattern */
13659 #define SP_END 0x40 /* leave cursor at end of match */
13661 static int get_search_arg __ARGS((typval_T *varp, int *flagsp));
13664 * Get flags for a search function.
13665 * Possibly sets "p_ws".
13666 * Returns BACKWARD, FORWARD or zero (for an error).
13668 static int
13669 get_search_arg(varp, flagsp)
13670 typval_T *varp;
13671 int *flagsp;
13673 int dir = FORWARD;
13674 char_u *flags;
13675 char_u nbuf[NUMBUFLEN];
13676 int mask;
13678 if (varp->v_type != VAR_UNKNOWN)
13680 flags = get_tv_string_buf_chk(varp, nbuf);
13681 if (flags == NULL)
13682 return 0; /* type error; errmsg already given */
13683 while (*flags != NUL)
13685 switch (*flags)
13687 case 'b': dir = BACKWARD; break;
13688 case 'w': p_ws = TRUE; break;
13689 case 'W': p_ws = FALSE; break;
13690 default: mask = 0;
13691 if (flagsp != NULL)
13692 switch (*flags)
13694 case 'c': mask = SP_START; break;
13695 case 'e': mask = SP_END; break;
13696 case 'm': mask = SP_RETCOUNT; break;
13697 case 'n': mask = SP_NOMOVE; break;
13698 case 'p': mask = SP_SUBPAT; break;
13699 case 'r': mask = SP_REPEAT; break;
13700 case 's': mask = SP_SETPCMARK; break;
13702 if (mask == 0)
13704 EMSG2(_(e_invarg2), flags);
13705 dir = 0;
13707 else
13708 *flagsp |= mask;
13710 if (dir == 0)
13711 break;
13712 ++flags;
13715 return dir;
13719 * Shared by search() and searchpos() functions
13721 static int
13722 search_cmn(argvars, match_pos, flagsp)
13723 typval_T *argvars;
13724 pos_T *match_pos;
13725 int *flagsp;
13727 int flags;
13728 char_u *pat;
13729 pos_T pos;
13730 pos_T save_cursor;
13731 int save_p_ws = p_ws;
13732 int dir;
13733 int retval = 0; /* default: FAIL */
13734 long lnum_stop = 0;
13735 int options = SEARCH_KEEP;
13736 int subpatnum;
13738 pat = get_tv_string(&argvars[0]);
13739 dir = get_search_arg(&argvars[1], flagsp); /* may set p_ws */
13740 if (dir == 0)
13741 goto theend;
13742 flags = *flagsp;
13743 if (flags & SP_START)
13744 options |= SEARCH_START;
13745 if (flags & SP_END)
13746 options |= SEARCH_END;
13748 /* Optional extra argument: line number to stop searching. */
13749 if (argvars[1].v_type != VAR_UNKNOWN
13750 && argvars[2].v_type != VAR_UNKNOWN)
13752 lnum_stop = get_tv_number_chk(&argvars[2], NULL);
13753 if (lnum_stop < 0)
13754 goto theend;
13758 * This function does not accept SP_REPEAT and SP_RETCOUNT flags.
13759 * Check to make sure only those flags are set.
13760 * Also, Only the SP_NOMOVE or the SP_SETPCMARK flag can be set. Both
13761 * flags cannot be set. Check for that condition also.
13763 if (((flags & (SP_REPEAT | SP_RETCOUNT)) != 0)
13764 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
13766 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
13767 goto theend;
13770 pos = save_cursor = curwin->w_cursor;
13771 subpatnum = searchit(curwin, curbuf, &pos, dir, pat, 1L,
13772 options, RE_SEARCH, (linenr_T)lnum_stop);
13773 if (subpatnum != FAIL)
13775 if (flags & SP_SUBPAT)
13776 retval = subpatnum;
13777 else
13778 retval = pos.lnum;
13779 if (flags & SP_SETPCMARK)
13780 setpcmark();
13781 curwin->w_cursor = pos;
13782 if (match_pos != NULL)
13784 /* Store the match cursor position */
13785 match_pos->lnum = pos.lnum;
13786 match_pos->col = pos.col + 1;
13788 /* "/$" will put the cursor after the end of the line, may need to
13789 * correct that here */
13790 check_cursor();
13793 /* If 'n' flag is used: restore cursor position. */
13794 if (flags & SP_NOMOVE)
13795 curwin->w_cursor = save_cursor;
13796 theend:
13797 p_ws = save_p_ws;
13799 return retval;
13803 * "search()" function
13805 static void
13806 f_search(argvars, rettv)
13807 typval_T *argvars;
13808 typval_T *rettv;
13810 int flags = 0;
13812 rettv->vval.v_number = search_cmn(argvars, NULL, &flags);
13816 * "searchdecl()" function
13818 static void
13819 f_searchdecl(argvars, rettv)
13820 typval_T *argvars;
13821 typval_T *rettv;
13823 int locally = 1;
13824 int thisblock = 0;
13825 int error = FALSE;
13826 char_u *name;
13828 rettv->vval.v_number = 1; /* default: FAIL */
13830 name = get_tv_string_chk(&argvars[0]);
13831 if (argvars[1].v_type != VAR_UNKNOWN)
13833 locally = get_tv_number_chk(&argvars[1], &error) == 0;
13834 if (!error && argvars[2].v_type != VAR_UNKNOWN)
13835 thisblock = get_tv_number_chk(&argvars[2], &error) != 0;
13837 if (!error && name != NULL)
13838 rettv->vval.v_number = find_decl(name, (int)STRLEN(name),
13839 locally, thisblock, SEARCH_KEEP) == FAIL;
13843 * Used by searchpair() and searchpairpos()
13845 static int
13846 searchpair_cmn(argvars, match_pos)
13847 typval_T *argvars;
13848 pos_T *match_pos;
13850 char_u *spat, *mpat, *epat;
13851 char_u *skip;
13852 int save_p_ws = p_ws;
13853 int dir;
13854 int flags = 0;
13855 char_u nbuf1[NUMBUFLEN];
13856 char_u nbuf2[NUMBUFLEN];
13857 char_u nbuf3[NUMBUFLEN];
13858 int retval = 0; /* default: FAIL */
13859 long lnum_stop = 0;
13861 /* Get the three pattern arguments: start, middle, end. */
13862 spat = get_tv_string_chk(&argvars[0]);
13863 mpat = get_tv_string_buf_chk(&argvars[1], nbuf1);
13864 epat = get_tv_string_buf_chk(&argvars[2], nbuf2);
13865 if (spat == NULL || mpat == NULL || epat == NULL)
13866 goto theend; /* type error */
13868 /* Handle the optional fourth argument: flags */
13869 dir = get_search_arg(&argvars[3], &flags); /* may set p_ws */
13870 if (dir == 0)
13871 goto theend;
13873 /* Don't accept SP_END or SP_SUBPAT.
13874 * Only one of the SP_NOMOVE or SP_SETPCMARK flags can be set.
13876 if ((flags & (SP_END | SP_SUBPAT)) != 0
13877 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
13879 EMSG2(_(e_invarg2), get_tv_string(&argvars[3]));
13880 goto theend;
13883 /* Optional fifth argument: skip expression */
13884 if (argvars[3].v_type == VAR_UNKNOWN
13885 || argvars[4].v_type == VAR_UNKNOWN)
13886 skip = (char_u *)"";
13887 else
13889 skip = get_tv_string_buf_chk(&argvars[4], nbuf3);
13890 if (argvars[5].v_type != VAR_UNKNOWN)
13892 lnum_stop = get_tv_number_chk(&argvars[5], NULL);
13893 if (lnum_stop < 0)
13894 goto theend;
13897 if (skip == NULL)
13898 goto theend; /* type error */
13900 retval = do_searchpair(spat, mpat, epat, dir, skip, flags,
13901 match_pos, lnum_stop);
13903 theend:
13904 p_ws = save_p_ws;
13906 return retval;
13910 * "searchpair()" function
13912 static void
13913 f_searchpair(argvars, rettv)
13914 typval_T *argvars;
13915 typval_T *rettv;
13917 rettv->vval.v_number = searchpair_cmn(argvars, NULL);
13921 * "searchpairpos()" function
13923 static void
13924 f_searchpairpos(argvars, rettv)
13925 typval_T *argvars;
13926 typval_T *rettv;
13928 pos_T match_pos;
13929 int lnum = 0;
13930 int col = 0;
13932 rettv->vval.v_number = 0;
13934 if (rettv_list_alloc(rettv) == FAIL)
13935 return;
13937 if (searchpair_cmn(argvars, &match_pos) > 0)
13939 lnum = match_pos.lnum;
13940 col = match_pos.col;
13943 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
13944 list_append_number(rettv->vval.v_list, (varnumber_T)col);
13948 * Search for a start/middle/end thing.
13949 * Used by searchpair(), see its documentation for the details.
13950 * Returns 0 or -1 for no match,
13952 long
13953 do_searchpair(spat, mpat, epat, dir, skip, flags, match_pos, lnum_stop)
13954 char_u *spat; /* start pattern */
13955 char_u *mpat; /* middle pattern */
13956 char_u *epat; /* end pattern */
13957 int dir; /* BACKWARD or FORWARD */
13958 char_u *skip; /* skip expression */
13959 int flags; /* SP_SETPCMARK and other SP_ values */
13960 pos_T *match_pos;
13961 linenr_T lnum_stop; /* stop at this line if not zero */
13963 char_u *save_cpo;
13964 char_u *pat, *pat2 = NULL, *pat3 = NULL;
13965 long retval = 0;
13966 pos_T pos;
13967 pos_T firstpos;
13968 pos_T foundpos;
13969 pos_T save_cursor;
13970 pos_T save_pos;
13971 int n;
13972 int r;
13973 int nest = 1;
13974 int err;
13975 int options = SEARCH_KEEP;
13977 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
13978 save_cpo = p_cpo;
13979 p_cpo = (char_u *)"";
13981 /* Make two search patterns: start/end (pat2, for in nested pairs) and
13982 * start/middle/end (pat3, for the top pair). */
13983 pat2 = alloc((unsigned)(STRLEN(spat) + STRLEN(epat) + 15));
13984 pat3 = alloc((unsigned)(STRLEN(spat) + STRLEN(mpat) + STRLEN(epat) + 23));
13985 if (pat2 == NULL || pat3 == NULL)
13986 goto theend;
13987 sprintf((char *)pat2, "\\(%s\\m\\)\\|\\(%s\\m\\)", spat, epat);
13988 if (*mpat == NUL)
13989 STRCPY(pat3, pat2);
13990 else
13991 sprintf((char *)pat3, "\\(%s\\m\\)\\|\\(%s\\m\\)\\|\\(%s\\m\\)",
13992 spat, epat, mpat);
13993 if (flags & SP_START)
13994 options |= SEARCH_START;
13996 save_cursor = curwin->w_cursor;
13997 pos = curwin->w_cursor;
13998 clearpos(&firstpos);
13999 clearpos(&foundpos);
14000 pat = pat3;
14001 for (;;)
14003 n = searchit(curwin, curbuf, &pos, dir, pat, 1L,
14004 options, RE_SEARCH, lnum_stop);
14005 if (n == FAIL || (firstpos.lnum != 0 && equalpos(pos, firstpos)))
14006 /* didn't find it or found the first match again: FAIL */
14007 break;
14009 if (firstpos.lnum == 0)
14010 firstpos = pos;
14011 if (equalpos(pos, foundpos))
14013 /* Found the same position again. Can happen with a pattern that
14014 * has "\zs" at the end and searching backwards. Advance one
14015 * character and try again. */
14016 if (dir == BACKWARD)
14017 decl(&pos);
14018 else
14019 incl(&pos);
14021 foundpos = pos;
14023 /* If the skip pattern matches, ignore this match. */
14024 if (*skip != NUL)
14026 save_pos = curwin->w_cursor;
14027 curwin->w_cursor = pos;
14028 r = eval_to_bool(skip, &err, NULL, FALSE);
14029 curwin->w_cursor = save_pos;
14030 if (err)
14032 /* Evaluating {skip} caused an error, break here. */
14033 curwin->w_cursor = save_cursor;
14034 retval = -1;
14035 break;
14037 if (r)
14038 continue;
14041 if ((dir == BACKWARD && n == 3) || (dir == FORWARD && n == 2))
14043 /* Found end when searching backwards or start when searching
14044 * forward: nested pair. */
14045 ++nest;
14046 pat = pat2; /* nested, don't search for middle */
14048 else
14050 /* Found end when searching forward or start when searching
14051 * backward: end of (nested) pair; or found middle in outer pair. */
14052 if (--nest == 1)
14053 pat = pat3; /* outer level, search for middle */
14056 if (nest == 0)
14058 /* Found the match: return matchcount or line number. */
14059 if (flags & SP_RETCOUNT)
14060 ++retval;
14061 else
14062 retval = pos.lnum;
14063 if (flags & SP_SETPCMARK)
14064 setpcmark();
14065 curwin->w_cursor = pos;
14066 if (!(flags & SP_REPEAT))
14067 break;
14068 nest = 1; /* search for next unmatched */
14072 if (match_pos != NULL)
14074 /* Store the match cursor position */
14075 match_pos->lnum = curwin->w_cursor.lnum;
14076 match_pos->col = curwin->w_cursor.col + 1;
14079 /* If 'n' flag is used or search failed: restore cursor position. */
14080 if ((flags & SP_NOMOVE) || retval == 0)
14081 curwin->w_cursor = save_cursor;
14083 theend:
14084 vim_free(pat2);
14085 vim_free(pat3);
14086 p_cpo = save_cpo;
14088 return retval;
14092 * "searchpos()" function
14094 static void
14095 f_searchpos(argvars, rettv)
14096 typval_T *argvars;
14097 typval_T *rettv;
14099 pos_T match_pos;
14100 int lnum = 0;
14101 int col = 0;
14102 int n;
14103 int flags = 0;
14105 rettv->vval.v_number = 0;
14107 if (rettv_list_alloc(rettv) == FAIL)
14108 return;
14110 n = search_cmn(argvars, &match_pos, &flags);
14111 if (n > 0)
14113 lnum = match_pos.lnum;
14114 col = match_pos.col;
14117 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
14118 list_append_number(rettv->vval.v_list, (varnumber_T)col);
14119 if (flags & SP_SUBPAT)
14120 list_append_number(rettv->vval.v_list, (varnumber_T)n);
14124 /*ARGSUSED*/
14125 static void
14126 f_server2client(argvars, rettv)
14127 typval_T *argvars;
14128 typval_T *rettv;
14130 #ifdef FEAT_CLIENTSERVER
14131 char_u buf[NUMBUFLEN];
14132 char_u *server = get_tv_string_chk(&argvars[0]);
14133 char_u *reply = get_tv_string_buf_chk(&argvars[1], buf);
14135 rettv->vval.v_number = -1;
14136 if (server == NULL || reply == NULL)
14137 return;
14138 if (check_restricted() || check_secure())
14139 return;
14140 # ifdef FEAT_X11
14141 if (check_connection() == FAIL)
14142 return;
14143 # endif
14145 if (serverSendReply(server, reply) < 0)
14147 EMSG(_("E258: Unable to send to client"));
14148 return;
14150 rettv->vval.v_number = 0;
14151 #else
14152 rettv->vval.v_number = -1;
14153 #endif
14156 /*ARGSUSED*/
14157 static void
14158 f_serverlist(argvars, rettv)
14159 typval_T *argvars;
14160 typval_T *rettv;
14162 char_u *r = NULL;
14164 #ifdef FEAT_CLIENTSERVER
14165 # ifdef WIN32
14166 r = serverGetVimNames();
14167 # else
14168 make_connection();
14169 if (X_DISPLAY != NULL)
14170 r = serverGetVimNames(X_DISPLAY);
14171 # endif
14172 #endif
14173 rettv->v_type = VAR_STRING;
14174 rettv->vval.v_string = r;
14178 * "setbufvar()" function
14180 /*ARGSUSED*/
14181 static void
14182 f_setbufvar(argvars, rettv)
14183 typval_T *argvars;
14184 typval_T *rettv;
14186 buf_T *buf;
14187 aco_save_T aco;
14188 char_u *varname, *bufvarname;
14189 typval_T *varp;
14190 char_u nbuf[NUMBUFLEN];
14192 rettv->vval.v_number = 0;
14194 if (check_restricted() || check_secure())
14195 return;
14196 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
14197 varname = get_tv_string_chk(&argvars[1]);
14198 buf = get_buf_tv(&argvars[0]);
14199 varp = &argvars[2];
14201 if (buf != NULL && varname != NULL && varp != NULL)
14203 /* set curbuf to be our buf, temporarily */
14204 aucmd_prepbuf(&aco, buf);
14206 if (*varname == '&')
14208 long numval;
14209 char_u *strval;
14210 int error = FALSE;
14212 ++varname;
14213 numval = get_tv_number_chk(varp, &error);
14214 strval = get_tv_string_buf_chk(varp, nbuf);
14215 if (!error && strval != NULL)
14216 set_option_value(varname, numval, strval, OPT_LOCAL);
14218 else
14220 bufvarname = alloc((unsigned)STRLEN(varname) + 3);
14221 if (bufvarname != NULL)
14223 STRCPY(bufvarname, "b:");
14224 STRCPY(bufvarname + 2, varname);
14225 set_var(bufvarname, varp, TRUE);
14226 vim_free(bufvarname);
14230 /* reset notion of buffer */
14231 aucmd_restbuf(&aco);
14236 * "setcmdpos()" function
14238 static void
14239 f_setcmdpos(argvars, rettv)
14240 typval_T *argvars;
14241 typval_T *rettv;
14243 int pos = (int)get_tv_number(&argvars[0]) - 1;
14245 if (pos >= 0)
14246 rettv->vval.v_number = set_cmdline_pos(pos);
14250 * "setline()" function
14252 static void
14253 f_setline(argvars, rettv)
14254 typval_T *argvars;
14255 typval_T *rettv;
14257 linenr_T lnum;
14258 char_u *line = NULL;
14259 list_T *l = NULL;
14260 listitem_T *li = NULL;
14261 long added = 0;
14262 linenr_T lcount = curbuf->b_ml.ml_line_count;
14264 lnum = get_tv_lnum(&argvars[0]);
14265 if (argvars[1].v_type == VAR_LIST)
14267 l = argvars[1].vval.v_list;
14268 li = l->lv_first;
14270 else
14271 line = get_tv_string_chk(&argvars[1]);
14273 rettv->vval.v_number = 0; /* OK */
14274 for (;;)
14276 if (l != NULL)
14278 /* list argument, get next string */
14279 if (li == NULL)
14280 break;
14281 line = get_tv_string_chk(&li->li_tv);
14282 li = li->li_next;
14285 rettv->vval.v_number = 1; /* FAIL */
14286 if (line == NULL || lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
14287 break;
14288 if (lnum <= curbuf->b_ml.ml_line_count)
14290 /* existing line, replace it */
14291 if (u_savesub(lnum) == OK && ml_replace(lnum, line, TRUE) == OK)
14293 changed_bytes(lnum, 0);
14294 check_cursor_col();
14295 rettv->vval.v_number = 0; /* OK */
14298 else if (added > 0 || u_save(lnum - 1, lnum) == OK)
14300 /* lnum is one past the last line, append the line */
14301 ++added;
14302 if (ml_append(lnum - 1, line, (colnr_T)0, FALSE) == OK)
14303 rettv->vval.v_number = 0; /* OK */
14306 if (l == NULL) /* only one string argument */
14307 break;
14308 ++lnum;
14311 if (added > 0)
14312 appended_lines_mark(lcount, added);
14316 * Used by "setqflist()" and "setloclist()" functions
14318 /*ARGSUSED*/
14319 static void
14320 set_qf_ll_list(wp, list_arg, action_arg, rettv)
14321 win_T *wp;
14322 typval_T *list_arg;
14323 typval_T *action_arg;
14324 typval_T *rettv;
14326 #ifdef FEAT_QUICKFIX
14327 char_u *act;
14328 int action = ' ';
14329 #endif
14331 rettv->vval.v_number = -1;
14333 #ifdef FEAT_QUICKFIX
14334 if (list_arg->v_type != VAR_LIST)
14335 EMSG(_(e_listreq));
14336 else
14338 list_T *l = list_arg->vval.v_list;
14340 if (action_arg->v_type == VAR_STRING)
14342 act = get_tv_string_chk(action_arg);
14343 if (act == NULL)
14344 return; /* type error; errmsg already given */
14345 if (*act == 'a' || *act == 'r')
14346 action = *act;
14349 if (l != NULL && set_errorlist(wp, l, action) == OK)
14350 rettv->vval.v_number = 0;
14352 #endif
14356 * "setloclist()" function
14358 /*ARGSUSED*/
14359 static void
14360 f_setloclist(argvars, rettv)
14361 typval_T *argvars;
14362 typval_T *rettv;
14364 win_T *win;
14366 rettv->vval.v_number = -1;
14368 win = find_win_by_nr(&argvars[0], NULL);
14369 if (win != NULL)
14370 set_qf_ll_list(win, &argvars[1], &argvars[2], rettv);
14374 * "setpos()" function
14376 /*ARGSUSED*/
14377 static void
14378 f_setpos(argvars, rettv)
14379 typval_T *argvars;
14380 typval_T *rettv;
14382 pos_T pos;
14383 int fnum;
14384 char_u *name;
14386 name = get_tv_string_chk(argvars);
14387 if (name != NULL)
14389 if (list2fpos(&argvars[1], &pos, &fnum) == OK)
14391 --pos.col;
14392 if (name[0] == '.') /* cursor */
14394 if (fnum == curbuf->b_fnum)
14396 curwin->w_cursor = pos;
14397 check_cursor();
14399 else
14400 EMSG(_(e_invarg));
14402 else if (name[0] == '\'') /* mark */
14403 (void)setmark_pos(name[1], &pos, fnum);
14404 else
14405 EMSG(_(e_invarg));
14411 * "setqflist()" function
14413 /*ARGSUSED*/
14414 static void
14415 f_setqflist(argvars, rettv)
14416 typval_T *argvars;
14417 typval_T *rettv;
14419 set_qf_ll_list(NULL, &argvars[0], &argvars[1], rettv);
14423 * "setreg()" function
14425 static void
14426 f_setreg(argvars, rettv)
14427 typval_T *argvars;
14428 typval_T *rettv;
14430 int regname;
14431 char_u *strregname;
14432 char_u *stropt;
14433 char_u *strval;
14434 int append;
14435 char_u yank_type;
14436 long block_len;
14438 block_len = -1;
14439 yank_type = MAUTO;
14440 append = FALSE;
14442 strregname = get_tv_string_chk(argvars);
14443 rettv->vval.v_number = 1; /* FAIL is default */
14445 if (strregname == NULL)
14446 return; /* type error; errmsg already given */
14447 regname = *strregname;
14448 if (regname == 0 || regname == '@')
14449 regname = '"';
14450 else if (regname == '=')
14451 return;
14453 if (argvars[2].v_type != VAR_UNKNOWN)
14455 stropt = get_tv_string_chk(&argvars[2]);
14456 if (stropt == NULL)
14457 return; /* type error */
14458 for (; *stropt != NUL; ++stropt)
14459 switch (*stropt)
14461 case 'a': case 'A': /* append */
14462 append = TRUE;
14463 break;
14464 case 'v': case 'c': /* character-wise selection */
14465 yank_type = MCHAR;
14466 break;
14467 case 'V': case 'l': /* line-wise selection */
14468 yank_type = MLINE;
14469 break;
14470 #ifdef FEAT_VISUAL
14471 case 'b': case Ctrl_V: /* block-wise selection */
14472 yank_type = MBLOCK;
14473 if (VIM_ISDIGIT(stropt[1]))
14475 ++stropt;
14476 block_len = getdigits(&stropt) - 1;
14477 --stropt;
14479 break;
14480 #endif
14484 strval = get_tv_string_chk(&argvars[1]);
14485 if (strval != NULL)
14486 write_reg_contents_ex(regname, strval, -1,
14487 append, yank_type, block_len);
14488 rettv->vval.v_number = 0;
14492 * "settabwinvar()" function
14494 static void
14495 f_settabwinvar(argvars, rettv)
14496 typval_T *argvars;
14497 typval_T *rettv;
14499 setwinvar(argvars, rettv, 1);
14503 * "setwinvar()" function
14505 static void
14506 f_setwinvar(argvars, rettv)
14507 typval_T *argvars;
14508 typval_T *rettv;
14510 setwinvar(argvars, rettv, 0);
14514 * "setwinvar()" and "settabwinvar()" functions
14516 static void
14517 setwinvar(argvars, rettv, off)
14518 typval_T *argvars;
14519 typval_T *rettv;
14520 int off;
14522 win_T *win;
14523 #ifdef FEAT_WINDOWS
14524 win_T *save_curwin;
14525 tabpage_T *save_curtab;
14526 #endif
14527 char_u *varname, *winvarname;
14528 typval_T *varp;
14529 char_u nbuf[NUMBUFLEN];
14530 tabpage_T *tp;
14532 rettv->vval.v_number = 0;
14534 if (check_restricted() || check_secure())
14535 return;
14537 #ifdef FEAT_WINDOWS
14538 if (off == 1)
14539 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
14540 else
14541 tp = curtab;
14542 #endif
14543 win = find_win_by_nr(&argvars[off], tp);
14544 varname = get_tv_string_chk(&argvars[off + 1]);
14545 varp = &argvars[off + 2];
14547 if (win != NULL && varname != NULL && varp != NULL)
14549 #ifdef FEAT_WINDOWS
14550 /* set curwin to be our win, temporarily */
14551 save_curwin = curwin;
14552 save_curtab = curtab;
14553 goto_tabpage_tp(tp);
14554 if (!win_valid(win))
14555 return;
14556 curwin = win;
14557 curbuf = curwin->w_buffer;
14558 #endif
14560 if (*varname == '&')
14562 long numval;
14563 char_u *strval;
14564 int error = FALSE;
14566 ++varname;
14567 numval = get_tv_number_chk(varp, &error);
14568 strval = get_tv_string_buf_chk(varp, nbuf);
14569 if (!error && strval != NULL)
14570 set_option_value(varname, numval, strval, OPT_LOCAL);
14572 else
14574 winvarname = alloc((unsigned)STRLEN(varname) + 3);
14575 if (winvarname != NULL)
14577 STRCPY(winvarname, "w:");
14578 STRCPY(winvarname + 2, varname);
14579 set_var(winvarname, varp, TRUE);
14580 vim_free(winvarname);
14584 #ifdef FEAT_WINDOWS
14585 /* Restore current tabpage and window, if still valid (autocomands can
14586 * make them invalid). */
14587 if (valid_tabpage(save_curtab))
14588 goto_tabpage_tp(save_curtab);
14589 if (win_valid(save_curwin))
14591 curwin = save_curwin;
14592 curbuf = curwin->w_buffer;
14594 #endif
14599 * "simplify()" function
14601 static void
14602 f_simplify(argvars, rettv)
14603 typval_T *argvars;
14604 typval_T *rettv;
14606 char_u *p;
14608 p = get_tv_string(&argvars[0]);
14609 rettv->vval.v_string = vim_strsave(p);
14610 simplify_filename(rettv->vval.v_string); /* simplify in place */
14611 rettv->v_type = VAR_STRING;
14614 static int
14615 #ifdef __BORLANDC__
14616 _RTLENTRYF
14617 #endif
14618 item_compare __ARGS((const void *s1, const void *s2));
14619 static int
14620 #ifdef __BORLANDC__
14621 _RTLENTRYF
14622 #endif
14623 item_compare2 __ARGS((const void *s1, const void *s2));
14625 static int item_compare_ic;
14626 static char_u *item_compare_func;
14627 static int item_compare_func_err;
14628 #define ITEM_COMPARE_FAIL 999
14631 * Compare functions for f_sort() below.
14633 static int
14634 #ifdef __BORLANDC__
14635 _RTLENTRYF
14636 #endif
14637 item_compare(s1, s2)
14638 const void *s1;
14639 const void *s2;
14641 char_u *p1, *p2;
14642 char_u *tofree1, *tofree2;
14643 int res;
14644 char_u numbuf1[NUMBUFLEN];
14645 char_u numbuf2[NUMBUFLEN];
14647 p1 = tv2string(&(*(listitem_T **)s1)->li_tv, &tofree1, numbuf1, 0);
14648 p2 = tv2string(&(*(listitem_T **)s2)->li_tv, &tofree2, numbuf2, 0);
14649 if (item_compare_ic)
14650 res = STRICMP(p1, p2);
14651 else
14652 res = STRCMP(p1, p2);
14653 vim_free(tofree1);
14654 vim_free(tofree2);
14655 return res;
14658 static int
14659 #ifdef __BORLANDC__
14660 _RTLENTRYF
14661 #endif
14662 item_compare2(s1, s2)
14663 const void *s1;
14664 const void *s2;
14666 int res;
14667 typval_T rettv;
14668 typval_T argv[3];
14669 int dummy;
14671 /* shortcut after failure in previous call; compare all items equal */
14672 if (item_compare_func_err)
14673 return 0;
14675 /* copy the values. This is needed to be able to set v_lock to VAR_FIXED
14676 * in the copy without changing the original list items. */
14677 copy_tv(&(*(listitem_T **)s1)->li_tv, &argv[0]);
14678 copy_tv(&(*(listitem_T **)s2)->li_tv, &argv[1]);
14680 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
14681 res = call_func(item_compare_func, (int)STRLEN(item_compare_func),
14682 &rettv, 2, argv, 0L, 0L, &dummy, TRUE, NULL);
14683 clear_tv(&argv[0]);
14684 clear_tv(&argv[1]);
14686 if (res == FAIL)
14687 res = ITEM_COMPARE_FAIL;
14688 else
14689 /* return value has wrong type */
14690 res = get_tv_number_chk(&rettv, &item_compare_func_err);
14691 if (item_compare_func_err)
14692 res = ITEM_COMPARE_FAIL;
14693 clear_tv(&rettv);
14694 return res;
14698 * "sort({list})" function
14700 static void
14701 f_sort(argvars, rettv)
14702 typval_T *argvars;
14703 typval_T *rettv;
14705 list_T *l;
14706 listitem_T *li;
14707 listitem_T **ptrs;
14708 long len;
14709 long i;
14711 rettv->vval.v_number = 0;
14712 if (argvars[0].v_type != VAR_LIST)
14713 EMSG2(_(e_listarg), "sort()");
14714 else
14716 l = argvars[0].vval.v_list;
14717 if (l == NULL || tv_check_lock(l->lv_lock, (char_u *)"sort()"))
14718 return;
14719 rettv->vval.v_list = l;
14720 rettv->v_type = VAR_LIST;
14721 ++l->lv_refcount;
14723 len = list_len(l);
14724 if (len <= 1)
14725 return; /* short list sorts pretty quickly */
14727 item_compare_ic = FALSE;
14728 item_compare_func = NULL;
14729 if (argvars[1].v_type != VAR_UNKNOWN)
14731 if (argvars[1].v_type == VAR_FUNC)
14732 item_compare_func = argvars[1].vval.v_string;
14733 else
14735 int error = FALSE;
14737 i = get_tv_number_chk(&argvars[1], &error);
14738 if (error)
14739 return; /* type error; errmsg already given */
14740 if (i == 1)
14741 item_compare_ic = TRUE;
14742 else
14743 item_compare_func = get_tv_string(&argvars[1]);
14747 /* Make an array with each entry pointing to an item in the List. */
14748 ptrs = (listitem_T **)alloc((int)(len * sizeof(listitem_T *)));
14749 if (ptrs == NULL)
14750 return;
14751 i = 0;
14752 for (li = l->lv_first; li != NULL; li = li->li_next)
14753 ptrs[i++] = li;
14755 item_compare_func_err = FALSE;
14756 /* test the compare function */
14757 if (item_compare_func != NULL
14758 && item_compare2((void *)&ptrs[0], (void *)&ptrs[1])
14759 == ITEM_COMPARE_FAIL)
14760 EMSG(_("E702: Sort compare function failed"));
14761 else
14763 /* Sort the array with item pointers. */
14764 qsort((void *)ptrs, (size_t)len, sizeof(listitem_T *),
14765 item_compare_func == NULL ? item_compare : item_compare2);
14767 if (!item_compare_func_err)
14769 /* Clear the List and append the items in the sorted order. */
14770 l->lv_first = l->lv_last = NULL;
14771 l->lv_len = 0;
14772 for (i = 0; i < len; ++i)
14773 list_append(l, ptrs[i]);
14777 vim_free(ptrs);
14782 * "soundfold({word})" function
14784 static void
14785 f_soundfold(argvars, rettv)
14786 typval_T *argvars;
14787 typval_T *rettv;
14789 char_u *s;
14791 rettv->v_type = VAR_STRING;
14792 s = get_tv_string(&argvars[0]);
14793 #ifdef FEAT_SPELL
14794 rettv->vval.v_string = eval_soundfold(s);
14795 #else
14796 rettv->vval.v_string = vim_strsave(s);
14797 #endif
14801 * "spellbadword()" function
14803 /* ARGSUSED */
14804 static void
14805 f_spellbadword(argvars, rettv)
14806 typval_T *argvars;
14807 typval_T *rettv;
14809 char_u *word = (char_u *)"";
14810 hlf_T attr = HLF_COUNT;
14811 int len = 0;
14813 if (rettv_list_alloc(rettv) == FAIL)
14814 return;
14816 #ifdef FEAT_SPELL
14817 if (argvars[0].v_type == VAR_UNKNOWN)
14819 /* Find the start and length of the badly spelled word. */
14820 len = spell_move_to(curwin, FORWARD, TRUE, TRUE, &attr);
14821 if (len != 0)
14822 word = ml_get_cursor();
14824 else if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
14826 char_u *str = get_tv_string_chk(&argvars[0]);
14827 int capcol = -1;
14829 if (str != NULL)
14831 /* Check the argument for spelling. */
14832 while (*str != NUL)
14834 len = spell_check(curwin, str, &attr, &capcol, FALSE);
14835 if (attr != HLF_COUNT)
14837 word = str;
14838 break;
14840 str += len;
14844 #endif
14846 list_append_string(rettv->vval.v_list, word, len);
14847 list_append_string(rettv->vval.v_list, (char_u *)(
14848 attr == HLF_SPB ? "bad" :
14849 attr == HLF_SPR ? "rare" :
14850 attr == HLF_SPL ? "local" :
14851 attr == HLF_SPC ? "caps" :
14852 ""), -1);
14856 * "spellsuggest()" function
14858 /*ARGSUSED*/
14859 static void
14860 f_spellsuggest(argvars, rettv)
14861 typval_T *argvars;
14862 typval_T *rettv;
14864 #ifdef FEAT_SPELL
14865 char_u *str;
14866 int typeerr = FALSE;
14867 int maxcount;
14868 garray_T ga;
14869 int i;
14870 listitem_T *li;
14871 int need_capital = FALSE;
14872 #endif
14874 if (rettv_list_alloc(rettv) == FAIL)
14875 return;
14877 #ifdef FEAT_SPELL
14878 if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
14880 str = get_tv_string(&argvars[0]);
14881 if (argvars[1].v_type != VAR_UNKNOWN)
14883 maxcount = get_tv_number_chk(&argvars[1], &typeerr);
14884 if (maxcount <= 0)
14885 return;
14886 if (argvars[2].v_type != VAR_UNKNOWN)
14888 need_capital = get_tv_number_chk(&argvars[2], &typeerr);
14889 if (typeerr)
14890 return;
14893 else
14894 maxcount = 25;
14896 spell_suggest_list(&ga, str, maxcount, need_capital, FALSE);
14898 for (i = 0; i < ga.ga_len; ++i)
14900 str = ((char_u **)ga.ga_data)[i];
14902 li = listitem_alloc();
14903 if (li == NULL)
14904 vim_free(str);
14905 else
14907 li->li_tv.v_type = VAR_STRING;
14908 li->li_tv.v_lock = 0;
14909 li->li_tv.vval.v_string = str;
14910 list_append(rettv->vval.v_list, li);
14913 ga_clear(&ga);
14915 #endif
14918 static void
14919 f_split(argvars, rettv)
14920 typval_T *argvars;
14921 typval_T *rettv;
14923 char_u *str;
14924 char_u *end;
14925 char_u *pat = NULL;
14926 regmatch_T regmatch;
14927 char_u patbuf[NUMBUFLEN];
14928 char_u *save_cpo;
14929 int match;
14930 colnr_T col = 0;
14931 int keepempty = FALSE;
14932 int typeerr = FALSE;
14934 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
14935 save_cpo = p_cpo;
14936 p_cpo = (char_u *)"";
14938 str = get_tv_string(&argvars[0]);
14939 if (argvars[1].v_type != VAR_UNKNOWN)
14941 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
14942 if (pat == NULL)
14943 typeerr = TRUE;
14944 if (argvars[2].v_type != VAR_UNKNOWN)
14945 keepempty = get_tv_number_chk(&argvars[2], &typeerr);
14947 if (pat == NULL || *pat == NUL)
14948 pat = (char_u *)"[\\x01- ]\\+";
14950 if (rettv_list_alloc(rettv) == FAIL)
14951 return;
14952 if (typeerr)
14953 return;
14955 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
14956 if (regmatch.regprog != NULL)
14958 regmatch.rm_ic = FALSE;
14959 while (*str != NUL || keepempty)
14961 if (*str == NUL)
14962 match = FALSE; /* empty item at the end */
14963 else
14964 match = vim_regexec_nl(&regmatch, str, col);
14965 if (match)
14966 end = regmatch.startp[0];
14967 else
14968 end = str + STRLEN(str);
14969 if (keepempty || end > str || (rettv->vval.v_list->lv_len > 0
14970 && *str != NUL && match && end < regmatch.endp[0]))
14972 if (list_append_string(rettv->vval.v_list, str,
14973 (int)(end - str)) == FAIL)
14974 break;
14976 if (!match)
14977 break;
14978 /* Advance to just after the match. */
14979 if (regmatch.endp[0] > str)
14980 col = 0;
14981 else
14983 /* Don't get stuck at the same match. */
14984 #ifdef FEAT_MBYTE
14985 col = (*mb_ptr2len)(regmatch.endp[0]);
14986 #else
14987 col = 1;
14988 #endif
14990 str = regmatch.endp[0];
14993 vim_free(regmatch.regprog);
14996 p_cpo = save_cpo;
15000 * "str2nr()" function
15002 static void
15003 f_str2nr(argvars, rettv)
15004 typval_T *argvars;
15005 typval_T *rettv;
15007 int base = 10;
15008 char_u *p;
15009 long n;
15011 if (argvars[1].v_type != VAR_UNKNOWN)
15013 base = get_tv_number(&argvars[1]);
15014 if (base != 8 && base != 10 && base != 16)
15016 EMSG(_(e_invarg));
15017 return;
15021 p = skipwhite(get_tv_string(&argvars[0]));
15022 vim_str2nr(p, NULL, NULL, base == 8 ? 2 : 0, base == 16 ? 2 : 0, &n, NULL);
15023 rettv->vval.v_number = n;
15026 #ifdef HAVE_STRFTIME
15028 * "strftime({format}[, {time}])" function
15030 static void
15031 f_strftime(argvars, rettv)
15032 typval_T *argvars;
15033 typval_T *rettv;
15035 char_u result_buf[256];
15036 struct tm *curtime;
15037 time_t seconds;
15038 char_u *p;
15040 rettv->v_type = VAR_STRING;
15042 p = get_tv_string(&argvars[0]);
15043 if (argvars[1].v_type == VAR_UNKNOWN)
15044 seconds = time(NULL);
15045 else
15046 seconds = (time_t)get_tv_number(&argvars[1]);
15047 curtime = localtime(&seconds);
15048 /* MSVC returns NULL for an invalid value of seconds. */
15049 if (curtime == NULL)
15050 rettv->vval.v_string = vim_strsave((char_u *)_("(Invalid)"));
15051 else
15053 # ifdef FEAT_MBYTE
15054 vimconv_T conv;
15055 char_u *enc;
15057 conv.vc_type = CONV_NONE;
15058 enc = enc_locale();
15059 convert_setup(&conv, p_enc, enc);
15060 if (conv.vc_type != CONV_NONE)
15061 p = string_convert(&conv, p, NULL);
15062 # endif
15063 if (p != NULL)
15064 (void)strftime((char *)result_buf, sizeof(result_buf),
15065 (char *)p, curtime);
15066 else
15067 result_buf[0] = NUL;
15069 # ifdef FEAT_MBYTE
15070 if (conv.vc_type != CONV_NONE)
15071 vim_free(p);
15072 convert_setup(&conv, enc, p_enc);
15073 if (conv.vc_type != CONV_NONE)
15074 rettv->vval.v_string = string_convert(&conv, result_buf, NULL);
15075 else
15076 # endif
15077 rettv->vval.v_string = vim_strsave(result_buf);
15079 # ifdef FEAT_MBYTE
15080 /* Release conversion descriptors */
15081 convert_setup(&conv, NULL, NULL);
15082 vim_free(enc);
15083 # endif
15086 #endif
15089 * "stridx()" function
15091 static void
15092 f_stridx(argvars, rettv)
15093 typval_T *argvars;
15094 typval_T *rettv;
15096 char_u buf[NUMBUFLEN];
15097 char_u *needle;
15098 char_u *haystack;
15099 char_u *save_haystack;
15100 char_u *pos;
15101 int start_idx;
15103 needle = get_tv_string_chk(&argvars[1]);
15104 save_haystack = haystack = get_tv_string_buf_chk(&argvars[0], buf);
15105 rettv->vval.v_number = -1;
15106 if (needle == NULL || haystack == NULL)
15107 return; /* type error; errmsg already given */
15109 if (argvars[2].v_type != VAR_UNKNOWN)
15111 int error = FALSE;
15113 start_idx = get_tv_number_chk(&argvars[2], &error);
15114 if (error || start_idx >= (int)STRLEN(haystack))
15115 return;
15116 if (start_idx >= 0)
15117 haystack += start_idx;
15120 pos = (char_u *)strstr((char *)haystack, (char *)needle);
15121 if (pos != NULL)
15122 rettv->vval.v_number = (varnumber_T)(pos - save_haystack);
15126 * "string()" function
15128 static void
15129 f_string(argvars, rettv)
15130 typval_T *argvars;
15131 typval_T *rettv;
15133 char_u *tofree;
15134 char_u numbuf[NUMBUFLEN];
15136 rettv->v_type = VAR_STRING;
15137 rettv->vval.v_string = tv2string(&argvars[0], &tofree, numbuf, 0);
15138 if (tofree == NULL)
15139 rettv->vval.v_string = vim_strsave(rettv->vval.v_string);
15143 * "strlen()" function
15145 static void
15146 f_strlen(argvars, rettv)
15147 typval_T *argvars;
15148 typval_T *rettv;
15150 rettv->vval.v_number = (varnumber_T)(STRLEN(
15151 get_tv_string(&argvars[0])));
15155 * "strpart()" function
15157 static void
15158 f_strpart(argvars, rettv)
15159 typval_T *argvars;
15160 typval_T *rettv;
15162 char_u *p;
15163 int n;
15164 int len;
15165 int slen;
15166 int error = FALSE;
15168 p = get_tv_string(&argvars[0]);
15169 slen = (int)STRLEN(p);
15171 n = get_tv_number_chk(&argvars[1], &error);
15172 if (error)
15173 len = 0;
15174 else if (argvars[2].v_type != VAR_UNKNOWN)
15175 len = get_tv_number(&argvars[2]);
15176 else
15177 len = slen - n; /* default len: all bytes that are available. */
15180 * Only return the overlap between the specified part and the actual
15181 * string.
15183 if (n < 0)
15185 len += n;
15186 n = 0;
15188 else if (n > slen)
15189 n = slen;
15190 if (len < 0)
15191 len = 0;
15192 else if (n + len > slen)
15193 len = slen - n;
15195 rettv->v_type = VAR_STRING;
15196 rettv->vval.v_string = vim_strnsave(p + n, len);
15200 * "strridx()" function
15202 static void
15203 f_strridx(argvars, rettv)
15204 typval_T *argvars;
15205 typval_T *rettv;
15207 char_u buf[NUMBUFLEN];
15208 char_u *needle;
15209 char_u *haystack;
15210 char_u *rest;
15211 char_u *lastmatch = NULL;
15212 int haystack_len, end_idx;
15214 needle = get_tv_string_chk(&argvars[1]);
15215 haystack = get_tv_string_buf_chk(&argvars[0], buf);
15217 rettv->vval.v_number = -1;
15218 if (needle == NULL || haystack == NULL)
15219 return; /* type error; errmsg already given */
15221 haystack_len = (int)STRLEN(haystack);
15222 if (argvars[2].v_type != VAR_UNKNOWN)
15224 /* Third argument: upper limit for index */
15225 end_idx = get_tv_number_chk(&argvars[2], NULL);
15226 if (end_idx < 0)
15227 return; /* can never find a match */
15229 else
15230 end_idx = haystack_len;
15232 if (*needle == NUL)
15234 /* Empty string matches past the end. */
15235 lastmatch = haystack + end_idx;
15237 else
15239 for (rest = haystack; *rest != '\0'; ++rest)
15241 rest = (char_u *)strstr((char *)rest, (char *)needle);
15242 if (rest == NULL || rest > haystack + end_idx)
15243 break;
15244 lastmatch = rest;
15248 if (lastmatch == NULL)
15249 rettv->vval.v_number = -1;
15250 else
15251 rettv->vval.v_number = (varnumber_T)(lastmatch - haystack);
15255 * "strtrans()" function
15257 static void
15258 f_strtrans(argvars, rettv)
15259 typval_T *argvars;
15260 typval_T *rettv;
15262 rettv->v_type = VAR_STRING;
15263 rettv->vval.v_string = transstr(get_tv_string(&argvars[0]));
15267 * "submatch()" function
15269 static void
15270 f_submatch(argvars, rettv)
15271 typval_T *argvars;
15272 typval_T *rettv;
15274 rettv->v_type = VAR_STRING;
15275 rettv->vval.v_string =
15276 reg_submatch((int)get_tv_number_chk(&argvars[0], NULL));
15280 * "substitute()" function
15282 static void
15283 f_substitute(argvars, rettv)
15284 typval_T *argvars;
15285 typval_T *rettv;
15287 char_u patbuf[NUMBUFLEN];
15288 char_u subbuf[NUMBUFLEN];
15289 char_u flagsbuf[NUMBUFLEN];
15291 char_u *str = get_tv_string_chk(&argvars[0]);
15292 char_u *pat = get_tv_string_buf_chk(&argvars[1], patbuf);
15293 char_u *sub = get_tv_string_buf_chk(&argvars[2], subbuf);
15294 char_u *flg = get_tv_string_buf_chk(&argvars[3], flagsbuf);
15296 rettv->v_type = VAR_STRING;
15297 if (str == NULL || pat == NULL || sub == NULL || flg == NULL)
15298 rettv->vval.v_string = NULL;
15299 else
15300 rettv->vval.v_string = do_string_sub(str, pat, sub, flg);
15304 * "synID(lnum, col, trans)" function
15306 /*ARGSUSED*/
15307 static void
15308 f_synID(argvars, rettv)
15309 typval_T *argvars;
15310 typval_T *rettv;
15312 int id = 0;
15313 #ifdef FEAT_SYN_HL
15314 long lnum;
15315 long col;
15316 int trans;
15317 int transerr = FALSE;
15319 lnum = get_tv_lnum(argvars); /* -1 on type error */
15320 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
15321 trans = get_tv_number_chk(&argvars[2], &transerr);
15323 if (!transerr && lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
15324 && col >= 0 && col < (long)STRLEN(ml_get(lnum)))
15325 id = syn_get_id(curwin, lnum, (colnr_T)col, trans, NULL);
15326 #endif
15328 rettv->vval.v_number = id;
15332 * "synIDattr(id, what [, mode])" function
15334 /*ARGSUSED*/
15335 static void
15336 f_synIDattr(argvars, rettv)
15337 typval_T *argvars;
15338 typval_T *rettv;
15340 char_u *p = NULL;
15341 #ifdef FEAT_SYN_HL
15342 int id;
15343 char_u *what;
15344 char_u *mode;
15345 char_u modebuf[NUMBUFLEN];
15346 int modec;
15348 id = get_tv_number(&argvars[0]);
15349 what = get_tv_string(&argvars[1]);
15350 if (argvars[2].v_type != VAR_UNKNOWN)
15352 mode = get_tv_string_buf(&argvars[2], modebuf);
15353 modec = TOLOWER_ASC(mode[0]);
15354 if (modec != 't' && modec != 'c'
15355 #ifdef FEAT_GUI
15356 && modec != 'g'
15357 #endif
15359 modec = 0; /* replace invalid with current */
15361 else
15363 #ifdef FEAT_GUI
15364 if (gui.in_use)
15365 modec = 'g';
15366 else
15367 #endif
15368 if (t_colors > 1)
15369 modec = 'c';
15370 else
15371 modec = 't';
15375 switch (TOLOWER_ASC(what[0]))
15377 case 'b':
15378 if (TOLOWER_ASC(what[1]) == 'g') /* bg[#] */
15379 p = highlight_color(id, what, modec);
15380 else /* bold */
15381 p = highlight_has_attr(id, HL_BOLD, modec);
15382 break;
15384 case 'f': /* fg[#] */
15385 p = highlight_color(id, what, modec);
15386 break;
15388 case 'i':
15389 if (TOLOWER_ASC(what[1]) == 'n') /* inverse */
15390 p = highlight_has_attr(id, HL_INVERSE, modec);
15391 else /* italic */
15392 p = highlight_has_attr(id, HL_ITALIC, modec);
15393 break;
15395 case 'n': /* name */
15396 p = get_highlight_name(NULL, id - 1);
15397 break;
15399 case 'r': /* reverse */
15400 p = highlight_has_attr(id, HL_INVERSE, modec);
15401 break;
15403 case 's': /* standout */
15404 p = highlight_has_attr(id, HL_STANDOUT, modec);
15405 break;
15407 case 'u':
15408 if (STRLEN(what) <= 5 || TOLOWER_ASC(what[5]) != 'c')
15409 /* underline */
15410 p = highlight_has_attr(id, HL_UNDERLINE, modec);
15411 else
15412 /* undercurl */
15413 p = highlight_has_attr(id, HL_UNDERCURL, modec);
15414 break;
15417 if (p != NULL)
15418 p = vim_strsave(p);
15419 #endif
15420 rettv->v_type = VAR_STRING;
15421 rettv->vval.v_string = p;
15425 * "synIDtrans(id)" function
15427 /*ARGSUSED*/
15428 static void
15429 f_synIDtrans(argvars, rettv)
15430 typval_T *argvars;
15431 typval_T *rettv;
15433 int id;
15435 #ifdef FEAT_SYN_HL
15436 id = get_tv_number(&argvars[0]);
15438 if (id > 0)
15439 id = syn_get_final_id(id);
15440 else
15441 #endif
15442 id = 0;
15444 rettv->vval.v_number = id;
15448 * "system()" function
15450 static void
15451 f_system(argvars, rettv)
15452 typval_T *argvars;
15453 typval_T *rettv;
15455 char_u *res = NULL;
15456 char_u *p;
15457 char_u *infile = NULL;
15458 char_u buf[NUMBUFLEN];
15459 int err = FALSE;
15460 FILE *fd;
15462 if (argvars[1].v_type != VAR_UNKNOWN)
15465 * Write the string to a temp file, to be used for input of the shell
15466 * command.
15468 if ((infile = vim_tempname('i')) == NULL)
15470 EMSG(_(e_notmp));
15471 return;
15474 fd = mch_fopen((char *)infile, WRITEBIN);
15475 if (fd == NULL)
15477 EMSG2(_(e_notopen), infile);
15478 goto done;
15480 p = get_tv_string_buf_chk(&argvars[1], buf);
15481 if (p == NULL)
15483 fclose(fd);
15484 goto done; /* type error; errmsg already given */
15486 if (fwrite(p, STRLEN(p), 1, fd) != 1)
15487 err = TRUE;
15488 if (fclose(fd) != 0)
15489 err = TRUE;
15490 if (err)
15492 EMSG(_("E677: Error writing temp file"));
15493 goto done;
15497 res = get_cmd_output(get_tv_string(&argvars[0]), infile,
15498 SHELL_SILENT | SHELL_COOKED);
15500 #ifdef USE_CR
15501 /* translate <CR> into <NL> */
15502 if (res != NULL)
15504 char_u *s;
15506 for (s = res; *s; ++s)
15508 if (*s == CAR)
15509 *s = NL;
15512 #else
15513 # ifdef USE_CRNL
15514 /* translate <CR><NL> into <NL> */
15515 if (res != NULL)
15517 char_u *s, *d;
15519 d = res;
15520 for (s = res; *s; ++s)
15522 if (s[0] == CAR && s[1] == NL)
15523 ++s;
15524 *d++ = *s;
15526 *d = NUL;
15528 # endif
15529 #endif
15531 done:
15532 if (infile != NULL)
15534 mch_remove(infile);
15535 vim_free(infile);
15537 rettv->v_type = VAR_STRING;
15538 rettv->vval.v_string = res;
15542 * "tabpagebuflist()" function
15544 /* ARGSUSED */
15545 static void
15546 f_tabpagebuflist(argvars, rettv)
15547 typval_T *argvars;
15548 typval_T *rettv;
15550 #ifndef FEAT_WINDOWS
15551 rettv->vval.v_number = 0;
15552 #else
15553 tabpage_T *tp;
15554 win_T *wp = NULL;
15556 if (argvars[0].v_type == VAR_UNKNOWN)
15557 wp = firstwin;
15558 else
15560 tp = find_tabpage((int)get_tv_number(&argvars[0]));
15561 if (tp != NULL)
15562 wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
15564 if (wp == NULL)
15565 rettv->vval.v_number = 0;
15566 else
15568 if (rettv_list_alloc(rettv) == FAIL)
15569 rettv->vval.v_number = 0;
15570 else
15572 for (; wp != NULL; wp = wp->w_next)
15573 if (list_append_number(rettv->vval.v_list,
15574 wp->w_buffer->b_fnum) == FAIL)
15575 break;
15578 #endif
15583 * "tabpagenr()" function
15585 /* ARGSUSED */
15586 static void
15587 f_tabpagenr(argvars, rettv)
15588 typval_T *argvars;
15589 typval_T *rettv;
15591 int nr = 1;
15592 #ifdef FEAT_WINDOWS
15593 char_u *arg;
15595 if (argvars[0].v_type != VAR_UNKNOWN)
15597 arg = get_tv_string_chk(&argvars[0]);
15598 nr = 0;
15599 if (arg != NULL)
15601 if (STRCMP(arg, "$") == 0)
15602 nr = tabpage_index(NULL) - 1;
15603 else
15604 EMSG2(_(e_invexpr2), arg);
15607 else
15608 nr = tabpage_index(curtab);
15609 #endif
15610 rettv->vval.v_number = nr;
15614 #ifdef FEAT_WINDOWS
15615 static int get_winnr __ARGS((tabpage_T *tp, typval_T *argvar));
15618 * Common code for tabpagewinnr() and winnr().
15620 static int
15621 get_winnr(tp, argvar)
15622 tabpage_T *tp;
15623 typval_T *argvar;
15625 win_T *twin;
15626 int nr = 1;
15627 win_T *wp;
15628 char_u *arg;
15630 twin = (tp == curtab) ? curwin : tp->tp_curwin;
15631 if (argvar->v_type != VAR_UNKNOWN)
15633 arg = get_tv_string_chk(argvar);
15634 if (arg == NULL)
15635 nr = 0; /* type error; errmsg already given */
15636 else if (STRCMP(arg, "$") == 0)
15637 twin = (tp == curtab) ? lastwin : tp->tp_lastwin;
15638 else if (STRCMP(arg, "#") == 0)
15640 twin = (tp == curtab) ? prevwin : tp->tp_prevwin;
15641 if (twin == NULL)
15642 nr = 0;
15644 else
15646 EMSG2(_(e_invexpr2), arg);
15647 nr = 0;
15651 if (nr > 0)
15652 for (wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
15653 wp != twin; wp = wp->w_next)
15654 ++nr;
15655 return nr;
15657 #endif
15660 * "tabpagewinnr()" function
15662 /* ARGSUSED */
15663 static void
15664 f_tabpagewinnr(argvars, rettv)
15665 typval_T *argvars;
15666 typval_T *rettv;
15668 int nr = 1;
15669 #ifdef FEAT_WINDOWS
15670 tabpage_T *tp;
15672 tp = find_tabpage((int)get_tv_number(&argvars[0]));
15673 if (tp == NULL)
15674 nr = 0;
15675 else
15676 nr = get_winnr(tp, &argvars[1]);
15677 #endif
15678 rettv->vval.v_number = nr;
15683 * "tagfiles()" function
15685 /*ARGSUSED*/
15686 static void
15687 f_tagfiles(argvars, rettv)
15688 typval_T *argvars;
15689 typval_T *rettv;
15691 char_u fname[MAXPATHL + 1];
15692 tagname_T tn;
15693 int first;
15695 if (rettv_list_alloc(rettv) == FAIL)
15697 rettv->vval.v_number = 0;
15698 return;
15701 for (first = TRUE; ; first = FALSE)
15702 if (get_tagfname(&tn, first, fname) == FAIL
15703 || list_append_string(rettv->vval.v_list, fname, -1) == FAIL)
15704 break;
15705 tagname_free(&tn);
15709 * "taglist()" function
15711 static void
15712 f_taglist(argvars, rettv)
15713 typval_T *argvars;
15714 typval_T *rettv;
15716 char_u *tag_pattern;
15718 tag_pattern = get_tv_string(&argvars[0]);
15720 rettv->vval.v_number = FALSE;
15721 if (*tag_pattern == NUL)
15722 return;
15724 if (rettv_list_alloc(rettv) == OK)
15725 (void)get_tags(rettv->vval.v_list, tag_pattern);
15729 * "tempname()" function
15731 /*ARGSUSED*/
15732 static void
15733 f_tempname(argvars, rettv)
15734 typval_T *argvars;
15735 typval_T *rettv;
15737 static int x = 'A';
15739 rettv->v_type = VAR_STRING;
15740 rettv->vval.v_string = vim_tempname(x);
15742 /* Advance 'x' to use A-Z and 0-9, so that there are at least 34 different
15743 * names. Skip 'I' and 'O', they are used for shell redirection. */
15746 if (x == 'Z')
15747 x = '0';
15748 else if (x == '9')
15749 x = 'A';
15750 else
15752 #ifdef EBCDIC
15753 if (x == 'I')
15754 x = 'J';
15755 else if (x == 'R')
15756 x = 'S';
15757 else
15758 #endif
15759 ++x;
15761 } while (x == 'I' || x == 'O');
15765 * "test(list)" function: Just checking the walls...
15767 /*ARGSUSED*/
15768 static void
15769 f_test(argvars, rettv)
15770 typval_T *argvars;
15771 typval_T *rettv;
15773 /* Used for unit testing. Change the code below to your liking. */
15774 #if 0
15775 listitem_T *li;
15776 list_T *l;
15777 char_u *bad, *good;
15779 if (argvars[0].v_type != VAR_LIST)
15780 return;
15781 l = argvars[0].vval.v_list;
15782 if (l == NULL)
15783 return;
15784 li = l->lv_first;
15785 if (li == NULL)
15786 return;
15787 bad = get_tv_string(&li->li_tv);
15788 li = li->li_next;
15789 if (li == NULL)
15790 return;
15791 good = get_tv_string(&li->li_tv);
15792 rettv->vval.v_number = test_edit_score(bad, good);
15793 #endif
15797 * "tolower(string)" function
15799 static void
15800 f_tolower(argvars, rettv)
15801 typval_T *argvars;
15802 typval_T *rettv;
15804 char_u *p;
15806 p = vim_strsave(get_tv_string(&argvars[0]));
15807 rettv->v_type = VAR_STRING;
15808 rettv->vval.v_string = p;
15810 if (p != NULL)
15811 while (*p != NUL)
15813 #ifdef FEAT_MBYTE
15814 int l;
15816 if (enc_utf8)
15818 int c, lc;
15820 c = utf_ptr2char(p);
15821 lc = utf_tolower(c);
15822 l = utf_ptr2len(p);
15823 /* TODO: reallocate string when byte count changes. */
15824 if (utf_char2len(lc) == l)
15825 utf_char2bytes(lc, p);
15826 p += l;
15828 else if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
15829 p += l; /* skip multi-byte character */
15830 else
15831 #endif
15833 *p = TOLOWER_LOC(*p); /* note that tolower() can be a macro */
15834 ++p;
15840 * "toupper(string)" function
15842 static void
15843 f_toupper(argvars, rettv)
15844 typval_T *argvars;
15845 typval_T *rettv;
15847 rettv->v_type = VAR_STRING;
15848 rettv->vval.v_string = strup_save(get_tv_string(&argvars[0]));
15852 * "tr(string, fromstr, tostr)" function
15854 static void
15855 f_tr(argvars, rettv)
15856 typval_T *argvars;
15857 typval_T *rettv;
15859 char_u *instr;
15860 char_u *fromstr;
15861 char_u *tostr;
15862 char_u *p;
15863 #ifdef FEAT_MBYTE
15864 int inlen;
15865 int fromlen;
15866 int tolen;
15867 int idx;
15868 char_u *cpstr;
15869 int cplen;
15870 int first = TRUE;
15871 #endif
15872 char_u buf[NUMBUFLEN];
15873 char_u buf2[NUMBUFLEN];
15874 garray_T ga;
15876 instr = get_tv_string(&argvars[0]);
15877 fromstr = get_tv_string_buf_chk(&argvars[1], buf);
15878 tostr = get_tv_string_buf_chk(&argvars[2], buf2);
15880 /* Default return value: empty string. */
15881 rettv->v_type = VAR_STRING;
15882 rettv->vval.v_string = NULL;
15883 if (fromstr == NULL || tostr == NULL)
15884 return; /* type error; errmsg already given */
15885 ga_init2(&ga, (int)sizeof(char), 80);
15887 #ifdef FEAT_MBYTE
15888 if (!has_mbyte)
15889 #endif
15890 /* not multi-byte: fromstr and tostr must be the same length */
15891 if (STRLEN(fromstr) != STRLEN(tostr))
15893 #ifdef FEAT_MBYTE
15894 error:
15895 #endif
15896 EMSG2(_(e_invarg2), fromstr);
15897 ga_clear(&ga);
15898 return;
15901 /* fromstr and tostr have to contain the same number of chars */
15902 while (*instr != NUL)
15904 #ifdef FEAT_MBYTE
15905 if (has_mbyte)
15907 inlen = (*mb_ptr2len)(instr);
15908 cpstr = instr;
15909 cplen = inlen;
15910 idx = 0;
15911 for (p = fromstr; *p != NUL; p += fromlen)
15913 fromlen = (*mb_ptr2len)(p);
15914 if (fromlen == inlen && STRNCMP(instr, p, inlen) == 0)
15916 for (p = tostr; *p != NUL; p += tolen)
15918 tolen = (*mb_ptr2len)(p);
15919 if (idx-- == 0)
15921 cplen = tolen;
15922 cpstr = p;
15923 break;
15926 if (*p == NUL) /* tostr is shorter than fromstr */
15927 goto error;
15928 break;
15930 ++idx;
15933 if (first && cpstr == instr)
15935 /* Check that fromstr and tostr have the same number of
15936 * (multi-byte) characters. Done only once when a character
15937 * of instr doesn't appear in fromstr. */
15938 first = FALSE;
15939 for (p = tostr; *p != NUL; p += tolen)
15941 tolen = (*mb_ptr2len)(p);
15942 --idx;
15944 if (idx != 0)
15945 goto error;
15948 ga_grow(&ga, cplen);
15949 mch_memmove((char *)ga.ga_data + ga.ga_len, cpstr, (size_t)cplen);
15950 ga.ga_len += cplen;
15952 instr += inlen;
15954 else
15955 #endif
15957 /* When not using multi-byte chars we can do it faster. */
15958 p = vim_strchr(fromstr, *instr);
15959 if (p != NULL)
15960 ga_append(&ga, tostr[p - fromstr]);
15961 else
15962 ga_append(&ga, *instr);
15963 ++instr;
15967 rettv->vval.v_string = ga.ga_data;
15971 * "type(expr)" function
15973 static void
15974 f_type(argvars, rettv)
15975 typval_T *argvars;
15976 typval_T *rettv;
15978 int n;
15980 switch (argvars[0].v_type)
15982 case VAR_NUMBER: n = 0; break;
15983 case VAR_STRING: n = 1; break;
15984 case VAR_FUNC: n = 2; break;
15985 case VAR_LIST: n = 3; break;
15986 case VAR_DICT: n = 4; break;
15987 default: EMSG2(_(e_intern2), "f_type()"); n = 0; break;
15989 rettv->vval.v_number = n;
15993 * "values(dict)" function
15995 static void
15996 f_values(argvars, rettv)
15997 typval_T *argvars;
15998 typval_T *rettv;
16000 dict_list(argvars, rettv, 1);
16004 * "virtcol(string)" function
16006 static void
16007 f_virtcol(argvars, rettv)
16008 typval_T *argvars;
16009 typval_T *rettv;
16011 colnr_T vcol = 0;
16012 pos_T *fp;
16013 int fnum = curbuf->b_fnum;
16015 fp = var2fpos(&argvars[0], FALSE, &fnum);
16016 if (fp != NULL && fp->lnum <= curbuf->b_ml.ml_line_count
16017 && fnum == curbuf->b_fnum)
16019 getvvcol(curwin, fp, NULL, NULL, &vcol);
16020 ++vcol;
16023 rettv->vval.v_number = vcol;
16027 * "visualmode()" function
16029 /*ARGSUSED*/
16030 static void
16031 f_visualmode(argvars, rettv)
16032 typval_T *argvars;
16033 typval_T *rettv;
16035 #ifdef FEAT_VISUAL
16036 char_u str[2];
16038 rettv->v_type = VAR_STRING;
16039 str[0] = curbuf->b_visual_mode_eval;
16040 str[1] = NUL;
16041 rettv->vval.v_string = vim_strsave(str);
16043 /* A non-zero number or non-empty string argument: reset mode. */
16044 if ((argvars[0].v_type == VAR_NUMBER
16045 && argvars[0].vval.v_number != 0)
16046 || (argvars[0].v_type == VAR_STRING
16047 && *get_tv_string(&argvars[0]) != NUL))
16048 curbuf->b_visual_mode_eval = NUL;
16049 #else
16050 rettv->vval.v_number = 0; /* return anything, it won't work anyway */
16051 #endif
16055 * "winbufnr(nr)" function
16057 static void
16058 f_winbufnr(argvars, rettv)
16059 typval_T *argvars;
16060 typval_T *rettv;
16062 win_T *wp;
16064 wp = find_win_by_nr(&argvars[0], NULL);
16065 if (wp == NULL)
16066 rettv->vval.v_number = -1;
16067 else
16068 rettv->vval.v_number = wp->w_buffer->b_fnum;
16072 * "wincol()" function
16074 /*ARGSUSED*/
16075 static void
16076 f_wincol(argvars, rettv)
16077 typval_T *argvars;
16078 typval_T *rettv;
16080 validate_cursor();
16081 rettv->vval.v_number = curwin->w_wcol + 1;
16085 * "winheight(nr)" function
16087 static void
16088 f_winheight(argvars, rettv)
16089 typval_T *argvars;
16090 typval_T *rettv;
16092 win_T *wp;
16094 wp = find_win_by_nr(&argvars[0], NULL);
16095 if (wp == NULL)
16096 rettv->vval.v_number = -1;
16097 else
16098 rettv->vval.v_number = wp->w_height;
16102 * "winline()" function
16104 /*ARGSUSED*/
16105 static void
16106 f_winline(argvars, rettv)
16107 typval_T *argvars;
16108 typval_T *rettv;
16110 validate_cursor();
16111 rettv->vval.v_number = curwin->w_wrow + 1;
16115 * "winnr()" function
16117 /* ARGSUSED */
16118 static void
16119 f_winnr(argvars, rettv)
16120 typval_T *argvars;
16121 typval_T *rettv;
16123 int nr = 1;
16125 #ifdef FEAT_WINDOWS
16126 nr = get_winnr(curtab, &argvars[0]);
16127 #endif
16128 rettv->vval.v_number = nr;
16132 * "winrestcmd()" function
16134 /* ARGSUSED */
16135 static void
16136 f_winrestcmd(argvars, rettv)
16137 typval_T *argvars;
16138 typval_T *rettv;
16140 #ifdef FEAT_WINDOWS
16141 win_T *wp;
16142 int winnr = 1;
16143 garray_T ga;
16144 char_u buf[50];
16146 ga_init2(&ga, (int)sizeof(char), 70);
16147 for (wp = firstwin; wp != NULL; wp = wp->w_next)
16149 sprintf((char *)buf, "%dresize %d|", winnr, wp->w_height);
16150 ga_concat(&ga, buf);
16151 # ifdef FEAT_VERTSPLIT
16152 sprintf((char *)buf, "vert %dresize %d|", winnr, wp->w_width);
16153 ga_concat(&ga, buf);
16154 # endif
16155 ++winnr;
16157 ga_append(&ga, NUL);
16159 rettv->vval.v_string = ga.ga_data;
16160 #else
16161 rettv->vval.v_string = NULL;
16162 #endif
16163 rettv->v_type = VAR_STRING;
16167 * "winrestview()" function
16169 /* ARGSUSED */
16170 static void
16171 f_winrestview(argvars, rettv)
16172 typval_T *argvars;
16173 typval_T *rettv;
16175 dict_T *dict;
16177 if (argvars[0].v_type != VAR_DICT
16178 || (dict = argvars[0].vval.v_dict) == NULL)
16179 EMSG(_(e_invarg));
16180 else
16182 curwin->w_cursor.lnum = get_dict_number(dict, (char_u *)"lnum");
16183 curwin->w_cursor.col = get_dict_number(dict, (char_u *)"col");
16184 #ifdef FEAT_VIRTUALEDIT
16185 curwin->w_cursor.coladd = get_dict_number(dict, (char_u *)"coladd");
16186 #endif
16187 curwin->w_curswant = get_dict_number(dict, (char_u *)"curswant");
16188 curwin->w_set_curswant = FALSE;
16190 curwin->w_topline = get_dict_number(dict, (char_u *)"topline");
16191 #ifdef FEAT_DIFF
16192 curwin->w_topfill = get_dict_number(dict, (char_u *)"topfill");
16193 #endif
16194 curwin->w_leftcol = get_dict_number(dict, (char_u *)"leftcol");
16195 curwin->w_skipcol = get_dict_number(dict, (char_u *)"skipcol");
16197 check_cursor();
16198 changed_cline_bef_curs();
16199 invalidate_botline();
16200 redraw_later(VALID);
16202 if (curwin->w_topline == 0)
16203 curwin->w_topline = 1;
16204 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
16205 curwin->w_topline = curbuf->b_ml.ml_line_count;
16206 #ifdef FEAT_DIFF
16207 check_topfill(curwin, TRUE);
16208 #endif
16213 * "winsaveview()" function
16215 /* ARGSUSED */
16216 static void
16217 f_winsaveview(argvars, rettv)
16218 typval_T *argvars;
16219 typval_T *rettv;
16221 dict_T *dict;
16223 dict = dict_alloc();
16224 if (dict == NULL)
16225 return;
16226 rettv->v_type = VAR_DICT;
16227 rettv->vval.v_dict = dict;
16228 ++dict->dv_refcount;
16230 dict_add_nr_str(dict, "lnum", (long)curwin->w_cursor.lnum, NULL);
16231 dict_add_nr_str(dict, "col", (long)curwin->w_cursor.col, NULL);
16232 #ifdef FEAT_VIRTUALEDIT
16233 dict_add_nr_str(dict, "coladd", (long)curwin->w_cursor.coladd, NULL);
16234 #endif
16235 dict_add_nr_str(dict, "curswant", (long)curwin->w_curswant, NULL);
16237 dict_add_nr_str(dict, "topline", (long)curwin->w_topline, NULL);
16238 #ifdef FEAT_DIFF
16239 dict_add_nr_str(dict, "topfill", (long)curwin->w_topfill, NULL);
16240 #endif
16241 dict_add_nr_str(dict, "leftcol", (long)curwin->w_leftcol, NULL);
16242 dict_add_nr_str(dict, "skipcol", (long)curwin->w_skipcol, NULL);
16246 * "winwidth(nr)" function
16248 static void
16249 f_winwidth(argvars, rettv)
16250 typval_T *argvars;
16251 typval_T *rettv;
16253 win_T *wp;
16255 wp = find_win_by_nr(&argvars[0], NULL);
16256 if (wp == NULL)
16257 rettv->vval.v_number = -1;
16258 else
16259 #ifdef FEAT_VERTSPLIT
16260 rettv->vval.v_number = wp->w_width;
16261 #else
16262 rettv->vval.v_number = Columns;
16263 #endif
16267 * "writefile()" function
16269 static void
16270 f_writefile(argvars, rettv)
16271 typval_T *argvars;
16272 typval_T *rettv;
16274 int binary = FALSE;
16275 char_u *fname;
16276 FILE *fd;
16277 listitem_T *li;
16278 char_u *s;
16279 int ret = 0;
16280 int c;
16282 if (argvars[0].v_type != VAR_LIST)
16284 EMSG2(_(e_listarg), "writefile()");
16285 return;
16287 if (argvars[0].vval.v_list == NULL)
16288 return;
16290 if (argvars[2].v_type != VAR_UNKNOWN
16291 && STRCMP(get_tv_string(&argvars[2]), "b") == 0)
16292 binary = TRUE;
16294 /* Always open the file in binary mode, library functions have a mind of
16295 * their own about CR-LF conversion. */
16296 fname = get_tv_string(&argvars[1]);
16297 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
16299 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
16300 ret = -1;
16302 else
16304 for (li = argvars[0].vval.v_list->lv_first; li != NULL;
16305 li = li->li_next)
16307 for (s = get_tv_string(&li->li_tv); *s != NUL; ++s)
16309 if (*s == '\n')
16310 c = putc(NUL, fd);
16311 else
16312 c = putc(*s, fd);
16313 if (c == EOF)
16315 ret = -1;
16316 break;
16319 if (!binary || li->li_next != NULL)
16320 if (putc('\n', fd) == EOF)
16322 ret = -1;
16323 break;
16325 if (ret < 0)
16327 EMSG(_(e_write));
16328 break;
16331 fclose(fd);
16334 rettv->vval.v_number = ret;
16338 * Translate a String variable into a position.
16339 * Returns NULL when there is an error.
16341 static pos_T *
16342 var2fpos(varp, lnum, fnum)
16343 typval_T *varp;
16344 int lnum; /* TRUE when $ is last line */
16345 int *fnum; /* set to fnum for '0, 'A, etc. */
16347 char_u *name;
16348 static pos_T pos;
16349 pos_T *pp;
16351 /* Argument can be [lnum, col, coladd]. */
16352 if (varp->v_type == VAR_LIST)
16354 list_T *l;
16355 int len;
16356 int error = FALSE;
16358 l = varp->vval.v_list;
16359 if (l == NULL)
16360 return NULL;
16362 /* Get the line number */
16363 pos.lnum = list_find_nr(l, 0L, &error);
16364 if (error || pos.lnum <= 0 || pos.lnum > curbuf->b_ml.ml_line_count)
16365 return NULL; /* invalid line number */
16367 /* Get the column number */
16368 pos.col = list_find_nr(l, 1L, &error);
16369 if (error)
16370 return NULL;
16371 len = (long)STRLEN(ml_get(pos.lnum));
16372 /* Accept a position up to the NUL after the line. */
16373 if (pos.col == 0 || (int)pos.col > len + 1)
16374 return NULL; /* invalid column number */
16375 --pos.col;
16377 #ifdef FEAT_VIRTUALEDIT
16378 /* Get the virtual offset. Defaults to zero. */
16379 pos.coladd = list_find_nr(l, 2L, &error);
16380 if (error)
16381 pos.coladd = 0;
16382 #endif
16384 return &pos;
16387 name = get_tv_string_chk(varp);
16388 if (name == NULL)
16389 return NULL;
16390 if (name[0] == '.') /* cursor */
16391 return &curwin->w_cursor;
16392 if (name[0] == '\'') /* mark */
16394 pp = getmark_fnum(name[1], FALSE, fnum);
16395 if (pp == NULL || pp == (pos_T *)-1 || pp->lnum <= 0)
16396 return NULL;
16397 return pp;
16400 #ifdef FEAT_VIRTUALEDIT
16401 pos.coladd = 0;
16402 #endif
16404 if (name[0] == 'w' && lnum)
16406 pos.col = 0;
16407 if (name[1] == '0') /* "w0": first visible line */
16409 update_topline();
16410 pos.lnum = curwin->w_topline;
16411 return &pos;
16413 else if (name[1] == '$') /* "w$": last visible line */
16415 validate_botline();
16416 pos.lnum = curwin->w_botline - 1;
16417 return &pos;
16420 else if (name[0] == '$') /* last column or line */
16422 if (lnum)
16424 pos.lnum = curbuf->b_ml.ml_line_count;
16425 pos.col = 0;
16427 else
16429 pos.lnum = curwin->w_cursor.lnum;
16430 pos.col = (colnr_T)STRLEN(ml_get_curline());
16432 return &pos;
16434 return NULL;
16438 * Convert list in "arg" into a position and optional file number.
16439 * When "fnump" is NULL there is no file number, only 3 items.
16440 * Note that the column is passed on as-is, the caller may want to decrement
16441 * it to use 1 for the first column.
16442 * Return FAIL when conversion is not possible, doesn't check the position for
16443 * validity.
16445 static int
16446 list2fpos(arg, posp, fnump)
16447 typval_T *arg;
16448 pos_T *posp;
16449 int *fnump;
16451 list_T *l = arg->vval.v_list;
16452 long i = 0;
16453 long n;
16455 /* List must be: [fnum, lnum, col, coladd], where "fnum" is only there
16456 * when "fnump" isn't NULL and "coladd" is optional. */
16457 if (arg->v_type != VAR_LIST
16458 || l == NULL
16459 || l->lv_len < (fnump == NULL ? 2 : 3)
16460 || l->lv_len > (fnump == NULL ? 3 : 4))
16461 return FAIL;
16463 if (fnump != NULL)
16465 n = list_find_nr(l, i++, NULL); /* fnum */
16466 if (n < 0)
16467 return FAIL;
16468 if (n == 0)
16469 n = curbuf->b_fnum; /* current buffer */
16470 *fnump = n;
16473 n = list_find_nr(l, i++, NULL); /* lnum */
16474 if (n < 0)
16475 return FAIL;
16476 posp->lnum = n;
16478 n = list_find_nr(l, i++, NULL); /* col */
16479 if (n < 0)
16480 return FAIL;
16481 posp->col = n;
16483 #ifdef FEAT_VIRTUALEDIT
16484 n = list_find_nr(l, i, NULL);
16485 if (n < 0)
16486 posp->coladd = 0;
16487 else
16488 posp->coladd = n;
16489 #endif
16491 return OK;
16495 * Get the length of an environment variable name.
16496 * Advance "arg" to the first character after the name.
16497 * Return 0 for error.
16499 static int
16500 get_env_len(arg)
16501 char_u **arg;
16503 char_u *p;
16504 int len;
16506 for (p = *arg; vim_isIDc(*p); ++p)
16508 if (p == *arg) /* no name found */
16509 return 0;
16511 len = (int)(p - *arg);
16512 *arg = p;
16513 return len;
16517 * Get the length of the name of a function or internal variable.
16518 * "arg" is advanced to the first non-white character after the name.
16519 * Return 0 if something is wrong.
16521 static int
16522 get_id_len(arg)
16523 char_u **arg;
16525 char_u *p;
16526 int len;
16528 /* Find the end of the name. */
16529 for (p = *arg; eval_isnamec(*p); ++p)
16531 if (p == *arg) /* no name found */
16532 return 0;
16534 len = (int)(p - *arg);
16535 *arg = skipwhite(p);
16537 return len;
16541 * Get the length of the name of a variable or function.
16542 * Only the name is recognized, does not handle ".key" or "[idx]".
16543 * "arg" is advanced to the first non-white character after the name.
16544 * Return -1 if curly braces expansion failed.
16545 * Return 0 if something else is wrong.
16546 * If the name contains 'magic' {}'s, expand them and return the
16547 * expanded name in an allocated string via 'alias' - caller must free.
16549 static int
16550 get_name_len(arg, alias, evaluate, verbose)
16551 char_u **arg;
16552 char_u **alias;
16553 int evaluate;
16554 int verbose;
16556 int len;
16557 char_u *p;
16558 char_u *expr_start;
16559 char_u *expr_end;
16561 *alias = NULL; /* default to no alias */
16563 if ((*arg)[0] == K_SPECIAL && (*arg)[1] == KS_EXTRA
16564 && (*arg)[2] == (int)KE_SNR)
16566 /* hard coded <SNR>, already translated */
16567 *arg += 3;
16568 return get_id_len(arg) + 3;
16570 len = eval_fname_script(*arg);
16571 if (len > 0)
16573 /* literal "<SID>", "s:" or "<SNR>" */
16574 *arg += len;
16578 * Find the end of the name; check for {} construction.
16580 p = find_name_end(*arg, &expr_start, &expr_end,
16581 len > 0 ? 0 : FNE_CHECK_START);
16582 if (expr_start != NULL)
16584 char_u *temp_string;
16586 if (!evaluate)
16588 len += (int)(p - *arg);
16589 *arg = skipwhite(p);
16590 return len;
16594 * Include any <SID> etc in the expanded string:
16595 * Thus the -len here.
16597 temp_string = make_expanded_name(*arg - len, expr_start, expr_end, p);
16598 if (temp_string == NULL)
16599 return -1;
16600 *alias = temp_string;
16601 *arg = skipwhite(p);
16602 return (int)STRLEN(temp_string);
16605 len += get_id_len(arg);
16606 if (len == 0 && verbose)
16607 EMSG2(_(e_invexpr2), *arg);
16609 return len;
16613 * Find the end of a variable or function name, taking care of magic braces.
16614 * If "expr_start" is not NULL then "expr_start" and "expr_end" are set to the
16615 * start and end of the first magic braces item.
16616 * "flags" can have FNE_INCL_BR and FNE_CHECK_START.
16617 * Return a pointer to just after the name. Equal to "arg" if there is no
16618 * valid name.
16620 static char_u *
16621 find_name_end(arg, expr_start, expr_end, flags)
16622 char_u *arg;
16623 char_u **expr_start;
16624 char_u **expr_end;
16625 int flags;
16627 int mb_nest = 0;
16628 int br_nest = 0;
16629 char_u *p;
16631 if (expr_start != NULL)
16633 *expr_start = NULL;
16634 *expr_end = NULL;
16637 /* Quick check for valid starting character. */
16638 if ((flags & FNE_CHECK_START) && !eval_isnamec1(*arg) && *arg != '{')
16639 return arg;
16641 for (p = arg; *p != NUL
16642 && (eval_isnamec(*p)
16643 || *p == '{'
16644 || ((flags & FNE_INCL_BR) && (*p == '[' || *p == '.'))
16645 || mb_nest != 0
16646 || br_nest != 0); mb_ptr_adv(p))
16648 if (*p == '\'')
16650 /* skip over 'string' to avoid counting [ and ] inside it. */
16651 for (p = p + 1; *p != NUL && *p != '\''; mb_ptr_adv(p))
16653 if (*p == NUL)
16654 break;
16656 else if (*p == '"')
16658 /* skip over "str\"ing" to avoid counting [ and ] inside it. */
16659 for (p = p + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
16660 if (*p == '\\' && p[1] != NUL)
16661 ++p;
16662 if (*p == NUL)
16663 break;
16666 if (mb_nest == 0)
16668 if (*p == '[')
16669 ++br_nest;
16670 else if (*p == ']')
16671 --br_nest;
16674 if (br_nest == 0)
16676 if (*p == '{')
16678 mb_nest++;
16679 if (expr_start != NULL && *expr_start == NULL)
16680 *expr_start = p;
16682 else if (*p == '}')
16684 mb_nest--;
16685 if (expr_start != NULL && mb_nest == 0 && *expr_end == NULL)
16686 *expr_end = p;
16691 return p;
16695 * Expands out the 'magic' {}'s in a variable/function name.
16696 * Note that this can call itself recursively, to deal with
16697 * constructs like foo{bar}{baz}{bam}
16698 * The four pointer arguments point to "foo{expre}ss{ion}bar"
16699 * "in_start" ^
16700 * "expr_start" ^
16701 * "expr_end" ^
16702 * "in_end" ^
16704 * Returns a new allocated string, which the caller must free.
16705 * Returns NULL for failure.
16707 static char_u *
16708 make_expanded_name(in_start, expr_start, expr_end, in_end)
16709 char_u *in_start;
16710 char_u *expr_start;
16711 char_u *expr_end;
16712 char_u *in_end;
16714 char_u c1;
16715 char_u *retval = NULL;
16716 char_u *temp_result;
16717 char_u *nextcmd = NULL;
16719 if (expr_end == NULL || in_end == NULL)
16720 return NULL;
16721 *expr_start = NUL;
16722 *expr_end = NUL;
16723 c1 = *in_end;
16724 *in_end = NUL;
16726 temp_result = eval_to_string(expr_start + 1, &nextcmd, FALSE);
16727 if (temp_result != NULL && nextcmd == NULL)
16729 retval = alloc((unsigned)(STRLEN(temp_result) + (expr_start - in_start)
16730 + (in_end - expr_end) + 1));
16731 if (retval != NULL)
16733 STRCPY(retval, in_start);
16734 STRCAT(retval, temp_result);
16735 STRCAT(retval, expr_end + 1);
16738 vim_free(temp_result);
16740 *in_end = c1; /* put char back for error messages */
16741 *expr_start = '{';
16742 *expr_end = '}';
16744 if (retval != NULL)
16746 temp_result = find_name_end(retval, &expr_start, &expr_end, 0);
16747 if (expr_start != NULL)
16749 /* Further expansion! */
16750 temp_result = make_expanded_name(retval, expr_start,
16751 expr_end, temp_result);
16752 vim_free(retval);
16753 retval = temp_result;
16757 return retval;
16761 * Return TRUE if character "c" can be used in a variable or function name.
16762 * Does not include '{' or '}' for magic braces.
16764 static int
16765 eval_isnamec(c)
16766 int c;
16768 return (ASCII_ISALNUM(c) || c == '_' || c == ':' || c == AUTOLOAD_CHAR);
16772 * Return TRUE if character "c" can be used as the first character in a
16773 * variable or function name (excluding '{' and '}').
16775 static int
16776 eval_isnamec1(c)
16777 int c;
16779 return (ASCII_ISALPHA(c) || c == '_');
16783 * Set number v: variable to "val".
16785 void
16786 set_vim_var_nr(idx, val)
16787 int idx;
16788 long val;
16790 vimvars[idx].vv_nr = val;
16794 * Get number v: variable value.
16796 long
16797 get_vim_var_nr(idx)
16798 int idx;
16800 return vimvars[idx].vv_nr;
16803 #if defined(FEAT_AUTOCMD) || defined(PROTO)
16805 * Get string v: variable value. Uses a static buffer, can only be used once.
16807 char_u *
16808 get_vim_var_str(idx)
16809 int idx;
16811 return get_tv_string(&vimvars[idx].vv_tv);
16813 #endif
16816 * Set v:count, v:count1 and v:prevcount.
16818 void
16819 set_vcount(count, count1)
16820 long count;
16821 long count1;
16823 vimvars[VV_PREVCOUNT].vv_nr = vimvars[VV_COUNT].vv_nr;
16824 vimvars[VV_COUNT].vv_nr = count;
16825 vimvars[VV_COUNT1].vv_nr = count1;
16829 * Set string v: variable to a copy of "val".
16831 void
16832 set_vim_var_string(idx, val, len)
16833 int idx;
16834 char_u *val;
16835 int len; /* length of "val" to use or -1 (whole string) */
16837 /* Need to do this (at least) once, since we can't initialize a union.
16838 * Will always be invoked when "v:progname" is set. */
16839 vimvars[VV_VERSION].vv_nr = VIM_VERSION_100;
16841 vim_free(vimvars[idx].vv_str);
16842 if (val == NULL)
16843 vimvars[idx].vv_str = NULL;
16844 else if (len == -1)
16845 vimvars[idx].vv_str = vim_strsave(val);
16846 else
16847 vimvars[idx].vv_str = vim_strnsave(val, len);
16851 * Set v:register if needed.
16853 void
16854 set_reg_var(c)
16855 int c;
16857 char_u regname;
16859 if (c == 0 || c == ' ')
16860 regname = '"';
16861 else
16862 regname = c;
16863 /* Avoid free/alloc when the value is already right. */
16864 if (vimvars[VV_REG].vv_str == NULL || vimvars[VV_REG].vv_str[0] != c)
16865 set_vim_var_string(VV_REG, &regname, 1);
16869 * Get or set v:exception. If "oldval" == NULL, return the current value.
16870 * Otherwise, restore the value to "oldval" and return NULL.
16871 * Must always be called in pairs to save and restore v:exception! Does not
16872 * take care of memory allocations.
16874 char_u *
16875 v_exception(oldval)
16876 char_u *oldval;
16878 if (oldval == NULL)
16879 return vimvars[VV_EXCEPTION].vv_str;
16881 vimvars[VV_EXCEPTION].vv_str = oldval;
16882 return NULL;
16886 * Get or set v:throwpoint. If "oldval" == NULL, return the current value.
16887 * Otherwise, restore the value to "oldval" and return NULL.
16888 * Must always be called in pairs to save and restore v:throwpoint! Does not
16889 * take care of memory allocations.
16891 char_u *
16892 v_throwpoint(oldval)
16893 char_u *oldval;
16895 if (oldval == NULL)
16896 return vimvars[VV_THROWPOINT].vv_str;
16898 vimvars[VV_THROWPOINT].vv_str = oldval;
16899 return NULL;
16902 #if defined(FEAT_AUTOCMD) || defined(PROTO)
16904 * Set v:cmdarg.
16905 * If "eap" != NULL, use "eap" to generate the value and return the old value.
16906 * If "oldarg" != NULL, restore the value to "oldarg" and return NULL.
16907 * Must always be called in pairs!
16909 char_u *
16910 set_cmdarg(eap, oldarg)
16911 exarg_T *eap;
16912 char_u *oldarg;
16914 char_u *oldval;
16915 char_u *newval;
16916 unsigned len;
16918 oldval = vimvars[VV_CMDARG].vv_str;
16919 if (eap == NULL)
16921 vim_free(oldval);
16922 vimvars[VV_CMDARG].vv_str = oldarg;
16923 return NULL;
16926 if (eap->force_bin == FORCE_BIN)
16927 len = 6;
16928 else if (eap->force_bin == FORCE_NOBIN)
16929 len = 8;
16930 else
16931 len = 0;
16933 if (eap->read_edit)
16934 len += 7;
16936 if (eap->force_ff != 0)
16937 len += (unsigned)STRLEN(eap->cmd + eap->force_ff) + 6;
16938 # ifdef FEAT_MBYTE
16939 if (eap->force_enc != 0)
16940 len += (unsigned)STRLEN(eap->cmd + eap->force_enc) + 7;
16941 if (eap->bad_char != 0)
16942 len += (unsigned)STRLEN(eap->cmd + eap->bad_char) + 7;
16943 # endif
16945 newval = alloc(len + 1);
16946 if (newval == NULL)
16947 return NULL;
16949 if (eap->force_bin == FORCE_BIN)
16950 sprintf((char *)newval, " ++bin");
16951 else if (eap->force_bin == FORCE_NOBIN)
16952 sprintf((char *)newval, " ++nobin");
16953 else
16954 *newval = NUL;
16956 if (eap->read_edit)
16957 STRCAT(newval, " ++edit");
16959 if (eap->force_ff != 0)
16960 sprintf((char *)newval + STRLEN(newval), " ++ff=%s",
16961 eap->cmd + eap->force_ff);
16962 # ifdef FEAT_MBYTE
16963 if (eap->force_enc != 0)
16964 sprintf((char *)newval + STRLEN(newval), " ++enc=%s",
16965 eap->cmd + eap->force_enc);
16966 if (eap->bad_char != 0)
16967 sprintf((char *)newval + STRLEN(newval), " ++bad=%s",
16968 eap->cmd + eap->bad_char);
16969 # endif
16970 vimvars[VV_CMDARG].vv_str = newval;
16971 return oldval;
16973 #endif
16976 * Get the value of internal variable "name".
16977 * Return OK or FAIL.
16979 static int
16980 get_var_tv(name, len, rettv, verbose)
16981 char_u *name;
16982 int len; /* length of "name" */
16983 typval_T *rettv; /* NULL when only checking existence */
16984 int verbose; /* may give error message */
16986 int ret = OK;
16987 typval_T *tv = NULL;
16988 typval_T atv;
16989 dictitem_T *v;
16990 int cc;
16992 /* truncate the name, so that we can use strcmp() */
16993 cc = name[len];
16994 name[len] = NUL;
16997 * Check for "b:changedtick".
16999 if (STRCMP(name, "b:changedtick") == 0)
17001 atv.v_type = VAR_NUMBER;
17002 atv.vval.v_number = curbuf->b_changedtick;
17003 tv = &atv;
17007 * Check for user-defined variables.
17009 else
17011 v = find_var(name, NULL);
17012 if (v != NULL)
17013 tv = &v->di_tv;
17016 if (tv == NULL)
17018 if (rettv != NULL && verbose)
17019 EMSG2(_(e_undefvar), name);
17020 ret = FAIL;
17022 else if (rettv != NULL)
17023 copy_tv(tv, rettv);
17025 name[len] = cc;
17027 return ret;
17031 * Handle expr[expr], expr[expr:expr] subscript and .name lookup.
17032 * Also handle function call with Funcref variable: func(expr)
17033 * Can all be combined: dict.func(expr)[idx]['func'](expr)
17035 static int
17036 handle_subscript(arg, rettv, evaluate, verbose)
17037 char_u **arg;
17038 typval_T *rettv;
17039 int evaluate; /* do more than finding the end */
17040 int verbose; /* give error messages */
17042 int ret = OK;
17043 dict_T *selfdict = NULL;
17044 char_u *s;
17045 int len;
17046 typval_T functv;
17048 while (ret == OK
17049 && (**arg == '['
17050 || (**arg == '.' && rettv->v_type == VAR_DICT)
17051 || (**arg == '(' && rettv->v_type == VAR_FUNC))
17052 && !vim_iswhite(*(*arg - 1)))
17054 if (**arg == '(')
17056 /* need to copy the funcref so that we can clear rettv */
17057 functv = *rettv;
17058 rettv->v_type = VAR_UNKNOWN;
17060 /* Invoke the function. Recursive! */
17061 s = functv.vval.v_string;
17062 ret = get_func_tv(s, (int)STRLEN(s), rettv, arg,
17063 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
17064 &len, evaluate, selfdict);
17066 /* Clear the funcref afterwards, so that deleting it while
17067 * evaluating the arguments is possible (see test55). */
17068 clear_tv(&functv);
17070 /* Stop the expression evaluation when immediately aborting on
17071 * error, or when an interrupt occurred or an exception was thrown
17072 * but not caught. */
17073 if (aborting())
17075 if (ret == OK)
17076 clear_tv(rettv);
17077 ret = FAIL;
17079 dict_unref(selfdict);
17080 selfdict = NULL;
17082 else /* **arg == '[' || **arg == '.' */
17084 dict_unref(selfdict);
17085 if (rettv->v_type == VAR_DICT)
17087 selfdict = rettv->vval.v_dict;
17088 if (selfdict != NULL)
17089 ++selfdict->dv_refcount;
17091 else
17092 selfdict = NULL;
17093 if (eval_index(arg, rettv, evaluate, verbose) == FAIL)
17095 clear_tv(rettv);
17096 ret = FAIL;
17100 dict_unref(selfdict);
17101 return ret;
17105 * Allocate memory for a variable type-value, and make it emtpy (0 or NULL
17106 * value).
17108 static typval_T *
17109 alloc_tv()
17111 return (typval_T *)alloc_clear((unsigned)sizeof(typval_T));
17115 * Allocate memory for a variable type-value, and assign a string to it.
17116 * The string "s" must have been allocated, it is consumed.
17117 * Return NULL for out of memory, the variable otherwise.
17119 static typval_T *
17120 alloc_string_tv(s)
17121 char_u *s;
17123 typval_T *rettv;
17125 rettv = alloc_tv();
17126 if (rettv != NULL)
17128 rettv->v_type = VAR_STRING;
17129 rettv->vval.v_string = s;
17131 else
17132 vim_free(s);
17133 return rettv;
17137 * Free the memory for a variable type-value.
17139 void
17140 free_tv(varp)
17141 typval_T *varp;
17143 if (varp != NULL)
17145 switch (varp->v_type)
17147 case VAR_FUNC:
17148 func_unref(varp->vval.v_string);
17149 /*FALLTHROUGH*/
17150 case VAR_STRING:
17151 vim_free(varp->vval.v_string);
17152 break;
17153 case VAR_LIST:
17154 list_unref(varp->vval.v_list);
17155 break;
17156 case VAR_DICT:
17157 dict_unref(varp->vval.v_dict);
17158 break;
17159 case VAR_NUMBER:
17160 case VAR_UNKNOWN:
17161 break;
17162 default:
17163 EMSG2(_(e_intern2), "free_tv()");
17164 break;
17166 vim_free(varp);
17171 * Free the memory for a variable value and set the value to NULL or 0.
17173 void
17174 clear_tv(varp)
17175 typval_T *varp;
17177 if (varp != NULL)
17179 switch (varp->v_type)
17181 case VAR_FUNC:
17182 func_unref(varp->vval.v_string);
17183 /*FALLTHROUGH*/
17184 case VAR_STRING:
17185 vim_free(varp->vval.v_string);
17186 varp->vval.v_string = NULL;
17187 break;
17188 case VAR_LIST:
17189 list_unref(varp->vval.v_list);
17190 varp->vval.v_list = NULL;
17191 break;
17192 case VAR_DICT:
17193 dict_unref(varp->vval.v_dict);
17194 varp->vval.v_dict = NULL;
17195 break;
17196 case VAR_NUMBER:
17197 varp->vval.v_number = 0;
17198 break;
17199 case VAR_UNKNOWN:
17200 break;
17201 default:
17202 EMSG2(_(e_intern2), "clear_tv()");
17204 varp->v_lock = 0;
17209 * Set the value of a variable to NULL without freeing items.
17211 static void
17212 init_tv(varp)
17213 typval_T *varp;
17215 if (varp != NULL)
17216 vim_memset(varp, 0, sizeof(typval_T));
17220 * Get the number value of a variable.
17221 * If it is a String variable, uses vim_str2nr().
17222 * For incompatible types, return 0.
17223 * get_tv_number_chk() is similar to get_tv_number(), but informs the
17224 * caller of incompatible types: it sets *denote to TRUE if "denote"
17225 * is not NULL or returns -1 otherwise.
17227 static long
17228 get_tv_number(varp)
17229 typval_T *varp;
17231 int error = FALSE;
17233 return get_tv_number_chk(varp, &error); /* return 0L on error */
17236 long
17237 get_tv_number_chk(varp, denote)
17238 typval_T *varp;
17239 int *denote;
17241 long n = 0L;
17243 switch (varp->v_type)
17245 case VAR_NUMBER:
17246 return (long)(varp->vval.v_number);
17247 case VAR_FUNC:
17248 EMSG(_("E703: Using a Funcref as a number"));
17249 break;
17250 case VAR_STRING:
17251 if (varp->vval.v_string != NULL)
17252 vim_str2nr(varp->vval.v_string, NULL, NULL,
17253 TRUE, TRUE, &n, NULL);
17254 return n;
17255 case VAR_LIST:
17256 EMSG(_("E745: Using a List as a number"));
17257 break;
17258 case VAR_DICT:
17259 EMSG(_("E728: Using a Dictionary as a number"));
17260 break;
17261 default:
17262 EMSG2(_(e_intern2), "get_tv_number()");
17263 break;
17265 if (denote == NULL) /* useful for values that must be unsigned */
17266 n = -1;
17267 else
17268 *denote = TRUE;
17269 return n;
17273 * Get the lnum from the first argument.
17274 * Also accepts ".", "$", etc., but that only works for the current buffer.
17275 * Returns -1 on error.
17277 static linenr_T
17278 get_tv_lnum(argvars)
17279 typval_T *argvars;
17281 typval_T rettv;
17282 linenr_T lnum;
17284 lnum = get_tv_number_chk(&argvars[0], NULL);
17285 if (lnum == 0) /* no valid number, try using line() */
17287 rettv.v_type = VAR_NUMBER;
17288 f_line(argvars, &rettv);
17289 lnum = rettv.vval.v_number;
17290 clear_tv(&rettv);
17292 return lnum;
17296 * Get the lnum from the first argument.
17297 * Also accepts "$", then "buf" is used.
17298 * Returns 0 on error.
17300 static linenr_T
17301 get_tv_lnum_buf(argvars, buf)
17302 typval_T *argvars;
17303 buf_T *buf;
17305 if (argvars[0].v_type == VAR_STRING
17306 && argvars[0].vval.v_string != NULL
17307 && argvars[0].vval.v_string[0] == '$'
17308 && buf != NULL)
17309 return buf->b_ml.ml_line_count;
17310 return get_tv_number_chk(&argvars[0], NULL);
17314 * Get the string value of a variable.
17315 * If it is a Number variable, the number is converted into a string.
17316 * get_tv_string() uses a single, static buffer. YOU CAN ONLY USE IT ONCE!
17317 * get_tv_string_buf() uses a given buffer.
17318 * If the String variable has never been set, return an empty string.
17319 * Never returns NULL;
17320 * get_tv_string_chk() and get_tv_string_buf_chk() are similar, but return
17321 * NULL on error.
17323 static char_u *
17324 get_tv_string(varp)
17325 typval_T *varp;
17327 static char_u mybuf[NUMBUFLEN];
17329 return get_tv_string_buf(varp, mybuf);
17332 static char_u *
17333 get_tv_string_buf(varp, buf)
17334 typval_T *varp;
17335 char_u *buf;
17337 char_u *res = get_tv_string_buf_chk(varp, buf);
17339 return res != NULL ? res : (char_u *)"";
17342 char_u *
17343 get_tv_string_chk(varp)
17344 typval_T *varp;
17346 static char_u mybuf[NUMBUFLEN];
17348 return get_tv_string_buf_chk(varp, mybuf);
17351 static char_u *
17352 get_tv_string_buf_chk(varp, buf)
17353 typval_T *varp;
17354 char_u *buf;
17356 switch (varp->v_type)
17358 case VAR_NUMBER:
17359 sprintf((char *)buf, "%ld", (long)varp->vval.v_number);
17360 return buf;
17361 case VAR_FUNC:
17362 EMSG(_("E729: using Funcref as a String"));
17363 break;
17364 case VAR_LIST:
17365 EMSG(_("E730: using List as a String"));
17366 break;
17367 case VAR_DICT:
17368 EMSG(_("E731: using Dictionary as a String"));
17369 break;
17370 case VAR_STRING:
17371 if (varp->vval.v_string != NULL)
17372 return varp->vval.v_string;
17373 return (char_u *)"";
17374 default:
17375 EMSG2(_(e_intern2), "get_tv_string_buf()");
17376 break;
17378 return NULL;
17382 * Find variable "name" in the list of variables.
17383 * Return a pointer to it if found, NULL if not found.
17384 * Careful: "a:0" variables don't have a name.
17385 * When "htp" is not NULL we are writing to the variable, set "htp" to the
17386 * hashtab_T used.
17388 static dictitem_T *
17389 find_var(name, htp)
17390 char_u *name;
17391 hashtab_T **htp;
17393 char_u *varname;
17394 hashtab_T *ht;
17396 ht = find_var_ht(name, &varname);
17397 if (htp != NULL)
17398 *htp = ht;
17399 if (ht == NULL)
17400 return NULL;
17401 return find_var_in_ht(ht, varname, htp != NULL);
17405 * Find variable "varname" in hashtab "ht".
17406 * Returns NULL if not found.
17408 static dictitem_T *
17409 find_var_in_ht(ht, varname, writing)
17410 hashtab_T *ht;
17411 char_u *varname;
17412 int writing;
17414 hashitem_T *hi;
17416 if (*varname == NUL)
17418 /* Must be something like "s:", otherwise "ht" would be NULL. */
17419 switch (varname[-2])
17421 case 's': return &SCRIPT_SV(current_SID).sv_var;
17422 case 'g': return &globvars_var;
17423 case 'v': return &vimvars_var;
17424 case 'b': return &curbuf->b_bufvar;
17425 case 'w': return &curwin->w_winvar;
17426 #ifdef FEAT_WINDOWS
17427 case 't': return &curtab->tp_winvar;
17428 #endif
17429 case 'l': return current_funccal == NULL
17430 ? NULL : &current_funccal->l_vars_var;
17431 case 'a': return current_funccal == NULL
17432 ? NULL : &current_funccal->l_avars_var;
17434 return NULL;
17437 hi = hash_find(ht, varname);
17438 if (HASHITEM_EMPTY(hi))
17440 /* For global variables we may try auto-loading the script. If it
17441 * worked find the variable again. Don't auto-load a script if it was
17442 * loaded already, otherwise it would be loaded every time when
17443 * checking if a function name is a Funcref variable. */
17444 if (ht == &globvarht && !writing
17445 && script_autoload(varname, FALSE) && !aborting())
17446 hi = hash_find(ht, varname);
17447 if (HASHITEM_EMPTY(hi))
17448 return NULL;
17450 return HI2DI(hi);
17454 * Find the hashtab used for a variable name.
17455 * Set "varname" to the start of name without ':'.
17457 static hashtab_T *
17458 find_var_ht(name, varname)
17459 char_u *name;
17460 char_u **varname;
17462 hashitem_T *hi;
17464 if (name[1] != ':')
17466 /* The name must not start with a colon or #. */
17467 if (name[0] == ':' || name[0] == AUTOLOAD_CHAR)
17468 return NULL;
17469 *varname = name;
17471 /* "version" is "v:version" in all scopes */
17472 hi = hash_find(&compat_hashtab, name);
17473 if (!HASHITEM_EMPTY(hi))
17474 return &compat_hashtab;
17476 if (current_funccal == NULL)
17477 return &globvarht; /* global variable */
17478 return &current_funccal->l_vars.dv_hashtab; /* l: variable */
17480 *varname = name + 2;
17481 if (*name == 'g') /* global variable */
17482 return &globvarht;
17483 /* There must be no ':' or '#' in the rest of the name, unless g: is used
17485 if (vim_strchr(name + 2, ':') != NULL
17486 || vim_strchr(name + 2, AUTOLOAD_CHAR) != NULL)
17487 return NULL;
17488 if (*name == 'b') /* buffer variable */
17489 return &curbuf->b_vars.dv_hashtab;
17490 if (*name == 'w') /* window variable */
17491 return &curwin->w_vars.dv_hashtab;
17492 #ifdef FEAT_WINDOWS
17493 if (*name == 't') /* tab page variable */
17494 return &curtab->tp_vars.dv_hashtab;
17495 #endif
17496 if (*name == 'v') /* v: variable */
17497 return &vimvarht;
17498 if (*name == 'a' && current_funccal != NULL) /* function argument */
17499 return &current_funccal->l_avars.dv_hashtab;
17500 if (*name == 'l' && current_funccal != NULL) /* local function variable */
17501 return &current_funccal->l_vars.dv_hashtab;
17502 if (*name == 's' /* script variable */
17503 && current_SID > 0 && current_SID <= ga_scripts.ga_len)
17504 return &SCRIPT_VARS(current_SID);
17505 return NULL;
17509 * Get the string value of a (global/local) variable.
17510 * Returns NULL when it doesn't exist.
17512 char_u *
17513 get_var_value(name)
17514 char_u *name;
17516 dictitem_T *v;
17518 v = find_var(name, NULL);
17519 if (v == NULL)
17520 return NULL;
17521 return get_tv_string(&v->di_tv);
17525 * Allocate a new hashtab for a sourced script. It will be used while
17526 * sourcing this script and when executing functions defined in the script.
17528 void
17529 new_script_vars(id)
17530 scid_T id;
17532 int i;
17533 hashtab_T *ht;
17534 scriptvar_T *sv;
17536 if (ga_grow(&ga_scripts, (int)(id - ga_scripts.ga_len)) == OK)
17538 /* Re-allocating ga_data means that an ht_array pointing to
17539 * ht_smallarray becomes invalid. We can recognize this: ht_mask is
17540 * at its init value. Also reset "v_dict", it's always the same. */
17541 for (i = 1; i <= ga_scripts.ga_len; ++i)
17543 ht = &SCRIPT_VARS(i);
17544 if (ht->ht_mask == HT_INIT_SIZE - 1)
17545 ht->ht_array = ht->ht_smallarray;
17546 sv = &SCRIPT_SV(i);
17547 sv->sv_var.di_tv.vval.v_dict = &sv->sv_dict;
17550 while (ga_scripts.ga_len < id)
17552 sv = &SCRIPT_SV(ga_scripts.ga_len + 1);
17553 init_var_dict(&sv->sv_dict, &sv->sv_var);
17554 ++ga_scripts.ga_len;
17560 * Initialize dictionary "dict" as a scope and set variable "dict_var" to
17561 * point to it.
17563 void
17564 init_var_dict(dict, dict_var)
17565 dict_T *dict;
17566 dictitem_T *dict_var;
17568 hash_init(&dict->dv_hashtab);
17569 dict->dv_refcount = 99999;
17570 dict_var->di_tv.vval.v_dict = dict;
17571 dict_var->di_tv.v_type = VAR_DICT;
17572 dict_var->di_tv.v_lock = VAR_FIXED;
17573 dict_var->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
17574 dict_var->di_key[0] = NUL;
17578 * Clean up a list of internal variables.
17579 * Frees all allocated variables and the value they contain.
17580 * Clears hashtab "ht", does not free it.
17582 void
17583 vars_clear(ht)
17584 hashtab_T *ht;
17586 vars_clear_ext(ht, TRUE);
17590 * Like vars_clear(), but only free the value if "free_val" is TRUE.
17592 static void
17593 vars_clear_ext(ht, free_val)
17594 hashtab_T *ht;
17595 int free_val;
17597 int todo;
17598 hashitem_T *hi;
17599 dictitem_T *v;
17601 hash_lock(ht);
17602 todo = (int)ht->ht_used;
17603 for (hi = ht->ht_array; todo > 0; ++hi)
17605 if (!HASHITEM_EMPTY(hi))
17607 --todo;
17609 /* Free the variable. Don't remove it from the hashtab,
17610 * ht_array might change then. hash_clear() takes care of it
17611 * later. */
17612 v = HI2DI(hi);
17613 if (free_val)
17614 clear_tv(&v->di_tv);
17615 if ((v->di_flags & DI_FLAGS_FIX) == 0)
17616 vim_free(v);
17619 hash_clear(ht);
17620 ht->ht_used = 0;
17624 * Delete a variable from hashtab "ht" at item "hi".
17625 * Clear the variable value and free the dictitem.
17627 static void
17628 delete_var(ht, hi)
17629 hashtab_T *ht;
17630 hashitem_T *hi;
17632 dictitem_T *di = HI2DI(hi);
17634 hash_remove(ht, hi);
17635 clear_tv(&di->di_tv);
17636 vim_free(di);
17640 * List the value of one internal variable.
17642 static void
17643 list_one_var(v, prefix)
17644 dictitem_T *v;
17645 char_u *prefix;
17647 char_u *tofree;
17648 char_u *s;
17649 char_u numbuf[NUMBUFLEN];
17651 s = echo_string(&v->di_tv, &tofree, numbuf, ++current_copyID);
17652 list_one_var_a(prefix, v->di_key, v->di_tv.v_type,
17653 s == NULL ? (char_u *)"" : s);
17654 vim_free(tofree);
17657 static void
17658 list_one_var_a(prefix, name, type, string)
17659 char_u *prefix;
17660 char_u *name;
17661 int type;
17662 char_u *string;
17664 msg_attr(prefix, 0); /* don't use msg(), it overwrites "v:statusmsg" */
17665 if (name != NULL) /* "a:" vars don't have a name stored */
17666 msg_puts(name);
17667 msg_putchar(' ');
17668 msg_advance(22);
17669 if (type == VAR_NUMBER)
17670 msg_putchar('#');
17671 else if (type == VAR_FUNC)
17672 msg_putchar('*');
17673 else if (type == VAR_LIST)
17675 msg_putchar('[');
17676 if (*string == '[')
17677 ++string;
17679 else if (type == VAR_DICT)
17681 msg_putchar('{');
17682 if (*string == '{')
17683 ++string;
17685 else
17686 msg_putchar(' ');
17688 msg_outtrans(string);
17690 if (type == VAR_FUNC)
17691 msg_puts((char_u *)"()");
17695 * Set variable "name" to value in "tv".
17696 * If the variable already exists, the value is updated.
17697 * Otherwise the variable is created.
17699 static void
17700 set_var(name, tv, copy)
17701 char_u *name;
17702 typval_T *tv;
17703 int copy; /* make copy of value in "tv" */
17705 dictitem_T *v;
17706 char_u *varname;
17707 hashtab_T *ht;
17708 char_u *p;
17710 if (tv->v_type == VAR_FUNC)
17712 if (!(vim_strchr((char_u *)"wbs", name[0]) != NULL && name[1] == ':')
17713 && !ASCII_ISUPPER((name[0] != NUL && name[1] == ':')
17714 ? name[2] : name[0]))
17716 EMSG2(_("E704: Funcref variable name must start with a capital: %s"), name);
17717 return;
17719 if (function_exists(name))
17721 EMSG2(_("E705: Variable name conflicts with existing function: %s"),
17722 name);
17723 return;
17727 ht = find_var_ht(name, &varname);
17728 if (ht == NULL || *varname == NUL)
17730 EMSG2(_(e_illvar), name);
17731 return;
17734 v = find_var_in_ht(ht, varname, TRUE);
17735 if (v != NULL)
17737 /* existing variable, need to clear the value */
17738 if (var_check_ro(v->di_flags, name)
17739 || tv_check_lock(v->di_tv.v_lock, name))
17740 return;
17741 if (v->di_tv.v_type != tv->v_type
17742 && !((v->di_tv.v_type == VAR_STRING
17743 || v->di_tv.v_type == VAR_NUMBER)
17744 && (tv->v_type == VAR_STRING
17745 || tv->v_type == VAR_NUMBER)))
17747 EMSG2(_("E706: Variable type mismatch for: %s"), name);
17748 return;
17752 * Handle setting internal v: variables separately: we don't change
17753 * the type.
17755 if (ht == &vimvarht)
17757 if (v->di_tv.v_type == VAR_STRING)
17759 vim_free(v->di_tv.vval.v_string);
17760 if (copy || tv->v_type != VAR_STRING)
17761 v->di_tv.vval.v_string = vim_strsave(get_tv_string(tv));
17762 else
17764 /* Take over the string to avoid an extra alloc/free. */
17765 v->di_tv.vval.v_string = tv->vval.v_string;
17766 tv->vval.v_string = NULL;
17769 else if (v->di_tv.v_type != VAR_NUMBER)
17770 EMSG2(_(e_intern2), "set_var()");
17771 else
17772 v->di_tv.vval.v_number = get_tv_number(tv);
17773 return;
17776 clear_tv(&v->di_tv);
17778 else /* add a new variable */
17780 /* Can't add "v:" variable. */
17781 if (ht == &vimvarht)
17783 EMSG2(_(e_illvar), name);
17784 return;
17787 /* Make sure the variable name is valid. */
17788 for (p = varname; *p != NUL; ++p)
17789 if (!eval_isnamec1(*p) && (p == varname || !VIM_ISDIGIT(*p))
17790 && *p != AUTOLOAD_CHAR)
17792 EMSG2(_(e_illvar), varname);
17793 return;
17796 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
17797 + STRLEN(varname)));
17798 if (v == NULL)
17799 return;
17800 STRCPY(v->di_key, varname);
17801 if (hash_add(ht, DI2HIKEY(v)) == FAIL)
17803 vim_free(v);
17804 return;
17806 v->di_flags = 0;
17809 if (copy || tv->v_type == VAR_NUMBER)
17810 copy_tv(tv, &v->di_tv);
17811 else
17813 v->di_tv = *tv;
17814 v->di_tv.v_lock = 0;
17815 init_tv(tv);
17820 * Return TRUE if di_flags "flags" indicate read-only variable "name".
17821 * Also give an error message.
17823 static int
17824 var_check_ro(flags, name)
17825 int flags;
17826 char_u *name;
17828 if (flags & DI_FLAGS_RO)
17830 EMSG2(_(e_readonlyvar), name);
17831 return TRUE;
17833 if ((flags & DI_FLAGS_RO_SBX) && sandbox)
17835 EMSG2(_(e_readonlysbx), name);
17836 return TRUE;
17838 return FALSE;
17842 * Return TRUE if typeval "tv" is set to be locked (immutable).
17843 * Also give an error message, using "name".
17845 static int
17846 tv_check_lock(lock, name)
17847 int lock;
17848 char_u *name;
17850 if (lock & VAR_LOCKED)
17852 EMSG2(_("E741: Value is locked: %s"),
17853 name == NULL ? (char_u *)_("Unknown") : name);
17854 return TRUE;
17856 if (lock & VAR_FIXED)
17858 EMSG2(_("E742: Cannot change value of %s"),
17859 name == NULL ? (char_u *)_("Unknown") : name);
17860 return TRUE;
17862 return FALSE;
17866 * Copy the values from typval_T "from" to typval_T "to".
17867 * When needed allocates string or increases reference count.
17868 * Does not make a copy of a list or dict but copies the reference!
17870 static void
17871 copy_tv(from, to)
17872 typval_T *from;
17873 typval_T *to;
17875 to->v_type = from->v_type;
17876 to->v_lock = 0;
17877 switch (from->v_type)
17879 case VAR_NUMBER:
17880 to->vval.v_number = from->vval.v_number;
17881 break;
17882 case VAR_STRING:
17883 case VAR_FUNC:
17884 if (from->vval.v_string == NULL)
17885 to->vval.v_string = NULL;
17886 else
17888 to->vval.v_string = vim_strsave(from->vval.v_string);
17889 if (from->v_type == VAR_FUNC)
17890 func_ref(to->vval.v_string);
17892 break;
17893 case VAR_LIST:
17894 if (from->vval.v_list == NULL)
17895 to->vval.v_list = NULL;
17896 else
17898 to->vval.v_list = from->vval.v_list;
17899 ++to->vval.v_list->lv_refcount;
17901 break;
17902 case VAR_DICT:
17903 if (from->vval.v_dict == NULL)
17904 to->vval.v_dict = NULL;
17905 else
17907 to->vval.v_dict = from->vval.v_dict;
17908 ++to->vval.v_dict->dv_refcount;
17910 break;
17911 default:
17912 EMSG2(_(e_intern2), "copy_tv()");
17913 break;
17918 * Make a copy of an item.
17919 * Lists and Dictionaries are also copied. A deep copy if "deep" is set.
17920 * For deepcopy() "copyID" is zero for a full copy or the ID for when a
17921 * reference to an already copied list/dict can be used.
17922 * Returns FAIL or OK.
17924 static int
17925 item_copy(from, to, deep, copyID)
17926 typval_T *from;
17927 typval_T *to;
17928 int deep;
17929 int copyID;
17931 static int recurse = 0;
17932 int ret = OK;
17934 if (recurse >= DICT_MAXNEST)
17936 EMSG(_("E698: variable nested too deep for making a copy"));
17937 return FAIL;
17939 ++recurse;
17941 switch (from->v_type)
17943 case VAR_NUMBER:
17944 case VAR_STRING:
17945 case VAR_FUNC:
17946 copy_tv(from, to);
17947 break;
17948 case VAR_LIST:
17949 to->v_type = VAR_LIST;
17950 to->v_lock = 0;
17951 if (from->vval.v_list == NULL)
17952 to->vval.v_list = NULL;
17953 else if (copyID != 0 && from->vval.v_list->lv_copyID == copyID)
17955 /* use the copy made earlier */
17956 to->vval.v_list = from->vval.v_list->lv_copylist;
17957 ++to->vval.v_list->lv_refcount;
17959 else
17960 to->vval.v_list = list_copy(from->vval.v_list, deep, copyID);
17961 if (to->vval.v_list == NULL)
17962 ret = FAIL;
17963 break;
17964 case VAR_DICT:
17965 to->v_type = VAR_DICT;
17966 to->v_lock = 0;
17967 if (from->vval.v_dict == NULL)
17968 to->vval.v_dict = NULL;
17969 else if (copyID != 0 && from->vval.v_dict->dv_copyID == copyID)
17971 /* use the copy made earlier */
17972 to->vval.v_dict = from->vval.v_dict->dv_copydict;
17973 ++to->vval.v_dict->dv_refcount;
17975 else
17976 to->vval.v_dict = dict_copy(from->vval.v_dict, deep, copyID);
17977 if (to->vval.v_dict == NULL)
17978 ret = FAIL;
17979 break;
17980 default:
17981 EMSG2(_(e_intern2), "item_copy()");
17982 ret = FAIL;
17984 --recurse;
17985 return ret;
17989 * ":echo expr1 ..." print each argument separated with a space, add a
17990 * newline at the end.
17991 * ":echon expr1 ..." print each argument plain.
17993 void
17994 ex_echo(eap)
17995 exarg_T *eap;
17997 char_u *arg = eap->arg;
17998 typval_T rettv;
17999 char_u *tofree;
18000 char_u *p;
18001 int needclr = TRUE;
18002 int atstart = TRUE;
18003 char_u numbuf[NUMBUFLEN];
18005 if (eap->skip)
18006 ++emsg_skip;
18007 while (*arg != NUL && *arg != '|' && *arg != '\n' && !got_int)
18009 p = arg;
18010 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
18013 * Report the invalid expression unless the expression evaluation
18014 * has been cancelled due to an aborting error, an interrupt, or an
18015 * exception.
18017 if (!aborting())
18018 EMSG2(_(e_invexpr2), p);
18019 break;
18021 if (!eap->skip)
18023 if (atstart)
18025 atstart = FALSE;
18026 /* Call msg_start() after eval1(), evaluating the expression
18027 * may cause a message to appear. */
18028 if (eap->cmdidx == CMD_echo)
18029 msg_start();
18031 else if (eap->cmdidx == CMD_echo)
18032 msg_puts_attr((char_u *)" ", echo_attr);
18033 p = echo_string(&rettv, &tofree, numbuf, ++current_copyID);
18034 if (p != NULL)
18035 for ( ; *p != NUL && !got_int; ++p)
18037 if (*p == '\n' || *p == '\r' || *p == TAB)
18039 if (*p != TAB && needclr)
18041 /* remove any text still there from the command */
18042 msg_clr_eos();
18043 needclr = FALSE;
18045 msg_putchar_attr(*p, echo_attr);
18047 else
18049 #ifdef FEAT_MBYTE
18050 if (has_mbyte)
18052 int i = (*mb_ptr2len)(p);
18054 (void)msg_outtrans_len_attr(p, i, echo_attr);
18055 p += i - 1;
18057 else
18058 #endif
18059 (void)msg_outtrans_len_attr(p, 1, echo_attr);
18062 vim_free(tofree);
18064 clear_tv(&rettv);
18065 arg = skipwhite(arg);
18067 eap->nextcmd = check_nextcmd(arg);
18069 if (eap->skip)
18070 --emsg_skip;
18071 else
18073 /* remove text that may still be there from the command */
18074 if (needclr)
18075 msg_clr_eos();
18076 if (eap->cmdidx == CMD_echo)
18077 msg_end();
18082 * ":echohl {name}".
18084 void
18085 ex_echohl(eap)
18086 exarg_T *eap;
18088 int id;
18090 id = syn_name2id(eap->arg);
18091 if (id == 0)
18092 echo_attr = 0;
18093 else
18094 echo_attr = syn_id2attr(id);
18098 * ":execute expr1 ..." execute the result of an expression.
18099 * ":echomsg expr1 ..." Print a message
18100 * ":echoerr expr1 ..." Print an error
18101 * Each gets spaces around each argument and a newline at the end for
18102 * echo commands
18104 void
18105 ex_execute(eap)
18106 exarg_T *eap;
18108 char_u *arg = eap->arg;
18109 typval_T rettv;
18110 int ret = OK;
18111 char_u *p;
18112 garray_T ga;
18113 int len;
18114 int save_did_emsg;
18116 ga_init2(&ga, 1, 80);
18118 if (eap->skip)
18119 ++emsg_skip;
18120 while (*arg != NUL && *arg != '|' && *arg != '\n')
18122 p = arg;
18123 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
18126 * Report the invalid expression unless the expression evaluation
18127 * has been cancelled due to an aborting error, an interrupt, or an
18128 * exception.
18130 if (!aborting())
18131 EMSG2(_(e_invexpr2), p);
18132 ret = FAIL;
18133 break;
18136 if (!eap->skip)
18138 p = get_tv_string(&rettv);
18139 len = (int)STRLEN(p);
18140 if (ga_grow(&ga, len + 2) == FAIL)
18142 clear_tv(&rettv);
18143 ret = FAIL;
18144 break;
18146 if (ga.ga_len)
18147 ((char_u *)(ga.ga_data))[ga.ga_len++] = ' ';
18148 STRCPY((char_u *)(ga.ga_data) + ga.ga_len, p);
18149 ga.ga_len += len;
18152 clear_tv(&rettv);
18153 arg = skipwhite(arg);
18156 if (ret != FAIL && ga.ga_data != NULL)
18158 if (eap->cmdidx == CMD_echomsg)
18160 MSG_ATTR(ga.ga_data, echo_attr);
18161 out_flush();
18163 else if (eap->cmdidx == CMD_echoerr)
18165 /* We don't want to abort following commands, restore did_emsg. */
18166 save_did_emsg = did_emsg;
18167 EMSG((char_u *)ga.ga_data);
18168 if (!force_abort)
18169 did_emsg = save_did_emsg;
18171 else if (eap->cmdidx == CMD_execute)
18172 do_cmdline((char_u *)ga.ga_data,
18173 eap->getline, eap->cookie, DOCMD_NOWAIT|DOCMD_VERBOSE);
18176 ga_clear(&ga);
18178 if (eap->skip)
18179 --emsg_skip;
18181 eap->nextcmd = check_nextcmd(arg);
18185 * Skip over the name of an option: "&option", "&g:option" or "&l:option".
18186 * "arg" points to the "&" or '+' when called, to "option" when returning.
18187 * Returns NULL when no option name found. Otherwise pointer to the char
18188 * after the option name.
18190 static char_u *
18191 find_option_end(arg, opt_flags)
18192 char_u **arg;
18193 int *opt_flags;
18195 char_u *p = *arg;
18197 ++p;
18198 if (*p == 'g' && p[1] == ':')
18200 *opt_flags = OPT_GLOBAL;
18201 p += 2;
18203 else if (*p == 'l' && p[1] == ':')
18205 *opt_flags = OPT_LOCAL;
18206 p += 2;
18208 else
18209 *opt_flags = 0;
18211 if (!ASCII_ISALPHA(*p))
18212 return NULL;
18213 *arg = p;
18215 if (p[0] == 't' && p[1] == '_' && p[2] != NUL && p[3] != NUL)
18216 p += 4; /* termcap option */
18217 else
18218 while (ASCII_ISALPHA(*p))
18219 ++p;
18220 return p;
18224 * ":function"
18226 void
18227 ex_function(eap)
18228 exarg_T *eap;
18230 char_u *theline;
18231 int j;
18232 int c;
18233 int saved_did_emsg;
18234 char_u *name = NULL;
18235 char_u *p;
18236 char_u *arg;
18237 char_u *line_arg = NULL;
18238 garray_T newargs;
18239 garray_T newlines;
18240 int varargs = FALSE;
18241 int mustend = FALSE;
18242 int flags = 0;
18243 ufunc_T *fp;
18244 int indent;
18245 int nesting;
18246 char_u *skip_until = NULL;
18247 dictitem_T *v;
18248 funcdict_T fudi;
18249 static int func_nr = 0; /* number for nameless function */
18250 int paren;
18251 hashtab_T *ht;
18252 int todo;
18253 hashitem_T *hi;
18254 int sourcing_lnum_off;
18257 * ":function" without argument: list functions.
18259 if (ends_excmd(*eap->arg))
18261 if (!eap->skip)
18263 todo = (int)func_hashtab.ht_used;
18264 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
18266 if (!HASHITEM_EMPTY(hi))
18268 --todo;
18269 fp = HI2UF(hi);
18270 if (!isdigit(*fp->uf_name))
18271 list_func_head(fp, FALSE);
18275 eap->nextcmd = check_nextcmd(eap->arg);
18276 return;
18280 * ":function /pat": list functions matching pattern.
18282 if (*eap->arg == '/')
18284 p = skip_regexp(eap->arg + 1, '/', TRUE, NULL);
18285 if (!eap->skip)
18287 regmatch_T regmatch;
18289 c = *p;
18290 *p = NUL;
18291 regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC);
18292 *p = c;
18293 if (regmatch.regprog != NULL)
18295 regmatch.rm_ic = p_ic;
18297 todo = (int)func_hashtab.ht_used;
18298 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
18300 if (!HASHITEM_EMPTY(hi))
18302 --todo;
18303 fp = HI2UF(hi);
18304 if (!isdigit(*fp->uf_name)
18305 && vim_regexec(&regmatch, fp->uf_name, 0))
18306 list_func_head(fp, FALSE);
18311 if (*p == '/')
18312 ++p;
18313 eap->nextcmd = check_nextcmd(p);
18314 return;
18318 * Get the function name. There are these situations:
18319 * func normal function name
18320 * "name" == func, "fudi.fd_dict" == NULL
18321 * dict.func new dictionary entry
18322 * "name" == NULL, "fudi.fd_dict" set,
18323 * "fudi.fd_di" == NULL, "fudi.fd_newkey" == func
18324 * dict.func existing dict entry with a Funcref
18325 * "name" == func, "fudi.fd_dict" set,
18326 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
18327 * dict.func existing dict entry that's not a Funcref
18328 * "name" == NULL, "fudi.fd_dict" set,
18329 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
18331 p = eap->arg;
18332 name = trans_function_name(&p, eap->skip, 0, &fudi);
18333 paren = (vim_strchr(p, '(') != NULL);
18334 if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip)
18337 * Return on an invalid expression in braces, unless the expression
18338 * evaluation has been cancelled due to an aborting error, an
18339 * interrupt, or an exception.
18341 if (!aborting())
18343 if (!eap->skip && fudi.fd_newkey != NULL)
18344 EMSG2(_(e_dictkey), fudi.fd_newkey);
18345 vim_free(fudi.fd_newkey);
18346 return;
18348 else
18349 eap->skip = TRUE;
18352 /* An error in a function call during evaluation of an expression in magic
18353 * braces should not cause the function not to be defined. */
18354 saved_did_emsg = did_emsg;
18355 did_emsg = FALSE;
18358 * ":function func" with only function name: list function.
18360 if (!paren)
18362 if (!ends_excmd(*skipwhite(p)))
18364 EMSG(_(e_trailing));
18365 goto ret_free;
18367 eap->nextcmd = check_nextcmd(p);
18368 if (eap->nextcmd != NULL)
18369 *p = NUL;
18370 if (!eap->skip && !got_int)
18372 fp = find_func(name);
18373 if (fp != NULL)
18375 list_func_head(fp, TRUE);
18376 for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j)
18378 if (FUNCLINE(fp, j) == NULL)
18379 continue;
18380 msg_putchar('\n');
18381 msg_outnum((long)(j + 1));
18382 if (j < 9)
18383 msg_putchar(' ');
18384 if (j < 99)
18385 msg_putchar(' ');
18386 msg_prt_line(FUNCLINE(fp, j), FALSE);
18387 out_flush(); /* show a line at a time */
18388 ui_breakcheck();
18390 if (!got_int)
18392 msg_putchar('\n');
18393 msg_puts((char_u *)" endfunction");
18396 else
18397 emsg_funcname("E123: Undefined function: %s", name);
18399 goto ret_free;
18403 * ":function name(arg1, arg2)" Define function.
18405 p = skipwhite(p);
18406 if (*p != '(')
18408 if (!eap->skip)
18410 EMSG2(_("E124: Missing '(': %s"), eap->arg);
18411 goto ret_free;
18413 /* attempt to continue by skipping some text */
18414 if (vim_strchr(p, '(') != NULL)
18415 p = vim_strchr(p, '(');
18417 p = skipwhite(p + 1);
18419 ga_init2(&newargs, (int)sizeof(char_u *), 3);
18420 ga_init2(&newlines, (int)sizeof(char_u *), 3);
18422 if (!eap->skip)
18424 /* Check the name of the function. */
18425 if (name != NULL)
18426 arg = name;
18427 else
18428 arg = fudi.fd_newkey;
18429 if (arg != NULL)
18431 if (*arg == K_SPECIAL)
18432 j = 3;
18433 else
18434 j = 0;
18435 while (arg[j] != NUL && (j == 0 ? eval_isnamec1(arg[j])
18436 : eval_isnamec(arg[j])))
18437 ++j;
18438 if (arg[j] != NUL)
18439 emsg_funcname(_(e_invarg2), arg);
18444 * Isolate the arguments: "arg1, arg2, ...)"
18446 while (*p != ')')
18448 if (p[0] == '.' && p[1] == '.' && p[2] == '.')
18450 varargs = TRUE;
18451 p += 3;
18452 mustend = TRUE;
18454 else
18456 arg = p;
18457 while (ASCII_ISALNUM(*p) || *p == '_')
18458 ++p;
18459 if (arg == p || isdigit(*arg)
18460 || (p - arg == 9 && STRNCMP(arg, "firstline", 9) == 0)
18461 || (p - arg == 8 && STRNCMP(arg, "lastline", 8) == 0))
18463 if (!eap->skip)
18464 EMSG2(_("E125: Illegal argument: %s"), arg);
18465 break;
18467 if (ga_grow(&newargs, 1) == FAIL)
18468 goto erret;
18469 c = *p;
18470 *p = NUL;
18471 arg = vim_strsave(arg);
18472 if (arg == NULL)
18473 goto erret;
18474 ((char_u **)(newargs.ga_data))[newargs.ga_len] = arg;
18475 *p = c;
18476 newargs.ga_len++;
18477 if (*p == ',')
18478 ++p;
18479 else
18480 mustend = TRUE;
18482 p = skipwhite(p);
18483 if (mustend && *p != ')')
18485 if (!eap->skip)
18486 EMSG2(_(e_invarg2), eap->arg);
18487 break;
18490 ++p; /* skip the ')' */
18492 /* find extra arguments "range", "dict" and "abort" */
18493 for (;;)
18495 p = skipwhite(p);
18496 if (STRNCMP(p, "range", 5) == 0)
18498 flags |= FC_RANGE;
18499 p += 5;
18501 else if (STRNCMP(p, "dict", 4) == 0)
18503 flags |= FC_DICT;
18504 p += 4;
18506 else if (STRNCMP(p, "abort", 5) == 0)
18508 flags |= FC_ABORT;
18509 p += 5;
18511 else
18512 break;
18515 /* When there is a line break use what follows for the function body.
18516 * Makes 'exe "func Test()\n...\nendfunc"' work. */
18517 if (*p == '\n')
18518 line_arg = p + 1;
18519 else if (*p != NUL && *p != '"' && !eap->skip && !did_emsg)
18520 EMSG(_(e_trailing));
18523 * Read the body of the function, until ":endfunction" is found.
18525 if (KeyTyped)
18527 /* Check if the function already exists, don't let the user type the
18528 * whole function before telling him it doesn't work! For a script we
18529 * need to skip the body to be able to find what follows. */
18530 if (!eap->skip && !eap->forceit)
18532 if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL)
18533 EMSG(_(e_funcdict));
18534 else if (name != NULL && find_func(name) != NULL)
18535 emsg_funcname(e_funcexts, name);
18538 if (!eap->skip && did_emsg)
18539 goto erret;
18541 msg_putchar('\n'); /* don't overwrite the function name */
18542 cmdline_row = msg_row;
18545 indent = 2;
18546 nesting = 0;
18547 for (;;)
18549 msg_scroll = TRUE;
18550 need_wait_return = FALSE;
18551 sourcing_lnum_off = sourcing_lnum;
18553 if (line_arg != NULL)
18555 /* Use eap->arg, split up in parts by line breaks. */
18556 theline = line_arg;
18557 p = vim_strchr(theline, '\n');
18558 if (p == NULL)
18559 line_arg += STRLEN(line_arg);
18560 else
18562 *p = NUL;
18563 line_arg = p + 1;
18566 else if (eap->getline == NULL)
18567 theline = getcmdline(':', 0L, indent);
18568 else
18569 theline = eap->getline(':', eap->cookie, indent);
18570 if (KeyTyped)
18571 lines_left = Rows - 1;
18572 if (theline == NULL)
18574 EMSG(_("E126: Missing :endfunction"));
18575 goto erret;
18578 /* Detect line continuation: sourcing_lnum increased more than one. */
18579 if (sourcing_lnum > sourcing_lnum_off + 1)
18580 sourcing_lnum_off = sourcing_lnum - sourcing_lnum_off - 1;
18581 else
18582 sourcing_lnum_off = 0;
18584 if (skip_until != NULL)
18586 /* between ":append" and "." and between ":python <<EOF" and "EOF"
18587 * don't check for ":endfunc". */
18588 if (STRCMP(theline, skip_until) == 0)
18590 vim_free(skip_until);
18591 skip_until = NULL;
18594 else
18596 /* skip ':' and blanks*/
18597 for (p = theline; vim_iswhite(*p) || *p == ':'; ++p)
18600 /* Check for "endfunction". */
18601 if (checkforcmd(&p, "endfunction", 4) && nesting-- == 0)
18603 if (line_arg == NULL)
18604 vim_free(theline);
18605 break;
18608 /* Increase indent inside "if", "while", "for" and "try", decrease
18609 * at "end". */
18610 if (indent > 2 && STRNCMP(p, "end", 3) == 0)
18611 indent -= 2;
18612 else if (STRNCMP(p, "if", 2) == 0
18613 || STRNCMP(p, "wh", 2) == 0
18614 || STRNCMP(p, "for", 3) == 0
18615 || STRNCMP(p, "try", 3) == 0)
18616 indent += 2;
18618 /* Check for defining a function inside this function. */
18619 if (checkforcmd(&p, "function", 2))
18621 if (*p == '!')
18622 p = skipwhite(p + 1);
18623 p += eval_fname_script(p);
18624 if (ASCII_ISALPHA(*p))
18626 vim_free(trans_function_name(&p, TRUE, 0, NULL));
18627 if (*skipwhite(p) == '(')
18629 ++nesting;
18630 indent += 2;
18635 /* Check for ":append" or ":insert". */
18636 p = skip_range(p, NULL);
18637 if ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p'))
18638 || (p[0] == 'i'
18639 && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n'
18640 && (!ASCII_ISALPHA(p[2]) || (p[2] == 's'))))))
18641 skip_until = vim_strsave((char_u *)".");
18643 /* Check for ":python <<EOF", ":tcl <<EOF", etc. */
18644 arg = skipwhite(skiptowhite(p));
18645 if (arg[0] == '<' && arg[1] =='<'
18646 && ((p[0] == 'p' && p[1] == 'y'
18647 && (!ASCII_ISALPHA(p[2]) || p[2] == 't'))
18648 || (p[0] == 'p' && p[1] == 'e'
18649 && (!ASCII_ISALPHA(p[2]) || p[2] == 'r'))
18650 || (p[0] == 't' && p[1] == 'c'
18651 && (!ASCII_ISALPHA(p[2]) || p[2] == 'l'))
18652 || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b'
18653 && (!ASCII_ISALPHA(p[3]) || p[3] == 'y'))
18654 || (p[0] == 'm' && p[1] == 'z'
18655 && (!ASCII_ISALPHA(p[2]) || p[2] == 's'))
18658 /* ":python <<" continues until a dot, like ":append" */
18659 p = skipwhite(arg + 2);
18660 if (*p == NUL)
18661 skip_until = vim_strsave((char_u *)".");
18662 else
18663 skip_until = vim_strsave(p);
18667 /* Add the line to the function. */
18668 if (ga_grow(&newlines, 1 + sourcing_lnum_off) == FAIL)
18670 if (line_arg == NULL)
18671 vim_free(theline);
18672 goto erret;
18675 /* Copy the line to newly allocated memory. get_one_sourceline()
18676 * allocates 250 bytes per line, this saves 80% on average. The cost
18677 * is an extra alloc/free. */
18678 p = vim_strsave(theline);
18679 if (p != NULL)
18681 if (line_arg == NULL)
18682 vim_free(theline);
18683 theline = p;
18686 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = theline;
18688 /* Add NULL lines for continuation lines, so that the line count is
18689 * equal to the index in the growarray. */
18690 while (sourcing_lnum_off-- > 0)
18691 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = NULL;
18693 /* Check for end of eap->arg. */
18694 if (line_arg != NULL && *line_arg == NUL)
18695 line_arg = NULL;
18698 /* Don't define the function when skipping commands or when an error was
18699 * detected. */
18700 if (eap->skip || did_emsg)
18701 goto erret;
18704 * If there are no errors, add the function
18706 if (fudi.fd_dict == NULL)
18708 v = find_var(name, &ht);
18709 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
18711 emsg_funcname("E707: Function name conflicts with variable: %s",
18712 name);
18713 goto erret;
18716 fp = find_func(name);
18717 if (fp != NULL)
18719 if (!eap->forceit)
18721 emsg_funcname(e_funcexts, name);
18722 goto erret;
18724 if (fp->uf_calls > 0)
18726 emsg_funcname("E127: Cannot redefine function %s: It is in use",
18727 name);
18728 goto erret;
18730 /* redefine existing function */
18731 ga_clear_strings(&(fp->uf_args));
18732 ga_clear_strings(&(fp->uf_lines));
18733 vim_free(name);
18734 name = NULL;
18737 else
18739 char numbuf[20];
18741 fp = NULL;
18742 if (fudi.fd_newkey == NULL && !eap->forceit)
18744 EMSG(_(e_funcdict));
18745 goto erret;
18747 if (fudi.fd_di == NULL)
18749 /* Can't add a function to a locked dictionary */
18750 if (tv_check_lock(fudi.fd_dict->dv_lock, eap->arg))
18751 goto erret;
18753 /* Can't change an existing function if it is locked */
18754 else if (tv_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg))
18755 goto erret;
18757 /* Give the function a sequential number. Can only be used with a
18758 * Funcref! */
18759 vim_free(name);
18760 sprintf(numbuf, "%d", ++func_nr);
18761 name = vim_strsave((char_u *)numbuf);
18762 if (name == NULL)
18763 goto erret;
18766 if (fp == NULL)
18768 if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL)
18770 int slen, plen;
18771 char_u *scriptname;
18773 /* Check that the autoload name matches the script name. */
18774 j = FAIL;
18775 if (sourcing_name != NULL)
18777 scriptname = autoload_name(name);
18778 if (scriptname != NULL)
18780 p = vim_strchr(scriptname, '/');
18781 plen = (int)STRLEN(p);
18782 slen = (int)STRLEN(sourcing_name);
18783 if (slen > plen && fnamecmp(p,
18784 sourcing_name + slen - plen) == 0)
18785 j = OK;
18786 vim_free(scriptname);
18789 if (j == FAIL)
18791 EMSG2(_("E746: Function name does not match script file name: %s"), name);
18792 goto erret;
18796 fp = (ufunc_T *)alloc((unsigned)(sizeof(ufunc_T) + STRLEN(name)));
18797 if (fp == NULL)
18798 goto erret;
18800 if (fudi.fd_dict != NULL)
18802 if (fudi.fd_di == NULL)
18804 /* add new dict entry */
18805 fudi.fd_di = dictitem_alloc(fudi.fd_newkey);
18806 if (fudi.fd_di == NULL)
18808 vim_free(fp);
18809 goto erret;
18811 if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL)
18813 vim_free(fudi.fd_di);
18814 vim_free(fp);
18815 goto erret;
18818 else
18819 /* overwrite existing dict entry */
18820 clear_tv(&fudi.fd_di->di_tv);
18821 fudi.fd_di->di_tv.v_type = VAR_FUNC;
18822 fudi.fd_di->di_tv.v_lock = 0;
18823 fudi.fd_di->di_tv.vval.v_string = vim_strsave(name);
18824 fp->uf_refcount = 1;
18826 /* behave like "dict" was used */
18827 flags |= FC_DICT;
18830 /* insert the new function in the function list */
18831 STRCPY(fp->uf_name, name);
18832 hash_add(&func_hashtab, UF2HIKEY(fp));
18834 fp->uf_args = newargs;
18835 fp->uf_lines = newlines;
18836 #ifdef FEAT_PROFILE
18837 fp->uf_tml_count = NULL;
18838 fp->uf_tml_total = NULL;
18839 fp->uf_tml_self = NULL;
18840 fp->uf_profiling = FALSE;
18841 if (prof_def_func())
18842 func_do_profile(fp);
18843 #endif
18844 fp->uf_varargs = varargs;
18845 fp->uf_flags = flags;
18846 fp->uf_calls = 0;
18847 fp->uf_script_ID = current_SID;
18848 goto ret_free;
18850 erret:
18851 ga_clear_strings(&newargs);
18852 ga_clear_strings(&newlines);
18853 ret_free:
18854 vim_free(skip_until);
18855 vim_free(fudi.fd_newkey);
18856 vim_free(name);
18857 did_emsg |= saved_did_emsg;
18861 * Get a function name, translating "<SID>" and "<SNR>".
18862 * Also handles a Funcref in a List or Dictionary.
18863 * Returns the function name in allocated memory, or NULL for failure.
18864 * flags:
18865 * TFN_INT: internal function name OK
18866 * TFN_QUIET: be quiet
18867 * Advances "pp" to just after the function name (if no error).
18869 static char_u *
18870 trans_function_name(pp, skip, flags, fdp)
18871 char_u **pp;
18872 int skip; /* only find the end, don't evaluate */
18873 int flags;
18874 funcdict_T *fdp; /* return: info about dictionary used */
18876 char_u *name = NULL;
18877 char_u *start;
18878 char_u *end;
18879 int lead;
18880 char_u sid_buf[20];
18881 int len;
18882 lval_T lv;
18884 if (fdp != NULL)
18885 vim_memset(fdp, 0, sizeof(funcdict_T));
18886 start = *pp;
18888 /* Check for hard coded <SNR>: already translated function ID (from a user
18889 * command). */
18890 if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA
18891 && (*pp)[2] == (int)KE_SNR)
18893 *pp += 3;
18894 len = get_id_len(pp) + 3;
18895 return vim_strnsave(start, len);
18898 /* A name starting with "<SID>" or "<SNR>" is local to a script. But
18899 * don't skip over "s:", get_lval() needs it for "s:dict.func". */
18900 lead = eval_fname_script(start);
18901 if (lead > 2)
18902 start += lead;
18904 end = get_lval(start, NULL, &lv, FALSE, skip, flags & TFN_QUIET,
18905 lead > 2 ? 0 : FNE_CHECK_START);
18906 if (end == start)
18908 if (!skip)
18909 EMSG(_("E129: Function name required"));
18910 goto theend;
18912 if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range)))
18915 * Report an invalid expression in braces, unless the expression
18916 * evaluation has been cancelled due to an aborting error, an
18917 * interrupt, or an exception.
18919 if (!aborting())
18921 if (end != NULL)
18922 EMSG2(_(e_invarg2), start);
18924 else
18925 *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR);
18926 goto theend;
18929 if (lv.ll_tv != NULL)
18931 if (fdp != NULL)
18933 fdp->fd_dict = lv.ll_dict;
18934 fdp->fd_newkey = lv.ll_newkey;
18935 lv.ll_newkey = NULL;
18936 fdp->fd_di = lv.ll_di;
18938 if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL)
18940 name = vim_strsave(lv.ll_tv->vval.v_string);
18941 *pp = end;
18943 else
18945 if (!skip && !(flags & TFN_QUIET) && (fdp == NULL
18946 || lv.ll_dict == NULL || fdp->fd_newkey == NULL))
18947 EMSG(_(e_funcref));
18948 else
18949 *pp = end;
18950 name = NULL;
18952 goto theend;
18955 if (lv.ll_name == NULL)
18957 /* Error found, but continue after the function name. */
18958 *pp = end;
18959 goto theend;
18962 if (lv.ll_exp_name != NULL)
18964 len = (int)STRLEN(lv.ll_exp_name);
18965 if (lead <= 2 && lv.ll_name == lv.ll_exp_name
18966 && STRNCMP(lv.ll_name, "s:", 2) == 0)
18968 /* When there was "s:" already or the name expanded to get a
18969 * leading "s:" then remove it. */
18970 lv.ll_name += 2;
18971 len -= 2;
18972 lead = 2;
18975 else
18977 if (lead == 2) /* skip over "s:" */
18978 lv.ll_name += 2;
18979 len = (int)(end - lv.ll_name);
18983 * Copy the function name to allocated memory.
18984 * Accept <SID>name() inside a script, translate into <SNR>123_name().
18985 * Accept <SNR>123_name() outside a script.
18987 if (skip)
18988 lead = 0; /* do nothing */
18989 else if (lead > 0)
18991 lead = 3;
18992 if ((lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name))
18993 || eval_fname_sid(*pp))
18995 /* It's "s:" or "<SID>" */
18996 if (current_SID <= 0)
18998 EMSG(_(e_usingsid));
18999 goto theend;
19001 sprintf((char *)sid_buf, "%ld_", (long)current_SID);
19002 lead += (int)STRLEN(sid_buf);
19005 else if (!(flags & TFN_INT) && builtin_function(lv.ll_name))
19007 EMSG2(_("E128: Function name must start with a capital or contain a colon: %s"), lv.ll_name);
19008 goto theend;
19010 name = alloc((unsigned)(len + lead + 1));
19011 if (name != NULL)
19013 if (lead > 0)
19015 name[0] = K_SPECIAL;
19016 name[1] = KS_EXTRA;
19017 name[2] = (int)KE_SNR;
19018 if (lead > 3) /* If it's "<SID>" */
19019 STRCPY(name + 3, sid_buf);
19021 mch_memmove(name + lead, lv.ll_name, (size_t)len);
19022 name[len + lead] = NUL;
19024 *pp = end;
19026 theend:
19027 clear_lval(&lv);
19028 return name;
19032 * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case).
19033 * Return 2 if "p" starts with "s:".
19034 * Return 0 otherwise.
19036 static int
19037 eval_fname_script(p)
19038 char_u *p;
19040 if (p[0] == '<' && (STRNICMP(p + 1, "SID>", 4) == 0
19041 || STRNICMP(p + 1, "SNR>", 4) == 0))
19042 return 5;
19043 if (p[0] == 's' && p[1] == ':')
19044 return 2;
19045 return 0;
19049 * Return TRUE if "p" starts with "<SID>" or "s:".
19050 * Only works if eval_fname_script() returned non-zero for "p"!
19052 static int
19053 eval_fname_sid(p)
19054 char_u *p;
19056 return (*p == 's' || TOUPPER_ASC(p[2]) == 'I');
19060 * List the head of the function: "name(arg1, arg2)".
19062 static void
19063 list_func_head(fp, indent)
19064 ufunc_T *fp;
19065 int indent;
19067 int j;
19069 msg_start();
19070 if (indent)
19071 MSG_PUTS(" ");
19072 MSG_PUTS("function ");
19073 if (fp->uf_name[0] == K_SPECIAL)
19075 MSG_PUTS_ATTR("<SNR>", hl_attr(HLF_8));
19076 msg_puts(fp->uf_name + 3);
19078 else
19079 msg_puts(fp->uf_name);
19080 msg_putchar('(');
19081 for (j = 0; j < fp->uf_args.ga_len; ++j)
19083 if (j)
19084 MSG_PUTS(", ");
19085 msg_puts(FUNCARG(fp, j));
19087 if (fp->uf_varargs)
19089 if (j)
19090 MSG_PUTS(", ");
19091 MSG_PUTS("...");
19093 msg_putchar(')');
19094 msg_clr_eos();
19095 if (p_verbose > 0)
19096 last_set_msg(fp->uf_script_ID);
19100 * Find a function by name, return pointer to it in ufuncs.
19101 * Return NULL for unknown function.
19103 static ufunc_T *
19104 find_func(name)
19105 char_u *name;
19107 hashitem_T *hi;
19109 hi = hash_find(&func_hashtab, name);
19110 if (!HASHITEM_EMPTY(hi))
19111 return HI2UF(hi);
19112 return NULL;
19115 #if defined(EXITFREE) || defined(PROTO)
19116 void
19117 free_all_functions()
19119 hashitem_T *hi;
19121 /* Need to start all over every time, because func_free() may change the
19122 * hash table. */
19123 while (func_hashtab.ht_used > 0)
19124 for (hi = func_hashtab.ht_array; ; ++hi)
19125 if (!HASHITEM_EMPTY(hi))
19127 func_free(HI2UF(hi));
19128 break;
19131 #endif
19134 * Return TRUE if a function "name" exists.
19136 static int
19137 function_exists(name)
19138 char_u *name;
19140 char_u *nm = name;
19141 char_u *p;
19142 int n = FALSE;
19144 p = trans_function_name(&nm, FALSE, TFN_INT|TFN_QUIET, NULL);
19145 nm = skipwhite(nm);
19147 /* Only accept "funcname", "funcname ", "funcname (..." and
19148 * "funcname(...", not "funcname!...". */
19149 if (p != NULL && (*nm == NUL || *nm == '('))
19151 if (builtin_function(p))
19152 n = (find_internal_func(p) >= 0);
19153 else
19154 n = (find_func(p) != NULL);
19156 vim_free(p);
19157 return n;
19161 * Return TRUE if "name" looks like a builtin function name: starts with a
19162 * lower case letter and doesn't contain a ':' or AUTOLOAD_CHAR.
19164 static int
19165 builtin_function(name)
19166 char_u *name;
19168 return ASCII_ISLOWER(name[0]) && vim_strchr(name, ':') == NULL
19169 && vim_strchr(name, AUTOLOAD_CHAR) == NULL;
19172 #if defined(FEAT_PROFILE) || defined(PROTO)
19174 * Start profiling function "fp".
19176 static void
19177 func_do_profile(fp)
19178 ufunc_T *fp;
19180 fp->uf_tm_count = 0;
19181 profile_zero(&fp->uf_tm_self);
19182 profile_zero(&fp->uf_tm_total);
19183 if (fp->uf_tml_count == NULL)
19184 fp->uf_tml_count = (int *)alloc_clear((unsigned)
19185 (sizeof(int) * fp->uf_lines.ga_len));
19186 if (fp->uf_tml_total == NULL)
19187 fp->uf_tml_total = (proftime_T *)alloc_clear((unsigned)
19188 (sizeof(proftime_T) * fp->uf_lines.ga_len));
19189 if (fp->uf_tml_self == NULL)
19190 fp->uf_tml_self = (proftime_T *)alloc_clear((unsigned)
19191 (sizeof(proftime_T) * fp->uf_lines.ga_len));
19192 fp->uf_tml_idx = -1;
19193 if (fp->uf_tml_count == NULL || fp->uf_tml_total == NULL
19194 || fp->uf_tml_self == NULL)
19195 return; /* out of memory */
19197 fp->uf_profiling = TRUE;
19201 * Dump the profiling results for all functions in file "fd".
19203 void
19204 func_dump_profile(fd)
19205 FILE *fd;
19207 hashitem_T *hi;
19208 int todo;
19209 ufunc_T *fp;
19210 int i;
19211 ufunc_T **sorttab;
19212 int st_len = 0;
19214 todo = (int)func_hashtab.ht_used;
19215 sorttab = (ufunc_T **)alloc((unsigned)(sizeof(ufunc_T) * todo));
19217 for (hi = func_hashtab.ht_array; todo > 0; ++hi)
19219 if (!HASHITEM_EMPTY(hi))
19221 --todo;
19222 fp = HI2UF(hi);
19223 if (fp->uf_profiling)
19225 if (sorttab != NULL)
19226 sorttab[st_len++] = fp;
19228 if (fp->uf_name[0] == K_SPECIAL)
19229 fprintf(fd, "FUNCTION <SNR>%s()\n", fp->uf_name + 3);
19230 else
19231 fprintf(fd, "FUNCTION %s()\n", fp->uf_name);
19232 if (fp->uf_tm_count == 1)
19233 fprintf(fd, "Called 1 time\n");
19234 else
19235 fprintf(fd, "Called %d times\n", fp->uf_tm_count);
19236 fprintf(fd, "Total time: %s\n", profile_msg(&fp->uf_tm_total));
19237 fprintf(fd, " Self time: %s\n", profile_msg(&fp->uf_tm_self));
19238 fprintf(fd, "\n");
19239 fprintf(fd, "count total (s) self (s)\n");
19241 for (i = 0; i < fp->uf_lines.ga_len; ++i)
19243 if (FUNCLINE(fp, i) == NULL)
19244 continue;
19245 prof_func_line(fd, fp->uf_tml_count[i],
19246 &fp->uf_tml_total[i], &fp->uf_tml_self[i], TRUE);
19247 fprintf(fd, "%s\n", FUNCLINE(fp, i));
19249 fprintf(fd, "\n");
19254 if (sorttab != NULL && st_len > 0)
19256 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
19257 prof_total_cmp);
19258 prof_sort_list(fd, sorttab, st_len, "TOTAL", FALSE);
19259 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
19260 prof_self_cmp);
19261 prof_sort_list(fd, sorttab, st_len, "SELF", TRUE);
19265 static void
19266 prof_sort_list(fd, sorttab, st_len, title, prefer_self)
19267 FILE *fd;
19268 ufunc_T **sorttab;
19269 int st_len;
19270 char *title;
19271 int prefer_self; /* when equal print only self time */
19273 int i;
19274 ufunc_T *fp;
19276 fprintf(fd, "FUNCTIONS SORTED ON %s TIME\n", title);
19277 fprintf(fd, "count total (s) self (s) function\n");
19278 for (i = 0; i < 20 && i < st_len; ++i)
19280 fp = sorttab[i];
19281 prof_func_line(fd, fp->uf_tm_count, &fp->uf_tm_total, &fp->uf_tm_self,
19282 prefer_self);
19283 if (fp->uf_name[0] == K_SPECIAL)
19284 fprintf(fd, " <SNR>%s()\n", fp->uf_name + 3);
19285 else
19286 fprintf(fd, " %s()\n", fp->uf_name);
19288 fprintf(fd, "\n");
19292 * Print the count and times for one function or function line.
19294 static void
19295 prof_func_line(fd, count, total, self, prefer_self)
19296 FILE *fd;
19297 int count;
19298 proftime_T *total;
19299 proftime_T *self;
19300 int prefer_self; /* when equal print only self time */
19302 if (count > 0)
19304 fprintf(fd, "%5d ", count);
19305 if (prefer_self && profile_equal(total, self))
19306 fprintf(fd, " ");
19307 else
19308 fprintf(fd, "%s ", profile_msg(total));
19309 if (!prefer_self && profile_equal(total, self))
19310 fprintf(fd, " ");
19311 else
19312 fprintf(fd, "%s ", profile_msg(self));
19314 else
19315 fprintf(fd, " ");
19319 * Compare function for total time sorting.
19321 static int
19322 #ifdef __BORLANDC__
19323 _RTLENTRYF
19324 #endif
19325 prof_total_cmp(s1, s2)
19326 const void *s1;
19327 const void *s2;
19329 ufunc_T *p1, *p2;
19331 p1 = *(ufunc_T **)s1;
19332 p2 = *(ufunc_T **)s2;
19333 return profile_cmp(&p1->uf_tm_total, &p2->uf_tm_total);
19337 * Compare function for self time sorting.
19339 static int
19340 #ifdef __BORLANDC__
19341 _RTLENTRYF
19342 #endif
19343 prof_self_cmp(s1, s2)
19344 const void *s1;
19345 const void *s2;
19347 ufunc_T *p1, *p2;
19349 p1 = *(ufunc_T **)s1;
19350 p2 = *(ufunc_T **)s2;
19351 return profile_cmp(&p1->uf_tm_self, &p2->uf_tm_self);
19354 #endif
19357 * If "name" has a package name try autoloading the script for it.
19358 * Return TRUE if a package was loaded.
19360 static int
19361 script_autoload(name, reload)
19362 char_u *name;
19363 int reload; /* load script again when already loaded */
19365 char_u *p;
19366 char_u *scriptname, *tofree;
19367 int ret = FALSE;
19368 int i;
19370 /* If there is no '#' after name[0] there is no package name. */
19371 p = vim_strchr(name, AUTOLOAD_CHAR);
19372 if (p == NULL || p == name)
19373 return FALSE;
19375 tofree = scriptname = autoload_name(name);
19377 /* Find the name in the list of previously loaded package names. Skip
19378 * "autoload/", it's always the same. */
19379 for (i = 0; i < ga_loaded.ga_len; ++i)
19380 if (STRCMP(((char_u **)ga_loaded.ga_data)[i] + 9, scriptname + 9) == 0)
19381 break;
19382 if (!reload && i < ga_loaded.ga_len)
19383 ret = FALSE; /* was loaded already */
19384 else
19386 /* Remember the name if it wasn't loaded already. */
19387 if (i == ga_loaded.ga_len && ga_grow(&ga_loaded, 1) == OK)
19389 ((char_u **)ga_loaded.ga_data)[ga_loaded.ga_len++] = scriptname;
19390 tofree = NULL;
19393 /* Try loading the package from $VIMRUNTIME/autoload/<name>.vim */
19394 if (source_runtime(scriptname, FALSE) == OK)
19395 ret = TRUE;
19398 vim_free(tofree);
19399 return ret;
19403 * Return the autoload script name for a function or variable name.
19404 * Returns NULL when out of memory.
19406 static char_u *
19407 autoload_name(name)
19408 char_u *name;
19410 char_u *p;
19411 char_u *scriptname;
19413 /* Get the script file name: replace '#' with '/', append ".vim". */
19414 scriptname = alloc((unsigned)(STRLEN(name) + 14));
19415 if (scriptname == NULL)
19416 return FALSE;
19417 STRCPY(scriptname, "autoload/");
19418 STRCAT(scriptname, name);
19419 *vim_strrchr(scriptname, AUTOLOAD_CHAR) = NUL;
19420 STRCAT(scriptname, ".vim");
19421 while ((p = vim_strchr(scriptname, AUTOLOAD_CHAR)) != NULL)
19422 *p = '/';
19423 return scriptname;
19426 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
19429 * Function given to ExpandGeneric() to obtain the list of user defined
19430 * function names.
19432 char_u *
19433 get_user_func_name(xp, idx)
19434 expand_T *xp;
19435 int idx;
19437 static long_u done;
19438 static hashitem_T *hi;
19439 ufunc_T *fp;
19441 if (idx == 0)
19443 done = 0;
19444 hi = func_hashtab.ht_array;
19446 if (done < func_hashtab.ht_used)
19448 if (done++ > 0)
19449 ++hi;
19450 while (HASHITEM_EMPTY(hi))
19451 ++hi;
19452 fp = HI2UF(hi);
19454 if (STRLEN(fp->uf_name) + 4 >= IOSIZE)
19455 return fp->uf_name; /* prevents overflow */
19457 cat_func_name(IObuff, fp);
19458 if (xp->xp_context != EXPAND_USER_FUNC)
19460 STRCAT(IObuff, "(");
19461 if (!fp->uf_varargs && fp->uf_args.ga_len == 0)
19462 STRCAT(IObuff, ")");
19464 return IObuff;
19466 return NULL;
19469 #endif /* FEAT_CMDL_COMPL */
19472 * Copy the function name of "fp" to buffer "buf".
19473 * "buf" must be able to hold the function name plus three bytes.
19474 * Takes care of script-local function names.
19476 static void
19477 cat_func_name(buf, fp)
19478 char_u *buf;
19479 ufunc_T *fp;
19481 if (fp->uf_name[0] == K_SPECIAL)
19483 STRCPY(buf, "<SNR>");
19484 STRCAT(buf, fp->uf_name + 3);
19486 else
19487 STRCPY(buf, fp->uf_name);
19491 * ":delfunction {name}"
19493 void
19494 ex_delfunction(eap)
19495 exarg_T *eap;
19497 ufunc_T *fp = NULL;
19498 char_u *p;
19499 char_u *name;
19500 funcdict_T fudi;
19502 p = eap->arg;
19503 name = trans_function_name(&p, eap->skip, 0, &fudi);
19504 vim_free(fudi.fd_newkey);
19505 if (name == NULL)
19507 if (fudi.fd_dict != NULL && !eap->skip)
19508 EMSG(_(e_funcref));
19509 return;
19511 if (!ends_excmd(*skipwhite(p)))
19513 vim_free(name);
19514 EMSG(_(e_trailing));
19515 return;
19517 eap->nextcmd = check_nextcmd(p);
19518 if (eap->nextcmd != NULL)
19519 *p = NUL;
19521 if (!eap->skip)
19522 fp = find_func(name);
19523 vim_free(name);
19525 if (!eap->skip)
19527 if (fp == NULL)
19529 EMSG2(_(e_nofunc), eap->arg);
19530 return;
19532 if (fp->uf_calls > 0)
19534 EMSG2(_("E131: Cannot delete function %s: It is in use"), eap->arg);
19535 return;
19538 if (fudi.fd_dict != NULL)
19540 /* Delete the dict item that refers to the function, it will
19541 * invoke func_unref() and possibly delete the function. */
19542 dictitem_remove(fudi.fd_dict, fudi.fd_di);
19544 else
19545 func_free(fp);
19550 * Free a function and remove it from the list of functions.
19552 static void
19553 func_free(fp)
19554 ufunc_T *fp;
19556 hashitem_T *hi;
19558 /* clear this function */
19559 ga_clear_strings(&(fp->uf_args));
19560 ga_clear_strings(&(fp->uf_lines));
19561 #ifdef FEAT_PROFILE
19562 vim_free(fp->uf_tml_count);
19563 vim_free(fp->uf_tml_total);
19564 vim_free(fp->uf_tml_self);
19565 #endif
19567 /* remove the function from the function hashtable */
19568 hi = hash_find(&func_hashtab, UF2HIKEY(fp));
19569 if (HASHITEM_EMPTY(hi))
19570 EMSG2(_(e_intern2), "func_free()");
19571 else
19572 hash_remove(&func_hashtab, hi);
19574 vim_free(fp);
19578 * Unreference a Function: decrement the reference count and free it when it
19579 * becomes zero. Only for numbered functions.
19581 static void
19582 func_unref(name)
19583 char_u *name;
19585 ufunc_T *fp;
19587 if (name != NULL && isdigit(*name))
19589 fp = find_func(name);
19590 if (fp == NULL)
19591 EMSG2(_(e_intern2), "func_unref()");
19592 else if (--fp->uf_refcount <= 0)
19594 /* Only delete it when it's not being used. Otherwise it's done
19595 * when "uf_calls" becomes zero. */
19596 if (fp->uf_calls == 0)
19597 func_free(fp);
19603 * Count a reference to a Function.
19605 static void
19606 func_ref(name)
19607 char_u *name;
19609 ufunc_T *fp;
19611 if (name != NULL && isdigit(*name))
19613 fp = find_func(name);
19614 if (fp == NULL)
19615 EMSG2(_(e_intern2), "func_ref()");
19616 else
19617 ++fp->uf_refcount;
19622 * Call a user function.
19624 static void
19625 call_user_func(fp, argcount, argvars, rettv, firstline, lastline, selfdict)
19626 ufunc_T *fp; /* pointer to function */
19627 int argcount; /* nr of args */
19628 typval_T *argvars; /* arguments */
19629 typval_T *rettv; /* return value */
19630 linenr_T firstline; /* first line of range */
19631 linenr_T lastline; /* last line of range */
19632 dict_T *selfdict; /* Dictionary for "self" */
19634 char_u *save_sourcing_name;
19635 linenr_T save_sourcing_lnum;
19636 scid_T save_current_SID;
19637 funccall_T fc;
19638 int save_did_emsg;
19639 static int depth = 0;
19640 dictitem_T *v;
19641 int fixvar_idx = 0; /* index in fixvar[] */
19642 int i;
19643 int ai;
19644 char_u numbuf[NUMBUFLEN];
19645 char_u *name;
19646 #ifdef FEAT_PROFILE
19647 proftime_T wait_start;
19648 #endif
19650 /* If depth of calling is getting too high, don't execute the function */
19651 if (depth >= p_mfd)
19653 EMSG(_("E132: Function call depth is higher than 'maxfuncdepth'"));
19654 rettv->v_type = VAR_NUMBER;
19655 rettv->vval.v_number = -1;
19656 return;
19658 ++depth;
19660 line_breakcheck(); /* check for CTRL-C hit */
19662 fc.caller = current_funccal;
19663 current_funccal = &fc;
19664 fc.func = fp;
19665 fc.rettv = rettv;
19666 rettv->vval.v_number = 0;
19667 fc.linenr = 0;
19668 fc.returned = FALSE;
19669 fc.level = ex_nesting_level;
19670 /* Check if this function has a breakpoint. */
19671 fc.breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, (linenr_T)0);
19672 fc.dbg_tick = debug_tick;
19675 * Note about using fc.fixvar[]: This is an array of FIXVAR_CNT variables
19676 * with names up to VAR_SHORT_LEN long. This avoids having to alloc/free
19677 * each argument variable and saves a lot of time.
19680 * Init l: variables.
19682 init_var_dict(&fc.l_vars, &fc.l_vars_var);
19683 if (selfdict != NULL)
19685 /* Set l:self to "selfdict". Use "name" to avoid a warning from
19686 * some compiler that checks the destination size. */
19687 v = &fc.fixvar[fixvar_idx++].var;
19688 name = v->di_key;
19689 STRCPY(name, "self");
19690 v->di_flags = DI_FLAGS_RO + DI_FLAGS_FIX;
19691 hash_add(&fc.l_vars.dv_hashtab, DI2HIKEY(v));
19692 v->di_tv.v_type = VAR_DICT;
19693 v->di_tv.v_lock = 0;
19694 v->di_tv.vval.v_dict = selfdict;
19695 ++selfdict->dv_refcount;
19699 * Init a: variables.
19700 * Set a:0 to "argcount".
19701 * Set a:000 to a list with room for the "..." arguments.
19703 init_var_dict(&fc.l_avars, &fc.l_avars_var);
19704 add_nr_var(&fc.l_avars, &fc.fixvar[fixvar_idx++].var, "0",
19705 (varnumber_T)(argcount - fp->uf_args.ga_len));
19706 v = &fc.fixvar[fixvar_idx++].var;
19707 STRCPY(v->di_key, "000");
19708 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
19709 hash_add(&fc.l_avars.dv_hashtab, DI2HIKEY(v));
19710 v->di_tv.v_type = VAR_LIST;
19711 v->di_tv.v_lock = VAR_FIXED;
19712 v->di_tv.vval.v_list = &fc.l_varlist;
19713 vim_memset(&fc.l_varlist, 0, sizeof(list_T));
19714 fc.l_varlist.lv_refcount = 99999;
19715 fc.l_varlist.lv_lock = VAR_FIXED;
19718 * Set a:firstline to "firstline" and a:lastline to "lastline".
19719 * Set a:name to named arguments.
19720 * Set a:N to the "..." arguments.
19722 add_nr_var(&fc.l_avars, &fc.fixvar[fixvar_idx++].var, "firstline",
19723 (varnumber_T)firstline);
19724 add_nr_var(&fc.l_avars, &fc.fixvar[fixvar_idx++].var, "lastline",
19725 (varnumber_T)lastline);
19726 for (i = 0; i < argcount; ++i)
19728 ai = i - fp->uf_args.ga_len;
19729 if (ai < 0)
19730 /* named argument a:name */
19731 name = FUNCARG(fp, i);
19732 else
19734 /* "..." argument a:1, a:2, etc. */
19735 sprintf((char *)numbuf, "%d", ai + 1);
19736 name = numbuf;
19738 if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN)
19740 v = &fc.fixvar[fixvar_idx++].var;
19741 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
19743 else
19745 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
19746 + STRLEN(name)));
19747 if (v == NULL)
19748 break;
19749 v->di_flags = DI_FLAGS_RO;
19751 STRCPY(v->di_key, name);
19752 hash_add(&fc.l_avars.dv_hashtab, DI2HIKEY(v));
19754 /* Note: the values are copied directly to avoid alloc/free.
19755 * "argvars" must have VAR_FIXED for v_lock. */
19756 v->di_tv = argvars[i];
19757 v->di_tv.v_lock = VAR_FIXED;
19759 if (ai >= 0 && ai < MAX_FUNC_ARGS)
19761 list_append(&fc.l_varlist, &fc.l_listitems[ai]);
19762 fc.l_listitems[ai].li_tv = argvars[i];
19763 fc.l_listitems[ai].li_tv.v_lock = VAR_FIXED;
19767 /* Don't redraw while executing the function. */
19768 ++RedrawingDisabled;
19769 save_sourcing_name = sourcing_name;
19770 save_sourcing_lnum = sourcing_lnum;
19771 sourcing_lnum = 1;
19772 sourcing_name = alloc((unsigned)((save_sourcing_name == NULL ? 0
19773 : STRLEN(save_sourcing_name)) + STRLEN(fp->uf_name) + 13));
19774 if (sourcing_name != NULL)
19776 if (save_sourcing_name != NULL
19777 && STRNCMP(save_sourcing_name, "function ", 9) == 0)
19778 sprintf((char *)sourcing_name, "%s..", save_sourcing_name);
19779 else
19780 STRCPY(sourcing_name, "function ");
19781 cat_func_name(sourcing_name + STRLEN(sourcing_name), fp);
19783 if (p_verbose >= 12)
19785 ++no_wait_return;
19786 verbose_enter_scroll();
19788 smsg((char_u *)_("calling %s"), sourcing_name);
19789 if (p_verbose >= 14)
19791 char_u buf[MSG_BUF_LEN];
19792 char_u numbuf2[NUMBUFLEN];
19793 char_u *tofree;
19795 msg_puts((char_u *)"(");
19796 for (i = 0; i < argcount; ++i)
19798 if (i > 0)
19799 msg_puts((char_u *)", ");
19800 if (argvars[i].v_type == VAR_NUMBER)
19801 msg_outnum((long)argvars[i].vval.v_number);
19802 else
19804 trunc_string(tv2string(&argvars[i], &tofree,
19805 numbuf2, 0), buf, MSG_BUF_CLEN);
19806 msg_puts(buf);
19807 vim_free(tofree);
19810 msg_puts((char_u *)")");
19812 msg_puts((char_u *)"\n"); /* don't overwrite this either */
19814 verbose_leave_scroll();
19815 --no_wait_return;
19818 #ifdef FEAT_PROFILE
19819 if (do_profiling == PROF_YES)
19821 if (!fp->uf_profiling && has_profiling(FALSE, fp->uf_name, NULL))
19822 func_do_profile(fp);
19823 if (fp->uf_profiling
19824 || (fc.caller != NULL && &fc.caller->func->uf_profiling))
19826 ++fp->uf_tm_count;
19827 profile_start(&fp->uf_tm_start);
19828 profile_zero(&fp->uf_tm_children);
19830 script_prof_save(&wait_start);
19832 #endif
19834 save_current_SID = current_SID;
19835 current_SID = fp->uf_script_ID;
19836 save_did_emsg = did_emsg;
19837 did_emsg = FALSE;
19839 /* call do_cmdline() to execute the lines */
19840 do_cmdline(NULL, get_func_line, (void *)&fc,
19841 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
19843 --RedrawingDisabled;
19845 /* when the function was aborted because of an error, return -1 */
19846 if ((did_emsg && (fp->uf_flags & FC_ABORT)) || rettv->v_type == VAR_UNKNOWN)
19848 clear_tv(rettv);
19849 rettv->v_type = VAR_NUMBER;
19850 rettv->vval.v_number = -1;
19853 #ifdef FEAT_PROFILE
19854 if (do_profiling == PROF_YES && (fp->uf_profiling
19855 || (fc.caller != NULL && &fc.caller->func->uf_profiling)))
19857 profile_end(&fp->uf_tm_start);
19858 profile_sub_wait(&wait_start, &fp->uf_tm_start);
19859 profile_add(&fp->uf_tm_total, &fp->uf_tm_start);
19860 profile_self(&fp->uf_tm_self, &fp->uf_tm_start, &fp->uf_tm_children);
19861 if (fc.caller != NULL && &fc.caller->func->uf_profiling)
19863 profile_add(&fc.caller->func->uf_tm_children, &fp->uf_tm_start);
19864 profile_add(&fc.caller->func->uf_tml_children, &fp->uf_tm_start);
19867 #endif
19869 /* when being verbose, mention the return value */
19870 if (p_verbose >= 12)
19872 ++no_wait_return;
19873 verbose_enter_scroll();
19875 if (aborting())
19876 smsg((char_u *)_("%s aborted"), sourcing_name);
19877 else if (fc.rettv->v_type == VAR_NUMBER)
19878 smsg((char_u *)_("%s returning #%ld"), sourcing_name,
19879 (long)fc.rettv->vval.v_number);
19880 else
19882 char_u buf[MSG_BUF_LEN];
19883 char_u numbuf2[NUMBUFLEN];
19884 char_u *tofree;
19886 /* The value may be very long. Skip the middle part, so that we
19887 * have some idea how it starts and ends. smsg() would always
19888 * truncate it at the end. */
19889 trunc_string(tv2string(fc.rettv, &tofree, numbuf2, 0),
19890 buf, MSG_BUF_CLEN);
19891 smsg((char_u *)_("%s returning %s"), sourcing_name, buf);
19892 vim_free(tofree);
19894 msg_puts((char_u *)"\n"); /* don't overwrite this either */
19896 verbose_leave_scroll();
19897 --no_wait_return;
19900 vim_free(sourcing_name);
19901 sourcing_name = save_sourcing_name;
19902 sourcing_lnum = save_sourcing_lnum;
19903 current_SID = save_current_SID;
19904 #ifdef FEAT_PROFILE
19905 if (do_profiling == PROF_YES)
19906 script_prof_restore(&wait_start);
19907 #endif
19909 if (p_verbose >= 12 && sourcing_name != NULL)
19911 ++no_wait_return;
19912 verbose_enter_scroll();
19914 smsg((char_u *)_("continuing in %s"), sourcing_name);
19915 msg_puts((char_u *)"\n"); /* don't overwrite this either */
19917 verbose_leave_scroll();
19918 --no_wait_return;
19921 did_emsg |= save_did_emsg;
19922 current_funccal = fc.caller;
19924 /* The a: variables typevals were not alloced, only free the allocated
19925 * variables. */
19926 vars_clear_ext(&fc.l_avars.dv_hashtab, FALSE);
19928 vars_clear(&fc.l_vars.dv_hashtab); /* free all l: variables */
19929 --depth;
19933 * Add a number variable "name" to dict "dp" with value "nr".
19935 static void
19936 add_nr_var(dp, v, name, nr)
19937 dict_T *dp;
19938 dictitem_T *v;
19939 char *name;
19940 varnumber_T nr;
19942 STRCPY(v->di_key, name);
19943 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
19944 hash_add(&dp->dv_hashtab, DI2HIKEY(v));
19945 v->di_tv.v_type = VAR_NUMBER;
19946 v->di_tv.v_lock = VAR_FIXED;
19947 v->di_tv.vval.v_number = nr;
19951 * ":return [expr]"
19953 void
19954 ex_return(eap)
19955 exarg_T *eap;
19957 char_u *arg = eap->arg;
19958 typval_T rettv;
19959 int returning = FALSE;
19961 if (current_funccal == NULL)
19963 EMSG(_("E133: :return not inside a function"));
19964 return;
19967 if (eap->skip)
19968 ++emsg_skip;
19970 eap->nextcmd = NULL;
19971 if ((*arg != NUL && *arg != '|' && *arg != '\n')
19972 && eval0(arg, &rettv, &eap->nextcmd, !eap->skip) != FAIL)
19974 if (!eap->skip)
19975 returning = do_return(eap, FALSE, TRUE, &rettv);
19976 else
19977 clear_tv(&rettv);
19979 /* It's safer to return also on error. */
19980 else if (!eap->skip)
19983 * Return unless the expression evaluation has been cancelled due to an
19984 * aborting error, an interrupt, or an exception.
19986 if (!aborting())
19987 returning = do_return(eap, FALSE, TRUE, NULL);
19990 /* When skipping or the return gets pending, advance to the next command
19991 * in this line (!returning). Otherwise, ignore the rest of the line.
19992 * Following lines will be ignored by get_func_line(). */
19993 if (returning)
19994 eap->nextcmd = NULL;
19995 else if (eap->nextcmd == NULL) /* no argument */
19996 eap->nextcmd = check_nextcmd(arg);
19998 if (eap->skip)
19999 --emsg_skip;
20003 * Return from a function. Possibly makes the return pending. Also called
20004 * for a pending return at the ":endtry" or after returning from an extra
20005 * do_cmdline(). "reanimate" is used in the latter case. "is_cmd" is set
20006 * when called due to a ":return" command. "rettv" may point to a typval_T
20007 * with the return rettv. Returns TRUE when the return can be carried out,
20008 * FALSE when the return gets pending.
20011 do_return(eap, reanimate, is_cmd, rettv)
20012 exarg_T *eap;
20013 int reanimate;
20014 int is_cmd;
20015 void *rettv;
20017 int idx;
20018 struct condstack *cstack = eap->cstack;
20020 if (reanimate)
20021 /* Undo the return. */
20022 current_funccal->returned = FALSE;
20025 * Cleanup (and inactivate) conditionals, but stop when a try conditional
20026 * not in its finally clause (which then is to be executed next) is found.
20027 * In this case, make the ":return" pending for execution at the ":endtry".
20028 * Otherwise, return normally.
20030 idx = cleanup_conditionals(eap->cstack, 0, TRUE);
20031 if (idx >= 0)
20033 cstack->cs_pending[idx] = CSTP_RETURN;
20035 if (!is_cmd && !reanimate)
20036 /* A pending return again gets pending. "rettv" points to an
20037 * allocated variable with the rettv of the original ":return"'s
20038 * argument if present or is NULL else. */
20039 cstack->cs_rettv[idx] = rettv;
20040 else
20042 /* When undoing a return in order to make it pending, get the stored
20043 * return rettv. */
20044 if (reanimate)
20045 rettv = current_funccal->rettv;
20047 if (rettv != NULL)
20049 /* Store the value of the pending return. */
20050 if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL)
20051 *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv;
20052 else
20053 EMSG(_(e_outofmem));
20055 else
20056 cstack->cs_rettv[idx] = NULL;
20058 if (reanimate)
20060 /* The pending return value could be overwritten by a ":return"
20061 * without argument in a finally clause; reset the default
20062 * return value. */
20063 current_funccal->rettv->v_type = VAR_NUMBER;
20064 current_funccal->rettv->vval.v_number = 0;
20067 report_make_pending(CSTP_RETURN, rettv);
20069 else
20071 current_funccal->returned = TRUE;
20073 /* If the return is carried out now, store the return value. For
20074 * a return immediately after reanimation, the value is already
20075 * there. */
20076 if (!reanimate && rettv != NULL)
20078 clear_tv(current_funccal->rettv);
20079 *current_funccal->rettv = *(typval_T *)rettv;
20080 if (!is_cmd)
20081 vim_free(rettv);
20085 return idx < 0;
20089 * Free the variable with a pending return value.
20091 void
20092 discard_pending_return(rettv)
20093 void *rettv;
20095 free_tv((typval_T *)rettv);
20099 * Generate a return command for producing the value of "rettv". The result
20100 * is an allocated string. Used by report_pending() for verbose messages.
20102 char_u *
20103 get_return_cmd(rettv)
20104 void *rettv;
20106 char_u *s = NULL;
20107 char_u *tofree = NULL;
20108 char_u numbuf[NUMBUFLEN];
20110 if (rettv != NULL)
20111 s = echo_string((typval_T *)rettv, &tofree, numbuf, 0);
20112 if (s == NULL)
20113 s = (char_u *)"";
20115 STRCPY(IObuff, ":return ");
20116 STRNCPY(IObuff + 8, s, IOSIZE - 8);
20117 if (STRLEN(s) + 8 >= IOSIZE)
20118 STRCPY(IObuff + IOSIZE - 4, "...");
20119 vim_free(tofree);
20120 return vim_strsave(IObuff);
20124 * Get next function line.
20125 * Called by do_cmdline() to get the next line.
20126 * Returns allocated string, or NULL for end of function.
20128 /* ARGSUSED */
20129 char_u *
20130 get_func_line(c, cookie, indent)
20131 int c; /* not used */
20132 void *cookie;
20133 int indent; /* not used */
20135 funccall_T *fcp = (funccall_T *)cookie;
20136 ufunc_T *fp = fcp->func;
20137 char_u *retval;
20138 garray_T *gap; /* growarray with function lines */
20140 /* If breakpoints have been added/deleted need to check for it. */
20141 if (fcp->dbg_tick != debug_tick)
20143 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
20144 sourcing_lnum);
20145 fcp->dbg_tick = debug_tick;
20147 #ifdef FEAT_PROFILE
20148 if (do_profiling == PROF_YES)
20149 func_line_end(cookie);
20150 #endif
20152 gap = &fp->uf_lines;
20153 if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
20154 || fcp->returned)
20155 retval = NULL;
20156 else
20158 /* Skip NULL lines (continuation lines). */
20159 while (fcp->linenr < gap->ga_len
20160 && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL)
20161 ++fcp->linenr;
20162 if (fcp->linenr >= gap->ga_len)
20163 retval = NULL;
20164 else
20166 retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]);
20167 sourcing_lnum = fcp->linenr;
20168 #ifdef FEAT_PROFILE
20169 if (do_profiling == PROF_YES)
20170 func_line_start(cookie);
20171 #endif
20175 /* Did we encounter a breakpoint? */
20176 if (fcp->breakpoint != 0 && fcp->breakpoint <= sourcing_lnum)
20178 dbg_breakpoint(fp->uf_name, sourcing_lnum);
20179 /* Find next breakpoint. */
20180 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
20181 sourcing_lnum);
20182 fcp->dbg_tick = debug_tick;
20185 return retval;
20188 #if defined(FEAT_PROFILE) || defined(PROTO)
20190 * Called when starting to read a function line.
20191 * "sourcing_lnum" must be correct!
20192 * When skipping lines it may not actually be executed, but we won't find out
20193 * until later and we need to store the time now.
20195 void
20196 func_line_start(cookie)
20197 void *cookie;
20199 funccall_T *fcp = (funccall_T *)cookie;
20200 ufunc_T *fp = fcp->func;
20202 if (fp->uf_profiling && sourcing_lnum >= 1
20203 && sourcing_lnum <= fp->uf_lines.ga_len)
20205 fp->uf_tml_idx = sourcing_lnum - 1;
20206 /* Skip continuation lines. */
20207 while (fp->uf_tml_idx > 0 && FUNCLINE(fp, fp->uf_tml_idx) == NULL)
20208 --fp->uf_tml_idx;
20209 fp->uf_tml_execed = FALSE;
20210 profile_start(&fp->uf_tml_start);
20211 profile_zero(&fp->uf_tml_children);
20212 profile_get_wait(&fp->uf_tml_wait);
20217 * Called when actually executing a function line.
20219 void
20220 func_line_exec(cookie)
20221 void *cookie;
20223 funccall_T *fcp = (funccall_T *)cookie;
20224 ufunc_T *fp = fcp->func;
20226 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
20227 fp->uf_tml_execed = TRUE;
20231 * Called when done with a function line.
20233 void
20234 func_line_end(cookie)
20235 void *cookie;
20237 funccall_T *fcp = (funccall_T *)cookie;
20238 ufunc_T *fp = fcp->func;
20240 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
20242 if (fp->uf_tml_execed)
20244 ++fp->uf_tml_count[fp->uf_tml_idx];
20245 profile_end(&fp->uf_tml_start);
20246 profile_sub_wait(&fp->uf_tml_wait, &fp->uf_tml_start);
20247 profile_add(&fp->uf_tml_total[fp->uf_tml_idx], &fp->uf_tml_start);
20248 profile_self(&fp->uf_tml_self[fp->uf_tml_idx], &fp->uf_tml_start,
20249 &fp->uf_tml_children);
20251 fp->uf_tml_idx = -1;
20254 #endif
20257 * Return TRUE if the currently active function should be ended, because a
20258 * return was encountered or an error occured. Used inside a ":while".
20261 func_has_ended(cookie)
20262 void *cookie;
20264 funccall_T *fcp = (funccall_T *)cookie;
20266 /* Ignore the "abort" flag if the abortion behavior has been changed due to
20267 * an error inside a try conditional. */
20268 return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
20269 || fcp->returned);
20273 * return TRUE if cookie indicates a function which "abort"s on errors.
20276 func_has_abort(cookie)
20277 void *cookie;
20279 return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT;
20282 #if defined(FEAT_VIMINFO) || defined(FEAT_SESSION)
20283 typedef enum
20285 VAR_FLAVOUR_DEFAULT,
20286 VAR_FLAVOUR_SESSION,
20287 VAR_FLAVOUR_VIMINFO
20288 } var_flavour_T;
20290 static var_flavour_T var_flavour __ARGS((char_u *varname));
20292 static var_flavour_T
20293 var_flavour(varname)
20294 char_u *varname;
20296 char_u *p = varname;
20298 if (ASCII_ISUPPER(*p))
20300 while (*(++p))
20301 if (ASCII_ISLOWER(*p))
20302 return VAR_FLAVOUR_SESSION;
20303 return VAR_FLAVOUR_VIMINFO;
20305 else
20306 return VAR_FLAVOUR_DEFAULT;
20308 #endif
20310 #if defined(FEAT_VIMINFO) || defined(PROTO)
20312 * Restore global vars that start with a capital from the viminfo file
20315 read_viminfo_varlist(virp, writing)
20316 vir_T *virp;
20317 int writing;
20319 char_u *tab;
20320 int is_string = FALSE;
20321 typval_T tv;
20323 if (!writing && (find_viminfo_parameter('!') != NULL))
20325 tab = vim_strchr(virp->vir_line + 1, '\t');
20326 if (tab != NULL)
20328 *tab++ = '\0'; /* isolate the variable name */
20329 if (*tab == 'S') /* string var */
20330 is_string = TRUE;
20332 tab = vim_strchr(tab, '\t');
20333 if (tab != NULL)
20335 if (is_string)
20337 tv.v_type = VAR_STRING;
20338 tv.vval.v_string = viminfo_readstring(virp,
20339 (int)(tab - virp->vir_line + 1), TRUE);
20341 else
20343 tv.v_type = VAR_NUMBER;
20344 tv.vval.v_number = atol((char *)tab + 1);
20346 set_var(virp->vir_line + 1, &tv, FALSE);
20347 if (is_string)
20348 vim_free(tv.vval.v_string);
20353 return viminfo_readline(virp);
20357 * Write global vars that start with a capital to the viminfo file
20359 void
20360 write_viminfo_varlist(fp)
20361 FILE *fp;
20363 hashitem_T *hi;
20364 dictitem_T *this_var;
20365 int todo;
20366 char *s;
20367 char_u *p;
20368 char_u *tofree;
20369 char_u numbuf[NUMBUFLEN];
20371 if (find_viminfo_parameter('!') == NULL)
20372 return;
20374 fprintf(fp, _("\n# global variables:\n"));
20376 todo = (int)globvarht.ht_used;
20377 for (hi = globvarht.ht_array; todo > 0; ++hi)
20379 if (!HASHITEM_EMPTY(hi))
20381 --todo;
20382 this_var = HI2DI(hi);
20383 if (var_flavour(this_var->di_key) == VAR_FLAVOUR_VIMINFO)
20385 switch (this_var->di_tv.v_type)
20387 case VAR_STRING: s = "STR"; break;
20388 case VAR_NUMBER: s = "NUM"; break;
20389 default: continue;
20391 fprintf(fp, "!%s\t%s\t", this_var->di_key, s);
20392 p = echo_string(&this_var->di_tv, &tofree, numbuf, 0);
20393 if (p != NULL)
20394 viminfo_writestring(fp, p);
20395 vim_free(tofree);
20400 #endif
20402 #if defined(FEAT_SESSION) || defined(PROTO)
20404 store_session_globals(fd)
20405 FILE *fd;
20407 hashitem_T *hi;
20408 dictitem_T *this_var;
20409 int todo;
20410 char_u *p, *t;
20412 todo = (int)globvarht.ht_used;
20413 for (hi = globvarht.ht_array; todo > 0; ++hi)
20415 if (!HASHITEM_EMPTY(hi))
20417 --todo;
20418 this_var = HI2DI(hi);
20419 if ((this_var->di_tv.v_type == VAR_NUMBER
20420 || this_var->di_tv.v_type == VAR_STRING)
20421 && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
20423 /* Escape special characters with a backslash. Turn a LF and
20424 * CR into \n and \r. */
20425 p = vim_strsave_escaped(get_tv_string(&this_var->di_tv),
20426 (char_u *)"\\\"\n\r");
20427 if (p == NULL) /* out of memory */
20428 break;
20429 for (t = p; *t != NUL; ++t)
20430 if (*t == '\n')
20431 *t = 'n';
20432 else if (*t == '\r')
20433 *t = 'r';
20434 if ((fprintf(fd, "let %s = %c%s%c",
20435 this_var->di_key,
20436 (this_var->di_tv.v_type == VAR_STRING) ? '"'
20437 : ' ',
20439 (this_var->di_tv.v_type == VAR_STRING) ? '"'
20440 : ' ') < 0)
20441 || put_eol(fd) == FAIL)
20443 vim_free(p);
20444 return FAIL;
20446 vim_free(p);
20450 return OK;
20452 #endif
20455 * Display script name where an item was last set.
20456 * Should only be invoked when 'verbose' is non-zero.
20458 void
20459 last_set_msg(scriptID)
20460 scid_T scriptID;
20462 char_u *p;
20464 if (scriptID != 0)
20466 p = home_replace_save(NULL, get_scriptname(scriptID));
20467 if (p != NULL)
20469 verbose_enter();
20470 MSG_PUTS(_("\n\tLast set from "));
20471 MSG_PUTS(p);
20472 vim_free(p);
20473 verbose_leave();
20478 #endif /* FEAT_EVAL */
20480 #if defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) || defined(PROTO)
20483 #ifdef WIN3264
20485 * Functions for ":8" filename modifier: get 8.3 version of a filename.
20487 static int get_short_pathname __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
20488 static int shortpath_for_invalid_fname __ARGS((char_u **fname, char_u **bufp, int *fnamelen));
20489 static int shortpath_for_partial __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
20492 * Get the short pathname of a file.
20493 * Returns 1 on success. *fnamelen is 0 for nonexistant path.
20495 static int
20496 get_short_pathname(fnamep, bufp, fnamelen)
20497 char_u **fnamep;
20498 char_u **bufp;
20499 int *fnamelen;
20501 int l,len;
20502 char_u *newbuf;
20504 len = *fnamelen;
20506 l = GetShortPathName(*fnamep, *fnamep, len);
20507 if (l > len - 1)
20509 /* If that doesn't work (not enough space), then save the string
20510 * and try again with a new buffer big enough
20512 newbuf = vim_strnsave(*fnamep, l);
20513 if (newbuf == NULL)
20514 return 0;
20516 vim_free(*bufp);
20517 *fnamep = *bufp = newbuf;
20519 l = GetShortPathName(*fnamep,*fnamep,l+1);
20521 /* Really should always succeed, as the buffer is big enough */
20524 *fnamelen = l;
20525 return 1;
20529 * Create a short path name. Returns the length of the buffer it needs.
20530 * Doesn't copy over the end of the buffer passed in.
20532 static int
20533 shortpath_for_invalid_fname(fname, bufp, fnamelen)
20534 char_u **fname;
20535 char_u **bufp;
20536 int *fnamelen;
20538 char_u *s, *p, *pbuf2, *pbuf3;
20539 char_u ch;
20540 int len, len2, plen, slen;
20542 /* Make a copy */
20543 len2 = *fnamelen;
20544 pbuf2 = vim_strnsave(*fname, len2);
20545 pbuf3 = NULL;
20547 s = pbuf2 + len2 - 1; /* Find the end */
20548 slen = 1;
20549 plen = len2;
20551 if (after_pathsep(pbuf2, s + 1))
20553 --s;
20554 ++slen;
20555 --plen;
20560 /* Go back one path-seperator */
20561 while (s > pbuf2 && !after_pathsep(pbuf2, s + 1))
20563 --s;
20564 ++slen;
20565 --plen;
20567 if (s <= pbuf2)
20568 break;
20570 /* Remeber the character that is about to be blatted */
20571 ch = *s;
20572 *s = 0; /* get_short_pathname requires a null-terminated string */
20574 /* Try it in situ */
20575 p = pbuf2;
20576 if (!get_short_pathname(&p, &pbuf3, &plen))
20578 vim_free(pbuf2);
20579 return -1;
20581 *s = ch; /* Preserve the string */
20582 } while (plen == 0);
20584 if (plen > 0)
20586 /* Remeber the length of the new string. */
20587 *fnamelen = len = plen + slen;
20588 vim_free(*bufp);
20589 if (len > len2)
20591 /* If there's not enough space in the currently allocated string,
20592 * then copy it to a buffer big enough.
20594 *fname= *bufp = vim_strnsave(p, len);
20595 if (*fname == NULL)
20596 return -1;
20598 else
20600 /* Transfer pbuf2 to being the main buffer (it's big enough) */
20601 *fname = *bufp = pbuf2;
20602 if (p != pbuf2)
20603 strncpy(*fname, p, plen);
20604 pbuf2 = NULL;
20606 /* Concat the next bit */
20607 strncpy(*fname + plen, s, slen);
20608 (*fname)[len] = '\0';
20610 vim_free(pbuf3);
20611 vim_free(pbuf2);
20612 return 0;
20616 * Get a pathname for a partial path.
20618 static int
20619 shortpath_for_partial(fnamep, bufp, fnamelen)
20620 char_u **fnamep;
20621 char_u **bufp;
20622 int *fnamelen;
20624 int sepcount, len, tflen;
20625 char_u *p;
20626 char_u *pbuf, *tfname;
20627 int hasTilde;
20629 /* Count up the path seperators from the RHS.. so we know which part
20630 * of the path to return.
20632 sepcount = 0;
20633 for (p = *fnamep; p < *fnamep + *fnamelen; mb_ptr_adv(p))
20634 if (vim_ispathsep(*p))
20635 ++sepcount;
20637 /* Need full path first (use expand_env() to remove a "~/") */
20638 hasTilde = (**fnamep == '~');
20639 if (hasTilde)
20640 pbuf = tfname = expand_env_save(*fnamep);
20641 else
20642 pbuf = tfname = FullName_save(*fnamep, FALSE);
20644 len = tflen = (int)STRLEN(tfname);
20646 if (!get_short_pathname(&tfname, &pbuf, &len))
20647 return -1;
20649 if (len == 0)
20651 /* Don't have a valid filename, so shorten the rest of the
20652 * path if we can. This CAN give us invalid 8.3 filenames, but
20653 * there's not a lot of point in guessing what it might be.
20655 len = tflen;
20656 if (shortpath_for_invalid_fname(&tfname, &pbuf, &len) == -1)
20657 return -1;
20660 /* Count the paths backward to find the beginning of the desired string. */
20661 for (p = tfname + len - 1; p >= tfname; --p)
20663 #ifdef FEAT_MBYTE
20664 if (has_mbyte)
20665 p -= mb_head_off(tfname, p);
20666 #endif
20667 if (vim_ispathsep(*p))
20669 if (sepcount == 0 || (hasTilde && sepcount == 1))
20670 break;
20671 else
20672 sepcount --;
20675 if (hasTilde)
20677 --p;
20678 if (p >= tfname)
20679 *p = '~';
20680 else
20681 return -1;
20683 else
20684 ++p;
20686 /* Copy in the string - p indexes into tfname - allocated at pbuf */
20687 vim_free(*bufp);
20688 *fnamelen = (int)STRLEN(p);
20689 *bufp = pbuf;
20690 *fnamep = p;
20692 return 0;
20694 #endif /* WIN3264 */
20697 * Adjust a filename, according to a string of modifiers.
20698 * *fnamep must be NUL terminated when called. When returning, the length is
20699 * determined by *fnamelen.
20700 * Returns valid flags.
20701 * When there is an error, *fnamep is set to NULL.
20704 modify_fname(src, usedlen, fnamep, bufp, fnamelen)
20705 char_u *src; /* string with modifiers */
20706 int *usedlen; /* characters after src that are used */
20707 char_u **fnamep; /* file name so far */
20708 char_u **bufp; /* buffer for allocated file name or NULL */
20709 int *fnamelen; /* length of fnamep */
20711 int valid = 0;
20712 char_u *tail;
20713 char_u *s, *p, *pbuf;
20714 char_u dirname[MAXPATHL];
20715 int c;
20716 int has_fullname = 0;
20717 #ifdef WIN3264
20718 int has_shortname = 0;
20719 #endif
20721 repeat:
20722 /* ":p" - full path/file_name */
20723 if (src[*usedlen] == ':' && src[*usedlen + 1] == 'p')
20725 has_fullname = 1;
20727 valid |= VALID_PATH;
20728 *usedlen += 2;
20730 /* Expand "~/path" for all systems and "~user/path" for Unix and VMS */
20731 if ((*fnamep)[0] == '~'
20732 #if !defined(UNIX) && !(defined(VMS) && defined(USER_HOME))
20733 && ((*fnamep)[1] == '/'
20734 # ifdef BACKSLASH_IN_FILENAME
20735 || (*fnamep)[1] == '\\'
20736 # endif
20737 || (*fnamep)[1] == NUL)
20739 #endif
20742 *fnamep = expand_env_save(*fnamep);
20743 vim_free(*bufp); /* free any allocated file name */
20744 *bufp = *fnamep;
20745 if (*fnamep == NULL)
20746 return -1;
20749 /* When "/." or "/.." is used: force expansion to get rid of it. */
20750 for (p = *fnamep; *p != NUL; mb_ptr_adv(p))
20752 if (vim_ispathsep(*p)
20753 && p[1] == '.'
20754 && (p[2] == NUL
20755 || vim_ispathsep(p[2])
20756 || (p[2] == '.'
20757 && (p[3] == NUL || vim_ispathsep(p[3])))))
20758 break;
20761 /* FullName_save() is slow, don't use it when not needed. */
20762 if (*p != NUL || !vim_isAbsName(*fnamep))
20764 *fnamep = FullName_save(*fnamep, *p != NUL);
20765 vim_free(*bufp); /* free any allocated file name */
20766 *bufp = *fnamep;
20767 if (*fnamep == NULL)
20768 return -1;
20771 /* Append a path separator to a directory. */
20772 if (mch_isdir(*fnamep))
20774 /* Make room for one or two extra characters. */
20775 *fnamep = vim_strnsave(*fnamep, (int)STRLEN(*fnamep) + 2);
20776 vim_free(*bufp); /* free any allocated file name */
20777 *bufp = *fnamep;
20778 if (*fnamep == NULL)
20779 return -1;
20780 add_pathsep(*fnamep);
20784 /* ":." - path relative to the current directory */
20785 /* ":~" - path relative to the home directory */
20786 /* ":8" - shortname path - postponed till after */
20787 while (src[*usedlen] == ':'
20788 && ((c = src[*usedlen + 1]) == '.' || c == '~' || c == '8'))
20790 *usedlen += 2;
20791 if (c == '8')
20793 #ifdef WIN3264
20794 has_shortname = 1; /* Postpone this. */
20795 #endif
20796 continue;
20798 pbuf = NULL;
20799 /* Need full path first (use expand_env() to remove a "~/") */
20800 if (!has_fullname)
20802 if (c == '.' && **fnamep == '~')
20803 p = pbuf = expand_env_save(*fnamep);
20804 else
20805 p = pbuf = FullName_save(*fnamep, FALSE);
20807 else
20808 p = *fnamep;
20810 has_fullname = 0;
20812 if (p != NULL)
20814 if (c == '.')
20816 mch_dirname(dirname, MAXPATHL);
20817 s = shorten_fname(p, dirname);
20818 if (s != NULL)
20820 *fnamep = s;
20821 if (pbuf != NULL)
20823 vim_free(*bufp); /* free any allocated file name */
20824 *bufp = pbuf;
20825 pbuf = NULL;
20829 else
20831 home_replace(NULL, p, dirname, MAXPATHL, TRUE);
20832 /* Only replace it when it starts with '~' */
20833 if (*dirname == '~')
20835 s = vim_strsave(dirname);
20836 if (s != NULL)
20838 *fnamep = s;
20839 vim_free(*bufp);
20840 *bufp = s;
20844 vim_free(pbuf);
20848 tail = gettail(*fnamep);
20849 *fnamelen = (int)STRLEN(*fnamep);
20851 /* ":h" - head, remove "/file_name", can be repeated */
20852 /* Don't remove the first "/" or "c:\" */
20853 while (src[*usedlen] == ':' && src[*usedlen + 1] == 'h')
20855 valid |= VALID_HEAD;
20856 *usedlen += 2;
20857 s = get_past_head(*fnamep);
20858 while (tail > s && after_pathsep(s, tail))
20859 --tail;
20860 *fnamelen = (int)(tail - *fnamep);
20861 #ifdef VMS
20862 if (*fnamelen > 0)
20863 *fnamelen += 1; /* the path separator is part of the path */
20864 #endif
20865 while (tail > s && !after_pathsep(s, tail))
20866 mb_ptr_back(*fnamep, tail);
20869 /* ":8" - shortname */
20870 if (src[*usedlen] == ':' && src[*usedlen + 1] == '8')
20872 *usedlen += 2;
20873 #ifdef WIN3264
20874 has_shortname = 1;
20875 #endif
20878 #ifdef WIN3264
20879 /* Check shortname after we have done 'heads' and before we do 'tails'
20881 if (has_shortname)
20883 pbuf = NULL;
20884 /* Copy the string if it is shortened by :h */
20885 if (*fnamelen < (int)STRLEN(*fnamep))
20887 p = vim_strnsave(*fnamep, *fnamelen);
20888 if (p == 0)
20889 return -1;
20890 vim_free(*bufp);
20891 *bufp = *fnamep = p;
20894 /* Split into two implementations - makes it easier. First is where
20895 * there isn't a full name already, second is where there is.
20897 if (!has_fullname && !vim_isAbsName(*fnamep))
20899 if (shortpath_for_partial(fnamep, bufp, fnamelen) == -1)
20900 return -1;
20902 else
20904 int l;
20906 /* Simple case, already have the full-name
20907 * Nearly always shorter, so try first time. */
20908 l = *fnamelen;
20909 if (!get_short_pathname(fnamep, bufp, &l))
20910 return -1;
20912 if (l == 0)
20914 /* Couldn't find the filename.. search the paths.
20916 l = *fnamelen;
20917 if (shortpath_for_invalid_fname(fnamep, bufp, &l ) == -1)
20918 return -1;
20920 *fnamelen = l;
20923 #endif /* WIN3264 */
20925 /* ":t" - tail, just the basename */
20926 if (src[*usedlen] == ':' && src[*usedlen + 1] == 't')
20928 *usedlen += 2;
20929 *fnamelen -= (int)(tail - *fnamep);
20930 *fnamep = tail;
20933 /* ":e" - extension, can be repeated */
20934 /* ":r" - root, without extension, can be repeated */
20935 while (src[*usedlen] == ':'
20936 && (src[*usedlen + 1] == 'e' || src[*usedlen + 1] == 'r'))
20938 /* find a '.' in the tail:
20939 * - for second :e: before the current fname
20940 * - otherwise: The last '.'
20942 if (src[*usedlen + 1] == 'e' && *fnamep > tail)
20943 s = *fnamep - 2;
20944 else
20945 s = *fnamep + *fnamelen - 1;
20946 for ( ; s > tail; --s)
20947 if (s[0] == '.')
20948 break;
20949 if (src[*usedlen + 1] == 'e') /* :e */
20951 if (s > tail)
20953 *fnamelen += (int)(*fnamep - (s + 1));
20954 *fnamep = s + 1;
20955 #ifdef VMS
20956 /* cut version from the extension */
20957 s = *fnamep + *fnamelen - 1;
20958 for ( ; s > *fnamep; --s)
20959 if (s[0] == ';')
20960 break;
20961 if (s > *fnamep)
20962 *fnamelen = s - *fnamep;
20963 #endif
20965 else if (*fnamep <= tail)
20966 *fnamelen = 0;
20968 else /* :r */
20970 if (s > tail) /* remove one extension */
20971 *fnamelen = (int)(s - *fnamep);
20973 *usedlen += 2;
20976 /* ":s?pat?foo?" - substitute */
20977 /* ":gs?pat?foo?" - global substitute */
20978 if (src[*usedlen] == ':'
20979 && (src[*usedlen + 1] == 's'
20980 || (src[*usedlen + 1] == 'g' && src[*usedlen + 2] == 's')))
20982 char_u *str;
20983 char_u *pat;
20984 char_u *sub;
20985 int sep;
20986 char_u *flags;
20987 int didit = FALSE;
20989 flags = (char_u *)"";
20990 s = src + *usedlen + 2;
20991 if (src[*usedlen + 1] == 'g')
20993 flags = (char_u *)"g";
20994 ++s;
20997 sep = *s++;
20998 if (sep)
21000 /* find end of pattern */
21001 p = vim_strchr(s, sep);
21002 if (p != NULL)
21004 pat = vim_strnsave(s, (int)(p - s));
21005 if (pat != NULL)
21007 s = p + 1;
21008 /* find end of substitution */
21009 p = vim_strchr(s, sep);
21010 if (p != NULL)
21012 sub = vim_strnsave(s, (int)(p - s));
21013 str = vim_strnsave(*fnamep, *fnamelen);
21014 if (sub != NULL && str != NULL)
21016 *usedlen = (int)(p + 1 - src);
21017 s = do_string_sub(str, pat, sub, flags);
21018 if (s != NULL)
21020 *fnamep = s;
21021 *fnamelen = (int)STRLEN(s);
21022 vim_free(*bufp);
21023 *bufp = s;
21024 didit = TRUE;
21027 vim_free(sub);
21028 vim_free(str);
21030 vim_free(pat);
21033 /* after using ":s", repeat all the modifiers */
21034 if (didit)
21035 goto repeat;
21039 return valid;
21043 * Perform a substitution on "str" with pattern "pat" and substitute "sub".
21044 * "flags" can be "g" to do a global substitute.
21045 * Returns an allocated string, NULL for error.
21047 char_u *
21048 do_string_sub(str, pat, sub, flags)
21049 char_u *str;
21050 char_u *pat;
21051 char_u *sub;
21052 char_u *flags;
21054 int sublen;
21055 regmatch_T regmatch;
21056 int i;
21057 int do_all;
21058 char_u *tail;
21059 garray_T ga;
21060 char_u *ret;
21061 char_u *save_cpo;
21063 /* Make 'cpoptions' empty, so that the 'l' flag doesn't work here */
21064 save_cpo = p_cpo;
21065 p_cpo = (char_u *)"";
21067 ga_init2(&ga, 1, 200);
21069 do_all = (flags[0] == 'g');
21071 regmatch.rm_ic = p_ic;
21072 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
21073 if (regmatch.regprog != NULL)
21075 tail = str;
21076 while (vim_regexec_nl(&regmatch, str, (colnr_T)(tail - str)))
21079 * Get some space for a temporary buffer to do the substitution
21080 * into. It will contain:
21081 * - The text up to where the match is.
21082 * - The substituted text.
21083 * - The text after the match.
21085 sublen = vim_regsub(&regmatch, sub, tail, FALSE, TRUE, FALSE);
21086 if (ga_grow(&ga, (int)(STRLEN(tail) + sublen -
21087 (regmatch.endp[0] - regmatch.startp[0]))) == FAIL)
21089 ga_clear(&ga);
21090 break;
21093 /* copy the text up to where the match is */
21094 i = (int)(regmatch.startp[0] - tail);
21095 mch_memmove((char_u *)ga.ga_data + ga.ga_len, tail, (size_t)i);
21096 /* add the substituted text */
21097 (void)vim_regsub(&regmatch, sub, (char_u *)ga.ga_data
21098 + ga.ga_len + i, TRUE, TRUE, FALSE);
21099 ga.ga_len += i + sublen - 1;
21100 /* avoid getting stuck on a match with an empty string */
21101 if (tail == regmatch.endp[0])
21103 if (*tail == NUL)
21104 break;
21105 *((char_u *)ga.ga_data + ga.ga_len) = *tail++;
21106 ++ga.ga_len;
21108 else
21110 tail = regmatch.endp[0];
21111 if (*tail == NUL)
21112 break;
21114 if (!do_all)
21115 break;
21118 if (ga.ga_data != NULL)
21119 STRCPY((char *)ga.ga_data + ga.ga_len, tail);
21121 vim_free(regmatch.regprog);
21124 ret = vim_strsave(ga.ga_data == NULL ? str : (char_u *)ga.ga_data);
21125 ga_clear(&ga);
21126 p_cpo = save_cpo;
21128 return ret;
21131 #endif /* defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) */