Search code examples
python-sphinxrestructuredtext

Deindent Block in Sphinx literalinclude Directive


I have a block of code in a file that I want to include in an example in Sphinx documentation, using a literalinclude directive.

But that code is in a function, so when I include it, in the example each line is indented by one level more than I'd like.

.. literalinclude:: ../../examples/example.py
   :language: python
   :lines: 13-42
   :tab-width: 0

Produces

    import foo
    from foo import bar

    print("I'm indented too far")

Is there any other way to remove or deindent the literal block?


Solution

  • literalinclude has a dedent option:

    .. literalinclude:: ../../examples/example.py
       :language: python
       :lines: 13-42
       :tab-width: 0
       :dedent: 4
    

    The option is mentioned under "Additional options" in the literalinclude documentation, but the details are in the documentation for code-block.