我想要一个命令来接收一些文本并以某种样式打印出来等。我还想确保打印的行不会有强制换行符,即如果有人这样做
\mymacro{first paragraph \\ second paragraph}
我想打印first paragraph second paragraph
并使其遵循基于线宽的正常换行
答案1
在宏定义设置的某个本地组中
\def\\{\relax\ifhmode\unskip\fi\space\ignorespaces}
这样a\\b a \\ b
每个行为a b
都会\\
删除其自身之前的任何空格,添加一个空格,然后忽略任何后续空格。
大卫
答案2
递归来过滤掉\\
。
\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}
如果你想要一个不会耗尽堆栈的版本,那么
\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}
答案3
我还发现了这个解决方法,它重新定义\\
为生成一个空字符串
\newcommand\mymacro[1]{ {\let \\ \empty #1} }