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

horizontal alignmentspacing

I a chat discussion it was suggested that \hspace*{\fill} (with a space before it to allow for a line break) was sufficient to always get the text following aligned to the right. And indeed, it is aligned to the right.

However, in one case it is inserting an additional line break where one should not be required as illustrated by the last example here. I want the text bumped to the next line if and only if (iff ) there is no room:

enter image description here

If I remove the space before the \hspace*{\fill}, there are cases (second and third) where a new line should have been inserted but is not:

enter image description here

Related Question:

I have tried the suggestions at the related question and:

  • Martin Scharrer's suggestion of using \hbox{}\hfill results in the text being on the left for the last case.
  • Herbert's \When macro exhibits a similar problem for the last case.
  • Thorsten Donig's \signed macro does yield the correct number of lines, but portions of the file name for the middle two cases show up on the second line when they easily fit in the first line.

Notes:

I believe that this is unrelated to the problem, as I was able to reproduce the problem without it. But, am mentioning it here in case it causes an issue with the proposed solution.

I am using \texttt for the file name. This resulted in an additional complication which I initially thought was the cause of the problem. So, my actual use case is commented out below and it incorporates a solution from


Code:

\documentclass{article}
\usepackage[paperwidth=7.0cm,showframe]{geometry}
\usepackage{xcolor}
\usepackage{xparse}


\newcommand*{\FillLine}[2]{%
\noindent\parbox{\linewidth}{%
    \raggedright
    File:~#2 % <-- Need space here
    %Space before \hspace* allows for a break before it
    \hspace*{\fill}\texttt{\small CONFIDENTIAL}% 
}%
}

%\newcommand*{\EnableHyphenationInTexttt}{\hyphenchar\font=45\relax}
%
%\newcommand*{\FillLine}[2]{%
%    \noindent\parbox{\linewidth}{%
%       \raggedright
%       File:~\texttt{\EnableHyphenationInTexttt#2} % <-- Need space here
%       %Space before \hspace* allows for a break before it
%       \hspace*{\fill}\texttt{\small CONFIDENTIAL}% 
%    }%
%}

\begin{document}
\FillLine{Name}{Value}

\bigskip
\FillLine{Name}{A-Long-Value}

\bigskip
\FillLine{Name}{iiiiiii-iiiii-iiiiiii}

\bigskip
\FillLine{Name}{Some-Really-Really-Long-Value}
\end{document}

Best Answer

You can encourage TeX not to break the lines with \linepenalty

enter image description here

\newcommand*{\FillLine}[2]{%
\noindent\parbox{\linewidth}{%
    \rightskip\fill\parfillskip-\rightskip
    \linepenalty100
    \exhyphenpenalty0
    File:~#2\linebreak[0] % <-- Need space here
    %Space before \hspace* allows for a break before it
    \hspace*{\fill}\texttt{\small CONFIDENTIAL}% 
}%
}
Related Question