Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

I would like to use LaTeX to document my C++ code, since I am able to typeset mathematics easily, as well as create diagrams using TikZ. I made a minimal LaTeX template for testing, but I have already encountered some problems that I would like to fix:

  • Spaces are not generated at the end of each line of text in the escaped LaTeX code (if you look at the rendered output below, you should see some words stuck together).
  • I would like environments in the escaped LaTeX code to stay within the shaded boundary, with line numbers to the left of each line (as it is with the rest of the code). In particular, I want to enforce a 1:1 correspondence between the number of a line of source code and its rendered output in the PDF.

Can you please suggest a fix for these problems? Ideally, I would also like to be able to include TikZ pictures in the documentation, so that the diagram takes up exactly as many lines of code as the length of the escaped LaTeX code that I use to create it. But if this is too difficult to achieve, then I'm fine without it.

Thank you very much for your time!

The Rendered Output enter image description here

The LaTeX Code

\documentclass[11pt, a4paper]{article}
\usepackage[T1]{fontenc}
\usepackage[top=0.4in,bottom=0in,left=0.7in,right=0.7in]{geometry}
\usepackage{listings}
\usepackage{mdframed}
\usepackage[usenames,dvipsnames]{xcolor}
\pagestyle{empty}

\lstset{
    language=C++,
    basicstyle=\sffamily,
    commentstyle=\color{white!40!black},
    escapechar=`,
    escapebegin=\color{white!40!black},
    escapeend={},
    keywordstyle=\bfseries\color{Periwinkle},
    numbers=left,
    numberstyle=\sffamily\tiny\color{gray},
    showstringspaces=false
}
\begin{document}
\begin{mdframed}[backgroundcolor=yellow!20,linewidth=0pt,
    innertopmargin=0pt,innerbottommargin=0pt]
{\footnotesize
\lstinputlisting{test.hpp}
}
\end{mdframed}
\end{document}

The Sample C++ Header

/*
** File Name:   test.hpp
** Date:    04/25/2012
*/

#ifndef TEST_HPP_INCLUDED__
#define TEST_HPP_INCLUDED__

/*
** Template Parameters:
**
`\begin{enumerate}
\item[Schedule] A forward iterator that traverses the edge ordering that
ought to be used for each iteration.
\item[EdgeToFactorMap] A map of edges to factors. We can always transform a
graph such that the node potentials are subsumed into the edge potentials, so
this constraint does not result in a loss of generality.
\item[MessageFunc] A function used to compute the message
$\delta_{i \rightarrow j}$. It should accept as parameters the following:
\begin{itemize}
     \item A const reference to a factor along $E_{ij}$.
     \item A reference to the target factor to be written to.
     \item The starting and ending iterators to a container of factors
     representing the messages received by the sending clique, $C_{i}$.
     \item The starting and ending iterators to a container of factors
     representing the messages received by the receiving clique, $C_{j}$.
\end{itemize}
\item[Allocator] The allocator that ought to be used to obtain temporary
memory for the algorithm.
\end{enumerate}`
**
*/
template <
    class Schedule,
    class EdgeToFactorMap,
    class MessageFunc,
    class Allocator
>

#endif
share|improve this question

2 Answers 2

up vote 2 down vote accepted

I don't really know the listings package so there may be a higher level interface to this, but I would

  1. use description rather than enumerate so that laTex is expecting wider labels and doesn't stick them in the left margin
  2. define the end of line character to gobble two ** if they are there and increment the line counter. (actually typesetting the line number is harder if you are allowing normal latex typesetting at the same time)
  3. I also commented out adforn as I don't have it.

So I get: enter image description here

code file:

/*
** File Name:   test.hpp
** Date:    04/25/2012
*/

#ifndef TEST_HPP_INCLUDED__
#define TEST_HPP_INCLUDED__

/*
** Template Parameters:
**
** `\begin{description}
** \item[Schedule] A forward iterator that traverses the edge ordering that
** ought to be used for each iteration.
** \item[EdgeToFactorMap] A map of edges to factors. We can always transform a
** graph such that the node potentials are subsumed into the edge potentials, so
** this constraint does not result in a loss of generality.
** \item[MessageFunc] A function used to compute the message
** $\delta_{i \rightarrow j}$. It should accept as parameters the following:
** \begin{itemize}
**      \item A const reference to a factor along $E_{ij}$.
**      \item A reference to the target factor to be written to.
**      \item The starting and ending iterators to a container of factors
**      representing the messages received by the sending clique, $C_{i}$.
**      \item The starting and ending iterators to a container of factors
**      representing the messages received by the receiving clique, $C_{j}$.
** \end{itemize}
** \item[Allocator] The allocator that ought to be used to obtain temporary
** memory for the algorithm.
** \end{description}`
**
*/
template <
    class Schedule,
    class EdgeToFactorMap,
    class MessageFunc,
    class Allocator
>

#endif

TeX file:

\documentclass[11pt, a4paper]{article}
%\usepackage{adforn}
\usepackage[T1]{fontenc}
\usepackage[top=0.4in,bottom=0in,left=0.7in,right=0.7in]{geometry}
\usepackage{listings}
\usepackage{mdframed}
\usepackage[usenames,dvipsnames]{xcolor}
\pagestyle{empty}

\def\sstar{**}
\begingroup
\makeatletter
\endlinechar-1
\catcode`\^^M\active
\gdef\foo{%
\let\savedM^^M%
\def^^M##1##2{%
\global\advance\lst@lineno\@ne
\global\advance\c@lstnumber\@ne
\def\tmpa{##1##2}%
\ifx\tmpa\sstar
\expandafter\@gobbletwo
\fi
##1##2}%
}
\endgroup

\lstset{
    language=C++,
    basicstyle=\sffamily,
    commentstyle=\color{white!40!black},
    escapechar=`,
    escapebegin=\color{white!40!black}\foo,
    escapeend={},
    keywordstyle=\bfseries\color{Periwinkle},
    numbers=left,
    numberstyle=\sffamily\tiny\color{gray},
    showstringspaces=false
}
\begin{document}
\begin{mdframed}[backgroundcolor=yellow!20,linewidth=0pt,
    innertopmargin=0pt,innerbottommargin=0pt]
{\footnotesize
\lstinputlisting{test.hpp}
}
\end{mdframed}
\end{document}
share|improve this answer
    
Thanks for the answer! Using \catcode\^^M\active` solves the spacing issue. However, I'm having some trouble compiling the TeX file as it is: ! LaTeX Error: Something's wrong--perhaps a missing \item. See the LaTeX manual or LaTeX Companion for explanation. Type H <return> for immediate help. ... l.13 ** \item[Schedule] Do you know what could be causing the problem? –  void-pointer Apr 25 '12 at 17:26
    
Oops, never mind -- it was a mistake on my part. The file compiles successfully. –  void-pointer Apr 25 '12 at 17:58

I have some partial solutions to my problems, so I'll post them as I come up with them. It is possible to fix the indentation problem in simple cases by appending

\def\leftoff{1.5in}
\setlength{\leftmargini}{\leftmargini+\leftoff}
\setlength{\leftmarginii}{\leftmarginii+\leftoff}

to the preamble. This fixes the simple use cases but adds excess indentation in cases where the enumerate environment is nested in another. Consequently, I recommend that you not use the enumerate environment inside the source code except inside tables, and instead use the tabular environment as the outermost container. This makes better use of the space, and takes care of setting the proper margins.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.