blob: 00acd4f55b8b9572783a4b824108dea8ccc50be2 [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
Victor Stinner272d8882017-06-16 08:59:01 +020013import io
Georg Brandl35903c82014-10-30 22:55:13 +010014from os import path
15from time import asctime
16from pprint import pformat
17from docutils.io import StringOutput
Ned Deily50f58162017-07-15 15:28:02 -040018from docutils.parsers.rst import Directive
Georg Brandl35903c82014-10-30 22:55:13 +010019from docutils.utils import new_document
Martin v. Löwis5680d0c2008-04-10 03:06:53 +000020
21from docutils import nodes, utils
Georg Brandl239990d2013-10-12 20:50:21 +020022
Georg Brandl35903c82014-10-30 22:55:13 +010023from sphinx import addnodes
24from sphinx.builders import Builder
INADA Naokic351ce62017-03-08 19:07:13 +090025from sphinx.locale import translators
Georg Brandl68818862010-11-06 07:19:35 +000026from sphinx.util.nodes import split_explicit_title
Georg Brandl239990d2013-10-12 20:50:21 +020027from sphinx.writers.html import HTMLTranslator
Georg Brandl35903c82014-10-30 22:55:13 +010028from sphinx.writers.text import TextWriter
Georg Brandl239990d2013-10-12 20:50:21 +020029from sphinx.writers.latex import LaTeXTranslator
Georg Brandl35903c82014-10-30 22:55:13 +010030from sphinx.domains.python import PyModulelevel, PyClassmember
31
32# Support for checking for suspicious markup
33
34import suspicious
35
36
37ISSUE_URI = 'https://bugs.python.org/issue%s'
Brett Cannon79ab8be2017-02-10 15:10:13 -080038SOURCE_URI = 'https://github.com/python/cpython/tree/master/%s'
Martin v. Löwis5680d0c2008-04-10 03:06:53 +000039
Benjamin Peterson5c6d7872009-02-06 02:40:07 +000040# monkey-patch reST parser to disable alphabetic and roman enumerated lists
41from docutils.parsers.rst.states import Body
42Body.enum.converters['loweralpha'] = \
43 Body.enum.converters['upperalpha'] = \
44 Body.enum.converters['lowerroman'] = \
45 Body.enum.converters['upperroman'] = lambda x: None
46
Georg Brandl83e51f42012-10-10 16:45:11 +020047# monkey-patch HTML and LaTeX translators to keep doctest blocks in the
48# doctest docs themselves
49orig_visit_literal_block = HTMLTranslator.visit_literal_block
Georg Brandl35903c82014-10-30 22:55:13 +010050orig_depart_literal_block = LaTeXTranslator.depart_literal_block
51
52
Georg Brandl83e51f42012-10-10 16:45:11 +020053def new_visit_literal_block(self, node):
54 meta = self.builder.env.metadata[self.builder.current_docname]
55 old_trim_doctest_flags = self.highlighter.trim_doctest_flags
56 if 'keepdoctest' in meta:
57 self.highlighter.trim_doctest_flags = False
58 try:
59 orig_visit_literal_block(self, node)
60 finally:
61 self.highlighter.trim_doctest_flags = old_trim_doctest_flags
62
Georg Brandl83e51f42012-10-10 16:45:11 +020063
Georg Brandl83e51f42012-10-10 16:45:11 +020064def new_depart_literal_block(self, node):
65 meta = self.builder.env.metadata[self.curfilestack[-1]]
66 old_trim_doctest_flags = self.highlighter.trim_doctest_flags
67 if 'keepdoctest' in meta:
68 self.highlighter.trim_doctest_flags = False
69 try:
70 orig_depart_literal_block(self, node)
71 finally:
72 self.highlighter.trim_doctest_flags = old_trim_doctest_flags
73
Georg Brandl35903c82014-10-30 22:55:13 +010074
75HTMLTranslator.visit_literal_block = new_visit_literal_block
Georg Brandl83e51f42012-10-10 16:45:11 +020076LaTeXTranslator.depart_literal_block = new_depart_literal_block
Benjamin Peterson5c6d7872009-02-06 02:40:07 +000077
Georg Brandl35903c82014-10-30 22:55:13 +010078
Georg Brandl495f7b52009-10-27 15:28:25 +000079# Support for marking up and linking to bugs.python.org issues
80
Martin v. Löwis5680d0c2008-04-10 03:06:53 +000081def issue_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
82 issue = utils.unescape(text)
Brett Cannon79ab8be2017-02-10 15:10:13 -080083 text = 'bpo-' + issue
Martin v. Löwis5680d0c2008-04-10 03:06:53 +000084 refnode = nodes.reference(text, text, refuri=ISSUE_URI % issue)
85 return [refnode], []
86
87
Georg Brandl68818862010-11-06 07:19:35 +000088# Support for linking to Python source files easily
89
90def source_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
91 has_t, title, target = split_explicit_title(text)
92 title = utils.unescape(title)
93 target = utils.unescape(target)
94 refnode = nodes.reference(title, title, refuri=SOURCE_URI % target)
95 return [refnode], []
96
97
Georg Brandl495f7b52009-10-27 15:28:25 +000098# Support for marking up implementation details
99
Georg Brandl495f7b52009-10-27 15:28:25 +0000100class ImplementationDetail(Directive):
101
102 has_content = True
103 required_arguments = 0
104 optional_arguments = 1
105 final_argument_whitespace = True
106
INADA Naokic351ce62017-03-08 19:07:13 +0900107 # This text is copied to templates/dummy.html
108 label_text = 'CPython implementation detail:'
109
Georg Brandl495f7b52009-10-27 15:28:25 +0000110 def run(self):
111 pnode = nodes.compound(classes=['impl-detail'])
INADA Naokic351ce62017-03-08 19:07:13 +0900112 label = translators['sphinx'].gettext(self.label_text)
Georg Brandl495f7b52009-10-27 15:28:25 +0000113 content = self.content
INADA Naokic351ce62017-03-08 19:07:13 +0900114 add_text = nodes.strong(label, label)
Georg Brandl495f7b52009-10-27 15:28:25 +0000115 if self.arguments:
116 n, m = self.state.inline_text(self.arguments[0], self.lineno)
117 pnode.append(nodes.paragraph('', '', *(n + m)))
118 self.state.nested_parse(content, self.content_offset, pnode)
119 if pnode.children and isinstance(pnode[0], nodes.paragraph):
INADA Naokic351ce62017-03-08 19:07:13 +0900120 content = nodes.inline(pnode[0].rawsource, translatable=True)
121 content.source = pnode[0].source
122 content.line = pnode[0].line
123 content += pnode[0].children
124 pnode[0].replace_self(nodes.paragraph('', '', content,
125 translatable=False))
Georg Brandl495f7b52009-10-27 15:28:25 +0000126 pnode[0].insert(0, add_text)
127 pnode[0].insert(1, nodes.Text(' '))
128 else:
129 pnode.insert(0, nodes.paragraph('', '', add_text))
130 return [pnode]
131
132
Georg Brandl8a1caa22010-07-29 16:01:11 +0000133# Support for documenting decorators
134
Georg Brandl8a1caa22010-07-29 16:01:11 +0000135class PyDecoratorMixin(object):
136 def handle_signature(self, sig, signode):
137 ret = super(PyDecoratorMixin, self).handle_signature(sig, signode)
138 signode.insert(0, addnodes.desc_addname('@', '@'))
139 return ret
140
141 def needs_arglist(self):
142 return False
143
Georg Brandl35903c82014-10-30 22:55:13 +0100144
Georg Brandl8a1caa22010-07-29 16:01:11 +0000145class PyDecoratorFunction(PyDecoratorMixin, PyModulelevel):
146 def run(self):
147 # a decorator function is a function after all
148 self.name = 'py:function'
149 return PyModulelevel.run(self)
150
Georg Brandl35903c82014-10-30 22:55:13 +0100151
Georg Brandl8a1caa22010-07-29 16:01:11 +0000152class PyDecoratorMethod(PyDecoratorMixin, PyClassmember):
153 def run(self):
154 self.name = 'py:method'
155 return PyClassmember.run(self)
156
157
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100158class PyCoroutineMixin(object):
159 def handle_signature(self, sig, signode):
160 ret = super(PyCoroutineMixin, self).handle_signature(sig, signode)
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100161 signode.insert(0, addnodes.desc_annotation('coroutine ', 'coroutine '))
162 return ret
163
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100164
165class PyCoroutineFunction(PyCoroutineMixin, PyModulelevel):
166 def run(self):
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100167 self.name = 'py:function'
168 return PyModulelevel.run(self)
169
170
171class PyCoroutineMethod(PyCoroutineMixin, PyClassmember):
172 def run(self):
173 self.name = 'py:method'
174 return PyClassmember.run(self)
175
176
Berker Peksag6e9d2e62015-12-08 12:14:50 +0200177class PyAbstractMethod(PyClassmember):
178
179 def handle_signature(self, sig, signode):
180 ret = super(PyAbstractMethod, self).handle_signature(sig, signode)
181 signode.insert(0, addnodes.desc_annotation('abstractmethod ',
182 'abstractmethod '))
183 return ret
184
185 def run(self):
186 self.name = 'py:method'
187 return PyClassmember.run(self)
188
189
Georg Brandl281d6ba2010-11-12 08:57:12 +0000190# Support for documenting version of removal in deprecations
191
Georg Brandl281d6ba2010-11-12 08:57:12 +0000192class DeprecatedRemoved(Directive):
193 has_content = True
194 required_arguments = 2
195 optional_arguments = 1
196 final_argument_whitespace = True
197 option_spec = {}
198
Georg Brandl7ed509a2014-01-21 19:20:31 +0100199 _label = 'Deprecated since version %s, will be removed in version %s'
200
Georg Brandl281d6ba2010-11-12 08:57:12 +0000201 def run(self):
202 node = addnodes.versionmodified()
203 node.document = self.state.document
204 node['type'] = 'deprecated-removed'
205 version = (self.arguments[0], self.arguments[1])
206 node['version'] = version
Georg Brandl7ed509a2014-01-21 19:20:31 +0100207 text = self._label % version
Georg Brandl281d6ba2010-11-12 08:57:12 +0000208 if len(self.arguments) == 3:
209 inodes, messages = self.state.inline_text(self.arguments[2],
210 self.lineno+1)
Georg Brandl7ed509a2014-01-21 19:20:31 +0100211 para = nodes.paragraph(self.arguments[2], '', *inodes)
212 node.append(para)
Georg Brandl281d6ba2010-11-12 08:57:12 +0000213 else:
Georg Brandl7ed509a2014-01-21 19:20:31 +0100214 messages = []
215 if self.content:
216 self.state.nested_parse(self.content, self.content_offset, node)
Berker Peksageb1a3cd2014-11-08 22:40:22 +0200217 if len(node):
Georg Brandl7ed509a2014-01-21 19:20:31 +0100218 if isinstance(node[0], nodes.paragraph) and node[0].rawsource:
219 content = nodes.inline(node[0].rawsource, translatable=True)
220 content.source = node[0].source
221 content.line = node[0].line
222 content += node[0].children
223 node[0].replace_self(nodes.paragraph('', '', content))
Berker Peksageb1a3cd2014-11-08 22:40:22 +0200224 node[0].insert(0, nodes.inline('', '%s: ' % text,
225 classes=['versionmodified']))
Ned Deilyb682fd32014-09-22 14:44:22 -0700226 else:
Georg Brandl7ed509a2014-01-21 19:20:31 +0100227 para = nodes.paragraph('', '',
Georg Brandl35903c82014-10-30 22:55:13 +0100228 nodes.inline('', '%s.' % text,
229 classes=['versionmodified']))
Berker Peksageb1a3cd2014-11-08 22:40:22 +0200230 node.append(para)
Georg Brandl281d6ba2010-11-12 08:57:12 +0000231 env = self.state.document.settings.env
232 env.note_versionchange('deprecated', version[0], node, self.lineno)
Georg Brandl7ed509a2014-01-21 19:20:31 +0100233 return [node] + messages
Georg Brandl281d6ba2010-11-12 08:57:12 +0000234
235
Georg Brandl2cac28b2012-09-30 15:10:06 +0200236# Support for including Misc/NEWS
237
Brett Cannon79ab8be2017-02-10 15:10:13 -0800238issue_re = re.compile('(?:[Ii]ssue #|bpo-)([0-9]+)')
Georg Brandl44d0c212012-10-01 19:08:50 +0200239whatsnew_re = re.compile(r"(?im)^what's new in (.*?)\??$")
Georg Brandl2cac28b2012-09-30 15:10:06 +0200240
Georg Brandl35903c82014-10-30 22:55:13 +0100241
Georg Brandl2cac28b2012-09-30 15:10:06 +0200242class MiscNews(Directive):
243 has_content = False
244 required_arguments = 1
245 optional_arguments = 0
246 final_argument_whitespace = False
247 option_spec = {}
248
249 def run(self):
250 fname = self.arguments[0]
251 source = self.state_machine.input_lines.source(
252 self.lineno - self.state_machine.input_offset - 1)
253 source_dir = path.dirname(path.abspath(source))
Georg Brandl44d0c212012-10-01 19:08:50 +0200254 fpath = path.join(source_dir, fname)
255 self.state.document.settings.record_dependencies.add(fpath)
Georg Brandl2cac28b2012-09-30 15:10:06 +0200256 try:
Victor Stinner272d8882017-06-16 08:59:01 +0200257 with io.open(fpath, encoding='utf-8') as fp:
Georg Brandl2cac28b2012-09-30 15:10:06 +0200258 content = fp.read()
Georg Brandl2cac28b2012-09-30 15:10:06 +0200259 except Exception:
260 text = 'The NEWS file is not available.'
261 node = nodes.strong(text, text)
262 return [node]
Brett Cannon79ab8be2017-02-10 15:10:13 -0800263 content = issue_re.sub(r'`bpo-\1 <https://bugs.python.org/issue\1>`__',
Georg Brandl2cac28b2012-09-30 15:10:06 +0200264 content)
Georg Brandl44d0c212012-10-01 19:08:50 +0200265 content = whatsnew_re.sub(r'\1', content)
Georg Brandl2cac28b2012-09-30 15:10:06 +0200266 # remove first 3 lines as they are the main heading
Georg Brandl6c475812012-10-01 19:27:05 +0200267 lines = ['.. default-role:: obj', ''] + content.splitlines()[3:]
Georg Brandl2cac28b2012-09-30 15:10:06 +0200268 self.state_machine.insert_input(lines, fname)
269 return []
270
271
Georg Brandl6b38daa2008-06-01 21:05:17 +0000272# Support for building "topic help" for pydoc
273
274pydoc_topic_labels = [
Jelle Zijlstraac317702017-10-05 20:24:46 -0700275 'assert', 'assignment', 'async', 'atom-identifiers', 'atom-literals',
276 'attribute-access', 'attribute-references', 'augassign', 'await',
277 'binary', 'bitwise', 'bltin-code-objects', 'bltin-ellipsis-object',
Benjamin Peterson0d31d582010-06-06 02:44:41 +0000278 'bltin-null-object', 'bltin-type-objects', 'booleans',
Georg Brandl6b38daa2008-06-01 21:05:17 +0000279 'break', 'callable-types', 'calls', 'class', 'comparisons', 'compound',
280 'context-managers', 'continue', 'conversions', 'customization', 'debugger',
281 'del', 'dict', 'dynamic-features', 'else', 'exceptions', 'execmodel',
282 'exprlists', 'floating', 'for', 'formatstrings', 'function', 'global',
283 'id-classes', 'identifiers', 'if', 'imaginary', 'import', 'in', 'integers',
Benjamin Petersonf5a3d692010-08-31 14:31:01 +0000284 'lambda', 'lists', 'naming', 'nonlocal', 'numbers', 'numeric-types',
285 'objects', 'operator-summary', 'pass', 'power', 'raise', 'return',
286 'sequence-types', 'shifting', 'slicings', 'specialattrs', 'specialnames',
287 'string-methods', 'strings', 'subscriptions', 'truth', 'try', 'types',
288 'typesfunctions', 'typesmapping', 'typesmethods', 'typesmodules',
289 'typesseq', 'typesseq-mutable', 'unary', 'while', 'with', 'yield'
Georg Brandl6b38daa2008-06-01 21:05:17 +0000290]
291
Georg Brandl6b38daa2008-06-01 21:05:17 +0000292
293class PydocTopicsBuilder(Builder):
294 name = 'pydoc-topics'
295
296 def init(self):
297 self.topics = {}
298
299 def get_outdated_docs(self):
300 return 'all pydoc topics'
301
302 def get_target_uri(self, docname, typ=None):
303 return '' # no URIs
304
305 def write(self, *ignored):
306 writer = TextWriter(self)
Benjamin Peterson5879d412009-03-30 14:51:56 +0000307 for label in self.status_iterator(pydoc_topic_labels,
308 'building topics... ',
309 length=len(pydoc_topic_labels)):
Georg Brandl80ff2ad2010-07-31 08:27:46 +0000310 if label not in self.env.domaindata['std']['labels']:
Georg Brandl6b38daa2008-06-01 21:05:17 +0000311 self.warn('label %r not in documentation' % label)
312 continue
Georg Brandl80ff2ad2010-07-31 08:27:46 +0000313 docname, labelid, sectname = self.env.domaindata['std']['labels'][label]
Georg Brandl6b38daa2008-06-01 21:05:17 +0000314 doctree = self.env.get_and_resolve_doctree(docname, self)
315 document = new_document('<section node>')
316 document.append(doctree.ids[labelid])
317 destination = StringOutput(encoding='utf-8')
318 writer.write(document, destination)
Ned Deilyb682fd32014-09-22 14:44:22 -0700319 self.topics[label] = writer.output
Georg Brandl6b38daa2008-06-01 21:05:17 +0000320
321 def finish(self):
Ned Deilyb682fd32014-09-22 14:44:22 -0700322 f = open(path.join(self.outdir, 'topics.py'), 'wb')
Georg Brandl6b38daa2008-06-01 21:05:17 +0000323 try:
Ned Deilyb682fd32014-09-22 14:44:22 -0700324 f.write('# -*- coding: utf-8 -*-\n'.encode('utf-8'))
325 f.write(('# Autogenerated by Sphinx on %s\n' % asctime()).encode('utf-8'))
326 f.write(('topics = ' + pformat(self.topics) + '\n').encode('utf-8'))
Georg Brandl6b38daa2008-06-01 21:05:17 +0000327 finally:
328 f.close()
329
Georg Brandl495f7b52009-10-27 15:28:25 +0000330
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000331# Support for documenting Opcodes
332
Georg Brandl4833e5b2010-07-03 10:41:33 +0000333opcode_sig_re = re.compile(r'(\w+(?:\+\d)?)(?:\s*\((.*)\))?')
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000334
Georg Brandl35903c82014-10-30 22:55:13 +0100335
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000336def parse_opcode_signature(env, sig, signode):
337 """Transform an opcode signature into RST nodes."""
338 m = opcode_sig_re.match(sig)
339 if m is None:
340 raise ValueError
341 opname, arglist = m.groups()
342 signode += addnodes.desc_name(opname, opname)
Georg Brandl4833e5b2010-07-03 10:41:33 +0000343 if arglist is not None:
344 paramlist = addnodes.desc_parameterlist()
345 signode += paramlist
346 paramlist += addnodes.desc_parameter(arglist, arglist)
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000347 return opname.strip()
348
349
Georg Brandl281d6ba2010-11-12 08:57:12 +0000350# Support for documenting pdb commands
351
Georg Brandl02053ee2010-07-18 10:11:03 +0000352pdbcmd_sig_re = re.compile(r'([a-z()!]+)\s*(.*)')
353
354# later...
Georg Brandl35903c82014-10-30 22:55:13 +0100355# pdbargs_tokens_re = re.compile(r'''[a-zA-Z]+ | # identifiers
Georg Brandl02053ee2010-07-18 10:11:03 +0000356# [.,:]+ | # punctuation
357# [\[\]()] | # parens
358# \s+ # whitespace
359# ''', re.X)
360
Georg Brandl35903c82014-10-30 22:55:13 +0100361
Georg Brandl02053ee2010-07-18 10:11:03 +0000362def parse_pdb_command(env, sig, signode):
363 """Transform a pdb command signature into RST nodes."""
364 m = pdbcmd_sig_re.match(sig)
365 if m is None:
366 raise ValueError
367 name, args = m.groups()
368 fullname = name.replace('(', '').replace(')', '')
369 signode += addnodes.desc_name(name, name)
370 if args:
371 signode += addnodes.desc_addname(' '+args, ' '+args)
372 return fullname
373
374
Martin v. Löwis5680d0c2008-04-10 03:06:53 +0000375def setup(app):
376 app.add_role('issue', issue_role)
Georg Brandl68818862010-11-06 07:19:35 +0000377 app.add_role('source', source_role)
Georg Brandl495f7b52009-10-27 15:28:25 +0000378 app.add_directive('impl-detail', ImplementationDetail)
Georg Brandl281d6ba2010-11-12 08:57:12 +0000379 app.add_directive('deprecated-removed', DeprecatedRemoved)
Georg Brandl6b38daa2008-06-01 21:05:17 +0000380 app.add_builder(PydocTopicsBuilder)
Benjamin Peterson28d88b42009-01-09 03:03:23 +0000381 app.add_builder(suspicious.CheckSuspiciousMarkupBuilder)
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000382 app.add_description_unit('opcode', 'opcode', '%s (opcode)',
383 parse_opcode_signature)
Georg Brandl02053ee2010-07-18 10:11:03 +0000384 app.add_description_unit('pdbcommand', 'pdbcmd', '%s (pdb command)',
385 parse_pdb_command)
Benjamin Petersonf91df042009-02-13 02:50:59 +0000386 app.add_description_unit('2to3fixer', '2to3fixer', '%s (2to3 fixer)')
Georg Brandl8a1caa22010-07-29 16:01:11 +0000387 app.add_directive_to_domain('py', 'decorator', PyDecoratorFunction)
388 app.add_directive_to_domain('py', 'decoratormethod', PyDecoratorMethod)
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100389 app.add_directive_to_domain('py', 'coroutinefunction', PyCoroutineFunction)
390 app.add_directive_to_domain('py', 'coroutinemethod', PyCoroutineMethod)
Berker Peksag6e9d2e62015-12-08 12:14:50 +0200391 app.add_directive_to_domain('py', 'abstractmethod', PyAbstractMethod)
Georg Brandl2cac28b2012-09-30 15:10:06 +0200392 app.add_directive('miscnews', MiscNews)
Georg Brandlbae334c2014-09-30 22:17:41 +0200393 return {'version': '1.0', 'parallel_read_safe': True}