Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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?

share|improve this question
add comment

3 Answers

up vote 5 down vote accepted

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}
share|improve this answer
    
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
add comment

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.

share|improve this answer
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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