Skip to content

Instantly share code, notes, and snippets.

@namuol
Last active December 16, 2015 18:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save namuol/8f3cd36a8d2f6ac8899d to your computer and use it in GitHub Desktop.
Save namuol/8f3cd36a8d2f6ac8899d to your computer and use it in GitHub Desktop.
Node.js: Line highlights in Markdown using marked + pygmentize
#
# Inspired by http://zpao.com/posts/adding-line-highlights-to-markdown-code-fences/
# by Paul O'Shannessy
#
marked = require 'marked'
pygmentize = require 'pygmentize-bundled'
renderer = new marked.Renderer()
renderer.code = (code, lang) ->
return "<div class='highlight'><code class='#{lang.split('{')[0]}'><pre>#{code}</pre></code></div>"
marked.setOptions
gfm: true
renderer: renderer
highlight: (code, lang, cb) ->
[lang, lines] = lang.split '{'
hl_lines = []
if lines?
for l in lines.split(',')
match = l.match /(\d+)-(\d+)/
if not match
hl_lines.push parseInt l
else
start = parseInt match[1]
end = parseInt match[2]
hl_lines.push [start..end]...
pygmentize {
lang: lang
format: 'html'
options: {
hl_lines: hl_lines.join(' ')
nowrap: true
}
}, code, (err, result) ->
return cb err if err
cb null, result.toString()
return
text =
'''
```js{3,6-8}
var blah,
foo;
// This line will be highlighted!
foo = 40;
blah = foo + 2;
/*
These lines will be highlighted, too!
*/
console.log(blah);
```
'''
marked text, (err, result) ->
throw err if err
console.log result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment