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 }.)
\verbalso messes with hyphenation and line-breaking; and that it prints underscores weirdly. – Quuxplusone Mar 01 '17 at 00:19\verband\textttthe 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. – David Carlisle Mar 01 '17 at 00:26\usepackage{listings} \lstset{basicstyle=\ttfamily} \let\code\lstinlineto your preamble... – Werner Mar 01 '17 at 00:39\lstset{autodedent}the extra space goes away. But actually I want to get rid ofbasicstyle=\ttfamily\footnotesizein the inline context as well, or else the text becomes too small when it's inline. Time to read even more of thelistingsmanual, I guess... – Quuxplusone Mar 01 '17 at 01:06