index.js 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. var Prism = require('prismjs');
  2. var languages = require('prismjs').languages;
  3. var path = require('path');
  4. var fs = require('fs');
  5. var cheerio = require('cheerio');
  6. var mkdirp = require('mkdirp');
  7. var DEFAULT_LANGUAGE = 'markup';
  8. var MAP_LANGUAGES = {
  9. 'py': 'python',
  10. 'js': 'javascript',
  11. 'rb': 'ruby',
  12. 'cs': 'csharp',
  13. 'html': 'markup'
  14. };
  15. // Base languages syntaxes, extended by other syntaxes, need to be
  16. // required before all.
  17. var PRELUDE = ['clike', 'javascript', 'markup', 'c', 'ruby', 'css'];
  18. PRELUDE.map(requireSyntax);
  19. /**
  20. * Load the syntax definition for a language id
  21. */
  22. function requireSyntax(lang) {
  23. require('prismjs/components/prism-' + lang + '.js');
  24. }
  25. function getAssets() {
  26. var cssFiles = this.config.get('pluginsConfig.prism.css', []);
  27. var cssFolder = null;
  28. var cssNames = [];
  29. var cssName = null;
  30. if (cssFiles.length === 0) {
  31. cssFiles.push('prismjs/themes/prism.css');
  32. }
  33. cssFiles.forEach(function(cssFile) {
  34. var cssPath = require.resolve(cssFile);
  35. cssFolder = path.dirname(cssPath);
  36. cssName = path.basename(cssPath);
  37. cssNames.push(cssName);
  38. });
  39. return {
  40. assets: cssFolder,
  41. css: cssNames
  42. };
  43. }
  44. module.exports = {
  45. book: getAssets,
  46. ebook: function() {
  47. // Adding prism-ebook.css to the CSS collection forces Gitbook
  48. // reference to it in the html markup that is converted into a PDF.
  49. var assets = getAssets.call(this);
  50. assets.css.push('prism-ebook.css');
  51. return assets;
  52. },
  53. blocks: {
  54. code: function(block) {
  55. var highlighted = '';
  56. // Normalize language id
  57. var lang = block.kwargs.language || DEFAULT_LANGUAGE;
  58. lang = MAP_LANGUAGES[lang] || lang;
  59. // Try and find the language definition in components folder
  60. if (!languages[lang]) {
  61. try {
  62. requireSyntax(lang);
  63. } catch (e) {
  64. console.warn('Failed to load prism syntax: ' + lang);
  65. console.warn(e);
  66. }
  67. }
  68. if (!languages[lang]) lang = DEFAULT_LANGUAGE;
  69. // Check against html, prism "markup" works for this
  70. if (lang === 'html') {
  71. lang = 'markup';
  72. }
  73. try {
  74. // The process can fail (failed to parse)
  75. highlighted = Prism.highlight(block.body, languages[lang]);
  76. } catch (e) {
  77. console.warn('Failed to highlight:');
  78. console.warn(e);
  79. highlighted = block.body;
  80. }
  81. return highlighted;
  82. }
  83. },
  84. hooks: {
  85. // Manually copy prism-ebook.css into the temporary directory that Gitbook uses for inlining
  86. // styles from this plugin. The getAssets() (above) function can't be leveraged because
  87. // ebook-prism.css lives outside the folder referenced by this plugin's config.
  88. //
  89. // @Inspiration https://github.com/GitbookIO/plugin-styles-less/blob/master/index.js#L8
  90. init: function() {
  91. var book = this;
  92. if (book.output.name !== 'ebook') {
  93. // Logic below does not apply to non-ebook formats
  94. return;
  95. }
  96. var outputDirectory = path.join(book.output.root(), '/gitbook/gitbook-plugin-prism');
  97. var outputFile = path.resolve(outputDirectory, 'prism-ebook.css');
  98. var inputFile = path.resolve(__dirname, './prism-ebook.css');
  99. mkdirp.sync(outputDirectory);
  100. try {
  101. fs.writeFileSync(outputFile, fs.readFileSync(inputFile));
  102. } catch (e) {
  103. console.warn('Failed to write prism-ebook.css. See https://git.io/v1LHY for side effects.');
  104. console.warn(e);
  105. }
  106. },
  107. page: function(page) {
  108. var highlighted = false;
  109. var $ = cheerio.load(page.content);
  110. // Prism css styles target the <code> and <pre> blocks using
  111. // a substring CSS selector:
  112. //
  113. // code[class*="language-"], pre[class*="language-"]
  114. //
  115. // Adding "language-" to <pre> element should be sufficient to trigger
  116. // correct color theme.
  117. $('pre').each(function() {
  118. highlighted = true;
  119. const $this = $(this);
  120. $this.addClass('language-');
  121. });
  122. if (highlighted) {
  123. page.content = $.html();
  124. }
  125. return page;
  126. }
  127. }
  128. };