I recommend to not use escapeinside
for this purpose, as it somewhat defeats the purpose to leave the verbatim environment and use special commands to still get them typeset verbatim. Instead use the features listings
provides for styling your code. Here are two suggestions to get the desired result.
Define keywords
listings
allows you to define several sets of keywords where each set can be styled differently. So we can just define set 1 to consist of only the root
keyword and apply the red color to this keyword. Green then becomes the default color for your listing. Note that @
has to be redefined as other character to allow listings
' keyword parser to properly stop whenever an @
occurs in the input.
\lstset{
basicstyle = {\ttfamily\color{ForestGreen}},
keywords = [1]{root},
keywordstyle = [1]{\color{red}},
alsoother = {@}
}
Use the literate
option
Keywords work quite well in many cases, but sometimes we need to consider a bit more context. In case you only want root
to be displayed red when it occurs before an @
, you can define a literate
rule to replace each literal occurence of root@
by a properly styled replacement text, in that case a red root
string and an @
that has the default style.
\lstset{
basicstyle = {\ttfamily\color{ForestGreen}},
literate = {root@}{{\color{red}root}@}5
}
EDIT: More pleasant tilde
As noted in one of the comments, the default tilde character is too high for the use in filepaths. The url
package provides a more pleasant version that can be used throughout our listings by also using the literate
option as mentioned above. We just add the following line to \lstset
:
literate={~}{\urltilde}1
where \urltilde
is defined as
\newcommand\urltilde{\url{~}}
Here's the (updated) full code for both versions:
\documentclass{article}
\usepackage{listings}
\usepackage{lmodern}
\usepackage[dvipsnames]{xcolor}
\usepackage{url}
\newcommand\urltilde{\url{~}}
\begin{document}
\lstset{
showstringspaces=false,
columns=flexible,
escapeinside={(*}{*)},
basicstyle={\ttfamily\color{ForestGreen}},
keywords=[1]{root},
keywordstyle=[1]{\color{red}},
alsoother={@},
literate={~}{\urltilde}1
}
\begin{lstlisting}[caption={Command prompt}]
(*\color{red}root*)(*\color{ForestGreen}@hostname:~\#*)
root@hostname:~#
\end{lstlisting}
\bigskip
\lstset{
showstringspaces=false,
columns=flexible,
escapeinside={(*}{*)},
basicstyle={\ttfamily\color{ForestGreen}},
literate={root@}{{\color{red}root}@}5 {~}{\urltilde}1
}
\begin{lstlisting}[caption={Command prompt}]
(*\color{red}root*)(*\color{ForestGreen}@hostname:~\#*)
root@hostname:~#
\end{lstlisting}
\end{document}