//<pre><nowiki>
/* segregate-refs.js: A user script to simplify editing of articles
using inline ref tags with the Cite.php extension to MediaWiki.
Copyright (c) 2010, PleaseStand
This software is licensed under these licenses:
1. Creative Commons Attribution-Share Alike 3.0 Unported License
(see <http://creativecommons.org/licenses/by-sa/3.0/> for the text)
2. GNU Free Documentation License, any published version.
(see <http://www.gnu.org/copyleft/fdl.html> for the text)
3. Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
You may select the license(s) of your choice if you wish to copy, modify, or
distribute this software. If you modify the software and do not wish to
license your changes under one or more of the licenses, please remove
the license(s) from the list above.
*/
/*global window, addOnloadHook, SegregateRefsJsL10n, SegregateRefsJsAllowConversion,
wikEdUseWikEd, WikEdUpdateTextarea, WikEdUpdateFrame*/
SegregateRefsJsEmptyRefsWarningGiven, SegregateRefsJsAllowConversion,
SegregateRefsJsCompleteSearch, wikEdUseWikEd, WikEdUpdateTextarea,
// <nowiki>
WikEdUpdateFrame*/
// Translate the right-hand side of these if necessary.
// var SegregateRefsJsL10n = {
var SegregateRefsJsMsgs = {
version: 1.11,
buttonText: "Segregate refs for editing",
buttonStyle: "background: #dfd;",
buttonConvertText: "Migrate article to LDR",
buttonConvertStyle: "background: #fdd;",
autoWord: "Auto",
convertRefsWarning: "WARNING: You need consensus to migrate an article to list-defined references format (LDR) BEFORE you do so.\n\nClick Cancel now if consensus has not been established in favor of this migration. If there is consensus to make the conversion, click OK to do so.",
emptyRefsWarning: "IMPORTANT: This page includes one or more named " +
groupPrompt: "Please enter the name of a group (as it appears in the wikitext, including any quotes). Leave this blank if unsure.",
"footnotes of which the first occurrence(s) have no contents, which is " +
refsHeader: "Inline footnotes",
"not best practice. This script does not harm such footnotes, however " +
convertHeader: "Generated refs list",
"you should be aware that this script ONLY CHECKS THE FIRST REF TAG " +
refsCommentComplete: "<!-- Converted to LDR format\n using [[User:PleaseStand/References segregator]] -->\n\n",
"it finds for the actual citation or note text, and you must work within " +
convertSummary: "Converted footnotes to LDR format (using [[User:PleaseStand/References segregator|segregate-refs]])",
"this limitation. Any change to the empty ref tag will replace the " +
convertFurther: "This script has done most of the work. However, you still need to do the following:\n\n* Insert the refs list in the new textbox into the proper place in the wikitext.\n* If converting a special group, optionally remove the group attributes.\n* Replace all autogenerated names with human-generated names.\n\nYou can do the above with the Find/Replace command in many text editors. (Always use the quoted form of the attributes.) Then, paste the text back into the edit form and save the page.",
"footnote entirely and leave the old note text hidden.\n\n" +
integrateWarning: "The refs listed below are missing from the text. If you continue, they will be permanently deleted. Are you sure?\n\nUnused refs: "
"BEFORE concluding from the footnotes list that a ref is in fact empty, " +
"please manually check all identically-named ref tags for the contents. " +
"\n\nDo you acknowledge this limitation of the script? DO NOT CLICK OK " +
"UNTIL YOU HAVE READ THE ABOVE INFORMATION.",
convertRefsWarning: "WARNING: You need consensus to migrate an article " +
"to list-defined references format (LDR) BEFORE you do so.\n\nClick " +
"Cancel now if consensus has not been established in favor of this " +
"migration. If there is consensus to make the conversion, click OK to " +
"do so.",
groupPrompt: "Please enter the name of a group (as it appears in the " +
"wikitext, including any quotes). Leave this blank if unsure.",
refsHeader: "Inline footnotes",
convertHeader: "Generated refs list",
refsCommentIncomplete: "<!-- This list of footnotes may be incomplete. " +
"Do not use for conversion purposes. -->\n\n",
refsCommentComplete: "<!-- Converted to LDR format\n" +
" using [[User:PleaseStand/References segregator]] -->\n\n",
convertSummary: "Converted footnotes to LDR format (using " +
"[[User:PleaseStand/References segregator|segregate-refs]])",
convertFurther: "This script has done most of the work. However, you still " +
"need to do the following:\n\n* Insert the refs list in the new textbox " +
"into the proper place in the wikitext.\n* If converting a special " +
"group, optionally remove the group attributes.\n* Replace all " +
"autogenerated names with human-generated names.\n\nYou can do the above " +
"with the Find/Replace command in many text editors. (Always use the " +
"quoted form of the attributes.) Then, paste the text back into the edit " +
"form and save the page.",
integrateWarning: "The refs listed below are missing from the text. If you " +
"continue, they will be permanently deleted. Are you sure?\n\nUnused refs: "
};
( function ( $ ) {
// Begin encapsulation (prevent interference with other scripts)
(function(){
// "Semi-global" variables (function-scoped variables private to this script)
var editForm, refsDiv, refsH2, mainTextbox, refsTextbox, randPrefix, messages,
refsButton, convertButton, complete, unloadHandlerRegistered = false;
/**
// Define a (very important) function that is better than hasOwnProperty
* Unquote a wikitext tag attribute.
function has(obj, key) {
*
return Object.hasOwnProperty.call(obj, key);
* @param string quotedValue
* @return string
*/
function htmlUnquote( quotedValue ) {
var d = document.createElement( 'div' );
d.innerHTML = '<input value=' + quotedValue + '></input>';
return d.firstChild.value;
}
/**
// Setting a slice of a string
* Quote a wikitext tag attribute, choosing single quotes versus
function setSlice(t, replacement, indexFrom, indexTo) {
* double quotes depending on which is shorter.
if(typeof indexTo == "undefined") {
*
return t.slice(0, indexFrom) + replacement;
* @param string value
}
* @return string
return t.slice(0, indexFrom) + replacement + t.slice(indexTo);
*/
}
function htmlQuote( value ) {
var sQ, dQ;
value = value.replace( /\&/g, '&' );
// Unquoting from an HTML-quoted form
sQ = "'" + value.replace( /'/g, ''' ) + "'",
function htmlUnquote(t) {
dQ = '"' + value.replace( /"/g, '"' ) + '"';
// Let's use the browser's functionality for the hard work,
// since MediaWiki/PHP supports many different HTML entities.
// (Note: innerHTML is not W3C-standard)
var d = window.document.createElement("div");
d.innerHTML = "<input value=" + t + "></input>";
return d.firstChild.value;
}
return sQ.length < dQ.length ? sQ : dQ;
// Quoting using HTML quotes. Chooses single quotes versus
// double quotes depending on which is shorter.
function htmlQuote(t) {
// Escape ampersands
var s = t.replace(/\&/g, "&");
// Try both kinds of quotes
var sQ = "'" + s.replace(/'/g, "'") + "'",
dQ = '"' + s.replace(/"/g, """) + '"';
// Choose the shorter, preferring double quotes if equal in length
return (sQ.length < dQ.length ? sQ : dQ);
}
// Looks for ref tags in the text, skipping problematic extension tags.
// OBJECTS
// For example, "references" may contain out-of-line refs, which should be skipped.
function RefScanner( argWikiText ) {
// RefScanner: Use for identifying ref tags in text. (No nested refs please)
this.wikiText = argWikiText;
function RefScanner(argWikiText) {
this.refScanRegex = /(?:<!--[\s\S]*?-->|<(nowiki|source|references|ref)(?:|\s(?:[^"']|"[^"]*"|'[^']*')*?)(?:\/>|(?:>[\s\S]*?<\/\1(?:|\s[^>]*)>)))/gi;
this.wikiText = argWikiText;
// The tags listed below other than "ref" are there for an obvious reason.
// NB: "references" is here to prevent out-of-line refs from being returned.
this.refScanRegex = /(?:<!--[\s\S]*?-->|<(nowiki|source|references|ref)(?:\s|(?:[^"']|"[^"]*"|'[^']*')*?)(?:\/>|(?:>[\s\S]*?<\/\1(?:|\s[^>]*)>)))/gi;
}
RefScanner.prototype = {
// ReturnsGet the next ref found infrom the text.
RefScanner.prototype.getRef getRef:= function getRef() {
var results;
do {
results = this.refScanRegex.exec( this.wikiText );
if ( if(!results ) {
return null;
}
}
if if(typeof results[1] === "undefined" ) {
results = [0, 0];
}
}
} while ( results[1].toString().toLowerCase() !== "'ref"' );
return results[0];
}
};
// RefParser: Use for extractingExtracts attributes from ref tags.
function RefParser( argWikiText ) {
// This is mostly a copy of refScanRegex, except that the whole string must be a ref,
this.wikiText = argWikiText;
// and no more, and two parts are extracted: $1=attributes, $2=remaining portion of ref
// The below regex is mostly a copy of the refScanRegex above, except that
var refParseRegex = /^<ref(|\s(?:[^"']|"[^"]*"|'[^']*')*?)(\/>|(?:>[\s\S]*?<\/ref(?:|\s[^>]*)>))$/i;
// the whole string must be a ref, and no more, and two parts are extracted:
// $1=attributes, $2=remaining portion of ref
this.wikiText = argWikiText;
var refParseRegex = /^<ref(|\s(?:[^"']|"[^"]*"|'[^']*')*?)(\/>|(?:>[\s\S]*?<\/ref(?:|\s[^>]*)>))$/i;
this.parsedRef = refParseRegex.exec( this.wikiText );
if ( !this.parsedRef ) {
throw new Error(" 'invalid ref"' );
}
}
RefParser.prototype = {
// Get all attributes of the tag.
getAttributes: function getAttributes() {
RefParser.prototype.getAttributes = function () {
// In this regex, we need to extract a single name-value pair at a time.
// In this regex, we need to extract a single name-value pair at a time.
var attParseRegex = /\s([^\s=>]+)\s*=\s*("[^"]*"|'[^']*'|[^\s"']*)/g;
var attParseRegex = /\s([^\s=>]+)\s*=\s*("[^"]*"|'[^']*'|[^\s"']*)/g;
if(!this.parsedRef) {
if ( !this.parsedRef ) {
return null;
return null;
}
}
var attributes = {}, results;
var attributes = Object.create( null ), results;
while((results = attParseRegex.exec(this.parsedRef[1]))) {
while ( ( results = attParseRegex.exec( this.parsedRef[1] ) ) ) {
attributes[results[1].toLowerCase()] = htmlUnquote(results[2]);
attributes[results[1].toLowerCase()] = htmlUnquote( results[2] );
}
}
return attributes;
return attributes;
}
};
/**
// FUNCTIONS
* Segregate refs from content.
*
* @param string argWikiText The original wikitext
* @param string group The name of the ref group to process (default group is '')
* @param bool caseCues Mark the original ref code locations using capitalization?
* @return Object
*/
function segregateRefs( argWikiText, group, caseCues ) {
var prefixChars, randNo, randPrefix, refPreferred, scanner, ref, parser, attributes,
refGroup, refName, refStored, refEmpty, refLong, unnamedRefs = 0,
refNames = Object.create( null ), refCodes = [], refShort, outWikiText = '', offset = 0;
// Create a random prefix for autogenerated ref names
// segregateRefs: Use for segregating refs from content.
prefixChars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
// If completeSearch == true, the function looks in all occurrences for ref
randNo = Math.floor( Math.random() * ( prefixChars.length * prefixChars.length ) );
// contents. If completeSearch == false, the function only checks the first.
randPrefix = messages.autoWord
// group is the reference group to limit the operation to. The empty string
+ prefixChars.charAt( Math.floor( randNo / prefixChars.length ) )
// refers to all ungrouped refs. caseCues is whether or not to use
+ prefixChars.charAt(randNo % prefixChars.length) +
// capitalization to designate a preferred ref code ___location.
'-';
function segregateRefs(argWikiText, completeSearch, group, caseCues) {
// Create athe randombeginning prefixof the code for autogenerateda preferred ref names.___location
refPreferred = caseCues ? '<REF ' : '<ref ';
// in theory this has a 1/1296 probability of collision - extremely low
var prefixChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",
scanner = new RefScanner( argWikiText );
randNo = Math.floor(Math.random() *
(prefixChars.length * prefixChars.length));
while ( ( ref = scanner.getRef() ) ) {
randPrefix = messages.autoWord + prefixChars.charAt(Math.floor(randNo /
parser = new RefParser( ref );
prefixChars.length)) + prefixChars.charAt(randNo % prefixChars.length) +
attributes = parser.getAttributes();
"-";
refGroup = attributes.group || '';
// Create the beginning of the code for a preferred ref ___location
if ( group != refGroup ) {
var refPreferred = caseCues ? "<REF " : "<ref ";
// The ref is in a different group
continue;
// Variables for the main code
}
var scanner = new RefScanner(argWikiText), unnamedRefs = 0, refNames = {},
ref, refStored, parser, attributes, refName, refLong, refShort,
if ( attributes.name !== undefined ) {
refCodes = [], refEmpty, emptyRefsWarningGiven = false, refGroup;
// The ref already has a name (possibly the empty string)
refName = attributes.name;
// Disable the empty refs warning (see below) if the user has disabled it
refStored = refName in refNames;
if(typeof SegregateRefsJsEmptyRefsWarningGiven != "undefined" &&
refEmpty = parser.parsedRef[2].slice( -2 ) == '/>' ||
SegregateRefsJsEmptyRefsWarningGiven) {
parser.parsedRef[2].slice( 0, 3 ) == '></';
emptyRefsWarningGiven = true;
refLong = ref;
}
} else {
while((ref = scanner.getRef())) {
// We have to autogenerate one
parser = new RefParser(ref);
refName = randPrefix + ( ++unnamedRefs ).toString(10);
attributes = parser.getAttributes();
refStored = false;
refEmpty = false;
// First make sure that the ref is in the right group.
refLong = '<ref name=' + htmlQuote( refName ) +
refGroup = has(attributes, "group") ? attributes.group : "";
parser.parsedRef[1] + parser.parsedRef[2];
if(group != refGroup) {
}
continue;
}
if ( !refStored ) {
// DoesFound the first ref haveof athis name?
refNames[refName] = {
// (Note: No matter how incorrect it seems, the empty string is
code: refCodes.length,
// an acceptable ref name to the MediaWiki parser, as verified by
empty: refEmpty
// informal testing.)
};
if(!has(attributes, "name")) {
refCodes[refNames[refName].code] = refLong;
// Bad: it doesn't have one - create a name for it
refStored = false;
// Make a short code for the ref
refEmpty = false;
if ( refEmpty ) {
refName = randPrefix + (++unnamedRefs).toString(10);
refShort = refLong;
// Change the corresponding ref code
} else if ( refGroup === '' ) {
refLong = "<ref name=" + htmlQuote(refName) +
refShort = refPreferred + 'name=' + htmlQuote( refName ) + '/>';
parser.parsedRef[1] + parser.parsedRef[2];
} else {
refShort = refPreferred + 'name=' + htmlQuote( refName ) +
// Good: it has a name.
' group=' + htmlQuote( refGroup ) + '/>';
refName = attributes.name;
}
refLong = ref;
// Check if the ref name has already been seen.
} else if ( !refEmpty && refNames[refName].empty ) {
refStored = has(refNames, refName);
// Already found an empty ref under this name, yet this one is non-empty
// Check if the ref has no contents.
// Fill in the long code for the existing entry
refEmpty = (parser.parsedRef[2].slice(-2) == "/>") ||
refCodes[refNames[refName].code] = refLong;
(parser.parsedRef[2].slice(0, 3) == "></");
refNames[refName].empty = false;
// Since this script, when not set in complete search mode, checks
// only the first occurrence of a ref for contents, inform the user
// Make a short code for the ref
// of this limitation if it may pose a problem.
refShort = refPreferred + 'name=' + htmlQuote( refName );
if(!completeSearch && !emptyRefsWarningGiven && !refStored) {
if ( refGroup !== '' ) {
if(refEmpty) {
refShort += ' group=' + htmlQuote( refGroup ) + '/>';
if(!window.confirm(messages.emptyRefsWarning)) {
}
return false;
refShort += '/>';
}
emptyRefsWarningGiven = true;
} else {
}
// Leave the ref as-is
}
refShort = caseCues ? refLong.replace( /^<REF/, "<ref" ) : refLong;
}
}
// Is the ref's name unique?
// Replace the long code with the short code
if(!refStored) {
outWikiText += argWikiText.slice( offset, scanner.refScanRegex.lastIndex - ref.length );
// Unique: add it to the list of refs
outWikiText += refShort;
refNames[refName] = {
offset = scanner.refScanRegex.lastIndex;
code: refCodes.length,
}
empty: refEmpty
};
outWikiText += argWikiText.slice( offset );
refCodes[refNames[refName].code] = refLong;
return {
// Make a short code for the ref
wikiText: outWikiText,
if(refEmpty) {
refCodes: refCodes,
refShort = refLong;
randPrefix: randPrefix
} else if(!refGroup.length) {
};
refShort = refPreferred + "name=" +
htmlQuote(refName) + "/>";
} else {
refShort = refPreferred + "name=" + htmlQuote(refName) +
" " + "group=" + htmlQuote(refGroup) + "/>";
}
// Otherwise, is the current longcode not empty?
// (only when in complete search mode, and when another non-empty,
// same-named ref has not been encountered)
} else if (completeSearch && !refEmpty && refNames[refName].empty) {
// Not empty: fill in the long code and make a short code
refCodes[refNames[refName].code] = refLong;
refNames[refName].empty = false;
if(!refGroup.length) {
refShort = refPreferred + "name=" +
htmlQuote(refName) + "/>";
} else {
refShort = refPreferred + "name=" + htmlQuote(refName) +
" " + "group=" + htmlQuote(refGroup) + "/>";
}
} else {
// Leave the ref as-is in the original wikitext
// (except if caseCues apply)
if(caseCues) {
refShort = refLong.replace(/^<REF/, "<ref");
} else {
refShort = refLong;
}
}
// Replace the long code with the short code
scanner.wikiText = setSlice(scanner.wikiText, refShort,
scanner.refScanRegex.lastIndex - ref.length,
scanner.refScanRegex.lastIndex);
// Update lastIndex accordingly
scanner.refScanRegex.lastIndex += refShort.length - ref.length;
}
return {
wikiText: scanner.wikiText,
refCodes: refCodes,
randPrefix: randPrefix
};
}
/**
// integrateRefs: Use for inserting ref contents back into text
* Insert ref contents back into the text.
*
* @param string argWikiText The wikitext without ref contents
* @param string argRefText The ref contents
* @param string randPrefix The randPrefix value returned by segregateRefs()
* @param string caseCues The caseCues argument passed to segregateRefs()
*/
function integrateRefs(argWikiText, argRefText, randPrefix, caseCues) {
// A function to removeRemove an autogenerated ref name (if possible).
function cleanRefLong(dirtyRef) {
var cleanRegex = /^<(ref) name=(?:"[^"]*"|'[^']*'|[^\s"']*)/i;
return dirtyRef.replace(cleanRegex, "'<$1"');
}
}
var scanner, ref, parser, attributes, refCodes = Object.create( null ), usageFreq = Object.create( null ),
// Variables for the main code
preferredRef = Object.create( null ), refLong, outWikiText = '', offset = 0;
var scanner, ref, parser, attributes, refCodes = {}, usageFreq = {},
preferredRef = {}, refLong;
// First, we build an associative array of all the ref codes
// First,that we buildmight anneed associativeto arrayput ofback allinto the ref codestext.
scanner = new RefScanner( argRefText );
// that we might need to put back into the text.
while ( ( ref = scanner.getRef() ) ) {
parser = new RefParser( ref );
// NOTE: JavaScript does not actually offer real associative array
attributes = parser.getAttributes();
// functionality, so we emulate it using objects and the has() function
if ( attributes.name !== undefined ) {
// we defined earlier that is used to verify a property's existence.
// Only use the first ref having each name
scanner = new RefScanner(argRefText);
if ( !( attributes.name in refCodes ) ) {
while((ref = scanner.getRef())) {
refCodes[attributes.name] = ref;
parser = new RefParser(ref);
}
attributes = parser.getAttributes();
}
if(has(attributes, "name")) {
}
// Only use the first ref with each name
if(!refCodes.hasOwnProperty(attributes.name)) {
// Next, we build an associative array that holds the usage frequency
refCodes[attributes.name] = ref;
// of every ref name used in text, and whether there is a preferred ref,
}
// if caseCues are enabled.
}
scanner = new RefScanner( argWikiText );
}
while ( ( ref = scanner.getRef() ) ) {
parser = new RefParser( ref );
// Next, we build an associative array that holds the usage frequency
attributes = parser.getAttributes();
// of every ref name used in text, and whether there is a preferred ref,
if ( attributes.name !== undefined ) {
// if caseCues are selected.
if ( !( attributes.name in usageFreq ) ) {
scanner = new RefScanner(argWikiText);
usageFreq[attributes.name] = 1;
while((ref = scanner.getRef())) {
} else {
parser = new RefParser(ref);
usageFreq[attributes = parser.getAttributes()name]++;
}
if(has(attributes, "name")) {
if ( caseCues && ref.slice( 0, 4 ) == '<REF' ) {
if(!has(usageFreq, attributes.name)) {
preferredRef[attributes.name] = true;
// We found a new name
}
usageFreq[attributes.name] = 1;
}
} else {
}
// We already found this name
usageFreq[attributes.name]++;
// Finally, we go through the text again and this time we insert the
}
// ref codes where we need to, but only in the first place
if(caseCues) {
// a ref name appears (or the first preferred ___location).
if(ref.slice(0, 4) == "<REF") {
scanner = new RefScanner( argWikiText );
preferredRef[attributes.name] = true;
while ( ( ref = scanner.getRef() ) ) {
}
parser = new RefParser( ref );
}
attributes = parser.getAttributes();
}
if ( 'name' in attributes ) {
}
// Is this name on the replacement list?
if ( attributes.name in refCodes ) {
// Finally, we go through the text again and this time we insert the
// ref codes where we need to, but only in the first place
// If we are using caseCues, and another ___location is
// a ref name appears (or the first preferred ___location).
// preferred, skip to the next ref.
scanner = new RefScanner(argWikiText);
if ( caseCues && attributes.name in preferredRef &&
while((ref = scanner.getRef())) {
ref.slice( 0, 4 ) != '<REF'
parser = new RefParser(ref);
) {
attributes = parser.getAttributes();
continue;
if(has(attributes, "name")) {
}
// Is this name on the replacement list?
if(has(refCodes, attributes.name)) {
// Is this name an autogenerated name?
if ( attributes.name.slice( 0, randPrefix.length ) == randPrefix ) {
// If we are using caseCues, and another ___location is
// Yes: is the name used multiple times?
// preferred, skip to the next ref.
if(caseCues && has(preferredRef, usageFreq[attributes.name] > 1 ) &&{
// Multiple: the replacement code should be the same
ref.slice(0, 4) != "<REF") {
// as that stored in the ref textbox.
continue;
refLong = refCodes[attributes.name];
}
} else {
// Single: replacement code must not include the name,
// Is this name an autogenerated name?
// at least not if the citation was untouched.
if(attributes.name.slice(0, randPrefix.length) == randPrefix) {
// (We don't want to add unnecessary autonames)
// Yes: is the name used multiple times?
refLong = cleanRefLong( if(usageFreqrefCodes[attributes.name] > 1) {;
}
// Multiple: the replacement code should be the same
} else {
// as that stored in the ref textbox.
// No: the replacement code should be the same
refLong = refCodes[attributes.name];
// as that stored in the ref textbox.
} else {
// (We want to preserve all human-generated names)
// Single: replacement code must not include the name,
refLong = refCodes[attributes.name];
// at least not if the citation was untouched.
}
// (We don't want to add unnecessary autonames)
refLong = cleanRefLong(refCodes[attributes.name]);
// Replace the short code with the long code
}
outWikiText += argWikiText.slice( offset, scanner.refScanRegex.lastIndex - ref.length );
} else {
outWikiText += refLong;
// No: the replacement code should be the same
offset = scanner.refScanRegex.lastIndex;
// as that stored in the ref textbox.
// (We want to preserve all human-generated names)
// Delete the name from the replacement list
refLong = refCodes[attributes.name];
delete refCodes[attributes.name];
}
}
}
// Replace the short code with the long code
}
scanner.wikiText = setSlice(scanner.wikiText, refLong,
scanner.refScanRegex.lastIndex - ref.length,
outWikiText += argWikiText.slice( offset );
scanner.refScanRegex.lastIndex);
// Update lastIndex accordingly
return {
scanner.refScanRegex.lastIndex += refLong.length - ref.length;
wikiText: outWikiText,
unusedRefs: refCodes
// Delete the name from the replacement list
};
delete refCodes[attributes.name];
}
}
}
// Return both the combined output and the ref codes that were not used.
return {wikiText: scanner.wikiText, unusedRefs: refCodes};
}
/**
// Clears the undo history of a textarea by removing it
* Clear the undo history of a textarea by removing it from the document
// from the DOM and then inserting it again.
* and then inserting it again.
*
* @param HTMLTextareaElement ta The textarea element
*/
function clearUndoHistory(ta) {
var pn = ta.parentNode, ns = ta.nextSibling;
pn.insertBefore(pn.removeChild(ta), ns);
}
function unloadHandler(evt) {
// Local variables
var result, refName, unusedRefNamesQuoted = [];
// wikEd compatibility (frame -> textarea)
if(typeof wikEdUseWikEd != "undefined" && wikEdUseWikEd) {
WikEdUpdateTextarea();
}
}
// Do the actual integration work
result = integrateRefs(mainTextbox.value, refsTextbox.value, randPrefix, true);
randPrefix, complete);
// Find all unused ref names
for(refName in result.unusedRefs) {
unusedRefNamesQuoted.push(htmlQuote(refName));
// Find all unused ref names
}
for(refName in result.unusedRefs) {
// If any refs are unused, warn and allow the user to cancel;
if(has(result.unusedRefs, refName)) {
// we do not do this on unload because it is not really possible.
unusedRefNamesQuoted.push(htmlQuote(refName));
if(evt.type == "submit" && unusedRefNamesQuoted.length) {
}
if(!window.confirm(messages.integrateWarning +
}
unusedRefNamesQuoted.join(", "))) {
// If any refs are unused, warn and allow the user to cancel;
// Don't submit form
// we do not do this on unload because it is not really possible.
evt.preventDefault();
if(evt.type == "submit" && unusedRefNamesQuoted.length) {
return false;
if(!window.confirm(messages.integrateWarning +
}
unusedRefNamesQuoted.join(", "))) {
}
// Don't submit form
evt.preventDefault();
// Otherwise, update the textbox.
return false;
mainTextbox.value = result.wikiText;
}
}
// wikEd compatibility (textarea -> frame)
if(typeof wikEdUseWikEd != "undefined" && wikEdUseWikEd) {
// Otherwise, update the textbox.
WikEdUpdateFrame();
mainTextbox.value = result.wikiText;
}
// wikEd compatibility (textarea -> frame)
// Deactivate this event handler
if(typeof wikEdUseWikEd != "undefined" && wikEdUseWikEd) {
window.removeEventListener("submit", unloadHandler, false);
WikEdUpdateFrame();
window.removeEventListener("unload", unloadHandler, false);
}
unloadHandlerRegistered = false;
// Deactivate this event handler
// We can delete the header and refs textbox now
window.removeEventListener("submit", unloadHandler, false);
refsDiv.removeChild(refsH2);
window.removeEventListener("unload", unloadHandler, false);
refsDiv.removeChild(refsTextbox);
unloadHandlerRegistered = false;
return true;
// We can delete the header and refs textbox now
refsDiv.removeChild(refsH2);
refsDiv.removeChild(refsTextbox);
return true;
}
function refsButtonHandler() { // Called when script activated by button click
// Both buttons should disappear
if(convertButton.parentNode){
convertButton.parentNode.removeChild(convertButton);
}
}
if(refsButton.parentNode) {
refsButton.parentNode.removeChild(refsButton);
}
}
// Allow for disabling usage of the complete search mode
// when segregating refs for editing.
if(typeof SegregateRefsJsCompleteSearch != "undefined" &&
!SegregateRefsJsCompleteSearch) {
complete = false;
} else {
complete = true;
}
// wikEd compatibility (frame -> textarea)
if(typeof wikEdUseWikEd != "undefined" && wikEdUseWikEd) {
WikEdUpdateTextarea();
}
// Do the actual segregation work and save the random prefix
var segFormat = segregateRefs(mainTextbox.value, complete, "", complete);
if(!segFormat) {
return false;
}
randPrefix = segFormat.randPrefix;
// Update the textbox
mainTextbox.value = segFormat.wikiText;
clearUndoHistory(mainTextbox);
// wikEd compatibility (textarea -> frame)
if(typeof wikEdUseWikEd != "undefined" && wikEdUseWikEd) {
WikEdUpdateFrame();
}
// Inline refs header
refsH2 = window.document.createElement("h2");
refsH2.appendChild(window.document.createTextNode(messages.refsHeader));
refsH2.style.borderColor = "silver";
refsH2.style.borderStyle = "solid";
refsH2.style.borderWidth = "1px 0";
refsH2.style.fontSize = "100%";
refsH2.style.fontWeight = "100%";
refsH2.style.lineHeight = "normal";
refsH2.style.margin = "0";
refsH2.style.padding = "0.5em 0 0";
refsH2.style.textAlign = "center";
// Inline refs textbox
refsTextbox = window.document.createElement("textarea");
refsTextbox.id = "PsRefsTextbox";
if(!complete) {
refsTextbox.value = messages.refsCommentIncomplete +
segFormat.refCodes.join("\n\n");
} else {
refsTextbox.value = segFormat.refCodes.join("\n\n");
}
refsTextbox.rows = Math.floor(mainTextbox.rows / 2);
refsTextbox.cols = mainTextbox.cols;
refsTextbox.style.border = "none";
refsTextbox.style.lineHeight = "1.5em";
refsTextbox.style.margin = "0";
refsTextbox.style.resize = "vertical";
refsTextbox.style.width = "100%";
// wikEd compatibility (frame -> textarea)
// Add to document
if(typeof wikEdUseWikEd != "undefined" && wikEdUseWikEd) {
refsDiv.appendChild(refsH2);
WikEdUpdateTextarea();
refsDiv.appendChild(refsTextbox);
}
// Set up the submit handler (to integrate refs when done editing)
// Do the actual segregation work and save the random prefix
window.addEventListener("submit", unloadHandler, false);
var segFormat = segregateRefs(mainTextbox.value, "", true);
window.addEventListener("unload", unloadHandler, false);
if(!segFormat) {
unloadHandlerRegistered = true;
return false;
}
// Don't submit form
randPrefix = segFormat.randPrefix;
return false;
// Update the textbox
mainTextbox.value = segFormat.wikiText;
clearUndoHistory(mainTextbox);
// wikEd compatibility (textarea -> frame)
if(typeof wikEdUseWikEd != "undefined" && wikEdUseWikEd) {
WikEdUpdateFrame();
}
// Inline refs header
refsH2 = document.createElement("h2");
refsH2.appendChild(document.createTextNode(messages.refsHeader));
refsH2.style.borderColor = "silver";
refsH2.style.borderStyle = "solid";
refsH2.style.borderWidth = "1px 0";
refsH2.style.fontSize = "100%";
refsH2.style.fontWeight = "100%";
refsH2.style.lineHeight = "normal";
refsH2.style.margin = "0";
refsH2.style.padding = "0.5em 0 0";
refsH2.style.textAlign = "center";
// Inline refs textbox
refsTextbox = document.createElement("textarea");
refsTextbox.id = "PsRefsTextbox";
refsTextbox.value = segFormat.refCodes.join("\n\n");
refsTextbox.rows = 12;
refsTextbox.style.border = "none";
refsTextbox.style.lineHeight = "1.5em";
refsTextbox.style.margin = "0";
refsTextbox.style.resize = "vertical";
refsTextbox.style.width = "100%";
// Add to document
refsDiv.appendChild(refsH2);
refsDiv.appendChild(refsTextbox);
// Set up the submit handler (to integrate refs when done editing)
window.addEventListener("submit", unloadHandler, false);
window.addEventListener("unload", unloadHandler, false);
unloadHandlerRegistered = true;
// Don't submit form
return false;
}
function convertButtonHandler() { // Called when script activated by button click
// Display warning
if(!window.confirm(messages.convertRefsWarning)) {
return false;
}
}
// Which group?
var group = window.prompt(messages.groupPrompt, "");
if(group === null) {
return false;
}
}
group = htmlUnquote(group);
// The first button should disappear
if(refsButton.parentNode) {
refsButton.parentNode.removeChild(refsButton);
}
}
// Do the actual segregation work and save the random prefix
var segFormat = segregateRefs(mainTextbox.value, true, group, false);
if(!segFormat) {
return false;
}
}
randPrefix = segFormat.randPrefix;
// wikEd compatibility (frame -> textarea)
if(typeof wikEdUseWikEd != "undefined" && wikEdUseWikEd) {
WikEdUpdateTextarea();
}
}
// Update the textbox
mainTextbox.value = segFormat.wikiText;
clearUndoHistory(mainTextbox);
// wikEd compatibility (textarea -> frame)
if(typeof wikEdUseWikEd != "undefined" && wikEdUseWikEd) {
WikEdUpdateFrame();
}
}
// Inline refs header
refsH2 = window.document.createElement("h2");
refsH2.appendChild(window.document.createTextNode(messages.convertHeader));
refsH2.style.borderColor = "silver";
refsH2.style.borderStyle = "solid";
refsH2.style.borderWidth = "1px 0";
refsH2.style.fontSize = "100%";
refsH2.style.fontWeight = "100%";
refsH2.style.lineHeight = "normal";
refsH2.style.margin = "0";
refsH2.style.padding = "0.5em 0 0";
refsH2.style.textAlign = "center";
// Inline refs textbox
if(!refsTextbox) {
// Does not exist; creating
refsTextbox = window.document.createElement("textarea");
refsTextbox.id = "PsRefsTextbox";
refsTextbox.value = messages.refsCommentComplete +
segFormat.refCodes.join("\n");
refsTextbox.rows = Math.floor(mainTextbox.rows / 2)12;
refsTextbox.cols = mainTextbox.cols;
refsTextbox.style.border = "none";
refsTextbox.style.lineHeight = "1.5em";
refsTextbox.style.margin = "0";
refsTextbox.style.resize = "vertical";
refsTextbox.style.width = "100%";
// Add to document
refsDiv.appendChild(refsH2);
refsDiv.appendChild(refsTextbox);
} else {
// Already exists
refsTextbox.value = messages.refsCommentComplete +
segFormat.refCodes.join("\n");
}
}
// Set a default edit summary.
window. document.getElementById("wpSummary").value = messages.convertSummary;
// Show the further instructions.
window.alert(messages.convertFurther);
// Don't submit form
return false;
}
function getEditboxContents() { // ajaxPreview compatibility
if(unloadHandlerRegistered) {
// wikEd compatibility (frame -> textarea)
if(typeof wikEdUseWikEd != "undefined" && wikEdUseWikEd) {
WikEdUpdateTextarea();
}
return integrateRefs(mainTextbox.value, refsTextbox.value,
randPrefix, complete).wikiText;
} else {
return mainTextbox.value;
}
}
$( function () {
// Leave a global for ajaxPreview to use.
window.getEditboxContents = getEditboxContents;
try {
// Handle message translations
function loadHandler() { // This function is called on page load
messages = (typeof SegregateRefsJsL10n == "object" &&
try {
typeof SegregateRefsJsL10n.version != "undefined" &&
SegregateRefsJsL10n.version == 1.11 ? SegregateRefsJsL10n :
if( !window.addEventListener ) {
SegregateRefsJsMsgs);
return;
}
// Only activate on edit pages (that are not section edit pages)
if(!document.getElementById("editform") ||
// Handle message translations
document.getElementById("editform").wpSection.value.length) {
messages = (typeof SegregateRefsJsL10n == "object" &&
return;
typeof SegregateRefsJsL10n.version != "undefined" &&
}
SegregateRefsJsL10n.version == 1.11 ? SegregateRefsJsL10n :
SegregateRefsJsMsgs);
// Get the edit form
editForm = document.getElementById("editform");
// Only activate on edit pages (that are not section edit pages)
// Get the edit box
if(!window.document.getElementById("editform") ||
mainTextbox = window.document.getElementById("editformwpTextbox1").wpSection.value.length) {;
return;
// Make the "segregate" button
}
refsButton = document.createElement("input");
refsButton.type = "button";
// Get the edit form
refsButton.value = messages.buttonText;
editForm = window.document.getElementById("editform");
refsButton.setAttribute("style", messages.buttonStyle);
// Get the edit box
refsButton.onclick = refsButtonHandler;
mainTextbox = window.document.getElementById("wpTextbox1");
// Make the "segregateconvert" button
refsButton convertButton = window.document.createElement("input");
refsButton convertButton.type = "button";
refsButton convertButton.value = messages.buttonTextbuttonConvertText;
refsButton convertButton.setAttribute("style", messages.buttonStylebuttonConvertStyle);
refsButton convertButton.onclick = refsButtonHandlerconvertButtonHandler;
if(typeof SegregateRefsJsAllowConversion == "undefined" ||
// Make the "convert" button
!SegregateRefsJsAllowConversion) {
convertButton = window.document.createElement("input");
convertButton.typesetAttribute("style", ="display: none;"button");
}
convertButton.value = messages.buttonConvertText;
convertButton.setAttribute("style", messages.buttonConvertStyle);
// Add the refs div
convertButton.onclick = convertButtonHandler;
refsDiv = document.createElement("div");
refsDiv.appendChild(refsButton);
if(typeof SegregateRefsJsAllowConversion == "undefined" ||
refsDiv.appendChild(convertButton);
!SegregateRefsJsAllowConversion) {
// Find position within the edit form to insert it at
convertButton.setAttribute("style", "display: none;");
var refsDivPos = mainTextbox, refsDivPosParent = refsDivPos.parentNode;
}
while (refsDivPosParent !== editForm) {
refsDivPos = refsDivPosParent;
// Add the refs div
refsDivPosParent = refsDivPos.parentNode;
refsDiv = window.document.createElement("div");
if (!refsDivPosParent) {
refsDiv.appendChild(refsButton);
refsDivPos = mainTextbox;
refsDiv.appendChild(convertButton);
refsDivPosParent = refsDivPos.parentNode;
mainTextbox.parentNode.insertBefore(refsDiv, mainTextbox.nextSibling);
break;
} catch(e) {
}
}
}
refsDivPos = refsDivPos.nextSibling;
if (refsDivPos && refsDivPos.classList.contains("wikiEditor-ui-clear")) {
refsDivPos = refsDivPos.nextSibling;
}
refsDivPosParent.insertBefore(refsDiv, refsDivPos);
} catch(e) {
}
} );
// Register document ready handler
$j(loadHandler);
})( jQuery );
// </nowiki></pre>
|