OK - this is what I am doing based on jsFiddle's suggestion and it works. Only problem is I do not have Windows and in IE where I do have it copy to clipboard, apparently the line breaks are broken, but that's not this question (and I suspect a .replace() can fix it - I just need access to windows to play with IE):
function lineBreakCount(str){
// http://snippets.dzone.com/posts/show/5770
/* counts \n */
try {
return((str.match(/[^\n]*\n[^\n]*/gi).length));
} catch(e) {
return 0;
}
}
function nodeToCopy($node) {
// For Code Snippets - [AW]
$pre = $node.find('pre:first');
var string = $pre.text();
if (window.clipboardData && clipboardData.setData) {
clipboardData.setData('text', string);
} else {
var n = 1 + lineBreakCount(string);
$pre.attr('class','nodisplay');
$pre.after('<textarea readonly="readonly" rows="' + n + '" class="dbg-copycode">' + string.replace(/</g,'<').replace(/>/,'>') + '</textarea>');
$node.find('textarea:first').focus();
$node.find('textarea:first').select();
$node.find('div:last').find('button').replaceWith('<button class="dbg-copycode" type="button" title="Restore syntax highlight">Restore</button>');
$node.find('div:last').find('button').click(function() {restorePreFromText($(this).parent().parent())});
}
}
function restorePreFromText($node) {
// For Code Snippets - [AW]
$node.find('pre:first').removeAttr('class');
$node.find('textarea').remove();
$node.find('div:last').find('button').replaceWith('<button class="dbg-copycode" type="button" title="Select code example for copying">Select Code</button>');
$node.find('div:last').find('button').click(function() {nodeToCopy($(this).parent().parent())});
}
$(document).ready(function() {
// For Code Snippets - [AW]
var copybutton = 'Select Code';
var copytitle = 'Select code example for copying';
if (window.clipboardData && clipboardData.setData) {
copybutton = 'Copy Code';
copytitle = 'Copy code example to clipboard';
}
$('pre[data-code]').after('<div class="dbg-rbutton"><button class="dbg-copycode" type="button" title="' + copytitle + '">' + copybutton + '</button></div>');
$('.dbg-copycode').click(function() {nodeToCopy($(this).parent().parent())});
});
The reason I'm not using .hide() where I hide the pre block is because .hide() adds a style attribute which is forbidden under the Mozilla CSP policy the server uses, so I have to set a class attribute instead.