blob: 31d8c06dbb5e260c68c795a7f5c9683103ead935 [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'
Larry Hastingscf1a3cd2014-03-15 22:34:24 -070013SOURCE_URI = 'http://hg.python.org/cpython/file/3.4/%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']))
183 node.append(para)
Georg Brandl281d6ba2010-11-12 08:57:12 +0000184 env = self.state.document.settings.env
185 env.note_versionchange('deprecated', version[0], node, self.lineno)
Georg Brandl7ed509a2014-01-21 19:20:31 +0100186 return [node] + messages
Georg Brandl281d6ba2010-11-12 08:57:12 +0000187
Georg Brandlf7b2f362014-02-16 09:46:36 +0100188# for Sphinx < 1.2
189versionlabels['deprecated-removed'] = DeprecatedRemoved._label
190
Georg Brandl281d6ba2010-11-12 08:57:12 +0000191
Georg Brandl2cac28b2012-09-30 15:10:06 +0200192# Support for including Misc/NEWS
193
194import re
195import codecs
Georg Brandl2cac28b2012-09-30 15:10:06 +0200196
Georg Brandl44d0c212012-10-01 19:08:50 +0200197issue_re = re.compile('([Ii])ssue #([0-9]+)')
198whatsnew_re = re.compile(r"(?im)^what's new in (.*?)\??$")
Georg Brandl2cac28b2012-09-30 15:10:06 +0200199
200class MiscNews(Directive):
201 has_content = False
202 required_arguments = 1
203 optional_arguments = 0
204 final_argument_whitespace = False
205 option_spec = {}
206
207 def run(self):
208 fname = self.arguments[0]
209 source = self.state_machine.input_lines.source(
210 self.lineno - self.state_machine.input_offset - 1)
211 source_dir = path.dirname(path.abspath(source))
Georg Brandl44d0c212012-10-01 19:08:50 +0200212 fpath = path.join(source_dir, fname)
213 self.state.document.settings.record_dependencies.add(fpath)
Georg Brandl2cac28b2012-09-30 15:10:06 +0200214 try:
Georg Brandl44d0c212012-10-01 19:08:50 +0200215 fp = codecs.open(fpath, encoding='utf-8')
Georg Brandl2cac28b2012-09-30 15:10:06 +0200216 try:
217 content = fp.read()
218 finally:
219 fp.close()
220 except Exception:
221 text = 'The NEWS file is not available.'
222 node = nodes.strong(text, text)
223 return [node]
Georg Brandl44d0c212012-10-01 19:08:50 +0200224 content = issue_re.sub(r'`\1ssue #\2 <http://bugs.python.org/\2>`__',
Georg Brandl2cac28b2012-09-30 15:10:06 +0200225 content)
Georg Brandl44d0c212012-10-01 19:08:50 +0200226 content = whatsnew_re.sub(r'\1', content)
Georg Brandl2cac28b2012-09-30 15:10:06 +0200227 # remove first 3 lines as they are the main heading
Georg Brandl6c475812012-10-01 19:27:05 +0200228 lines = ['.. default-role:: obj', ''] + content.splitlines()[3:]
Georg Brandl2cac28b2012-09-30 15:10:06 +0200229 self.state_machine.insert_input(lines, fname)
230 return []
231
232
Georg Brandl6b38daa2008-06-01 21:05:17 +0000233# Support for building "topic help" for pydoc
234
235pydoc_topic_labels = [
236 'assert', 'assignment', 'atom-identifiers', 'atom-literals',
237 'attribute-access', 'attribute-references', 'augassign', 'binary',
238 'bitwise', 'bltin-code-objects', 'bltin-ellipsis-object',
Benjamin Peterson0d31d582010-06-06 02:44:41 +0000239 'bltin-null-object', 'bltin-type-objects', 'booleans',
Georg Brandl6b38daa2008-06-01 21:05:17 +0000240 'break', 'callable-types', 'calls', 'class', 'comparisons', 'compound',
241 'context-managers', 'continue', 'conversions', 'customization', 'debugger',
242 'del', 'dict', 'dynamic-features', 'else', 'exceptions', 'execmodel',
243 'exprlists', 'floating', 'for', 'formatstrings', 'function', 'global',
244 'id-classes', 'identifiers', 'if', 'imaginary', 'import', 'in', 'integers',
Benjamin Petersonf5a3d692010-08-31 14:31:01 +0000245 'lambda', 'lists', 'naming', 'nonlocal', 'numbers', 'numeric-types',
246 'objects', 'operator-summary', 'pass', 'power', 'raise', 'return',
247 'sequence-types', 'shifting', 'slicings', 'specialattrs', 'specialnames',
248 'string-methods', 'strings', 'subscriptions', 'truth', 'try', 'types',
249 'typesfunctions', 'typesmapping', 'typesmethods', 'typesmodules',
250 'typesseq', 'typesseq-mutable', 'unary', 'while', 'with', 'yield'
Georg Brandl6b38daa2008-06-01 21:05:17 +0000251]
252
253from os import path
254from time import asctime
255from pprint import pformat
256from docutils.io import StringOutput
257from docutils.utils import new_document
Benjamin Peterson6e43fb12008-12-21 00:16:13 +0000258
Benjamin Peterson28d88b42009-01-09 03:03:23 +0000259from sphinx.builders import Builder
260from sphinx.writers.text import TextWriter
Georg Brandldb6f1082008-12-01 23:02:51 +0000261
Georg Brandl6b38daa2008-06-01 21:05:17 +0000262
263class PydocTopicsBuilder(Builder):
264 name = 'pydoc-topics'
265
266 def init(self):
267 self.topics = {}
268
269 def get_outdated_docs(self):
270 return 'all pydoc topics'
271
272 def get_target_uri(self, docname, typ=None):
273 return '' # no URIs
274
275 def write(self, *ignored):
276 writer = TextWriter(self)
Benjamin Peterson5879d412009-03-30 14:51:56 +0000277 for label in self.status_iterator(pydoc_topic_labels,
278 'building topics... ',
279 length=len(pydoc_topic_labels)):
Georg Brandl80ff2ad2010-07-31 08:27:46 +0000280 if label not in self.env.domaindata['std']['labels']:
Georg Brandl6b38daa2008-06-01 21:05:17 +0000281 self.warn('label %r not in documentation' % label)
282 continue
Georg Brandl80ff2ad2010-07-31 08:27:46 +0000283 docname, labelid, sectname = self.env.domaindata['std']['labels'][label]
Georg Brandl6b38daa2008-06-01 21:05:17 +0000284 doctree = self.env.get_and_resolve_doctree(docname, self)
285 document = new_document('<section node>')
286 document.append(doctree.ids[labelid])
287 destination = StringOutput(encoding='utf-8')
288 writer.write(document, destination)
Georg Brandl50fdcdf2012-03-04 16:12:02 +0100289 self.topics[label] = writer.output.encode('utf-8')
Georg Brandl6b38daa2008-06-01 21:05:17 +0000290
291 def finish(self):
Georg Brandl5617db82009-04-27 16:28:57 +0000292 f = open(path.join(self.outdir, 'topics.py'), 'w')
Georg Brandl6b38daa2008-06-01 21:05:17 +0000293 try:
Georg Brandl50fdcdf2012-03-04 16:12:02 +0100294 f.write('# -*- coding: utf-8 -*-\n')
Georg Brandl6b38daa2008-06-01 21:05:17 +0000295 f.write('# Autogenerated by Sphinx on %s\n' % asctime())
296 f.write('topics = ' + pformat(self.topics) + '\n')
297 finally:
298 f.close()
299
Georg Brandl495f7b52009-10-27 15:28:25 +0000300
Benjamin Peterson28d88b42009-01-09 03:03:23 +0000301# Support for checking for suspicious markup
302
303import suspicious
Georg Brandl6b38daa2008-06-01 21:05:17 +0000304
Georg Brandl495f7b52009-10-27 15:28:25 +0000305
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000306# Support for documenting Opcodes
307
308import re
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000309
Georg Brandl4833e5b2010-07-03 10:41:33 +0000310opcode_sig_re = re.compile(r'(\w+(?:\+\d)?)(?:\s*\((.*)\))?')
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000311
312def parse_opcode_signature(env, sig, signode):
313 """Transform an opcode signature into RST nodes."""
314 m = opcode_sig_re.match(sig)
315 if m is None:
316 raise ValueError
317 opname, arglist = m.groups()
318 signode += addnodes.desc_name(opname, opname)
Georg Brandl4833e5b2010-07-03 10:41:33 +0000319 if arglist is not None:
320 paramlist = addnodes.desc_parameterlist()
321 signode += paramlist
322 paramlist += addnodes.desc_parameter(arglist, arglist)
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000323 return opname.strip()
324
325
Georg Brandl281d6ba2010-11-12 08:57:12 +0000326# Support for documenting pdb commands
327
Georg Brandl02053ee2010-07-18 10:11:03 +0000328pdbcmd_sig_re = re.compile(r'([a-z()!]+)\s*(.*)')
329
330# later...
331#pdbargs_tokens_re = re.compile(r'''[a-zA-Z]+ | # identifiers
332# [.,:]+ | # punctuation
333# [\[\]()] | # parens
334# \s+ # whitespace
335# ''', re.X)
336
337def parse_pdb_command(env, sig, signode):
338 """Transform a pdb command signature into RST nodes."""
339 m = pdbcmd_sig_re.match(sig)
340 if m is None:
341 raise ValueError
342 name, args = m.groups()
343 fullname = name.replace('(', '').replace(')', '')
344 signode += addnodes.desc_name(name, name)
345 if args:
346 signode += addnodes.desc_addname(' '+args, ' '+args)
347 return fullname
348
349
Martin v. Löwis5680d0c2008-04-10 03:06:53 +0000350def setup(app):
351 app.add_role('issue', issue_role)
Georg Brandl68818862010-11-06 07:19:35 +0000352 app.add_role('source', source_role)
Georg Brandl495f7b52009-10-27 15:28:25 +0000353 app.add_directive('impl-detail', ImplementationDetail)
Georg Brandl281d6ba2010-11-12 08:57:12 +0000354 app.add_directive('deprecated-removed', DeprecatedRemoved)
Georg Brandl6b38daa2008-06-01 21:05:17 +0000355 app.add_builder(PydocTopicsBuilder)
Benjamin Peterson28d88b42009-01-09 03:03:23 +0000356 app.add_builder(suspicious.CheckSuspiciousMarkupBuilder)
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000357 app.add_description_unit('opcode', 'opcode', '%s (opcode)',
358 parse_opcode_signature)
Georg Brandl02053ee2010-07-18 10:11:03 +0000359 app.add_description_unit('pdbcommand', 'pdbcmd', '%s (pdb command)',
360 parse_pdb_command)
Benjamin Petersonf91df042009-02-13 02:50:59 +0000361 app.add_description_unit('2to3fixer', '2to3fixer', '%s (2to3 fixer)')
Georg Brandl8a1caa22010-07-29 16:01:11 +0000362 app.add_directive_to_domain('py', 'decorator', PyDecoratorFunction)
363 app.add_directive_to_domain('py', 'decoratormethod', PyDecoratorMethod)
Georg Brandl2cac28b2012-09-30 15:10:06 +0200364 app.add_directive('miscnews', MiscNews)