1

My editor requires me to have a non-white background in my code listings. In order to make my code listings look nicer, I use the literate setting of listings to change underscores (which are very wide in the T1 font encoding) into narrower rules. Since I want the reader to be able to copy code from the PDF into a text editor and get syntactically valid code out, I am currently inserting an "invisible" textual underscore in addition to the rule.

I make the underscore invisible by using \textcolor to make it the same color as the non-white code listing background. However, this doesn't work when I typeset code with \lstinline where the background is white.

Thus I want the color of the underscore to change: In the lstlisting environment it should be grey, and in \lstinline it should be white. How do I achieve this?

Minimal Working Example:

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{color,listings}
\lstset{backgroundcolor=\color[rgb]{0.85,0.85,0.86},
        literate={_}{\niceunderscore}1}
\newcommand{\niceunderscore}{%
  % Invisible underscore that can be copied in the PDF:
  \makebox[0pt][l]{\makebox[3pt][c]{%
    \textcolor[rgb]{0.85,0.85,0.86}{\_}}}%
  % Visible, noncopyable rule:
  \rule[-0.4pt]{3pt}{0.4pt}}
\begin{document}
This is what \lstinline+foo_bar+ looks like:
\begin{lstlisting}
foo_bar
\end{lstlisting}
\end{document}

Screenshot of above example

As you can see, the underscore is visible as a grey character below the black rule in the inline text, but in the lstlisting environment, it is invisible like I want it to be.

1 Answer 1

2

Imho you can use the TextStyle-Hook:

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{xcolor}

\definecolor{mygray}{rgb}{0.85,0.85,0.86}
\newcommand\mylstcolor{mygray}

\usepackage{listings}
\lstset{backgroundcolor=\color{mygray},
        literate={_}{\niceunderscore}1}


\newcommand{\niceunderscore}{%
  % Invisible underscore that can be copied in the PDF:
  \makebox[0pt][l]{\makebox[3pt][c]{%
    \textcolor{\mylstcolor}{\_}}}%
  % Visible, noncopyable rule:
  \rule[-0.4pt]{3pt}{0.4pt}}


\makeatletter  
\lst@AddToHook{TextStyle}{\def\mylstcolor{white}}
\makeatother

\begin{document}


This is what \lstinline+foo_bar+ looks like:
\begin{lstlisting}
foo_bar
\end{lstlisting}
\end{document}

enter image description here

You must log in to answer this question.

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