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?

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}
  • 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. – ThiefMaster Nov 27 '10 at 16:58
  • @ThiefMaster: I agree, it's pretty ugly to have the ":". – Hendrik Vogt Nov 27 '10 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.