blob: 169989180c0a00430931b3e737c927b7ca3e4612 [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 Brandl14b5a4d2014-10-02 08:26:26 +02008 :copyright: 2008-2014 by Georg Brandl.
Georg Brandlc3051922008-04-09 17:58:56 +00009 :license: Python license.
10"""
11
Alex Gaynor9c2ce252014-10-13 12:58:03 -070012ISSUE_URI = 'https://bugs.python.org/issue%s'
Benjamin Peterson05137ed2014-09-13 01:44:34 -040013SOURCE_URI = 'https://hg.python.org/cpython/file/2.7/%s'
Georg Brandlc3051922008-04-09 17:58:56 +000014
15from docutils import nodes, utils
Georg Brandlaf3ef922013-10-12 20:50:21 +020016
Sandro Tosid6e87f42012-01-14 16:42:21 +010017from sphinx.util.nodes import split_explicit_title
Georg Brandl14b5a4d2014-10-02 08:26:26 +020018from sphinx.util.compat import Directive
Georg Brandlaf3ef922013-10-12 20:50:21 +020019from sphinx.writers.html import HTMLTranslator
20from sphinx.writers.latex import LaTeXTranslator
Georg Brandlc3051922008-04-09 17:58:56 +000021
Georg Brandl85c5ccf2009-02-05 11:38:23 +000022# monkey-patch reST parser to disable alphabetic and roman enumerated lists
23from docutils.parsers.rst.states import Body
24Body.enum.converters['loweralpha'] = \
25 Body.enum.converters['upperalpha'] = \
26 Body.enum.converters['lowerroman'] = \
27 Body.enum.converters['upperroman'] = lambda x: None
28
Georg Brandl74954562012-10-10 16:45:11 +020029# monkey-patch HTML and LaTeX translators to keep doctest blocks in the
30# doctest docs themselves
31orig_visit_literal_block = HTMLTranslator.visit_literal_block
32def new_visit_literal_block(self, node):
33 meta = self.builder.env.metadata[self.builder.current_docname]
34 old_trim_doctest_flags = self.highlighter.trim_doctest_flags
35 if 'keepdoctest' in meta:
36 self.highlighter.trim_doctest_flags = False
37 try:
38 orig_visit_literal_block(self, node)
39 finally:
40 self.highlighter.trim_doctest_flags = old_trim_doctest_flags
41
42HTMLTranslator.visit_literal_block = new_visit_literal_block
43
44orig_depart_literal_block = LaTeXTranslator.depart_literal_block
45def new_depart_literal_block(self, node):
46 meta = self.builder.env.metadata[self.curfilestack[-1]]
47 old_trim_doctest_flags = self.highlighter.trim_doctest_flags
48 if 'keepdoctest' in meta:
49 self.highlighter.trim_doctest_flags = False
50 try:
51 orig_depart_literal_block(self, node)
52 finally:
53 self.highlighter.trim_doctest_flags = old_trim_doctest_flags
54
55LaTeXTranslator.depart_literal_block = new_depart_literal_block
Georg Brandl85c5ccf2009-02-05 11:38:23 +000056
Georg Brandl08be2e22009-10-22 08:05:04 +000057# Support for marking up and linking to bugs.python.org issues
58
Georg Brandlc3051922008-04-09 17:58:56 +000059def issue_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
60 issue = utils.unescape(text)
61 text = 'issue ' + issue
62 refnode = nodes.reference(text, text, refuri=ISSUE_URI % issue)
63 return [refnode], []
64
65
Éric Araujof595a762011-08-19 00:12:33 +020066# Support for linking to Python source files easily
67
68def source_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
Sandro Tosid6e87f42012-01-14 16:42:21 +010069 has_t, title, target = split_explicit_title(text)
70 title = utils.unescape(title)
71 target = utils.unescape(target)
72 refnode = nodes.reference(title, title, refuri=SOURCE_URI % target)
Éric Araujof595a762011-08-19 00:12:33 +020073 return [refnode], []
74
75
Georg Brandl08be2e22009-10-22 08:05:04 +000076# Support for marking up implementation details
77
Georg Brandl08be2e22009-10-22 08:05:04 +000078class ImplementationDetail(Directive):
79
80 has_content = True
81 required_arguments = 0
82 optional_arguments = 1
83 final_argument_whitespace = True
84
85 def run(self):
86 pnode = nodes.compound(classes=['impl-detail'])
87 content = self.content
Georg Brandla0547222009-10-22 11:01:46 +000088 add_text = nodes.strong('CPython implementation detail:',
89 'CPython implementation detail:')
Georg Brandlf5f7c662009-10-22 11:28:23 +000090 if self.arguments:
91 n, m = self.state.inline_text(self.arguments[0], self.lineno)
92 pnode.append(nodes.paragraph('', '', *(n + m)))
Georg Brandl08be2e22009-10-22 08:05:04 +000093 self.state.nested_parse(content, self.content_offset, pnode)
Georg Brandla0547222009-10-22 11:01:46 +000094 if pnode.children and isinstance(pnode[0], nodes.paragraph):
95 pnode[0].insert(0, add_text)
96 pnode[0].insert(1, nodes.Text(' '))
97 else:
98 pnode.insert(0, nodes.paragraph('', '', add_text))
Georg Brandl08be2e22009-10-22 08:05:04 +000099 return [pnode]
100
101
Sandro Tosid6e87f42012-01-14 16:42:21 +0100102# Support for documenting decorators
103
104from sphinx import addnodes
105from sphinx.domains.python import PyModulelevel, PyClassmember
106
107class PyDecoratorMixin(object):
108 def handle_signature(self, sig, signode):
109 ret = super(PyDecoratorMixin, self).handle_signature(sig, signode)
110 signode.insert(0, addnodes.desc_addname('@', '@'))
111 return ret
112
113 def needs_arglist(self):
114 return False
115
116class PyDecoratorFunction(PyDecoratorMixin, PyModulelevel):
117 def run(self):
118 # a decorator function is a function after all
119 self.name = 'py:function'
120 return PyModulelevel.run(self)
121
122class PyDecoratorMethod(PyDecoratorMixin, PyClassmember):
123 def run(self):
124 self.name = 'py:method'
125 return PyClassmember.run(self)
126
127
Georg Brandl681001e2008-06-01 20:33:55 +0000128# Support for building "topic help" for pydoc
129
130pydoc_topic_labels = [
131 'assert', 'assignment', 'atom-identifiers', 'atom-literals',
132 'attribute-access', 'attribute-references', 'augassign', 'binary',
133 'bitwise', 'bltin-code-objects', 'bltin-ellipsis-object',
Sandro Tosid6e87f42012-01-14 16:42:21 +0100134 'bltin-null-object', 'bltin-type-objects', 'booleans',
135 'break', 'callable-types', 'calls', 'class', 'comparisons', 'compound',
136 'context-managers', 'continue', 'conversions', 'customization', 'debugger',
Ezio Melottif6c0ec42014-02-14 07:04:15 +0200137 'del', 'dict', 'dynamic-features', 'else', 'exceptions', 'exec', 'execmodel',
Sandro Tosid6e87f42012-01-14 16:42:21 +0100138 'exprlists', 'floating', 'for', 'formatstrings', 'function', 'global',
139 'id-classes', 'identifiers', 'if', 'imaginary', 'import', 'in', 'integers',
Benjamin Peterson71e2d2e2013-03-23 10:09:24 -0500140 'lambda', 'lists', 'naming', 'numbers', 'numeric-types',
Ezio Melottif6c0ec42014-02-14 07:04:15 +0200141 'objects', 'operator-summary', 'pass', 'power', 'print', 'raise', 'return',
Sandro Tosid6e87f42012-01-14 16:42:21 +0100142 'sequence-types', 'shifting', 'slicings', 'specialattrs', 'specialnames',
143 'string-methods', 'strings', 'subscriptions', 'truth', 'try', 'types',
144 'typesfunctions', 'typesmapping', 'typesmethods', 'typesmodules',
145 'typesseq', 'typesseq-mutable', 'unary', 'while', 'with', 'yield'
Georg Brandl681001e2008-06-01 20:33:55 +0000146]
147
148from os import path
149from time import asctime
150from pprint import pformat
151from docutils.io import StringOutput
152from docutils.utils import new_document
Benjamin Petersona2813c92008-12-20 23:48:54 +0000153
Benjamin Peterson1a67f582009-01-08 04:01:00 +0000154from sphinx.builders import Builder
155from sphinx.writers.text import TextWriter
Benjamin Petersoncb948f12008-12-01 12:52:51 +0000156
Georg Brandl681001e2008-06-01 20:33:55 +0000157
158class PydocTopicsBuilder(Builder):
159 name = 'pydoc-topics'
160
161 def init(self):
162 self.topics = {}
163
164 def get_outdated_docs(self):
165 return 'all pydoc topics'
166
167 def get_target_uri(self, docname, typ=None):
168 return '' # no URIs
169
170 def write(self, *ignored):
171 writer = TextWriter(self)
Benjamin Petersonc5206b32009-03-29 21:50:14 +0000172 for label in self.status_iterator(pydoc_topic_labels,
173 'building topics... ',
174 length=len(pydoc_topic_labels)):
Sandro Tosid6e87f42012-01-14 16:42:21 +0100175 if label not in self.env.domaindata['std']['labels']:
Georg Brandl681001e2008-06-01 20:33:55 +0000176 self.warn('label %r not in documentation' % label)
177 continue
Sandro Tosid6e87f42012-01-14 16:42:21 +0100178 docname, labelid, sectname = self.env.domaindata['std']['labels'][label]
Georg Brandl681001e2008-06-01 20:33:55 +0000179 doctree = self.env.get_and_resolve_doctree(docname, self)
180 document = new_document('<section node>')
181 document.append(doctree.ids[labelid])
182 destination = StringOutput(encoding='utf-8')
183 writer.write(document, destination)
Georg Brandl14b5a4d2014-10-02 08:26:26 +0200184 self.topics[label] = writer.output
Georg Brandl681001e2008-06-01 20:33:55 +0000185
186 def finish(self):
Georg Brandl14b5a4d2014-10-02 08:26:26 +0200187 f = open(path.join(self.outdir, 'topics.py'), 'wb')
Georg Brandl681001e2008-06-01 20:33:55 +0000188 try:
Georg Brandl14b5a4d2014-10-02 08:26:26 +0200189 f.write('# -*- coding: utf-8 -*-\n'.encode('utf-8'))
190 f.write(('# Autogenerated by Sphinx on %s\n' % asctime()).encode('utf-8'))
191 f.write(('topics = ' + pformat(self.topics) + '\n').encode('utf-8'))
Georg Brandl681001e2008-06-01 20:33:55 +0000192 finally:
193 f.close()
194
Georg Brandl08be2e22009-10-22 08:05:04 +0000195
Georg Brandl700cf282009-01-04 10:23:49 +0000196# Support for checking for suspicious markup
197
198import suspicious
Georg Brandl681001e2008-06-01 20:33:55 +0000199
Georg Brandl08be2e22009-10-22 08:05:04 +0000200
Georg Brandld4c7e632008-07-23 15:17:09 +0000201# Support for documenting Opcodes
202
203import re
Georg Brandld4c7e632008-07-23 15:17:09 +0000204
Sandro Tosid6e87f42012-01-14 16:42:21 +0100205opcode_sig_re = re.compile(r'(\w+(?:\+\d)?)(?:\s*\((.*)\))?')
Georg Brandld4c7e632008-07-23 15:17:09 +0000206
207def parse_opcode_signature(env, sig, signode):
208 """Transform an opcode signature into RST nodes."""
209 m = opcode_sig_re.match(sig)
210 if m is None:
211 raise ValueError
212 opname, arglist = m.groups()
213 signode += addnodes.desc_name(opname, opname)
Sandro Tosid6e87f42012-01-14 16:42:21 +0100214 if arglist is not None:
215 paramlist = addnodes.desc_parameterlist()
216 signode += paramlist
217 paramlist += addnodes.desc_parameter(arglist, arglist)
Georg Brandld4c7e632008-07-23 15:17:09 +0000218 return opname.strip()
219
220
Sandro Tosid6e87f42012-01-14 16:42:21 +0100221# Support for documenting pdb commands
222
223pdbcmd_sig_re = re.compile(r'([a-z()!]+)\s*(.*)')
224
225# later...
226#pdbargs_tokens_re = re.compile(r'''[a-zA-Z]+ | # identifiers
227# [.,:]+ | # punctuation
228# [\[\]()] | # parens
229# \s+ # whitespace
230# ''', re.X)
231
232def parse_pdb_command(env, sig, signode):
233 """Transform a pdb command signature into RST nodes."""
234 m = pdbcmd_sig_re.match(sig)
235 if m is None:
236 raise ValueError
237 name, args = m.groups()
238 fullname = name.replace('(', '').replace(')', '')
239 signode += addnodes.desc_name(name, name)
240 if args:
241 signode += addnodes.desc_addname(' '+args, ' '+args)
242 return fullname
243
244
Georg Brandlc3051922008-04-09 17:58:56 +0000245def setup(app):
246 app.add_role('issue', issue_role)
Éric Araujof595a762011-08-19 00:12:33 +0200247 app.add_role('source', source_role)
Georg Brandl08be2e22009-10-22 08:05:04 +0000248 app.add_directive('impl-detail', ImplementationDetail)
Georg Brandl681001e2008-06-01 20:33:55 +0000249 app.add_builder(PydocTopicsBuilder)
Georg Brandl700cf282009-01-04 10:23:49 +0000250 app.add_builder(suspicious.CheckSuspiciousMarkupBuilder)
Georg Brandld4c7e632008-07-23 15:17:09 +0000251 app.add_description_unit('opcode', 'opcode', '%s (opcode)',
252 parse_opcode_signature)
Sandro Tosid6e87f42012-01-14 16:42:21 +0100253 app.add_description_unit('pdbcommand', 'pdbcmd', '%s (pdb command)',
254 parse_pdb_command)
Benjamin Petersone0820e22009-02-07 23:01:19 +0000255 app.add_description_unit('2to3fixer', '2to3fixer', '%s (2to3 fixer)')
Sandro Tosid6e87f42012-01-14 16:42:21 +0100256 app.add_directive_to_domain('py', 'decorator', PyDecoratorFunction)
257 app.add_directive_to_domain('py', 'decoratormethod', PyDecoratorMethod)
Georg Brandl75070f02014-09-30 22:17:41 +0200258 return {'version': '1.0', 'parallel_read_safe': True}