djangodocs.py 14 KB

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