请考虑以下 MWE:
\documentclass{article}
\newcommand{\mymargin}{\hspace*{3em}}
\newcommand{\innerbox}[1]{\mymargin\fbox{#1}\mymargin}
\newcommand{\outerbox}[1]{\fbox{#1}}
\begin{document}
test \innerbox{Hello} test% OK
test \outerbox{\innerbox{Hello} test \innerbox{Hello} test \innerbox{Hello}}% I don't want space at beginning and end of box
test \outerbox{\fbox{Hello}\mymargin{} test \innerbox{Hello} test \mymargin\fbox{Hello}}% what i'd like
\end{document}
(实际上,盒子的定义更加复杂,但我认为这不会改变任何逻辑)
我希望使用\innerbox
inside\outerbox
不会在框的开始和结束处产生空格。
我想我应该扩展参数#1
(一旦去掉了不必要的空格)\outerbox
并检测第一个和最后一个标记是否相等\mymargin
,然后进行必要的更改,但我真的不知道该怎么做。有什么想法吗?
答案1
您可以检查(忽略空格)的参数中的第一个标记是否\outerbox
是\innerbox
,在这种情况下,插入一个负空格进行补偿。
最后,您可以递归地删除所有粘合节点。
\documentclass{article}
\newcommand{\mymarginwidth}{3em}
\newcommand{\mymargin}{\hspace*{\mymarginwidth}}
\newcommand{\negmymargin}{\hspace*{-\mymarginwidth}}
\newcommand{\innerbox}[1]{\mymargin\fbox{#1}\mymargin}
\makeatletter
\newcommand{\outerbox}[1]{%
\fbox{%
\@ifnextchar\innerbox{\negmymargin}{}#1%
\forever@unskip
}%
}
\newcommand{\forever@unskip}{%
\ifnum\lastnodetype=11
\expandafter\unskip\expandafter\forever@unskip
\fi
}
\makeatother
\begin{document}
test \innerbox{Hello} test
test \outerbox{\innerbox{Hello} test \innerbox{Hello} test \innerbox{Hello}}
test \outerbox{\fbox{Hello}\mymargin{} test \innerbox{Hello} test \mymargin\fbox{Hello}}
test \outerbox{test \innerbox{Hello} test \innerbox{Hello}}
test \outerbox{\innerbox{Hello} test \innerbox{Hello} test}
test \outerbox{ test \innerbox{Hello} test \innerbox{Hello} }
test \outerbox{ \innerbox{Hello} test \innerbox{Hello} test }
\end{document}
答案2
此版本省略了位于任何水平盒子中的空格\innerbox
,而不仅仅是\outerbox
\documentclass{article}
\newcommand{\mymargin}{\hspace*{3em}}
\newcommand{\innerbox}[1]{\ifhmode\ifinner\else\mymargin\fi\fi\fbox{#1}\ifhmode\ifinner\else\mymargin\fi\fi}
\newcommand{\outerbox}[1]{\fbox{#1}}
\begin{document}
test \innerbox{Hello} test% OK
test \outerbox{\innerbox{Hello} test \innerbox{Hello} test \innerbox{Hello}}% I don't want space at beginning and end of box
test \outerbox{\fbox{Hello}\mymargin{} test \innerbox{Hello} test \mymargin\fbox{Hello}}% what i'd like
\end{document}
egreg 指出,你可能不是你想要的样子,所以......
\documentclass{article}
\newcommand{\mymargin}{\hspace*{3em}}
\newcommand{\innerbox}[1]{\ifhmode\ifnum\lastpenalty=-1\else\mymargin\fi\fi\fbox{#1}\mymargin}
\newcommand{\outerbox}[1]{\fbox{\penalty-1#1\unskip\unskip}}
\begin{document}
test \innerbox{Hello} test% OK
test \outerbox{\innerbox{Hello} test \innerbox{Hello} test \innerbox{Hello}}% I don't want space at beginning and end of box
test \outerbox{\fbox{Hello}\mymargin{} test \innerbox{Hello} test \mymargin\fbox{Hello}}% what i'd like
\end{document}