Stackedit/public/res/extensions/markdownSectionParser.js

62 lines
2.7 KiB
JavaScript
Raw Normal View History

define([
2013-11-17 22:59:03 +00:00
"underscore",
"extensions/markdownExtra",
"extensions/mathJax",
"classes/Extension",
], function(_, markdownExtra, mathJax, Extension) {
var markdownSectionParser = new Extension("markdownSectionParser", "Markdown section parser");
2013-11-07 23:10:38 +00:00
var eventMgr;
markdownSectionParser.onEventMgrCreated = function(eventMgrParameter) {
eventMgr = eventMgrParameter;
};
markdownSectionParser.onPagedownConfigure = function(editor) {
2013-11-17 22:59:03 +00:00
// Build a regexp to look for section delimiters
var regexp = '^.+[ \\t]*\\n=+[ \\t]*\\n+|^.+[ \\t]*\\n-+[ \\t]*\\n+|^\\#{1,6}[ \\t]*.+?[ \\t]*\\#*\\n+'; // Title delimiters
2013-11-21 17:47:19 +00:00
if(markdownExtra.enabled) {
2013-11-17 22:59:03 +00:00
if(_.some(markdownExtra.config.extensions, function(extension) {
return extension == "fenced_code_gfm";
})) {
regexp = '^```.*\\n[\\s\\S]*?\\n```|' + regexp; // Fenced block delimiters
}
}
2013-11-21 17:47:19 +00:00
if(mathJax.enabled) {
2013-11-17 22:59:03 +00:00
// Math delimiter has to follow 1 empty line to be considered as a section delimiter
regexp = '^[ \\t]*\\n\\$\\$[\\s\\S]*?\\$\\$|' + regexp; // $$ math block delimiters
regexp = '^[ \\t]*\\n\\\\\\\\[[\\s\\S]*?\\\\\\\\]|' + regexp; // \\[ \\] math block delimiters
regexp = '^[ \\t]*\\n\\\\?\\\\begin\\{[a-z]*\\*?\\}[\\s\\S]*?\\\\end\\{[a-z]*\\*?\\}|' + regexp; // \\begin{...} \\end{...} math block delimiters
2013-11-17 22:59:03 +00:00
}
regexp = new RegExp(regexp, 'gm');
2013-11-17 22:59:03 +00:00
var converter = editor.getConverter();
converter.hooks.chain("preConversion", function(text) {
eventMgr.previewStartTime = new Date();
var tmpText = text + "\n\n";
function addSection(startOffset, endOffset) {
var sectionText = tmpText.substring(offset, endOffset);
sectionList.push({
text: sectionText,
textWithDelimiter: '\n<div class="se-section-delimiter"></div>\n\n' + sectionText + '\n'
});
}
var sectionList = [], offset = 0;
2013-11-17 22:59:03 +00:00
// Look for delimiters
tmpText.replace(regexp, function(match, matchOffset) {
// Create a new section with the text preceding the delimiter
addSection(offset, matchOffset);
2013-11-17 22:59:03 +00:00
offset = matchOffset;
});
// Last section
addSection(offset, text.length);
eventMgr.onSectionsCreated(sectionList);
2013-11-17 22:59:03 +00:00
return _.reduce(sectionList, function(result, section) {
return result + section.textWithDelimiter;
}, '');
});
};
return markdownSectionParser;
});