# Code highlighting for imported source files

I have several source code files that I would like to include in my document.

I know that I can use verbatiminput to get the lines from the file, and use lstlisting to highlight the code, but I cannot seem to use them both together. What I have in mind is something like:

\usepackage{listings}
\usepackage{verbatim}
\begin{document}
\lstset{language=Java}
\begin{lstlisting}[frame=single]
\verbatiminput{filename.java}
\end{lstlisting}
\end{document}


But naturally this does not work, as the \verbatiminput{filename.java} will not get executed inside of the lstlisting.

• don't use verbatiminput, listings has commands for including files, eg \lstinputlisting use instead of the lstlisting env, which is for code within the document – David Carlisle Nov 30 '13 at 22:32
• @DavidCarlisle that's definitely an answer. – masu Nov 30 '13 at 22:41
• @masu ah I hadn't actually tested it I just stole the words from an answer earlier today: tex.stackexchange.com/a/147758/1090 – David Carlisle Nov 30 '13 at 22:44

listings offers these commands:

1. \lstinline -- for code snippets (similar to \verb but can highlight code)
2. \lstlisting -- Environment where you can put your code in display mode.
3. \lstinputlisting -- for including standalone files.

Here is an example:

\documentclass{article}
\usepackage{filecontents}
\begin{filecontents*}{filename.java}
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World");
}
}
\end{filecontents*}
\usepackage{listings}

\begin{document}
\lstset{language=Java}
This is where a code snippet: \lstinline!public static HelloWorld {! comes

And here is the displayed code:

\begin{lstlisting}[frame=single]
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World");
}
}
\end{lstlisting}

And now to include an external source file:
\lstinputlisting[frame=single]{filename.java}
\end{document}


For your case, use \lstinputlisting