[Tex/LaTex] Using listings morecomment option to color code up to the end of the line

listings

I use the following code to color my shell statements:

\lstdefinestyle{sh}{
  breaklines=false,
  language=sh,
  commentstyle=\color{cyan},
  keywordstyle=\color{blue},
  stringstyle=\color{purple},
  identifierstyle=\color{black},
  morecomment=[n][\color{red}]{\ -}{\ },
}

But something unexpected happened:

$ ./configure --foo
$ make

It color the --foo successfully, but it also color the $ in front of make. I know that is because the end of comment is defined to <space>, LaTeX color the $.

But I don't want this coloring? It there a solution to such case?

Or, I know that it may be possible to use a option like: morecomment=[n][\color{red}]{\ -}{<newline>}. But I don't know what to put in the position of <newline>.

Thanks!

Best Answer

You haven't provided a complete MWE, I hope this solution works also in your own document.

\documentclass{article}
\usepackage{xcolor}
\usepackage{listings}
\lstset{
    basicstyle=\ttfamily,
    language=bash,
    showstringspaces=false,
    morecomment=[s][\color{red}]{\ -}{\ },
    otherkeywords={$},
}

\begin{document}
\begin{lstlisting}
$ ./configure --foo       
$ make
\end{lstlisting}
\end{document}

enter image description here

Related Question