是否可以定义一个命令,根据其参数文本是否占用多行来采取不同的操作?
我希望如果文本块只有一行则居中,否则两端对齐。
答案1
像这样吗?
\documentclass{article}
\usepackage[showframe]{geometry}% just to make it easy to see the effect
\makeatletter
\def\centerorjustify#1{%
\setbox\@tempboxa\hbox{#1}%
\ifdim\wd\@tempboxa>\linewidth
#1%
\else
\begin{center}%
#1%
\end{center}%
\fi
}
\begin{document}
\centerorjustify{Hello}
\centerorjustify{Hello world}
\centerorjustify{A long text that will be a little shorter than the text width.}
\centerorjustify{A longer text that will be longer than a line so that we can see the effect of the macro. Yeah, I don't know what else to type in here}
\end{document}
该宏将内容放入其中,\hbox
并将其宽度与之进行比较,\linewdith
如果较短则将其居中。
答案2
只是为了好玩:
你可能会误用 caption 包来实现类似的行为
\documentclass{article}
\usepackage{caption}
\usepackage{newfloat}
\DeclareCaptionFormat{empty}{#3}
\DeclareFloatingEnvironment{my}
\captionsetup[my]{format=empty}
\begin{document}
\captionof{my}{one line}
\captionof{my}{longt text over multiple lines with much longer text and even longer text so that it stretches over multiple lines}
\end{document}