Stackedit/public/res/extensions/markdownSectionParser.js
2014-03-17 02:01:46 +00:00

76 lines
2.8 KiB
JavaScript

define([
"underscore",
"extensions/markdownExtra",
"extensions/mathJax",
"classes/Extension",
], function(_, markdownExtra, mathJax, Extension) {
var markdownSectionParser = new Extension("markdownSectionParser", "Markdown section parser");
var eventMgr;
markdownSectionParser.onEventMgrCreated = function(eventMgrParameter) {
eventMgr = eventMgrParameter;
};
var sectionList = [];
// Regexp to look for section delimiters
var regexp = '^.+[ \\t]*\\n=+[ \\t]*\\n+|^.+[ \\t]*\\n-+[ \\t]*\\n+|^\\#{1,6}[ \\t]*.+?[ \\t]*\\#*\\n+'; // Title delimiters
markdownSectionParser.onPagedownConfigure = function(editor) {
if(markdownExtra.enabled) {
if(_.some(markdownExtra.config.extensions, function(extension) {
return extension == "fenced_code_gfm";
})) {
regexp = '^```.*\\n[\\s\\S]*?\\n```|' + regexp; // Fenced block delimiters
}
}
if(mathJax.enabled) {
// 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
}
regexp = new RegExp(regexp, 'gm');
var converter = editor.getConverter();
converter.hooks.chain("preConversion", function() {
return _.reduce(sectionList, function(result, section) {
return result + section.previewText;
}, '');
});
};
var trimLen;
markdownSectionParser.onMarkdownTrim = function(len) {
trimLen = len;
};
var sectionCounter = 0;
function parseFileContent(fileDesc) {
var text = fileDesc.content.substring(trimLen);
var tmpText = text + "\n\n";
function addSection(startOffset, endOffset) {
var sectionText = tmpText.substring(offset, endOffset);
sectionList.push({
id: ++sectionCounter,
text: sectionText
});
}
sectionList = [];
var offset = 0;
// Look for delimiters
tmpText.replace(regexp, function(match, matchOffset) {
// Create a new section with the text preceding the delimiter
addSection(offset, matchOffset);
offset = matchOffset;
});
// Last section
addSection(offset, text.length);
eventMgr.onSectionsCreated(sectionList);
}
markdownSectionParser.onFileOpen = parseFileContent;
markdownSectionParser.onContentChanged = parseFileContent;
return markdownSectionParser;
});