blob: 8607531b24e2c09d6d565d57399434727a742dcb [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
Georg Brandladf68152009-04-11 20:34:17 +00008 :copyright: 2008, 2009 by Georg Brandl.
Georg Brandlc3051922008-04-09 17:58:56 +00009 :license: Python license.
10"""
11
12ISSUE_URI = 'http://bugs.python.org/issue%s'
13
14from docutils import nodes, utils
15
Georg Brandlec7d3902009-02-23 10:41:11 +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 Brandlf004d9d2009-10-27 15:39:53 +000023# monkey-patch HTML translator to give versionmodified paragraphs a class
24from sphinx.writers.html import HTMLTranslator
25from sphinx.locale import versionlabels
26HTMLTranslator.visit_versionmodified = new_visit_versionmodified
27
28def new_visit_versionmodified(self, node):
29 self.body.append(self.starttag(node, 'p', CLASS=node['type']))
30 text = versionlabels[node['type']] % node['version']
31 if len(node):
32 text += ': '
33 else:
34 text += '.'
35 self.body.append('<span class="versionmodified">%s</span>' % text)
36
Georg Brandlec7d3902009-02-23 10:41:11 +000037
Georg Brandl5d2eb342009-10-27 15:08:27 +000038# Support for marking up and linking to bugs.python.org issues
39
Georg Brandlc3051922008-04-09 17:58:56 +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 Brandl5d2eb342009-10-27 15:08:27 +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 Brandl681001e2008-06-01 20:33:55 +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',
81 'bltin-file-objects', 'bltin-null-object', 'bltin-type-objects', 'booleans',
82 'break', 'callable-types', 'calls', 'class', 'coercion-rules',
83 'comparisons', 'compound', 'context-managers', 'continue', 'conversions',
84 'customization', 'debugger', 'del', 'dict', 'dynamic-features', 'else',
85 'exceptions', 'exec', 'execmodel', 'exprlists', 'floating', 'for',
86 'formatstrings', 'function', 'global', 'id-classes', 'identifiers', 'if',
87 'imaginary', 'import', 'in', 'integers', 'lambda', 'lists', 'naming',
88 'numbers', 'numeric-types', 'objects', 'operator-summary', 'pass', 'power',
89 'print', 'raise', 'return', 'sequence-methods', 'sequence-types',
90 'shifting', 'slicings', 'specialattrs', 'specialnames',
91 'string-conversions', 'string-methods', 'strings', 'subscriptions', 'truth',
92 'try', 'types', 'typesfunctions', 'typesmapping', 'typesmethods',
93 'typesmodules', 'typesseq', 'typesseq-mutable', 'unary', 'while', 'with',
94 'yield'
95]
96
97from os import path
98from time import asctime
99from pprint import pformat
100from docutils.io import StringOutput
101from docutils.utils import new_document
Benjamin Petersonc6e80eb2008-12-21 17:01:26 +0000102
Georg Brandlbadbba42009-01-26 23:06:17 +0000103try:
104 from sphinx.builders import Builder
105except ImportError:
Georg Brandladf68152009-04-11 20:34:17 +0000106 # using Sphinx < 0.6, which has a different package layout
Georg Brandlbadbba42009-01-26 23:06:17 +0000107 from sphinx.builder import Builder
Georg Brandladf68152009-04-11 20:34:17 +0000108 # monkey-patch toctree directive to accept (and ignore) the :numbered: flag
109 from sphinx.directives.other import toctree_directive
110 toctree_directive.options['numbered'] = toctree_directive.options['glob']
Georg Brandlbadbba42009-01-26 23:06:17 +0000111
112try:
113 from sphinx.writers.text import TextWriter
114except ImportError:
115 from sphinx.textwriter import TextWriter
Georg Brandl23f74902008-12-02 08:25:00 +0000116
Georg Brandl681001e2008-06-01 20:33:55 +0000117
118class PydocTopicsBuilder(Builder):
119 name = 'pydoc-topics'
120
121 def init(self):
122 self.topics = {}
123
124 def get_outdated_docs(self):
125 return 'all pydoc topics'
126
127 def get_target_uri(self, docname, typ=None):
128 return '' # no URIs
129
130 def write(self, *ignored):
131 writer = TextWriter(self)
132 for label in self.status_iterator(pydoc_topic_labels, 'building topics... '):
133 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):
145 f = open(path.join(self.outdir, 'pydoc_topics.py'), 'w')
146 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 Brandl5d2eb342009-10-27 15:08:27 +0000152
Benjamin Peterson9f7ae1b2009-01-09 03:04:01 +0000153# Support for checking for suspicious markup
154
155import suspicious
Georg Brandl681001e2008-06-01 20:33:55 +0000156
Georg Brandl5d2eb342009-10-27 15:08:27 +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)
Georg Brandl5d2eb342009-10-27 15:08:27 +0000180 app.add_directive('impl-detail', ImplementationDetail)
Georg Brandl681001e2008-06-01 20:33:55 +0000181 app.add_builder(PydocTopicsBuilder)
Benjamin Peterson9f7ae1b2009-01-09 03:04:01 +0000182 app.add_builder(suspicious.CheckSuspiciousMarkupBuilder)
Georg Brandld4c7e632008-07-23 15:17:09 +0000183 app.add_description_unit('opcode', 'opcode', '%s (opcode)',
184 parse_opcode_signature)
Georg Brandl27e87232009-10-27 13:31:19 +0000185 app.add_description_unit('2to3fixer', '2to3fixer', '%s (2to3 fixer)')