2 * The reveal.js markdown plugin. Handles parsing of
3 * markdown inside of presentations as well as loading
4 * of external markdown documents.
6 (function( root, factory ) {
7 if( typeof exports === 'object' ) {
8 module.exports = factory( require( './marked' ) );
11 // Browser globals (root is window)
12 root.RevealMarkdown = factory( root.marked );
13 root.RevealMarkdown.initialize();
15 }( this, function( marked ) {
17 if( typeof marked === 'undefined' ) {
18 throw 'The reveal.js Markdown plugin requires marked to be loaded';
21 if( typeof hljs !== 'undefined' ) {
23 highlight: function( lang, code ) {
24 return hljs.highlightAuto( lang, code ).value;
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.+?)$';
34 var SCRIPT_END_PLACEHOLDER = '__SCRIPT_END__';
38 * Retrieves the markdown contents of a slide section
39 * element. Normalizes leading tabs/whitespace.
41 function getMarkdownFromSlide( section ) {
43 var template = section.querySelector( 'script' );
45 // strip leading whitespace so it isn't evaluated as code
46 var text = ( template || section ).textContent;
48 // restore script end tags
49 text = text.replace( new RegExp( SCRIPT_END_PLACEHOLDER, 'g' ), '</script>' );
51 var leadingWs = text.match( /^\n?(\s*)/ )[1].length,
52 leadingTabs = text.match( /^\n?(\t*)/ )[1].length;
54 if( leadingTabs > 0 ) {
55 text = text.replace( new RegExp('\\n?\\t{' + leadingTabs + '}','g'), '\n' );
57 else if( leadingWs > 1 ) {
58 text = text.replace( new RegExp('\\n? {' + leadingWs + '}', 'g'), '\n' );
66 * Given a markdown slide section element, this will
67 * return all arguments that aren't related to markdown
68 * parsing. Used to forward any other user-defined arguments
69 * to the output markdown slide.
71 function getForwardedAttributes( section ) {
73 var attributes = section.attributes;
76 for( var i = 0, len = attributes.length; i < len; i++ ) {
77 var name = attributes[i].name,
78 value = attributes[i].value;
80 // disregard attributes that are used for markdown loading/parsing
81 if( /data\-(markdown|separator|vertical|notes)/gi.test( name ) ) continue;
84 result.push( name + '="' + value + '"' );
91 return result.join( ' ' );
96 * Inspects the given options and fills out default
97 * values for what's not defined.
99 function getSlidifyOptions( options ) {
101 options = options || {};
102 options.separator = options.separator || DEFAULT_SLIDE_SEPARATOR;
103 options.notesSeparator = options.notesSeparator || DEFAULT_NOTES_SEPARATOR;
104 options.attributes = options.attributes || '';
111 * Helper function for constructing a markdown slide.
113 function createMarkdownSlide( content, options ) {
115 options = getSlidifyOptions( options );
117 var notesMatch = content.split( new RegExp( options.notesSeparator, 'mgi' ) );
119 if( notesMatch.length === 2 ) {
120 content = notesMatch[0] + '<aside class="notes" data-markdown>' + notesMatch[1].trim() + '</aside>';
123 // prevent script end tags in the content from interfering
125 content = content.replace( /<\/script>/g, SCRIPT_END_PLACEHOLDER );
127 return '<script type="text/template">' + content + '</script>';
132 * Parses a data string into multiple slides based
133 * on the passed in separator arguments.
135 function slidify( markdown, options ) {
137 options = getSlidifyOptions( options );
139 var separatorRegex = new RegExp( options.separator + ( options.verticalSeparator ? '|' + options.verticalSeparator : '' ), 'mg' ),
140 horizontalSeparatorRegex = new RegExp( options.separator );
145 wasHorizontal = true,
149 // iterate until all blocks between separators are stacked up
150 while( matches = separatorRegex.exec( markdown ) ) {
153 // determine direction (horizontal by default)
154 isHorizontal = horizontalSeparatorRegex.test( matches[0] );
156 if( !isHorizontal && wasHorizontal ) {
157 // create vertical stack
158 sectionStack.push( [] );
161 // pluck slide content from markdown input
162 content = markdown.substring( lastIndex, matches.index );
164 if( isHorizontal && wasHorizontal ) {
165 // add to horizontal stack
166 sectionStack.push( content );
169 // add to vertical stack
170 sectionStack[sectionStack.length-1].push( content );
173 lastIndex = separatorRegex.lastIndex;
174 wasHorizontal = isHorizontal;
177 // add the remaining slide
178 ( wasHorizontal ? sectionStack : sectionStack[sectionStack.length-1] ).push( markdown.substring( lastIndex ) );
180 var markdownSections = '';
182 // flatten the hierarchical stack, and insert <section data-markdown> tags
183 for( var i = 0, len = sectionStack.length; i < len; i++ ) {
185 if( sectionStack[i] instanceof Array ) {
186 markdownSections += '<section '+ options.attributes +'>';
188 sectionStack[i].forEach( function( child ) {
189 markdownSections += '<section data-markdown>' + createMarkdownSlide( child, options ) + '</section>';
192 markdownSections += '</section>';
195 markdownSections += '<section '+ options.attributes +' data-markdown>' + createMarkdownSlide( sectionStack[i], options ) + '</section>';
199 return markdownSections;
204 * Parses any current data-markdown slides, splits
205 * multi-slide markdown into separate sections and
206 * handles loading of external markdown.
208 function processSlides() {
210 var sections = document.querySelectorAll( '[data-markdown]'),
213 for( var i = 0, len = sections.length; i < len; i++ ) {
215 section = sections[i];
217 if( section.getAttribute( 'data-markdown' ).length ) {
219 var xhr = new XMLHttpRequest(),
220 url = section.getAttribute( 'data-markdown' );
222 datacharset = section.getAttribute( 'data-charset' );
224 // see https://developer.mozilla.org/en-US/docs/Web/API/element.getAttribute#Notes
225 if( datacharset != null && datacharset != '' ) {
226 xhr.overrideMimeType( 'text/html; charset=' + datacharset );
229 xhr.onreadystatechange = function() {
230 if( xhr.readyState === 4 ) {
231 // file protocol yields status code 0 (useful for local debug, mobile applications etc.)
232 if ( ( xhr.status >= 200 && xhr.status < 300 ) || xhr.status === 0 ) {
234 section.outerHTML = slidify( xhr.responseText, {
235 separator: section.getAttribute( 'data-separator' ),
236 verticalSeparator: section.getAttribute( 'data-separator-vertical' ),
237 notesSeparator: section.getAttribute( 'data-separator-notes' ),
238 attributes: getForwardedAttributes( section )
244 section.outerHTML = '<section data-state="alert">' +
245 'ERROR: The attempt to fetch ' + url + ' failed with HTTP status ' + xhr.status + '.' +
246 'Check your browser\'s JavaScript console for more details.' +
247 '<p>Remember that you need to serve the presentation HTML from a HTTP server.</p>' +
254 xhr.open( 'GET', url, false );
260 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 );
264 else if( section.getAttribute( 'data-separator' ) || section.getAttribute( 'data-separator-vertical' ) || section.getAttribute( 'data-separator-notes' ) ) {
266 section.outerHTML = slidify( getMarkdownFromSlide( section ), {
267 separator: section.getAttribute( 'data-separator' ),
268 verticalSeparator: section.getAttribute( 'data-separator-vertical' ),
269 notesSeparator: section.getAttribute( 'data-separator-notes' ),
270 attributes: getForwardedAttributes( section )
275 section.innerHTML = createMarkdownSlide( getMarkdownFromSlide( section ) );
282 * Check if a node value has the attributes pattern.
283 * If yes, extract it and add that value as one or several attributes
284 * the the terget element.
286 * You need Cache Killer on Chrome to see the effect on any FOM transformation
287 * directly on refresh (F5)
288 * http://stackoverflow.com/questions/5690269/disabling-chrome-cache-for-website-development/7000899#answer-11786277
290 function addAttributeInElement( node, elementTarget, separator ) {
292 var mardownClassesInElementsRegex = new RegExp( separator, 'mg' );
293 var mardownClassRegex = new RegExp( "([^\"= ]+?)=\"([^\"=]+?)\"", 'mg' );
294 var nodeValue = node.nodeValue;
295 if( matches = mardownClassesInElementsRegex.exec( nodeValue ) ) {
297 var classes = matches[1];
298 nodeValue = nodeValue.substring( 0, matches.index ) + nodeValue.substring( mardownClassesInElementsRegex.lastIndex );
299 node.nodeValue = nodeValue;
300 while( matchesClass = mardownClassRegex.exec( classes ) ) {
301 elementTarget.setAttribute( matchesClass[1], matchesClass[2] );
309 * Add attributes to the parent element of a text node,
310 * or the element of an attribute node.
312 function addAttributes( section, element, previousElement, separatorElementAttributes, separatorSectionAttributes ) {
314 if ( element != null && element.childNodes != undefined && element.childNodes.length > 0 ) {
315 previousParentElement = element;
316 for( var i = 0; i < element.childNodes.length; i++ ) {
317 childElement = element.childNodes[i];
321 aPreviousChildElement = element.childNodes[j];
322 if ( typeof aPreviousChildElement.setAttribute == 'function' && aPreviousChildElement.tagName != "BR" ) {
323 previousParentElement = aPreviousChildElement;
329 parentSection = section;
330 if( childElement.nodeName == "section" ) {
331 parentSection = childElement ;
332 previousParentElement = childElement ;
334 if ( typeof childElement.setAttribute == 'function' || childElement.nodeType == Node.COMMENT_NODE ) {
335 addAttributes( parentSection, childElement, previousParentElement, separatorElementAttributes, separatorSectionAttributes );
340 if ( element.nodeType == Node.COMMENT_NODE ) {
341 if ( addAttributeInElement( element, previousElement, separatorElementAttributes ) == false ) {
342 addAttributeInElement( element, section, separatorSectionAttributes );
348 * Converts any current data-markdown slides in the
351 function convertSlides() {
353 var sections = document.querySelectorAll( '[data-markdown]');
355 for( var i = 0, len = sections.length; i < len; i++ ) {
357 var section = sections[i];
359 // Only parse the same slide once
360 if( !section.getAttribute( 'data-markdown-parsed' ) ) {
362 section.setAttribute( 'data-markdown-parsed', true )
364 var notes = section.querySelector( 'aside.notes' );
365 var markdown = getMarkdownFromSlide( section );
367 section.innerHTML = marked( markdown );
368 addAttributes( section, section, null, section.getAttribute( 'data-element-attributes' ) ||
369 section.parentNode.getAttribute( 'data-element-attributes' ) ||
370 DEFAULT_ELEMENT_ATTRIBUTES_SEPARATOR,
371 section.getAttribute( 'data-attributes' ) ||
372 section.parentNode.getAttribute( 'data-attributes' ) ||
373 DEFAULT_SLIDE_ATTRIBUTES_SEPARATOR);
375 // If there were notes, we need to re-add them after
376 // having overwritten the section's HTML
378 section.appendChild( notes );
390 initialize: function() {
395 // TODO: Do these belong in the API?
396 processSlides: processSlides,
397 convertSlides: convertSlides,