I often typeset mathematical formulas about computer programs (loop invariants, etc.).
I typeset them in typewriter font, saying in my preamble \lstset{basicstyle=\ttfamily}
.
I could say
$\frac{\text{\lstinline£x£}}2$
but this is cumbersome. I want to type
$\frac{\lstinline£x£}2$
So, in a fashion similar to that answer, I created a math-mode version of \lstinline
and I use \ifmmode
to select the appropriate variant (see MWE at the end) :
\newcommand\lstinlinemm[1][]{%
\hbox\bgroup % the \hbox is new
\def\lst@boxpos{b}%
\lsthk@PreSet\lstset{flexiblecolumns,#1}%
\lsthk@TextStyle
\lstinline@}
However, this does not appropriately scale the font size when typesetting eg. a fraction.
Replacing \hbox
with amstext
's \text@
(which is the mathmode version of \text
) leads the code to be typeset in mathmode instead of textmode, and the reason for that is unclear to me. This is a problem because it gives rise to an error pertaining to \ttfamily
not being available in math mode.
An interesting answer told me that using \mathchoice
is more complicated than I thought, because each size version is typeset, due to TeX not knowing beforehand if the regular or scriptsize variant will be necessary.
So that would imply moving the verbatim code snippet around, which I understand is not a trivial thing.
It seems that Lua can interact with LuaTeX's input processing. This answer cites the process_input_buffer
callback to store verbatim text to a lua variable and then use it. However, I understand it works line by line, so is not applicable to my case, as I of course do not want to break line in my tex source within a formula.
Paul Isambert's article quoted in the answer also gives an example using the token_filter
callback. I think this might be used as well to gobble the code snippet to a lua variable, then feed it to \text
. However, token_filter
no longer exists since 2016.
A MWE follows :
\documentclass{standalone}
\usepackage{amsmath,listings}
\lstset{basicstyle=\ttfamily}
\makeatletter
\newcommand\lstinlinemm[1][]{%
\hbox\bgroup
\def\lst@boxpos{b}%
\lsthk@PreSet\lstset{flexiblecolumns,#1}%
\lsthk@TextStyle
\lstinline@}
% On renomme le lstinline d'origine
\let\lstinlinetm\lstinline %%
% On met en place la sélection de la bonne version selon le mode actif
\DeclareRobustCommand\lstinline{\ifmmode\let\nextlstinline\lstinlinemm\else\let\nextlstinline\lstinlinetm\fi\nextlstinline}
\newcommand\£{\lstinline£} %£
\begin{document}
$\frac{\£x£}2$ $\frac{\text{\£x£}}2$
\end{document}
$\frac{\mathtt{...}}{...}$