0

I want to create a conditional if it is not defined yet. The following is my unsuccessful attempt.

%%% in file A
\documentclass{article}

\newif\ifdraft\drafttrue
\def\OptionLoaded{}

%%% in file B
\ifx \OptionLoaded \undefined
  \newif\ifdraft\draftfalse
\fi

\begin{document}
hello
\end{document}

Error Incomplete \ifx raises when I compile the sample code.

2
  • Welcome to TeX.SX! Once I comment out the initial \newif\ifdraft\drafttrue this complies for me without any problems. – user30471 Sep 24 '20 at 7:16
  • @Andrew I also found that. But that is exactly what I need: if file A defines \ifdraft, then file B do nothing; if file A doesn't define \ifdraft, then file B should define it. – Tianren Liu Sep 24 '20 at 7:21
3

If you use the LaTeX tests they take care to lift the true and false branches out of the tex primitive conditional:

%%% in file A
\documentclass{article}

\newif\ifdraft\drafttrue
\def\OptionLoaded{}

%%% in file B
\makeatletter
\@ifundefined{OptionLoaded}{\newif\ifdraft\draftfalse}{}
\makeatother

\begin{document}
hello
\end{document}

Your version fails as when the conditional is defined the \ifx test is false so in

\ifx \OptionLoaded \undefined
  \newif\ifdraft\draftfalse
\fi

Tex tries to skip past \newif\ifdraft\draftfalse without evaluating anything so \newif is just an inert token, however when skipping it does match \if tokens so sees \ifdraft and the \fi but it carries on skipping expecting another \fi to close the \ifx.

1
  • +1 Perhaps in the real use-case \OptionLoaded is needed but at least in the MWE it is redundant and, instead, you could use \@ifundefined{ifdraft}{\newif\ifdraft\draftfalse}{}. – user30471 Sep 24 '20 at 7:25
0

As explained by David Carlisle, when TeX reads \newif\ifdraft\draftfalse, it will ignore \newif and consider \ifdraft as the opening of a conditional. Thus another workaround is to replace \ifdraft with \csname ifdraft\endcsname.

%%% in file A
\documentclass{article}

\newif\ifdraft\drafttrue
\def\OptionLoaded{}

%%% in file B
\ifx \OptionLoaded \undefined
  \expandafter\newif\csname ifdraft\endcsname\draftfalse
\fi

\begin{document}
\ifdraft
  hello
\else
  world
\fi
\end{document}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.