LaTeX:自动识别代码段落

时间:2010-10-12 14:25:44

标签: latex lines

我正在编写一个程序(在C中,但我认为这不是那么相关)与LaTeX中的一些纪录片材料有关。我希望纪录片材料包含原始代码中的代码片段。

为了包含源代码并使其保持最新,我在文档中执行以下操作:

\lstinputlisting[firstline=200, lastline=210]{../src/source.c)

这会自动将../src/source.c的行200到210(包含例如函数)加载到我的文档中。

但是,如果我在第200行之前添加一些行,这意味着第200行“向下漫游”,所以我必须调整它以获得原始函数。

所以这是我的问题:有没有人知道如何动态告诉lstinputlisting(或任何足够的替代品)来判断要采用哪条线?

我想象如下:我在我的C源代码中添加了特殊注释,这些注释将被lstinputlisting识别,例如

/// lstinputlisting "myfunc" BEGIN
int myFunction(int x){
  return x+2;
}
/// lstinputlisting "myfunc" END

然后,lstlisting会扫描文件,只包含BEGINEND之间的行。

4 个答案:

答案 0 :(得分:13)

我在你的帖子发表几个月后回答,但我在下面描述的lstlists的功能已经在这个包中了好几年了。

要查找的关键字是选项linerange,为方便起见,rangeprefixrangesuffix

这是一个完整的例子。

\documentclass{article}
\usepackage{fullpage,times,listings}
\lstloadlanguages{C++}

\lstset{language=C++,keywordstyle=\bfseries,commentstyle=\itshape,
  rangeprefix=//----------------,rangesuffix=----------------,
  includerangemarker=false,columns=spaceflexible}

\begin{document}
We first show the main function.
\lstinputlisting[linerange=main0-main1]{code.cpp}
Then we show the implementation.
\lstinputlisting[linerange=fact0-fact1]{code.cpp}
\end{document}

然后在code.cpp中保存以下内容:

#include <cassert>

//----------------fact0----------------
// A recursive implementation of factorial
int factorial(int i)
{
    if(i)
        return i * factorial(i-1);
    else
        return 1;
}
//----------------fact1----------------

//----------------main0----------------
// Test the implementation.
int main()
{
    assert(factorial(5) == 120);
}
//----------------main1----------------

这是一个很好的解决方案,因为不可避免地编辑代码,然后更新一个TeX文件中的行号变得乏味。使用符号解决了这个问题,但它也在代码本身留下了痕迹,如果行数发生变化,或者宽度变化过大,则需要确认排版输出看起来仍然合理。

最后,在编辑代码之后,只有在标记的块中插入/删除时才需要再次排版乳胶文件。

答案 1 :(得分:1)

在C中使用#include会不会更容易?

这不是完美的,但足够好,解决方案。

这是一个例子(无法编译,我上次在C 5年前写过的东西):

主要C计划:

    #include <stdio.h>

    //function included from separate file -- will be included in LaTeX too
    #include "fun_x.c"         

    int main() 
    {
      int d = 0;
      printf("%d", fun_x(d));

    //code included from separate file -- will be included in LaTeX too
    #include "calc.c"

      return 0;
    }

fun_x.c档案:

int fun_x(int c) 
{
  c++;
  return c;
}

calc.c档案:

d = 99;
d = fun_x(d);

LaTeX来源:

\begin{document}
...

\lstinputlisting{../src/fun_x.c)

...

\lstinputlisting{../src/calc.c)

...

\end{document}

答案 2 :(得分:1)

实现这一目标的唯一合理方法就是创建一个makefile并负责生成正确的输出。

假设sourcefile.c在./src中,而LaTeX文件在./tex中,那么./tex/Makefile看起来像这样:

doc.tex: sourcefile.grep
        <command to compile doc.tex>
sourcefile.grep: 
        <command to grep/whatever to dump from 
        ../src/sourcefile.c to ./tex/sourcefile.grep>

然后doc.tex中的lstlist会指向./src/sourcefile.grep

答案 3 :(得分:1)

这样的事情是discussed on the TeX SE前一段时间,一个答案使用了一个包catchfilebetweentags。这不能直接解决您的问题,但也许您可以使用它来提供您想要的片段\lstlistings,也许再次使用临时文件。