User:Gerbrant/edit/selection.js

module("Gerbrant.edit.selection", new function()

{

if(document.selection && !is_gecko) // IE

this.replaceTextareaSelection = function(t, f)

{

t.focus();

var r = document.selection.createRange()

var selText = r.text;

if(f) r.text = f(selText);

return selText;

}

else // Others

this.replaceTextareaSelection = function(t, f)

{

var start = t.selectionStart;

if(start == undefined) (function(m)

{

alert(m);

throw new Error(m);

})("Can't access the selection in textareas because your browser neither supports document.selection for this, nor does it support selectionStart and selectionEnd.");

var end = t.selectionEnd;

var text = t.value;

var selText = text.substring(start, end);

if(f)

{

var scrollTop = t.scrollTop;

var newText = f(selText);

t.value = text.substring(0, start) + newText + text.substring(end);

t.scrollTop = scrollTop;

t.selectionEnd = (t.selectionStart = start) + newText.length;

setTimeout(function()

{

t.selectionEnd = (t.selectionStart = start) + newText.length;

}, 0);

}

return selText;

}

this.replaceSelection = function(f)

{

return this.replaceTextareaSelection(document.getElementById("wpTextbox1"), f);

}

});