Extending Markdown With Pygments to support Syntax Highlighting

Extending Markdown With Pygments to support Syntax Highlighting

Last updated:

In order to have code in Markdown code blocks get nicely decorated you need to use a third-party syntax highlighter because Markdown doesn't do it out of the box.

I'd like to syntax highlight my code somewhere along the lines of github-flavoured markdown.

For my PHP projects, I'll use the following tools:

Once you've installed them in your machine (I recommend composer, of course), rendering a markdown text into HTML is as simple as this:

echo Michelf\MarkdownExtra::defaultTransform($markdown_text);

You can render code blocks in one of two ways:

  • Indent text by 4 or more spaces with a blank line before that block.
  • Wrap your code with ``` (three consecutive grave accents). These are called fenced code blocks.

Now a nice improvement upon regular Markdown is the ability to say what language your code blocks are written in, like this example from github: github-flavoured markdown

This is what I did:

Locate method _doFencedCodeBlocks_callback (around line 2835 in file Markdown.php) and add a bit of code so that it looks like this:

<?php
$pre_attr_str  = $this->code_attr_on_pre ? $attr_str : '';
$code_attr_str = $this->code_attr_on_pre ? '' : $attr_str;

//EDITING STARTS
if($classname !== ''){
    $codeblock = (new \KzykHys\Pygments\Pygments())->highlight(html_entity_decode($codeblock),$classname,'html');
}else{
    $codeblock  = "<pre$pre_attr_str><code$code_attr_str>$codeblock</code></pre>";
}
//EDITING ENDS

return "\n\n".$this->hashBlock($codeblock)."\n\n";
}

This will make your fenced code blocks with languages render beautifully (a là Github) provided you also include the correct CSS stylesheet to color the output - Here is a nice collection of all different styles you can apply to your code blocks. Experiment at will!

References

  • Pygments - this is what's getting all the work done.