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

5

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

1
  • Works like a charm, especially when within a custom class and defining a function where I don't have control over incoming argument data. Aug 8, 2022 at 12:08
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
    Jun 28, 2017 at 10:49
  • @egreg sorry, forgot to add group
    – Uko
    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 .