Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

I using the following settings for code listings.

\usepackage{listings}
\usepackage{textcomp}
\lstset{language=Java,
    keywordstyle=\color{RoyalBlue},
    basicstyle=\scriptsize\ttfamily,
    commentstyle=\color{Green}\ttfamily,
    rulecolor=\color{black},
    upquote=true,
    numbers=left,
    numberstyle=\tiny\color{gray},
    stepnumber=1,
    numbersep=8pt,
    showstringspaces=false,
    breaklines=true,
    frameround=ftff,
    frame=single,
    belowskip=3em,
    belowcaptionskip=.25\baselineskip
}

The actual code listing contains comments as well as URLs. How can I ensure that only the comment will be colored with commentstyle but not the URL that contains a double slash // as well?

// This is a comment.
http://tex.stackexchange.com

In the example tex.stackexchange.com would be colored Green.

share|improve this question
add comment

1 Answer

up vote 4 down vote accepted

You can use

morecomment=[l][basicstyle]{http://},

which gives

enter image description here

\documentclass{article}
\usepackage{xcolor}
\usepackage{listings}
\usepackage{textcomp}
\lstset{language=Java,
    keywordstyle=\color{RoyalBlue},
    basicstyle=\scriptsize\ttfamily,
    commentstyle=\color{green}\ttfamily,
    rulecolor=\color{black},
    upquote=true,
    numbers=left,
    numberstyle=\tiny\color{gray},
    stepnumber=1,
    numbersep=8pt,
    showstringspaces=false,
    breaklines=true,
    frameround=ftff,
    frame=single,
    belowskip=3em,
    belowcaptionskip=.25\baselineskip,
    morecomment=[l][basicstyle]{http://}, %<---- NEW BIT!
}


\begin{document}

\begin{lstlisting}
// This is a comment.
http://tex.stackexchange.com
hello world
// another comment http://tex.stackexchange.com
\end{lstlisting}

\end{document}
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.