User:Omegatron/monobook.js/headingformattingfixer.js

From Wikipedia, the free encyclopedia

Note: After saving, you have to bypass your browser's cache to see the changes. Mozilla/Safari: hold down Shift while clicking Reload (or press Ctrl-Shift-R), Internet Explorer: press Ctrl-F5, Opera/Konqueror: press F5.

function headingfixer() {
    var txt = document.editform.wpTextbox1;

    // Format heading markup the way it is generated with the + tab
    txt.value = txt.value.replace(/((^|\n)={2,})( |\t)*(.*?)( |\t)*(={2,})/g, '$1 $4 $6\n\n');

    // 1 blank line before the headings 
    // (this is super-kludgy because of the newlines conflicting when one heading is right after another)
    // (seems to work, though, for now.  some other day...)
    txt.value = txt.value.replace(/(\n+={2,}) (.*?) (={2,})/g, '\n\n$1 $2 $3');

    // Remove all extra newlines?
    txt.value = txt.value.replace(/(\n[ \t\v\r\f]*){2,}/g, '\n\n');

    // Spaces after * and # lists
    txt.value = txt.value.replace(/(^|\n)((\*|\#|\;|\:)+)\s*(\w|\[|\"|\'|\{)/g, '$1$2 $4');

    // Format External links and See also according to the Manual of Style
    txt.value = txt.value.replace(/\=\= external links? \=\=/ig, '== External links ==');
    txt.value = txt.value.replace(/\=\= see also \=\=/ig, '== See also ==');

    // Add a tag to the summary box
    var txt = document.editform.wpSummary;
    var summary = "[[User:Omegatron#Regular expressions|Regex heading and whitespace fixer]]";
	if (txt.value.indexOf(summary) == -1) {
		if (txt.value.match(/[^\*\/\s][^\/\s]?\s*$/)) {
			txt.value += " | ";
		}
		txt.value += summary;
	}

    // Press the diff button to check it
    document.editform.wpDiff.click()
}

addOnloadHook(function () {
    if(document.forms.editform) {
        addLink('p-cactions', 'javascript:headingfixer()', '==', 'ca-headingfixer', 'Fixes heading whitespace and deletes excess newlines', '-', '');
    }
});