diff options
author | Samy Pessé <samypesse@gmail.com> | 2016-04-27 16:22:17 +0200 |
---|---|---|
committer | Samy Pessé <samypesse@gmail.com> | 2016-04-27 16:22:17 +0200 |
commit | e50422bce588ec5a0b5581bf3963b0995138de4c (patch) | |
tree | 5128b5759c2bed3d9cac21fa8de5ccc1b3ead7bb /lib/output/modifiers/highlightCode.js | |
parent | 999882e72327e06dd2fd346ca13eccb1c7e8781f (diff) | |
download | gitbook-e50422bce588ec5a0b5581bf3963b0995138de4c.zip gitbook-e50422bce588ec5a0b5581bf3963b0995138de4c.tar.gz gitbook-e50422bce588ec5a0b5581bf3963b0995138de4c.tar.bz2 |
Use code TemplateBlock to highlight code
Diffstat (limited to 'lib/output/modifiers/highlightCode.js')
-rw-r--r-- | lib/output/modifiers/highlightCode.js | 48 |
1 files changed, 30 insertions, 18 deletions
diff --git a/lib/output/modifiers/highlightCode.js b/lib/output/modifiers/highlightCode.js index deabd68..dcd9d24 100644 --- a/lib/output/modifiers/highlightCode.js +++ b/lib/output/modifiers/highlightCode.js @@ -1,7 +1,35 @@ +var is = require('is'); var Promise = require('../../utils/promise'); var editHTMLElement = require('./editHTMLElement'); /** + Return language for a code blocks from a list of class names + + @param {Array<String>} + @return {String} +*/ +function getLanguageForClass(classNames) { + return classNames + .map(function(cl) { + // Markdown + if (cl.search('lang-') === 0) { + return cl.slice('lang-'.length); + } + + // Asciidoc + if (cl.search('language-') === 0) { + return cl.slice('language-'.length); + } + + return null; + }) + .find(function(cl) { + return Boolean(cl); + }); +} + + +/** Highlight all code elements @param {Function(lang, body) -> String} highlight @@ -11,28 +39,12 @@ var editHTMLElement = require('./editHTMLElement'); function highlightCode(highlight, $) { return editHTMLElement($, 'code', function($code) { var classNames = ($code.attr('class') || '').split(' '); - var lang = classNames - .map(function(cl) { - // Markdown - if (cl.search('lang-') === 0) { - return cl.slice('lang-'.length); - } - - // Asciidoc - if (cl.search('language-') === 0) { - return cl.slice('language-'.length); - } - - return null; - }) - .find(function(cl) { - return Boolean(cl); - }); + var lang = getLanguageForClass(classNames); var source = $code.text(); return Promise(highlight(lang, source)) .then(function(r) { - if (r.html) { + if (is.string(r.html)) { $code.html(r.html); } else { $code.text(r.text); |