index.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. }
  36. catch(e) {
  37. console.warn('Failed to highlight:');
  38. console.warn(e);
  39. highlighted = block.body;
  40. }
  41. return highlighted;
  42. }
  43. }
  44. };