Utente:Alex brollo/PersonalTools.js
Notarella: Aroppo pubbreca putisse necessità 'e pulezzà 'a caché d' 'o navigatóre pe vedé 'e cagnamienti.
- Firefox / Safari: Sprémme 'o buttóne maiuscole e ffà clic ncopp'a Recarreca, o pure spremme Ctrl-F5 o Ctrl-R (⌘-R ncopp'a Mac)
- Google Chrome: spremme Ctrl-Shift-R (⌘-Shift-R ncopp'a nu Mac)
- Internet Explorer/edge: Spremme 'o buttóne Ctrl pe' tramente ca faie click ncopp'a Refresh, o pure spremmere Ctrl-F5
- Opera: Vaje addò 'o Menu → Mpustaziune (Opera → Mpustaziune ncopp' 'o Mac) e po' ncopp'a Privacy & sicurezza → Pulezza date d' 'o browser → Immaggene e file d' 'a cache.
// Nuova versione importata da en.source; completa eliminazione di eis. Revisione di alcuni shortcuts per problemi con Alt sotto windows.
ws={};
importStylesheet('User:Alex brollo/PersonalTools.css' );
// inizializzazione di localStorage.memoRegex come oggetto vuoto se indefinito
if (localStorage.memoRegex===undefined) {
localStorage.memoRegex=JSON.stringify({});
}
if (localStorage.memoRegexEdited===undefined) {
localStorage.memoRegexEdited=false; // nota: viene salvato come stringa "false"
}
mw.activeElement=$("#wpTextbox1")[0];
$("textarea, input[type!='checkbox'][type!='button'][type!='search'][type!='hidden'][type!='submit'][type!='radio'][name!='wpAntispam']").focusin(function () {
mw.activeElement=this;
});
/**
* http://www.openjs.com/scripts/events/keyboard_shortcuts/
* Version : 2.01.B
* By Binny V A
* License : BSD
*/
var shortcut = {
'all_shortcuts':{},//All the shortcuts are stored in this array
'add': function(shortcut_combination,callback,opt) {
//Provide a set of default options
var default_options = {
'type':'keydown',
'propagate':false,
'disable_in_input':false,
'target':document,
'keycode':false
};
if(!opt) opt = default_options;
else {
for(var dfo in default_options) {
if(typeof opt[dfo] == 'undefined') opt[dfo] = default_options[dfo];
}
}
var ele = opt.target;
if(typeof opt.target == 'string') ele = document.getElementById(opt.target);
var ths = this;
shortcut_combination = shortcut_combination.toLowerCase();
//The function to be called at keypress
var func = function(e) {
e = e || window.event;
if(opt.disable_in_input) { //Don't enable shortcut keys in Input, Textarea fields
var element;
if(e.target) element=e.target;
else if(e.srcElement) element=e.srcElement;
if(element.nodeType==3) element=element.parentNode;
if(element.tagName == 'INPUT' || element.tagName == 'TEXTAREA') return;
}
//Find Which key is pressed
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
var character = String.fromCharCode(code).toLowerCase();
if(code == 188) character=","; //If the user presses , when the type is onkeydown
if(code == 190) character="."; //If the user presses , when the type is onkeydown
var keys = shortcut_combination.split("+");
//Key Pressed - counts the number of valid keypresses - if it is same as the number of keys, the shortcut function is invoked
var kp = 0;
//Work around for stupid Shift key bug created by using lowercase - as a result the shift+num combination was broken
var shift_nums = {
"`":"~",
"1":"!",
"2":"@",
"3":"#",
"4":"$",
"5":"%",
"6":"^",
"7":"&",
"8":"*",
"9":"(",
"0":")",
"-":"_",
"=":"+",
";":":",
"'":"\"",
",":"<",
".":">",
"/":"?",
"\\":"|"
};
//Special Keys - and their codes
var special_keys = {
'esc':27,
'escape':27,
'tab':9,
'space':32,
'return':13,
'enter':13,
'backspace':8,
'scrolllock':145,
'scroll_lock':145,
'scroll':145,
'capslock':20,
'caps_lock':20,
'caps':20,
'numlock':144,
'num_lock':144,
'num':144,
'pause':19,
'break':19,
'insert':45,
'home':36,
'delete':46,
'end':35,
'pageup':33,
'page_up':33,
'pu':33,
'pagedown':34,
'page_down':34,
'pd':34,
'left':37,
'up':38,
'right':39,
'down':40,
'f1':112,
'f2':113,
'f3':114,
'f4':115,
'f5':116,
'f6':117,
'f7':118,
'f8':119,
'f9':120,
'f10':121,
'f11':122,
'f12':123
};
var modifiers = {
shift: { wanted:false, pressed:false},
ctrl : { wanted:false, pressed:false},
alt : { wanted:false, pressed:false},
meta : { wanted:false, pressed:false} //Meta is Mac specific
};
if(e.ctrlKey) modifiers.ctrl.pressed = true;
if(e.shiftKey) modifiers.shift.pressed = true;
if(e.altKey) modifiers.alt.pressed = true;
if(e.metaKey) modifiers.meta.pressed = true;
for(var i=0; k=keys[i],i<keys.length; i++) {
//Modifiers
if(k == 'ctrl' || k == 'control') {
kp++;
modifiers.ctrl.wanted = true;
} else if(k == 'shift') {
kp++;
modifiers.shift.wanted = true;
} else if(k == 'alt') {
kp++;
modifiers.alt.wanted = true;
} else if(k == 'meta') {
kp++;
modifiers.meta.wanted = true;
} else if(k.length > 1) { //If it is a special key
if(special_keys[k] == code) kp++;
} else if(opt.keycode) {
if(opt.keycode == code) kp++;
} else { //The special keys did not match
if(character == k) kp++;
else {
if(shift_nums[character] && e.shiftKey) { //Stupid Shift key bug created by using lowercase
character = shift_nums[character];
if(character == k) kp++;
}
}
}
}
if(kp == keys.length &&
modifiers.ctrl.pressed == modifiers.ctrl.wanted &&
modifiers.shift.pressed == modifiers.shift.wanted &&
modifiers.alt.pressed == modifiers.alt.wanted &&
modifiers.meta.pressed == modifiers.meta.wanted) {
callback(e);
if(!opt['propagate']) { //Stop the event
//e.cancelBubble is supported by IE - this will kill the bubbling process.
e.cancelBubble = true;
e.returnValue = false;
//e.stopPropagation works in Firefox.
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
return false;
}
}
};
this.all_shortcuts[shortcut_combination] = {
'callback':func,
'target':ele,
'event': opt['type']
};
//Attach the function with the event
if(ele.addEventListener) ele.addEventListener(opt['type'], func, false);
else if(ele.attachEvent) ele.attachEvent('on'+opt['type'], func);
else ele['on'+opt['type']] = func;
},
//Remove the shortcut - just specify the shortcut and I will remove the binding
'remove':function(shortcut_combination) {
shortcut_combination = shortcut_combination.toLowerCase();
var binding = this.all_shortcuts[shortcut_combination];
delete(this.all_shortcuts[shortcut_combination]);
if(!binding) return;
var type = binding['event'];
var ele = binding['target'];
var callback = binding['callback'];
if(ele.detachEvent) ele.detachEvent('on'+type, callback);
else if(ele.removeEventListener) ele.removeEventListener(type, callback, false);
else ele['on'+type] = false;
}
}
ws.alertMessage = function (title, text) {
if (text === undefined) {
text = title;
title = undefined;
}
var id = Math.random().toString(36).substring(5);
var box = '<div class="alert-message" id="' + id + '">'
+ '<button class="button alert-message-close">x</button>';
if (title)
box += '<strong>' + title + '</strong><br>' ;
box += text + '</div>';
$('#bodyContent').append(box);
$('.alert-message-close').click(function() {
$('.alert-message-close').parents('.alert-message').remove();
});
$("#" + id).fadeTo(3000, 500).slideUp(500, function() {
$("#" + id).slideUp(500).remove();
});
};
count = function(testo, stringa) {
var n = 0;
while (testo.indexOf(stringa) > -1) {
n = n + 1;
testo = testo.replace(stringa, "");
}
return n;
}
;
ws.find_stringa = function(testo, idi, idf, dc, x) {
var idip = testo.indexOf(idi);
var idfp = testo.indexOf(idf, idip + idi.length) + idf.length;
var vvalore="";
if (idip > -1 && idfp > -1) {
if (x !== "") {
while (count(testo.slice(idip, idfp), x) > count(testo.slice(idip, idfp), idf)) {
idfp = testo.indexOf(idf, idfp) + idf.length;
}
}
if (dc === 0) {
vvalore = testo.slice(idip + idi.length, idfp - idf.length);
} else {
vvalore = testo.slice(idip, idfp);
}
} else {
vvalore = "";
}
return vvalore;
}
;
ws.produciLista = function(testo, s1, s2, delim, x) {
var lista = [];
var elemento="";
while (ws.find_stringa(testo, s1, s2, !0, x) > "") {
elemento = ws.find_stringa(testo, s1, s2, !0, x);
testo = testo.replace(elemento, "");
if (delim) {
lista.push(elemento);
} else {
lista.push(elemento.slice(s1.length, -s2.length));
}
}
return lista;
}
;
/* memoRegex */
ws.memoRegex=JSON.parse(localStorage.memoRegex);
// https://la.wikisource.org/wiki/Usor:Alex_brollo/PersonalTools.js
// caricamento dell'oggetto memoRegex per selezione di codice in modalità edit
ws.caricaRegex=function () {
var memo=JSON.parse(localStorage.memoRegex);
var toAdd=JSON.parse(ws.selection()[1]);
for (var m in toAdd) {
memo[m]=toAdd[m];
}
localStorage.memoRegex=JSON.stringify(memo);
ws.memoRegex=JSON.parse(localStorage.memoRegex);
// alert("Le sostituzioni selezionate sono state caricate");
};
// lancio della serie di regex su header. body, footer
ws.memoRegexRun=function () {
var testo="";
testo=$("#wpTextbox1").val();
$.each(ws.memoRegex,function(index,value) {
// verifica se corre sectionEdit e se è attiva una section con nome
if (ws.sectionEdit && ws.sectionEdit.name!=="") {
// verifica se nel commento esiste un prefisso/suffisso, e se corrisponde alla section attiva
if (test(value[0],ws.sectionEdit.name)) {
testo=testo.replace(RegExp(index,value[2]),value[1]);
}
// altrimenti esegui
} else {
testo=testo.replace(RegExp(index,value[2]),value[1]);
}
});
$("#wpTextbox1").val(testo);
if (mw.config.get("wgCanonicalNamespace")==="Page") {
testo=$("#wpHeaderTextbox").val();
$.each(ws.memoRegex,function(index,value) {
testo=testo.replace(RegExp(index,value[2]),value[1]);
});
$("#wpHeaderTextbox").val(testo);
testo=$("#wpFooterTextbox").val();
$.each(ws.memoRegex,function(index,value) {
testo=testo.replace(RegExp(index,value[2]),value[1]);
});
$("#wpFooterTextbox").val(testo);
}
};
// caricamento dell'oggetto memoRegex da pagina remota di default (nDiscussioni_indice correlato alla pagina corrente)
ws.caricaRegexRemoto=function () {
// se siamo in nsPagina tenta di caricare una memoRegex memorizzata in Discussioni indice
if (mw.config.get("wgCanonicalNamespace")=="Page") {
var paginaFonte=mw.config.get("wgPageName");
paginaFonte="Index_talk:"+(/.+:(.+)\//).exec(paginaFonte)[1]; console.log(paginaFonte);
paginaFonte=$.ajax({url:"/w/index.php?action=raw&title="+paginaFonte+"&r="+Math.random(),async:false}).responseText;console.log(paginaFonte);
var codiceMemoregex=ws.find_stringa(paginaFonte,'{"','"]}',1); console.log(codiceMemoregex);
var memo={};
try {
memo=JSON.parse(codiceMemoregex);
localStorage.memoRegex=JSON.stringify(memo);
ws.memoRegex=JSON.parse(localStorage.memoRegex);
ws.alertMessage("MemoRegex", "Le sostituzioni correlate alla pagina sono state caricate");
}
catch(err) {
ws.alertMessage("MemoRegex", "La pagina Discussioni indice non esiste/non contiene memoRegex");
localStorage.memoRegex="{}";
}
// in ns diversi da nsPagina, tenta di caricare in modo additivo le regex contenuto in un testo selezionato
} else {
if (ws.selection()[1]!=="") {
ws.caricaRegex();
}
}
};
// funzione generica di salvataggio di pagina remota
ws.salvaPagina = function (title,text,summary) {
new mw.Api().postWithToken( 'edit', {
action: 'edit',
title: title,
summary: summary,
text: text,
}).done(function( data ) {
if ( data && data.edit && data.edit.result == 'Success' ) {
console.log("OK, pagina " + title + "salvata");
}
});
};
// salvataggio memoRegex su pagina remota (nsDiscussioni_indice)
ws.salvaRegexRemoto=function() {
if (mw.config.get("wgCanonicalNamespace")=="Page") {
var paginaFonte=mw.config.get("wgPageName");
paginaFonte="Index talk:"+(/.+:(.+)\//).exec(paginaFonte)[1]; console.log(paginaFonte);
var regexOld="";
var testoPaginaFonte="";
var regexFormattato="";
//paginaFonte="Index talk:"+paginaFonte;
testoPaginaFonte = $.ajax({url:mw.config.get("wgServer")+"/w/index.php?action=raw&title="+paginaFonte,async:false}).responseText;
var errore=ws.find_stringa(testoPaginaFonte,"<!DOCTYPE html>","</html>",1);
if (errore!=="") {
testoPaginaFonte=testoPaginaFonte.replace(errore,"");
}
regexFormattato=localStorage.memoRegex.replace(/("\],)/g,"$1\n");
regexOld=ws.find_stringa(testoPaginaFonte,'{"','"]}',1);
if (regexOld!=="") {
testoPaginaFonte=testoPaginaFonte.replace(regexOld,regexFormattato);
} else {
testoPaginaFonte+="\n== memoRegex ==\n<nowiki>"+regexFormattato+"</nowiki>\n";
}
ws.salvaPagina(paginaFonte,testoPaginaFonte,"salvataggio memoregex");
ws.alertMessage("MemoRegex", "Regex have been saved into "+paginaFonte);
} else {
ws.alertMessage("MemoRegex", "Routine can only be called from nsPage");
}
};
// funzione generica di creazione di bottoni in "bottoniera"
ws.newButton=function(nome, funzione, azione, messaggio) {
// azione è una stringa composta da v,e,s,h rispettivamente view,edit,submit,history
// se nome è un oggetto svolgilo
var p;
if (typeof(nome) === "string") {
p = {
nome: nome,
funzione: funzione,
azione: azione,
messaggio: messaggio
};
} else {
p = nome;
}
if (p.messaggio===undefined) p.messaggio="Nessun aiuto registrato";
if (p.classe===undefined) p.classe="baseButton";
if (p.stile===undefined) p.stile="background-color: #f0f0f0; border: 1px solid #d0d0d0; padding: 3px 6px;"+
"display: inline-block; font-size: 12px; margin: 0; cursor: pointer; border-radius:4px;";
if (p.namespaces!==undefined) {
var listaNamespaces=p.namespaces.split("|");
for (var i=0; i<listaNamespaces.length; i+=1) {
listaNamespaces[i]=$.trim(listaNamespaces[i]);
if (["ns0", "Main", "Principale"].indexOf(listaNamespaces[i]) !== -1) {
listaNamespaces[i] === "";
}
}
if ($.inArray(mw.config.get('wgCanonicalNamespace'),p.namespaces.split(","))==-1) return;
}
// Passo 1: se newtatooo non esiste, lo crea
if ($("#newtattoo").length===0) creaBottoniera();
// fine se azione=history
if (mw.config.get('wgAction') === "history") {
return;
}
// normalizzazione function
if (p.funzione.indexOf("(") === -1 && p.funzione.indexOf(")") === -1) {
p.funzione += "()";
}
// default: bottone presente in view, edit,
if (p.azione === undefined) {
p.azione = "ves";
}
// messaggio di default
if (p.messaggio === undefined) {
p.messaggio = "Nessun messaggio di aiuto registrato";
}
// valutazione condizione di visualizzazione
if (mw.config.get('wgAction') === "edit" && p.azione.indexOf("e") === -1) {
return;
}
if (mw.config.get('wgAction') === "view" && p.azione.indexOf("v") === -1) {
return;
}
if (mw.config.get('wgAction') === "submit" && p.azione.indexOf("s") === -1) {
return;
}
// caso pulsante=immagine
var html = "";
if (p.nome.substring(0, 2) == "//") {
html = '<img class="'+p.classe+'" style="'+p.stile+'" src="' + p.nome + '" onclick="' + p.funzione + '" title="' + p.messaggio +'"';
if (p.ondblclick!==undefined) html+=' ondblclick="'+p.ondblclick+'"';
html+='/>';
}
// caso pulsante=label
else {
html = '<button class="'+p.classe+'" style="'+p.stile+'" type="button" title="' + p.messaggio + '" onclick="' + p.funzione +'"';
if (p.ondblclick!==undefined) html+=' ondblclick="'+p.ondblclick+'"';
html+='><small>' + p.nome + '</small></button>';
}
$("#newtattoo").append($(html));
return false;
};
/* funzione di creazione della bottoniera
Dopo l'esecuzione, esiste #newtattoo */
function creaBottoniera() {
$('#' + (mw.user.options.get('skin') === 'modern' ? 'mw_' : '') + 'content')
.append('<div id="newtattoo" align="right" style="position:fixed;bottom:0; right:0; background-color:white; border: 1px solid; border-color:#F0F0F0; z-index:1500;"></div>');
}
/*
Confronta il suffisso o il prefisso di un nome di sezione nel commento
di una regex, con il nome della sezione corrente; restituisce true o false.
Per indicare un prefisso: --testo
Per indicare un suffisso: testo--
*/
function test(commento,sezione) {
var r_pref=/ (\w+)--/;
var r_suff=/--(\w+)/;
var ok=false;
if (r_pref.test(commento) || r_suff.test(commento)) {
if (r_pref.test(commento)) {
if (RegExp("^"+r_pref.exec(commento)[1]).test(sezione)) ok=true;
} else {
if (r_suff.test(commento)) {
if (RegExp(r_suff.exec(commento)[1]+"$").test(sezione)) ok=true;
}
}
} else ok=true;
return ok;
}
// comandi lanciati al momento del caricamento della pagina corrente
// ws.newButton("regex up","ws.caricaRegex","es","Carica le sostituzioni selezionate");
ws.newButton("salva regex", "ws.salvaRegexRemoto","es","Scarica sulla pagina Discussioni indice le sostituzioni attive");
ws.newButton("carica regex", "ws.caricaRegexRemoto","es","Allinea memoRegex alla pagina Discussioni indice");
ws.newButton("esegui regex", "ws.memoRegexRun","es","Esegue le sostituzioni memorizzate");
if (mw.config.get("wgCanonicalNamespace")==="Page" && mw.config.get("wgAction")==="edit" ) {
// caricamento del nome base pagina corrente
localStorage.currentBasePage=(/.+?:(.+)\/\d+$/m).exec(mw.config.get("wgPageName"))[1];
// se localStorage.currentRegexBasePage non è definito definiscilo
if (localStorage.currentRegexBasePage===undefined) {
localStorage.currentRegexBasePage=localStorage.currentBasePage;
}
// se le regex memorizzate sono relative a un'altra BasePage carica le regex appropriate
if (localStorage.currentRegexBasePage!==localStorage.currentBasePage) {
localStorage.currentRegexBasePage=localStorage.currentBasePage;
mw.caricaRegexRemoto();
}
}
/* findReplace */
$('body').append(
'<div id="findReplace_box" class="box" style="display:none;">' +
'<div class="box-title">Trova & Sostituisci<span class="icon-close findReplace_box_close"></span></div>' +
'<div class="box-main">' +
'<div class="width-50">Cerca (testo o espressione regolare):</div>' +
'<div class="width-50"><input type="text" id="findReplace_find" size="55"/></div>' +
'<div class="width-50">Sostituisci con: </div>' +
'<div class="width-50"><input type="text" id="findReplace_replace" size="55"/></div>' +
'<div class="width-50">Commento: </div>'+
'<div class="width-50"><input type="text" id="findReplace_doc" size="55"/></div>' +
'<div>' +
'<input type="checkbox" id="findReplace_regex"/><label for="findReplace_regex">Espressione regolare</label><br/>' +
'<input type="checkbox" id="findReplace_maiusc"/><label for="findReplace_maiusc">Non distinguere maiuscole/minuscole</label><br/>' +
'<input type="checkbox" id="findReplace_multiriga"/><label for="findReplace_multiriga">Multiriga</label><br/>' +
'<input type="checkbox" id="findReplace_ricorda"/><label for="findReplace_ricorda">Ricorda questa sostituzione (<a target="_blank" href="/wiki/Aiuto:MemoRegex">MemoRegex</a>)</label></div>' +
'<div class="text-right"><input id="findReplace_box_ok" type="button" class="btn blue" value="Applica" />' +
'<input type="button" class="btn blue findReplace_box_close" value="Chiudi" /></div></div>');
ws.selection=function (area){
/*
if(area===undefined){
if(mw.config.get("wgCanonicalNamespace")=="Page"||$("#editBox").length===1)
area=1;
else
area=0;
}
var txtarea=$('textarea')[area];
var txt=$(txtarea).val();
*/
var txt=mw.activeElement.value;
var s=[];
s[0]=txt.substring(0,mw.activeElement.selectionStart);
s[1]=txt.substring(mw.activeElement.selectionStart,mw.activeElement.selectionEnd);
s[2]=txt.substring(mw.activeElement.selectionEnd);
return s;
} ;
// riscrive mw.activeElement e ristabilisce il focus/la selezione attiva
// riceve un array tipo [testo precedente, testo selezionato, testo seguente]
// pone il cursore a fine selezione
ws.scriviSel=function(t) {
mw.activeElement.value=t.join("");
mw.activeElement.selectionStart=t[0].length;
mw.activeElement.selectionEnd= t[0].length + t[1].length;
mw.activeElement.focus();
}
// idem, poi attiva la selezione
ws.scriviSelAlt=function(t) {
mw.activeElement.value=t.join("");
mw.activeElement.selectionStart=t[0].length + t[1].length;
mw.activeElement.selectionEnd= t[0].length + t[1].length;
mw.activeElement.focus();
};
ws.toggleNote = function() {
var editbox = document.getElementsByName('wpTextbox1')[0];
var lista, marks, refs,i;
if (editbox.value.indexOf("<sup>nota</sup>") == -1) {
lista = ws.produciLista(editbox.value, "<ref", '</' + 'ref>', 1);
lista = jQuery.grep(lista, function(n, i) {
return (n.indexOf('<ref ' + 'follow=') == -1);
});
for (i = 0; i < lista.length; i += 1) {
editbox.value = editbox.value.replace(lista[i], "<sup>nota</sup>");
editbox.value = editbox.value + "\n" + lista[i];
}
} else {
marks = count(editbox.value, '<ref' + '>') + count(editbox.value, '<ref ' + 'name=') + count(editbox.value, '<ref ' + 'group=');
refs = count(editbox.value, "<sup>nota</sup>");
if (marks != refs) {
alert("ATTENZIONE: discordanza fra numero delle <br />note (" + marks + ") e numero dei segnaposti (" + refs + "). Controllare!");
return;
}
lista = ws.produciLista(editbox.value, "<ref", '</' + 'ref>', 1);
lista = jQuery.grep(lista, function(n, i) {
return (n.indexOf('<ref ' + 'follow=') == -1);
});
editbox.value = editbox.value.replace(/\n<ref/g, "<ref");
for (i = 0; i < lista.length; i += 1) {
editbox.value = editbox.value.replace(lista[i], "");
}
for (i = 0; i < lista.length; i += 1) {
editbox.value = editbox.value.replace("<sup>nota</sup>", lista[i]);
}
}
};
ws.mostraTrovaSostituisci = function() {
$('#findReplace_box').css("display", "block");
var t = ws.selection();
$("#findReplace_find").attr("value", t[1]);
$("#findReplace_replace").attr("value", t[1]).click();
};
$('#findReplace_box_ok').click(function(e) {
ws.trovaSostituisci();
});
$('.findReplace_box_close').click(function(e) {
ws.nascondiTrovaSostituisci();
});
ws.nascondiTrovaSostituisci = function() {
$('#findReplace_box').css("display", "none");
};
ws.regexRepl = function(trova, sostituisci, modificatori) {
if (modificatori === undefined) modificatori = 'g';
var regex = new RegExp(trova, modificatori);
var testo = $('[name=wpTextbox1]').val();
$('[name=wpTextbox1]').val(testo.replace(regex, sostituisci));
};
ws.trovaSostituisci = function() {
var trova = $('#findReplace_find').val();
var sostituisci = $('#findReplace_replace').val()
.replace(/\\n/g, '\n').replace(/\\t/g, '\t'); //abilita \n e \t come caratteri speciali newline e tab
var commento=$('#findReplace_doc').val();
var isRegex = $('#findReplace_regex').is(':checked');
var isMaiusc = $('#findReplace_maiusc').is(':checked');
var isMultiriga = $('#findReplace_multiriga').is(':checked');
var isRicorda = $('#findReplace_ricorda').is(':checked');
var regexParams = 'g';
if (!isRegex) {
//escape dei caratteri speciali delle regex
trova = trova.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
if (isMaiusc) {
regexParams += 'i';
}
if (isMultiriga) {
regexParams += 'm';
}
//applica la sostituzione nella pagina corrente
regex = new RegExp(trova, regexParams);
/* testo = $('[name=wpTextbox1]').val();
$('[name=wpTextbox1]').val(testo.replace(regex, sostituisci)); */
// attivazione su tutti i tre campi se in nsPagina
if (mw.config.get("wgCanonicalNamespace")==="Page") {
for (i=0;i<3;i+=1) {
ws.scriviBox(ws.leggiBox(i).replace(regex,sostituisci),i);
}
} else {
ws.scriviBox(ws.leggiBox().replace(regex,sostituisci));
}
// Temporanea disabilitazione
//updatePreview();
//se l'utente ha spuntato "Ricorda", salva in localStorage
if (isRicorda) {
// se localStorage.memoRegex esiste lo carico in ws.memoRegex
if (localStorage.memoRegex!==undefined) ws.memoRegex=JSON.parse(localStorage.memoRegex);
if (ws.memoRegex===undefined) ws.memoRegex={};
commento=commento.replace("(regex)","");
if (isRegex) {
commento+="(regex)";
}
// aggiorno localStorage["regex"]
ws.memoRegex[trova]=[commento,sostituisci,regexParams]; console.log("Passato per riga 549");
localStorage.memoRegex=JSON.stringify(ws.memoRegex);
localStorage.memoRegexEdited=true;
}
};
ws.leggiBox=function (area) {
if (area === undefined) {
if (mw.config.get('wgCanonicalNamespace') == "Page" || $("#editBox").length===1) area = 1;
else area = 0;
}
return $('textarea')[area] === undefined ? '' : $('textarea')[area].value;
};
ws.scriviBox=function (testo, area, ss, se) {
if (area === undefined || area === "") {
if (mw.config.get('wgCanonicalNamespace') == "Page" || $("#editBox").length===1) {
area = 1;
} else {
area = 0;
}
}
$('textarea')[area].value = testo;
// console.log("area:", area);
if (ss !== undefined && se !== undefined) {
$('textarea')[area].selectionStart = ss;
$('textarea')[area].selectionEnd = se;
}
};
/* FI */
/* inserimento template FI standard */
if ( typeof $ != 'undefined' && typeof $.fn.wikiEditor != 'undefined' && mw.config.get("wgCanonicalNamespace")==="Page") {$( function() {
var nomeBase, numeroPagina, nomeImmagine, fi;
nomeBase=mw.config.get("wgTitle").match(/(.+)\./)[1].replace("Page:","");
numeroPagina=mw.config.get("wgTitle").match(/\/(\d+)$/)[1];
nomeImmagine=nomeBase+" (page #1 crop).jpg".replace("#1",numeroPagina);
fi="{{FI\n|file = #1\n| width = 400px\n| float = floating-center\n| caption = \n}}".replace("#1",nomeImmagine);
// console.log(nomeImmagine);
$( '#wpTextbox1' ).wikiEditor( 'addToToolbar', {
'section': 'advanced',
'group': 'insert',
'tools': {'FI': {
label: 'Inserisci template FI',
type: 'button',
icon: '//upload.wikimedia.org/wikipedia/commons/6/68/Pulsante_img.png',
action: {type: 'callback',
execute: function() {
/* nomeBase=mw.config.get("wgTitle").match(/(.+)\./)[1];
numeroPagina=mw.config.get("wgTitle").match(/\/(\d+)$/)[1];
nomeImmagine=nomeBase+" (page #1 crop).jpg".replace("#1",numeroPagina);*/
fi="{{FI\n|file = #1\n| width = 400px\n| float = floating-center\n| caption = \n}}".replace("#1",nomeImmagine);
// console.log("Nuova versione gadget FI");
//mw.toolbar.insertTags(fi,"");
$(mw.activeElement).textSelection( 'encapsulateSelection', { pre: fi, post: '' } );
}
}
}
}});});}
// routine per newRi
ws.newRi=function() {
var currentHeader=ws.leggiBox("0");
// se manca un Rh oppure esiste ma è vuoto
if (/{{ri/i.test(currentHeader)===false || currentHeader.indexOf("{{Rh|||}}")!==-1) {
var header=ws.find_stringa(testo2PagPrec[0],"/>","</noinclude>",0);
header=ws.newAutoRi(header);
// se header contiene Rh, rulla
if (header.indexOf("{{Rh")!==-1) ws.scriviBox(header,"0");
}
};
ws.newAutoRi=function(header) {
function incrementa(t){
var pagina=/(\d+)/.exec(t)[1];
var pnew=(pagina*1+2)+"";
return t.replace(pagina,pnew);
}
// normalizzazione Rh
header=header.replace("{{rh|","{{Rh|");
var oldRi=ws.find_stringa(header,"{{Rh|","}}",1,"{{");
if (oldRi==="") return header;
var parsedRi=ws.parseTemplate("Rh",oldRi);
// analisi
var valido=[];
var pagina="";
for (i=1;i<4;i+=1) {
if (/^\d+$/.test(parsedRi[0][i]) || /— \d+ —/.test(parsedRi[0][i]) || /\|\d+}/.test(parsedRi[0][i])) valido.push(i);
}
// console.log(valido,parsedRi);
switch (valido.length) {
case 0:
break;
case 1:
// pagina=/(\d+)/.exec(parsedRi[0][valido[0]])[1];
parsedRi[0][valido[0]]=incrementa(parsedRi[0][valido[0]]);
break;
default:
break;
}
return header.replace(oldRi,ws.rewriteTemplate(parsedRi));
};
ws.parseTemplate=function(template, testo) {
function cod(testo) {
var l = ws.produciLista(testo, "{"+"{", "}}", 1, "{{");
for (var i = 0; i < l.length; i += 1) {
testo = testo.replace(l[i], l[i].replace(/\|/g, "__!__").replace(/=/g, "__eq__"));
}
l = ws.produciLista(testo, "[[", "]]", 1, "[[");
for (i = 0; i < l.length; i += 1) {
testo = testo.replace(l[i], l[i].replace(/\|/g, "__!__"));
}
return testo;
}
function decod(testo) {
testo = testo.replace(/__!__/g, "|").replace(/__eq__/g, "=");
return testo;
}
if (testo === undefined) testo = ws.leggiBox();
var cap=template.substring(0,1).toLocaleUpperCase()+template.substring(1);
testo=testo.replace("{{"+cap,"{{"+template);
var t = ws.find_stringa(testo, "{"+"{" + template, "}}", 1, "{{");
var l = []; // lista delle keys
t = "0=" + t.substring(2, t.length - 2); // nome del template in parametro "0"
l.push["0"];
var ts = {};
var n = 1;
t = cod(t);
t = t.split("|");
// element for element
for (i = 0; i < t.length; i += 1) {
// case param is positional
if (t[i].indexOf("=") == -1) {
t[i] = n + "=" + t[i];
n = n + 1;
}
var els = [];
els[0] = t[i].substring(0, t[i].indexOf("=")).trim();
els[1] = t[i].substring(t[i].indexOf("=") + 1).trim();
if (els[1][els[1].length - 1] == "\n") els[1] = els[1].substring(0, els[1].length - 1);
ts[els[0]] = decod(els[1]);
l.push(els[0]);
}
return [ts, l];
};
ws.rewriteTemplate=function(x,mini) {
if (mini===undefined) mini=true;
var testo = "";
if (mini) {
$.each(x[1], function (indice, valore) {
if ((/^\d+$/).test(valore))
testo += "|" + x[0][valore];
else
testo += "|" + valore + "=" + x[0][valore];
});
testo = "{" + "{" + testo.substring(1) + "}}";
} else {
$.each(x[1], function (indice, valore) {
if (valore != "0") testo += " | " + valore + " = " + x[0][valore] + "\n";
});
testo = "{{" + x[0]["0"] + "\n" + testo + "}}\n";
testo = testo.replace(/\n\s\|\s\d*\s=\s/g, "\n | ");
}
return testo;
}
/* attivazione shortcuts e buttons */
// shortcut.add("Ctrl+i", function () {$(mw.activeElement).textSelection( 'encapsulateSelection', { pre:"''", post: "''" } );});
shortcut.add("Ctrl+i", function () {$(mw.activeElement).textSelection( 'encapsulateSelection', { pre:"''", post: "''" } );});
shortcut.add("Ctrl+b", function () {$(mw.activeElement).textSelection( 'encapsulateSelection', { pre:"'''", post: "'''" } );});
shortcut.add("Ctrl+Shift+s", function () {$(mw.activeElement).textSelection( 'encapsulateSelection', { pre:"{{Sc|", post: "}}" } );});
shortcut.add("Ctrl+Shift+c", function () {$(mw.activeElement).textSelection( 'encapsulateSelection', { pre:"{{C|class=|", post: "}}" } );});
shortcut.add("Ctrl+Alt+n", function() {
var t = ws.selection();
if (t[1].length < 5) {
t[1] = "<sup>nota</sup>";
} else {
t[1] = "<ref>" + t[1] + "</ref>";
}
ws.scriviSelAlt(t);
});
shortcut.add("Ctrl+Alt+g", function () {$(mw.activeElement).textSelection( 'encapsulateSelection', { pre:"{{Greek|", post: "|?}}" } );});
shortcut.add("Ctrl+Shift+f", ws.mostraTrovaSostituisci);
ws.newButton("Fr","ws.mostraTrovaSostituisci","es","carica Find & Replace");
ws.alt7=function() {ws.memoRegexRun(); if (ws.leggiBox(0).indexOf("{{Rh")===-1) ws.newRi();};
ws.newButton("Alt 7","ws.alt7","es","postOcr");
shortcut.add("Ctrl+Shift+7", ws.alt7);
shortcut.add("Ctrl+Shift+1",function () {$(".quality1 input").click(); $("#wpSave").click(); return false;});
shortcut.add("Ctrl+Shift+3",function () {$(".quality3 input").click(); $("#wpSave").click(); return false;});
shortcut.add("Ctrl+Shift+0",function () {$(".quality0 input").click(); $("#wpSave").click(); return false;});
ws.alt8=function() {
// eliminazione acapo che esclude sia i testi <poem> che le righe che iniziano con ";:#*" (liste html)
var editbox = document.getElementsByName('wpTextbox1')[0];
var poemNumber=0;
var listaGlobale=[];
// fase 1: codifica
if (editbox.value.indexOf("<poem") != -1) {
lista = ws.produciLista(editbox.value, "<poem", "</poem>", 1);
listaGlobale=[].concat(lista);
poemNumber=lista.length;
for (i = 0; i <= lista.length - 1; i = i + 1) {
marcatore = "###" + i + "###";
editbox.value = editbox.value.replace(lista[i], marcatore);
}
}
editbox.value=editbox.value.replace("{{Poem", "{{poem").replace("{{Mlb", "{{mlb");
if (editbox.value.indexOf("{{poem") != -1) {
lista = produciLista(editbox.value, "{" + "{poem", "}}", 1,"{{");
listaGlobale=listaGlobale.concat(lista);
for (i = 0; i <= lista.length - 1; i = i + 1) {
marcatore = "###" + (i+poemNumber) + "###";
editbox.value = editbox.value.replace(lista[i], marcatore);
}
}
if (editbox.value.indexOf("{{mlb") != -1) {
lista = ws.produciLista(editbox.value, "{" + "{mlb", "}}", 1,"{{");
listaGlobale=listaGlobale.concat(lista);
for (i = 0; i <= lista.length - 1; i = i + 1) {
marcatore = "###" + (i+poemNumber) + "###";
editbox.value = editbox.value.replace(lista[i], marcatore);
}
}
// fase2: eliminazione acapo singoli, con conservazione dei multipli
//if (mw.config.get("wgTitle").indexOf("Trattato di archeologia (Gentile).djvu")==-1) {
editbox.value = editbox.value.replace(/([^>}\n])\n([^<\n\:\;\*\#\|\{])/g, '$1 $2'); //linux
editbox.value = editbox.value.replace(/([^>}\r\n])\r\n([^<\r\n\:\;\*\#\|\{])/g, '$1 $2'); //windows
// }
// eliminazione sequenze di spazi, sostituiti da spazio singolo
editbox.value = editbox.value.replace(/ +/g, ' ');
// sostituzione spazio dopo marcatore
editbox.value=editbox.value.replace(/### /g,"###\n");
// fase 3: decodifica
if (editbox.value.indexOf("###0###") != -1) {
for (i = 0; i <= listaGlobale.length - 1; i = i + 1) {
marcatore = "###" + i + "###";
editbox.value = editbox.value.replace(marcatore, listaGlobale[i]);
}
}
// fase 4: sistemazione a capo attorno a poem
//editbox.value=editbox.value.replace(/ <poem>/g,"\n<poem>").replace(/<\/poem> /g,"</poem>\n");
editbox.value=editbox.value.replace(/### /g,"###\n");
//updatePreview();
};
ws.newButton("Alt 8","ws.alt8","es","riunisci testo paragrafi");
shortcut.add("Ctrl+Shift+8", ws.alt8);
/*shortcut.add("Ctrl+Alt+8",function() {
// eliminazione acapo che esclude sia i testi <poem> che le righe che iniziano con ";:#*" (liste html)
var editbox = document.getElementsByName('wpTextbox1')[0];
var poemNumber=0;
var listaGlobale=[];
// fase 1: codifica
if (editbox.value.indexOf("<poem") != -1) {
lista = ws.produciLista(editbox.value, "<poem", "</poem>", 1);
listaGlobale=[].concat(lista);
poemNumber=lista.length;
for (i = 0; i <= lista.length - 1; i = i + 1) {
marcatore = "###" + i + "###";
editbox.value = editbox.value.replace(lista[i], marcatore);
}
}
editbox.value=editbox.value.replace("{{Poem", "{{poem").replace("{{Mlb", "{{mlb");
if (editbox.value.indexOf("{{poem") != -1) {
lista = produciLista(editbox.value, "{" + "{poem", "}}", 1,"{{");
listaGlobale=listaGlobale.concat(lista);
for (i = 0; i <= lista.length - 1; i = i + 1) {
marcatore = "###" + (i+poemNumber) + "###";
editbox.value = editbox.value.replace(lista[i], marcatore);
}
}
if (editbox.value.indexOf("{{mlb") != -1) {
lista = ws.produciLista(editbox.value, "{" + "{mlb", "}}", 1,"{{");
listaGlobale=listaGlobale.concat(lista);
for (i = 0; i <= lista.length - 1; i = i + 1) {
marcatore = "###" + (i+poemNumber) + "###";
editbox.value = editbox.value.replace(lista[i], marcatore);
}
}
// fase2: eliminazione acapo singoli, con conservazione dei multipli
//if (mw.config.get("wgTitle").indexOf("Trattato di archeologia (Gentile).djvu")==-1) {
editbox.value = editbox.value.replace(/([^>}\n])\n([^<\n\:\;\*\#\|\{])/g, '$1 $2'); //linux
editbox.value = editbox.value.replace(/([^>}\r\n])\r\n([^<\r\n\:\;\*\#\|\{])/g, '$1 $2'); //windows
// }
// eliminazione sequenze di spazi, sostituiti da spazio singolo
editbox.value = editbox.value.replace(/ +/g, ' ');
// sostituzione spazio dopo marcatore
editbox.value=editbox.value.replace(/### /g,"###\n");
// fase 3: decodifica
if (editbox.value.indexOf("###0###") != -1) {
for (i = 0; i <= listaGlobale.length - 1; i = i + 1) {
marcatore = "###" + i + "###";
editbox.value = editbox.value.replace(marcatore, listaGlobale[i]);
}
}
// fase 4: sistemazione a capo attorno a poem
//editbox.value=editbox.value.replace(/ <poem>/g,"\n<poem>").replace(/<\/poem> /g,"</poem>\n");
editbox.value=editbox.value.replace(/### /g,"###\n");
//updatePreview();
});*/
ws.alt6=function() {textbox = document.getElementsByName('wpTextbox1')[0];
testo = textbox.value;
poems = ws.produciLista(testo, "<poem", "</poem>", 1);
for (i = 0; i < poems.length; i += 1) {
testo = testo.replace(poems[i], "[#" + i + "#]");
}
testo = testo.replace(/ \n/g, "\n").replace(/([\.\?\!]\n)([^\n])/g, '$1\n$2');
for (i = 0; i < poems.length; i += 1) {
testo = testo.replace("[#" + i + "#]", poems[i]);
}
textbox.value = testo;
//updatePreview();
};
ws.newButton("Alt 6","ws.alt6","es","Separa paragrafi");
shortcut.add("Ctrl+Shift+6", ws.alt6);
/*shortcut.add("Ctrl+Alt+6",function() {
textbox = document.getElementsByName('wpTextbox1')[0];
testo = textbox.value;
poems = ws.produciLista(testo, "<poem>", "</poem>", 1);
for (i = 0; i < poems.length; i += 1) {
testo = testo.replace(poems[i], "[#" + i + "#]");
}
testo = testo.replace(/ \n/g, "\n").replace(/([\.\?\!]\n)([^\n])/g, '$1\n$2');
for (i = 0; i < poems.length; i += 1) {
testo = testo.replace("[#" + i + "#]", poems[i]);
}
textbox.value = testo;
//updatePreview();
});*/
// rimuovi prima riga della pagina
ws.alt5=function() {
var editbox = document.getElementsByName('wpTextbox1')[0];
if (editbox.value.substring(0, 6) == "<poem>") {
editbox.value = editbox.value.replace(/<poem\>.+\n/, "<poem>");
} else {
editbox.value = editbox.value.replace(/.+\n+/, "");
}
};
ws.newButton("Alt 5","ws.alt5","es","Elimina prima riga");
shortcut.add("Ctrl+Shift+5", ws.alt5);
/*shortcut.add("Ctrl+Alt+5",function() {
var editbox = document.getElementsByName('wpTextbox1')[0];
if (editbox.value.substring(0, 6) == "<poem>") {
editbox.value = editbox.value.replace(/<poem\>.+\n/, "<poem>");
} else {
editbox.value = editbox.value.replace(/.+\n+/, "");
}
});*/
// toggle maiuscole-minuscole nella selezione
ws.up_low=function(){
var t=ws.selection();
if(t[1]===t[1].toLocaleUpperCase()) t[1]=t[1].toLocaleLowerCase();else t[1]=t[1].toLocaleUpperCase();
ws.scriviSel(t);};
ws.newButton("A↔a", "ws.up_low()", "es","Applica maiuscolo/minuscolo alla selezione, alternandole");
// Nascondi-visualizza pannello sinistro
ws.full_page=function(){
$("#mw-panel").toggle();
if ($("#content").css("margin-left")=="0px")
$("#content").css("margin-left", "176px");
else
$("#content").css("margin-left", "0");
};
ws.newButton("n↓↑","ws.toggleNote","es","Sposta le note");
ws.newButton("fp", "ws.full_page", "es","Nascondi-visualizza pannello sinistro");
ws.shortcut=shortcut;
importScript("User:Alex_brollo/PersonalButtons.js");