\if 语句来判断是否已创建新章节

\if 语句来判断是否已创建新章节

我正在尝试创建一个条件函数来确定是否已创建新章节(与 MWE 的目的不同)。尽管尝试了不同的方法,但到目前为止,我还没有成功。

代码首先检查是否已创建存储当前章节计数器的命令。如果已创建,则它会尝试将当前章节计数器与存储的计数器进行比较。

该 MWE 的预期输出是:

如果该命令\ifnewchaptercreated在第 1 章中第一次调用,则返回“新章节:第 1 章”,如果调用多次,则返回“第 1 章已创建”。然后,如果在新章节中调用该命令,则在第一次调用时,它将写入“新章节:第 2 章”,其他所有调用时,它将写入“第 2 章已创建”。

\documentclass[a4paper,10pt]{report}
\usepackage{fontspec}
\usepackage{ifthen}

\newcommand\ifnewchaptercreated{\ifthenelse{\isundefined\storecurrentchapter}{%
\newcommand\storecurrentchapter{\arabic{chapter}}
New chapter: Chapter \arabic{chapter}\par
}%
{\ifthenelse{\equal{\arabic{chapter}}{\storecurrentchapter}}{
New chapter: Chapter \arabic{chapter}.\par
}{ %
Chapter \arabic{chapter} already created.\par
} %
}}

\usepackage[linktoc=all]{hyperref}

\begin{document}

\chapter{A chapter}

\ifnewchaptercreated
\ifnewchaptercreated

\chapter{Another chapter}

\ifnewchaptercreated
\ifnewchaptercreated

\end{document}

答案1

以下是您要实现的目标的精简版:

在此处输入图片描述

\documentclass{report}

\newif\ifnewchapter% Create conditional
\newchapterfalse% Set conditional to false
\let\oldchapter\chapter
\renewcommand{\chapter}{%
  \global\newchaptertrue% A new \chapter has been created
  \oldchapter}% Regular old \chapter

\newcommand\ifnewchaptercreated{%
  \ifnewchapter% Check if new \chapter is created
    New chapter created%
    \global\newchapterfalse% Set conditional to false
  \else% New \chapter has not been created (or already used)
    No new chapter created%
  \fi
}

\begin{document}

\chapter{A chapter}

\ifnewchaptercreated \par
\ifnewchaptercreated \par
\ifnewchaptercreated \par
\ifnewchaptercreated

\chapter{Another chapter}

\ifnewchaptercreated \par
\ifnewchaptercreated

\end{document}

方法是“拦截”\chapter并将条件 - \ifnewchapter- 设置为 TRUE。然后,在使用 时\ifnewchaptercreated,我们检查条件并相应地重置它。

答案2

您可以使用该etoolbox包来

  1. 创建一个在您拨打电话时打开的开关\chapter

  2. 使用切换按钮来确定章节是否已创建。诀窍是执行检查的命令将切换按钮设置为 false

以下是具体操作方法

\documentclass[11pt]{report}

\usepackage{etoolbox}

\newtoggle{chaptercreated}
\preto{\chapter}{\toggletrue{chaptercreated}}

\newcommand{\ifnewchaptercreated}{%
  \iftoggle{chaptercreated}
    {Last chapter created \thechapter{}}
    {Chapter \thechapter{} already created}%
  \togglefalse{chaptercreated}%
}

\begin{document}
\chapter{A chapter}

\ifnewchaptercreated
\ifnewchaptercreated

\chapter{Another chapter}

\ifnewchaptercreated
\ifnewchaptercreated
\end{document}

相关内容