This is related to Simplify the use of ampersand & in glossaries description, but having read those answers and tried something based on them, I'm finding it still doesn't work for my case.
Basically I'm trying to make a macro \code{...}
that will typeset ...
in monospace font, inline. I guess I'm looking for something fairly similar to WEB's |...|
syntax, except that |
would be a fairly bad choice of delimiter character for my purposes.
For example, I want this:
To capture a reference to the local variable \code{snake_case},
we write \code{[&snake_case]}.
to typeset as if I'd written
To capture a reference to the local variable \texttt{snake\_case},
we write \texttt{[\&snake\_case]}.
I'm going to be writing a lot of inline code snippets, so I'd prefer not to have to remember to backslash-escape any special character if it's at all avoidable.
My attempt so far is:
% make _ a non-special character
\usepackage{underscore}
% make & a non-special character
\newcommand{\makeampletter}{\catcode`\&=12\relax}
\newcommand{\makeampother}{\catcode`\&=4\relax}
\newcommand{\code}[1]{\makeampletter\texttt{#1}\makeampother}
I am vaguely aware of the existence of \verb|...|
, but answers like When should one use \verb and when \texttt have made me wary of it; I'd rather use something that acts as much like \texttt
as possible, and where I 100% understand how I'm deviating from \texttt
when I use it.
(Bonus points for not only fixing my ampersand issue but also addressing my inevitable future issues with %
, {
, and }
.)
\verb
also messes with hyphenation and line-breaking; and that it prints underscores weirdly.\verb
and\texttt
the issues with verb not working on arguments of other commands are just related to catcode. if you fix the&
catcode change in your definition and do the same for all the other special characters then you will just have the definition of\verb
.\usepackage{listings} \lstset{basicstyle=\ttfamily} \let\code\lstinline
to your preamble...