Search code examples
latextexlistings

How to embed LaTeX keywords inside a LaTeX document using 'listings'


I want to cite LaTeX code into my document but how do I embed the keywords "\begin{lstlisting}" and "\end{lstlisting}" correctly?

CODE BELOW DOES NOT WORK (obviously):

\lstset{language=TeX, basicstyle=\footnotesize, numbers=left, numberstyle=\tiny, frame=single}

\begin{lstlisting}

\begin{lstlisting}          % this is code

place your source code here % this is code

\end{lstlisting}            % this is code

\end{lstlisting}

Solution

  • Do you have \usepackage{listings} in your preamble? If so, it should work. TeX is a supported language.

    Here's a minimal example:

    \documentclass{article}
    \usepackage{listings}
    \begin{document}
      This is a StackOverflow test file.\\
      To use \texttt{lstlisting}, include this in the preamble:
      \begin{lstlisting}
        \usepackage{listings}
      \end{lstlisting}
      Hope that helped :)
    \end{document}
    

    which compiles to

    enter image description here

    EDIT

    To quote commands from the listings package (actually, only for \end{lstlisting}), escape to latex to print the \ character and you're all set. In the following, I've defined @ as the escape character and everything within two @ symbols is typeset in LaTeX. So here, I've input the \ using LaTeX and the rest within lstlisting and the \end{...} sequence is not interpreted as a closing the environment.

    \documentclass{article}
    \usepackage{listings}
    \begin{document}
    This is a StackOverflow test file.\\
    Use escape characters to escape to \LaTeX 
    \lstset{escapechar=\@}
    \begin{lstlisting}
      \begin{lstlisting}
          some code here
      @\textbackslash@end{lstlisting}
    \end{lstlisting}
    Hope that helped :)
    \end{document}
    

    The output is

    enter image description here