| 1 |
import os |
| 2 |
import json |
| 3 |
from pkg_resources import resource_filename |
| 4 |
|
| 5 |
from docutils import nodes |
| 6 |
from docutils.utils import new_document |
| 7 |
|
| 8 |
from sphinx.transforms import SphinxTransform |
| 9 |
from sphinx.util.docutils import LoggingReporter |
| 10 |
from sphinx.util.fileutil import copy_asset |
| 11 |
|
| 12 |
from . import __version__ |
| 13 |
|
| 14 |
|
| 15 |
class EmojiSubstitutions(SphinxTransform): |
| 16 |
default_priority = 211 |
| 17 |
|
| 18 |
def __init__(self, document, startnode=None): |
| 19 |
super().__init__(document, startnode) |
| 20 |
self.parser = self.app.registry.create_source_parser(self.app, 'rst') |
| 21 |
|
| 22 |
def apply(self): |
| 23 |
config = self.document.settings.env.config |
| 24 |
settings, source = self.document.settings, self.document['source'] |
| 25 |
codes = resource_filename(__name__, 'codes.json') |
| 26 |
replacements = json.load(open(codes)) |
| 27 |
to_handle = (set(replacements.keys()) - |
| 28 |
set(self.document.substitution_defs)) |
| 29 |
|
| 30 |
for ref in self.document.traverse(nodes.substitution_reference): |
| 31 |
refname = ref['refname'] |
| 32 |
if refname in to_handle: |
| 33 |
text = replacements[refname] |
| 34 |
|
| 35 |
doc = new_document(source, settings) |
| 36 |
doc.reporter = LoggingReporter.from_reporter(doc.reporter) |
| 37 |
self.parser.parse(text, doc) |
| 38 |
|
| 39 |
substitution = doc.next_node() |
| 40 |
|
| 41 |
if isinstance(substitution, nodes.paragraph): |
| 42 |
substitution = substitution.next_node() |
| 43 |
ref.replace_self(substitution) |
| 44 |
|
| 45 |
|
| 46 |
def copy_asset_files(app, exc): |
| 47 |
asset_files = [ |
| 48 |
resource_filename(__name__, 'twemoji.js'), |
| 49 |
resource_filename(__name__, 'twemoji.css'), |
| 50 |
] |
| 51 |
if exc is None: |
| 52 |
for path in asset_files: |
| 53 |
copy_asset(path, os.path.join(app.outdir, '_static')) |
| 54 |
|
| 55 |
|
| 56 |
def setup(app): |
| 57 |
app.connect('build-finished', copy_asset_files) |
| 58 |
style = app.config._raw_config.get('sphinxemoji_style') |
| 59 |
if style == 'twemoji': |
| 60 |
app.add_js_file('https://twemoji.maxcdn.com/v/latest/twemoji.min.js') |
| 61 |
app.add_js_file('twemoji.js') |
| 62 |
app.add_css_file('twemoji.css') |
| 63 |
app.add_transform(EmojiSubstitutions) |
| 64 |
return {'version': __version__, 'parallel_read_safe': True} |