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