In this question, answers suggested using \newcommand{\code}[1]{\texttt{#1}} to type in a stylized code font. This works rather nicely, however, I am trying to write about code in a website, where the format/convention for naming functions is to have them be multiple_words_long_with_underscores_representing_spaces. However, I'm rather lazy, and would rather not have to repeatedly preface each underscore with a backslash. I realize I could use find-replace-methods, but is there a latex method to add this into my \newcommand{\code}[1]{\texttt{#1}} shortcut?
Asked
Active
Viewed 391 times
5
Zach Hunter
- 153
2 Answers
0
\documentclass{article}
\newcommand\ustexttt[1]{\bgroup\ttfamily\ustextttaux#1\relax\relax}
\def\ustextttaux#1#2\relax{\ifx_#1\_\else#1\fi
\allowbreak
\ifx\relax#2\relax\def\next{\egroup}\else\def\next{\ustextttaux#2\relax}\fi
\next}
\begin{document}
Here is an example
\ustexttt{multiple_words_long_with_underscores_representing_spaces}
of converted underscores, with autobreak enabled.
\end{document}
If you only want linebreaking following underscores, you can move the \allowbreak inside the prior \ifx block, following the \_.
Steven B. Segletes
- 237,551


\detokenize? – daleif Sep 19 '19 at 15:37listings; that's my motivation for using it. – Werner Sep 19 '19 at 16:25\detokenizewill not linebreak. That may or may not be an issue for the OP. – Steven B. Segletes Sep 19 '19 at 16:57