6

When not specifying a caption for a lstlisting nothing is shown below the listing while "Listing #: mycaption" is displayed as soon as I specify a caption.

However, I'd like "Listing #" to be displayed for all listings; even those without a caption (those with a caption should keep their "Listing #: mycaption" of course). Is this possible? If yes, how?

3 Answers 3

5

You can use caption=\relax; however, then you'll get "Listing #:" with the colon. I don't know how to remove this.

EDIT: OK, here's a nasty hack that removes the colon if the caption is \relax. It works with my version of listings, but it might not work in future versions.

\documentclass{article}
\usepackage{listings}
\begin{document}
\makeatletter
\def\test@relax{\relax}
\let\save@fnum@lstlisting\fnum@lstlisting
\def\fnum@lstlisting{%
    \save@fnum@lstlisting
    \ifx\lst@caption\test@relax\expandafter\@gobble\fi
    }
\makeatother
\begin{lstlisting}[caption=\relax]
a:=b
\end{lstlisting}
\end{document}
2
  • I've already got that answer on IRC - with the caption below the listing that looks pretty ugly so it's not what I'm looking for. Commented Nov 27, 2010 at 16:58
  • @ThiefMaster: I agree, it's pretty ugly to have the ":". Commented Nov 27, 2010 at 17:10
1

My idea is everything else than a nice solution but here you go:

\newcommand\emptytitle{\lstlistingname\ \thelstlisting}
\newcommand\nextlst{\addtocounter{lstlisting}{1}}

\begin{lstlisting}[language=C,title=\emptytitle]
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    printf("Hallo Welt!\n");
    return EXIT_SUCCESS;
} /* end main() */
\end{lstlisting}

\nextlst
\begin{lstlisting}[language=C,title=\emptytitle]
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    printf("Hallo Welt!\n");
    return EXIT_SUCCESS;
} /* end main() */
\end{lstlisting}

Btw. \newcommand\emptytitle{\lstlistingname\ \thelstlisting \nextlst} does not work because somehow the counter makes +2 jumps.

0

My workaround was to pass this title argument

title={\lstlistingname\space\thelstlisting}

to each listing. This very tedious, but I'm using Lyx, so it's relatively simple to just copy listings arounds.

You must log in to answer this question.

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