给代码片段编号(如方程式编号,而不是行号)

给代码片段编号(如方程式编号,而不是行号)

我可以在 minted 中为我的代码片段编号,就像方程编号一样,这样它们的右侧就会有 (1) 等,以便可以引用它们吗?(例如,写一些类似“组合代码片段 (1) 和 (2) 得到 xyz...”的内容)。同时也让其他人可以引用它们。我不想创建完整的浮动列表,我想在文本流中执行此操作,就像方程一样。

以下是我使用一些代码表达的意思:

Some text... blah.
\begin{minted}{cpp}
int a=0;
int b=5;
\end{minted} % => I want this code fragment to have a number on the right side, like equations do.
Now here (or later in the text), I would like to refer to above code fragment.

数学也是如此:

\begin{equation}
a=0     % this will get a numbering, i.e. "(1)" on the right side
\label{myeq}
\end{equation}
As we can see in Eq. \ref{myeq}, ...blah.

因此文本看起来会像“正如我们在等式 1 中看到的,...等等。”

但是该语法不适用于 minted。

我更愿意在 minted 中执行此操作,而不是切换到列表。

答案1

您可以使用 来完成此操作tcolorbox。根据需要自定义框架。

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

\NewTCBListing[auto counter]{codefragment}{mo}{%
  before skip=\topsep,
  after skip=\topsep,
  colback=red!5!white,colframe=red!75!black,
  comment={\hfill(\thetcbcounter)\IfValueT{#2}{\listinglabel{#2}}},
  listing outside comment,
  righthand width=2.5em,
  sidebyside gap=0pt,
  minted language=#1,
}
\makeatletter
\newcommand{\listinglabel}[1]{%
  \edef\@currentlabel{\thetcbcounter}\label{#1}%
}
\makeatother


\begin{document}

Some text... blah. Some text... blah. Some text... blah.
Some text... blah. Some text... blah. Some text... blah.
Some text... blah.
\begin{codefragment}{cpp}[frag-A]
int a=0;
int b=5;
\end{codefragment}
Now here (or later in the text), I would like to refer to above code fragment
and I can:~\eqref{frag-A}.

Some text... blah. Some text... blah. Some text... blah.
Some text... blah. Some text... blah. Some text... blah.
Some text... blah.
\begin{codefragment}{cpp}[frag-B]
int a=0;
int b=5;
\end{codefragment}
Now here (or later in the text), I would like to refer to above code fragment
and I can:~\eqref{frag-B}.

\end{document}

在此处输入图片描述

相关内容