blob: d44b052540da92ec3fc7764bb1441a6f4829f2c7 [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
Georg Brandl281d6ba2010-11-12 08:57:12 +0000167# Support for documenting version of removal in deprecations
168
Georg Brandl281d6ba2010-11-12 08:57:12 +0000169class DeprecatedRemoved(Directive):
170 has_content = True
171 required_arguments = 2
172 optional_arguments = 1
173 final_argument_whitespace = True
174 option_spec = {}
175
Georg Brandl7ed509a2014-01-21 19:20:31 +0100176 _label = 'Deprecated since version %s, will be removed in version %s'
177
Georg Brandl281d6ba2010-11-12 08:57:12 +0000178 def run(self):
179 node = addnodes.versionmodified()
180 node.document = self.state.document
181 node['type'] = 'deprecated-removed'
182 version = (self.arguments[0], self.arguments[1])
183 node['version'] = version
Georg Brandl7ed509a2014-01-21 19:20:31 +0100184 text = self._label % version
Georg Brandl281d6ba2010-11-12 08:57:12 +0000185 if len(self.arguments) == 3:
186 inodes, messages = self.state.inline_text(self.arguments[2],
187 self.lineno+1)
Georg Brandl7ed509a2014-01-21 19:20:31 +0100188 para = nodes.paragraph(self.arguments[2], '', *inodes)
189 node.append(para)
Georg Brandl281d6ba2010-11-12 08:57:12 +0000190 else:
Georg Brandl7ed509a2014-01-21 19:20:31 +0100191 messages = []
192 if self.content:
193 self.state.nested_parse(self.content, self.content_offset, node)
Berker Peksageb1a3cd2014-11-08 22:40:22 +0200194 if len(node):
Georg Brandl7ed509a2014-01-21 19:20:31 +0100195 if isinstance(node[0], nodes.paragraph) and node[0].rawsource:
196 content = nodes.inline(node[0].rawsource, translatable=True)
197 content.source = node[0].source
198 content.line = node[0].line
199 content += node[0].children
200 node[0].replace_self(nodes.paragraph('', '', content))
Berker Peksageb1a3cd2014-11-08 22:40:22 +0200201 node[0].insert(0, nodes.inline('', '%s: ' % text,
202 classes=['versionmodified']))
Ned Deilyb682fd32014-09-22 14:44:22 -0700203 else:
Georg Brandl7ed509a2014-01-21 19:20:31 +0100204 para = nodes.paragraph('', '',
Georg Brandl35903c82014-10-30 22:55:13 +0100205 nodes.inline('', '%s.' % text,
206 classes=['versionmodified']))
Berker Peksageb1a3cd2014-11-08 22:40:22 +0200207 node.append(para)
Georg Brandl281d6ba2010-11-12 08:57:12 +0000208 env = self.state.document.settings.env
209 env.note_versionchange('deprecated', version[0], node, self.lineno)
Georg Brandl7ed509a2014-01-21 19:20:31 +0100210 return [node] + messages
Georg Brandl281d6ba2010-11-12 08:57:12 +0000211
212
Georg Brandl2cac28b2012-09-30 15:10:06 +0200213# Support for including Misc/NEWS
214
Georg Brandl44d0c212012-10-01 19:08:50 +0200215issue_re = re.compile('([Ii])ssue #([0-9]+)')
216whatsnew_re = re.compile(r"(?im)^what's new in (.*?)\??$")
Georg Brandl2cac28b2012-09-30 15:10:06 +0200217
Georg Brandl35903c82014-10-30 22:55:13 +0100218
Georg Brandl2cac28b2012-09-30 15:10:06 +0200219class MiscNews(Directive):
220 has_content = False
221 required_arguments = 1
222 optional_arguments = 0
223 final_argument_whitespace = False
224 option_spec = {}
225
226 def run(self):
227 fname = self.arguments[0]
228 source = self.state_machine.input_lines.source(
229 self.lineno - self.state_machine.input_offset - 1)
230 source_dir = path.dirname(path.abspath(source))
Georg Brandl44d0c212012-10-01 19:08:50 +0200231 fpath = path.join(source_dir, fname)
232 self.state.document.settings.record_dependencies.add(fpath)
Georg Brandl2cac28b2012-09-30 15:10:06 +0200233 try:
Georg Brandl44d0c212012-10-01 19:08:50 +0200234 fp = codecs.open(fpath, encoding='utf-8')
Georg Brandl2cac28b2012-09-30 15:10:06 +0200235 try:
236 content = fp.read()
237 finally:
238 fp.close()
239 except Exception:
240 text = 'The NEWS file is not available.'
241 node = nodes.strong(text, text)
242 return [node]
Alex Gaynore285cdd2014-10-13 12:58:03 -0700243 content = issue_re.sub(r'`\1ssue #\2 <https://bugs.python.org/\2>`__',
Georg Brandl2cac28b2012-09-30 15:10:06 +0200244 content)
Georg Brandl44d0c212012-10-01 19:08:50 +0200245 content = whatsnew_re.sub(r'\1', content)
Georg Brandl2cac28b2012-09-30 15:10:06 +0200246 # remove first 3 lines as they are the main heading
Georg Brandl6c475812012-10-01 19:27:05 +0200247 lines = ['.. default-role:: obj', ''] + content.splitlines()[3:]
Georg Brandl2cac28b2012-09-30 15:10:06 +0200248 self.state_machine.insert_input(lines, fname)
249 return []
250
251
Georg Brandl6b38daa2008-06-01 21:05:17 +0000252# Support for building "topic help" for pydoc
253
254pydoc_topic_labels = [
255 'assert', 'assignment', 'atom-identifiers', 'atom-literals',
256 'attribute-access', 'attribute-references', 'augassign', 'binary',
257 'bitwise', 'bltin-code-objects', 'bltin-ellipsis-object',
Benjamin Peterson0d31d582010-06-06 02:44:41 +0000258 'bltin-null-object', 'bltin-type-objects', 'booleans',
Georg Brandl6b38daa2008-06-01 21:05:17 +0000259 'break', 'callable-types', 'calls', 'class', 'comparisons', 'compound',
260 'context-managers', 'continue', 'conversions', 'customization', 'debugger',
261 'del', 'dict', 'dynamic-features', 'else', 'exceptions', 'execmodel',
262 'exprlists', 'floating', 'for', 'formatstrings', 'function', 'global',
263 'id-classes', 'identifiers', 'if', 'imaginary', 'import', 'in', 'integers',
Benjamin Petersonf5a3d692010-08-31 14:31:01 +0000264 'lambda', 'lists', 'naming', 'nonlocal', 'numbers', 'numeric-types',
265 'objects', 'operator-summary', 'pass', 'power', 'raise', 'return',
266 'sequence-types', 'shifting', 'slicings', 'specialattrs', 'specialnames',
267 'string-methods', 'strings', 'subscriptions', 'truth', 'try', 'types',
268 'typesfunctions', 'typesmapping', 'typesmethods', 'typesmodules',
269 'typesseq', 'typesseq-mutable', 'unary', 'while', 'with', 'yield'
Georg Brandl6b38daa2008-06-01 21:05:17 +0000270]
271
Georg Brandl6b38daa2008-06-01 21:05:17 +0000272
273class PydocTopicsBuilder(Builder):
274 name = 'pydoc-topics'
275
276 def init(self):
277 self.topics = {}
278
279 def get_outdated_docs(self):
280 return 'all pydoc topics'
281
282 def get_target_uri(self, docname, typ=None):
283 return '' # no URIs
284
285 def write(self, *ignored):
286 writer = TextWriter(self)
Benjamin Peterson5879d412009-03-30 14:51:56 +0000287 for label in self.status_iterator(pydoc_topic_labels,
288 'building topics... ',
289 length=len(pydoc_topic_labels)):
Georg Brandl80ff2ad2010-07-31 08:27:46 +0000290 if label not in self.env.domaindata['std']['labels']:
Georg Brandl6b38daa2008-06-01 21:05:17 +0000291 self.warn('label %r not in documentation' % label)
292 continue
Georg Brandl80ff2ad2010-07-31 08:27:46 +0000293 docname, labelid, sectname = self.env.domaindata['std']['labels'][label]
Georg Brandl6b38daa2008-06-01 21:05:17 +0000294 doctree = self.env.get_and_resolve_doctree(docname, self)
295 document = new_document('<section node>')
296 document.append(doctree.ids[labelid])
297 destination = StringOutput(encoding='utf-8')
298 writer.write(document, destination)
Ned Deilyb682fd32014-09-22 14:44:22 -0700299 self.topics[label] = writer.output
Georg Brandl6b38daa2008-06-01 21:05:17 +0000300
301 def finish(self):
Ned Deilyb682fd32014-09-22 14:44:22 -0700302 f = open(path.join(self.outdir, 'topics.py'), 'wb')
Georg Brandl6b38daa2008-06-01 21:05:17 +0000303 try:
Ned Deilyb682fd32014-09-22 14:44:22 -0700304 f.write('# -*- coding: utf-8 -*-\n'.encode('utf-8'))
305 f.write(('# Autogenerated by Sphinx on %s\n' % asctime()).encode('utf-8'))
306 f.write(('topics = ' + pformat(self.topics) + '\n').encode('utf-8'))
Georg Brandl6b38daa2008-06-01 21:05:17 +0000307 finally:
308 f.close()
309
Georg Brandl495f7b52009-10-27 15:28:25 +0000310
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000311# Support for documenting Opcodes
312
Georg Brandl4833e5b2010-07-03 10:41:33 +0000313opcode_sig_re = re.compile(r'(\w+(?:\+\d)?)(?:\s*\((.*)\))?')
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000314
Georg Brandl35903c82014-10-30 22:55:13 +0100315
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000316def parse_opcode_signature(env, sig, signode):
317 """Transform an opcode signature into RST nodes."""
318 m = opcode_sig_re.match(sig)
319 if m is None:
320 raise ValueError
321 opname, arglist = m.groups()
322 signode += addnodes.desc_name(opname, opname)
Georg Brandl4833e5b2010-07-03 10:41:33 +0000323 if arglist is not None:
324 paramlist = addnodes.desc_parameterlist()
325 signode += paramlist
326 paramlist += addnodes.desc_parameter(arglist, arglist)
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000327 return opname.strip()
328
329
Georg Brandl281d6ba2010-11-12 08:57:12 +0000330# Support for documenting pdb commands
331
Georg Brandl02053ee2010-07-18 10:11:03 +0000332pdbcmd_sig_re = re.compile(r'([a-z()!]+)\s*(.*)')
333
334# later...
Georg Brandl35903c82014-10-30 22:55:13 +0100335# pdbargs_tokens_re = re.compile(r'''[a-zA-Z]+ | # identifiers
Georg Brandl02053ee2010-07-18 10:11:03 +0000336# [.,:]+ | # punctuation
337# [\[\]()] | # parens
338# \s+ # whitespace
339# ''', re.X)
340
Georg Brandl35903c82014-10-30 22:55:13 +0100341
Georg Brandl02053ee2010-07-18 10:11:03 +0000342def parse_pdb_command(env, sig, signode):
343 """Transform a pdb command signature into RST nodes."""
344 m = pdbcmd_sig_re.match(sig)
345 if m is None:
346 raise ValueError
347 name, args = m.groups()
348 fullname = name.replace('(', '').replace(')', '')
349 signode += addnodes.desc_name(name, name)
350 if args:
351 signode += addnodes.desc_addname(' '+args, ' '+args)
352 return fullname
353
354
Martin v. Löwis5680d0c2008-04-10 03:06:53 +0000355def setup(app):
356 app.add_role('issue', issue_role)
Georg Brandl68818862010-11-06 07:19:35 +0000357 app.add_role('source', source_role)
Georg Brandl495f7b52009-10-27 15:28:25 +0000358 app.add_directive('impl-detail', ImplementationDetail)
Georg Brandl281d6ba2010-11-12 08:57:12 +0000359 app.add_directive('deprecated-removed', DeprecatedRemoved)
Georg Brandl6b38daa2008-06-01 21:05:17 +0000360 app.add_builder(PydocTopicsBuilder)
Benjamin Peterson28d88b42009-01-09 03:03:23 +0000361 app.add_builder(suspicious.CheckSuspiciousMarkupBuilder)
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000362 app.add_description_unit('opcode', 'opcode', '%s (opcode)',
363 parse_opcode_signature)
Georg Brandl02053ee2010-07-18 10:11:03 +0000364 app.add_description_unit('pdbcommand', 'pdbcmd', '%s (pdb command)',
365 parse_pdb_command)
Benjamin Petersonf91df042009-02-13 02:50:59 +0000366 app.add_description_unit('2to3fixer', '2to3fixer', '%s (2to3 fixer)')
Georg Brandl8a1caa22010-07-29 16:01:11 +0000367 app.add_directive_to_domain('py', 'decorator', PyDecoratorFunction)
368 app.add_directive_to_domain('py', 'decoratormethod', PyDecoratorMethod)
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100369 app.add_directive_to_domain('py', 'coroutinefunction', PyCoroutineFunction)
370 app.add_directive_to_domain('py', 'coroutinemethod', PyCoroutineMethod)
Georg Brandl2cac28b2012-09-30 15:10:06 +0200371 app.add_directive('miscnews', MiscNews)
Georg Brandlbae334c2014-09-30 22:17:41 +0200372 return {'version': '1.0', 'parallel_read_safe': True}