4

I am trying to create a macro which always places the text in its argument on the right side of the line and then the line should end.

For example:

Left-Text \mymacro{Right-Text} 

should have text on the left and then when the text is done $\box$ should be placed on the right, but on the same line (as long as it fits).

I have tried

\newcommand{\mymacro}[1]{\hfill \mbox{#1}}

which works fine provided that Right-Text fits on the last line of Left-Text.

However, if Right-Text gets moved to a new line then it appears on the left side.

For example:

\documentclass{amsart}
\begin{document}
Doesn't work 

Left Text 0123456789 Left Text 0123456789 Left Text 0123456789
\mymacro{Right Text} 

Works

Left Text 0123456789 Left Text 0123456789 Left Text 0123456789 Left Text 0123456789
\mymacro{Right Text} 

Works

Left Text 0123456789 Left Text 0123456789
\mymacro{Right Text} 

\end{document}
1
  • Welcome to TeX.SX! Please help us to help you and add a minimal working example (MWE) that illustrates your problem. It will be much easier for us to reproduce your situation and find out what the issue is when we see compilable code, starting with \documentclass{...} and ending with \end{document}.
    – cfr
    Commented Jul 6, 2014 at 3:20

1 Answer 1

3

The star form of \hspace avoids to get canceled at the start of a new line:

\newcommand*{\mymacro}[1]{\hspace*{\fill}\mbox{#1}\penalty-9999\relax}

The penalty allows a line break, but it does not force one (-10000) to avoid an underfull \hbox warning, if the paragraph ends after \mymacro.

5
  • Thanks! This seems to work perfectly. Out of curiosity, what is the difference between \newcommand* and \newcommand? Commented Jul 6, 2014 at 18:12
  • @NateAckerman: TeX complains, if the argument contains empty lines (\par tokens). Since the text for \mymacro is intended to be a small part of a paragraph, TeX can earlier complain, if the closing argument brace has been forgotten. Commented Jul 6, 2014 at 18:21
  • Thanks that is helpful. I was also curious about the more general differences between these commands. But I will ask this as a question. Commented Jul 6, 2014 at 20:38
  • @NateAckerman: What's the difference between \newcommand and \newcommand*? Commented Jul 6, 2014 at 20:44
  • Thanks. I found that link as I was about to write my question:) Commented Jul 6, 2014 at 23:37

You must log in to answer this question.

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