How to: add code highlighting to markup preview

That’s what you can get in HTML:

The following builds on input from @sylumer, @agiletortoise and @Andreas_Haberle.
To highlight code blocks in the markdown preview, one needs

  • the files prism.js and prism.css available here. Before you download, you have to decide which languages you want to highlight. It doesn’t matter if you use the minimized or the full version of the files, but of course the minimized versions are smaller – which might come in handy (see below).
  • a preview template. Any of the existing ones is fine, just export it into Drafts’ Template directory in iCloud from one of the predefined preview actions. Let’s call it “highlight”.
  • (optionally): A webserver to serve the Prism files or a Gist (as described here). See below for an alternative.

Assuming that the files are available at http://example.com/Prism, add these lines to the <head> section of your template, just before </head>

<link href="https://example.com/Prism/prism.css" rel="stylesheet"/>
<script src="https://example.com/Prism/prism.js"></script>

Now create a new action “My Highlight” (or whatever you want to call it) with “HTML preview” as its first step. Use the “Import” button to replace the predefined template with the new one (“highlight”).

In order to get highlighted code blocks, you need to tell Prism about the language. That’s done like
this:

```language-xxx

at the beginning of the block. xxx is “javascript” or “js” for JavaScript, and you’ll find all supported names on the Prism website. They support pretty much any language in use today.

If you can not serve the prism files from a website (either your own or a Gist), you can still highlight code blocks. In this case, you have to include prism.js and prism.css into your template like so:

<style>
... complete content of prism.css
</style>
<script>
... complete content of prism.js 
</script>

That bloats the template somewhat, but should work fine otherwise. In that case, the minimized versions of the files come in handy.

1 Like