Adding Syntax Highlighting (Code Formatting) to Ghost

Adding Syntax Highlighting (Code Formatting) to Ghost

Update: I have switched to using Prism for my syntax highlighting. I wrote a blog post about how to switch.

I have found a way to format my source code with Ghost. By default, you use four spaces to indicate to Ghost that you are writing code.

To get highlighting to work, I had to use Google's Code Prettify. Unfortunately, it requires that you use a <pre/> tag to contain your code. I say unfortunately because I was hoping to keep a "pure" markdown blog. I guess it's worth it for me to have code formatting. Since code prettify uses JavaScript, this will not work in most RSS readers, so having the <pre/> tag is the way to go.

To use it in Ghost, simply access your settings and click on <> Code Injection from the menu on the left. Then, in the footer, paste the following code:

<script src="//cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js?skin=sons-of-obsidian" type="text/javascript">

Once you've added that script to your footer, you simply need to use the following code to insert source code:

<pre class="prettyprint linenums"><code>function someCode(){
    // this is code
}
</pre></code>

A note about adding <script/> tags using this process: you will have to HTML encode the first < on the line, or Ghost will think you are trying to embed a script.

So, in the example above, this is what the first line looks like:

<pre class="prettyprint linenums lang-htm"><code>&lt;script src=...</script></code></pre>

It's a little kludgy, but it works. I'm guessing this is inherent in the behavior of the web browser, as this is the same type of issue I was running into using the browser-based WYSIWYG editor on WordPress.

Once again, I had to HTML Encode the < on the <pre/> tags so the system wouldn't get confused.

Update: I just learned that it is necessary to completely encode any HTML you use when putting it withinin a <pre/> tag. I have also learned that it is necessary to put the code in a <code/> tag within the <pre/> tag so that the Ghost engine doesn't incorrectly interpret == (that's reserved markdown for highlighting).

Here is what the above code looks like when "prettyfied":

function someCode(){
    // this is code
}

Also, when using the ` character to show <pre/> tag, you will need to make sure that you use an empty tag by displaying it as I have (with the / character at the end). This will ensure that it does not get confused and actually render a <pre/> tag. I have had mixed results using the ` character for inline code when showing HTML, so your results may vary.

And, to display the ` character in your posts, you will need to use

&#96;

post image credit: Stanly Ng