latexlistingslstlisting

How to change color in lstlisting (LaTeX) if the first symbol is $?


By formatting command-line snippets with LaTeX lstlisting, I want to separate input commands from their outputs as follows:

In the command-line snippet:

$date
Sat Jun  1 14:31:01 CEST 2019

$date has to be in blue

Sat Jun 1 14:31:01 CEST 2019 has to be in black

So the idea is to find all strings with the $ first symbol and colorize them.

I've search through usual commands as string or comment with rudimentary regexp but without luck. Is it really possible?


Solution

  • You could set up $ as comment character:

    \documentclass{article}
    
    \usepackage{listings}
    \usepackage{xcolor}
    
    \lstset{
    commentstyle=\color{blue},
    morecomment=[l]{$},
    }
    
    \begin{document}
    
    \begin{lstlisting}
    $date
    Sat Jun  1 14:31:01 CEST 2019
    \end{lstlisting}
    
    \end{document}
    

    enter image description here