markdown.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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. DEFAULT_SLIDE_ATTRIBUTES_SEPARATOR = '^.*?<!--\\\sslide-attributes:\\\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. var leadingWs = text.match( /^\n?(\s*)/ )[1].length,
  39. leadingTabs = text.match( /^\n?(\t*)/ )[1].length;
  40. if( leadingTabs > 0 ) {
  41. text = text.replace( new RegExp('\\n?\\t{' + leadingTabs + '}','g'), '\n' );
  42. }
  43. else if( leadingWs > 1 ) {
  44. text = text.replace( new RegExp('\\n? {' + leadingWs + '}','g'), '\n' );
  45. }
  46. return text;
  47. }
  48. /**
  49. * Given a markdown slide section element, this will
  50. * return all arguments that aren't related to markdown
  51. * parsing. Used to forward any other user-defined arguments
  52. * to the output markdown slide.
  53. */
  54. function getForwardedAttributes( section ) {
  55. var attributes = section.attributes;
  56. var result = [];
  57. for( var i = 0, len = attributes.length; i < len; i++ ) {
  58. var name = attributes[i].name,
  59. value = attributes[i].value;
  60. // disregard attributes that are used for markdown loading/parsing
  61. if( /data\-(markdown|separator|vertical|notes|attributes)/gi.test( name ) ) continue;
  62. if( value ) {
  63. result.push( name + '=' + value );
  64. }
  65. else {
  66. result.push( name );
  67. }
  68. }
  69. return result.join( ' ' );
  70. }
  71. /**
  72. * Inspects the given options and fills out default
  73. * values for what's not defined.
  74. */
  75. function getSlidifyOptions( options ) {
  76. options = options || {};
  77. options.separator = options.separator || DEFAULT_SLIDE_SEPARATOR;
  78. options.notesSeparator = options.notesSeparator || DEFAULT_NOTES_SEPARATOR;
  79. options.attributes = options.attributes || '';
  80. options.slideAttributesSeparator = options.slideAttributesSeparator || DEFAULT_SLIDE_ATTRIBUTES_SEPARATOR;
  81. return options;
  82. }
  83. /**
  84. * Helper function for constructing a markdown slide.
  85. */
  86. function createMarkdownSlide( content, options ) {
  87. options = getSlidifyOptions( options );
  88. var notesMatch = content.split( new RegExp( options.notesSeparator, 'mgi' ) );
  89. if( notesMatch.length === 2 ) {
  90. content = notesMatch[0] + '<aside class="notes" data-markdown>' + notesMatch[1].trim() + '</aside>';
  91. }
  92. return '<script type="text/template">' + content + '</script>';
  93. }
  94. /**
  95. * Parses a data string into multiple slides based
  96. * on the passed in separator arguments.
  97. */
  98. function slidify( markdown, options ) {
  99. options = getSlidifyOptions( options );
  100. var separatorRegex = new RegExp( options.separator + ( options.verticalSeparator ? '|' + options.verticalSeparator : '' ), 'mg' ),
  101. horizontalSeparatorRegex = new RegExp( options.separator ),
  102. slideAttributesSeparatorRegex = new RegExp( options.slideAttributesSeparator, 'm' );
  103. var matches,
  104. lastIndex = 0,
  105. isHorizontal,
  106. wasHorizontal = true,
  107. content,
  108. sectionStack = [],
  109. matchAttributes,
  110. slideAttributes = "";
  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. // The 'data-xxx' attributes of the first child must be set on the wrapping parent section to be effective
  141. // Mainly for data-transition (otherwise, it is ignored for the first vertical slide)
  142. firstChild = sectionStack[i][0];
  143. matchAttributes = slideAttributesSeparatorRegex.exec( firstChild );
  144. slideAttributes = matchAttributes ? matchAttributes[1] : "";
  145. dataAttributes = "";
  146. if( slideAttributes != "" ) {
  147. // http://stackoverflow.com/questions/18025762/javascript-regex-replace-all-word-characters-except-word-characters-between-ch
  148. // Keep only data-attributes for the parent slide section.
  149. dataAttributes = slideAttributes.replace( /(data-\S+=\"[^\"]+?\")|\w|[\"=]/g, function(a, b) { return b || ''; });
  150. }
  151. markdownSections += '<section '+ options.attributes + ' ' + dataAttributes + '>';
  152. sectionStack[i].forEach( function( child ) {
  153. matchAttributes = slideAttributesSeparatorRegex.exec( child );
  154. slideAttributes = matchAttributes ? matchAttributes[1] : "";
  155. child = matchAttributes ? child.replace( slideAttributesSeparatorRegex,"" ) : child
  156. markdownSections += '<section ' + slideAttributes + ' data-markdown>' + createMarkdownSlide( child, options ) + '</section>';
  157. } );
  158. markdownSections += '</section>';
  159. }
  160. else {
  161. matchAttributes = slideAttributesSeparatorRegex.exec( sectionStack[i] );
  162. slideAttributes = matchAttributes ? matchAttributes[1] : "";
  163. content = matchAttributes ? sectionStack[i].replace( slideAttributesSeparatorRegex,"" ) : sectionStack[i]
  164. markdownSections += '<section '+ options.attributes + ' ' + slideAttributes +' data-markdown>' + createMarkdownSlide( content, options ) + '</section>';
  165. }
  166. }
  167. return markdownSections;
  168. }
  169. /**
  170. * Parses any current data-markdown slides, splits
  171. * multi-slide markdown into separate sections and
  172. * handles loading of external markdown.
  173. */
  174. function processSlides() {
  175. var sections = document.querySelectorAll( '[data-markdown]'),
  176. section;
  177. for( var i = 0, len = sections.length; i < len; i++ ) {
  178. section = sections[i];
  179. if( section.getAttribute( 'data-markdown' ).length ) {
  180. var xhr = new XMLHttpRequest(),
  181. url = section.getAttribute( 'data-markdown' );
  182. datacharset = section.getAttribute( 'data-charset' );
  183. // see https://developer.mozilla.org/en-US/docs/Web/API/element.getAttribute#Notes
  184. if( datacharset != null && datacharset != '' ) {
  185. xhr.overrideMimeType( 'text/html; charset=' + datacharset );
  186. }
  187. xhr.onreadystatechange = function() {
  188. if( xhr.readyState === 4 ) {
  189. if ( xhr.status >= 200 && xhr.status < 300 ) {
  190. section.outerHTML = slidify( xhr.responseText, {
  191. separator: section.getAttribute( 'data-separator' ),
  192. verticalSeparator: section.getAttribute( 'data-vertical' ),
  193. notesSeparator: section.getAttribute( 'data-notes' ),
  194. attributes: getForwardedAttributes( section ),
  195. slideAttributesSeparator: section.getAttribute( 'data-attributes' ),
  196. });
  197. }
  198. else {
  199. section.outerHTML = '<section data-state="alert">' +
  200. 'ERROR: The attempt to fetch ' + url + ' failed with HTTP status ' + xhr.status + '.' +
  201. 'Check your browser\'s JavaScript console for more details.' +
  202. '<p>Remember that you need to serve the presentation HTML from a HTTP server.</p>' +
  203. '</section>';
  204. }
  205. }
  206. };
  207. xhr.open( 'GET', url, false );
  208. try {
  209. xhr.send();
  210. }
  211. catch ( e ) {
  212. 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 );
  213. }
  214. }
  215. else if( section.getAttribute( 'data-separator' ) || section.getAttribute( 'data-vertical' ) || section.getAttribute( 'data-notes' ) ) {
  216. section.outerHTML = slidify( getMarkdownFromSlide( section ), {
  217. separator: section.getAttribute( 'data-separator' ),
  218. verticalSeparator: section.getAttribute( 'data-vertical' ),
  219. notesSeparator: section.getAttribute( 'data-notes' ),
  220. attributes: getForwardedAttributes( section ),
  221. slideAttributesSeparator: section.getAttribute( 'data-attributes' ),
  222. });
  223. }
  224. else {
  225. var content = getMarkdownFromSlide( section );
  226. var slideAttributesSeparatorRegex = new RegExp( section.getAttribute( 'data-attributes' ) || DEFAULT_SLIDE_ATTRIBUTES_SEPARATOR, 'm' );
  227. var matchAttributes = slideAttributesSeparatorRegex.exec( content );
  228. if ( matchAttributes ) {
  229. var slideAttributes = matchAttributes[1];
  230. content = content.replace( slideAttributesSeparatorRegex,"" );
  231. var slideAttributesRegex = new RegExp( "([^\"= ]+?)=\"([^\"=]+?)\"", 'mg' );
  232. while( matchesAttributes = slideAttributesRegex.exec( slideAttributes ) ) {
  233. section.setAttribute( matchesAttributes[1], matchesAttributes[2] );
  234. }
  235. }
  236. section.innerHTML = createMarkdownSlide( content );
  237. }
  238. }
  239. }
  240. /**
  241. * Check if a node value has the attributes pattern.
  242. * If yes, extract it and add that value as one or several attributes
  243. * the the terget element.
  244. *
  245. * You need Cache Killer on Chrome to see the effect on any FOM transformation
  246. * directly on refresh (F5)
  247. * http://stackoverflow.com/questions/5690269/disabling-chrome-cache-for-website-development/7000899#answer-11786277
  248. */
  249. function addAttributeInElement( node, elementTarget, separator ) {
  250. var mardownClassesInElementsRegex = new RegExp( separator, 'mg' );
  251. var mardownClassRegex = new RegExp( "([^\"= ]+?)=\"([^\"=]+?)\"", 'mg' );
  252. var nodeValue = node.nodeValue;
  253. if( matches = mardownClassesInElementsRegex.exec( nodeValue ) ) {
  254. var classes = matches[1];
  255. nodeValue = nodeValue.substring( 0, matches.index ) + nodeValue.substring( mardownClassesInElementsRegex.lastIndex );
  256. node.nodeValue = nodeValue;
  257. while( matchesClass = mardownClassRegex.exec( classes ) ) {
  258. elementTarget.setAttribute( matchesClass[1], matchesClass[2] );
  259. }
  260. }
  261. }
  262. /**
  263. * Add attributes to the parent element of a text node,
  264. * or the element of an attribute node.
  265. */
  266. function addAttributes( element, separator ) {
  267. if( element.childNodes.length > 0 ) {
  268. for( var i = 0; i < element.childNodes.length; i++ ) {
  269. addAttributes( element.childNodes[i], separator );
  270. }
  271. }
  272. var nodeValue;
  273. var elementTarget;
  274. // From http://stackoverflow.com/questions/9178174/find-all-text-nodes
  275. if( element.nodeType == Node.TEXT_NODE && /\S/.test(element.nodeValue) ) {
  276. addAttributeInElement( element, element.parentNode, separator );
  277. }
  278. if( element.nodeType == Node.ELEMENT_NODE && element.attributes.length > 0 ) {
  279. for( var j = 0; j < element.attributes.length; j++ ){
  280. var attr = element.attributes[j];
  281. addAttributeInElement( attr, element, separator );
  282. }
  283. }
  284. }
  285. /**
  286. * Converts any current data-markdown slides in the
  287. * DOM to HTML.
  288. */
  289. function convertSlides() {
  290. var sections = document.querySelectorAll( '[data-markdown]');
  291. for( var i = 0, len = sections.length; i < len; i++ ) {
  292. var section = sections[i];
  293. // Only parse the same slide once
  294. if( !section.getAttribute( 'data-markdown-parsed' ) ) {
  295. section.setAttribute( 'data-markdown-parsed', true )
  296. var notes = section.querySelector( 'aside.notes' );
  297. var markdown = getMarkdownFromSlide( section );
  298. section.innerHTML = marked( markdown );
  299. addAttributes( section, section.getAttribute( 'data-element-attributes' ) ||
  300. section.parentNode.getAttribute( 'data-element-attributes' ) ||
  301. DEFAULT_ELEMENT_ATTRIBUTES_SEPARATOR );
  302. // If there were notes, we need to re-add them after
  303. // having overwritten the section's HTML
  304. if( notes ) {
  305. section.appendChild( notes );
  306. }
  307. }
  308. }
  309. }
  310. // API
  311. return {
  312. initialize: function() {
  313. processSlides();
  314. convertSlides();
  315. },
  316. // TODO: Do these belong in the API?
  317. processSlides: processSlides,
  318. convertSlides: convertSlides,
  319. slidify: slidify
  320. };
  321. }));