Jump to content

User:Fish bowl/global.js

From Meta, a Wikimedia project coordination wiki
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5.
mw.loader.load('//en.wiktionary.org/w/index.php?title=User:Fish_bowl/AjaxEdit.js&action=raw&ctype=text/javascript');
//mw.loader.load('//en.wiktionary.org/w/index.php?title=MediaWiki:Gadget-AjaxEdit.js&action=raw&ctype=text/javascript');
//mw.loader.load('//en.wikipedia.org/w/index.php?title=MediaWiki:Gadget-edittop.js&action=raw&ctype=text/javascript');
mw.loader.load('//en.wikipedia.org/w/index.php?title=User:Gary/comments_in_local_time.js&action=raw&ctype=text/javascript');

// <nowiki>

String.prototype.contains = function(text) {
	return this.indexOf(text) > -1;
};

var tB = document.getElementById('wpTextbox1');
tB = (tB ? tB.value : '');

// Wikisource
if (mw.config.get('wgNoticeProject') === 'wikisource') {
	// OCR
	if (0) {
		mw.loader.load('//wikisource.org/w/index.php?title=MediaWiki:OCR.js&action=raw&ctype=text/javascript');
		mw.loader.load('//wikisource.org/w/index.php?title=MediaWiki:GoogleOCR.js&action=raw&ctype=text/javascript');
	}

	// add page numbers
	if (mw.config.get('wgContentLanguage') !== 'en') {
		mw.loader.load('//en.wikisource.org/w/index.php?title=MediaWiki:PageNumbers.js&action=raw&ctype=text/javascript');
	}

	// henkan
	if (0) {
		mw.loader.load('//ja.wikisource.org/w/index.php?title=User:CES1596/MediaWiki-Gadget-to-old-char0.js&action=raw&ctype=text/javascript');
		mw.loader.load('//ja.wikisource.org/w/index.php?title=User:CES1596/MediaWiki-Gadget-to-old-char2.js&action=raw&ctype=text/javascript');
		mw.loader.load('//ja.wikisource.org/w/index.php?title=User:CES1596/MediaWiki-Gadget-to-old-char3.js&action=raw&ctype=text/javascript');
	}
}

// https://meta.wikimedia.org/wiki/TemplateScript
$.ajax('//tools-static.wmflabs.org/meta/scripts/pathoschild.templatescript.js', { dataType:'script', cache:true }).then(function() {
	pathoschild.TemplateScript.add({
		name: 'unified zh',
		enabled: tB.contains('===Hanzi===') || (tB.contains('===Han character===') && !tB.contains('===Definitions===')),
		script: function(editor) {
			//window.open('https://cjjc.weblio.jp/content/' + mw.config.get('wgPageName'));
			editor
				.replace(/==(Cantonese|Mandarin)==[\s\S]+(?=\n==(Cantonese|Mandarin)==|)/g, '')
				.replace(/((.+Han ref.+\n)+)/, '$1' + '\n' + '{' + '{subst:#invoke:User:Suzukaze-c/02|newhz}}')
				.appendEditSummary('unified Chinese')
				.clickDiff()
			;
		}
	});
	pathoschild.TemplateScript.add({
		name: 'ja-readings',
		enabled: tB.contains('{{ja-readings'),
		script: function(editor) {
			editor
				.replace(/(\*? ?)\{\{ja-readings/g, '{' + '{subst:#invoke:User:Suzukaze-c/02|test_13')
				.appendEditSummary('{{ja-readings}} update')
				.clickDiff()
			;
		}
	});
	pathoschild.TemplateScript.add({
		name: 'to ja-r',
		enabled: mw.config.get('wgNoticeProject') === 'wiktionary',
		script: function(editor) {
			editor
				.replace(/({{ja-l\|)([^|}]+)(}})/g, '[[$2]]')
				.replace(/({{ja-l)(\|[^|}]+)(\|[^|}]+)?(\|[^|}]+)?(\|[^|}]+)?}}/g, '{{ja-r$2$3$5}}')
				.replace(/({{[lm][|/]ja\||\[\[)([々あ-龥]+)(}}|\]\]) \([^あ-ー()]*([あ-ー]+)[^あ-ー()]*\)/g, '{{ja-r|$2|$4}}')
				.replace(/({{[lm][|/]ja\|)/g, '{' + '{subst:#invoke:User:Suzukaze-c/02|r|')
				.replace(/(\[\[)([々あ-龥]+)(\]\])/g, '{' + '{subst:#invoke:User:Suzukaze-c/02|r|$2}}')
				.appendEditSummary('use {{ja-r}}')
				.clickDiff()
			;
		}
	});
	pathoschild.TemplateScript.add({
		name: 'to ja-see',
		enabled: mw.config.get('wgNoticeProject') === 'wiktionary',
		script: function(editor) {
			editor
				.replace(/(==Japanese==)([\s\S]+)(----|$)/g, function(all, header, content, footer) {
					var a = [];
					content.replace(/{{ja-def\|(.+)}}/g, function(all, entry) { a.push(entry) });
					return header + '\n{{ja-see|' + a.join('|') + '}}' + footer;
				})
				.appendEditSummary(document.getElementById('wpTextbox1').value.match(/{{ja-see.+?}}/g).join(' '))
			;
		}
	});
	pathoschild.TemplateScript.add({
		name: 'ko l',
		enabled: mw.config.get('wgNoticeProject') === 'wiktionary',
		script: function(editor) {
			editor
				.replace(/ko-inline/g, 'ko-l')
				.replace(/\|4=/g, '|')
				.replace(
					/([가-힣]*)(?:{{ko-l\||\[\[)([가-힣 ]+)(?:}}|\]\])([가-힣]*) \(([㐀-鿕\[\]-]*)[^)]*\) ?([^\n]+)?/g,
					function(_, hangA, hangB, hangC, hani, gloss) {
						return '{{l|ko|' + hangA + hangB + hangC + (hani ? '(' + hani.replace(/[\[\]]/g, '').replace(/-/g, '▼') + ')' : '') + (gloss ? '|t=' + gloss : '') + '}}';
					}
				)
				.replace(/{{ko-l\|(.*?)}}/gm, function(_, sub) {
						sub = sub.replace(/\|+/g, '|');
						sub = sub.replace(/\|\}/g, '}');
						i = '';

						sub = sub.replace(/([ㅅㅁㄴㄹ가-힣]+)(.*)\|([㐀-鿕‒—]+)/g, '$1($3)$2');

						sub = sub.replace(/(\[\[|\{\{)(.+)(\]\]|\}\})?/g, function(match) { return match.replace(/\|/g, '|') } ); // ignore wikilinks and templates. last brackets are optional bc $sub could sth like "말나리||{{taxlink|Lilium distichum|species|noshow=1"

						var rebuild = [];
						var q = undefined;
						sub.split('|').forEach(function(param) {
							if (param.match(/^''/)) {
								param = "pos" + i + "=" + param.replace(/''/g, '');
							} else if (param.match(/^gloss=/)) {
								param = "t" + i + "=" + param.replace(/^gloss=/g, '');
							} else if (param.match(/^tr=/)) {
								param = "tr" + i + "=" + param.replace(/^tr=/g, '');
							} else if (param.match(/^5=/)) {
								q = param.replace(/^5=/g, '');
								return;
							} else if (!param.match(/[ㅅㅁㄴㄹ가-힣]+/)) {
								param = "t" + i + "=" + param;
							} else if (param.match(/[ㅅㅁㄴㄹ가-힣]+/) && param.match(/^[^-].*-$/)) {
								param = "[[" + param.replace(/-/, "다") + "|" + param + "]]";
							}
							rebuild.push(param);
						});
						i++;

						return '{{l|ko|' + rebuild.join('|') + '}}' + (q ? ' {{q|' + q + '}}' : '');
				})
				.replace(/|/g, '|') // restore wikilinks and templates
				.replace(/ko\|-}} {{l\|ko\|/g, 'ko|') // ety
				.replace(/^\|{{[lm]\|ko\|(.+)}}: (.+)/gm, function(_, params, t) {
					return '|' + params.replace(/\|([^=]+?)=([^|]+)/, '<$1:$2>') + '<t:' + t + '>';
				})
				.replace(/^\|(?:{{q\|([^}]+?)}} )?{{[lm]\|ko\|(.+?)}}(?: {{q\|([^}]+?)}})?/gm, function(_, q1, params, q2) {
					return '|' + params.replace(/\|\|/g, '|t=').replace(/\|([^=]+?)=([^|]+)/g, '<$1:$2>').replace(/>\|(.+)/g, '|$1>') + (q1 ? '<q:' + q1 + '>' : '') + (q2 ? '<q:' + q2 + '>' : '');
				}) // {{der2}}; the last replace is to resolve `<t:[[link>|alt]]` problems
				.replace(/\(''([^\)]+)''\)/g, '{{q|$1}}')
				.replace(/([a-z,.]) {{l\|ko\|/g, '$1 {{m|ko|')
				.appendEditSummary('replace {{ko-l}}')
				.clickDiff()
			;
		}
	});
	pathoschild.TemplateScript.add({
		name: 'ko com, af',
		enabled: mw.config.get('wgNoticeProject') === 'wiktionary',
		script: function(editor) {
			var compound_new = '';
			editor
				.replace(/&nbsp;\+&nbsp;/gm, ' + ')
				.replace(/the ([^{}]+?) {{ko-l\|(.+?)}}/gm, "{{ko-l|-$2|''$1''}}") // /[^{}]+/: [[귀밑털]]
				.replace(/(\+|and) (the suffix|the native Korean verb)/gm, ' + ')
				.replace(/and ({{ko-l\|)/gm, ' + $1')
				.replace(/({{ko-l\|(.*?)}}(?: *\+ *|[.,]|$)){2,}/gm, function(all) {
					all = all.replace(/—|–/g, '-');
					all = all.replace(/\|+/g, '|');
					all = all.replace(/\|\}/g, '}');
					all = all.replace(/\|(하다|되다)/g, '|-$1');

					var i = 1;
					all = all.replace(/{{ko-l\|(.*?)}}(?: *\+ *|[.,]|$)/gm, function(_, sub) {
						sub = sub.replace(/([ㅅㅁㄴㄹ가-힣]+)(.*)\|(?:\d=)?([㐀-鿕]+)/g, '$1($3)$2');

						var rebuild = [];
						sub.split('|').forEach(function(param) {
							if (param.match(/^''/)) {
								param = "pos" + i + "=" + param.replace(/''/g, '');
							} else if (!param.match(/[ㅅㅁㄴㄹ가-힣]+/)) {
								param = "t" + i + "=" + param;
							} else if (param.match(/[ㅅㅁㄴㄹ가-힣]+/) && param.match(/^[^-].*-$/) && !param.match(/[()]/)) {
								param = "[[" + param.replace(/-/, "다") + "|" + param + "]]";
							}
							rebuild.push(param);
						});
						i++;
						return '|' + rebuild.join('|');
					});
					compound_new = '{{compound|ko' + all + '}}.';
					if (compound_new.match(/[{|]-[^ㅅ]|[^ㅅ]-[|}]/g)) {
						compound_new = compound_new.replace(/compound/, 'affix');
					}
					compound_new = compound_new.replace(/\-하다(\|t2=[^|}]+|\|pos2=[^|}]+)?\}\}/, '-하다|t2=to do|pos2=[[light verb]] deriving active verbs}}');
					compound_new = compound_new.replace(/\-되다(\|t2=[^|}]+|\|pos2=[^|}]+)?\}\}/, '-되다|t2=to become|pos2=[[light verb]] deriving active verbs}}');
					compound_new = compound_new.replace(/\-롭다(\|t2=[^|}]+|\|pos2=[^|}]+)?\}\}/, '-롭다|pos2=suffix deriving adjectives}}');
					return compound_new;
				})
				.appendEditSummary(compound_new)
				.clickDiff()
			;
		}
	});
	pathoschild.TemplateScript.add({
		name: 'ocr掃除',
		forNamespaces: 'page',
		script: function(editor) {
			// confirm, since Ctrl-Z won't work
			if (window.confirm("Clean OCR?")) {
				if (mw.config.get('wgContentLanguage') == 'ja') editor
					.replace(/〓究/g, '●硏究')
					.replace(/〓育/g, '●敎育')
					.replace(/〓師/g, '●敎師')
					.replace(/〓へ/g, '●敎へ')
					.replace(/布〓/g, '●布敎')
					.replace(/〓朝/g, '●淸朝')
					.replace(/〓論/g, '●槪論')
					.replace(/,/g, "●,")
					.replace(/·/g, '・') // katakana middle dot
				;

				if (mw.config.get('wgContentLanguage') == 'zh') editor
					.replace(/([晉普昔学宇郎篇及叉注台成合會欸挑妤随交卡裹頤])/g, '●$1') // 音、字、即、爲、又、註、合、或、令、曾、欵、拼、好、隨、文、本、裏、頭
					.replace(/油頭/g, '●汕頭')
					.replace(/拉了化/g, '●拉丁化')
					.replace(/爱/g, '●爰')
					.replace(/([文交][盲官宮])/g, '●文盲')

					.replace(/説/g, '說')

					.replace(/●(普通|普及|普遍)/g, '$1')
					.replace(/研究●會/g, '研究會')

					.replace(/[・]/g, '.') // katakana middle dot
					.replace(/['"]/g, '●')
					.replace(/、/g, "●、")
				;

				editor
					//.replace(/[‘’]/g, "'")
					//.replace(/[“”]/g, '"')
					.replace(/[˙·]/g, ".")
					.replace(/[°。]/g, "。")
					.replace(/、/g, "、")
					.replace(/ã/g, 'ā')
					.replace(/ẽ/g, 'ē')
					.replace(/ĩ/g, 'ī')
					.replace(/õ/g, 'ō')
					.replace(/ũ/g, 'ū')
					.replace(/ı/g, 'i')
					.replace(/[\[「]([^\[「」\]]+?)[」\]]/g, '「$1」') // mismatched brackets `[abc」`
					.replace(/眾/g, '衆')
					.replace(/為/g, '爲')
					//.replace(/教/g, '敎')
					.replace(/真/g, '眞')
					.replace(/吕/g, '呂')
					.replace(/宫/g, '宮')
					.replace(/别/g, '別')
					.replace(/内/g, '內')
					.replace(/○/g, '〇') // circle → zero
					.replace(/—/g, '&mdash;')
					.replace(/^-/gm, '&mdash;')
					.replace(/- *\n([^ ]+)/g, '〓$1\n') // join hyphenated word; insert newline after hyphenated word
					.replace(/[^ぁ-ヿ〇㐀-龥a-zA-Z0-9À-Þà-ÿāēīōū"'….,:;!?&〓●‘’“”\n\(\)\[\]。,、々「」『』【】〔〕-]/g, ' ') // restrict charset
					.replace(/[A-ZÀ-Þ]{3,}( [A-ZÀ-Þ]+)*/g, function(a) { return a[0] + a.slice(1).toLowerCase(); }) // remove SHOUTING
					.replace(/ *([\[\(]) */g, ' $1') // space brackets
					.replace(/ *([\]\)]) */g, '$1 ') // space brackets
					.replace(/ +([.,:;!?。-])/g, '$1') // space punctuation (/ +/ instead of /\s+/, for zh)
					.replace(/ +/g, ' ') // collapse consecutive spaces
					.replace(/(^ +| +$)/gm, '') // remove leading and trailing spaces
					.replace(/^\n+/g, '') // remove leading newlines
					.replace(/ *[.…]{3,} *\n?/gm, '……') // trim consecutive dots (table of contents, etc.)
					.replace(/(\S)"\s+(.+?\S)"/g, '$1 "$2"') // fix "weird quotation marks" ([[s:Page:Jstraitsrsa31-33.pdf/659]])
					.replace(/, ([A-Z])"/g, '〓 $2') // comma + caps
					//.replace(/^.{0,2}\n/gm, '') // remove lines of length <=2
					.replace(/^[^㐀-龥]{0,2}\n/gm, '') // remove lines of length <=2 (non-cjk only)
					//.replace(/^[^㐀-龥]{0,2}\n/gm, '\n') // remove lines of length <=2 (non-cjk only) (preserve newlines to appease the diff view)
					//.replace(/(\n+)(\w?)/g, function(a, s, letter) { return (s.length > 1 ? '\n\n' : (letter.toUpperCase() === letter ? '\n' : ' ')) + letter; })
				;

				if (mw.config.get('wgContentLanguage') == 'zh' || mw.config.get('wgContentLanguage') == 'ja') editor
					.replace(/ *[..] */g, '。')
					.replace(/ *\, */g, ',')
					.replace(/ *\: */g, ':')
					.replace(/ *\; */g, ';')
					.replace(/ *\! */g, '!')
					.replace(/ *\? */g, '?')
					.replace(/ *\( */g, '(')
					.replace(/ *\) */g, ')')
					.replace(/mdash;/g, 'mdash;')
					//.replace(/\ +(?=[^a-zA-Z])|(?<=[^a-zA-Z])\ +/g, '') // replace non-Latin spaces
					.replace(/\ +(?=[^a-zA-Z])|(?<=[^a-zA-Z])\ +/g, (mw.config.get('wgPageName').contains('官話講義') ? ':' : '')) // replace non-Latin spaces

					.replace(/\-+(?=[^a-zA-Z])|(?<=[^a-zA-Z])\-+/g, '-') // replace non-Latin hyphens
				;

				//editor.appendEditSummary('clean ocr');
			}
		}
	});
	pathoschild.TemplateScript.add({
		name: '改行壓縮',
		forNamespaces: 'page',
		script: function(editor) {
			editor
				.replace(/\n+/g, '\n')
			;
		}
	});
	pathoschild.TemplateScript.add({
		name: '改行除去',
		forNamespaces: 'page',
		script: function(editor) {
			editor
				.replace(/\n{2,}/g, '@')
				.replace(/-\n/g, '〓')
				.replace(/([,.])\n/g, '$1 ')
				.replace(/\n/g, ' ')
				.replace(/@/g, '\n\n')
			;
		}
	});
	pathoschild.TemplateScript.add({
		name: '[.!?]後ニ空格',
		forNamespaces: 'page',
		script: function(editor) {
			editor
				.replace(/([.!?]) +/g, '$1\n')
				.replace(/(.+?;.+?), ?(.+?;.+?)\./g, '$1.\n$2.') // fielde swatow "Rom; Eng; Rom; Eng; Rom; Eng."
				.replace(/(.+?;.+?), ?(.+?;.+?)\./g, '$1.\n$2.') // ditto
				.replace(/(.+?;.+?), ?(.+?;.+?)\./g, '$1.\n$2.') // ditto
				.replace(/(.+?;.+?), ?(.+?;.+?)\./g, '$1.\n$2.') // ditto
			;
		}
	});
	pathoschild.TemplateScript.add({
		name: 'ルビa',
		forNamespaces: 'page',
		enabled: mw.config.get('wgContentLanguage') === 'ja',
		script: function(editor) {
			editor
				.replace(/([㐀-龥々]+)/g, "〘$1〙")
			;
		}
	});
	pathoschild.TemplateScript.add({
		name: 'キレイニ',
		forNamespaces: 'page',
		enabled: mw.config.get('wgContentLanguage') === 'ja',
		script: function(editor) {
			editor
				/* [[wikisource:ja:User:CES1596/to-ruby0.js]] */

				.replace(/[〘]([^〘〙]+)[〙]/g, function(all, text) { return text.replace(/^(.+?)([ぁ-ヿ]+)$/g, "{{r|" + '$1' + "|" + '$2' + "}}"); })
				.replace(/((?:[々〇〻\u3400-\u9FFF\uF900-\uFAFF]|[\uD840-\uD87F][\uDC00-\uDFFF])+)[``]([〱〲/″\{}ぁ-ゞァ-ヾx]+)[``]/g, "{{r|" + '$1' + "|" + '$2' + "}}")
				.replace(/x/g, "{{難読部}}")

				.replace(/¥1/g, "{{一}}")
				.replace(/¥2/g, "{{二}}")
				.replace(/¥ー/g, "{{竪}}")
				.replace(/¥r/g, "{{レ}}")
			;
		}
	});
	pathoschild.TemplateScript.add({
		name: 'abc順',
		forNamespaces: 'page',
		script: function(editor) {
			var initial = prompt();
			var re_initial = new RegExp('^[^' + initial + '\n].+', 'gm');
			editor
				//.replace(/(,)[^,]+$/gm, '$1')
				.replace(re_initial, '')
				.replace(/(\n)\n*/g, '$1')
				.replace(/^\n*/g, '')
			;
			editor.set(editor.get().split("\n\n").sort().join("\n").trim());
		}
	});
	pathoschild.TemplateScript.add({
		name: '粵音指南',
		forNamespaces: 'page',
		enabled: mw.config.get('wgPageName').contains('Yue_yin_zhi_nan'),
		script: function(editor) {
			editor
				.prepend('{{縱書框|\n')
				.append('}}')
				.replace(/([、])/g, '{{縱書標點|$1}}')
				.replace(/「([^」]+)」/g, '{{縱書專名號|$1}}')
				.replace(/ /g, ' ')
				.appendEditSummary('format')
			;
		}
	});
	pathoschild.TemplateScript.add({
		name: 'CDO',
		forNamespaces: 'page',
		enabled: mw.config.get('wgPageName').contains('Chinese_language_in_the_Foochow_dialect'),
		script: function(editor) {
			editor
				.replace(/==/g, '<noinclude>{{multicol-break}}</noinclude>')
				.replace(/\[(.+?)\]/g, function(a, b) { return '{{cdo-Maclay entry|' + b.replace(/\./g, '|') + '}}'; })
				.replace(/x`/g, '<ref>〓〓</ref>`')

				.replace(/\/([^<>]+?)\//g, function(a, b) {
					var text = '';
					text += '{{cdo-Maclay rom|';
					text += b.replace(/(\d)/g, '|$1').replace(/ /g, '|').replace(/aa/g, 'ă').replace(/ee/g, 'é').replace(/er/g, 'ë').replace(/oo/g, 'ó').replace(/ii/g, 'ü').replace(/hh/g, 'ʻ');
					text += '}}';
					return text;
				});
		}
	});
	pathoschild.TemplateScript.add({
		name: 'CDO [pre]',
		forNamespaces: 'page',
		enabled: mw.config.get('wgPageName').contains('English-Chinese_dictionary_of_the_Foochow_dialect'),
		script: function(editor) {
			editor
				.replace(/,.+/g, ',')
				.replace(/\n+/g, '\n')
				.replace(/,/g, ', ')
			;

			editor.set("\n\n" + editor.get().split("\n").sort().join("\n").trim());
		}
	});
	pathoschild.TemplateScript.add({
		name: 'CDO',
		forNamespaces: 'page',
		enabled: mw.config.get('wgPageName').contains('English-Chinese_dictionary_of_the_Foochow_dialect'),
		script: function(editor) {
			function cdoConvert(text) {
				return text
					.replace(/([aiueo])\1/g, '$1̤')
					.replace(/2/g, '́')
					.replace(/3/g, '̀')
					.replace(/5/g, '̂')
					.replace(/6/g, '̆')
					.replace(/7/g, '̄')
				;
			}

			editor
				.replace(/<\/([a-z]+)>/g, '@!$1!@')
				.replace(/{{hi\/s}}/g, '@!his!@')
				.replace(/{{hi\/e}}/g, '@!hie!@')

				.replace(/--/g, '&ndash;')
				.replace(/(?:\/|<i>)(.*?)(?:\/|@!i!@)/g, function(_, text) {
					// NFD: for when i type+save with real diacritics, but also want to type ee→e̤
					return '<i>' + cdoConvert(text.normalize('NFD')) + '</i>';
				})
				.replace(/(.+)(\n+)/g, function(_, line, newline) {
					return line + (line.contains('<i>') ? '\n\n' : '\n');
				})

				.replace(/@!his!@/g, '\n{{hi/s}}')
				.replace(/@!hie!@/g, '{{hi/e}}')
				.replace(/@!([a-z]+)!@/g, '</$1>')

				.replace(/ +\n/g, '\n')
				.replace(/,\n/g, ', \n')
			;
		}
	});
	pathoschild.TemplateScript.add({
		name: 'CDO',
		forNamespaces: 'page',
		enabled: mw.config.get('wgPageName').contains('Manual_of_the_Foochow_Dialect'),
		script: function(editor) {
			function cdoConvert(text) {
				return text
					.replace(/([aiueo])\1/g, '$1̤')
					.replace(/2/g, '́')
					.replace(/3/g, '̀')
					.replace(/5/g, '̂')
					.replace(/6/g, '̆')
					.replace(/7/g, '̄')
				;
			}

			editor
				.replace(/(\n:)(.+)/g, function(_, a, text) {
					return a + cdoConvert(text);
				})
				.replace(/(\n#)(.+\d.*)/g, function(_, a, text) {
					return a + cdoConvert(text);
				})
				.replace(/\/([^\/<>]+)\//g, function(_, text) {
					return "<i>" + cdoConvert(text) + "</i>";
				});
		}
	});
	pathoschild.TemplateScript.add({
		name: 'NAN',
		forNamespaces: 'page',
		enabled: mw.config.get('wgPageName').contains('Dictionary_of_the_Swatow_dialect'),
		script: function(editor) {
			editor
				.replace(/o`/g, 'o̤')
				.replace(/u`/g, 'ṳ')
				.replace(/n`/g, 'ⁿ')
				.replace(/`/g, '�')
				.replace(/([aiueownm]|o̤|ṳ)2/g, '$1́')
				.replace(/([aiueownm]|o̤|ṳ)3/g, '$1̀')
				.replace(/([aiueownm]|o̤|ṳ)5/g, '$1̂')
				.replace(/([aiueownm]|o̤|ṳ)6/g, '$1̆')
				.replace(/([aiueownm]|o̤|ṳ)7/g, '$1̄')

				.replace(/(?:^|\n+)=({{SIC\|[^=\n]+\|([^=\n]+)}}|([^=\n]+))\n/g, '<section end="〓" />\n\n<section begin="$2$3" /><h3>$1</h3>\n')
				.replace(/==/g, '<noinclude>{{multicol-break}}</noinclude>')
				.replace(/\[(.+?)\]/g, function(a, b) { return '{{swatow entry|〓|' + b.replace(/ /g, '|') + '}}'; })
				.replace(/^({{[Ss]watow[ _]entry[^}]+}})\s*(.+)/gm, '* $1\n* $2')
				.replace(/(.*?[;!?].*?[.!?])(?: )/g, '$1\n') // break lines with ! or ? or .
				.replace(/^([^*;:\n].*?[;!?])(?:\s*)(.+)/gm, '; $1\n: $2')
				.replace(/^;.+/gm, function(_) {
					return _.replace(/:/g, '<nowiki>:</nowiki>');
				})

				// fix bad division
				.replace(/^;(.+)\n:(.+[;!?])/gm, function(_, a, b) {
					b = b.normalize('NFD');
					return ';' + a + (b.match(/[̤́̀̂̆̄ⁿ]/) ? b.replace(/(.+[̤́̀̂̆̄ⁿ].*?[;!?])/, '$1\n:') : '\n:' + b);
				})

				.appendEditSummary('fmt')
			;
		}
	});
	pathoschild.TemplateScript.add({
		name: 'NAN new format',
		forNamespaces: 'page',
		enabled: mw.config.get('wgPageName').contains('Dictionary_of_the_Swatow_dialect'),
		script: function(editor) {
			//editor.set(editor.get().normalize('NFD'));
			editor
				.replace(/^\n+/, '') // remove leading newlines (only once)
				.replace(/\n+$/, '') // remove trailing newlines (only once)
				.replace(/^ *| *$/gm, '') // remove leading/trailing spaces
				.replace(/\n+/gm, function(_) { return _.length > 1 ? _ : ' ' }) // remove single newlines
				.replace(/\s*<br *\/?>\s*/g, '<br>')
				.replace(/\s*{{swatow[ _]gap}}\s*/gi, '<sg>')
				.replace(/^({{swatow[ _]entry.*?}})\s*(.*?)(<br>|<sg>)/gmi, '* $1\n* $2\n')
				.replace(/^({{swatow[ _]entry.*?}})\s*(.+)$/gmi, '* $1\n$2')
				.replace(/<sg>/gmi, '\n') // break at "gap"
				.replace(/(\.)(\s*<noinclude>{{multicol-break}}<\/noinclude>)?/g, '$1$2\n') // break after a period
				.replace(/(.*?[;!?].*?[!?])(?:<sg>| )/g, '$1\n') // break lines with ! or ?
				.replace(/^\s*([^*A-Z].*?[;!?])\s*(.*?)([.!?](?:<section.+>|<noinclude>{{multicol-break}}<\/noinclude>)?|\n*$)$/gm, '; $1\n: $2$3')
				.replace(/\n([^;:<]+)$/g, '\n; $1') // incomplete Teochew line
				.replace(/^;.+/gm, function(_) {
					return _.replace(/:/g, '<nowiki>:</nowiki>');
				})

				// fix bad division
				.replace(/^;(.+)\n:(.+[;!?])/gm, function(_, a, b) {
					b = b.normalize('NFD');
					return ';' + a + (b.match(/[̤́̀̂̆̄ⁿ]/) ? b.replace(/(.+[̤́̀̂̆̄ⁿ].*?[;!?])/, '$1\n:') : '\n:' + b);
				})
				// fix bad location of multicol-break
				.replace(/\n([;:] )(<noinclude>{{multicol-break}}<\/noinclude>)/gm, '$2\n$1')

				.replace(/{{center\|—\s*(.*?)\s*—}}/g, '<h3>$1</h3>')

				.appendEditSummary('use new formatting')
			;
		}
	});
	pathoschild.TemplateScript.add({
		name: 'YUE',
		forNamespaces: 'page',
		enabled: mw.config.get('wgPageName').contains("The_beginner's_first_book_in_the_Chinese_language"),
		script: function(editor) {
			editor
				.replace(/--/g, '&mdash;')

				.replace(/((?:.*[a-zA-Z].*\n){2,})((?:.*[㐀-龥].*\n){2,})((?:.*[a-zA-Z].*\n){2,})/g, function(_, h, z, r) {
					h = h.trim().split('\n');
					z = z.trim().split('\n');
					r = r.trim().split('\n');
					var ret = [];
					for (var i = 0; i <= Math.max(h.length, z.length, r.length); i++) {
						ret.push(h[i] || '');
						ret.push(z[i] || '');
						ret.push(r[i] || '');
					}
					return ret.join('\n');
				})

				.replace(/([^\n]*)\n(x?.*[㐀-鿕].*)\n([^\n]*)/g, function(_, h, z, r) {
					//h = h.replace(/(, |{{ditto.+}} )(.+)/g, '$1<i>$2</i>');
					z = z.replace(/x/g, '');
					r = r.replace(/^./g, function(a) { return a.toUpperCase() });
					return '; ' + h + '\n: ' + z + '\n:: ' + r;
				})

				// [[s:en:Page:Handbook of the Swatow vernacular.djvu/205]]
				.replace(/[\W\w]+/, function(text) {
					text = text.split('\n');
					for (var i = 0; i < text.length; i++) {
						j = i;
						if (text[i].startsWith('..')) {
							while (text[j] && text[j].startsWith('..') || text[j].startsWith('{{ditto|')) {
								j--;
							}
							var ditto_match = text[j].match(/^[^,]+,/);
							text[i] = text[i].replace(/^\.\./gm, '{{ditto|' + ditto_match + '}}');
						}
					}
					return text.join('\n');
				})

				.appendEditSummary('fmt')
			;
		}
	});
	pathoschild.TemplateScript.add({
		name: 'NAN',
		forNamespaces: 'page',
		enabled: mw.config.get('wgPageName').contains('in_the_Tie-chiu_dialect'),
		script: function(editor) {
			editor
				.replace(/AQ`/g, 'À')
				.replace(/aq`/g, 'à')
				.replace(/AR`/g, 'Á')
				.replace(/ar`/g, 'á')
				.replace(/O`/g, 'Ó')
				.replace(/o`/g, 'ó')
				.replace(/U`/g, 'Ù')
				.replace(/u`/g, 'ù')
				.replace(/N`/g, 'ᴺ')
				.replace(/n`/g, 'ⁿ')
				.replace(/W`/g, 'ᵁ')
				.replace(/w`/g, 'ᵘ')
				//.replace(/4`/g, '꜆') // this fucking book. ă? a꜆?
				.replace(/4`/g, '\u0306')
				.replace(/""/g, 'ʼ') // ʼNg
				.replace(/`/g, 'ʽ')
				// ÀàÁáÓóÙùᴺⁿᵁᵘ\u0306ʼʽ

				//.replace(/\n*[==]{2}/g, '<noinclude>{{multicol-break}}</noinclude>')

				.replace(
					/@([^\n]+)\n([^@]+)(\n+|$)/g,
					'\n<section begin="$1"/><h3 style="text-align: center;">$1.</h3>\n$2<section end="$1"/>\n'
				)

				.replace(/^~([^\n]+)/gm, function(_, t) {
					return (
						t.toUpperCase().replace(/ /g, '&emsp;') +
						'@' +
						t.replace(/([^ ])([^ ]+)/g, function(_, tA, tB) {
							return tA.toUpperCase() + tB;
						}).replace(/ /g, '\n\n\n@')
					);
				})

				//.replace(/^([^\d\nA-Za-z-]+)([\d-]+)/gm, ';$1<sup>$2</sup>:')
				.replace(/^(\{\{[^}]+\}\}|[㐀-鿕]{1,2}|\+[^a-z]{2})([A-Za-zÀàÁáÓóÙùᴺⁿᵁᵘ\u0306ʼʽ ]+)$/gm, function(_, z, rs) {
					// /+[^a-z]+/ because astral cjk
					rs = rs.split(' ');
					for (var i = 0; i < rs.length; i++) {
						rs[i] = rs[i][0].toUpperCase() + rs[i].slice(1);
						if (rs[i].contains('\u0306')) {
							rs[i] = '[[../' + rs[i].normalize('NFD').replace('\u0306', '') + '/|' + rs[i] + ']]';
						} else {
							rs[i] = '[[../' + rs[i] + '/]]';
						}
					}
					if (rs[1]) {
						rs[1] = '<i>' + rs[1] + '</i>';
					}
					return z.replace('+', '') + ' ' + rs.join(' ');
				})

				;
		}
	});
	pathoschild.TemplateScript.add({
		name: 'CMN',
		forNamespaces: 'page',
		enabled: mw.config.get('wgPageName').contains('Western_Mandarin'),
		script: function(editor) {
			editor
				.replace(/(The [^\n]+ radical[^\n]+\n)([㐀-鿕]|x[^ ])/g, '$10\n$2') // add "+0 strokes" header

				.replace(/(^|\n)(\d\d?)\n/g, '$1$1<h4 style="text-align: center;">$2</h4>\n\n')
				.replace(/(^|\n)([A-Z])\n/g, '$1$1<h3 style="text-align: center;">$2.</h3>\n\n')

				.replace(/(^|\n)(The (\d\d?)[a-z][a-z] radical\. \(.\))\n/g, function(_, s, text, n) {
					return ('<section end="' + (n-1) + '" />\n\n<section begin="' + n + '" /><h3 style="text-align: center;">' + text + '</h3>\n');
				})

				.replace(/@(.*?)@/g, 'x{{sinogram|$1}}')

				// [[s:en:Page:Western Mandarin.pdf/617]]
				// [[s:en:Page:Western Mandarin.pdf/617]]
				.replace(/(^|\n)([㐀-鿕]+|x[^ \s]*) ((?:[ -]?[a-z` ,]+[\d,]+)+)(?:\n([A-Za-z ]{2,}))?/g, function(_, sp, z, rom, gloss) {
					if (z == 'x') {
						z = undefined;
					}
					return sp + '; ' + (z ? z.replace(/x/g, '') + ' ' : '') + '{{sc|' + rom.replace(/(\d+)/g, '<sup>$1</sup>') + '.}}' + (gloss ? '\n: ' + gloss : '');
				})

				.replace(/(^|\n)([㐀-鿕]+|x[^ \s]+)(?:\n([A-Za-z ]{2,}|<i>[A-Za-z ]{2,}))?/g, '$1:; $2\n:: $3')

				.replace(/([iu])`/gi, '$1̈')
				.replace(/`/g, 'ʻ')
			;
		}
	});
	pathoschild.TemplateScript.add({
		name: 'CMN family',
		forNamespaces: 'page',
		enabled: mw.config.get('wgPageName').contains('Western_Mandarin'),
		script: function(editor) {
			editor
				.replace(/(^|\n)([A-Z])/g, '$1; $2')
				.replace(/(^|\n)([㐀-鿕])/g, '$1: $2')
			;
		}
	});
	pathoschild.TemplateScript.add({
		name: 'アクセント辭典',
		forNamespaces: 'page',
		enabled: mw.config.get('wgPageName').contains('Japanese_Accent_Dictionary'),
		script: function(editor) {
			var pagenumber = mw.config.get('wgPageName').match(/\d+$/);
			var left_right = 'L';
			if (pagenumber) {
				pagenumber = pagenumber[0];
				pagenumber = Number(pagenumber);
				pagenumber = pagenumber - 14;
				left_right = (pagenumber % 2) === 0 ? 'L' : 'R';
			}

			if (document.getElementById('wpHeaderTextbox').value === '') {
				document.getElementById('wpHeaderTextbox').value = (
					'{{rh|' +
					(left_right === 'L' ? pagenumber : '') +
					'|000—000|' +
					(left_right === 'R' ? pagenumber : '') +
					'}}\n{{rule}}'
				);
			}

			editor
				.replace(/^([^;\s]+)( |$)/gm, ';$1:')
				.replace(/[。.](.*?)[。.]/g, '<u>$1</u>')
				.replace(/、/g, ',')

				.replace(/^;.+:/gm, function(a) {
					a = a.replace(/([ぁ-ん])/g, function(_, kana) {
						return String.fromCharCode(kana.charCodeAt(0) + 0x60);
					});
					return a;
				})
			;
		}
	});
	pathoschild.TemplateScript.add({
		name: '倭語類解',
		forNamespaces: 'page',
		enabled: mw.config.get('wgPageName').contains('倭語類解'),
		script: function(editor) {
			editor
				.replace(/(.*[㐀-鿕].*)\n(.+)\n(.+)\n(○.+)/gm, ';$1\n:$2\n:$3\n:$4')
				.replace(/(.*[㐀-鿕].*)\n(.+)\n(○.+)/gm, ';$1\n:$2\n:$3')
				.appendEditSummary('fmt')
			;
		}
	});
	pathoschild.TemplateScript.add({
		name: '論語諺解',
		forNamespaces: 'page',
		enabled: mw.config.get('wgPageName').contains('論語諺解'),
		script: function(editor) {
			editor
				.replace(/([㐀-鿕]|[^;:\n가-힣ㄱ-ㆎᄀ-ᇿꥠ-ꥼힰ-ퟻ]+\([㐀-鿕]\))([가-힣]|[ᄀ-ᅟ][ᅠ-ᆧ][ᆨ-ᇿ]?)/gm, '{{ruby|$1|$2}}')
				.appendEditSummary('ruby')
			;
		}
	});
	pathoschild.TemplateScript.add({
		name: '華英通語',
		forNamespaces: 'page',
		enabled: mw.config.get('wgPageName').contains('福澤全集巻一') || mw.config.get('wgPageName').contains('華英通語'),
		script: function(editor) {
			var lang_line_chunk = editor.get().trim().split('\n\n');
			var text_assembled = [];
			var lang_line_chunk_longest_length = 0; // want to skip over japlish...
			for (var i = 0; i < lang_line_chunk.length; i++) {
				var lang_lines = lang_line_chunk[i].split('\n');
				if (lang_lines.length > lang_line_chunk_longest_length) lang_line_chunk_longest_length = lang_lines.length;
				for (var j = 0; j < lang_line_chunk_longest_length; j++) {
					if (!lang_lines[j]) lang_lines[j] = '';
					if (!text_assembled[j]) text_assembled[j] = '';
					text_assembled[j] += '|' + lang_lines[j].trim();
					if (i == 2) text_assembled[j] += '\n'; // but keep a place for japlish in the template
				}
			}
			editor.set('{{華英通語\n' + text_assembled.join('\n') + '\n}}');
		}
	});
	pathoschild.TemplateScript.add({
		name: 'DLI台山話',
		forNamespaces: 'page',
		enabled: mw.config.get('wgPageName').contains('FSI-ED022176'),
		script: function(editor) {
			editor
				.replace(/.+[㐀-鿕].+/g, function(all) {
					all = all
						.replace(/ +/g, '')
						.replace(/['A-Za-z0-9À-ÿ]+/g, '〓〓〓')
						.replace(/([㐀-龥])〓/g, '$1 〓')
						.replace(/〓([㐀-龥])/g, '〓 $1')
						.replace(/有有/g, '有冇')
						.replace(/[該咳]/g, '𡀲')
					;
					return all;
				})
			;
		}
	});
	pathoschild.TemplateScript.add({
		name: '正音咀華',
		forNamespaces: 'page',
		enabled: mw.config.get('wgPageName').contains('正音咀華'),
		script: function(editor) {
			editor
				.replace(/(.)[.](.)/g, '{{ruby|$1|$2}}')
				.replace(/(.)\[(.+?)\]/g, '{{ruby|$1|$2}}')
				.replace(/^(.+) /gm, ';$1:')
				.replace(/清/g, '淸')
				.replace(/丟/g, '丢')
				.replace(/飲/g, '飮')
			;
		}
	});
	pathoschild.TemplateScript.add({
		name: '福州歌謠',
		forNamespaces: 'page',
		enabled: mw.config.get('wgPageName').contains('福州歌謠'),
		script: function(editor) {
			var text = editor.get().split("\n\n");
			editor.set(
				'<h1>'+text[0]+'</h1>\n\n<poem>\n'+text[1]+'\n</poem>\n\n<references />\n'+text[2].replace(/(.+)/g, '<ref>$1</ref>') +
				'\n\n' +
				'<h1>'+text[3]+'</h1>\n\n<poem>\n'+text[4]+'\n</poem>\n\n<references />\n'+text[5].replace(/(.+)/g, '<ref>$1</ref>')
			);
		}
	});
	pathoschild.TemplateScript.add({
		name: 'number superscr',
		forNamespaces: 'page',
		script: function(editor) {
			editor
				.replace(/1/g, '¹')
				.replace(/2/g, '²')
				.replace(/3/g, '³')
				.replace(/4/g, '⁴')
				.replace(/5/g, '⁵')
				.replace(/6/g, '⁶')
				.replace(/7/g, '⁷')
				.replace(/8/g, '⁸')
				.replace(/9/g, '⁹')
				.replace(/0/g, '⁰')
			;
		}
	});
});