![\newkeycommand 中的兩個 \IfEq 導致失敗](https://rvso.com/image/348643/%5Cnewkeycommand%20%E4%B8%AD%E7%9A%84%E5%85%A9%E5%80%8B%20%5CIfEq%20%E5%B0%8E%E8%87%B4%E5%A4%B1%E6%95%97.png)
考慮這個 .tex 文件
\documentclass[10pt]{article}
\usepackage{MWE}
\MWESettings[X=8]{article}
\begin{document}
The answer is \name
\end{document}
MWE.sty 在哪裡
\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{MWE}
\RequirePackage{xstring}
\RequirePackage{keycommand}
\newkeycommand{\MWESettings}[X=1][1]
{
\IfEq{#1}{article} { \newcommand{\name}{article \commandkey{X}} } <-- Line A
\IfEq{#1}{news} { \newcommand{\name}{news \commandKey{X}} } <-- Line B
}
如果我 pdflatex .tex 文件,我會收到此錯誤:
See the LaTeX manual or LaTeX Companion for explanation.
Type H <return> for immediate help.
...
l.4 \begin{d
ocument}
我究竟做錯了什麼?
答案1
據我了解你的程式碼,你會喜歡的
\MWESettings[X=8]{article}
做
\newcommand{\name}{article 8}
儘管
\MWESettings[X=5]{news}
做
\newcommand{\name}{news 5}
你忘了「假分支」:它應該是
\IfEq{<string-a>}{<string-b>}{<true>}{<false>}
所以這有效。
\documentclass[10pt]{article}
\usepackage{xstring}
\usepackage{keycommand}
\newkeycommand{\MWESettings}[X=1][1]
{%
\IfEq{#1}{article}{\newcommand{\name}{article \commandkey{X}}}{}% <-- Line A
\IfEq{#1}{news} {\newcommand{\name}{news \commandkey{X}}}{}% <-- Line B
}
\MWESettings[X=8]{article}
\begin{document}
The answer is \name
\end{document}
另請注意,您在程式碼中引入了許多不需要的空格。
目前尚不清楚為什麼不直接使用#1
而不是文本\IfEq
,但我想這是一個簡化的範例。
不是我推薦的keycommand
。不同的實作xparse
:
\documentclass[10pt]{article}
\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentCommand{\MWESettings}{O{X=1}m}
{
\keys_set:nn { kreher/mwe } { #1 }
\cs_new:Npx \name
{
\str_case:nn { #2 }
{
{article}{article}
{news}{news}
}~\l_kreher_mwe_x_tl
}
}
\keys_define:nn { kreher/mwe }
{
X .tl_set:N = \l_kreher_mwe_x_tl,
}
\ExplSyntaxOff
\MWESettings[X=8]{article}
\begin{document}
The answer is \name
\end{document}