LaTex:在lstlisting环境中代码分页的问题。
在使用LaTeX时,不免会引用代码,当代码块很长时,很有可能出现分页情况。如果此时你还插入页码了,那就会报错。本文将介绍如何解决这个问题。
在listings宏包手册(下面简称“手册”)里面有这么一句话:
The package supports closed frames only for listings which don’t cross pages.
If a listing is split on two pages, there is neither a bottom rule at the bottom of a page, nor a top rule on the following page.
If you insist on these rules, you might want to use framed.sty by Donald Arseneau.
翻译过来就是个意思:
该包仅支持不跨页的列表的封闭框架。如果在两页上拆分列表,则页面底部既没有底部规则,下页上也没有顶部规则。
如果你坚持这些规则,你可能想要使用由唐纳德·阿尔塞诺框.
这说明了,我们是可以跨页显示代码的,只是需要加一个framed环境。手册里面也给出了模板:
\begin{framed}
\begin{lstlisting}
or \lstinputlisting{...}
\end{lstlisting}
\end{framed}
需要注意的是,framed环境需要加一个宏包\usepackage{framed} 。
在这里我们举一个关于Matlab的例子。
\documentclass{ctexart}
\usepackage{listings}
\usepackage{xcolor}
\usepackage{framed}
\lstset{numbers=left, keywordstyle=\color{blue!70}, commentstyle=\color{red!50!green!50!blue!50}, backgroundcolor=\color{yellow!10}, frame=shadowbox, rulesepcolor= \color{red!20!green!20!blue!20}, escapeinside=``, xleftmargin=2em, xrightmargin=2em, aboveskip=1em, numberstyle=\tiny\ttfamily, basicstyle=\ttfamily, breakatwhitespace=false, breaklines=true, captionpos=b, keepspaces=true, showspaces=false, showstringspaces=false, showtabs=false, mathescape}%代码块格式设置
\pagestyle{plain}%没有页眉,页脚包含一个居中的页码。
\begin{document}
1\par
1\par
1\par
1\par
1\par
1\par
1\par
1\par
1\par
1\par
1\par
1\par
1\par
1\par
1\par
1\par
1\par
1\par
1\par
1\par
1\par
1\par
1\par
1\par
1\par
1\par
1\par
1\par
\textbf{代码:}
\begin{framed}
\begin{lstlisting}[language=Matlab]
a = input(`"请输入a的值:"`);
if rem(a,2)==0
b = a/2;
fprintf("b = `\%`d \n",b)
else
b = a;
fprintf("b = `\%`d \n",b)
end
\end{lstlisting}
\end{framed}
\end{document}
运行结果:
上面的1全是为了凑行数的不需要在意。通过结果可以看出我们已经实现了我们需要的结果(但是看起来有点别扭)。
在这里我还要强调一下关于“逃逸”的使用,我一直认为“逃逸”只适用于汉语的逃逸,所以输出百分号这个问题也困扰了我一个星期,也是最近在lstlisting宏包手册中找到的答案。手册里面有这么一句话,解决了我对百分号输出的困扰!
Note that TEX’s special characters like the curly braces, the space, the percent sign, and such must be escaped with a backslash.
翻译过来就是:
请注意,TEX 的特殊字符(如大括号、空格、百分比符号等)必须使用反斜杠转义。
我搜遍了国内网站都没有找到解决方法,人家一句话就解决了这个问题,可见listings宏包手册到底有多么重要。(国外很多人都用latex写日志,并且资料也很多,CTAN里面有很多很多外籍大佬,就是在国内打开速度太慢)。这样解释就应该明白刚刚的%是如何输出的了,直接“逃逸”就可以了(不要忘记转义输出)。
第一次写blog,有错误和排版问题欢迎指出。