User:DemonDays64/Scripts/Ref tag spacing.js

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.
// Documentation: [[User:DemonDays64/Scripts/Ref tag spacing]]
mw.loader.using('mediawiki.util', function () {

	$(document).ready(function () {
		var pageBeforeEdit;
		var modifiedPage;
		var previousSummary;

		//add a tab on the left
		var dumbQuotesLink = mw.util.addPortletLink("p-tb", "#", "Ref tag spacing", "t-ref-space", "Remove spaces between periods and references");
		$(dumbQuotesLink).click(function (event) {
			event.preventDefault();
			editPage();
		});
		function runRegex(regex) {
			modifiedPage = modifiedPage.replace(regex.find, regex.replace);
		}

		function makeAndRunRegex(findRegex, replace) {
			var regexObject = {
				find: findRegex,
				replace: replace
			};
			runRegex(regexObject);
		}
		function doEdit() {
			document.editform.wpTextbox1.value = modifiedPage;
		}
		function setEditSummary(summary, isMinor) {
			document.editform.wpMinoredit.checked = isMinor;
			previousSummary = document.editform.wpSummary.value;
			if (previousSummary !== "") {
				if (!previousSummary.includes(summary)) {
					document.editform.wpSummary.value = document.editform.wpSummary.value + " | " + summary;
				}
			}
			else {
				document.editform.wpSummary.value = summary;
			}
		}
		function showDiff() {
			doaction("diff");
		}
		function editPage() {
			pageBeforeEdit = document.editform.wpTextbox1.value;
			modifiedPage = pageBeforeEdit;

			// quote with period then space then reference
			makeAndRunRegex(/(("|')?\.("|')?) <ref/g, "$1<ref");
			// quote with comma then space then reference
			makeAndRunRegex(/(("|')?,("|')?) <ref/g, "$1<ref");
			// quote with word then space then reference
			makeAndRunRegex(/(\w) <ref/g, "$1<ref");
			// quote reference then quote or word with no space
			makeAndRunRegex(/<\/ref>((\w)|"|')/g, "</ref> $1");
			doEdit();
			setEditSummary("Fixed some spacing with [[User:DemonDays64/Scripts/Ref tag spacing.js|script]]", true);
			showDiff();
		}
	});
});