Hawkes Blog
Windows reboot | Linux be root
Hawkes Blog

Change Pelicans syntax highlighting

Short How-To: Use SyntaxHighlighter with Pelican

Pygments is great but if lets try a different one :)

  1. get the latest SyntaxHighlighter Version from SyntaxHighlighter and put the script and styles folder in the static folder of your pelican theme
  2. edit your base/header template
  • add to head part
<<< snipp
<script src="{{ SITEURL }}/theme/syntax/shAutoloader.js" type="text/javascript"></script>
<link href="{{ SITEURL }}/theme/syntax/styles/shCore.css" rel="stylesheet" type="text/css" />
<link href="{{ SITEURL }}/theme/syntax/styles/shThemeRDark.css" rel="stylesheet" type="text/css" />
  • add to the end
  • donĀ“t forget to switch the path according to your setup
<script>
        SyntaxHighlighter.autoloader(
            'shell  {{ SITEURL }}/theme/syntax/shBrushBash.js',
            'python {{ SITEURL }}/theme/syntax/shBrushPython.js',
            'js     {{ SITEURL }}/theme/syntax/shBrushJScript.js',
            'html   {{ SITEURL }}/theme/syntax/shBrushXml.js'
        );
        SyntaxHighlighter.vars.discoveredBrushes = null;
        SyntaxHighlighter.all()
</script>

3. edit rstdirectives.py - add the following below the pygments entry

from cgi import escape

<<< snip

#deactivate pygments
#directives.register_directive('syntax', Pygments)
#directives.register_directive('sourcecode', Pygments)

class SyntaxHighlighter(Directive):
    """
        Source code syntax hightlighting with SyntaxHighlighter.
        http://alexgorbatchev.com/SyntaxHighlighter

    """
    required_arguments = 1
    optional_arguments = 0
    final_argument_whitespace = True
    has_content = True

    def run(self):
        self.assert_has_content()
        # shell is default
        highlight = "shell"

        if self.arguments[0]:
            if self.arguments[0] in ("python", "py", "pyc"):
                highlight = "python"
            elif self.arguments[0] in ("javascript", "js", "jquery"):
                highlight = "js"
            elif self.arguments[0] in ("html", "htm", "web"):
                highlight = "html"

        parsed = '<pre class="brush: {0}">{1}</pre>'.format(highlight, self._get_escaped_content())
        return [nodes.raw('', parsed, format='html')]

    def _get_escaped_content(self):
        return u'\n'.join(map(escape, self.content))

#which keyword should trigger it
directives.register_directive('syntax', SyntaxHighlighter)
directives.register_directive('sourcecode', SyntaxHighlighter)

there are only 4 brushes implemented at the moment, but you can easily add more if needed

an improved version is available here

And the final result: highlight-test

MfG Hawkes

Thx to Source


comments powered by Disqus