markdown.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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( root, factory ) {
  7. if( typeof exports === 'object' ) {
  8. module.exports = factory( require( './marked' ) );
  9. }
  10. else {
  11. // Browser globals (root is window)
  12. root.RevealMarkdown = factory( root.marked );
  13. root.RevealMarkdown.initialize();
  14. }
  15. }( this, function( marked ) {
  16. if( typeof marked === 'undefined' ) {
  17. throw 'The reveal.js Markdown plugin requires marked to be loaded';
  18. }
  19. if( typeof hljs !== 'undefined' ) {
  20. marked.setOptions({
  21. highlight: function( lang, code ) {
  22. return hljs.highlightAuto( lang, code ).value;
  23. }
  24. });
  25. }
  26. var DEFAULT_SLIDE_SEPARATOR = '^\n---\n$',
  27. DEFAULT_NOTES_SEPARATOR = 'note:';
  28. DEFAULT_ELEMENT_ATTRIBUTES_SEPARATOR = '{_\s*?([^}]+?)}';
  29. /**
  30. * Retrieves the markdown contents of a slide section
  31. * element. Normalizes leading tabs/whitespace.
  32. */
  33. function getMarkdownFromSlide( section ) {
  34. var template = section.querySelector( 'script' );
  35. // strip leading whitespace so it isn't evaluated as code
  36. var text = ( template || section ).textContent;
  37. var leadingWs = text.match( /^\n?(\s*)/ )[1].length,
  38. leadingTabs = text.match( /^\n?(\t*)/ )[1].length;
  39. if( leadingTabs > 0 ) {
  40. text = text.replace( new RegExp('\\n?\\t{' + leadingTabs + '}','g'), '\n' );
  41. }
  42. else if( leadingWs > 1 ) {
  43. text = text.replace( new RegExp('\\n? {' + leadingWs + '}'), '\n' );
  44. }
  45. return text;
  46. }
  47. /**
  48. * Given a markdown slide section element, this will
  49. * return all arguments that aren't related to markdown
  50. * parsing. Used to forward any other user-defined arguments
  51. * to the output markdown slide.
  52. */
  53. function getForwardedAttributes( section ) {
  54. var attributes = section.attributes;
  55. var result = [];
  56. for( var i = 0, len = attributes.length; i < len; i++ ) {
  57. var name = attributes[i].name,
  58. value = attributes[i].value;
  59. // disregard attributes that are used for markdown loading/parsing
  60. if( /data\-(markdown|separator|vertical|notes)/gi.test( name ) ) continue;
  61. if( value ) {
  62. result.push( name + '=' + value );
  63. }
  64. else {
  65. result.push( name );
  66. }
  67. }
  68. return result.join( ' ' );
  69. }
  70. /**
  71. * Inspects the given options and fills out default
  72. * values for what's not defined.
  73. */
  74. function getSlidifyOptions( options ) {
  75. options = options || {};
  76. options.separator = options.separator || DEFAULT_SLIDE_SEPARATOR;
  77. options.notesSeparator = options.notesSeparator || DEFAULT_NOTES_SEPARATOR;
  78. options.attributes = options.attributes || '';
  79. return options;
  80. }
  81. /**
  82. * Helper function for constructing a markdown slide.
  83. */
  84. function createMarkdownSlide( content, options ) {
  85. options = getSlidifyOptions( options );
  86. var notesMatch = content.split( new RegExp( options.notesSeparator, 'mgi' ) );
  87. if( notesMatch.length === 2 ) {
  88. content = notesMatch[0] + '<aside class="notes" data-markdown>' + notesMatch[1].trim() + '</aside>';
  89. }
  90. return '<script type="text/template">' + content + '</script>';
  91. }
  92. /**
  93. * Parses a data string into multiple slides based
  94. * on the passed in separator arguments.
  95. */
  96. function slidify( markdown, options ) {
  97. options = getSlidifyOptions( options );
  98. var separatorRegex = new RegExp( options.separator + ( options.verticalSeparator ? '|' + options.verticalSeparator : '' ), 'mg' ),
  99. horizontalSeparatorRegex = new RegExp( options.separator );
  100. var matches,
  101. lastIndex = 0,
  102. isHorizontal,
  103. wasHorizontal = true,
  104. content,
  105. sectionStack = [];
  106. // iterate until all blocks between separators are stacked up
  107. while( matches = separatorRegex.exec( markdown ) ) {
  108. notes = null;
  109. // determine direction (horizontal by default)
  110. isHorizontal = horizontalSeparatorRegex.test( matches[0] );
  111. if( !isHorizontal && wasHorizontal ) {
  112. // create vertical stack
  113. sectionStack.push( [] );
  114. }
  115. // pluck slide content from markdown input
  116. content = markdown.substring( lastIndex, matches.index );
  117. if( isHorizontal && wasHorizontal ) {
  118. // add to horizontal stack
  119. sectionStack.push( content );
  120. }
  121. else {
  122. // add to vertical stack
  123. sectionStack[sectionStack.length-1].push( content );
  124. }
  125. lastIndex = separatorRegex.lastIndex;
  126. wasHorizontal = isHorizontal;
  127. }
  128. // add the remaining slide
  129. ( wasHorizontal ? sectionStack : sectionStack[sectionStack.length-1] ).push( markdown.substring( lastIndex ) );
  130. var markdownSections = '';
  131. // flatten the hierarchical stack, and insert <section data-markdown> tags
  132. for( var i = 0, len = sectionStack.length; i < len; i++ ) {
  133. // vertical
  134. if( sectionStack[i] instanceof Array ) {
  135. markdownSections += '<section '+ options.attributes +'>';
  136. sectionStack[i].forEach( function( child ) {
  137. markdownSections += '<section data-markdown>' + createMarkdownSlide( child, options ) + '</section>';
  138. } );
  139. markdownSections += '</section>';
  140. }
  141. else {
  142. markdownSections += '<section '+ options.attributes +' data-markdown>' + createMarkdownSlide( sectionStack[i], options ) + '</section>';
  143. }
  144. }
  145. return markdownSections;
  146. }
  147. /**
  148. * Parses any current data-markdown slides, splits
  149. * multi-slide markdown into separate sections and
  150. * handles loading of external markdown.
  151. */
  152. function processSlides() {
  153. var sections = document.querySelectorAll( '[data-markdown]'),
  154. section;
  155. for( var i = 0, len = sections.length; i < len; i++ ) {
  156. section = sections[i];
  157. if( section.getAttribute( 'data-markdown' ).length ) {
  158. var xhr = new XMLHttpRequest(),
  159. url = section.getAttribute( 'data-markdown' );
  160. datacharset = section.getAttribute( 'data-charset' );
  161. // see https://developer.mozilla.org/en-US/docs/Web/API/element.getAttribute#Notes
  162. if( datacharset != null && datacharset != '' ) {
  163. xhr.overrideMimeType( 'text/html; charset=' + datacharset );
  164. }
  165. xhr.onreadystatechange = function() {
  166. if( xhr.readyState === 4 ) {
  167. if ( xhr.status >= 200 && xhr.status < 300 ) {
  168. section.outerHTML = slidify( xhr.responseText, {
  169. separator: section.getAttribute( 'data-separator' ),
  170. verticalSeparator: section.getAttribute( 'data-vertical' ),
  171. notesSeparator: section.getAttribute( 'data-notes' ),
  172. attributes: getForwardedAttributes( section )
  173. });
  174. }
  175. else {
  176. section.outerHTML = '<section data-state="alert">' +
  177. 'ERROR: The attempt to fetch ' + url + ' failed with HTTP status ' + xhr.status + '.' +
  178. 'Check your browser\'s JavaScript console for more details.' +
  179. '<p>Remember that you need to serve the presentation HTML from a HTTP server.</p>' +
  180. '</section>';
  181. }
  182. }
  183. };
  184. xhr.open( 'GET', url, false );
  185. try {
  186. xhr.send();
  187. }
  188. catch ( e ) {
  189. 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 );
  190. }
  191. }
  192. else if( section.getAttribute( 'data-separator' ) || section.getAttribute( 'data-vertical' ) || section.getAttribute( 'data-notes' ) ) {
  193. section.outerHTML = slidify( getMarkdownFromSlide( section ), {
  194. separator: section.getAttribute( 'data-separator' ),
  195. verticalSeparator: section.getAttribute( 'data-vertical' ),
  196. notesSeparator: section.getAttribute( 'data-notes' ),
  197. attributes: getForwardedAttributes( section )
  198. });
  199. }
  200. else {
  201. section.innerHTML = createMarkdownSlide( getMarkdownFromSlide( section ) );
  202. }
  203. }
  204. }
  205. /**
  206. * Check if a node value has the attributes pattern.
  207. * If yes, extract it and add that value as one or several attributes
  208. * the the terget element.
  209. *
  210. * You need Cache Killer on Chrome to see the effect on any FOM transformation
  211. * directly on refresh (F5)
  212. * http://stackoverflow.com/questions/5690269/disabling-chrome-cache-for-website-development/7000899#answer-11786277
  213. */
  214. function addAttributeInElement( node, elementTarget, separator ) {
  215. var mardownClassesInElementsRegex = new RegExp( separator, 'mg' );
  216. var mardownClassRegex = new RegExp( "([^\"= ]+?)=\"([^\"=]+?)\"", 'mg' );
  217. var nodeValue = node.nodeValue;
  218. if( matches = mardownClassesInElementsRegex.exec( nodeValue ) ) {
  219. var classes = matches[1];
  220. nodeValue = nodeValue.substring( 0, matches.index ) + nodeValue.substring( mardownClassesInElementsRegex.lastIndex );
  221. node.nodeValue = nodeValue;
  222. while( matchesClass = mardownClassRegex.exec( classes ) ) {
  223. elementTarget.setAttribute( matchesClass[1], matchesClass[2] );
  224. }
  225. }
  226. }
  227. /**
  228. * Add attributes to the parent element of a text node,
  229. * or the element of an attribute node.
  230. */
  231. function addAttributes( element, separator ) {
  232. if( element.childNodes.length > 0 ) {
  233. for( var i = 0; i < element.childNodes.length; i++ ) {
  234. addAttributes( element.childNodes[i], separator );
  235. }
  236. }
  237. var nodeValue;
  238. var elementTarget;
  239. // From http://stackoverflow.com/questions/9178174/find-all-text-nodes
  240. if( element.nodeType == Node.TEXT_NODE && /\S/.test(element.nodeValue) ) {
  241. addAttributeInElement( element, element.parentNode, separator );
  242. }
  243. if( element.nodeType == Node.ELEMENT_NODE && element.attributes.length > 0 ) {
  244. for( var j = 0; j < element.attributes.length; j++ ){
  245. var attr = element.attributes[j];
  246. addAttributeInElement( attr, element, separator );
  247. }
  248. }
  249. }
  250. /**
  251. * Converts any current data-markdown slides in the
  252. * DOM to HTML.
  253. */
  254. function convertSlides() {
  255. var sections = document.querySelectorAll( '[data-markdown]');
  256. for( var i = 0, len = sections.length; i < len; i++ ) {
  257. var section = sections[i];
  258. // Only parse the same slide once
  259. if( !section.getAttribute( 'data-markdown-parsed' ) ) {
  260. section.setAttribute( 'data-markdown-parsed', true )
  261. var notes = section.querySelector( 'aside.notes' );
  262. var markdown = getMarkdownFromSlide( section );
  263. section.innerHTML = marked( markdown );
  264. addAttributes( section, section.getAttribute( 'data-element-attributes' ) ||
  265. section.parentNode.getAttribute( 'data-element-attributes' ) ||
  266. DEFAULT_ELEMENT_ATTRIBUTES_SEPARATOR );
  267. // If there were notes, we need to re-add them after
  268. // having overwritten the section's HTML
  269. if( notes ) {
  270. section.appendChild( notes );
  271. }
  272. }
  273. }
  274. }
  275. // API
  276. return {
  277. initialize: function() {
  278. processSlides();
  279. convertSlides();
  280. },
  281. // TODO: Do these belong in the API?
  282. processSlides: processSlides,
  283. convertSlides: convertSlides,
  284. slidify: slidify
  285. };
  286. }));