# lstlisting framed with the caption inside the frame

How do I made a lstlistings look like following?

The best I could get was:

The code for the second image is:

\begin{lstlisting}[caption=id(in), frame=single]
out <- in;
return out;
\end{lstlisting}


The code for the first image is:

% \usepackage[boxruled,linesnumbered]{algorithm2e}
\begin{algorithm}
$out \gets in$\;
\Return{$out$}\;
\caption{id(in)}
\end{algorithm}

• Possible duplicate: Source code listing with frame around code? – Werner Aug 18 '15 at 23:42
• I tried the code at that link but could not figure out how to change it to make the caption like the first image. – Bilal Syed Hussain Aug 18 '15 at 23:47
• ...at least you can reference it. It provides context, and shows that you've searched the site. Moreover, it will isolate your problem rather than giving some broadly-defined problem. – Werner Aug 18 '15 at 23:58

May I suggest you to use tcolorbox and its wonderful interaction with listings. A little example (adjust the settings according to your needs):

\documentclass{article}
\usepackage[many]{tcolorbox}
\tcbuselibrary{listings}

\newtcblisting[auto counter]{mytcblisting}[2][]{
enhanced,
breakable,
arc=0pt,
outer arc=0pt,
listing only,
colback=white,
colframe=black,
fonttitle=\normalfont,
colbacktitle=white,
coltitle=black,
before skip=6pt,
after skip=6pt,
listing options={
columns=fullflexible,
basicstyle=\ttfamily\small,
numbers=left,
numbersep=10pt,
xleftmargin=15pt
},
title={{\bfseries Algorithm~\thetcbcounter:} #2},
#1
}

\begin{document}

\begin{mytcblisting}{Some example algorithm}
A test listing
and
some more
code
\end{mytcblisting}

\end{document}


The result:

• I had to comment out the line before skip and after skip to make this work because of this error: I do not know the key '/tcb/before skip', to which you passed '6pt', and I am going to ignore it. Perhaps you misspelled it. – Bilal Syed Hussain Aug 18 '15 at 23:51
• @BilalHussain The error indicates that you are using an outdated version of tcolorbox. Please update tcolorbox. – Gonzalo Medina Aug 18 '15 at 23:53