
我試圖將逗號分隔的清單儲存到鍵值屬性中以便稍後使用,但我無法讓它正常工作。
我不太明白 Latex 如何解析 keyval 參數,但我的猜測是它將參數作為純文字處理。
這是我目前擁有的程式碼:
\documentclass{article}
\usepackage{expl3}
\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentCommand { \getvmeta } { m } { \prop_item:cn { g_rvnlatex_doc_prop } { #1 } }
\NewDocumentCommand { \setvmeta } { m m } { \prop_gput:cnV { g_rvnlatex_doc_prop } { #1 } #2 }
\keys_define:nn { ravenhill/latex/meta } {
author .clist_set:N = \l_rvnlatex_author_clist ,
}
\NewDocumentCommand { \setup } { m } {
\group_begin:
\prop_new:c { g_rvnlatex_doc_prop }
\keys_set:nn { ravenhill/latex/meta } { #1 }
\setvmeta { author } { \l_rvnlatex_author_clist }
\group_end:
}
\NewDocumentCommand { \authorblock } { } {
\clist_new:N \l__authblock_authcopy_clist
\clist_set:Nn \l__authblock_authcopy_clist { \getvmeta { author } }
\clist_use:Nnnn \l__authblock_authcopy_clist { ~and~ } { ,~ } { ,~and~ }
}
\ExplSyntaxOff
\setup {
author = {John, Bob},
}
\begin{document}
\authorblock
\end{document}
我得到的結果John,Bob
是John and Bob
.
我有什麼遺漏的嗎?
答案1
你的猜測是正確的。當你使用
\clist_set:Nn \l__authblock_authcopy_clist { \getvmeta { author } }
clist 解析器只看到哪\getvmeta { author }
一個,就其而言,與getvmeta { author }
,因為它沒有逗號。
要公開傳遞給鍵的逗號列表author
,您必須擴展\getvmeta{author}
其內容。為此,請使用\clist_set:Nx
(x
表示窮舉擴展)。它會起作用,因為\prop_item:Nn
透過擴充功能起作用,因此它可以在擴充上下文中傳回該項目(您也必須\getvmeta
透過使用 聲明它來允許擴充)。\NewExpandableDocumentCommand
另外,將變數宣告移到使用者層級命令之外:您永遠不知道是否有人會嘗試使用(例如\setup
兩次),如果他們這樣做,您的程式碼在嘗試聲明已存在的變數時將會出錯。
\documentclass{article}
\usepackage{expl3}
\usepackage{xparse}
\ExplSyntaxOn
\NewExpandableDocumentCommand { \getvmeta } { m }
{ \prop_item:Nn \g_rvnlatex_doc_prop {#1} }
\NewDocumentCommand { \setvmeta } { m m }
{ \prop_gput:NnV \g_rvnlatex_doc_prop {#1} #2 }
\keys_define:nn { ravenhill/latex/meta }
{ author .clist_set:N = \l_rvnlatex_author_clist }
\prop_new:N \g_rvnlatex_doc_prop
\clist_new:N \l__authblock_authcopy_clist
\NewDocumentCommand \setup { m }
{
\group_begin:
\keys_set:nn { ravenhill/latex/meta } {#1}
\setvmeta { author } { \l_rvnlatex_author_clist }
\group_end:
}
\NewDocumentCommand \authorblock { }
{
\clist_set:Nx \l__authblock_authcopy_clist { \getvmeta { author } }
\clist_use:Nnnn \l__authblock_authcopy_clist { ~and~ } { ,~ } { ,~and~ }
}
\ExplSyntaxOff
\setup{author = {John, Bob}}
\begin{document}
\authorblock
\end{document}