Utente:Salvatore Ingala/commandline.js

Da Wikipedia, l'enciclopedia libera.
Vai alla navigazione Vai alla ricerca

Questa pagina definisce alcuni parametri di aspetto e comportamento generale di tutte le pagine. Per personalizzarli vedi Aiuto:Stile utente.


Nota: dopo aver salvato è necessario pulire la cache del proprio browser per vedere i cambiamenti (per le pagine globali è comunque necessario attendere qualche minuto). Per Mozilla / Firefox / Safari: fare clic su Ricarica tenendo premuto il tasto delle maiuscole, oppure premere Ctrl-F5 o Ctrl-R (Command-R su Mac); per Chrome: premere Ctrl-Shift-R (Command-Shift-R su un Mac); per Konqueror: premere il pulsante Ricarica o il tasto F5; per Opera può essere necessario svuotare completamente la cache dal menù Strumenti → Preferenze; per Internet Explorer: mantenere premuto il tasto Ctrl mentre si preme il pulsante Aggiorna o premere Ctrl-F5.

/* <pre><nowiki> */

/**** Command Line Start ****/

/*
Commandline versione 2.3
Scritto da [[Utente:Salvatore Ingala]]; e alcuni spezzoni di codice di Timendum e Jalo.

Rilasciato ai sensi delle licenze GFDL e GPL.
*/
if (typeof (arrayArgument) == 'undefined') { //non sovrascriviamo se è già stato definito
	arrayArgument = new Array(" ", "aeronautica", "Africa", "agricoltura", "album musicali", "allevamento", "alpinismo", "animali", "anime e manga", "antropologia", "antroponimi", "apicoltura", "archeologia", "architettura", "arte", "arti divinatorie", "arti marziali", "associazioni", "astronomia", "atletica", "automobilismo", "aziende", "baseball", "Bisanzio", "biografie", "biologia", "blues", "botanica", "buddhismo", "calcio (sport)", "canottaggio", "cattolicesimo", "chimica", "ciclismo", "cinema", "classica", "cristianesimo",
		"cucina", "curling", "danza", "diritto", "ebraismo", "ecologia", "economia", "editoria", "educazione", "Europa", "F1", "fantascienza", "film", "filosofia", "fisica", "font", "fotografia", "fumetti", "funghi", "GDR", "genetica", "geografia", "Giappone", "giochi", "golf", "guerra", "Guerre Stellari", "Harry Potter", "hockey", "informatica", "ingegneria", "hip hop", "jazz",
		"letteratura", "LGBT", "lingue", "linguistica", "mare", "matematica", "meccanica", "medicina", "metal", "mineralogia", "mitologia", "mitologia greca", "mitologia romana", "mitologia azteca", "mitologia cinese", "mitologia egizia", "mitologia inca", "mitologia maya", "mitologia mesopotamica", "mitologia norrena", "mitologia slava", "mitologia ugro-finnica", "motociclismo", "musei", "musica", "musica elettronica", "nautica", "neopaganesimo", "numismatica", "nuoto", "paleontologia", "pallacanestro", "pallamano", "pallanuoto", "pallavolo", "pattinaggio", "pesca sportiva", "piante", "politica", "Pokémon", "psicologia", "pugilato", "punk", "radio", "religione", "rock", "rugby", "santi", "scacchi", "scienza", "scherma", "sci", "sicurezza",
		"skeleton", "sociologia", "software libero", "solidarietà", "sport", "sport invernali", "stadi", "Star Trek", "storia", "subacquea", "Taoismo", "teatro", "tecnologia", "telecomunicazioni", "televisione", "tennis", "tiro con l'arco", "Tolkien", "trasporti", "turismo", "vela", "videogiochi", "vini", "voci comuni", "Walt Disney", "wrestling", "zoologia");
}


arrayLingue = new Array("bulgara", "catalana", "cinese", "danese", "esperanto", "finlandese", "francese", "giapponese", "greca", "inglese",
	"islandese", "italiana", "latina", "lettone", "maltese", "moldava", "norvegese", "olandese", "polacca", "portoghese", "rumena",
	"russa", "slovena", "spagnola", "svedese", "tedesca", "ucraina", "ungherese");


//IMPOSTAZIONI PREDEFINITE

if (typeof (cmdHotKey) == 'undefined') cmdHotKey = 'z';
if (typeof (cmdQuickHotKey) == 'undefined') cmdQuickHotKey = 'x';

if (typeof (cmdCookieExpiration) == 'undefined') cmdCookieExpiration = 20;


if (typeof (fixformat_list) == 'undefined') {
	//nessuna sostituzione impostata, usa quelle standard
	fixformat_list = new Array(
		[/[’`]/g, "'"],
		[/[“”]/g, '"'],
		[/,,/g, ','],
		[/([a-zA-Z]{3,})a' /g, "$1à "],
		[/([^pc])o' /g, "$1ò "],
		[/u' /g, "ù "],
		[/i' /g, "ì "],
		[/ dò/g, " do"],
		[/\bE'(\s)/g, "È$1"],
		[/^E' /gm, "È "],
		[/ É /g, " È "],
		[/^É /gm, "È "],
		[/ e' /g, " è "],
		[/ é /g, " è "],
		[/ fà /g, " fa "],
		[/ fù /g, " fu "],
		[/ nè /g, " né "],
		[/ ne' /g, " né "],
		[/\b([Aa])nzich(è|e')/g, "$1nziché"],
		[/\b([Aa])ffinch(è|e')/g, "$1ffinché"],
		[/\b([Bb])ench(è|e')/g, "$1enché"],
		[/\b([Cc])ioé/g, "$1ioè"],
		[/\b([Nn])onch(è|e')/g, "$1onché"],
		[/\b([Pp])erch(è|e')/g, "$1erché"],
		[/\b([Pp])er(ó|o') /g, '$1erò '],
		[/\b([Pp])iu' /g, "$1iù "],
		[/\b([Pp])ò/g, "$1o'"],
		[/\b([Pp])oich(è|e') /g, "$1oiché "],
		[/\b([Pp])ropio\b/g, "$1roprio"],
		[/\b([Pp])u(o'|o) /g, '$1uò '],
		[/\b([Qq])uì /g, "$1ui "],
		[/\b([Qq])uà /g, "$1ua "],
		[/\b([Qq])ual'è/g, "$1ual è"],
		[/ sà /g, " sa "],
		[/ sè /g, " sé "],
		[/si' /g, "sì"],
		[/ sò /g, " so "],
		[/ sù /g, " su "],
		[/ tr(è|e'|é) /g, " tre "],
		[/\b([Ss])ucessivo\b/g, "$1uccessivo"],
		[/\[\[[Cc]ategory:/g, "[[Categoria:"],
		[/\[\[[Ii]mage:/g, "[[Immagine:"],
		[/&lt;/g, '<'],
		[/&gt;/g, '>'],
		[/&amp;/g, '&'],
		[/&quot;/g, '"'],
		[/&agrave;/g, 'à'],
		[/&egrave;/g, 'è'],
		[/&eacute;/g, 'é'],
		[/&igrave;/g, 'ì'],
		[/&iexcl;/g, '¡'],
		[/&cent;/g, '¢'],
		[/&pound;/g, '£'],
		[/&yen;/g, '¥'],
		[/&acute;/g, "'"],
		[/&plusmn;/g, '±'],
		[/&times;/g, '×'],
		[/&divide;/g, '÷'],
		[/&micro;/g, 'µ'],
		[/&deg;/g, '°'],
		[/&frac14;/g, '¼'],
		[/&frac12;/g, '½'],
		[/&frac34;/g, '¾'],
		[/&sup1;/g, '¹'],
		[/&sup2;/g, '²'],
		[/&sup3;/g, '³'],
		[/&sect;/g, '§'],
		[/<br>\n\n/g, '\n\n'],
		[/<br[\/]?>/gi, '<br />']
	);
}

if (typeof (fixformat_subject) == 'undefined') fixformat_subject = 'correzioni automatiche; ';

//FINE IMPOSTAZIONI PREDEFINITE

// Funzioni di utilità generale

//Codice preso inizialmente da http://en.wikipedia.org/wiki/User:Cacycle/wikEd.js
function cmdGetCookie(name) {
	var cookie = ' ' + document.cookie;
	var search = ' ' + name + '=';
	var setStr = '';
	var offset = 0;
	var end = 0;
	offset = cookie.indexOf(search);
	if (offset != -1) {
		offset += search.length;
		end = cookie.indexOf(';', offset)
		if (end == -1)
			end = cookie.length;
		setStr = cookie.substring(offset, end);
		setStr = setStr.replace(/\\+/g, ' ');
		setStr = decodeURIComponent(setStr);
	}
	return (setStr);
}

//Codice preso inizialmente da http://en.wikipedia.org/wiki/User:Cacycle/wikEd.js
function cmdSetCookie(name, value, expires, path, domain, secure) {
	var cookie = name + '=' + encodeURIComponent(value);
	if (expires != null) {
		var date = new Date();
		date.setTime(date.getTime() + expires * 1000);
		cookie += "; expires=" + date.toGMTString();
	}
	if (path != null)
		cookie += '; path=' + path;
	else
		cookie += "; path=/";
	if (domain != null)
		cookie += '; domain=' + domain;
	if (secure != null)
		cookie += '; secure';
	document.cookie = cookie;
}

function cmdDeleteCookie(name) {
	document.cookie = (name + "=0; expires=Fri, 27 Jul 2001 10:10:10 UTC; path=/");
}

/* Fine Funzioni gestione cookie */

// recupera un parametro dall'URL
function cmdGetParam(name, h) {
	if (h == null) h = window.location.href;
	var qmarkpos = h.indexOf('?');
	if (qmarkpos == -1) return '';
	var a = h.substring(qmarkpos + 1).split('&');
	for (var i = 0; i < a.length; i++) {
		var eq = a[i].indexOf('=');
		if (eq == -1) continue;
		if (a[i].substring(0, eq) == name) return a[i].substring(eq + 1);
	}
	return '';
}

//mette in maiuscolo il primo carattere di str
function cmdUpFirst(str) {
	if (str)
		return str.substring(0, 1).toUpperCase() + str.substring(1);
	else
		return str;
}

//Funzioni di Timendum
//Segna "modifica minore"
function TimenME() {
	document.getElementById("wpMinoredit").checked = 1;
}
//Aggiungi all'oggetto (ma evita i duplicati)
function TimenSA(text) {
	var summ = document.getElementById("wpSummary");
	if (summ == null) return;
	var t = summ.value;
	if (t.indexOf(text) == -1) {
		t = t.replace(/\s+$/, ""); //rimuovi whitespaces

		if (t.length > 0)
			t += t.charAt(t.length - 1) == ";" ? " " : "; ";

		t += text;
		summ.value = t;
	}
}

//Aggiungi testo prima
function TimenPr(text) {
	cmdWEUpdateTextarea();
	var wpTextbox1 = document.getElementById("wpTextbox1");
	wpTextbox1.value = text + wpTextbox1.value;
	cmdWEUpdateFrame();
}

//Aggiungi testo dopo
function TimenDp(text) {
	cmdWEUpdateTextarea();
	var wpTextbox1 = document.getElementById("wpTextbox1");
	wpTextbox1.value += text;
	cmdWEUpdateFrame();
}

function cmdGiorno() {
	var today = new Date();
	return today.getDate();
}

function cmdMese() {
	var today = new Date();
	return (new Array("gennaio", "febbraio", "marzo", "aprile", "maggio", "giugno", "luglio", "agosto",
		"settembre", "ottobre", "novembre", "dicembre"))[today.getMonth()];
}

function cmdAnno() {
	var today = new Date();
	return today.getFullYear();
}

//Prova a completare string usando dict come  dizionario.
//Restituisce -1 se c'è ambiguità, 0 se non trova nessuna corrispondenza, o la stringa completa se trova una sola occorrenza
//Versione per dizionario di tipo object
function cmdAutoComplete1(dict, string, failIfAmbiguous) {
	var found = ''
	if ((string == "") || (string == null)) return string;
	for (var x in dict)
		if (x.indexOf(string) == 0) {
			if (!failIfAmbiguous)
				return x;
			if (found == '')
				found = x;
			else
				return -1;
		}
	if (found != '') return found;
	return 0;
}

//Versione per dizionario di tipo array
function cmdAutoComplete2(dict, string, failIfAmbiguous) {
	var found = ''
	var i;
	if ((string == "") || (string == null)) return "";
	for (i = 0; i < dict.length; i++)
		if (dict[i].indexOf(string) == 0) {
			if (!failIfAmbiguous)
				return dict[i];
			if (found == '')
				found = dict[i];
			else
				return -1;
		}
	if (found != '')
		return found;
	return 0;
}


//Prova ad auto-completare l'argomento usando arrayArgument[] come dizionario;
//In caso di fallimento restituisce arg
function cmdAutoCompleteArgument(arg) {
	var completed = cmdAutoComplete2(arrayArgument, arg, false);
	if ((completed == -1) || (completed == 0))
		return arg;
	else
		return completed;
}

//Comandi
//cmd['nome comando'] = [funzione, 'commento'];
if (typeof cmd == 'undefined') cmd = new Object();
cmd['a'] = [cmd_a, 'Da aiutare; richiede motivo e argomento'];
cmd['c'] = [cmd_c, 'Da aiutare; richiede motivo e argomento'];
cmd['e'] = [cmd_e, 'Avviso enciclopedicità dubbia; richiede motivo e argomento'];
cmd['p'] = [cmd_p, 'Avviso nNPOV; richiede motivo e argomento'];
cmd['w'] = [cmd_w, 'Da wikificare; richiede argomento'];
cmd['s'] = [cmd_s, 'Stub; richiede argomento (opzionale)'];
cmd['t'] = [cmd_t, 'Da tradurre; richiede lingua e argomento'];
cmd['o'] = [cmd_o, 'Pagina orfana; richiede argomento (opzionale)'];
cmd['categorizzare'] = [cmd_categorizzare, 'Da categorizzare'];
cmd['unire'] = [cmd_unire, 'Da unire; richiede la voce simile'];
cmd['purge'] = [cmd_purge, 'Aggiorna la cache'];
cmd['fixformat'] = [cmd_fixformat, 'Sostituzioni automatiche'];
cmd['replace'] = [cmd_replace, 'Cerca e sostituisci'];
cmd['benvenuto'] = [cmd_benvenuto, 'Messaggio di benvenuto'];

cmd['save'] = [cmd_save, 'Simula la pressione del tasto di salvataggio'];
cmd['preview'] = [cmd_preview, 'Simula la pressione del tasto "Visualizza anteprima"'];
cmd['diff'] = [cmd_diff, 'Simula la pressione del tasto "Mostra cambiamenti"'];

cmd['goto'] = [cmd_goto, 'Va ad un\'altra pagina di wiki; richiede destinazione ed action'];
cmd['eval'] = [cmd_eval, 'Esegue del codice javascript'];
cmd['evalvar'] = [cmd_evalvar, 'Esegue del codice javascript e assegna il risultato ad una variabile. Richiede variabile e codice da eseguire.'];
cmd['setvar'] = [cmd_setvar, 'Imposta il valore di una variabile'];
cmd['process'] = [cmd_process, 'Processa la parte restante di commandline'];
cmd['processn'] = [cmd_processn, 'Processa i successivi n blocchi. Richiede n'];
cmd['insertbefore'] = [cmd_insertbefore, 'Inserisce del testo all\'inizio; richiede il testo da inserire'];
cmd['insertafter'] = [cmd_insertafter, 'Inserisce del testo alla fine; richiede il testo da inserire'];
cmd['setsummary'] = [cmd_setsummary, 'Imposta il campo oggetto della modifica; richiede il testo'];
cmd['setminor'] = [cmd_setminor, 'Selezione o deseleziona la checkbox "modifica minore"; richiede 0 o 1'];
cmd['prompt'] = [cmd_prompt, 'Imposta una variabile richiedendo input di tipo stringa all\'utente'];
cmd['alert'] = [cmd_alert, 'Mostra un messaggio'];
cmd['skip'] = [cmd_skip, 'Salta i successivi n blocchi; richiede n'];
cmd['label'] = [cmd_label, 'Indica una label nel codice. Prende un argomento e non fa nulla'];
cmd['jump'] = [cmd_jump, 'Salta ad una label'];
cmd['stop'] = [cmd_stop, 'Interrompe definitivamente l\'esecuzione dello script'];
cmd['ifvoidpage'] = [cmd_ifvoidpage, 'Se la casella di editing è vuota, passa al blocco successivo, altrimenti salta 2 blocchi'];
cmd['iftrue'] = [cmd_iftrue, 'Valuta un\'espressione fra due valori, salta 2 blocchi se è falsa'];
cmd['nop'] = [cmd_nop, 'No Operation'];
cmd['add'] = [cmd_add, 'Somma; richiede la variabile di destinazione e il numero o il nome della variabile da sommare'];
cmd['sub'] = [cmd_sub, 'Sottrazione; richiede la variabile di destinazione e il numero o il nome della variabile da sottrarre'];
cmd['mul'] = [cmd_mul, 'Moltiplicazione; richiede la variabile di destinazione e il numero o il nome della variabile per cui moltiplicare'];
cmd['div'] = [cmd_div, 'Divisione intera; richiede la variabile di destinazione e il valore/nome del divisore'];
cmd['mod'] = [cmd_mod, 'Resto della divisione intera; richiede la variabile di destinazione e il valore/nome del divisore'];

cmd['sleep'] = [cmd_sleep, 'Interrompe l\'esecuzione dello script per un intervallo di tempo; richiede la durata in millisecondi'];

cmd['grep'] = [cmd_grep, 'Lascia solo le righe che soddisfano una certa RegExp'];
cmd['uniq'] = [cmd_uniq, 'Lascia solo la prima fra le righe che matchano allo stesso modo una certa RegExp'];

cmd['runscript'] = [cmd_runscript, 'Esegue uno script'];

cmd['unsafe'] = [cmd_unsafe, 'Richiede all\'utente di passare alla modalità unsafe.'];

cmdIsSafe = new Object();
cmdIsSafe['a'] = true;
cmdIsSafe['c'] = true;
cmdIsSafe['e'] = true;
cmdIsSafe['p'] = true;
cmdIsSafe['w'] = true;
cmdIsSafe['s'] = true;
cmdIsSafe['t'] = true;
cmdIsSafe['o'] = true;
cmdIsSafe['categorizzare'] = true;
cmdIsSafe['unire'] = true;
cmdIsSafe['purge'] = true;
cmdIsSafe['fixformat'] = true;
cmdIsSafe['replace'] = true;
cmdIsSafe['benvenuto'] = true;

cmdIsSafe['preview'] = true;
cmdIsSafe['diff'] = true;

cmdIsSafe['goto'] = true;
cmdIsSafe['setvar'] = true;
cmdIsSafe['process'] = true;
cmdIsSafe['processn'] = true;
cmdIsSafe['insertbefore'] = true;
cmdIsSafe['insertafter'] = true;
cmdIsSafe['setsummary'] = true;
cmdIsSafe['setminor'] = true;
cmdIsSafe['prompt'] = true;
cmdIsSafe['alert'] = true;
cmdIsSafe['skip'] = true;
cmdIsSafe['label'] = true;
cmdIsSafe['jump'] = true;
cmdIsSafe['stop'] = true;
cmdIsSafe['ifvoidpage'] = true;
cmdIsSafe['iftrue'] = true;
cmdIsSafe['nop'] = true;
cmdIsSafe['add'] = true;
cmdIsSafe['sub'] = true;
cmdIsSafe['mul'] = true;
cmdIsSafe['div'] = true;
cmdIsSafe['mod'] = true;

cmdIsSafe['sleep'] = true;

cmdIsSafe['grep'] = true;
cmdIsSafe['uniq'] = true;

cmdIsSafe['unsafe'] = true;


cmdScript = new Object();


//Preleva un argomento dalla commandline se possibile, altrimenti preleva tramite prompt()
function cmdGetArg(text) {
	if (cmdline_command_array[cmdline_next_argument] != null)
		return cmdPreprocessBlock(cmdline_command_array[cmdline_next_argument++]);
	else {
		var retval = prompt(text, "");
		if (retval == null)
			return "";
		else
			return retval;
	}
}

//Ritorna una stringa con i comandi ancora da eseguire
function cmdReencodeCmdLine() {
	if (typeof (cmdline_next_argument) == 'undefined') return "";
	var res = "";
	var cna = cmdline_next_argument;
	var command;
	while ((command = cmdline_command_array[cna++]) != null)
		res = res + "#" + command;
	return res == "" ? res : res.substring(1); //rimuoviamo il "#" di troppo
}

//Salva su cookie i comandi non ancora eseguiti e distrugge quella corrente
//Salva anche lo stato delle variabili di runtime, se ce ne sono
//L'esecuzione ripartirà solo alla pagina title (quella corrente se title non viene fornito)
function cmdSaveCmdLine(title) {
	if (typeof (title) == 'undefined') title = mw.config.get('wgPageName');

	var c = "";

	c += cmdSafeMode ? '!sm#' : '!um#';

	if (typeof (cmd_savevars) != 'undefined')
		for (x in cmd_savevars)
			c += "_rv#" + x + "#" + cmd_vars[x] + "#"; //rimane un # in più

	var t = cmdReencodeCmdLine(); //parte rimanente di commandline
	c += t;

	cmdline_command_array = new Array();
	if (t != "")
		for (var i = 0; i < 5; i++)
			if (cmdGetCookie("cmdAutoRunPage" + i) == '') {
				cmdSetCookie("cmdAutoRunPage" + i, title, cmdCookieExpiration);
				cmdSetCookie("cmdAutoRunCommand" + i, c, cmdCookieExpiration);
				break;
			}
}

function cmdEncodeCommandlineInFormAction() {
	var cl = cmdReencodeCmdLine();
	var f = document.getElementsByTagName('form')[0];
	if (f) {
		f.method = "POST";
		f.action += "&fakeaction=runcommand&command=" + encodeURIComponent(cl);
	}
}

function cmdIsEditing() {
	return document.getElementById("wpTextbox1") != null;
}

//Se la pagina non è aperta in modifica, salva la commandline (compreso l'ultimo comando) e apre la pagina in modifica.
function cmdEnsureEditing() {
	if (!cmdIsEditing()) {
		cmdline_next_argument--;
		cmdSaveCmdLine();
		location.href = mw.config.get('wgServer') + "/w/index.php?title=" + encodeURIComponent(mw.config.get('wgPageName')) + "&action=edit";
		return true;
	}
	return false;
}

//Template:A
function cmd_a() {
	if (cmdEnsureEditing()) return;
	TimenPr('{{A|motivo=' + (cmdGetArg("Motivo")) + '|argomento=' + (cmdAutoCompleteArgument(cmdGetArg("Argomento"), false)) + '|mese=' + cmdMese() + ' ' + cmdAnno() + '|firma=~~~~}}\n');
	TimenSA('+da aiutare; ');
	TimenME();
}
//Template:W
function cmd_w() {
	if (cmdEnsureEditing()) return;
	TimenPr('{{W|argomento=' + (cmdAutoCompleteArgument(cmdGetArg("Argomento"), false)) + '|mese=' + cmdMese() + ' ' + cmdAnno() + '|firma=~~~~}}\n');
	TimenSA('+wikificare; ');
	TimenME();
}
//Template:E
function cmd_e() {
	if (cmdEnsureEditing()) return;
	TimenPr('{{E|' + (cmdGetArg("Motivo")) + '|' + (cmdAutoCompleteArgument(cmdGetArg("Argomento"), false)) + '|' + cmdMese() + ' ' + cmdAnno() + '|~~~~}}\n');
	TimenSA('+avviso enciclopedicità dubbia; ');
	TimenME();
}
//Template:P
function cmd_p() {
	if (cmdEnsureEditing()) return;
	TimenPr('{{P|motivo=' + (cmdGetArg("Motivo")) + '|argomento=' + (cmdAutoCompleteArgument(cmdGetArg("Argomento"), false)) + '|mese=' + cmdMese() + ' ' + cmdAnno() + '|firma=~~~~}}\n');
	TimenSA('+avviso nNPOV; ');
	TimenME();
}
//Template:C
function cmd_c() {
	if (cmdEnsureEditing()) return;
	TimenPr('{{C|motivo=' + (cmdGetArg("Motivo")) + '|argomento=' + (cmdAutoCompleteArgument(cmdGetArg("Argomento"), false)) + '|mese=' + cmdMese() + ' ' + cmdAnno() + '|firma=~~~~}}\n');
	TimenSA('+da controllare; ');
	TimenME();
}
//Template {{S}}
function cmd_s() {
	if (cmdEnsureEditing()) return;

	var arg = cmdGetArg("Argomento");
	var pipepos = arg.indexOf("|");
	if (pipepos == -1)
		var argomento = cmdAutoCompleteArgument(arg, false);
	else
		var argomento = cmdAutoCompleteArgument(arg.substring(0, pipepos), false) + "|" + cmdAutoCompleteArgument(arg.substring(pipepos + 1), false);

	TimenPr('{{S' + (((argomento != null) && (argomento != '')) ? ('|' + argomento + '}}\n') : '}}\n'));
	TimenSA('+stub; ');
	TimenME();
}
//Template:T
function cmd_t() {
	if (cmdEnsureEditing()) return;

	var lingua = cmdAutoComplete2(arrayLingue, cmdGetArg("Lingua"), false);
	var argomento = cmdAutoCompleteArgument(cmdGetArg("Argomento"));

	TimenPr('{{T|lingua=' + lingua + '|argomento=' + argomento + '|data=' + cmdMese() + ' ' + cmdAnno() + '}}\n');
	TimenSA('+da tradurre; ');
	TimenME();
}
//Template:O
function cmd_o() {
	if (cmdEnsureEditing()) return;
	TimenPr('{{O|' + cmdAutoCompleteArgument(cmdGetArg("Argomento"), false) + '|mese=' + cmdMese() + ' ' + cmdAnno() + '}}\n');
	TimenSA('+avviso orfana; ');
	TimenME();
}

//Template {{categorizzare}}
function cmd_categorizzare() {
	if (cmdEnsureEditing()) return;
	TimenDp('{{Categorizzare}}\n');
	TimenSA('da categorizzare; ');
	TimenME();
}
//Template {{Da unire}}
function cmd_unire() {
	if (cmdEnsureEditing()) return;
	TimenPr('{{Da unire|' + cmdGetArg("Voce:") + '}}\n');
	TimenSA('+da unire; ');
	TimenME();
}

//Benvenuto ai nuovi utenti
function cmd_benvenuto() {
	if (cmdEnsureEditing()) return;
	TimenDp('{{benve|nome={{subst:PAGENAME}}|~~~ ~~~~~}}');
	TimenSA('Benvenuto su it.wiki!');
	TimenME();
}

//Aggiorna cache
function cmd_purge() {
	cmdSaveCmdLine();
	location.href = mw.config.get('wgServer') + mw.config.get('wgScriptPath') + "/index.php?title=" + mw.config.get('wgPageName') + "&action=purge";
}

//Sostituzioni automatiche
function cmd_fixformat() {
	if (cmdEnsureEditing()) return;
	if (typeof (fixformat_list) == 'undefined') return;

	cmdWEUpdateTextarea();

	var wpTextbox1 = document.getElementById("wpTextbox1");
	var prev = wpTextbox1.value;
	for (i = 0; i < fixformat_list.length; i++) {
		try {
			wpTextbox1.value = wpTextbox1.value.replace(fixformat_list[i][0], fixformat_list[i][1]);
		} catch (e) { /* nothing */ }
	}

	cmdWEUpdateFrame();

	if (wpTextbox1.value != prev) {
		TimenSA(fixformat_subject);
		TimenME();
	}
}

//Cerca e sostituisci
function cmd_replace() {
	if (cmdEnsureEditing()) return;
	var s = cmdGetArg("Regexp da cercare?");
	if (s) {
		var r = cmdGetArg("Sostituire con?").replace(/\\n/g, "\n");
		if (!r && r != '') return;

		cmdWEUpdateTextarea();

		try {
			var wpTextbox1 = document.getElementById("wpTextbox1");
			wpTextbox1.value = cmdParams['t'] ? wpTextbox1.value.replace(s, r) : wpTextbox1.value.replace(new RegExp(s, "g"), r);
		} catch (e) { /* nothing */ }

		cmdWEUpdateFrame();
	}
}

//Premi "Salva"
function cmd_save() {
	if (!cmdIsEditing()) return;
	cmdSaveCmdLine();
	document.getElementById("wpSave").click();
}

//Premi "Visualizza anteprima"
function cmd_preview() {
	if (!cmdIsEditing()) return;

	if (cmdParams['u'])
		cmdEncodeCommandlineInFormAction();
	else
		cmdSaveCmdLine();

	document.getElementById("wpPreview").click();
	cmd_stop();
}

//Premi "Mostra cambiamenti"
function cmd_diff() {
	if (!cmdIsEditing()) return;

	if (cmdParams['u'])
		cmdEncodeCommandlineInFormAction();
	else
		cmdSaveCmdLine();

	document.getElementById("wpDiff").click();
	cmd_stop();
}

//Vai ad un'altra pagina
function cmd_goto() {
	var dst = cmdGetArg("Destinazione");
	var action = cmdGetArg("action");
	var fa = "";
	if (cmdParams['u'])
		fa = "&fakeaction=runcommand&command=" + encodeURIComponent(cmdReencodeCmdLine());
	else
		cmdSaveCmdLine(dst.replace(/ /g, "_"));

	location.href = mw.config.get('wgServer') + "/w/index.php?title=" + encodeURIComponent(dst) + "&action=" + action + fa;
	cmd_stop();
}

//Esegue codice JavaScript
function cmd_eval() {
	var jscode = cmdGetArg("Comando JavaScript:");
	eval(jscode);
}

//Esegue codice JavaScript e salva il risultato in una variabile
function cmd_evalvar() {
	var name = cmdGetArg("Nome della variabile:");
	var jscode = cmdGetArg("Comando JavaScript:");
	cmdSetVar(name, eval(jscode));
}

//Esegue codice JavaScript
function cmd_setvar() {
	var n = cmdGetArg("Nome variabile:");
	var v = cmdGetArg("Valore:");
	cmdSetVar(n, v);
}

//Esegue codice JavaScript
function cmd_process() {
	var c = cmdPreprocess(cmdReencodeCmdLine());
	//WARNING: variabile globale
	cmdline_command_array = c.split('#');
	//WARNING: variabile globale: indice del prossimo argomento da leggere
	cmdline_next_argument = 0;
}

//Processa solo i successivi n blocchi
function cmd_processn() {
	var n = parseInt(cmdGetArg("Numero di blocchi:"));
	if (isNaN(n) || (n == 0)) return;
	var c1 = "",
		c2 = "";
	for (var i = 0; i < n; i++)
		c1 += cmdline_command_array[cmdline_next_argument + i] + "#";
	cmdline_next_argument += n;


	c2 = cmdReencodeCmdLine();

	//alert("c1 = " + c1 + "; c2 = " + c2);

	c1 = cmdPreprocess(c1) + c2;
	cmdline_command_array = c1.split("#");
	cmdline_next_argument = 0;
}

//Ripristina una variabile al vecchio valore.
function cmd_restorevar() {
	var n = cmdGetArg("Nome variabile:");
	var v = cmdGetArg("Valore:");
	cmdSetVar(n, v);
}

//Inserisce del testo all'inizio
function cmd_insertbefore() {
	var text = cmdGetArg("Testo da inserire");
	TimenPr(unescape(text));
}

//Inserisce del testo alla fine
function cmd_insertafter() {
	var text = cmdGetArg("Testo da inserire");
	TimenDp(unescape(text));
}

//Imposta l'oggetto della modifica
function cmd_setsummary() {
	var txt = cmdGetArg("Oggetto:");
	var summ = document.getElementById("wpSummary");
	if (summ == null) return;
	summ.value = unescape(txt);
}

//Imposta come modifica minore
function cmd_setminor() {
	var t = cmdGetArg("inserire 0 (deselezionato) o 1 (selezionato):");
	var m = document.getElementById("wpMinoredit");
	if (m) {
		if (t == "0") m.checked = 0;
		if (t == "1") m.checked = 1;
	}
}

//Chiede input all'utente
function cmd_prompt() {
	var text = cmdGetArg("Testo da mostrare all'utente:");
	var varname = cmdGetArg("Nome della variabile da impostare:");
	cmdSetVar(varname, escape(prompt(text, "")));
}

//Mostra un messaggio
function cmd_alert() {
	var t = cmdGetArg("Testo da mostrare all'utente:");
	if (t != null) alert(unescape(t));
}

//Salta i successivi n blocchi
function cmd_skip() {
	var n = parseInt(cmdGetArg("Blocchi da saltare:"));
	if (!isNaN(n))
		cmdline_next_argument += n;
}

//Label nel codice. Prende un argomento ma non fa nulla.
function cmd_label() {
	var arg = cmdGetArg("Nome label:");
}

//Salta all'istruzione successiva ad una label
function cmd_jump() {
	var dst = cmdGetArg("Label di destinazione:");
	while (cmdline_command_array[cmdline_next_argument]) {
		var b1 = cmdline_command_array[cmdline_next_argument].trim();
		var b2 = cmdline_command_array[cmdline_next_argument + 1].trim();
		if ((b1 == 'label') && (b2 == dst)) {
			cmdline_next_argument += 2;
			return;
		}
		cmdline_next_argument++;
	}
	alert("Errore: Label '" + dst + "' non trovata.");
	stop();
}

//Se la casella di modifica non è vuota, salta avanti di 2 blocchi
function cmd_ifvoidpage() {
	cmdWEUpdateTextarea();
	if (document.getElementById("wpTextbox1").value)
		cmdline_next_argument += 2;
}

//Confronta due valori come interi o, se non è possibile, come float o, infine, come stringhe.
function cmd_iftrue() {
	var v1 = cmdGetArg("Primo valore:");
	var op = cmdGetArg("Operando (<, <=, ==, >, >=, !=):");
	var v2 = cmdGetArg("Secondo valore:");
	var v1i = parseInt(v1);
	var v2i = parseInt(v2);
	var v1f = parseFloat(v1);
	var v2f = parseFloat(v2);

	if (!isNaN(v1i) && !isNaN(v2i))
		switch (op) { //Confronto fra stringhe
		case '<':
			cmdline_next_argument += v1i < v2i ? 0 : 2;
			break;
		case '<=':
			cmdline_next_argument += v1i <= v2i ? 0 : 2;
			break;
		case '==':
			cmdline_next_argument += v1i == v2i ? 0 : 2;
			break;
		case '>=':
			cmdline_next_argument += v1i >= v2i ? 0 : 2;
			break;
		case '>':
			cmdline_next_argument += v1i > v2i ? 0 : 2;
			break;
		case '!=':
			cmdline_next_argument += v1i != v2i ? 0 : 2;
			break;
		}
	else if (!isNaN(v1f) && !isNaN(v2f))
		switch (op) { //Confronto tra float
		case '<':
			cmdline_next_argument += v1f < v2f ? 0 : 2;
			break;
		case '<=':
			cmdline_next_argument += v1f <= v2f ? 0 : 2;
			break;
		case '==':
			cmdline_next_argument += v1f == v2f ? 0 : 2;
			break;
		case '>=':
			cmdline_next_argument += v1f >= v2f ? 0 : 2;
			break;
		case '>':
			cmdline_next_argument += v1f > v2f ? 0 : 2;
			break;
		case '!=':
			cmdline_next_argument += v1f != v2f ? 0 : 2;
			break;
		}
	else
		switch (op) { //Confronto tra stringhe
		case '<':
			cmdline_next_argument += v1 < v2 ? 0 : 2;
			break;
		case '<=':
			cmdline_next_argument += v1 <= v2 ? 0 : 2;
			break;
		case '==':
			cmdline_next_argument += v1 == v2 ? 0 : 2;
			break;
		case '>=':
			cmdline_next_argument += v1 >= v2 ? 0 : 2;
			break;
		case '>':
			cmdline_next_argument += v1 > v2 ? 0 : 2;
			break;
		case '!=':
			cmdline_next_argument += v1 != v2 ? 0 : 2;
			break;
		}
}

//No OPeration
function cmd_nop() {}

//Fine forzata script
function cmd_stop() {
	cmdline_command_array = new Array();
	cmdline_next_argument = 0;
}

//Esegui uno script
function cmd_runscript() {
	var name = cmdGetArg("Nome dello script:");
	if ((name) && (cmdScript[name])) {
		cmd_stop();
		cmdRunCommand(cmdScript[name], true);
	}
}

//Aggiunge un valore ad una variabile
function cmd_add() {
	var varname = cmdGetArg("Nome della variabile:");
	var n = cmdGetArg("Valore o nome della variabile da aggiungere:");
	if (isNaN(n))
		n = cmd_vars[n];
	cmd_vars[varname] = "" + (parseInt(cmd_vars[varname]) + parseInt(n));
}

//Sottrae un valore ad una variabile
function cmd_sub() {
	var varname = cmdGetArg("Nome della variabile:");
	var n = cmdGetArg("Valore o nome della variabile da sottrarre:");
	if (isNaN(n))
		n = cmd_vars[n];
	cmd_vars[varname] = "" + (parseInt(cmd_vars[varname]) - parseInt(n));
}

//Moltiplica una variabile intera per un valore
function cmd_mul() {
	var varname = cmdGetArg("Nome della variabile:");
	var n = cmdGetArg("Valore o nome della variabile da sottrarre:");
	if (isNaN(n))
		n = cmd_vars[n];
	cmd_vars[varname] = "" + (parseInt(cmd_vars[varname]) * parseInt(n));
}

//Divisione intera tra una variabile e un valore
function cmd_div() {
	var varname = cmdGetArg("Nome del dividendo:");
	var n = cmdGetArg("Valore o nome del divisore:");

	if (isNaN(parseInt(n)))
		n = cmd_vars[n];
	else
		n = parseInt(n);
	cmd_vars[varname] = "" + (parseInt(cmd_vars[varname] - cmd_vars[varname] % n) / n);
}

//Resto della divisione intera
function cmd_mod() {
	var varname = cmdGetArg("Nome del dividendo:");
	var n = cmdGetArg("Valore o nome del divisore:");

	if (isNaN(parseInt(n)))
		n = cmd_vars[n];

	cmd_vars[varname] = "" + (parseInt(cmd_vars[varname]) % parseInt(n));
}

function cmd_sleep() {
	var re = parseInt(cmdGetArg("Intervallo:"));
	if (!isNaN(re)) {
		var c = escape(cmdReencodeCmdLine());
		setTimeout('cmdRunCommand(unescape("' + c + '"));', re);
	}
	cmd_stop();
}

//Codice in comune per cmd_grep e cmd_uniq
function cmdPreparePageContent(text) {
	//Trasformiamo Allpages in una normale lista
	res = text;
	if (mw.config.get('wgPageName') == 'Speciale:TutteLePagine')
		res = res.replace(/<tr>|<\/tr>|/g, "").replace(/<td>/g, "<li>").replace(/<\/td>/g, "</li>");

	var res = res.replace(/><li/g, ">\n<li") //porta sempre a capo i <li>
		.replace(/><img src=/g, ">\n<img src="); //e anche le immagini

	return res;
}

function cmd_grep() {
	var re = cmdGetArg("Regular expression:");
	var regexp = new RegExp(re);
	var mustInvert = cmdParams['v'] ? true : false;

	var content = document.getElementById('bodyContent');
	var html = content.innerHTML;

	var start = html.indexOf("<!-- start content -->") + "<!-- start content -->".length;
	var end = html.indexOf("<!-- end content -->");

	var filtered = cmdPreparePageContent(html.substring(start, end));
	var a = filtered.split("\n");
	var b = new Array();
	for (var i = 0; i < a.length; i++) {
		if ((a[i].indexOf("<li") == 0) ||
			(a[i].indexOf("<img") == 0)) {
			var res = regexp.test(a[i]);
			if (mustInvert) res = res ? false : true;
			if (res) b.push(a[i]);
		} else b.push(a[i]);
	}
	content.innerHTML = html.substring(0, start) + b.join("\n") + html.substring(end);
}

function cmd_uniq() {
	var re = cmdGetArg("Regular expression:");
	var regexp = new RegExp(re);
	var mustInvert = cmdParams['v'] ? true : false;

	var content = document.getElementById('bodyContent');
	var html = content.innerHTML;

	var start = html.indexOf("<!-- start content -->") + "<!-- start content -->".length;
	var end = html.indexOf("<!-- end content -->");

	var filtered = cmdPreparePageContent(html.substring(start, end));

	var a = filtered.split("\n");
	var b = new Array();

	var seen = new Object();

	for (var i = 0; i < a.length; i++) {
		if ((a[i].indexOf("<li") == 0) ||
			(a[i].indexOf("<img") == 0)) {
			var m = regexp.exec(a[i]);
			if (m == null)
				b.push(a[i]);
			else if (!seen[m[0]]) {
				seen[m[0]] = true;
				b.push(a[i]);
			}
		} else b.push(a[i]);
	}
	content.innerHTML = html.substring(0, start) + b.join("\n") + html.substring(end);
}

function cmd_unsafe() {
	if ((cmdSafeMode) && !confirm('Lo script in esecuzione nella commandline ha richiesto di passare alla modalità Unsafe.\n' +
			'In modalità Unsafe lo script è in grado, se richiesto, di eseguire operazioni di salvataggio su Wikipedia\n\n' +
			'Premere OK solo se si è sicuri di voler continuare.'))
		cmd_stop();
	else
		cmdSafeMode = false; //disattiva la Safe Mode
}

function cmdPreprocess(cmd) {
	//Parsing variabili predefinite

	cmd = " " + cmd + " "; //un carattere qualsiasi diverso da '$'

	cmdSetVar("title", mw.config.get('wgPageName'), false);
	cmdSetVar("plaintitle", mw.config.get('wgPageName').replace(/_/g, " "), false);
	cmdSetVar("currentyear", "" + cmdAnno(), false);
	cmdSetVar("currentmonthname", "" + cmdMese(), false);
	cmdSetVar("currentmonth", "" + ((new Date()).getMonth() + 1), false);
	cmdSetVar("currentday", "" + cmdGiorno(), false);
	cmdSetVar("null", "", false);

	//Parsing variabili di runtime
	if (typeof (cmd_vars) != 'undefined') {
		for (x in cmd_vars)
			cmd = cmd.replace(new RegExp("([^$])\\$\\$" + x + "([^a-zA-Z])", "g"), "$1" + "<<substitution><" + x + ">>" + "$2");
		for (x in cmd_vars) {
			var tmp = cmd_vars[x].replace(/\$/g, "<<<dollar>>>");
			cmd = cmd.replace(new RegExp("<<substitution><" + x + ">>", "g"), tmp).replace(/<<<dollar>>>/g, "$");
		}
	}

	//Trasformiamo ogni $$.(n).$ in $$.(n-1).$ (es.: $$$$variabile --> $$$variabile)
	cmd = cmd.replace(/(\$*)\$\$\$()/g, "$1" + "$$$");
	return cmd.substring(1, cmd.length - 1);
}

//Processa un singolo blocco se il suo primo carattere è "@"
function cmdPreprocessBlock(txt) {
	if (txt.charAt(0) != '@')
		return txt;
	return cmdPreprocess(txt.substring(1));
}

function cmdSetVar(variabile, valore, toSave) {
	if (typeof (toSave) == 'undefined') toSave = true;
	if (typeof (cmd_vars) == 'undefined') cmd_vars = new Object();
	if (typeof (cmd_savevars) == 'undefined') cmd_savevars = new Object();
	cmd_vars[variabile] = unescape(valore);
	if (toSave) cmd_savevars[variabile] = unescape(valore);
}

function cmdRunCommand(command, mustprocess, safemode) {
	if ((command == null) || (command == "")) return;
	var commandline = command;

	if (safemode) cmdSafeMode = true;
	else cmdSafeMode = false;

	//WARNING: variabile globale
	cmdline_command_array = commandline.split('#');
	//WARNING: variabile globale: indice del prossimo argomento da leggere
	cmdline_next_argument = 0;

	//Ripristina variabili di runtime
	while (cmdline_command_array[cmdline_next_argument] == "_rv") {
		cmdline_next_argument++;
		cmd_restorevar();
	}

	commandline = mustprocess ? cmdPreprocess(cmdReencodeCmdLine()) : cmdReencodeCmdLine();

	cmdline_command_array = commandline.split('#');
	cmdline_next_argument = 0;

	while ((command = cmdline_command_array[cmdline_next_argument++]) != null) {

		command = cmdPreprocessBlock(command.trim());
		if (command.indexOf("#") != -1) {
			cmdline_command_array = (command + cmdReencodeCmdLine()).split("#");
			command = cmdline_command_array[0];
			cmdline_next_argument = 1;
		}

		command = command.trim();

		//Modifiers
		var params = command.split("/");
		command = params[0];
		cmdParams = new Object();
		for (var i = 1; i < params.length; i++) {
			var eqpos = params[i].indexOf("=");
			if (eqpos != -1)
				cmdParams[params[i].substring(0, eqpos)] = params[i].substring(eqpos + 1);
			else
				cmdParams[params[i]] = true;
		}

		if (cmd[command] != null) {
			//alert("Comando: " + command);
			if (cmdSafeMode && (cmdIsSafe[command] !== true)) {
				alert("Comando " + command + " non autorizzato in safe mode.");
				cmd_stop();
				return;
			}
			cmd[command][0](command);
			continue;
		}
		//Cerchiamo se è prefisso univoco di un comando
		var completed = cmdAutoComplete1(cmd, command, true)
		if ((completed != 0) && (completed != -1)) {
			if (cmdSafeMode && (cmdIsSafe[completed] !== true)) {
				alert("Comando " + completed + " non autorizzato in safe mode.");
				cmd_stop();
				return;
			}
			cmd[completed][0](); //tutto a posto, eseguiamo
		} else {
			alert("Comando sconosciuto: " + command + ". Ignoro e continuo.");
		}
	}
}

function showCommandLine() {
	var c = prompt("Comando:", "");
	if (c && cmdScript[c]) cmdRunCommand(cmdScript[c], true);
	else cmdRunCommand(c, true);
}

function addCommandLine() {
	var tb = document.getElementById('p-tb').getElementsByTagName('ul')[0];
	var na = document.createElement('a');
	na.href = "javascript:showCommandLine()";
	na.appendChild(document.createTextNode('Command line'));
	var li = document.createElement('li');
	li.id = 'tb-cmdline';
	li.appendChild(na);
	tb.appendChild(li);

	jQuery(document).bind('keydown', cmdManageHotKey);
}
addOnloadHook(addCommandLine);

function cmdManageHotKey(e) {
	if ((e) && (e.altKey && e.shiftKey && e.ctrlKey)) {
		var charCode = (e.charCode) ? e.charCode : ((e.which) ? e.which : e.keyCode);
		switch (String.fromCharCode(charCode).toLowerCase()) {
		case cmdHotKey:
			showCommandLine();
			return false;
		case cmdQuickHotKey:
			cmdRunCommand(cmdQuickCommand, true);
			return false;
		}
	}
}

function cmdLineAutoRunCommands() {
	//AutoRun via URL
	if (cmdGetParam("fakeaction") == "runcommand") {
		var commandline = decodeURIComponent(cmdGetParam("command"));
		cmdRunCommand(commandline, true, true);
	}

	//AutoRun via cookies
	for (var i = 0; i < 4; i++) {
		var title = cmdGetCookie("cmdAutoRunPage" + i);
		var commandline = cmdGetCookie("cmdAutoRunCommand" + i);
		var sm = commandline.substring(0, 4); //safe mode?
		commandline = commandline.substring(4);

		if (mw.config.get('wgPageName') == title) {
			cmdDeleteCookie("cmdAutoRunPage" + i);
			cmdDeleteCookie("cmdAutoRunCommand" + i);
			cmdRunCommand(commandline, false, sm == '!sm#');
			break;
		}
	}
}
addOnloadHook(cmdLineAutoRunCommands);

//CODICE DI COMPATIBILITA' CON wikEd
// WikEdKeyFrame: Ridefinito il metodo che, altrimenti, trapperebbe ogni tasto schiacciato impedendo
// l'uso di 'Alt+z' quando ci si trova sulla finestra di modifica

function cmdWEUpdateTextarea() {
	if (typeof wikEd != 'undefined' && wikEd.useWikEd)
		WikEdUpdateTextarea();
}

function cmdWEUpdateFrame() {
	if (typeof wikEd != 'undefined' && wikEd.useWikEd)
		WikEdUpdateFrame();
}

function WikEdKeyFrame(event) {
	if (typeof wikEd != 'undefined' && wikEd.useWikEd) {
		if (event.type == 'keypress')
			cmdManageHotKey(event);

		switch (event.type) {
			// trap the tab key
		case 'keydown':
			switch (event.keyCode) {
			case 9:
				if (event.shiftKey == false) {
					event.preventDefault();

					// scroll to text input top
					if (wikEdFullScreenMode == false) {
						var inputWrapperTop = WikEdGetOffsetTop(wikEdInputWrapper);
						window.scroll(0, inputWrapperTop);
					}

					// focus the summary
					wikEdSummaryText.focus();
				}
				break;
			}
			break;

			// trap any other frame event
		case 'keyup':
		case 'keypress':
		case 'mouseup':

			// grey out inactive buttons
			WikEdInactiveButtons();

			// reset the frame DOM cache
			wikEdFrameDOMCache = null;
			break;
		}
	}
	return;
}

__COMMANDLINE_LOADED = true;

/**** Command Line End ****/

/* </nowiki></pre> */