0

I need to add a second caption at the bottom of a listing for the source. But i didnt find how to achieve that. Is there some possibility?

Current minimal example:

\documentclass[12pt,oneside,titlepage,listof=totoc,bibliography=totoc]{scrartcl}
\usepackage[a4paper, left=4cm, right=2cm, top=4cm, bottom=2cm]{geometry}
\usepackage{listings}
\usepackage{scrlayer-scrpage}
\pagestyle{scrheadings}

\begin{document}

\section{some section}
Some Text.
\begin{lstlisting} [caption={some code},captionpos=t]
    int i = 0;
\end{lstlisting}
More Text. Below the figure should be a second caption with the source.

\end{document}

I know that i can position the caption with captionpos=b below the figure. But i want a second caption, which doesnt appear in the listings list.

1 Answer 1

1

Here's a simple solution that adds an extra listings option source (similar to caption) which displays the option's text below the corresponding listing.

For this we hook into the internal macro \lst@MakeCaption which is called before and after typesetting the listing's code to display the caption. In this case, if the user defined a source text, it's printed when \lst@MakeCaption is called below the listing. In the curent version the source is just displayed in a box with centered text, defined by the \lst@makesourcebox macro.

\documentclass[12pt,oneside,titlepage,listof=totoc,bibliography=totoc]{scrartcl}
\usepackage[a4paper, left=4cm, right=2cm, top=4cm, bottom=2cm]{geometry}
\usepackage{listings}
\usepackage{xcolor}

\makeatletter

\lst@Key{source}{}{\def\lst@source{#1}}

\let\orig@lst@MakeCaption=\lst@MakeCaption
\def\lst@MakeCaption#1{%
    \orig@lst@MakeCaption#1%
    \ifx b#1%
        \ifx\lst@source\@empty\else
            \noindent
            \expandafter\lst@makesourcebox\expandafter{\lst@source}%
            \vskip\belowcaptionskip
        \fi
    \fi
}

\def\lst@makesourcebox#1{%
    \makebox[\linewidth][c]{\itshape\small Source: #1}%
}

\makeatother

\lstset{backgroundcolor=\color{lightgray}}

\begin{document}

\section{some section}
Some Text.
\begin{lstlisting} [caption={some code}, captionpos=t, source={internet}]
    int i = 0;
\end{lstlisting}

\begin{lstlisting} [caption={comment}]
    // int i = 1;
\end{lstlisting}

\begin{lstlisting} [caption={more code}, captionpos=b, source={also internet}]
    int i = 2;
\end{lstlisting}
More Text. Below the figure should be a second caption with the source.

\end{document}

outputs

enter image description here

1
  • Awesome, thank you.
    – Dennis F.
    Oct 18, 2019 at 10:33

You must log in to answer this question.

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