(function($) {

/*

Twinkle.tag = function friendlytag {
	/* 기능 비활성화 : 아직 준비 안 됨 (2020-08-12) */
	if (true) {
		return;

	// redirect tagging
	if (Morebits.wiki.isPageRedirect) {
		Twinkle.tag.mode = 'redirect';
		Twinkle.addPortletLink;
	// file tagging
		Twinkle.tag.mode = 'file';
		Twinkle.addPortletLink;
	// article/draft article tagging
		Twinkle.tag.mode = 'article';
		// Can't remove tags when not viewing current version
		Twinkle.tag.canRemove = (mw.config.get('wgCurRevisionId') === mw.config.get('wgRevisionId')) &&
			// Disabled on latest diff because the diff slider could be used to slide
			// away from the latest diff without causing the script to reload
		Twinkle.addPortletLink;

Twinkle.tag.checkedTags = [];

Twinkle.tag.callback = function friendlytagCallback {
	var Window = new Morebits.simpleWindow;
	Window.setScriptName('Twinkle');
	// anyone got a good policy/guideline/info page/instructional page link??
	Window.addFooterLink;

	var form = new Morebits.quickForm(Twinkle.tag.callback.evaluate);

	form.append({
		type: 'input',
		label: 'Filter tag list: ',
		name: 'quickfilter',
		size: '30px',
		event: function twinkletagquickfilter {
			// flush the DOM of all existing underline spans
			$allCheckboxDivs.find('.search-hit').each(function {
				var label_element = e.parentElement;
				// This would convert 
				// to 
				label_element.innerHTML = label_element.textContent;

			if (this.value) {
				$allCheckboxDivs.hide;
				$allHeaders.hide;
				var searchString = this.value;
				var searchRegex = new RegExp(mw.util.escapeRegExp(searchString), 'i');

				$allCheckboxDivs.find('label').each(function {
					var label_text = this.textContent;
					var searchHit = searchRegex.exec(label_text);
					if (searchHit) {
						var range = document.createRange;
						var textnode = this.childNodes[0];
						range.selectNodeContents(textnode);
						range.setStart;
						range.setEnd;
						var underline_span = $('').addClass('search-hit').css[0];
						range.surroundContents(underline_span);
						this.parentElement.style.display = 'block'; // show
				$allCheckboxDivs.show;
				$allHeaders.show;

	switch (Twinkle.tag.mode) {
		case 'article':
			Window.setTitle('Article maintenance tagging');

			// Build sorting and lookup object flatObject, which is always
			// needed but also used to generate the alphabetical list
			// Would be infinitely better with Object.values, but, alas, IE 11
			Twinkle.tag.article.flatObject = {};
			Object.keys(Twinkle.tag.article.tagList).forEach(function(group) {
				Object.keys(Twinkle.tag.article.tagList[group]).forEach(function(subgroup) {
					if (Array.isArray(Twinkle.tag.article.tagList[group][subgroup])) {
						Twinkle.tag.article.tagList[group][subgroup].forEach(function(item) {
							Twinkle.tag.article.flatObject[item.tag] = { description: item.description, excludeMI: !!item.excludeMI };
						Twinkle.tag.article.flatObject[Twinkle.tag.article.tagList[group][subgroup].tag] = {description: Twinkle.tag.article.tagList[group][subgroup].description, excludeMI: !!Twinkle.tag.article.tagList[group][subgroup].excludeMI };

			form.append({
				type: 'select',
				name: 'sortorder',
				label: 'View this list:',
				tooltip: 'You can change the default view order in your Twinkle preferences (WP:TWPREFS).',
				event: Twinkle.tag.updateSortOrder,
				list: [
				]

			if (!Twinkle.tag.canRemove) {
				var divElement = document.createElement('div');
				divElement.innerHTML = 'For removal of existing tags, please open Tag menu from the current version of article';
				form.append({
					type: 'div',
					name: 'untagnotice',
					label: divElement

			form.append({
				type: 'div',
				id: 'tagWorkArea',
				className: 'morebits-scrollbox',
				style: 'max-height: 28em'

			form.append({
				type: 'checkbox',
				list: [
						label: 'Group inside if possible',
						value: 'group',
						name: 'group',
						tooltip: 'If applying two or more templates supported by and this box is checked, all supported templates will be grouped inside a template.',
						checked: Twinkle.getPref('groupByDefault')
				]

			form.append({
				type: 'input',
				label: 'Reason',
				name: 'reason',
				tooltip: 'Optional reason to be appended in edit summary. Recommended when removing tags.',
				size: '60px'

			break;

		case 'file':
			Window.setTitle('File maintenance tagging');

			form.append;
			form.append;

			form.append;
			form.append;

			form.append;
			form.append;

			form.append;
			form.append;

			form.append;
			form.append;

			if (Twinkle.getPref('customFileTagList').length) {
				form.append;
				form.append({ type: 'checkbox', name: 'tags', list: Twinkle.getPref('customFileTagList') });
			break;

		case 'redirect':
			Window.setTitle('Redirect tagging');

			var i = 1;
			$.each(Twinkle.tag.redirectList, function {
				form.append;
				var subdiv = form.append;
				$.each(group, function {
					subdiv.append({ type: 'div', label: [ Morebits.htmlNode ] });
					subdiv.append({
						type: 'checkbox',
						name: 'tags',
						list: subgroup.map(function (item) {
							return { value: item.tag, label: ': ' + item.description, subgroup: item.subgroup };

			if (Twinkle.getPref('customRedirectTagList').length) {
				form.append;
				form.append({ type: 'checkbox', name: 'tags', list: Twinkle.getPref('customRedirectTagList') });
			break;

		default:
			alert('Twinkle.tag: unknown mode ' + Twinkle.tag.mode);
			break;

	if (document.getElementsByClassName('patrollink').length) {
		form.append({
			type: 'checkbox',
			list: [
					label: 'Mark the page as patrolled/reviewed',
					value: 'patrol',
					name: 'patrol',
					checked: Twinkle.getPref('markTaggedPagesAsPatrolled')
			]
	form.append;

	var result = form.render;
	Window.setContent(result);
	Window.display;

	// for quick filter:
	$allCheckboxDivs = $(result).find('[name$=tags]').parent;
	$allHeaders = $(result).find('h5');
	result.quickfilter.focus; // place cursor in the quick filter field as soon as window is opened
	result.quickfilter.autocomplete = 'off'; // disable browser suggestions
	result.quickfilter.addEventListener('keypress', function(e) {
		if (e.keyCode === 13) { // prevent enter key from accidentally submitting the form
			e.preventDefault;
			return false;

	if (Twinkle.tag.mode === 'article') {

		Twinkle.tag.alreadyPresentTags = [];

		if (Twinkle.tag.canRemove) {
			// Look for existing maintenance tags in the lead section and put them in array

			// All tags are HTML table elements that are direct children of .mw-parser-output,
			// except when they are within 
			$('.mw-parser-output').children.each(function parsehtml {

				// break out on encountering the first heading, which means we are no
				// longer in the lead section
				if (e.tagName === 'H2') {
					return false;

				// The ability to remove tags depends on the template's |name=
				// parameter bearing the template's correct name (preferably) or a name that at
				// least redirects to the actual name

				// All tags have their first class name as "box-" + template name
				if (e.className.indexOf('box-') === 0) {
					if (e.classList[0] === 'box-Multiple_issues') {
						$(e).find('.ambox').each(function {
							var tag = e.classList[0].slice(4).replace;
							Twinkle.tag.alreadyPresentTags.push(tag);
						return true; // continue

					var tag = e.classList[0].slice(4).replace;
					Twinkle.tag.alreadyPresentTags.push(tag);

			// and are usually placed at the end
			if ($('.box-Uncategorized').length) {
				Twinkle.tag.alreadyPresentTags.push('Uncategorized');
			if ($('.box-Improve_categories').length) {
				Twinkle.tag.alreadyPresentTags.push('Improve categories');

		// Add status text node after Submit button
		var statusNode = document.createElement('small');
		statusNode.id = 'tw-tag-status';
		Twinkle.tag.status = {
			// initial state; defined like this because these need to be available for reference
			// in the click event handler
			numAdded: 0,
			numRemoved: 0
		$('button.tw-tag-submit').after(statusNode);

		// fake a change event on the sort dropdown, to initialize the tag list
		var evt = document.createEvent('Event');
		evt.initEvent;
		result.sortorder.dispatchEvent(evt);

		// Redirects and files: Add a link to each template's description page
		Morebits.quickForm.getElements.forEach(generateLinks);

// $allCheckboxDivs and $allHeaders are defined globally, rather than in the
// quickfilter event function, to avoid having to recompute them on every keydown
var $allCheckboxDivs, $allHeaders;

Twinkle.tag.updateSortOrder = function(e) {
	var form = e.target.form;
	var sortorder = e.target.value;
	Twinkle.tag.checkedTags = form.getChecked('tags');

	var container = new Morebits.quickForm.element({ type: 'fragment' });

	// function to generate a checkbox, with appropriate subgroup if needed
	var makeCheckbox = function {
		var checkbox = { value: tag, label: ': ' + description };
		if (Twinkle.tag.checkedTags.indexOf(tag) !== -1) {
			checkbox.checked = true;
		switch (tag) {
			case 'Cleanup':
				checkbox.subgroup = {
					name: 'cleanup',
					type: 'input',
					label: 'Specific reason why cleanup is needed: ',
					tooltip: 'Required.',
					size: 35
				break;
			case 'Close paraphrasing':
				checkbox.subgroup = {
					name: 'closeParaphrasing',
					type: 'input',
					label: 'Source: ',
					tooltip: 'Source that has been closely paraphrased'
				break;
			case 'Copy edit':
				checkbox.subgroup = {
					name: 'copyEdit',
					type: 'input',
					label: '"This article may require copy editing for..." ',
					tooltip: 'e.g. "consistent spelling". Optional.',
					size: 35
				break;
			case 'Copypaste':
				checkbox.subgroup = {
					name: 'copypaste',
					type: 'input',
					label: 'Source URL: ',
					tooltip: 'If known.',
					size: 50
				break;
			case 'Expand language':
				checkbox.subgroup = [ {
					name: 'expandLanguageLangCode',
					type: 'input',
					label: 'Language code: ',
					tooltip: 'Language code of the language from which article is to be expanded from'
					name: 'expandLanguageArticle',
					type: 'input',
					label: 'Name of article: ',
					tooltip: 'Name of article to be expanded from, without the interwiki prefix'
				];
				break;
			case 'Expert needed':
				checkbox.subgroup = [
						name: 'expertNeeded',
						type: 'input',
						label: 'Name of relevant WikiProject: ',
						tooltip: 'Optionally, enter the name of a WikiProject which might be able to help recruit an expert. Don\'t include the "WikiProject" prefix.'
						name: 'expertNeededReason',
						type: 'input',
						label: 'Reason: ',
						tooltip: 'Short explanation describing the issue. Either Reason or Talk link is required.'
						name: 'expertNeededTalk',
						type: 'input',
						label: 'Talk discussion: ',
						tooltip: 'Name of the section of this article\'s talk page where the issue is being discussed. Do not give a link, just the name of the section. Either Reason or Talk link is required.'
				];
				break;
			case 'Globalize':
				checkbox.subgroup = {
					name: 'globalizeRegion',
					type: 'input',
					label: 'Over-represented country or region'
				break;
			case 'History merge':
				checkbox.subgroup = [
						name: 'histmergeOriginalPage',
						type: 'input',
						label: 'Other article: ',
						tooltip: 'Name of the page that should be merged into this one (required).'
						name: 'histmergeReason',
						type: 'input',
						label: 'Reason: ',
						tooltip: 'Short explanation describing the reason a history merge is needed. Should probably begin with "because" and end with a period.'
						name: 'histmergeSysopDetails',
						type: 'input',
						label: 'Extra details: ',
						tooltip: 'For complex cases, provide extra instructions for the reviewing administrator.'
				];
				break;
			case 'Merge':
			case 'Merge from':
			case 'Merge to':
				var otherTagName = 'Merge';
				switch (tag) {
					case 'Merge from':
						otherTagName = 'Merge to';
						break;
					case 'Merge to':
						otherTagName = 'Merge from';
						break;
					// no default
				checkbox.subgroup = [
						name: 'mergeTarget',
						type: 'input',
						label: 'Other article(s): ',
						tooltip: 'If specifying multiple articles, separate them with pipe characters: Article one|Article two'
						name: 'mergeTagOther',
						type: 'checkbox',
						list: [
								label: 'Tag the other article with a tag',
								checked: true,
								tooltip: 'Only available if a single article name is entered.'
						]
				];
				if (mw.config.get('wgNamespaceNumber') === 0) {
					checkbox.subgroup.push({
						name: 'mergeReason',
						type: 'textarea',
						label: 'Rationale for merge (will be posted on ' +
							(tag === 'Merge to' ? 'the other article\'s' : 'this article\'s') + ' talk page):',
						tooltip: 'Optional, but strongly recommended. Leave blank if not wanted. Only available if a single article name is entered.'
				break;
			case 'Not English':
			case 'Rough translation':
				checkbox.subgroup = [
						name: 'translationLanguage',
						type: 'input',
						label: 'Language of article (if known): ',
						tooltip: 'Consider looking at WP:LRC for help. If listing the article at PNT, please try to avoid leaving this box blank, unless you are completely unsure.'
				];
				if (tag === 'Not English') {
					checkbox.subgroup.push({
						name: 'translationNotify',
						type: 'checkbox',
						list: [
								label: 'Notify article creator',
								checked: true,
								tooltip: "Places on the creator's talk page."
						]
				if (mw.config.get('wgNamespaceNumber') === 0) {
					checkbox.subgroup.push({
						name: 'translationPostAtPNT',
						type: 'checkbox',
						list: [
								label: 'List this article at Wikipedia:Pages needing translation into English (PNT)',
								checked: true
						]
					checkbox.subgroup.push({
						name: 'translationComments',
						type: 'textarea',
						label: 'Additional comments to post at PNT',
						tooltip: 'Optional, and only relevant if "List this article ..." above is checked.'
				break;
			case 'Notability':
				checkbox.subgroup = {
					name: 'notability',
					type: 'select',
					list: [
					]
				break;
			default:
				break;
		return checkbox;

	var makeCheckboxesForAlreadyPresentTags = function {
		container.append;
		var subdiv = container.append;
		var checkboxes = [];
		var unCheckedTags = e.target.form.getUnchecked('existingTags');
		Twinkle.tag.alreadyPresentTags.forEach(function(tag) {
			var checkbox =
					value: tag,
					label: '' + (Twinkle.tag.article.flatObject[tag] ? ': ' + Twinkle.tag.article.flatObject[tag].description : ''),
					checked: unCheckedTags.indexOf(tag) === -1,
					style: 'font-style: italic'

			checkboxes.push(checkbox);
		subdiv.append({
			type: 'checkbox',
			name: 'existingTags',
			list: checkboxes

	if (sortorder === 'cat') { // categorical sort order
		// function to iterate through the tags and create a checkbox for each one
		var doCategoryCheckboxes = function {
			var checkboxes = [];
			$.each(subgroup, function {
				if (Twinkle.tag.alreadyPresentTags.indexOf(item.tag) === -1) {
					checkboxes.push(makeCheckbox);
			subdiv.append({
				type: 'checkbox',
				name: 'tags',
				list: checkboxes

		if (Twinkle.tag.alreadyPresentTags.length > 0) {
			makeCheckboxesForAlreadyPresentTags;
		var i = 1;
		// go through each category and sub-category and append lists of checkboxes
		$.each(Twinkle.tag.article.tagList, function {
			container.append;
			var subdiv = container.append;
			if (Array.isArray(group)) {
				doCategoryCheckboxes;
				$.each(group, function {
					subdiv.append({ type: 'div', label: [ Morebits.htmlNode ] });
					doCategoryCheckboxes;
		if (Twinkle.tag.alreadyPresentTags.length > 0) {
			makeCheckboxesForAlreadyPresentTags;
			container.append;

		// Avoid repeatedly resorting
		Twinkle.tag.article.alphabeticalList = Twinkle.tag.article.alphabeticalList || Object.keys(Twinkle.tag.article.flatObject).sort;
		var checkboxes = [];
		Twinkle.tag.article.alphabeticalList.forEach(function(tag) {
			if (Twinkle.tag.alreadyPresentTags.indexOf(tag) === -1) {
				checkboxes.push(makeCheckbox);
		container.append({
			type: 'checkbox',
			name: 'tags',
			list: checkboxes

	// append any custom tags
	if (Twinkle.getPref('customTagList').length) {
		container.append;
		container.append({ type: 'checkbox', name: 'tags',
			list: Twinkle.getPref('customTagList').map(function(el) {
				el.checked = Twinkle.tag.checkedTags.indexOf(el.value) !== -1;
				return el;

	var $workarea = $(form).find('#tagWorkArea');
	var rendered = container.render;
	$workarea.empty.append(rendered);

	// for quick filter:
	$allCheckboxDivs = $workarea.find.parent;
	$allHeaders = $workarea.find;
	form.quickfilter.value = ''; // clear search, because the search results are not preserved over mode change
	form.quickfilter.focus;

	// style adjustments
	$workarea.find('h5').css({ 'font-size': '110%' });
	$workarea.find('h5:not(:first-child)').css({ 'margin-top': '1em' });
	$workarea.find('div').filter(':has(span.quickformDescription)').css({ 'margin-top': '0.4em' });

	Morebits.quickForm.getElements.forEach(generateLinks);
	Morebits.quickForm.getElements.forEach(generateLinks);

	// tally tags added/removed, update statusNode text
	var statusNode = document.getElementById('tw-tag-status');
	$.click(function {
		if (this.name === 'tags') {
			Twinkle.tag.status.numAdded += this.checked ? 1 : -1;
			Twinkle.tag.status.numRemoved += this.checked ? -1 : 1;

		var firstPart = 'Adding ' + Twinkle.tag.status.numAdded + ' tag' + (Twinkle.tag.status.numAdded > 1 ? 's' : '');
		var secondPart = 'Removing ' + Twinkle.tag.status.numRemoved + ' tag' + (Twinkle.tag.status.numRemoved > 1 ? 's' : '');
		statusNode.textContent =
			(Twinkle.tag.status.numAdded ? ' ' + firstPart : '') +
			(Twinkle.tag.status.numRemoved ? (Twinkle.tag.status.numAdded ? '; ' : ' ') + secondPart : '');

/**
var generateLinks = function(checkbox) {
	var link = Morebits.htmlNode;
	link.setAttribute;
	var tagname = checkbox.values;
	link.setAttribute('href', mw.util.getUrl(
		(tagname.indexOf(':') === -1 ? 'Template:' : '') +
		(tagname.indexOf('|') === -1 ? tagname : tagname.slice(0, tagname.indexOf('|')))
	));
	link.setAttribute;
	$(checkbox).parent.append;

// Tags for ARTICLES start here
Twinkle.tag.article = {};

// Tags arranged by category; will be used to generate the alphabetical list,
// but tags should be in alphabetical order within the categories
// excludeMI: true indicate a tag that *does not* work inside 
// Add new categories with discretion - the list is long enough as is!
Twinkle.tag.article.tagList = {
	'Cleanup and maintenance tags': {
		'General cleanup': [
		],
		'Potentially unwanted content': [
		],
		'Structure, formatting, and lead section': [
		],
		'Fiction-related cleanup': [
		]
	'General content issues': {
		'Importance and notability': [
		],
		'Style of writing': [
		],
		'Sense (or lack thereof)': [
		],
		'Information and detail': [
		],
		'Timeliness': [
		],
		'Neutrality, bias, and factual accuracy': [
		],
		'Verifiability and sources': [
		]
	'Specific content issues': {
		'Language': [
		],
		'Links': [
		],
		'Referencing technique': [
		],
		'Categories': [
		]
	'Merging': [
	],
	'Informational': [
	]

// Tags for REDIRECTS start here
// Not by policy, but the list roughly approximates items with >500
// transclusions from Template:R template index
Twinkle.tag.redirectList = {
	'Grammar, punctuation, and spelling': {
		'Abbreviation': [
		],
		'Capitalisation': [
		],
		'Grammar & punctuation': [
		],
		'Parts of speech': [
		],
		'Spelling': [
		]
	'Alternative names': {
		'General': [
				tag: 'R from alternative language',
				description: 'redirect from or to a title in another language',
				subgroup: [
						name: 'altLangFrom',
						type: 'input',
						label: 'From language (two-letter code): ',
						tooltip: 'Enter the two-letter code of the language the redirect name is in; such as en for English, de for German'
						name: 'altLangTo',
						type: 'input',
						label: 'To language (two-letter code): ',
						tooltip: 'Enter the two-letter code of the language the target name is in; such as en for English, de for German'
						name: 'altLangInfo',
						type: 'div',
						label: $.parseHTML('')
				]
		],
		'People': [
		],
		'Technical': [

		],
		'Organisms': [
		],
		'Geography': [
		]
	'Navigation aids': {
		'Navigation': [

		],
		'Disambiguation': [
		],
		'Merge, duplicate & move': [
		],
		'Namespace': [
		]
	'Media': {
		'General': [
		],
		'Fiction': [

		]
	'Miscellaneous': {
		'Related information': [
		],
		'With possibilities': [
		],
		'ISO codes': [
		],
		'Printworthiness': [
		]

// maintenance tags for FILES start here

Twinkle.tag.file = {};

Twinkle.tag.file.licenseList = [
];

Twinkle.tag.file.commonsList = [
		label: ' (other reason)',
		value: 'Do not move to Commons_reason',
		subgroup: {
			type: 'input',
			name: 'DoNotMoveToCommons',
			label: 'Reason: ',
			tooltip: 'Enter the reason why this image should not be moved to Commons (required)'
		label: ': request to keep local copy of a Commons file',
		value: 'Keep local',
		subgroup: {
			type: 'input',
			name: 'keeplocalName',
			label: 'Commons image name if different: ',
			tooltip: 'Name of the image on Commons (if different from local name), excluding the File: prefix:'
		label: ': file has been copied to Commons',
		value: 'Now Commons',
		subgroup: {
			type: 'input',
			name: 'nowcommonsName',
			label: 'Commons image name if different: ',
			tooltip: 'Name of the image on Commons (if different from local name), excluding the File: prefix:'
];

Twinkle.tag.file.cleanupList = [
		label: ': general cleanup', value: 'Cleanup image',
		subgroup: {
			type: 'input',
			name: 'cleanupimageReason',
			label: 'Reason: ',
			tooltip: 'Enter the reason for cleanup (required)'
		label: ': file should be renamed according to the criteria at WP:FMV',
		value: 'Rename media',
		subgroup: [
				type: 'input',
				name: 'renamemediaNewname',
				label: 'New name: ',
				tooltip: 'Enter the new name for the image (optional)'
				type: 'input',
				name: 'renamemediaReason',
				label: 'Reason: ',
				tooltip: 'Enter the reason for the rename (optional)'
		]
		label: ': PNG, GIF or JPEG should be vector graphics', value: 'Should be SVG',
		subgroup: {
			name: 'svgCategory',
			type: 'select',
			list: [
			]
];

Twinkle.tag.file.qualityList = [
		label: '', value: 'Image-Poor-Quality',
		subgroup: {
			type: 'input',
			name: 'ImagePoorQualityReason',
			label: 'Reason: ',
			tooltip: 'Enter the reason why this image is so bad (required)'
		label: ': disputed chemical structures', value: 'Low quality chem',
		subgroup: {
			type: 'input',
			name: 'lowQualityChemReason',
			label: 'Reason: ',
			tooltip: 'Enter the reason why the diagram is disputed (required)'
];

Twinkle.tag.file.replacementList = [
];
Twinkle.tag.file.replacementList.forEach(function(el) {
	el.subgroup = {
		type: 'input',
		label: 'Replacement file: ',
		tooltip: 'Enter the name of the file which replaces this one (required)',
		name: el.value.replace + 'File'

Twinkle.tag.callbacks = {
	article: function articleCallback(pageobj) {

		// Remove tags that become superfluous with this action
		var pageText = pageobj.getPageText.replace(/\{\{\s*([Uu]serspace draft)\s*(\|(?:\{\{[^{}]*\}\}|[^{}])*)?\}\}\s*/g, '');
		var params = pageobj.getCallbackParameters;

		/**
		var postRemoval = function {
			if (params.tagsToRemove.length) {
				// Remove empty if found
				pageText = pageText.replace(/\{\{(multiple ?issues|article ?issues|mi)\s*\|\s*\}\}\n?/im, '');
				// Remove single-element if found
				pageText = pageText.replace(/\{\{(?:multiple ?issues|article ?issues|mi)\s*\|\s*(\{\{[^}]+\}\})\s*\}\}/im, '$1');

			// Build edit summary
			var makeSentence = function(array) {
				if (array.length < 3) {
					return array.join(' and ');
				var last = array.pop;
				return array.join + ', and ' + last;
			var makeTemplateLink = function(tag) {
				var text = '';

			var summaryText;
			var addedTags = params.tags.map(makeTemplateLink);
			var removedTags = params.tagsToRemove.map(makeTemplateLink);
			if (addedTags.length) {
				summaryText = 'Added ' + makeSentence(addedTags);
				summaryText += removedTags.length ? '; and removed ' + makeSentence(removedTags) : '';
				summaryText = 'Removed ' + makeSentence(removedTags);
			summaryText += ' tag' + (addedTags.length + removedTags.length > 1 ? 's' : '');
			if (params.reason) {
				summaryText += ': ' + params.reason;

			// avoid truncated summaries
			if (summaryText.length > (499 - Twinkle.getPref('summaryAd').length)) {
				summaryText = summaryText.replace(/\[\[[^|]+\|([^\]]+)\]\]/g, '$1');

			pageobj.setPageText(pageText);
			pageobj.setEditSummary(summaryText + Twinkle.getPref('summaryAd'));
			pageobj.setWatchlist(Twinkle.getPref('watchTaggedPages'));
			pageobj.setMinorEdit(Twinkle.getPref('markTaggedPagesAsMinor'));
			pageobj.setCreateOption('nocreate');
			pageobj.save(function {
				// special functions for merge tags
				if (params.mergeReason) {
					// post the rationale on the talk page (only operates in main namespace)
					var talkpageText = '\n\n== ' + params.talkDiscussionTitleLinked + ' ==\n\n';
					talkpageText += params.mergeReason.trim + ' ~~~~';
					var talkpage = new Morebits.wiki.page;
					talkpage.setAppendText(talkpageText);
					talkpage.setEditSummary('/* ' + params.talkDiscussionTitle + ' */ new section' + Twinkle.getPref('summaryAd'));
					talkpage.setWatchlist(Twinkle.getPref('watchMergeDiscussions'));
					talkpage.setCreateOption('recreate');
					talkpage.append;
				if (params.mergeTagOther) {
					// tag the target page if requested
					var otherTagName = 'Merge';
					if (params.mergeTag === 'Merge from') {
						otherTagName = 'Merge to';
						otherTagName = 'Merge from';
					var newParams = {
						tags: [otherTagName],
						tagsToRemove: [],
						tagsToRemain: [],
						mergeTarget: Morebits.pageNameNorm,
						discussArticle: params.discussArticle,
						talkDiscussionTitle: params.talkDiscussionTitle,
						talkDiscussionTitleLinked: params.talkDiscussionTitleLinked
					var otherpage = new Morebits.wiki.page(params.mergeTarget, 'Tagging other page (' +
						params.mergeTarget + ')');
					otherpage.setCallbackParameters(newParams);
					otherpage.load(Twinkle.tag.callbacks.article);

				// post at WP:PNT for and tag
				if (params.translationPostAtPNT) {
					var pntPage = new Morebits.wiki.page;
					pntPage.setFollowRedirect(true);
					pntPage.load(function friendlytagCallbacksTranslationListPage(pageobj) {
						var old_text = pageobj.getPageText;

						var template = params.tags.indexOf('Rough translation') !== -1 ? 'duflu' : 'needtrans';
						var lang = params.translationLanguage;
						var reason = params.translationComments;

						var templateText = ' ~~~~';

						var text, summary;
						if (template === 'duflu') {
							text = old_text + '\n\n' + templateText;
							summary = 'Translation cleanup requested on ';
							text = old_text.replace(/\n+(==\s?Translated pages that could still use some cleanup\s?==)/,
								'\n\n' + templateText + '\n\n$1');
							summary = 'Translation' + (lang ? ' from ' + lang : '') + ' requested on ';

						if (text === old_text) {
							pageobj.getStatusElement.error('failed to find target spot for the discussion');
							return;
						pageobj.setPageText(text);
						pageobj.setEditSummary(summary + ' :' + Morebits.pageNameNorm + '' + Twinkle.getPref('summaryAd'));
						pageobj.setCreateOption('recreate');
						pageobj.save;
				if (params.translationNotify) {
					pageobj.lookupCreation(function(innerPageobj) {
						var initialContrib = innerPageobj.getCreator;

						// Disallow warning yourself
						if (initialContrib === mw.config.get('wgUserName')) {
							innerPageobj.getStatusElement.warn('You (' + initialContrib + ') created this page; skipping user notification');
							return;

						var userTalkPage = new Morebits.wiki.page('User talk:' + initialContrib,
							'Notifying initial contributor (' + initialContrib + ')');
						var notifytext = '\n\n== Your article ' + Morebits.pageNameNorm + '==\n' +
							' ~~~~';
						userTalkPage.setAppendText(notifytext);
						userTalkPage.setEditSummary('Notice: Please use English when contributing to the English Wikipedia.' +
							Twinkle.getPref('summaryAd'));
						userTalkPage.setCreateOption('recreate');
						userTalkPage.setFollowRedirect;
						userTalkPage.append;

			if (params.patrol) {
				pageobj.triage;

		/**
		var removeTags = function removeTags {

			if (params.tagsToRemove.length === 0) {
				postRemoval;
				return;

			Morebits.status.info;

			var getRedirectsFor = [];

			// Remove the tags from the page text, if found in its proper name,
			// otherwise moves it to `getRedirectsFor` array earmarking it for
			// later removal
			params.tagsToRemove.forEach(function removeTag(tag) {
				var tag_re = new RegExp('\\{\\{' + Morebits.pageNameRegex(tag) + '\\s*(\\|[^}]+)?\\}\\}\\n?');

				if (tag_re.test(pageText)) {
					pageText = pageText.replace;
					getRedirectsFor.push('Template:' + tag);

			if (!getRedirectsFor.length) {
				postRemoval;
				return;

			// Remove tags which appear in page text as redirects
			var api = new Morebits.wiki.api('Getting template redirects', {
				'action': 'query',
				'prop': 'linkshere',
				'titles': getRedirectsFor.join('|'),
				'redirects': 1, // follow redirect if the class name turns out to be a redirect page
				'lhnamespace': '10', // template namespace only
				'lhshow': 'redirect',
				'lhlimit': 'max' // 500 is max for normal users, 5000 for bots and sysops

				$(apiobj.responseXML).find('page').each(function {
					var removed = false;
					$(page).find('lh').each(function {
						var tag = $(el).attr('title').slice(9);
						var tag_re = new RegExp('\\{\\{' + Morebits.pageNameRegex(tag) + '\\s*(\\|[^}]*)?\\}\\}\\n?');
						if (tag_re.test(pageText)) {
							pageText = pageText.replace;
							removed = true;
							return false; // break out of $.each
					if (!removed) {
						Morebits.status.warn;

				postRemoval;

			api.post;

		if (!params.tags.length) {
			removeTags;
			return;

		var tagRe, tagText = '', tags = [], groupableTags = [], groupableExistingTags = [];
		// Executes first: addition of selected tags

		/**
		var addTag = function articleAddTag {
			var currentTag = '';
			if (tagName === 'Uncategorized' || tagName === 'Improve categories') {
				pageText += '\n\n }}';
				currentTag += ' }}\n';
				tagText += currentTag;

		/**
		var addUngroupedTags = function {
			$.each;

			// Insert tag after short description or any hatnotes,
			// as well as deletion/protection-related templates
			var wikipage = new Morebits.wikitext.page(pageText);
			var templatesAfter = Twinkle.hatnoteRegex +
				// Protection templates
				'pp|pp-.*?|' +
				// CSD
				'db|delete|db-.*?|speedy deletion-.*?|' +
				// PROD
				'(?:proposed deletion|prod blp)\\/dated(?:\\s*\\|(?:concern|user|timestamp|help).*)+|' +
				// not a hatnote, but sometimes under a CSD or AfD
				'salt|proposed deletion endorsed';
			// AfD is special, as the tag includes html comments before and after the actual template
			// trailing whitespace/newline needed since this subst's a newline
			var afdRegex = '(?:<!--.*AfD.*\\n\\{\\{(?:Article for deletion\\/dated|AfDM).*\\}\\}\\n<!--.*(?:\\n<!--.*)?AfD.*(?:\\s*\\n))?';
			pageText = wikipage.insertAfterTemplates.getText;

			removeTags;

		// Separate tags into groupable ones (`groupableTags`) and non-groupable ones (`tags`)
		params.tags.forEach(function(tag) {
			tagRe = new RegExp('\\{\\{' + tag + '(\\||\\}\\})', 'im');
			// regex check for preexistence of tag can be skipped if in canRemove mode
			if (Twinkle.tag.canRemove || !tagRe.exec(pageText)) {
				// condition Twinkle.tag.article.tags[tag] to ensure that its not a custom tag
				// Custom tags are assumed non-groupable, since we don't know whether MI template supports them
				if (Twinkle.tag.article.flatObject[tag] && !Twinkle.tag.article.flatObject[tag].excludeMI) {
					groupableTags.push(tag);
					tags.push(tag);
				if (tag === 'Merge from' || tag === 'History merge') {
					tags.push(tag);
					Morebits.status.warn;
					// don't do anything else with merge tags
					if (['Merge', 'Merge to'].indexOf(tag) !== -1) {
						params.mergeTarget = params.mergeReason = params.mergeTagOther = null;

		// To-be-retained existing tags that are groupable
		params.tagsToRemain.forEach(function(tag) {
			if (!Twinkle.tag.article.flatObject[tag].excludeMI) {
				groupableExistingTags.push(tag);

		var miTest = /\{\{(multiple ?issues|article ?issues|mi)(?!\s*\|\s*section\s*=)[^}]+\{/im.exec(pageText);

		if (miTest && groupableTags.length > 0) {
			Morebits.status.info;

			tagText = '';
			$.each;

			var miRegex = new RegExp('(\\{\\{\\s*' + miTest[1] + '\\s*(?:\\|(?:\\{\\{[^{}]*\\}\\}|[^{}])*)?)\\}\\}\\s*', 'im');
			pageText = pageText.replace;
			tagText = '';

			addUngroupedTags;

			Morebits.status.info;

			tagText += '\n';

				addUngroupedTags;

			var getRedirectsFor = [];

			// Reposition the tags on the page into , if found with its
			// proper name, else moves it to `getRedirectsFor` array to be handled later
			groupableExistingTags.forEach(function repositionTagIntoMI(tag) {
				var tag_re = new RegExp('(\\{\\{' + Morebits.pageNameRegex(tag) + '\\s*(\\|[^}]+)?\\}\\}\\n?)');
				if (tag_re.test(pageText)) {
					tagText += tag_re.exec(pageText)[1];
					pageText = pageText.replace;
					getRedirectsFor.push('Template:' + tag);

			if (!getRedirectsFor.length) {
				addNewTagsToMI;
				return;

			var api = new Morebits.wiki.api('Getting template redirects', {
				'action': 'query',
				'prop': 'linkshere',
				'titles': getRedirectsFor.join('|'),
				'redirects': 1,
				'lhnamespace': '10', // template namespace only
				'lhshow': 'redirect',
				'lhlimit': 'max' // 500 is max for normal users, 5000 for bots and sysops
				$(apiobj.responseXML).find('page').each(function {
					var found = false;
					$(page).find('lh').each(function {
						var tag = $(el).attr('title').slice(9);
						var tag_re = new RegExp('(\\{\\{' + Morebits.pageNameRegex(tag) + '\\s*(\\|[^}]*)?\\}\\}\\n?)');
						if (tag_re.test(pageText)) {
							tagText += tag_re.exec(pageText)[1];
							pageText = pageText.replace;
							found = true;
							return false; // break out of $.each
					if (!found) {
						Morebits.status.warn;
				addNewTagsToMI;
			api.post;

			tags = tags.concat(groupableTags);
			addUngroupedTags;

	redirect: function redirect(pageobj) {
		var params = pageobj.getCallbackParameters,
			pageText = pageobj.getPageText,
			tagRe, tagText = '', summaryText = 'Added',
			tags = [], i;

		for (i = 0; i < params.tags.length; i++) {
			tagRe = new RegExp('(\\{\\{' + params.tags[i] + '(\\||\\}\\}))', 'im');
			if (!tagRe.exec(pageText)) {
				tags.push(params.tags[i]);
				Morebits.status.warn;

		var addTag = function redirectAddTag {
			tagText += '\n';

			if (tagIndex > 0) {
				if (tagIndex === (tags.length - 1)) {
					summaryText += ' and';
					summaryText += ',';

			summaryText += ' ';

		if (!tags.length) {
			Morebits.status.warn;

		tags.sort;
		$.each;

		// Check for all Rcat shell redirects (from #433)
		if (pageText.match(/{{(?:redr|this is a redirect|r(?:edirect)?(?:.?cat.*)?[ _]?sh)/i)) {
			// Regex inspired by User:Kephir/gadgets/sagittarius.js (Special:PermaLink/831402893)
			var oldTags = pageText.match(/(\s*{{[A-Za-z ]+\|)((?:[^|{}]*|{{[^}]*}})+)(}})\s*/i);
			pageText = pageText.replace;
			// Fold any pre-existing Rcats into taglist and under Rcatshell
			var pageTags = pageText.match(/\s*/img);
			var oldPageTags = '';
			if (pageTags) {
				pageTags.forEach(function(pageTag) {
					var pageRe = new RegExp;
					pageText = pageText.replace;
					pageTag = pageTag.trim;
					oldPageTags += '\n' + pageTag;
			pageText += '\n';

		summaryText += (tags.length > 0 ? ' tag' + (tags.length > 1 ? 's' : ' ') : 'rcat shell') + ' to redirect';

		// avoid truncated summaries
		if (summaryText.length > (499 - Twinkle.getPref('summaryAd').length)) {
			summaryText = summaryText.replace(/\[\[[^|]+\|([^\]]+)\]\]/g, '$1');

		pageobj.setPageText(pageText);
		pageobj.setEditSummary(summaryText + Twinkle.getPref('summaryAd'));
		pageobj.setWatchlist(Twinkle.getPref('watchTaggedPages'));
		pageobj.setMinorEdit(Twinkle.getPref('markTaggedPagesAsMinor'));
		pageobj.setCreateOption('nocreate');
		pageobj.save;

		if (params.patrol) {
			pageobj.triage;

	file: function friendlytagCallbacksFile(pageobj) {
		var text = pageobj.getPageText;
		var params = pageobj.getCallbackParameters;
		var summary = 'Adding ';

		// Add maintenance tags
		if (params.tags.length) {

			var tagtext = '', currentTag;
			$.each(params.tags, function {
				// when other commons-related tags are placed, remove "move to Commons" tag
				if (['Keep local', 'Now Commons', 'Do not move to Commons_reason', 'Do not move to Commons'].indexOf(tag) !== -1) {
					text = text.replace(/\{\{(mtc|(copy |move )?to ?commons|move to wikimedia commons|copy to wikimedia commons)[^}]*\}\}/gi, '');

				currentTag = tag === 'Do not move to Commons_reason' ? 'Do not move to Commons' : tag;

				switch (tag) {
					case 'Now Commons':
						currentTag = 'subst:' + currentTag; // subst
						if (params.nowcommonsName !== '') {
							currentTag += '|1=' + params.nowcommonsName;
						break;
					case 'Keep local':
						if (params.keeplocalName !== '') {
							currentTag += '|1=' + params.keeplocalName;
						break;
					case 'Rename media':
						if (params.renamemediaNewname !== '') {
							currentTag += '|1=' + params.renamemediaNewname;
						if (params.renamemediaReason !== '') {
							currentTag += '|2=' + params.renamemediaReason;
						break;
					case 'Cleanup image':
						currentTag += '|1=' + params.cleanupimageReason;
						break;
					case 'Image-Poor-Quality':
						currentTag += '|1=' + params.ImagePoorQualityReason;
						break;
					case 'Low quality chem':
						currentTag += '|1=' + params.lowQualityChemReason;
						break;
					case 'Vector version available':
						text = text.replace(/\{\{((convert to |convertto|should be |shouldbe|to)?svg|badpng|vectorize)[^}]*\}\}/gi, '');
						/* falls through */
					case 'PNG version available':
						/* falls through */
					case 'Obsolete':
						currentTag += '|1=' + params[tag.replace + 'File'];
						break;
					case 'Do not move to Commons_reason':
						currentTag += '|reason=' + params.DoNotMoveToCommons;
						break;
					case 'Orphaned non-free revisions':
						currentTag = 'subst:' + currentTag; // subst
						// remove and redirects
						text = text.replace(/\{\{\s*(Template\s*:\s*)?(Non-free reduce|FairUseReduce|Fairusereduce|Fair Use Reduce|Fair use reduce|Reduce size|Reduce|Fair-use reduce|Image-toobig|Comic-ovrsize-img|Non-free-reduce|Nfr|Smaller image|Nonfree reduce)\s*(\|(?:\{\{[^{}]*\}\}|[^{}])*)?\}\}\s*/ig, '');
						currentTag += '|date=';
						break;
					case 'Copy to Commons':
						currentTag += '|human=' + mw.config.get('wgUserName');
						break;
					case 'Should be SVG':
						currentTag += '|' + params.svgCategory;
						break;
					default:
						break; // don't care

				currentTag = '\n';

				tagtext += currentTag;
				summary += ', ';

			if (!tagtext) {
				pageobj.getStatusElement.warn('User canceled operation; nothing to do');
				return;

			text = tagtext + text;

		pageobj.setPageText(text);
		pageobj.setEditSummary(summary.substring + Twinkle.getPref('summaryAd'));
		pageobj.setWatchlist(Twinkle.getPref('watchTaggedPages'));
		pageobj.setMinorEdit(Twinkle.getPref('markTaggedPagesAsMinor'));
		pageobj.setCreateOption('nocreate');
		pageobj.save;

		if (params.patrol) {
			pageobj.triage;

Twinkle.tag.callback.evaluate = function friendlytagCallbackEvaluate(e) {
	var form = e.target;
	var params = Morebits.quickForm.getInputData(form);

	// Validation

	// Given an array of incompatible tags, check if we have two or more selected
	var checkIncompatible = function {
		var count = conflicts.reduce(function {
			return sum += params.tags.indexOf(tag) !== -1;
		if (count > 1) {
			var message = 'Please select only one of: , .';
			message += extra ? ' ' + extra : '';
			alert(message);
			return true;
	// Given a tag, ensure an associate parameter is present
	// Maybe just sock this away in each function???
	var checkParameter = function {
		description = description || 'a reason';
		if (params.tags.indexOf(tag) !== -1 && params[parameter].trim === '') {
			alert('You must specify ' + description + ' for the tag.');
			return true;

	// We could theoretically put them all checkIncompatible calls in a
	// forEach loop, but it's probably clearer not to have [[array one],
	// [array two]] devoid of context. Likewise, all the checkParameter
	// calls could be in one if, but could be similarly confusing.
	switch (Twinkle.tag.mode) {
		case 'article':
			params.tagsToRemove = form.getUnchecked('existingTags'); // not in `input`
			params.tagsToRemain = params.existingTags || []; // container not created if none present

			if ((params.tags.indexOf('Merge') !== -1) || (params.tags.indexOf('Merge from') !== -1) ||
				(params.tags.indexOf('Merge to') !== -1)) {
				if (checkIncompatible(['Merge', 'Merge from', 'Merge to'], 'If several merges are required, use and separate the article names with pipes (although in this case Twinkle cannot tag the other articles automatically).')) {
					return;
				if (!params.mergeTarget) {
					alert('Please specify the title of the other article for use in the merge template.');
					return;
				if ((params.mergeTagOther || params.mergeReason) && params.mergeTarget.indexOf('|') !== -1) {
					alert;
					return;

			if (checkIncompatible) {
				return;
			if (checkParameter) {
				return;
			if (checkParameter) {
				return;
			if (checkParameter) {
				return;
			break;

		case 'file':
			if (checkIncompatible) {
				return;
			if (checkIncompatible) {
				return;
			if (checkIncompatible) {
				return;
			if (checkIncompatible) {
				return;
			if (checkIncompatible) {
				return;

			// Get extension from either mime-type or title, if not present 
			var extension = ((extension = $('.mime-type').text) && extension.split(/\//)[1]) || mw.Title.newFromText(Morebits.pageNameNorm).getExtension;
			if (extension) {
				var extensionUpper = extension.toUpperCase;

				// What self-respecting file format has *two* extensions?!
				if (extensionUpper === 'JPG') {
					extension = 'JPEG';

				// We've already ensured above that there can be only one of and ,
				// so these check that it actually matches the file's actual extension. We need to check
				// if any tags start with a string, which means using string's indexOf, since can't
				// use ES6y things like find or findIndex.

				// Bad GIF|JPEG|SVG
				if ((params.tags.toString.indexOf('Bad ') !== -1) && (params.tags.indexOf('Bad ' + extensionUpper) === -1)) {
					alert;
					return;
				// Should be PNG|SVG
				if ((params.tags.toString.indexOf('Should be ') !== -1) && (params.tags.indexOf('Should be ' + extensionUpper) === -1)) {
					alert;
					return;

				// Overcompressed JPEG
				if (params.tags.indexOf('Overcompressed JPEG') !== -1 && extensionUpper !== 'JPEG') {
					alert;
					return;
				// Bad trace and Bad font
				if (extensionUpper !== 'SVG') {
					if (params.tags.indexOf('Bad trace') !== -1) {
						alert;
						return;
						alert;
						return;

			if (checkParameter) {
				return;
			if (checkParameter) {
				return;
			if (checkParameter) {
				return;
			// Silly to provide the same string to each of these
			if (checkParameter ||
				checkParameter ||
				checkParameter) {
				return;
			if (checkParameter) {
				return;
			break;

		case 'redirect':
			break;

		default:
			alert('Twinkle.tag: unknown mode ' + Twinkle.tag.mode);
			break;

	// File/redirect: return if no tags selected
	// Article: return if no tag is selected and no already present tag is deselected
	if (params.tags.length === 0 && (Twinkle.tag.mode !== 'article' || params.tagsToRemove.length === 0)) {
		alert('You must select at least one tag!');
		return;

	Morebits.simpleWindow.setButtonsEnabled(false);
	Morebits.status.init(form);

	Morebits.wiki.actionCompleted.redirect = Morebits.pageNameNorm;
	Morebits.wiki.actionCompleted.notice = 'Tagging complete, reloading article in a few seconds';
	if (Twinkle.tag.mode === 'redirect') {
		Morebits.wiki.actionCompleted.followRedirect = false;

	var wikipedia_page = new Morebits.wiki.page;
	wikipedia_page.setCallbackParameters(params);
	wikipedia_page.load(Twinkle.tag.callbacks[Twinkle.tag.mode]);

Twinkle.addInitCallback;