TransWikia.com

Undesired spaces in newenvironment break commands

TeX - LaTeX Asked on July 27, 2021

I created a new environment to change the behavior of the toc for appendices. The commands work fine when using them outside newenvironment, but not within newenvironment.

The root cause seems the line addtocontents{toc}{letprotectl@chapterprotectl@section}: Outside the environment, the corresponding line in MWE.toc is let l@chapter l@section while the same command within the new environment leads to the toc line let l @chapterl @section (please notice the spaces before the @ symbols).

How can I get rid of the space before the @ sign?

enter image description here

MWE:

documentclass{scrbook} 
usepackage{appendix}

newenvironment{myappendices}{
makeatletter
addappheadtotoc
addtocontents{toc}{begingroup}
addtocontents{toc}{letprotectl@chapterprotectl@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}{letprotectl@chapterprotectl@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}

One Answer

Although the solution didn't come from me (credits goes to egreg and David Carlisle in the comments of the question), I'll post a proper answer to this question.

Moving makeatletter and makeatother outside the environment solved the issue indeed:

makeatletter
newenvironment{myappendices}{%
  addappheadtotoc%
  addtocontents{toc}{begingroup}%
  addtocontents{toc}{letprotectl@chapterprotectl@section}%
}{%
  addtocontents{toc}{endgroup}%
}%
makeatother

enter image description here

Below the full MWE (now working):

documentclass{scrbook} 
usepackage{appendix}

makeatletter
newenvironment{myappendices}{%
  addappheadtotoc%
  addtocontents{toc}{begingroup}%
  addtocontents{toc}{letprotectl@chapterprotectl@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}{letprotectl@chapterprotectl@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}

Correct answer by kromuchi on July 27, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP