From 1e88e10c780047864b437ef4def7b562be764077 Mon Sep 17 00:00:00 2001 From: gryf Date: Wed, 6 Jul 2022 16:51:13 +0200 Subject: [PATCH] Added ability for syntax highlight in code blocks. Docutils can leverage pygments python package to create syntax highlight inside code blocks. Implementation consists two custom classes for getting HTML code tag contain appropriate class keyword and value. --- Dockerfile | 2 +- rst2htmlbody.py | 25 +++++++++++++++++++++++-- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/Dockerfile b/Dockerfile index 291d6e8..e4bca49 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ FROM gitea/gitea:latest COPY ./rst2htmlbody.py /bin/rst2htmlbody -RUN apk --no-cache add py3-docutils && \ +RUN apk --no-cache add py3-docutils py3-pygments && \ chmod 755 /bin/rst2htmlbody diff --git a/rst2htmlbody.py b/rst2htmlbody.py index 426fa41..fe81ebe 100755 --- a/rst2htmlbody.py +++ b/rst2htmlbody.py @@ -5,6 +5,20 @@ from docutils import core from docutils.writers import html5_polyglot +# add class "chroma" to the code block, to get the syntax highlighting +class CustomHTMLTranslator(html5_polyglot.HTMLTranslator): + def visit_literal_block(self, node): + self.body.append(self.starttag(node, 'pre', '', CLASS='literal-block')) + if 'code' in node.get('classes', []): + self.body.append('') + + +class CustomWriter(html5_polyglot.Writer): + def __init__(self): + super().__init__() + self.translator_class = CustomHTMLTranslator + + def main(): if not sys.stdin.isatty(): text = sys.stdin.readlines() @@ -15,8 +29,15 @@ def main(): with open(sys.argv[1]) as fobj: text = fobj.read() - parts = core.publish_parts(writer=html5_polyglot.Writer(), - source=''.join(text)) + try: + import pygments + settings = {'syntax_highlight': 'short'} + except ImportError: + settings = {'syntax_highlight': 'none'} + + parts = core.publish_parts(writer=CustomWriter(), + source=''.join(text), + settings_overrides=settings) print(parts.get('body', ''))