1

I'm trying to specifically input python code into a document. Therefore, I used lstinputlisting as such:

\lstinputlisting[language=Python, firstline=37, lastline=45, caption={this is a long caption},label={lst:testlabel}]{./code/test_code.py}

My first question is, is there an equivalent listpath like there is for a graphicspath for when you will be importing multiple listings from another directory? I've searched and I can't find it.

Secondly, what if I want to have a short and long caption for the listing? Something like

\lstinputlisting[language=Python, firstline=37, lastline=45, caption=[short caption]{this is a long caption},label={lst:testlabel}]{./code/test_code.py}

doesn't compile. Same with additional parameters, like if I want to make the listing a target for hyperref. This:

\lstinputlisting[language=Python, firstline=37, lastline=45, caption={this is a long caption},label={lst:testlabel},hypertarget{target}]{./code/test_code.py}

doesn't appear to work either. I would look into using lstlisting but it doesn't seem like it would work there either, especially since I'd prefer to import the code to keep it cleaner.

1 Answer 1

0

The square brackets inside optional arguments are not protected, thus \lstinputlisting would see language=..., caption=[short caption as optional argument and ] is the file name. Curly braces around the value help:

\lstinputlisting[
  language=python,
  firstline=37,
  lastline=45,
  caption={[short caption]{this is a long caption},
  ...
]{code/test_code.py}

There is no equivalent to \graphicspath for listings. Workarounds:

  • A macro can be used for the path component at the beginning of the file name.

  • Environment variable TEXINPUTS could include the source file directories.

  • An internal \input@path could be set, which also applies to input TeX files, packages, classes, e.g.:

    \makeatletter
    \def\input@path{{pathA/}{pathB/}}
    \makeatother
    

The hyper target can be set outside the listings at the beginning. The listings itself can cross page boundaries, which is not allowed for link targets.

You must log in to answer this question.

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