The problem is that the exercise is technically a listing which here contains another listing. The listing outputs overwrite themselves.
My solution proposal is to guard the inner listing by giving it a private listing output file \jobname.spectemp
. So, use for the inner listing an environment like this:
\newenvironment{encapsmlstlisting}{%
\begingroup\tcbverbatimwrite{\jobname.spectemp}%
}{\endtcbverbatimwrite\endgroup%
\mlstinputlisting{\jobname.spectemp}%
}
I added this to your code and changed mlstlisting
to encapsmlstlisting
for the critical example. This gives the following (note my #####
marks inside the code):
\documentclass[12pt,a4paper,twoside]{book}%
\usepackage{graphicx,amsmath,amsfonts,amssymb,mathptmx}
\usepackage[french]{babel}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{fancybox} % définit des macros pour des boîtes, des cadres, etc.
\usepackage[svgnames,x11names,hyperref]{xcolor} % définit les couleurs par noms
\usepackage{colortbl,array}
\usepackage[section]{algorithm} %Gère les algorithmes
\usepackage{algpseudocode} % Codes semblables à fortran ou pascal ou C
\usepackage{multicol,wrapfig,lmodern}
\usepackage[bf,textfont={footnotesize,it}]{caption}
\usepackage[toc,page,title,titletoc,header]{appendix}
\usepackage[margin=2cm,includefoot,includehead]{geometry}
\setlength{\parindent}{4ex} % indentation au début de chaque paragraphe
\setlength{\parskip}{2ex plus 0.5ex minus 0.2ex} % espace vertical entre
\usepackage[colorlinks,linkcolor=black,pageanchor]{hyperref}%
\usepackage[plainheadsepline,nouppercase]{scrpage2}
\pagestyle{scrheadings}
\renewcommand{\chaptermark}[1]{\markboth{{\thechapter. #1}}{}}
\renewcommand{\sectionmark}[1]{\markright{ \thesection.\ #1}{}}
\newcommand\chapterstring{Chapitre}
\usepackage{titlesec}
%
% chapitres dans un box
\titleformat{\chapter}[frame] {\bfseries\sffamily\color{Blue4}} {\filright
\enspace \Large \chapterstring~\thechapter} {14pt} {\Large\filcenter}
%
% sections avec rule
\titleformat{\section}{\vspace{0mm plus 1cm}\addpenalty{-1000}\color{Blue4}
\Large\bfseries\sffamily}{\thesection}{1em}{}[{\color{Blue4}\titlerule[0.5pt]}]
%
% sous-sections
\titleformat{\subsection}{\addpenalty{-500}\large\bfseries\sffamily}{
\thesubsection}{1em}{}
%
% sous-sous-sections
\titleformat{\subsubsection}{\penalty-500\vspace{0pt plus 2pt}{}\bfseries
\sffamily}{\thesubsubsection}{}{}[\vspace{-14pt}]
%
% Divers macros tcolorbox
%-----------------------------------------------------------------------------
% Divers Box en couleur avec le package tcolorbox
% Faire attention à l'ordre des options!!!
\usepackage[theorems,minted,listingsutf8,documentation,breakable]{tcolorbox}
\usepackage{varioref}
%
% command shell
\newtcblisting{commandshell}{colback=white,colupper=black,colframe=yellow!75
!black,listing only,listing options={style=tcblatex,language=sh},every listing
line={\textcolor{red}{\small\ttfamily\bfseries root \$> }}}
%
% Mots clés en couleur dans les listings
% Compiler avec pdflatex -shell-escape input
%
% Script entre un \begin et un \end avec caption
\newtcblisting[auto counter,number within=section]{mlstlisting}[1]{
listing engine=minted,minted style=default,minted language=python,
minted options={fontsize=\small,linenos,numbersep=3mm,mathescape},
colback=blue!3!white,colframe=blue!75!black,listing only,left=5mm,enhanced,
overlay={\begin{tcbclipinterior}\fill[red!20!blue!20!white] (frame.south west)
rectangle ([xshift=5mm]frame.north west);\end{tcbclipinterior}},breakable,
title=Script QuTiP \thetcbcounter: #1
}
%
% Script dans un fichier qu'on charge avec caption et label
\newtcbinputlisting[use counter from=mlstlisting]{\mlstinputlisting}[2][]{%
listing engine=minted,minted language=python,minted style=default,
minted options={fontsize=\small,linenos,numbersep=3mm,mathescape},
listing file={#2},
colback=violet!3!white,colframe=violet!85!black,fonttitle=\bfseries,
listing only,left=5mm,enhanced,
overlay={\begin{tcbclipinterior}\fill[red!20!blue!20!white] (frame.south west)
rectangle ([xshift=5mm]frame.north west);\end{tcbclipinterior}},breakable,
title=Script QuTiP \thetcbcounter: #1
}
% Output du Script précédent
\newtcbinputlisting[use counter from=mlstlisting]{\mclstinputlisting}[2][]{%
listing engine=minted,minted language=python,minted style=default,
minted options={fontsize=\small,linenos,numbersep=3mm,mathescape},listing
file={#2}, colback=blue!3!white,colframe=blue!60!white,fonttitle=\bfseries,
listing only,left=5mm,enhanced,
overlay={\begin{tcbclipinterior}\fill[red!20!blue!20!white] (frame.south west)
rectangle ([xshift=5mm]frame.north west);\end{tcbclipinterior}},breakable,
title=Script Ouput QuTiP \thetcbcounter: #1
}
%################################ ADDITIONAL (START)
\newenvironment{encapsmlstlisting}{%
\begingroup\tcbverbatimwrite{\jobname.spectemp}%
}{\endtcbverbatimwrite\endgroup%
\mlstinputlisting{\jobname.spectemp}%
}
%################################ ADDITIONAL (STOP)
% Procédure d'ouverture et de fermeture du fichier des solutions
%
\newcounter{texercise}
%
\newwrite\solout
\def\openoutsol{\immediate\openout\solout\jobname.sol}
\def\solfile#1{solutions/texercise#1.tex}
\def\writesol#1{\immediate\write\solout{\noexpand\processsol{\thetcbcounter}{#1}
}}%
\def\closeoutsol{\immediate\closeout\solout}
\def\inputsol{\IfFileExists{\jobname.sol}{\input{\jobname.sol}}{}}
%
% Excercises Style
\tcbset{
texercisestyle/.style={arc=0.5mm, colframe=blue!25!yellow!90!white,
colback=blue!25!yellow!5!white, coltitle=blue!25!yellow!40!black,
fonttitle=\small\sffamily\bfseries, fontupper=\small, fontlower=\small}
}
%
% Noyau de l'environnement Exercice avec les labels exercice (exe:#2) et
% solution (sol:#2)
\newtcolorbox[auto counter,number within=section,list inside=exam]%
{texercise}[2][]{texercisestyle,listing file={\solfile\thetcbcounter},
label={exe:#2},phantom={\writesol{#2}},title={Exercice
\thetcbcounter\hfill\mdseries Solution à la page \pageref{sol:#2}},
list entry={\protect\numberline{\thetcbcounter}Exercice avec solution à la
page \pageref{sol:#2}},breakable,#1}
%
%
% Solution part
% \usepackage{hyperref} % for \phantomsection
\newcommand{\processsol}[2]{%
\tcbinputlisting{texercisestyle,text only,
phantom={\phantomsection\label{sol:#2}},%
title={Solution Exercice \ref{exe:#2} de la page \pageref{exe:#2}},
listing file={\solfile{#1}},breakable}}
%
%-----------------------------------------------------------------------------
% Macro des ``theorems'' colorés
% Théorème avec caption et label
\newcounter{mytheorem}[section]
\def\themytheorem{\thesection.\arabic{mytheorem}}
\tcbmaketheorem{theorem}{Théorème}{fonttitle=\bfseries\upshape,
fontupper=\slshape,arc=0mm, colback=red!3,colframe=red!75!black,
separator sign dash,breakable}
{mytheorem}{th}
%
% Définition avec caption et label
\newcounter{mydefi}[section]
\def\themydefi{\thesection.\arabic{mydefi}}
\tcbmaketheorem{definition}{Définition}{fonttitle=\bfseries\upshape,
fontupper=\slshape, arc=0mm, colback=blue!3,colframe=blue!75!black,
separator sign dash,breakable}
{mydefi}{df}
%
% Principe avec caption et label
\newcounter{myprinc}[section]
\def\themyprinc{\thesection.\arabic{myprinc}}
\tcbmaketheorem{principe}{Principe}{fonttitle=\bfseries\upshape,
fontupper=\slshape, arc=0mm, colback=green!3,colframe=green!35!black,
separator sign dash,breakable}
{myprinc}{pr}
%
% Proposition avec caption et label
\newcounter{myprop}[section]
\def\themyprop{\thesection.\arabic{myprop}}
\tcbmaketheorem{proposition}{Proposition}{fonttitle=\bfseries\upshape,
fontupper=\slshape, arc=0mm, colback=green!3,colframe=green!35!black,
separator sign dash,breakable}
{myprop}{prp}
%
% % Remarque avec caption et label
\newcounter{myrmq}[section]
\def\themyrmq{\thesection.\arabic{myrmq}}
\tcbmaketheorem{remark}{Remarque}{fonttitle=\bfseries\upshape,
fontupper=\slshape, arc=0mm, colback=yellow!3,colframe=yellow!35!black,
separator sign dash,breakable}
{myrmq}{rq}
%
% % Exemple avec caption et label
\newcounter{myexpl}[section]
\def\themyexpl{\thesection.\arabic{myexpl}}
\tcbmaketheorem{example}{Exemple}{fonttitle=\bfseries\upshape,
fontupper=\slshape, arc=0mm, colback=red!50!yellow!5!white,
colframe=red!50!yellow!50!black, separator sign dash,breakable}
{myexpl}{exp}
%-----------------------------------------------------------------------
%
\setcounter{MaxMatrixCols}{30}
\setlength{\abovecaptionskip}{0pt}
\setlength{\belowcaptionskip}{0pt}
% Macro des abbréviations
\newenvironment{proof}[1][Preuve]{\noindent\textbf{#1.} }{\ \rule{0.5em}{0.5em}}
% Prise en compte du numéro de la section dans les différentes numérotations
\numberwithin{equation}{section}
\numberwithin{figure}{section}
\numberwithin{table}{section}
% Ramener la typologie française à la typologie standard (anglo-saxone)
\frenchbsetup{StandardLayout}
% Défintion des commandes raccourcies personnelles
\newcommand{\opn}[1]{\ensuremath{\operatorname{#1}}} % Operatorname
\newcommand{\bls}[1]{\ensuremath{\boldsymbol{#1}}} %Boldsymbol
\newcommand{\av}[1]{\ensuremath{\langle{#1}\rangle}} %Average
\newcommand{\bra}[1]{\langle{#1}\vert} %Dirac ket
\newcommand{\ket}[1]{\vert{#1}\rangle} % Dirac bra
%
%
%
\begin{document}
\chapter{Calculs quantiques}
% Ouverture du fichier Solution
\openoutsol
%
\section{Interpreteur Spyder}
\begin{commandshell}
sudo apt-get install spyder
\end{commandshell}
\begin{texercise}{CX}
%
\begin{tcboutputlisting}
En vertu de la relation (\vref{eq:CX}), on a le script \texttt{IPhyton}
ci-dessous.
%########## CHANGED (begin)
\begin{encapsmlstlisting}
In [2]:
CX=tensor(basis(2,0)*basis(2,0).dag(),qeye(2))+tensor(basis(2,1)*basis(2,
1).dag(),sigmax())
In [3]: CX
Out[3]:
Quantum object: dims = [[2, 2], [2, 2]], shape = [4, 4], type = oper, isherm =
True
Qobj data =
[[ 1. 0. 0. 0.]
[ 0. 1. 0. 0.]
[ 0. 0. 0. 1.]
[ 0. 0. 1. 0.]]
\end{encapsmlstlisting}
%########## CHANGED (end)
\end{tcboutputlisting}
%
Proposer un script QuTiP, qui donne la matrice de la porte logique
quantique $CX$, sans utiliser la fonction \texttt{qutip.cnot}.
%
\end{texercise}
\begin{texercise}{separable_state}
%
\begin{tcboutputlisting}
%
The state (\vref{eq:GEntSt}) can be equivalently rewritten as
\begin{equation}
\ket{\psi}=a\{\ket{00}+b_0e^{i\varphi_0}\ket{01}+b_1e^{i\varphi_1}
\ket{10}+b_1b_0e^{i(\varphi_0+\varphi_1)}\ket{11}\}.
\label{eq:GEntSt2}
\end{equation}
The application of \texttt{CNOT}\ gate to (\vref{eq:GEntSt2}) leads to
\begin{equation}
\mathtt{CNOT}\ket{\psi}=a\{\ket{00}+b_0e^{i\varphi_0}\ket{01}+b_1
e^{i\varphi_1}\ket{11}+b_1b_0e^{i(\varphi_0+\varphi_1)}\ket{10}\}
\end{equation}
which is separable if and only if $b_0e^{i\varphi_0}=1$. Thus, \texttt{CNOT}
generated an entangled state if and only if at least one of the following 2
conditions is fulfiled:%
\begin{equation}
b_0\neq1,\,\varphi_0\neq0
\end{equation}
\end{tcboutputlisting}
%
The most general separable state of the two qubits can be written, up to an
overall phase, as%
\begin{equation}
\ket{\psi}=a(\ket{0} +b_1e^{i\varphi_1}\ket{1})\otimes(\ket{0}
+b_0e^{i\varphi_0}\ket{1}),
\label{eq:GEntSt}
\end{equation}
where $a$ is set to the completure. What conditions should the real
coefficients $b_0$, $b_1$, $\varphi_0$ and $\varphi_1$ satisfy in
order that $\mathtt{CNOT}\ket{\psi}$ be entangled?
%
\end{texercise}
% Fermeture du fichier Solution
\closeoutsol
%
%
\tcblistof[\subsection]{exam}{Solutions des Exercices%
\label{listofexercises}}
%
% \newpage
% Charger les Solutions des Exercices du cours
\inputsol
\end{document}
Finally, we get the correct output:
![enter image description here](https://i.stack.imgur.com/nc6ti.png)
Unfortunately, gooble
really is ignored. This key has no effect on \lstinline
or \lstinputlisting
(taken from the listings
manual) and tcblisting
uses \lstinputlisting
internally.
The following links consider some tricks to circumvent the problem:
autogobble for lstinputlistings
How to extend the \lstinputlisting command
For the current MWE, this could be applied as the following:
\documentclass{beamer}
\usepackage{lmodern}
\usepackage[listings]{tcolorbox}
\lstdefinestyle{mystyle}{language=[LaTeX]TeX,
basicstyle=\ttfamily,
texcsstyle=*\color{blue},
breaklines=true,
keywordstyle=\color{green!30!black},
commentstyle=\color{red},
morekeywords={},
otherkeywords={$,\{,\},[,],&},
backgroundcolor=\color{gray!30},
escapeinside=<>,
moretexcs={maketitle},
showtabs=true,
showspaces=true,
tabsize=2,
gobble=2
}
\begin{document}
\begin{frame}[fragile]
\frametitle{Listing}
\begin{lstlisting}[style=mystyle]
\documentclass{}
preamble
\begin{document}
document text
\end{document}
\end{lstlisting}
\begin{tcblisting}{
listing options={style=mystyle,framexleftmargin=-14pt,numbersep=-7pt,xleftmargin=-14pt},
listing only,
}
\documentclass{}
preamble
\begin{document}
document text
\end{document}
\end{tcblisting}
\end{frame}
\end{document}
![enter image description here](https://i.stack.imgur.com/1oZJt.png)
Without showspaces
this would look OK. Another option for tcblisting
would be to play with the left
key to shift everything to the left.
Hopefully, \lstinputlisting
will support gobble
some day.
Best Answer
I don't know about
mathescape
, but presumably you don't want/need to enter math mode anyway, since you just want to make a box.So use
escapechar=<char>
instead. I've turned your code snippets into an MWE to more clearly show the solution, but the sameescapechar=|
(or some other character not used anywhere in the listing) is equally valid insidelisting options
in your environment's definition.Here's the full code made into a compilable example: