\newkeycommand 中的兩個 \IfEq 導致失敗

\newkeycommand 中的兩個 \IfEq 導致失敗

考慮這個 .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}

相關內容