doc: add sphinx numref compatibility fallback
[dpdk.git] / doc / guides / conf.py
1 #   BSD LICENSE
2 #   Copyright(c) 2010-2015 Intel Corporation. All rights reserved.
3 #   All rights reserved.
4 #
5 #   Redistribution and use in source and binary forms, with or without
6 #   modification, are permitted provided that the following conditions
7 #   are met:
8 #
9 #   * Redistributions of source code must retain the above copyright
10 #   notice, this list of conditions and the following disclaimer.
11 #   * Redistributions in binary form must reproduce the above copyright
12 #   notice, this list of conditions and the following disclaimer in
13 #   the documentation and/or other materials provided with the
14 #   distribution.
15 #   * Neither the name of Intel Corporation nor the names of its
16 #   contributors may be used to endorse or promote products derived
17 #   from this software without specific prior written permission.
18 #
19 #   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 #   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 #   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 #   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 #   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 #   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 #   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 #   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 #   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 #   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 #   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31 import subprocess
32 from docutils import nodes
33 from distutils.version import LooseVersion
34 from sphinx import __version__ as sphinx_version
35 from sphinx.highlighting import PygmentsBridge
36 from pygments.formatters.latex import LatexFormatter
37
38 project = 'DPDK'
39
40 html_show_copyright = False
41
42 version = subprocess.check_output(['make', '-sRrC', '../../', 'showversion']).decode('utf-8')
43 release = version
44
45 master_doc = 'index'
46
47 latex_documents = [
48     ('index',
49      'doc.tex',
50      '',
51      '',
52      'manual')
53 ]
54
55 # Latex directives to be included directly in the latex/pdf docs.
56 latex_preamble = r"""
57 \usepackage[utf8]{inputenc}
58 \usepackage{DejaVuSansMono}
59 \usepackage[T1]{fontenc}
60 \usepackage{helvet}
61 \renewcommand{\familydefault}{\sfdefault}
62 \RecustomVerbatimEnvironment{Verbatim}{Verbatim}{xleftmargin=5mm}
63 """
64
65 # Configuration for the latex/pdf docs.
66 latex_elements = {
67     'papersize': 'a4paper',
68     'pointsize': '11pt',
69     # remove blank pages
70     'classoptions': ',openany,oneside',
71     'babel': '\\usepackage[english]{babel}',
72     # customize Latex formatting
73     'preamble': latex_preamble
74 }
75
76 # Override the default Latex formatter in order to modify the
77 # code/verbatim blocks.
78 class CustomLatexFormatter(LatexFormatter):
79     def __init__(self, **options):
80         super(CustomLatexFormatter, self).__init__(**options)
81         # Use the second smallest font size for code/verbatim blocks.
82         self.verboptions = r'formatcom=\footnotesize'
83
84 # Replace the default latex formatter.
85 PygmentsBridge.latex_formatter = CustomLatexFormatter
86
87 ######## :numref: fallback ########
88 # The following hook functions add some simple handling for the :numref:
89 # directive for Sphinx versions prior to 1.3.1. The functions replace the
90 # :numref: reference with a link to the target (for all Sphinx doc types).
91 # It doesn't try to label figures/tables.
92
93 def numref_role(reftype, rawtext, text, lineno, inliner):
94     """
95     Add a Sphinx role to handle numref references. Note, we can't convert
96     the link here because the doctree isn't build and the target information
97     isn't available.
98     """
99     # Add an identifier to distinguish numref from other references.
100     newnode = nodes.reference('',
101                               '',
102                               refuri='_local_numref_#%s' % text,
103                               internal=True)
104     return [newnode], []
105
106 def process_numref(app, doctree, from_docname):
107     """
108     Process the numref nodes once the doctree has been built and prior to
109     writing the files. The processing involves replacing the numref with a
110     link plus text to indicate if it is a Figure or Table link.
111     """
112
113     # Iterate over the reference nodes in the doctree.
114     for node in doctree.traverse(nodes.reference):
115         target = node.get('refuri', '')
116
117         # Look for numref nodes.
118         if target.startswith('_local_numref_#'):
119             target = target.replace('_local_numref_#', '')
120
121             # Get the target label and link information from the Sphinx env.
122             data = app.builder.env.domains['std'].data
123             docname, label, _ = data['labels'].get(target, ('', '', ''))
124             relative_url = app.builder.get_relative_uri(from_docname, docname)
125
126             # Add a text label to the link.
127             if target.startswith('figure'):
128                 caption = 'Figure'
129             elif target.startswith('table'):
130                 caption = 'Table'
131             else:
132                 caption = 'Link'
133
134             # New reference node with the updated link information.
135             newnode = nodes.reference('',
136                                       caption,
137                                       refuri='%s#%s' % (relative_url, label),
138                                       internal=True)
139             node.replace_self(newnode)
140
141 def setup(app):
142     if LooseVersion(sphinx_version) < LooseVersion('1.3.1'):
143         print('Upgrade sphinx to version >= 1.3.1 for '
144               'improved Figure/Table number handling.')
145         # Add a role to handle :numref: references.
146         app.add_role('numref', numref_role)
147         # Process the numref references once the doctree has been created.
148         app.connect('doctree-resolved', process_numref)