(function() {
var utils;
utils = {
slugify: function(text) {
return text.toLowerCase().replace(/\s+/g, "-").replace(/[^\w\-]+/g, "").replace(/\-\-+/g, "-").replace(/^-+/, "").replace(/-+$/, "");
}
};
Markdown.Toc = (function() {
var TocElement, buildToc, groupTags, toc;
toc = {};
TocElement = function(tagName, anchor, text) {
this.tagName = tagName;
this.anchor = anchor;
this.text = text;
this.children = [];
};
TocElement.prototype.childrenToString = function() {
var child, i, len, ref, result;
if (this.children.length === 0) {
return "";
}
result = "
\n";
ref = this.children;
for (i = 0, len = ref.length; i < len; i++) {
child = ref[i];
result += child.toString();
}
result += "
\n";
return result;
};
TocElement.prototype.toString = function() {
var result;
result = "";
if (this.anchor && this.text) {
result += "" + this.text + "";
}
result += this.childrenToString() + "\n";
return result;
};
groupTags = function(array, level) {
var currentElement, element, i, len, pushCurrentElement, result, tagName;
pushCurrentElement = function() {
if (currentElement !== undefined) {
if (currentElement.children.length > 0) {
currentElement.children = groupTags(currentElement.children, level + 1);
}
return result.push(currentElement);
}
};
level = level || 1;
tagName = "H" + level;
result = [];
currentElement = void 0;
for (i = 0, len = array.length; i < len; i++) {
element = array[i];
if (element.tagName !== tagName) {
if (level !== 6) {
if (currentElement === undefined) {
currentElement = new TocElement();
}
currentElement.children.push(element);
}
} else {
pushCurrentElement();
currentElement = element;
}
}
pushCurrentElement();
return result;
};
buildToc = function($el) {
var anchorList, createAnchor, elementList;
createAnchor = function(el) {
var anchor, id, index;
id = el.id || utils.slugify(el.textContent) || "title";
anchor = id;
index = 0;
while (_.has(anchorList, anchor)) {
anchor = id + "-" + (++index);
}
anchorList[anchor] = true;
el.id = anchor;
return anchor;
};
anchorList = {};
elementList = [];
$el.find("h1, h2, h3, h4, h5, h6").each(function(index, elt) {
return elementList.push(new TocElement(elt.tagName, createAnchor(elt), elt.textContent));
});
elementList = groupTags(elementList);
return "\n
\n" + elementList.join("") + "
\n
\n";
};
toc.apply = function($el) {
var htmlToc, marker, tocExp;
marker = "\\[(TOC|toc)\\]";
tocExp = new RegExp('^' + marker + '$');
htmlToc = buildToc($el);
return $el.find("p").each(function(index, elt) {
if (tocExp.test(elt.innerHTML)) {
return elt.innerHTML = htmlToc;
}
});
};
return toc;
})();
}).call(this);