我定义了一个命令,在文本周围画一个框,并可选择在这个框内放置另一个字符。
命令如下(与 MWE 一起):
\documentclass{minimal}
\newlength{\xboxh} % Sets a macro for the height
\newlength{\xboxw} % and for the width
\newcommand{\putbox}[2][]{
\settoheight{\xboxh}{#2}% Gets the height
\settowidth{\xboxw}{#2}% and width of the input
\frame{\phantom{\rule{\xboxw}{\xboxh}}}% And draws a frame around it
\setbox0=\hbox{#1\unskip}\ifdim\wd0=0pt% And if the optional argument is not empty
\relax
\else
\hspace{-\xboxw}#1% Prints it too
\fi\relax
}
\begin{document}
Some text to \putbox{Z} fill up space \par
Some text to \putbox[Z]{Z} fill up space \par
Some text to \(\putbox{Z}\) fill up space
Some text to \(\putbox[Z]{Z}\) fill up space
\end{document}
该命令在文本和数学模式下的行为应该相同。但事实并非如此。在文本模式下使用时,该命令会在框前后输出不需要的空格,并且还会错放框的内容(如果有):
如何修复命令的间距问题?
答案1
您的定义中有一个虚假的空间\putbox
:
\documentclass{article}
\newlength{\xboxh} % Sets a macro for the height
\newlength{\xboxw} % and for the width
\newcommand{\putbox}[2][]{% <------------------- spurious space
\settoheight{\xboxh}{#2}% Gets the height
\settowidth{\xboxw}{#2}% and width of the input
\frame{\phantom{\rule{\xboxw}{\xboxh}}}% And draws a frame around it
\setbox0=\hbox{#1\unskip}\ifdim\wd0=0pt% And if the optional argument is not empty
\relax
\else
\hspace{-\xboxw}#1% Prints it too
\fi\relax
}
\begin{document}
Some text to \putbox{Z} fill up space
Some text to \putbox[Z]{Z} fill up space
Some text to \(\putbox{Z}\) fill up space
Some text to \(\putbox[Z]{Z}\) fill up space
Width of Z: \setbox0=\hbox{Z}\the\wd0
Width of $Z$: \setbox0=\hbox{$Z$}\the\wd0
\end{document}
注意\hbox
以文本模式设置其内容。
答案2
您不需要测量;此外,您忘记了深度。
\documentclass{article}
\usepackage{amsmath}
\usepackage{xparse}
\makeatletter
\NewDocumentCommand{\putbox}{sm}{%
\begingroup
\ifmmode\@tempswatrue\else\@tempswafalse\fi
\setlength{\fboxsep}{-\fboxrule}%
\fbox{\IfBooleanTF{#1}{\po@math{#2}}{\po@math{\phantom{#2}}}}%
\endgroup
}
\newcommand{\po@math}[1]{\if@tempswa\ensuremath{#1}\else#1\fi}
\makeatother
\begin{document}
Some text to \putbox{Z} fill up space
Some text to \putbox*{Z} fill up space
Some text to \putbox*{g} fill up space
Some text to \(\putbox{Z}\) fill up space
Some text to \(\putbox*{Z}\) fill up space
Some text to \(\putbox*{g}\) fill up space
\end{document}
如您所见,如果在数学模式下调用宏,则参数也会在数学模式下排版。*
-variant 打印符号。