xparse 和 enumerate 的问题

xparse 和 enumerate 的问题

我正在尝试让以下文档发挥作用

\documentclass[10pt]{article}
\usepackage{enumitem}

\newcounter{foo}
\newcounter{bar}[foo]
\addtocounter{foo}{1}

\usepackage{xparse}
\usepackage{xstring}

\NewDocumentEnvironment{\PF}{m o}{
  \IfStrEqCase{#1}{%
    {0}{\def\Label{\alph*) }}%
    {1}{\def\Label{\phantom{\alph*) }}%
    }[\def\Label{\alph*}]}%
    \IfValueTF{#2}{ \stepcounter{foo} \setcounter{bar}{1} }{}%
    { \stepcounter{bar} \textbf{\Roman{foo}. Problem \arabic{bar} }}%     
    \begin{enumerate}[label = \Label]}{\end{enumerate}}

\begin{document}

\begin{PF}{1}
\item hello
\end{PF}

\begin{PF}{0}
\item 
\end{PF}

\begin{PF}{1}[2]
\item hello
\end{PF}

\end{document}

但编译总是失败,我无法看到我的错误。我想定义一个名为的环境,PF我可以选择在环境中使用哪个标签enumeratePF还定义了一个每次递增的计数器,直到使用可选环境。我想要的输出是

I. Problem 1 
        Hello 

I. Problem 2 
     a) Howdy

II. Problem 1 
     a) foobar

但可惜=(

答案1

请注意作为注释添加的更改;我还删除了一些空格。

\documentclass[10pt]{article}
\usepackage{enumitem,xstring,xparse}

\newcounter{foo}
\newcounter{bar}[foo]
\stepcounter{foo} % better then \addtocounter

\NewDocumentEnvironment{PF}{m o}{% not \PF!
  \IfStrEqCase{#1}{%
    {0}{\def\Label{\alph*) }}%
    {1}{\def\Label{\protect\phantom{\alph*) }}% note \protect
    }[\def\Label{\alph*}]}%
    % bar is stepped only once and \noindent is added
    \IfValueT{#2}{\stepcounter{foo}}% no need of a false branch
    {\noindent\stepcounter{bar}\textbf{\Roman{foo}. Problem \arabic{bar}}}%
    \begin{enumerate}[label = \Label]}{\end{enumerate}}


\begin{document}

\begin{PF}{1}
\item hello
\end{PF}

\begin{PF}{0}
\item hello
\end{PF}

\begin{PF}{1}[2]
\item hello
\end{PF}

\end{document}

在此处输入图片描述


我会使用键值语法。

\documentclass[10pt]{article}
\usepackage{xstring,enumitem}
\newcounter{fasitdel}
\newcounter{fasitopg}[fasitdel]
\addtocounter{fasitdel}{1}
\addtocounter{fasitopg}{1}

\usepackage{xparse}

\ExplSyntaxOn
\keys_define:nn {PF}
 {
  label .bool_set:N = \l_pf_label_bool,
  label .default:n = false,
  step  .bool_set:N = \l_pf_step_bool,
  step  .default:n = false,
 }

\NewDocumentEnvironment{PF}{O{}}
 {
  \keys_set:nn {PF} { #1 }
  \bool_if:NT \l_pf_step_bool
   {\stepcounter{fasitdel}\stepcounter{fasitopg}}
  \noindent\textbf{\Roman{fasitdel}.~Oppgave~\arabic{fasitopg}}
  \stepcounter{fasitopg}
  \bool_if:NTF \l_pf_label_bool
   {\begin{enumerate}[label = \alph*)~]}
   {\begin{enumerate}[label = \protect\phantom{\alph*)~}]}
 }
 {\end{enumerate}}
\ExplSyntaxOff

\begin{document}

\begin{PF}[label=true]
\item hello
\end{PF}

\begin{PF}
\item Howdy 
\end{PF}

\begin{PF}[label=true,step=true]
\item foo 
\end{PF}

\end{document}

在此处输入图片描述

相关内容