Counters for Chapter and Section environments when using tcolorbox for listings

This is a followup question of this question. With my MWE I'm getting wrong Listing numbers, wrong toc (including Chapter and Section environments from listings) and wrong bookmarks in pdf toc. Any help will be highly appreciated. Thanks

MWE

\documentclass[oneside]{book}
\usepackage{listings}
\usepackage{tcolorbox}
\tcbuselibrary{listings}%
\usepackage{xcolor}
\usepackage[bookmarks=true, bookmarksopenlevel=2]{hyperref}

%Definition of New Environments
\tcbset{
texexp/.style={colframe=green!85!black, colback=red!5!white,
coltitle=red!50!yellow!3!black, left=6mm,
listing options={style=tcblatex,numbers=left,numberstyle=\tiny\color{red!75!black}},
fonttitle=\small\textsc\bfseries, fontupper=\small, fontlower=\small},
example/.style 2 args={texexp,
title={Listing \thetcbcounter: #1},label={#2}},
}

\newtcblisting{texexp}[1]{texexp,#1}

\newtcblisting[auto counter,number within=section]{texexptitled}[3][]{%
example={#2}{#3},#1}

\newtcolorbox[use counter from=texexptitled]{texexptitledspec}[3][]{%
example={#2}{#3},#1}

\lstset{ % General setup for the package
language={[LaTeX]TeX},
basicstyle=\small\sffamily,
numbers=left,
numberstyle=\tiny,
frame=tb,
tabsize=4,
columns=fixed,
showstringspaces=false,
showtabs=false,
keepspaces,
keywordstyle=\color{blue}
}%

\tcbset{listing engine={listings}}

\usepackage[english]{babel}
\usepackage{blindtext}

%%% Storage tool macros

\newcommand{\newbackupcounter}[1]{%
\ifltxcounter{#1}{%
\newcounter{backup#1}%
}{}%
}%

\newcommand{\PushCounterValue}[1]{%
\ifltxcounter{#1}{%
\setcounter{backup#1}{\number\value{#1}}
\setcounter{#1}{0}
}{%
}%
}%

\newcommand{\PushCounterValues}{%
\forlistloop{\PushCounterValue}{\restorecounterlist}%
}%

\newcommand{\PopCounterValue}[1]{%
\ifltxcounter{#1}{%
\setcounter{#1}{\number\value{backup#1}}%
\setcounter{backup#1}{0}% For 'safety'
}{}%
}%

\newcommand{\PopCounterValues}{%
\forlistloop{\PopCounterValue}{\restorecounterlist}%
}%

\AtBeginDocument{%
% Setup the counter lists and provide the backup counters
\forlistloop{\newbackupcounter}{\restorecounterlist}%
}%

\begin{document}

\tableofcontents

\mainmatter

\chapter{First Chapter}
\section{First Section}
\subsection{Outer subsection Number one}
\subsection{Outer subsection Number two}

\blindtext

% Redefine the document environment within a group
\begingroup
\PushCounterValues% Push the counter values to the backup values
\renewenvironment{document}{}{}
\renewcommand\documentclass[2][]{}
\setcounter{chapter}{0}

\begin{texexptitled}{Example}{mylab}
\documentclass{book}
\begin{document}
\chapter{Chapter Test}
\section{Section 334}
Here, we use Example  with a title line.
\end{document}
\end{texexptitled}
\PopCounterValues% Restore the original counter values%

\endgroup

\chapter{New Chapter}
\section{New Section}
\blindtext

\end{document}


Output

• Your \tableofcontents is outside of \begin{document}...\end{document} – user31729 Aug 20 '14 at 7:15
• The problem is deep inside the way tcolorbox uses counters. I can't figure out quickly – user31729 Aug 20 '14 at 7:36
• My bad. Sorry for this @ChristianHupfer. Even putting \tableofcontents inside of \begin{document}...\end{document} has issues. – MYaseen208 Aug 20 '14 at 7:38
• I think I got it, see the answer, but I can't do more checks right now, I am off for about three or four hours. – user31729 Aug 20 '14 at 7:41

I propose to put the the structure saving commands into the lower part only. Such, the numbering of the tcolorbox is not affected.

To avoid the tocs and bookmarks problems, I suggest to deactivate \addtocontents and \addcontentsline as was done for \documentclass.

My answer creates a new option protect structure which contains all this stuff.

\tcbset{protect structure/.style={
before lower={\begingroup%
\PushCounterValues% Push the counter values to the backup values
\renewenvironment{document}{}{}%
\renewcommand\documentclass[2][]{}%
\renewcommand\chaptermark[1]{}%
\renewcommand\sectionmark[1]{}%
#1%
},
after lower={%
\PopCounterValues% Restore the original counter values%
\endgroup%
}},
protect structure/.default=}


It takes a parameter where counter settings can be given; here:

protect structure={\setcounter{chapter}{0}}


Now, all together, we get:

\documentclass[oneside]{book}
\usepackage{listings}
\usepackage{tcolorbox}
\tcbuselibrary{listings}%
\usepackage{xcolor}
\usepackage[bookmarks=true, bookmarksopenlevel=2]{hyperref}

%Definition of New Environments
\tcbset{
texexp/.style={colframe=green!85!black, colback=red!5!white,
coltitle=red!50!yellow!3!black, left=6mm,
listing options={style=tcblatex,numbers=left,numberstyle=\tiny\color{red!75!black}},
fonttitle=\small\textsc\bfseries, fontupper=\small, fontlower=\small},
example/.style 2 args={texexp,
title={Listing \thetcbcounter: #1},label={#2}},
}

\newtcblisting{texexp}[1]{texexp,#1}

\newtcblisting[auto counter,number within=section]{texexptitled}[3][]{%
example={#2}{#3},#1}

\newtcolorbox[use counter from=texexptitled]{texexptitledspec}[3][]{%
example={#2}{#3},#1}

\lstset{ % General setup for the package
language={[LaTeX]TeX},
basicstyle=\small\sffamily,
numbers=left,
numberstyle=\tiny,
frame=tb,
tabsize=4,
columns=fixed,
showstringspaces=false,
showtabs=false,
keepspaces,
keywordstyle=\color{blue}
}%

\tcbset{listing engine={listings}}

\usepackage[english]{babel}
\usepackage{blindtext}

%%% Storage tool macros

\newcommand{\newbackupcounter}[1]{%
\ifltxcounter{#1}{%
\newcounter{backup#1}%
}{}%
}%

\newcommand{\PushCounterValue}[1]{%
\ifltxcounter{#1}{%
\setcounter{backup#1}{\number\value{#1}}
\setcounter{#1}{0}
}{%
}%
}%

\newcommand{\PushCounterValues}{%
\forlistloop{\PushCounterValue}{\restorecounterlist}%
}%

\newcommand{\PopCounterValue}[1]{%
\ifltxcounter{#1}{%
\setcounter{#1}{\number\value{backup#1}}%
\setcounter{backup#1}{0}% For 'safety'
}{}%
}%

\newcommand{\PopCounterValues}{%
\forlistloop{\PopCounterValue}{\restorecounterlist}%
}%

\AtBeginDocument{%
% Setup the counter lists and provide the backup counters
\forlistloop{\newbackupcounter}{\restorecounterlist}%
}%

\tcbset{protect structure/.style={
before lower={\begingroup%
\PushCounterValues% Push the counter values to the backup values
\renewenvironment{document}{}{}%
\renewcommand\documentclass[2][]{}%
\renewcommand\chaptermark[1]{}%
\renewcommand\sectionmark[1]{}%
#1%
},
after lower={%
\PopCounterValues% Restore the original counter values%
\endgroup%
}},
protect structure/.default=}

\begin{document}

\tableofcontents

\mainmatter

\chapter{First Chapter}
\section{First Section}
\subsection{Outer subsection Number one}
\subsection{Outer subsection Number two}

\blindtext

\begin{texexptitled}[protect structure={\setcounter{chapter}{0}}]{Example}{mylab}
\documentclass{book}
\begin{document}
\chapter{Chapter Test}
\section{Section 334}
Here, we use Example  with a title line.
\end{document}
\end{texexptitled}

\chapter{New Chapter}
\section{New Section}
\blindtext

\end{document}

• Thanks @Thomas F. Sturm for your answer. Your provided code works fine except for TOC and Bookmars in TOC in pdf view. I also don't want to include chapters and sections appearing in listings to my TOC. – MYaseen208 Aug 20 '14 at 9:34
• @MYaseen208 That's mysterious. I don't have such entries using the answer code... Could you double-check again with the answer code? – Thomas F. Sturm Aug 20 '14 at 9:46
• @MYaseen208 I've just added a deactivation of \chaptermark and \sectionmark which seems to be a good idea. But this is not connected to TOC and bookmarks. – Thomas F. Sturm Aug 20 '14 at 9:55
• @ThomasF.Sturm: Some off-topic comment -- I like your tcolorbox package and recommend it on many occasions where appropiate -- perhaps it would be a good idea to provide the possibility of listing LaTeX documents within the outer documents without much ado... of course, not any preamble command can be disabled etc. – user31729 Aug 20 '14 at 10:02
• @ChristianHupfer I have the fear that many things easily could go wrong if full documents are included. It can work with a simple preamble but many users may be disappointed if their special preamble does not work. Nevertheless, I will think about it. – Thomas F. Sturm Aug 20 '14 at 10:11

The number within option in the definition of texexptitled has to be set to backupsection or \backupchapter (perhaps better)

\documentclass[oneside]{book}
\usepackage{listings}
\usepackage{tcolorbox}
\tcbuselibrary{listings}%
\usepackage{xcolor}
\usepackage[bookmarks=true, bookmarksopenlevel=2]{hyperref}

%Definition of New Environments
\tcbset{
texexp/.style={colframe=green!85!black, colback=red!5!white,
coltitle=red!50!yellow!3!black, left=6mm,
listing options={style=tcblatex,numbers=left,numberstyle=\tiny\color{red!75!black}},
fonttitle=\small\textsc\bfseries, fontupper=\small, fontlower=\small},
example/.style 2 args={texexp,
title={Listing \thetcbcounter: #1},label={#2}},
}

\newtcblisting{texexp}[1]{texexp,#1}

\newtcblisting[auto counter,number within=backupsection]{texexptitled}[3][]{%
example={#2}{#3},#1}

\newtcolorbox[use counter from=texexptitled]{texexptitledspec}[3][]{%
example={#2}{#3},#1}

\lstset{ % General setup for the package
language={[LaTeX]TeX},
basicstyle=\small\sffamily,
numbers=left,
numberstyle=\tiny,
frame=tb,
tabsize=4,
columns=fixed,
showstringspaces=false,
showtabs=false,
keepspaces,
keywordstyle=\color{blue}
}%

\tcbset{listing engine={listings}}

\usepackage[english]{babel}
\usepackage{blindtext}

%%% Storage tool macros

\newcommand{\newbackupcounter}[1]{%
\ifltxcounter{#1}{%
\newcounter{backup#1}%
}{}%
}%

\newcommand{\PushCounterValue}[1]{%
\ifltxcounter{#1}{%
\setcounter{backup#1}{\number\value{#1}}
\setcounter{#1}{0}
}{%
}%
}%

\newcommand{\PushCounterValues}{%
\forlistloop{\PushCounterValue}{\restorecounterlist}%
}%

\newcommand{\PopCounterValue}[1]{%
\ifltxcounter{#1}{%
\setcounter{#1}{\number\value{backup#1}}%
\setcounter{backup#1}{0}% For 'safety'
}{}%
}%

\newcommand{\PopCounterValues}{%
\forlistloop{\PopCounterValue}{\restorecounterlist}%
}%

\AtBeginDocument{%
% Setup the counter lists and provide the backup counters
\forlistloop{\newbackupcounter}{\restorecounterlist}%
}%

\begin{document}

\tableofcontents
\mainmatter

\chapter{First Chapter}
\section{First Section}
\subsection{Outer subsection Number one}
\subsection{Outer subsection Number two}

\blindtext

% Redefine the document environment within a group
\begingroup
\PushCounterValues% Push the counter values to the backup values
\renewenvironment{document}{}{}
\renewcommand\documentclass[2][]{}
\setcounter{chapter}{0}

\begin{texexptitled}{Example}{mylab}
\documentclass{book}
\begin{document}
\chapter{Chapter Test}
\section{Section 334}
Here, we use Example  with a title line.
\end{document}
\end{texexptitled}
\PopCounterValues% Restore the original counter values%

\endgroup

\chapter{New Chapter}
\section{New Section}
\blindtext

\end{document}

• Thanks @christianhupfer for your answer. Your provided code works fine except for TOC and Bookmars in TOC in pdf view. I also don't want to include chapters and sections appearing in listings to my TOC. – MYaseen208 Aug 20 '14 at 9:35
• @MYaseen208: I had no time for doing that too... Use Thomas F. Sturm's answer. I am writing on a tablet, having no chance to test code etc. – user31729 Aug 20 '14 at 9:36
• @ChristianHupfer By the way: The push/pop counter idea of yours from former answers is clever :-) – Thomas F. Sturm Aug 20 '14 at 10:00
• @ThomasF.Sturm: See my comment to your answer... you can readily use that code (and definitely improve it) for an extension of tcolorbox, perhaps? The push/pop counters can (must?) be extended for table and figure counters too, but there are so many environments from other packages, it would be impossible to include any counter by premature definition – user31729 Aug 20 '14 at 10:03