# listings interfering with babel

Consider this script:

\documentclass{article}
%\usepackage[latvian]{babel}
\usepackage{listings}
\begin{document}
\end{document}


I get an error

(/usr/local/texlive/2018/texmf-dist/tex/latex/listings/listings.cfg))
(./latvianpres.aux)

! LaTeX Error: No counter 'chapter' defined.


if I uncomment the line

%\usepackage[latvian]{babel}


What is the problem and how to solve it?

• latvian defines \thechapter and this confuses listings. I would say it is a babel-latvian bug. Notify the author. – Ulrike Fischer Dec 6 '18 at 19:31

It looks like a bug in Latvian babel (as Ulrike Fischer said). The file latvian.ldf (loaded by babel) defines \thechapter:

\def\thechapter{%
\ifx\chapter\undefined\relax\else
\arabic{chapter}.\fi}


independently if you are using a class with or without \chapters. Later on, \AtBeginDocument listings defines the lstlisting counter conditionally if \thechapter is defined:

\newcounter{lstlisting}[chapter]


or if not:

\newcounter{lstlisting}


When \thechapter exist (it does, when latvian.ldf is loaded), listings tries to hook the lstlisting counter to the chapter counter, which does not exist and you get the error.

You can work around it with this:

\documentclass{article}
\usepackage[latvian]{babel}
\usepackage{listings}

\let\THEchapter\thechapter
\let\thechapter\relax
\begin{document}
\let\thechapter\THEchapter

\end{document}

• :-/ Not that latvian.ldf should not be fixed (there is no "local" maintainer, and therefore I'm maintaining it in the sense I'm fixings bugs), but there is clearly a bug in the listings side, too: if the counter chapter is used, this is exactly what must be tested, and not another macro. – Javier Bezos Dec 8 '18 at 7:51
• @JavierBezos You're right, it really doesn't make much sense :/ – Phelype Oleinik Dec 9 '18 at 20:59