# how to include listings using \lstinputlisting

In a document embedding java code (actually processing) I can successfully embed listings using:

\begin[language=java]{lstlisting}
...
\end{lstlisting}


In an attempt to increase convenience, I wrote a new command that abbreviates this to:

\java

\end{lstlisting}


This works fine. However, in many instances it would be better to keep the listing external. This should be:

lstinputlisting[language=java]{code/openglprocessing/s00trianglegouraud.pde}


which I abbreviate:

\newcommand{\incjava}{\lstinputlisting[language=Java]}

\incjava{code/openglprocessing/s00trianglegouraud.pde}


Both formulations result in the following error:

! Undefined control sequence.
l.160 \incjava
{code/openglprocessing/s00trianglegouraud.pde}


While on the subject, is there any way to define a standard directory to avoid having to repeatedly refer to code/openglprocessing, in a similar manner to the graphics path for \includegraphics?

\graphicspath{ {img/} }

• Advice: Define a macro for the editor instead of LaTeX, the source code will be much more readable that way. – Johannes_B Jun 7 '15 at 12:50

Instead of \java, I would define an environment java. Then the \begin and \end macros are properly matched in the source code, also making some TeX editors happy. Such an environment is defined by \lstnewenvironment of package listings. Also an optional argument is added. Then the user can set some options in \begin{java}[...] for a particular listings.

The \incjava command should work as is does in the following example. Also this macro is given an optional argument for options to the particular listings.

\documentclass{article}
\usepackage{listings}

\lstnewenvironment{java}[1][]{%
\lstset{language=Java,#1}%
}{}

\newcommand*{\incjava}[1][]{%
\lstinputlisting[{language=Java,#1}]%
}

\begin{document}
\begin{java}
public class Example implements StringHandler {

/**
* Prints the given string.
*
* @param s  the given string
*/
@Override
public void handle(String s) {
System.out.println(s);
}

}
\end{java}

\incjava{Example.java}
\end{document}


There is no \listingspath for listing files, but \input@path for TeX files can be defined, e.g.:

\makeatletter
\providecommand*{\input@path}{}

Another variant is setting the environment variable TEXINPUTS to include the directory, example for TeX Live/Linux:
TEXINPUTS=:code/openglprocessing

The colon (Unix) or semicolon (Windows) at the beginning is important, because then the previous search path (from texmf.cnf) is added at this place.