Disallowing \textbf, \it, \sffamily, ... in argument of macro or environment
There's no list of the font changing commands available, but you can redefine \selectfont
, inside a group, to do nothing except issuing an error message.
\documentclass{article}
\makeatletter
\newcommand{\restricted}[1]{%
\begingroup
\let\selectfont\cgogolin@error
#1%
\endgroup
}
\newcommand{\cgogolin@error}{%
\@latex@error{Font change not allowed}
{You used a font changing command, which is\MessageBreak
not permitted here}%
}
\makeatother
\begin{document}
\restricted{calling me {\bfseries like} this \textit{is} not allowed}
\end{document}
Here's the output on the terminal:
! LaTeX Error: Font change not allowed.
See the LaTeX manual or LaTeX Companion for explanation.
Type H <return> for immediate help.
...
l.19 ...series like} this \textit{is} not allowed}
The following minimal example provides a selective font switch check by using etoolbox
's \patchcmd
. Each font switch is used to patch the argument of \restricted
. If it is successful, an error is generated, otherwise nothing happens.
\documentclass{article}
\usepackage{etoolbox}
\makeatletter
\newcommand{\restricted}[1]{%
\def\restricted@arg{#1}%
\renewcommand{\do}[1]{%
\patchcmd{\restricted@arg}% <cmd>
{##1}{##1}% <search><replace>
{\cgogolin@error}{}% <success><failure>
}
\docsvlist{\bfseries,\textit}% Check for certain font uses... add more
% <do stuff with #1>
}
\newcommand{\cgogolin@error}{%
\@latex@error{Font change not allowed}
{You used a font changing command, which is\MessageBreak
not permitted here}%
}
\makeatother
\begin{document}
Calling me {\bfseries like} this \textit{is} allowed.
\restricted{Calling me {\bfseries like} this \textit{is} not allowed.}
\end{document}
This comes with the caveat that it tests for explicit use of any particular font switch. For example, \bfseries
my be allowed if only checking for \textbf
, say. Also, no expansion is performed on the argument, so hidden font switches won't be picked up (for example, if \let\mybfseries\bfseries
is used).