4

I tried to use a switch \IfFileExists to define a command differently, but I get the illegal parameter error. I am running LaTeX from TeX Live 2021. A minimal example is:

\documentclass[12pt,fleqn]{article}
\usepackage[dvipsnames]{xcolor}
\IfFileExists{filename}
{\newcommand{\ABC}[1]{{\begin{color}{Red}{#1}\end{color}}}}
{\newcommand{\ABC}[1]{{\begin{color}{Blue}{#1}\end{color}}}}

\begin{document}
\ABC{Why?}
\end{document}
1

2 Answers 2

5

\IfFileExists doesn't work like “usual” conditionals: it stores the true and false branches in macros, and uses them later. This requires you to double every # in there:

\documentclass[12pt,fleqn]{article}
\usepackage[dvipsnames]{xcolor}
\IfFileExists{filename} %                 VV
{\newcommand{\ABC}[1]{{\begin{color}{Red}{##1}\end{color}}}}
{\newcommand{\ABC}[1]{{\begin{color}{Blue}{##1}\end{color}}}}

\begin{document}
\ABC{Why?}
\end{document}
3
  • Thanks, this is great. This was not my real question, unfortunately -- I posted the easier example hoping that it help with the bigger one. Since I can't figure it out, here is the actual true branch I want (which I got online to enable me to input a table as a file and use \midrule etc.): ``` \IfFileExists{filename}{\ExplSyntaxOn \cs_new:Npn \expandableinput #1 { \use:c { @@input } { \file_full_name:n {#1} } } \AddToHook{env/tabular/begin} { \cs_set_eq:NN \input \expandableinput } \AddToHook{env/tabular*/begin} { \cs_set_eq:NN \input \expandableinput } \ExplSyntaxOff}{} ```
    – nicolae
    Apr 7, 2022 at 14:23
  • To be clear, I did try doubling # to ## in the \ExplSyntax construction, it does not work. My goal is to apply this construction when I compile the file on my computer, as opposed to a coauthor running an older latex implementation. (Until he bothers to update..) That's why I used the \IfFileExists.
    – nicolae
    Apr 7, 2022 at 14:29
  • @nicolae That's a very different problem. You are using \ExplSyntaxOn inside the argument of \IfFileExists, but commands like \ExplSyntaxOn don't work (as you'd expect) inside arguments. You were a victim of the XY problem. I would suggest you ask a new question with the actual problem you want to solve Apr 7, 2022 at 14:29
2

You're best served with a different approach.

\documentclass{article}
\usepackage[dvipsnames]{xcolor}

\newcommand{\ABCdo}[2]{\leavevmode{\color{#1}#2}}

\IfFileExists{filename}
  {\newcommand{\ABC}{\ABCdo{Red}}}
  {\newcommand{\ABC}{\ABCdo{Blue}}}

\begin{document}
\ABC{Why?}
\end{document}

Output with filename (which does not exist):

enter image description here

Output with latex.ltx (which exists):

enter image description here

There is no color environment and, anyway, the text should not be braced.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .