blob: 2b5de1421e73082d6f15f6dca022b489fabe86d8 [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 Brandl239990d2013-10-12 20:50:21 +02008 :copyright: 2008-2013 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 Brandl26eb1102012-09-29 09:36:04 +020013SOURCE_URI = 'http://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 Brandl239990d2013-10-12 20:50:21 +020019from sphinx.writers.html import HTMLTranslator
20from sphinx.writers.latex import LaTeXTranslator
21from sphinx.locale import versionlabels
Martin v. Löwis5680d0c2008-04-10 03:06:53 +000022
Benjamin Peterson5c6d7872009-02-06 02:40:07 +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 Brandl239990d2013-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 Brandlee8783d2009-09-16 16:00:31 +000041
Georg Brandl83e51f42012-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
Benjamin Peterson5c6d7872009-02-06 02:40:07 +000069
Georg Brandl495f7b52009-10-27 15:28:25 +000070# Support for marking up and linking to bugs.python.org issues
71
Martin v. Löwis5680d0c2008-04-10 03:06:53 +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
Georg Brandl68818862010-11-06 07:19:35 +000079# Support for linking to Python source files easily
80
81def source_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
82 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)
86 return [refnode], []
87
88
Georg Brandl495f7b52009-10-27 15:28:25 +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
103 add_text = nodes.strong('CPython implementation detail:',
104 'CPython implementation detail:')
105 if self.arguments:
106 n, m = self.state.inline_text(self.arguments[0], self.lineno)
107 pnode.append(nodes.paragraph('', '', *(n + m)))
108 self.state.nested_parse(content, self.content_offset, pnode)
109 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))
114 return [pnode]
115
116
Georg Brandl8a1caa22010-07-29 16:01:11 +0000117# 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
Georg Brandl281d6ba2010-11-12 08:57:12 +0000143# 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 Brandl2cac28b2012-09-30 15:10:06 +0200178# Support for including Misc/NEWS
179
180import re
181import codecs
Georg Brandl2cac28b2012-09-30 15:10:06 +0200182
Georg Brandl44d0c212012-10-01 19:08:50 +0200183issue_re = re.compile('([Ii])ssue #([0-9]+)')
184whatsnew_re = re.compile(r"(?im)^what's new in (.*?)\??$")
Georg Brandl2cac28b2012-09-30 15:10:06 +0200185
186class MiscNews(Directive):
187 has_content = False
188 required_arguments = 1
189 optional_arguments = 0
190 final_argument_whitespace = False
191 option_spec = {}
192
193 def run(self):
194 fname = self.arguments[0]
195 source = self.state_machine.input_lines.source(
196 self.lineno - self.state_machine.input_offset - 1)
197 source_dir = path.dirname(path.abspath(source))
Georg Brandl44d0c212012-10-01 19:08:50 +0200198 fpath = path.join(source_dir, fname)
199 self.state.document.settings.record_dependencies.add(fpath)
Georg Brandl2cac28b2012-09-30 15:10:06 +0200200 try:
Georg Brandl44d0c212012-10-01 19:08:50 +0200201 fp = codecs.open(fpath, encoding='utf-8')
Georg Brandl2cac28b2012-09-30 15:10:06 +0200202 try:
203 content = fp.read()
204 finally:
205 fp.close()
206 except Exception:
207 text = 'The NEWS file is not available.'
208 node = nodes.strong(text, text)
209 return [node]
Georg Brandl44d0c212012-10-01 19:08:50 +0200210 content = issue_re.sub(r'`\1ssue #\2 <http://bugs.python.org/\2>`__',
Georg Brandl2cac28b2012-09-30 15:10:06 +0200211 content)
Georg Brandl44d0c212012-10-01 19:08:50 +0200212 content = whatsnew_re.sub(r'\1', content)
Georg Brandl2cac28b2012-09-30 15:10:06 +0200213 # remove first 3 lines as they are the main heading
Georg Brandl6c475812012-10-01 19:27:05 +0200214 lines = ['.. default-role:: obj', ''] + content.splitlines()[3:]
Georg Brandl2cac28b2012-09-30 15:10:06 +0200215 self.state_machine.insert_input(lines, fname)
216 return []
217
218
Georg Brandl6b38daa2008-06-01 21:05:17 +0000219# Support for building "topic help" for pydoc
220
221pydoc_topic_labels = [
222 'assert', 'assignment', 'atom-identifiers', 'atom-literals',
223 'attribute-access', 'attribute-references', 'augassign', 'binary',
224 'bitwise', 'bltin-code-objects', 'bltin-ellipsis-object',
Benjamin Peterson0d31d582010-06-06 02:44:41 +0000225 'bltin-null-object', 'bltin-type-objects', 'booleans',
Georg Brandl6b38daa2008-06-01 21:05:17 +0000226 'break', 'callable-types', 'calls', 'class', 'comparisons', 'compound',
227 'context-managers', 'continue', 'conversions', 'customization', 'debugger',
228 'del', 'dict', 'dynamic-features', 'else', 'exceptions', 'execmodel',
229 'exprlists', 'floating', 'for', 'formatstrings', 'function', 'global',
230 'id-classes', 'identifiers', 'if', 'imaginary', 'import', 'in', 'integers',
Benjamin Petersonf5a3d692010-08-31 14:31:01 +0000231 'lambda', 'lists', 'naming', 'nonlocal', 'numbers', 'numeric-types',
232 'objects', 'operator-summary', 'pass', 'power', 'raise', 'return',
233 'sequence-types', 'shifting', 'slicings', 'specialattrs', 'specialnames',
234 'string-methods', 'strings', 'subscriptions', 'truth', 'try', 'types',
235 'typesfunctions', 'typesmapping', 'typesmethods', 'typesmodules',
236 'typesseq', 'typesseq-mutable', 'unary', 'while', 'with', 'yield'
Georg Brandl6b38daa2008-06-01 21:05:17 +0000237]
238
239from os import path
240from time import asctime
241from pprint import pformat
242from docutils.io import StringOutput
243from docutils.utils import new_document
Benjamin Peterson6e43fb12008-12-21 00:16:13 +0000244
Benjamin Peterson28d88b42009-01-09 03:03:23 +0000245from sphinx.builders import Builder
246from sphinx.writers.text import TextWriter
Georg Brandldb6f1082008-12-01 23:02:51 +0000247
Georg Brandl6b38daa2008-06-01 21:05:17 +0000248
249class PydocTopicsBuilder(Builder):
250 name = 'pydoc-topics'
251
252 def init(self):
253 self.topics = {}
254
255 def get_outdated_docs(self):
256 return 'all pydoc topics'
257
258 def get_target_uri(self, docname, typ=None):
259 return '' # no URIs
260
261 def write(self, *ignored):
262 writer = TextWriter(self)
Benjamin Peterson5879d412009-03-30 14:51:56 +0000263 for label in self.status_iterator(pydoc_topic_labels,
264 'building topics... ',
265 length=len(pydoc_topic_labels)):
Georg Brandl80ff2ad2010-07-31 08:27:46 +0000266 if label not in self.env.domaindata['std']['labels']:
Georg Brandl6b38daa2008-06-01 21:05:17 +0000267 self.warn('label %r not in documentation' % label)
268 continue
Georg Brandl80ff2ad2010-07-31 08:27:46 +0000269 docname, labelid, sectname = self.env.domaindata['std']['labels'][label]
Georg Brandl6b38daa2008-06-01 21:05:17 +0000270 doctree = self.env.get_and_resolve_doctree(docname, self)
271 document = new_document('<section node>')
272 document.append(doctree.ids[labelid])
273 destination = StringOutput(encoding='utf-8')
274 writer.write(document, destination)
Georg Brandl50fdcdf2012-03-04 16:12:02 +0100275 self.topics[label] = writer.output.encode('utf-8')
Georg Brandl6b38daa2008-06-01 21:05:17 +0000276
277 def finish(self):
Georg Brandl5617db82009-04-27 16:28:57 +0000278 f = open(path.join(self.outdir, 'topics.py'), 'w')
Georg Brandl6b38daa2008-06-01 21:05:17 +0000279 try:
Georg Brandl50fdcdf2012-03-04 16:12:02 +0100280 f.write('# -*- coding: utf-8 -*-\n')
Georg Brandl6b38daa2008-06-01 21:05:17 +0000281 f.write('# Autogenerated by Sphinx on %s\n' % asctime())
282 f.write('topics = ' + pformat(self.topics) + '\n')
283 finally:
284 f.close()
285
Georg Brandl495f7b52009-10-27 15:28:25 +0000286
Benjamin Peterson28d88b42009-01-09 03:03:23 +0000287# Support for checking for suspicious markup
288
289import suspicious
Georg Brandl6b38daa2008-06-01 21:05:17 +0000290
Georg Brandl495f7b52009-10-27 15:28:25 +0000291
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000292# Support for documenting Opcodes
293
294import re
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000295
Georg Brandl4833e5b2010-07-03 10:41:33 +0000296opcode_sig_re = re.compile(r'(\w+(?:\+\d)?)(?:\s*\((.*)\))?')
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000297
298def parse_opcode_signature(env, sig, signode):
299 """Transform an opcode signature into RST nodes."""
300 m = opcode_sig_re.match(sig)
301 if m is None:
302 raise ValueError
303 opname, arglist = m.groups()
304 signode += addnodes.desc_name(opname, opname)
Georg Brandl4833e5b2010-07-03 10:41:33 +0000305 if arglist is not None:
306 paramlist = addnodes.desc_parameterlist()
307 signode += paramlist
308 paramlist += addnodes.desc_parameter(arglist, arglist)
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000309 return opname.strip()
310
311
Georg Brandl281d6ba2010-11-12 08:57:12 +0000312# Support for documenting pdb commands
313
Georg Brandl02053ee2010-07-18 10:11:03 +0000314pdbcmd_sig_re = re.compile(r'([a-z()!]+)\s*(.*)')
315
316# later...
317#pdbargs_tokens_re = re.compile(r'''[a-zA-Z]+ | # identifiers
318# [.,:]+ | # punctuation
319# [\[\]()] | # parens
320# \s+ # whitespace
321# ''', re.X)
322
323def parse_pdb_command(env, sig, signode):
324 """Transform a pdb command signature into RST nodes."""
325 m = pdbcmd_sig_re.match(sig)
326 if m is None:
327 raise ValueError
328 name, args = m.groups()
329 fullname = name.replace('(', '').replace(')', '')
330 signode += addnodes.desc_name(name, name)
331 if args:
332 signode += addnodes.desc_addname(' '+args, ' '+args)
333 return fullname
334
335
Martin v. Löwis5680d0c2008-04-10 03:06:53 +0000336def setup(app):
337 app.add_role('issue', issue_role)
Georg Brandl68818862010-11-06 07:19:35 +0000338 app.add_role('source', source_role)
Georg Brandl495f7b52009-10-27 15:28:25 +0000339 app.add_directive('impl-detail', ImplementationDetail)
Georg Brandl281d6ba2010-11-12 08:57:12 +0000340 app.add_directive('deprecated-removed', DeprecatedRemoved)
Georg Brandl6b38daa2008-06-01 21:05:17 +0000341 app.add_builder(PydocTopicsBuilder)
Benjamin Peterson28d88b42009-01-09 03:03:23 +0000342 app.add_builder(suspicious.CheckSuspiciousMarkupBuilder)
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000343 app.add_description_unit('opcode', 'opcode', '%s (opcode)',
344 parse_opcode_signature)
Georg Brandl02053ee2010-07-18 10:11:03 +0000345 app.add_description_unit('pdbcommand', 'pdbcmd', '%s (pdb command)',
346 parse_pdb_command)
Benjamin Petersonf91df042009-02-13 02:50:59 +0000347 app.add_description_unit('2to3fixer', '2to3fixer', '%s (2to3 fixer)')
Georg Brandl8a1caa22010-07-29 16:01:11 +0000348 app.add_directive_to_domain('py', 'decorator', PyDecoratorFunction)
349 app.add_directive_to_domain('py', 'decoratormethod', PyDecoratorMethod)
Georg Brandl2cac28b2012-09-30 15:10:06 +0200350 app.add_directive('miscnews', MiscNews)