# Listing Captions With Delimited Code Blocks and Pandoc

I am writing a new book in Markdown with splashes of LaTeX and using Pandoc to convert from the Markdown to LaTeX and then converting that to PDF.

One of the challenges of this is what I’d call the “fiddly bits” of tweaking my output to suit me and to look awesome for the final product.

One of these “fiddly bits” was adding captions to my code listings. After some playing around for a while I identified a simple way to do this.

Let’s start with the basics of syntax highlighting with the Markdown-Pandoc-LaTeX solution. I use delimited code blocks in Markdown, for example:


This is a code block.


They are converted into either Verbatim or Listings using the listings package in LaTeX (if you’re using the –listings command line flag with Pandoc as I am):

\begin{lstlisting}
This is a code block.
\end{lstlisting}

You can also pass information to configure the resulting code block in LaTeX, for example to get the language for syntax-highlighting:

Ruby
This is a Ruby syntax highlighted code block.


Will result in a listing like:

\begin{lstlisting}[language=Ruby]
This is a Ruby syntax highlighted code block.
\end{lstlisting}

But you can also add other key/value pairs to configure your code listings. Indeed there are some examples of key/values you can pass into the code block provided here.

One of the things I wanted was to pass in a caption to my LaTeX code listing which I discovered you can do like so:

{caption="This is a caption" .Ruby}
This is a Ruby syntax highlighted code block with a code caption.


Which results in a code listing in LaTeX like so:

\begin{lstlisting}[language=Ruby , caption=This is a caption]
This is a Ruby syntax highlighted code block with a code caption.
\end{lstlisting}

And hey presto listings with captions automatically created with Pandoc.