1

I am trying to center a lstlisting environment using tcolorbox (as suggested here). The method does work normally but doesn't render as expected in enumerate environment as shown below:

Output

I have tried the following and tweaked it many times but nothing worked.

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{listings}
\usepackage{enumitem}
\usepackage[most]{tcolorbox}

\newenvironment{code}[1][]{%
    \tcbwritetemp}%
    {\endtcbwritetemp%
    \tcbox[before=\begin{center},after=\end{center}]%
    {\tcbusetemplisting}%
    }%

\begin{document}    
    Start a list:
    \begin{enumerate}[label = \textbf{--}]
        \item Inside enumerate not working.
\begin{code}
if(x == 0){
    return 0;
}else{
    return 1;
}\end{code}
    \end{enumerate}
    This is what I want to achieve inside enumerate environment
\begin{code}
if(x == 0){
    return 0;
}else{
    return 1;
}
\end{code}
\end{document}

How can I achieve the desired output while roughly keeping the same outline of the logic used?

1 Answer 1

3

lstlisting, called in \tcbox, uses the current total left margin (\@totalleftmargin) to indent the listing accordingly when it is used inside a list environment. This works well when you use lstlisting in list environments directly, but fails with \tcbox. This seems to happen because \tcbox already indents the box and lstlisting indents the code again. To me this looks like a bug in the tcolorbox package.

A simple fix is to reset \@totalleftmargin to 0pt locally in the code environment:

\makeatletter
\newenvironment{code}[1][]{%
    \@totalleftmargin=0pt%
    \tcbwritetemp}%
    {\endtcbwritetemp%
    \tcbox[before=\begin{center},after=\end{center}]%
    {\tcbusetemplisting}%
    }%
\makeatother

which gives the desired output

enter image description here

1
  • 1
    Thank you a lot for the explanation and the answer! Works perfectly! May 28, 2019 at 21:49

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .