blob: 7baacc4757e28f1907c53c5a8e18df1d939bb3d7 [file] [log] [blame]
Martin v. Löwis5680d0c2008-04-10 03:06:53 +00001# -*- coding: utf-8 -*-
2"""
3 pyspecific.py
4 ~~~~~~~~~~~~~
5
6 Sphinx extension with Python doc-specific markup.
7
Georg Brandl7ed509a2014-01-21 19:20:31 +01008 :copyright: 2008-2014 by Georg Brandl.
Martin v. Löwis5680d0c2008-04-10 03:06:53 +00009 :license: Python license.
10"""
11
Georg Brandl35903c82014-10-30 22:55:13 +010012import re
13import codecs
14from os import path
15from time import asctime
16from pprint import pformat
17from docutils.io import StringOutput
18from docutils.utils import new_document
Martin v. Löwis5680d0c2008-04-10 03:06:53 +000019
20from docutils import nodes, utils
Georg Brandl239990d2013-10-12 20:50:21 +020021
Georg Brandl35903c82014-10-30 22:55:13 +010022from sphinx import addnodes
23from sphinx.builders import Builder
Georg Brandl68818862010-11-06 07:19:35 +000024from sphinx.util.nodes import split_explicit_title
Georg Brandlf7b2f362014-02-16 09:46:36 +010025from sphinx.util.compat import Directive
Georg Brandl239990d2013-10-12 20:50:21 +020026from sphinx.writers.html import HTMLTranslator
Georg Brandl35903c82014-10-30 22:55:13 +010027from sphinx.writers.text import TextWriter
Georg Brandl239990d2013-10-12 20:50:21 +020028from sphinx.writers.latex import LaTeXTranslator
Georg Brandl35903c82014-10-30 22:55:13 +010029from sphinx.domains.python import PyModulelevel, PyClassmember
30
31# Support for checking for suspicious markup
32
33import suspicious
34
35
36ISSUE_URI = 'https://bugs.python.org/issue%s'
37SOURCE_URI = 'https://hg.python.org/cpython/file/3.4/%s'
Martin v. Löwis5680d0c2008-04-10 03:06:53 +000038
Benjamin Peterson5c6d7872009-02-06 02:40:07 +000039# monkey-patch reST parser to disable alphabetic and roman enumerated lists
40from docutils.parsers.rst.states import Body
41Body.enum.converters['loweralpha'] = \
42 Body.enum.converters['upperalpha'] = \
43 Body.enum.converters['lowerroman'] = \
44 Body.enum.converters['upperroman'] = lambda x: None
45
Georg Brandl83e51f42012-10-10 16:45:11 +020046# monkey-patch HTML and LaTeX translators to keep doctest blocks in the
47# doctest docs themselves
48orig_visit_literal_block = HTMLTranslator.visit_literal_block
Georg Brandl35903c82014-10-30 22:55:13 +010049orig_depart_literal_block = LaTeXTranslator.depart_literal_block
50
51
Georg Brandl83e51f42012-10-10 16:45:11 +020052def new_visit_literal_block(self, node):
53 meta = self.builder.env.metadata[self.builder.current_docname]
54 old_trim_doctest_flags = self.highlighter.trim_doctest_flags
55 if 'keepdoctest' in meta:
56 self.highlighter.trim_doctest_flags = False
57 try:
58 orig_visit_literal_block(self, node)
59 finally:
60 self.highlighter.trim_doctest_flags = old_trim_doctest_flags
61
Georg Brandl83e51f42012-10-10 16:45:11 +020062
Georg Brandl83e51f42012-10-10 16:45:11 +020063def new_depart_literal_block(self, node):
64 meta = self.builder.env.metadata[self.curfilestack[-1]]
65 old_trim_doctest_flags = self.highlighter.trim_doctest_flags
66 if 'keepdoctest' in meta:
67 self.highlighter.trim_doctest_flags = False
68 try:
69 orig_depart_literal_block(self, node)
70 finally:
71 self.highlighter.trim_doctest_flags = old_trim_doctest_flags
72
Georg Brandl35903c82014-10-30 22:55:13 +010073
74HTMLTranslator.visit_literal_block = new_visit_literal_block
Georg Brandl83e51f42012-10-10 16:45:11 +020075LaTeXTranslator.depart_literal_block = new_depart_literal_block
Benjamin Peterson5c6d7872009-02-06 02:40:07 +000076
Georg Brandl35903c82014-10-30 22:55:13 +010077
Georg Brandl495f7b52009-10-27 15:28:25 +000078# Support for marking up and linking to bugs.python.org issues
79
Martin v. Löwis5680d0c2008-04-10 03:06:53 +000080def issue_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
81 issue = utils.unescape(text)
82 text = 'issue ' + issue
83 refnode = nodes.reference(text, text, refuri=ISSUE_URI % issue)
84 return [refnode], []
85
86
Georg Brandl68818862010-11-06 07:19:35 +000087# Support for linking to Python source files easily
88
89def source_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
90 has_t, title, target = split_explicit_title(text)
91 title = utils.unescape(title)
92 target = utils.unescape(target)
93 refnode = nodes.reference(title, title, refuri=SOURCE_URI % target)
94 return [refnode], []
95
96
Georg Brandl495f7b52009-10-27 15:28:25 +000097# Support for marking up implementation details
98
Georg Brandl495f7b52009-10-27 15:28:25 +000099class ImplementationDetail(Directive):
100
101 has_content = True
102 required_arguments = 0
103 optional_arguments = 1
104 final_argument_whitespace = True
105
106 def run(self):
107 pnode = nodes.compound(classes=['impl-detail'])
108 content = self.content
109 add_text = nodes.strong('CPython implementation detail:',
110 'CPython implementation detail:')
111 if self.arguments:
112 n, m = self.state.inline_text(self.arguments[0], self.lineno)
113 pnode.append(nodes.paragraph('', '', *(n + m)))
114 self.state.nested_parse(content, self.content_offset, pnode)
115 if pnode.children and isinstance(pnode[0], nodes.paragraph):
116 pnode[0].insert(0, add_text)
117 pnode[0].insert(1, nodes.Text(' '))
118 else:
119 pnode.insert(0, nodes.paragraph('', '', add_text))
120 return [pnode]
121
122
Georg Brandl8a1caa22010-07-29 16:01:11 +0000123# Support for documenting decorators
124
Georg Brandl8a1caa22010-07-29 16:01:11 +0000125class PyDecoratorMixin(object):
126 def handle_signature(self, sig, signode):
127 ret = super(PyDecoratorMixin, self).handle_signature(sig, signode)
128 signode.insert(0, addnodes.desc_addname('@', '@'))
129 return ret
130
131 def needs_arglist(self):
132 return False
133
Georg Brandl35903c82014-10-30 22:55:13 +0100134
Georg Brandl8a1caa22010-07-29 16:01:11 +0000135class PyDecoratorFunction(PyDecoratorMixin, PyModulelevel):
136 def run(self):
137 # a decorator function is a function after all
138 self.name = 'py:function'
139 return PyModulelevel.run(self)
140
Georg Brandl35903c82014-10-30 22:55:13 +0100141
Georg Brandl8a1caa22010-07-29 16:01:11 +0000142class PyDecoratorMethod(PyDecoratorMixin, PyClassmember):
143 def run(self):
144 self.name = 'py:method'
145 return PyClassmember.run(self)
146
147
Georg Brandl281d6ba2010-11-12 08:57:12 +0000148# Support for documenting version of removal in deprecations
149
Georg Brandl281d6ba2010-11-12 08:57:12 +0000150class DeprecatedRemoved(Directive):
151 has_content = True
152 required_arguments = 2
153 optional_arguments = 1
154 final_argument_whitespace = True
155 option_spec = {}
156
Georg Brandl7ed509a2014-01-21 19:20:31 +0100157 _label = 'Deprecated since version %s, will be removed in version %s'
158
Georg Brandl281d6ba2010-11-12 08:57:12 +0000159 def run(self):
160 node = addnodes.versionmodified()
161 node.document = self.state.document
162 node['type'] = 'deprecated-removed'
163 version = (self.arguments[0], self.arguments[1])
164 node['version'] = version
Georg Brandl7ed509a2014-01-21 19:20:31 +0100165 text = self._label % version
Georg Brandl281d6ba2010-11-12 08:57:12 +0000166 if len(self.arguments) == 3:
167 inodes, messages = self.state.inline_text(self.arguments[2],
168 self.lineno+1)
Georg Brandl7ed509a2014-01-21 19:20:31 +0100169 para = nodes.paragraph(self.arguments[2], '', *inodes)
170 node.append(para)
Georg Brandl281d6ba2010-11-12 08:57:12 +0000171 else:
Georg Brandl7ed509a2014-01-21 19:20:31 +0100172 messages = []
173 if self.content:
174 self.state.nested_parse(self.content, self.content_offset, node)
Berker Peksageb1a3cd2014-11-08 22:40:22 +0200175 if len(node):
Georg Brandl7ed509a2014-01-21 19:20:31 +0100176 if isinstance(node[0], nodes.paragraph) and node[0].rawsource:
177 content = nodes.inline(node[0].rawsource, translatable=True)
178 content.source = node[0].source
179 content.line = node[0].line
180 content += node[0].children
181 node[0].replace_self(nodes.paragraph('', '', content))
Berker Peksageb1a3cd2014-11-08 22:40:22 +0200182 node[0].insert(0, nodes.inline('', '%s: ' % text,
183 classes=['versionmodified']))
Georg Brandl90d76ca2014-09-22 21:18:24 +0200184 else:
Georg Brandl7ed509a2014-01-21 19:20:31 +0100185 para = nodes.paragraph('', '',
Georg Brandl35903c82014-10-30 22:55:13 +0100186 nodes.inline('', '%s.' % text,
187 classes=['versionmodified']))
Berker Peksageb1a3cd2014-11-08 22:40:22 +0200188 node.append(para)
Georg Brandl281d6ba2010-11-12 08:57:12 +0000189 env = self.state.document.settings.env
190 env.note_versionchange('deprecated', version[0], node, self.lineno)
Georg Brandl7ed509a2014-01-21 19:20:31 +0100191 return [node] + messages
Georg Brandl281d6ba2010-11-12 08:57:12 +0000192
193
Georg Brandl2cac28b2012-09-30 15:10:06 +0200194# Support for including Misc/NEWS
195
Georg Brandl44d0c212012-10-01 19:08:50 +0200196issue_re = re.compile('([Ii])ssue #([0-9]+)')
197whatsnew_re = re.compile(r"(?im)^what's new in (.*?)\??$")
Georg Brandl2cac28b2012-09-30 15:10:06 +0200198
Georg Brandl35903c82014-10-30 22:55:13 +0100199
Georg Brandl2cac28b2012-09-30 15:10:06 +0200200class MiscNews(Directive):
201 has_content = False
202 required_arguments = 1
203 optional_arguments = 0
204 final_argument_whitespace = False
205 option_spec = {}
206
207 def run(self):
208 fname = self.arguments[0]
209 source = self.state_machine.input_lines.source(
210 self.lineno - self.state_machine.input_offset - 1)
211 source_dir = path.dirname(path.abspath(source))
Georg Brandl44d0c212012-10-01 19:08:50 +0200212 fpath = path.join(source_dir, fname)
213 self.state.document.settings.record_dependencies.add(fpath)
Georg Brandl2cac28b2012-09-30 15:10:06 +0200214 try:
Georg Brandl44d0c212012-10-01 19:08:50 +0200215 fp = codecs.open(fpath, encoding='utf-8')
Georg Brandl2cac28b2012-09-30 15:10:06 +0200216 try:
217 content = fp.read()
218 finally:
219 fp.close()
220 except Exception:
221 text = 'The NEWS file is not available.'
222 node = nodes.strong(text, text)
223 return [node]
Alex Gaynore6f8c502014-10-13 12:58:03 -0700224 content = issue_re.sub(r'`\1ssue #\2 <https://bugs.python.org/\2>`__',
Georg Brandl2cac28b2012-09-30 15:10:06 +0200225 content)
Georg Brandl44d0c212012-10-01 19:08:50 +0200226 content = whatsnew_re.sub(r'\1', content)
Georg Brandl2cac28b2012-09-30 15:10:06 +0200227 # remove first 3 lines as they are the main heading
Georg Brandl6c475812012-10-01 19:27:05 +0200228 lines = ['.. default-role:: obj', ''] + content.splitlines()[3:]
Georg Brandl2cac28b2012-09-30 15:10:06 +0200229 self.state_machine.insert_input(lines, fname)
230 return []
231
232
Georg Brandl6b38daa2008-06-01 21:05:17 +0000233# Support for building "topic help" for pydoc
234
235pydoc_topic_labels = [
236 'assert', 'assignment', 'atom-identifiers', 'atom-literals',
237 'attribute-access', 'attribute-references', 'augassign', 'binary',
238 'bitwise', 'bltin-code-objects', 'bltin-ellipsis-object',
Benjamin Peterson0d31d582010-06-06 02:44:41 +0000239 'bltin-null-object', 'bltin-type-objects', 'booleans',
Georg Brandl6b38daa2008-06-01 21:05:17 +0000240 'break', 'callable-types', 'calls', 'class', 'comparisons', 'compound',
241 'context-managers', 'continue', 'conversions', 'customization', 'debugger',
242 'del', 'dict', 'dynamic-features', 'else', 'exceptions', 'execmodel',
243 'exprlists', 'floating', 'for', 'formatstrings', 'function', 'global',
244 'id-classes', 'identifiers', 'if', 'imaginary', 'import', 'in', 'integers',
Benjamin Petersonf5a3d692010-08-31 14:31:01 +0000245 'lambda', 'lists', 'naming', 'nonlocal', 'numbers', 'numeric-types',
246 'objects', 'operator-summary', 'pass', 'power', 'raise', 'return',
247 'sequence-types', 'shifting', 'slicings', 'specialattrs', 'specialnames',
248 'string-methods', 'strings', 'subscriptions', 'truth', 'try', 'types',
249 'typesfunctions', 'typesmapping', 'typesmethods', 'typesmodules',
250 'typesseq', 'typesseq-mutable', 'unary', 'while', 'with', 'yield'
Georg Brandl6b38daa2008-06-01 21:05:17 +0000251]
252
Georg Brandl6b38daa2008-06-01 21:05:17 +0000253
254class PydocTopicsBuilder(Builder):
255 name = 'pydoc-topics'
256
257 def init(self):
258 self.topics = {}
259
260 def get_outdated_docs(self):
261 return 'all pydoc topics'
262
263 def get_target_uri(self, docname, typ=None):
264 return '' # no URIs
265
266 def write(self, *ignored):
267 writer = TextWriter(self)
Benjamin Peterson5879d412009-03-30 14:51:56 +0000268 for label in self.status_iterator(pydoc_topic_labels,
269 'building topics... ',
270 length=len(pydoc_topic_labels)):
Georg Brandl80ff2ad2010-07-31 08:27:46 +0000271 if label not in self.env.domaindata['std']['labels']:
Georg Brandl6b38daa2008-06-01 21:05:17 +0000272 self.warn('label %r not in documentation' % label)
273 continue
Georg Brandl80ff2ad2010-07-31 08:27:46 +0000274 docname, labelid, sectname = self.env.domaindata['std']['labels'][label]
Georg Brandl6b38daa2008-06-01 21:05:17 +0000275 doctree = self.env.get_and_resolve_doctree(docname, self)
276 document = new_document('<section node>')
277 document.append(doctree.ids[labelid])
278 destination = StringOutput(encoding='utf-8')
279 writer.write(document, destination)
Georg Brandl90d76ca2014-09-22 21:18:24 +0200280 self.topics[label] = writer.output
Georg Brandl6b38daa2008-06-01 21:05:17 +0000281
282 def finish(self):
Georg Brandl90d76ca2014-09-22 21:18:24 +0200283 f = open(path.join(self.outdir, 'topics.py'), 'wb')
Georg Brandl6b38daa2008-06-01 21:05:17 +0000284 try:
Georg Brandl90d76ca2014-09-22 21:18:24 +0200285 f.write('# -*- coding: utf-8 -*-\n'.encode('utf-8'))
286 f.write(('# Autogenerated by Sphinx on %s\n' % asctime()).encode('utf-8'))
287 f.write(('topics = ' + pformat(self.topics) + '\n').encode('utf-8'))
Georg Brandl6b38daa2008-06-01 21:05:17 +0000288 finally:
289 f.close()
290
Georg Brandl495f7b52009-10-27 15:28:25 +0000291
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000292# Support for documenting Opcodes
293
Georg Brandl4833e5b2010-07-03 10:41:33 +0000294opcode_sig_re = re.compile(r'(\w+(?:\+\d)?)(?:\s*\((.*)\))?')
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000295
Georg Brandl35903c82014-10-30 22:55:13 +0100296
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000297def parse_opcode_signature(env, sig, signode):
298 """Transform an opcode signature into RST nodes."""
299 m = opcode_sig_re.match(sig)
300 if m is None:
301 raise ValueError
302 opname, arglist = m.groups()
303 signode += addnodes.desc_name(opname, opname)
Georg Brandl4833e5b2010-07-03 10:41:33 +0000304 if arglist is not None:
305 paramlist = addnodes.desc_parameterlist()
306 signode += paramlist
307 paramlist += addnodes.desc_parameter(arglist, arglist)
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000308 return opname.strip()
309
310
Georg Brandl281d6ba2010-11-12 08:57:12 +0000311# Support for documenting pdb commands
312
Georg Brandl02053ee2010-07-18 10:11:03 +0000313pdbcmd_sig_re = re.compile(r'([a-z()!]+)\s*(.*)')
314
315# later...
Georg Brandl35903c82014-10-30 22:55:13 +0100316# pdbargs_tokens_re = re.compile(r'''[a-zA-Z]+ | # identifiers
Georg Brandl02053ee2010-07-18 10:11:03 +0000317# [.,:]+ | # punctuation
318# [\[\]()] | # parens
319# \s+ # whitespace
320# ''', re.X)
321
Georg Brandl35903c82014-10-30 22:55:13 +0100322
Georg Brandl02053ee2010-07-18 10:11:03 +0000323def parse_pdb_command(env, sig, signode):
324 """Transform a pdb command signature into RST nodes."""
325 m = pdbcmd_sig_re.match(sig)
326 if m is None:
327 raise ValueError
328 name, args = m.groups()
329 fullname = name.replace('(', '').replace(')', '')
330 signode += addnodes.desc_name(name, name)
331 if args:
332 signode += addnodes.desc_addname(' '+args, ' '+args)
333 return fullname
334
335
Martin v. Löwis5680d0c2008-04-10 03:06:53 +0000336def setup(app):
337 app.add_role('issue', issue_role)
Georg Brandl68818862010-11-06 07:19:35 +0000338 app.add_role('source', source_role)
Georg Brandl495f7b52009-10-27 15:28:25 +0000339 app.add_directive('impl-detail', ImplementationDetail)
Georg Brandl281d6ba2010-11-12 08:57:12 +0000340 app.add_directive('deprecated-removed', DeprecatedRemoved)
Georg Brandl6b38daa2008-06-01 21:05:17 +0000341 app.add_builder(PydocTopicsBuilder)
Benjamin Peterson28d88b42009-01-09 03:03:23 +0000342 app.add_builder(suspicious.CheckSuspiciousMarkupBuilder)
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000343 app.add_description_unit('opcode', 'opcode', '%s (opcode)',
344 parse_opcode_signature)
Georg Brandl02053ee2010-07-18 10:11:03 +0000345 app.add_description_unit('pdbcommand', 'pdbcmd', '%s (pdb command)',
346 parse_pdb_command)
Benjamin Petersonf91df042009-02-13 02:50:59 +0000347 app.add_description_unit('2to3fixer', '2to3fixer', '%s (2to3 fixer)')
Georg Brandl8a1caa22010-07-29 16:01:11 +0000348 app.add_directive_to_domain('py', 'decorator', PyDecoratorFunction)
349 app.add_directive_to_domain('py', 'decoratormethod', PyDecoratorMethod)
Georg Brandl2cac28b2012-09-30 15:10:06 +0200350 app.add_directive('miscnews', MiscNews)
Georg Brandlbae334c2014-09-30 22:17:41 +0200351 return {'version': '1.0', 'parallel_read_safe': True}