Jump to content

User:Grilledcheeseisgreat/testingfasterversion.js

From Wikipedia, the free encyclopedia
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.
// This script converts American English spellings into British spellings.
// PLEASE READ THE DOCUMENTATION at [[User:Ohconfucius/EngvarB]] (click on the link above) before using.

// Feedback and constructive criticism are welcome.
// Any advice on improving the scripts are especially welcome.
// *********************************************************************************************
// <syntaxhighlight lang=javascript>
/**
 * TemplateScript adds configurable templates and scripts to the sidebar, and adds an example regex editor.
 * @see https://meta.wikimedia.org/wiki/TemplateScript
 * @update-token [[File:Pathoschild/templatescript.js]]
 */
$.ajax('//tools-static.wmflabs.org/meta/scripts/pathoschild.templatescript.js', {
	dataType: 'script',
	cache: true
}).then(function () {
	pathoschild.TemplateScript.add([
		{
			category: 'EngvarB', name: 'AMERICAN', isMinorEdit: true, script: function (editor) {
				ohc_ENGVAR_set_variation(editor, "U");
			}
		},
		{
			category: 'EngvarB', name: 'BRITISH', isMinorEdit: true, script: function (editor) {
				ohc_ENGVAR_set_variation(editor, "B");
			}
		},
		{
			category: 'EngvarB', name: 'OXFORD', isMinorEdit: true, script: function (editor) {
				ohc_ENGVAR_set_variation(editor, "O");
			}
		},
		{
			category: 'EngvarB', name: 'CANADIAN', isMinorEdit: true, script: function (editor) {
				ohc_ENGVAR_set_variation(editor, "C");
			}
		}
	]);
});
// </nowiki>

/** ------------------------------------------------------------------------ **/

// PROTECTION FROM STRING SUBSTITUTION
var protected_map;

function ohc_ENGVAR_protect(editor) {
    let text = editor.get();
    protected_map = [];

    const replace_string = (match) => {
        protected_map.push(match);
        return '⍌' + (protected_map.length - 1) + '⍍';
    };

    const patterns = [
    //	/(pre)(string)(post)/gi, // template
    //	/({{Election box begin)([\s\S]*?)({{Election box end}})/gi,
	/(<blockquote>)([\s\S]*?)(<\/blockquote>)/gi,
	/(\{\{blockquote\s*\|)([\s\S]*?)(\}\})/gi,
	/(<table[^<>]*?>)([^<>]*)(<\/table>)/gi,
	/(<gallery[^<>]*?>)([^<>]*)(<\/gallery>)/gi, //may be excessively broad in protecting image legends
	/(<timeline[^<>]*?>)([^<>]*)(<\/timeline>)/gi,
	/(<span\sstyle\s*=")(color)([^>]*>)/gi,
	/(<\/?\s?|<div class=.)(center)(.?\s?>)/gi, // <center> tags
	/(\bstyle=")([^"]*?)(;")/gi,
    //	/(=\s*)(color)(\s*:#)/gi,
	/(\{)((?:font |meta |party |)color)([^|]*\|)/gi, //color box templates
	/([:'"|{]+)(color|center)([:'"|])/gi,
	/({{(?:\w*\s|)\|\s?)(colors?|center)(\s?[=|])/gi, //

	/(align\/?[ ]*=\/?[ ]*([ "'][ ]*|))(center)([ ]*[ "']|)/gi, // align="center" in tables

	/({{)(Medical cases chart\/bar colors)([^}]+{{)/gi,
	/({{)(bar percent)(\|[^}]+}})/gi,

	/(<ref[^<>]*?>)([^<>]*)(<\/ref>)/gi,
	/(<ref name=)([^<>]*)(\/>)/gi,
	/([\s(]["“])([^"“”\n]*)(["”])/gi, // double quotes
	/({[\w ]{0,12}(?:quot[^|]{1,7}\s?|sic|(?:not a |)typo|as written)\|)([^}]+)(})/gi,

	/((?:Category):)([^|\]]*)([|\]])/gi, // cats, images
	/((?:File|Image):)([^|\].]*)(\.w{3}\b)/gi, // cats, images
	/((?:image\d?|image_skyline|image[ _]location\d?|image[ _](?:map|name)|img|pic)\s*=)([^|}]*)([|}])/gi, // images within templates infoboxes etc
	/(cite[ _]encyclopedia\s*\|)/gi,
	/(url\s*=)([^|}]*)([|}])/gi, // urls within templates infoboxes etc
	/(\[https?:)([^\]]*)(])/gi,
	/(\[https?:)([^\s\]]*)([\s\]])/gi,
	/(\[\[)([^|\]]*)(\|)/gi, // pipings
	/(\[\[)([^|\]]*)(\]\])/gi, // WL
	/({(?:See ?also|Main))(\|[^}]*)(})/gi, // see also and main templates
	/({{(?:external|wide )image\s?\|)([^}]+)(})/gi,
	/({{harv\w{,3}\s?\|)([^}]+)(})/gi,
	/({{wikisource\|)([^}]+)(})/gi,
	/({{)((?:NYT|WSJ)topic\s?\|[^}]*)(}})/gi,
    //	/({{\w*)([^|=[\]}]*)(}})/gi, // templates
    //	/({Party name with colou?r)(\s+)/gi,  //template not at risk
	/({Infobox )([\w ]*(?:organization|artifact))([\s|])/gi,

// parameters
	/(\|\s*)(colors(?:_label|))(\s*=)/gi,
	/(\|\s*)(\w* colou?r\s*\w*)(\s*=)/gi,
	/(\|\s*)(organizations?)(\s*=)/gi,
	/(\|\s*)(analog)(\s*=)/gi,
	/(\|\s*)(licen[cs]e ?(?:place|date|))(\s*=)/gi,
	/(\|\s*)(cleanup|color|coordinates\w*)(\s*=)/gi, // parameters within infoboxes
	/(\|\s*)(encyclopedia|\w*colors|(?:org|rom)anization|license)(\s*=)/gi,
    //	/(\|\s*)(local[ _]authority)(\s*=)/gi,
	/\|\s*ship[ _](?:armou?r|honou?rs)\s*=/gi,

	/\|\s*(?:title|chapter)\s*=[^|}]*/gi,

	/(\|(?:[^=|{}]*))(cleanup|encyclopa?edia|enroll?ment|honorific_prefix|honors|lockup\w{1,4}|organi[sz]ation|catalog\snumber)(\s*=)/g,
	/\|\/?\s*center\s*\|/gi, // |center| in files
	/([|!]\s*style\s*=[^|]*\|)/gi,

//white list
	/(Back in the U.S.S.R.)/g, // title of work
	/(Born in the U.S.A.|National Geographic Traveler)/g, // title of work
	/(U.S. News & World Report)/g, // title of work
	/(Traveling Wilburys?|Rockefeller)/g, // proper nouns
	/(Organi[sz]ation (?:for|of) (?:the |)[A-Z]\w)/g,
	/([A-Z]\w+ Organi[sz]ation)/g,
	/(to license)/gi,  // verb
	/(Mechani[sz]ed B(?:rigade|attalion))/g,
	/(New South Wales)/g,
	/(non-cooperation)/gi,
	/(paradise)/gi,
	/(rigor mortis)/gi,
	/(solid gr[ae]y)/gi,

	// protect from hyphenation
    //	/(\\breed(?:|s)[^aeiou]|[Rr]eegan)/g,

	// other whitelisting
    //	/([Ll]ikewise)/g,
    ];

    for (const pat of patterns) {
        text = text.replace(pat, replace_string);
    }

    editor.set(text);  
}

function ohc_ENGVAR_unprotect(editor) {
    let text = editor.get();
    let prev;
    do {
        prev = text;
        text = text.replace(/⍌([0-9]+)⍍/g, (_, i) => protected_map[i]);
    } while (text !== prev);
    editor.set(text);
}

/** ------------------------------------------------------------------------ **/

function ohc_ENGVAR_plain(editor) {
	// per https://www.gov.uk/guidance/style-guide/a-to-z-of-gov-uk-style
	// redundancies
	editor.replace(/B\.B\.C\.(?=[\W])/g, 'BBC');
	editor.replace(/U\.K\.(?=[\W])/g, 'UK');
	editor.replace(/U\.N\.(?=[\W])/g, 'UK');
	editor.replace(/U\.S\.A\.(?=[\W])/g, 'USA');
	editor.replace(/U\.S\.(?=[\W])/g, 'US');
	editor.replace(/E\.U\.(?=[\W])/g, 'EU');
	editor.replace(/(fill )out/gi, '$1in');
	editor.replace(/U\.S\.S\.R\./g, 'USSR');

	// agrammatical
	editor.replace(/(compris(?:ed|ing) )of /gi, '$1');

	// old-fashioned
    //	editor.replace(/(whil)st /gi, '$1e ');
    //	editor.replace(/(among)st /gi, '$1 ');

	// hyphenation
    //	editor.replace(/(co)(ordinat(e\b|ing|ion))/g, '$1-$2');
    //	editor.replace(/\b(re)(e\w[aeiou]\w{4,})/gi, '$1-$2');
    //	editor.replace(/\b(over|under)(r\w{4,})/gi, '$1-$2');

	// capitalisation
	// rem geographical regions - too many false positives
    //	editor.replace(/(local )authority/g, '$1council');
}

// ------------------------------------------------------------------
// Productive spelling families & Pre-compiled Data Structures
// ------------------------------------------------------------------

const DOUBLE_L_STEMS = [
	"appal",
	"bevel",
	"cancel", "counsel",
	"enrol", "enthral", "equal",
	"fuel",
	"initial",
	"jewel", "journal",
	"label", "level",
	"marvel", "model",
	"panel",
	"quarrel",
	"rival",
	"signal",
	"total", "travel",
];

const DOUBLE_L_COMPILED = DOUBLE_L_STEMS.map(stem => {
    if (stem.endsWith('el')) {
        return {
            stem: stem,
            regEdOrersIng: new RegExp('\\b' + stem + '(ed|or|ers|ing)\\b', 'gi'),
            regSingleL: new RegExp('\\b' + stem + 'l(ed|er|ers|ing)\\b', 'gi')
        };
    } else {
        return {
            stem: stem,
            regEdIng: new RegExp('\\b' + stem + '(ed|ing)\\b', 'gi'),
            regSingleLAl: new RegExp('\\b' + stem + 'l(ed|ing)\\b', 'gi')
        };
    }
});

const IZE_ISE_RE = /\b([a-z]{3,}(?:al|en|an|on|ar|or|er|[aeiou][bcdfghjklmnpqrtvwxyz]))iz(e[drs]?|ations?|abl[ey]|ing)\b/gi;
const NON_SUFFIX_ISE = /\b(?:advert|ar|chast|circumc|compr(?:om|)|de[mn]|desp|dev|disgu|ex(?:er|)c|franch|inc|likew|pr[eo]m|repr|rev|superv|surpr|telev)/i;

function convertDoubleL(editor) {
    let text = editor.get();
    DOUBLE_L_COMPILED.forEach(item => {
        if (item.regEdOrersIng) {
            text = text.replace(item.regEdOrersIng, item.stem + 'l$1');
        } else if (item.regEdIng) {
            text = text.replace(item.regEdIng, item.stem + 'l$1');
        }
    });
    editor.set(text);
}

function restoreSingleL(editor) {
	let text = editor.get();
    DOUBLE_L_COMPILED.forEach(item => {
        if (item.regSingleL) {
            text = text.replace(item.regSingleL, item.stem + '$1');
        } else if (item.regSingleLAl) {
            text = text.replace(item.regSingleLAl, item.stem + '$1');
        }
    });
    editor.set(text);
}

function convertIse(editor) {
    let text = editor.get();
    const MARKER = '\uE000';

    text = text.replace(
        /\b([a-z]{3,}(?:al|en|an|on|ar|or|er|[aeiou][bcdfghjklmnpqrtvwxyz]))iz(e[drs]?|ations?|abl[ey]|ing)\b/gi,
        (m, stem, suffix) => {
            if (NON_SUFFIX_ISE.test(stem)) return m;
            return stem + MARKER + 'is' + suffix;
        }
    );

    text = text.replace(/\b(emphas|real|recogn|synthes)iz(e[drs]?|ing)\b/gi,  '$1' + MARKER + 'is$2');
    text = text.replace(new RegExp(MARKER, 'g'), '');
    editor.set(text);
}

function restoreIze(editor) {
    let text = editor.get();
    text = text.replace(
        /\b([a-z]{3,}(?:al|en|an|on|ar|or|er|ic|ur|[aeiou][bcdfghjklmnpqrtvwxyz]))is(e[drs]?|ations?|abl[ey]|ing)\b/gi,
        (m, stem, suffix) => {
            if (NON_SUFFIX_ISE.test(m)) return m;
            return stem + 'iz' + suffix;
        }
    );
    text = text.replace(/\b(emphas|real|recogn|synthes)is(e[drs]?|ing)\b/gi,  '$1iz$2');
    editor.set(text);
}

// ------------------------------------------------------------------
// Pre-compiled Translation Tables for simple_a, simple_b, simple_c
// ------------------------------------------------------------------

const TABLE_A_ENTRIES = Object.entries({
    'ageing':               '$1aging',
    'aluminium':            '$1aluminum',
    '(adrenalin)e\\b':      '$1$2',
    '(annex)e\\b':          '$1$2',
    'artefact':             '$1artifact',
    '(ana|breatha|cata|hydro|para)lys(e[ds]?|ing)': '$1$2lyz$3',
    'bau(lk)': 				'$1ba$2',
    'diarrhoea': 			'$1diarrhea',
    '(de|of)fence': 		'$1$2fense',
    'licence': 				'$1license',
    '(licen)c(ing|ed)': 	'$1$2s$3',
    'per cent\\b': 			'$1percent',
    '(practi)s(ing|ed)': 	'$1$2c$3',
    '(furor)e\\b': 			'$1$2',
    '(light-|dark-|\\b)grey': '$1$2gray',
    'guerilla': 			'$1guerrilla',
    'jewellery': 			'$1jewelry',
    '(judg)e(ment)':        '$1$2$3',
    'manoeuvr(ab|ed?|ing)': '$1maneuver$2',
    'louv(red|ring)': 		'$1louve$2',
    'louvre': 				'$1louver',
    'paed(iatric|ophil)': 	'$1ped$2',
    'encyclopaedi(a|c)': 	'$1encyclopedi$2',
    'sceptic': 				'$1skeptic',
    'mollusc': 				'$1mollusk',
    'vapour(s?)\\b': 		'$1vapor$2',
    'liquorice': 			'$1licorice',

    // composite words
    '(break|drop|clean|line|lock|pick)-(out|up)': '$1$2$3',

    // words terminating in double l (US/Can)
    '(app|enthr)al\\b': 	'$1$2all',
    '(enrol)\\b': 			'$1$2l',
    '(fulf|inst)il\\b': 	'$1$2l',

    // oe/ae words
    'gynaeco': 				'$1gyneco',
    'haemo(gl|ly|ph|rr)': 	'$1hemo$2',
    'orthopaedic': 			'$1orthopedic',
//  'archaeo': '$1archeo', // disabling per user:coffeeandcrumbs (21/8/2018)
    'palaeonto': 			'$1paleonto',
    'oenology': 			'$1enology',
    'oesophag': 			'$1esophag',
    'oestrogen': 			'$1estrogen',
    '(an|)aesthe(sia|tic|tist)': '$1$2esthe$3',
    'homoeopath': 			'$1homeopath',
    '(omelet)te\\b': 		'$1$2',
    'rigour\\b': 			'$1rigor',
    '(an|leuk|septic|tox)aemi(a|c)': '$1$2emi$3',

    // 'f' words
    //'(S|s)ulfur': '$1$2ulphur',  //disabled per WP:ARTCOM

    'any more': 			'$1anymore',
    'speciality': 			'$1specialty',
    '(burgl)ari[sz](e[ds]?|ing)': '$1$2$3',

    // non-redundant e
    '((?:un|)(?:lik|liv|rat|sal|siz|shak))e(able)': '$1$2$3',

    // '~logu~' words
    '(ana|cata|epi|homo|mono|pro)logue([ds]?)\\b': '$1$2log$3', // removing "dialogue" per user:coffeeandcrumbs (21/8/2018)
    '(ana|cata|epi|homo|mono|pro)logu(ing)\\b': '$1$2log$3', // removing "dialogue" per user:coffeeandcrumbs (21/8/2018)

    // '~our' words
    '((?:un|)(?:arm|clam|harb|rum|savi?|tum))our(ed|ful|ing|less|ly|s?)\\b': '$1$2or$3', // removing "glamour" per user:coffeeandcrumbs (21/8/2018)
    '((?:un|)(?:arm|sav))our(ies|y|s?)\\b': '$1$2or$3',
    '(cand|col|flav|hum|od)our(ed|ful|fully|ings?|less|lessly|s?)\\b': '$1$2or$3',
    'neighbour(hood|ing|s?)': '$1neighbor$2',
    'behaviour(al|s?)\\b': '$1behavior$2',
    'favour(abl[ey]|ed|i[\\w]*|s?)\\b': '$1favor$2',
    'honour(abl[ey]|ed|ing|s?)\\b': '$1honor$2',
    '(endeav|lab)our(e[dr]|ing|s?)\\b': '$1$2or$3',
    'moul(d|t)(ed|ing|s?)\\b': '$1mol$2$3',

    // '~re~' words
    '(calib|fib|goit|lust|mit|nit|och|reconnoit|sab|saltpet|spect|theat|tit)re(d|ing|s?)': '$1$2er$3',
    '(centi|kilo|micro|milli|nano|-|hundred\\s|\\d\\s)metre': '$1$2meter',
    '(centi|milli|deci|pico|hecto|\\b)litre(s?)': '$1$2liter$3',
    '(mono)logue(s?)': '$1$2log$3', //rem "demagog"; rem "synagog" and "pedagog" June 2025
}).map(([word, replacement]) => ({
    regex: new RegExp('([ \\|\\[\\*])' + word, 'g'),
    replacement: replacement
}));

const TABLE2_A_ENTRIES = Object.entries({
    '([^\\w\\d\\-\\/=:])(col)our(\\W)': '$1$2our$3',
    '([^\\w\\d\\-\\/=:])(cent|epicent|recent)re(ed|ing)': '$1$2er$3',
    '([^\\w\\d\\-\\/=:])(cent|epicent|recent)re(s?)\\b': '$1$2er$3',
    '([ \\|\\[])(counc[ie])ll(e[dr]|ing|ors?)\\b': '$1$2l$3',
    '\\b([a-zA-Z]{3,})([^l])l(ful|ment)\\b': '$1$2ll$3',
}).map(([word, replacement]) => ({
    regex: new RegExp(word, 'g'),
    replacement: replacement
}));

function ohc_ENGVAR_simple_a(editor) {
    let text = editor.get();  
    for (const entry of TABLE_A_ENTRIES) {
        text = text.replace(entry.regex, entry.replacement);
    }
    for (const entry of TABLE2_A_ENTRIES) {
        text = text.replace(entry.regex, entry.replacement);
    }
    editor.set(text);  
	restoreSingleL(editor);
}

const TABLE_B_ENTRIES = Object.entries({
    'aging': '$1ageing',
    'aluminum': '$1aluminium',
    '(adrenalin)\\b': '$1$2e',
    '((?:an|the) annex)\\b': '$1$2e',
    'artifact': '$1artefact',
    '(ana|breatha|cata|hydro|para)lyz(e[ds]?|ing)': '$1$2lys$3',
    '(ba)(lk)': '$1$2u$3',
    'diarrhea': '$1diarrhoea',
    '(de|of)fense': '$1$2fence',
    'license': '$1licence',
    '(licen)c(ing|ed)': '$1$2s$3',
    'percent\\b': '$1per cent',
    'plow(s|ing|)\\b': '$1plough$2',
    '(practi)c(ing|ed)': '$1$2s$3',
    '(furor)\\b': '$1$2e',
    '(light-|dark-|\\b)gray': '$1$2grey',
    'guerilla': '$1guerrilla',
    'jewelry': '$1jewellery',
    '(judg)(ments?(?:al|))': '$1$2e$3',
    'maneuver(ab|ed|ing)': '$1manoeuvr$2',
    'maneuver': '$1manoeuvre',
    'meager': '$1meagre',
    'louve(red|ring)': '$1louv$2',
    '(louv|somb)er': '$1$2re',
    'ped(iatric|ophil)': '$1paed$2',
    'encyclopedi(a|c)': '$1encyclopaedi$2',
    'skeptic': '$1sceptic',
    'mollusk': '$1mollusc',
    'vapor(s?)\\b': '$1vapour$2',
    'liquorice': '$1liquorice',

    // composite words
    '(break|drop|clean|line|lock|pick)(out|up)': '$1$2-$3',

    // words terminating in double l
    '(app|enthr)all\\b': 	'$1$2al',
    '(enrol);\\b': 			'$1$2',
    '(fulf|inst)il;\\b': 	'$1$2',

    // oe/ae words
    'gyneco': '$1gynaeco',
    'hemo(globin|ly|phil|rr)': '$1haemo$2',
    'orthopedic': '$1orthopaedic',
    'archeo': '$1archaeo',
    'paleonto': '$1palaeonto',
    'enology': '$1oenology',
    'esophag': '$1oesophag',
    'estrogen': '$1oestrogen',
    '(an|)esthe(sia|tic|tist)': '$1$2aesthe$3',
    'anesthesiologist': '$1anaesthetist',
    'homeopath': '$1homoeopath',
//  'medieval\\b': '$1mediaeval',
    '(omelet)\\b': '$1$2te',
    'rigor\\b': '$1rigour',
    '(an|leuk|septic|tox)emi(a|c)': '$1$2aemi$3',

    // 'f' words
    //'(S|s)ulfur': '$1$2ulphur',  //disabled per WP:ARTCOM

    // vernacular
    'anymore': '$1any more',
    'speciality': '$1speciality',
    '(burgl)ari[sz](e[ds]?|ing)': '$1$2$3',
    'movie theat(er|re)': '$1cinema',
    'sidewalk': '$1pavement',

    // non-redundant e
    '((?:un|)(?:lik|liv|rat|sal|siz|shak))(able)': '$1$2e$3',

    // '~logu~' words
    '(ana|cata|dia|epi|homo|mono|pro)log(s|)\\b': '$1$2logue$3',
    '(cata|dia)loge?(ed|ing)\\b': '$1$2logu$3',

    // '~our' words
    '(arm|clam|glam|harb|rum|savi?|tum)or(ed|ful|ing|less|ly|s?)\\b': '$1$2our$3',
    '(arm|sav)or(ies|y|s?)\\b': '$1$2our$3',
    '(cand|col|flav|hum|od)or(ed|ful|fully|ings?|less|lessly|s?)\\b': '$1$2our$3',
    'neighbor(hood|ing|s?)': '$1neighbour$2',
    'behavior(al|s?)\\b': '$1behaviour$2',
    '(favo|hono)r(abl[ey]|ed|ing|s?)\\b': '$1$2ur$3',
    '(endeav|lab)or(e[dr]|ing|s?)\\b': '$1$2our$3',
    'mol(dy?|t)(ed|ing|s?)\\b': '$1moul$2$3',

    // '~re~' words
    '(calib|fib|goit|lust|mit|nit|och|reconnoit|sab|saltpet|spect|theat|tit)er(s?)\\b': '$1$2re$3',
    '(calib|fib|goit|lust|mit|nit|reconnoit|sab|saltpet|spect|theat|tit)er(ed|ing)': '$1$2r$3',
    '(\\b(?:[2-9]|\\d{2,3}|half|quarter|two|three|four|five|six|seven|eight|nine|ten)\\b) (lit|(?:kilo|)met)er\\b': '$1$2-$3re',
    '(centi|kilo|micro|milli|nano|-|hundred\\s|\\d\\s)meter': '$1$2metre',
    '(centi|milli|deci|pico|hecto|\\b)liter(s?)\\b': '$1$2litre$3',
    '(dema|peda|mono|syna)gog(s?)\\b': '$1$2gogue$3',
    '(\\b(?:[2-9]|\\d{2,3}|one|two|three|four|five|six|seven|eight|nine|ten)\\b) story': '$1$2-storey',

    // '~l' words where the 'l' doubles as past and present participle
    '(counc[ie])l(e[dr]|ing|ors?)\\b': '$1$2ll$3',
    '\\b([a-zA-Z]{3,})([^l])ll(ful|ment)\\b': '$1$2l$3',
}).map(([word, replacement]) => ({
    regex: new RegExp('([ \\|\\[\\*])' + word, 'g'),
    replacement: replacement
}));

const TABLE2_B_ENTRIES = Object.entries({
    '( [\\w\\D]*\\-)(col|flav|hum)ored': '$1$2oured',
    '([^\\w\\d\\-\\/=:])(col)or(\\W)': '$1$2our$3',
    '([^\\w\\d\\-\\/=:])(cent|epicent|recent)er(ed|ing)': '$1$2r$3',
    '([^\\w\\d\\-\\/=:])(cent|epicent|recent)er(s?)\\b': '$1$2re$3',
    '\\b([a-zA-Z]*)ll(ful|ment)\\b': '$1l$2',
}).map(([word, replacement]) => ({
    regex: new RegExp(word, 'g'),
    replacement: replacement
}));

function ohc_ENGVAR_simple_b(editor) {
    let text = editor.get();
    for (const entry of TABLE_B_ENTRIES) {
        text = text.replace(entry.regex, entry.replacement);
    }
    for (const entry of TABLE2_B_ENTRIES) {
        text = text.replace(entry.regex, entry.replacement);
    }
    editor.set(text);
	editor.replace(/₤ ?(\d)/g, '£$1');
    editor.replace(/\b(vice) (president|chairman|chancellor|minister)/gi, '$1-$2');
	convertDoubleL(editor);
}

const TABLE_C_ENTRIES = Object.entries({
    'ageing': '$1aging',
    'aluminum': '$1aluminium',
    '(adrenalin)\\b': '$1$2e',
    '((?:an|the) annex)\\b': '$1$2e',
    '(ana|breatha|cata|hydro|para)lyz(e[ds]?|ing)': '$1$2lys$3',
    '(ba)u(lk)': '$1$2$3',
    '(de|of)fense': '$1$2fence',
    'license': '$1licence',
    '(licen)c(ing|ed)': '$1$2s$3',
    'percent\\b': '$1per cent',
    '(practi)s(ing|ed)': '$1$2c$3',
    '(furor)\\b': '$1$2e',
    '(light-|dark-|\\b)gray': '$1$2grey',
    'guerilla': '$1guerrilla',
    'maneuver(ab|ed|ing)': '$1manoeuvr$2',
    'maneuver': '$1manoeuvre',
    'louve(red|ring)': '$1louv$2',
    'louver': '$1louvre',
    'encyclopaedi(a|c)': '$1encyclopedi$2',
    'skeptic': '$1sceptic',
    'mollusk': '$1mollusc',
    'vapor(s?)\\b': '$1vapour$2',
    'liquorice': '$1licorice',

    // composite words
//  'onstage': '$1on-stage',
    '(break|drop|clean|line|lock|pick)(out|up)': '$1$2-$3',

    // words terminating in double l (US/Can)
    '(app|enthr)al\\b': 	'$1$2all',
    '(enrol)\\b': 			'$1$2l',
    '(fulf|inst)il\\b': 	'$1$2l',

    // oe/ae words
    'anaesthesiologist': '$1anesthetist',
    '(an)aesthe(sia|tic|tist)': '$1$2esthe$3',
    'archaeo': '$1archeo',
    'diarrhoea': '$1diarrhea',
    'foetus': '$1fetus',
    'gyneco': '$1gynaeco',
    'haemo(globin|ly|phil|rr)': '$1haemo$2',
    'orthopaedic': '$1orthopedic',
    'oenology': '$1enology',
    'oesophag': '$1oesophag',
    'oestrogen': '$1oestrogen',
    'homoeopath': '$1homeopath',
    '(omelet)\\b': '$1$2te',
    'paed(iatric|ophil)': '$1ped$2',
    'palaeonto': '$1paleonto',
    'rigor(ous|)\\b': '$1rigour$2',
    '(an|leuk|septic|tox)aemi(a|c)': '$1$2emi$3',

    // 'f' words
    //'(S|s)ulfur': '$1$2ulphur',  //disabled per WP:ARTCOM

    'anymore': '$1any more',
    'speciality': '$1specialty',

    // non-redundant e
    '((?:un|)(?:lik|liv|rat|sal|siz|shak))(able)': '$1$2e$3',

    // '~logu~' words
    '(ana|cata|dia|homo|mono|pro)log(ed|ing|s?)\\b': '$1$2logue$3',

    // '~our' words
    '(arm|clam|glam|harb|rum|savi?|tum)or(ed|ful|ing|less|ly|s?)\\b': '$1$2our$3',
    '(arm|sav)or(ies|y|s?)\\b': '$1$2our$3',
    '(cand|col|flav|hum|od)or(ed|ful|fully|ings?|less|lessly|s?\\W)': '$1$2our$3',
    'neighborhood': '$1neighbourhood',
    'behavior(al|s?)\\b': '$1behaviour$2',
    'favor(abl[ey]|ed|i[\\w]*|s?)\\b': '$1favour$2',
    'honor(abl[ey]|ed|ing|s?)\\b': '$1honour$2',
    '(endeav|lab)or(e[dr]|ing|s|\\W)': '$1$2our$3',
    'mol(dy?|t)(ed|ing|s?)\\b': '$1moul$2$3',

    // '~re~' words
    '(calib|fib|goit|lust|mit|nit|och|reconnoit|sab|saltpet|spect|theat|tit)er(s?)\\b': '$1$2re$3',
    '(calib|fib|goit|lust|mit|nit|reconnoit|sab|saltpet|spect|theat|tit)er(ed|al|ing)': '$1$2r$3',
    '(centi|kilo|micro|milli|nano|-|hundred\\s|\\d\\s)meter': '$1$2metre',
    '(centi|milli|deci|pico|hecto|\\b)liter(s?)\\b': '$1$2litre$3',
    '(dema|peda|mono|syna)gog(s?)\\b': '$1$2gogue$3',

    // '~l' words where the 'l' doubles as past and present participle
    '\\b(counc[ie])l(e[dr]|ing|ors?)\\b': '$1$2ll$3',
    '\\b([a-z]*)ll(ful|ment)\\b': '$1l$2',
}).map(([word, replacement]) => ({
    regex: new RegExp('([ \\|\\[\\*])' + word, 'g'),
    replacement: replacement
}));

const TABLE2_C_ENTRIES = Object.entries({
    '( [\\w\\D]*\\-)(col|flav|hum)ored': '$1$2oured',
    '([^\\w\\d\\-\\/=:])(col)or(\\W)': '$1$2our$3',
    '([^\\w\\d\\-\\/=:])(cent|epicent|recent)er(ed|ing)': '$1$2r$3',
    '([^\\w\\d\\-\\/=:])(cent|epicent|recent)er(s?)\\b': '$1$2re$3',
}).map(([word, replacement]) => ({
    regex: new RegExp(word, 'g'),
    replacement: replacement
}));

function ohc_ENGVAR_simple_c(editor) {
    let text = editor.get();
    for (const entry of TABLE_C_ENTRIES) {
        text = text.replace(entry.regex, entry.replacement);
    }
    for (const entry of TABLE2_C_ENTRIES) {
        text = text.replace(entry.regex, entry.replacement);
    }
    editor.set(text);
	convertDoubleL(editor);
}

function ohc_ENGVAR_set_variation(editor, variation) {
    ohc_ENGVAR_protect(editor);
    let before = editor.get();
    if (variation == "U") { ohc_ENGVAR_simple_a(editor); restoreIze(editor); }
    if (variation == "B") { ohc_ENGVAR_simple_b(editor); convertIse(editor); }
    if (variation == "C") { ohc_ENGVAR_simple_c(editor); restoreIze(editor); }
    if (variation == "O") { ohc_ENGVAR_simple_b(editor); restoreIze(editor); }

    let after = editor.get();
    if (after !== before && variation !== "U") { ohc_ENGVAR_plain(editor); }

    ohc_ENGVAR_unprotect(editor);
    ohc_retask_pipes(editor);
    ohc_ENGVAR_insert_template(editor, variation);
    ohc_Reorder_template(editor);
    ohc_ENGVAR_edit_summary(editor, variation);
    editor.clickDiff();
}

/** ------------------------------------------------------------------------ **/

function ohc_retask_pipes(editor) {
	editor.replace(/([^\w\-.]\[\[)(?:(?:[a-zA-Z]+? |)[a-zA-Z]+?[^s ]i[sz]ation)\|((?:[a-zA-Z]+? |)[a-zA-Z]{3,12}[^s ]i[sz](?:e[drs]?|ations?|abl[ey]|ing))/g, '$1$2');
//	editor.replace(/(empha|synthe)siz(e|ing)/g, '$1sis$2');
}

/** ------------------------------------------------------------------------ **/

function month_year() {
    const monthMap = [
        'January', 'February', 'March', 'April', 'May', 'June',
        'July', 'August', 'September', 'October', 'November', 'December'
    ];
    const now = new Date();
    return `${monthMap[now.getMonth()]} ${now.getFullYear()}`;
}

function remove_deprecated(editor) {
    const deprecatedMatcher = /\{\{\s*Engvar(?:A|B|C)[^}]*\}\}\s*/gi;
    editor.replace(deprecatedMatcher, '');
    return editor;
}

function ohc_ENGVAR_insert_template(editor, variant) {
    editor = remove_deprecated(editor);  
    const currentDate = month_year();

    const PRESERVE = {
        'U': ['Use American English', 'Use Philippine English'],
        'B': [
            'Use Australian English', 'Use Ghanaian English', 'Use Hiberno-English',
            'Use Hong Kong English', 'Use Indian English', 'Use New Zealand English',
            'Use Nigerian English', 'Use Pakistani English', 'Use South African English', 'Use British English'
        ],
        'C': ['Use Canadian English'],
        'O': ['Use Oxford spelling']
    };

    const DEFAULT_TEMPLATE = {
        'U': 'Use American English',
        'B': 'Use British English',
        'C': 'Use Canadian English',
        'O': 'Use Oxford spelling'
    };

    const ALL_USE_TEMPLATES = [
		'Use American English', 'Use Australian English', 'Use British English',
		'Use Canadian English', 'Use Ghanaian English', 'Use Hiberno-English',
		'Use Hong Kong English', 'Use Indian English', 'Use New Zealand English',
		'Use Nigerian English', 'Use Oxford spelling', 'Use Pakistani English',
		'Use Philippine English', 'Use South African English'
	];

    const preserveList = PRESERVE[variant] || [];
    const defaultTpl = DEFAULT_TEMPLATE[variant];

    const escapedNames = ALL_USE_TEMPLATES
        .map(n => n.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
                   .replace(/\s+/g, '[\\s\\-]+'))
        .join('|');

    const anyTplRe = new RegExp(
        '\\{\\{\\s*(?:Template\\s*:\\s*)?(' + escapedNames + '|EngvarB)' +
        '(\\s*\\|[^}]*)?\\}\\}',
        'gi'
    );

    let preservedTemplateFound = null;   
    let text = editor.get();
    let scanMatch;
    const reScan = new RegExp(anyTplRe.source, 'gi');   
    while ((scanMatch = reScan.exec(text)) !== null) {
        const name = scanMatch[1].trim().replace(/[\s\-]+/g, ' ');   
        if (preserveList.some(p => p.toLowerCase() === name.toLowerCase())) {
            preservedTemplateFound = name;
            break;
        }
    }

    let insertionDone = false;
    text = text.replace(new RegExp(anyTplRe.source, 'gi'),
        function (match, rawName, paramStr) {
            const name = rawName.trim().replace(/[\s\-]+/g, ' ');
            const isEngvarB = /^EngvarB$/i.test(name);

            if (isEngvarB) {
                if (variant === 'B') {
                    return updateDate(match, name, paramStr, currentDate);
                } else {
                    return '';   
                }
            }

            const nameLC = name.toLowerCase();
            const isPreserved = preserveList.some(p => p.toLowerCase() === nameLC);

            if (isPreserved) {
                if (!insertionDone) insertionDone = true;
                return updateDate(match, name, paramStr, currentDate);
            }

            if (!insertionDone && !preservedTemplateFound) {
                insertionDone = true;
                return '{{' + defaultTpl + '|date=' + currentDate + '}}';
            }

            return '';  
        }
    );

    editor.set(text);

    if (!insertionDone) {
        const newTpl = '{{' + defaultTpl + '|date=' + currentDate + '}}';
        const shortdescRe = /\{\{\s*short\s+description\s*\|[^}]+\}\}\s*(\r?\n)?/i;

        if (editor.contains(shortdescRe)) {
            editor.replace(shortdescRe, m => m + newTpl + '\n');
        } else {
            editor.prepend(newTpl + '\n');
        }
    }
}

function updateDate(originalMatch, name, paramStr, newDate) {
    let params = (paramStr || '').replace(/^\|/, '').split('|');
    let paramMap = {};

    for (const p of params) {
        const eq = p.indexOf('=');
        if (eq !== -1) {
            const k = p.slice(0, eq).trim();
            const v = p.slice(eq + 1).trim();
            paramMap[k] = v;
        } else if (p.trim()) {
            paramMap[p.trim()] = true;
        }
    }

    paramMap['date'] = newDate;

    const paramString = Object.entries(paramMap)
        .map(([k, v]) => v === true ? k : k + '=' + v)
        .join('|');

    return '{{' + name + '|' + paramString + '}}';
}

function ohc_Reorder_template(editor) {
    editor.replace(/(\{\{Use \w+ (?:spelling|English) ?\|[^}]+\}\}\n?)(?:\{\{(?:(?!\}\})[\s\S])*\}\}\n?)*(\{\{[Ss]hort description ?\|[^}]+\}\}(?:<!--[^>]+-->)?\n?)/g, '$3$2$1');
}

function ohc_ENGVAR_edit_summary(){
	//Add a tag to the summary box
//	setoptions(minor='true');
	setreason('per [[WP:ENGVAR]] by [[User:Ohconfucius/script/EngvarB|script]]', 'append');
//	doaction('save');
}
// </syntaxhighlight>