blob: 76f6a9f9d7f6431058d702e407eb9c330405ce3c [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
Alex Gaynore285cdd2014-10-13 12:58:03 -070012ISSUE_URI = 'https://bugs.python.org/issue%s'
Benjamin Peterson50ff8582014-09-13 01:45:50 -040013SOURCE_URI = 'https://hg.python.org/cpython/file/default/%s'
Martin v. Löwis5680d0c2008-04-10 03:06:53 +000014
15from docutils import nodes, utils
Georg Brandl239990d2013-10-12 20:50:21 +020016
Georg Brandl68818862010-11-06 07:19:35 +000017from sphinx.util.nodes import split_explicit_title
Georg Brandlf7b2f362014-02-16 09:46:36 +010018from sphinx.util.compat import Directive
Georg Brandl239990d2013-10-12 20:50:21 +020019from sphinx.writers.html import HTMLTranslator
20from sphinx.writers.latex import LaTeXTranslator
Martin v. Löwis5680d0c2008-04-10 03:06:53 +000021
Benjamin Peterson5c6d7872009-02-06 02:40:07 +000022# monkey-patch reST parser to disable alphabetic and roman enumerated lists
23from docutils.parsers.rst.states import Body
24Body.enum.converters['loweralpha'] = \
25 Body.enum.converters['upperalpha'] = \
26 Body.enum.converters['lowerroman'] = \
27 Body.enum.converters['upperroman'] = lambda x: None
28
Georg Brandl83e51f42012-10-10 16:45:11 +020029# monkey-patch HTML and LaTeX translators to keep doctest blocks in the
30# doctest docs themselves
31orig_visit_literal_block = HTMLTranslator.visit_literal_block
32def new_visit_literal_block(self, node):
33 meta = self.builder.env.metadata[self.builder.current_docname]
34 old_trim_doctest_flags = self.highlighter.trim_doctest_flags
35 if 'keepdoctest' in meta:
36 self.highlighter.trim_doctest_flags = False
37 try:
38 orig_visit_literal_block(self, node)
39 finally:
40 self.highlighter.trim_doctest_flags = old_trim_doctest_flags
41
42HTMLTranslator.visit_literal_block = new_visit_literal_block
43
44orig_depart_literal_block = LaTeXTranslator.depart_literal_block
45def new_depart_literal_block(self, node):
46 meta = self.builder.env.metadata[self.curfilestack[-1]]
47 old_trim_doctest_flags = self.highlighter.trim_doctest_flags
48 if 'keepdoctest' in meta:
49 self.highlighter.trim_doctest_flags = False
50 try:
51 orig_depart_literal_block(self, node)
52 finally:
53 self.highlighter.trim_doctest_flags = old_trim_doctest_flags
54
55LaTeXTranslator.depart_literal_block = new_depart_literal_block
Benjamin Peterson5c6d7872009-02-06 02:40:07 +000056
Georg Brandl495f7b52009-10-27 15:28:25 +000057# Support for marking up and linking to bugs.python.org issues
58
Martin v. Löwis5680d0c2008-04-10 03:06:53 +000059def issue_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
60 issue = utils.unescape(text)
61 text = 'issue ' + issue
62 refnode = nodes.reference(text, text, refuri=ISSUE_URI % issue)
63 return [refnode], []
64
65
Georg Brandl68818862010-11-06 07:19:35 +000066# Support for linking to Python source files easily
67
68def source_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
69 has_t, title, target = split_explicit_title(text)
70 title = utils.unescape(title)
71 target = utils.unescape(target)
72 refnode = nodes.reference(title, title, refuri=SOURCE_URI % target)
73 return [refnode], []
74
75
Georg Brandl495f7b52009-10-27 15:28:25 +000076# Support for marking up implementation details
77
Georg Brandl495f7b52009-10-27 15:28:25 +000078class ImplementationDetail(Directive):
79
80 has_content = True
81 required_arguments = 0
82 optional_arguments = 1
83 final_argument_whitespace = True
84
85 def run(self):
86 pnode = nodes.compound(classes=['impl-detail'])
87 content = self.content
88 add_text = nodes.strong('CPython implementation detail:',
89 'CPython implementation detail:')
90 if self.arguments:
91 n, m = self.state.inline_text(self.arguments[0], self.lineno)
92 pnode.append(nodes.paragraph('', '', *(n + m)))
93 self.state.nested_parse(content, self.content_offset, pnode)
94 if pnode.children and isinstance(pnode[0], nodes.paragraph):
95 pnode[0].insert(0, add_text)
96 pnode[0].insert(1, nodes.Text(' '))
97 else:
98 pnode.insert(0, nodes.paragraph('', '', add_text))
99 return [pnode]
100
101
Georg Brandl8a1caa22010-07-29 16:01:11 +0000102# Support for documenting decorators
103
104from sphinx import addnodes
105from sphinx.domains.python import PyModulelevel, PyClassmember
106
107class PyDecoratorMixin(object):
108 def handle_signature(self, sig, signode):
109 ret = super(PyDecoratorMixin, self).handle_signature(sig, signode)
110 signode.insert(0, addnodes.desc_addname('@', '@'))
111 return ret
112
113 def needs_arglist(self):
114 return False
115
116class PyDecoratorFunction(PyDecoratorMixin, PyModulelevel):
117 def run(self):
118 # a decorator function is a function after all
119 self.name = 'py:function'
120 return PyModulelevel.run(self)
121
122class PyDecoratorMethod(PyDecoratorMixin, PyClassmember):
123 def run(self):
124 self.name = 'py:method'
125 return PyClassmember.run(self)
126
127
Georg Brandl281d6ba2010-11-12 08:57:12 +0000128# Support for documenting version of removal in deprecations
129
Georg Brandl281d6ba2010-11-12 08:57:12 +0000130class DeprecatedRemoved(Directive):
131 has_content = True
132 required_arguments = 2
133 optional_arguments = 1
134 final_argument_whitespace = True
135 option_spec = {}
136
Georg Brandl7ed509a2014-01-21 19:20:31 +0100137 _label = 'Deprecated since version %s, will be removed in version %s'
138
Georg Brandl281d6ba2010-11-12 08:57:12 +0000139 def run(self):
140 node = addnodes.versionmodified()
141 node.document = self.state.document
142 node['type'] = 'deprecated-removed'
143 version = (self.arguments[0], self.arguments[1])
144 node['version'] = version
Georg Brandl7ed509a2014-01-21 19:20:31 +0100145 text = self._label % version
Georg Brandl281d6ba2010-11-12 08:57:12 +0000146 if len(self.arguments) == 3:
147 inodes, messages = self.state.inline_text(self.arguments[2],
148 self.lineno+1)
Georg Brandl7ed509a2014-01-21 19:20:31 +0100149 para = nodes.paragraph(self.arguments[2], '', *inodes)
150 node.append(para)
Georg Brandl281d6ba2010-11-12 08:57:12 +0000151 else:
Georg Brandl7ed509a2014-01-21 19:20:31 +0100152 messages = []
153 if self.content:
154 self.state.nested_parse(self.content, self.content_offset, node)
Georg Brandl7ed509a2014-01-21 19:20:31 +0100155 if isinstance(node[0], nodes.paragraph) and node[0].rawsource:
156 content = nodes.inline(node[0].rawsource, translatable=True)
157 content.source = node[0].source
158 content.line = node[0].line
159 content += node[0].children
160 node[0].replace_self(nodes.paragraph('', '', content))
Georg Brandlf7b2f362014-02-16 09:46:36 +0100161 node[0].insert(0, nodes.inline('', '%s: ' % text,
162 classes=['versionmodified']))
Ned Deilyb682fd32014-09-22 14:44:22 -0700163 else:
Georg Brandl7ed509a2014-01-21 19:20:31 +0100164 para = nodes.paragraph('', '',
165 nodes.inline('', '%s.' % text, classes=['versionmodified']))
Berker Peksageb265ab2014-08-22 18:24:29 +0300166 if len(node):
167 node.insert(0, para)
168 else:
169 node.append(para)
Georg Brandl281d6ba2010-11-12 08:57:12 +0000170 env = self.state.document.settings.env
171 env.note_versionchange('deprecated', version[0], node, self.lineno)
Georg Brandl7ed509a2014-01-21 19:20:31 +0100172 return [node] + messages
Georg Brandl281d6ba2010-11-12 08:57:12 +0000173
174
Georg Brandl2cac28b2012-09-30 15:10:06 +0200175# Support for including Misc/NEWS
176
177import re
178import codecs
Georg Brandl2cac28b2012-09-30 15:10:06 +0200179
Georg Brandl44d0c212012-10-01 19:08:50 +0200180issue_re = re.compile('([Ii])ssue #([0-9]+)')
181whatsnew_re = re.compile(r"(?im)^what's new in (.*?)\??$")
Georg Brandl2cac28b2012-09-30 15:10:06 +0200182
183class MiscNews(Directive):
184 has_content = False
185 required_arguments = 1
186 optional_arguments = 0
187 final_argument_whitespace = False
188 option_spec = {}
189
190 def run(self):
191 fname = self.arguments[0]
192 source = self.state_machine.input_lines.source(
193 self.lineno - self.state_machine.input_offset - 1)
194 source_dir = path.dirname(path.abspath(source))
Georg Brandl44d0c212012-10-01 19:08:50 +0200195 fpath = path.join(source_dir, fname)
196 self.state.document.settings.record_dependencies.add(fpath)
Georg Brandl2cac28b2012-09-30 15:10:06 +0200197 try:
Georg Brandl44d0c212012-10-01 19:08:50 +0200198 fp = codecs.open(fpath, encoding='utf-8')
Georg Brandl2cac28b2012-09-30 15:10:06 +0200199 try:
200 content = fp.read()
201 finally:
202 fp.close()
203 except Exception:
204 text = 'The NEWS file is not available.'
205 node = nodes.strong(text, text)
206 return [node]
Alex Gaynore285cdd2014-10-13 12:58:03 -0700207 content = issue_re.sub(r'`\1ssue #\2 <https://bugs.python.org/\2>`__',
Georg Brandl2cac28b2012-09-30 15:10:06 +0200208 content)
Georg Brandl44d0c212012-10-01 19:08:50 +0200209 content = whatsnew_re.sub(r'\1', content)
Georg Brandl2cac28b2012-09-30 15:10:06 +0200210 # remove first 3 lines as they are the main heading
Georg Brandl6c475812012-10-01 19:27:05 +0200211 lines = ['.. default-role:: obj', ''] + content.splitlines()[3:]
Georg Brandl2cac28b2012-09-30 15:10:06 +0200212 self.state_machine.insert_input(lines, fname)
213 return []
214
215
Georg Brandl6b38daa2008-06-01 21:05:17 +0000216# Support for building "topic help" for pydoc
217
218pydoc_topic_labels = [
219 'assert', 'assignment', 'atom-identifiers', 'atom-literals',
220 'attribute-access', 'attribute-references', 'augassign', 'binary',
221 'bitwise', 'bltin-code-objects', 'bltin-ellipsis-object',
Benjamin Peterson0d31d582010-06-06 02:44:41 +0000222 'bltin-null-object', 'bltin-type-objects', 'booleans',
Georg Brandl6b38daa2008-06-01 21:05:17 +0000223 'break', 'callable-types', 'calls', 'class', 'comparisons', 'compound',
224 'context-managers', 'continue', 'conversions', 'customization', 'debugger',
225 'del', 'dict', 'dynamic-features', 'else', 'exceptions', 'execmodel',
226 'exprlists', 'floating', 'for', 'formatstrings', 'function', 'global',
227 'id-classes', 'identifiers', 'if', 'imaginary', 'import', 'in', 'integers',
Benjamin Petersonf5a3d692010-08-31 14:31:01 +0000228 'lambda', 'lists', 'naming', 'nonlocal', 'numbers', 'numeric-types',
229 'objects', 'operator-summary', 'pass', 'power', 'raise', 'return',
230 'sequence-types', 'shifting', 'slicings', 'specialattrs', 'specialnames',
231 'string-methods', 'strings', 'subscriptions', 'truth', 'try', 'types',
232 'typesfunctions', 'typesmapping', 'typesmethods', 'typesmodules',
233 'typesseq', 'typesseq-mutable', 'unary', 'while', 'with', 'yield'
Georg Brandl6b38daa2008-06-01 21:05:17 +0000234]
235
236from os import path
237from time import asctime
238from pprint import pformat
239from docutils.io import StringOutput
240from docutils.utils import new_document
Benjamin Peterson6e43fb12008-12-21 00:16:13 +0000241
Benjamin Peterson28d88b42009-01-09 03:03:23 +0000242from sphinx.builders import Builder
243from sphinx.writers.text import TextWriter
Georg Brandldb6f1082008-12-01 23:02:51 +0000244
Georg Brandl6b38daa2008-06-01 21:05:17 +0000245
246class PydocTopicsBuilder(Builder):
247 name = 'pydoc-topics'
248
249 def init(self):
250 self.topics = {}
251
252 def get_outdated_docs(self):
253 return 'all pydoc topics'
254
255 def get_target_uri(self, docname, typ=None):
256 return '' # no URIs
257
258 def write(self, *ignored):
259 writer = TextWriter(self)
Benjamin Peterson5879d412009-03-30 14:51:56 +0000260 for label in self.status_iterator(pydoc_topic_labels,
261 'building topics... ',
262 length=len(pydoc_topic_labels)):
Georg Brandl80ff2ad2010-07-31 08:27:46 +0000263 if label not in self.env.domaindata['std']['labels']:
Georg Brandl6b38daa2008-06-01 21:05:17 +0000264 self.warn('label %r not in documentation' % label)
265 continue
Georg Brandl80ff2ad2010-07-31 08:27:46 +0000266 docname, labelid, sectname = self.env.domaindata['std']['labels'][label]
Georg Brandl6b38daa2008-06-01 21:05:17 +0000267 doctree = self.env.get_and_resolve_doctree(docname, self)
268 document = new_document('<section node>')
269 document.append(doctree.ids[labelid])
270 destination = StringOutput(encoding='utf-8')
271 writer.write(document, destination)
Ned Deilyb682fd32014-09-22 14:44:22 -0700272 self.topics[label] = writer.output
Georg Brandl6b38daa2008-06-01 21:05:17 +0000273
274 def finish(self):
Ned Deilyb682fd32014-09-22 14:44:22 -0700275 f = open(path.join(self.outdir, 'topics.py'), 'wb')
Georg Brandl6b38daa2008-06-01 21:05:17 +0000276 try:
Ned Deilyb682fd32014-09-22 14:44:22 -0700277 f.write('# -*- coding: utf-8 -*-\n'.encode('utf-8'))
278 f.write(('# Autogenerated by Sphinx on %s\n' % asctime()).encode('utf-8'))
279 f.write(('topics = ' + pformat(self.topics) + '\n').encode('utf-8'))
Georg Brandl6b38daa2008-06-01 21:05:17 +0000280 finally:
281 f.close()
282
Georg Brandl495f7b52009-10-27 15:28:25 +0000283
Benjamin Peterson28d88b42009-01-09 03:03:23 +0000284# Support for checking for suspicious markup
285
286import suspicious
Georg Brandl6b38daa2008-06-01 21:05:17 +0000287
Georg Brandl495f7b52009-10-27 15:28:25 +0000288
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000289# Support for documenting Opcodes
290
291import re
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000292
Georg Brandl4833e5b2010-07-03 10:41:33 +0000293opcode_sig_re = re.compile(r'(\w+(?:\+\d)?)(?:\s*\((.*)\))?')
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000294
295def parse_opcode_signature(env, sig, signode):
296 """Transform an opcode signature into RST nodes."""
297 m = opcode_sig_re.match(sig)
298 if m is None:
299 raise ValueError
300 opname, arglist = m.groups()
301 signode += addnodes.desc_name(opname, opname)
Georg Brandl4833e5b2010-07-03 10:41:33 +0000302 if arglist is not None:
303 paramlist = addnodes.desc_parameterlist()
304 signode += paramlist
305 paramlist += addnodes.desc_parameter(arglist, arglist)
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000306 return opname.strip()
307
308
Georg Brandl281d6ba2010-11-12 08:57:12 +0000309# Support for documenting pdb commands
310
Georg Brandl02053ee2010-07-18 10:11:03 +0000311pdbcmd_sig_re = re.compile(r'([a-z()!]+)\s*(.*)')
312
313# later...
314#pdbargs_tokens_re = re.compile(r'''[a-zA-Z]+ | # identifiers
315# [.,:]+ | # punctuation
316# [\[\]()] | # parens
317# \s+ # whitespace
318# ''', re.X)
319
320def parse_pdb_command(env, sig, signode):
321 """Transform a pdb command signature into RST nodes."""
322 m = pdbcmd_sig_re.match(sig)
323 if m is None:
324 raise ValueError
325 name, args = m.groups()
326 fullname = name.replace('(', '').replace(')', '')
327 signode += addnodes.desc_name(name, name)
328 if args:
329 signode += addnodes.desc_addname(' '+args, ' '+args)
330 return fullname
331
332
Martin v. Löwis5680d0c2008-04-10 03:06:53 +0000333def setup(app):
334 app.add_role('issue', issue_role)
Georg Brandl68818862010-11-06 07:19:35 +0000335 app.add_role('source', source_role)
Georg Brandl495f7b52009-10-27 15:28:25 +0000336 app.add_directive('impl-detail', ImplementationDetail)
Georg Brandl281d6ba2010-11-12 08:57:12 +0000337 app.add_directive('deprecated-removed', DeprecatedRemoved)
Georg Brandl6b38daa2008-06-01 21:05:17 +0000338 app.add_builder(PydocTopicsBuilder)
Benjamin Peterson28d88b42009-01-09 03:03:23 +0000339 app.add_builder(suspicious.CheckSuspiciousMarkupBuilder)
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000340 app.add_description_unit('opcode', 'opcode', '%s (opcode)',
341 parse_opcode_signature)
Georg Brandl02053ee2010-07-18 10:11:03 +0000342 app.add_description_unit('pdbcommand', 'pdbcmd', '%s (pdb command)',
343 parse_pdb_command)
Benjamin Petersonf91df042009-02-13 02:50:59 +0000344 app.add_description_unit('2to3fixer', '2to3fixer', '%s (2to3 fixer)')
Georg Brandl8a1caa22010-07-29 16:01:11 +0000345 app.add_directive_to_domain('py', 'decorator', PyDecoratorFunction)
346 app.add_directive_to_domain('py', 'decoratormethod', PyDecoratorMethod)
Georg Brandl2cac28b2012-09-30 15:10:06 +0200347 app.add_directive('miscnews', MiscNews)
Georg Brandlbae334c2014-09-30 22:17:41 +0200348 return {'version': '1.0', 'parallel_read_safe': True}