User:Quarl/autoreplace.js

// User:Quarl/autoreplace.js - provides capability to replace strings (regular expressions) in edit boxes on submission.

// Strings between ... are not replaced.

// depends: wikipage.js, wikiedit.js, util.js

// recommends: smartsubmit.js

// external entry points:

// autoreplace.addReplacement("string", "replacement" || replacement_function);

// quarl 2006-01-04 initial version

// test:

// javascript:alert(autoreplace_replace_string_nonowiki("2 x 3 4 x 5 6", "x", "XXX"))

// javascript:alert(autoreplace_replace_strings("a ~~"+"~~ foo ~~"+"~~"))

//

autoreplace = new Object();

autoreplace.enabled = true;

autoreplace.replacements = Array();

// add a replacement

autoreplace.addReplacement = function(str, replacement) {

autoreplace.replacements.push([str,replacement]);

}

// deprecated

autoreplace_add = autoreplace.addReplacement;

autoreplace.fToStr = function(t) {

if (typeof t == 'function') t = t();

return ""+t;

}

autoreplace.replaceString = function(text, str, replacement) {

return text.replace(new RegExp(str,'g'), replacement);

}

autoreplace.replaceStringNoNowiki = function(text, str, replacement) {

var rtext = '';

while ( text.match(/(?:.|\n)*?<\/nowiki>|/) ) {

// save these before they get clobbered!

var left = RegExp.leftContext;

var match = RegExp.lastMatch;

var right = RegExp.rightContext;

rtext += autoreplace.replaceString(left, str, replacement) + match;

text = right;

}

rtext += autoreplace.replaceString(text, str, replacement)

return rtext;

}

autoreplace.replaceStrings = function(text) {

if (!text) return text;

for (i in autoreplace.replacements) {

r = autoreplace.replacements[i];

text = autoreplace.replaceStringNoNowiki(text, r[0], autoreplace.fToStr(r[1]));

}

return text;

}

autoreplace.preSubmitHook = function(editor, data, button) {

if (!autoreplace.enabled) return;

if (!data.wpTextbox1) return;

data.wpTextbox1 = autoreplace.replaceStrings(data.wpTextbox1);

}

autoreplace.load = function() {

WikiEditor.addPreSubmitHook(autoreplace.preSubmitHook);

}

$(autoreplace.load);

//