Fixed #14005 - Removed a few unneeded workarounds in the Sphinx extension. Thanks for the report and patch, Ramiro Morales.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@13447 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Jannis Leidel 2010-07-25 20:39:40 +00:00
parent fad4a93275
commit cd8758ef4d
3 changed files with 48 additions and 111 deletions

View File

@ -1,9 +1,9 @@
""" """
Sphinx plugins for Django documentation. Sphinx plugins for Django documentation.
""" """
import os
import docutils.nodes from docutils import nodes, transforms
import docutils.transforms
try: try:
import json import json
except ImportError: except ImportError:
@ -14,26 +14,12 @@ except ImportError:
from django.utils import simplejson as json from django.utils import simplejson as json
except ImportError: except ImportError:
json = None json = None
import os
import sphinx from sphinx import addnodes, roles
import sphinx.addnodes from sphinx.builders.html import StandaloneHTMLBuilder
try: from sphinx.writers.html import SmartyPantsHTMLTranslator
from sphinx import builders
except ImportError:
import sphinx.builder as builders
try:
import sphinx.builders.html as builders_html
except ImportError:
builders_html = builders
from sphinx.util.console import bold from sphinx.util.console import bold
import sphinx.directives
import sphinx.environment
try:
import sphinx.writers.html as sphinx_htmlwriter
except ImportError:
import sphinx.htmlwriter as sphinx_htmlwriter
import sphinx.roles
from docutils import nodes
def setup(app): def setup(app):
app.add_crossref_type( app.add_crossref_type(
@ -74,24 +60,20 @@ def setup(app):
app.add_transform(SuppressBlockquotes) app.add_transform(SuppressBlockquotes)
app.add_builder(DjangoStandaloneHTMLBuilder) app.add_builder(DjangoStandaloneHTMLBuilder)
# Monkeypatch PickleHTMLBuilder so that it doesn't die in Sphinx 0.4.2
if sphinx.__version__ == '0.4.2':
monkeypatch_pickle_builder()
def parse_version_directive(name, arguments, options, content, lineno, def parse_version_directive(name, arguments, options, content, lineno,
content_offset, block_text, state, state_machine): content_offset, block_text, state, state_machine):
env = state.document.settings.env env = state.document.settings.env
is_nextversion = env.config.django_next_version == arguments[0] is_nextversion = env.config.django_next_version == arguments[0]
ret = [] ret = []
node = sphinx.addnodes.versionmodified() node = addnodes.versionmodified()
ret.append(node) ret.append(node)
if not is_nextversion: if not is_nextversion:
if len(arguments) == 1: if len(arguments) == 1:
linktext = 'Please, see the release notes <releases-%s>' % (arguments[0]) linktext = 'Please, see the release notes <releases-%s>' % (arguments[0])
try: try:
xrefs = sphinx.roles.XRefRole()('ref', linktext, linktext, lineno, state) # Sphinx >= 1.0 xrefs = roles.XRefRole()('ref', linktext, linktext, lineno, state) # Sphinx >= 1.0
except: except:
xrefs = sphinx.roles.xfileref_role('ref', linktext, linktext, lineno, state) # Sphinx < 1.0 xrefs = roles.xfileref_role('ref', linktext, linktext, lineno, state) # Sphinx < 1.0
node.extend(xrefs[0]) node.extend(xrefs[0])
node['version'] = arguments[0] node['version'] = arguments[0]
else: else:
@ -106,29 +88,29 @@ def parse_version_directive(name, arguments, options, content, lineno,
env.note_versionchange(node['type'], node['version'], node, lineno) env.note_versionchange(node['type'], node['version'], node, lineno)
return ret return ret
class SuppressBlockquotes(docutils.transforms.Transform): class SuppressBlockquotes(transforms.Transform):
""" """
Remove the default blockquotes that encase indented list, tables, etc. Remove the default blockquotes that encase indented list, tables, etc.
""" """
default_priority = 300 default_priority = 300
suppress_blockquote_child_nodes = ( suppress_blockquote_child_nodes = (
docutils.nodes.bullet_list, nodes.bullet_list,
docutils.nodes.enumerated_list, nodes.enumerated_list,
docutils.nodes.definition_list, nodes.definition_list,
docutils.nodes.literal_block, nodes.literal_block,
docutils.nodes.doctest_block, nodes.doctest_block,
docutils.nodes.line_block, nodes.line_block,
docutils.nodes.table nodes.table
) )
def apply(self): def apply(self):
for node in self.document.traverse(docutils.nodes.block_quote): for node in self.document.traverse(nodes.block_quote):
if len(node.children) == 1 and isinstance(node.children[0], self.suppress_blockquote_child_nodes): if len(node.children) == 1 and isinstance(node.children[0], self.suppress_blockquote_child_nodes):
node.replace_self(node.children[0]) node.replace_self(node.children[0])
class DjangoHTMLTranslator(sphinx_htmlwriter.SmartyPantsHTMLTranslator): class DjangoHTMLTranslator(SmartyPantsHTMLTranslator):
""" """
Django-specific reST to HTML tweaks. Django-specific reST to HTML tweaks.
""" """
@ -136,42 +118,41 @@ class DjangoHTMLTranslator(sphinx_htmlwriter.SmartyPantsHTMLTranslator):
# Don't use border=1, which docutils does by default. # Don't use border=1, which docutils does by default.
def visit_table(self, node): def visit_table(self, node):
self.body.append(self.starttag(node, 'table', CLASS='docutils')) self.body.append(self.starttag(node, 'table', CLASS='docutils'))
# <big>? Really? # <big>? Really?
def visit_desc_parameterlist(self, node): def visit_desc_parameterlist(self, node):
self.body.append('(') self.body.append('(')
self.first_param = 1 self.first_param = 1
def depart_desc_parameterlist(self, node): def depart_desc_parameterlist(self, node):
self.body.append(')') self.body.append(')')
pass
# #
# Don't apply smartypants to literal blocks # Don't apply smartypants to literal blocks
# #
def visit_literal_block(self, node): def visit_literal_block(self, node):
self.no_smarty += 1 self.no_smarty += 1
sphinx_htmlwriter.SmartyPantsHTMLTranslator.visit_literal_block(self, node) SmartyPantsHTMLTranslator.visit_literal_block(self, node)
def depart_literal_block(self, node): def depart_literal_block(self, node):
sphinx_htmlwriter.SmartyPantsHTMLTranslator.depart_literal_block(self, node) SmartyPantsHTMLTranslator.depart_literal_block(self, node)
self.no_smarty -= 1 self.no_smarty -= 1
# #
# Turn the "new in version" stuff (versoinadded/versionchanged) into a # Turn the "new in version" stuff (versionadded/versionchanged) into a
# better callout -- the Sphinx default is just a little span, # better callout -- the Sphinx default is just a little span,
# which is a bit less obvious that I'd like. # which is a bit less obvious that I'd like.
# #
# FIXME: these messages are all hardcoded in English. We need to change # FIXME: these messages are all hardcoded in English. We need to change
# that to accomodate other language docs, but I can't work out how to make # that to accomodate other language docs, but I can't work out how to make
# that work and I think it'll require Sphinx 0.5 anyway. # that work.
# #
version_text = { version_text = {
'deprecated': 'Deprecated in Django %s', 'deprecated': 'Deprecated in Django %s',
'versionchanged': 'Changed in Django %s', 'versionchanged': 'Changed in Django %s',
'versionadded': 'New in Django %s', 'versionadded': 'New in Django %s',
} }
def visit_versionmodified(self, node): def visit_versionmodified(self, node):
self.body.append( self.body.append(
self.starttag(node, 'div', CLASS=node['type']) self.starttag(node, 'div', CLASS=node['type'])
@ -181,40 +162,27 @@ class DjangoHTMLTranslator(sphinx_htmlwriter.SmartyPantsHTMLTranslator):
len(node) and ":" or "." len(node) and ":" or "."
) )
self.body.append('<span class="title">%s</span> ' % title) self.body.append('<span class="title">%s</span> ' % title)
def depart_versionmodified(self, node): def depart_versionmodified(self, node):
self.body.append("</div>\n") self.body.append("</div>\n")
# Give each section a unique ID -- nice for custom CSS hooks # Give each section a unique ID -- nice for custom CSS hooks
# This is different on docutils 0.5 vs. 0.4... def visit_section(self, node):
old_ids = node.get('ids', [])
if hasattr(sphinx_htmlwriter.SmartyPantsHTMLTranslator, 'start_tag_with_title') and sphinx.__version__ == '0.4.2': node['ids'] = ['s-' + i for i in old_ids]
def start_tag_with_title(self, node, tagname, **atts): node['ids'].extend(old_ids)
node = { SmartyPantsHTMLTranslator.visit_section(self, node)
'classes': node.get('classes', []), node['ids'] = old_ids
'ids': ['s-%s' % i for i in node.get('ids', [])]
}
return self.starttag(node, tagname, **atts)
else:
def visit_section(self, node):
old_ids = node.get('ids', [])
node['ids'] = ['s-' + i for i in old_ids]
if sphinx.__version__ != '0.4.2':
node['ids'].extend(old_ids)
sphinx_htmlwriter.SmartyPantsHTMLTranslator.visit_section(self, node)
node['ids'] = old_ids
def parse_django_admin_node(env, sig, signode): def parse_django_admin_node(env, sig, signode):
command = sig.split(' ')[0] command = sig.split(' ')[0]
env._django_curr_admin_command = command env._django_curr_admin_command = command
title = "django-admin.py %s" % sig title = "django-admin.py %s" % sig
signode += sphinx.addnodes.desc_name(title, title) signode += addnodes.desc_name(title, title)
return sig return sig
def parse_django_adminopt_node(env, sig, signode): def parse_django_adminopt_node(env, sig, signode):
"""A copy of sphinx.directives.CmdoptionDesc.parse_signature()""" """A copy of sphinx.directives.CmdoptionDesc.parse_signature()"""
from sphinx import addnodes
try: try:
from sphinx.domains.std import option_desc_re # Sphinx >= 1.0 from sphinx.domains.std import option_desc_re # Sphinx >= 1.0
except: except:
@ -234,44 +202,8 @@ def parse_django_adminopt_node(env, sig, signode):
raise ValueError raise ValueError
return firstname return firstname
def monkeypatch_pickle_builder():
import shutil
from os import path
try:
import cPickle as pickle
except ImportError:
import pickle
def handle_finish(self):
# dump the global context
outfilename = path.join(self.outdir, 'globalcontext.pickle')
f = open(outfilename, 'wb')
try:
pickle.dump(self.globalcontext, f, 2)
finally:
f.close()
self.info(bold('dumping search index...')) class DjangoStandaloneHTMLBuilder(StandaloneHTMLBuilder):
self.indexer.prune(self.env.all_docs)
f = open(path.join(self.outdir, 'searchindex.pickle'), 'wb')
try:
self.indexer.dump(f, 'pickle')
finally:
f.close()
# copy the environment file from the doctree dir to the output dir
# as needed by the web app
shutil.copyfile(path.join(self.doctreedir, builders.ENV_PICKLE_FILENAME),
path.join(self.outdir, builders.ENV_PICKLE_FILENAME))
# touch 'last build' file, used by the web application to determine
# when to reload its environment and clear the cache
open(path.join(self.outdir, builders.LAST_BUILD_FILENAME), 'w').close()
builders.PickleHTMLBuilder.handle_finish = handle_finish
class DjangoStandaloneHTMLBuilder(builders_html.StandaloneHTMLBuilder):
""" """
Subclass to add some extra things we need. Subclass to add some extra things we need.
""" """

View File

@ -29,7 +29,7 @@ sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "_ext"))
extensions = ["djangodocs"] extensions = ["djangodocs"]
# Add any paths that contain templates here, relative to this directory. # Add any paths that contain templates here, relative to this directory.
templates_path = ["_templates"] # templates_path = []
# The suffix of source filenames. # The suffix of source filenames.
source_suffix = '.txt' source_suffix = '.txt'

View File

@ -15,6 +15,11 @@ __ http://docutils.sourceforge.net/
To actually build the documentation locally, you'll currently need to install To actually build the documentation locally, you'll currently need to install
Sphinx -- ``easy_install Sphinx`` should do the trick. Sphinx -- ``easy_install Sphinx`` should do the trick.
.. note::
Generation of the Django documentation will work with Sphinx version 0.6
or newer, but we recommend going straigh to Sphinx 1.0 or newer.
Then, building the html is easy; just ``make html`` from the ``docs`` directory. Then, building the html is easy; just ``make html`` from the ``docs`` directory.
To get started contributing, you'll want to read the `ReStructuredText To get started contributing, you'll want to read the `ReStructuredText