[Tex/LaTex] Bump right-aligned text to next line if no room

horizontal alignment

I'm trying to write a simple command that will put some text right-aligned, but bump it to the next line if it doesn't fit well. Since an image is worth a thousand words:

example

The "Normally" case is correct – that's what it should do. But if the line gets too long, I'd like it to bump to the next line, as shown in "Desired". Currently, what I have does "Failure". Here's what I've come up with so far:

\newcommand{\when}[1]{\hfill\mbox{\textit{#1}}}

Note: I had to manually push the "Desired" to the right with a \\ \strut, but I'd like the macro to automate this, and to not have to pick out the cases where I need to do that by hand. (Simply adding \\ \strut to the macro results in the wrong output for the "Normally" case.)

Best Answer

There are some cases where both Herbert's and Thorsten Donig's answers can be problematic. One situation is when the stuff at the end needs a new line, but that line also starts a new page. This makes an especially awkward widow, since it would start a page flushed right. The other potential problem involves hyphenation. Herbert's solution does not work properly on lines that are started by hyphenated words (it starts a new line even if there is enough space to flush right), and Thorsten Donig's solution seems to break hyphenation of the preceding word.

\documentclass{article}
\usepackage[papersize={10cm,5cm},textwidth=5cm,vmargin=5mm]{geometry}
\usepackage{calc,parskip}
\newcommand{\atend}{\makebox[2em][l]{\leaders\hbox{b}\hfill}}
\newcommand{\fillpage}{\vspace*{\textheight}\vspace*{-2\baselineskip}\vspace{-\parskip}}
\overfullrule=2pt
\pagestyle{empty}

\begin{document}
\fillpage

\newcommand\comfyfill[1]{{% = Herbert's \When
  \leftskip=0ptplus1fil\rightskip=-\leftskip\parfillskip=\leftskip
  \hfill \phantom{ } \textit{\mbox{#1}}\par}}

\makebox[\textwidth-2em]{\hrulefill a}\comfyfill{\atend}

\makebox[\textwidth-\widthof{charac- }]{\hrulefill} characterisation \comfyfill{\atend}

\makebox[\textwidth-\widthof{charac- }]{\hrulefill} charac- terisation \comfyfill{\atend}

\newpage
\fillpage

\renewcommand*{\comfyfill}[1]{% = Thorsten Donig's \signed
  \unskip\hspace*{1em plus 1fill}
  \nolinebreak[3]%
  \hspace*{\fill}\mbox{\emph{#1}}
  \parfillskip0pt\par
}

\makebox[\textwidth-2em]{\hrulefill a}\comfyfill{\atend}

\makebox[\textwidth-\widthof{charac- }]{\hrulefill} characterisation \comfyfill{\atend}

\makebox[\textwidth-\widthof{charac- }]{\hrulefill} charac- terisation \comfyfill{\atend}

\end{document}

Here is the output from Herbert's solution: Herbert's \When

An here is the output from Thorsten Donig's: enter image description here

Related Question