Jump to content

User:Cleared as filed/autoreplace.js

From Wikipedia, the free encyclopedia
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
// [[User:Quarl/autoreplace.js]] - provides capability to replace strings (regular expressions) in edit boxes on submission.
//    Strings between <nowiki> ... </nowiki> 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 <nowiki> 4 x 5 </nowiki> 6", "x", "XXX"))
//   javascript:alert(autoreplace_replace_strings("a ~~"+"~~ foo <nowiki>~~"+"~~</nowiki>"))

// <pre><nowiki>

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(/<nowiki>(?:.|\n)*?<\/nowiki>|<!--(?:.|\n)*?-->/) ) {
        // 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);
}

addOnloadHook(autoreplace.load);

// </nowiki></pre>