blob: 4b91253e080203f19c9b99c7f971edb80628a6e3 [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
Sandro Tosid6e87f42012-01-14 16:42:21 +01008 :copyright: 2008, 2009, 2010 by Georg Brandl.
Georg Brandlc3051922008-04-09 17:58:56 +00009 :license: Python license.
10"""
11
12ISSUE_URI = 'http://bugs.python.org/issue%s'
Éric Araujof595a762011-08-19 00:12:33 +020013SOURCE_URI = 'http://hg.python.org/cpython/file/2.7/%s'
Georg Brandlc3051922008-04-09 17:58:56 +000014
15from docutils import nodes, utils
Sandro Tosid6e87f42012-01-14 16:42:21 +010016from sphinx.util.nodes import split_explicit_title
Georg Brandlc3051922008-04-09 17:58:56 +000017
Georg Brandl85c5ccf2009-02-05 11:38:23 +000018# monkey-patch reST parser to disable alphabetic and roman enumerated lists
19from docutils.parsers.rst.states import Body
20Body.enum.converters['loweralpha'] = \
21 Body.enum.converters['upperalpha'] = \
22 Body.enum.converters['lowerroman'] = \
23 Body.enum.converters['upperroman'] = lambda x: None
24
Georg Brandl076ca5a2009-09-16 09:05:11 +000025# monkey-patch HTML translator to give versionmodified paragraphs a class
26def new_visit_versionmodified(self, node):
27 self.body.append(self.starttag(node, 'p', CLASS=node['type']))
28 text = versionlabels[node['type']] % node['version']
29 if len(node):
30 text += ': '
31 else:
32 text += '.'
33 self.body.append('<span class="versionmodified">%s</span>' % text)
34
35from sphinx.writers.html import HTMLTranslator
36from sphinx.locale import versionlabels
37HTMLTranslator.visit_versionmodified = new_visit_versionmodified
38
Georg Brandl85c5ccf2009-02-05 11:38:23 +000039
Georg Brandl08be2e22009-10-22 08:05:04 +000040# Support for marking up and linking to bugs.python.org issues
41
Georg Brandlc3051922008-04-09 17:58:56 +000042def issue_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
43 issue = utils.unescape(text)
44 text = 'issue ' + issue
45 refnode = nodes.reference(text, text, refuri=ISSUE_URI % issue)
46 return [refnode], []
47
48
Éric Araujof595a762011-08-19 00:12:33 +020049# Support for linking to Python source files easily
50
51def source_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
Sandro Tosid6e87f42012-01-14 16:42:21 +010052 has_t, title, target = split_explicit_title(text)
53 title = utils.unescape(title)
54 target = utils.unescape(target)
55 refnode = nodes.reference(title, title, refuri=SOURCE_URI % target)
Éric Araujof595a762011-08-19 00:12:33 +020056 return [refnode], []
57
58
Georg Brandl08be2e22009-10-22 08:05:04 +000059# Support for marking up implementation details
60
61from sphinx.util.compat import Directive
62
63class ImplementationDetail(Directive):
64
65 has_content = True
66 required_arguments = 0
67 optional_arguments = 1
68 final_argument_whitespace = True
69
70 def run(self):
71 pnode = nodes.compound(classes=['impl-detail'])
72 content = self.content
Georg Brandla0547222009-10-22 11:01:46 +000073 add_text = nodes.strong('CPython implementation detail:',
74 'CPython implementation detail:')
Georg Brandlf5f7c662009-10-22 11:28:23 +000075 if self.arguments:
76 n, m = self.state.inline_text(self.arguments[0], self.lineno)
77 pnode.append(nodes.paragraph('', '', *(n + m)))
Georg Brandl08be2e22009-10-22 08:05:04 +000078 self.state.nested_parse(content, self.content_offset, pnode)
Georg Brandla0547222009-10-22 11:01:46 +000079 if pnode.children and isinstance(pnode[0], nodes.paragraph):
80 pnode[0].insert(0, add_text)
81 pnode[0].insert(1, nodes.Text(' '))
82 else:
83 pnode.insert(0, nodes.paragraph('', '', add_text))
Georg Brandl08be2e22009-10-22 08:05:04 +000084 return [pnode]
85
86
Sandro Tosid6e87f42012-01-14 16:42:21 +010087# Support for documenting decorators
88
89from sphinx import addnodes
90from sphinx.domains.python import PyModulelevel, PyClassmember
91
92class PyDecoratorMixin(object):
93 def handle_signature(self, sig, signode):
94 ret = super(PyDecoratorMixin, self).handle_signature(sig, signode)
95 signode.insert(0, addnodes.desc_addname('@', '@'))
96 return ret
97
98 def needs_arglist(self):
99 return False
100
101class PyDecoratorFunction(PyDecoratorMixin, PyModulelevel):
102 def run(self):
103 # a decorator function is a function after all
104 self.name = 'py:function'
105 return PyModulelevel.run(self)
106
107class PyDecoratorMethod(PyDecoratorMixin, PyClassmember):
108 def run(self):
109 self.name = 'py:method'
110 return PyClassmember.run(self)
111
112
113# Support for documenting version of removal in deprecations
114
115from sphinx.locale import versionlabels
116from sphinx.util.compat import Directive
117
118versionlabels['deprecated-removed'] = \
119 'Deprecated since version %s, will be removed in version %s'
120
121class DeprecatedRemoved(Directive):
122 has_content = True
123 required_arguments = 2
124 optional_arguments = 1
125 final_argument_whitespace = True
126 option_spec = {}
127
128 def run(self):
129 node = addnodes.versionmodified()
130 node.document = self.state.document
131 node['type'] = 'deprecated-removed'
132 version = (self.arguments[0], self.arguments[1])
133 node['version'] = version
134 if len(self.arguments) == 3:
135 inodes, messages = self.state.inline_text(self.arguments[2],
136 self.lineno+1)
137 node.extend(inodes)
138 if self.content:
139 self.state.nested_parse(self.content, self.content_offset, node)
140 ret = [node] + messages
141 else:
142 ret = [node]
143 env = self.state.document.settings.env
144 env.note_versionchange('deprecated', version[0], node, self.lineno)
145 return ret
146
147
Georg Brandl681001e2008-06-01 20:33:55 +0000148# Support for building "topic help" for pydoc
149
150pydoc_topic_labels = [
151 'assert', 'assignment', 'atom-identifiers', 'atom-literals',
152 'attribute-access', 'attribute-references', 'augassign', 'binary',
153 'bitwise', 'bltin-code-objects', 'bltin-ellipsis-object',
Sandro Tosid6e87f42012-01-14 16:42:21 +0100154 'bltin-null-object', 'bltin-type-objects', 'booleans',
155 'break', 'callable-types', 'calls', 'class', 'comparisons', 'compound',
156 'context-managers', 'continue', 'conversions', 'customization', 'debugger',
157 'del', 'dict', 'dynamic-features', 'else', 'exceptions', 'execmodel',
158 'exprlists', 'floating', 'for', 'formatstrings', 'function', 'global',
159 'id-classes', 'identifiers', 'if', 'imaginary', 'import', 'in', 'integers',
160 'lambda', 'lists', 'naming', 'nonlocal', 'numbers', 'numeric-types',
161 'objects', 'operator-summary', 'pass', 'power', 'raise', 'return',
162 'sequence-types', 'shifting', 'slicings', 'specialattrs', 'specialnames',
163 'string-methods', 'strings', 'subscriptions', 'truth', 'try', 'types',
164 'typesfunctions', 'typesmapping', 'typesmethods', 'typesmodules',
165 'typesseq', 'typesseq-mutable', 'unary', 'while', 'with', 'yield'
Georg Brandl681001e2008-06-01 20:33:55 +0000166]
167
168from os import path
169from time import asctime
170from pprint import pformat
171from docutils.io import StringOutput
172from docutils.utils import new_document
Benjamin Petersona2813c92008-12-20 23:48:54 +0000173
Benjamin Peterson1a67f582009-01-08 04:01:00 +0000174from sphinx.builders import Builder
175from sphinx.writers.text import TextWriter
Benjamin Petersoncb948f12008-12-01 12:52:51 +0000176
Georg Brandl681001e2008-06-01 20:33:55 +0000177
178class PydocTopicsBuilder(Builder):
179 name = 'pydoc-topics'
180
181 def init(self):
182 self.topics = {}
183
184 def get_outdated_docs(self):
185 return 'all pydoc topics'
186
187 def get_target_uri(self, docname, typ=None):
188 return '' # no URIs
189
190 def write(self, *ignored):
191 writer = TextWriter(self)
Benjamin Petersonc5206b32009-03-29 21:50:14 +0000192 for label in self.status_iterator(pydoc_topic_labels,
193 'building topics... ',
194 length=len(pydoc_topic_labels)):
Sandro Tosid6e87f42012-01-14 16:42:21 +0100195 if label not in self.env.domaindata['std']['labels']:
Georg Brandl681001e2008-06-01 20:33:55 +0000196 self.warn('label %r not in documentation' % label)
197 continue
Sandro Tosid6e87f42012-01-14 16:42:21 +0100198 docname, labelid, sectname = self.env.domaindata['std']['labels'][label]
Georg Brandl681001e2008-06-01 20:33:55 +0000199 doctree = self.env.get_and_resolve_doctree(docname, self)
200 document = new_document('<section node>')
201 document.append(doctree.ids[labelid])
202 destination = StringOutput(encoding='utf-8')
203 writer.write(document, destination)
Sandro Tosid6e87f42012-01-14 16:42:21 +0100204 self.topics[label] = str(writer.output)
Georg Brandl681001e2008-06-01 20:33:55 +0000205
206 def finish(self):
Georg Brandl43819252009-04-26 09:56:44 +0000207 f = open(path.join(self.outdir, 'topics.py'), 'w')
Georg Brandl681001e2008-06-01 20:33:55 +0000208 try:
209 f.write('# Autogenerated by Sphinx on %s\n' % asctime())
210 f.write('topics = ' + pformat(self.topics) + '\n')
211 finally:
212 f.close()
213
Georg Brandl08be2e22009-10-22 08:05:04 +0000214
Georg Brandl700cf282009-01-04 10:23:49 +0000215# Support for checking for suspicious markup
216
217import suspicious
Georg Brandl681001e2008-06-01 20:33:55 +0000218
Georg Brandl08be2e22009-10-22 08:05:04 +0000219
Georg Brandld4c7e632008-07-23 15:17:09 +0000220# Support for documenting Opcodes
221
222import re
Georg Brandld4c7e632008-07-23 15:17:09 +0000223
Sandro Tosid6e87f42012-01-14 16:42:21 +0100224opcode_sig_re = re.compile(r'(\w+(?:\+\d)?)(?:\s*\((.*)\))?')
Georg Brandld4c7e632008-07-23 15:17:09 +0000225
226def parse_opcode_signature(env, sig, signode):
227 """Transform an opcode signature into RST nodes."""
228 m = opcode_sig_re.match(sig)
229 if m is None:
230 raise ValueError
231 opname, arglist = m.groups()
232 signode += addnodes.desc_name(opname, opname)
Sandro Tosid6e87f42012-01-14 16:42:21 +0100233 if arglist is not None:
234 paramlist = addnodes.desc_parameterlist()
235 signode += paramlist
236 paramlist += addnodes.desc_parameter(arglist, arglist)
Georg Brandld4c7e632008-07-23 15:17:09 +0000237 return opname.strip()
238
239
Sandro Tosid6e87f42012-01-14 16:42:21 +0100240# Support for documenting pdb commands
241
242pdbcmd_sig_re = re.compile(r'([a-z()!]+)\s*(.*)')
243
244# later...
245#pdbargs_tokens_re = re.compile(r'''[a-zA-Z]+ | # identifiers
246# [.,:]+ | # punctuation
247# [\[\]()] | # parens
248# \s+ # whitespace
249# ''', re.X)
250
251def parse_pdb_command(env, sig, signode):
252 """Transform a pdb command signature into RST nodes."""
253 m = pdbcmd_sig_re.match(sig)
254 if m is None:
255 raise ValueError
256 name, args = m.groups()
257 fullname = name.replace('(', '').replace(')', '')
258 signode += addnodes.desc_name(name, name)
259 if args:
260 signode += addnodes.desc_addname(' '+args, ' '+args)
261 return fullname
262
263
Georg Brandlc3051922008-04-09 17:58:56 +0000264def setup(app):
265 app.add_role('issue', issue_role)
Éric Araujof595a762011-08-19 00:12:33 +0200266 app.add_role('source', source_role)
Georg Brandl08be2e22009-10-22 08:05:04 +0000267 app.add_directive('impl-detail', ImplementationDetail)
Sandro Tosid6e87f42012-01-14 16:42:21 +0100268 app.add_directive('deprecated-removed', DeprecatedRemoved)
Georg Brandl681001e2008-06-01 20:33:55 +0000269 app.add_builder(PydocTopicsBuilder)
Georg Brandl700cf282009-01-04 10:23:49 +0000270 app.add_builder(suspicious.CheckSuspiciousMarkupBuilder)
Georg Brandld4c7e632008-07-23 15:17:09 +0000271 app.add_description_unit('opcode', 'opcode', '%s (opcode)',
272 parse_opcode_signature)
Sandro Tosid6e87f42012-01-14 16:42:21 +0100273 app.add_description_unit('pdbcommand', 'pdbcmd', '%s (pdb command)',
274 parse_pdb_command)
Benjamin Petersone0820e22009-02-07 23:01:19 +0000275 app.add_description_unit('2to3fixer', '2to3fixer', '%s (2to3 fixer)')
Sandro Tosid6e87f42012-01-14 16:42:21 +0100276 app.add_directive_to_domain('py', 'decorator', PyDecoratorFunction)
277 app.add_directive_to_domain('py', 'decoratormethod', PyDecoratorMethod)