blob: ff07adb7a6915d14f161f07bfc739af3ed3afba1 [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
Georg Brandlf004d9d2009-10-27 15:39:53 +000024def 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
Georg Brandl0f23fcf2009-10-27 20:13:06 +000033from sphinx.writers.html import HTMLTranslator
34from sphinx.locale import versionlabels
35HTMLTranslator.visit_versionmodified = new_visit_versionmodified
Georg Brandlec7d3902009-02-23 10:41:11 +000036
Georg Brandl5d2eb342009-10-27 15:08:27 +000037# Support for marking up and linking to bugs.python.org issues
38
Georg Brandlc3051922008-04-09 17:58:56 +000039def issue_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
40 issue = utils.unescape(text)
41 text = 'issue ' + issue
42 refnode = nodes.reference(text, text, refuri=ISSUE_URI % issue)
43 return [refnode], []
44
45
Georg Brandl5d2eb342009-10-27 15:08:27 +000046# Support for marking up implementation details
47
48from sphinx.util.compat import Directive
49
50class ImplementationDetail(Directive):
51
52 has_content = True
53 required_arguments = 0
54 optional_arguments = 1
55 final_argument_whitespace = True
56
57 def run(self):
58 pnode = nodes.compound(classes=['impl-detail'])
59 content = self.content
60 add_text = nodes.strong('CPython implementation detail:',
61 'CPython implementation detail:')
62 if self.arguments:
63 n, m = self.state.inline_text(self.arguments[0], self.lineno)
64 pnode.append(nodes.paragraph('', '', *(n + m)))
65 self.state.nested_parse(content, self.content_offset, pnode)
66 if pnode.children and isinstance(pnode[0], nodes.paragraph):
67 pnode[0].insert(0, add_text)
68 pnode[0].insert(1, nodes.Text(' '))
69 else:
70 pnode.insert(0, nodes.paragraph('', '', add_text))
71 return [pnode]
72
73
Georg Brandl681001e2008-06-01 20:33:55 +000074# Support for building "topic help" for pydoc
75
76pydoc_topic_labels = [
77 'assert', 'assignment', 'atom-identifiers', 'atom-literals',
78 'attribute-access', 'attribute-references', 'augassign', 'binary',
79 'bitwise', 'bltin-code-objects', 'bltin-ellipsis-object',
80 'bltin-file-objects', 'bltin-null-object', 'bltin-type-objects', 'booleans',
81 'break', 'callable-types', 'calls', 'class', 'coercion-rules',
82 'comparisons', 'compound', 'context-managers', 'continue', 'conversions',
83 'customization', 'debugger', 'del', 'dict', 'dynamic-features', 'else',
84 'exceptions', 'exec', 'execmodel', 'exprlists', 'floating', 'for',
85 'formatstrings', 'function', 'global', 'id-classes', 'identifiers', 'if',
86 'imaginary', 'import', 'in', 'integers', 'lambda', 'lists', 'naming',
87 'numbers', 'numeric-types', 'objects', 'operator-summary', 'pass', 'power',
88 'print', 'raise', 'return', 'sequence-methods', 'sequence-types',
89 'shifting', 'slicings', 'specialattrs', 'specialnames',
90 'string-conversions', 'string-methods', 'strings', 'subscriptions', 'truth',
91 'try', 'types', 'typesfunctions', 'typesmapping', 'typesmethods',
92 'typesmodules', 'typesseq', 'typesseq-mutable', 'unary', 'while', 'with',
93 'yield'
94]
95
96from os import path
97from time import asctime
98from pprint import pformat
99from docutils.io import StringOutput
100from docutils.utils import new_document
Benjamin Petersonc6e80eb2008-12-21 17:01:26 +0000101
Georg Brandlbadbba42009-01-26 23:06:17 +0000102try:
103 from sphinx.builders import Builder
104except ImportError:
Georg Brandladf68152009-04-11 20:34:17 +0000105 # using Sphinx < 0.6, which has a different package layout
Georg Brandlbadbba42009-01-26 23:06:17 +0000106 from sphinx.builder import Builder
Georg Brandladf68152009-04-11 20:34:17 +0000107 # monkey-patch toctree directive to accept (and ignore) the :numbered: flag
108 from sphinx.directives.other import toctree_directive
109 toctree_directive.options['numbered'] = toctree_directive.options['glob']
Georg Brandlbadbba42009-01-26 23:06:17 +0000110
111try:
112 from sphinx.writers.text import TextWriter
113except ImportError:
114 from sphinx.textwriter import TextWriter
Georg Brandl23f74902008-12-02 08:25:00 +0000115
Georg Brandl681001e2008-06-01 20:33:55 +0000116
117class PydocTopicsBuilder(Builder):
118 name = 'pydoc-topics'
119
120 def init(self):
121 self.topics = {}
122
123 def get_outdated_docs(self):
124 return 'all pydoc topics'
125
126 def get_target_uri(self, docname, typ=None):
127 return '' # no URIs
128
129 def write(self, *ignored):
130 writer = TextWriter(self)
131 for label in self.status_iterator(pydoc_topic_labels, 'building topics... '):
132 if label not in self.env.labels:
133 self.warn('label %r not in documentation' % label)
134 continue
135 docname, labelid, sectname = self.env.labels[label]
136 doctree = self.env.get_and_resolve_doctree(docname, self)
137 document = new_document('<section node>')
138 document.append(doctree.ids[labelid])
139 destination = StringOutput(encoding='utf-8')
140 writer.write(document, destination)
141 self.topics[label] = writer.output
142
143 def finish(self):
144 f = open(path.join(self.outdir, 'pydoc_topics.py'), 'w')
145 try:
146 f.write('# Autogenerated by Sphinx on %s\n' % asctime())
147 f.write('topics = ' + pformat(self.topics) + '\n')
148 finally:
149 f.close()
150
Georg Brandl5d2eb342009-10-27 15:08:27 +0000151
Benjamin Peterson9f7ae1b2009-01-09 03:04:01 +0000152# Support for checking for suspicious markup
153
154import suspicious
Georg Brandl681001e2008-06-01 20:33:55 +0000155
Georg Brandl5d2eb342009-10-27 15:08:27 +0000156
Georg Brandld4c7e632008-07-23 15:17:09 +0000157# Support for documenting Opcodes
158
159import re
160from sphinx import addnodes
161
162opcode_sig_re = re.compile(r'(\w+(?:\+\d)?)\s*\((.*)\)')
163
164def parse_opcode_signature(env, sig, signode):
165 """Transform an opcode signature into RST nodes."""
166 m = opcode_sig_re.match(sig)
167 if m is None:
168 raise ValueError
169 opname, arglist = m.groups()
170 signode += addnodes.desc_name(opname, opname)
171 paramlist = addnodes.desc_parameterlist()
172 signode += paramlist
173 paramlist += addnodes.desc_parameter(arglist, arglist)
174 return opname.strip()
175
176
Georg Brandlc3051922008-04-09 17:58:56 +0000177def setup(app):
178 app.add_role('issue', issue_role)
Georg Brandl5d2eb342009-10-27 15:08:27 +0000179 app.add_directive('impl-detail', ImplementationDetail)
Georg Brandl681001e2008-06-01 20:33:55 +0000180 app.add_builder(PydocTopicsBuilder)
Benjamin Peterson9f7ae1b2009-01-09 03:04:01 +0000181 app.add_builder(suspicious.CheckSuspiciousMarkupBuilder)
Georg Brandld4c7e632008-07-23 15:17:09 +0000182 app.add_description_unit('opcode', 'opcode', '%s (opcode)',
183 parse_opcode_signature)
Georg Brandl27e87232009-10-27 13:31:19 +0000184 app.add_description_unit('2to3fixer', '2to3fixer', '%s (2to3 fixer)')