在环境中放宽命令

在环境中放宽命令

需要设计一个可以打印一定长度的新环境。该环境在文档中多次使用,因此长度计算不止一次,导致错误“命令 #length# 已定义”。let\command\relax已尝试,但无用。MWE 是:

\documentclass[]{article}

%This is the environment
\newenvironment{relaxation}{
\newlength\mytmplen
\setlength\mytmplen{10pt}
\the\mytmplen
\let\mytmplen\relax
}
{}

\begin{document}

\begin{relaxation}
Runs fine, and pdf-output is also fine, when called once
\end{relaxation}

\begin{relaxation}
Shows error, but pdf-output is fine, when called again
\end{relaxation}

\end{document}

请注意,pdf 输出正常。编译器 (Texmaker) 显示错误,就是这样。任何帮助都值得感激。提前致谢。

编辑:为了完成,我想完成的事情在这里添加。创建一个新的块,它有一个标题、一个正文,以及一条分隔最后两个的线。线宽应等于较长的线宽,即标题/正文。因此,每次在环境中都会计算线宽(标题、正文和较长的线宽),并且该块在文本中出现多次。完整的工作示例是:

\documentclass[]{article}

\usepackage{environ}
\usepackage{tikz}

%This is the full environment
\NewEnviron{relaxation}[1]{
\newlength\tw\settowidth\tw{\textbf{#1}}
\newlength\bw\settowidth\bw{\BODY}

%Picking and assigning the lengthier one
\ifdim \tw > \bw
 \newlength{\lw}\settowidth{\lw}{\hspace{\tw}}
\else
 \newlength{\lw}\settowidth{\lw}{\hspace{\bw}}
\fi

%Trying to un-define
\let\bw\relax
\let\tw\relax

\begin{minipage}{\lw}
\textbf{#1}

\begin{tikzpicture}
\fill[rounded corners=0.1ex, fill=red] (0, 0) rectangle (\lw, 0.2ex) {};
\end{tikzpicture}
\let\lw\relax
%Trying to undefine

\BODY
\end{minipage}}

\begin{document}

\begin{relaxation}{Title}
Runs fine, and pdf-output is also fine, when called once
\end{relaxation}

\begin{relaxation}{Title}
Shows error, but pdf-output is fine, when called again
\end{relaxation}

\end{document}

如前所述,输出很好,但编译器显示错误。 ![在此处输入图片描述

答案1

为什么每次都要分配这些长度寄存器?

\documentclass[]{article}

\usepackage{environ}
\usepackage{tikz}

%This is the full environment
\newlength\bw
\newlength\lw
\newlength\tw

\NewEnviron{relaxation}[1]{%
  \settowidth\tw{\textbf{#1}}%
  \settowidth\bw{\BODY}%
  %Picking and assigning the lengthier one
  \ifdim \tw > \bw
    \setlength{\lw}{\tw}%
  \else
    \setlength{\lw}{\bw}%
  \fi
  \begin{minipage}{\lw}
  \textbf{#1}\par
  \begin{tikzpicture}
    \fill[rounded corners=0.1ex, fill=red] (0, 0) rectangle (\lw, 0.2ex) {};
  \end{tikzpicture}
  \BODY
  \end{minipage}%
}

\begin{document}

\begin{relaxation}{Title}
Runs fine, and pdf-output is also fine, when called once
\end{relaxation}

\bigskip

\begin{relaxation}{Title}
Shows error, but pdf-output is fine, when called again
\end{relaxation}

\end{document}

不是\settowidth{\lw}{\hspace{\tw}},但\setlength{\lw}{\tw}

当心未受保护的行尾可能会成为输出中不需要的空格。

在此处输入图片描述

相关内容