index.js 4.2 KB

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