User:Gerbrant/edit/autoReplace.js

From OpenWetWare
Jump to: navigation, search
new function()
{
	var settings, libsToLoad = 1, multiR, regexR, self = this;

	if(wgCanonicalNamespace == "Talk" ||
		wgCanonicalNamespace.slice(-5) == "_talk") return;

	try{  settings = Gerbrant.edit.autoReplace;  }catch(nosettings){}
	if(!settings) settings = {};

	this.show = function()
	{
		regexR.replace(multiR.getRE(), function(a)
		{
			return a != multiR.handler.apply(multiR, arguments);
		}, multiR.handler);
	};
	this.caption = "AutoReplace";

	this.diag = function()
	{
		if(libsToLoad >= 0) alert("Couldn't load all libraries.");
		else alert("All libraries are loaded.");
	};

	function libFinished()
	{
		if(--libsToLoad < 0) self.show();
		if(multiR && regexR) module("Gerbrant.edit.autoReplace", self);
	}

	loadModule("Gerbrant.edit.multiReplace", function(mr)
	{
		var lib, i;
		multiR = new mr;
		libFinished();

		function loadDefs(defs)
		{
			var i, def;
			for(i in defs)
			{
				def = defs[i];
				multiR.add(def.re, def.hf);
			}
		}

		function loadReplLib(libName)
		{
			libsToLoad++;
			loadModule(libName, function(defs)
			{
				loadDefs(defs);
				libFinished();
			});
		}

		if(!settings.noDefault) loadReplLib("Gerbrant.edit.autoReplace.default");

		lib = settings.lib;
		if(lib) for(i in lib) loadReplLib(lib[i]);

		lib = settings.defs;
		if(lib) loadDefs(lib);
	});

	loadModule("Gerbrant.edit.regexReplace", function(rr)
	{
		regexR = rr;
		libFinished();
	});
}