这是我第一次尝试宏keyval
。我有一个更复杂的宏,可以归结为下面给出的 MWE。这个想法是将一个段落排版为多列,其中列数是一个可选的命名参数。当我指定列数时,它就可以工作,但是当没有指定任何选项时,我希望默认为一列。
\documentclass{article}
\usepackage{keyval}
\usepackage{lipsum}
\usepackage{multicol}
\makeatletter
\def\printparagraph{\@ifnextchar[\@printparagraph{\@printparagraph[]}}
\def\@printparagraph[#1]{{\setkeys{pp}{#1}}}
\define@key{pp}{columns}{\begin{multicols}{#1}\lipsum[1]\end{multicols}}
\makeatother
\begin{document}
\printparagraph % this doesn't work, doesn't print anything!
\printparagraph[columns=2] % this works
\printparagraph[columns=3] % this works
\end{document}
答案1
您只需要在默认情况下打印虚拟文本:
\documentclass{article}
\usepackage{keyval}
\usepackage{lipsum}
\usepackage{multicol}
\makeatletter
\def\printparagraph{\@ifnextchar[\@printparagraph{\lipsum}}
\def\@printparagraph[#1]{{\setkeys{pp}{#1}}}
\define@key{pp}{columns}{\begin{multicols}{#1}\lipsum[1]\end{multicols}}
\makeatother
\begin{document}
\printparagraph %
\printparagraph[columns=2] % this works
\printparagraph[columns=3] % this works
\end{document}
答案2
\begin{multicols{1}
不起作用,但除此之外:我不会将多列放在键定义中,而只使用它来存储值。然后很容易设置默认值(我也会使用 l3keys 而不是 keyval,但这是另一个问题):
\documentclass{article}
\usepackage{keyval}
\usepackage{lipsum}
\usepackage{multicol}
\makeatletter
\newcount\my@columns@cnt
\def\printparagraph{\@ifnextchar[\@printparagraph{\@printparagraph[]}}
\def\@printparagraph[#1]{{%
\setkeys{pp}{columns,#1}%
\ifnum\my@columns@cnt=1
\expandafter\@firstoftwo
\else
\expandafter\@secondoftwo
\fi
{\lipsum[1]}
{\begin{multicols}{\the\my@columns@cnt}\lipsum[1]\end{multicols}}}}
\define@key{pp}{columns}[1]{\my@columns@cnt=#1\relax}
\makeatother
\begin{document}
\printparagraph % this doesn't work, doesn't print anything!
\printparagraph[columns=2] % this works
\printparagraph[columns=3] % this works
\end{document}