djangodocs.py 13 KB

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