User:Dcsohl/common.js

From Wikisource
Jump to navigation Jump to search
Note: After saving, changes may not occur immediately. Click here to learn how to bypass your browser's cache.
  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (Cmd-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (Cmd-Shift-R on a Mac)
  • Internet Explorer: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Clear the cache in Tools → Preferences

For details and instructions about other browsers, see Wikipedia:Bypass your cache.

// <syntaxhighlight lang="javascript">
/* global $, mw, importScript, pathoschild */

/**</syntaxhighlight>
 * TemplateScript adds configurable templates and scripts to the sidebar, and adds an example regex editor.
 * @see https://meta.wikimedia.org/wiki/TemplateScript
 * @update-token [[File:pathoschild/templatescript.js]]
 */
// <syntaxhighlight lang="javascript">
$.ajax('//tools-static.wmflabs.org/meta/scripts/pathoschild.templatescript.js', { dataType:'script', cache:true }).then(function() {
	// page NS
	pathoschild.TemplateScript.add(
		[
			{ name: 'cleanup', position: 'cursor', script: cleanup },
		],
		{ category: 'pre', forNameSpaces: 'page' }
	);
	
	pathoschild.TemplateScript.add(
		[
			{ name: 'join lines', script: joinlines },
			{ name: 'straight quotes', script: straightQuotes },
			{ name: 'curly quotes', script: curlyQuotes },
		],
		{ category: 'post', forNameSpaces: 'page' }
	);

	pathoschild.TemplateScript.add(
		[
			{ name: 'smallcaps', script: smallcaps },
			{ name: 'titlecase', script: titlecase },
			{ name: 'India Date', script: indiaDate },
			{ name: 'India To', script: indiaTo },
			{ name: 'India From', script: indiaFrom }
		],
		{ category:'page', forNamespaces:'page' } // common fields
	);
	
	function cleanup(editor) {
		editor
			// Digitized by Google (kill)
			.replace(/Digitized[\s\n]+by[^\n]+\n(Google)?/, '')
			// exactly one trailing space at the end of each line
			.replace(/ +\n/g, ' \n')

			// remove trailing whitespace preceding a hard line break
			.replace(/ +<br *\/?>/g, '<br />')

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

			// remove spaces before certain punctuation
			.replace(/([\w\)])\s([:;?!][\s—"”'’])/g, '$1$2')

			// remove space after opening quotes
			.replace(/(\s)(['‘"“]) (\w)/g, '$1$2$3')

			// f-ligatures
			.replace(/ff/g, 'ff')
			.replace(/fi/g, 'fi')
			.replace(/fl/g, 'fl')
			.replace(/ffi/g, 'ffi')
			.replace(/ffl/g, 'ffl')
			.replace(/ſt/g, 'ft')
			.replace(/st/g, 'st')

			// 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, '—');
	}
	
	function straightQuotes(editor) {
		editor
			.replace(/[‘’]/g, '\'')
			.replace(/[“”]/g, '\"');
	}
	
	function curlyQuotes(editor) {
		editor
			.replace(/(^|[\s|])'([\w\d.…])/gm, '$1‘$2') // left quote
			.replace(/([\w\d.,?!;—-])'($|[\s|}])/gm, '$1’$2') // right quote
			.replace(/([\w\d])'([;:])/g, '$1’$2') // with outside punc
			.replace(/(\w)'(\w)/g, '$1’$2') // apostrophe
			.replace(/(^|[\s|])"([\w\d.…])/gm, '$1“$2') // left double quote
			.replace(/([\w\d.,?!—-])"($|[\s|}])/gm, '$1”$2') // right double
			.replace(/([\w\d])'([;:])/g, '$1”$2'); // with outside punc
	}
	
	function indiaDate(editor) {
		editor.replaceSelection(function(pre) {
			return '{{right|{{smaller|' + pre.trim() + '}}|1em}}';
		});
	}
	
	function indiaTo(editor) {
		editor.replaceSelection(function(pre) {
			return '{{pseudoheading|' + pre.trim() + '}}';
		});
	}
	
	function indiaFrom(editor) {
		editor.replaceSelection(function(pre) {
			var lines = pre.split("\n");
			var retval = "";
			var lineCount = lines.length;
			for (var i in lines) {
				var ems = 1;
				if (lineCount > 1 && i == 0) {
					ems = 2;
				}
			    retval += '{{right|' + lines[i].trim() + '|' + ems + 'em}}\n';
			}
			return retval;
		});
	}
	
	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 '{{sc|' + pre + '}}';
		});
	}
	
	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 joinlines(editor) {
		var result = "";
		var lines = editor.get().split(/\n/);
		for (var i = 0; i < lines.length-1; i++) {
			lines[i] = lines[i].trim();
			var joiner = getJoiner(lines[i], lines[i+1]);
			if (lines[i].endsWith('-')) {
				lines[i] = lines[i].substr(0, lines[i].length-1);
			}
			lines[i] = lines[i] + joiner;
		}
		editor.set(lines.join(''));
	}
	
	function getJoiner(str1, str2) {
		if (str1.length == 0 || str2.length == 0) {
			if (str1.length == 0 && str2.length == 0) {
				return '';
			}
			return '\n';
		} else if (str1.endsWith('-') || str1.endsWith('—') || str2.startsWith('-') || str2.startsWith('—')) {
			return '';
		} else if ((str1.startsWith('{{') && str1.endsWith('}}')) || (str2.startsWith('{{') && str2.endsWith('}}'))) {
			return '\n';
		} else if ((str1.startsWith('#') && str1.endsWith('#')) || (str2.startsWith('#') && str2.endsWith('#'))) {
			return '\n';
		} else if (str2.startsWith('#')) {
			return '\n';
		}else {
			return ' ';
		}
	}
});