允许在长代码段中分页(使用浮动/列表)

允许在长代码段中分页(使用浮动/列表)

我在论文中插入代码片段时遇到了问题。到目前为止,大多数代码只有几行,而且运行良好。但是,我还想显示一些较大的代码(在附录中),在这里,我的配置会插入代码,但会忽略超出页面长度的任何内容。我设法使用 lstset 和 breaklines 解决了类似的行太长的问题(参见我的代码示例),但找不到针对此其他问题的类似方法。

我怀疑它与“代码”函数是浮点数有关。

    \documentclass[11pt,a4paper]{scrbook}

    \usepackage[utf8]{inputenc}
    \usepackage{geometry} % to change the page dimensions
    \geometry{a4paper} 
    \usepackage{paralist}
    \usepackage{hyperref}
    \usepackage{listings}
    \usepackage{float}
    \usepackage{verbatim} 
    \usepackage[caption = false]{subfig}
    \floatstyle{plain} 
    \newfloat{Code}{H}{myc}

    \lstset{language=R,
      breaklines=true,
    }

    \begin{document}
    \frontmatter
    \mainmatter

    \chapter{Code}

    \begin{Code}
    \centering
    \lstinputlisting[title=\textbf{R-Sourcecode: CodeExample.R}]{./code/CodeExample.R}
    \caption{\label{codelabel}Code to do stuff}
    \end{Code}

    \end{document}

答案1

我建议使用\captionof。请注意,您必须定义更多内容才能\newfloat使其正常工作,这就是我使用 KOMA 的原因\DeclareNewTOC

\documentclass[11pt,a4paper]{scrbook}

\usepackage[utf8]{inputenc}
\usepackage{listings}

\lstset{language=C,
  breaklines=true,
}

\DeclareNewTOC[% declare new float with the means of KOMA script
    float,% define the floating environments `Code` and `Code*`
    nonfloat,% define the non-floating environment `Code-`
    counterwithin=chapter,% reset the counter with every new chapter
    type=Code,% the name with which commands like the environment name are built
    name=Code,% the name printed in the captions and stuff
    listname={List of Codeblocks},% the name for the toc
  ]{Code}% file extension for toc-file

\begin{document}
\frontmatter
\mainmatter

\chapter{Code}

% not using float though it is defined because it won't be page breakable
\rule{\textwidth}{0.7\textheight}

\begin{center}
\captionof{Code}{Based on https://www.xkcd.com/221/\label{codelabel}}
\begin{lstlisting}
int getRandomNumber();
int main ( int argc, char* argv[] ) {
  int i;
  i = getRandomNumber();
  return i;
}
int getRandomNumber() {
  return 4; // chosen by fair dice roll.
            // guaranteed to be random.
}
\end{lstlisting}
\end{center}

\end{document}

结果是页面可分页并且带有标题。

相关内容