djangodocs.py 13 KB

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