每次调用 LaTeX 中的环境时创建新变量

Create new variable each time an environment in LaTeX is called

我为我的数学笔记创建了一个示例环境。它以示例的标题作为输入,并使用 tikz 绘制一些线条。但是,这样做需要标题的长度。

如果仅使用 \newlength{\lengthname} 后跟 \settowidth{\lengthname}{[length]} 调用一次环境,则此操作相对容易。但是,一旦多次调用,就必须定义不同的长度。我的(诚然很差)work-around 一直在传递不同长度的名称,#2,每次我使用我的示例环境时。

如何在每次使用我的环境时创建一个独特的 \newlength{\unique},或者,是否有更好的方法来实现我的目标?

\newenvironment{example}[2] % Example Environment
    {\refstepcounter{example}
    \newlength{#2}
    \settowidth{#2}{\small \textbf{Example \thesection.\theexample} --- #1}
    \bigskip\begin{tikzpicture}
        \draw (-0.5\columnwidth,-0.2)--(-0.5\columnwidth,0)--(0.5\columnwidth,0)--(0.5\columnwidth,-0.2);
        \fill[white] (-0.5#2-5pt,-1pt) rectangle (0.5#2+5pt,1pt);
        \tikzlabel{0}{-0.4}{\text{\small \textbf{Example \thesection.\theexample} --- #1}}
    \end{tikzpicture}}
    %
    {\begin{tikzpicture}
        \draw (-0.5\columnwidth,0.2) -- (-0.5\columnwidth,0) -- (0.5\columnwidth,0) -- (0.5\columnwidth,0.2);
    \end{tikzpicture}}

非常感谢。

我的建议是使用 tcolorbox 而不是自己绘制框架,但如果您必须使用 tikz,只需为标题使用白色背景即可。

请注意,您的代码会产生大量框溢出警告。您必须考虑缩进并且绘制列框不合适,因为您需要额外两倍于 tikz 线宽度的一半。我只是将宽度减小到 .49\columnwidth,但您也可以在计算中考虑线的宽度。

还要注意 --- 周围的间距。如果你之前不阻止宏吞掉space,它就不会居中。

\documentclass{article}

\usepackage{tikz}
\newcounter{example}


\newenvironment{example}[1]{%
  \refstepcounter{example}%
  \bigskip
  \noindent%
  \begin{tikzpicture}
    \draw (-0.49\columnwidth,-0.2)--(-0.49\columnwidth,0)--(0.49\columnwidth,0)--(0.49\columnwidth,-0.2);
    \node[fill=white,font=\small\bfseries] at (0,-1pt) {Example \thesection.\theexample{} --- #1};
  \end{tikzpicture}%
  \par%
}{%
  \par%
  \noindent%
  \begin{tikzpicture}
    \draw (-0.49\columnwidth,0.2) -- (-0.49\columnwidth,0) -- (0.49\columnwidth,0) -- (0.49\columnwidth,0.2);
  \end{tikzpicture}%
  \par%
}


\begin{document}


\begin{example}{test}
content...
\end{example}


\end{document}