2011年10月16日 星期日

Latex Code Listing


11. How can I get source code listings nicely printed?


Answer

Sorry, you are on your own, more or less.
I know that there are third-party LATEX packages that are tailored towards formatting and displaying of source code listings in LATEX documents. I did not have the time to investigate these packages for my own purposes, and so I was stuck with something really basic I wrote myself. Just in case that this quick 'n dirty hack might be all you need, too, I include it here.

Example usage

In the preamble, or in an appropriate include file:
\newenvironment{mylisting}
{\begin{list}{}{\setlength{\leftmargin}{1em}}\item\scriptsize\bfseries}
{\end{list}}

\newenvironment{mytinylisting}
{\begin{list}{}{\setlength{\leftmargin}{1em}}\item\tiny\bfseries}
{\end{list}}

In the manuscript:
\begin{mylisting}
\begin{verbatim}
  double a[n], b[n], c[n];

  for (i = 0; i < n; i++)
      c[i] = a[i] + b[i];
\end{verbatim}
\end{mylisting}


Result, before

'Before' screenshot

Result, after

'After' screenshot

2 則留言:

  1. You can actually try the "listings" package. It is simple to use, just like verbatim. I used it in my OOP class.

    回覆刪除
  2. 沒想到教授有在看這個網誌XD

    ftp://ftp.tex.ac.uk/tex-archive/macros/latex/contrib/listings/listings.pdf

    我找到listings的資料了,感覺很方便

    回覆刪除