markdown.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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. var DEFAULT_SLIDE_SEPARATOR = '^\r?\n---\r?\n$',
  20. DEFAULT_NOTES_SEPARATOR = 'note:',
  21. DEFAULT_ELEMENT_ATTRIBUTES_SEPARATOR = '\\\.element\\\s*?(.+?)$',
  22. DEFAULT_SLIDE_ATTRIBUTES_SEPARATOR = '\\\.slide:\\\s*?(\\\S.+?)$';
  23. var SCRIPT_END_PLACEHOLDER = '__SCRIPT_END__';
  24. /**
  25. * Retrieves the markdown contents of a slide section
  26. * element. Normalizes leading tabs/whitespace.
  27. */
  28. function getMarkdownFromSlide( section ) {
  29. var template = section.querySelector( 'script' );
  30. // strip leading whitespace so it isn't evaluated as code
  31. var text = ( template || section ).textContent;
  32. // restore script end tags
  33. text = text.replace( new RegExp( SCRIPT_END_PLACEHOLDER, 'g' ), '</script>' );
  34. var leadingWs = text.match( /^\n?(\s*)/ )[1].length,
  35. leadingTabs = text.match( /^\n?(\t*)/ )[1].length;
  36. if( leadingTabs > 0 ) {
  37. text = text.replace( new RegExp('\\n?\\t{' + leadingTabs + '}','g'), '\n' );
  38. }
  39. else if( leadingWs > 1 ) {
  40. text = text.replace( new RegExp('\\n? {' + leadingWs + '}', 'g'), '\n' );
  41. }
  42. return text;
  43. }
  44. /**
  45. * Given a markdown slide section element, this will
  46. * return all arguments that aren't related to markdown
  47. * parsing. Used to forward any other user-defined arguments
  48. * to the output markdown slide.
  49. */
  50. function getForwardedAttributes( section ) {
  51. var attributes = section.attributes;
  52. var result = [];
  53. for( var i = 0, len = attributes.length; i < len; i++ ) {
  54. var name = attributes[i].name,
  55. value = attributes[i].value;
  56. // disregard attributes that are used for markdown loading/parsing
  57. if( /data\-(markdown|separator|vertical|notes)/gi.test( name ) ) continue;
  58. if( value ) {
  59. result.push( name + '="' + value + '"' );
  60. }
  61. else {
  62. result.push( name );
  63. }
  64. }
  65. return result.join( ' ' );
  66. }
  67. /**
  68. * Inspects the given options and fills out default
  69. * values for what's not defined.
  70. */
  71. function getSlidifyOptions( options ) {
  72. options = options || {};
  73. options.separator = options.separator || DEFAULT_SLIDE_SEPARATOR;
  74. options.notesSeparator = options.notesSeparator || DEFAULT_NOTES_SEPARATOR;
  75. options.attributes = options.attributes || '';
  76. return options;
  77. }
  78. /**
  79. * Helper function for constructing a markdown slide.
  80. */
  81. function createMarkdownSlide( content, options ) {
  82. options = getSlidifyOptions( options );
  83. var notesMatch = content.split( new RegExp( options.notesSeparator, 'mgi' ) );
  84. if( notesMatch.length === 2 ) {
  85. content = notesMatch[0] + '<aside class="notes">' + marked(notesMatch[1].trim()) + '</aside>';
  86. }
  87. // prevent script end tags in the content from interfering
  88. // with parsing
  89. content = content.replace( /<\/script>/g, SCRIPT_END_PLACEHOLDER );
  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. // file protocol yields status code 0 (useful for local debug, mobile applications etc.)
  168. if ( ( xhr.status >= 200 && xhr.status < 300 ) || xhr.status === 0 ) {
  169. section.outerHTML = slidify( xhr.responseText, {
  170. separator: section.getAttribute( 'data-separator' ),
  171. verticalSeparator: section.getAttribute( 'data-separator-vertical' ),
  172. notesSeparator: section.getAttribute( 'data-separator-notes' ),
  173. attributes: getForwardedAttributes( section )
  174. });
  175. }
  176. else {
  177. section.outerHTML = '<section data-state="alert">' +
  178. 'ERROR: The attempt to fetch ' + url + ' failed with HTTP status ' + xhr.status + '.' +
  179. 'Check your browser\'s JavaScript console for more details.' +
  180. '<p>Remember that you need to serve the presentation HTML from a HTTP server.</p>' +
  181. '</section>';
  182. }
  183. }
  184. };
  185. xhr.open( 'GET', url, false );
  186. try {
  187. xhr.send();
  188. }
  189. catch ( e ) {
  190. 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 );
  191. }
  192. }
  193. else if( section.getAttribute( 'data-separator' ) || section.getAttribute( 'data-separator-vertical' ) || section.getAttribute( 'data-separator-notes' ) ) {
  194. section.outerHTML = slidify( getMarkdownFromSlide( section ), {
  195. separator: section.getAttribute( 'data-separator' ),
  196. verticalSeparator: section.getAttribute( 'data-separator-vertical' ),
  197. notesSeparator: section.getAttribute( 'data-separator-notes' ),
  198. attributes: getForwardedAttributes( section )
  199. });
  200. }
  201. else {
  202. section.innerHTML = createMarkdownSlide( getMarkdownFromSlide( section ) );
  203. }
  204. }
  205. }
  206. /**
  207. * Check if a node value has the attributes pattern.
  208. * If yes, extract it and add that value as one or several attributes
  209. * the the terget element.
  210. *
  211. * You need Cache Killer on Chrome to see the effect on any FOM transformation
  212. * directly on refresh (F5)
  213. * http://stackoverflow.com/questions/5690269/disabling-chrome-cache-for-website-development/7000899#answer-11786277
  214. */
  215. function addAttributeInElement( node, elementTarget, separator ) {
  216. var mardownClassesInElementsRegex = new RegExp( separator, 'mg' );
  217. var mardownClassRegex = new RegExp( "([^\"= ]+?)=\"([^\"=]+?)\"", 'mg' );
  218. var nodeValue = node.nodeValue;
  219. if( matches = mardownClassesInElementsRegex.exec( nodeValue ) ) {
  220. var classes = matches[1];
  221. nodeValue = nodeValue.substring( 0, matches.index ) + nodeValue.substring( mardownClassesInElementsRegex.lastIndex );
  222. node.nodeValue = nodeValue;
  223. while( matchesClass = mardownClassRegex.exec( classes ) ) {
  224. elementTarget.setAttribute( matchesClass[1], matchesClass[2] );
  225. }
  226. return true;
  227. }
  228. return false;
  229. }
  230. /**
  231. * Add attributes to the parent element of a text node,
  232. * or the element of an attribute node.
  233. */
  234. function addAttributes( section, element, previousElement, separatorElementAttributes, separatorSectionAttributes ) {
  235. if ( element != null && element.childNodes != undefined && element.childNodes.length > 0 ) {
  236. previousParentElement = element;
  237. for( var i = 0; i < element.childNodes.length; i++ ) {
  238. childElement = element.childNodes[i];
  239. if ( i > 0 ) {
  240. j = i - 1;
  241. while ( j >= 0 ) {
  242. aPreviousChildElement = element.childNodes[j];
  243. if ( typeof aPreviousChildElement.setAttribute == 'function' && aPreviousChildElement.tagName != "BR" ) {
  244. previousParentElement = aPreviousChildElement;
  245. break;
  246. }
  247. j = j - 1;
  248. }
  249. }
  250. parentSection = section;
  251. if( childElement.nodeName == "section" ) {
  252. parentSection = childElement ;
  253. previousParentElement = childElement ;
  254. }
  255. if ( typeof childElement.setAttribute == 'function' || childElement.nodeType == Node.COMMENT_NODE ) {
  256. addAttributes( parentSection, childElement, previousParentElement, separatorElementAttributes, separatorSectionAttributes );
  257. }
  258. }
  259. }
  260. if ( element.nodeType == Node.COMMENT_NODE ) {
  261. if ( addAttributeInElement( element, previousElement, separatorElementAttributes ) == false ) {
  262. addAttributeInElement( element, section, separatorSectionAttributes );
  263. }
  264. }
  265. }
  266. /**
  267. * Converts any current data-markdown slides in the
  268. * DOM to HTML.
  269. */
  270. function convertSlides() {
  271. var sections = document.querySelectorAll( '[data-markdown]');
  272. for( var i = 0, len = sections.length; i < len; i++ ) {
  273. var section = sections[i];
  274. // Only parse the same slide once
  275. if( !section.getAttribute( 'data-markdown-parsed' ) ) {
  276. section.setAttribute( 'data-markdown-parsed', true )
  277. var notes = section.querySelector( 'aside.notes' );
  278. var markdown = getMarkdownFromSlide( section );
  279. section.innerHTML = marked( markdown );
  280. addAttributes( section, section, null, section.getAttribute( 'data-element-attributes' ) ||
  281. section.parentNode.getAttribute( 'data-element-attributes' ) ||
  282. DEFAULT_ELEMENT_ATTRIBUTES_SEPARATOR,
  283. section.getAttribute( 'data-attributes' ) ||
  284. section.parentNode.getAttribute( 'data-attributes' ) ||
  285. DEFAULT_SLIDE_ATTRIBUTES_SEPARATOR);
  286. // If there were notes, we need to re-add them after
  287. // having overwritten the section's HTML
  288. if( notes ) {
  289. section.appendChild( notes );
  290. }
  291. }
  292. }
  293. }
  294. // API
  295. return {
  296. initialize: function() {
  297. if( typeof marked === 'undefined' ) {
  298. throw 'The reveal.js Markdown plugin requires marked to be loaded';
  299. }
  300. if( typeof hljs !== 'undefined' ) {
  301. marked.setOptions({
  302. highlight: function( code, lang ) {
  303. return hljs.highlightAuto( code, [lang] ).value;
  304. }
  305. });
  306. }
  307. var options = Reveal.getConfig().markdown;
  308. if ( options ) {
  309. marked.setOptions( options );
  310. }
  311. processSlides();
  312. convertSlides();
  313. },
  314. // TODO: Do these belong in the API?
  315. processSlides: processSlides,
  316. convertSlides: convertSlides,
  317. slidify: slidify
  318. };
  319. }));