Add support for abbreviations to reST translator (fixes #395).

This commit is contained in:
Dirkjan Ochtman 2012-07-17 13:30:06 +02:00
commit 636fd6cc38
4 changed files with 39 additions and 4 deletions

View file

@ -63,6 +63,18 @@ def render_node_to_html(document, node):
return visitor.astext()
class PelicanHTMLTranslator(HTMLTranslator):
def visit_abbreviation(self, node):
attrs = {}
if node.hasattr('explanation'):
attrs['title'] = node['explanation']
self.body.append(self.starttag(node, 'abbr', '', **attrs))
def depart_abbreviation(self, node):
self.body.append('</abbr>')
class RstReader(Reader):
enabled = bool(docutils)
file_extensions = ['rst']
@ -92,6 +104,7 @@ class RstReader(Reader):
pub = docutils.core.Publisher(
destination_class=docutils.io.StringOutput)
pub.set_components('standalone', 'restructuredtext', 'html')
pub.writer.translator_class = PelicanHTMLTranslator
pub.process_programmatic_settings(None, extra_params, None)
pub.set_source(source_path=filename)
pub.publish()

View file

@ -1,9 +1,10 @@
# -*- coding: utf-8 -*-
from docutils import nodes
from docutils.parsers.rst import directives, Directive
from docutils import nodes, utils
from docutils.parsers.rst import directives, roles, Directive
from pygments.formatters import HtmlFormatter
from pygments import highlight
from pygments.lexers import get_lexer_by_name, TextLexer
import re
INLINESTYLES = False
DEFAULT = HtmlFormatter(noclasses=INLINESTYLES)
@ -94,3 +95,18 @@ class YouTube(Directive):
nodes.raw('', '</div>', format='html')]
directives.register_directive('youtube', YouTube)
_abbr_re = re.compile('\((.*)\)$')
class abbreviation(nodes.Inline, nodes.TextElement): pass
def abbr_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
text = utils.unescape(text)
m = _abbr_re.search(text)
if m is None:
return [abbreviation(text, text)], []
abbr = text[:m.start()].strip()
expl = m.group(1)
return [abbreviation(abbr, abbr, explanation=expl)], []
roles.register_local_role('abbr', abbr_role)

View file

@ -2,3 +2,5 @@ Article title
#############
This is some content. With some stuff to "typogrify".
Now with added support for :abbr:`TLA (three letter acronym)`.

View file

@ -47,7 +47,9 @@ class RstReaderTest(unittest.TestCase):
# unmodified
content, _ = readers.read_file(_filename('article.rst'))
expected = "<p>This is some content. With some stuff to "\
"&quot;typogrify&quot;.</p>\n"
"&quot;typogrify&quot;.</p>\n<p>Now with added "\
'support for <abbr title="three letter acronym">'\
'TLA</abbr>.</p>\n'
self.assertEqual(content, expected)
@ -56,7 +58,9 @@ class RstReaderTest(unittest.TestCase):
content, _ = readers.read_file(_filename('article.rst'),
settings={'TYPOGRIFY': True})
expected = "<p>This is some content. With some stuff to&nbsp;"\
"&#8220;typogrify&#8221;.</p>\n"
"&#8220;typogrify&#8221;.</p>\n<p>Now with added "\
'support for <abbr title="three letter acronym">'\
'TLA</abbr>.</p>\n'
self.assertEqual(content, expected)
except ImportError: