retrography
5/5/2016 - 9:06 PM

User custom extension for Stackedit that converts CSV/TSVs in code fences into Markdown tables

User custom extension for Stackedit that converts CSV/TSVs in code fences into Markdown tables

userCustom.onPagedownConfigure = function(editor) {
	var converter = editor.getConverter();
	
	function csvToMarkdown( csvContent, delimiter, hasHeader ) {
		if( delimiter != "\t" ) {
			csvContent = csvContent.replace(/\t/g, "    ");
		}
		var columns = csvContent.split("\n");

		var tabularData = [];
		var maxRowLen = [];

		columns.forEach(function( e, i ) {
			if( typeof tabularData[i] == "undefined" ) {
				tabularData[i] = [];
			}

			var row = e.split(delimiter);

			row.forEach(function( ee, ii ) {
				if( typeof maxRowLen[ii] == "undefined" ) {
					maxRowLen[ii] = 0;
				}

				maxRowLen[ii] = Math.max(maxRowLen[ii], ee.length);
				tabularData[i][ii] = ee;
			});
		});

		var headerOutput = "";
		var seperatorOutput = "";

		maxRowLen.forEach(function( len ) {
			var spacer;
			spacer = Array(len + 1 + 2).join("-");
			seperatorOutput += "|" + spacer;

			spacer = Array(len + 1 + 2).join(" ");
			headerOutput += "|" + spacer;
		});

		headerOutput += "| \n";
		seperatorOutput += "| \n";

		if( hasHeader ) {
			headerOutput = "";
		}

		var rowOutput = "";
		var initHeader = true;
		tabularData.forEach(function( col ) {
			maxRowLen.forEach(function( len, y ) {
				var row = typeof col[y] == "undefined" ? "" : col[y];
				var spacing = Array((len - row.length) + 1).join(" ");

				if( hasHeader && initHeader ) {
					headerOutput += "| " + row + spacing + " ";
				} else {
					rowOutput += "| " + row + spacing + " ";
				}
			});

			if( hasHeader && initHeader ) {
				headerOutput += "| \n";
			} else {
				rowOutput += "| \n";
			}

			initHeader = false;
		});

		var output = headerOutput + seperatorOutput + rowOutput;
        return (hasHeader) ? output : "|" + output;
	}
	
	converter.hooks.chain("preConversion", function(text) {
        return text.replace(/^```(?: |\t)*(csv|tsv)(?: |\t)*(noheader)?(?: |\t)*$\n^([^]*?)\n^```/igm, function(match, type, noheader, data) {
            var delimiter = (type == "csv") ? "," : "\t";
            var header = (noheader !== "noheader") ? true : false;             
            return csvToMarkdown(data, delimiter, header);
        });        
	});
};