markdown.js 12 KB

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