MediaWiki:Common.js/User:Bawolff/sandbox/wiki2text
Appearance
//
mw.loader.load( '/w/index.php?title=' + 'User:Bawolff/mwapilib2.js' + '&action=raw&ctype=text/javascript' );
function filter (text) {
var out = '', char = '';
text = text.replace(/\n/g, '');
var divDepth = 0, tableDepth = 0;
var inTag = false, lastTag = false;
text = text.replace(/<p>/g, '\n\n');
text = text.replace(/<h2>/g, '\n<h2>')
text = text.replace(/<\/h2>/g, '</h2>\n')
for ( var i = 0; i < text.length; i++ ) {
lastTag =false;
char = text.charAt(i);
if (char === '<') {
inTag = true;
if (text.charAt(i+1) === 'd' && text.charAt(i+2) === 'i' && text.charAt(i+3) === 'v' ) {
divDepth++;
}
if (text.charAt(i+1) === 't' && text.charAt(i+2) === 'a' && text.charAt(i+3) === 'b' && text.charAt(i+4) === 'l' && text.charAt(i+5) === 'e' ) {
tableDepth++;
}
}
else if ( char === '>' ){
inTag = false;
lastTag = true;
if (text.charAt(i-1) === 'v' && text.charAt(i-2) === 'i' && text.charAt(i-3) === 'd' && text.charAt(i-4) === '/' ) {
divDepth--;
}
if (text.charAt(i-1) === 'e' && text.charAt(i-2) === 'l' && text.charAt(i-3) === 'b' && text.charAt(i-4) === 'a' && text.charAt(i-5) === 't' && text.charAt(i-6) === '/' ) {
tableDepth--;
}
}
if (divDepth < 0) {
throw new Error( 'ahhh! too many div end' );
}
if (tableDepth < 0) {
throw new Error( 'ahhh! too many table end' );
}
if (divDepth === 0 && !inTag && !lastTag && tableDepth === 0) out += char;
}
if (inTag || divDepth !== 0 || tableDepth !==0) {
throw new Error ('malformed input; (divDepth, tableDepth, tag) = ' +divDepth + tableDepth + inTag);
}
out = out.replace(/\n(?:\[edit\]\s)?(?:[sS]ources|[rR]elated\s[nN]ews)\n[\s\S]*$/, ''); // body only
return out;
}
if (mw.config.get('wgAction')==='view') {
$( function () {
if (!api) alert('api didn\'t load');
api().renderPage(prompt("Enter page you want to turn into plain text", "Over 100 dead in Libyan plane crash")).lift(filter).push().lift(alert).pop().
lift(function (t) { if (t.match(/</)) throw new Error('security error'); document.getElementById('bodyContent').innerHTML += '<pre>' + t + '</pre>'} ).
exec();
});
}
//