避免在代码清单中使用注释样式的 URL

避免在代码清单中使用注释样式的 URL

我使用以下设置来列出代码。

\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
}

实际的代码清单包含注释和 URL。如何确保只有注释会被着色,commentstyle而不包含双斜杠的 URL//也会被着色?

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

在示例中将tex.stackexchange.com是彩色的Green

答案1

您可以使用

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

这使

在此处输入图片描述

\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}

相关内容