blob: 9b5a5e3849cc285ca992682395860b6f4c67e1da [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)
Georg Brandl7ed509a2014-01-21 19:20:31 +0100175 if isinstance(node[0], nodes.paragraph) and node[0].rawsource:
176 content = nodes.inline(node[0].rawsource, translatable=True)
177 content.source = node[0].source
178 content.line = node[0].line
179 content += node[0].children
180 node[0].replace_self(nodes.paragraph('', '', content))
Georg Brandlf7b2f362014-02-16 09:46:36 +0100181 node[0].insert(0, nodes.inline('', '%s: ' % text,
182 classes=['versionmodified']))
Georg Brandl90d76ca2014-09-22 21:18:24 +0200183 else:
Georg Brandl7ed509a2014-01-21 19:20:31 +0100184 para = nodes.paragraph('', '',
Georg Brandl35903c82014-10-30 22:55:13 +0100185 nodes.inline('', '%s.' % text,
186 classes=['versionmodified']))
Berker Peksageb265ab2014-08-22 18:24:29 +0300187 if len(node):
188 node.insert(0, para)
189 else:
190 node.append(para)
Georg Brandl281d6ba2010-11-12 08:57:12 +0000191 env = self.state.document.settings.env
192 env.note_versionchange('deprecated', version[0], node, self.lineno)
Georg Brandl7ed509a2014-01-21 19:20:31 +0100193 return [node] + messages
Georg Brandl281d6ba2010-11-12 08:57:12 +0000194
195
Georg Brandl2cac28b2012-09-30 15:10:06 +0200196# Support for including Misc/NEWS
197
Georg Brandl44d0c212012-10-01 19:08:50 +0200198issue_re = re.compile('([Ii])ssue #([0-9]+)')
199whatsnew_re = re.compile(r"(?im)^what's new in (.*?)\??$")
Georg Brandl2cac28b2012-09-30 15:10:06 +0200200
Georg Brandl35903c82014-10-30 22:55:13 +0100201
Georg Brandl2cac28b2012-09-30 15:10:06 +0200202class MiscNews(Directive):
203 has_content = False
204 required_arguments = 1
205 optional_arguments = 0
206 final_argument_whitespace = False
207 option_spec = {}
208
209 def run(self):
210 fname = self.arguments[0]
211 source = self.state_machine.input_lines.source(
212 self.lineno - self.state_machine.input_offset - 1)
213 source_dir = path.dirname(path.abspath(source))
Georg Brandl44d0c212012-10-01 19:08:50 +0200214 fpath = path.join(source_dir, fname)
215 self.state.document.settings.record_dependencies.add(fpath)
Georg Brandl2cac28b2012-09-30 15:10:06 +0200216 try:
Georg Brandl44d0c212012-10-01 19:08:50 +0200217 fp = codecs.open(fpath, encoding='utf-8')
Georg Brandl2cac28b2012-09-30 15:10:06 +0200218 try:
219 content = fp.read()
220 finally:
221 fp.close()
222 except Exception:
223 text = 'The NEWS file is not available.'
224 node = nodes.strong(text, text)
225 return [node]
Alex Gaynore6f8c502014-10-13 12:58:03 -0700226 content = issue_re.sub(r'`\1ssue #\2 <https://bugs.python.org/\2>`__',
Georg Brandl2cac28b2012-09-30 15:10:06 +0200227 content)
Georg Brandl44d0c212012-10-01 19:08:50 +0200228 content = whatsnew_re.sub(r'\1', content)
Georg Brandl2cac28b2012-09-30 15:10:06 +0200229 # remove first 3 lines as they are the main heading
Georg Brandl6c475812012-10-01 19:27:05 +0200230 lines = ['.. default-role:: obj', ''] + content.splitlines()[3:]
Georg Brandl2cac28b2012-09-30 15:10:06 +0200231 self.state_machine.insert_input(lines, fname)
232 return []
233
234
Georg Brandl6b38daa2008-06-01 21:05:17 +0000235# Support for building "topic help" for pydoc
236
237pydoc_topic_labels = [
238 'assert', 'assignment', 'atom-identifiers', 'atom-literals',
239 'attribute-access', 'attribute-references', 'augassign', 'binary',
240 'bitwise', 'bltin-code-objects', 'bltin-ellipsis-object',
Benjamin Peterson0d31d582010-06-06 02:44:41 +0000241 'bltin-null-object', 'bltin-type-objects', 'booleans',
Georg Brandl6b38daa2008-06-01 21:05:17 +0000242 'break', 'callable-types', 'calls', 'class', 'comparisons', 'compound',
243 'context-managers', 'continue', 'conversions', 'customization', 'debugger',
244 'del', 'dict', 'dynamic-features', 'else', 'exceptions', 'execmodel',
245 'exprlists', 'floating', 'for', 'formatstrings', 'function', 'global',
246 'id-classes', 'identifiers', 'if', 'imaginary', 'import', 'in', 'integers',
Benjamin Petersonf5a3d692010-08-31 14:31:01 +0000247 'lambda', 'lists', 'naming', 'nonlocal', 'numbers', 'numeric-types',
248 'objects', 'operator-summary', 'pass', 'power', 'raise', 'return',
249 'sequence-types', 'shifting', 'slicings', 'specialattrs', 'specialnames',
250 'string-methods', 'strings', 'subscriptions', 'truth', 'try', 'types',
251 'typesfunctions', 'typesmapping', 'typesmethods', 'typesmodules',
252 'typesseq', 'typesseq-mutable', 'unary', 'while', 'with', 'yield'
Georg Brandl6b38daa2008-06-01 21:05:17 +0000253]
254
Georg Brandl6b38daa2008-06-01 21:05:17 +0000255
256class PydocTopicsBuilder(Builder):
257 name = 'pydoc-topics'
258
259 def init(self):
260 self.topics = {}
261
262 def get_outdated_docs(self):
263 return 'all pydoc topics'
264
265 def get_target_uri(self, docname, typ=None):
266 return '' # no URIs
267
268 def write(self, *ignored):
269 writer = TextWriter(self)
Benjamin Peterson5879d412009-03-30 14:51:56 +0000270 for label in self.status_iterator(pydoc_topic_labels,
271 'building topics... ',
272 length=len(pydoc_topic_labels)):
Georg Brandl80ff2ad2010-07-31 08:27:46 +0000273 if label not in self.env.domaindata['std']['labels']:
Georg Brandl6b38daa2008-06-01 21:05:17 +0000274 self.warn('label %r not in documentation' % label)
275 continue
Georg Brandl80ff2ad2010-07-31 08:27:46 +0000276 docname, labelid, sectname = self.env.domaindata['std']['labels'][label]
Georg Brandl6b38daa2008-06-01 21:05:17 +0000277 doctree = self.env.get_and_resolve_doctree(docname, self)
278 document = new_document('<section node>')
279 document.append(doctree.ids[labelid])
280 destination = StringOutput(encoding='utf-8')
281 writer.write(document, destination)
Georg Brandl90d76ca2014-09-22 21:18:24 +0200282 self.topics[label] = writer.output
Georg Brandl6b38daa2008-06-01 21:05:17 +0000283
284 def finish(self):
Georg Brandl90d76ca2014-09-22 21:18:24 +0200285 f = open(path.join(self.outdir, 'topics.py'), 'wb')
Georg Brandl6b38daa2008-06-01 21:05:17 +0000286 try:
Georg Brandl90d76ca2014-09-22 21:18:24 +0200287 f.write('# -*- coding: utf-8 -*-\n'.encode('utf-8'))
288 f.write(('# Autogenerated by Sphinx on %s\n' % asctime()).encode('utf-8'))
289 f.write(('topics = ' + pformat(self.topics) + '\n').encode('utf-8'))
Georg Brandl6b38daa2008-06-01 21:05:17 +0000290 finally:
291 f.close()
292
Georg Brandl495f7b52009-10-27 15:28:25 +0000293
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000294# Support for documenting Opcodes
295
Georg Brandl4833e5b2010-07-03 10:41:33 +0000296opcode_sig_re = re.compile(r'(\w+(?:\+\d)?)(?:\s*\((.*)\))?')
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000297
Georg Brandl35903c82014-10-30 22:55:13 +0100298
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000299def parse_opcode_signature(env, sig, signode):
300 """Transform an opcode signature into RST nodes."""
301 m = opcode_sig_re.match(sig)
302 if m is None:
303 raise ValueError
304 opname, arglist = m.groups()
305 signode += addnodes.desc_name(opname, opname)
Georg Brandl4833e5b2010-07-03 10:41:33 +0000306 if arglist is not None:
307 paramlist = addnodes.desc_parameterlist()
308 signode += paramlist
309 paramlist += addnodes.desc_parameter(arglist, arglist)
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000310 return opname.strip()
311
312
Georg Brandl281d6ba2010-11-12 08:57:12 +0000313# Support for documenting pdb commands
314
Georg Brandl02053ee2010-07-18 10:11:03 +0000315pdbcmd_sig_re = re.compile(r'([a-z()!]+)\s*(.*)')
316
317# later...
Georg Brandl35903c82014-10-30 22:55:13 +0100318# pdbargs_tokens_re = re.compile(r'''[a-zA-Z]+ | # identifiers
Georg Brandl02053ee2010-07-18 10:11:03 +0000319# [.,:]+ | # punctuation
320# [\[\]()] | # parens
321# \s+ # whitespace
322# ''', re.X)
323
Georg Brandl35903c82014-10-30 22:55:13 +0100324
Georg Brandl02053ee2010-07-18 10:11:03 +0000325def parse_pdb_command(env, sig, signode):
326 """Transform a pdb command signature into RST nodes."""
327 m = pdbcmd_sig_re.match(sig)
328 if m is None:
329 raise ValueError
330 name, args = m.groups()
331 fullname = name.replace('(', '').replace(')', '')
332 signode += addnodes.desc_name(name, name)
333 if args:
334 signode += addnodes.desc_addname(' '+args, ' '+args)
335 return fullname
336
337
Martin v. Löwis5680d0c2008-04-10 03:06:53 +0000338def setup(app):
339 app.add_role('issue', issue_role)
Georg Brandl68818862010-11-06 07:19:35 +0000340 app.add_role('source', source_role)
Georg Brandl495f7b52009-10-27 15:28:25 +0000341 app.add_directive('impl-detail', ImplementationDetail)
Georg Brandl281d6ba2010-11-12 08:57:12 +0000342 app.add_directive('deprecated-removed', DeprecatedRemoved)
Georg Brandl6b38daa2008-06-01 21:05:17 +0000343 app.add_builder(PydocTopicsBuilder)
Benjamin Peterson28d88b42009-01-09 03:03:23 +0000344 app.add_builder(suspicious.CheckSuspiciousMarkupBuilder)
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000345 app.add_description_unit('opcode', 'opcode', '%s (opcode)',
346 parse_opcode_signature)
Georg Brandl02053ee2010-07-18 10:11:03 +0000347 app.add_description_unit('pdbcommand', 'pdbcmd', '%s (pdb command)',
348 parse_pdb_command)
Benjamin Petersonf91df042009-02-13 02:50:59 +0000349 app.add_description_unit('2to3fixer', '2to3fixer', '%s (2to3 fixer)')
Georg Brandl8a1caa22010-07-29 16:01:11 +0000350 app.add_directive_to_domain('py', 'decorator', PyDecoratorFunction)
351 app.add_directive_to_domain('py', 'decoratormethod', PyDecoratorMethod)
Georg Brandl2cac28b2012-09-30 15:10:06 +0200352 app.add_directive('miscnews', MiscNews)
Georg Brandlbae334c2014-09-30 22:17:41 +0200353 return {'version': '1.0', 'parallel_read_safe': True}