blob: 415310d969f80ae308633ea34b5a795cfbc2305f [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 Brandl43819252009-04-26 09:56:44 +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 Brandl85c5ccf2009-02-05 11:38:23 +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 Brandl076ca5a2009-09-16 09:05:11 +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
Georg Brandl85c5ccf2009-02-05 11:38:23 +000037
Georg Brandl08be2e22009-10-22 08:05:04 +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 Brandl08be2e22009-10-22 08:05:04 +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
Georg Brandla0547222009-10-22 11:01:46 +000061 add_text = nodes.strong('CPython implementation detail:',
62 'CPython implementation detail:')
Georg Brandlf5f7c662009-10-22 11:28:23 +000063 if self.arguments:
64 n, m = self.state.inline_text(self.arguments[0], self.lineno)
65 pnode.append(nodes.paragraph('', '', *(n + m)))
Georg Brandl08be2e22009-10-22 08:05:04 +000066 self.state.nested_parse(content, self.content_offset, pnode)
Georg Brandla0547222009-10-22 11:01:46 +000067 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))
Georg Brandl08be2e22009-10-22 08:05:04 +000072 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 Petersona2813c92008-12-20 23:48:54 +0000102
Benjamin Peterson1a67f582009-01-08 04:01:00 +0000103from sphinx.builders import Builder
104from sphinx.writers.text import TextWriter
Benjamin Petersoncb948f12008-12-01 12:52:51 +0000105
Georg Brandl681001e2008-06-01 20:33:55 +0000106
107class PydocTopicsBuilder(Builder):
108 name = 'pydoc-topics'
109
110 def init(self):
111 self.topics = {}
112
113 def get_outdated_docs(self):
114 return 'all pydoc topics'
115
116 def get_target_uri(self, docname, typ=None):
117 return '' # no URIs
118
119 def write(self, *ignored):
120 writer = TextWriter(self)
Benjamin Petersonc5206b32009-03-29 21:50:14 +0000121 for label in self.status_iterator(pydoc_topic_labels,
122 'building topics... ',
123 length=len(pydoc_topic_labels)):
Georg Brandl681001e2008-06-01 20:33:55 +0000124 if label not in self.env.labels:
125 self.warn('label %r not in documentation' % label)
126 continue
127 docname, labelid, sectname = self.env.labels[label]
128 doctree = self.env.get_and_resolve_doctree(docname, self)
129 document = new_document('<section node>')
130 document.append(doctree.ids[labelid])
131 destination = StringOutput(encoding='utf-8')
132 writer.write(document, destination)
133 self.topics[label] = writer.output
134
135 def finish(self):
Georg Brandl43819252009-04-26 09:56:44 +0000136 f = open(path.join(self.outdir, 'topics.py'), 'w')
Georg Brandl681001e2008-06-01 20:33:55 +0000137 try:
138 f.write('# Autogenerated by Sphinx on %s\n' % asctime())
139 f.write('topics = ' + pformat(self.topics) + '\n')
140 finally:
141 f.close()
142
Georg Brandl08be2e22009-10-22 08:05:04 +0000143
Georg Brandl700cf282009-01-04 10:23:49 +0000144# Support for checking for suspicious markup
145
146import suspicious
Georg Brandl681001e2008-06-01 20:33:55 +0000147
Georg Brandl08be2e22009-10-22 08:05:04 +0000148
Georg Brandld4c7e632008-07-23 15:17:09 +0000149# Support for documenting Opcodes
150
151import re
152from sphinx import addnodes
153
154opcode_sig_re = re.compile(r'(\w+(?:\+\d)?)\s*\((.*)\)')
155
156def parse_opcode_signature(env, sig, signode):
157 """Transform an opcode signature into RST nodes."""
158 m = opcode_sig_re.match(sig)
159 if m is None:
160 raise ValueError
161 opname, arglist = m.groups()
162 signode += addnodes.desc_name(opname, opname)
163 paramlist = addnodes.desc_parameterlist()
164 signode += paramlist
165 paramlist += addnodes.desc_parameter(arglist, arglist)
166 return opname.strip()
167
168
Georg Brandlc3051922008-04-09 17:58:56 +0000169def setup(app):
170 app.add_role('issue', issue_role)
Georg Brandl08be2e22009-10-22 08:05:04 +0000171 app.add_directive('impl-detail', ImplementationDetail)
Georg Brandl681001e2008-06-01 20:33:55 +0000172 app.add_builder(PydocTopicsBuilder)
Georg Brandl700cf282009-01-04 10:23:49 +0000173 app.add_builder(suspicious.CheckSuspiciousMarkupBuilder)
Georg Brandld4c7e632008-07-23 15:17:09 +0000174 app.add_description_unit('opcode', 'opcode', '%s (opcode)',
175 parse_opcode_signature)
Benjamin Petersone0820e22009-02-07 23:01:19 +0000176 app.add_description_unit('2to3fixer', '2to3fixer', '%s (2to3 fixer)')