blob: 1808e2833a3a8d25c7f23a80c9c3c8d56c315870 [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
36from sphinx.locale import versionlabels
37HTMLTranslator.visit_versionmodified = new_visit_versionmodified
38
Benjamin Peterson5c6d7872009-02-06 02:40:07 +000039
Georg Brandl495f7b52009-10-27 15:28:25 +000040# Support for marking up and linking to bugs.python.org issues
41
Martin v. Löwis5680d0c2008-04-10 03:06:53 +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
Georg Brandl68818862010-11-06 07:19:35 +000049# Support for linking to Python source files easily
50
51def source_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
52 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)
56 return [refnode], []
57
58
Georg Brandl495f7b52009-10-27 15:28:25 +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
73 add_text = nodes.strong('CPython implementation detail:',
74 'CPython implementation detail:')
75 if self.arguments:
76 n, m = self.state.inline_text(self.arguments[0], self.lineno)
77 pnode.append(nodes.paragraph('', '', *(n + m)))
78 self.state.nested_parse(content, self.content_offset, pnode)
79 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))
84 return [pnode]
85
86
Georg Brandl8a1caa22010-07-29 16:01:11 +000087# 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
Georg Brandl281d6ba2010-11-12 08:57:12 +0000113# 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 Brandl2cac28b2012-09-30 15:10:06 +0200148# Support for including Misc/NEWS
149
150import re
151import codecs
Georg Brandl2cac28b2012-09-30 15:10:06 +0200152
Georg Brandl44d0c212012-10-01 19:08:50 +0200153issue_re = re.compile('([Ii])ssue #([0-9]+)')
154whatsnew_re = re.compile(r"(?im)^what's new in (.*?)\??$")
Georg Brandl2cac28b2012-09-30 15:10:06 +0200155
156class MiscNews(Directive):
157 has_content = False
158 required_arguments = 1
159 optional_arguments = 0
160 final_argument_whitespace = False
161 option_spec = {}
162
163 def run(self):
164 fname = self.arguments[0]
165 source = self.state_machine.input_lines.source(
166 self.lineno - self.state_machine.input_offset - 1)
167 source_dir = path.dirname(path.abspath(source))
Georg Brandl44d0c212012-10-01 19:08:50 +0200168 fpath = path.join(source_dir, fname)
169 self.state.document.settings.record_dependencies.add(fpath)
Georg Brandl2cac28b2012-09-30 15:10:06 +0200170 try:
Georg Brandl44d0c212012-10-01 19:08:50 +0200171 fp = codecs.open(fpath, encoding='utf-8')
Georg Brandl2cac28b2012-09-30 15:10:06 +0200172 try:
173 content = fp.read()
174 finally:
175 fp.close()
176 except Exception:
177 text = 'The NEWS file is not available.'
178 node = nodes.strong(text, text)
179 return [node]
Georg Brandl44d0c212012-10-01 19:08:50 +0200180 content = issue_re.sub(r'`\1ssue #\2 <http://bugs.python.org/\2>`__',
Georg Brandl2cac28b2012-09-30 15:10:06 +0200181 content)
Georg Brandl44d0c212012-10-01 19:08:50 +0200182 content = whatsnew_re.sub(r'\1', content)
Georg Brandl2cac28b2012-09-30 15:10:06 +0200183 # remove first 3 lines as they are the main heading
184 lines = content.splitlines()[3:]
185 self.state_machine.insert_input(lines, fname)
186 return []
187
188
Georg Brandl6b38daa2008-06-01 21:05:17 +0000189# Support for building "topic help" for pydoc
190
191pydoc_topic_labels = [
192 'assert', 'assignment', 'atom-identifiers', 'atom-literals',
193 'attribute-access', 'attribute-references', 'augassign', 'binary',
194 'bitwise', 'bltin-code-objects', 'bltin-ellipsis-object',
Benjamin Peterson0d31d582010-06-06 02:44:41 +0000195 'bltin-null-object', 'bltin-type-objects', 'booleans',
Georg Brandl6b38daa2008-06-01 21:05:17 +0000196 'break', 'callable-types', 'calls', 'class', 'comparisons', 'compound',
197 'context-managers', 'continue', 'conversions', 'customization', 'debugger',
198 'del', 'dict', 'dynamic-features', 'else', 'exceptions', 'execmodel',
199 'exprlists', 'floating', 'for', 'formatstrings', 'function', 'global',
200 'id-classes', 'identifiers', 'if', 'imaginary', 'import', 'in', 'integers',
Benjamin Petersonf5a3d692010-08-31 14:31:01 +0000201 'lambda', 'lists', 'naming', 'nonlocal', 'numbers', 'numeric-types',
202 'objects', 'operator-summary', 'pass', 'power', 'raise', 'return',
203 'sequence-types', 'shifting', 'slicings', 'specialattrs', 'specialnames',
204 'string-methods', 'strings', 'subscriptions', 'truth', 'try', 'types',
205 'typesfunctions', 'typesmapping', 'typesmethods', 'typesmodules',
206 'typesseq', 'typesseq-mutable', 'unary', 'while', 'with', 'yield'
Georg Brandl6b38daa2008-06-01 21:05:17 +0000207]
208
209from os import path
210from time import asctime
211from pprint import pformat
212from docutils.io import StringOutput
213from docutils.utils import new_document
Benjamin Peterson6e43fb12008-12-21 00:16:13 +0000214
Benjamin Peterson28d88b42009-01-09 03:03:23 +0000215from sphinx.builders import Builder
216from sphinx.writers.text import TextWriter
Georg Brandldb6f1082008-12-01 23:02:51 +0000217
Georg Brandl6b38daa2008-06-01 21:05:17 +0000218
219class PydocTopicsBuilder(Builder):
220 name = 'pydoc-topics'
221
222 def init(self):
223 self.topics = {}
224
225 def get_outdated_docs(self):
226 return 'all pydoc topics'
227
228 def get_target_uri(self, docname, typ=None):
229 return '' # no URIs
230
231 def write(self, *ignored):
232 writer = TextWriter(self)
Benjamin Peterson5879d412009-03-30 14:51:56 +0000233 for label in self.status_iterator(pydoc_topic_labels,
234 'building topics... ',
235 length=len(pydoc_topic_labels)):
Georg Brandl80ff2ad2010-07-31 08:27:46 +0000236 if label not in self.env.domaindata['std']['labels']:
Georg Brandl6b38daa2008-06-01 21:05:17 +0000237 self.warn('label %r not in documentation' % label)
238 continue
Georg Brandl80ff2ad2010-07-31 08:27:46 +0000239 docname, labelid, sectname = self.env.domaindata['std']['labels'][label]
Georg Brandl6b38daa2008-06-01 21:05:17 +0000240 doctree = self.env.get_and_resolve_doctree(docname, self)
241 document = new_document('<section node>')
242 document.append(doctree.ids[labelid])
243 destination = StringOutput(encoding='utf-8')
244 writer.write(document, destination)
Georg Brandl50fdcdf2012-03-04 16:12:02 +0100245 self.topics[label] = writer.output.encode('utf-8')
Georg Brandl6b38daa2008-06-01 21:05:17 +0000246
247 def finish(self):
Georg Brandl5617db82009-04-27 16:28:57 +0000248 f = open(path.join(self.outdir, 'topics.py'), 'w')
Georg Brandl6b38daa2008-06-01 21:05:17 +0000249 try:
Georg Brandl50fdcdf2012-03-04 16:12:02 +0100250 f.write('# -*- coding: utf-8 -*-\n')
Georg Brandl6b38daa2008-06-01 21:05:17 +0000251 f.write('# Autogenerated by Sphinx on %s\n' % asctime())
252 f.write('topics = ' + pformat(self.topics) + '\n')
253 finally:
254 f.close()
255
Georg Brandl495f7b52009-10-27 15:28:25 +0000256
Benjamin Peterson28d88b42009-01-09 03:03:23 +0000257# Support for checking for suspicious markup
258
259import suspicious
Georg Brandl6b38daa2008-06-01 21:05:17 +0000260
Georg Brandl495f7b52009-10-27 15:28:25 +0000261
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000262# Support for documenting Opcodes
263
264import re
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000265
Georg Brandl4833e5b2010-07-03 10:41:33 +0000266opcode_sig_re = re.compile(r'(\w+(?:\+\d)?)(?:\s*\((.*)\))?')
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000267
268def parse_opcode_signature(env, sig, signode):
269 """Transform an opcode signature into RST nodes."""
270 m = opcode_sig_re.match(sig)
271 if m is None:
272 raise ValueError
273 opname, arglist = m.groups()
274 signode += addnodes.desc_name(opname, opname)
Georg Brandl4833e5b2010-07-03 10:41:33 +0000275 if arglist is not None:
276 paramlist = addnodes.desc_parameterlist()
277 signode += paramlist
278 paramlist += addnodes.desc_parameter(arglist, arglist)
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000279 return opname.strip()
280
281
Georg Brandl281d6ba2010-11-12 08:57:12 +0000282# Support for documenting pdb commands
283
Georg Brandl02053ee2010-07-18 10:11:03 +0000284pdbcmd_sig_re = re.compile(r'([a-z()!]+)\s*(.*)')
285
286# later...
287#pdbargs_tokens_re = re.compile(r'''[a-zA-Z]+ | # identifiers
288# [.,:]+ | # punctuation
289# [\[\]()] | # parens
290# \s+ # whitespace
291# ''', re.X)
292
293def parse_pdb_command(env, sig, signode):
294 """Transform a pdb command signature into RST nodes."""
295 m = pdbcmd_sig_re.match(sig)
296 if m is None:
297 raise ValueError
298 name, args = m.groups()
299 fullname = name.replace('(', '').replace(')', '')
300 signode += addnodes.desc_name(name, name)
301 if args:
302 signode += addnodes.desc_addname(' '+args, ' '+args)
303 return fullname
304
305
Martin v. Löwis5680d0c2008-04-10 03:06:53 +0000306def setup(app):
307 app.add_role('issue', issue_role)
Georg Brandl68818862010-11-06 07:19:35 +0000308 app.add_role('source', source_role)
Georg Brandl495f7b52009-10-27 15:28:25 +0000309 app.add_directive('impl-detail', ImplementationDetail)
Georg Brandl281d6ba2010-11-12 08:57:12 +0000310 app.add_directive('deprecated-removed', DeprecatedRemoved)
Georg Brandl6b38daa2008-06-01 21:05:17 +0000311 app.add_builder(PydocTopicsBuilder)
Benjamin Peterson28d88b42009-01-09 03:03:23 +0000312 app.add_builder(suspicious.CheckSuspiciousMarkupBuilder)
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000313 app.add_description_unit('opcode', 'opcode', '%s (opcode)',
314 parse_opcode_signature)
Georg Brandl02053ee2010-07-18 10:11:03 +0000315 app.add_description_unit('pdbcommand', 'pdbcmd', '%s (pdb command)',
316 parse_pdb_command)
Benjamin Petersonf91df042009-02-13 02:50:59 +0000317 app.add_description_unit('2to3fixer', '2to3fixer', '%s (2to3 fixer)')
Georg Brandl8a1caa22010-07-29 16:01:11 +0000318 app.add_directive_to_domain('py', 'decorator', PyDecoratorFunction)
319 app.add_directive_to_domain('py', 'decoratormethod', PyDecoratorMethod)
Georg Brandl2cac28b2012-09-30 15:10:06 +0200320 app.add_directive('miscnews', MiscNews)