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 22:47, 19 May 2017 (attempt an escaping function). 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 escape(text, regexString, escapeTable, i)
{
	var regex = new RegEx(regexString, "g");
	text = text.replace(
		regex,
		function(match)
		{
			escapeTable[i] = match;
			replacement = "%%" + i + "%%";
			i += 1;
			return replacement;
		}
	);
	return text;
}

function cleanupFootnotes()
{
	var textbox = $("#wpTextbox1");
	
	if ( textbox )
	{
		var oldContents = textbox.val();
		var contents = oldContents;
		
		// Escape ref tags.
		var escaped = [];
		var i = 0;
		contents = escape(
			contents,
			"<ref[^>]*>[^<]+<\/ref>",
			escaped,
			i
		);
		
		if ( i > 0 )
		{
			mw.notify(i + " refs found.");
		}
		
		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(i + " corrections 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;
				}
			}
		);
	}
}