blob: 0cade46f1b660c2c27f3c2ce343e3d1e425b3274 [file] [log] [blame]
Georg Brandlc3051922008-04-09 17:58:56 +00001# -*- coding: utf-8 -*-
2"""
3 pyspecific.py
4 ~~~~~~~~~~~~~
5
6 Sphinx extension with Python doc-specific markup.
7
Georg Brandlaf3ef922013-10-12 20:50:21 +02008 :copyright: 2008-2013 by Georg Brandl.
Georg Brandlc3051922008-04-09 17:58:56 +00009 :license: Python license.
10"""
11
12ISSUE_URI = 'http://bugs.python.org/issue%s'
Benjamin Peterson05137ed2014-09-13 01:44:34 -040013SOURCE_URI = 'https://hg.python.org/cpython/file/2.7/%s'
Georg Brandlc3051922008-04-09 17:58:56 +000014
15from docutils import nodes, utils
Georg Brandlaf3ef922013-10-12 20:50:21 +020016
17import sphinx
Sandro Tosid6e87f42012-01-14 16:42:21 +010018from sphinx.util.nodes import split_explicit_title
Georg Brandlaf3ef922013-10-12 20:50:21 +020019from sphinx.writers.html import HTMLTranslator
20from sphinx.writers.latex import LaTeXTranslator
21from sphinx.locale import versionlabels
Georg Brandlc3051922008-04-09 17:58:56 +000022
Georg Brandl85c5ccf2009-02-05 11:38:23 +000023# monkey-patch reST parser to disable alphabetic and roman enumerated lists
24from docutils.parsers.rst.states import Body
25Body.enum.converters['loweralpha'] = \
26 Body.enum.converters['upperalpha'] = \
27 Body.enum.converters['lowerroman'] = \
28 Body.enum.converters['upperroman'] = lambda x: None
29
Georg Brandlaf3ef922013-10-12 20:50:21 +020030if sphinx.__version__[:3] < '1.2':
31 # monkey-patch HTML translator to give versionmodified paragraphs a class
32 def new_visit_versionmodified(self, node):
33 self.body.append(self.starttag(node, 'p', CLASS=node['type']))
34 text = versionlabels[node['type']] % node['version']
35 if len(node):
36 text += ': '
37 else:
38 text += '.'
39 self.body.append('<span class="versionmodified">%s</span>' % text)
40 HTMLTranslator.visit_versionmodified = new_visit_versionmodified
Georg Brandl076ca5a2009-09-16 09:05:11 +000041
Georg Brandl74954562012-10-10 16:45:11 +020042# monkey-patch HTML and LaTeX translators to keep doctest blocks in the
43# doctest docs themselves
44orig_visit_literal_block = HTMLTranslator.visit_literal_block
45def new_visit_literal_block(self, node):
46 meta = self.builder.env.metadata[self.builder.current_docname]
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_visit_literal_block(self, node)
52 finally:
53 self.highlighter.trim_doctest_flags = old_trim_doctest_flags
54
55HTMLTranslator.visit_literal_block = new_visit_literal_block
56
57orig_depart_literal_block = LaTeXTranslator.depart_literal_block
58def new_depart_literal_block(self, node):
59 meta = self.builder.env.metadata[self.curfilestack[-1]]
60 old_trim_doctest_flags = self.highlighter.trim_doctest_flags
61 if 'keepdoctest' in meta:
62 self.highlighter.trim_doctest_flags = False
63 try:
64 orig_depart_literal_block(self, node)
65 finally:
66 self.highlighter.trim_doctest_flags = old_trim_doctest_flags
67
68LaTeXTranslator.depart_literal_block = new_depart_literal_block
Georg Brandl85c5ccf2009-02-05 11:38:23 +000069
Georg Brandl08be2e22009-10-22 08:05:04 +000070# Support for marking up and linking to bugs.python.org issues
71
Georg Brandlc3051922008-04-09 17:58:56 +000072def issue_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
73 issue = utils.unescape(text)
74 text = 'issue ' + issue
75 refnode = nodes.reference(text, text, refuri=ISSUE_URI % issue)
76 return [refnode], []
77
78
Éric Araujof595a762011-08-19 00:12:33 +020079# Support for linking to Python source files easily
80
81def source_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
Sandro Tosid6e87f42012-01-14 16:42:21 +010082 has_t, title, target = split_explicit_title(text)
83 title = utils.unescape(title)
84 target = utils.unescape(target)
85 refnode = nodes.reference(title, title, refuri=SOURCE_URI % target)
Éric Araujof595a762011-08-19 00:12:33 +020086 return [refnode], []
87
88
Georg Brandl08be2e22009-10-22 08:05:04 +000089# Support for marking up implementation details
90
91from sphinx.util.compat import Directive
92
93class ImplementationDetail(Directive):
94
95 has_content = True
96 required_arguments = 0
97 optional_arguments = 1
98 final_argument_whitespace = True
99
100 def run(self):
101 pnode = nodes.compound(classes=['impl-detail'])
102 content = self.content
Georg Brandla0547222009-10-22 11:01:46 +0000103 add_text = nodes.strong('CPython implementation detail:',
104 'CPython implementation detail:')
Georg Brandlf5f7c662009-10-22 11:28:23 +0000105 if self.arguments:
106 n, m = self.state.inline_text(self.arguments[0], self.lineno)
107 pnode.append(nodes.paragraph('', '', *(n + m)))
Georg Brandl08be2e22009-10-22 08:05:04 +0000108 self.state.nested_parse(content, self.content_offset, pnode)
Georg Brandla0547222009-10-22 11:01:46 +0000109 if pnode.children and isinstance(pnode[0], nodes.paragraph):
110 pnode[0].insert(0, add_text)
111 pnode[0].insert(1, nodes.Text(' '))
112 else:
113 pnode.insert(0, nodes.paragraph('', '', add_text))
Georg Brandl08be2e22009-10-22 08:05:04 +0000114 return [pnode]
115
116
Sandro Tosid6e87f42012-01-14 16:42:21 +0100117# Support for documenting decorators
118
119from sphinx import addnodes
120from sphinx.domains.python import PyModulelevel, PyClassmember
121
122class PyDecoratorMixin(object):
123 def handle_signature(self, sig, signode):
124 ret = super(PyDecoratorMixin, self).handle_signature(sig, signode)
125 signode.insert(0, addnodes.desc_addname('@', '@'))
126 return ret
127
128 def needs_arglist(self):
129 return False
130
131class PyDecoratorFunction(PyDecoratorMixin, PyModulelevel):
132 def run(self):
133 # a decorator function is a function after all
134 self.name = 'py:function'
135 return PyModulelevel.run(self)
136
137class PyDecoratorMethod(PyDecoratorMixin, PyClassmember):
138 def run(self):
139 self.name = 'py:method'
140 return PyClassmember.run(self)
141
142
143# Support for documenting version of removal in deprecations
144
145from sphinx.locale import versionlabels
146from sphinx.util.compat import Directive
147
148versionlabels['deprecated-removed'] = \
149 'Deprecated since version %s, will be removed in version %s'
150
151class DeprecatedRemoved(Directive):
152 has_content = True
153 required_arguments = 2
154 optional_arguments = 1
155 final_argument_whitespace = True
156 option_spec = {}
157
158 def run(self):
159 node = addnodes.versionmodified()
160 node.document = self.state.document
161 node['type'] = 'deprecated-removed'
162 version = (self.arguments[0], self.arguments[1])
163 node['version'] = version
164 if len(self.arguments) == 3:
165 inodes, messages = self.state.inline_text(self.arguments[2],
166 self.lineno+1)
167 node.extend(inodes)
168 if self.content:
169 self.state.nested_parse(self.content, self.content_offset, node)
170 ret = [node] + messages
171 else:
172 ret = [node]
173 env = self.state.document.settings.env
174 env.note_versionchange('deprecated', version[0], node, self.lineno)
175 return ret
176
177
Georg Brandl681001e2008-06-01 20:33:55 +0000178# Support for building "topic help" for pydoc
179
180pydoc_topic_labels = [
181 'assert', 'assignment', 'atom-identifiers', 'atom-literals',
182 'attribute-access', 'attribute-references', 'augassign', 'binary',
183 'bitwise', 'bltin-code-objects', 'bltin-ellipsis-object',
Sandro Tosid6e87f42012-01-14 16:42:21 +0100184 'bltin-null-object', 'bltin-type-objects', 'booleans',
185 'break', 'callable-types', 'calls', 'class', 'comparisons', 'compound',
186 'context-managers', 'continue', 'conversions', 'customization', 'debugger',
Ezio Melottif6c0ec42014-02-14 07:04:15 +0200187 'del', 'dict', 'dynamic-features', 'else', 'exceptions', 'exec', 'execmodel',
Sandro Tosid6e87f42012-01-14 16:42:21 +0100188 'exprlists', 'floating', 'for', 'formatstrings', 'function', 'global',
189 'id-classes', 'identifiers', 'if', 'imaginary', 'import', 'in', 'integers',
Benjamin Peterson71e2d2e2013-03-23 10:09:24 -0500190 'lambda', 'lists', 'naming', 'numbers', 'numeric-types',
Ezio Melottif6c0ec42014-02-14 07:04:15 +0200191 'objects', 'operator-summary', 'pass', 'power', 'print', 'raise', 'return',
Sandro Tosid6e87f42012-01-14 16:42:21 +0100192 'sequence-types', 'shifting', 'slicings', 'specialattrs', 'specialnames',
193 'string-methods', 'strings', 'subscriptions', 'truth', 'try', 'types',
194 'typesfunctions', 'typesmapping', 'typesmethods', 'typesmodules',
195 'typesseq', 'typesseq-mutable', 'unary', 'while', 'with', 'yield'
Georg Brandl681001e2008-06-01 20:33:55 +0000196]
197
198from os import path
199from time import asctime
200from pprint import pformat
201from docutils.io import StringOutput
202from docutils.utils import new_document
Benjamin Petersona2813c92008-12-20 23:48:54 +0000203
Benjamin Peterson1a67f582009-01-08 04:01:00 +0000204from sphinx.builders import Builder
205from sphinx.writers.text import TextWriter
Benjamin Petersoncb948f12008-12-01 12:52:51 +0000206
Georg Brandl681001e2008-06-01 20:33:55 +0000207
208class PydocTopicsBuilder(Builder):
209 name = 'pydoc-topics'
210
211 def init(self):
212 self.topics = {}
213
214 def get_outdated_docs(self):
215 return 'all pydoc topics'
216
217 def get_target_uri(self, docname, typ=None):
218 return '' # no URIs
219
220 def write(self, *ignored):
221 writer = TextWriter(self)
Benjamin Petersonc5206b32009-03-29 21:50:14 +0000222 for label in self.status_iterator(pydoc_topic_labels,
223 'building topics... ',
224 length=len(pydoc_topic_labels)):
Sandro Tosid6e87f42012-01-14 16:42:21 +0100225 if label not in self.env.domaindata['std']['labels']:
Georg Brandl681001e2008-06-01 20:33:55 +0000226 self.warn('label %r not in documentation' % label)
227 continue
Sandro Tosid6e87f42012-01-14 16:42:21 +0100228 docname, labelid, sectname = self.env.domaindata['std']['labels'][label]
Georg Brandl681001e2008-06-01 20:33:55 +0000229 doctree = self.env.get_and_resolve_doctree(docname, self)
230 document = new_document('<section node>')
231 document.append(doctree.ids[labelid])
232 destination = StringOutput(encoding='utf-8')
233 writer.write(document, destination)
Sandro Tosid6e87f42012-01-14 16:42:21 +0100234 self.topics[label] = str(writer.output)
Georg Brandl681001e2008-06-01 20:33:55 +0000235
236 def finish(self):
Georg Brandl43819252009-04-26 09:56:44 +0000237 f = open(path.join(self.outdir, 'topics.py'), 'w')
Georg Brandl681001e2008-06-01 20:33:55 +0000238 try:
239 f.write('# Autogenerated by Sphinx on %s\n' % asctime())
240 f.write('topics = ' + pformat(self.topics) + '\n')
241 finally:
242 f.close()
243
Georg Brandl08be2e22009-10-22 08:05:04 +0000244
Georg Brandl700cf282009-01-04 10:23:49 +0000245# Support for checking for suspicious markup
246
247import suspicious
Georg Brandl681001e2008-06-01 20:33:55 +0000248
Georg Brandl08be2e22009-10-22 08:05:04 +0000249
Georg Brandld4c7e632008-07-23 15:17:09 +0000250# Support for documenting Opcodes
251
252import re
Georg Brandld4c7e632008-07-23 15:17:09 +0000253
Sandro Tosid6e87f42012-01-14 16:42:21 +0100254opcode_sig_re = re.compile(r'(\w+(?:\+\d)?)(?:\s*\((.*)\))?')
Georg Brandld4c7e632008-07-23 15:17:09 +0000255
256def parse_opcode_signature(env, sig, signode):
257 """Transform an opcode signature into RST nodes."""
258 m = opcode_sig_re.match(sig)
259 if m is None:
260 raise ValueError
261 opname, arglist = m.groups()
262 signode += addnodes.desc_name(opname, opname)
Sandro Tosid6e87f42012-01-14 16:42:21 +0100263 if arglist is not None:
264 paramlist = addnodes.desc_parameterlist()
265 signode += paramlist
266 paramlist += addnodes.desc_parameter(arglist, arglist)
Georg Brandld4c7e632008-07-23 15:17:09 +0000267 return opname.strip()
268
269
Sandro Tosid6e87f42012-01-14 16:42:21 +0100270# Support for documenting pdb commands
271
272pdbcmd_sig_re = re.compile(r'([a-z()!]+)\s*(.*)')
273
274# later...
275#pdbargs_tokens_re = re.compile(r'''[a-zA-Z]+ | # identifiers
276# [.,:]+ | # punctuation
277# [\[\]()] | # parens
278# \s+ # whitespace
279# ''', re.X)
280
281def parse_pdb_command(env, sig, signode):
282 """Transform a pdb command signature into RST nodes."""
283 m = pdbcmd_sig_re.match(sig)
284 if m is None:
285 raise ValueError
286 name, args = m.groups()
287 fullname = name.replace('(', '').replace(')', '')
288 signode += addnodes.desc_name(name, name)
289 if args:
290 signode += addnodes.desc_addname(' '+args, ' '+args)
291 return fullname
292
293
Georg Brandlc3051922008-04-09 17:58:56 +0000294def setup(app):
295 app.add_role('issue', issue_role)
Éric Araujof595a762011-08-19 00:12:33 +0200296 app.add_role('source', source_role)
Georg Brandl08be2e22009-10-22 08:05:04 +0000297 app.add_directive('impl-detail', ImplementationDetail)
Sandro Tosid6e87f42012-01-14 16:42:21 +0100298 app.add_directive('deprecated-removed', DeprecatedRemoved)
Georg Brandl681001e2008-06-01 20:33:55 +0000299 app.add_builder(PydocTopicsBuilder)
Georg Brandl700cf282009-01-04 10:23:49 +0000300 app.add_builder(suspicious.CheckSuspiciousMarkupBuilder)
Georg Brandld4c7e632008-07-23 15:17:09 +0000301 app.add_description_unit('opcode', 'opcode', '%s (opcode)',
302 parse_opcode_signature)
Sandro Tosid6e87f42012-01-14 16:42:21 +0100303 app.add_description_unit('pdbcommand', 'pdbcmd', '%s (pdb command)',
304 parse_pdb_command)
Benjamin Petersone0820e22009-02-07 23:01:19 +0000305 app.add_description_unit('2to3fixer', '2to3fixer', '%s (2to3 fixer)')
Sandro Tosid6e87f42012-01-14 16:42:21 +0100306 app.add_directive_to_domain('py', 'decorator', PyDecoratorFunction)
307 app.add_directive_to_domain('py', 'decoratormethod', PyDecoratorMethod)