User:Alex Smotrov/inserttags.js
Appearance
Code that you insert on this page could contain malicious content capable of compromising your account. If you import a script from another page with "importScript", "mw.loader.load", "iusc", or "lusc", take note that this causes you to dynamically load a remote script, which could be changed by others. Editors are responsible for all edits and actions they perform, including by scripts. User scripts are not centrally supported and may malfunction or become inoperable due to software changes. A guide to help you find broken scripts is available. If you are unsure whether code you are adding to this page is safe, you can ask at the appropriate village pump. This code will be executed when previewing this page. |
Documentation for this user script can be added at User:Alex Smotrov/inserttags. |
//see [[User:Alex Smotrov/insertTags()]]
function insertTags(tagOpen, tagClose, sampleText) {
var txtarea = document.editform.wpTextbox1;
var selText, isSample = false;
if (document.selection && document.selection.createRange) { // IE/Opera
//save window scroll position
var winScroll = document.documentElement.scrollTop;
//get current selection
txtarea.focus();
var range = document.selection.createRange();
selText = range.text;
//insert tags
checkSelectedText();
range.text = tagOpen + selText + tagClose;
//mark sample text as selected
if (isSample && range.moveStart){
if (window.opera) tagClose = tagClose.replace(/\n/g,'');
range.moveStart('character', - tagClose.length - selText.length);
range.moveEnd('character', - tagClose.length);
}
range.select();
//restore window scroll position
document.documentElement.scrollTop = winScroll
} else if (txtarea.selectionStart || txtarea.selectionStart == '0') { // Mozilla
//save textarea scroll position
var textScroll = txtarea.scrollTop;
//get current selection
txtarea.focus();
var startPos = txtarea.selectionStart;
var endPos = txtarea.selectionEnd;
selText = txtarea.value.substring(startPos, endPos);
//insert tags
checkSelectedText();
txtarea.value = txtarea.value.substring(0, startPos)
+ tagOpen + selText + tagClose
+ txtarea.value.substring(endPos, txtarea.value.length);
//set new selection
if (isSample) {
txtarea.selectionStart = startPos + tagOpen.length;
txtarea.selectionEnd = startPos + tagOpen.length + selText.length;
} else {
txtarea.selectionStart = startPos + tagOpen.length + selText.length + tagClose.length;
txtarea.selectionEnd = txtarea.selectionStart;
}
//restore textarea scroll position
txtarea.scrollTop = textScroll;
}
function checkSelectedText(){
if (!selText) {
selText = sampleText;
isSample = true;
} else if (selText.charAt(selText.length - 1) == ' ') { //exclude ending space char
selText = selText.substring(0, selText.length - 1);
tagClose += ' '
}
}
}