6

This question already has an answer here:

I was unsatisfied with how the # symbol looked in my document and had a look at this question. I tried to create a simple macro to replace

#

with

\texttt{\#}

I thought that a simple

\renewcommand{\#}{\texttt{\#}}

would do the trick. Instead, I'm getting a fatal (!) error.

[25] [26] [27] [28] [29] (c:/texlive/2017/texmf-dist/tex/latex/base/t1cmtt.fd)
! TeX capacity exceeded, sorry [grouping levels=255].
\hmode@bgroup ->\leavevmode \bgroup 


!  ==> Fatal error occurred, no output PDF file produced!
Transcript written on Thesis.log.

What is going wrong and why? How can I succesfully create the macro I need?

marked as duplicate by user156344, Raaja, Stefan Pinnow, Phelype Oleinik, Tiuri Apr 3 at 13:52

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 2
    Since LaTeX is a macro expansion language you essentially tell LaTeX to replace every occurrence of \# with \texttt{\#}. Since the replacement text (\texttt{\#}) contains \# again you end up with an infinite loop of replacements being attempted. After a while TeX gives up because its capacity is exceeded. – moewe Apr 3 at 10:20
  • 4
    In that case a trick like \let\oldhash\# \renewcommand{\#}{\texttt{\oldhash}} usually helps. The \let\oldhash\# copies the definition of \# into \oldhash and you can then use \oldhash in the replacement of \# to get the same effect but without the loop. Another way would be \renewcommand{\#}{\texttt{\char"23}} if you know where the # lives in your font. That said, I'm not quite sure if it is absolutely safe to redefine \#, so I would probably choose a new name making it unnecessary to avoid the loop. – moewe Apr 3 at 10:22
  • 4
    \let\hashtag\#\renewcommand\#{\texttt{\hashtag}} does work. Though, I'd just define \hashtag to be \texttt{\#} and then use \hashtag throughout. – daleif Apr 3 at 10:23
11

You cannot define a command in terms of itself like that, because upon finding \# TeX will replace it by \texttt{\#}, then replacing it by \texttt{\texttt{\#}} and so on.

Solution for the particular case

\renewcommand{\#}{\texttt{\symbol{`\#}}}

because the standard definition of \# is a streamlined form of \symbol{`\#}.

For other situations when \command just produces text,

\let\standardcommand=\command
\renewcommand{\command}{\texttt{\standardcommand}}

would work.

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