# How to float something right even if it wraps down a line?

I have a situation where I have some data in section headings (and sometimes normal paragraphs} that needs to be:

• floated right
• not split across lines

I was able to accomplish this for most cases with \hfill and \mbox{}, but in the event that the mbox'ed item gets sent to the next line, the hfill is left on the previous line. Here is some sample code that duplicates the problem:

\documentclass[a6paper]{scrartcl}
\usepackage{geometry}

\newcommand*\myref[1]{\hfill\mbox{\normalfont#1}}
\newcommand*\mysection[2]{\section*{#1\myref{#2}}}

\begin{document}

\mysection{Title One}{Ref Name NNN}

Lorem ipsum dolor sit amet, consectetuer adipiscing elit.

\mysection{Much Longer Title Two}{Ref Name NNN}

Ut purus elit, vestibulum ut, placerat ac, adipiscing vitae, felis.

\end{document}


This is producing something like this for me:

How can I get items that wrap like that to float right again?

Alternatively, is there a better way to put the content there? Semantically they don't have to go together. If the content was outside of the section heading but floated up into any available right side free space (not to exceed the top of the previous item) that would be awesome.

-

If a break is taken at \hfill, it will disappear at the beginning of the following line. With \hspace{0.5em} we introduce a feasible break point; then \hspace*{\fill} won't disappear at the start of the line if the break is taken at that space.

\documentclass[a6paper]{scrartcl}
\usepackage{geometry}

\newcommand*\myref[1]{\hspace{.5em}\hspace*{\fill}\mbox{\normalfont#1}}
\newcommand*\mysection[2]{\section*{#1\myref{#2}}}

\begin{document}

\mysection{Title One}{Ref Name NNN}

Lorem ipsum dolor sit amet, consectetuer adipiscing elit.

\mysection{Much Longer Title Two}{Ref Name NNN}

Ut purus elit, vestibulum ut, placerat ac, adipiscing vitae, felis.

\end{document}


-
you might want to insert a "minimum" space before the penalty -- if the two parts happen to almost exactly fill the line, the \fill can essentially disappear. – barbara beeton Mar 7 '14 at 21:08
@barbarabeeton You're right! Changed accordingly. – egreg Mar 7 '14 at 21:13