blob: a588b4d77f21ac30d1f631a0fe09e6a0598ee35a [file] [log] [blame]
Georg Brandlc3051922008-04-09 17:58:56 +00001# -*- coding: utf-8 -*-
2"""
3 pyspecific.py
4 ~~~~~~~~~~~~~
5
6 Sphinx extension with Python doc-specific markup.
7
Éric Araujof595a762011-08-19 00:12:33 +02008 :copyright: 2008-2011 by Georg Brandl.
Georg Brandlc3051922008-04-09 17:58:56 +00009 :license: Python license.
10"""
11
12ISSUE_URI = 'http://bugs.python.org/issue%s'
Éric Araujof595a762011-08-19 00:12:33 +020013SOURCE_URI = 'http://hg.python.org/cpython/file/2.7/%s'
Georg Brandlc3051922008-04-09 17:58:56 +000014
15from docutils import nodes, utils
16
Georg Brandl85c5ccf2009-02-05 11:38:23 +000017# monkey-patch reST parser to disable alphabetic and roman enumerated lists
18from docutils.parsers.rst.states import Body
19Body.enum.converters['loweralpha'] = \
20 Body.enum.converters['upperalpha'] = \
21 Body.enum.converters['lowerroman'] = \
22 Body.enum.converters['upperroman'] = lambda x: None
23
Georg Brandl076ca5a2009-09-16 09:05:11 +000024# monkey-patch HTML translator to give versionmodified paragraphs a class
25def new_visit_versionmodified(self, node):
26 self.body.append(self.starttag(node, 'p', CLASS=node['type']))
27 text = versionlabels[node['type']] % node['version']
28 if len(node):
29 text += ': '
30 else:
31 text += '.'
32 self.body.append('<span class="versionmodified">%s</span>' % text)
33
34from sphinx.writers.html import HTMLTranslator
35from sphinx.locale import versionlabels
36HTMLTranslator.visit_versionmodified = new_visit_versionmodified
37
Georg Brandl85c5ccf2009-02-05 11:38:23 +000038
Georg Brandl08be2e22009-10-22 08:05:04 +000039# Support for marking up and linking to bugs.python.org issues
40
Georg Brandlc3051922008-04-09 17:58:56 +000041def issue_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
42 issue = utils.unescape(text)
43 text = 'issue ' + issue
44 refnode = nodes.reference(text, text, refuri=ISSUE_URI % issue)
45 return [refnode], []
46
47
Éric Araujof595a762011-08-19 00:12:33 +020048# Support for linking to Python source files easily
49
50def source_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
51 path = utils.unescape(text)
52 refnode = nodes.reference(path, path, refuri=SOURCE_URI % path)
53 return [refnode], []
54
55
Georg Brandl08be2e22009-10-22 08:05:04 +000056# Support for marking up implementation details
57
58from sphinx.util.compat import Directive
59
60class ImplementationDetail(Directive):
61
62 has_content = True
63 required_arguments = 0
64 optional_arguments = 1
65 final_argument_whitespace = True
66
67 def run(self):
68 pnode = nodes.compound(classes=['impl-detail'])
69 content = self.content
Georg Brandla0547222009-10-22 11:01:46 +000070 add_text = nodes.strong('CPython implementation detail:',
71 'CPython implementation detail:')
Georg Brandlf5f7c662009-10-22 11:28:23 +000072 if self.arguments:
73 n, m = self.state.inline_text(self.arguments[0], self.lineno)
74 pnode.append(nodes.paragraph('', '', *(n + m)))
Georg Brandl08be2e22009-10-22 08:05:04 +000075 self.state.nested_parse(content, self.content_offset, pnode)
Georg Brandla0547222009-10-22 11:01:46 +000076 if pnode.children and isinstance(pnode[0], nodes.paragraph):
77 pnode[0].insert(0, add_text)
78 pnode[0].insert(1, nodes.Text(' '))
79 else:
80 pnode.insert(0, nodes.paragraph('', '', add_text))
Georg Brandl08be2e22009-10-22 08:05:04 +000081 return [pnode]
82
83
Georg Brandl681001e2008-06-01 20:33:55 +000084# Support for building "topic help" for pydoc
85
86pydoc_topic_labels = [
87 'assert', 'assignment', 'atom-identifiers', 'atom-literals',
88 'attribute-access', 'attribute-references', 'augassign', 'binary',
89 'bitwise', 'bltin-code-objects', 'bltin-ellipsis-object',
90 'bltin-file-objects', 'bltin-null-object', 'bltin-type-objects', 'booleans',
91 'break', 'callable-types', 'calls', 'class', 'coercion-rules',
92 'comparisons', 'compound', 'context-managers', 'continue', 'conversions',
93 'customization', 'debugger', 'del', 'dict', 'dynamic-features', 'else',
94 'exceptions', 'exec', 'execmodel', 'exprlists', 'floating', 'for',
95 'formatstrings', 'function', 'global', 'id-classes', 'identifiers', 'if',
96 'imaginary', 'import', 'in', 'integers', 'lambda', 'lists', 'naming',
97 'numbers', 'numeric-types', 'objects', 'operator-summary', 'pass', 'power',
98 'print', 'raise', 'return', 'sequence-methods', 'sequence-types',
99 'shifting', 'slicings', 'specialattrs', 'specialnames',
100 'string-conversions', 'string-methods', 'strings', 'subscriptions', 'truth',
101 'try', 'types', 'typesfunctions', 'typesmapping', 'typesmethods',
102 'typesmodules', 'typesseq', 'typesseq-mutable', 'unary', 'while', 'with',
103 'yield'
104]
105
106from os import path
107from time import asctime
108from pprint import pformat
109from docutils.io import StringOutput
110from docutils.utils import new_document
Benjamin Petersona2813c92008-12-20 23:48:54 +0000111
Benjamin Peterson1a67f582009-01-08 04:01:00 +0000112from sphinx.builders import Builder
113from sphinx.writers.text import TextWriter
Benjamin Petersoncb948f12008-12-01 12:52:51 +0000114
Georg Brandl681001e2008-06-01 20:33:55 +0000115
116class PydocTopicsBuilder(Builder):
117 name = 'pydoc-topics'
118
119 def init(self):
120 self.topics = {}
121
122 def get_outdated_docs(self):
123 return 'all pydoc topics'
124
125 def get_target_uri(self, docname, typ=None):
126 return '' # no URIs
127
128 def write(self, *ignored):
129 writer = TextWriter(self)
Benjamin Petersonc5206b32009-03-29 21:50:14 +0000130 for label in self.status_iterator(pydoc_topic_labels,
131 'building topics... ',
132 length=len(pydoc_topic_labels)):
Georg Brandl681001e2008-06-01 20:33:55 +0000133 if label not in self.env.labels:
134 self.warn('label %r not in documentation' % label)
135 continue
136 docname, labelid, sectname = self.env.labels[label]
137 doctree = self.env.get_and_resolve_doctree(docname, self)
138 document = new_document('<section node>')
139 document.append(doctree.ids[labelid])
140 destination = StringOutput(encoding='utf-8')
141 writer.write(document, destination)
142 self.topics[label] = writer.output
143
144 def finish(self):
Georg Brandl43819252009-04-26 09:56:44 +0000145 f = open(path.join(self.outdir, 'topics.py'), 'w')
Georg Brandl681001e2008-06-01 20:33:55 +0000146 try:
147 f.write('# Autogenerated by Sphinx on %s\n' % asctime())
148 f.write('topics = ' + pformat(self.topics) + '\n')
149 finally:
150 f.close()
151
Georg Brandl08be2e22009-10-22 08:05:04 +0000152
Georg Brandl700cf282009-01-04 10:23:49 +0000153# Support for checking for suspicious markup
154
155import suspicious
Georg Brandl681001e2008-06-01 20:33:55 +0000156
Georg Brandl08be2e22009-10-22 08:05:04 +0000157
Georg Brandld4c7e632008-07-23 15:17:09 +0000158# Support for documenting Opcodes
159
160import re
161from sphinx import addnodes
162
163opcode_sig_re = re.compile(r'(\w+(?:\+\d)?)\s*\((.*)\)')
164
165def parse_opcode_signature(env, sig, signode):
166 """Transform an opcode signature into RST nodes."""
167 m = opcode_sig_re.match(sig)
168 if m is None:
169 raise ValueError
170 opname, arglist = m.groups()
171 signode += addnodes.desc_name(opname, opname)
172 paramlist = addnodes.desc_parameterlist()
173 signode += paramlist
174 paramlist += addnodes.desc_parameter(arglist, arglist)
175 return opname.strip()
176
177
Georg Brandlc3051922008-04-09 17:58:56 +0000178def setup(app):
179 app.add_role('issue', issue_role)
Éric Araujof595a762011-08-19 00:12:33 +0200180 app.add_role('source', source_role)
Georg Brandl08be2e22009-10-22 08:05:04 +0000181 app.add_directive('impl-detail', ImplementationDetail)
Georg Brandl681001e2008-06-01 20:33:55 +0000182 app.add_builder(PydocTopicsBuilder)
Georg Brandl700cf282009-01-04 10:23:49 +0000183 app.add_builder(suspicious.CheckSuspiciousMarkupBuilder)
Georg Brandld4c7e632008-07-23 15:17:09 +0000184 app.add_description_unit('opcode', 'opcode', '%s (opcode)',
185 parse_opcode_signature)
Benjamin Petersone0820e22009-02-07 23:01:19 +0000186 app.add_description_unit('2to3fixer', '2to3fixer', '%s (2to3 fixer)')