foremark
Version:
A technology for writing semi-plain text documents that extends upon the concept of Markdeep.
78 lines • 3.32 kB
JavaScript
// This source code is largely based on `markdeep.js`
Object.defineProperty(exports, "__esModule", { value: true });
var TABLE_ROW = /(?:(?:\n|^)[ \t]*(?:(?:\|?[ \t\S]+?(?:\|[ \t\S]+?)+\|?)|\|[ \t\S]+\|)(?=\n|$))/.source;
var TABLE_SEPARATOR = /(?:\n|^)[ \t]*(?:(?:\|? *\:?-+\:?(?: *\| *\:?-+\:?)+ *\|?|)|\|[\:-]+\|)(?=\n|$)/.source;
var TABLE_CAPTION = /(?:\n|^)[ \t]*\[[^\n\|]+\][ \t]*(?=\n|$)/.source;
var TABLE_REGEXP = new RegExp(TABLE_ROW + TABLE_SEPARATOR + TABLE_ROW + '+(' + TABLE_CAPTION + ')?', 'g');
/** Maruku ("github")-style table processing */
function replaceTables(s) {
function trimTableRowEnds(row) {
return row.trim().replace(/^\||\|$/g, '');
}
s = s.replace(TABLE_REGEXP, function (match) {
// Found a table, actually parse it by rows
var rowArray = match.split('\n');
var result = '';
// Skip the bogus leading row
var startRow = (rowArray[0] === '') ? 1 : 0;
var caption = rowArray[rowArray.length - 1].trim();
if ((caption.length > 3) && (caption[0] === '[') && (caption[caption.length - 1] === ']')) {
// Remove the caption from the row array
rowArray.pop();
caption = caption.substring(1, caption.length - 1);
}
else {
caption = null;
}
// Parse the separator row for left/center/right-indicating colons
var columnStyle = [];
trimTableRowEnds(rowArray[startRow + 1]).replace(/:?-+:?/g, function (match) {
var left = (match[0] === ':');
var right = (match[match.length - 1] === ':');
columnStyle.push(' style="text-align:' + ((left && right) ? 'center' : (right ? 'right' : 'left')) + '"');
return '';
});
var row = rowArray[startRow + 1].trim();
var hasLeadingBar = row[0] === '|';
var hasTrailingBar = row[row.length - 1] === '|';
var tag = 'th';
var _loop_1 = function () {
// Remove leading and trailing whitespace and column delimiters
row = rowArray[r].trim();
if (!hasLeadingBar && (row[0] === '|')) {
// Empty first column
row = ' ' + row;
}
if (!hasTrailingBar && (row[row.length - 1] === '|')) {
// Empty last column
row += ' ';
}
row = trimTableRowEnds(row);
var i = 0;
result += "<tr><" + tag + columnStyle[0] + ">";
result += row.replace(/ *\| */g, function () {
++i;
return " </" + tag + "><" + tag + (columnStyle[i] || '') + "> ";
});
result += "</" + tag + "></tr>\n";
// Skip the header-separator row
if (r == startRow) {
++r;
tag = 'td';
}
};
for (var r = startRow; r < rowArray.length; ++r) {
_loop_1();
}
result = "<table class=\"table\">" + result + "</table>";
if (caption) {
caption = "<div class=\"tablecaption\">" + caption + "</div>";
result = caption + result;
}
return result;
});
return s;
}
exports.replaceTables = replaceTables;
//# sourceMappingURL=table.js.map
;