以下精彩文章对有关管理包选项的问题提供了以下答案:https://tex.stackexchange.com/a/707285/17200
\begin{filecontents*}[overwrite]{mypackage.sty}
% Preamble
\NeedsTeXFormat{LaTeX2e}[1994/06/01]
\ProvidesPackage{mypackage}[2024/01/01 MyPackage]
% Dependencies
\RequirePackage{pgfopts}
\RequirePackage{xparse}
\RequirePackage{xcolor}
\pgfkeys{/mypackage/.is family}
\def\mypackage@set#1{\pgfkeys{/mypackage,#1}}
\mypackage@set{
% storage
first-color/.store in=\mypackage@firstcolor,
second-color/.store in=\mypackage@secondcolor,
% default value
first-color=blue,
second-color=red,
mypackage@init/.style/.expanded={ % HERE
first-color=\mypackage@firstcolor,
second-color=\mypackage@secondcolor
}
}
\ProcessPgfPackageOptions{/mypackage}
\mypackage@set{
mypackage@init/.style/.expanded={ % HERE
first-color=\mypackage@firstcolor,
second-color=\mypackage@secondcolor
}
}
\NewDocumentCommand\newcolortheme{mm}{\mypackage@set{#1/.style={#2}}}
\NewDocumentCommand\printcolors{O{}}{%
\bgroup%
\mypackage@set{#1}%
\mypackage@firstcolor{} and \mypackage@secondcolor{}\par%
\egroup
}
\NewDocumentCommand\setcolors{m}{\mypackage@set{#1}}
\NewDocumentCommand\resetcolors{}{\mypackage@set{mypackage@init}}
\end{filecontents*}
\documentclass[preview=true,varwidth=true]{standalone}
\usepackage[first-color=green, second-color=yellow]{mypackage}
\newcolortheme{my theme}{first-color=brown, second-color=cyan}
% \setcolors{my theme/.style={first-color=brown, second-color=cyan}}
\begin{document}
\printcolors % Will print green and yellow
\printcolors[second-color=blue] % Will print green and blue
\printcolors % Will print green and yellow
\setcolors{second-color=black}
\printcolors % Will print green and black
\printcolors[first-color=purple] % Will print purple and black
\printcolors % Will print green and black
\setcolors{first-color=red}
\printcolors % Will print red and black
\setcolors{first-color=orange, second-color=pink}
\printcolors % Will print orange and pink
\resetcolors
\printcolors % Will print green and yellow
\printcolors[my theme] % Will print brown and cyan
\printcolors % Will print green and yellow
\setcolors{my theme}
\printcolors % Will print brown and cyan
\end{document}
问题:我想知道为什么mypackage@init
需要出现在之前和之后\ProcessPgfPackageOptions{/mypackage}
(在我注释的位置HERE
)?
附加问题:expanded
这是什么意思mypackage@init/.style/.expanded
/实现了什么?
答案1
第一个标记的位置不执行任何操作,除非有人使用包选项内的HERE
键(虽然我猜这不是有意的),只有第二个位置才是严格必要的,以设置颜色的默认值。mypackage@init
-handler.expanded
会pgfkeys
在将值传递给上面的键路径之前完全展开该值,因此 -handler.style
看不到宏\mypackage@firstcolor
或\mypackage@secondcolor
,而只能看到宏中存储的内容(因此在默认情况下是blue
和red
)。这样,无论何时mypackage@init
使用,颜色都会重置为加载包时有效的颜色。(如果省略了,.expanded
宏\mypackage@firstcolor
和\mypackage@secondcolor
将根据自身进行设置,因此\def\mypackage@firstcolor{\mypackage@firstcolor}
无论何时使用,都会建立一个无限循环)。