make markdown table using selection as column headers

Script key: make markdown table using selection as column headers

Posted by @cpaconnelly

Install

Details

Label
Voice Over make markdown table using selection as column headers
Script
// this script key takes the selection and uses each row
// as a table header in a new multi-markdown table
// the desired alignment for a column can be indicated
// by adding ,l ,c or ,r to the end of the row


var text = getSelectedText();

var columns = text.split('\n');

// get alignment for each row if present using ',c' ',r' or ',l'/nothing and store in array, trimming off formatting indicator if present

var alignment = [];

for (i = 0; i < columns.length; i++) {
    if (columns[i].endsWith(',r')) {
        alignment[i] = 'right';
        columns[i] = columns[i].slice(0,-2); //trim off the ,r
    } else if (columns[i].endsWith(',c')) {
        alignment[i] = 'center';
        columns[i] = columns[i].slice(0,-2);
    } else if (columns[i].endsWith(',l')) {
        alignment[i] = 'left';
        columns[i] = columns[i].slice(0,-2);
    } else {
        alignment[i] = 'left';
    }
}

// build separator row, taking account of alignment

var separatorRow = '|';

for (i = 0; i < columns.length; i++) {
    if (alignment[i] == 'right') {
        separatorRow = separatorRow + ' ----: |';
    } else if (alignment[i] == 'center') {
        separatorRow = separatorRow + ' :---: |';
    } else {
        separatorRow = separatorRow + ' :---- |';
    }
}    

// assemble table

table = '| ' + columns.join(' | ') + ' |\n' + separatorRow + '\n| ';

setSelectedText(table);






Advanced

Keyboard shortcut None
Hide key Yes

Discussion

comments powered by Disqus