I'm writing a user script to edit the whole html page: one of the features I will include would allow to edit the selected text as raw HTML. This look easy, just insert<xmp>
at the beginning of the selection, and </xmp>
at the end.
// from https://stackoverflow.com/a/8288313/2284570
var insertHtmlBeforeSelection, insertHtmlAfterSelection;
(function() {
function createInserter(isBefore) {
return function(html) {
var sel, range, node;
if (window.getSelection) {
// IE9 and non-IE
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = window.getSelection().getRangeAt(0);
range.collapse(isBefore);
// Range.createContextualFragment() would be useful here but is
// non-standard and not supported in all browsers (IE9, for one)
var el = document.createElement("div");
el.innerHTML = html;
var frag = document.createDocumentFragment(), node, lastNode;
while ( (node = el.firstChild) ) {
lastNode = frag.appendChild(node);
}
range.insertNode(frag);
}
} else if (document.selection && document.selection.createRange) {
// IE < 9
range = document.selection.createRange();
range.collapse(isBefore);
range.pasteHTML(html);
}
}
}
insertHtmlBeforeSelection = createInserter(true);
insertHtmlAfterSelection = createInserter(false);
})();
function ConvertToRaw() {
insertHtmlBeforeSelection('<xmp>');
insertHtmlAfterSelection('<xmp>');
}
This would be invoked by alt+c when text is selected. invoking alt+c again would remove the<xmp>
tags which would have resulted to rendered version back.
Since the<xmp>
tag is deprecated, how I can do this by scripting? If I encode the characters, it would be hard to decode them back without affecting previous ones...