| 1 |
""" |
| 2 |
Sphinx plugins for Django documentation. |
| 3 |
""" |
| 4 |
import json |
| 5 |
import os |
| 6 |
import re |
| 7 |
|
| 8 |
from docutils import nodes |
| 9 |
from docutils.parsers.rst import Directive |
| 10 |
from docutils.statemachine import ViewList |
| 11 |
from sphinx import addnodes |
| 12 |
from sphinx.builders.html import StandaloneHTMLBuilder |
| 13 |
from sphinx.directives.code import CodeBlock |
| 14 |
from sphinx.domains.std import Cmdoption |
| 15 |
from sphinx.errors import ExtensionError |
| 16 |
from sphinx.util import logging |
| 17 |
from sphinx.util.console import bold |
| 18 |
from sphinx.writers.html import HTMLTranslator |
| 19 |
|
| 20 |
logger = logging.getLogger(__name__) |
| 21 |
# RE for option descriptions without a '--' prefix |
| 22 |
simple_option_desc_re = re.compile( |
| 23 |
r'([-_a-zA-Z0-9]+)(\s*.*?)(?=,\s+(?:/|-|--)|$)') |
| 24 |
|
| 25 |
|
| 26 |
def setup(app): |
| 27 |
app.add_crossref_type( |
| 28 |
directivename="setting", |
| 29 |
rolename="setting", |
| 30 |
indextemplate="pair: %s; setting", |
| 31 |
) |
| 32 |
app.add_crossref_type( |
| 33 |
directivename="templatetag", |
| 34 |
rolename="ttag", |
| 35 |
indextemplate="pair: %s; template tag" |
| 36 |
) |
| 37 |
app.add_crossref_type( |
| 38 |
directivename="templatefilter", |
| 39 |
rolename="tfilter", |
| 40 |
indextemplate="pair: %s; template filter" |
| 41 |
) |
| 42 |
app.add_crossref_type( |
| 43 |
directivename="fieldlookup", |
| 44 |
rolename="lookup", |
| 45 |
indextemplate="pair: %s; field lookup type", |
| 46 |
) |
| 47 |
app.add_object_type( |
| 48 |
directivename="django-admin", |
| 49 |
rolename="djadmin", |
| 50 |
indextemplate="pair: %s; django-admin command", |
| 51 |
parse_node=parse_django_admin_node, |
| 52 |
) |
| 53 |
app.add_directive('django-admin-option', Cmdoption) |
| 54 |
app.add_config_value('django_next_version', '0.0', True) |
| 55 |
app.add_directive('versionadded', VersionDirective) |
| 56 |
app.add_directive('versionchanged', VersionDirective) |
| 57 |
app.add_builder(DjangoStandaloneHTMLBuilder) |
| 58 |
app.set_translator('djangohtml', DjangoHTMLTranslator) |
| 59 |
app.set_translator('json', DjangoHTMLTranslator) |
| 60 |
app.add_node( |
| 61 |
ConsoleNode, |
| 62 |
html=(visit_console_html, None), |
| 63 |
latex=(visit_console_dummy, depart_console_dummy), |
| 64 |
man=(visit_console_dummy, depart_console_dummy), |
| 65 |
text=(visit_console_dummy, depart_console_dummy), |
| 66 |
texinfo=(visit_console_dummy, depart_console_dummy), |
| 67 |
) |
| 68 |
app.add_directive('console', ConsoleDirective) |
| 69 |
app.connect('html-page-context', html_page_context_hook) |
| 70 |
app.add_role('default-role-error', default_role_error) |
| 71 |
return {'parallel_read_safe': True} |
| 72 |
|
| 73 |
|
| 74 |
class VersionDirective(Directive): |
| 75 |
has_content = True |
| 76 |
required_arguments = 1 |
| 77 |
optional_arguments = 1 |
| 78 |
final_argument_whitespace = True |
| 79 |
option_spec = {} |
| 80 |
|
| 81 |
def run(self): |
| 82 |
if len(self.arguments) > 1: |
| 83 |
msg = """Only one argument accepted for directive '{directive_name}::'. |
| 84 |
Comments should be provided as content, |
| 85 |
not as an extra argument.""".format(directive_name=self.name) |
| 86 |
raise self.error(msg) |
| 87 |
|
| 88 |
env = self.state.document.settings.env |
| 89 |
ret = [] |
| 90 |
node = addnodes.versionmodified() |
| 91 |
ret.append(node) |
| 92 |
|
| 93 |
if self.arguments[0] == env.config.django_next_version: |
| 94 |
node['version'] = "Development version" |
| 95 |
else: |
| 96 |
node['version'] = self.arguments[0] |
| 97 |
|
| 98 |
node['type'] = self.name |
| 99 |
if self.content: |
| 100 |
self.state.nested_parse(self.content, self.content_offset, node) |
| 101 |
try: |
| 102 |
env.get_domain('changeset').note_changeset(node) |
| 103 |
except ExtensionError: |
| 104 |
# Sphinx < 1.8: Domain 'changeset' is not registered |
| 105 |
env.note_versionchange(node['type'], node['version'], node, self.lineno) |
| 106 |
return ret |
| 107 |
|
| 108 |
|
| 109 |
class DjangoHTMLTranslator(HTMLTranslator): |
| 110 |
""" |
| 111 |
Django-specific reST to HTML tweaks. |
| 112 |
""" |
| 113 |
|
| 114 |
# Don't use border=1, which docutils does by default. |
| 115 |
def visit_table(self, node): |
| 116 |
self.context.append(self.compact_p) |
| 117 |
self.compact_p = True |
| 118 |
self._table_row_index = 0 # Needed by Sphinx |
| 119 |
self.body.append(self.starttag(node, 'table', CLASS='docutils')) |
| 120 |
|
| 121 |
def depart_table(self, node): |
| 122 |
self.compact_p = self.context.pop() |
| 123 |
self.body.append('</table>\n') |
| 124 |
|
| 125 |
def visit_desc_parameterlist(self, node): |
| 126 |
self.body.append('(') # by default sphinx puts <big> around the "(" |
| 127 |
self.first_param = 1 |
| 128 |
self.optional_param_level = 0 |
| 129 |
self.param_separator = node.child_text_separator |
| 130 |
self.required_params_left = sum(isinstance(c, addnodes.desc_parameter) for c in node.children) |
| 131 |
|
| 132 |
def depart_desc_parameterlist(self, node): |
| 133 |
self.body.append(')') |
| 134 |
|
| 135 |
# |
| 136 |
# Turn the "new in version" stuff (versionadded/versionchanged) into a |
| 137 |
# better callout -- the Sphinx default is just a little span, |
| 138 |
# which is a bit less obvious that I'd like. |
| 139 |
# |
| 140 |
# FIXME: these messages are all hardcoded in English. We need to change |
| 141 |
# that to accommodate other language docs, but I can't work out how to make |
| 142 |
# that work. |
| 143 |
# |
| 144 |
version_text = { |
| 145 |
'versionchanged': 'Changed in Django %s', |
| 146 |
'versionadded': 'New in Django %s', |
| 147 |
} |
| 148 |
|
| 149 |
def visit_versionmodified(self, node): |
| 150 |
self.body.append( |
| 151 |
self.starttag(node, 'div', CLASS=node['type']) |
| 152 |
) |
| 153 |
version_text = self.version_text.get(node['type']) |
| 154 |
if version_text: |
| 155 |
title = "%s%s" % ( |
| 156 |
version_text % node['version'], |
| 157 |
":" if len(node) else "." |
| 158 |
) |
| 159 |
self.body.append('<span class="title">%s</span> ' % title) |
| 160 |
|
| 161 |
def depart_versionmodified(self, node): |
| 162 |
self.body.append("</div>\n") |
| 163 |
|
| 164 |
# Give each section a unique ID -- nice for custom CSS hooks |
| 165 |
def visit_section(self, node): |
| 166 |
old_ids = node.get('ids', []) |
| 167 |
node['ids'] = ['s-' + i for i in old_ids] |
| 168 |
node['ids'].extend(old_ids) |
| 169 |
super().visit_section(node) |
| 170 |
node['ids'] = old_ids |
| 171 |
|
| 172 |
|
| 173 |
def parse_django_admin_node(env, sig, signode): |
| 174 |
command = sig.split(' ')[0] |
| 175 |
env.ref_context['std:program'] = command |
| 176 |
title = "django-admin %s" % sig |
| 177 |
signode += addnodes.desc_name(title, title) |
| 178 |
return command |
| 179 |
|
| 180 |
|
| 181 |
class DjangoStandaloneHTMLBuilder(StandaloneHTMLBuilder): |
| 182 |
""" |
| 183 |
Subclass to add some extra things we need. |
| 184 |
""" |
| 185 |
|
| 186 |
name = 'djangohtml' |
| 187 |
|
| 188 |
def finish(self): |
| 189 |
super().finish() |
| 190 |
logger.info(bold("writing templatebuiltins.js...")) |
| 191 |
xrefs = self.env.domaindata["std"]["objects"] |
| 192 |
templatebuiltins = { |
| 193 |
"ttags": [ |
| 194 |
n for ((t, n), (k, a)) in xrefs.items() |
| 195 |
if t == "templatetag" and k == "ref/templates/builtins" |
| 196 |
], |
| 197 |
"tfilters": [ |
| 198 |
n for ((t, n), (k, a)) in xrefs.items() |
| 199 |
if t == "templatefilter" and k == "ref/templates/builtins" |
| 200 |
], |
| 201 |
} |
| 202 |
outfilename = os.path.join(self.outdir, "templatebuiltins.js") |
| 203 |
with open(outfilename, 'w') as fp: |
| 204 |
fp.write('var django_template_builtins = ') |
| 205 |
json.dump(templatebuiltins, fp) |
| 206 |
fp.write(';\n') |
| 207 |
|
| 208 |
|
| 209 |
class ConsoleNode(nodes.literal_block): |
| 210 |
""" |
| 211 |
Custom node to override the visit/depart event handlers at registration |
| 212 |
time. Wrap a literal_block object and defer to it. |
| 213 |
""" |
| 214 |
tagname = 'ConsoleNode' |
| 215 |
|
| 216 |
def __init__(self, litblk_obj): |
| 217 |
self.wrapped = litblk_obj |
| 218 |
|
| 219 |
def __getattr__(self, attr): |
| 220 |
if attr == 'wrapped': |
| 221 |
return self.__dict__.wrapped |
| 222 |
return getattr(self.wrapped, attr) |
| 223 |
|
| 224 |
|
| 225 |
def visit_console_dummy(self, node): |
| 226 |
"""Defer to the corresponding parent's handler.""" |
| 227 |
self.visit_literal_block(node) |
| 228 |
|
| 229 |
|
| 230 |
def depart_console_dummy(self, node): |
| 231 |
"""Defer to the corresponding parent's handler.""" |
| 232 |
self.depart_literal_block(node) |
| 233 |
|
| 234 |
|
| 235 |
def visit_console_html(self, node): |
| 236 |
"""Generate HTML for the console directive.""" |
| 237 |
if self.builder.name in ('djangohtml', 'json') and node['win_console_text']: |
| 238 |
# Put a mark on the document object signaling the fact the directive |
| 239 |
# has been used on it. |
| 240 |
self.document._console_directive_used_flag = True |
| 241 |
uid = node['uid'] |
| 242 |
self.body.append('''\ |
| 243 |
<div class="console-block" id="console-block-%(id)s"> |
| 244 |
<input class="c-tab-unix" id="c-tab-%(id)s-unix" type="radio" name="console-%(id)s" checked> |
| 245 |
<label for="c-tab-%(id)s-unix" title="Linux/macOS">/</label> |
| 246 |
<input class="c-tab-win" id="c-tab-%(id)s-win" type="radio" name="console-%(id)s"> |
| 247 |
<label for="c-tab-%(id)s-win" title="Windows"></label> |
| 248 |
<section class="c-content-unix" id="c-content-%(id)s-unix">\n''' % {'id': uid}) |
| 249 |
try: |
| 250 |
self.visit_literal_block(node) |
| 251 |
except nodes.SkipNode: |
| 252 |
pass |
| 253 |
self.body.append('</section>\n') |
| 254 |
|
| 255 |
self.body.append('<section class="c-content-win" id="c-content-%(id)s-win">\n' % {'id': uid}) |
| 256 |
win_text = node['win_console_text'] |
| 257 |
highlight_args = {'force': True} |
| 258 |
linenos = node.get('linenos', False) |
| 259 |
|
| 260 |
def warner(msg): |
| 261 |
self.builder.warn(msg, (self.builder.current_docname, node.line)) |
| 262 |
|
| 263 |
highlighted = self.highlighter.highlight_block( |
| 264 |
win_text, 'doscon', warn=warner, linenos=linenos, **highlight_args |
| 265 |
) |
| 266 |
self.body.append(highlighted) |
| 267 |
self.body.append('</section>\n') |
| 268 |
self.body.append('</div>\n') |
| 269 |
raise nodes.SkipNode |
| 270 |
else: |
| 271 |
self.visit_literal_block(node) |
| 272 |
|
| 273 |
|
| 274 |
class ConsoleDirective(CodeBlock): |
| 275 |
""" |
| 276 |
A reStructuredText directive which renders a two-tab code block in which |
| 277 |
the second tab shows a Windows command line equivalent of the usual |
| 278 |
Unix-oriented examples. |
| 279 |
""" |
| 280 |
required_arguments = 0 |
| 281 |
# The 'doscon' Pygments formatter needs a prompt like this. '>' alone |
| 282 |
# won't do it because then it simply paints the whole command line as a |
| 283 |
# grey comment with no highlighting at all. |
| 284 |
WIN_PROMPT = r'...\> ' |
| 285 |
|
| 286 |
def run(self): |
| 287 |
|
| 288 |
def args_to_win(cmdline): |
| 289 |
changed = False |
| 290 |
out = [] |
| 291 |
for token in cmdline.split(): |
| 292 |
if token[:2] == './': |
| 293 |
token = token[2:] |
| 294 |
changed = True |
| 295 |
elif token[:2] == '~/': |
| 296 |
token = '%HOMEPATH%\\' + token[2:] |
| 297 |
changed = True |
| 298 |
elif token == 'make': |
| 299 |
token = 'make.bat' |
| 300 |
changed = True |
| 301 |
if '://' not in token and 'git' not in cmdline: |
| 302 |
out.append(token.replace('/', '\\')) |
| 303 |
changed = True |
| 304 |
else: |
| 305 |
out.append(token) |
| 306 |
if changed: |
| 307 |
return ' '.join(out) |
| 308 |
return cmdline |
| 309 |
|
| 310 |
def cmdline_to_win(line): |
| 311 |
if line.startswith('# '): |
| 312 |
return 'REM ' + args_to_win(line[2:]) |
| 313 |
if line.startswith('$ # '): |
| 314 |
return 'REM ' + args_to_win(line[4:]) |
| 315 |
if line.startswith('$ ./manage.py'): |
| 316 |
return 'manage.py ' + args_to_win(line[13:]) |
| 317 |
if line.startswith('$ manage.py'): |
| 318 |
return 'manage.py ' + args_to_win(line[11:]) |
| 319 |
if line.startswith('$ ./runtests.py'): |
| 320 |
return 'runtests.py ' + args_to_win(line[15:]) |
| 321 |
if line.startswith('$ ./'): |
| 322 |
return args_to_win(line[4:]) |
| 323 |
if line.startswith('$ python3'): |
| 324 |
return 'py ' + args_to_win(line[9:]) |
| 325 |
if line.startswith('$ python'): |
| 326 |
return 'py ' + args_to_win(line[8:]) |
| 327 |
if line.startswith('$ '): |
| 328 |
return args_to_win(line[2:]) |
| 329 |
return None |
| 330 |
|
| 331 |
def code_block_to_win(content): |
| 332 |
bchanged = False |
| 333 |
lines = [] |
| 334 |
for line in content: |
| 335 |
modline = cmdline_to_win(line) |
| 336 |
if modline is None: |
| 337 |
lines.append(line) |
| 338 |
else: |
| 339 |
lines.append(self.WIN_PROMPT + modline) |
| 340 |
bchanged = True |
| 341 |
if bchanged: |
| 342 |
return ViewList(lines) |
| 343 |
return None |
| 344 |
|
| 345 |
env = self.state.document.settings.env |
| 346 |
self.arguments = ['console'] |
| 347 |
lit_blk_obj = super().run()[0] |
| 348 |
|
| 349 |
# Only do work when the djangohtml HTML Sphinx builder is being used, |
| 350 |
# invoke the default behavior for the rest. |
| 351 |
if env.app.builder.name not in ('djangohtml', 'json'): |
| 352 |
return [lit_blk_obj] |
| 353 |
|
| 354 |
lit_blk_obj['uid'] = str(env.new_serialno('console')) |
| 355 |
# Only add the tabbed UI if there is actually a Windows-specific |
| 356 |
# version of the CLI example. |
| 357 |
win_content = code_block_to_win(self.content) |
| 358 |
if win_content is None: |
| 359 |
lit_blk_obj['win_console_text'] = None |
| 360 |
else: |
| 361 |
self.content = win_content |
| 362 |
lit_blk_obj['win_console_text'] = super().run()[0].rawsource |
| 363 |
|
| 364 |
# Replace the literal_node object returned by Sphinx's CodeBlock with |
| 365 |
# the ConsoleNode wrapper. |
| 366 |
return [ConsoleNode(lit_blk_obj)] |
| 367 |
|
| 368 |
|
| 369 |
def html_page_context_hook(app, pagename, templatename, context, doctree): |
| 370 |
# Put a bool on the context used to render the template. It's used to |
| 371 |
# control inclusion of console-tabs.css and activation of the JavaScript. |
| 372 |
# This way it's include only from HTML files rendered from reST files where |
| 373 |
# the ConsoleDirective is used. |
| 374 |
context['include_console_assets'] = getattr(doctree, '_console_directive_used_flag', False) |
| 375 |
|
| 376 |
|
| 377 |
def default_role_error( |
| 378 |
name, rawtext, text, lineno, inliner, options=None, content=None |
| 379 |
): |
| 380 |
msg = ( |
| 381 |
"Default role used (`single backticks`): %s. Did you mean to use two " |
| 382 |
"backticks for ``code``, or miss an underscore for a `link`_ ?" |
| 383 |
% rawtext |
| 384 |
) |
| 385 |
logger.warning(msg, location=(inliner.document.current_source, lineno)) |
| 386 |
return [nodes.Text(text)], [] |