Jump to content

User:Erutuon/scripts/footnoteCleanup.js

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Erutuon (talk | contribs) at 23:01, 19 May 2017 (verbal agreement). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
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.
var namespaceNumber = mw.config.values.wgNamespaceNumber;

if ( namespaceNumber === 0 )
{
	$("#editform").prepend('<div id="footnote-cleanup"><a href="javascript:cleanupFootnotes()">clean up footnotes</a></div>');
}

function cleanupFootnotes()
{
	var textbox = $("#wpTextbox1");
	
	if ( textbox )
	{
		var oldContents = textbox.val();
		var contents = oldContents;
		
		var escaped = [];
		var i = 0;
		
		var escape = function(text, regexString)
		{
			var regex = new RegExp(regexString, "g");
			text = text.replace(
				regex,
				function(match)
				{
					escaped[i] = match;
					replacement = "%%" + i + "%%";
					i += 1;
					return replacement;
				}
			);
			return text;
		};
		
		// Escape ref tags.
		contents = escape(
			contents,
			"<ref[^>]*>[^<]+<\/ref>"
		);
		
		if ( i > 0 )
		{
			mw.notify(i + " refs found.");
		}
		
		var punctuation = "[\.\,\;\:\)]{1,3}";
		
		var count = 0;
		var replacements = [];
		contents = contents.replace(
			/((?:%%\d+%%)+)([\.\,\;\:\)]{1,3})/g,
			function(match, capture1, capture2)
			{
				count += 1;
				var replacement = capture2 + capture1;
				replacements.push(replacement);
				return replacement;
			}
		);
		
		mw.notify(count + " correction" + ( i === 1 && "" || "s" ) + "made: " + replacements.join());
		
		contents = contents.replace(
			/%%(\d+)%%/g,
			function(wholematch, number) {
				number = Number(number);
				return escaped[number];
			}
		);
		
		var isUnchanged = ( oldContents === contents );
		
		if ( isUnchanged )
		{
			mw.notify("No misplaced footnotes were found.");
		}
		
		textbox.val(contents);
		$("#wpSummary").val(function(index, summary)
			{
				mw.notify(summary);
				
				var addition = "made sure refs are after punctuation with [[User:Erutuon/footnoteCleanup.js|JavaScript]]";
				
				afterSectionName = summary.match(/^\/\*[^\*]+\*\/\s+(.+)/);
				
				if ( afterSectionName && afterSectionName[1].length > 1 )
				{
					addition = "; " + addition;
				}
				
				if ( !isUnchanged )
				{
					return summary + addition;
				}
			}
		);
	}
}