4

I have to escape underscores very frequently inside \texttt, because I use it to mark functions and variables.

I'd like to redefine \texttt, under different name, so I could write \mycommand{my_variable_name} instead of \texttt{my\_variable\_name}.

3
  • 1
    \verb!my_variable_name! does the same ;-)
    – user31729
    Apr 7, 2016 at 20:09
  • Do you plan to have spaces in the argument to \mycommand? Or just strings of plain characters and _?
    – egreg
    Apr 7, 2016 at 20:18
  • @egreg I do not plan to have spaces but it'd be nice to have.
    – Luke
    Apr 7, 2016 at 20:21

2 Answers 2

5

You are done with

\newcommand{\myvar}[1]{%
  \texttt{\detokenize{#1}}%
}

provided you load fontenc with the T1 option. Otherwise you need category code changes, which make the command not suitable to be in the argument to another command.

\documentclass{article}
\usepackage[T1]{fontenc}

\newcommand{\myvar}[1]{%
  \texttt{\detokenize{#1}}%
}

\begin{document}

Here is a variable \myvar{my_variable_name} and also
in a description
\begin{description}
\item[\myvar{my_variable_name}] is a nice variable
\end{description}

\end{document}

enter image description here

6
  • Is \detokenize{#1} the core part of the solution? What does T1 mean?
    – Luke
    Apr 8, 2016 at 13:31
  • @Luke Yes, \detokenize is the key; T1 is a font encoding where printable ASCII characters appear as themselves, contrary to what happens with the default OT1 encoding.
    – egreg
    Apr 8, 2016 at 13:33
  • Does it mean I won't be able to write math equations in the same document?
    – Luke
    Apr 8, 2016 at 13:46
  • @Luke Why? There's no reason to worry about math.
    – egreg
    Apr 8, 2016 at 14:02
  • "printable ASCII characters appear as themselves" I guess I didn't get that part.
    – Luke
    Apr 8, 2016 at 14:29
4

You can try to use verbatim mode, i.e. \verb!my_name! -- this is output always as \texttt or use xparse and define a command with verbatim argument 'v', but this macro can't be used in another macro.

This works with spaces too.

Note: The \begingroup...\endgroup is to prevent the leaking of \ttfamily to the following text.

\documentclass{article}

\usepackage{xparse}

\NewDocumentCommand{\mycommand}{+v}{%
  \begingroup
  \ttfamily #1%
  \endgroup
}

\begin{document}
\verb!my_variable_name!

\mycommand{my_variable_name}

\end{document}
2
  • It doesn't seem to work inside \item: \begin{description} ... \item[\verb!abc(d_e, e_f)!] -- blah, blah \end{description}
    – Luke
    Apr 7, 2016 at 20:29
  • @Luke: That's what I wrote: You can't use neither of them in another macro. And your question did not contain \item ...
    – user31729
    Apr 7, 2016 at 20:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .