User:Magnus Manske/tmpl.js
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
// <nowiki><pre>
if ( ( mw.config.get('wgAction') == "submit" || mw.config.get('wgAction') == "edit" ) && mw.config.get('wgNamespaceNumber') == 0 ) {
addOnloadHook ( init_tmpl ) ;
}
var tmpl_active = 0 ;
var tmpl_original = '' ;
var tmpl_template_texts = new Array () ;
var tmpl_keys = new Array () ;
function init_tmpl () {
tmpl_hook_button ( 'wpSave' ) ;
tmpl_hook_button ( 'wpPreview' ) ;
tmpl_hook_button ( 'wpDiff' ) ;
tmpl_parse_textbox () ;
}
function tmpl_hook_button ( id ) {
var b = document.getElementById ( id ) ;
b.onclick = function () { tmpl_rejoin() ; return true ; } ;
}
function tmpl_rejoin () {
if ( tmpl_active == 0 ) return ;
var tb = document.getElementById('wpTextbox1') ;
var all = tb.value ;
for ( var akey in tmpl_keys ) {
var key = tmpl_keys[akey] ;
if ( null == key.match ( /^##TEMPLATE\d+:/ ) ) continue ;
var text = tmpl_template_texts[akey] ;
all = all.split(key).join("{{"+text+"}}");
}
tmpl_active = 0 ;
tb.value = all ;
}
function tmpl_parse_textbox () {
if ( tmpl_active == 1 ) return ;
tmpl_active = 1 ;
var tb = document.getElementById('wpTextbox1') ;
tmpl_original = tb.value ;
var tcnt = 0 ;
var ts = '' ;
var ns = '' ;
var curt = 0 ;
for ( var a = 0 ; a < tmpl_original.length ; a++ ) {
if ( tmpl_original[a] == '{' && tmpl_original[a+1] == '{' ) {
tcnt++ ;
a++ ;
if ( tcnt > 1 ) ts += '{{' ;
} else if ( tmpl_original[a] == '}' && tmpl_original[a+1] == '}' ) {
if ( tcnt > 1 ) ts += '}}' ;
if ( tcnt > 0 ) tcnt-- ;
if ( tcnt == 0 ) {
if ( 1 == ts.split('\|').length ) { // Just a simple template, no parameters
ns += "{{" + ts + "}}" ;
} else {
curt++ ;
var tname = tmpl_get_template_name ( ts ) ;
var key1 = "##TEMPLATE" + curt + ":" + tname + "##" ;
tmpl_keys[curt] = key1 ;
ns += key1 ;
tmpl_template_texts[curt] = ts ;
}
ts = '' ;
}
a++ ;
} else {
if ( tcnt == 0 ) {
ns += tmpl_original[a] ;
} else {
ts += tmpl_original[a] ;
}
}
}
tb.value = ns ;
tb.ondblclick = tmpl_textbox_dblclick ;
}
function tmpl_get_template_name ( text ) {
text = text.split('\|').shift() ;
text = text.split('\{').shift() ;
text = text.replace ( /\s+$/ , '' ) ;
text = text.replace ( /^\s+/ , '' ) ;
return text ;
}
function tmpl_textbox_dblclick () {
var tb = document.getElementById('wpTextbox1') ;
var len = tb.value.length;
var start = tb.selectionStart-2;
var end = tb.selectionEnd+1;
if ( start < 0 ) return ;
if ( end >= tb.value.length ) return ;
var sel = tb.value.substring(start, end);
if ( null == sel.match ( /^##TEMPLATE\d+:$/ ) ) return ;
var num = sel.match ( /\d+/ ) ;
var text = tmpl_template_texts[num] ;
alert ( num + " stands for:\n" + text ) ;
}
// </pre></nowiki>