![\newenvironment 中断命令中不需要的空格](https://linux22.com/image/437098/%5Cnewenvironment%20%E4%B8%AD%E6%96%AD%E5%91%BD%E4%BB%A4%E4%B8%AD%E4%B8%8D%E9%9C%80%E8%A6%81%E7%9A%84%E7%A9%BA%E6%A0%BC.png)
我创建了一个新环境来更改附录的目录行为。这些命令在 外部使用时可以正常工作\newenvironment
,但在 内部则不行\newenvironment
。
根本原因似乎是该行\addtocontents{toc}{\let\protect\l@chapter\protect\l@section}
:在环境之外,MWE.toc 中的对应行是,\let \l@chapter \l@section
而在新环境中,相同的命令会导致 toc 行\let \l @chapter\l @section
(请注意符号前的空格@
)。
我怎样才能去掉 @ 符号前的空格?
梅威瑟:
\documentclass{scrbook}
\usepackage{appendix}
\newenvironment{myappendices}{
\makeatletter
\addappheadtotoc
\addtocontents{toc}{\begingroup}
\addtocontents{toc}{\let\protect\l@chapter\protect\l@section}
\makeatother}{
\addtocontents{toc}{\endgroup}
}
\flushbottom
\begin{document}
\tableofcontents
\mainmatter
\chapter{One}
\chapter{Two}
\appendix
% version without \newenvironment: works
\makeatletter
\addappheadtotoc
\addtocontents{toc}{\begingroup}
\addtocontents{toc}{\let\protect\l@chapter\protect\l@section}
\makeatother
\chapter{Appendix One}
\chapter{Appendix Two}
\addtocontents{toc}{\endgroup}
% version with \newenvironment: broken toc
\begin{myappendices}
\chapter{Appendix Three}
\chapter{Appendix Four}
\end{myappendices}
\end{document}
答案1
虽然解决方案不是我提出的(在问题的评论中感谢 egreg 和 David Carlisle),但我会对这个问题发布适当的答案。
移到环境之外确实解决了这个问题\makeatletter
:\makeatother
\makeatletter
\newenvironment{myappendices}{%
\addappheadtotoc%
\addtocontents{toc}{\begingroup}%
\addtocontents{toc}{\let\protect\l@chapter\protect\l@section}%
}{%
\addtocontents{toc}{\endgroup}%
}%
\makeatother
以下是完整的 MWE(现在正在运行):
\documentclass{scrbook}
\usepackage{appendix}
\makeatletter
\newenvironment{myappendices}{%
\addappheadtotoc%
\addtocontents{toc}{\begingroup}%
\addtocontents{toc}{\let\protect\l@chapter\protect\l@section}%
}{%
\addtocontents{toc}{\endgroup}%
}%
\makeatother
\flushbottom
\begin{document}
\tableofcontents
\mainmatter
\chapter{One}
\chapter{Two}
\appendix
% version without \newenvironment: works
\makeatletter
\addappheadtotoc
\addtocontents{toc}{\begingroup}
\addtocontents{toc}{\let\protect\l@chapter\protect\l@section}
\makeatother
\chapter{Appendix One}
\chapter{Appendix Two}
\addtocontents{toc}{\endgroup}
% version with \newenvironment: works now, too
\begin{myappendices}
\chapter{Appendix Three}
\chapter{Appendix Four}
\end{myappendices}
\end{document}