Real simple one — how do you define \codemath{...} to do \text{\lstinline{...}}?

I've tried the following so far:

\newcommand{\codemath}{\text\lstinline}        % does nothing
\newcommand{\codemath}{\text \lstinline}       % does nothing
\newcommand{\codemath}{\text\ \lstinline}      % works, but with extra space

\newcommand{\codemath}{\text{\lstinline}}      % does nothing
\newcommand{\codemath}{\text{\lstinline}       % error
\newcommand{\codemath}{\text\{\lstinline}      % works, but with extra {

I've seen a lot of questions about "wrapping", "multiple arguments", and "nesting", none of which have helped me. Neither has Overleaf.

  • Welcome to tex.sx. Many verbatim-type environments require explicit in-line positioning of the ending marker in order to terminate the environment. (Think about it.) I believe that lstinline may be such an environment. In that case, what you request would be impossible. This should be confirmed (or demonstrated to be wrong) by someone who actually uses lstinline. Apr 28, 2020 at 13:29

1 Answer 1


You can escape from math mode by using \hbox\bgroup and using \lst@DeInit for issuing the closing \egroup.

The trick comes from https://tex.stackexchange.com/a/357339/4427


  \leavevmode % just in case this sneaks out of math mode




enter image description here

  • Thank you! The code runs and is displayed correctly, but I still get a LaTeX error (warning?) that says Command \ttfamily invalid in math mode...please use the math alphabet \mathtt instead of the \ttfamily command. Can I ignore this safely? Apr 29, 2020 at 1:10
  • Another issue: when \codemath is wrapped with $$ \begin{cases} ... \end{cases} $$, the following two errors and produced: Missing } inserted and Extra }, or forgotten $. Apr 29, 2020 at 3:17

You must log in to answer this question.

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