djangodocs.py 14 KB

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