MediaWiki:Gadget-wikify.js: розьніца паміж вэрсіямі

Зьвесткі зь Вікіпэдыі — вольнай энцыкляпэдыі
Змесціва выдалена Змесціва дададзена
д лінкаванае апісаньне
слушнае хаваньне шаблёнаў
(не паказаныя 2 прамежныя вэрсіі аўтарства таго ж удзельніка)
Радок 124: Радок 124:
hideTag('math')
hideTag('math')
txt = txt.replace(/( |\n|\r)+\{\{(·|•|\*)\}\}/g, '{{$2}}'); //before {{·/•/*}}, usually in templates
txt = txt.replace(/( |\n|\r)+\{\{(·|•|\*)\}\}/g, '{{$2}}'); //before {{·/•/*}}, usually in templates
hideExpr(/{\{[\s\S]+?}}/g) //templates
hideTemplates(); // templates
hideExpr(/^ .*/mg) //lines starting with space
hideExpr(/^ .*/mg) //lines starting with space
hideExpr(/(https?|ftp|news|nntp|telnet|irc|gopher):\/\/[^\s\[\]<>"]+ ?/gi) //links
hideExpr(/(https?|ftp|news|nntp|telnet|irc|gopher):\/\/[^\s\[\]<>"]+ ?/gi) //links
Радок 298: Радок 298:
}
}
*/
*/
}

function hideTemplates() {
var nestedLevel = 0;
var templatesHash = [];
var currentTemplate = {};
for(var i = 0; i < txt.length; ++i) {
if(txt.substr(i, 2) === '{{') {
if(!(nestedLevel++))
currentTemplate.start = i;
++i;
} else if(txt.substr(i, 2) === '}}') {
if(!(--nestedLevel)) {
currentTemplate.end = i+2;
templatesHash.push(currentTemplate);
currentTemplate = {};
nestedLevel = 0;
}
++i;
}
}

for(var i = templatesHash.length-1; i >= 0; --i) {
var tplCode = txt.substring(templatesHash[i].start, templatesHash[i].end);
txt = txt.substring(0, templatesHash[i].start) + '\x01' + hidden.push(tplCode) + '\x02' + txt.substr(templatesHash[i].end);
}
}
}



Вэрсія ад 02:54, 6 студзеня 2013

//  _________________________________________________________________________________________
// |                                                                                         |
// |                   === УВАГА: ГЛЯБАЛЬНЫ ФАЙЛ ГАДЖЭТА ===                                 |
// |           Зьмены на гэтай старонцы закрануць значную колькасьць удзельнікаў.            |
// |     Калі ласка, перад рэдагаваньнем абмяркоўвайце зьмены на старонцы абмеркаваньня.     |
// |_________________________________________________________________________________________|
//
// Імпартавана з [[Удзельнік:Zedlik/wikifikatar.js]] і [[ru:MediaWiki:Wikificator.js]] з вэрсіі ад 03.04.2010
// Для атрыманьня апісаньня і даведкі глядзіце [[Вікіпэдыя:Вікіфікатар]]
// Лякальная адаптацыя: zedlik
// Суправаджальнік: Wizardist
// Вікіфікатар

mw.messages.set({
	'wikify-cant-work':'Вікіфікатар ня можа працаваць у вашым браўзэры.\n\nWikificator can not work in your browser',
	'wikify-full-text':'Вікіфікатар апрацуе ўвесь тэкст. Працягнуць?',
	'wikify-talk-page':'Вікіфікатар не апрацоўвае старонкі абмеркаваньня цалкам.\n\nВылучыце вашае паведамленьне — апрацаванае будзе толькі яно.',
	'wikify-summary-message':'[[ВП:Вікіфікатар|вікіфікацыя]]',
	'wikify-button-label':'Вікіфікаваць'
});

function WikifButton() {
	if(!mediaWiki.user.options.get('usebetatoolbar')) {
		return; // не карыстаешся кашэрным тулбарам — не карыстаешся вікіфікатарам
	}
	mw.loader.using('ext.wikiEditor.toolbar', function(){
		$( '#wpTextbox1' ).wikiEditor( 'addToToolbar', {
			'section': 'main',
			'group': 'gadgets',
			'tools': {
				'wikification': {
					label: mw.messages.get('wikify-button-label'),
					type: 'button',
					icon: '//upload.wikimedia.org/wikipedia/commons/0/06/Wikify-toolbutton.png',
					action: {
						type: 'callback',
						execute: Wikify
					}
				}
			}
		} );
	});
}

function Wikify() {
	if(('code'.replace(/d/g, 'r') != 'core') //check regexp support
	||
	(navigator.appName == 'Netscape' && navigator.appVersion.substr(0, 1) < 5)) {
		alert(mw.messages.get('wikify-cant-work'));
		return
	}

	var txt, hidden = [],
		hidIdx = 0,
		wpTextbox1 = document.editform.wpTextbox1
	var winScroll = document.documentElement.scrollTop //remember window scroll
	wpTextbox1.focus()

	if(typeof wpTextbox1.selectionStart != 'undefined' && (navigator.productSub > 20031000 || is_opera || is_safari)) { //Mozilla/Opera/Safari3
		var textScroll = wpTextbox1.scrollTop
		var startPos = wpTextbox1.selectionStart
		var endPos = wpTextbox1.selectionEnd
		txt = wpTextbox1.value.substring(startPos, endPos)
		if(txt == '') processAllText()
		else {
			processText()
			wpTextbox1.value = wpTextbox1.value.substring(0, startPos) + txt + wpTextbox1.value.substring(endPos)
		}
		wpTextbox1.selectionStart = startPos
		wpTextbox1.selectionEnd = startPos + txt.length
		wpTextbox1.scrollTop = textScroll

	} else if(document.selection && document.selection.createRange) { //IE
		var range = document.selection.createRange()
		txt = range.text
		if(txt == '') processAllText()
		else {
			processText()
			range.text = txt
			//if (!window.opera) txt = txt.replace(/\r/g,'')
			if(range.moveStart) range.moveStart('character', -txt.length)
			range.select()
		}

	} else // other browsers
	if(confirm(mw.messages.get('wikify-full-text'))) processAllText()

	document.documentElement.scrollTop = winScroll // scroll back, for IE/Opera

	//functions
	function processAllText() {
		txt = wpTextbox1.value
		processText()
		txt = txt.replace(/^[\n\r]+/, '')
		wpTextbox1.value = txt
		txt = ''
		// if (window.auto_comment && window.insertSummary) insertSummary('вікіфікацыя')
		if(window.addSumm && document.getElementById("wpSummary").value.indexOf(mw.messages.get('wikify-summary-message')) < 0) addSumm(mw.messages.get('wikify-summary-message'))
	}



	function processText() {

		var u = '\u00A0' //unbreakable space
		if(wgNamespaceNumber % 2 || wgNamespaceNumber == 4) { //is talk page
			u = ' '
			var sigs = txt.match(/\d\d:\d\d, \d\d? \S{3,8} 20\d\d \(UTC\)/g)
			if(sigs && sigs.length > 1) {
				alert(mw.messages.get('wikify-talk-page'));
				return
			}
		}

		if(typeof wikifikatarUserDefinedPreTagHideHook == 'function') {
			txt = wikifikatarUserDefinedPreTagHideHook(txt);
		}

		hideTag('nowiki')
		hideTag('pre')
		hideExpr('<source [^>]+>[\\s\\S]+?<\\/source>')
		hideTag('code')
		hideTag('tt')
		hideTag('math')
		txt = txt.replace(/( |\n|\r)+\{\{(·|•|\*)\}\}/g, '{{$2}}'); //before {{·/•/*}}, usually in templates
		hideTemplates(); // templates
		hideExpr(/^ .*/mg) //lines starting with space
		hideExpr(/(https?|ftp|news|nntp|telnet|irc|gopher):\/\/[^\s\[\]<>"]+ ?/gi) //links
		hideExpr(/^#(redirect|перанакіраваньне)/i)
		hideTag('gallery')

		txt = txt.replace(/ +(\n|\r)/g, '$1') //spaces at EOL
		txt = '\n' + txt + '\n'

		if(typeof wikifikatarUserDefinedPreProcessHook == 'function') {
			txt = wikifikatarUserDefinedPreProcessHook(txt);
		}

		txt = txt.replace(/(\[\[:?)(category|категория):( *)/ig, '$1Катэгорыя:');
		txt = txt.replace(/(\[\[:?)(image|file|выява):( *)/ig, '$1Файл:');
		// Year and century ranges
		txt = txt.replace(/(?!ISBN)(\(|\s)(\[\[[12]?\d{3}\]\])[\u00A0 ]?(-|--|–|—) ?(\[\[[12]?\d{3}\]\])(\W)/g, '$1$2—$4$5')
		txt = txt.replace(/(\[\[[12]?\d{3}\]\]) ?(гг?\.)/g, '$1' + u + '$2')
		txt = txt.replace(/(\(|\s)(\[\[[IVX]{1,5}\]\])[\u00A0 ]?(-|--|–|—) ?(\[\[[IVX]{1,5}\]\])(\W)/g, '$1$2—$4$5')
		txt = txt.replace(/(\[\[[IVX]{1,5}\]\]) ?(стст?\.)/g, '$1' + u + '$2')
		// txt = txt.replace(/\[\[(\d+)\sгод\]\]/g, '[[$1]]'+u+'год')
		// txt = txt.replace(/\[\[(\d+)\sгод\|\1\]\]\s(год|гад)/g, '[[$1]]'+u+'$2')
		// txt = txt.replace(/\[\[(\d+)\sгод\|\1\s(год|гад)([а-я]{0,3})\]\]/g, '[[$1]]'+u+'$2$3')
		// txt = txt.replace(/\[\[((\d+)(?: (?:год )?у [\wa-яёіўА-ЯЁІЎ ]+\|\2))\]\][\u00A0 ](год[а-яёіў]*)/g, '[[$1'+u+'$3]]')
		// Nice links
		txt = txt.replace(/(\[\[[^|\[\]]*)[\u00AD\u200E\u200F]+([^\[\]]*\]\])/g, '$1$2') // Soft Hyphen & DirMark
		txt = txt.replace(/\[\[ *([a-zA-Zа-яёіўА-ЯЁІЎ\u00A0-\u00FF %!\"$&'()*,\-—.\/0-9:;=?\\@\^_`’~]+) *\| *(\1)([a-zа-яёіў]*) *\]\]/g, '[[$2]]$3') // "
		txt = txt.replace(/\[\[ *([^|\[\]]+)([^|\[\]]+) *\| *\1 *\]\]\2/g, '[[$1$2]]') // паўтор тэксту за спасылкай
		txt = txt.replace(/\[\[ *(?!Файл:|Катэгорыя:)([a-zA-Zа-яёА-ЯЁ\u00A0-\u00FF %!\"$&'()*,\-—.\/0-9:;=?\\@\^_`’~]+) *\| *([^|[\]]+) *\]\]([a-zа-яёіў]+)/g, '[[$1|$2$3]]') // "
		hideExpr(/\[\[[^\]|]+/g) //only link part
		txt = txt.replace(/<<(\S.+\S)>>/g, '"$1"') //<<text>> -> "text"
		//square and cube
		txt = txt.replace(/(<sup>2<\/sup>|&sup2;)/gi, '²');
		txt = txt.replace(/(<sup>3<\/sup>|&sup3;)/gi, '³');
		//tags → wikicode
		txt = txt.replace(/<(b|strong)>(.*?)<\/(b|strong)>/gi, "'''$2'''")
		txt = txt.replace(/<(i|em)>(.*?)<\/(i|em)>/gi, "''$2''")
		txt = txt.replace(/<hr ?\/?>/gi, '----')
		//improve hr and br
		txt = txt.replace(/<hr ([^\/>]+?) ?\/?>/gi, '<hr $1 />')
		txt = txt.replace(/<br( [^\/>]+?)? ?\/?>/gi, '<br$1 />')
		txt = txt.replace(/(\n== *[a-zа-яёіў\s\.:]+ *==\n+)<references *\/>/ig, '$1{\{зноскі}}')
		hideExpr(/<[a-z][^>]*?>/gi) //hide tags
		// hideExpr('\\w+ *= *"[^"]*"') //also tables attributes //[ \w%;:]
		hideExpr(/^({\||\|-).*/mg) //table/row def
		hideExpr(/(^\||^!|!!|\|\|) *[a-z]+=[^|]+\|(?!\|)/mgi) //cell style
		hideExpr(/\| +/g) //formatted cell
		txt = txt.replace(/[ \t]+/g, ' ') //double spaces
		//Entities 
		txt = txt.replace(/&#(\d+);?/g, function (n, a) {
			return String.fromCharCode(a)
		}) // &#769;
		txt = txt.replace(/&#x([0-9a-f]{1,4});?/gi, function (n, a) {
			return String.fromCharCode(eval('0x' + a.substr(-4)))
		}) // &#x301;
		//Headers
		txt = txt.replace(/^(=+)[ \t\f\v]*(.*?)[ \t\f\v]*=+$/gm, '$1 $2 $1') //add spaces in section headers
		txt = txt.replace(/([^\r\n])(\r?\n==.*==\r?\n)/g, '$1\n$2') //add empty line before section header
		txt = txt.replace(/^== (Г|г)л(\.?|ядзіце) ?таксама ==$/gm, '== Глядзіце таксама ==')
		txt = txt.replace(/^== (З|з)носкі ==$/gm, '== Крыніцы ==')
		txt = txt.replace(/^== (З|з)ь?нешнія ?спасылкі ==$/gm, '== Вонкавыя спасылкі ==')
		txt = txt.replace(/^== (.+)[.:] ==$/gm, '== $1 ==')


		//Temporary replacements
		txt = txt.replace(/–/g, '-')
		txt = txt.replace(/«|»|“|”|„/g, '"')
		txt = ' ' + txt

		// For LaTeX
		txt = txt.replace(/"---/g, '--')
		// Minus handler
		txt = txt.replace(/(sup>|sub>|\s)-(\d)/g, '$1−$2')
		// Replace hyphens and en dashes with normal dashes
		txt = txt.replace(/&(#151|[nm]dash);/g, '—')
		txt = txt.replace(/(&nbsp;|[\f\n\r\t\v\u00A0\u2028\u2029])(-|--|–) /g, '$1— ')
		txt = txt.replace(/(\d)--(\d)/g, '$1—$2')

		// Entities etc. → Unicode chars
		txt = txt.replace(/&copy;/gi, '©')
		txt = txt.replace(/&reg;/gi, '®')
		txt = txt.replace(/&sect;/gi, '§')
		txt = txt.replace(/&euro;/gi, '€')
		txt = txt.replace(/&yen;/gi, '¥')
		txt = txt.replace(/&pound;/gi, '£')
		txt = txt.replace(/&deg;/g, '°')
		txt = txt.replace(/\(tm\)|\(тм\)|&trade;/gi, '™')
		// txt = txt.replace(/\.\.\.|&hellip;/g,'…')
		txt = txt.replace(/\+-(?!\+|-)|&plusmn;/g, '±')
		txt = txt.replace(/~=/g, '≈')
		txt = txt.replace(/\^2(\D)/g, '²$1')
		txt = txt.replace(/\^3(\D)/g, '³$1')
		txt = txt.replace(/&((la|ra|bd|ld)quo|quot);/g, '"')
		txt = txt.replace(/([\wа-яА-ЯёЁіІґҐўЎ])'([\wа-яА-ЯёЁіІґҐўЎ])/g, '$1’$2') //'
		// Year and century ranges
		txt = txt.replace(/(\(|\s)([12]?\d{3})[\u00A0 ]?(-|--|–|—) ?([12]?\d{3})(\W)/g, '$1$2—$4$5')
		txt = txt.replace(/([12]?\d{3}) ?(гг?\.)/g, '$1' + u + '$2')
		txt = txt.replace(/(\(|\s)([IVX]{1,5})[\u00A0 ]?(-|--|–|—) ?([IVX]{1,5})(\W)/g, '$1$2—$4$5')
		txt = txt.replace(/([IVX]{1,5}) ?(стст?\.)/g, '$1' + u + '$2')

		// Reductions
		txt = txt.replace(/(Т|т)\. ?б\./g, '$1о бок')
		txt = txt.replace(/(Т|т)обо/g, '$1о бок')
		txt = txt.replace(/(У|у) т\. ?л\./g, '$1 тым ліку')
		txt = txt.replace(/(Ў|ў) т\. ?л\./g, '$1 тым ліку')
		txt = txt.replace(/(і|І) г\. ?д\./g, '$1' + u + 'г\.' + u + 'д\.')
		txt = txt.replace(/(і|І) т\. ?п\./g, '$1' + u + 'да т\.' + u + 'п\.')
		txt = txt.replace(/(і|І) да т\. ?п\./g, '$1' + u + 'да т\.' + u + 'п\.')
		txt = txt.replace(/(Т)\. ?н\./g, 'Г\.' + u + 'зв\.')
		txt = txt.replace(/(\s)(т)\. ?н\./g, '$1г\.' + u + 'зв\.') // false positive on "у II ст. н. э."
		txt = txt.replace(/(Т)\. ?зв\./g, 'Г\.' + u + 'зв\.')
		txt = txt.replace(/(т)\. ?зв\./g, 'г\.' + u + 'зв\.')
		txt = txt.replace(/н\. ?э\./g, 'н\.' + u + 'э\.')
		txt = txt.replace(/(Д|д)(а|\.) н\. ?э\./g, '$1а' + u + 'н\.' + u + 'э\.')
		txt = txt.replace(/(\d) ?(млн|млрд|трлн|(?:м|с|д|к)?м|[км]?г|с)\.?( ([^\.А-ЯЁІҐЎ])|[,;.])(?!\[.*?\|[А-Я].*?\])/g, '$1' + u + '$2$3')
		txt = txt.replace(/(\d) (тыс)([^\.А-Яа-яЁёІіҐґЎў])/g, '$1' + u + '$2.$3')
		//txt = txt.replace(/(\d) (млн|млрд|трлн)([^А-Яа-яЁёІіҐґЎў])/g, '$1'+u+'$2$3')
		// Insert/delete spaces
		txt = txt.replace(/^([#*:]+)[ \t\f\v]*(?!\{\|)([^ \t\f\v*#:;])/gm, '$1 $2') //space after #*: unless before table
		txt = txt.replace(/(\S) (-|--|–|—) (\S)/g, '$1' + u + '— $3')
		txt = txt.replace(/([А-ЯЁІҐЎ]\.) ?([А-ЯЁІҐЎ]\.) ?([А-ЯЁІҐЎ][а-яёіґў])/g, '$1' + u + '$2' + u + '$3')
		txt = txt.replace(/([А-ЯЁІҐЎ]\.)([А-ЯЁІҐЎ]\.)/g, '$1 $2')
		txt = txt.replace(/([а-яЁІҐЎ]\.)([А-ЯA-ZЁІҐЎ])/g, '$1 $2') // word. word
		txt = txt.replace(/([)"а-яa-zёіґў\]])\s*,([\[("а-яa-z])/g, '$1, $2') // word, word
		txt = txt.replace(/([)"а-яa-zёіґў\]])\s([,;])\s([\[("а-яa-zёіґў])/g, '$1$2 $3')
		// txt = txt.replace(/([^%\/\w]\d+?(?:[.,]\d+?)?) ?([%‰])(?!-[А-Яа-яЁёІіҐґЎў])/g, '$1'+u+'$2') //5 %
		txt = txt.replace(/([^%\/\w]\d+?(?:[.,]\d+?)?) ?([%‰])(?!-[А-Яа-яЁёІіҐґЎў])/g, '$1' + '$2') //5%
		txt = txt.replace(/(\d) ([%‰])(?=-[А-Яа-яЁёІіҐґЎў])/g, '$1$2') //5%-ы
		// txt = txt.replace(/([№§])(\s*)(\d)/g, '$1'+u+'$3')
		txt = txt.replace(/\( +/g, '(').replace(/ +\)/g, ')') //inside ()
		// Degrees
		txt = txt.replace(/([\s\d=≈≠≤≥<>—("'|])([+±−-]?\d+?(?:[.,]\d+?)?)(([ °^*]| [°^*])C)(?=[\s"').,;!?|])/gm, '$1$2' + u + '°C') //'
		txt = txt.replace(/([\s\d=≈≠≤≥<>—("'|])([+±−-]?\d+?(?:[.,]\d+?)?)(([ °^*]| [°^*])F)(?=[\s"').,;|!?])/gm, '$1$2' + u + '°F') //'
		//"" → «»
		for(var i = 1; i <= 3; i++)
		txt = txt.replace(/([\xa0\s\x02!|#'"\/(;+-])"([^"]*)([^\s"(|])"([^a-zA-Zа-яА-ЯёіўґЁІЎҐ0-9])/g, '$1«$2$3»$4') //"
		while(/«[^»]*«/.test(txt))
		txt = txt.replace(/«([^»]*)«([^»]*)»/g, '«$1„$2“')

		// часовы фікс для ISBN/ISSN
		txt = txt.replace(/(ISSN|ISBN)\s+(\d+)—/g, '$1 $2-');

		txt = txt.substr(2, txt.length - 3); // remove extra characters
		if(typeof wikifikatarUserDefinedAfterProcessHook == 'function') {
			txt = wikifikatarUserDefinedAfterProcessHook(txt);
		}

		if('0'.replace('0', '$$') == '$') ////$ in replacing string is special, except in IE
		for(var i = 0; i < hidden.length; i++) hidden[i] = hidden[i].replace(/\$/g, '$$$$')

		restoreAll()

		if(typeof wikifikatarUserDefinedAfterTagRestoreHook == 'function') {
			txt = wikifikatarUserDefinedAfterTagRestoreHook(txt);
		}

	}


	function hideExpr(expr) {
		txt = txt.replace(expr, function (s) {
			return '\x01' + hidden.push(s) + '\x02'
		});
		/*
var ma = txt.match(new RegExp(expr, 'mgi'))
if (!ma) return
for (var i=0; i<ma.length; i++) {
txt = txt.replace(ma[i], '\x01' + hidIdx + '\x02')
hidden[hidIdx] = ma[i] 
if ('0'.replace('0','$$') == '$') //$ in 2nd arg is special even if 1st arg is a string, except in IE
hidden[hidIdx] = hidden[hidIdx].replace(/\$/g, '$$$$') //$ → $$, then it's converted back to $ on restore
hidIdx++
}
*/
	}

	function hideTemplates() {
		var nestedLevel = 0;
		var templatesHash = [];
		var currentTemplate = {};
		for(var i = 0; i < txt.length; ++i) {
			if(txt.substr(i, 2) === '{{') {
				if(!(nestedLevel++))
					currentTemplate.start = i;
				++i;
			} else if(txt.substr(i, 2) === '}}') {
				if(!(--nestedLevel)) {
					currentTemplate.end = i+2;
					templatesHash.push(currentTemplate);
					currentTemplate = {};
					nestedLevel = 0;
				}
				++i;
			}
		}

		for(var i = templatesHash.length-1; i >= 0; --i) {
			var tplCode = txt.substring(templatesHash[i].start, templatesHash[i].end);
			txt = txt.substring(0, templatesHash[i].start) + '\x01' + hidden.push(tplCode) + '\x02' + txt.substr(templatesHash[i].end);
		}
	}

	function hideTag(tag) {
		hideExpr(RegExp('<' + tag + '( [^>]+)?>[\\s\\S]+?<\\/' + tag + '>', 'gi'))
		// hideExpr('<' + tag + '>[\\s\\S]+?<\\/' + tag + '>')
	}

	function restoreAll() {
		while(hidden.length > 0)
		txt = txt.replace('\x01' + hidden.length + '\x02', hidden.pop())
	}
}

$('#wpTextbox1').bind('wikiEditor-toolbar-buildGroup-gadgets', function(event) {
  WikifButton();
});

// Канец коду Вікіфікатара
//