index.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. var Prism = require('prismjs');
  2. var languages = require('prismjs').languages;
  3. var path = require('path');
  4. var DEFAULT_LANGUAGE = 'markup';
  5. var MAP_LANGUAGES = {
  6. 'py': 'python',
  7. 'js': 'javascript',
  8. 'rb': 'ruby',
  9. 'csharp': 'cs',
  10. 'html': 'markup'
  11. };
  12. function getAssets() {
  13. var book = this;
  14. var cssFiles = this.config.get('pluginsConfig.prism.css', []);
  15. var cssFolder = null;
  16. var cssNames = [];
  17. if(cssFiles.length === 0) {
  18. cssFiles.push('prismjs/themes/prism.css');
  19. }
  20. cssFiles.forEach(function(cssFile) {
  21. var cssPath = require.resolve(cssFile);
  22. cssFolder = path.dirname(cssPath);
  23. cssName = path.basename(cssPath);
  24. cssNames.push(cssName);
  25. });
  26. var assets = {
  27. assets: cssFolder,
  28. css: cssNames
  29. };
  30. return assets;
  31. }
  32. module.exports = {
  33. book: getAssets,
  34. ebook: getAssets,
  35. blocks: {
  36. code: function(block) {
  37. var highlighted = '';
  38. // Normalize language id
  39. var lang = block.kwargs.language || DEFAULT_LANGUAGE;
  40. lang = MAP_LANGUAGES[lang] || lang;
  41. // Try and find the language definition in components folder
  42. if (!languages[lang]) {
  43. try {
  44. require('prismjs/components/prism-' + lang + '.js');
  45. }catch(e) {
  46. console.warn('Failed to load prism syntax: '+ lang);
  47. console.warn(e);
  48. }
  49. }
  50. if (!languages[lang]) lang = DEFAULT_LANGUAGE;
  51. // Check against html, prism "markup" works for this
  52. if (lang === 'html') {
  53. lang = 'markup';
  54. }
  55. try {
  56. // The process can fail (failed to parse)
  57. highlighted = Prism.highlight(block.body, languages[lang]);
  58. } catch(e) {
  59. console.warn('Failed to highlight:');
  60. console.warn(e);
  61. highlighted = block.body;
  62. }
  63. return highlighted;
  64. }
  65. }
  66. };