markdown.js 12 KB

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