xref: /vim-8.2.3635/src/ex_eval.c (revision cc7ff3fc)
1 /* vi:set ts=8 sts=4 sw=4:
2  *
3  * VIM - Vi IMproved	by Bram Moolenaar
4  *
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  */
9 
10 /*
11  * ex_eval.c: functions for Ex command line for the +eval feature.
12  */
13 
14 #include "vim.h"
15 
16 #if defined(FEAT_EVAL) || defined(PROTO)
17 
18 static void	free_msglist __ARGS((struct msglist *l));
19 static int	throw_exception __ARGS((void *, int, char_u *));
20 static char_u	*get_end_emsg __ARGS((struct condstack *cstack));
21 
22 /*
23  * Exception handling terms:
24  *
25  *	:try		":try" command		\
26  *	    ...		try block		|
27  *	:catch RE	":catch" command	|
28  *	    ...		catch clause		|- try conditional
29  *	:finally	":finally" command	|
30  *	    ...		finally clause		|
31  *	:endtry		":endtry" command	/
32  *
33  * The try conditional may have any number of catch clauses and at most one
34  * finally clause.  A ":throw" command can be inside the try block, a catch
35  * clause, the finally clause, or in a function called or script sourced from
36  * there or even outside the try conditional.  Try conditionals may be nested.
37  */
38 
39 /*
40  * Configuration whether an exception is thrown on error or interrupt.  When
41  * the preprocessor macros below evaluate to FALSE, an error (did_emsg) or
42  * interrupt (got_int) under an active try conditional terminates the script
43  * after the non-active finally clauses of all active try conditionals have been
44  * executed.  Otherwise, errors and/or interrupts are converted into catchable
45  * exceptions (did_throw additionally set), which terminate the script only if
46  * not caught.  For user exceptions, only did_throw is set.  (Note: got_int can
47  * be set asynchronously afterwards by a SIGINT, so did_throw && got_int is not
48  * a reliant test that the exception currently being thrown is an interrupt
49  * exception.  Similarly, did_emsg can be set afterwards on an error in an
50  * (unskipped) conditional command inside an inactive conditional, so did_throw
51  * && did_emsg is not a reliant test that the exception currently being thrown
52  * is an error exception.)  -  The macros can be defined as expressions checking
53  * for a variable that is allowed to be changed during execution of a script.
54  */
55 #if 0
56 /* Expressions used for testing during the development phase. */
57 # define THROW_ON_ERROR		(!eval_to_number("$VIMNOERRTHROW"))
58 # define THROW_ON_INTERRUPT	(!eval_to_number("$VIMNOINTTHROW"))
59 # define THROW_TEST
60 #else
61 /* Values used for the Vim release. */
62 # define THROW_ON_ERROR		TRUE
63 # define THROW_ON_ERROR_TRUE
64 # define THROW_ON_INTERRUPT	TRUE
65 # define THROW_ON_INTERRUPT_TRUE
66 #endif
67 
68 static void	catch_exception __ARGS((except_T *excp));
69 static void	finish_exception __ARGS((except_T *excp));
70 static void	discard_exception __ARGS((except_T *excp, int was_finished));
71 static void	report_pending __ARGS((int action, int pending, void *value));
72 
73 /*
74  * When several errors appear in a row, setting "force_abort" is delayed until
75  * the failing command returned.  "cause_abort" is set to TRUE meanwhile, in
76  * order to indicate that situation.  This is useful when "force_abort" was set
77  * during execution of a function call from an expression: the aborting of the
78  * expression evaluation is done without producing any error messages, but all
79  * error messages on parsing errors during the expression evaluation are given
80  * (even if a try conditional is active).
81  */
82 static int cause_abort = FALSE;
83 
84 /*
85  * Return TRUE when immediately aborting on error, or when an interrupt
86  * occurred or an exception was thrown but not caught.  Use for ":{range}call"
87  * to check whether an aborted function that does not handle a range itself
88  * should be called again for the next line in the range.  Also used for
89  * cancelling expression evaluation after a function call caused an immediate
90  * abort.  Note that the first emsg() call temporarily resets "force_abort"
91  * until the throw point for error messages has been reached.  That is, during
92  * cancellation of an expression evaluation after an aborting function call or
93  * due to a parsing error, aborting() always returns the same value.
94  */
95     int
96 aborting()
97 {
98     return (did_emsg && force_abort) || got_int || did_throw;
99 }
100 
101 /*
102  * The value of "force_abort" is temporarily reset by the first emsg() call
103  * during an expression evaluation, and "cause_abort" is used instead.  It might
104  * be necessary to restore "force_abort" even before the throw point for the
105  * error message has been reached.  update_force_abort() should be called then.
106  */
107     void
108 update_force_abort()
109 {
110     if (cause_abort)
111 	force_abort = TRUE;
112 }
113 
114 /*
115  * Return TRUE if a command with a subcommand resulting in "retcode" should
116  * abort the script processing.  Can be used to suppress an autocommand after
117  * execution of a failing subcommand as long as the error message has not been
118  * displayed and actually caused the abortion.
119  */
120     int
121 should_abort(retcode)
122     int		retcode;
123 {
124     return ((retcode == FAIL && trylevel != 0 && !emsg_silent) || aborting());
125 }
126 
127 /*
128  * Return TRUE if a function with the "abort" flag should not be considered
129  * ended on an error.  This means that parsing commands is continued in order
130  * to find finally clauses to be executed, and that some errors in skipped
131  * commands are still reported.
132  */
133     int
134 aborted_in_try()
135 {
136     /* This function is only called after an error.  In this case, "force_abort"
137      * determines whether searching for finally clauses is necessary. */
138     return force_abort;
139 }
140 
141 /*
142  * cause_errthrow(): Cause a throw of an error exception if appropriate.
143  * Return TRUE if the error message should not be displayed by emsg().
144  * Sets "ignore", if the emsg() call should be ignored completely.
145  *
146  * When several messages appear in the same command, the first is usually the
147  * most specific one and used as the exception value.  The "severe" flag can be
148  * set to TRUE, if a later but severer message should be used instead.
149  */
150     int
151 cause_errthrow(mesg, severe, ignore)
152     char_u	*mesg;
153     int		severe;
154     int		*ignore;
155 {
156     struct msglist *elem;
157     struct msglist **plist;
158 
159     /*
160      * Do nothing when displaying the interrupt message or reporting an
161      * uncaught exception (which has already been discarded then) at the top
162      * level.  Also when no exception can be thrown.  The message will be
163      * displayed by emsg().
164      */
165     if (suppress_errthrow)
166 	return FALSE;
167 
168     /*
169      * If emsg() has not been called previously, temporarily reset
170      * "force_abort" until the throw point for error messages has been
171      * reached.  This ensures that aborting() returns the same value for all
172      * errors that appear in the same command.  This means particularly that
173      * for parsing errors during expression evaluation emsg() will be called
174      * multiply, even when the expression is evaluated from a finally clause
175      * that was activated due to an aborting error, interrupt, or exception.
176      */
177     if (!did_emsg)
178     {
179 	cause_abort = force_abort;
180 	force_abort = FALSE;
181     }
182 
183     /*
184      * If no try conditional is active and no exception is being thrown and
185      * there has not been an error in a try conditional or a throw so far, do
186      * nothing (for compatibility of non-EH scripts).  The message will then
187      * be displayed by emsg().  When ":silent!" was used and we are not
188      * currently throwing an exception, do nothing.  The message text will
189      * then be stored to v:errmsg by emsg() without displaying it.
190      */
191     if (((trylevel == 0 && !cause_abort) || emsg_silent) && !did_throw)
192 	return FALSE;
193 
194     /*
195      * Ignore an interrupt message when inside a try conditional or when an
196      * exception is being thrown or when an error in a try conditional or
197      * throw has been detected previously.  This is important in order that an
198      * interrupt exception is catchable by the innermost try conditional and
199      * not replaced by an interrupt message error exception.
200      */
201     if (mesg == (char_u *)_(e_interr))
202     {
203 	*ignore = TRUE;
204 	return TRUE;
205     }
206 
207     /*
208      * Ensure that all commands in nested function calls and sourced files
209      * are aborted immediately.
210      */
211     cause_abort = TRUE;
212 
213     /*
214      * When an exception is being thrown, some commands (like conditionals) are
215      * not skipped.  Errors in those commands may affect what of the subsequent
216      * commands are regarded part of catch and finally clauses.  Catching the
217      * exception would then cause execution of commands not intended by the
218      * user, who wouldn't even get aware of the problem.  Therefor, discard the
219      * exception currently being thrown to prevent it from being caught.  Just
220      * execute finally clauses and terminate.
221      */
222     if (did_throw)
223     {
224 	/* When discarding an interrupt exception, reset got_int to prevent the
225 	 * same interrupt being converted to an exception again and discarding
226 	 * the error exception we are about to throw here. */
227 	if (current_exception->type == ET_INTERRUPT)
228 	    got_int = FALSE;
229 	discard_current_exception();
230     }
231 
232 #ifdef THROW_TEST
233     if (!THROW_ON_ERROR)
234     {
235 	/*
236 	 * Print error message immediately without searching for a matching
237 	 * catch clause; just finally clauses are executed before the script
238 	 * is terminated.
239 	 */
240 	return FALSE;
241     }
242     else
243 #endif
244     {
245 	/*
246 	 * Prepare the throw of an error exception, so that everything will
247 	 * be aborted (except for executing finally clauses), until the error
248 	 * exception is caught; if still uncaught at the top level, the error
249 	 * message will be displayed and the script processing terminated
250 	 * then.  -  This function has no access to the conditional stack.
251 	 * Thus, the actual throw is made after the failing command has
252 	 * returned.  -  Throw only the first of several errors in a row, except
253 	 * a severe error is following.
254 	 */
255 	if (msg_list != NULL)
256 	{
257 	    plist = msg_list;
258 	    while (*plist != NULL)
259 		plist = &(*plist)->next;
260 
261 	    elem = (struct msglist *)alloc((unsigned)sizeof(struct msglist));
262 	    if (elem == NULL)
263 	    {
264 		suppress_errthrow = TRUE;
265 		EMSG(_(e_outofmem));
266 	    }
267 	    else
268 	    {
269 		elem->msg = vim_strsave(mesg);
270 		if (elem->msg == NULL)
271 		{
272 		    vim_free(elem);
273 		    suppress_errthrow = TRUE;
274 		    EMSG(_(e_outofmem));
275 		}
276 		else
277 		{
278 		    elem->next = NULL;
279 		    elem->throw_msg = NULL;
280 		    *plist = elem;
281 		    if (plist == msg_list || severe)
282 		    {
283 			char_u	    *tmsg;
284 
285 			/* Skip the extra "Vim " prefix for message "E458". */
286 			tmsg = elem->msg;
287 			if (STRNCMP(tmsg, "Vim E", 5) == 0
288 				&& VIM_ISDIGIT(tmsg[5])
289 				&& VIM_ISDIGIT(tmsg[6])
290 				&& VIM_ISDIGIT(tmsg[7])
291 				&& tmsg[8] == ':'
292 				&& tmsg[9] == ' ')
293 			    (*msg_list)->throw_msg = &tmsg[4];
294 			else
295 			    (*msg_list)->throw_msg = tmsg;
296 		    }
297 		}
298 	    }
299 	}
300 	return TRUE;
301     }
302 }
303 
304 /*
305  * Free a "msg_list" and the messages it contains.
306  */
307     static void
308 free_msglist(l)
309     struct msglist  *l;
310 {
311     struct msglist  *messages, *next;
312 
313     messages = l;
314     while (messages != NULL)
315     {
316 	next = messages->next;
317 	vim_free(messages->msg);
318 	vim_free(messages);
319 	messages = next;
320     }
321 }
322 
323 /*
324  * Free global "*msg_list" and the messages it contains, then set "*msg_list"
325  * to NULL.
326  */
327     void
328 free_global_msglist()
329 {
330     free_msglist(*msg_list);
331     *msg_list = NULL;
332 }
333 
334 /*
335  * Throw the message specified in the call to cause_errthrow() above as an
336  * error exception.  If cstack is NULL, postpone the throw until do_cmdline()
337  * has returned (see do_one_cmd()).
338  */
339     void
340 do_errthrow(cstack, cmdname)
341     struct condstack	*cstack;
342     char_u		*cmdname;
343 {
344     /*
345      * Ensure that all commands in nested function calls and sourced files
346      * are aborted immediately.
347      */
348     if (cause_abort)
349     {
350 	cause_abort = FALSE;
351 	force_abort = TRUE;
352     }
353 
354     /* If no exception is to be thrown or the conversion should be done after
355      * returning to a previous invocation of do_one_cmd(), do nothing. */
356     if (msg_list == NULL || *msg_list == NULL)
357 	return;
358 
359     if (throw_exception(*msg_list, ET_ERROR, cmdname) == FAIL)
360 	free_msglist(*msg_list);
361     else
362     {
363 	if (cstack != NULL)
364 	    do_throw(cstack);
365 	else
366 	    need_rethrow = TRUE;
367     }
368     *msg_list = NULL;
369 }
370 
371 /*
372  * do_intthrow(): Replace the current exception by an interrupt or interrupt
373  * exception if appropriate.  Return TRUE if the current exception is discarded,
374  * FALSE otherwise.
375  */
376     int
377 do_intthrow(cstack)
378     struct condstack	*cstack;
379 {
380     /*
381      * If no interrupt occurred or no try conditional is active and no exception
382      * is being thrown, do nothing (for compatibility of non-EH scripts).
383      */
384     if (!got_int || (trylevel == 0 && !did_throw))
385 	return FALSE;
386 
387 #ifdef THROW_TEST	/* avoid warning for condition always true */
388     if (!THROW_ON_INTERRUPT)
389     {
390 	/*
391 	 * The interrupt aborts everything except for executing finally clauses.
392 	 * Discard any user or error or interrupt exception currently being
393 	 * thrown.
394 	 */
395 	if (did_throw)
396 	    discard_current_exception();
397     }
398     else
399 #endif
400     {
401 	/*
402 	 * Throw an interrupt exception, so that everything will be aborted
403 	 * (except for executing finally clauses), until the interrupt exception
404 	 * is caught; if still uncaught at the top level, the script processing
405 	 * will be terminated then.  -  If an interrupt exception is already
406 	 * being thrown, do nothing.
407 	 *
408 	 */
409 	if (did_throw)
410 	{
411 	    if (current_exception->type == ET_INTERRUPT)
412 		return FALSE;
413 
414 	    /* An interrupt exception replaces any user or error exception. */
415 	    discard_current_exception();
416 	}
417 	if (throw_exception("Vim:Interrupt", ET_INTERRUPT, NULL) != FAIL)
418 	    do_throw(cstack);
419     }
420 
421     return TRUE;
422 }
423 
424 /*
425  * Get an exception message that is to be stored in current_exception->value.
426  */
427     char_u *
428 get_exception_string(value, type, cmdname, should_free)
429     void	*value;
430     int		type;
431     char_u	*cmdname;
432     int		*should_free;
433 {
434     char_u	*ret, *mesg;
435     int		cmdlen;
436     char_u	*p, *val;
437 
438     if (type == ET_ERROR)
439     {
440 	*should_free = FALSE;
441 	mesg = ((struct msglist *)value)->throw_msg;
442 	if (cmdname != NULL && *cmdname != NUL)
443 	{
444 	    cmdlen = (int)STRLEN(cmdname);
445 	    ret = vim_strnsave((char_u *)"Vim(",
446 					   4 + cmdlen + 2 + (int)STRLEN(mesg));
447 	    if (ret == NULL)
448 		return ret;
449 	    STRCPY(&ret[4], cmdname);
450 	    STRCPY(&ret[4 + cmdlen], "):");
451 	    val = ret + 4 + cmdlen + 2;
452 	}
453 	else
454 	{
455 	    ret = vim_strnsave((char_u *)"Vim:", 4 + (int)STRLEN(mesg));
456 	    if (ret == NULL)
457 		return ret;
458 	    val = ret + 4;
459 	}
460 
461 	/* msg_add_fname may have been used to prefix the message with a file
462 	 * name in quotes.  In the exception value, put the file name in
463 	 * parentheses and move it to the end. */
464 	for (p = mesg; ; p++)
465 	{
466 	    if (*p == NUL
467 		    || (*p == 'E'
468 			&& VIM_ISDIGIT(p[1])
469 			&& (p[2] == ':'
470 			    || (VIM_ISDIGIT(p[2])
471 				&& (p[3] == ':'
472 				    || (VIM_ISDIGIT(p[3])
473 					&& p[4] == ':'))))))
474 	    {
475 		if (*p == NUL || p == mesg)
476 		    STRCAT(val, mesg);  /* 'E123' missing or at beginning */
477 		else
478 		{
479 		    /* '"filename" E123: message text' */
480 		    if (mesg[0] != '"' || p-2 < &mesg[1] ||
481 			    p[-2] != '"' || p[-1] != ' ')
482 			/* "E123:" is part of the file name. */
483 			continue;
484 
485 		    STRCAT(val, p);
486 		    p[-2] = NUL;
487 		    sprintf((char *)(val + STRLEN(p)), " (%s)", &mesg[1]);
488 		    p[-2] = '"';
489 		}
490 		break;
491 	    }
492 	}
493     }
494     else
495     {
496 	*should_free = FALSE;
497 	ret = (char_u *) value;
498     }
499 
500     return ret;
501 }
502 
503 
504 /*
505  * Throw a new exception.  Return FAIL when out of memory or it was tried to
506  * throw an illegal user exception.  "value" is the exception string for a
507  * user or interrupt exception, or points to a message list in case of an
508  * error exception.
509  */
510     static int
511 throw_exception(value, type, cmdname)
512     void	*value;
513     int		type;
514     char_u	*cmdname;
515 {
516     except_T	*excp;
517     int		should_free;
518 
519     /*
520      * Disallow faking Interrupt or error exceptions as user exceptions.  They
521      * would be treated differently from real interrupt or error exceptions
522      * when no active try block is found, see do_cmdline().
523      */
524     if (type == ET_USER)
525     {
526 	if (STRNCMP((char_u *)value, "Vim", 3) == 0
527 		&& (((char_u *)value)[3] == NUL || ((char_u *)value)[3] == ':'
528 		    || ((char_u *)value)[3] == '('))
529 	{
530 	    EMSG(_("E608: Cannot :throw exceptions with 'Vim' prefix"));
531 	    goto fail;
532 	}
533     }
534 
535     excp = (except_T *)alloc((unsigned)sizeof(except_T));
536     if (excp == NULL)
537 	goto nomem;
538 
539     if (type == ET_ERROR)
540 	/* Store the original message and prefix the exception value with
541 	 * "Vim:" or, if a command name is given, "Vim(cmdname):". */
542 	excp->messages = (struct msglist *)value;
543 
544     excp->value = get_exception_string(value, type, cmdname, &should_free);
545     if (excp->value == NULL && should_free)
546 	goto nomem;
547 
548     excp->type = type;
549     excp->throw_name = vim_strsave(sourcing_name == NULL
550 					      ? (char_u *)"" : sourcing_name);
551     if (excp->throw_name == NULL)
552     {
553 	if (should_free)
554 	    vim_free(excp->value);
555 	goto nomem;
556     }
557     excp->throw_lnum = sourcing_lnum;
558 
559     if (p_verbose >= 13 || debug_break_level > 0)
560     {
561 	int	save_msg_silent = msg_silent;
562 
563 	if (debug_break_level > 0)
564 	    msg_silent = FALSE;		/* display messages */
565 	else
566 	    verbose_enter();
567 	++no_wait_return;
568 	if (debug_break_level > 0 || *p_vfile == NUL)
569 	    msg_scroll = TRUE;	    /* always scroll up, don't overwrite */
570 
571 	smsg((char_u *)_("Exception thrown: %s"), excp->value);
572 	msg_puts((char_u *)"\n");   /* don't overwrite this either */
573 
574 	if (debug_break_level > 0 || *p_vfile == NUL)
575 	    cmdline_row = msg_row;
576 	--no_wait_return;
577 	if (debug_break_level > 0)
578 	    msg_silent = save_msg_silent;
579 	else
580 	    verbose_leave();
581     }
582 
583     current_exception = excp;
584     return OK;
585 
586 nomem:
587     vim_free(excp);
588     suppress_errthrow = TRUE;
589     EMSG(_(e_outofmem));
590 fail:
591     current_exception = NULL;
592     return FAIL;
593 }
594 
595 /*
596  * Discard an exception.  "was_finished" is set when the exception has been
597  * caught and the catch clause has been ended normally.
598  */
599     static void
600 discard_exception(excp, was_finished)
601     except_T		*excp;
602     int			was_finished;
603 {
604     char_u		*saved_IObuff;
605 
606     if (excp == NULL)
607     {
608 	EMSG(_(e_internal));
609 	return;
610     }
611 
612     if (p_verbose >= 13 || debug_break_level > 0)
613     {
614 	int	save_msg_silent = msg_silent;
615 
616 	saved_IObuff = vim_strsave(IObuff);
617 	if (debug_break_level > 0)
618 	    msg_silent = FALSE;		/* display messages */
619 	else
620 	    verbose_enter();
621 	++no_wait_return;
622 	if (debug_break_level > 0 || *p_vfile == NUL)
623 	    msg_scroll = TRUE;	    /* always scroll up, don't overwrite */
624 	smsg(was_finished
625 		    ? (char_u *)_("Exception finished: %s")
626 		    : (char_u *)_("Exception discarded: %s"),
627 		excp->value);
628 	msg_puts((char_u *)"\n");   /* don't overwrite this either */
629 	if (debug_break_level > 0 || *p_vfile == NUL)
630 	    cmdline_row = msg_row;
631 	--no_wait_return;
632 	if (debug_break_level > 0)
633 	    msg_silent = save_msg_silent;
634 	else
635 	    verbose_leave();
636 	STRCPY(IObuff, saved_IObuff);
637 	vim_free(saved_IObuff);
638     }
639     if (excp->type != ET_INTERRUPT)
640 	vim_free(excp->value);
641     if (excp->type == ET_ERROR)
642 	free_msglist(excp->messages);
643     vim_free(excp->throw_name);
644     vim_free(excp);
645 }
646 
647 /*
648  * Discard the exception currently being thrown.
649  */
650     void
651 discard_current_exception()
652 {
653     discard_exception(current_exception, FALSE);
654     current_exception = NULL;
655     did_throw = FALSE;
656     need_rethrow = FALSE;
657 }
658 
659 /*
660  * Put an exception on the caught stack.
661  */
662     static void
663 catch_exception(excp)
664     except_T	*excp;
665 {
666     excp->caught = caught_stack;
667     caught_stack = excp;
668     set_vim_var_string(VV_EXCEPTION, excp->value, -1);
669     if (*excp->throw_name != NUL)
670     {
671 	if (excp->throw_lnum != 0)
672 	    vim_snprintf((char *)IObuff, IOSIZE, _("%s, line %ld"),
673 				    excp->throw_name, (long)excp->throw_lnum);
674 	else
675 	    vim_snprintf((char *)IObuff, IOSIZE, "%s", excp->throw_name);
676 	set_vim_var_string(VV_THROWPOINT, IObuff, -1);
677     }
678     else
679 	/* throw_name not set on an exception from a command that was typed. */
680 	set_vim_var_string(VV_THROWPOINT, NULL, -1);
681 
682     if (p_verbose >= 13 || debug_break_level > 0)
683     {
684 	int	save_msg_silent = msg_silent;
685 
686 	if (debug_break_level > 0)
687 	    msg_silent = FALSE;		/* display messages */
688 	else
689 	    verbose_enter();
690 	++no_wait_return;
691 	if (debug_break_level > 0 || *p_vfile == NUL)
692 	    msg_scroll = TRUE;	    /* always scroll up, don't overwrite */
693 
694 	smsg((char_u *)_("Exception caught: %s"), excp->value);
695 	msg_puts((char_u *)"\n");   /* don't overwrite this either */
696 
697 	if (debug_break_level > 0 || *p_vfile == NUL)
698 	    cmdline_row = msg_row;
699 	--no_wait_return;
700 	if (debug_break_level > 0)
701 	    msg_silent = save_msg_silent;
702 	else
703 	    verbose_leave();
704     }
705 }
706 
707 /*
708  * Remove an exception from the caught stack.
709  */
710     static void
711 finish_exception(excp)
712     except_T	*excp;
713 {
714     if (excp != caught_stack)
715 	EMSG(_(e_internal));
716     caught_stack = caught_stack->caught;
717     if (caught_stack != NULL)
718     {
719 	set_vim_var_string(VV_EXCEPTION, caught_stack->value, -1);
720 	if (*caught_stack->throw_name != NUL)
721 	{
722 	    if (caught_stack->throw_lnum != 0)
723 		vim_snprintf((char *)IObuff, IOSIZE,
724 			_("%s, line %ld"), caught_stack->throw_name,
725 			(long)caught_stack->throw_lnum);
726 	    else
727 		vim_snprintf((char *)IObuff, IOSIZE, "%s",
728 						    caught_stack->throw_name);
729 	    set_vim_var_string(VV_THROWPOINT, IObuff, -1);
730 	}
731 	else
732 	    /* throw_name not set on an exception from a command that was
733 	     * typed. */
734 	    set_vim_var_string(VV_THROWPOINT, NULL, -1);
735     }
736     else
737     {
738 	set_vim_var_string(VV_EXCEPTION, NULL, -1);
739 	set_vim_var_string(VV_THROWPOINT, NULL, -1);
740     }
741 
742     /* Discard the exception, but use the finish message for 'verbose'. */
743     discard_exception(excp, TRUE);
744 }
745 
746 /*
747  * Flags specifying the message displayed by report_pending.
748  */
749 #define RP_MAKE		0
750 #define RP_RESUME	1
751 #define RP_DISCARD	2
752 
753 /*
754  * Report information about something pending in a finally clause if required by
755  * the 'verbose' option or when debugging.  "action" tells whether something is
756  * made pending or something pending is resumed or discarded.  "pending" tells
757  * what is pending.  "value" specifies the return value for a pending ":return"
758  * or the exception value for a pending exception.
759  */
760     static void
761 report_pending(action, pending, value)
762     int		action;
763     int		pending;
764     void	*value;
765 {
766     char_u	*mesg;
767     char	*s;
768     int		save_msg_silent;
769 
770 
771     switch (action)
772     {
773 	case RP_MAKE:
774 	    mesg = (char_u *)_("%s made pending");
775 	    break;
776 	case RP_RESUME:
777 	    mesg = (char_u *)_("%s resumed");
778 	    break;
779 	/* case RP_DISCARD: */
780 	default:
781 	    mesg = (char_u *)_("%s discarded");
782 	    break;
783     }
784 
785     switch (pending)
786     {
787 	case CSTP_NONE:
788 	    return;
789 
790 	case CSTP_CONTINUE:
791 	    s = ":continue";
792 	    break;
793 	case CSTP_BREAK:
794 	    s = ":break";
795 	    break;
796 	case CSTP_FINISH:
797 	    s = ":finish";
798 	    break;
799 	case CSTP_RETURN:
800 	    /* ":return" command producing value, allocated */
801 	    s = (char *)get_return_cmd(value);
802 	    break;
803 
804 	default:
805 	    if (pending & CSTP_THROW)
806 	    {
807 		vim_snprintf((char *)IObuff, IOSIZE,
808 						(char *)mesg, _("Exception"));
809 		mesg = vim_strnsave(IObuff, (int)STRLEN(IObuff) + 4);
810 		STRCAT(mesg, ": %s");
811 		s = (char *)((except_T *)value)->value;
812 	    }
813 	    else if ((pending & CSTP_ERROR) && (pending & CSTP_INTERRUPT))
814 		s = _("Error and interrupt");
815 	    else if (pending & CSTP_ERROR)
816 		s = _("Error");
817 	    else /* if (pending & CSTP_INTERRUPT) */
818 		s = _("Interrupt");
819     }
820 
821     save_msg_silent = msg_silent;
822     if (debug_break_level > 0)
823 	msg_silent = FALSE;	/* display messages */
824     ++no_wait_return;
825     msg_scroll = TRUE;		/* always scroll up, don't overwrite */
826     smsg(mesg, (char_u *)s);
827     msg_puts((char_u *)"\n");   /* don't overwrite this either */
828     cmdline_row = msg_row;
829     --no_wait_return;
830     if (debug_break_level > 0)
831 	msg_silent = save_msg_silent;
832 
833     if (pending == CSTP_RETURN)
834 	vim_free(s);
835     else if (pending & CSTP_THROW)
836 	vim_free(mesg);
837 }
838 
839 /*
840  * If something is made pending in a finally clause, report it if required by
841  * the 'verbose' option or when debugging.
842  */
843     void
844 report_make_pending(pending, value)
845     int		pending;
846     void	*value;
847 {
848     if (p_verbose >= 14 || debug_break_level > 0)
849     {
850 	if (debug_break_level <= 0)
851 	    verbose_enter();
852 	report_pending(RP_MAKE, pending, value);
853 	if (debug_break_level <= 0)
854 	    verbose_leave();
855     }
856 }
857 
858 /*
859  * If something pending in a finally clause is resumed at the ":endtry", report
860  * it if required by the 'verbose' option or when debugging.
861  */
862     void
863 report_resume_pending(pending, value)
864     int		pending;
865     void	*value;
866 {
867     if (p_verbose >= 14 || debug_break_level > 0)
868     {
869 	if (debug_break_level <= 0)
870 	    verbose_enter();
871 	report_pending(RP_RESUME, pending, value);
872 	if (debug_break_level <= 0)
873 	    verbose_leave();
874     }
875 }
876 
877 /*
878  * If something pending in a finally clause is discarded, report it if required
879  * by the 'verbose' option or when debugging.
880  */
881     void
882 report_discard_pending(pending, value)
883     int		pending;
884     void	*value;
885 {
886     if (p_verbose >= 14 || debug_break_level > 0)
887     {
888 	if (debug_break_level <= 0)
889 	    verbose_enter();
890 	report_pending(RP_DISCARD, pending, value);
891 	if (debug_break_level <= 0)
892 	    verbose_leave();
893     }
894 }
895 
896 
897 /*
898  * ":if".
899  */
900     void
901 ex_if(eap)
902     exarg_T	*eap;
903 {
904     int		error;
905     int		skip;
906     int		result;
907     struct condstack	*cstack = eap->cstack;
908 
909     if (cstack->cs_idx == CSTACK_LEN - 1)
910 	eap->errmsg = (char_u *)N_("E579: :if nesting too deep");
911     else
912     {
913 	++cstack->cs_idx;
914 	cstack->cs_flags[cstack->cs_idx] = 0;
915 
916 	/*
917 	 * Don't do something after an error, interrupt, or throw, or when there
918 	 * is a surrounding conditional and it was not active.
919 	 */
920 	skip = did_emsg || got_int || did_throw || (cstack->cs_idx > 0
921 		&& !(cstack->cs_flags[cstack->cs_idx - 1] & CSF_ACTIVE));
922 
923 	result = eval_to_bool(eap->arg, &error, &eap->nextcmd, skip);
924 
925 	if (!skip && !error)
926 	{
927 	    if (result)
928 		cstack->cs_flags[cstack->cs_idx] = CSF_ACTIVE | CSF_TRUE;
929 	}
930 	else
931 	    /* set TRUE, so this conditional will never get active */
932 	    cstack->cs_flags[cstack->cs_idx] = CSF_TRUE;
933     }
934 }
935 
936 /*
937  * ":endif".
938  */
939     void
940 ex_endif(eap)
941     exarg_T	*eap;
942 {
943     did_endif = TRUE;
944     if (eap->cstack->cs_idx < 0
945 	    || (eap->cstack->cs_flags[eap->cstack->cs_idx]
946 					   & (CSF_WHILE | CSF_FOR | CSF_TRY)))
947 	eap->errmsg = (char_u *)N_("E580: :endif without :if");
948     else
949     {
950 	/*
951 	 * When debugging or a breakpoint was encountered, display the debug
952 	 * prompt (if not already done).  This shows the user that an ":endif"
953 	 * is executed when the ":if" or a previous ":elseif" was not TRUE.
954 	 * Handle a ">quit" debug command as if an interrupt had occurred before
955 	 * the ":endif".  That is, throw an interrupt exception if appropriate.
956 	 * Doing this here prevents an exception for a parsing error being
957 	 * discarded by throwing the interrupt exception later on.
958 	 */
959 	if (!(eap->cstack->cs_flags[eap->cstack->cs_idx] & CSF_TRUE)
960 						    && dbg_check_skipped(eap))
961 	    (void)do_intthrow(eap->cstack);
962 
963 	--eap->cstack->cs_idx;
964     }
965 }
966 
967 /*
968  * ":else" and ":elseif".
969  */
970     void
971 ex_else(eap)
972     exarg_T	*eap;
973 {
974     int		error;
975     int		skip;
976     int		result;
977     struct condstack	*cstack = eap->cstack;
978 
979     /*
980      * Don't do something after an error, interrupt, or throw, or when there is
981      * a surrounding conditional and it was not active.
982      */
983     skip = did_emsg || got_int || did_throw || (cstack->cs_idx > 0
984 	    && !(cstack->cs_flags[cstack->cs_idx - 1] & CSF_ACTIVE));
985 
986     if (cstack->cs_idx < 0
987 	    || (cstack->cs_flags[cstack->cs_idx]
988 					   & (CSF_WHILE | CSF_FOR | CSF_TRY)))
989     {
990 	if (eap->cmdidx == CMD_else)
991 	{
992 	    eap->errmsg = (char_u *)N_("E581: :else without :if");
993 	    return;
994 	}
995 	eap->errmsg = (char_u *)N_("E582: :elseif without :if");
996 	skip = TRUE;
997     }
998     else if (cstack->cs_flags[cstack->cs_idx] & CSF_ELSE)
999     {
1000 	if (eap->cmdidx == CMD_else)
1001 	{
1002 	    eap->errmsg = (char_u *)N_("E583: multiple :else");
1003 	    return;
1004 	}
1005 	eap->errmsg = (char_u *)N_("E584: :elseif after :else");
1006 	skip = TRUE;
1007     }
1008 
1009     /* if skipping or the ":if" was TRUE, reset ACTIVE, otherwise set it */
1010     if (skip || cstack->cs_flags[cstack->cs_idx] & CSF_TRUE)
1011     {
1012 	if (eap->errmsg == NULL)
1013 	    cstack->cs_flags[cstack->cs_idx] = CSF_TRUE;
1014 	skip = TRUE;	/* don't evaluate an ":elseif" */
1015     }
1016     else
1017 	cstack->cs_flags[cstack->cs_idx] = CSF_ACTIVE;
1018 
1019     /*
1020      * When debugging or a breakpoint was encountered, display the debug prompt
1021      * (if not already done).  This shows the user that an ":else" or ":elseif"
1022      * is executed when the ":if" or previous ":elseif" was not TRUE.  Handle
1023      * a ">quit" debug command as if an interrupt had occurred before the
1024      * ":else" or ":elseif".  That is, set "skip" and throw an interrupt
1025      * exception if appropriate.  Doing this here prevents that an exception
1026      * for a parsing errors is discarded when throwing the interrupt exception
1027      * later on.
1028      */
1029     if (!skip && dbg_check_skipped(eap) && got_int)
1030     {
1031 	(void)do_intthrow(cstack);
1032 	skip = TRUE;
1033     }
1034 
1035     if (eap->cmdidx == CMD_elseif)
1036     {
1037 	result = eval_to_bool(eap->arg, &error, &eap->nextcmd, skip);
1038 	/* When throwing error exceptions, we want to throw always the first
1039 	 * of several errors in a row.  This is what actually happens when
1040 	 * a conditional error was detected above and there is another failure
1041 	 * when parsing the expression.  Since the skip flag is set in this
1042 	 * case, the parsing error will be ignored by emsg(). */
1043 
1044 	if (!skip && !error)
1045 	{
1046 	    if (result)
1047 		cstack->cs_flags[cstack->cs_idx] = CSF_ACTIVE | CSF_TRUE;
1048 	    else
1049 		cstack->cs_flags[cstack->cs_idx] = 0;
1050 	}
1051 	else if (eap->errmsg == NULL)
1052 	    /* set TRUE, so this conditional will never get active */
1053 	    cstack->cs_flags[cstack->cs_idx] = CSF_TRUE;
1054     }
1055     else
1056 	cstack->cs_flags[cstack->cs_idx] |= CSF_ELSE;
1057 }
1058 
1059 /*
1060  * Handle ":while" and ":for".
1061  */
1062     void
1063 ex_while(eap)
1064     exarg_T	*eap;
1065 {
1066     int		error;
1067     int		skip;
1068     int		result;
1069     struct condstack	*cstack = eap->cstack;
1070 
1071     if (cstack->cs_idx == CSTACK_LEN - 1)
1072 	eap->errmsg = (char_u *)N_("E585: :while/:for nesting too deep");
1073     else
1074     {
1075 	/*
1076 	 * The loop flag is set when we have jumped back from the matching
1077 	 * ":endwhile" or ":endfor".  When not set, need to initialise this
1078 	 * cstack entry.
1079 	 */
1080 	if ((cstack->cs_lflags & CSL_HAD_LOOP) == 0)
1081 	{
1082 	    ++cstack->cs_idx;
1083 	    ++cstack->cs_looplevel;
1084 	    cstack->cs_line[cstack->cs_idx] = -1;
1085 	}
1086 	cstack->cs_flags[cstack->cs_idx] =
1087 			       eap->cmdidx == CMD_while ? CSF_WHILE : CSF_FOR;
1088 
1089 	/*
1090 	 * Don't do something after an error, interrupt, or throw, or when
1091 	 * there is a surrounding conditional and it was not active.
1092 	 */
1093 	skip = did_emsg || got_int || did_throw || (cstack->cs_idx > 0
1094 		&& !(cstack->cs_flags[cstack->cs_idx - 1] & CSF_ACTIVE));
1095 	if (eap->cmdidx == CMD_while)
1096 	{
1097 	    /*
1098 	     * ":while bool-expr"
1099 	     */
1100 	    result = eval_to_bool(eap->arg, &error, &eap->nextcmd, skip);
1101 	}
1102 	else
1103 	{
1104 	    void *fi;
1105 
1106 	    /*
1107 	     * ":for var in list-expr"
1108 	     */
1109 	    if ((cstack->cs_lflags & CSL_HAD_LOOP) != 0)
1110 	    {
1111 		/* Jumping here from a ":continue" or ":endfor": use the
1112 		 * previously evaluated list. */
1113 		fi = cstack->cs_forinfo[cstack->cs_idx];
1114 		error = FALSE;
1115 	    }
1116 	    else
1117 	    {
1118 		/* Evaluate the argument and get the info in a structure. */
1119 		fi = eval_for_line(eap->arg, &error, &eap->nextcmd, skip);
1120 		cstack->cs_forinfo[cstack->cs_idx] = fi;
1121 	    }
1122 
1123 	    /* use the element at the start of the list and advance */
1124 	    if (!error && fi != NULL && !skip)
1125 		result = next_for_item(fi, eap->arg);
1126 	    else
1127 		result = FALSE;
1128 
1129 	    if (!result)
1130 	    {
1131 		free_for_info(fi);
1132 		cstack->cs_forinfo[cstack->cs_idx] = NULL;
1133 	    }
1134 	}
1135 
1136 	/*
1137 	 * If this cstack entry was just initialised and is active, set the
1138 	 * loop flag, so do_cmdline() will set the line number in cs_line[].
1139 	 * If executing the command a second time, clear the loop flag.
1140 	 */
1141 	if (!skip && !error && result)
1142 	{
1143 	    cstack->cs_flags[cstack->cs_idx] |= (CSF_ACTIVE | CSF_TRUE);
1144 	    cstack->cs_lflags ^= CSL_HAD_LOOP;
1145 	}
1146 	else
1147 	{
1148 	    cstack->cs_lflags &= ~CSL_HAD_LOOP;
1149 	    /* If the ":while" evaluates to FALSE or ":for" is past the end of
1150 	     * the list, show the debug prompt at the ":endwhile"/":endfor" as
1151 	     * if there was a ":break" in a ":while"/":for" evaluating to
1152 	     * TRUE. */
1153 	    if (!skip && !error)
1154 		cstack->cs_flags[cstack->cs_idx] |= CSF_TRUE;
1155 	}
1156     }
1157 }
1158 
1159 /*
1160  * ":continue"
1161  */
1162     void
1163 ex_continue(eap)
1164     exarg_T	*eap;
1165 {
1166     int		idx;
1167     struct condstack	*cstack = eap->cstack;
1168 
1169     if (cstack->cs_looplevel <= 0 || cstack->cs_idx < 0)
1170 	eap->errmsg = (char_u *)N_("E586: :continue without :while or :for");
1171     else
1172     {
1173 	/* Try to find the matching ":while".  This might stop at a try
1174 	 * conditional not in its finally clause (which is then to be executed
1175 	 * next).  Therefor, inactivate all conditionals except the ":while"
1176 	 * itself (if reached). */
1177 	idx = cleanup_conditionals(cstack, CSF_WHILE | CSF_FOR, FALSE);
1178 	if (idx >= 0 && (cstack->cs_flags[idx] & (CSF_WHILE | CSF_FOR)))
1179 	{
1180 	    rewind_conditionals(cstack, idx, CSF_TRY, &cstack->cs_trylevel);
1181 
1182 	    /*
1183 	     * Set CSL_HAD_CONT, so do_cmdline() will jump back to the
1184 	     * matching ":while".
1185 	     */
1186 	    cstack->cs_lflags |= CSL_HAD_CONT;	/* let do_cmdline() handle it */
1187 	}
1188 	else
1189 	{
1190 	    /* If a try conditional not in its finally clause is reached first,
1191 	     * make the ":continue" pending for execution at the ":endtry". */
1192 	    cstack->cs_pending[idx] = CSTP_CONTINUE;
1193 	    report_make_pending(CSTP_CONTINUE, NULL);
1194 	}
1195     }
1196 }
1197 
1198 /*
1199  * ":break"
1200  */
1201     void
1202 ex_break(eap)
1203     exarg_T	*eap;
1204 {
1205     int		idx;
1206     struct condstack	*cstack = eap->cstack;
1207 
1208     if (cstack->cs_looplevel <= 0 || cstack->cs_idx < 0)
1209 	eap->errmsg = (char_u *)N_("E587: :break without :while or :for");
1210     else
1211     {
1212 	/* Inactivate conditionals until the matching ":while" or a try
1213 	 * conditional not in its finally clause (which is then to be
1214 	 * executed next) is found.  In the latter case, make the ":break"
1215 	 * pending for execution at the ":endtry". */
1216 	idx = cleanup_conditionals(cstack, CSF_WHILE | CSF_FOR, TRUE);
1217 	if (idx >= 0 && !(cstack->cs_flags[idx] & (CSF_WHILE | CSF_FOR)))
1218 	{
1219 	    cstack->cs_pending[idx] = CSTP_BREAK;
1220 	    report_make_pending(CSTP_BREAK, NULL);
1221 	}
1222     }
1223 }
1224 
1225 /*
1226  * ":endwhile" and ":endfor"
1227  */
1228     void
1229 ex_endwhile(eap)
1230     exarg_T	*eap;
1231 {
1232     struct condstack	*cstack = eap->cstack;
1233     int			idx;
1234     char_u		*err;
1235     int			csf;
1236     int			fl;
1237 
1238     if (eap->cmdidx == CMD_endwhile)
1239     {
1240 	err = e_while;
1241 	csf = CSF_WHILE;
1242     }
1243     else
1244     {
1245 	err = e_for;
1246 	csf = CSF_FOR;
1247     }
1248 
1249     if (cstack->cs_looplevel <= 0 || cstack->cs_idx < 0)
1250 	eap->errmsg = err;
1251     else
1252     {
1253 	fl =  cstack->cs_flags[cstack->cs_idx];
1254 	if (!(fl & csf))
1255 	{
1256 	    /* If we are in a ":while" or ":for" but used the wrong endloop
1257 	     * command, do not rewind to the next enclosing ":for"/":while". */
1258 	    if (fl & CSF_WHILE)
1259 		eap->errmsg = (char_u *)_("E732: Using :endfor with :while");
1260 	    else if (fl & CSF_FOR)
1261 		eap->errmsg = (char_u *)_("E733: Using :endwhile with :for");
1262 	}
1263 	if (!(fl & (CSF_WHILE | CSF_FOR)))
1264 	{
1265 	    if (!(fl & CSF_TRY))
1266 		eap->errmsg = e_endif;
1267 	    else if (fl & CSF_FINALLY)
1268 		eap->errmsg = e_endtry;
1269 	    /* Try to find the matching ":while" and report what's missing. */
1270 	    for (idx = cstack->cs_idx; idx > 0; --idx)
1271 	    {
1272 		fl =  cstack->cs_flags[idx];
1273 		if ((fl & CSF_TRY) && !(fl & CSF_FINALLY))
1274 		{
1275 		    /* Give up at a try conditional not in its finally clause.
1276 		     * Ignore the ":endwhile"/":endfor". */
1277 		    eap->errmsg = err;
1278 		    return;
1279 		}
1280 		if (fl & csf)
1281 		    break;
1282 	    }
1283 	    /* Cleanup and rewind all contained (and unclosed) conditionals. */
1284 	    (void)cleanup_conditionals(cstack, CSF_WHILE | CSF_FOR, FALSE);
1285 	    rewind_conditionals(cstack, idx, CSF_TRY, &cstack->cs_trylevel);
1286 	}
1287 
1288 	/*
1289 	 * When debugging or a breakpoint was encountered, display the debug
1290 	 * prompt (if not already done).  This shows the user that an
1291 	 * ":endwhile"/":endfor" is executed when the ":while" was not TRUE or
1292 	 * after a ":break".  Handle a ">quit" debug command as if an
1293 	 * interrupt had occurred before the ":endwhile"/":endfor".  That is,
1294 	 * throw an interrupt exception if appropriate.  Doing this here
1295 	 * prevents that an exception for a parsing error is discarded when
1296 	 * throwing the interrupt exception later on.
1297 	 */
1298 	else if (cstack->cs_flags[cstack->cs_idx] & CSF_TRUE
1299 		&& !(cstack->cs_flags[cstack->cs_idx] & CSF_ACTIVE)
1300 		&& dbg_check_skipped(eap))
1301 	    (void)do_intthrow(cstack);
1302 
1303 	/*
1304 	 * Set loop flag, so do_cmdline() will jump back to the matching
1305 	 * ":while" or ":for".
1306 	 */
1307 	cstack->cs_lflags |= CSL_HAD_ENDLOOP;
1308     }
1309 }
1310 
1311 
1312 /*
1313  * ":throw expr"
1314  */
1315     void
1316 ex_throw(eap)
1317     exarg_T	*eap;
1318 {
1319     char_u	*arg = eap->arg;
1320     char_u	*value;
1321 
1322     if (*arg != NUL && *arg != '|' && *arg != '\n')
1323 	value = eval_to_string_skip(arg, &eap->nextcmd, eap->skip);
1324     else
1325     {
1326 	EMSG(_(e_argreq));
1327 	value = NULL;
1328     }
1329 
1330     /* On error or when an exception is thrown during argument evaluation, do
1331      * not throw. */
1332     if (!eap->skip && value != NULL)
1333     {
1334 	if (throw_exception(value, ET_USER, NULL) == FAIL)
1335 	    vim_free(value);
1336 	else
1337 	    do_throw(eap->cstack);
1338     }
1339 }
1340 
1341 /*
1342  * Throw the current exception through the specified cstack.  Common routine
1343  * for ":throw" (user exception) and error and interrupt exceptions.  Also
1344  * used for rethrowing an uncaught exception.
1345  */
1346     void
1347 do_throw(cstack)
1348     struct condstack	*cstack;
1349 {
1350     int		idx;
1351     int		inactivate_try = FALSE;
1352 
1353     /*
1354      * Cleanup and inactivate up to the next surrounding try conditional that
1355      * is not in its finally clause.  Normally, do not inactivate the try
1356      * conditional itself, so that its ACTIVE flag can be tested below.  But
1357      * if a previous error or interrupt has not been converted to an exception,
1358      * inactivate the try conditional, too, as if the conversion had been done,
1359      * and reset the did_emsg or got_int flag, so this won't happen again at
1360      * the next surrounding try conditional.
1361      */
1362 #ifndef THROW_ON_ERROR_TRUE
1363     if (did_emsg && !THROW_ON_ERROR)
1364     {
1365 	inactivate_try = TRUE;
1366 	did_emsg = FALSE;
1367     }
1368 #endif
1369 #ifndef THROW_ON_INTERRUPT_TRUE
1370     if (got_int && !THROW_ON_INTERRUPT)
1371     {
1372 	inactivate_try = TRUE;
1373 	got_int = FALSE;
1374     }
1375 #endif
1376     idx = cleanup_conditionals(cstack, 0, inactivate_try);
1377     if (idx >= 0)
1378     {
1379 	/*
1380 	 * If this try conditional is active and we are before its first
1381 	 * ":catch", set THROWN so that the ":catch" commands will check
1382 	 * whether the exception matches.  When the exception came from any of
1383 	 * the catch clauses, it will be made pending at the ":finally" (if
1384 	 * present) and rethrown at the ":endtry".  This will also happen if
1385 	 * the try conditional is inactive.  This is the case when we are
1386 	 * throwing an exception due to an error or interrupt on the way from
1387 	 * a preceding ":continue", ":break", ":return", ":finish", error or
1388 	 * interrupt (not converted to an exception) to the finally clause or
1389 	 * from a preceding throw of a user or error or interrupt exception to
1390 	 * the matching catch clause or the finally clause.
1391 	 */
1392 	if (!(cstack->cs_flags[idx] & CSF_CAUGHT))
1393 	{
1394 	    if (cstack->cs_flags[idx] & CSF_ACTIVE)
1395 		cstack->cs_flags[idx] |= CSF_THROWN;
1396 	    else
1397 		/* THROWN may have already been set for a catchable exception
1398 		 * that has been discarded.  Ensure it is reset for the new
1399 		 * exception. */
1400 		cstack->cs_flags[idx] &= ~CSF_THROWN;
1401 	}
1402 	cstack->cs_flags[idx] &= ~CSF_ACTIVE;
1403 	cstack->cs_exception[idx] = current_exception;
1404     }
1405 #if 0
1406     /* TODO: Add optimization below.  Not yet done because of interface
1407      * problems to eval.c and ex_cmds2.c. (Servatius) */
1408     else
1409     {
1410 	/*
1411 	 * There are no catch clauses to check or finally clauses to execute.
1412 	 * End the current script or function.  The exception will be rethrown
1413 	 * in the caller.
1414 	 */
1415 	if (getline_equal(eap->getline, eap->cookie, get_func_line))
1416 	    current_funccal->returned = TRUE;
1417 	elseif (eap->get_func_line == getsourceline)
1418 	    ((struct source_cookie *)eap->cookie)->finished = TRUE;
1419     }
1420 #endif
1421 
1422     did_throw = TRUE;
1423 }
1424 
1425 /*
1426  * ":try"
1427  */
1428     void
1429 ex_try(eap)
1430     exarg_T	*eap;
1431 {
1432     int		skip;
1433     struct condstack	*cstack = eap->cstack;
1434 
1435     if (cstack->cs_idx == CSTACK_LEN - 1)
1436 	eap->errmsg = (char_u *)N_("E601: :try nesting too deep");
1437     else
1438     {
1439 	++cstack->cs_idx;
1440 	++cstack->cs_trylevel;
1441 	cstack->cs_flags[cstack->cs_idx] = CSF_TRY;
1442 	cstack->cs_pending[cstack->cs_idx] = CSTP_NONE;
1443 
1444 	/*
1445 	 * Don't do something after an error, interrupt, or throw, or when there
1446 	 * is a surrounding conditional and it was not active.
1447 	 */
1448 	skip = did_emsg || got_int || did_throw || (cstack->cs_idx > 0
1449 		&& !(cstack->cs_flags[cstack->cs_idx - 1] & CSF_ACTIVE));
1450 
1451 	if (!skip)
1452 	{
1453 	    /* Set ACTIVE and TRUE.  TRUE means that the corresponding ":catch"
1454 	     * commands should check for a match if an exception is thrown and
1455 	     * that the finally clause needs to be executed. */
1456 	    cstack->cs_flags[cstack->cs_idx] |= CSF_ACTIVE | CSF_TRUE;
1457 
1458 	    /*
1459 	     * ":silent!", even when used in a try conditional, disables
1460 	     * displaying of error messages and conversion of errors to
1461 	     * exceptions.  When the silent commands again open a try
1462 	     * conditional, save "emsg_silent" and reset it so that errors are
1463 	     * again converted to exceptions.  The value is restored when that
1464 	     * try conditional is left.  If it is left normally, the commands
1465 	     * following the ":endtry" are again silent.  If it is left by
1466 	     * a ":continue", ":break", ":return", or ":finish", the commands
1467 	     * executed next are again silent.  If it is left due to an
1468 	     * aborting error, an interrupt, or an exception, restoring
1469 	     * "emsg_silent" does not matter since we are already in the
1470 	     * aborting state and/or the exception has already been thrown.
1471 	     * The effect is then just freeing the memory that was allocated
1472 	     * to save the value.
1473 	     */
1474 	    if (emsg_silent)
1475 	    {
1476 		eslist_T	*elem;
1477 
1478 		elem = (eslist_T *)alloc((unsigned)sizeof(struct eslist_elem));
1479 		if (elem == NULL)
1480 		    EMSG(_(e_outofmem));
1481 		else
1482 		{
1483 		    elem->saved_emsg_silent = emsg_silent;
1484 		    elem->next = cstack->cs_emsg_silent_list;
1485 		    cstack->cs_emsg_silent_list = elem;
1486 		    cstack->cs_flags[cstack->cs_idx] |= CSF_SILENT;
1487 		    emsg_silent = 0;
1488 		}
1489 	    }
1490 	}
1491 
1492     }
1493 }
1494 
1495 /*
1496  * ":catch /{pattern}/" and ":catch"
1497  */
1498     void
1499 ex_catch(eap)
1500     exarg_T	*eap;
1501 {
1502     int		idx = 0;
1503     int		give_up = FALSE;
1504     int		skip = FALSE;
1505     int		caught = FALSE;
1506     char_u	*end;
1507     int		save_char = 0;
1508     char_u	*save_cpo;
1509     regmatch_T	regmatch;
1510     int		prev_got_int;
1511     struct condstack	*cstack = eap->cstack;
1512     char_u	*pat;
1513 
1514     if (cstack->cs_trylevel <= 0 || cstack->cs_idx < 0)
1515     {
1516 	eap->errmsg = (char_u *)N_("E603: :catch without :try");
1517 	give_up = TRUE;
1518     }
1519     else
1520     {
1521 	if (!(cstack->cs_flags[cstack->cs_idx] & CSF_TRY))
1522 	{
1523 	    /* Report what's missing if the matching ":try" is not in its
1524 	     * finally clause. */
1525 	    eap->errmsg = get_end_emsg(cstack);
1526 	    skip = TRUE;
1527 	}
1528 	for (idx = cstack->cs_idx; idx > 0; --idx)
1529 	    if (cstack->cs_flags[idx] & CSF_TRY)
1530 		break;
1531 	if (cstack->cs_flags[idx] & CSF_FINALLY)
1532 	{
1533 	    /* Give up for a ":catch" after ":finally" and ignore it.
1534 	     * Just parse. */
1535 	    eap->errmsg = (char_u *)N_("E604: :catch after :finally");
1536 	    give_up = TRUE;
1537 	}
1538 	else
1539 	    rewind_conditionals(cstack, idx, CSF_WHILE | CSF_FOR,
1540 						       &cstack->cs_looplevel);
1541     }
1542 
1543     if (ends_excmd(*eap->arg))	/* no argument, catch all errors */
1544     {
1545 	pat = (char_u *)".*";
1546 	end = NULL;
1547 	eap->nextcmd = find_nextcmd(eap->arg);
1548     }
1549     else
1550     {
1551 	pat = eap->arg + 1;
1552 	end = skip_regexp(pat, *eap->arg, TRUE, NULL);
1553     }
1554 
1555     if (!give_up)
1556     {
1557 	/*
1558 	 * Don't do something when no exception has been thrown or when the
1559 	 * corresponding try block never got active (because of an inactive
1560 	 * surrounding conditional or after an error or interrupt or throw).
1561 	 */
1562 	if (!did_throw || !(cstack->cs_flags[idx] & CSF_TRUE))
1563 	    skip = TRUE;
1564 
1565 	/*
1566 	 * Check for a match only if an exception is thrown but not caught by
1567 	 * a previous ":catch".  An exception that has replaced a discarded
1568 	 * exception is not checked (THROWN is not set then).
1569 	 */
1570 	if (!skip && (cstack->cs_flags[idx] & CSF_THROWN)
1571 		&& !(cstack->cs_flags[idx] & CSF_CAUGHT))
1572 	{
1573 	    if (end != NULL && *end != NUL && !ends_excmd(*skipwhite(end + 1)))
1574 	    {
1575 		EMSG(_(e_trailing));
1576 		return;
1577 	    }
1578 
1579 	    /* When debugging or a breakpoint was encountered, display the
1580 	     * debug prompt (if not already done) before checking for a match.
1581 	     * This is a helpful hint for the user when the regular expression
1582 	     * matching fails.  Handle a ">quit" debug command as if an
1583 	     * interrupt had occurred before the ":catch".  That is, discard
1584 	     * the original exception, replace it by an interrupt exception,
1585 	     * and don't catch it in this try block. */
1586 	    if (!dbg_check_skipped(eap) || !do_intthrow(cstack))
1587 	    {
1588 		/* Terminate the pattern and avoid the 'l' flag in 'cpoptions'
1589 		 * while compiling it. */
1590 		if (end != NULL)
1591 		{
1592 		    save_char = *end;
1593 		    *end = NUL;
1594 		}
1595 		save_cpo  = p_cpo;
1596 		p_cpo = (char_u *)"";
1597 		regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
1598 		regmatch.rm_ic = FALSE;
1599 		if (end != NULL)
1600 		    *end = save_char;
1601 		p_cpo = save_cpo;
1602 		if (regmatch.regprog == NULL)
1603 		    EMSG2(_(e_invarg2), pat);
1604 		else
1605 		{
1606 		    /*
1607 		     * Save the value of got_int and reset it.  We don't want
1608 		     * a previous interruption cancel matching, only hitting
1609 		     * CTRL-C while matching should abort it.
1610 		     */
1611 		    prev_got_int = got_int;
1612 		    got_int = FALSE;
1613 		    caught = vim_regexec_nl(&regmatch, current_exception->value,
1614 			    (colnr_T)0);
1615 		    got_int |= prev_got_int;
1616 		    vim_regfree(regmatch.regprog);
1617 		}
1618 	    }
1619 	}
1620 
1621 	if (caught)
1622 	{
1623 	    /* Make this ":catch" clause active and reset did_emsg, got_int,
1624 	     * and did_throw.  Put the exception on the caught stack. */
1625 	    cstack->cs_flags[idx] |= CSF_ACTIVE | CSF_CAUGHT;
1626 	    did_emsg = got_int = did_throw = FALSE;
1627 	    catch_exception((except_T *)cstack->cs_exception[idx]);
1628 	    /* It's mandatory that the current exception is stored in the cstack
1629 	     * so that it can be discarded at the next ":catch", ":finally", or
1630 	     * ":endtry" or when the catch clause is left by a ":continue",
1631 	     * ":break", ":return", ":finish", error, interrupt, or another
1632 	     * exception. */
1633 	    if (cstack->cs_exception[cstack->cs_idx] != current_exception)
1634 		EMSG(_(e_internal));
1635 	}
1636 	else
1637 	{
1638 	    /*
1639 	     * If there is a preceding catch clause and it caught the exception,
1640 	     * finish the exception now.  This happens also after errors except
1641 	     * when this ":catch" was after the ":finally" or not within
1642 	     * a ":try".  Make the try conditional inactive so that the
1643 	     * following catch clauses are skipped.  On an error or interrupt
1644 	     * after the preceding try block or catch clause was left by
1645 	     * a ":continue", ":break", ":return", or ":finish", discard the
1646 	     * pending action.
1647 	     */
1648 	    cleanup_conditionals(cstack, CSF_TRY, TRUE);
1649 	}
1650     }
1651 
1652     if (end != NULL)
1653 	eap->nextcmd = find_nextcmd(end);
1654 }
1655 
1656 /*
1657  * ":finally"
1658  */
1659     void
1660 ex_finally(eap)
1661     exarg_T	*eap;
1662 {
1663     int		idx;
1664     int		skip = FALSE;
1665     int		pending = CSTP_NONE;
1666     struct condstack	*cstack = eap->cstack;
1667 
1668     if (cstack->cs_trylevel <= 0 || cstack->cs_idx < 0)
1669 	eap->errmsg = (char_u *)N_("E606: :finally without :try");
1670     else
1671     {
1672 	if (!(cstack->cs_flags[cstack->cs_idx] & CSF_TRY))
1673 	{
1674 	    eap->errmsg = get_end_emsg(cstack);
1675 	    for (idx = cstack->cs_idx - 1; idx > 0; --idx)
1676 		if (cstack->cs_flags[idx] & CSF_TRY)
1677 		    break;
1678 	    /* Make this error pending, so that the commands in the following
1679 	     * finally clause can be executed.  This overrules also a pending
1680 	     * ":continue", ":break", ":return", or ":finish". */
1681 	    pending = CSTP_ERROR;
1682 	}
1683 	else
1684 	    idx = cstack->cs_idx;
1685 
1686 	if (cstack->cs_flags[idx] & CSF_FINALLY)
1687 	{
1688 	    /* Give up for a multiple ":finally" and ignore it. */
1689 	    eap->errmsg = (char_u *)N_("E607: multiple :finally");
1690 	    return;
1691 	}
1692 	rewind_conditionals(cstack, idx, CSF_WHILE | CSF_FOR,
1693 						       &cstack->cs_looplevel);
1694 
1695 	/*
1696 	 * Don't do something when the corresponding try block never got active
1697 	 * (because of an inactive surrounding conditional or after an error or
1698 	 * interrupt or throw) or for a ":finally" without ":try" or a multiple
1699 	 * ":finally".  After every other error (did_emsg or the conditional
1700 	 * errors detected above) or after an interrupt (got_int) or an
1701 	 * exception (did_throw), the finally clause must be executed.
1702 	 */
1703 	skip = !(cstack->cs_flags[cstack->cs_idx] & CSF_TRUE);
1704 
1705 	if (!skip)
1706 	{
1707 	    /* When debugging or a breakpoint was encountered, display the
1708 	     * debug prompt (if not already done).  The user then knows that the
1709 	     * finally clause is executed. */
1710 	    if (dbg_check_skipped(eap))
1711 	    {
1712 		/* Handle a ">quit" debug command as if an interrupt had
1713 		 * occurred before the ":finally".  That is, discard the
1714 		 * original exception and replace it by an interrupt
1715 		 * exception. */
1716 		(void)do_intthrow(cstack);
1717 	    }
1718 
1719 	    /*
1720 	     * If there is a preceding catch clause and it caught the exception,
1721 	     * finish the exception now.  This happens also after errors except
1722 	     * when this is a multiple ":finally" or one not within a ":try".
1723 	     * After an error or interrupt, this also discards a pending
1724 	     * ":continue", ":break", ":finish", or ":return" from the preceding
1725 	     * try block or catch clause.
1726 	     */
1727 	    cleanup_conditionals(cstack, CSF_TRY, FALSE);
1728 
1729 	    /*
1730 	     * Make did_emsg, got_int, did_throw pending.  If set, they overrule
1731 	     * a pending ":continue", ":break", ":return", or ":finish".  Then
1732 	     * we have particularly to discard a pending return value (as done
1733 	     * by the call to cleanup_conditionals() above when did_emsg or
1734 	     * got_int is set).  The pending values are restored by the
1735 	     * ":endtry", except if there is a new error, interrupt, exception,
1736 	     * ":continue", ":break", ":return", or ":finish" in the following
1737 	     * finally clause.  A missing ":endwhile", ":endfor" or ":endif"
1738 	     * detected here is treated as if did_emsg and did_throw had
1739 	     * already been set, respectively in case that the error is not
1740 	     * converted to an exception, did_throw had already been unset.
1741 	     * We must not set did_emsg here since that would suppress the
1742 	     * error message.
1743 	     */
1744 	    if (pending == CSTP_ERROR || did_emsg || got_int || did_throw)
1745 	    {
1746 		if (cstack->cs_pending[cstack->cs_idx] == CSTP_RETURN)
1747 		{
1748 		    report_discard_pending(CSTP_RETURN,
1749 					   cstack->cs_rettv[cstack->cs_idx]);
1750 		    discard_pending_return(cstack->cs_rettv[cstack->cs_idx]);
1751 		}
1752 		if (pending == CSTP_ERROR && !did_emsg)
1753 		    pending |= (THROW_ON_ERROR) ? CSTP_THROW : 0;
1754 		else
1755 		    pending |= did_throw ? CSTP_THROW : 0;
1756 		pending |= did_emsg  ? CSTP_ERROR     : 0;
1757 		pending |= got_int   ? CSTP_INTERRUPT : 0;
1758 		cstack->cs_pending[cstack->cs_idx] = pending;
1759 
1760 		/* It's mandatory that the current exception is stored in the
1761 		 * cstack so that it can be rethrown at the ":endtry" or be
1762 		 * discarded if the finally clause is left by a ":continue",
1763 		 * ":break", ":return", ":finish", error, interrupt, or another
1764 		 * exception.  When emsg() is called for a missing ":endif" or
1765 		 * a missing ":endwhile"/":endfor" detected here, the
1766 		 * exception will be discarded. */
1767 		if (did_throw && cstack->cs_exception[cstack->cs_idx]
1768 							 != current_exception)
1769 		    EMSG(_(e_internal));
1770 	    }
1771 
1772 	    /*
1773 	     * Set CSL_HAD_FINA, so do_cmdline() will reset did_emsg,
1774 	     * got_int, and did_throw and make the finally clause active.
1775 	     * This will happen after emsg() has been called for a missing
1776 	     * ":endif" or a missing ":endwhile"/":endfor" detected here, so
1777 	     * that the following finally clause will be executed even then.
1778 	     */
1779 	    cstack->cs_lflags |= CSL_HAD_FINA;
1780 	}
1781     }
1782 }
1783 
1784 /*
1785  * ":endtry"
1786  */
1787     void
1788 ex_endtry(eap)
1789     exarg_T	*eap;
1790 {
1791     int		idx;
1792     int		skip;
1793     int		rethrow = FALSE;
1794     int		pending = CSTP_NONE;
1795     void	*rettv = NULL;
1796     struct condstack	*cstack = eap->cstack;
1797 
1798     if (cstack->cs_trylevel <= 0 || cstack->cs_idx < 0)
1799 	eap->errmsg = (char_u *)N_("E602: :endtry without :try");
1800     else
1801     {
1802 	/*
1803 	 * Don't do something after an error, interrupt or throw in the try
1804 	 * block, catch clause, or finally clause preceding this ":endtry" or
1805 	 * when an error or interrupt occurred after a ":continue", ":break",
1806 	 * ":return", or ":finish" in a try block or catch clause preceding this
1807 	 * ":endtry" or when the try block never got active (because of an
1808 	 * inactive surrounding conditional or after an error or interrupt or
1809 	 * throw) or when there is a surrounding conditional and it has been
1810 	 * made inactive by a ":continue", ":break", ":return", or ":finish" in
1811 	 * the finally clause.  The latter case need not be tested since then
1812 	 * anything pending has already been discarded. */
1813 	skip = did_emsg || got_int || did_throw ||
1814 	    !(cstack->cs_flags[cstack->cs_idx] & CSF_TRUE);
1815 
1816 	if (!(cstack->cs_flags[cstack->cs_idx] & CSF_TRY))
1817 	{
1818 	    eap->errmsg = get_end_emsg(cstack);
1819 	    /* Find the matching ":try" and report what's missing. */
1820 	    idx = cstack->cs_idx;
1821 	    do
1822 		--idx;
1823 	    while (idx > 0 && !(cstack->cs_flags[idx] & CSF_TRY));
1824 	    rewind_conditionals(cstack, idx, CSF_WHILE | CSF_FOR,
1825 						       &cstack->cs_looplevel);
1826 	    skip = TRUE;
1827 
1828 	    /*
1829 	     * If an exception is being thrown, discard it to prevent it from
1830 	     * being rethrown at the end of this function.  It would be
1831 	     * discarded by the error message, anyway.  Resets did_throw.
1832 	     * This does not affect the script termination due to the error
1833 	     * since "trylevel" is decremented after emsg() has been called.
1834 	     */
1835 	    if (did_throw)
1836 		discard_current_exception();
1837 	}
1838 	else
1839 	{
1840 	    idx = cstack->cs_idx;
1841 
1842 	    /*
1843 	     * If we stopped with the exception currently being thrown at this
1844 	     * try conditional since we didn't know that it doesn't have
1845 	     * a finally clause, we need to rethrow it after closing the try
1846 	     * conditional.
1847 	     */
1848 	    if (did_throw && (cstack->cs_flags[idx] & CSF_TRUE)
1849 		    && !(cstack->cs_flags[idx] & CSF_FINALLY))
1850 		rethrow = TRUE;
1851 	}
1852 
1853 	/* If there was no finally clause, show the user when debugging or
1854 	 * a breakpoint was encountered that the end of the try conditional has
1855 	 * been reached: display the debug prompt (if not already done).  Do
1856 	 * this on normal control flow or when an exception was thrown, but not
1857 	 * on an interrupt or error not converted to an exception or when
1858 	 * a ":break", ":continue", ":return", or ":finish" is pending.  These
1859 	 * actions are carried out immediately.
1860 	 */
1861 	if ((rethrow || (!skip
1862 			&& !(cstack->cs_flags[idx] & CSF_FINALLY)
1863 			&& !cstack->cs_pending[idx]))
1864 		&& dbg_check_skipped(eap))
1865 	{
1866 	    /* Handle a ">quit" debug command as if an interrupt had occurred
1867 	     * before the ":endtry".  That is, throw an interrupt exception and
1868 	     * set "skip" and "rethrow". */
1869 	    if (got_int)
1870 	    {
1871 		skip = TRUE;
1872 		(void)do_intthrow(cstack);
1873 		/* The do_intthrow() call may have reset did_throw or
1874 		 * cstack->cs_pending[idx].*/
1875 		rethrow = FALSE;
1876 		if (did_throw && !(cstack->cs_flags[idx] & CSF_FINALLY))
1877 		    rethrow = TRUE;
1878 	    }
1879 	}
1880 
1881 	/*
1882 	 * If a ":return" is pending, we need to resume it after closing the
1883 	 * try conditional; remember the return value.  If there was a finally
1884 	 * clause making an exception pending, we need to rethrow it.  Make it
1885 	 * the exception currently being thrown.
1886 	 */
1887 	if (!skip)
1888 	{
1889 	    pending = cstack->cs_pending[idx];
1890 	    cstack->cs_pending[idx] = CSTP_NONE;
1891 	    if (pending == CSTP_RETURN)
1892 		rettv = cstack->cs_rettv[idx];
1893 	    else if (pending & CSTP_THROW)
1894 		current_exception = cstack->cs_exception[idx];
1895 	}
1896 
1897 	/*
1898 	 * Discard anything pending on an error, interrupt, or throw in the
1899 	 * finally clause.  If there was no ":finally", discard a pending
1900 	 * ":continue", ":break", ":return", or ":finish" if an error or
1901 	 * interrupt occurred afterwards, but before the ":endtry" was reached.
1902 	 * If an exception was caught by the last of the catch clauses and there
1903 	 * was no finally clause, finish the exception now.  This happens also
1904 	 * after errors except when this ":endtry" is not within a ":try".
1905 	 * Restore "emsg_silent" if it has been reset by this try conditional.
1906 	 */
1907 	(void)cleanup_conditionals(cstack, CSF_TRY | CSF_SILENT, TRUE);
1908 
1909 	--cstack->cs_idx;
1910 	--cstack->cs_trylevel;
1911 
1912 	if (!skip)
1913 	{
1914 	    report_resume_pending(pending,
1915 		    (pending == CSTP_RETURN) ? rettv :
1916 		    (pending & CSTP_THROW) ? (void *)current_exception : NULL);
1917 	    switch (pending)
1918 	    {
1919 		case CSTP_NONE:
1920 		    break;
1921 
1922 		/* Reactivate a pending ":continue", ":break", ":return",
1923 		 * ":finish" from the try block or a catch clause of this try
1924 		 * conditional.  This is skipped, if there was an error in an
1925 		 * (unskipped) conditional command or an interrupt afterwards
1926 		 * or if the finally clause is present and executed a new error,
1927 		 * interrupt, throw, ":continue", ":break", ":return", or
1928 		 * ":finish". */
1929 		case CSTP_CONTINUE:
1930 		    ex_continue(eap);
1931 		    break;
1932 		case CSTP_BREAK:
1933 		    ex_break(eap);
1934 		    break;
1935 		case CSTP_RETURN:
1936 		    do_return(eap, FALSE, FALSE, rettv);
1937 		    break;
1938 		case CSTP_FINISH:
1939 		    do_finish(eap, FALSE);
1940 		    break;
1941 
1942 		/* When the finally clause was entered due to an error,
1943 		 * interrupt or throw (as opposed to a ":continue", ":break",
1944 		 * ":return", or ":finish"), restore the pending values of
1945 		 * did_emsg, got_int, and did_throw.  This is skipped, if there
1946 		 * was a new error, interrupt, throw, ":continue", ":break",
1947 		 * ":return", or ":finish".  in the finally clause. */
1948 		default:
1949 		    if (pending & CSTP_ERROR)
1950 			did_emsg = TRUE;
1951 		    if (pending & CSTP_INTERRUPT)
1952 			got_int = TRUE;
1953 		    if (pending & CSTP_THROW)
1954 			rethrow = TRUE;
1955 		    break;
1956 	    }
1957 	}
1958 
1959 	if (rethrow)
1960 	    /* Rethrow the current exception (within this cstack). */
1961 	    do_throw(cstack);
1962     }
1963 }
1964 
1965 /*
1966  * enter_cleanup() and leave_cleanup()
1967  *
1968  * Functions to be called before/after invoking a sequence of autocommands for
1969  * cleanup for a failed command.  (Failure means here that a call to emsg()
1970  * has been made, an interrupt occurred, or there is an uncaught exception
1971  * from a previous autocommand execution of the same command.)
1972  *
1973  * Call enter_cleanup() with a pointer to a cleanup_T and pass the same
1974  * pointer to leave_cleanup().  The cleanup_T structure stores the pending
1975  * error/interrupt/exception state.
1976  */
1977 
1978 /*
1979  * This function works a bit like ex_finally() except that there was not
1980  * actually an extra try block around the part that failed and an error or
1981  * interrupt has not (yet) been converted to an exception.  This function
1982  * saves the error/interrupt/ exception state and prepares for the call to
1983  * do_cmdline() that is going to be made for the cleanup autocommand
1984  * execution.
1985  */
1986     void
1987 enter_cleanup(csp)
1988     cleanup_T	*csp;
1989 {
1990     int		pending = CSTP_NONE;
1991 
1992     /*
1993      * Postpone did_emsg, got_int, did_throw.  The pending values will be
1994      * restored by leave_cleanup() except if there was an aborting error,
1995      * interrupt, or uncaught exception after this function ends.
1996      */
1997     if (did_emsg || got_int || did_throw || need_rethrow)
1998     {
1999 	csp->pending = (did_emsg     ? CSTP_ERROR     : 0)
2000 		     | (got_int      ? CSTP_INTERRUPT : 0)
2001 		     | (did_throw    ? CSTP_THROW     : 0)
2002 		     | (need_rethrow ? CSTP_THROW     : 0);
2003 
2004 	/* If we are currently throwing an exception (did_throw), save it as
2005 	 * well.  On an error not yet converted to an exception, update
2006 	 * "force_abort" and reset "cause_abort" (as do_errthrow() would do).
2007 	 * This is needed for the do_cmdline() call that is going to be made
2008 	 * for autocommand execution.  We need not save *msg_list because
2009 	 * there is an extra instance for every call of do_cmdline(), anyway.
2010 	 */
2011 	if (did_throw || need_rethrow)
2012 	    csp->exception = current_exception;
2013 	else
2014 	{
2015 	    csp->exception = NULL;
2016 	    if (did_emsg)
2017 	    {
2018 		force_abort |= cause_abort;
2019 		cause_abort = FALSE;
2020 	    }
2021 	}
2022 	did_emsg = got_int = did_throw = need_rethrow = FALSE;
2023 
2024 	/* Report if required by the 'verbose' option or when debugging.  */
2025 	report_make_pending(pending, csp->exception);
2026     }
2027     else
2028     {
2029 	csp->pending = CSTP_NONE;
2030 	csp->exception = NULL;
2031     }
2032 }
2033 
2034 /*
2035  * See comment above enter_cleanup() for how this function is used.
2036  *
2037  * This function is a bit like ex_endtry() except that there was not actually
2038  * an extra try block around the part that failed and an error or interrupt
2039  * had not (yet) been converted to an exception when the cleanup autocommand
2040  * sequence was invoked.
2041  *
2042  * This function has to be called with the address of the cleanup_T structure
2043  * filled by enter_cleanup() as an argument; it restores the error/interrupt/
2044  * exception state saved by that function - except there was an aborting
2045  * error, an interrupt or an uncaught exception during execution of the
2046  * cleanup autocommands.  In the latter case, the saved error/interrupt/
2047  * exception state is discarded.
2048  */
2049     void
2050 leave_cleanup(csp)
2051     cleanup_T	*csp;
2052 {
2053     int		pending = csp->pending;
2054 
2055     if (pending == CSTP_NONE)	/* nothing to do */
2056 	return;
2057 
2058     /* If there was an aborting error, an interrupt, or an uncaught exception
2059      * after the corresponding call to enter_cleanup(), discard what has been
2060      * made pending by it.  Report this to the user if required by the
2061      * 'verbose' option or when debugging. */
2062     if (aborting() || need_rethrow)
2063     {
2064 	if (pending & CSTP_THROW)
2065 	    /* Cancel the pending exception (includes report). */
2066 	    discard_exception((except_T *)csp->exception, FALSE);
2067 	else
2068 	    report_discard_pending(pending, NULL);
2069 
2070 	/* If an error was about to be converted to an exception when
2071 	 * enter_cleanup() was called, free the message list. */
2072 	if (msg_list != NULL)
2073 	    free_global_msglist();
2074     }
2075 
2076     /*
2077      * If there was no new error, interrupt, or throw between the calls
2078      * to enter_cleanup() and leave_cleanup(), restore the pending
2079      * error/interrupt/exception state.
2080      */
2081     else
2082     {
2083 	/*
2084 	 * If there was an exception being thrown when enter_cleanup() was
2085 	 * called, we need to rethrow it.  Make it the exception currently
2086 	 * being thrown.
2087 	 */
2088 	if (pending & CSTP_THROW)
2089 	    current_exception = csp->exception;
2090 
2091 	/*
2092 	 * If an error was about to be converted to an exception when
2093 	 * enter_cleanup() was called, let "cause_abort" take the part of
2094 	 * "force_abort" (as done by cause_errthrow()).
2095 	 */
2096 	else if (pending & CSTP_ERROR)
2097 	{
2098 	    cause_abort = force_abort;
2099 	    force_abort = FALSE;
2100 	}
2101 
2102 	/*
2103 	 * Restore the pending values of did_emsg, got_int, and did_throw.
2104 	 */
2105 	if (pending & CSTP_ERROR)
2106 	    did_emsg = TRUE;
2107 	if (pending & CSTP_INTERRUPT)
2108 	    got_int = TRUE;
2109 	if (pending & CSTP_THROW)
2110 	    need_rethrow = TRUE;    /* did_throw will be set by do_one_cmd() */
2111 
2112 	/* Report if required by the 'verbose' option or when debugging. */
2113 	report_resume_pending(pending,
2114 		   (pending & CSTP_THROW) ? (void *)current_exception : NULL);
2115     }
2116 }
2117 
2118 
2119 /*
2120  * Make conditionals inactive and discard what's pending in finally clauses
2121  * until the conditional type searched for or a try conditional not in its
2122  * finally clause is reached.  If this is in an active catch clause, finish
2123  * the caught exception.
2124  * Return the cstack index where the search stopped.
2125  * Values used for "searched_cond" are (CSF_WHILE | CSF_FOR) or CSF_TRY or 0,
2126  * the latter meaning the innermost try conditional not in its finally clause.
2127  * "inclusive" tells whether the conditional searched for should be made
2128  * inactive itself (a try conditional not in its finally clause possibly find
2129  * before is always made inactive).  If "inclusive" is TRUE and
2130  * "searched_cond" is CSF_TRY|CSF_SILENT, the saved former value of
2131  * "emsg_silent", if reset when the try conditional finally reached was
2132  * entered, is restored (used by ex_endtry()).  This is normally done only
2133  * when such a try conditional is left.
2134  */
2135     int
2136 cleanup_conditionals(cstack, searched_cond, inclusive)
2137     struct condstack   *cstack;
2138     int		searched_cond;
2139     int		inclusive;
2140 {
2141     int		idx;
2142     int		stop = FALSE;
2143 
2144     for (idx = cstack->cs_idx; idx >= 0; --idx)
2145     {
2146 	if (cstack->cs_flags[idx] & CSF_TRY)
2147 	{
2148 	    /*
2149 	     * Discard anything pending in a finally clause and continue the
2150 	     * search.  There may also be a pending ":continue", ":break",
2151 	     * ":return", or ":finish" before the finally clause.  We must not
2152 	     * discard it, unless an error or interrupt occurred afterwards.
2153 	     */
2154 	    if (did_emsg || got_int || (cstack->cs_flags[idx] & CSF_FINALLY))
2155 	    {
2156 		switch (cstack->cs_pending[idx])
2157 		{
2158 		    case CSTP_NONE:
2159 			break;
2160 
2161 		    case CSTP_CONTINUE:
2162 		    case CSTP_BREAK:
2163 		    case CSTP_FINISH:
2164 			report_discard_pending(cstack->cs_pending[idx], NULL);
2165 			cstack->cs_pending[idx] = CSTP_NONE;
2166 			break;
2167 
2168 		    case CSTP_RETURN:
2169 			report_discard_pending(CSTP_RETURN,
2170 						      cstack->cs_rettv[idx]);
2171 			discard_pending_return(cstack->cs_rettv[idx]);
2172 			cstack->cs_pending[idx] = CSTP_NONE;
2173 			break;
2174 
2175 		    default:
2176 			if (cstack->cs_flags[idx] & CSF_FINALLY)
2177 			{
2178 			    if (cstack->cs_pending[idx] & CSTP_THROW)
2179 			    {
2180 				/* Cancel the pending exception.  This is in the
2181 				 * finally clause, so that the stack of the
2182 				 * caught exceptions is not involved. */
2183 				discard_exception((except_T *)
2184 					cstack->cs_exception[idx],
2185 					FALSE);
2186 			    }
2187 			    else
2188 				report_discard_pending(cstack->cs_pending[idx],
2189 					NULL);
2190 			    cstack->cs_pending[idx] = CSTP_NONE;
2191 			}
2192 			break;
2193 		}
2194 	    }
2195 
2196 	    /*
2197 	     * Stop at a try conditional not in its finally clause.  If this try
2198 	     * conditional is in an active catch clause, finish the caught
2199 	     * exception.
2200 	     */
2201 	    if (!(cstack->cs_flags[idx] & CSF_FINALLY))
2202 	    {
2203 		if ((cstack->cs_flags[idx] & CSF_ACTIVE)
2204 			&& (cstack->cs_flags[idx] & CSF_CAUGHT))
2205 		    finish_exception((except_T *)cstack->cs_exception[idx]);
2206 		/* Stop at this try conditional - except the try block never
2207 		 * got active (because of an inactive surrounding conditional
2208 		 * or when the ":try" appeared after an error or interrupt or
2209 		 * throw). */
2210 		if (cstack->cs_flags[idx] & CSF_TRUE)
2211 		{
2212 		    if (searched_cond == 0 && !inclusive)
2213 			break;
2214 		    stop = TRUE;
2215 		}
2216 	    }
2217 	}
2218 
2219 	/* Stop on the searched conditional type (even when the surrounding
2220 	 * conditional is not active or something has been made pending).
2221 	 * If "inclusive" is TRUE and "searched_cond" is CSF_TRY|CSF_SILENT,
2222 	 * check first whether "emsg_silent" needs to be restored. */
2223 	if (cstack->cs_flags[idx] & searched_cond)
2224 	{
2225 	    if (!inclusive)
2226 		break;
2227 	    stop = TRUE;
2228 	}
2229 	cstack->cs_flags[idx] &= ~CSF_ACTIVE;
2230 	if (stop && searched_cond != (CSF_TRY | CSF_SILENT))
2231 	    break;
2232 
2233 	/*
2234 	 * When leaving a try conditional that reset "emsg_silent" on its
2235 	 * entry after saving the original value, restore that value here and
2236 	 * free the memory used to store it.
2237 	 */
2238 	if ((cstack->cs_flags[idx] & CSF_TRY)
2239 		&& (cstack->cs_flags[idx] & CSF_SILENT))
2240 	{
2241 	    eslist_T	*elem;
2242 
2243 	    elem = cstack->cs_emsg_silent_list;
2244 	    cstack->cs_emsg_silent_list = elem->next;
2245 	    emsg_silent = elem->saved_emsg_silent;
2246 	    vim_free(elem);
2247 	    cstack->cs_flags[idx] &= ~CSF_SILENT;
2248 	}
2249 	if (stop)
2250 	    break;
2251     }
2252     return idx;
2253 }
2254 
2255 /*
2256  * Return an appropriate error message for a missing endwhile/endfor/endif.
2257  */
2258    static char_u *
2259 get_end_emsg(cstack)
2260     struct condstack	*cstack;
2261 {
2262     if (cstack->cs_flags[cstack->cs_idx] & CSF_WHILE)
2263 	return e_endwhile;
2264     if (cstack->cs_flags[cstack->cs_idx] & CSF_FOR)
2265 	return e_endfor;
2266     return e_endif;
2267 }
2268 
2269 
2270 /*
2271  * Rewind conditionals until index "idx" is reached.  "cond_type" and
2272  * "cond_level" specify a conditional type and the address of a level variable
2273  * which is to be decremented with each skipped conditional of the specified
2274  * type.
2275  * Also free "for info" structures where needed.
2276  */
2277     void
2278 rewind_conditionals(cstack, idx, cond_type, cond_level)
2279     struct condstack   *cstack;
2280     int		idx;
2281     int		cond_type;
2282     int		*cond_level;
2283 {
2284     while (cstack->cs_idx > idx)
2285     {
2286 	if (cstack->cs_flags[cstack->cs_idx] & cond_type)
2287 	    --*cond_level;
2288 	if (cstack->cs_flags[cstack->cs_idx] & CSF_FOR)
2289 	    free_for_info(cstack->cs_forinfo[cstack->cs_idx]);
2290 	--cstack->cs_idx;
2291     }
2292 }
2293 
2294 /*
2295  * ":endfunction" when not after a ":function"
2296  */
2297     void
2298 ex_endfunction(eap)
2299     exarg_T	*eap UNUSED;
2300 {
2301     EMSG(_("E193: :endfunction not inside a function"));
2302 }
2303 
2304 /*
2305  * Return TRUE if the string "p" looks like a ":while" or ":for" command.
2306  */
2307     int
2308 has_loop_cmd(p)
2309     char_u	*p;
2310 {
2311     int		len;
2312 
2313     /* skip modifiers, white space and ':' */
2314     for (;;)
2315     {
2316 	while (*p == ' ' || *p == '\t' || *p == ':')
2317 	    ++p;
2318 	len = modifier_len(p);
2319 	if (len == 0)
2320 	    break;
2321 	p += len;
2322     }
2323     if ((p[0] == 'w' && p[1] == 'h')
2324 	    || (p[0] == 'f' && p[1] == 'o' && p[2] == 'r'))
2325 	return TRUE;
2326     return FALSE;
2327 }
2328 
2329 #endif /* FEAT_EVAL */
2330