markdown.js 12 KB

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