2

I'm trying to have a non-captionned listing using tcolorbox and minted. I've made a macro that automates the task, with the title of the snippet as optional argument.

My goal is, when the optional argument is empty, not print a caption (nor register the listing in the list of listings).

I don't see how I can do it, since there is no possibility to add an ifcase in the tcolorbox declaration.

Here is my MWE :

\documentclass{article}
\usepackage[most,minted]{tcolorbox}
\usepackage{listings}

\usepackage{filecontents}
\begin{filecontents*}{helloworld.java}
public class HelloWorld {
    // A 'Hello World' in Java
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}
\end{filecontents*}


\AtBeginDocument{
\newtcbinputlisting[blend into=listings]{\mylisting}[2][]{%
    listing engine=minted,
    listing file={#2},
    listing only,
    breakable,
    title={Listing \thetcbcounter: #1},
    list text=#1,
    label={lst:\thetcbcounter},
    detach title,
    listing above comment,
    comment=\centering\tcbtitletext,
    enhanced jigsaw,
    sharp corners,
    boxrule=0.4pt,
    top=0pt,
    bottom=0pt,
    minted language=java,
    minted style=colorful,
    minted options={%
        tabsize=2,
        fontsize=\footnotesize,
        xleftmargin=2em,
        autogobble=true,
        numbers=left,
        numbersep=5pt,
        fontsize=\footnotesize,
        breaklines=true,
    },
    left=-2em,
    left skip=1em,
    width=\linewidth-1em,}

}

\begin{document}
    
\lstlistoflistings
    
\section{Test}

\mylisting{helloworld.java}  % This should not have a caption

\mylisting[Hello world]{helloworld.java}


\end{document}

How can I do it ? As you can see, the 1st listing in the MWE does have an empty caption, where it shouldn't.

MWE output

1
  • Two options. You can declare two different boxes one with title and one without and a third one where you test the title and decide to use one or another. The second solution could be to look what blend into listingds does and include this code in your box only when a title exists. Take a look a xparse library in tcolorbox documentation. In this answer which is not related with you r question can see how conditinals provided by xparse library can be used.
    – Ignasi
    Mar 12, 2021 at 9:05

0

You must log in to answer this question.

Browse other questions tagged .