[Tex/LaTex] Adding a caption or title to a listing in an mdframed environment

listingssectioning

I have several pieces of Matlab script I have put into boxes using the below method. I want to be able to call them listings 1 2 3 4 etc. Preferably a command that will do it automatically for me. New to LaTeX so no idea I have searched and found very little.

\documentclass[a4paper,12pt]{article}
    \usepackage{mdframed}
    \begin{document}
    \begin{mdframed}[skipabove=\topsep,skipbelow=\topsep]
    \begin{verbatim}
    S = 55; % Value of the underlying
   ...
    V =
        2.2147   %This is the value of our put option
    \end{verbatim}
    \end{mdframed}
    \end{document}

Best Answer

If you want to keep your current settings (mdframed+verbatim), you can use the \captionof command from the caption package to obtain a caption. Another option is to use the features provided by the listings package (instead of using mdframed+verbatim) to write your listings; the lstlisting environment gives you the possibility to have a frame and caption for your listings:

\documentclass[a4paper,12pt]{article}
\usepackage{listings}
\usepackage{mdframed}
\usepackage{caption}
\captionsetup[lstlisting]{labelsep=none}

\lstset{frame={tblr}}

\begin{document}

\begin{lstlisting}[caption={\null}]
    S = 55; % Value of the underlying
   ...
    V =
        2.2147   %This is the value of our put option
\end{lstlisting}

\begin{mdframed}[skipabove=\topsep,skipbelow=\topsep]
\captionof{lstlisting}{}
\begin{verbatim}
    S = 55; % Value of the underlying
   ...
    V =
        2.2147   %This is the value of our put option
\end{verbatim}
\end{mdframed}

\end{document}

enter image description here

If you want this to apply automatically, you can surround verbatim with a mdframed and use the settings key to automatically generate the caption:

\documentclass[a4paper,12pt]{article}
\usepackage{mdframed}
\usepackage{listings}
\usepackage{caption}

\captionsetup[lstlisting]{labelsep=none}

\surroundwithmdframed[
  skipabove=\topsep,
  skipbelow=\topsep,
  settings=\captionof{lstlisting}{}
]{verbatim}

\begin{document}

\begin{verbatim}
    S = 55; % Value of the underlying
   ...
    V =
        2.2147   %This is the value of our put option
\end{verbatim}

\begin{verbatim}
    S = 55; % Value of the underlying
   ...
    V =
        8.2147   %This is the value of our put option
\end{verbatim}

\end{document}

enter image description here