0

Can somebody please show the correct way to display my source code in LaTeX?

I want to display the following PHP code:

$id = addslashes($_GET['id']);

I tried to do it as follows, but I get an error about a label that has not yet been referenced:

\begin{lstlisting}
$id = addslashes($_GET['id']);
\label{phpheg}
\end{lstlisting}
1
  • Welcome to TeX.SE! Your post was migrated here from Stack Overflow. Please register on this site, too, and make sure that both accounts are associated with each other (by using the same OpenID), otherwise you won't be able to comment on or accept answers or edit your question. – Werner Oct 9 '16 at 15:18
3

As described in the documentation of the listings package, you have to define the caption and label in the options of the lstlisting environment. This is required because any text within lstlisting is typeset, so your code prints \label{phpheg} in the PDF, instead of calling that as a LaTeX command.

\documentclass{article}
\usepackage{listings}
\begin{document}
    See Listing~\ref{phpheg} for details.
\begin{lstlisting}[caption={PHP Code},label=phpheg]
$id = addslashes($_GET['id']);
\end{lstlisting}
    More text.
\end{document}

Note: as Werner says in his comment, as everything between \begin{lstlisting} and \end{lstlisting} is printed, thus indented code is also typeset indented. As a work-around, you can (and should) write the listing without any indention (as above).

As proposed by MaxNoe, you can use the lstautogobble package as a workaround: simply add \usepackage{autogobble} and set autogobble=true in the settings of lstlistings.

3
  • Be aware that indenting your lstlisting environment as well as the code contained within it may result in indentation when setting it. – Werner Oct 9 '16 at 4:54
  • there's lstautogobble – MaxNoe Oct 9 '16 at 10:10
  • Thanks for you inputs, I tried to make that more clear in my answer. – hbaderts Oct 9 '16 at 15:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy