[Tex/LaTex] Code highlighting for imported source files

highlightingsourcecodeverbatim

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.

Best Answer

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}

enter image description here

For your case, use \lstinputlisting