18

How can I make the \lstinputlisting to search for files in a given directory? I'm thinking of a solution along the lines of the solution to this question.

I would like to have a solution like

\lstinputpath{/some/path/in/the/system}
\lstinputlisting{file.ext}

where file.ext resides in /some/path/in/the/system. I tried to search for such solution without luck. I found that inside of the definition of \lstinputlistings the authors use a \lst@inputpath. However, a naive modification of this macro doesn't yield any results.

20

The listings package provides a key called inputpath for specifying a path where \lstinputlisting should search for source files. Note that inputpath is only documented in the listings developer's guide, not in the user manual; if you haven't compiled the developer's guide, searching for "inputpath" in listings.dtx will lead you to the definition of the inputpath key. To use the latter, simply write

\lstset{inputpath=<path-in-question>}

somewhere in your document (not necessarily in your preamble, but after loading listings, of course). If you really insist on using a macro similar to \graphicspath, you can define an \lstinputpath macro yourself, like so

\newcommand*\lstinputpath[1]{\lstset{inputpath=#1}}

The code below assumes that the file sample.c resides in a subdirectory called test of your working directory.

enter image description here

\documentclass{article}

\usepackage{listings}

\newcommand*\lstinputpath[1]{\lstset{inputpath=#1}}

\lstinputpath{test}

\begin{document}
\lstinputlisting[
  language   = C,
  basicstyle = \ttfamily,
  frame      = single,
  caption    = {Hello world in C},
]{sample.c}
\end{document}
  • The use of the key is cleaner than redefining the macro. I didn't found that key when going through the code. Authors should really make that more clear. – adn Mar 25 '14 at 20:32
  • 1
    @adn See my edit. – jub0bs Mar 25 '14 at 21:31
  • Is there any way to bring up the developer's guide via texdoc? – Sean Allred Mar 31 '14 at 1:49
  • @SeanAllred I'm not sure, but I don't think so. The user's guide explains how to generate the developer's guide, though. – jub0bs Mar 31 '14 at 11:26
  • 1
    Are multiple paths allowed? If so, could you modify the answer to demonstrate multiple paths? – kando Sep 21 '16 at 18:25

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.