扩展答案这里。我定义了一个自定义环境,它会自动将章节号添加到其自己的计数器上。显然,这只适用于那些定义章节号并产生错误的文档类article
。
有没有办法在环境本身中构建一个 if/then 语句,只有当 chapternumber 已定义时才为章节号添加前缀,否则跳过前缀?
%\documentclass{article}
\documentclass{report}
\usepackage{xkeyval}
\usepackage{noindentafter}
\makeatletter
\define@boolkey{fam}[myenv@]{title}[true]{}
\define@boolkey{fam}[myenv@]{notitle}[true]{\ifmyenv@notitle\myenv@titlefalse\else\myenv@titletrue\fi}
\define@cmdkey{fam}[myenv@]{label}[\relax]{}
\define@cmdkey{fam}[myenv@]{repeat}[\relax]{}
\newcounter{myenvcnt}[chapter]%
\renewcommand{\themyenvcnt}{\thechapter.\arabic{myenvcnt}}
\newenvironment{myenv}[1][]{%
\setkeys{fam}{title,label,repeat,#1}%
\ifmyenv@title%
\par%
\expandafter\ifx\myenv@repeat\relax
\refstepcounter{myenvcnt}%
\expandafter\ifx\myenv@label\relax\else\label{\myenv@label}\fi
\else
\renewcommand{\themyenvcnt}{\ref{\myenv@repeat}}%
\fi
\subsubsection*{\textit{myenv\ \themyenvcnt}}%
\par\nobreak%
\else% = if no title
\par\addvspace{\bigskipamount}%
\fi
\edef\@currentlabel{\themyenvcnt}%
}{\par\addvspace{\bigskipamount}%
}
\NoIndentAfterEnv{myenv}
\appto\@noindent@newenv@hook{\par}{}{}
\makeatother
\begin{document}
\begin{myenv}
My environment.
\end{myenv}
\myenv{Test}
\end{document}
如果能提供任何关于如何做到这一点或从哪里开始的帮助,我将非常感激。
答案1
您可以使用以下内容:
%\documentclass{article}
\documentclass{report}
\usepackage{xkeyval}
\usepackage{noindentafter}
\makeatletter
\define@boolkey{fam}[myenv@]{title}[true]{}
\define@boolkey{fam}[myenv@]{notitle}[true]{\ifmyenv@notitle\myenv@titlefalse\else\myenv@titletrue\fi}
\define@cmdkey{fam}[myenv@]{label}[\relax]{}
\define@cmdkey{fam}[myenv@]{repeat}[\relax]{}
\newcounter{myenvcnt}
\@ifundefined{chapter}{}{%
\@addtoreset{myenvcnt}{chapter}
\renewcommand{\themyenvcnt}{\thechapter.\arabic{myenvcnt}}}
\newenvironment{myenv}[1][]{%
\setkeys{fam}{title,label,repeat,#1}%
\ifmyenv@title%
\par%
\expandafter\ifx\myenv@repeat\relax
\refstepcounter{myenvcnt}%
\expandafter\ifx\myenv@label\relax\else\label{\myenv@label}\fi
\else
\renewcommand{\themyenvcnt}{\ref{\myenv@repeat}}%
\fi
\subsubsection*{\textit{myenv\ \themyenvcnt}}%
\par\nobreak%
\else% = if no title
\par\addvspace{\bigskipamount}%
\fi
\edef\@currentlabel{\themyenvcnt}%
}{\par\addvspace{\bigskipamount}%
}
\NoIndentAfterEnv{myenv}
\appto\@noindent@newenv@hook{\par}{}{}
\makeatother
\begin{document}
\begin{myenv}
My environment.
\end{myenv}
\myenv{Test}
\end{document}