2

I have a command which formats a piece of text a certain way. Simple example:

\begincommand{\myformat}[1]{\texttt{#1}}

I want to be able to place this command inside other text formatting commmands and have those "outer" commands have no effect on the text enclosed in my command.

If I write

\textbf{Some \myformat{example} text.}
\emph{Some \myformat{example} text.}

I want this to be displayed the same as if I had written

\textbf{Some }\myformat{example}\textbf{ text.}
\emph{Some }\myformat{example}\emph{ text.}

Is it possible to "protect" the formatting on a piece of text in situations like this? So that all text formatting applied within \myformat is applied, but all further formatting is ignored?

4

Redefine \myformat to change the font used to \normalfont before setting new styles/shapes:

enter image description here

\documentclass{article}

\DeclareTextFontCommand{\myformat}{\normalfont\ttfamily}

\begin{document}

\textbf{Some \texttt{example} text.}
\emph{Some \texttt{example} text.}

\textbf{Some \myformat{example} text.}
\emph{Some \myformat{example} text.}

\end{document}

Using \DeclareTextFontCommand as opposed to merely

\newcommand{\myformat}[1]{{\normalfont\ttfamily #1}}

makes the command

  • robust,
  • work in math mode (since the text is placed in a box), and
  • inserts the appropriate italic correction (if needed).
  • Or, \DeclareTextFontCommand{\myformat}{\normalfont\ttfamily} (this is actually better, since it handles automatic insertion of the italic correction). – GuM Feb 15 '17 at 23:20
  • … and defines a robust command, too! – GuM Feb 15 '17 at 23:27
  • @GustavoMezzetti: That's neat. I'll add it. – Werner Feb 15 '17 at 23:28
  • Yes, it is superior under all respects, I think. Drawback: can be used only in preamble. – GuM Feb 15 '17 at 23:30
  • 1
    OK, after the edit I have no longer withheld my upvote ;-) But there’s one more Good Thing about \DeclareTextFontCommand I’d mention: if the amsmath package is loaded, the \myformat command will automagically switch to the correct size when used, for example, in a susbcript (inside math). In other words, in that case the argument is wrapped in a \hbox that, in turn, is wrapped in a \mathchoice. – GuM Feb 16 '17 at 0:55

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.