markdown.js 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. /**
  2. * The reveal.js markdown plugin. Handles parsing of
  3. * markdown inside of presentations as well as loading
  4. * of external markdown documents.
  5. */
  6. (function(){
  7. if( typeof marked === 'undefined' ) {
  8. throw 'The reveal.js Markdown plugin requires marked to be loaded';
  9. }
  10. if( typeof hljs !== 'undefined' ) {
  11. marked.setOptions({
  12. highlight: function( lang, code ) {
  13. return hljs.highlightAuto( lang, code ).value;
  14. }
  15. });
  16. }
  17. /**
  18. * Retrieves the markdown contents of a slide section
  19. * element. Normalizes leading tabs/whitespace.
  20. */
  21. function getMarkdownFromSlide( section ) {
  22. var template = section.querySelector( 'script' );
  23. // strip leading whitespace so it isn't evaluated as code
  24. var text = ( template || section ).textContent;
  25. var leadingWs = text.match( /^\n?(\s*)/ )[1].length,
  26. leadingTabs = text.match( /^\n?(\t*)/ )[1].length;
  27. if( leadingTabs > 0 ) {
  28. text = text.replace( new RegExp('\\n?\\t{' + leadingTabs + '}','g'), '\n' );
  29. }
  30. else if( leadingWs > 1 ) {
  31. text = text.replace( new RegExp('\\n? {' + leadingWs + '}','g'), '\n' );
  32. }
  33. return text;
  34. }
  35. /**
  36. * Given a markdown slide section element, this will
  37. * return all arguments that aren't related to markdown
  38. * parsing. Used to forward any other user-defined arguments
  39. * to the output markdown slide.
  40. */
  41. function getForwardedAttributes( section ) {
  42. var attributes = section.attributes;
  43. var result = [];
  44. for( var i = 0, len = attributes.length; i < len; i++ ) {
  45. var name = attributes[i].name,
  46. value = attributes[i].value;
  47. // disregard attributes that are used for markdown loading/parsing
  48. if( /data\-(markdown|separator|vertical|notes)/gi.test( name ) ) continue;
  49. if( value ) {
  50. result.push( name + '=' + value );
  51. }
  52. else {
  53. result.push( name );
  54. }
  55. }
  56. return result.join( ' ' );
  57. }
  58. /**
  59. * Helper function for constructing a markdown slide.
  60. */
  61. function createMarkdownSlide( content, options ) {
  62. var notesMatch = content.split( new RegExp( options.notesSeparator, 'mgi' ) );
  63. if( notesMatch.length === 2 ) {
  64. content = notesMatch[0] + '<aside class="notes" data-markdown>' + notesMatch[1].trim() + '</aside>';
  65. }
  66. return '<script type="text/template">' + content + '</script>';
  67. }
  68. /**
  69. * Parses a data string into multiple slides based
  70. * on the passed in separator arguments.
  71. */
  72. function slidifyMarkdown( markdown, options ) {
  73. options = options || {};
  74. options.separator = options.separator || '^\n---\n$';
  75. options.notesSeparator = options.notesSeparator || 'note:';
  76. options.attributes = options.attributes || '';
  77. var separatorRegex = new RegExp( options.separator + ( options.verticalSeparator ? '|' + options.verticalSeparator : '' ), 'mg' ),
  78. horizontalSeparatorRegex = new RegExp( options.separator );
  79. var matches,
  80. lastIndex = 0,
  81. isHorizontal,
  82. wasHorizontal = true,
  83. content,
  84. sectionStack = [];
  85. // iterate until all blocks between separators are stacked up
  86. while( matches = separatorRegex.exec( markdown ) ) {
  87. notes = null;
  88. // determine direction (horizontal by default)
  89. isHorizontal = horizontalSeparatorRegex.test( matches[0] );
  90. if( !isHorizontal && wasHorizontal ) {
  91. // create vertical stack
  92. sectionStack.push( [] );
  93. }
  94. // pluck slide content from markdown input
  95. content = markdown.substring( lastIndex, matches.index );
  96. if( isHorizontal && wasHorizontal ) {
  97. // add to horizontal stack
  98. sectionStack.push( content );
  99. }
  100. else {
  101. // add to vertical stack
  102. sectionStack[sectionStack.length-1].push( content );
  103. }
  104. lastIndex = separatorRegex.lastIndex;
  105. wasHorizontal = isHorizontal;
  106. }
  107. // add the remaining slide
  108. ( wasHorizontal ? sectionStack : sectionStack[sectionStack.length-1] ).push( markdown.substring( lastIndex ) );
  109. var markdownSections = '';
  110. // flatten the hierarchical stack, and insert <section data-markdown> tags
  111. for( var i = 0, len = sectionStack.length; i < len; i++ ) {
  112. // vertical
  113. if( sectionStack[i].propertyIsEnumerable( length ) && typeof sectionStack[i].splice === 'function' ) {
  114. markdownSections += '<section '+ options.attributes +'>';
  115. sectionStack[i].forEach( function( child ) {
  116. markdownSections += '<section data-markdown>' + createMarkdownSlide( child, options ) + '</section>';
  117. } );
  118. markdownSections += '</section>';
  119. }
  120. else {
  121. markdownSections += '<section '+ options.attributes +' data-markdown>' + createMarkdownSlide( sectionStack[i], options ) + '</section>';
  122. }
  123. }
  124. return markdownSections;
  125. }
  126. function loadExternalMarkdown() {
  127. var sections = document.querySelectorAll( '[data-markdown]'),
  128. section;
  129. for( var i = 0, len = sections.length; i < len; i++ ) {
  130. section = sections[i];
  131. if( section.getAttribute( 'data-markdown' ).length ) {
  132. var xhr = new XMLHttpRequest(),
  133. url = section.getAttribute( 'data-markdown' );
  134. datacharset = section.getAttribute( 'data-charset' );
  135. // see https://developer.mozilla.org/en-US/docs/Web/API/element.getAttribute#Notes
  136. if( datacharset != null && datacharset != '' ) {
  137. xhr.overrideMimeType( 'text/html; charset=' + datacharset );
  138. }
  139. xhr.onreadystatechange = function() {
  140. if( xhr.readyState === 4 ) {
  141. if ( xhr.status >= 200 && xhr.status < 300 ) {
  142. section.outerHTML = slidifyMarkdown( xhr.responseText, {
  143. separator: section.getAttribute( 'data-separator' ),
  144. verticalSeparator: section.getAttribute( 'data-vertical' ),
  145. notesSeparator: section.getAttribute( 'data-notes' ),
  146. attributes: getForwardedAttributes( section )
  147. });
  148. }
  149. else {
  150. section.outerHTML = '<section data-state="alert">' +
  151. 'ERROR: The attempt to fetch ' + url + ' failed with HTTP status ' + xhr.status + '.' +
  152. 'Check your browser\'s JavaScript console for more details.' +
  153. '<p>Remember that you need to serve the presentation HTML from a HTTP server.</p>' +
  154. '</section>';
  155. }
  156. }
  157. };
  158. xhr.open( 'GET', url, false );
  159. try {
  160. xhr.send();
  161. }
  162. catch ( e ) {
  163. alert( 'Failed to get the Markdown file ' + url + '. Make sure that the presentation and the file are served by a HTTP server and the file can be found there. ' + e );
  164. }
  165. }
  166. else if( section.getAttribute( 'data-separator' ) ) {
  167. section.outerHTML = slidifyMarkdown( getMarkdownFromSlide( section ), {
  168. separator: section.getAttribute( 'data-separator' ),
  169. verticalSeparator: section.getAttribute( 'data-vertical' ),
  170. notesSeparator: section.getAttribute( 'data-notes' ),
  171. attributes: getForwardedAttributes( section )
  172. });
  173. }
  174. }
  175. }
  176. function convertMarkdownToHTML() {
  177. var sections = document.querySelectorAll( '[data-markdown]');
  178. for( var i = 0, len = sections.length; i < len; i++ ) {
  179. var section = sections[i];
  180. var notes = section.querySelector( 'aside.notes' );
  181. var markdown = getMarkdownFromSlide( section );
  182. section.innerHTML = marked( markdown );
  183. // If there were notes, we need to re-add them after
  184. // having overwritten the section's HTML
  185. if( notes ) {
  186. section.appendChild( notes );
  187. }
  188. }
  189. }
  190. loadExternalMarkdown();
  191. convertMarkdownToHTML();
  192. })();