# Put mbox on the right even if a newline is just before it

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?

• – Ulrike Fischer Aug 20 '15 at 7:48
• @UlrikeFischer oops. I've made some research before asking the question but don't see this one. Thank you – Romain Picot Aug 20 '15 at 7:51
• One can't always find relevant answers. I had the advantage to know that it is there. – Ulrike Fischer Aug 20 '15 at 7:56
• – egreg Aug 20 '15 at 8:11
• I'd advise you to use @WillRobertson's solution, as that is way more stable than my "works-sometimes-but-not-always" solution. At least then you won't get any nasty surprises. – sodd Aug 20 '15 at 8:16

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 :)

• You should also set (locally) \parfillskip to 0pt. – Ulrike Fischer Aug 20 '15 at 8:01