mdframed 中出现“已定义”错误

mdframed 中出现“已定义”错误

这是一个利用 mdframed 的自定义定理环境:

\documentclass{article}

\usepackage[margin=1in]{geometry}
\usepackage[framemethod=tikz]{mdframed}
\usepackage{ifthen}

%theorembox style
\mdfdefinestyle{theorembox}{%
    leftmargin=2em,
    rightmargin=2em,
    innertopmargin=8pt,
    innerbottommargin=8pt,
    roundcorner=8pt,
    backgroundcolor=gray!15
}

%theorem
\newenvironment{theorem}[1][]{%
    \newcounter{thm}
    \setcounter{thm}{1}
    \newsavebox{\thmargbox}
    \savebox{\thmargbox}{#1}
    \begin{list}{}{%
        \setlength{\leftmargin}{0pt}
        \setlength{\rightmargin}{0pt}
    }       
        \item
        \begin{mdframed}[style=theorembox]
            {\large Theorem \arabic{thm}\quad\ifthenelse{\wd\thmargbox=0}{}{#1\par}}%
}{%     
        \end{mdframed}
    \end{list}
    \stepcounter{thm}
}

\begin{document}

\begin{theorem}[First Theorem] 
  If $a\sim b$, then $b\sim a$.
\end{theorem}

%\begin{theorem}[Second Theorem] 
%  If $a\sim b$ and $b\sim c$, then $a\sim c$.
%\end{theorem}

\end{document}

自定义定理环境

但是,如果应用第二定理,则会报告以下错误:

! LaTeX Error:  Command \c@thm already defined.

我认为这可能与我的计数器而不是 mdframed 更相关,但如果能得到任何帮助我将不胜感激。

答案1

您必须移动\newcounter{thm}并将 替换\setcounter{thm}{1}为,最后\refstepcounter{thm}删除。\stepcounter{thm}

但是有更好的方法可以利用tcolorbox标准定理环境来实现你想要的效果。

\documentclass{article}
\usepackage{amsthm}
\usepackage[many]{tcolorbox}

\newtheoremstyle{largebreak}
  {}% use the default space above
  {}% use the default space below
  {\normalfont}% body font
  {}% indent (0pt)
  {\large}% header font
  {}% punctuation
  {\newline}% break after header
  {\thmname{#1}\thmnumber{ #2}\thmnote{\quad #3}}% header spec

\theoremstyle{largebreak}
\newtheorem{theorem}{Theorem}
\tcolorboxenvironment{theorem}{
  colback=gray!15,
  boxrule=0.4pt,
}

\begin{document}

\begin{theorem}[First Theorem]
  If $a\sim b$, then $b\sim a$.
\end{theorem}

\begin{theorem}[Second Theorem]
  If $a\sim b$ and $b\sim c$, then $a\sim c$.
\end{theorem}

\begin{theorem}% no optional argument
$1+1=2$, no question.
\end{theorem}

\end{document}

在此处输入图片描述

您可以使用以下方法获得类似的结果mdframed

\documentclass{article}
\usepackage{amsthm}
\usepackage[framemethod=tikz]{mdframed}

\newtheoremstyle{largebreak}
  {}% use the default space above
  {}% use the default space below
  {\normalfont}% body font
  {}% indent (0pt)
  {\large}% header font
  {}% punctuation
  {\newline}% break after header
  {\thmname{#1}\thmnumber{ #2}\thmnote{\quad #3}}% header spec

\theoremstyle{largebreak}
\newmdtheoremenv[
    leftmargin=2em,
    rightmargin=2em,
    innertopmargin=2pt,
    innerbottommargin=8pt,
    roundcorner=8pt,
    backgroundcolor=gray!15
]{theorem}{Theorem}

\begin{document}

\begin{theorem}[First Theorem] 
  If $a\sim b$, then $b\sim a$.
\end{theorem}

\begin{theorem}[Second Theorem] 
  If $a\sim b$ and $b\sim c$, then $a\sim c$.
\end{theorem}

\begin{theorem}% no optional argument
$1+1=2$, no question.
\end{theorem}

\end{document}

在此处输入图片描述

相关内容