blob: 7111c06c91d940b1271f2ff1957a756b631809e9 [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 Brandlc7b69082010-10-06 08:08:40 +00008 :copyright: 2008, 2009, 2010 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'
13
14from docutils import nodes, utils
15
Benjamin Peterson5c6d7872009-02-06 02:40:07 +000016# monkey-patch reST parser to disable alphabetic and roman enumerated lists
17from docutils.parsers.rst.states import Body
18Body.enum.converters['loweralpha'] = \
19 Body.enum.converters['upperalpha'] = \
20 Body.enum.converters['lowerroman'] = \
21 Body.enum.converters['upperroman'] = lambda x: None
22
Georg Brandlb044b2a2009-09-16 16:05:59 +000023# monkey-patch HTML translator to give versionmodified paragraphs a class
24def new_visit_versionmodified(self, node):
25 self.body.append(self.starttag(node, 'p', CLASS=node['type']))
26 text = versionlabels[node['type']] % node['version']
27 if len(node):
28 text += ': '
29 else:
30 text += '.'
31 self.body.append('<span class="versionmodified">%s</span>' % text)
32
33from sphinx.writers.html import HTMLTranslator
34from sphinx.locale import versionlabels
35HTMLTranslator.visit_versionmodified = new_visit_versionmodified
36
Benjamin Peterson5c6d7872009-02-06 02:40:07 +000037
Georg Brandl628e6f92009-10-27 20:24:45 +000038# Support for marking up and linking to bugs.python.org issues
39
Martin v. Löwis5680d0c2008-04-10 03:06:53 +000040def issue_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
41 issue = utils.unescape(text)
42 text = 'issue ' + issue
43 refnode = nodes.reference(text, text, refuri=ISSUE_URI % issue)
44 return [refnode], []
45
46
Georg Brandl628e6f92009-10-27 20:24:45 +000047# Support for marking up implementation details
48
49from sphinx.util.compat import Directive
50
51class ImplementationDetail(Directive):
52
53 has_content = True
54 required_arguments = 0
55 optional_arguments = 1
56 final_argument_whitespace = True
57
58 def run(self):
59 pnode = nodes.compound(classes=['impl-detail'])
60 content = self.content
61 add_text = nodes.strong('CPython implementation detail:',
62 'CPython implementation detail:')
63 if self.arguments:
64 n, m = self.state.inline_text(self.arguments[0], self.lineno)
65 pnode.append(nodes.paragraph('', '', *(n + m)))
66 self.state.nested_parse(content, self.content_offset, pnode)
67 if pnode.children and isinstance(pnode[0], nodes.paragraph):
68 pnode[0].insert(0, add_text)
69 pnode[0].insert(1, nodes.Text(' '))
70 else:
71 pnode.insert(0, nodes.paragraph('', '', add_text))
72 return [pnode]
73
74
Georg Brandl6b38daa2008-06-01 21:05:17 +000075# Support for building "topic help" for pydoc
76
77pydoc_topic_labels = [
78 'assert', 'assignment', 'atom-identifiers', 'atom-literals',
79 'attribute-access', 'attribute-references', 'augassign', 'binary',
80 'bitwise', 'bltin-code-objects', 'bltin-ellipsis-object',
Benjamin Peterson2d5abf02010-06-06 02:51:17 +000081 'bltin-null-object', 'bltin-type-objects', 'booleans',
Georg Brandl6b38daa2008-06-01 21:05:17 +000082 'break', 'callable-types', 'calls', 'class', 'comparisons', 'compound',
83 'context-managers', 'continue', 'conversions', 'customization', 'debugger',
84 'del', 'dict', 'dynamic-features', 'else', 'exceptions', 'execmodel',
85 'exprlists', 'floating', 'for', 'formatstrings', 'function', 'global',
86 'id-classes', 'identifiers', 'if', 'imaginary', 'import', 'in', 'integers',
Benjamin Peterson2f40d7d2010-08-31 14:32:27 +000087 'lambda', 'lists', 'naming', 'nonlocal', 'numbers', 'numeric-types',
88 'objects', 'operator-summary', 'pass', 'power', 'raise', 'return',
89 'sequence-types', 'shifting', 'slicings', 'specialattrs', 'specialnames',
90 'string-methods', 'strings', 'subscriptions', 'truth', 'try', 'types',
91 'typesfunctions', 'typesmapping', 'typesmethods', 'typesmodules',
92 'typesseq', 'typesseq-mutable', 'unary', 'while', 'with', 'yield'
Georg Brandl6b38daa2008-06-01 21:05:17 +000093]
94
95from os import path
96from time import asctime
97from pprint import pformat
98from docutils.io import StringOutput
99from docutils.utils import new_document
Benjamin Peterson6e43fb12008-12-21 00:16:13 +0000100
Benjamin Peterson28d88b42009-01-09 03:03:23 +0000101from sphinx.builders import Builder
102from sphinx.writers.text import TextWriter
Georg Brandldb6f1082008-12-01 23:02:51 +0000103
Georg Brandl6b38daa2008-06-01 21:05:17 +0000104
105class PydocTopicsBuilder(Builder):
106 name = 'pydoc-topics'
107
108 def init(self):
109 self.topics = {}
110
111 def get_outdated_docs(self):
112 return 'all pydoc topics'
113
114 def get_target_uri(self, docname, typ=None):
115 return '' # no URIs
116
117 def write(self, *ignored):
118 writer = TextWriter(self)
Benjamin Peterson5879d412009-03-30 14:51:56 +0000119 for label in self.status_iterator(pydoc_topic_labels,
120 'building topics... ',
121 length=len(pydoc_topic_labels)):
Georg Brandl6b38daa2008-06-01 21:05:17 +0000122 if label not in self.env.labels:
123 self.warn('label %r not in documentation' % label)
124 continue
125 docname, labelid, sectname = self.env.labels[label]
126 doctree = self.env.get_and_resolve_doctree(docname, self)
127 document = new_document('<section node>')
128 document.append(doctree.ids[labelid])
129 destination = StringOutput(encoding='utf-8')
130 writer.write(document, destination)
131 self.topics[label] = str(writer.output)
132
133 def finish(self):
Georg Brandl5617db82009-04-27 16:28:57 +0000134 f = open(path.join(self.outdir, 'topics.py'), 'w')
Georg Brandl6b38daa2008-06-01 21:05:17 +0000135 try:
136 f.write('# Autogenerated by Sphinx on %s\n' % asctime())
137 f.write('topics = ' + pformat(self.topics) + '\n')
138 finally:
139 f.close()
140
Georg Brandl628e6f92009-10-27 20:24:45 +0000141
Benjamin Peterson28d88b42009-01-09 03:03:23 +0000142# Support for checking for suspicious markup
143
144import suspicious
Georg Brandl6b38daa2008-06-01 21:05:17 +0000145
Georg Brandl628e6f92009-10-27 20:24:45 +0000146
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000147# Support for documenting Opcodes
148
149import re
150from sphinx import addnodes
151
Georg Brandlc7b69082010-10-06 08:08:40 +0000152opcode_sig_re = re.compile(r'(\w+(?:\+\d)?)(?:\s*\((.*)\))?')
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000153
154def parse_opcode_signature(env, sig, signode):
155 """Transform an opcode signature into RST nodes."""
156 m = opcode_sig_re.match(sig)
157 if m is None:
158 raise ValueError
159 opname, arglist = m.groups()
160 signode += addnodes.desc_name(opname, opname)
Georg Brandlc7b69082010-10-06 08:08:40 +0000161 if arglist is not None:
162 paramlist = addnodes.desc_parameterlist()
163 signode += paramlist
164 paramlist += addnodes.desc_parameter(arglist, arglist)
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000165 return opname.strip()
166
167
Martin v. Löwis5680d0c2008-04-10 03:06:53 +0000168def setup(app):
169 app.add_role('issue', issue_role)
Georg Brandl628e6f92009-10-27 20:24:45 +0000170 app.add_directive('impl-detail', ImplementationDetail)
Georg Brandl6b38daa2008-06-01 21:05:17 +0000171 app.add_builder(PydocTopicsBuilder)
Benjamin Peterson28d88b42009-01-09 03:03:23 +0000172 app.add_builder(suspicious.CheckSuspiciousMarkupBuilder)
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000173 app.add_description_unit('opcode', 'opcode', '%s (opcode)',
174 parse_opcode_signature)
Benjamin Petersonf91df042009-02-13 02:50:59 +0000175 app.add_description_unit('2to3fixer', '2to3fixer', '%s (2to3 fixer)')