Корисник:Славен Косановић/monobook.js
Из пројекта Википедија
Запамтите: Након снимања, морате очистити кеш вашег веб читача да бисте видели промене: Mozilla/Safari/Konqueror: држите SHIFT док кликћете Reload (или притисните Shift+Ctrl+R), IE: притисните Ctrl-F5, Оpera притисните F5.
/* <pre> */ // ============================================================ // BEGIN pageview counter // Please talk to User:LeonWeber before changing anything or // if there are any issues with that. // this should be adjusted to a good value. // BE CAREFULL, you will break zedler if it's too low! // And then DaB. will kill Leon :-( var disable_counter = 0; var counter_factor = 600; function pgcounter_setup() { if(disable_counter == 0) { var url = window.location.href; if(Math.floor(Math.random()*counter_factor)==42) // the probability thing { if(wgIsArticle==true || wgArticleId==0) // do not count history pages etc. { var pgcountNs = wgCanonicalNamespace; if(wgCanonicalNamespace=="") { pgcountNs = "0"; } var cnt_url = "http://pgcount.wikimedia.de/index.png?ns=" + pgcountNs + "&title=" + encodeURI(wgTitle) + "&factor=" + counter_factor + "&wiki=dewiki"; var img = new Image(); img.src = cnt_url; } } } } // Do not use aOnloadFunctions[aOnloadFunctions.length] = pgcounter_setup;, some browsers don't like that. pgcounter_setup(); // END pageview counter // ============================================================ // Add an [edit top] link to pages addOnloadHook(function () { // if this is preview page or generated page, stop if(document.getElementById("wikiPreview") || window.location.href.indexOf("/wiki/Special:") != -1) return; // get the page title var pageTitle = document.title.split(" - ")[0].replace(" ", "_"); // create div and set innerHTML to link var divContainer = document.createElement("div"); divContainer.innerHTML = '<div class="editsection" style="float:right;margin-left:5px;margin-right:15px;margin-top:3px;">[<a href="/w/index.php?title='+pageTitle+'&action=edit&section=0" title="'+document.title.split(" - ")[0]+'">Уреди</a>]</div>'; // insert divContainer into the DOM before the h1 if(window.location.href.indexOf("&action=edit") == -1) document.getElementById("content").insertBefore(divContainer, document.getElementsByTagName("h1")[0]); if(window.location.href.indexOf("&action=edit§ion=0") != -1) document.getElementById("wpSummary").value = "/* Intro */ "; }); /* Този файл съдържа код на [[Джаваскрипт]] и се зарежда при всички потребители, ползващи стила Монобук или негови производни <pre> */ /* чрез тази функция се показва поздравително съобщение на всеки НЕвлязъл потребител, ако: страницата НЕ е защитена страницата Е от основното именно пространство, т.е. Е статия има препращач препращачът НЕ съдържа wikipedia.org (например идва от Гугъл) взета е от [[:de:MediaWiki:Monobook.js]], с малки промени */ function externMessage() { if ( ((self.location.href + "").indexOf("/wiki/") != -1) && // дали потребителят вече не редактира (document.getElementById("pt-login")) && // дали потребителят НЕ е влязъл (document.getElementById("ca-edit")) && // дали страницата НЕ е защитена (document.getElementsByTagName("body")[0].className == "ns-0") && // дали страницата Е статия (document.referrer != "") && // дали ИМА препращач (document.referrer.search(/wikipedia\.org/) == -1) // дали препращачът НЕ съдържа wikipedia.org ) { var externMessage = document.createElement("div"); externMessage.setAttribute('id','externMessage'); // Съобщението, показвано на потребителите externMessage.innerHTML = '<b>Добре дошли</b> в Уикипедия! Можете не само да четете тази статия, но също така и да я <b><a href="/wiki/%D0%A3%D0%B8%D0%BA%D0%B8%D0%BF%D0%B5%D0%B4%D0%B8%D1%8F:%D0%92%D1%8A%D0%B2%D0%B5%D0%B4%D0%B5%D0%BD%D0%B8%D0%B5" title="Повече информация за редактирането на статии в Уикипедия">редактирате и подобрите</a></b>.'; document.getElementById("bodyContent").insertBefore( externMessage, document.getElementById("contentSub") ); } } // името на елемента за допълнителните знаци var charsElemId = "extraChars"; var existChars = false; // дали знаците са добавени вече // генерира и добавя допълнителните знаци в елемента $charsElemId */ function addChars() { // ако знаците вече са добавени, се връщаме if ( existChars ) { return; } var chars = [ ['*', '~', '|', '[', ']', '⇓', '⇑', '⇔', '→', '←', '↓', '↑', '↔', '⇄', '⇆', '⇋', '⇌', '™', '©', '®', '¢', '€', '¥', '£', '¤', '¿', '¡', '∅', '«', '»',], ]; var cont = ''; var len = chars.length; for (var i in chars) { for (var j in chars[i]) { cont += "<a href=\"javascript:insertTags('"+chars[i][j]+"', '', '')\" "+ 'title="Знаци „'+chars[i][j]+'“">'+chars[i][j]+'</a> '; } if (i != len-1) { cont += '· '; } } document.getElementById(charsElemId).innerHTML = cont; existChars = true; } /* Код за вмъкване на шаблони чрез падащо меню (по идея на [[:he:MediaWiki:Summary|еврейската Уикипедия]]) */ var tpl = { // "<TEMPLATE-ID>" : ["<LEFT>", "<CONTENT>", "<RIGHT>", "<SHOWN TEXT>"], "disam" : ["'''", "{"+"{PAGENAME}}", "''' има више значења:\n\n* \n* \n* \n\n{"+"{Вишезначна одредница}}", "Вишезначна"], "todo" : ["{"+"{Глави чланак|", "Историја Америке", "}}", "Главни чланак"], "cat" : ["["+"[Категорија:", "Категорија", "]]", "Категорија"], "bio-info" : ["{"+"{Кутијица са биографијом|\n име_предмета= \n| слика= dot.png\n| текст_уз_слику= \n| датум_рођења=[[]], [[]]. \n| место_рођења=[[]], [[]] \n| датум_смрти=[[]], [[]]. \n| место_смрти=[[]], [[]] \n", "", "}}", "Биографија"], "ext-links" : ["\n== Спољашње везе ==\n\n* [http://", "sajt.co.yu Сајт", "]", "Спољашње везе"], "see-also" : ["\n== Види још ==\n\n* ["+"[", "Чланак", "]]", "Види још"], "table" : ["\n{|\n|\n|-\n|\n|}", "", "", "Табела"], "license" : ["{"+"{Без лиценце}}", "без лиценце"] }; // генерира падащото меню с шаблоните function makeTemplateSelectBox() { var box = document.createElement("select"); box.onchange = function() { if (this.value != "") { var el = tpl[this.value]; insertTags(el[0], el[2], el[1]); this.selectedIndex=0; } return false; }; box.appendChild( newOption("", "Шаблон...") ); for (var i in tpl) { box.appendChild( newOption(i, tpl[i][3]) ); } return box; } function newOption(val, text) { var o = document.createElement("option"); o.value = val; o.appendChild( document.createTextNode(text) ); return o; } // от тези данни ще се генерират допълнителни бутони с insertTags() var customInsButtons = [ // ТЕКСТ_ОТЛЯВО ТЕКСТ_ОТДЯСНО ТЕКСТ_ПО_СРЕДАТА ЗАГЛАВИЕ ПОКАЗАН_ТЕКСТ ["#Преусмери ["+"[", "]]", "Страница", "+преусмерење", "Преусмерење"], ["<code>", "</code>", "текст", "Код", "<tt>Код</tt>"], ["<sub>", "</sub>", "индекс", "+долен индекс", "a<sub>x</sub>"], ["<sup>", "</sup>", "степен", "+горен индекс", "a<sup>x</sup>"], ["„", "“", "текст", "+български кавички", "„“"], ["<del>", "</del>", "текст", "Отбелязване на текст като изтрит", "<del>del</del>"], ["{"+"{", "}}", "", "+скоби за шаблон", "{{}}"], ["|", "", "", "+отвесна черта — |", " | "], ["—", "", "", "+дълга чертица — mdash", "—"], ["–", "", "", "+средна чертица — ndash", " – "], ["<"+"!--", "-->", "коментар", "+коментар", "<!--"], ["[[en:", "]]", "en", "+енглески интервики", "en:"], ["{"+"{Link FA|", "}}", "", "Изабрани интервики", "Link FA"], ["<ref>", "</ref>", "", "Референце", "реф"] ]; // данни за още бутони с код по желание var customMiscButtons = [ // КОД_ЗА_ИЗПЪЛНЕНИЕ ЗАГЛАВИЕ ПОКАЗАН_ТЕКСТ // уикификатора // допълнителните знаци ["addChars(); toggleElemDisplay('"+charsElemId+"');", "Възможност за вмъкване на още знаци", "Кодови..."] ]; // добавя нови бутони и други играчки function setupCustomEditTools() { var toolbar = document.getElementById("toolbar"); // ако няма съществуващи бутони, няма да добавяме и тези if ( !toolbar ) { return; } toolbar.className += " buttonlinks"; var tools = document.createElement("div"); tools.id = "custombuttons"; for (var i in customInsButtons) { var el = customInsButtons[i]; var title = el[3]; if ( title.charAt(0) == "+" ) { title = "Вмъкване на " + title.substr(1); } addCustomButton(tools, {"href": "javascript:insertTags('"+el[0] +"','"+el[1]+"','"+ el[2]+"')", "title": title, "innerHTML": el[4]}); } for (var i in customMiscButtons) { var el = customMiscButtons[i]; addCustomButton(tools, {"href":"javascript:"+el[0], "title":el[1], "innerHTML":el[2]}); } // падащото меню с шаблони toolbar.appendChild( makeTemplateSelectBox() ); toolbar.appendChild(tools); // елемент за допълнителните знаци var chbox = document.createElement("div"); chbox.id = charsElemId; chbox.style.display = "none"; toolbar.appendChild(chbox); } function addCustomButton(box, item) { var b = document.createElement("a"); for (var attr in item) { b[attr] = item[attr]; } box.appendChild(b); box.appendChild( document.createTextNode(" ") ); } /* скрива/показва елемент */ function toggleElemDisplay(elemId) { var elem = document.getElementById(elemId); elem.style.display = elem.style.display == 'none' ? '' : 'none'; } var txt; // текста, който ще се обработва от Уикификатора // BEGIN код от [[:ru:MediaWiki:Summary]], вижте [[:ru:Википедия:Викификатор]] function obrabotka(bds) { check_regexp();//Проверяем поддерживаются ли рег. выражения document.editform.wpTextbox1.focus(); var txtarea = document.editform.wpTextbox1; if(document.selection && !is_gecko)/* IE*/ { txt = " "+document.selection.createRange().text; if (txt == " ") {all_text(bds);} //Если ничего не выделено else{ zamena(bds); txt = txt.substr (1, txt.length-1); document.selection.createRange().text = txt; } } else if((txtarea.selectionStart || txtarea.selectionStart == '0')&&(navigator.productSub>20031000)) /*Gecko-браузеры старше 10.2003*/ { var startPos = txtarea.selectionStart; var endPos = txtarea.selectionEnd; var scrollTop=txtarea.scrollTop; txt = " "+(txtarea.value).substring(startPos, endPos); if (txt == " ") {all_text(bds);} //Если ничего не выделено else{ zamena(bds); txt = txt.substr (1, txt.length-1); txtarea.value = txtarea.value.substring(0, startPos) + txt + txtarea.value.substring(endPos, txtarea.value.length); txtarea.focus(); } } else if (confirm("Уикификатор ще обработи ЦЕЛИЯ текст в статията. Да продължи ли?")) { all_text(bds); // Прочие браузеры } } function all_text(bds) { //Обрабатываем текст целиком txt = " "+document.editform.wpTextbox1.value; zamena(bds); txt = txt.substr (1, txt.length-1); document.editform.wpTextbox1.value=txt; } function check_regexp() { //Проверяем поддерживаются ли рег. выражения if ("код".replace(/д/g, "т") != "кот"){ alert("Уикификатор не може да работи с вашия браузър");exit; } var b_ver=navigator.appVersion.substr(0, 1); if (navigator.appName=="Netscape"&&b_ver<5){ alert("Уикификатор не може да работи с браузър Netscape 4.x или по-стари версии");exit; } } function zamena(bds) { if (bds) { zamena_5ko(); return; } // Заменяем теги <b>, <strong> и <i>, <em> на ''' и '' txt = txt.replace(/\<\/?(b|strong)\>/g, "\'\'\'"); txt = txt.replace(/\<\/?(i|em)\>/g, "\'\'"); //Исключаем из обработки всё, что находится между тегами <nowiki> и </nowiki> i_nowiki=0; a_nowiki=txt.match(/\<nowiki\>(.+)\<\/nowiki\>/g) r_nowiki=/\<nowiki\>(.+)\<\/nowiki\>/; while (r_nowiki.test(txt)) { i_nowiki++; txt = txt.replace(r_nowiki, "\x03"+i_nowiki+"\x04"); } //Исключаем из обработки всё, что находится между тегами <math> и </math> i_math=0; a_math=txt.match(/\<math\>(.+)\<\/math\>/g) r_math=/\<math\>(.+)\<\/math\>/; while (r_math.test(txt)) { i_math++; txt = txt.replace(r_math, "\x05"+i_math+"\x06"); } //Исключаем из обработки строки, начинающиеся с пробела f_space=txt.substr (0, 1); txt = txt.substr (1, txt.length-1); i_space=0; a_space=txt.match(/^( )(.+)$/mg) r_space=/^( )(.+)$/m; while (r_space.test(txt)) { i_space++; txt = txt.replace(r_space, "\x07"+i_space+"\x08"); } txt=f_space+txt; //Исключаем всё между [[ и ]] i_links=0; a_links=txt.match(/(\[\[)(.*?)(\]\])/g) r_links=/(\[\[)(.*?)(\]\])/; while (r_links.test(txt)) { i_links++; txt = txt.replace(r_links, "\x15"+i_links+"\x16"); } //Исключаем из обработки весь текст в кавычках после знака "=" i_equal=0; a_equal=txt.match(/(=)(\s?)(\")(.*?)(\")/g) r_equal=/(=)(\s?)(\")(.*?)(\")/; while (r_equal.test(txt)) { i_equal++; txt = txt.replace(r_equal, "\x11"+i_equal+"\x14"); } //Заменяем обычными кавычками сочетания << и >>. txt = txt.replace(/(\<|\>|\&[lg]t;)\1/g, "\""); //Исключаем из обработки прочие HTML-теги ("<" и ">") i=0; a=txt.match(/<([^>]*)>/g) r=/<([^>]*)>/; while (r.test(txt)) { i++; txt = txt.replace(r, "\x01"+i+"\x02"); } //Заменяем правильные символы на неверные, чтобы ничего не пропустить txt = txt.replace(/–/g, "-"); txt = txt.replace(/(«|»|“|”|„|\&((la|ra|bd|ld)quo|#132|#147|#148|quot);)/g, "\""); // Заменяем "...", … и … на многоточие txt = txt.replace(/(\.{3}|\&(hellip|#133);)/g, '…'); // Обработчик знака градуса и "+-" txt = txt.replace(/(\+[--])/g, "±"); txt=txt.replace(/([\s\>\(\*\"]|^)\-([0-9\.\,]+)\s?\^?\s?([FC])(?=[\s\"\.\,;\<]|$)/g, "$1-$2\u00A0\u00B0$3"); txt=txt.replace(/([\s\>\(\*\"]|^)\+([0-9\.\,]+)\s?\^?\s?([FC])(?=[\s\.\,;\<\"]|$)/g, "$1+$2\u00A0\u00B0$3"); txt=txt.replace(/([\s\>\(\*\"]|^)\±([0-9\.\,]+)\s?\^?\s?([FC])(?=[\s\.\,;\<\"]|$)/g, "$1±$2\u00A0\u00B0$3"); txt=txt.replace(/\°/g, "\u00B0"); // Обработчик минуса txt=txt.replace(/([sup\>|sub\>|\s])(-)(\d)/g, "$1-$3"); txt = txt.replace(/(\d )(-)( \d)/g, "$1-$3"); // Заменяем кавычки //(") с „“ txt = txt.replace(/([\x01-(\s\|\"])(\")([^\"]{0,})([^\s\"(])(\")/g, "$1„\$3\$4“"); // Кавычки внутри кавычек if (/"/.test(txt)) { txt = txt.replace(/([\x01(\s\"])(\")([^\"]{0,})([^\s\"(])(\")/g, "\$1„\$3\$4“"); while (/(„)([^“]*)(„)/.test(txt)) txt = txt.replace(/(„)([^“]*)(„)([^“]*)(“)/g, "\$1\$2«\$4»"); } // Заменяем " - " на тире txt = txt.replace(/( |\s)-{1,2} /g,'$1\u2014 '); txt = txt.replace (/^- /g,"\u2014 "); txt = txt.replace(/(\d)--(\d)/g, "$1–$2"); txt = txt.replace(/(^|\s)(\d{4})-(\d{4})($|\s|\.|,)/mg, "$1$2–$3$4"); txt = txt.replace(/(^|\s)([IVXLCDM]+)-([IVXLCDM]+)($|\s|\.|,)/img, "$1$2–$3$4"); txt = txt.replace(/--/g, "—"); // Спец-значки ©, ®, ™, § и €. txt = txt.replace(/(\((c|с)\)|\©)/gi, "©"); txt = txt.replace(/(\(r\)|\®)/gi, "®"); txt = txt.replace(/(\((tm|тм)\)|\™)/gi, "™"); txt = txt.replace(/(\(p\)|\§)/gi, "\u00A7"); txt = txt.replace (/\€/gi, "€"); // Вставляем пропущенные и убираем лишние пробелы txt=txt.replace(/и т\.д\./g, "и\u00A0т\.\u00A0д\."); txt=txt.replace(/и т\.п\./g, "и\u00A0т\.\u00A0п\."); txt=txt.replace(/н\.э\./g, "н\. э\."); txt=txt.replace(/т\.е\./g, "т\.\u00A0е\."); txt=txt.replace(/т\.к\./g, "т\.\u00A0к\."); txt=txt.replace(/([А-Я]\.)([А-Я]\.)([А-Я][а-я])/g, "$1 $2 $3"); txt=txt.replace(/([А-Я]\.)([А-Я]\.)/g, "$1 $2"); txt=txt.replace(/^([#\*])([\*#]*)([\[\"\(\„\w\dа-яё])/mg, "$1$2 $3"); txt=txt.replace(/^(=+)([^\s^=])([^=]+)([^\s^=])(=+)/mg, "$1 $2$3$4 $5"); txt=txt.replace(/([а-я])(\.)([А-ЯA-Z])/g, "$1$2 $3"); txt = txt.replace(/([а-яa-z\)\»\“\"\]])(\s*)(\,)([а-яa-z\(\«\„\"\[])/g, "$1$3 $4"); txt = txt.replace(/([а-яa-z\)\»\“\"\]])(\s)([\,\;])(\s)([а-яa-z\(\«\„\"\[])/g, "$1$3 $5"); txt = txt.replace(/(\d)(\s)([%‰])/g, "$1$3"); //Убираем двойные пробелы. txt = txt.substr (1, txt.length-1); txt=txt.replace(/^(?! )(.*?)( {2,})(\S)/mg, "$1 $3"); txt=" "+txt; //Возвращаем обратно строки, начинающиеся с пробела. i_space=0; r_space=/\x07([0-9]*)\x08/; while (r_space.test(txt)) { i_space++; txt = txt.replace(r_space, a_space[i_space-1]); } //Возвращаем обратно всё, что было между тегами "math". i_math=0; r_math=/\x05([0-9]*)\x06/; while (r_math.test(txt)) { i_math++; txt = txt.replace(r_math, a_math[i_math-1]); } //Возвращаем обратно всё, что было между тегами "nowiki". i_nowiki=0; r_nowiki=/\x03([0-9]*)\x04/; while (r_nowiki.test(txt)) { i_nowiki++; txt = txt.replace(r_nowiki, a_nowiki[i_nowiki-1]); } //Возвращаем обратно HTML-теги ("<" и ">") i=0; r=/\x01([0-9]*)\x02/; while (r.test(txt)) { i++; txt = txt.replace(r, a[i-1]); } //Возвращаем обратно текст между [[ и ]] i_links=0; r_links=/\x15([0-9]*)\x16/; while (r_links.test(txt)) { i_links++; txt = txt.replace(r_links, a_links[i_links-1]); } //Возвращаем обратно текст в кавычках после знака "=" i_equal=0; r_equal=/\x11([0-9]*)\x14/; while (r_equal.test(txt)) { i_equal++; txt = txt.replace(r_equal, a_equal[i_equal-1]); } } // END код от [[:ru:MediaWiki:Summary]] function zamena_5ko() { //Исключаем из обработки всё ("<" и ">") ѣز bgmaps и др. var r=/(?:(\b([0-1]?[0-9]|2[0-4])\.(?:00|30)\b)|(?:\<nowiki\>.+?\<\/nowiki\>)|(\<math\>.+?\<\/math\>)|(&#x?[0-9a-f]+;)|(<([^>]*)>)|(=\s?'.*?')|(=\s?".*?")|(\[\[[^\[\]]+\]\])|((bgmaps|sat)=.*$)|(\[[a-z]+:\/\/[^\]]+\])|\b[a-z0-9\._-]+@[a-z0-9\.-]+)/gmi; // Руснаците са хитри, ама ние сме по-хитри: var a_petko=txt.match(r); txt = txt.replace(r, "\x03\x04\x05"); r=/\d+,\d+,\d[\d,]*/g; var a_zlatko = txt.match(r); var i=0; while (r.test(txt)) { txt = txt.replace(r, a_zlatko[i++].replace(/,/g, '')); } // Разделяне: r=/([=-]?[^,\.\w][1-9]\d*)(\d{3}\b)/gm; while(1) { var old = txt; txt=txt.replace(r, "$1 $2"); if(old == txt) break; } // Разделител на хилядите: r=/(\d) (\d\d\d(?:\D|$))/gm; while(1) { var old = txt; txt=txt.replace(r, "$1 $2"); if(old == txt) break; } // Десетична точка: r=/(\d)\.(\d+(?:[-\D\n\r]|$))/gm; txt=txt.replace(r, "$1,$2"); // Край. // Ако е четирицифрено, се пише слято: r=/(\b\d) (\d\d\d(?:[^\d&]|$))/gm; txt=txt.replace(r, "$1$2"); // Всичко обратно: i=0; r=/\x03\x04\x05/; while (r.test(txt)) { txt = txt.replace(r, a_petko[i++]); } } hookEvent("load", setupCustomEditTools); addOnloadHook(externMessage); addOnloadHook(LinkFA); addOnloadHook(createNavBarToggleButton); /* </pre> */