使用 mdframed 和 listing 创建新环境

使用 mdframed 和 listing 创建新环境

lstlisting我有一些在环境中使用环境的代码片段mdframed

\begin{mdframed}[roundcorner=5pt]
\begin{lstlisting}[mathescape, caption={some snippet}, label=lst:snippet1, numbers=left,numberstyle=\tiny ,stepnumber=2, showstringspaces=false, basicstyle=\small, xleftmargin=-5pt, frame=b]
// blabla some code
\end{lstlisting}
\end{mdframed}

现在我不想每次编写代码片段时都输入所有参数,所以我想我可以创建一个这样的新环境:

\newenvironment{lst}[2]
{%
\begin{mdframed}[roundcorner=5pt]%
\begin{lstlisting}[mathescape, caption={#1}, label=#2, numbers=left,numberstyle=\tiny ,stepnumber=2, showstringspaces=false, basicstyle=\small, xleftmargin=-5pt, frame=b]%
}%
{%
\end{lstlisting}%
\end{mdframed}%
}

但是当我尝试使用它时,它无法编译并出现很多错误消息。

\begin{lst}{some caption}{lst:label1}
    // blabla code
\end{lst}

为什么它不起作用?我怎样才能让它起作用?

编辑:我刚刚发现\lstnewenvironment可以创建一个新的列表环境。但我仍然无法弄清楚如何在一个环境语句中封装mdframed和。lstlisting

编辑2:最小(非)工作示例:

\documentclass{scrreprt}

\usepackage{listings}
\usepackage[framemethod=TikZ]{mdframed}

\newenvironment{lst}[2]
{%
\begin{mdframed}[roundcorner=5pt]%
\begin{lstlisting}[mathescape, caption={#1}, label=#2, numbers=left,numberstyle=\tiny ,stepnumber=2, showstringspaces=false, basicstyle=\small, xleftmargin=-5pt, frame=b]%
}%
{%
\end{lstlisting}%
\end{mdframed}%
}

\begin{document}

A framed listing %\ref{lst:label1}:
\begin{lst}{fancy title}{lst:label1}
// initializing a
int a = 5;
\end{lst}

\end{document}

答案1

你必须使用\lstnewenvironment

\documentclass{scrreprt}

\usepackage{listings}
\usepackage[framemethod=TikZ]{mdframed}

\lstnewenvironment{lst}[2]
  {%
   \mdframed[roundcorner=5pt]%
   \lstset{
     mathescape,
     caption={#1},
     label=#2,
     numbers=left,
     numberstyle=\tiny,
     stepnumber=2,
     showstringspaces=false,
     basicstyle=\small,
     xleftmargin=-5pt,
     frame=b,
   }%
  }
  {\endmdframed}

\begin{document}

A framed listing \ref{lst:label1}:
\begin{lst}{fancy title}{lst:label1}
// initializing a
int a = 5;
\end{lst}

\end{document}

enter image description here

答案2

tcolorbox这是一种使用及其“自动”环绕的方法listings

\documentclass{scrreprt}

%\usepackage{listings}
%\usepackage[framemethod=TikZ]{mdframed}
\usepackage[most]{tcolorbox}


\newtcblisting[auto counter]{lst}[2][]{%
  listing options={mathescape,
    caption={#2},
    numbers=left,
    numberstyle=\tiny,
    stepnumber=2,
    showstringspaces=false,
    basicstyle=\small,
    xleftmargin=-5pt,
    frame=b},
  listing only, 
  left=5pt,
  enhanced jigsaw,
  listing remove caption=false,
  colback=white!80!yellow,
  boxrule=1pt,
  drop shadow,
  #1
}

\begin{document}

See \ref{somelabel}


\begin{lst}[label=somelabel]{fancy title}
// initializing a
int a = 5;
\end{lst}


\end{document}

enter image description here

相关内容