blob: 63112830ba02eb9308cf92bc00c67c78b29bbb47 [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'
Larry Hastings40040df2015-05-23 17:41:13 -070037SOURCE_URI = 'https://hg.python.org/cpython/file/3.5/%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
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100148class PyCoroutineMixin(object):
149 def handle_signature(self, sig, signode):
150 ret = super(PyCoroutineMixin, self).handle_signature(sig, signode)
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100151 signode.insert(0, addnodes.desc_annotation('coroutine ', 'coroutine '))
152 return ret
153
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100154
155class PyCoroutineFunction(PyCoroutineMixin, PyModulelevel):
156 def run(self):
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100157 self.name = 'py:function'
158 return PyModulelevel.run(self)
159
160
161class PyCoroutineMethod(PyCoroutineMixin, PyClassmember):
162 def run(self):
163 self.name = 'py:method'
164 return PyClassmember.run(self)
165
166
Berker Peksag6e9d2e62015-12-08 12:14:50 +0200167class PyAbstractMethod(PyClassmember):
168
169 def handle_signature(self, sig, signode):
170 ret = super(PyAbstractMethod, self).handle_signature(sig, signode)
171 signode.insert(0, addnodes.desc_annotation('abstractmethod ',
172 'abstractmethod '))
173 return ret
174
175 def run(self):
176 self.name = 'py:method'
177 return PyClassmember.run(self)
178
179
Georg Brandl281d6ba2010-11-12 08:57:12 +0000180# Support for documenting version of removal in deprecations
181
Georg Brandl281d6ba2010-11-12 08:57:12 +0000182class DeprecatedRemoved(Directive):
183 has_content = True
184 required_arguments = 2
185 optional_arguments = 1
186 final_argument_whitespace = True
187 option_spec = {}
188
Georg Brandl7ed509a2014-01-21 19:20:31 +0100189 _label = 'Deprecated since version %s, will be removed in version %s'
190
Georg Brandl281d6ba2010-11-12 08:57:12 +0000191 def run(self):
192 node = addnodes.versionmodified()
193 node.document = self.state.document
194 node['type'] = 'deprecated-removed'
195 version = (self.arguments[0], self.arguments[1])
196 node['version'] = version
Georg Brandl7ed509a2014-01-21 19:20:31 +0100197 text = self._label % version
Georg Brandl281d6ba2010-11-12 08:57:12 +0000198 if len(self.arguments) == 3:
199 inodes, messages = self.state.inline_text(self.arguments[2],
200 self.lineno+1)
Georg Brandl7ed509a2014-01-21 19:20:31 +0100201 para = nodes.paragraph(self.arguments[2], '', *inodes)
202 node.append(para)
Georg Brandl281d6ba2010-11-12 08:57:12 +0000203 else:
Georg Brandl7ed509a2014-01-21 19:20:31 +0100204 messages = []
205 if self.content:
206 self.state.nested_parse(self.content, self.content_offset, node)
Berker Peksageb1a3cd2014-11-08 22:40:22 +0200207 if len(node):
Georg Brandl7ed509a2014-01-21 19:20:31 +0100208 if isinstance(node[0], nodes.paragraph) and node[0].rawsource:
209 content = nodes.inline(node[0].rawsource, translatable=True)
210 content.source = node[0].source
211 content.line = node[0].line
212 content += node[0].children
213 node[0].replace_self(nodes.paragraph('', '', content))
Berker Peksageb1a3cd2014-11-08 22:40:22 +0200214 node[0].insert(0, nodes.inline('', '%s: ' % text,
215 classes=['versionmodified']))
Ned Deilyb682fd32014-09-22 14:44:22 -0700216 else:
Georg Brandl7ed509a2014-01-21 19:20:31 +0100217 para = nodes.paragraph('', '',
Georg Brandl35903c82014-10-30 22:55:13 +0100218 nodes.inline('', '%s.' % text,
219 classes=['versionmodified']))
Berker Peksageb1a3cd2014-11-08 22:40:22 +0200220 node.append(para)
Georg Brandl281d6ba2010-11-12 08:57:12 +0000221 env = self.state.document.settings.env
222 env.note_versionchange('deprecated', version[0], node, self.lineno)
Georg Brandl7ed509a2014-01-21 19:20:31 +0100223 return [node] + messages
Georg Brandl281d6ba2010-11-12 08:57:12 +0000224
225
Georg Brandl2cac28b2012-09-30 15:10:06 +0200226# Support for including Misc/NEWS
227
Georg Brandl44d0c212012-10-01 19:08:50 +0200228issue_re = re.compile('([Ii])ssue #([0-9]+)')
229whatsnew_re = re.compile(r"(?im)^what's new in (.*?)\??$")
Georg Brandl2cac28b2012-09-30 15:10:06 +0200230
Georg Brandl35903c82014-10-30 22:55:13 +0100231
Georg Brandl2cac28b2012-09-30 15:10:06 +0200232class MiscNews(Directive):
233 has_content = False
234 required_arguments = 1
235 optional_arguments = 0
236 final_argument_whitespace = False
237 option_spec = {}
238
239 def run(self):
240 fname = self.arguments[0]
241 source = self.state_machine.input_lines.source(
242 self.lineno - self.state_machine.input_offset - 1)
243 source_dir = path.dirname(path.abspath(source))
Georg Brandl44d0c212012-10-01 19:08:50 +0200244 fpath = path.join(source_dir, fname)
245 self.state.document.settings.record_dependencies.add(fpath)
Georg Brandl2cac28b2012-09-30 15:10:06 +0200246 try:
Georg Brandl44d0c212012-10-01 19:08:50 +0200247 fp = codecs.open(fpath, encoding='utf-8')
Georg Brandl2cac28b2012-09-30 15:10:06 +0200248 try:
249 content = fp.read()
250 finally:
251 fp.close()
252 except Exception:
253 text = 'The NEWS file is not available.'
254 node = nodes.strong(text, text)
255 return [node]
Alex Gaynore285cdd2014-10-13 12:58:03 -0700256 content = issue_re.sub(r'`\1ssue #\2 <https://bugs.python.org/\2>`__',
Georg Brandl2cac28b2012-09-30 15:10:06 +0200257 content)
Georg Brandl44d0c212012-10-01 19:08:50 +0200258 content = whatsnew_re.sub(r'\1', content)
Georg Brandl2cac28b2012-09-30 15:10:06 +0200259 # remove first 3 lines as they are the main heading
Georg Brandl6c475812012-10-01 19:27:05 +0200260 lines = ['.. default-role:: obj', ''] + content.splitlines()[3:]
Georg Brandl2cac28b2012-09-30 15:10:06 +0200261 self.state_machine.insert_input(lines, fname)
262 return []
263
264
Georg Brandl6b38daa2008-06-01 21:05:17 +0000265# Support for building "topic help" for pydoc
266
267pydoc_topic_labels = [
268 'assert', 'assignment', 'atom-identifiers', 'atom-literals',
269 'attribute-access', 'attribute-references', 'augassign', 'binary',
270 'bitwise', 'bltin-code-objects', 'bltin-ellipsis-object',
Benjamin Peterson0d31d582010-06-06 02:44:41 +0000271 'bltin-null-object', 'bltin-type-objects', 'booleans',
Georg Brandl6b38daa2008-06-01 21:05:17 +0000272 'break', 'callable-types', 'calls', 'class', 'comparisons', 'compound',
273 'context-managers', 'continue', 'conversions', 'customization', 'debugger',
274 'del', 'dict', 'dynamic-features', 'else', 'exceptions', 'execmodel',
275 'exprlists', 'floating', 'for', 'formatstrings', 'function', 'global',
276 'id-classes', 'identifiers', 'if', 'imaginary', 'import', 'in', 'integers',
Benjamin Petersonf5a3d692010-08-31 14:31:01 +0000277 'lambda', 'lists', 'naming', 'nonlocal', 'numbers', 'numeric-types',
278 'objects', 'operator-summary', 'pass', 'power', 'raise', 'return',
279 'sequence-types', 'shifting', 'slicings', 'specialattrs', 'specialnames',
280 'string-methods', 'strings', 'subscriptions', 'truth', 'try', 'types',
281 'typesfunctions', 'typesmapping', 'typesmethods', 'typesmodules',
282 'typesseq', 'typesseq-mutable', 'unary', 'while', 'with', 'yield'
Georg Brandl6b38daa2008-06-01 21:05:17 +0000283]
284
Georg Brandl6b38daa2008-06-01 21:05:17 +0000285
286class PydocTopicsBuilder(Builder):
287 name = 'pydoc-topics'
288
289 def init(self):
290 self.topics = {}
291
292 def get_outdated_docs(self):
293 return 'all pydoc topics'
294
295 def get_target_uri(self, docname, typ=None):
296 return '' # no URIs
297
298 def write(self, *ignored):
299 writer = TextWriter(self)
Benjamin Peterson5879d412009-03-30 14:51:56 +0000300 for label in self.status_iterator(pydoc_topic_labels,
301 'building topics... ',
302 length=len(pydoc_topic_labels)):
Georg Brandl80ff2ad2010-07-31 08:27:46 +0000303 if label not in self.env.domaindata['std']['labels']:
Georg Brandl6b38daa2008-06-01 21:05:17 +0000304 self.warn('label %r not in documentation' % label)
305 continue
Georg Brandl80ff2ad2010-07-31 08:27:46 +0000306 docname, labelid, sectname = self.env.domaindata['std']['labels'][label]
Georg Brandl6b38daa2008-06-01 21:05:17 +0000307 doctree = self.env.get_and_resolve_doctree(docname, self)
308 document = new_document('<section node>')
309 document.append(doctree.ids[labelid])
310 destination = StringOutput(encoding='utf-8')
311 writer.write(document, destination)
Ned Deilyb682fd32014-09-22 14:44:22 -0700312 self.topics[label] = writer.output
Georg Brandl6b38daa2008-06-01 21:05:17 +0000313
314 def finish(self):
Ned Deilyb682fd32014-09-22 14:44:22 -0700315 f = open(path.join(self.outdir, 'topics.py'), 'wb')
Georg Brandl6b38daa2008-06-01 21:05:17 +0000316 try:
Ned Deilyb682fd32014-09-22 14:44:22 -0700317 f.write('# -*- coding: utf-8 -*-\n'.encode('utf-8'))
318 f.write(('# Autogenerated by Sphinx on %s\n' % asctime()).encode('utf-8'))
319 f.write(('topics = ' + pformat(self.topics) + '\n').encode('utf-8'))
Georg Brandl6b38daa2008-06-01 21:05:17 +0000320 finally:
321 f.close()
322
Georg Brandl495f7b52009-10-27 15:28:25 +0000323
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000324# Support for documenting Opcodes
325
Georg Brandl4833e5b2010-07-03 10:41:33 +0000326opcode_sig_re = re.compile(r'(\w+(?:\+\d)?)(?:\s*\((.*)\))?')
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000327
Georg Brandl35903c82014-10-30 22:55:13 +0100328
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000329def parse_opcode_signature(env, sig, signode):
330 """Transform an opcode signature into RST nodes."""
331 m = opcode_sig_re.match(sig)
332 if m is None:
333 raise ValueError
334 opname, arglist = m.groups()
335 signode += addnodes.desc_name(opname, opname)
Georg Brandl4833e5b2010-07-03 10:41:33 +0000336 if arglist is not None:
337 paramlist = addnodes.desc_parameterlist()
338 signode += paramlist
339 paramlist += addnodes.desc_parameter(arglist, arglist)
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000340 return opname.strip()
341
342
Georg Brandl281d6ba2010-11-12 08:57:12 +0000343# Support for documenting pdb commands
344
Georg Brandl02053ee2010-07-18 10:11:03 +0000345pdbcmd_sig_re = re.compile(r'([a-z()!]+)\s*(.*)')
346
347# later...
Georg Brandl35903c82014-10-30 22:55:13 +0100348# pdbargs_tokens_re = re.compile(r'''[a-zA-Z]+ | # identifiers
Georg Brandl02053ee2010-07-18 10:11:03 +0000349# [.,:]+ | # punctuation
350# [\[\]()] | # parens
351# \s+ # whitespace
352# ''', re.X)
353
Georg Brandl35903c82014-10-30 22:55:13 +0100354
Georg Brandl02053ee2010-07-18 10:11:03 +0000355def parse_pdb_command(env, sig, signode):
356 """Transform a pdb command signature into RST nodes."""
357 m = pdbcmd_sig_re.match(sig)
358 if m is None:
359 raise ValueError
360 name, args = m.groups()
361 fullname = name.replace('(', '').replace(')', '')
362 signode += addnodes.desc_name(name, name)
363 if args:
364 signode += addnodes.desc_addname(' '+args, ' '+args)
365 return fullname
366
367
Martin v. Löwis5680d0c2008-04-10 03:06:53 +0000368def setup(app):
369 app.add_role('issue', issue_role)
Georg Brandl68818862010-11-06 07:19:35 +0000370 app.add_role('source', source_role)
Georg Brandl495f7b52009-10-27 15:28:25 +0000371 app.add_directive('impl-detail', ImplementationDetail)
Georg Brandl281d6ba2010-11-12 08:57:12 +0000372 app.add_directive('deprecated-removed', DeprecatedRemoved)
Georg Brandl6b38daa2008-06-01 21:05:17 +0000373 app.add_builder(PydocTopicsBuilder)
Benjamin Peterson28d88b42009-01-09 03:03:23 +0000374 app.add_builder(suspicious.CheckSuspiciousMarkupBuilder)
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000375 app.add_description_unit('opcode', 'opcode', '%s (opcode)',
376 parse_opcode_signature)
Georg Brandl02053ee2010-07-18 10:11:03 +0000377 app.add_description_unit('pdbcommand', 'pdbcmd', '%s (pdb command)',
378 parse_pdb_command)
Benjamin Petersonf91df042009-02-13 02:50:59 +0000379 app.add_description_unit('2to3fixer', '2to3fixer', '%s (2to3 fixer)')
Georg Brandl8a1caa22010-07-29 16:01:11 +0000380 app.add_directive_to_domain('py', 'decorator', PyDecoratorFunction)
381 app.add_directive_to_domain('py', 'decoratormethod', PyDecoratorMethod)
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100382 app.add_directive_to_domain('py', 'coroutinefunction', PyCoroutineFunction)
383 app.add_directive_to_domain('py', 'coroutinemethod', PyCoroutineMethod)
Berker Peksag6e9d2e62015-12-08 12:14:50 +0200384 app.add_directive_to_domain('py', 'abstractmethod', PyAbstractMethod)
Georg Brandl2cac28b2012-09-30 15:10:06 +0200385 app.add_directive('miscnews', MiscNews)
Georg Brandlbae334c2014-09-30 22:17:41 +0200386 return {'version': '1.0', 'parallel_read_safe': True}