2

Is it possible to define a command that takes different actions based on whether the text of its argument will occupy more than one line?

I want to have a block of text that is centered if it's only one line and justified otherwise.

  • 3
    \def\macro#1{\setbox0=\hbox{#1}\ifdim\wd0<\textwidth <centered>\else<justified>\fi} – Manuel Apr 10 '18 at 13:55
5

Something like this?

enter image description here

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

The macro puts the content in an \hbox and compares its width with \linewdith and centers if it is shorter.

5

Just for fun:

you can mis-use the caption package for a similar behaviour

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

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.