markdown.js 12 KB

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