diff options
author | Samy Pessé <samypesse@gmail.com> | 2016-04-27 15:42:55 +0200 |
---|---|---|
committer | Samy Pessé <samypesse@gmail.com> | 2016-04-27 15:42:55 +0200 |
commit | 999882e72327e06dd2fd346ca13eccb1c7e8781f (patch) | |
tree | 6a9ff7102871dfb4106d47e35c5d3031f787b90b /lib/output/modifiers/highlightCode.js | |
parent | d68dc82159555833b364a1571fff4b630c6a5bd4 (diff) | |
download | gitbook-999882e72327e06dd2fd346ca13eccb1c7e8781f.zip gitbook-999882e72327e06dd2fd346ca13eccb1c7e8781f.tar.gz gitbook-999882e72327e06dd2fd346ca13eccb1c7e8781f.tar.bz2 |
Add test for highlightCode html modifier
Diffstat (limited to 'lib/output/modifiers/highlightCode.js')
-rw-r--r-- | lib/output/modifiers/highlightCode.js | 44 |
1 files changed, 44 insertions, 0 deletions
diff --git a/lib/output/modifiers/highlightCode.js b/lib/output/modifiers/highlightCode.js new file mode 100644 index 0000000..deabd68 --- /dev/null +++ b/lib/output/modifiers/highlightCode.js @@ -0,0 +1,44 @@ +var Promise = require('../../utils/promise'); +var editHTMLElement = require('./editHTMLElement'); + +/** + Highlight all code elements + + @param {Function(lang, body) -> String} highlight + @param {HTMLDom} $ + @return {Promise} +*/ +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 source = $code.text(); + + return Promise(highlight(lang, source)) + .then(function(r) { + if (r.html) { + $code.html(r.html); + } else { + $code.text(r.text); + } + }); + }); +} + +module.exports = highlightCode; |