我如何强制“描述”环境中的标签保持在边距内?

我如何强制“描述”环境中的标签保持在边距内?

中的标签description默认超出边距。我尝试使用labelwidth=\widthof{Described Item} + 2.5\labelsep,效果很好。但是,我想description自动处理对齐并且不超过边距,就像enumerate和一样itemize

所需的输出显示在这里,但我希望它是自动的,而不是通过手动调整labelwidth

在此处输入图片描述

\documentclass[]{report}


\usepackage{enumitem}

\usepackage{calc}
\usepackage[showframe=true]{geometry}

\begin{document}


This is an example of a description list, which shows how elegant the \texttt{description} environment. Note how the option entry \texttt{labelwidth=$\backslash$widthof$\lbrace$Described Item$\rbrace$ + 2.5$\backslash$labelsep} aligns the description item to the paragraph

\begin{description}[labelwidth=\widthof{Described Item} + 2.5\labelsep, labelsep=5mm, align=right]
    \item[Described Item] The description
    \item[Described] The description
\end{description}


See how the description labels go beyond the margin:

\begin{description}[itemindent=0mm, labelsep=3mm, align=right]
    \item[Described Item] The description
    \item[Described] The description
\end{description}



\end{document}

答案1

环境mydescription运行文本两次。第一次运行(在保存框内)计算所需的labelwidth。警告,任何全局更改都将泄露。可以根据具体情况禁用这些。

请注意,宽度是使用粗体字体来测量的。

\documentclass[]{report}
\usepackage{enumitem}

%\usepackage{calc}
\usepackage[showframe=true]{geometry}
\usepackage{environ}

\newlength{\descwidth}% reserve global name

\NewEnviron{mydescription}[1][]{% #1 = optional parmeters for description
  \global\descwidth=0pt
  \sbox1{\def\item[##1]{\sbox0{\textbf{##1}}%
      \ifdim\descwidth<\wd0 \global\descwidth=\wd0\fi}%
    \let\stepcounter=\relax% % disable global change macros
    \let\refstepcounter=\relax
    \BODY}% compute maximum width
  \description[labelwidth=\descwidth, align=right, #1]
    \BODY
  \enddescription}

\begin{document}

\begin{mydescription}[labelsep=5mm]
    \item[Described Item] The description\footnote{test}
    \item[Described] The description
\end{mydescription}

\end{document}

演示


此解决方案需要运行两次,并影响所有mydescription环境。它会缓慢增加标签宽度,然后将最终值保存到辅助文件中。下一次运行会读取此值\begin{document}

\documentclass[]{report}
\usepackage{enumitem}

%\usepackage{calc}
\usepackage[showframe=true]{geometry}

\newlength{\descwidth}
\setlength{\descwidth}{0pt}
\makeatletter
\AtEndDocument{\write\@auxout{\string\global\string\descwidth=\the\descwidth}}
\makeatother

\newenvironment{mydescription}[1][]% #1 = optional parmeters for description
{\description[labelwidth=\descwidth, align=right, #1]
   \let\DefaultItem=\item
   \def\item[##1]{\sbox0{\textbf{##1}}%
     \ifdim\descwidth<\wd0 \global\descwidth=\wd0\fi
     \DefaultItem[##1]}%
}{\enddescription}

\begin{document}

\begin{mydescription}[labelsep=5mm]
    \item[Described Item] The description\footnote{test}
    \item[Described] The description
\end{mydescription}

\end{document}

相关内容