index.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. var Prism = require('prismjs');
  2. var languages = require('prism-languages');
  3. var path = require('path');
  4. var prismCSS = require.resolve('prismjs/themes/prism.css');
  5. var DEFAULT_LANGUAGE = 'markup';
  6. var MAP_LANGUAGES = {
  7. 'py': 'python',
  8. 'js': 'javascript',
  9. 'json': 'javascript',
  10. 'rb': 'ruby',
  11. 'csharp': 'cs',
  12. 'html': 'markup'
  13. };
  14. var assets = {
  15. assets: path.dirname(prismCSS),
  16. css: [path.basename(prismCSS)]
  17. };
  18. module.exports = {
  19. book: assets,
  20. ebook: assets,
  21. blocks: {
  22. code: function(block) {
  23. var highlighted = '';
  24. // Normalize language id
  25. var lang = block.kwargs.language || DEFAULT_LANGUAGE;
  26. lang = MAP_LANGUAGES[lang] || lang;
  27. if (!languages[lang]) lang = DEFAULT_LANGUAGE;
  28. // Check against html, prism "markup" works for this
  29. if (lang === 'html') {
  30. lang = 'markup';
  31. }
  32. try {
  33. // The process can fail (failed to parse)
  34. highlighted = Prism.highlight(block.body, languages[lang]);
  35. } catch(e) {
  36. console.warn('Failed to highlight:');
  37. console.warn(e);
  38. highlighted = block.body;
  39. }
  40. return highlighted;
  41. }
  42. }
  43. };