
SE,最近我正在玩弄expl3
一點xparse
,我遇到了以下問題:我想創建一個命令來創建一個新命令 - 類似於這個帖子。只要第二個命令沒有任何參數,這並不難;嘗試建立一個接受參數的命令有點棘手。
到目前為止我得到了什麼:
\documentclass{article}
\usepackage{xparse}
\NewDocumentCommand\test{ m}
{
\NewDocumentCommand#1 {m}
{My name is \string#1, king of kings}
}
\begin{document}
\test{\ozymandias}
\ozymandias{\manthano}
\end{document}
這個輸出My name is ozymandias, king of kings
,給了正確的十四行詩,但不是我想要的。我知道問題出在哪裡,但我只是不知道該如何解決它:)
答案1
我想知道\string#1
裡面的情況。
裡面的新指令可以建構為
\expandafter\NewDocumentCommand\csname #1\endcsname{...}{....}
即必須先建構新序列的名稱\expandafter
(先給予名稱,然後\NewDocumentCommand
執行操作)。對於傳統\newcommand
等也必須採取相同的方法\renewcommand
。
但是,該\test
命令必須用作\test{ozymandias}
,不帶\
!
請注意,有必要使用##1
存取內部巨集的第一個參數(如果需要的話),後續參數用##2
等編號。
\documentclass{article}
\usepackage{xparse}
\NewDocumentCommand{\manthano}{}{Manthano}
\NewDocumentCommand\test{ m}
{%
\expandafter\NewDocumentCommand\csname #1\endcsname{m}{%
My name is ##1, king of kings%
}
}
\begin{document}
\test{ozymandias}
\ozymandias{\manthano}
\end{document}
編輯:要使用\test
with \
,您必須使命令適應
\makeatletter
\NewDocumentCommand\test{ m}
{%
\expandafter\NewDocumentCommand\csname\expandafter\@gobble\string #1\endcsname{m}{%
My name is ##1, king of kings%
}
}
\makeatother