
我有一個列表,我想hline
在列表之前和之後添加一個。使用frames
style 參數不能如預期運作,原因有兩個: 1. 我想保留一個左欄作為編號和原始碼的分隔符號; 2. 框架頂線/底線與左邊線之間沒有間隙。
範例程式碼是
\documentclass{article}
\usepackage{listings}
\usepackage{lipsum}
\lstdefinestyle{CEE}{language=C, frame=l, numbers=left, numbersep=1em, xleftmargin=2em}
\begin{document}
\lipsum[1]
\begin{lstlisting}[style=CEE, caption={Hello world}]
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("Hello world\n");
return 0;
}
\end{lstlisting}
\lipsum[2]
\end{document}
這給了我們:
但我希望一個\hline
應該填充整個\textwidth
,而不僅僅是框架寬度,如(GIMP編輯)
請注意,間距和線寬不正確,因為這只是 gimp 編輯。這個想法與table
環境中發現的間距相同。作為:
答案1
我使用該包tcolorbox
來獲取線路。您可以修改環境選項tmpbox
以滿足您的需求。但有一個問題;我認為不可能定義一個將tmpbox
和組合在一起的新環境lstlisting
。所以你tmpbox
每次都必須明確地調用。
\documentclass[11pt, a4paper]{article}
\usepackage{geometry}
\usepackage{tikz}
\usetikzlibrary{calc}
\usepackage{tcolorbox}
\tcbuselibrary{skins,breakable}
\newenvironment{tmpbox}{%
\tcolorbox[%
empty,
parbox=false,
noparskip,
enhanced,
breakable,
frame hidden,
boxrule=0pt,
colback=white,
left=-.5ex, % right=-4pt,
before skip=.1ex plus 2pt,
after skip=1ex plus 2pt,
overlay unbroken and last={%
\draw ($(frame.north west)+(0, -6ex)$)
-- +(1\textwidth, 0);
\draw ($(frame.south west)+(0, 2ex)$)
-- +(1\textwidth, 0);
}]
}{\endtcolorbox}
\usepackage{listings}
\lstdefinestyle{CEE}{%
frame=l, language=C, numbers=left, numbersep=1em, xleftmargin=2em
}
\usepackage{lipsum}
\begin{document}
\begin{center}\large\bfseries
Adding horizontal lines about listings
\end{center}
% See \verb|https://en.wikibooks.org/wiki/LaTeX/Source_Code_Listings|.
\lipsum[1]
\begin{tmpbox}
\begin{lstlisting}[style=CEE, caption={Hello world with hlines}]
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("Hello world\n");
return 0;
}
\end{lstlisting}
\end{tmpbox}
\lipsum[3]
\begin{lstlisting}[style=CEE, caption={Hello world}]
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("Hello world\n");
return 0;
}
\end{lstlisting}
\lipsum[4]
\end{document}