Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refs #20910 -- Replaced snippet directive with code-block. #10356

Merged
merged 1 commit into from Sep 10, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
141 changes: 1 addition & 140 deletions docs/_ext/djangodocs.py
Expand Up @@ -6,14 +6,13 @@
import re

from docutils import nodes
from docutils.parsers.rst import Directive, directives
from docutils.parsers.rst import Directive
from docutils.statemachine import ViewList
from sphinx import addnodes
from sphinx.builders.html import StandaloneHTMLBuilder
from sphinx.directives import CodeBlock
from sphinx.domains.std import Cmdoption
from sphinx.util.console import bold
from sphinx.util.nodes import set_source_info
from sphinx.writers.html import HTMLTranslator

# RE for option descriptions without a '--' prefix
Expand Down Expand Up @@ -53,17 +52,6 @@ def setup(app):
app.add_directive('versionadded', VersionDirective)
app.add_directive('versionchanged', VersionDirective)
app.add_builder(DjangoStandaloneHTMLBuilder)

# register the snippet directive
app.add_directive('snippet', SnippetWithFilename)
# register a node for snippet directive so that the xml parser
# knows how to handle the enter/exit parsing event
app.add_node(snippet_with_filename,
html=(visit_snippet, depart_snippet_literal),
latex=(visit_snippet_latex, depart_snippet_latex),
man=(visit_snippet_literal, depart_snippet_literal),
text=(visit_snippet_literal, depart_snippet_literal),
texinfo=(visit_snippet_literal, depart_snippet_literal))
app.set_translator('djangohtml', DjangoHTMLTranslator)
app.set_translator('json', DjangoHTMLTranslator)
app.add_node(
Expand All @@ -79,133 +67,6 @@ def setup(app):
return {'parallel_read_safe': True}


class snippet_with_filename(nodes.literal_block):
"""
Subclass the literal_block to override the visit/depart event handlers
"""
pass


def visit_snippet_literal(self, node):
"""
default literal block handler
"""
self.visit_literal_block(node)


def depart_snippet_literal(self, node):
"""
default literal block handler
"""
self.depart_literal_block(node)


def visit_snippet(self, node):
"""
HTML document generator visit handler
"""
lang = self.highlightlang
linenos = node.rawsource.count('\n') >= self.highlightlinenothreshold - 1
fname = node['filename']
highlight_args = node.get('highlight_args', {})
if 'language' in node:
# code-block directives
lang = node['language']
highlight_args['force'] = True
if 'linenos' in node:
linenos = node['linenos']

def warner(msg):
self.builder.warn(msg, (self.builder.current_docname, node.line))

highlighted = self.highlighter.highlight_block(node.rawsource, lang,
warn=warner,
linenos=linenos,
**highlight_args)
starttag = self.starttag(node, 'div', suffix='',
CLASS='highlight-%s snippet' % lang)
self.body.append(starttag)
self.body.append('<div class="snippet-filename">%s</div>\n''' % (fname,))
self.body.append(highlighted)
self.body.append('</div>\n')
raise nodes.SkipNode


def visit_snippet_latex(self, node):
"""
Latex document generator visit handler
"""
code = node.rawsource.rstrip('\n')

lang = self.hlsettingstack[-1][0]
linenos = code.count('\n') >= self.hlsettingstack[-1][1] - 1
fname = node['filename']
highlight_args = node.get('highlight_args', {})
if 'language' in node:
# code-block directives
lang = node['language']
highlight_args['force'] = True
if 'linenos' in node:
linenos = node['linenos']

def warner(msg):
self.builder.warn(msg, (self.curfilestack[-1], node.line))

hlcode = self.highlighter.highlight_block(code, lang, warn=warner,
linenos=linenos,
**highlight_args)

self.body.append(
'\n{\\colorbox[rgb]{0.9,0.9,0.9}'
'{\\makebox[\\textwidth][l]'
'{\\small\\texttt{%s}}}}\n' % (
# Some filenames have '_', which is special in latex.
fname.replace('_', r'\_'),
)
)

if self.table:
hlcode = hlcode.replace('\\begin{Verbatim}',
'\\begin{OriginalVerbatim}')
self.table.has_problematic = True
self.table.has_verbatim = True

hlcode = hlcode.rstrip()[:-14] # strip \end{Verbatim}
hlcode = hlcode.rstrip() + '\n'
self.body.append('\n' + hlcode + '\\end{%sVerbatim}\n' %
(self.table and 'Original' or ''))

# Prevent rawsource from appearing in output a second time.
raise nodes.SkipNode


def depart_snippet_latex(self, node):
"""
Latex document generator depart handler.
"""
pass


class SnippetWithFilename(Directive):
"""
The 'snippet' directive that allows to add the filename (optional)
of a code snippet in the document. This is modeled after CodeBlock.
"""
has_content = True
optional_arguments = 1
option_spec = {'filename': directives.unchanged_required}

def run(self):
code = '\n'.join(self.content)

literal = snippet_with_filename(code, code)
if self.arguments:
literal['language'] = self.arguments[0]
literal['filename'] = self.options['filename']
set_source_info(self, literal)
return [literal]


class VersionDirective(Directive):
has_content = True
required_arguments = 1
Expand Down
5 changes: 2 additions & 3 deletions docs/_theme/djangodocs-epub/static/epub.css
Expand Up @@ -29,15 +29,14 @@ pre {
}

/* Header for some code blocks. */
.snippet-filename {
.code-block-caption {
background-color: #393939;
color: white;
margin: 0;
padding: 0.5em;
font: bold 90% monospace;
}
.snippet-filename + .highlight > pre,
.snippet-filename + pre {
.literal-block-wrapper pre {
margin-top: 0;
}

Expand Down
5 changes: 2 additions & 3 deletions docs/_theme/djangodocs/static/djangodocs.css
Expand Up @@ -101,9 +101,8 @@ pre { font-size:small; background:#E0FFB8; border:1px solid #94da3a; border-widt
dt .literal, table .literal { background:none; }
#bd a.reference { text-decoration: none; }
#bd a.reference tt.literal { border-bottom: 1px #234f32 dotted; }
div.snippet-filename { color: white; background-color: #234F32; margin: 0; padding: 2px 5px; width: 100%; font-family: monospace; font-size: small; line-height: 1.3em; }
div.snippet-filename + div.highlight > pre { margin-top: 0; }
div.snippet-filename + pre { margin-top: 0; }
div.code-block-caption { color: white; background-color: #234F32; margin: 0; padding: 2px 5px; width: 100%; font-family: monospace; font-size: small; line-height: 1.3em; }
div.literal-block-wrapper pre { margin-top: 0; }

/* Restore colors of pygments hyperlinked code */
#bd .highlight .k a:link, #bd .highlight .k a:visited { color: #000000; text-decoration: none; border-bottom: 1px dotted #000000; }
Expand Down
2 changes: 1 addition & 1 deletion docs/howto/initial-data.txt
Expand Up @@ -58,7 +58,7 @@ look like in JSON:

And here's that same fixture as YAML:

.. code-block:: none
.. code-block:: yaml

- model: myapp.person
pk: 1
Expand Down
20 changes: 10 additions & 10 deletions docs/howto/writing-migrations.txt
Expand Up @@ -39,8 +39,8 @@ attribute::
You can also provide hints that will be passed to the :meth:`allow_migrate()`
method of database routers as ``**hints``:

.. snippet::
:filename: myapp/dbrouters.py
.. code-block:: python
:caption: myapp/dbrouters.py

class MyRouter:

Expand Down Expand Up @@ -97,8 +97,8 @@ the respective field according to your needs.
of the three new files) to the last migration, change ``AddField`` to
``AlterField``, and add imports of ``uuid`` and ``models``. For example:

.. snippet::
:filename: 0006_remove_uuid_null.py
.. code-block:: python
:caption: 0006_remove_uuid_null.py

# Generated by Django A.B on YYYY-MM-DD HH:MM
from django.db import migrations, models
Expand All @@ -121,8 +121,8 @@ the respective field according to your needs.
* Edit the first migration file. The generated migration class should look
similar to this:

.. snippet::
:filename: 0004_add_uuid_field.py
.. code-block:: python
:caption: 0004_add_uuid_field.py

class Migration(migrations.Migration):

Expand All @@ -148,8 +148,8 @@ the respective field according to your needs.
unique value (UUID in the example) for each existing row. Also add an import
of ``uuid``. For example:

.. snippet::
:filename: 0005_populate_uuid_values.py
.. code-block:: python
:caption: 0005_populate_uuid_values.py

# Generated by Django A.B on YYYY-MM-DD HH:MM
from django.db import migrations
Expand Down Expand Up @@ -279,8 +279,8 @@ project anywhere without first installing and then uninstalling the old app.

Here's a sample migration:

.. snippet::
:filename: myapp/migrations/0124_move_old_app_to_new_app.py
.. code-block:: python
:caption: myapp/migrations/0124_move_old_app_to_new_app.py

from django.apps import apps as global_apps
from django.db import migrations
Expand Down
4 changes: 2 additions & 2 deletions docs/internals/contributing/writing-code/coding-style.txt
Expand Up @@ -123,8 +123,8 @@ Imports

For example (comments are for explanatory purposes only):

.. snippet::
:filename: django/contrib/admin/example.py
.. code-block:: python
:caption: django/contrib/admin/example.py

# future
from __future__ import unicode_literals
Expand Down
4 changes: 2 additions & 2 deletions docs/internals/contributing/writing-code/unit-tests.txt
Expand Up @@ -446,8 +446,8 @@ Since this pattern involves a lot of boilerplate, Django provides the
:func:`~django.test.utils.isolate_apps` instances are correctly
installed, you should pass the set of targeted ``app_label`` as arguments:

.. snippet::
:filename: tests/app_label/tests.py
.. code-block:: python
:caption: tests/app_label/tests.py

from django.db import models
from django.test import SimpleTestCase
Expand Down
4 changes: 2 additions & 2 deletions docs/internals/howto-release-django.txt
Expand Up @@ -62,8 +62,8 @@ You'll need a few things before getting started:

* Access to Django's record on PyPI. Create a file with your credentials:

.. snippet::
:filename: ~/.pypirc
.. code-block:: ini
:caption: ~/.pypirc

[pypi]
username:YourUsername
Expand Down
28 changes: 14 additions & 14 deletions docs/intro/overview.txt
Expand Up @@ -25,8 +25,8 @@ The :doc:`data-model syntax </topics/db/models>` offers many rich ways of
representing your models -- so far, it's been solving many years' worth of
database-schema problems. Here's a quick example:

.. snippet::
:filename: mysite/news/models.py
.. code-block:: python
:caption: mysite/news/models.py

from django.db import models

Expand Down Expand Up @@ -145,8 +145,8 @@ production ready :doc:`administrative interface </ref/contrib/admin/index>` --
a website that lets authenticated users add, change and delete objects. It's
as easy as registering your model in the admin site:

.. snippet::
:filename: mysite/news/models.py
.. code-block:: python
:caption: mysite/news/models.py

from django.db import models

Expand All @@ -156,8 +156,8 @@ as easy as registering your model in the admin site:
content = models.TextField()
reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)

.. snippet::
:filename: mysite/news/admin.py
.. code-block:: python
:caption: mysite/news/admin.py

from django.contrib import admin

Expand Down Expand Up @@ -188,8 +188,8 @@ to decouple URLs from Python code.
Here's what a URLconf might look like for the ``Reporter``/``Article``
example above:

.. snippet::
:filename: mysite/news/urls.py
.. code-block:: python
:caption: mysite/news/urls.py

from django.urls import path

Expand Down Expand Up @@ -228,8 +228,8 @@ Generally, a view retrieves data according to the parameters, loads a template
and renders the template with the retrieved data. Here's an example view for
``year_archive`` from above:

.. snippet::
:filename: mysite/news/views.py
.. code-block:: python
:caption: mysite/news/views.py

from django.shortcuts import render

Expand Down Expand Up @@ -257,8 +257,8 @@ in the first directory, it checks the second, and so on.
Let's say the ``news/year_archive.html`` template was found. Here's what that
might look like:

.. snippet:: html+django
:filename: mysite/news/templates/news/year_archive.html
.. code-block:: html+django
:caption: mysite/news/templates/news/year_archive.html

{% extends "base.html" %}

Expand Down Expand Up @@ -298,8 +298,8 @@ in templates: each template has to define only what's unique to that template.
Here's what the "base.html" template, including the use of :doc:`static files
</howto/static-files/index>`, might look like:

.. snippet:: html+django
:filename: mysite/templates/base.html
.. code-block:: html+django
:caption: mysite/templates/base.html

{% load static %}
<html>
Expand Down