Sphinx (documentation tool): set tab width in output

Question:

How do you set tab width in HTML output of Sphinx code snippets highlighted by Pygments?
By default it is the annoying 8, but I want 4.
Did not find a word about this setting in Sphinx conf.py.

Asked By: jbasko

||

Answers:

You will need to write a Sphinx Extension. Add your custom Lexer, and apply it with VisibleWhitespaceFilter.

Answered By: iElectric

I asked the same question on sphinx-dev group and it turns out it’s a problem with Docutils which is used by Sphinx. Docutils replace all tabs with 8 spaces and currently there is no way to change that value from Sphinx.

http://groups.google.com/group/sphinx-dev/browse_thread/thread/35b8071ffe9a8feb

The only feasible solution seems to be to follow the advice from S.Lott and John Paulett in comments to my question — use spaces instead of tabs.

Answered By: jbasko

Add something like this to your conf.py:

import re

def process_docstring(app, what, name, obj, options, lines):
    spaces_pat = re.compile(r"( {8})")
    ll = []
    for l in lines:
        ll.append(spaces_pat.sub("    ",l))
    lines[:] = ll

def setup(app):
    app.connect('autodoc-process-docstring', process_docstring)

See also Sphinx Docstring preprocessing documentation.

Answered By: gieffe

I’ve changes the font-size of the white-space in my custom.css This is a easy tweak and works very well. This will only change the code-block and nothing else. Which is what I wanted.

_static/custon.css

div.highlight pre .w {
    font-size: 50%;
}

Note: The solution of Docstring preprocessing was messing up my python code docstring which was causing error’s while build.

Answered By: Philippe Forest

There’s a way: add the following to conf.py

def setup(app):
    app.connect('autodoc-process-docstring', process_docstring)

def env_before_read_docs(app, env, docnames):
    env.settings["tab_width"] = 4

I’m not sure where the documentation is (so there’s no guarantee this API is stable), but there’s a comment in sphinx/environment/__init__.py:

# the docutils settings for building
self.settings = default_settings.copy()

which is precisely what we want here.

Answered By: user202729

In 2023, and with Sphinx v6.1.3 I have solved this problem by including a file named docutils.conf in the source folder, with the only content:

[restructuredtext parser]
tab_width: 4

and it worked!

I found this trick here

Answered By: Martí
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.