2

I'm having difficulty formatting code listings with embedded math, using lstlisting with mathescape=true. In particular I'm finding it difficult to lay out code using indentation when there is math to the left of the code I want to indent.

In the following, I'd like to align the = symbols in each of the blocks of equations:

enter image description here

In the first block I've tried using spaces, but the math font seems to cause subsequent fixed-width text to no longer align with column boundaries.

In the second block of equations I'm using tabs, which seems to help.

The third block shows that tabs aren't as reliable as one might hope: there are math mode fragments which cause subsequent tab characters to fail to align properly with tab stops.

Is there a way to achieve reliable lstlisting indentation in the presence of math, either using tab characters and/or some kind of absolute tab stops?

\documentclass{article}
\usepackage{listings}

\lstset{basicstyle=\ttfamily, mathescape=true, columns=fixed, tabsize=2}

\begin{document}
\begin{lstlisting}
    ab = d
    $[c]^\triangleright$ = d

        ab  = d
    $[c]^\triangleright$        = d

    ab                  = d
    $[c]^\triangleright$                        = d
        $[(x_1, .., x_n): \kappa]^\triangleright$       = d
    \end{lstlisting}
\end{document}

1 Answer 1

1

You can use \mathmakebox from mathtools:

\documentclass{article}
\usepackage{listings}
\usepackage{mathtools}

\lstset{basicstyle=\ttfamily, mathescape=true, columns=fixed, tabsize=2}

\begin{document}
\begin{lstlisting}
    $\mathmakebox[1in][l]{\text{ab}}$ = d
    $\mathmakebox[1in][l]{[c]^\triangleright}$ = d
    $\mathmakebox[1in][l]{[(x_1, .., x_n): \kappa]^\triangleright}$ = d
\end{lstlisting}
\end{document}

enter image description here

2
  • Thanks, that's useful to know about. I guess this means placing everything to the LHS of = in such a box, which isn't so nice for the parts that I want to keep in plain "code" style (such as ab above). But it's another tool in the toolbox.
    – Roly
    Jul 1, 2022 at 14:23
  • 1
    Putting \hfill in the code of Andrey L., maybe it's better for you $\mathmakebox[1in][l]{\hfill\text{ab}}$ = d $\mathmakebox[1in][l]{\hfill[c]^\triangleright}$ = d $\mathmakebox[1in][l]{\hfill[(x_1, .., x_n): \kappa]^\triangleright}$ = d
    – pascal974
    Jul 2, 2022 at 6:13

You must log in to answer this question.

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