I use this excellent approach for inserting external Python code in my document. How to highlight Python syntax in LaTeX Listings \lstinputlistings command

\pythonexternal[caption=test, label=lst.test.py]{test.py}

But how can I number the listing in my document?

I have tried:


The result: "! Package chngcntr Error: lstlisting is not a counter."

  • lstlisting - I have tried lstlistings, listing... nothing solved this problem... – GenXGer Jul 14 '18 at 13:35

The listings package delays the definition of the lstlisting counter until the AtBeginDocument phase. (See lines 1567 to 1576 in the file listings.sty for the complete details.) Hence, the \counterwithin{lstlisting}{section} instruction has to be wrapped in an \AtBeginDocument instruction in order to be successful.

enter image description here

\setcounter{section}{3} % just for this example
\begin{lstlisting}[caption={Hello World}]
  • Thank you very much! :) \AtBeginDocument{\counterwithin{lstlisting}{section}} solved my problem - thank you :) – GenXGer Jul 14 '18 at 14:03

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.