User:Mpaa/common.js

/* One-click "Without text" */ mw.loader.load('//en.wikisource.org/w/index.php?title=MediaWiki:Gadget-Without text.js&action=raw&ctype=text/javascript')

/************* // linter config object var myLintHints = { };
 * Linter errors

// lint in all namespaces myLintHints.rooms = "*";

// communicate user defined object mw.hook( "lintHint.config" ).fire( myLintHints );

// finally, load gadget mw.loader.load( "https://en.wikipedia.org/w/index.php?title=User:PerfektesChaos/js/lintHint/r.js&action=raw&bcache=1&maxage=86400&ctype=text/javascript" );

/************* mw.user.options.set({ 'nopinserter_auto_advance': true });
 * Option for nop gadget, from Inductiveload

/************* $(function {	var qualityContainer = document.getElementById('wpQuality-container');	if (!qualityContainer) return;
 * Without Text, from Hesperian

var quality0 = qualityContainer.getElementsByClassName('quality0'); var withouttext = quality0[0].childNodes[0];

withouttext.addEventListener('click', function {		document.getElementsByName('wpTextbox1')[0].value = "";		document.getElementsByName('wpHeaderTextbox')[0].value = "";		document.getElementsByName('wpFooterTextbox')[0].value = "";		document.getElementsByName('wpSave')[0].click;	}); });

/************* //function colourBackground( pageBG, editboxBG, fontColour, linkColour, newLinkColour, extLinkColour){ //	$('#content').css('background-color', pageBG) //	$('#content').css('color', fontColour) //	$('a').css('color', linkColour) //	$('.new').css('color', newLinkColour) //	$('.extiw').css('color', extLinkColour) //	$('textarea, input').css('background-color', editboxBG) //}
 * Eye strainer, from Inductiveload [[File:Links to Eyestrainer]]

//if (mw.config.get('wgAction') == "edit" || mw.config.get('wgAction')=="submit"){ //	$( function {setTimeout("colourBackground('#DDD', '#DDD', '#222', '#22F', '#BA0000', '#33F')", 100)}); //}

$(function {	var qualityContainer = document.getElementById('wpQuality-container');	if (!qualityContainer) return;

var quality0 = qualityContainer.getElementsByClassName('quality0'); var withouttext = quality0[0].childNodes[0];

withouttext.addEventListener('click', function {		var textbox = document.getElementsByName('wpTextbox1')[0];

if (-1 == textbox.value.indexOf("{{iwpage")) { textbox.value = ""; }		document.getElementsByName('wpHeaderTextbox')[0].value = ""; document.getElementsByName('wpFooterTextbox')[0].value = ""; document.getElementsByName('wpSave')[0].click; }); });

// $(function {	var qualityContainer = document.getElementById('wpQuality-container');	if (!qualityContainer) return;

var quality2 = qualityContainer.getElementsByClassName('quality2'); var problematic = quality2[0].childNodes[0];

problematic.addEventListener('click', function {		if (document.getElementsByName('wpTextbox1')[0].value == "") {			document.getElementsByName('wpSummary')[0].value = "/* Problematic */ ";			document.getElementsByName('wpHeaderTextbox')[0].value = "";			document.getElementsByName('wpFooterTextbox')[0].value = "";			document.getElementsByName('wpSave')[0].click;		} else if (document.getElementsByName('wpTextbox1')[0].value == "") {			document.getElementsByName('wpSummary')[0].value = "/* Problematic */ ";			document.getElementsByName('wpHeaderTextbox')[0].value = "";			document.getElementsByName('wpFooterTextbox')[0].value = "";			document.getElementsByName('wpSave')[0].click;		} else if (document.getElementsByName('wpTextbox1')[0].value == "") {			document.getElementsByName('wpSummary')[0].value = "/* Problematic */ ";			document.getElementsByName('wpHeaderTextbox')[0].value = "";			document.getElementsByName('wpFooterTextbox')[0].value = ""; document.getElementsByName('wpSave')[0].click; } else if (document.getElementsByName('wpTextbox1')[0].value == "") { document.getElementsByName('wpSummary')[0].value = "/* Problematic */ "; document.getElementsByName('wpHeaderTextbox')[0].value = ""; document.getElementsByName('wpFooterTextbox')[0].value = ""; document.getElementsByName('wpSave')[0].click; } else if (document.getElementsByName('wpTextbox1')[0].value == "") { document.getElementsByName('wpSummary')[0].value = "/* Problematic */ "; document.getElementsByName('wpHeaderTextbox')[0].value = ""; document.getElementsByName('wpFooterTextbox')[0].value = ""; document.getElementsByName('wpSave')[0].click; }	}); }); //

/** * TemplateScript adds configurable templates and scripts to the sidebar, and adds an example regex editor. * @see https://meta.wikimedia.org/wiki/TemplateScript * @update-token */ // $.ajax('//tools-static.wmflabs.org/meta/scripts/pathoschild.templatescript.js', { dataType:'script', cache:true }).then(function {	/*********	** Register scripts	*********/	pathoschild.TemplateScript.add([ // stuff I routinely do at the start { name: 'headerMpaa', script: headerMpaa }, { name: 'custom', script: customMpaa }, { name: 'footnote', script: footnoteMpaa },

// stuff I routinely do at the start { name: 'header', script: header, forNamespaces: 'page' }, { name: 'blockcenter', script: blockcenter, forNamespaces: 'page' }, { name: 'clean up', script: function(editor) { cleanup(editor, false); }, forNamespaces: 'page', accessKey: '<' }, { name: 'clean up (poem)', script: function(editor) { cleanup(editor, true); }, forNamespaces: 'page', accessKey: '<' }, { name: 'uc', script: uc, forNamespaces: 'page' },

// stuff I can do any time { name: 'title', script: maketitle, accessKey: 't' }, { name: 'author', script: author, accessKey: 'a' }, { name: 'author (surname first)', script: surnameFirst, accessKey: ',' }, { name: 'small-caps', script: smallcaps, accessKey: 'c' }, { name: 'lower', script: lower, accessKey: 'l' }, { name: 'upper', script: upper, accessKey: 'u' },

// stuff I do at the end { name: 'hws', script: hws, accessKey: '8', forNamespaces: 'page' }, { name: 'hwe', script: hwe, accessKey: '9', forNamespaces: 'page' }, { name: 'makeref', script: makeref, forNamespaces: 'page' }, { name: 'footer', script: footer, forNamespaces: 'page' },

// stuff I only do via shortcuts; if I could create these shortcuts without adding them to the sidebar, I would. { name: 'ligature', script: ligature, accessKey: '-' }, { name: 'diaresis', script: diareses, accessKey: ':' }, { name: 'acute', script: acute, accessKey: '\'' }, { name: 'grave', script: grave, accessKey: '`' }, { name: 'circumflex', script: circumflex, accessKey: '6' }, { name: 'pagename', script: putpagename, accessKey: 'n' }, { name: 'reload', script: reload_page_image } ]);

/*********	** Define scripts *********/	// === FOR CONVERSIONS === /**	 * Convenience function: convert some text into title case. */	function titlecase(text) { // split text into individual words and examine them one by one var textArray = text.toLowerCase.split(" "); for (var i in textArray) { switch (textArray[i]) { case "a": case "an": case "and": case "as": case "at": case "but": case "by": case "etcetera": case "etc.": case "for": case "from": case "in": case "nor": case "of": case "o'": case "on": case "or": case "the": case "to": case "with": case "versus": case "vs.": case "v.": case "yet": break; // don't capitalise articles, "to" as part of an infinitive, prepositions or short conjunctions default: // capitalise everything else textArray[i] = textArray[i].substring(0, 1).toUpperCase + textArray[i].substring(1, textArray[i].length); break; }		}

// capitalise first word regardless textArray[0] = textArray[0].substring(0, 1).toUpperCase + textArray[0].substring(1, textArray[0].length);

// capitalise last word regardless var last = textArray.length - 1; textArray[last] = textArray[last].substring(0, 1).toUpperCase + textArray[last].substring(1, textArray[last].length);

// reconstruct title var titleCase = ""; for (i in textArray) { titleCase += textArray[i]; if (i < last) titleCase += " "; }

return titleCase; }

function customMpaa(editor) { editor .replace(/'(?!\w)/g, '"')			.replace(/ '/g, ' "') .replace(/^'/m, '"')

.replace(/”/g, '"')			.replace(/“/g, '"') .replace(/’/g, "'") .replace(/‘/g, "'") .replace(/ ([;|:|\?|!])/g, '$1') .replace(/ $/mg, ''); }

function headerMpaa(editor) { var textArray = editor.get.split('\n'); var text = textArray[0];

editor.forField('#wpHeaderTextbox') .set(text.replace(/(\d+)?\s?((\s?([A-Z]|[a-z])+[\.|'|’|–|—|-]?)+)\s?(\d+)?/g, '$1'));

textArray.splice(0, 1); editor.set(textArray.join('\n')); }

// just mark it with tags and continue. // Once you've got to the end of the page and proofed the references, simply highlight each reference in turn, // and use this function to move it to its proper position. function footnoteMpaa { var editbox = $('#wpTextbox1').get(0); editbox.value = editbox.value.replace(/ '); editbox.focus;

var refStart = editbox.selectionStart; var refEnd = editbox.selectionEnd;

var firstref = editbox.value.indexOf(' ');

var str = editbox.value.slice(refStart, refEnd); str = str.replace(/^\s+|\s+$/g, '');

if (firstref !== -1) editbox.value = editbox.value.slice(0, firstref + 5) + str + editbox.value.slice(firstref + 5, refStart) + editbox.value.slice(refEnd); }

function cleanup(editor, poem) { var headerbox = editor.forField('#wpHeaderTextbox'); var footerbox = editor.forField('#wpFooterTextbox');

// anything noincluded at the start or end of the edit box should be pushed into the header and footer respectively. if (editor.get.match(/^ /)) { var e = editor.get.indexOf(" ");

// append to header a trimmed version of whatever is inside the leading noinclude headerbox.append('\n' + editor.get.substr(11, e - 11).replace(/^\s+|\s+$/g, ''));

// remove leading noinclude from editbox editor.set(editor.get.substr(e + 12)); }

if (editor.get.match(/<\/noinclude>$/)) { var s = editor.get.lastIndexOf(" ");

// prepend to footer a trimmed version of whatever is inside the trailing noinclude footerbox.prepend(editor.get.substr(s + 11, editor.get.length - s - 11 - 12).replace(/^\s+|\s+$/g, '') + '\n');

// remove trailing noinclude from editbox editor.set(editor.get.substr(0, s)); }

editor // remove trailing spaces at the end of each line .replace(/ +\n/g, '\n')

// remove trailing whitespace preceding a hard line break .replace(/ +/g, ' ')

// remove trailing whitespace at the end of page text .replace(/\s+$/g, '')

// remove trailing spaces at the end of refs .replace(/ +<\/ref>/g, ' ')

// remove trailing spaces at the end of template calls .replace(/ +}}/g, '}}')

// convert double-hyphen to mdash (avoiding breaking HTML comment syntax) .replace(/([^\!])--([^>])/g, '$1—$2')

// remove spacing around mdash, but only if it has spaces on both sides // (we don't want to remove the trailing space from "...as follows:— ",			// bearing in mind that the space will already be gone if at end of line). .replace(/ +— +/g, '—')

// join words that are hyphenated across a line break // (but leave "|-" table syntax alone) .replace(/([^\|])-\n/g, '$1');

// stuff to do only if the page doesn't contain a tag: if (editor.get.indexOf(" ") === -1) { editor // lines that start with " should probably be new lines,				// if the previous line ends in punctuation,				// other than a comma or semicolon				// and let's get rid of trailing space while we're at it				.replace(/([^\n\w,;])\n\" */g, '$1\n\n"')

// lines that end with " should probably precede a new line,				// unless preceded by a comma,				// or unless the new line starts with a lower-case letter;				// and let's get rid of preceding space while we're at it				.replace(/([^,])\ *\"\n([^a-z\n])/g, '$1"\n\n$2');

if (poem) { // for poems I want to preserve line breaks // by inserting hard breaks editor.replace(/([^>}\|\n])\n([^:#\*<{\|\n])/g, '$1 \n$2').append(' '); }			else { // remove single line breaks; preserve multiple. // but not if there's a tag, template or table syntax either side of the line break editor.replace(/([^>}\|\n])\n([^:#\*<{\|\n])/g, '$1 $2'); }

// collapse sequences of spaces into a single space editor.replace(/ +/g, ' '); }

editor // dump spurious hard breaks at the end of paragraphs .replace(/\n\n/g, '\n\n')

// remove unwanted spaces around punctuation marks .replace(/ ([;:\?!,])/g, '$1')

// unicodify .replace(/&mdash;/g, '—') .replace(/–/g, '–')

//OCR fixes // convert i9 to 19, etc.			.replace(/[il]([0-9])/g, '1$1')

// "the", "them", "their", etcetera .replace(/tlie/g, 'the')

// remove "�" .replace(/�/g, '')

// "U" -> "ll" when preceded by a lowercase letter. .replace(/([a-z])U/g, '$1ll')

// replace "float center" with "block center"; original template name was misleading enough be warrant routinely fixing .replace(/\{\{float center/g, '{{block center')

.replace(/ \s*([.\n]*?)\s*<\/center>/g, '{{center|$1}}');

// temporary fix just for Portrait if (mw.config.get('wgTitle').indexOf('A Portrait of the Artist as a Young Man') !== -1) editor.replace(/\n\n\n/g, '\n\n'); }

// automatically insert running header into header box function header(editor) { var pagenum = parseInt((mw.config.get('wgTitle').match(/\.djvu\/([0-9]+)/) || {})[1], 10); if (pagenum == null) return; var isEven = (pagenum % 2 === 0);

var headerbox = editor.forField('#wpHeaderTextbox'); var headertext; var generic = true;

for (var f in specialFormats) { var format = specialFormats[f]; if (location.href.indexOf(encodeURI(format[0].replace(/ /g, "_")).replace(/\'/g, "%27")) !== -1) { headertext = isEven ? format[1] : format[2]; generic = false; break; }		}

// no special header matched, use a generic running header if (generic) { headertext = isEven ? '' // assume verso, with page number at left : '';		}

headerbox.set(			$.trim(headerbox.get + '\n' + headertext)		);

// if this is unproofed text, then delete the first line of the OCR text, which presumably is raw OCR of the header we've just inserted var proofed = $('#pagequality').length && !$('#pagequality').is('.quality1'); if (!proofed) editor.set(editor.get.slice(editor.get.indexOf('\n') + 1)); }

// insert formatted references into footer box, if needed. function footer(editor) { var footerbox = editor.forField('#wpFooterTextbox');

if (editor.get.indexOf(" ") === -1 && editor.get.indexOf("{{#tag:ref") === -1) { // page contains no refs var generic = true; for (var f in specialFormats) { var format = specialFormats[f]; if (location.href.indexOf(encodeURI(format[0].replace(/ /g, "_")).replace(/\'/g, "%27")) !== -1) { footerbox.set(format[3]); generic = false; break; }			}

// no special footer matched, use just strip out the references tag if (generic) footerbox.set(''); } else { var generic = true; for (var f in specialFormats) { var format = specialFormats[f]; if (-1 != location.href.indexOf(encodeURI(format[0].replace(/ /g, "_")).replace(/\'/g, "%27"))) { footerbox.set(format[4]); generic = false; break; }			}			// no special footer matched, so use a generic ref tag if (generic) footerbox.set('{{block center|{{smallrefs}}}}'); }	}

// automatically insert block center wrapping into header box function blockcenter(editor) { editor.forField('#wpHeaderTextbox').append('\n'); editor.forField('#wpFooterTextbox').prepend('\n'); }

//Make selected text into appropriately capitalised title link // e.g. "THE MAN FROM SNOWY RIVER" —> "THE MAN FROM SNOWY RIVER" function maketitle(editor) { editor.replaceSelection(function(text) {			var target = titlecase(text);			return target == text				?  + text + 				:  + text + ;		}); }

//Make selected text into author link function author(editor) { editor.replaceSelection(function(name) {			// if name contains a comma, switch around when linking			var commaPos = name.indexOf(',');			var target = commaPos === -1				? name				: name.substr(commaPos + 1).replace(/^\s+|\s+$/g, ) + ' ' + name.substr(0, commaPos).replace(/^\s+|\s+$/g, );

// if name is all in capitals, convert target to title case. if (target == target.toUpperCase) target = titlecase(target);

return  + name + ; });	}

function surnameFirst(editor) { editor.replaceSelection(function(name) {			// If name is all in capitals, convert target to title case.			var target = name === name.toUpperCase				? titlecase(name)				: name;

// split text into individual words var nameArray = name.split(" ");

// put last first, followed by a comma, then all the rest preceded by spaces name = nameArray[nameArray.length - 1] + ","; for (i = 0; i < nameArray.length - 1; i++) name = name + " " + nameArray[i];

return  + name + ; });	}

//Mark selected text up with small-caps function smallcaps(editor) { editor.replaceSelection(function(pre) {			// Applying small-caps to all-caps text is pointless...			// ... unless the all-caps is OCR of text that is actually small-caps.			// Check if text is all-caps, and if it is, convert it to title case before applying small-caps.			if (pre == pre.toUpperCase)				pre = titlecase(pre);

return ''; });	}

// As you work your way through the page, when you encounter a reference, just mark it with tags and continue. // Once you've got to the end of the page and proofed the references, simply highlight each reference in turn, // and use this function to move it to its proper position. function makeref(editor) { var editbox = $('#wpTextbox1').get(0); editbox.focus; var refStart = editbox.selectionStart; var refEnd = editbox.selectionEnd;

var firstref = editbox.value.indexOf(' '); if (firstref !== -1) editbox.value = editbox.value.slice(0, firstref + 5) + editbox.value.slice(refStart, refEnd) + editbox.value.slice(firstref + 5, refStart) + editbox.value.slice(refEnd); }

//wrap first word in hwe template function hwe(editor) { var to = editor.get.search(/\W/); if (to == -1) to = editor.get.length;

var pre = editor.get.substring(0, to); var post = ''; editor.set(post + editor.get.substring(to)); }

//wrap last word in hws template function hws(editor) { var from = editor.get.lastIndexOf(" "); from = (from == -1) ? 0			: from + 1;

var pre = editor.get.substring(from); if (pre.slice(-1) == "-") pre = pre.slice(0, -1);

var post = ''; editor.set(editor.get.substring(0, from) + post); }

function putpagename(editor) { var pagename = mw.config.get('wgPageName').replace(/_/g, ' '); editor.replaceSelection(pagename); }

function ligature(editor) { editor.replaceSelection(function(pre) {			switch (pre) {				case 'ae':					return 'æ';				case 'AE':					return 'Æ';				case 'oe':					return 'œ';				case 'OE':					return 'Œ';				default:					return pre;			}		}); }

function diareses(editor) { editor.replaceSelection(function(pre) {			switch (pre) {				case 'a':					return 'ä';				case 'A':					return 'Ä';				case 'e':					return 'ë';				case 'E':					return 'Ë';				case 'i':					return 'ï';				case 'I':					return 'Ï';				case 'o':					return 'ö';				case 'O':					return 'Ö';				case 'u':					return 'ü';				case 'U':					return 'Ü';				case 'y':					return 'ÿ';				default:					return pre;			}		}); }

function acute(editor) { editor.replaceSelection(function(pre) {			switch (pre) {				case 'a':					return 'á';				case 'A':					return 'Á';				case 'c':					return 'ć';				case 'C':					return 'Ć';				case 'e':					return 'é';				case 'E':					return 'É';				case 'g':					return 'ģ';				case 'i':					return 'í';				case 'I':					return 'Í';				case 'o':					return 'ó';				case 'O':					return 'Ó';				case 'l':					return 'ĺ';				case 'L':					return 'Ĺ';				case 'n':					return 'ń';				case 'N':					return 'Ń';				case 'r':					return 'ŕ';				case 'R':					return 'Ŕ';				case 's':					return 'ś';				case 'S':					return 'Ś';				case 'u':					return 'ú';				case 'U':					return 'Ú';				case 'y':					return 'ý';				case 'Y':					return 'Ý';				case 'z':					return 'ź';				case 'Z':					return 'Ź';				default:					return pre;			}		}); }

function grave(editor) { editor.replaceSelection(function(pre) {			switch (pre) {				case 'a':					return 'à';				case 'A':					return 'À';				case 'e':					return 'è';				case 'E':					return 'È';				case 'i':					return 'ì';				case 'I':					return 'Ì';				case 'o':					return 'ò';				case 'O':					return 'Ò';				case 'u':					return 'ù';				case 'U':					return 'Ù';				default:					return pre;			}		}); }

function circumflex(editor) { editor.replaceSelection(function(pre) {			switch (pre) {				case 'a':					return 'â';				case 'A':					return 'Â';				case 'c':					return 'ĉ';				case 'C':					return 'Ĉ';				case 'e':					return 'ê';				case 'E':					return 'Ê';				case 'g':					return 'ĝ';				case 'G':					return 'Ĝ';				case 'h':					return 'ĥ';				case 'H':					return 'Ĥ';				case 'i':					return 'î';				case 'I':					return 'Î';				case 'j':					return 'ĵ';				case 'J':					return 'Ĵ';				case 'o':					return 'ô';				case 'O':					return 'Ô';				case 's':					return 'ŝ';				case 'S':					return 'Ŝ';				case 'u':					return 'û';				case 'U':					return 'Û';				case 'w':					return 'ŵ';				case 'W':					return 'Ŵ';				case 'y':					return 'ŷ';				case 'Y':					return 'Ŷ';				default:					return pre;			}		}); }

function uc(editor) { var matches = editor.get.match(/\{\{[Uu]c\s*\|\s*([^\}]+)\}\}/g); while (matches != null) { editor.replace(matches[0], matches[1].toUpperCase); matches = editor.get.match(/\{\{[Uu]c\s*\|\s*([^\}]+)\}\}/g); }	}

function lower(editor) { editor.replaceSelection(function(text) {			return text.toLowerCase;		}); }

function upper(editor) { editor.replaceSelection(function(text) {			return text.toUpperCase;		}); }

function reload_page_image(editor) { $('#ProofReadImage').attr('src', function(i, val) {			return val.replace(/-([0-9]+)px/, function(num) { return '-' + (num[1] * 9 / 10) + 'px'; });		});	} }); //

// == IMPORT WORK-SPECIFIC INFORMATION ABOUT HEADERS, FOOTERS, REFS, ETC == //get specialFormats variable from work.js mw.loader.load('//en.wikisource.org/w/index.php?title=User:Mpaa/works.js&action=raw&ctype=text/javascript');