blob: d1b492a21734bc290858c265f3471e2f64081b14 [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
12ISSUE_URI = 'http://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
17import sphinx
Georg Brandl68818862010-11-06 07:19:35 +000018from sphinx.util.nodes import split_explicit_title
Georg Brandlf7b2f362014-02-16 09:46:36 +010019from sphinx.util.compat import Directive
Georg Brandl239990d2013-10-12 20:50:21 +020020from sphinx.writers.html import HTMLTranslator
21from sphinx.writers.latex import LaTeXTranslator
22from sphinx.locale import versionlabels
Martin v. Löwis5680d0c2008-04-10 03:06:53 +000023
Benjamin Peterson5c6d7872009-02-06 02:40:07 +000024# monkey-patch reST parser to disable alphabetic and roman enumerated lists
25from docutils.parsers.rst.states import Body
26Body.enum.converters['loweralpha'] = \
27 Body.enum.converters['upperalpha'] = \
28 Body.enum.converters['lowerroman'] = \
29 Body.enum.converters['upperroman'] = lambda x: None
30
Georg Brandlf7b2f362014-02-16 09:46:36 +010031SPHINX11 = sphinx.__version__[:3] < '1.2'
32
33if SPHINX11:
Georg Brandl239990d2013-10-12 20:50:21 +020034 # monkey-patch HTML translator to give versionmodified paragraphs a class
35 def new_visit_versionmodified(self, node):
36 self.body.append(self.starttag(node, 'p', CLASS=node['type']))
37 text = versionlabels[node['type']] % node['version']
38 if len(node):
39 text += ':'
40 else:
41 text += '.'
42 self.body.append('<span class="versionmodified">%s</span> ' % text)
43 HTMLTranslator.visit_versionmodified = new_visit_versionmodified
Georg Brandlee8783d2009-09-16 16:00:31 +000044
Georg Brandl83e51f42012-10-10 16:45:11 +020045# monkey-patch HTML and LaTeX translators to keep doctest blocks in the
46# doctest docs themselves
47orig_visit_literal_block = HTMLTranslator.visit_literal_block
48def new_visit_literal_block(self, node):
49 meta = self.builder.env.metadata[self.builder.current_docname]
50 old_trim_doctest_flags = self.highlighter.trim_doctest_flags
51 if 'keepdoctest' in meta:
52 self.highlighter.trim_doctest_flags = False
53 try:
54 orig_visit_literal_block(self, node)
55 finally:
56 self.highlighter.trim_doctest_flags = old_trim_doctest_flags
57
58HTMLTranslator.visit_literal_block = new_visit_literal_block
59
60orig_depart_literal_block = LaTeXTranslator.depart_literal_block
61def new_depart_literal_block(self, node):
62 meta = self.builder.env.metadata[self.curfilestack[-1]]
63 old_trim_doctest_flags = self.highlighter.trim_doctest_flags
64 if 'keepdoctest' in meta:
65 self.highlighter.trim_doctest_flags = False
66 try:
67 orig_depart_literal_block(self, node)
68 finally:
69 self.highlighter.trim_doctest_flags = old_trim_doctest_flags
70
71LaTeXTranslator.depart_literal_block = new_depart_literal_block
Benjamin Peterson5c6d7872009-02-06 02:40:07 +000072
Georg Brandl495f7b52009-10-27 15:28:25 +000073# Support for marking up and linking to bugs.python.org issues
74
Martin v. Löwis5680d0c2008-04-10 03:06:53 +000075def issue_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
76 issue = utils.unescape(text)
77 text = 'issue ' + issue
78 refnode = nodes.reference(text, text, refuri=ISSUE_URI % issue)
79 return [refnode], []
80
81
Georg Brandl68818862010-11-06 07:19:35 +000082# Support for linking to Python source files easily
83
84def source_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
85 has_t, title, target = split_explicit_title(text)
86 title = utils.unescape(title)
87 target = utils.unescape(target)
88 refnode = nodes.reference(title, title, refuri=SOURCE_URI % target)
89 return [refnode], []
90
91
Georg Brandl495f7b52009-10-27 15:28:25 +000092# Support for marking up implementation details
93
Georg Brandl495f7b52009-10-27 15:28:25 +000094class ImplementationDetail(Directive):
95
96 has_content = True
97 required_arguments = 0
98 optional_arguments = 1
99 final_argument_whitespace = True
100
101 def run(self):
102 pnode = nodes.compound(classes=['impl-detail'])
103 content = self.content
104 add_text = nodes.strong('CPython implementation detail:',
105 'CPython implementation detail:')
106 if self.arguments:
107 n, m = self.state.inline_text(self.arguments[0], self.lineno)
108 pnode.append(nodes.paragraph('', '', *(n + m)))
109 self.state.nested_parse(content, self.content_offset, pnode)
110 if pnode.children and isinstance(pnode[0], nodes.paragraph):
111 pnode[0].insert(0, add_text)
112 pnode[0].insert(1, nodes.Text(' '))
113 else:
114 pnode.insert(0, nodes.paragraph('', '', add_text))
115 return [pnode]
116
117
Georg Brandl8a1caa22010-07-29 16:01:11 +0000118# Support for documenting decorators
119
120from sphinx import addnodes
121from sphinx.domains.python import PyModulelevel, PyClassmember
122
123class PyDecoratorMixin(object):
124 def handle_signature(self, sig, signode):
125 ret = super(PyDecoratorMixin, self).handle_signature(sig, signode)
126 signode.insert(0, addnodes.desc_addname('@', '@'))
127 return ret
128
129 def needs_arglist(self):
130 return False
131
132class PyDecoratorFunction(PyDecoratorMixin, PyModulelevel):
133 def run(self):
134 # a decorator function is a function after all
135 self.name = 'py:function'
136 return PyModulelevel.run(self)
137
138class PyDecoratorMethod(PyDecoratorMixin, PyClassmember):
139 def run(self):
140 self.name = 'py:method'
141 return PyClassmember.run(self)
142
143
Georg Brandl281d6ba2010-11-12 08:57:12 +0000144# Support for documenting version of removal in deprecations
145
Georg Brandl281d6ba2010-11-12 08:57:12 +0000146class DeprecatedRemoved(Directive):
147 has_content = True
148 required_arguments = 2
149 optional_arguments = 1
150 final_argument_whitespace = True
151 option_spec = {}
152
Georg Brandl7ed509a2014-01-21 19:20:31 +0100153 _label = 'Deprecated since version %s, will be removed in version %s'
154
Georg Brandl281d6ba2010-11-12 08:57:12 +0000155 def run(self):
156 node = addnodes.versionmodified()
157 node.document = self.state.document
158 node['type'] = 'deprecated-removed'
159 version = (self.arguments[0], self.arguments[1])
160 node['version'] = version
Georg Brandl7ed509a2014-01-21 19:20:31 +0100161 text = self._label % version
Georg Brandl281d6ba2010-11-12 08:57:12 +0000162 if len(self.arguments) == 3:
163 inodes, messages = self.state.inline_text(self.arguments[2],
164 self.lineno+1)
Georg Brandl7ed509a2014-01-21 19:20:31 +0100165 para = nodes.paragraph(self.arguments[2], '', *inodes)
166 node.append(para)
Georg Brandl281d6ba2010-11-12 08:57:12 +0000167 else:
Georg Brandl7ed509a2014-01-21 19:20:31 +0100168 messages = []
169 if self.content:
170 self.state.nested_parse(self.content, self.content_offset, node)
Georg Brandl7ed509a2014-01-21 19:20:31 +0100171 if isinstance(node[0], nodes.paragraph) and node[0].rawsource:
172 content = nodes.inline(node[0].rawsource, translatable=True)
173 content.source = node[0].source
174 content.line = node[0].line
175 content += node[0].children
176 node[0].replace_self(nodes.paragraph('', '', content))
Georg Brandlf7b2f362014-02-16 09:46:36 +0100177 if not SPHINX11:
178 node[0].insert(0, nodes.inline('', '%s: ' % text,
179 classes=['versionmodified']))
180 elif not SPHINX11:
Georg Brandl7ed509a2014-01-21 19:20:31 +0100181 para = nodes.paragraph('', '',
182 nodes.inline('', '%s.' % text, classes=['versionmodified']))
Berker Peksageb265ab2014-08-22 18:24:29 +0300183 if len(node):
184 node.insert(0, para)
185 else:
186 node.append(para)
Georg Brandl281d6ba2010-11-12 08:57:12 +0000187 env = self.state.document.settings.env
188 env.note_versionchange('deprecated', version[0], node, self.lineno)
Georg Brandl7ed509a2014-01-21 19:20:31 +0100189 return [node] + messages
Georg Brandl281d6ba2010-11-12 08:57:12 +0000190
Georg Brandlf7b2f362014-02-16 09:46:36 +0100191# for Sphinx < 1.2
192versionlabels['deprecated-removed'] = DeprecatedRemoved._label
193
Georg Brandl281d6ba2010-11-12 08:57:12 +0000194
Georg Brandl2cac28b2012-09-30 15:10:06 +0200195# Support for including Misc/NEWS
196
197import re
198import codecs
Georg Brandl2cac28b2012-09-30 15:10:06 +0200199
Georg Brandl44d0c212012-10-01 19:08:50 +0200200issue_re = re.compile('([Ii])ssue #([0-9]+)')
201whatsnew_re = re.compile(r"(?im)^what's new in (.*?)\??$")
Georg Brandl2cac28b2012-09-30 15:10:06 +0200202
203class MiscNews(Directive):
204 has_content = False
205 required_arguments = 1
206 optional_arguments = 0
207 final_argument_whitespace = False
208 option_spec = {}
209
210 def run(self):
211 fname = self.arguments[0]
212 source = self.state_machine.input_lines.source(
213 self.lineno - self.state_machine.input_offset - 1)
214 source_dir = path.dirname(path.abspath(source))
Georg Brandl44d0c212012-10-01 19:08:50 +0200215 fpath = path.join(source_dir, fname)
216 self.state.document.settings.record_dependencies.add(fpath)
Georg Brandl2cac28b2012-09-30 15:10:06 +0200217 try:
Georg Brandl44d0c212012-10-01 19:08:50 +0200218 fp = codecs.open(fpath, encoding='utf-8')
Georg Brandl2cac28b2012-09-30 15:10:06 +0200219 try:
220 content = fp.read()
221 finally:
222 fp.close()
223 except Exception:
224 text = 'The NEWS file is not available.'
225 node = nodes.strong(text, text)
226 return [node]
Georg Brandl44d0c212012-10-01 19:08:50 +0200227 content = issue_re.sub(r'`\1ssue #\2 <http://bugs.python.org/\2>`__',
Georg Brandl2cac28b2012-09-30 15:10:06 +0200228 content)
Georg Brandl44d0c212012-10-01 19:08:50 +0200229 content = whatsnew_re.sub(r'\1', content)
Georg Brandl2cac28b2012-09-30 15:10:06 +0200230 # remove first 3 lines as they are the main heading
Georg Brandl6c475812012-10-01 19:27:05 +0200231 lines = ['.. default-role:: obj', ''] + content.splitlines()[3:]
Georg Brandl2cac28b2012-09-30 15:10:06 +0200232 self.state_machine.insert_input(lines, fname)
233 return []
234
235
Georg Brandl6b38daa2008-06-01 21:05:17 +0000236# Support for building "topic help" for pydoc
237
238pydoc_topic_labels = [
239 'assert', 'assignment', 'atom-identifiers', 'atom-literals',
240 'attribute-access', 'attribute-references', 'augassign', 'binary',
241 'bitwise', 'bltin-code-objects', 'bltin-ellipsis-object',
Benjamin Peterson0d31d582010-06-06 02:44:41 +0000242 'bltin-null-object', 'bltin-type-objects', 'booleans',
Georg Brandl6b38daa2008-06-01 21:05:17 +0000243 'break', 'callable-types', 'calls', 'class', 'comparisons', 'compound',
244 'context-managers', 'continue', 'conversions', 'customization', 'debugger',
245 'del', 'dict', 'dynamic-features', 'else', 'exceptions', 'execmodel',
246 'exprlists', 'floating', 'for', 'formatstrings', 'function', 'global',
247 'id-classes', 'identifiers', 'if', 'imaginary', 'import', 'in', 'integers',
Benjamin Petersonf5a3d692010-08-31 14:31:01 +0000248 'lambda', 'lists', 'naming', 'nonlocal', 'numbers', 'numeric-types',
249 'objects', 'operator-summary', 'pass', 'power', 'raise', 'return',
250 'sequence-types', 'shifting', 'slicings', 'specialattrs', 'specialnames',
251 'string-methods', 'strings', 'subscriptions', 'truth', 'try', 'types',
252 'typesfunctions', 'typesmapping', 'typesmethods', 'typesmodules',
253 'typesseq', 'typesseq-mutable', 'unary', 'while', 'with', 'yield'
Georg Brandl6b38daa2008-06-01 21:05:17 +0000254]
255
256from os import path
257from time import asctime
258from pprint import pformat
259from docutils.io import StringOutput
260from docutils.utils import new_document
Benjamin Peterson6e43fb12008-12-21 00:16:13 +0000261
Benjamin Peterson28d88b42009-01-09 03:03:23 +0000262from sphinx.builders import Builder
263from sphinx.writers.text import TextWriter
Georg Brandldb6f1082008-12-01 23:02:51 +0000264
Georg Brandl6b38daa2008-06-01 21:05:17 +0000265
266class PydocTopicsBuilder(Builder):
267 name = 'pydoc-topics'
268
269 def init(self):
270 self.topics = {}
271
272 def get_outdated_docs(self):
273 return 'all pydoc topics'
274
275 def get_target_uri(self, docname, typ=None):
276 return '' # no URIs
277
278 def write(self, *ignored):
279 writer = TextWriter(self)
Benjamin Peterson5879d412009-03-30 14:51:56 +0000280 for label in self.status_iterator(pydoc_topic_labels,
281 'building topics... ',
282 length=len(pydoc_topic_labels)):
Georg Brandl80ff2ad2010-07-31 08:27:46 +0000283 if label not in self.env.domaindata['std']['labels']:
Georg Brandl6b38daa2008-06-01 21:05:17 +0000284 self.warn('label %r not in documentation' % label)
285 continue
Georg Brandl80ff2ad2010-07-31 08:27:46 +0000286 docname, labelid, sectname = self.env.domaindata['std']['labels'][label]
Georg Brandl6b38daa2008-06-01 21:05:17 +0000287 doctree = self.env.get_and_resolve_doctree(docname, self)
288 document = new_document('<section node>')
289 document.append(doctree.ids[labelid])
290 destination = StringOutput(encoding='utf-8')
291 writer.write(document, destination)
Georg Brandl50fdcdf2012-03-04 16:12:02 +0100292 self.topics[label] = writer.output.encode('utf-8')
Georg Brandl6b38daa2008-06-01 21:05:17 +0000293
294 def finish(self):
Georg Brandl5617db82009-04-27 16:28:57 +0000295 f = open(path.join(self.outdir, 'topics.py'), 'w')
Georg Brandl6b38daa2008-06-01 21:05:17 +0000296 try:
Georg Brandl50fdcdf2012-03-04 16:12:02 +0100297 f.write('# -*- coding: utf-8 -*-\n')
Georg Brandl6b38daa2008-06-01 21:05:17 +0000298 f.write('# Autogenerated by Sphinx on %s\n' % asctime())
299 f.write('topics = ' + pformat(self.topics) + '\n')
300 finally:
301 f.close()
302
Georg Brandl495f7b52009-10-27 15:28:25 +0000303
Benjamin Peterson28d88b42009-01-09 03:03:23 +0000304# Support for checking for suspicious markup
305
306import suspicious
Georg Brandl6b38daa2008-06-01 21:05:17 +0000307
Georg Brandl495f7b52009-10-27 15:28:25 +0000308
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000309# Support for documenting Opcodes
310
311import re
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000312
Georg Brandl4833e5b2010-07-03 10:41:33 +0000313opcode_sig_re = re.compile(r'(\w+(?:\+\d)?)(?:\s*\((.*)\))?')
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000314
315def parse_opcode_signature(env, sig, signode):
316 """Transform an opcode signature into RST nodes."""
317 m = opcode_sig_re.match(sig)
318 if m is None:
319 raise ValueError
320 opname, arglist = m.groups()
321 signode += addnodes.desc_name(opname, opname)
Georg Brandl4833e5b2010-07-03 10:41:33 +0000322 if arglist is not None:
323 paramlist = addnodes.desc_parameterlist()
324 signode += paramlist
325 paramlist += addnodes.desc_parameter(arglist, arglist)
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000326 return opname.strip()
327
328
Georg Brandl281d6ba2010-11-12 08:57:12 +0000329# Support for documenting pdb commands
330
Georg Brandl02053ee2010-07-18 10:11:03 +0000331pdbcmd_sig_re = re.compile(r'([a-z()!]+)\s*(.*)')
332
333# later...
334#pdbargs_tokens_re = re.compile(r'''[a-zA-Z]+ | # identifiers
335# [.,:]+ | # punctuation
336# [\[\]()] | # parens
337# \s+ # whitespace
338# ''', re.X)
339
340def parse_pdb_command(env, sig, signode):
341 """Transform a pdb command signature into RST nodes."""
342 m = pdbcmd_sig_re.match(sig)
343 if m is None:
344 raise ValueError
345 name, args = m.groups()
346 fullname = name.replace('(', '').replace(')', '')
347 signode += addnodes.desc_name(name, name)
348 if args:
349 signode += addnodes.desc_addname(' '+args, ' '+args)
350 return fullname
351
352
Martin v. Löwis5680d0c2008-04-10 03:06:53 +0000353def setup(app):
354 app.add_role('issue', issue_role)
Georg Brandl68818862010-11-06 07:19:35 +0000355 app.add_role('source', source_role)
Georg Brandl495f7b52009-10-27 15:28:25 +0000356 app.add_directive('impl-detail', ImplementationDetail)
Georg Brandl281d6ba2010-11-12 08:57:12 +0000357 app.add_directive('deprecated-removed', DeprecatedRemoved)
Georg Brandl6b38daa2008-06-01 21:05:17 +0000358 app.add_builder(PydocTopicsBuilder)
Benjamin Peterson28d88b42009-01-09 03:03:23 +0000359 app.add_builder(suspicious.CheckSuspiciousMarkupBuilder)
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000360 app.add_description_unit('opcode', 'opcode', '%s (opcode)',
361 parse_opcode_signature)
Georg Brandl02053ee2010-07-18 10:11:03 +0000362 app.add_description_unit('pdbcommand', 'pdbcmd', '%s (pdb command)',
363 parse_pdb_command)
Benjamin Petersonf91df042009-02-13 02:50:59 +0000364 app.add_description_unit('2to3fixer', '2to3fixer', '%s (2to3 fixer)')
Georg Brandl8a1caa22010-07-29 16:01:11 +0000365 app.add_directive_to_domain('py', 'decorator', PyDecoratorFunction)
366 app.add_directive_to_domain('py', 'decoratormethod', PyDecoratorMethod)
Georg Brandl2cac28b2012-09-30 15:10:06 +0200367 app.add_directive('miscnews', MiscNews)