2

Within a listings environment I want to do $\text{\ttfamily\_}$within mathescape. The reason for wanting to do that is to be able to use \left and \rightwhen doing some pseudocode style. Example:

\documentclass{article}
\usepackage{listings}
\usepackage{amsmath}
\lstdefinestyle{mystyle}{
  basicstyle=\ttfamily,
  mathescape
}
\begin{document}
\bgroup
  \begin{lstlisting}[style=mystyle]
    $\displaystyle\left(\sum_i\text{\ttfamily my\_var}\right)$:
    $\texttt{my\_var}\neq$ my_var because $\texttt\_\neq$_
  \end{lstlisting}
\egroup
\end{document}

Result: Output of example code

In the output above, the kerning between the letters are off, as well as the underscore thickness. I can live with the kerning, but I need the underscore fixed. Any suggestions?

Thanks :D

2
  • 1
    columns=fullflexible
    – egreg
    Jun 25, 2019 at 6:56
  • @egreg that fixes the kerning! Nice :) Jun 25, 2019 at 7:55

2 Answers 2

4

For the underscore use T1-encoding. The spacing in the listings is set/added by listings, so you would need to adjust this.

\documentclass{article}
\usepackage{listings}
\usepackage{amsmath}
\lstdefinestyle{mystyle}{
  basicstyle=\ttfamily,
  mathescape
}
\usepackage[T1]{fontenc}
\begin{document}
\bgroup
  \begin{lstlisting}[style=mystyle]
    $\displaystyle\left(\sum_i\text{\ttfamily my\_var}\right)$:
    $\texttt{my\_var}\neq$ my_var because $\texttt\_\neq$_
  \end{lstlisting}
\egroup
\end{document}

enter image description here

0

If one however decided to ignore Why you should use \usepackage[T1]{fontenc} and just wanted a dirty fix to use the fontenc in the listings:

\documentclass{article}
\usepackage{listings}
\usepackage{amsmath}
\lstdefinestyle{mystyle}{
  basicstyle=\ttfamily,
  mathescape,
  columns=fullflexible%<- Letter kerning fix from @egreg's comment
}
\begin{document}
\bgroup
  \fontencoding{T1}%<- Temporary change font encoding (not recommended)
  \begin{lstlisting}[style=mystyle]
    $\displaystyle\left(\sum_i\text{\ttfamily my\_var}\right)$:
    $\texttt{my\_var}=$ my_var because $\texttt\_=$_
  \end{lstlisting}
\egroup
\end{document}

You must log in to answer this question.

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