process-docstring.py 1.58 KB
Newer Older
Robert McGibbon's avatar
Robert McGibbon committed
1
2
3
4
import re

def process_docstring(app, what, name, obj, options, lines):
    """This hook edits the docstrings to replace "<tt><pre>" html tags
5
    and deprecated markers with sphinx directives.
Robert McGibbon's avatar
Robert McGibbon committed
6
7
8
9
10
11
12
    """
    def repl(m):
        s = m.group(1)
        if not s.startswith(linesep):
            s = linesep + s
        newline = '.. code-block:: c++' + linesep
        return newline + '    ' + s.replace(linesep, linesep + '    ')
13
14
15
16
    def repl2(m):
        s = m.group(1)
        if not s.startswith(linesep):
            s = linesep + s
17
        newline = '|LINEBREAK|.. admonition::|LINEBREAK|   Deprecated' + linesep
18
        return newline + '    ' + s.replace(linesep, linesep + '    ')
John Chodera's avatar
John Chodera committed
19
20
21
    def repl3(m):
        s = m.group(1)
        return '*' + s + '*'
Robert McGibbon's avatar
Robert McGibbon committed
22
23
24
25
26
27

    linesep = '|LINEBREAK|'
    joined = linesep.join(lines)

    joined = re.sub(r'<tt><pre>((|LINEBREAK|)?.*?)</pre></tt>', repl, joined)
    joined = re.sub(r'<tt>(.*?)</tt>', repl, joined)
28
    joined = re.sub(r'@deprecated(.*?\|LINEBREAK\|)', repl2, joined, flags=re.IGNORECASE)
John Chodera's avatar
John Chodera committed
29
    joined = re.sub(r'<i>(.*?)</i>', repl3, joined)
Robert McGibbon's avatar
Robert McGibbon committed
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
    lines[:] = [(l if not l.isspace() else '') for l in joined.split(linesep)]


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


def test():
    lines    = ['Hello World', '<tt><pre>', 'contents', '</pre></tt>', '', '<tt>contents2</tt>']
    linesRef = ['Hello World', '.. code-block:: c++', '', '    contents', '', '', '.. code-block:: c++', '', '    contents2']
    process_docstring(None, None, None, None, None, lines)
    assert lines == linesRef

if __name__ == '__main__':
    test()