I would like to highlight code snippets in a grayish background with a rounded frame. I can achieve this partially with mdframed, but the caption is inside the frame.
I also tried with codebox with:
\newtcblisting{codebox}[1]{
arc=4pt,
colback=GitHubGray,
boxrule=0.5pt,
breakable,
listing only,
listing options={
caption={#1},
label=lst:label
}
}
However, the solution isn't very pretty. I would rather prefer a traditional caption that I can use with \listoflistings later.
\documentclass{article}
\usepackage{lipsum}
\usepackage{color}
\usepackage{listings}
\usepackage[framemethod=tikz]{mdframed}
\definecolor{GitHubGray}{rgb}{0.9,0.9,0.9}
\lstset{
language=c,
breaklines=true,
keywordstyle=\bfseries\color{black},
basicstyle=\ttfamily\color{black}\fontsize{9pt}{10pt}\selectfont,
emphstyle={\em \color{gray}},
keepspaces=true,
showspaces=false,
showtabs=true,
tabsize=2,
upquote=true,
aboveskip=2pt,
belowskip=2pt,
framexleftmargin=2pt,
extendedchars=true,
inputencoding=utf8,
}
\mdfsetup{%
roundcorner=4pt,
innerleftmargin=2mm,
innertopmargin=4.5mm, % Magical value
%linecolor=black!50,%
innerbottommargin=1mm, % Magical value
backgroundcolor=GitHubGray
}
\begin{document}
\section{Example}
\lipsum[1]
\begin{mdframed}
\begin{lstlisting}[caption={caption text},label=lst:label]
#include <stdio.h>
int main(int argc, char **argv) {
printf("Hello, world!\n");
}
\end{lstlisting}
\end{mdframed}
\lipsum[2]
\end{document}
Is there a way to achieve this without the magical constants (top/bottom margin) and ideally less boilerplate (no additional \begin/\end something before and after the lstlisting.
Is that possible?

tcolorbox: https://tex.stackexchange.com/a/305392/36296 – samcarter_is_at_topanswers.xyz Jan 04 '24 at 13:02