1

I have a set of documents I work with, where I include various files to complete them. So the main document might appear:

\section{Section A}

\input{SectionText1}

\input{SectionText2}

\section{Section B}

\input{SectionText3}

The reason I do this is so that I can change text in a single master file, and simply insert them into the different files I am trying to create. Therefore the important "SectionText" is the same across documents. I do not always include the same subfiles however, and I would like to put cross-references in, that will automatically be included in the main document if I have included the file with the label in it, but not print the relevant text if I have not.

To that end, I have created a new command:

\newcommand{\condlab}[2]{\ifdefined\r@#1 #2 \else \fi}

Which I execute in the text

\condlab{sec:Label}{The text I want to include}

That does not work. It always includes the text, and it includes the "@sec:Label"

If I write

\ifdefined\mycommand Include \else Not this \fi

In the text with a defined or undefined newcommand it works as intended. If I try:

\ifdefined\r@sec:Label

I get exactly the same result as with the newcommand, which makes sense. Suggestions?

  • Did you remember the required \makeatletter\makeatother pair that is required when dealing with macronames with @ in the name? Also you cannot do \ifdefined\r@#1 #2 \else \fi it will not make the macro ifdefined has to look at before it looks at it. You might want to have a look at the etoolbox package. Thirdly, please always post a full example instead of sniplet. Then it is a lot easier for others to test your code, they do not have to sit and guess. – daleif Oct 24 '18 at 14:03

1 Answers1

2

Testing whether a macro exists is possible using

\ifcsname <csname>\endcsname
  % <true> (\<csname> exists)
\else
  % <false> (\<csname> does not exist)
\fi

This is simplified using etoolbox's \ifcsdef{<csname>}{<true>}{<false>}:

enter image description here

\documentclass{article}

\usepackage{etoolbox}

\newcommand{\condlab}[2]{\ifcsdef{r@#1}{#2}{}}

\begin{document}

\section{A section}
\label{sec:label}

\condlab{sec:label}{This text will be included.}

\condlab{sec:label2}{This text won't be included.}

\end{document}

The above usage (even with \ifcsname <csname>\endcsname) avoids the use of a \makeatletter...\makeatother pair since the control sequence is constructed rather than stated explicitly as a control sequence.

Werner
  • 603,163