将环境与 if 语句结合会导致错误

将环境与 if 语句结合会导致错误

我有以下 MWE:

\documentclass{article}
\RequirePackage[utf8]{inputenc}
\usepackage{xcolor}
\usepackage{lettrine}
\usepackage{blindtext}
\usepackage{gtrcrd}
\newcounter{Cnt}
\setcounter{Cnt}{1}
\input EileenBl.fd
\newcommand*\initfamily{\usefont{U}{EileenBl}{xl}{n}}
\newenvironment{Testenvironment}[2][]{%
    \lettrine[lhang=1, nindent=0pt, lines=1]{\initfamily #2}{}%
}{}
\newenvironment{BigEnv}
{
    \begin{minipage}{\linewidth}
%       \centering
%       \ifnum\theCnt=1%
            \begin{Testenvironment}%
%       \fi         
}
{
%   \ifnum\theCnt=1%
        \end{Testenvironment}%  
%   \fi
    \end{minipage}
}

\usepackage{blindtext}

\begin{document}
\begin{BigEnv}
    A \blindtext
\end{BigEnv}
\end{document}

我希望lettrine只有当计数器Cnt设置为 1 时才有自定义环境,否则不设置。如上所示,编译时没有错误,但 lettrine 的环境始终适用。如果我取消注释注释行,则会收到很多错误,例如! Extra \endcsname.。为什么?我如何在 LaTeX 中实现我的意图?

答案1

这是你想要的吗?我会\if....在里面进行测试TestEnvironment

\documentclass{article}
\RequirePackage[utf8]{inputenc}
\usepackage{xcolor}
\usepackage{lettrine}
\usepackage{blindtext}
\usepackage{gtrcrd}
\newcounter{Cnt}
\setcounter{Cnt}{1}
\input EileenBl.fd

\newif\ifuselettrine
\newcommand*\initfamily{\usefont{U}{EileenBl}{xl}{n}}
\newenvironment{Testenvironment}[2][]{%
  \ifuselettrine%
  \lettrine[lhang=1, nindent=0pt, lines=1]{\initfamily #2}{}%
  \fi
}{}
\newenvironment{BigEnv}
{%
  \begin{minipage}{\linewidth}
    \centering
    \begin{Testenvironment}%
  }{%
  \end{Testenvironment}%  
\end{minipage}
}

\usepackage{blindtext}

\begin{document}
\begin{BigEnv}
    A \blindtext
\end{BigEnv}
\uselettrinetrue
\begin{BigEnv}
    A \blindtext
\end{BigEnv}

\end{document}

在此处输入图片描述

另一种方法是fakeenvironment使用\LetLtxMacro

\documentclass{article}
\RequirePackage[utf8]{inputenc}
\usepackage{xcolor}
\usepackage{lettrine}
\usepackage{blindtext}
\usepackage{gtrcrd}
\usepackage{letltxmacro}
\newcounter{Cnt}
\setcounter{Cnt}{1}
\input EileenBl.fd

\newcommand*\initfamily{\usefont{U}{EileenBl}{xl}{n}}
\newenvironment{Testenvironment}[2][]{%
  \lettrine[lhang=1, nindent=0pt, lines=1]{\initfamily #2}{}%
}{}

%Now let's define a dummy environment that does absolutely nothing
\newenvironment{fakeenvironment}{}{}
\newenvironment{BigEnv}
{%
  \ifnum\value{Cnt}=1\relax
  %Ah, the 'real' environment is requested, so make `\fakeenvironment` behave like `Testenvironment`, by copying its code!
  \LetLtxMacro\fakeenvironment\Testenvironment%
  \LetLtxMacro\endfakeenvironment\endTestenvironment
  \fi
  \begin{minipage}{\linewidth}
    \centering
    \begin{fakeenvironment}
    }{%
    \end{fakeenvironment}%  
  \end{minipage}%
}

\usepackage{blindtext}

\begin{document}
\begin{BigEnv}
    A \blindtext
\end{BigEnv}
\setcounter{Cnt}{0}
\begin{BigEnv}
    A \blindtext
\end{BigEnv}
\setcounter{Cnt}{1}
\begin{BigEnv}
    A \blindtext
\end{BigEnv}



\end{document}

相关内容