Skip to content

Instantly share code, notes, and snippets.

@gregmac
Last active August 29, 2015 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gregmac/10324836 to your computer and use it in GitHub Desktop.
Save gregmac/10324836 to your computer and use it in GitHub Desktop.
JIRA paste table helper
/*
Listens for a paste event into a JIRA wiki textarea
If there is at least one tab and newline in the pasted text,
and then every line contains the same number of tabs,
it is turned into a table using JIRA wiki markup syntax.
By Greg MacLellan, 2014-04-09. BSD License.
*/
jQuery('textarea.wiki-textfield').live('paste', function() {
var self = jQuery(this);
var originalText = self.val();
var originalStart = self[0].selectionStart;
var originalEnd = self[0].selectionEnd;
console.log('pasted text', self);
setTimeout(function() {
var newText = self.val();
var endOfPaste = self[0].selectionStart;
//console.log('pasted text: original start/end: ', originalStart, originalEnd, /*'calculated start/end:', start, end, */ 'current', self[0].selectionStart, self[0].selectionEnd);
var pasted = newText.substr(originalStart, endOfPaste).trim();
if ((pasted.indexOf('\t') > 0) && (pasted.indexOf('\n') > 0)) {
var lines = pasted.split('\n');
var expectedNumColumns = lines[0].match(/\t/g);
if (expectedNumColumns == null) {
console.log('pasted text: could not find any columns in first line -- not tablizing');
return;
}
var tablized = '||'+lines[0].replace(/\t/g,'||')+'||\n';
for(var i=1;i<lines.length;i++){
// count number of columns in each row, if it doesn't match
// the first, then stop everything, we won't be replacing the text.
var numColumns = lines[i].match(/\t/g);
if (numColumns == null || numColumns.count != expectedNumColumns.count) {
console.log('pasted text: row '+i+' has '+(numColumns ? numColumns.count : 0)+' columns but first row has '+expectedNumColumns.count+' - not tablizing');
return;
}
tablized += '|'+lines[i].replace(/\t/g,'|')+'|\n';
}
console.log('pasted text: tablized', self, pasted, tablized);
var finalText = '';
if (originalStart > 0) {
finalText = originalText.substring(0, originalStart) + '\n\n';
}
finalText += tablized + '\n' + originalText.substring(originalEnd);
self.val(finalText);
} else {
console.log('pasted text: contains no tabs/newslines. ignoring.');
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment