【问题标题】:Create new variable each time an environment in LaTeX is called每次调用 LaTeX 中的环境时创建新变量
【发布时间】:2020-10-06 18:02:05
【问题描述】:

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

当使用\newlength{\lengthname} 后跟\settowidth{\lengthname}{[length]} 只调用一次环境时,这相对容易。但是,一旦多次调用它,就必须定义不同的长度。我(诚然很差)的解决方法是在每次使用示例环境时传递不同长度的名称#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}}

非常感谢。

【问题讨论】:

  • 你能不能做一个minimal reproducible example 而不仅仅是一个代码片段?
  • 为什么每次调用环境都使用新的长度?为什么不能简单地重复使用同一个?
  • 无论如何,如果 tcolorbox 有一个定理库,为什么还要重新发明轮子?

标签: latex latex-environment


【解决方案1】:

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

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

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

\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}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    • 1970-01-01
    • 1970-01-01
    • 2015-04-14
    相关资源
    最近更新 更多