Jump to content

User:Mr. Stradivarius/chessboardfix.js

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Mr. Stradivarius (talk | contribs) at 08:18, 27 October 2014 (add a comment with installation instructions). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
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.
/* This script fixes duplicate parameters in chess template invocations. If a
* chess template uses the previous standard invocation style, e.g. something
* like this:

{{Chess diagram
| tright
| 
|= 

 8 |rd|nd|bd|qd|kd|bd|nd|rd|=
 7 |pd|pd|pd|pd|  |pd|pd|pd|=
 6 |  |  |  |  |  |  |  |  |=
 5 |  |  |  |  |pd|  |  |  |=
 4 |  |  |  |  |pl|pl|  |  |=
 3 |  |  |  |  |  |  |  |  |=
 2 |pl|pl|pl|pl|  |  |pl|pl|=
 1 |rl|nl|bl|ql|kl|bl|nl|rl|=
    a  b  c  d  e  f  g  h  

| The King's Gambit
}}

* Then it will be transformed into something like this:

{{Chess diagram
| tright
| 

|rd|nd|bd|qd|kd|bd|nd|rd
|pd|pd|pd|pd|  |pd|pd|pd
|  |  |  |  |  |  |  |  
|  |  |  |  |pd|  |  |  
|  |  |  |  |pl|pl|  |  
|  |  |  |  |  |  |  |  
|pl|pl|pl|pl|  |  |pl|pl
|rl|nl|bl|ql|kl|bl|nl|rl

| The King's Gambit
}}

* To use it, highlight the chess template invocation that you want to fix in the
* edit window, and click the "Fix chessboards" link in the toolbar (below "what
* links here").
* 
* To install the script, put the following code in [[Special:MyPage/skin.js]]:
 
importScript('User:Mr. Stradivarius/chessboardfix.js'); // Linkback: [[User:Mr. Stradivarius/chessboardfix.js]]
 
*/

var myContent = document.getElementsByName( 'wpTextbox1' )[0];

function replaceSelection( replace ) {
	// Replace currently selected text with the string s.
	var len = myContent.value.length;
	var start = myContent.selectionStart;
	var end = myContent.selectionEnd;
	var sel = myContent.value.substring( start, end );

	if ( typeof( replace ) == 'function' ) {
		replace = replace( sel );
	}

	myContent.value = myContent.value.substring( 0, start )
		+ replace
		+ myContent.value.substring( end, len );
}

function wpChessboardFix() {
	replaceSelection( function ( sel ) {
		sel = sel.replace( /\n *\d+ *((?:\| *.. *)+)\| *= */g, '\n$1' );
		sel = sel.replace( /\n *\|= *\n+/g, '\n\n' );
		sel = sel.replace( /\n *(?:[a-zA-Z][a-zA-Z]?\b *)+\n+/g, '\n\n' );
		sel = sel.replace( /\n *[bB]oard *\w+ *\n+/g, '\n' );
		return sel;
	} );
}

function TTscriptButton() {
  addPortletLink('p-tb','javascript:wpChessboardFix()','Fix chessboards','t-chessboardfix');
}

if (wgNamespaceNumber != -1 && myContent) {
	addOnloadHook(TTscriptButton);
}