This morning I've been working on adding syntax highlighting to the code blocks on this website. I'd like to share my findings.
I chose the markdown it library to parse my markdown files, as it has a highlight option built in.
import Markdown from 'markdown-it';import highlight from './highlight';const md = new;const ;
highlight takes the form of a function.
/*** Adds meaningful markup to code block so we* can later style with CSS* @param string code – Code block* @param string id – The code block's language identified. e.g. js or css* @return string Code block now with meaningful markup*/const
Note that Highlights only works with Node. Since I am doing this server-side, that's not a problem for me.
import Highlights from 'highlights';const highlighter = new;const,
Get your grammar right
The term grammar in these circles means what language the code block is thought to be.
Each Highlights language package has a
highlightSync method above, we pass in a
property that we have derived from the code block's language
highlightSync is called, the available language
packages are iterated over and a match is attempted on the
scopeName's. The first match wins, and that language package
is used to markup the code block.
getScope function exists to map the language
identifier passed into the
highlight function, to the
scopeName of the desired language package.
Fear not. Highlights has a method that lets us define additional grammars. For example, language-babel.
Our markdown code blocks now have meaningful markup. All that's left is for some styling.
In theory, you should be able to add the CSS file of your favorite Atom syntax theme. I like to keep it minimal, and have added a few styles of my own.
Talk to me on twitter @colinmeinke.