blob: e8eb70368a37e80fa217d4c9acabb0ecbbecff80 [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 Brandl50fdcdf2012-03-04 16:12:02 +01008 :copyright: 2008, 2009, 2010, 2011, 2012 by Georg Brandl.
Martin v. Löwis5680d0c2008-04-10 03:06:53 +00009 :license: Python license.
10"""
11
12ISSUE_URI = 'http://bugs.python.org/issue%s'
Georg Brandld6e857b2012-09-29 09:03:54 +020013SOURCE_URI = 'http://hg.python.org/cpython/file/3.3/%s'
Martin v. Löwis5680d0c2008-04-10 03:06:53 +000014
15from docutils import nodes, utils
Georg Brandl68818862010-11-06 07:19:35 +000016from sphinx.util.nodes import split_explicit_title
Martin v. Löwis5680d0c2008-04-10 03:06:53 +000017
Benjamin Peterson5c6d7872009-02-06 02:40:07 +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 Brandlee8783d2009-09-16 16:00:31 +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):
Georg Brandlab712142012-03-25 20:31:57 +020030 text += ':'
Georg Brandlee8783d2009-09-16 16:00:31 +000031 else:
32 text += '.'
Georg Brandlab712142012-03-25 20:31:57 +020033 self.body.append('<span class="versionmodified">%s</span> ' % text)
Georg Brandlee8783d2009-09-16 16:00:31 +000034
35from sphinx.writers.html import HTMLTranslator
Georg Brandl83e51f42012-10-10 16:45:11 +020036from sphinx.writers.latex import LaTeXTranslator
Georg Brandlee8783d2009-09-16 16:00:31 +000037from sphinx.locale import versionlabels
38HTMLTranslator.visit_versionmodified = new_visit_versionmodified
Georg Brandl83e51f42012-10-10 16:45:11 +020039HTMLTranslator.visit_versionmodified = new_visit_versionmodified
Georg Brandlee8783d2009-09-16 16:00:31 +000040
Georg Brandl83e51f42012-10-10 16:45:11 +020041# monkey-patch HTML and LaTeX translators to keep doctest blocks in the
42# doctest docs themselves
43orig_visit_literal_block = HTMLTranslator.visit_literal_block
44def new_visit_literal_block(self, node):
45 meta = self.builder.env.metadata[self.builder.current_docname]
46 old_trim_doctest_flags = self.highlighter.trim_doctest_flags
47 if 'keepdoctest' in meta:
48 self.highlighter.trim_doctest_flags = False
49 try:
50 orig_visit_literal_block(self, node)
51 finally:
52 self.highlighter.trim_doctest_flags = old_trim_doctest_flags
53
54HTMLTranslator.visit_literal_block = new_visit_literal_block
55
56orig_depart_literal_block = LaTeXTranslator.depart_literal_block
57def new_depart_literal_block(self, node):
58 meta = self.builder.env.metadata[self.curfilestack[-1]]
59 old_trim_doctest_flags = self.highlighter.trim_doctest_flags
60 if 'keepdoctest' in meta:
61 self.highlighter.trim_doctest_flags = False
62 try:
63 orig_depart_literal_block(self, node)
64 finally:
65 self.highlighter.trim_doctest_flags = old_trim_doctest_flags
66
67LaTeXTranslator.depart_literal_block = new_depart_literal_block
Benjamin Peterson5c6d7872009-02-06 02:40:07 +000068
Georg Brandl495f7b52009-10-27 15:28:25 +000069# Support for marking up and linking to bugs.python.org issues
70
Martin v. Löwis5680d0c2008-04-10 03:06:53 +000071def issue_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
72 issue = utils.unescape(text)
73 text = 'issue ' + issue
74 refnode = nodes.reference(text, text, refuri=ISSUE_URI % issue)
75 return [refnode], []
76
77
Georg Brandl68818862010-11-06 07:19:35 +000078# Support for linking to Python source files easily
79
80def source_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
81 has_t, title, target = split_explicit_title(text)
82 title = utils.unescape(title)
83 target = utils.unescape(target)
84 refnode = nodes.reference(title, title, refuri=SOURCE_URI % target)
85 return [refnode], []
86
87
Georg Brandl495f7b52009-10-27 15:28:25 +000088# Support for marking up implementation details
89
90from sphinx.util.compat import Directive
91
92class ImplementationDetail(Directive):
93
94 has_content = True
95 required_arguments = 0
96 optional_arguments = 1
97 final_argument_whitespace = True
98
99 def run(self):
100 pnode = nodes.compound(classes=['impl-detail'])
101 content = self.content
102 add_text = nodes.strong('CPython implementation detail:',
103 'CPython implementation detail:')
104 if self.arguments:
105 n, m = self.state.inline_text(self.arguments[0], self.lineno)
106 pnode.append(nodes.paragraph('', '', *(n + m)))
107 self.state.nested_parse(content, self.content_offset, pnode)
108 if pnode.children and isinstance(pnode[0], nodes.paragraph):
109 pnode[0].insert(0, add_text)
110 pnode[0].insert(1, nodes.Text(' '))
111 else:
112 pnode.insert(0, nodes.paragraph('', '', add_text))
113 return [pnode]
114
115
Georg Brandl8a1caa22010-07-29 16:01:11 +0000116# Support for documenting decorators
117
118from sphinx import addnodes
119from sphinx.domains.python import PyModulelevel, PyClassmember
120
121class PyDecoratorMixin(object):
122 def handle_signature(self, sig, signode):
123 ret = super(PyDecoratorMixin, self).handle_signature(sig, signode)
124 signode.insert(0, addnodes.desc_addname('@', '@'))
125 return ret
126
127 def needs_arglist(self):
128 return False
129
130class PyDecoratorFunction(PyDecoratorMixin, PyModulelevel):
131 def run(self):
132 # a decorator function is a function after all
133 self.name = 'py:function'
134 return PyModulelevel.run(self)
135
136class PyDecoratorMethod(PyDecoratorMixin, PyClassmember):
137 def run(self):
138 self.name = 'py:method'
139 return PyClassmember.run(self)
140
141
Georg Brandl281d6ba2010-11-12 08:57:12 +0000142# Support for documenting version of removal in deprecations
143
144from sphinx.locale import versionlabels
145from sphinx.util.compat import Directive
146
147versionlabels['deprecated-removed'] = \
148 'Deprecated since version %s, will be removed in version %s'
149
150class DeprecatedRemoved(Directive):
151 has_content = True
152 required_arguments = 2
153 optional_arguments = 1
154 final_argument_whitespace = True
155 option_spec = {}
156
157 def run(self):
158 node = addnodes.versionmodified()
159 node.document = self.state.document
160 node['type'] = 'deprecated-removed'
161 version = (self.arguments[0], self.arguments[1])
162 node['version'] = version
163 if len(self.arguments) == 3:
164 inodes, messages = self.state.inline_text(self.arguments[2],
165 self.lineno+1)
166 node.extend(inodes)
167 if self.content:
168 self.state.nested_parse(self.content, self.content_offset, node)
169 ret = [node] + messages
170 else:
171 ret = [node]
172 env = self.state.document.settings.env
173 env.note_versionchange('deprecated', version[0], node, self.lineno)
174 return ret
175
176
Georg Brandl2cac28b2012-09-30 15:10:06 +0200177# Support for including Misc/NEWS
178
179import re
180import codecs
Georg Brandl2cac28b2012-09-30 15:10:06 +0200181
Georg Brandl44d0c212012-10-01 19:08:50 +0200182issue_re = re.compile('([Ii])ssue #([0-9]+)')
183whatsnew_re = re.compile(r"(?im)^what's new in (.*?)\??$")
Georg Brandl2cac28b2012-09-30 15:10:06 +0200184
185class MiscNews(Directive):
186 has_content = False
187 required_arguments = 1
188 optional_arguments = 0
189 final_argument_whitespace = False
190 option_spec = {}
191
192 def run(self):
193 fname = self.arguments[0]
194 source = self.state_machine.input_lines.source(
195 self.lineno - self.state_machine.input_offset - 1)
196 source_dir = path.dirname(path.abspath(source))
Georg Brandl44d0c212012-10-01 19:08:50 +0200197 fpath = path.join(source_dir, fname)
198 self.state.document.settings.record_dependencies.add(fpath)
Georg Brandl2cac28b2012-09-30 15:10:06 +0200199 try:
Georg Brandl44d0c212012-10-01 19:08:50 +0200200 fp = codecs.open(fpath, encoding='utf-8')
Georg Brandl2cac28b2012-09-30 15:10:06 +0200201 try:
202 content = fp.read()
203 finally:
204 fp.close()
205 except Exception:
206 text = 'The NEWS file is not available.'
207 node = nodes.strong(text, text)
208 return [node]
Georg Brandl44d0c212012-10-01 19:08:50 +0200209 content = issue_re.sub(r'`\1ssue #\2 <http://bugs.python.org/\2>`__',
Georg Brandl2cac28b2012-09-30 15:10:06 +0200210 content)
Georg Brandl44d0c212012-10-01 19:08:50 +0200211 content = whatsnew_re.sub(r'\1', content)
Georg Brandl2cac28b2012-09-30 15:10:06 +0200212 # remove first 3 lines as they are the main heading
Georg Brandl6c475812012-10-01 19:27:05 +0200213 lines = ['.. default-role:: obj', ''] + content.splitlines()[3:]
Georg Brandl2cac28b2012-09-30 15:10:06 +0200214 self.state_machine.insert_input(lines, fname)
215 return []
216
217
Georg Brandl6b38daa2008-06-01 21:05:17 +0000218# Support for building "topic help" for pydoc
219
220pydoc_topic_labels = [
221 'assert', 'assignment', 'atom-identifiers', 'atom-literals',
222 'attribute-access', 'attribute-references', 'augassign', 'binary',
223 'bitwise', 'bltin-code-objects', 'bltin-ellipsis-object',
Benjamin Peterson0d31d582010-06-06 02:44:41 +0000224 'bltin-null-object', 'bltin-type-objects', 'booleans',
Georg Brandl6b38daa2008-06-01 21:05:17 +0000225 'break', 'callable-types', 'calls', 'class', 'comparisons', 'compound',
226 'context-managers', 'continue', 'conversions', 'customization', 'debugger',
227 'del', 'dict', 'dynamic-features', 'else', 'exceptions', 'execmodel',
228 'exprlists', 'floating', 'for', 'formatstrings', 'function', 'global',
229 'id-classes', 'identifiers', 'if', 'imaginary', 'import', 'in', 'integers',
Benjamin Petersonf5a3d692010-08-31 14:31:01 +0000230 'lambda', 'lists', 'naming', 'nonlocal', 'numbers', 'numeric-types',
231 'objects', 'operator-summary', 'pass', 'power', 'raise', 'return',
232 'sequence-types', 'shifting', 'slicings', 'specialattrs', 'specialnames',
233 'string-methods', 'strings', 'subscriptions', 'truth', 'try', 'types',
234 'typesfunctions', 'typesmapping', 'typesmethods', 'typesmodules',
235 'typesseq', 'typesseq-mutable', 'unary', 'while', 'with', 'yield'
Georg Brandl6b38daa2008-06-01 21:05:17 +0000236]
237
238from os import path
239from time import asctime
240from pprint import pformat
241from docutils.io import StringOutput
242from docutils.utils import new_document
Benjamin Peterson6e43fb12008-12-21 00:16:13 +0000243
Benjamin Peterson28d88b42009-01-09 03:03:23 +0000244from sphinx.builders import Builder
245from sphinx.writers.text import TextWriter
Georg Brandldb6f1082008-12-01 23:02:51 +0000246
Georg Brandl6b38daa2008-06-01 21:05:17 +0000247
248class PydocTopicsBuilder(Builder):
249 name = 'pydoc-topics'
250
251 def init(self):
252 self.topics = {}
253
254 def get_outdated_docs(self):
255 return 'all pydoc topics'
256
257 def get_target_uri(self, docname, typ=None):
258 return '' # no URIs
259
260 def write(self, *ignored):
261 writer = TextWriter(self)
Benjamin Peterson5879d412009-03-30 14:51:56 +0000262 for label in self.status_iterator(pydoc_topic_labels,
263 'building topics... ',
264 length=len(pydoc_topic_labels)):
Georg Brandl80ff2ad2010-07-31 08:27:46 +0000265 if label not in self.env.domaindata['std']['labels']:
Georg Brandl6b38daa2008-06-01 21:05:17 +0000266 self.warn('label %r not in documentation' % label)
267 continue
Georg Brandl80ff2ad2010-07-31 08:27:46 +0000268 docname, labelid, sectname = self.env.domaindata['std']['labels'][label]
Georg Brandl6b38daa2008-06-01 21:05:17 +0000269 doctree = self.env.get_and_resolve_doctree(docname, self)
270 document = new_document('<section node>')
271 document.append(doctree.ids[labelid])
272 destination = StringOutput(encoding='utf-8')
273 writer.write(document, destination)
Georg Brandl50fdcdf2012-03-04 16:12:02 +0100274 self.topics[label] = writer.output.encode('utf-8')
Georg Brandl6b38daa2008-06-01 21:05:17 +0000275
276 def finish(self):
Georg Brandl5617db82009-04-27 16:28:57 +0000277 f = open(path.join(self.outdir, 'topics.py'), 'w')
Georg Brandl6b38daa2008-06-01 21:05:17 +0000278 try:
Georg Brandl50fdcdf2012-03-04 16:12:02 +0100279 f.write('# -*- coding: utf-8 -*-\n')
Georg Brandl6b38daa2008-06-01 21:05:17 +0000280 f.write('# Autogenerated by Sphinx on %s\n' % asctime())
281 f.write('topics = ' + pformat(self.topics) + '\n')
282 finally:
283 f.close()
284
Georg Brandl495f7b52009-10-27 15:28:25 +0000285
Benjamin Peterson28d88b42009-01-09 03:03:23 +0000286# Support for checking for suspicious markup
287
288import suspicious
Georg Brandl6b38daa2008-06-01 21:05:17 +0000289
Georg Brandl495f7b52009-10-27 15:28:25 +0000290
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000291# Support for documenting Opcodes
292
293import re
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000294
Georg Brandl4833e5b2010-07-03 10:41:33 +0000295opcode_sig_re = re.compile(r'(\w+(?:\+\d)?)(?:\s*\((.*)\))?')
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000296
297def parse_opcode_signature(env, sig, signode):
298 """Transform an opcode signature into RST nodes."""
299 m = opcode_sig_re.match(sig)
300 if m is None:
301 raise ValueError
302 opname, arglist = m.groups()
303 signode += addnodes.desc_name(opname, opname)
Georg Brandl4833e5b2010-07-03 10:41:33 +0000304 if arglist is not None:
305 paramlist = addnodes.desc_parameterlist()
306 signode += paramlist
307 paramlist += addnodes.desc_parameter(arglist, arglist)
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000308 return opname.strip()
309
310
Georg Brandl281d6ba2010-11-12 08:57:12 +0000311# Support for documenting pdb commands
312
Georg Brandl02053ee2010-07-18 10:11:03 +0000313pdbcmd_sig_re = re.compile(r'([a-z()!]+)\s*(.*)')
314
315# later...
316#pdbargs_tokens_re = re.compile(r'''[a-zA-Z]+ | # identifiers
317# [.,:]+ | # punctuation
318# [\[\]()] | # parens
319# \s+ # whitespace
320# ''', re.X)
321
322def parse_pdb_command(env, sig, signode):
323 """Transform a pdb command signature into RST nodes."""
324 m = pdbcmd_sig_re.match(sig)
325 if m is None:
326 raise ValueError
327 name, args = m.groups()
328 fullname = name.replace('(', '').replace(')', '')
329 signode += addnodes.desc_name(name, name)
330 if args:
331 signode += addnodes.desc_addname(' '+args, ' '+args)
332 return fullname
333
334
Martin v. Löwis5680d0c2008-04-10 03:06:53 +0000335def setup(app):
336 app.add_role('issue', issue_role)
Georg Brandl68818862010-11-06 07:19:35 +0000337 app.add_role('source', source_role)
Georg Brandl495f7b52009-10-27 15:28:25 +0000338 app.add_directive('impl-detail', ImplementationDetail)
Georg Brandl281d6ba2010-11-12 08:57:12 +0000339 app.add_directive('deprecated-removed', DeprecatedRemoved)
Georg Brandl6b38daa2008-06-01 21:05:17 +0000340 app.add_builder(PydocTopicsBuilder)
Benjamin Peterson28d88b42009-01-09 03:03:23 +0000341 app.add_builder(suspicious.CheckSuspiciousMarkupBuilder)
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000342 app.add_description_unit('opcode', 'opcode', '%s (opcode)',
343 parse_opcode_signature)
Georg Brandl02053ee2010-07-18 10:11:03 +0000344 app.add_description_unit('pdbcommand', 'pdbcmd', '%s (pdb command)',
345 parse_pdb_command)
Benjamin Petersonf91df042009-02-13 02:50:59 +0000346 app.add_description_unit('2to3fixer', '2to3fixer', '%s (2to3 fixer)')
Georg Brandl8a1caa22010-07-29 16:01:11 +0000347 app.add_directive_to_domain('py', 'decorator', PyDecoratorFunction)
348 app.add_directive_to_domain('py', 'decoratormethod', PyDecoratorMethod)
Georg Brandl2cac28b2012-09-30 15:10:06 +0200349 app.add_directive('miscnews', MiscNews)