Syntax highlighted code examples in Datasette#
I wanted to add syntax highlighting to the new tutorial Data analysis with SQLite and Python.
That page is using the new {% markdown %}
tag from datasette-render-markdown.
I figured out a recipe for adding GitHub-style syntax highlighting to Markdown rendered using that tag.
Dependencies#
1datasette install datasette-render-markdown2datasette install Pygments
Pygments is an optional dependency for the Python markdown
library which enables syntax highlighting via an extension.
The template markup#
Here’s the recipe that worked:
1{% markdown2 extensions="fenced_code codehilite"3 extra_tags="span div"4 extra_attrs="span:class div:class" %}5## Here comes some code6Python code here:7```python8def this_will_be(highlighted):9 "This works10 pass11```12Other languages work too:13```sql14select 1 + 1;15```16{% endmarkdown %}
The magic is all in that opening {% markdown %}
tag.
We’re loading two markdown extensions:
- fenced_code adds support for those triple-backtick code blocks, and enables tagging them with the language name as well.
- codehilite adds syntax highlighting. This will only work if Pygments is installed - it will fail silently otherwise.
datasette-render-markdown
defaults to stripping all but the safest HTML tags and attributes using Bleach.
In this case we want to keep span
and div
tags, since those are used by the syntax highlighter. We also want both of those tags to be allowed to have the class
element on them.
The resulting HTML looks something like this (truncated):
1<div class="codehilite">2 <pre><span></span><code><span class="k">def</span> <span class="nf">parse_pep</span><span class="p">(</span>
Adding the CSS#
Pygments has a neat collection of default styles. I decided I liked “sas”.
I couldn’t see an obvious way to output the CSS, so I used ChatGPT to help figure out this Python one-liner to print out the CSS:
1python -c 'from pygments.formatters import HtmlFormatter2from pygments.styles import get_style_by_name3formatter = HtmlFormatter(style="sas")4print(formatter.get_style_defs(".codehilite"))5'
I later found out that wasn’t necessary - you can run this instead:
1pygmentize -f html -S sas -a .codehilite
Both of those will output the CSS you need to add to your stylesheet to style the syntax highlighted text.