djangodocs.py 17 KB

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