4

In order to make grey boxes around code in my document I am using:

\usepackage{listings}
\usepackage{xcolor} %custom colours
\usepackage{mdframed} %nice frames
\definecolor{light-gray}{gray}{0.95} %the shade of grey that stack

\begin{mdframed}[backgroundcolor=light-gray, roundcorner=10pt,leftmargin=1, rightmargin=1, innerleftmargin=15, innertopmargin=15,innerbottommargin=15, outerlinewidth=1, linecolor=light-gray]  
\begin{lstlisting}[language=Python]
    Program here
\end{lstlisting}
\end{mdframed}

Is there any way to condense the two begin's with junk into one begin{program} end{program}? I am pretty new to Late and am not sure how to make these custom commands.

1
  • Have you had a look at the tcolorbox package. If I'm not mistaken, it provides a combined construction.
    – daleif
    Commented Aug 26, 2015 at 18:15

1 Answer 1

4

You can use

\surroundwithmdframed[<options>]{<environment>}

A complete example:

\documentclass{article}
\usepackage{listings}
\usepackage{xcolor} %custom colours
\usepackage[framemethod=tikz]{mdframed} %nice frames
\definecolor{light-gray}{gray}{0.95} %the shade of grey that stack

\surroundwithmdframed[backgroundcolor=light-gray, roundcorner=10pt,leftmargin=1, rightmargin=1, innerleftmargin=15, innertopmargin=15,innerbottommargin=15, outerlinewidth=1, linecolor=light-gray]{lstlisting}

\begin{document}

\begin{lstlisting}[language=Python,caption={A test listing}]
    Program here
\end{lstlisting}

\end{document}

The result:

enter image description here

By the way, you should use

\usepackage[framemethod=tikz]{mdframed} %nice frames

as I did in my example; otherwise, some options (such as roundcorner) will be ignored.

However, I'd like to suggest you an alternative using the powerful tcolorbox package and its nice interaction with listings:

\documentclass{article}
\usepackage{listings}
\usepackage{xcolor} %custom colours
\usepackage[most]{tcolorbox} %nice frames
\definecolor{light-gray}{gray}{0.95} %the shade of grey that stack

\newtcblisting{mytcbox}[1][]{
  breakable,
  enhanced,
  colback=light-gray,
  colframe=light-gray,
  boxrule=0pt,
  arc=10pt,
  auto outer arc,
  listing only,
  listing options={#1}
}

\begin{document}

\begin{mytcbox}[language=Python]
    Program here
\end{mytcbox}

\end{document}

The result:

enter image description here

2
  • Thanks! It looks great. However, for some reason captions aren't showing up now. Commented Aug 26, 2015 at 19:42
  • @user2154420 Please see my updated answer. Captions work OK. Are you getting something different? If so, please consider opening a follow-up question. Commented Aug 26, 2015 at 19:47

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .