I would like to be able to build a conditional to execute one set of code if the conditional would compile, versus another if the code would generate an error. Take the following code block which fails for instance:
\documentclass[•]{article}
\edef\temptwo{\tempone}
\def\tempone{test}
\edef\temptwo{\tempone}
\begin{document}
\temptwo
\end{document}
This above codeblock fails because the original \edef\temptwo tries to expand the argument, which looks for \tempone which has not yet been defined. I know that I can fix this specific example by using a \ifcsname \endcsname type conditional. My question is, is there a general way to make a command, say \iferror that will parse for any kind of pdflatex error in the argument, and not just check to see if a csname is defined? In short, I'd like something like the below pseudocode:
\documentclass[•]{article}
\newcommand{\iferror}[2]{
\ifthisworks{#1} % \ifthisworks will execute only if #1 is executable code
\else % If it's not executable code, execute #2
#2
\fi
\iferror{\edef\temptwo{\tempone}}{\def\tempone{test}}
\iferror{\edef\temptwo{\tempone}}{\def\tempone{test}}
\begin{document}
\temptwo
\end{document}
In the above code, ideally, the first \iferror will see that the first argument would error due to an undefined control sequence, and thus execute the second argument, defining \tempone. Then the second call of \iferror would correctly define \temptwo.
However, I'd like \iferror to be flexible, for example:
\documentclass[•]{article}
\newcommand{\iferror}[2]{
\ifthisworks{#1} % \ifthisworks will execute only if #1 is executable code
\else % If it's not executable code, execute #2
#2
\fi
\begin{document}
\iferror{{}foo}{foome} % This should execute "{}foo".
\iferror{\if foo}{foome}% This should execute "foome" as the \if fails to close.
\iferror{\frac{1}{2}}{foome}% This should execute "foome" because of no mathmode.
$\iferror{\frac{1}{2}}{foome}$% This should execute "\frac{1}{2}" because we are in mathmode.
\end{document}
Is there something this general, or am I stuck with doing situational checks? I'd be especially interested in something that can check to see if you get environmental conflicts. For example, if you need to be in mathmode to execute the code and you aren't, then execute argument 2. If you need to be not in mathmode and you are, then execute argument 2. Otherwise execute argument 1.
\ensuremathto prevent errors from missing math mode? – samcarter_is_at_topanswers.xyz Apr 04 '18 at 16:43\TextOrMath– David Carlisle Apr 04 '18 at 16:47