2

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

2

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

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}
0

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.