源代码列出了像LaTeX的实用程序员书籍?

时间:2010-07-17 17:13:53

标签: formatting latex

当我阅读Pragmatic Bookshelf的书籍时,它具有以下格式:

http://img210.imageshack.us/img210/2965/screenshot20100717at121.png

  • 如何使用LaTeX做到这一点?左侧的行号,着色源代码和灰色源名称。
  • 使用LaTeX列出源代码的工具是什么?

1 个答案:

答案 0 :(得分:18)

用于格式化LaTeX中源代码的包是listings。在其手册here中查看它可以执行的操作。

这是我设法得到的接近程度:

The listing, as typeset in LaTeX http://i29.tinypic.com/wb8bdi.png

标题中的文件名也是Download链接的目标。抱歉没有圆角。那些可以用TikZ完成。

以下是序言:

\usepackage{listings}
\usepackage[T1]{fontenc}
\usepackage[scaled]{beramono}
\usepackage{tgadventor}
\usepackage[usenames,dvipsnames]{color}
\usepackage[colorlinks=true]{hyperref}

\definecolor{lineno}{rgb}{0.5,0.5,0.5}
\definecolor{code}{rgb}{0,0.1,0.6}
\definecolor{keyword}{rgb}{0.5,0.1,0.1}
\definecolor{titlebox}{rgb}{0.85,0.85,0.85}
\definecolor{download}{rgb}{0.8,0.1,0.5}
\definecolor{title}{rgb}{0.4,0.4,0.4}

\lstset{
    language=Lisp,
    basicstyle=\ttfamily\small\color{code},
    showspaces=false,
    showstringspaces=false,
    numbers=left,
    firstnumber=1,
    stepnumber=5,
    numberfirstline=true,
    numberstyle=\color{lineno}\sffamily\scriptsize,
    keywordstyle=\color{keyword}\bfseries,
    stringstyle=\itshape,
    morekeywords={dosync,if},
    deletekeywords={alter}
}

\makeatletter
\gdef\lst@SkipOrPrintLabel{%
    \ifnum\lst@skipnumbers=\z@
        \global\advance\lst@skipnumbers-\lst@stepnumber\relax
        \lst@PlaceNumber
        \lst@numberfirstlinefalse
    \else
        \lst@ifnumberfirstline
            {\def\thelstnumber{Line \@arabic\c@lstnumber}\lst@PlaceNumber}%
            \lst@numberfirstlinefalse
        \else
            {\def\thelstnumber{-}\lst@PlaceNumber}%
        \fi
    \fi
    \global\advance\lst@skipnumbers\@ne}%
\def\lst@maketitle#1{
   \vskip\abovecaptionskip
   \colorbox{titlebox}{
       \scriptsize
       \color{download}\ttfamily\href{http://example.com/#1}{Download}
       \color{title}\sffamily\bfseries#1}
   \vskip\belowcaptionskip}
\makeatother

然后,使用以下内容在主体中排版列表:

\begin{lstlisting}[title=examples/introduction.clj]
(defn hello
  "Writes hello message to *out*. Calls you by username.
  Knows if you have been here before."
  [username]
  (dosync
    (let [past-visitor (@visitors username)]
      (if past-visitor
        (str "Welcome back, " username)
        (do
          (alter visitors conj username)
          (str "Hello, " username))))))
\end{lstlisting}

我喜欢LaTeX。