4

I want to write two words on the right of the page. sometext TWO WORDS so I put a \hfill just before and because I don't want any break in the two words, I use \mbox:

sometext \hfill \mbox{TWO WORDS}

But sometimes I have a really long text before \hfill and so a line break is put but always after the \hfill. So TWO WORDS stay on the left.

I've tried using ragged possibility without any success.

So how can I break before the \hfill or justify part of the sentence to the right?

5

1 Answer 1

9

It's important to remember that \hspace and \hfill "collapse to zero" at the beginning of a line. \hspace*, on the other hand, does not. Others have already mentioned this, but there are few more subtleties to take into account.

\newcommand\OnRight[1]{%
  \unskip           % (1)
  \hfill            % (2)
  \penalty100\relax % (3)
  \hspace*{0.5em}%    (4)
  \hspace*{\fill}%    (5)
  \mbox{#1}%          (6)
}
  1. prevent leading spaces from affecting output
  2. don't set the current line with justification
  3. prefer line-breaks to overfull lines
  4. a default "hard space" that needs to be included
  5. the pushing-right flexible space
  6. the unbreakable content itself

Minimal example below that demonstrates some (not all) of these features.

\documentclass{article}
\newcommand\OnRight[1]{%
  \unskip\hfill\penalty100\relax\hspace*{0.5em}\hspace*{\fill}\mbox{#1}%
}
\begin{document}
\begin{itemize}
  \item a short line \OnRight{\fbox{abc xyz}}
  \item a single line that is longer but edging towards two but not quite \OnRight{\fbox{abc mno xyz}}
  \item a single line that is xx longer but edging towards two but not quite \OnRight{\fbox{abc mno xyz}}
  \item a single line that is extra longer but edging towards two but not quite \OnRight{\fbox{abc mno xyz}}
  \item a single line that is extra longer but edging towards two but not quite quite \OnRight{\fbox{abc mno xyz}}
\end{itemize}
\end{document}

Update: Ulrike suggests (I think) the following improvement:

\newcommand\OnRight[1]{%
  \begingroup
    \parfillskip=0pt\relax
    \unskip\hfil\penalty100\relax\hspace*{0.5em}\hfil\mbox{#1}%
    \par
  \endgroup
}

I am not entirely sure that you always want to insert \par in there, so I'll leave both solutions for now :)

1
  • 3
    You should also set (locally) \parfillskip to 0pt. Aug 20, 2015 at 8:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .