8

I want to have a command that receives some text and prints it out in a certain style, etc. I also want to ensure that the printed line will not have forced linebreaks i.e. if someone does

\mymacro{first paragraph \\ second paragraph}

I want to print first paragraph second paragraph and make it follow the normal line breaking based on the line width

3 Answers 3

6

within some local group set up by your macro define

\def\\{\relax\ifhmode\unskip\fi\space\ignorespaces}

so that a\\b a \\ b each act like a b as \\ will remove any space before itself, add one space and then ignore any following spaces.

David

3
  • Works like a charm, especially when within a custom class and defining a function where I don't have control over incoming argument data. Commented Aug 8, 2022 at 12:08
  • I couldn't get this to work, could you possibly provide an example of it's use?
    – crobar
    Commented Jun 10 at 10:22
  • @crobar rather than me guess what you did wrong, better if you make a small complete example and ask a new question referencing this one Commented Jun 10 at 10:37
2

A recursion to filter out \\.

\documentclass[10pt]{article}
\newcommand\mymacro[1]{\mymacroaux#1\\\relax}
\long\def\mymacroaux#1\\#2\relax{%
  #1\ifx\relax#2\else\unskip\ \mymacroaux\ignorespaces#2\relax\fi}
\begin{document}
\mymacro{first paragraph \\ second paragraph}X

\mymacro{first paragraph \\ second paragraph} X

\mymacro{first paragraph \\ second paragraph\\3rd paragraph }X

\mymacro{first paragraph 

second paragraph\\3rd paragraph 

Fourth para} X
\end{document}

enter image description here

If you wanted a version that did not deplete the stack, then

\documentclass[10pt]{article}
\newcommand\mymacro[1]{\mymacroaux#1\\\relax}
\long\def\mymacroaux#1\\#2\relax{%
  #1%
  \ifx\relax#2\relax\def\next{}%
  \else\unskip\ \def\next{\mymacroaux\ignorespaces#2\relax}%
  \fi%
  \next%
}
\begin{document}
\mymacro{first paragraph \\ second paragraph}X

\mymacro{first paragraph \\ second paragraph} X

\mymacro{first paragraph \\ second paragraph\\3rd paragraph }X

\mymacro{first paragraph 

second paragraph\\3rd paragraph 

Fourth para} X
\end{document}
2

I also found this workaround which redefines \\ to produce an empty string

\newcommand\mymacro[1]{ {\let \\ \empty #1} }
2
  • Well, this will disable \\ forever (in the current group). Moreover you'll not be removing excess spaces.
    – egreg
    Commented Jun 28, 2017 at 10:49
  • @egreg sorry, forgot to add group
    – Uko
    Commented Jun 29, 2017 at 6:21

You must log in to answer this question.

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