[Tex/LaTex] Adding caption and counter to source code environment

captionscounterslistingsmintedsourcecode

I have a source code listing with minted environment.
How can I make a counter/caption to be shown as follows.

enter image description here

I also need to make \tableofsourcecode to enlist all the source code references.

The used source code environment is minted.

\documentclass[article]{memoir}

\usepackage{listings}
\usepackage{xcolor}
\usepackage{textcomp}
\usepackage[T1]{fontenc}
\usepackage{minted}

\begin{document}

\begin{minted}[mathescape,
               linenos,
               numbersep=5pt,
               gobble=0,
               frame=lines,
               framesep=2mm,
               fontsize=\tiny]{java}
public static void main(String[] args) {
    try {
        Registry r = LocateRegistry.getRegistry();
        r.bind("printer", new RemotePrinterImpl());
    }
    catch (Exception e){
        e.printStackTrace();
    }
}
\end{minted}

\end{document} 

Best Answer

You can use the listing environment as follows:

\documentclass[article]{memoir}

\usepackage{listings}
\usepackage{xcolor}
\usepackage{textcomp}
\usepackage[T1]{fontenc}
\usepackage{minted}

\renewcommand\listingscaption{code}

\begin{document}

\listoflistings

\begin{listing}
\caption{main}
\begin{minted}[mathescape,
               linenos,
               numbersep=5pt,
               gobble=0,
               frame=lines,
               framesep=2mm,
               fontsize=\tiny]{java}
public static void main(String[] args) {
    try {
        Registry r = LocateRegistry.getRegistry();
        r.bind("printer", new RemotePrinterImpl());
    }
    catch (Exception e){
        e.printStackTrace();
    }
}
\end{minted}

\end{listing}

\end{document} 

The default caption would be 'Listing 1: main'. So you can change the listingcaption with \renewcommand\listingscaption{code} to whatever you want, 'code 1: main' in this case.

EDIT: to print a list of all listings, you can use the \listoflistings command.

Related Question