在列表中使用 linerange 时的视觉分离

在列表中使用 linerange 时的视觉分离

我已经阅读了listings文档,无法在使用该linerange选项上插入清单中的某种视觉反馈。

答案1

一种方法是将每个行范围的清单分开,并在它们之间放置一个装饰物。有很多选择可以用作分隔符。为了说明这一点,我使用了这个问题的装饰在列表与此问题之间的另一个问题之间如何插入边界在列表结束时。

在此处输入图片描述

以下是代码:

\documentclass{article}
\usepackage{filecontents}
\usepackage{listings}

%------------------------ Used for ornament between listings
% Ornament from https://tex.stackexchange.com/questions/11320/end-of-paragraph-with-ornament
\usepackage{pifont,fourier-orns}% These are needed only for the ornament 

\newcommand\crulefill[1][1ex]{\leavevmode\leaders\hrule depth \dimexpr-#1+0.4pt height #1\hfill\kern0pt}
\newcommand\ornline[2][1ex]{\trivlist\item\crulefill[#1]#2\crulefill[#1]\endtrivlist}

%------------------------ Used for ornament at end of listings
%https://tex.stackexchange.com/questions/30973/how-do-i-insert-a-border-below-text/30979#30979
\usepackage{xcolor}% http://ctan.org/pkg/xcolor
\usepackage{xparse}% http://ctan.org/pkg/xparse
\NewDocumentCommand{\myrule}{O{1pt} O{3pt} O{black}}{%
  \par\nobreak % don't break a page here
  \kern\the\prevdepth % don't take into account the depth of the preceding line
  \kern#2 % space before the rule
  {\color{#3}\hrule height #1 width\hsize} % the rule
  \kern#2 % space after the rule
  \nointerlineskip % no additional space after the rule
}
%------------------------

\begin{filecontents*}{foo.java}
 public int nextInt(int n) {
     if (n<=0)
        throw new IllegalArgumentException("n must be positive");

     if ((n & -n) == n)  // i.e., n is a power of 2
         return (int)((n * (long)next(31)) >> 31);

     int bits, val;
     do {
         bits = next(31);
         val = bits % n;
     } while(bits - val + (n-1) < 0);
     return val;
 }
\end{filecontents*}

\lstdefinestyle{MyListStyle} {numbers=left, language=Java}

\begin{document}
\lstinputlisting[style=MyListStyle,linerange={2-6},firstnumber=2]{foo.java}
\ornline[0.6ex]{\decoone}

\lstinputlisting[style=MyListStyle,linerange={9-11},firstnumber=9]{foo.java}
\myrule[5pt][5pt][orange]
\end{document}

相关内容