Thumbnail

Life and Learning Powered by Obtvse

Simple Syntax Highlighting + LaTeX

Ever wanted to add syntax highlighting and to your own website? Well, with highlight.js and MathJax it only takes 5 minutes to set up!

Syntax Highlighting

There are a lot of syntax highlighting libraries out there. The easiest one to use in my opinion is highlight.js. All you have to do is a few lines of Javascript and CSS! There are also quite a few themes you can pick from. As you can see, I’m partial to solarized.

  <script src="/highlight.min.js"></script>
  <script>
    hljs.tabReplace = '    '; // optional
    hljs.initHighlightingOnLoad();
  </script>  
  <link href="/solarized_light.css" 
        rel="stylesheet" type="text/css">

With this code snippet, highlight.js will scan through the DOM and highlight any region surrounded by <pre><code> … </pre></code>. The language-type is detected automatically.

def foo():
    print "this is some python"

LaTeX

Adding LaTeX support is even easier. All you have to do is add this to your HTML. (Download URL here).

<script type="text/javascript" src="/MathJax.js"></script>

With this, you can use \ ( #LaTex_Here# \ ) for inline math and \ [ \#LaTex_Here# \ ] for display math. Just one caveat: this creates problems if you are also using Markdown, since some LaTeX characters will be interpreted as Markdown characters. The way to get around this is to explicitly use <script> tags of the right type:

<script id="maxwell" type="math/tex; mode=display">
\begin{aligned}
\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\   \nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0 \end{aligned}
</script>

That renders to Maxwell’s equations (right click to copy the LaTeX, definitely my favorite feature):

That’s it! Someone has already done all the heavy lifting for us. With 7 lines of HTML, you’ve enabled syntax highlighting and LaTeX!

Back to Blog
blog comments powered by Disqus