9

I am trying to explore writing a .tex in a 'indentation' style, like this:

\documentclass{article}
\usepackage{listings}

\begin{document}
    Hello latex!
    \begin{lstlisting}[language=python, frame=single]
        def nice():
            print('This is a nice piece of code')
    \end{lstlisting}
\end{document}

However the output is unsatisfying because of the indentation before the code. The tabs push the code rightward and it is definitely not what I wanted.

A false example

Is there a way to set Listings to ignore a arbitrary number of indentations, like in this case, would be two? Or maybe make it smart so Listings can learn that the first line of code is the base code where following code indent on?

P.s. And I noticed some weird underline stuff going on in my picture. Don't know why though

1 Answer 1

11

You can use the gobble option to remove leading whitespace from the output of a listing. As you use “hard” tabulators, you should also tell it which tab size you prefer (option tabsize), because tabulators are expanded to spaces first.

The whitespace is displayed verbatim because it's in a string. The idea is that spaces matter there, but showstringspaces=false disables that feature. In most cases, the explicit spaces are not as annoying as in this short example.

To showcase these two options:

\documentclass{article}
\usepackage{listings}

\begin{document}
    Hello latex!

    \begin{lstlisting}[language=python, frame=single, gobble=8, tabsize=4]
        def nice():
            print('This is a nice piece of code')
    \end{lstlisting}

    \begin{lstlisting}[language=python, frame=single, gobble=8, tabsize=4, showstringspaces=false]
        def nicer(maybe):
            print('This is a nice piece of code')
    \end{lstlisting}
\end{document}

output

3
  • This did not move all my source code to the right. Tried \begin{lstlisting}[language=Java, numbers=none, frame=single, gobble=8, tabsize=4, showstringspaces=false] Aug 6, 2019 at 3:02
  • 1
    @GregHilston I don't understand. This answer is essentially about moving code to the left to compensate for extra indentation caused by trying to make the LaTeX source look “nice”. If you want to add extra indentation, you're better off asking a separate question. Or do you want some feature that automatically adds spaces in your LaTeX source code? In that case, the answer depends on your editor, but it almost certainly has nothing to do with the gobble option.
    – wrtlprnft
    Aug 6, 2019 at 5:09
  • 1
    I didn't understand what gobble did and I totally prematurely wrote the comment above. I ended up using autogobble and everything worked perfectly. Apologies, but thanks for the response! Aug 6, 2019 at 13:22

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .