blob: 8c45274bb27b51c4184f18e798da25d4f1805259 [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'
Mariatta52b8c552017-02-12 12:59:20 -080013SOURCE_URI = 'https://github.com/python/cpython/tree/2.7/%s'
Georg Brandlc3051922008-04-09 17:58:56 +000014
15from docutils import nodes, utils
Ned Deily64a9f3d2017-07-15 23:06:57 -040016from docutils.parsers.rst import Directive
Georg Brandlaf3ef922013-10-12 20:50:21 +020017
Benjamin Peterson7d196762018-04-16 23:54:08 -070018from sphinx.util import status_iterator
Sandro Tosid6e87f42012-01-14 16:42:21 +010019from sphinx.util.nodes import split_explicit_title
Georg Brandlaf3ef922013-10-12 20:50:21 +020020from sphinx.writers.html import HTMLTranslator
21from sphinx.writers.latex import LaTeXTranslator
Benjamin Peterson7d196762018-04-16 23:54:08 -070022from sphinx.writers.text import TextTranslator
Georg Brandlc3051922008-04-09 17:58:56 +000023
Georg Brandl85c5ccf2009-02-05 11:38:23 +000024# monkey-patch reST parser to disable alphabetic and roman enumerated lists
25from docutils.parsers.rst.states import Body
26Body.enum.converters['loweralpha'] = \
27 Body.enum.converters['upperalpha'] = \
28 Body.enum.converters['lowerroman'] = \
29 Body.enum.converters['upperroman'] = lambda x: None
30
Georg Brandl74954562012-10-10 16:45:11 +020031# monkey-patch HTML and LaTeX translators to keep doctest blocks in the
32# doctest docs themselves
33orig_visit_literal_block = HTMLTranslator.visit_literal_block
34def new_visit_literal_block(self, node):
35 meta = self.builder.env.metadata[self.builder.current_docname]
36 old_trim_doctest_flags = self.highlighter.trim_doctest_flags
37 if 'keepdoctest' in meta:
38 self.highlighter.trim_doctest_flags = False
39 try:
40 orig_visit_literal_block(self, node)
41 finally:
42 self.highlighter.trim_doctest_flags = old_trim_doctest_flags
43
44HTMLTranslator.visit_literal_block = new_visit_literal_block
45
46orig_depart_literal_block = LaTeXTranslator.depart_literal_block
47def new_depart_literal_block(self, node):
48 meta = self.builder.env.metadata[self.curfilestack[-1]]
49 old_trim_doctest_flags = self.highlighter.trim_doctest_flags
50 if 'keepdoctest' in meta:
51 self.highlighter.trim_doctest_flags = False
52 try:
53 orig_depart_literal_block(self, node)
54 finally:
55 self.highlighter.trim_doctest_flags = old_trim_doctest_flags
56
57LaTeXTranslator.depart_literal_block = new_depart_literal_block
Georg Brandl85c5ccf2009-02-05 11:38:23 +000058
Georg Brandl08be2e22009-10-22 08:05:04 +000059# Support for marking up and linking to bugs.python.org issues
60
Georg Brandlc3051922008-04-09 17:58:56 +000061def issue_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
62 issue = utils.unescape(text)
Mariatta52b8c552017-02-12 12:59:20 -080063 text = 'bpo-'+ issue
Georg Brandlc3051922008-04-09 17:58:56 +000064 refnode = nodes.reference(text, text, refuri=ISSUE_URI % issue)
65 return [refnode], []
66
67
Éric Araujof595a762011-08-19 00:12:33 +020068# Support for linking to Python source files easily
69
70def source_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
Sandro Tosid6e87f42012-01-14 16:42:21 +010071 has_t, title, target = split_explicit_title(text)
72 title = utils.unescape(title)
73 target = utils.unescape(target)
74 refnode = nodes.reference(title, title, refuri=SOURCE_URI % target)
Éric Araujof595a762011-08-19 00:12:33 +020075 return [refnode], []
76
77
Georg Brandl08be2e22009-10-22 08:05:04 +000078# Support for marking up implementation details
79
Georg Brandl08be2e22009-10-22 08:05:04 +000080class ImplementationDetail(Directive):
81
82 has_content = True
83 required_arguments = 0
84 optional_arguments = 1
85 final_argument_whitespace = True
86
87 def run(self):
88 pnode = nodes.compound(classes=['impl-detail'])
89 content = self.content
Georg Brandla0547222009-10-22 11:01:46 +000090 add_text = nodes.strong('CPython implementation detail:',
91 'CPython implementation detail:')
Georg Brandlf5f7c662009-10-22 11:28:23 +000092 if self.arguments:
93 n, m = self.state.inline_text(self.arguments[0], self.lineno)
94 pnode.append(nodes.paragraph('', '', *(n + m)))
Georg Brandl08be2e22009-10-22 08:05:04 +000095 self.state.nested_parse(content, self.content_offset, pnode)
Georg Brandla0547222009-10-22 11:01:46 +000096 if pnode.children and isinstance(pnode[0], nodes.paragraph):
97 pnode[0].insert(0, add_text)
98 pnode[0].insert(1, nodes.Text(' '))
99 else:
100 pnode.insert(0, nodes.paragraph('', '', add_text))
Georg Brandl08be2e22009-10-22 08:05:04 +0000101 return [pnode]
102
103
Sandro Tosid6e87f42012-01-14 16:42:21 +0100104# Support for documenting decorators
105
106from sphinx import addnodes
107from sphinx.domains.python import PyModulelevel, PyClassmember
108
109class PyDecoratorMixin(object):
110 def handle_signature(self, sig, signode):
111 ret = super(PyDecoratorMixin, self).handle_signature(sig, signode)
112 signode.insert(0, addnodes.desc_addname('@', '@'))
113 return ret
114
115 def needs_arglist(self):
116 return False
117
118class PyDecoratorFunction(PyDecoratorMixin, PyModulelevel):
119 def run(self):
120 # a decorator function is a function after all
121 self.name = 'py:function'
122 return PyModulelevel.run(self)
123
124class PyDecoratorMethod(PyDecoratorMixin, PyClassmember):
125 def run(self):
126 self.name = 'py:method'
127 return PyClassmember.run(self)
128
129
Georg Brandl681001e2008-06-01 20:33:55 +0000130# Support for building "topic help" for pydoc
131
132pydoc_topic_labels = [
133 'assert', 'assignment', 'atom-identifiers', 'atom-literals',
134 'attribute-access', 'attribute-references', 'augassign', 'binary',
135 'bitwise', 'bltin-code-objects', 'bltin-ellipsis-object',
Senthil Kumaran788db632016-01-06 03:54:18 -0800136 'bltin-file-objects', 'bltin-null-object', 'bltin-type-objects', 'booleans',
Sandro Tosid6e87f42012-01-14 16:42:21 +0100137 'break', 'callable-types', 'calls', 'class', 'comparisons', 'compound',
138 'context-managers', 'continue', 'conversions', 'customization', 'debugger',
Ezio Melottif6c0ec42014-02-14 07:04:15 +0200139 'del', 'dict', 'dynamic-features', 'else', 'exceptions', 'exec', 'execmodel',
Sandro Tosid6e87f42012-01-14 16:42:21 +0100140 'exprlists', 'floating', 'for', 'formatstrings', 'function', 'global',
141 'id-classes', 'identifiers', 'if', 'imaginary', 'import', 'in', 'integers',
Benjamin Peterson71e2d2e2013-03-23 10:09:24 -0500142 'lambda', 'lists', 'naming', 'numbers', 'numeric-types',
Ezio Melottif6c0ec42014-02-14 07:04:15 +0200143 'objects', 'operator-summary', 'pass', 'power', 'print', 'raise', 'return',
Sandro Tosid6e87f42012-01-14 16:42:21 +0100144 'sequence-types', 'shifting', 'slicings', 'specialattrs', 'specialnames',
145 'string-methods', 'strings', 'subscriptions', 'truth', 'try', 'types',
146 'typesfunctions', 'typesmapping', 'typesmethods', 'typesmodules',
147 'typesseq', 'typesseq-mutable', 'unary', 'while', 'with', 'yield'
Georg Brandl681001e2008-06-01 20:33:55 +0000148]
149
150from os import path
151from time import asctime
152from pprint import pformat
153from docutils.io import StringOutput
154from docutils.utils import new_document
Benjamin Petersona2813c92008-12-20 23:48:54 +0000155
Benjamin Peterson1a67f582009-01-08 04:01:00 +0000156from sphinx.builders import Builder
157from sphinx.writers.text import TextWriter
Benjamin Petersoncb948f12008-12-01 12:52:51 +0000158
Georg Brandl681001e2008-06-01 20:33:55 +0000159
160class PydocTopicsBuilder(Builder):
161 name = 'pydoc-topics'
162
Benjamin Peterson7d196762018-04-16 23:54:08 -0700163 default_translator_class = TextTranslator
164
Georg Brandl681001e2008-06-01 20:33:55 +0000165 def init(self):
166 self.topics = {}
Benjamin Peterson7d196762018-04-16 23:54:08 -0700167 self.secnumbers = {}
Georg Brandl681001e2008-06-01 20:33:55 +0000168
169 def get_outdated_docs(self):
170 return 'all pydoc topics'
171
172 def get_target_uri(self, docname, typ=None):
173 return '' # no URIs
174
175 def write(self, *ignored):
176 writer = TextWriter(self)
Benjamin Peterson7d196762018-04-16 23:54:08 -0700177 for label in status_iterator(pydoc_topic_labels,
178 'building topics... ',
179 length=len(pydoc_topic_labels)):
Sandro Tosid6e87f42012-01-14 16:42:21 +0100180 if label not in self.env.domaindata['std']['labels']:
Georg Brandl681001e2008-06-01 20:33:55 +0000181 self.warn('label %r not in documentation' % label)
182 continue
Sandro Tosid6e87f42012-01-14 16:42:21 +0100183 docname, labelid, sectname = self.env.domaindata['std']['labels'][label]
Georg Brandl681001e2008-06-01 20:33:55 +0000184 doctree = self.env.get_and_resolve_doctree(docname, self)
185 document = new_document('<section node>')
186 document.append(doctree.ids[labelid])
187 destination = StringOutput(encoding='utf-8')
188 writer.write(document, destination)
Georg Brandl14b5a4d2014-10-02 08:26:26 +0200189 self.topics[label] = writer.output
Georg Brandl681001e2008-06-01 20:33:55 +0000190
191 def finish(self):
Georg Brandl14b5a4d2014-10-02 08:26:26 +0200192 f = open(path.join(self.outdir, 'topics.py'), 'wb')
Georg Brandl681001e2008-06-01 20:33:55 +0000193 try:
Georg Brandl14b5a4d2014-10-02 08:26:26 +0200194 f.write('# -*- coding: utf-8 -*-\n'.encode('utf-8'))
195 f.write(('# Autogenerated by Sphinx on %s\n' % asctime()).encode('utf-8'))
196 f.write(('topics = ' + pformat(self.topics) + '\n').encode('utf-8'))
Georg Brandl681001e2008-06-01 20:33:55 +0000197 finally:
198 f.close()
199
Georg Brandl08be2e22009-10-22 08:05:04 +0000200
Georg Brandl700cf282009-01-04 10:23:49 +0000201# Support for checking for suspicious markup
202
203import suspicious
Georg Brandl681001e2008-06-01 20:33:55 +0000204
Georg Brandl08be2e22009-10-22 08:05:04 +0000205
Georg Brandld4c7e632008-07-23 15:17:09 +0000206# Support for documenting Opcodes
207
208import re
Georg Brandld4c7e632008-07-23 15:17:09 +0000209
Sandro Tosid6e87f42012-01-14 16:42:21 +0100210opcode_sig_re = re.compile(r'(\w+(?:\+\d)?)(?:\s*\((.*)\))?')
Georg Brandld4c7e632008-07-23 15:17:09 +0000211
212def parse_opcode_signature(env, sig, signode):
213 """Transform an opcode signature into RST nodes."""
214 m = opcode_sig_re.match(sig)
215 if m is None:
216 raise ValueError
217 opname, arglist = m.groups()
218 signode += addnodes.desc_name(opname, opname)
Sandro Tosid6e87f42012-01-14 16:42:21 +0100219 if arglist is not None:
220 paramlist = addnodes.desc_parameterlist()
221 signode += paramlist
222 paramlist += addnodes.desc_parameter(arglist, arglist)
Georg Brandld4c7e632008-07-23 15:17:09 +0000223 return opname.strip()
224
225
Sandro Tosid6e87f42012-01-14 16:42:21 +0100226# Support for documenting pdb commands
227
228pdbcmd_sig_re = re.compile(r'([a-z()!]+)\s*(.*)')
229
230# later...
231#pdbargs_tokens_re = re.compile(r'''[a-zA-Z]+ | # identifiers
232# [.,:]+ | # punctuation
233# [\[\]()] | # parens
234# \s+ # whitespace
235# ''', re.X)
236
237def parse_pdb_command(env, sig, signode):
238 """Transform a pdb command signature into RST nodes."""
239 m = pdbcmd_sig_re.match(sig)
240 if m is None:
241 raise ValueError
242 name, args = m.groups()
243 fullname = name.replace('(', '').replace(')', '')
244 signode += addnodes.desc_name(name, name)
245 if args:
246 signode += addnodes.desc_addname(' '+args, ' '+args)
247 return fullname
248
249
Georg Brandlc3051922008-04-09 17:58:56 +0000250def setup(app):
251 app.add_role('issue', issue_role)
Éric Araujof595a762011-08-19 00:12:33 +0200252 app.add_role('source', source_role)
Georg Brandl08be2e22009-10-22 08:05:04 +0000253 app.add_directive('impl-detail', ImplementationDetail)
Georg Brandl681001e2008-06-01 20:33:55 +0000254 app.add_builder(PydocTopicsBuilder)
Georg Brandl700cf282009-01-04 10:23:49 +0000255 app.add_builder(suspicious.CheckSuspiciousMarkupBuilder)
Georg Brandld4c7e632008-07-23 15:17:09 +0000256 app.add_description_unit('opcode', 'opcode', '%s (opcode)',
257 parse_opcode_signature)
Sandro Tosid6e87f42012-01-14 16:42:21 +0100258 app.add_description_unit('pdbcommand', 'pdbcmd', '%s (pdb command)',
259 parse_pdb_command)
Benjamin Petersone0820e22009-02-07 23:01:19 +0000260 app.add_description_unit('2to3fixer', '2to3fixer', '%s (2to3 fixer)')
Sandro Tosid6e87f42012-01-14 16:42:21 +0100261 app.add_directive_to_domain('py', 'decorator', PyDecoratorFunction)
262 app.add_directive_to_domain('py', 'decoratormethod', PyDecoratorMethod)
Georg Brandl75070f02014-09-30 22:17:41 +0200263 return {'version': '1.0', 'parallel_read_safe': True}