我想定义一个新环境,如果内容可以排版在一行上,则使内容居中,但如果内容需要排版在多行上,则使内容两端对齐。
\documentclass{article}
\usepackage{lipsum}
\newenvironment{mycenter}{\noindent}{}
\begin{document}
\begin{mycenter}%
This should be centered since it is a single line
\end{mycenter}
\begin{mycenter}%
This should be justified since it is multiple lines. \lipsum[1]
\end{mycenter}
\end{document}
我有一个复杂的想法,使用Environ
包裹来捕捉内容,然后将它们粘在盒子里并尝试检查盒子的高度。有没有更简单的方法?
答案1
\documentclass{article}
\usepackage{lipsum}
\newenvironment{mycenter}{\vbox\bgroup\bgroup
\parindent0pt\relax}{%
\par
\ifnum\prevgraf=1
\setbox0\lastbox
\noindent\hskip\parfillskip\hbox{\unhbox0}\par
\fi
\egroup\egroup}
\begin{document}
\begin{mycenter}%
This should be centered since it is a single line
\end{mycenter}
\begin{mycenter}%
This should be justified since it is multiple lines. \lipsum[1]
\end{mycenter}
\end{document}