বিষয়বস্তুতে চলুন

ব্যবহারকারী:রবি/common.js: সংশোধিত সংস্করণের মধ্যে পার্থক্য

ভারতপিডিয়া থেকে
রবি (আলোচনা | অবদান)
রবি (আলাপ)-এর সম্পাদিত 63052 নম্বর সংশোধনটি বাতিল করা হয়েছে
রবি (আলোচনা | অবদান)
সম্পাদনা সারাংশ নেই
৪,৫৬৮ নং লাইন: ৪,৫৬৮ নং লাইন:


$(document).ready(AJAXPreview.onLoad);
$(document).ready(AJAXPreview.onLoad);
// vim: ts=4 sw=4 et
//<nowiki>
function loadReplyLink( $, mw, isOnSectionWatchlistPage ) {
    var TIMESTAMP_REGEX = /\(UTC(?:(?:−|\+)\d+?(?:\.\d+)?)?\)\S*?\s*$/m;
    var EDIT_REQ_REGEX = /^((Semi|Template|Extended-confirmed)-p|P)rotected edit request on \d\d? \w+ \d{4}/;
    var EDIT_REQ_TPL_REGEX = /\{\{edit (template|fully|extended|semi)-protected\s*(\|.+?)*\}\}/;
    var LITERAL_SIGNATURE = "~~" + "~~"; // split up because it might get processed
    var i18n = {
        "en": {
            "rl-advert": " (using [[w:en:User:Enterprisey/reply-link|reply-link]])",
            "rl-error-status": "There was an error while replying! Please leave a note at " +
                "<a href='https://en.wikipedia.org/wiki/User_talk:Enterprisey/reply-link'>the script's talk page</a>" +
                " with any errors in <a href='https://en.wikipedia.org/wiki/WP:JSERROR'>the browser console</a>, if possible.",
            "rl-replying-to": "Replying to ",
            "rl-reloading": "automatically reloading",
            "rl-reload": "Reload",
            "rl-saved": "Reply saved!",
            "rl-cancel": "cancel ",
            "rl-placeholder": "Reply here!",
            "rl-reply": "Reply",
            "rl-preview": "Preview",
            "rl-cancel-button": "Cancel",
            "rl-started-reply": "You've started a reply but haven't posted it",
            "rl-loading": "Loading...",
            "rl-reply-label": "reply",
            "rl-to-label": " to ",
            "rl-auto-indent": "Automatically indent?",
            "rl-out-of-date": "Someone has edited this page since you started replying!",
            "rl-edit-fail": "While replying, the edit failed."
        },
        "pt": {
            "rl-advert": "(usando [[w:en:User:Enterprisey/reply-link|reply-link]])",
            "rl-error-status": "Ocorreu um erro ao responder! Por favor deixe um comentário na " +
                "<a href='https://en.wikipedia.org/wiki/User_talk:Enterprisey/reply-link'>página de discussão do script</a>" +
                " informando os erros que apareçam <a href='https://en.wikipedia.org/wiki/WP:JSERROR'>no console do navegador</a>, se possível.",
            "rl-replying-to": "Respondendo a ",
            "rl-reloading": "recarregando automaticamente",
            "rl-reload": "Recarregar",
            "rl-saved": "Resposta publicada!",
            "rl-cancel": "cancelar ",
            "rl-placeholder": "Responda aqui!",
            "rl-reply": "Responder",
            "rl-preview": "Prever",
            "rl-cancel-button": "Cancelar",
            "rl-started-reply": "Você começou a responder, mas não publicou sua resposta",
            "rl-loading": "Carregando...",
            "rl-reply-label": "responder",
            "rl-to-label": " a ",
            "rl-auto-indent": "Indentar automaticamente?"
        }
    };
    var HEADER_SELECTOR = "h1,h2,h3,h4,h5,h6";
    var MAX_UNICODE_DECIMAL = 1114111;
    var HEADER_REGEX = /^\s*=(=*)\s*(.+?)\s*\1=\s*(?:<!--.+?-->\s*)?$/gm;
    var JUMP_COOKIE_KEY = "reply_link_jump";
    // T:TDYK, used at the end of loadReplyLink
    var TTDYK = "Template:Did_you_know_nominations";
    var RFA_PG = "Wikipedia:Requests_for_adminship/";
    // Threshold for indentation when we offer to outdent
    var OUTDENT_THRESH = 8;
    // All of the interface message keys that we explicitly load
    var INT_MSG_KEYS = [ "mycontris" ];
    // Date format regexes in signatures (i.e. the "default date format")
    var DATE_FMT_RGX = {
        "//en.wikipedia.org": /\d\d:\d\d,\s\d{1,2}\s\w+?\s\d{4}/.source,
        "//test.wikipedia.org": /\d\d:\d\d,\s\d{1,2}\s\w+?\s\d{4}/.source,
        "//simple.wikipedia.org": /\d\d:\d\d,\s\d{1,2}\s\w+?\s\d{4}/.source,
        "//en.wikisource.org": /\d\d:\d\d,\s\d{1,2}\s\w+?\s\d{4}/.source,
        "//meta.wikimedia.org": /\d\d:\d\d,\s\d{1,2}\s\w+?\s\d{4}/.source,
        "//pt.wikipedia.org": /\d\dh\d\dmin\sde \d{1,2} de \w+? de \d{4}/.source,
        "//commons.wikimedia.org": /\d\d:\d\d,\s\d{1,2}\s\w+?\s\d{4}/.source
    }
    // Shared API object
    var api;
    /*
    * Regex *sources* for a "userspace" link. Basically the
    * localized equivalent of User( talk)?|Special:Contributions/
    * Initialized in buildUserspcLinkRgx, which is called near the top
    * of the closure in handleWrapperClick.
    *
    * Three subproperties: und for underscores instead of spaces (e.g.
    * "User_talk"), spc for spaces (e.g. "User talk"), and both for
    * a regex combining the two (used for matching on wikitext).
    */
    var userspcLinkRgx = null;
    /**
    * This dictionary is some global state that holds a dictionary
    * for each "(reply)" link (keyed by their unique IDs):
    *
    *  - indentation, the indentation string for the comment (e.g. ":*::")
    *  - sigIdx, the zero-based index of the signature from the top
    *    of the section
    *
    * This dictionary is populated in attachLinks, and unpacked in the
    * click handler for the links (defined in attachLinkAfterNode); the
    * values are then passed to doReply.
    */
    var metadata = {};
    /**
    * This global string flag is:
    *
    *  - "AfD" if the current page is an AfD page
    *  - "MfD" if the current page is an MfD page
    *  - "TfD" if the current page is a TfD log page
    *  - "CfD" if the current page is a CfD log page
    *  - "FfD" if the current page is a FfD log page
    *  - "" otherwise
    *
    * This flag is initialized in onReady and used in attachLinkAfterNode
    */
    var xfdType;
    /**
    * The current page name, including namespace, because we may be reading it
    * a lot (especially in findUsernameInElem if we're on someone's user
    * talk page). Has underscores instead of spaces!
    */
    var currentPageName;
    /**
    * A map for signatures that contain redirects, so that they can still
    * pass the sanity check. This will be updated manually, because I
    * don't want the overhead of a whole 'nother API call in the middle
    * of the reply process. If this map grows too much, though, I'll
    * consider switching to either a toolforge-hosted API or the
    * Wikipedia API. Used in doReply, for the username sanity check.
    */
    var sigRedirectMapping = {
        "Salvidrim": "Salvidrim!"
    };
    /**
    * When the reply is saved via API, this flag is set to true to
    * disable the onbeforeunload handler.
    */
    var replyWasSaved = false;
    /**
    * Cache for getWikitext.
    */
    var getWikitextCache = {};
    // Polyfill from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
    if( !String.prototype.includes ) {
        String.prototype.includes = function( search, start ) {
            if( search instanceof RegExp ) {
                throw TypeError('first argument must not be a RegExp');
            }
            if( start === undefined ) {
                start = 0;
            }
            return this.indexOf( search, start ) !== -1;
        };
    }
    /**
    * Get the formatted namespace name for a namespace ID.
    * Quick ref: user = 2, proj = 4
    */
    function fmtNs( nsId ) {
        return mw.config.get( "wgFormattedNamespaces" )[ nsId ];
    }
    /**
    * Escapes a string for inclusion in a regex.
    */
    function escapeForRegex( s ) {
        return s.replace( /[-\/\\^$*+?.()|[\]{}]/g, '\\$&' );
    }
    /*
    * MediaWiki turns spaces before certain punctuation marks
    * into non-breaking spaces, so fix those. This is done by
    * the armorFrenchSpaces function in Mediawiki, in the file
    * /includes/parser/Sanitizer.php
    */
    function deArmorFrenchSpaces( text ) {
        return text.replace( /\xA0([?:;!%»›])/g, " $1" )
            .replace( /([«‹])\xA0/g, "$1 " );
    }
    /**
    * Remove duplicates from an array.
    * https://stackoverflow.com/a/9229821/1757964
    */
    function removeDuplicates( array ) {
        var seen = {};
        return array.filter( function( item ) {
            return seen.hasOwnProperty( item ) ? false : ( seen[ item ] = true );
        } );
    }
    /**
    * Capitalize the first letter of a string.
    */
    function capFirstLetter( someString ) {
        return someString.charAt( 0 ).toUpperCase() + someString.slice( 1 );
    }
    /**
    * Namespace name to ID.
    * For example, nsNameToId( "Template" ) === 10.
    */
    function nsNameToId( nsName ) {
        return mw.config.get( "wgNamespaceIds" )[ nsName.toLowerCase().replace( / /g, "_" ) ];
    }
    /**
    * Canonical-ize a namespace.
    */
    function canonicalizeNs( ns ) {
        return fmtNs( nsNameToId( ns ) );
    }
    /**
    * This function converts any (index-able) iterable into a list.
    */
    function iterableToList( nl ) {
        var len = nl.length;
        var arr = new Array( len );
        for( var i = 0; i < len; i++ ) arr[i] = nl[i];
        return arr;
    }
    /**
    * Process HTML character entities.
    * From https://stackoverflow.com/a/46851765
    */
    function processCharEntities( text ) {
        var el = document.createElement('div');
        return text.replace( /\&[#0-9a-z]+;/gi, function ( enc ) {
            el.innerHTML = enc;
            return el.innerText
        } );
    }
    /**
    * Process HTML character entities, MediaWiki style
    * From https://stackoverflow.com/a/46851765
    */
    function processCharEntitiesWikitext( text ) {
        var el = document.createElement('div');
        return text.replace( /\&[#0-9a-z]+;/gi, function ( enc ) {
            if( /#\d+/.test( enc ) ) {
                if( parseInt( enc.slice( 1 ) ) > MAX_UNICODE_DECIMAL ) {
                    return enc;
                }
            }
            el.innerHTML = enc;
            return el.innerText
        } );
    }
    /**
    * When there's a panel being shown, this function sets the status
    * in the panel to the first argument. The callback function is
    * optional.
    */
    function setStatus ( status, callback ) {
        var statusElement = $( "#reply-dialog-status" );
        statusElement.fadeOut( function () {
            statusElement.html( status ).fadeIn( callback );
        } );
    }
    /**
    * Sets the panel status when an error happened. Good for use in
    * catch blocks.
    */
    function setStatusError( e ) {
        console.error(e);
        setStatus( mw.msg( "rl-error-status" ) );
        if( e.message ) {
            console.log( "Content request error: " + JSON.stringify( e.message ) );
        }
        console.log( "DEBUG INFORMATION: '"+currentPageName+"' @ " + mw.config.get( "wgCurRevisionId" ) );
        throw e;
    }
    /**
    * Given some wikitext, processes it to get just the text content.
    * This function should be identical to the MediaWiki function
    * that gets the wikitext between the equal signs and comes up
    * with the id's that anchor the headers.
    */
    function wikitextToTextContent( wikitext ) {
        return processCharEntities( wikitext )
            .replace( /\[\[:?(?:[^\|\]]+?\|)?([^\]\|]+?)\]\]/g, "$1" )
            .replace( /\{\{\s*tl\s*\|\s*(.+?)\s*\}\}/g, "{{$1}}" )
            .replace( /\{\{\s*[Uu]\s*\|\s*(.+?)\s*\}\}/g, "$1" )
            .replace( /('''?)(.+?)\1/g, "$2" )
            .replace( /<s>(.+?)<\/s>/g, "$1" )
            .replace( /<big>(.+?)<\/big>/g, "$1" )
            .replace( /<span.*?>(.*?)<\/span>/g, "$1" );
    }
    function wikitextHeaderEqualsDomHeader( wikitextHeader, domHeader ) {
        return wikitextToTextContent( wikitextHeader ) === deArmorFrenchSpaces( domHeader );
    }
    /**
    * Finds and returns the div that is the immediate parent of the
    * first talk page header on the page, so that we can read all the
    * sections by iterating through its child nodes.
    */
    function findMainContentEl() {
        // Which header are we looking for?
        var targetHeader = "h2";
        if( xfdType || currentPageName.startsWith( RFA_PG ) ) targetHeader = "h3";
        if( currentPageName.startsWith( TTDYK ) ) targetHeader = "h4";
        // The element itself will be the text span in the h2; its
        // parent will be the h2; and the parent of the h2 is the
        // content container that we want
        var candidates = document.querySelectorAll( targetHeader + " > span.mw-headline" );
        if( !candidates.length ) {
            return document.getElementById( "mw-content-text" );
        }
        var candidate = candidates[ candidates.length - 1 ].parentElement.parentElement;
        // Compatibility with User:Kephir/gadgets/unclutter.js
        if( candidate.className.includes( "kephir-unclutter-discussion-wrapper" ) ) {
            candidate = candidate.parentElement;
        }
        // Compatibility with User:Enterprisey/hover-edit-section
        // That script puts each section in its own div, so we need to
        // go out another level if it's running
        if( candidate.className === "hover-edit-section" ) {
            candidate = candidate.parentElement;
        }
        return candidate;
    }
    /**
    * Gets the wikitext of a page with the given title (namespace required).
    * Returns an object with keys "content" and "timestamp".
    */
    function getWikitext( title, useCaching ) {
        if( useCaching === undefined ) useCaching = false;
        if( useCaching && getWikitextCache[ title ] ) {
            return $.when( getWikitextCache[ title ] );
        }
        return $.getJSON(
            mw.util.wikiScript( "api" ),
            {
                format: "json",
                action: "query",
                prop: "revisions",
                rvprop: "timestamp|content|ids",
                rvslots: "main",
                rvlimit: 1,
                titles: title,
                formatversion: 2,
            }
        ).then( function ( data ) {
            if( data.query.pages[0].revisions ) {
                var rev = data.query.pages[0].revisions[0];
                var result = { revId: rev.revid, timestamp: rev.timestamp, content: rev.slots.main.content };
                getWikitextCache[ title ] = result;
                return result;
            } else {
                console.error( data );
                throw new Error( "[getWikitext] bad response: " + data );
                return {};
            }
        } );
    }
    function getLastRevId( title ) {
        return $.getJSON(
            mw.util.wikiScript( "api" ),
            {
                format: "json",
                action: "query",
                prop: "revisions",
                rvprop: "ids",
                rvslots: "main",
                rvlimit: 1,
                titles: title,
                formatversion: 2,
            }
        ).then( function ( data ) {
            return data.query.pages[0].revisions[0].revid;
        } );
    }
    function getPathToElement( givenEl ) {
        var path = [];
        var currEl = givenEl;
        while( ( currEl.id !== "mw-content-text" ) && ( currEl.tagName.toLowerCase() !== "body" ) ) {
            path.push( iterableToList( currEl.parentNode.children ).indexOf( currEl ) );
            currEl = currEl.parentNode;
        }
        return path.join( "|" );
    }
    function followPathToElement( path ) {
        path = path.split( "|" );
        var el = document.getElementById( "mw-content-text" );
        for( var i = path.length - 1; i >= 0; i-- ) {
            el = el.children[parseInt(path[i])];
        }
        return el;
    }
    function highlightContainerOf( el ) {
        outer:
        while( true ) {
            switch( el.tagName.toLowerCase() ) {
                case "ul":
                case "ol":
                case "li":
                case "dd":
                case "dl":
                case "p":
                case "div":
                case "table":
                case "td":
                    break outer;
            }
            el = el.parentNode;
        }
        el.className += "reply-link-jump-highlight";
    }
    function getTimestampGivenAuthorLink( authorLink ) {
        var currNode = authorLink;
        // The .localcomments element check is for compatibilty with the [[WP:Comments in Local Time]] gadget
        while( !currNode.textContent.includes( "(UTC)" ) && ( currNode.className !== "localcomments" ) ) {
            if( currNode.nextSibling ) {
                currNode = currNode.nextSibling;
            } else {
                currNode = currNode.parentNode;
            }
        }
        if( currNode.textContent.includes( "(UTC)" ) ) {
            var matches = currNode.textContent.match( new RegExp( DATE_FMT_RGX[mw.config.get( "wgServer" )], "g" ) );
            if( matches.length > 0 ) {
                return matches[ matches.length - 1 ];
            }
        } else if( currNode.className === "localcomments" ) {
            var matches = currNode.getAttribute( "title" ).match( new RegExp( DATE_FMT_RGX[mw.config.get( "wgServer" )], "g" ) );
            if( matches.length > 0 ) {
                return matches[ matches.length - 1 ];
            }
        }
        return null;
    }
    /**
    * Creates userspcLinkRgx. Called in handleWrapperClick and the test
    * runner at the bottom.
    */
    function buildUserspcLinkRgx() {
        if( userspcLinkRgx ) {
            return;
        }
        var nsIdMap = mw.config.get( "wgNamespaceIds" );
        var nsRgxFragments = [];
        var contribsSecondFrag = ":" + escapeForRegex( mw.messages.get( "mycontris" ) ) + "\\/";
        for( var nsName in nsIdMap ) {
            if( !nsIdMap.hasOwnProperty( nsName ) ) continue;
            switch( nsIdMap[nsName] ) {
                case 2:
                case 3:
                    nsRgxFragments.push( escapeForRegex( capFirstLetter( nsName ) ) + "\\s*:" );
                    break;
                case -1:
                    nsRgxFragments.push( escapeForRegex( capFirstLetter( nsName ) ) + contribsSecondFrag );
                    break;
            }
        }
        userspcLinkRgx = {};
        userspcLinkRgx.spc = "(?:" + nsRgxFragments.join( "|" ).replace( /_/g, " " ) + ")";
        userspcLinkRgx.und = userspcLinkRgx.spc.replace( / /g, "_" );
        userspcLinkRgx.both = userspcLinkRgx.spc.replace( / /g, "(?: |_)" );
    }
    /**
    * Is there a signature (four tildes) present in the given text,
    * outside of a nowiki element?
    */
    function hasSig( text ) {
        // no literal signature?
        if( !text.includes( LITERAL_SIGNATURE ) ) return false;
        // if there's a literal signature and no nowiki elements,
        // there must be a real signature
        if( !text.includes( "<nowiki>" ) ) return true;
        // Save all nowiki spans
        var nowikiSpanStarts = []; // list of ignored span beginnings
        var nowikiSpanLengths = []; // list of ignored span lengths
        var NOWIKI_RE = /<nowiki>.*?<\/nowiki>/g;
        var spanMatch;
        do {
            spanMatch = NOWIKI_RE.exec( text );
            if( spanMatch ) {
                nowikiSpanStarts.push( spanMatch.index );
                nowikiSpanLengths.push( spanMatch[0].length );
            }
        } while( spanMatch );
        // So that we don't check every ignore span every time
        var nowikiSpanStartIdx = 0;
        var LIT_SIG_RE = new RegExp( LITERAL_SIGNATURE, "g" );
        var sigMatch;
        matchLoop:
        do {
            sigMatch = LIT_SIG_RE.exec( text );
            if( sigMatch ) {
                // Check that we're not inside a nowiki
                for( var nwIdx = nowikiSpanStartIdx; nwIdx <
                    nowikiSpanStarts.length; nwIdx++ ) {
                    if( sigMatch.index > nowikiSpanStarts[nwIdx] ) {
                        if ( sigMatch.index + sigMatch[0].length <=
                            nowikiSpanStarts[nwIdx] + nowikiSpanLengths[nwIdx] ) {
                            // Invalid sig
                            continue matchLoop;
                        } else {
                            // We'll never encounter this span again, since
                            // headers only get later and later in the wikitext
                            nowikiSpanStartIdx = nwIdx;
                        }
                    }
                }
                // We aren't inside a nowiki
                return true;
            }
        } while( sigMatch );
        return false;
    }
    /**
    * Given an Element object, attempt to recover a username from it.
    * Also will check up to two elements prior to the passed element.
    * Returns null if no username was found. Otherwise, returns an
    * object with these properties:
    *
    *  - username: The username that we found.
    *  - link: The DOM element for the link from which we got the
    *    username.
    */
    function findUsernameInElem( el ) {
        if( !el ) return null;
        var links;
        for( let i = 0; i < 3; i++ ) {
            if( el === null ) break;
            links = el.tagName.toLowerCase() === "a" ? [ el ]
                : el.querySelectorAll( "a" );
            //console.log(i,"top of outer for in findUsernameInElem ",el, " links -> ",links);
            // Compatibility with "Comments in Local Time"
            if( el.className.includes( "localcomments" ) ) i--;
            // If we couldn't get any links, try again with prev elem
            if( !links ) continue;
            var link; // his name isn't zelda
            for( var j = 0; j < links.length; j++ ) {
                link = links[j];
                //console.log(link,decodeURIComponent(link.getAttribute("href")));
                if( link.className.includes( "mw-selflink" ) ) {
                    return { username: currentPageName.replace( /.+:/, "" )
                        .replace( /_/g, " " ), link: link };
                }
                // Also matches redlinks. Why people have redlinks in their sigs on
                // purpose, I may never know.
                //console.log( "^\\/(?:wiki\\/" + userspcLinkRgx.und + /(.+?)(?:\/.+?)?(?:#.+)?|w\/index\.php\?title=User(?:_talk)?:(.+?)&action=edit&redlink=1/.source + ")$" )
                var sigLinkRe = new RegExp( "\\/(?:wiki\\/" + userspcLinkRgx.und + /(.+?)(?:\/.+?)?(?:#.+)?|w\/index\.php\?title=/.source + userspcLinkRgx.und + /(.+?)&action=edit&redlink=1/.source + ")$" );
                var liveDecodedHref = decodeURIComponent( link.getAttribute( "href" ) );
                if( liveDecodedHref.startsWith( "/" ) ) {
                    liveDecodedHref = "https:" + mw.config.get( "wgServer" ) + liveDecodedHref;
                }
                var usernameMatch = sigLinkRe.exec( liveDecodedHref );
                if( usernameMatch ) {
                //console.log("usernameMatch",usernameMatch)
                    var rawUsername = usernameMatch[1] ? usernameMatch[1] : usernameMatch[2];
                    return {
                        username: decodeURIComponent( rawUsername ).replace( /_/g, " " ),
                        link: link
                    };
                }
            }
            // Go backwards one element and try again
            el = el.previousElementSibling;
        }
        return null;
    }
    /**
    * Given a reply-link-wrapper span, attempts to find who wrote
    * the comment that precedes it. For information about the return
    * value, see the documentation for findUsernameInElem.
    */
    function getCommentAuthor( wrapper ) {
        var sigNode = wrapper.previousSibling;
        //console.log(sigNode,sigNode.style,sigNode.style ? sigNode.style.getPropertyValue("size"):"");
        var smallOrFake = sigNode.nodeType === 1 &&
                ( sigNode.tagName.toLowerCase() === "small" ||
                ( sigNode.tagName.toLowerCase() === "span" &&
                    sigNode.style && ( sigNode.style.getPropertyValue( "font-size" ) === "85%" ||
                                      sigNode.style.getPropertyValue( "font-size" ).indexOf( "small" ) === 0 ) ) );
        var possUserLinkElem = ( smallOrFake && sigNode.children.length > 1 )
            ? sigNode.children[sigNode.children.length-1]
            : sigNode.previousElementSibling;
        return findUsernameInElem( possUserLinkElem );
    }
    /**
    * Given the wikitext of a section, attempt to find the first edit
    * request template in it, and then mark that template as answered.
    * Returns the modified section wikitext.
    */
    function markEditReqAnswered( sectionWikitext ) {
        var editReqMatch = EDIT_REQ_TPL_REGEX.exec( sectionWikitext );
        if( !editReqMatch ) {
            console.error( "Couldn't find an edit request!" );
            return sectionWikitext;
        }
        var ansParamMatch = /ans(wered)?=.*?(\||\}\})/.exec( editReqMatch[0] );
        if( !ansParamMatch ) {
            sectionWikitext = sectionWikitext.replace(
                editReqMatch[0],
                editReqMatch[0].replace( "}}", "answered=yes}}" )
            );
        } else {
            var newEditReqTpl = editReqMatch[0].replace( ansParamMatch[0],
                "answered=yes" + ansParamMatch[2] );
            sectionWikitext = sectionWikitext.replace(
                editReqMatch[0],
                newEditReqTpl
            );
        }
        return sectionWikitext;
    }
    function allContentHeaders() {
        var allHeaders = document.querySelector( "#mw-content-text" )
            .querySelectorAll( HEADER_SELECTOR );
        return iterableToList( allHeaders )
            .filter( function ( header ) {
                // The word "Contents" at the top of the table of contents is a heading
                return ( header.getAttribute( "id" ) !== "mw-toc-heading" );
            } );
    }
    /**
    * Given a header element, finds the title (full with namespace, spaces
    * instead of underscores) of the page it's from.
    */
    function pageNameOfHeader( header ) {
        var editLinks = iterableToList( header.querySelectorAll( ".mw-editsection a" ) )
            .filter( function ( e ) { return e.textContent.indexOf( "edit" ) === 0; } );
        if( editLinks.length ) {
            var encoded = editLinks[0]
                .getAttribute( "href" )
                .match( /title=(.+?)(?:$|&)/ )
                [1];
            return decodeURIComponent( encoded ).replace( /_/g, " " );
        } else {
            return null;
        }
    }
    /**
    * Given a DOM object in the current page corresponding to a link in a
    * signature, locate the section header (i.e. h1, h2, etc element) for the
    * section containing that comment.
    */
    function findSectionHeaderElement( sigLinkElem ) {
        var nearestHeader = null;
        var currElem = sigLinkElem;
        var sigLinkTopPos = sigLinkElem.getBoundingClientRect().top;
        loop:
        while( ( currElem.id !== "mw-content-text" ) && ( currElem.tagName.toLowerCase() !== "body" ) ) {
            var familiarTagName = false;
            switch( currElem.tagName.toLowerCase() ) {
                case "ul":
                case "ol":
                case "li":
                case "dd":
                case "dl":
                case "a":
                case "i":
                case "code":
                    // Headers aren't in these elements (and it would be a waste to check)
                    break;
                case "h1":
                case "h2":
                case "h3":
                case "h4":
                case "h5":
                case "h6":
                    // Well, that was convenient (found a header)
                    nearestHeader = currElem;
                    break loop;
                case "p":
                case "span": // unlikely, but we'll check anyway
                case "div":
                case "table": // yeah, sometimes people put their whole talk page in a template
                case "td":
                case "sub":
                case "sup":
                case "b":
                    familiarTagName = true;
                default:
                    var tagName = currElem.tagName.toLowerCase();
                    if( !familiarTagName ) {
                        // just in case there's a tag not listed here that needs special handling
                        console.warn( "unknown tag name ", tagName, " ", currElem );
                    }
                    var childHeaders = currElem.querySelectorAll( HEADER_SELECTOR );
                    if( childHeaders ) {
                        childHeaders = iterableToList( childHeaders )
                            .filter( function ( header ) {
                                // We don't want to pick up headers below the comment
                                return header.getBoundingClientRect().top < sigLinkTopPos;
                            } );
                        if( childHeaders.length > 0 ) {
                            nearestHeader = childHeaders[childHeaders.length - 1];
                            break loop;
                        }
                    }
                    break;
            } // end switch ( currElem.tagName )
            if( currElem.previousElementSibling ) {
                currElem = currElem.previousElementSibling;
            } else {
                currElem = currElem.parentNode;
            }
        } // end while
        if( nearestHeader === null ) {
            console.warn( "nearestHeader was null" );
        }
        return nearestHeader;
    }
    /**
    * Finds a section in the given page's wikitext.
    *
    * If givenHeaderEl is null, that means it's the "zeroth" section, i.e.
    * the section that ends at the first page header.
    */
function findSectionInPageWikitext( givenHeaderEl, pageTitle, pageWikitext ) {
        var allHeaders = document.querySelector( "#mw-content-text" )
            .querySelectorAll( HEADER_SELECTOR );
        var allHeadersFromTarget = iterableToList( allHeaders )
            .filter( function ( header ) {
                // The word "Contents" at the top of the table of contents is a heading
                return ( header.getAttribute( "id" ) !== "mw-toc-heading" ) &&
                    pageNameOfHeader( header ) === pageTitle;
            } );
        // Find all the headers in the wikitext
        // Save all ignored spans
        var ignoredSpanStarts = []; // list of ignored span beginnings
        var ignoredSpanLengths = []; // list of ignored span lengths
        var IGNORED_RE = /(?:<(nowiki|pre|noinclude|source)>[\s\S]*?<\/\1>)|<!--[\s\S]+?-->/g;
        var spanMatch;
        do {
            spanMatch = IGNORED_RE.exec( pageWikitext );
            if( spanMatch ) {
                ignoredSpanStarts.push( spanMatch.index );
                ignoredSpanLengths.push( spanMatch[0].length );
            }
        } while( spanMatch );
        // So that we don't check every ignore span every time
        var ignoredSpanStartIdx = 0;
        var headerMatches = [];
        var headerMatch;
        matchLoop:
        do {
            headerMatch = HEADER_REGEX.exec( pageWikitext );
            if( headerMatch ) {
                // Check that we're not inside a ignored span
                for( var ignoredIdx = ignoredSpanStartIdx; ignoredIdx <
                    ignoredSpanStarts.length; ignoredIdx++ ) {
                    if( headerMatch.index > ignoredSpanStarts[ignoredIdx] ) {
                        if ( headerMatch.index + headerMatch[0].length <=
                            ignoredSpanStarts[ignoredIdx] + ignoredSpanLengths[ignoredIdx] ) {
                            // Not a header, since we're inside a ignored span
                            continue matchLoop;
                        } else {
                            // We'll never encounter this span again, since
                            // headers only get later and later in the wikitext
                            ignoredSpanStartIdx = ignoredIdx;
                        }
                    }
                }
                headerMatches.push( headerMatch );
            }
        } while( headerMatch );
        // We'll use this dictionary to calculate the duplicate index
        var headersByText = {};
        for( var i = 0; i < headerMatches.length; i++ ) {
            // Group 2 of HEADER_REGEX is the header text
            var text = headerMatches[i][2];
            headersByText[text] = ( headersByText[text] || [] ).concat( i );
        }
        // allHeadersFromTarget should contain every header we found in the wikitext
        // (and more, if sourcePageName was transcluded multiple times)
        if( allHeadersFromTarget.length % headerMatches.length !== 0 ) {
            for( var i = 0; i < Math.max( allHeadersFromTarget.length, headerMatches.length ); i++ ) {
                console.error( i, allHeadersFromTarget[i], allHeadersFromTarget[i] && allHeadersFromTarget[i].textContent, headerMatches[i] );
            }
            throw new Error( "non-divisble header list lengths" );
        }
        if( givenHeaderEl === null ) {
            var sectionEndIdx = headerMatches[0] ? headerMatches[0].index : pageWikitext.length;
            return {
                title: "",
                dupIdx: 0,
                startIdx: 0,
                endIdx: sectionEndIdx,
                idxInDomHeaders: -1,
            };
        }
        var headerIdx = allHeadersFromTarget.indexOf( givenHeaderEl );
        if( headerIdx < 0 ) {
            console.error( 'givenHeaderEl', givenHeaderEl );
            console.error( 'allHeadersFromTarget', allHeadersFromTarget );
            throw new Error( "givenHeaderEl not in allHeadersFromTarget" );
        }
        var trueHeaderIdx = headerIdx % headerMatches.length;
        var headerText = headerMatches[trueHeaderIdx][2];
        // NOTE! The duplicate index is calculated relative to the
        // *wikitext* header matches (because that's how the backend
        // does it)! That is, if we have a page that includes two
        // headers, both called "a", and we transclude that page
        // twice, the result will be four headers called "a". But we
        // want to assign those four headers, respectively, the
        // duplicate indices of 0, 1, 0, 1. That's why we use
        // trueHeaderIdx here, not headerIdx.
        var dupIdx = headersByText[headerText].indexOf( trueHeaderIdx );
        var sectionStartIdx = headerMatches[trueHeaderIdx].index;
        var sectionEndIdx = headerMatches[trueHeaderIdx + 1]
                ? headerMatches[trueHeaderIdx + 1].index
                : pageWikitext.length;
        return {
            title: headerText,
            dupIdx: dupIdx,
            startIdx: sectionStartIdx,
            endIdx: sectionEndIdx,
            idxInDomHeaders: headerIdx,
        };
    }
    /**
    * Given a DOM object in the current page corresponding to a link in a
    * signature, locate the section containing that comment. That section may
    * not be in the current page!
    */
    function findSectionMain( sigLinkElem ) {
        var nearestHeader = findSectionHeaderElement( sigLinkElem );
        var pageTitle = ( nearestHeader ? pageNameOfHeader( nearestHeader ) : currentPageName ).replace( /_/g, " " );
        return getWikitext( pageTitle, /* useCaching */ true ).then( function ( revObj ) {
            var pageText = revObj.content;
            var sectionObj = findSectionInPageWikitext( nearestHeader, pageTitle, pageText );
            sectionObj.pageTitle = pageTitle;
            sectionObj.revObj = revObj;
            sectionObj.headerEl = nearestHeader;
            //sectionObj.level = parseInt( nearestHeader.tagName.substring( 1 ) ); // that is, cut off the "h" at the beginning
            return sectionObj;
        }, function ( err ) { throw new Error( err ); } );
    }
    /**
    * Converts a (zero-based) signature index to a pair of string indices into
    * the given section wikitext, indicating the start and the end of the
    * requested signature. The return value is an object with two properties,
    * "start" for the starting index and "end" for the ending index (i.e. the
    * index of the first character after the signature).
    *
    * Returns null if we couldn't find anything.
    */
    function sigIdxToStrIdx( sectionWikitext, sigIdx ) {
        //console.log( "In sigIdxToStrIdx, sigIdx = " + sigIdx );
        // There are certain regions that we skip while attaching links:
        //
        //  - Spans with the class delsort-notice
        //  - Divs with the class xfd-relist (and other divs)
        //
        // So, we grab the corresponding wikitext regions with regexes,
        // and store each region's start index in spanStartIndices, and
        // each region's length in spanLengths. Then, whenever we find a
        // signature with the right index, if it's included in one of
        // these regions, we skip it and move on.
        var spanStartIndices = [];
        var spanLengths = [];
        var DELSORT_SPAN_RE_TXT = /<small class="delsort-notice">(?:<small>.+?<\/small>|.)+?<\/small>/.source;
        var XFD_RELIST_RE_TXT = /<div class="xfd_relist"[\s\S]+?<\/div>(\s*|<!--.+?-->)*/.source;
        var SKIP_REGION_RE = new RegExp("(" + DELSORT_SPAN_RE_TXT + ")|(" +
            XFD_RELIST_RE_TXT + ")|(" +
            /<s>.+?<\/s>/.source + ")", // struck regions (I don't care about nested ones)
            "ig");
        var skipRegionMatch;
        while( ( skipRegionMatch = SKIP_REGION_RE.exec( sectionWikitext ) ) !== null ) {
            spanStartIndices.push( skipRegionMatch.index );
            spanLengths.push( skipRegionMatch[0].length );
        }
        // Also skip transclusions of {{tq}} and {{tq2}}. These transclusions
        // have a high chance of containing other templates, so instead search
        // for closing curly braces at the right nesting level with a counter.
        var TQ_START_RE = /\{\{\s*tq2?/g;
        var tqStartMatch;
        while( ( tqStartMatch = TQ_START_RE.exec( sectionWikitext ) ) !== null ) {
            var currentNestingLevel = 2; // two curly braces started the template
            var wikitextIdx = tqStartMatch.index + tqStartMatch[0].length;
            while( ( currentNestingLevel > 0 ) && ( wikitextIdx < sectionWikitext.length ) ) {
                if( sectionWikitext.charAt( wikitextIdx ) === "{" ) {
                    currentNestingLevel += 1;
                } else if( sectionWikitext.charAt( wikitextIdx ) === "}" ) {
                    currentNestingLevel -= 1;
                }
                wikitextIdx += 1;
            }
            spanStartIndices.push( tqStartMatch.index );
            spanLengths.push( wikitextIdx - tqStartMatch.index );
        }
        //console.log(spanStartIndices,spanLengths);
        var dateFmtRgx = DATE_FMT_RGX[mw.config.get( "wgServer" )];
        if( !dateFmtRgx ) {
            throw new Error( "Error! I don't know the native date format used by the server '" + mw.config.get( "wgServer" ) + "'!" );
        }
        /*
        * I apologize for making you have to read this regex.
        * I made a summary, though:
        *
        *  - a wikilink, without a ]] inside it
        *  - some text, without a link to userspace or user talk space
        *  - a timestamp
        *  - as an alternative to all of the above, an autosigned script
        *    and a timestamp
        *  - some comments/whitespace or some non-whitespace
        *  - finally, the end of the line
        *
        * It's also localized.
        */
        var sigRgxSrc = "(?:" + /\[\[\s*(?:m:)?:?\s*/.source + "(" + userspcLinkRgx.both +
                /([^\]\n]|\](?!\]))*?/.source + ")" + /\]\]\)?/.source + "(" +
                /[^\[\n]|\[(?!\[)|\[\[/.source + "(?!" + userspcLinkRgx.both +
                "))*?" + DATE_FMT_RGX[mw.config.get( "wgServer" )] +
                /\s+\(UTC\)|class\s*=\s*"autosigned".+?\(UTC\)<\/small>/.source +
                ")" + /(\S*([ \t\f]|<!--.*?-->)*(?:\{\{.+?\}\})?(?!\S)|\s?\S+([ \t\f]|<!--.*?-->)*)$/.source;
        var sigRgx = new RegExp( sigRgxSrc, "igm" );
        var matchIdx = 0;
        var match;
        var matchIdxEnd;
        var dstSpnIdx;
        sigMatchLoop:
        for( ; true ; matchIdx++ ) {
            match = sigRgx.exec( sectionWikitext );
            if( !match ) {
                console.error("[sigIdxToStrIdx] out of matches, matchIdx was",matchIdx,"sigIdx was",sigIdx);
                return null;
            }
            //console.log( "sig match (matchIdx = " + matchIdx + ") is >" + match[0] + "< (index = " + match.index + ")" );
            matchIdxEnd = match.index + match[0].length;
            // Validate that we're not inside a delsort span
            for( dstSpnIdx = 0; dstSpnIdx < spanStartIndices.length; dstSpnIdx++ ) {
                //console.log(spanStartIndices[dstSpnIdx],match.index,
                //    matchIdxEnd, spanStartIndices[dstSpnIdx] +
                //        spanLengths[dstSpnIdx] );
                if( match.index > spanStartIndices[dstSpnIdx] &&
                    ( matchIdxEnd <= spanStartIndices[dstSpnIdx] +
                        spanLengths[dstSpnIdx] ) ) {
                    // That wasn't really a match (as in, this match does not
                    // correspond to any sig idx in the DOM), so we can't
                    // increment matchIdx
                    matchIdx--;
                    continue sigMatchLoop;
                }
            }
            if( matchIdx === sigIdx ) {
                return {
                    start: match.index,
                    end: match.index + match[0].length,
                };
            }
        }
    }
    /**
    * Inserts fullReply on the next sensible line after strIdx in
    * sectionWikitext. indentLvl is the indentation level of the
    * comment we're replying to.
    *
    * This function essentially takes the indentation level and
    * position of the current comment, and looks for the first comment
    * that's indented strictly less than the current one. Then, it
    * puts the reply on the line right before that comment, and returns
    * the modified section wikitext.
    */
    function insertTextAfterIdx( sectionWikitext, strIdx, indentLvl, fullReply ) {
        //console.log( "[insertTextAfterIdx] indentLvl = " + indentLvl );
        // strIdx should point to the end of a line
        var counter = 0;
        while( ( sectionWikitext[ strIdx ] !== "\n" ) && ( counter++ <= 50 ) ) strIdx++;
        var slicedSecWikitext = sectionWikitext.slice( strIdx );
        //console.log("slicedSecWikitext = >>" + slicedSecWikitext.slice(0,50) + "<<");
        slicedSecWikitext = slicedSecWikitext.replace( /^\n/, "" );
        var candidateLines = slicedSecWikitext.split( "\n" );
        //console.log( "candidateLines =", candidateLines );
        // number of the line in sectionWikitext that'll be right after reply
        var replyLine = 0;
        var INDENT_RE = /^[:*#]+/;
        if( slicedSecWikitext.trim().length > 0 ) {
            var currIndentation, currIndentationLvl, i;
            // Now, loop through all the comments replying to that
            // one and place our reply after the last one
            for( i = 0; i < candidateLines.length; i++ ) {
                if( candidateLines[i].trim() === "" ) {
                    continue;
                }
                // Detect indentation level of current line
                currIndentation = INDENT_RE.exec( candidateLines[i] );
                currIndentationLvl = currIndentation ? currIndentation[0].length : 0;
                //console.log(i + ">" + candidateLines[i] + "< => " + currIndentationLvl);
                if( currIndentationLvl <= indentLvl ) {
                    // If it's an XfD, we might have found a relist
                    // comment instead, so check for that
                    if( xfdType && /<div class="xfd_relist"/.test( candidateLines[i] ) ) {
                        // Our reply might go on the line above the xfd_relist line
                        var potentialReplyLine = i;
                        // Walk through the relist notice, line by line
                        // After this loop, i will point to the line on which
                        // the notice ends
                        var NEW_COMMENTS_RE = /Please add new comments below this line/;
                        while( !NEW_COMMENTS_RE.test( candidateLines[i] ) ) {
                            i++;
                        }
                        // Relists are treated as if they're indented at level 1
                        if( 1 <= indentLvl ) {
                            replyLine = potentialReplyLine;
                            break;
                        }
                    } else {
                        //console.log( "cIL <= iL, breaking" );
                        break;
                    }
                } else {
                    replyLine = i + 1;
                }
            }
            if( i === candidateLines.length ) {
                replyLine = i;
            }
        } else {
            // In this case, we may be replying to the last comment in a section
            replyLine = candidateLines.length;
        }
        // Walk backwards until non-empty line
        while( replyLine >= 1 && candidateLines[replyLine - 1].trim() === "" ) replyLine--;
        //console.log( "replyLine = " + replyLine );
        // Splice into slicedSecWikitext
        slicedSecWikitext = candidateLines
            .slice( 0, replyLine )
            .concat( [ fullReply ], candidateLines.slice( replyLine ) )
            .join( "\n" );
        // We may need an additional newline if the two slices don't have any
        var optionalNewline = ( !sectionWikitext.slice( 0, strIdx ).endsWith( "\n" ) &&
                    !slicedSecWikitext.startsWith( "\n" ) ) ? "\n" : "";
        // Splice into sectionWikitext
        sectionWikitext = sectionWikitext.slice( 0, strIdx ) +
            optionalNewline + slicedSecWikitext;
        return sectionWikitext;
    }
    function performInPlaceReload( sigLinkElem, sectionObj ) {
        return $.getJSON(
            mw.util.wikiScript( "api" ),
            {
                format: "json",
                action: "parse",
                prop: "text",
                section: sectionObj.idxInDomHeaders + 1,
                page: sectionObj.pageTitle,
                formatversion: 2,
            }
        ).then( function ( parseResult ) {
            if( parseResult.parse.text ) {
                var cmtLinkPath = getPathToElement( sigLinkElem );
                // Delete all DOM elements in the current section
                var nextHeaderEl = allContentHeaders()[sectionObj.idxInDomHeaders + 1];
                var currEl = sectionObj.headerEl.nextElementSibling;
                while( currEl && ( currEl !== nextHeaderEl ) ) {
                    var nextEl = currEl.nextElementSibling;
                    currEl.parentNode.removeChild( currEl );
                    currEl = nextEl;
                }
                // Now write in the new stuff
                var newHtml = new DOMParser().parseFromString( parseResult.parse.text, "text/html" );
                // Select inside of .mw-parser-output
                newHtml = newHtml.querySelector( ".mw-parser-output" );
                // Remove initial header
                newHtml.removeChild( newHtml.children[0] );
                $( sectionObj.headerEl ).after( newHtml.children );
                mw.hook( "wikipage.content" ).fire( $( newHtml.children ) );
                delete getWikitextCache[sectionObj.pageTitle];
                var newCmtLink = followPathToElement( cmtLinkPath );
                highlightContainerOf( newCmtLink );
            } else {
                console.error( parseResult );
                setStatus( "Failed to load in new version." );
            }
        } );
    }
    /**
    * Using the text in #reply-dialog-field, add a reply to the current page.
    * rplyToXfdNom is true if we're replying to an XfD nom, in which case we
    * should use an asterisk instead of a colon.  revObj is the object returned
    * by getWikitext for the page with the comment; sectionObj is the object
    * returned by findSectionMain for the comment.
    *
    * Returns a Deferred that resolves/rejects when the reply succeeds/fails.
    */
    function doReply( parentCmtObj, cmtAuthorAndLink, rplyToXfdNom, sectionObj, canMakeSectionEdit ) {
        var deferred = $.Deferred();
        var revObj = sectionObj.revObj;
        var wikitext = revObj.content;
        try {
            // Generate reply in wikitext form
            var reply = document.getElementById( "reply-dialog-field" ).value.trim();
            // Add a signature if one isn't already there
            if( !hasSig( reply ) ) {
                reply += " " + ( window.replyLinkSigPrefix ?
                    window.replyLinkSigPrefix : "" ) + LITERAL_SIGNATURE;
            }
            var isUsingAutoIndentation = window.replyLinkAutoIndentation === "checkbox"
                ? ( !document.getElementById( "reply-link-option-auto-indent" ) ||
                    document.getElementById( "reply-link-option-auto-indent" ).checked )
                : window.replyLinkAutoIndentation === "always";
            if( isUsingAutoIndentation ) {
                var replyLines = reply.split( "\n" );
                // If we're outdenting, reset indentation and add the
                // outdent template. This requires that there be at least
                // one character of indentation.
                var outdentCheckbox = document.getElementById( "reply-link-option-outdent" );
                if( outdentCheckbox && outdentCheckbox.checked ) {
                    replyLines[0] = "{" + "{od|" + parentCmtObj.indentation.slice( 0, -1 ) +
                        "}}" + replyLines[0];
                    parentCmtObj.indentation = "";
                }
                // Compose reply by adding indentation at the beginning of
                // each line (if not replying to an XfD nom) or {{pb}}'s
                // between lines (if replying to an XfD nom)
                var fullReply;
                if( rplyToXfdNom ) {
                    // If there's a list in this reply, it's a bad idea to
                    // use pb's, even though the markup'll probably be broken
                    if( replyLines.some( function ( l ) { return l.substr( 0, 1 ) === "*"; } ) ) {
                        fullReply = replyLines.map( function ( line ) {
                            return parentCmtObj.indentation + "*" + line;
                        } ).join( "\n" );
                    } else {
                        fullReply = parentCmtObj.indentation + "* " + replyLines.join( "{{pb}}" );
                    }
                } else {
                    fullReply = replyLines.map( function ( line ) {
                        return parentCmtObj.indentation + ":" + line;
                    } ).join( "\n" );
                }
            } else {
                fullReply = reply;
            }
            var sectionWikitext = wikitext.slice( sectionObj.startIdx, sectionObj.endIdx )
                .trim(); // extra whitespace just messes stuff up
            var oldSectionWikitext = sectionWikitext; // We'll String.replace old w/ new
            // Now, obtain the index of the end of the comment
            var sigStartStrIdx = null;
            var sigEndStrIdx = null;
            if( !parentCmtObj.endStrIdx ) {
                var strIndices = sigIdxToStrIdx( sectionWikitext, parentCmtObj.sigIdx );
                sigStartStrIdx = strIndices && strIndices.start;
                sigEndStrIdx = strIndices && strIndices.end;
            } else {
                sigEndStrIdx = parentCmtObj.endStrIdx;
            }
            // Check for a valid sigEndStrIdx
            if( sigEndStrIdx === null ) {
                throw( "Null sigEndStrIdx (signature not found in wikitext)" );
            }
            // Determine the user who wrote the comment, for
            // edit-summary and sanity-check purposes
            var userRgx = new RegExp( /\[\[\s*(?:m:)?:?\s*/.source + userspcLinkRgx.both + /\s*(.+?)(?:\/.+?)?(?:#.+?)?\s*(?:\|.+?)?\]\]/.source, "ig" );
            var userMatches = processCharEntitiesWikitext( sectionWikitext.slice( sigStartStrIdx || 0, sigEndStrIdx ) ).match( userRgx );
            var cmtAuthorWktxt = userRgx.exec( userMatches[userMatches.length - 1] )[1];
            if( cmtAuthorWktxt === "DoNotArchiveUntil" ) {
                userRgx.lastIndex = 0;
                cmtAuthorWktxt = userRgx.exec( userMatches[userMatches.length - 2] )[1];
            }
            // Normalize case, because that's what happens during
            // wikitext-to-HTML processing; also underscores to spaces
            function sanitizeUsername( u ) {
                u = u.charAt( 0 ).toUpperCase() + u.substr( 1 );
                return u.replace( /_/g, " " );
            }
            cmtAuthorWktxt = sanitizeUsername( cmtAuthorWktxt );
            var cmtAuthorDom = sanitizeUsername( cmtAuthorAndLink.username );
            // Is the sig username the same as the DOM one?  We attempt to check
            // sigRedirectMapping in case the naive check fails
            if( cmtAuthorWktxt !== cmtAuthorDom &&
                    processCharEntitiesWikitext( cmtAuthorWktxt ) !== cmtAuthorDom &&
                    sigRedirectMapping[ cmtAuthorWktxt ] !== cmtAuthorDom ) {
                throw new Error( "Sig username assert failed! Found " +
                    cmtAuthorWktxt + " but expected " + cmtAuthorDom +
                    " (wikitext vs DOM)" );
            }
            // Another check: timestamp
            var htmlTimestamp = getTimestampGivenAuthorLink( cmtAuthorAndLink.link );
            var textTimestampMatches = sectionWikitext.slice( sigStartStrIdx || 0, sigEndStrIdx ).match( new RegExp( DATE_FMT_RGX[mw.config.get( "wgServer" )], "g" ) );
            if( textTimestampMatches.length > 0 ) {
                var textTimestamp = textTimestampMatches[ textTimestampMatches.length - 1 ];
                if( htmlTimestamp !== textTimestamp ) {
                    throw new Error( "Timestamp assert failed! HTML had '" + htmlTimestamp + "' but wikitext had '" + textTimestamp + "'" );
                }
            } else {
                console.warn( "textTimestampMatches was empty" );
            }
            // Actually insert our reply into the section wikitext
            sectionWikitext = insertTextAfterIdx( sectionWikitext, sigEndStrIdx,
                    parentCmtObj.indentation.length, fullReply );
            // Also, if the user wanted the edit request to be answered, do that
            var editReqCheckbox = document.getElementById( "reply-link-option-edit-req" );
            var markedEditReq = false;
            if( editReqCheckbox && editReqCheckbox.checked ) {
                sectionWikitext = markEditReqAnswered( sectionWikitext );
                markedEditReq = true;
            }
            // If the user preferences indicate a dry run, print what the
            // wikitext would have been post-edit and bail out
            var dryRunCheckbox = document.getElementById( "reply-link-option-dry-run" );
            if( window.replyLinkDryRun === "always" || ( dryRunCheckbox && dryRunCheckbox.checked ) ) {
                console.log( "~~~~~~ DRY RUN CONCLUDED ~~~~~~" );
                console.log( sectionWikitext );
                setStatus( "Check the console for the dry-run results." );
                document.querySelector( "#reply-link-buttons button" ).disabled = false;
                deferred.resolve();
                return deferred;
            }
            // Build summary
            var defaultSummmary = mw.msg( "rl-replying-to" ) +
                ( rplyToXfdNom ? xfdType + " nomination by " : "" ) +
                cmtAuthorWktxt +
                ( markedEditReq ? " and marking edit request as answered" : "" );
            var customSummaryField = document.getElementById( "reply-link-summary" );
            var summaryCore = defaultSummmary;
            if( window.replyLinkCustomSummary && customSummaryField.value ) {
                summaryCore = customSummaryField.value.trim();
            }
            var sectionId = sectionObj.headerEl ? sectionObj.headerEl.querySelector( "span.mw-headline" ).id : sectionObj.title;
            var summary = "/* " + sectionId.replace( /_/g, " " ) + " */ " + summaryCore + mw.msg( "rl-advert" );
            var editParams = {
                action: "edit",
                title: sectionObj.pageTitle,
                summary: summary,
                basetimestamp: revObj.timestamp,
            };
            if( canMakeSectionEdit && ( sectionObj.idxInDomHeaders !== null ) ) {
                editParams.section = sectionObj.idxInDomHeaders + 1;
                if( sectionWikitext.startsWith( oldSectionWikitext ) ) {
                    editParams.appendtext = "\n" + sectionWikitext.substring( oldSectionWikitext.length ).trim();
                } else {
                    editParams.text = sectionWikitext;
                }
            } else {
                var newWikitext = wikitext.replace( oldSectionWikitext, sectionWikitext );
                editParams.text = newWikitext;
            }
            // Send another request, this time to actually edit the page
            api.postWithEditToken( editParams ).done ( function ( data ) {
                // We put this function on the window object because we
                // give the user a "reload" link, and it'll trigger the function.
                // TODO goodness knows why I made this a property on the window object
                window.replyLinkReload = function () {
                    window.location.hash = sectionId;
                    var path = getPathToElement( cmtAuthorAndLink.link );
                    document.cookie = JUMP_COOKIE_KEY + "=" + path;
                    window.location.reload( true );
                };
                if ( data && data.edit && data.edit.result && data.edit.result == "Success" ) {
                    var needPurge = sectionObj.pageTitle !== currentPageName.replace( /_/g, " " );
                    function finishReply( _ ) {
                        if( canMakeSectionEdit && window.replyLinkAutoReload && window.replyLinkLoadNewInPlace ) {
                            performInPlaceReload( cmtAuthorAndLink.link, sectionObj );
                        } else {
                            var reloadHtml = window.replyLinkAutoReload ? mw.msg( "rl-reloading" )
                                : "<a href='javascript:window.replyLinkReload()' class='reply-link-reload'>" + mw.msg( "rl-reload" ) + "</a>";
                            setStatus( mw.msg( "rl-saved" ) + " (" + reloadHtml + ")" );
                            // Required to permit reload to happen, checked in onbeforeunload
                            replyWasSaved = true;
                            if( window.replyLinkAutoReload ) {
                                window.replyLinkReload();
                            }
                            deferred.resolve();
                        }
                    }
                    if( needPurge ) {
                        setStatus( "Reply saved! Purging..." );
                        api.post( { action: "purge", titles: currentPageName } ).done( finishReply );
                    } else {
                        finishReply();
                    }
                } else {
                    if( data && data.edit && data.edit.spamblacklist ) {
                        setStatus( "Error! Your post contained a link on the <a href=" +
                            "\"https://en.wikipedia.org/wiki/Wikipedia:Spam_blacklist\"" +
                            ">spam blacklist</a>. Remove the link(s) to: " +
                            data.edit.spamblacklist.split( "|" ).join( ", " ) + " to allow saving." );
                        document.querySelector( "#reply-link-buttons button" ).disabled = false;
                    } else {
                        setStatus( "While saving, the edit query returned an error." +
                            " Check the browser console for more information." );
                    }
                    deferred.reject();
                }
                //console.log(data);
                document.getElementById( "reply-dialog-field" ).style["background-image"] = "";
            } ).fail ( function( code, result ) {
                setStatus( mw.msg( "rl-edit-fail" ) );
                console.log(code);
                console.log(result);
                deferred.reject();
            } );
        } catch ( e ) {
            setStatusError( e );
            deferred.reject();
        }
        return deferred;
    }
    function checkCanMakeSectionEdit( sectionObj ) {
        var fullWikitext = sectionObj.revObj.content;
        if( sectionObj.idxInDomHeaders === null ) {
            return $.when( false );
        }
        // First, check if includeonly and noinclude are gonna ruin our day, by
        // seeing if there are any section headers inside includeonly and
        // noinclude elements.
        var disruptiveSectionRegex = /<(includeonly|noinclude)>[\s\S]+?==[\s\S]+?<\/(\1)>/;
        if( disruptiveSectionRegex.test( fullWikitext ) ) {
            return $.when( false );
        }
        return $.getJSON(
            mw.util.wikiScript( "api" ),
            {
                format: "json",
                action: "parse",
                prop: "wikitext",
                section: sectionObj.idxInDomHeaders + 1,
                page: sectionObj.pageTitle,
                formatversion: 2,
            }
        ).then( function ( parseResult ) {
            var parseSectionWikitext = parseResult.parse.wikitext;
            var officialSectionWikitext = fullWikitext.slice( sectionObj.startIdx, sectionObj.endIdx )
                .trim();
            // Trim because parseSectionWikitext also gets trimmed by the API
            if( officialSectionWikitext !== parseSectionWikitext ) {
                // Bit of debug info
                /*
                console.log( "oswlen",officialSectionWikitext.length,"pswlen",parseSectionWikitext.length );
                for ( var i = 0; i < Math.max( officialSectionWikitext.length, parseSectionWikitext.length ); i++  ) {
                    if( officialSectionWikitext[i] !== parseSectionWikitext[i] ) {
                        console.log( 'osw substr',
                            JSON.stringify( officialSectionWikitext.substring( i ) ),
                            'psw substr',
                            JSON.stringify( parseSectionWikitext.substring( i ) ) );
                        break;
                    }
                }
                */
            }
            return officialSectionWikitext === parseSectionWikitext;
        } );
    }
    function handleWrapperClick( linkLabel, parent, rplyToXfdNom, parentCmtObj, sectionObj ) {
        return function ( evt ) {
            $.when( mw.messages.exists( INT_MSG_KEYS[0] ) ? 1 :
                    api.loadMessages( INT_MSG_KEYS ) ).then( function () {
                var newLink = this;
                var newLinkWrapper = this.parentNode;
                buildUserspcLinkRgx();
                // Remove previous panel
                var prevPanel = document.getElementById( "reply-link-panel" );
                if( prevPanel ) {
                    prevPanel.remove();
                }
                // Reset previous cancel links
                var cancelLinks = iterableToList( document.querySelectorAll(
                            ".reply-link-wrapper a" ) );
                cancelLinks.forEach( function ( el ) {
                    if( el != newLink ) el.textContent = el.dataset.originalLabel;
                } );
                // Handle disable action
                if( newLink.textContent === linkLabel ) {
                    // Disable this link
                    newLink.textContent = mw.msg( "rl-cancel" ) + linkLabel;
                } else {
                    // We've already cancelled the reply
                    newLink.textContent = linkLabel;
                    evt.preventDefault();
                    return false;
                }
                // Figure out the username of the author
                // of the comment we're replying to
                var cmtAuthorAndLink = getCommentAuthor( newLinkWrapper );
                try {
                    var cmtAuthor = cmtAuthorAndLink.username,
                        cmtLink = cmtAuthorAndLink.link;
                } catch ( e ) {
                    setStatusError( e );
                }
                // Create panel
                var panelEl = document.createElement( "div" );
                panelEl.id = "reply-link-panel";
                panelEl.innerHTML = "<textarea id='reply-dialog-field' class='mw-ui-input'" +
                    " placeholder='" + mw.msg( "rl-placeholder" ) + "'></textarea>" +
                    ( window.replyLinkCustomSummary ? "<label for='reply-link-summary'>Summary: </label>" +
                        "<input id='reply-link-summary' class='mw-ui-input' placeholder='Edit summary' " +
                        "value='Replying to " + cmtAuthor.replace( /'/g, "&#39;" ) + "'/><br />" : "" ) +
                    "<table style='border-collapse:collapse'><tr><td id='reply-link-buttons' style='width: " +
                    ( window.replyLinkPreloadPing === "button" ? "325" : "255" ) + "px'>" +
                    "<button id='reply-dialog-button' class='mw-ui-button mw-ui-progressive'>" + mw.msg( "rl-reply" ) + "</button> " +
                    "<button id='reply-link-preview-button' class='mw-ui-button'>" + mw.msg( "rl-preview" ) + "</button>" +
                    ( window.replyLinkPreloadPing === "button" ?
                        " <button id='reply-link-ping-button' class='mw-ui-button'>Ping</button>" : "" ) +
                    "<button id='reply-link-cancel-button' class='mw-ui-button mw-ui-quiet mw-ui-destructive'>" + mw.msg( "rl-cancel-button" ) + "</button></td>" +
                    "<td id='reply-dialog-status'></span><div style='clear:left'></td></tr></table>" +
                    "<div id='reply-link-options' class='gone-on-empty' style='margin-top: 0.5em'></div>" +
                    "<div id='reply-link-preview' class='gone-on-empty' style='border: thin dashed gray; padding: 0.5em; margin-top: 0.5em'></div>";
                parent.insertBefore( panelEl, newLinkWrapper.nextSibling );
                var replyDialogField = document.getElementById( "reply-dialog-field" );
                replyDialogField.style = "padding: 0.625em; min-height: 10em; margin-bottom: 0.75em; line-height: 1.3";
                if( window.replyLinkPreloadPing === "always" &&
                        cmtAuthor &&
                        cmtAuthor !== mw.config.get( "wgUserName" ) &&
                        cmtAuthor !== mw.config.get( "wgRelevantUserName" ) &&
                        !/(\d+.){3}\d+/.test( cmtAuthor ) ) {
                    replyDialogField.value = window.replyLinkPreloadPingTpl.replace( "##", cmtAuthor );
                }
                // Fill up #reply-link-options
                function newOption( id, text, defaultOn ) {
                    var newCheckbox = document.createElement( "input" );
                    newCheckbox.type = "checkbox";
                    newCheckbox.id = id;
                    if( defaultOn ) {
                        newCheckbox.checked = true;
                    }
                    var newLabel = document.createElement( "label" );
                    newLabel.htmlFor = id;
                    newLabel.appendChild( document.createTextNode( text ) );
                    document.getElementById( "reply-link-options" ).appendChild( newCheckbox );
                    document.getElementById( "reply-link-options" ).appendChild( newLabel );
                }
                if( parentCmtObj.sigIdx === null && parentCmtObj.endStrIdx === null ) {
                    parentCmtObj.sigIdx = metadata[this.id].sigIdx;
                }
                // If the dry-run option is "checkbox", add an option to make it
                // a dry run
                if( window.replyLinkDryRun === "checkbox" ) {
                    newOption( "reply-link-option-dry-run", "Don't actually edit?", true );
                }
                // If the current section header text indicates an edit request,
                // offer to mark it as answered
                //if( ourMetadata[1] && EDIT_REQ_REGEX.test( ourMetadata[1][1] ) ) {
                //    newOption( "reply-link-option-edit-req", "Mark edit request as answered?", false );
                //}
                // If the previous comment was indented by OUTDENT_THRESH,
                // offer to outdent
                if( parentCmtObj.indentation.length >= OUTDENT_THRESH ) {
                    newOption( "reply-link-option-outdent", "Outdent?", false );
                }
                if( window.replyLinkAutoIndentation === "checkbox" ) {
                    newOption( "reply-link-option-auto-indent", mw.msg( "rl-auto-indent" ), true );
                }
                /* Commented out because I could never get it to work
                // Autofill with a recommendation if we're replying to a nom
                if( rplyToXfdNom ) {
                    replyDialogField.value = "'''Comment'''";
                    // Highlight the "Comment" part so the user can change it
                    var range = document.createRange();
                    range.selectNodeContents( replyDialogField );
                    //range.setStart( replyDialogField, 3 ); // start of "Comment"
                    //range.setEnd( replyDialogField, 10 ); // end of "Comment"
                    var sel = window.getSelection();
                    sel.removeAllRanges();
                    sel.addRange( range );
                }*/
                // Close handler
                window.onbeforeunload = function ( e ) {
                    if( !replyWasSaved &&
                            document.getElementById( "reply-dialog-field" ) &&
                            document.getElementById( "reply-dialog-field" ).value ) {
                        var txt = mw.msg( "rl-started-reply" );
                        e.returnValue = txt;
                        return txt;
                    }
                };
                // Start loading in the section object, so we don't have to do it in startReply
                try {
                    var sectionObjPromise = ( sectionObj === null ) ? findSectionMain( cmtLink ) : $.when( sectionObj );
                } catch ( e ) {
                    console.error( e );
                    setStatus( "Error locating the section: " + e );
                    document.querySelector( "#reply-link-buttons button" ).disabled = true;
                }
                // Also, check if we can get away with sending just a section edit
                var canMakeSectionEditPromise = sectionObjPromise.then( checkCanMakeSectionEdit );
                // Called by the "Reply" button, Ctrl-Enter in the text area, and
                // Enter/Ctrl-Enter in the summary field
                function startReply() {
                    // Change UI to make it clear we're performing an operation
                    document.getElementById( "reply-dialog-field" ).style["background-image"] =
                        "url(" + window.replyLinkPendingImageUrl + ")";
                    document.querySelector( "#reply-link-buttons button" ).disabled = true;
                    setStatus( mw.msg( "rl-loading" ) );
                    var revidCheckPromise = sectionObjPromise.then( function ( sectionObj ) {
                        return getLastRevId( sectionObj.pageTitle );
                    } );
                    $.when(
                        sectionObjPromise,
                        revidCheckPromise,
                        canMakeSectionEditPromise,
                    ).then( function ( sectionObj, currentRevId, canMakeSectionEdit ) {
                        if( currentRevId > sectionObj.pageRevId ) {
                            // Someone's edited this page since we parsed it
                            setStatus( mw.msg( "rl-out-of-date" ) );
                        } else {
                            doReply(
                                parentCmtObj,
                                cmtAuthorAndLink,
                                rplyToXfdNom,
                                sectionObj,
                                canMakeSectionEdit
                            );
                        }
                    }, function ( err ) {
                        console.error( err );
                        setStatus( "Error (async), probably while locating the section: " + err );
                    } );
                }
                // Event listener for the "Reply" button
                document.getElementById( "reply-dialog-button" )
                    .addEventListener( "click", startReply );
                // Event listener for the text area
                document.getElementById( "reply-dialog-field" )
                    .addEventListener( "keydown", function ( e ) {
                        if( e.ctrlKey && ( e.keyCode == 10 || e.keyCode == 13 ) ) {
                            startReply();
                        }
                    } );
                // Event listener for the "Preview" button
                document.getElementById( "reply-link-preview-button" )
                    .addEventListener( "click", function () {
                        var reply = document.getElementById( "reply-dialog-field" ).value.trim();
                        // Add a signature if one isn't already there
                        if( !hasSig( reply ) ) {
                            reply += " " + ( window.replyLinkSigPrefix ?
                                window.replyLinkSigPrefix : "" ) + LITERAL_SIGNATURE;
                        }
                        var sanitizedCode = encodeURIComponent( reply );
                        sectionObjPromise.then( function ( sectionObj ) {
                            $.post( "https:" + mw.config.get( "wgServer" ) +
                                "/w/api.php?action=parse&format=json&title=" +
                                    encodeURIComponent( sectionObj.pageTitle ) + "&text=" + sanitizedCode +
                                    "&pst=1&prop=text&formatversion=2",
                                function ( res ) {
                                    if ( !res || !res.parse || !res.parse.text ) return console.error( "Preview failed" );
                                    document.getElementById( "reply-link-preview" ).innerHTML = res.parse.text;
                                    // Add target="_blank" to links to make them open in a new tab by default
                                    var links = document.querySelectorAll( "#reply-link-preview a" );
                                    for( var i = 0, n = links.length; i < n; i++ ) {
                                        links[i].setAttribute( "target", "_blank" );
                                    }
                                } );
                        } );
                    } );
                if( window.replyLinkPreloadPing === "button" ) {
                    document.getElementById( "reply-link-ping-button" )
                        .addEventListener( "click", function () {
                            var cmtAuthorEscaped = cmtAuthor.replace( /=/g, "{{=}}" );
                            replyDialogField.value = window.replyLinkPreloadPingTpl
                                .replace( "##", cmtAuthorEscaped ) + replyDialogField.value;
                        } );
                }
                // Event listener for the "Cancel" button
                document.getElementById( "reply-link-cancel-button" )
                    .addEventListener( "click", function () {
                        newLink.textContent = linkLabel;
                        panelEl.remove();
                    } );
                // Event listeners for the custom edit summary field
                if( window.replyLinkCustomSummary ) {
                    document.getElementById( "reply-link-summary" )
                        .addEventListener( "keydown", function ( e ) {
                            if( e.keyCode == 10 || e.keyCode == 13 ) {
                                startReply();
                            }
                        } );
                }
                if( newLinkWrapper.dataset.replyLinkInstant === true ) {
                    startReply();
                    newLinkWrapper.dataset.replyLinkInstant = false;
                }
                if( window.replyLinkTestInstantReply ) {
                    startReply();
                }
            }.bind( this ) );
            // Cancel default event handler
            evt.preventDefault();
            return false;
        }
    }
    /**
    * Adds a "(reply)" link after the provided text node, giving it
    * the provided element id. anyIndentation is true if there's any
    * indentation (i.e. indentation string is not the empty string)
    */
    function attachLinkAfterNode( node, preferredId, parentCmtObj, sectionObj ) {
        // Choose a parent node - walk up tree until we're under a dd, li,
        // p, or div. This walk is a bit unsafe, but this function should
        // only get called in a place where the walk will succeed.
        var parent = node;
        do {
            parent = parent.parentNode;
        } while( !( /^(p|dd|li|div|td)$/.test( parent.tagName.toLowerCase() ) ) );
        // Determine whether we're replying to an XfD nom
        var rplyToXfdNom = false;
        if( xfdType === "AfD" || xfdType === "MfD" ) {
            // If the parent comment is non-indented, we are replying to a nom
            rplyToXfdNom = !parentCmtObj.sigIdx;
        } else if( xfdType === "TfD" || xfdType === "FfD" ) {
            // If the sibling before the previous sibling of this node
            // is a h4, then this is a nom
            rplyToXfdNom = parent.previousElementSibling &&
                parent.previousElementSibling.previousElementSibling &&
                parent.previousElementSibling.previousElementSibling.nodeType === 1 &&
                parent.previousElementSibling.previousElementSibling.tagName.toLowerCase() === "h4";
        } else if( xfdType === "CfD" ) {
            // If our grandparent is a dl and our grandparent's previous
            // sibling is a h4, then this is a nom
            rplyToXfdNom = parent.parentNode.tagName.toLowerCase() === "dl" &&
                parent.parentNode.previousElementSibling.nodeType === 1 &&
                parent.parentNode.previousElementSibling.tagName.toLowerCase() === "h4";
        }
        // Choose link label: if we're replying to an XfD, customize it
        var linkLabel = mw.msg( "rl-reply-label" ) + ( rplyToXfdNom ? mw.msg( "rl-to-label" ) + xfdType : "" );
        // Construct new link
        var newLinkWrapper = document.createElement( "span" );
        newLinkWrapper.className = "reply-link-wrapper";
        var newLink = document.createElement( "a" );
        newLink.href = "#";
        newLink.id = preferredId;
        newLink.dataset.originalLabel = linkLabel;
        newLink.appendChild( document.createTextNode( linkLabel ) );
        newLink.addEventListener( "click", handleWrapperClick( linkLabel, parent, rplyToXfdNom, parentCmtObj, sectionObj ) );
        newLinkWrapper.appendChild( document.createTextNode( " (" ) );
        newLinkWrapper.appendChild( newLink );
        newLinkWrapper.appendChild( document.createTextNode( ")" ) );
        // Insert new link into DOM
        parent.insertBefore( newLinkWrapper, node.nextSibling );
    }
    /**
    * Uses attachLinkAfterTextNode to add a reply link after every
    * timestamp on the page.
    */
    function attachLinks () {
        var mainContent = findMainContentEl();
        if( !mainContent ) {
            console.error( "No main content element found; exiting." );
            return;
        }
        var contentEls = mainContent.children;
        // Find the index of the first header in contentEls
        var headerIndex = 0;
        for( headerIndex = 0; headerIndex < contentEls.length; headerIndex++ ) {
            if( contentEls[ headerIndex ].matches( HEADER_SELECTOR ) ) break;
        }
        // If we didn't find any headers at all, that's a problem and we
        // should bail
        if( mainContent.querySelector( "div.hover-edit-section" ) ) {
            headerIndex = 0;
        } else if( headerIndex === contentEls.length ) {
            console.error( "Didn't find any headers - hit end of loop!" );
            return;
        }
        // We also should include the first header
        if( headerIndex > 0 ) {
            headerIndex--;
        }
        // Each element is a 2-element list of [level, node]
        var parseStack = iterableToList( contentEls ).slice( headerIndex );
        parseStack.reverse();
        parseStack = parseStack.map( function ( el ) { return [ "", el ]; } );
        // Main parse loop
        var node;
        var currIndentation; // A string of symbols, like ":*::"
        var newIndentSymbol;
        var stackEl; // current element from the parse stack
        var idNum = 0; // used to make id's for the links
        var linkId = ""; // will be the element id for this link
        while( parseStack.length ) {
            stackEl = parseStack.pop();
            node = stackEl[1];
            currIndentation = stackEl[0];
            // Compatibility with "Comments in Local Time"
            var isLocalCommentsSpan = node.nodeType === 1 &&
                "span" === node.tagName.toLowerCase() &&
                node.className.includes( "localcomments" );
            var isSmall = node.nodeType === 1 && (
                    node.tagName.toLowerCase() === "small" ||
                    ( node.tagName.toLowerCase() === "span" &&
                    node.style && node.style.getPropertyValue( "font-size" ) === "85%" ) );
            // Small nodes are okay, unless they're delsort notices
            var isOkSmallNode = isSmall &&
                !node.className.includes( "delsort-notice" );
            if( ( node.nodeType === 3 ) ||
                    isOkSmallNode ||
                    isLocalCommentsSpan )  {
                // If the current node has a timestamp, attach a link to it
                // Also, no links after timestamps, because it's just like
                // having normal text afterwards, which is rejected (because
                // that means someone put a timestamp in the middle of a
                // paragraph)
                var hasLinkAfterwardsNotInBlockEl = node.nextElementSibling &&
                    ( node.nextElementSibling.tagName.toLowerCase() === "a" ||
                        ( node.nextElementSibling.tagName.match( /^(span|small)$/i ) &&
                            node.nextElementSibling.querySelector( "a" ) ) );
                if( TIMESTAMP_REGEX.test( node.textContent ) &&
                        ( node.previousSibling || isSmall ) &&
                        !hasLinkAfterwardsNotInBlockEl ) {
                    linkId = "reply-link-" + idNum;
                    var parentCmtObj = {
                        indentation: currIndentation,
                        sigIdx: null,
                        endStrIdx: null
                    };
                    attachLinkAfterNode( node, linkId, parentCmtObj, /* sectionObj */ null );
                    idNum++;
                    // Update global metadata dictionary
                    metadata[linkId] = {};
                    //metadata[linkId].indentation = currIndentation; // It's already being passed into attachLinkAfterNode
                }
            } else if( node.nodeType === 1 &&
                    /^(div|p|dl|dd|ul|li|span|ol|table|tbody|tr|td)$/.test( node.tagName.toLowerCase() ) ) {
                switch( node.tagName.toLowerCase() ) {
                    case "dl": newIndentSymbol = ":"; break;
                    case "ul": newIndentSymbol = "*"; break;
                    case "ol": newIndentSymbol = "#"; break;
                    case "div":
                        if( node.className.includes( "xfd_relist" ) || node.className.includes( "thumbcaption" ) ) {
                            continue;
                        }
                        break;
                    default: newIndentSymbol = ""; break;
                }
                var childNodes = node.childNodes;
                for( let i = 0, numNodes = childNodes.length; i < numNodes; i++ ) {
                    parseStack.push( [ currIndentation + newIndentSymbol,
                        childNodes[i] ] );
                }
            }
        }
        // This loop adds sigIdx entries in the metadata dictionary
        var sigIdxEls = iterableToList( mainContent.querySelectorAll(
                HEADER_SELECTOR + ",span.reply-link-wrapper a" ) );
        var currSigIdx = 0, j, numSigIdxEls, currHeaderEl, currHeaderData;
        var headerIdx = 0; // index of the current header
        var headerLvl = 0; // level of the current header
        for( j = 0, numSigIdxEls = sigIdxEls.length; j < numSigIdxEls; j++ ) {
            var headerTagNameMatch = /^h(\d+)$/.exec(
                sigIdxEls[j].tagName.toLowerCase() );
            if( headerTagNameMatch ) {
                currHeaderEl = sigIdxEls[j];
                // Test to make sure we're not in the table of contents
                if( currHeaderEl.parentNode.className === "toctitle" ) {
                    continue;
                }
                // Reset signature counter
                currSigIdx = 0;
            } else {
                metadata[ sigIdxEls[j].id ].sigIdx = currSigIdx;
                currSigIdx++;
            }
        }
        // Disable links inside hatnotes, archived discussions
        var badRegionsSelector = "div.archived,div.resolved,table";
        var badRegions = mainContent.querySelectorAll( badRegionsSelector );
        for( var i = 0; i < badRegions.length; i++ ) {
            var badRegion = badRegions[i];
            var insideArchived = badRegion.querySelectorAll( ".reply-link-wrapper" );
            for( var j = 0; j < insideArchived.length; j++ ) {
                insideArchived[j].parentNode.removeChild( insideArchived[j] );
            }
        }
    }
    function runTestMode() {
        // We never want to make actual edits
        window.replyLinkDryRun = "always";
        // Simulate having a panel open
        $( "#mw-content-text" )
            .append( $( "<div>" )
                .append( $( "<textarea>" ).attr( "id", "reply-dialog-field" ).val( "hi" ) )
                .append( $( "<div>" ).attr( "id", "reply-link-buttons" )
                    .append( $( "<button> " ) ) ) );
        mw.util.addCSS( ".reply-link-wrapper { background-color: orange; }" );
        api.loadMessages( INT_MSG_KEYS ).then( function () {
            buildUserspcLinkRgx();
            // Statistics variables
            var successes = 0, failures = 0;
            // Run one test on a wrapper link
            function runOneTestOn( wrapper ) {
                try {
                    var cmtAuthorAndLink = getCommentAuthor( wrapper );
                    var ourMetadata = metadata[ wrapper.children[0].id ];
                    findSectionMain( cmtAuthorAndLink.link ).then( function ( sectionObj ) {
                        doReply(
                            ourMetadata.indentation,
                            ourMetadata.sigIdx,
                            cmtAuthorAndLink,
                            /* rplyToXfdNom */ false,
                            sectionObj
                        ).done( function () {
                            wrapper.style.background = "green";
                            successes++;
                        } ).fail( function () {
                            wrapper.style.background = "red";
                            failures++;
                        } );
                    } );
                } catch ( e ) {
                    console.error( e );
                    wrapper.style.background = "red";
                    failures++;
                }
            }
            var wrappers = Array.from( document.querySelectorAll( ".reply-link-wrapper" ) );
            function runOneTest() {
                var wrapper = wrappers.shift();
                if( wrapper ) {
                    runOneTestOn( wrapper );
                    setTimeout( runOneTest, 250 );
                } else {
                    var results = successes + " successes, " + failures + " failures";
                    $( "#mw-content-text" ).prepend( results ).append( results );
                }
            }
            //console.log = function() {};
            setTimeout( runOneTest, 0 );
        } );
    }
    function onReady() {
        var lang_code = mw.config.get( "wgUserLanguage" )
        // Replace default English interface by translation if available
        var interface_messages = $.extend( {}, i18n.en, i18n[ lang_code.split('-')[0] ], i18n[ lang_code ] );
        // Define interface messages
        mw.messages.set( interface_messages );
        // Exit if history page or edit page or oldid
        if( mw.config.get( "wgAction" ) === "history" ) return;
        if( document.getElementById( "editform" ) ) return;
        if( window.location.search.includes( "oldid=" ) ) return;
        api = new mw.Api();
        mw.util.addCSS(
            "#reply-link-panel { padding: 1em; margin-left: 1.6em; "+
              "max-width: 1200px; width: 66%; margin-top: 0.5em; }"+
            ".gone-on-empty:empty { display: none; }"
        );
        mw.loader.load( "https://en.wikipedia.org/w/index.php?title=User:Enterprisey/mw-ui-button.css&action=raw&ctype=text/css", "text/css" );
        // Pre-load interface messages; we will check again when a (reply)
        // link is clicked
        api.loadMessages( INT_MSG_KEYS );
        // Initialize the xfdType global variable, which must happen
        // before the call to attachLinks
        currentPageName = mw.config.get( "wgPageName" );
        xfdType = "";
        if( mw.config.get( "wgNamespaceNumber" ) === 4) {
            if( currentPageName.startsWith( "Wikipedia:Articles_for_deletion/" ) ) {
                xfdType = "AfD";
            } else if( currentPageName.startsWith( "Wikipedia:Miscellany_for_deletion/" ) ) {
                xfdType = "MfD";
            } else if( currentPageName.startsWith( "Wikipedia:Templates_for_discussion/Log/" ) ) {
                xfdType = "TfD";
            } else if( currentPageName.startsWith( "Wikipedia:Categories_for_discussion/Log/" ) ) {
                xfdType = "CfD";
            } else if( currentPageName.startsWith( "Wikipedia:Files_for_discussion/" ) ) {
                xfdType = "FfD";
            }
        }
        // Default values for some preferences
        function defaultValue( prefName, defaultValue ) { if( window[prefName] === undefined ) window[prefName] = defaultValue; }
        defaultValue( "replyLinkAutoReload",      !isOnSectionWatchlistPage );
        defaultValue( "replyLinkDryRun",          "never" );
        defaultValue( "replyLinkPreloadPing",      "always" );
        defaultValue( "replyLinkPreloadPingTpl",  "{{u|##}}, " );
        defaultValue( "replyLinkCustomSummary",    false );
        defaultValue( "replyLinkTestMode",        false );
        defaultValue( "replyLinkTestInstantReply", false );
        defaultValue( "replyLinkAutoIndentation",  "checkbox" );
        defaultValue( "replyLinkLoadNewInPlace",  true );
        // Insert "reply" links into DOM
        if( !isOnSectionWatchlistPage ) {
            attachLinks();
        }
        // If test mode is enabled, create a link for that
        if( window.replyLinkTestMode &&
                document.getElementsByClassName( "reply-link-sig-check-container" ).length === 0 ) {
            mw.util.addPortletLink( "p-cactions", "#", "reply-link test mode", "pt-reply-link-test" )
                .addEventListener( "click", runTestMode );
            var dryRunToCheckboxLink = mw.util.addPortletLink( "p-cactions", "#",
                    "reply-link: dry-run = checkbox", "pt-reply-link-dry-run-checkbox",
                    "Set window.replyLinkDryRun to 'checkbox'" )
                .addEventListener( "click", function () { window.replyLinkDryRun = "checkbox" } );
            // Also add "sig check" links to each section header
            $( "#mw-content-text" ).find( HEADER_SELECTOR ).each( function ( idx, header ) {
                $( header ).find( ".mw-editsection *" ).last().before(
                    "<span style='color: #54595d'> | </span>",
                    $( "<span>", { "class": "reply-link-sig-check-container" } ).append(
                        $( "<a>" )
                            .attr( "href", "#" )
                            .text( "sig check" )
                            .click( function () {
                                buildUserspcLinkRgx();
                                var sigEls = $( header ).nextUntil( HEADER_SELECTOR ).find( '.reply-link-wrapper' ).toArray();
                                findSectionMain( sigEls[0] ).then( function ( sectionObj ) {
                                    var sectionWikitext = sectionObj.revObj.content.substring( sectionObj.startIdx, sectionObj.endIdx );
                                    for( var sigIdx = 0; sigIdx < sigEls.length; sigIdx++ ) {
                                        var strIndices = sigIdxToStrIdx( sectionWikitext, sigIdx );
                                        var sigText = sectionWikitext.substring( strIndices.start, strIndices.end );
                                        $( sigEls[sigIdx] ).last().before( " ", $( "<abbr>", { title: sigText } ).text( sigText.substring( sigText.length - 50 ) ) );
                                    }
                                } );
                                return false;
                            } ) ) );
            } );
        }
        // This large string creats the "pending" texture
        window.replyLinkPendingImageUrl = "data:image/gif;base64,R0lGODlhGAAYAKIGAP7+/vv7+/Ly8u/v7+7u7v///////wAAACH/C05FVFNDQVBFMi4wAwEAAAAh+QQFAAAGACwAAAAAGAAYAAADU0hKAvUwvjCWbTIXahfWEdcxDgiJ3Wdu1UiUK5quUzuqoHzBuZ3yGp0HmBEqcEHfjmYkMZXDp8sZgx6JkiayaKWatFhJd1uckrPWcygdXrvUJ1sCACH5BAUAAAYALAAAAAAYABgAAANTSLokUDBKGAZbbupSr8qb1HlgSFnkY55eo67jVZoxM4c189IoubKtmyaH2W2IH+OwJ1NOkK4fVPhk2pwia1GqTXJbUVg3zANTs2asZHwWpX+cQQIAIfkEBQAABgAsAAAAABgAGAAAA1E4tLwCJcoZQ2uP6hLUJdk2dR8IiRL5hSjnXSyqwmc7Y7X84m21MzHRrZET/oA9V8nUGwKLGqcDSpEybcdpM3vVLYNRLrgqpo7K2685hcaqkwkAIfkEBQAABgAsAAAAABgAGAAAA1RYFUP+TgBFq2IQSstxjhNnNR+xiVVQmiF6kdnpLrDWul58o7k9vyUZrvYQ8oigHy24E/UgzQ4yonwWo6kp62dNzrrbr9YoXZEt4HPWjKWk20CmKwEAIfkEBQAABgAsAAAAABgAGAAAA1NYWjH08Amwam0xTstxlhR3OR+xiYv3nahCrmHLlGbcqpqN4hB7vzmZggcSMoA9nYhYMzJ9O2RRyCQoO1KJM9uUVaFYGtjyvY7E5hR3fC6x1WhRAgAh+QQFAAAGACwAAAAAGAAYAAADVFi6FUMwQgGYVU5Kem3WU9UtH8iN2AMSJ1pq7fhuoquaNXrDubyyvc4shCLtIjHZkVhsLIFN5yopfFIvQ2gze/U8CUHsVxDNam2/rjEdZpjVKTYjAQAh+QQFAAAGACwAAAAAGAAYAAADU1i6G0MwQgGYVU5Kem3WU9U1D0hwI1aCaPqxortq7fjSsT1veXfzqcUuUrOZTj3fEBlUmYrKZ/LyCzULVWYzC6Uuu57vNHwcM7KnKxpMOrKdUkUCACH5BAUAAAYALAAAAAAYABgAAANTWLqsMSTKKEC7b856W9aU1S0fyI0OBBInWmrt+G6iq5q1fMN5N0sx346GSq1YPcwQmLwsQ0XHMShcUZXWpud53WajhR8SLO4yytozN016EthGawIAIfkEBQAABgAsAAAAABgAGAAAA1MoUNzOYZBJ53o41ipwltukeI4WEiMJgWGqmu31sptLwrV805zu4T3V6oTyfYi2H4+SPJ6aDyDTiFmKqFEktmSFRrvbhrQoHMbKhbGX+wybc+hxAgAh+QQFAAAGACwAAAAAGAAYAAADVEgqUP7QhaHqajFPW1nWFEd4H7SJBFZKoSisz+mqpcyRq23hdXvTH10HCEKNiBHhBVZQHplOXtC3Q5qoQyh2CYtaIdsn1CidosrFGbO5RSfb35gvAQAh+QQFAAAGACwAAAAAGAAYAAADU0iqAvUwvjCWbTIXahfWEdcRHzhVY2mKnQqynWOeIzPTtZvBl7yiKd8L2BJqeB7jjti7IRlKyZMUDTGTzis0W6Nyc1XIVJfRep1dslSrtoJvG1QCACH5BAUAAAYALAAAAAAYABgAAANSSLoqUDBKGAZbbupSb3ub1HlZGI1XaXIWCa4oo5ox9tJteof1sm+9xoqS0w2DhBmwKPtNkEoN1Cli2o7WD9ajhWWT1NM3+hyHiVzwlkuemIecBAAh+QQFAAAGACwAAAAAGAAYAAADUxhD3CygyEnlcg3WXQLOEUcpH6GJE/mdaHdhLKrCYTs7sXiDrbQ/NdkLF9QNHUXO79FzlUzJyhLam+Y21ujoyLNxgdUv1fu8SsXmbVmbQrN97l4CACH5BAUAAAYALAAAAAAYABgAAANSWBpD/k4ARetq8EnLWdYTV3kfsYkV9p3oUpphW5AZ29KQjeKgfJU6ES8Su6lyxd2x5xvCfLPlIymURqDOpywbtHCpXqvW+OqOxGbKt4kGn8vuBAAh+QQFAAAGACwAAAAAGAAYAAADU1iqMfTwCbBqbTFOy3GWFHc5H7GJi/edaKFmbEuuYeuWZt2+UIzyIBtjptH9iD2jCJgTupBBIdO3hDalVoKykxU4mddddzvCUS3gc7mkTo2xZmUCACH5BAUAAAYALAAAAAAYABgAAANTWLoaQzBCAZhtT0Z6rdNb1S0fSHAjZp5iWoKom8Ht+GqxPeP1uEs52yrYuYVSpN+kV1SykCoatGBcTqtPKJZ42TK7TsLXExZcy+PkMB2VIrHZQgIAIfkEBQAABgAsAAAAABgAGAAAA1RYuhxDMEIBmFVOSnpt1lPVLR/IjdgDEidaau34bqKrmrV8w3k3RzHfjoZaDIE934qVvPyYxdQqKJw2PUdo9El1ZrtYa7TAvTayBDMJLRg/tbYlJwEAIfkEBQAABgAsAAAAABgAGAAAA1IItdwbg8gphbsFUioUZtpWeV8WiURXPqeorqFLfvH2ljU3Y/l00y3b7tIbrUyo1NBRVB6bv09Qd8wko7yp8al1clFYYjfMHC/L4HOjSF6bq80EACH5BAUAAAYALAAAAAAYABgAAANTSALV/i0MQqtiMEtrcX4bRwkfFIpL6Zxcqhas5apxNZf16OGTeL2wHmr3yf1exltR2CJqmDKnCWqTgqg6YAF7RPq6NKxy6Rs/y9YrWpszT9fAWgIAOw==";
        // Respond to any [[User:Enterprisey/reply-link auto instant reply]] transclusions
        var autoReplies = document.querySelectorAll( ".reply-link-auto-instant-reply" );
        if( autoReplies.length > 0 ) {
            window.replyLinkTestInstantReply = true;
        }
        for( var i = 0; i < autoReplies.length; i++ ) {
            var el = autoReplies[i];
            while( el && el.className !== "reply-link-wrapper" ) {
                el = el.nextElementSibling;
            }
            if( el ) {
                el.dataset.replyLinkInstant = true;
                el.querySelector( "a" ).click();
            }
        }
        // Jump CSS
        mw.loader.addStyleTag( "@keyframes reply-link-jump-highlight-keyframes { from { background-color: #ffb; } to { background-color: transparent; } } .reply-link-jump-highlight { animation: reply-link-jump-highlight-keyframes  2s; }" );
        // Timeout to give other scripts time to load
        setTimeout( function () {
            // If there's an element to jump to, jump to it
            var jumpCookieIdx = document.cookie.indexOf( JUMP_COOKIE_KEY );
            if( jumpCookieIdx >= 0 ) {
                try {
                    var path = new RegExp( JUMP_COOKIE_KEY + "=([^;]+)" ).exec( document.cookie )[1];
                    var el = followPathToElement( path );
                    el.scrollIntoView();
                    highlightContainerOf( el );
                } catch( e ) { console.error(e); }
                document.cookie = JUMP_COOKIE_KEY + "=; expires=Thu, 01 Jan 1970 00:00:01 GMT";
            }
        }, 500 );
    } // end function onReady
    mw.loader.load( "mediawiki.ui.input", "text/css" );
    mw.loader.using( [ "mediawiki.util", "mediawiki.api" ] ).then( function () {
        mw.hook( "wikipage.content" ).add( onReady );
        if( isOnSectionWatchlistPage ) {
            mw.hook( "replylink.attachlinkafter" ).add( attachLinkAfterNode );
        }
    } );
    // Return functions for testing
    return {
        "iterableToList": iterableToList,
        "sigIdxToStrIdx": sigIdxToStrIdx,
        "insertTextAfterIdx": insertTextAfterIdx,
        "wikitextToTextContent": wikitextToTextContent
    };
}
// Export functions for testing
if( typeof module === typeof {} ) {
    module.exports = { "loadReplyLink": loadReplyLink };
}
// If we're in the right environment, load the script
if( jQuery !== undefined && mediaWiki !== undefined ) {
    var currNamespace = mw.config.get( "wgNamespaceNumber" );
    // Also enable on T:TDYK and its subpages
    var ttdykPage = mw.config.get( "wgPageName" ).indexOf( "Template:Did_you_know_nominations" ) === 0;
    // Normal "read" view and not a diff view
    var normalView = mw.config.get( "wgIsArticle" ) &&
            !mw.config.get( "wgDiffOldId" );
    if( normalView && ( currNamespace % 2 === 1 || currNamespace === 4 || ttdykPage ) ) {
        loadReplyLink( jQuery, mediaWiki );
    }
    if( currNamespace === -1 && ( mw.config.get( "wgTitle" ) === "BlankPage/section-watchlist" ) ) {
        loadReplyLink( jQuery, mediaWiki, /* section-watchlist */ true );
    }
}
//</nowiki>

১৯:০৬, ২০ এপ্রিল ২০২২ তারিখে সংশোধিত সংস্করণ

/**
 * Blendet eine „Auto-Format“-Funktion in der Werkzeugleiste ein, die viele typische Wikifizierungs-Fehler
 * automatisch korrigiert. Eine ausführliche Beschreibung ist auf der Diskussionsseite zu finden.
 * (<nowiki> zur Umgehung von [[bugzilla:8761]].)
 */
( function( $, mw ) {
	if ( !document.forms['editform']
		|| ( mw.config.get( 'wgAction' ) !== 'edit' && mw.config.get( 'wgAction' ) !== 'submit' )
	) {
		return;
	}

	function escapeRE( s ) {
		return s.replace( /([$()*+\-.?[\\\]^{|}])/g, '\\$1' );
	}

	mw.libs = mw.libs || {};

	mw.libs.autoFormatter = {
		/**
		 * @param {HTMLAnchorElement} [clickedElement]
		 * @return {boolean}
		 */
		click: function( clickedElement ) {
			var e = document.forms['editform'].elements,
				textbox = e['wpTextbox1'],
				summaryElement = e['wpSummary'];
			if ( !textbox ) {
				return false;
			}

			/* Reset the button as fast as possible, even before triggering WikEd */
			this.updateButton( clickedElement );

			if ( window.wikEd && window.wikEd.useWikEd ) {
				wikEd.UpdateTextarea();
			}

			this.clickedElement = clickedElement;
			this.isAll = false;
			this.isDisambiguation = /\{\{\s*[Bb]egriffsklärung\s*[|}]/.test( textbox.value );
			this.lang = mw.config.get( 'wgContentLanguage' );
			this.localisation = typeof window.autoFormatLocalisation === 'undefined' ||
				window.autoFormatLocalisation === true ? this.lang : window.autoFormatLocalisation;

			var hasChanges = this.cleanElement( textbox );
			summaryElement.value = this.cleanSummary( summaryElement.value );

			if ( window.wikEd && window.wikEd.useWikEd ) {
				wikEd.UpdateFrame();
			}
			if ( hasChanges ) {
				mw.hook( 'AutoFormatterDoneWithChange' ).fire();
			}

			/* Do not follow the links href if the clicked element was a link */
			return false;
		},
		isChanged: function( oldValue, newValue ) {
			/* Entfernte Leerräume am Textende zählen nie als Änderung */
			oldValue = oldValue.replace( /\s+$/, '' );
			newValue = newValue.replace( /\s+$/, '' );
			/* Entfernte Leerräume am Zeilenende nicht als Änderung anzeigen, aber trotzdem ersetzen */
			var changed = oldValue.replace( /[\r ]+\n/g, '\n' ) !== newValue.replace( /[\r ]+\n/g, '\n' );
			this.updateButton( this.clickedElement, changed );

			/* Normalisierte Zeilenumbrüche nie als Änderung werten, das vermeidet Flackern */
			return changed || oldValue.replace( /\r+$/gm, '' ) !== newValue;
		},
		/**
		 * @param {HTMLAnchorElement} [a]
		 * @param {boolean} [changed]
		 */
		updateButton: function( a, changed ) {
			if ( !a || !a.nodeType || a.rel === 'autoFormatter' ) {
				$( a && a.nodeType ? a : '[rel=autoFormatter]' ).css( {
					backgroundColor: changed ? '#DEF740' : '',
					borderRadius: changed ? '3px' : '',
					opacity: changed === false ? '.4' : ''
				} );
			} else if ( a && a.style ) {
				a.style.color = changed === false ? 'silver' : ( changed ? 'green' : '' );
			}
		},
		cleanElement: function( e ) {
			var t;

			e.focus();
			if ( typeof e.selectionStart === 'number' ) {
				var scroll = e.scrollTop,
					s1 = e.selectionStart,
					s2 = e.selectionEnd;

				if ( s2 > s1 && ( s1 > 0 || s2 < e.value.length ) ) {
					t = this.cleanText( e.value.substring( s1, s2 ) );
					if ( t === false ) {
						return false;
					}
					var newValue = e.value.substr( 0, s1 ) + t + e.value.substr( s2 );
					e.value = newValue;
					/* Fix for Opera */
					s2 = s1 + t.length + ( e.value.length - newValue.length );
				} else if ( !this.cleanAll( e ) ) {
					return false;
				}
				e.selectionStart = s1;
				e.selectionEnd = s2;
				e.scrollTop = scroll;
				return true;
			} else if ( typeof document.selection === 'object' ) {
				var range = document.selection.createRange();
				if ( range.text.length ) {
					t = this.cleanText( range.text );
					if ( t !== false ) {
						range.text = t;
					}
					return t !== false;
				} else {
					return this.cleanAll( e );
				}
			} else {
				return this.cleanAll( e );
			}
		},
		cleanAll: function( e ) {
			this.isAll = true;
			var t = this.cleanText( $( e ).val() );
			if ( t !== false ) {
				$( e ).val( t.replace( /^\s*\n/, '' ) );
			}
			return t !== false;
		},
		/**
		 * @param {string} summary
		 * @return {string}
		 */
		cleanSummary: function( summary ) {
			summary = this.cleanWikimediaLinks( summary );
			summary = this.cleanInternalLinks( summary );
			return this.cleanTypography( summary );
		},
		/**
		 * @param {string} t
		 * @return {string|boolean}
		 */
		cleanText: function( t ) {
			var oldValue = t;

			/* Remove control characters, undefined code points, LINE/PARAGRAPH SEPARATOR, BOM */
			t = t.replace( /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F\u2028\u2029\uFEFF]+/g, '' );
			t = t.replace(
				/[\t ]*[\t\xA0\xAD\u1680\u180E\u2000-\u200D\u202F\u205F\u2060\u3000]+[\t\r ]*\n/g,
				'\n'
			);
			t = t.replace( /(^|==|[^=\\]) +\n/g, '$1\n' );

			/* Unsichtbares weiches Trennzeichen sichtbar machen, egal wo */
			t = t.replace( /(?:\xAD|&#*(?:shy|x0*AD\b|0*173\b);?)+/gi, '&shy;' );
			/* ZERO WIDTH SPACE nur im Lateinischen entfernen */
			t = t.replace( /([\x00-\u024F])\u200B+(?=[\x00-\u024F])/g, '$1' );
			/* LRM ist wirkungslos, wenn es neben einem LR-Zeichen steht */
			t = t.replace( /\u200E+(?=[A-Z\]ªµºÀ-ÖØ-öø-\u02B8])/gi, '' );
			t = t.replace( /([A-ZªµºÀ-ÖØ-öø-\u02B8])\u200E+/gi, '$1' );
			t = t.replace( /\u200E+/g, '&lrm;' );

			t = this.backupNowikis( t );
			t = this.cleanCharacterEntities( t );
			t = this.cleanGalleries( t );
			t = this.backupFilenames( t );
			t = this.cleanHeadlines( t );

			/* Einheitliche Schreibweisen für Schlüsselwörter incl. Leerzeichenausgleich */
			t = t.replace(
				/\{\{\s*(SEITENTITEL|DISPLAYTITLE):\s*/gi,
				this.localisation === 'de' ? '{\{SEITENTITEL:' : this.localisation
					? '{\{DISPLAYTITLE:'
					: '{\{$1:'
			);
			t = t.replace(
				/#(WEITERLEITUNG|REDIRECT)[\s:=]*\[+\s*([^[\]|]*[^\s[\]|])(?:\s*\|[^[\]]*)?\]+/gi,
				this.localisation === 'de' ? '#WEITERLEITUNG [[$2]]' : this.localisation
					? '#REDIRECT [[$2]]'
					: '#$1 [[$2]]'
			);
			t = t.replace(
				/\[\[ *(Category|Kategorie)\s*:\s*([^[\]|]*[^\s[\]|])\s*(?=[\]|])/gi,
				this.localisation === 'de' ? '[[Kategorie:$2' : this.localisation
					? '[[Category:$2'
					: '[[$1:$2'
			);

			t = this.cleanThumbnails( t );
			t = this.cleanReferences( t );
			t = this.cleanTags( t );
			t = this.cleanExternalLinks( t );
			t = this.cleanWikimediaLinks( t );
			t = this.cleanInternalLinks( t );
			t = this.cleanTemplates( t );
			t = this.cleanISSNs( t );

			t = t.replace(
				/\bclass\s*=\s*(?:(") *([ \w-]*? ?))?(?: *\bprettytable\b)+/g,
				'class=$1$2wikitable'
			);
			/* Unnötige Leerzeichen bei HTML-Attributen, wichtig vor den Anführungszeichen */
			t = t.replace( /[!<|][ \w"-;=?[\]]*\b *= +"/g, function( $0 ) {
				return $0.replace( /(\b[a-z]+\b) *= *"/g, '$1="' );
			} );

			/* Ersten Interlanguage-Link suchen; 9 wegen [[zh-classical:…]] */
			var i = t.search( /^\[\[ *[a-z]{2,3}(?:-[a-z-]{2,9})? *:/m ),
				slice;
			if ( i > 0 ) {
				i = Math.max( i, t.indexOf( '<references', i ) );
				slice = t.slice( i );
				t = t.slice( 0, i );
			}
			t = this.cleanTypography( t );
			t = this.cleanDates( t );
			if ( slice ) {
				t += slice;
			}

			t = this.cleanDuplicateLinks( t );
			t = this.cleanUnits( t );
			t = this.cleanNonBreakingSpaces( t );
			t = this.cleanISBNs( t );
			t = this.cleanPMIDs( t );
			t = this.cleanCategories( t );
			t = this.cleanNewlines( t );

			t = this.cleanRedundantTemplateParameters( t );
			t = this.cleanTemplatesByRules( t );
			t = this.executeUserReplacements( t );

			t = this.restoreFilenames( t );
			t = this.restoreNowikis( t );

			var changed = this.isChanged( oldValue, t );
			return changed ? t : false;
		},
		cleanCharacterEntities: function( t ) {
			var entities = {
				/* Unicodeblock Basis-Lateinisch (U+0000 bis U+007F) */
				'grave': '`',
				/* Unicodeblock Lateinisch-1, Ergänzung (U+0080 bis U+00FF) */
				'cent': '¢', 'pound': '£', 'yen': '¥', 'sect': '§', 'laquo': '«', 'deg': '°',
				'plusmn': '±', 'pm': '±', 'sup2': '²', 'sup3': '³', 'acute': '´', 'centerdot': '·',
				'middot': '·', 'raquo': '»', 'frac14': '¼', 'frac12': '½', 'half': '½',
				'frac34': '¾', 'Auml': 'Ä', 'Ouml': 'Ö', 'times': '×', 'Uuml': 'Ü', 'szlig': 'ß',
				'auml': 'ä', 'ouml': 'ö', 'div': '÷', 'divide': '÷', 'uuml': 'ü',
				/* Unicodeblock Allgemeine Interpunktion (U+2000 bis U+206F) */
				'ndash': '–', 'mdash': '—', 'lsquo': '‘', 'rsquo': '’', 'rsquor': '’',
				'lsquor': '‚', 'sbquo': '‚', 'ldquo': '“', 'rdquo': '”', 'rdquor': '”',
				'bdquo': '„', 'ldquor': '„', 'dagger': '†', 'Dagger': '‡', 'ddagger': '‡',
				'bull': '•', 'bullet': '•', 'hellip': '…', 'mldr': '…', 'permil': '‰', 'prime': '′',
				'Prime': '″', 'lsaquo': '‹', 'rsaquo': '›',
				/* Unicodeblock Währungszeichen (U+20A0 bis U+20CF) */
				'euro': '€',
				/* Unicodeblock Pfeile (U+2190 bis U+21FF) */
				'rarr': '→', 'harr': '↔',
				/* Unicodeblock Mathematische Operatoren (U+2200 bis U+22FF) */
				'minus': '−', 'infin': '∞', 'ap': '≈', 'approx': '≈', 'asymp': '≈', 'ne': '≠',
				'le': '≤', 'leq': '≤', 'ge': '≥', 'geq': '≥'
			};
			/* Limit to U+FFFF because of compatibility reasons, keep &#x1000F; intact */
			t = t.replace(
				/&#*(x([\dA-F]{2,})|(\d{3,})|[a-z]{2,9}\d{0,2}\b)(?![\dA-F=]);?/gi,
				function( $0, $1, $2, $3 ) {
					if ( $2 ) {
						$3 = parseInt( $2, 16 );
					}
					/* Don't decode spaces and control characters */
					if ( $3 > 160 && $3 < 8191
						|| $3 > 8207 && $3 < 8232
						|| $3 > 8239 && $3 < 8287
						|| $3 > 8303 && $3 < 55296
					) {
						return String.fromCharCode( $3 );
					}
					return entities[$1] || entities[$1.toLowerCase()] || $0;
				}
			);
			t = t.replace( /&#*(?:amp|x0*26|0*38)\b;?/gi, '&amp;' );
			t = t.replace( /&amp;(?![#\w])/gi, '&' );
			/* Geschützte Leerzeichen einheitlich als "&nbsp;", vereinfacht viele folgende Suchmuster */
			return t.replace( /&#*(?:nbsp|x0*A0\b|0*160\b);?/gi, '&nbsp;' );
		},
		cleanTags: function( t ) {
			t = t.replace( /(<\/?s)trike\b/gi, '$1' );
			t = t.replace(
				/<sub\s*(>[^<>]*<)\s*(?:su[bp]\s*[.\/\\]+|[.\/\\]+\s*su[bp])\s*>/gi,
				'<sub$1/sub>'
			);
			t = t.replace(
				/<sup\s*(>[^<>]*<)\s*(?:su[bp]\s*[.\/\\]+|[.\/\\]+\s*su[bp])\s*>/gi,
				'<sup$1/sup>'
			);

			/* Drop default font attributes */
			t = t.replace(
				/(<font\b[^<>]*?)\s+fa\w+(?:[\s"',=]*(?:Arial|Helvetica(?:\W?N\w*)?|sans\W?serif)\b)+[\s"';]*(?=\s\w+\s*=|>)/gi,
				'$1'
			);
			t = t.replace(
				/(<font\b[^<>]*?)\s+size[\s"',=]*(?:-1\b|2\b|100\b[ ,.]*\d*%|1(?:\.0*)?em\b)["';]*/gi,
				'$1'
			);
			/* Remove tags with no content and no attributes */
			t = t.replace(
				/<(\w+)\s*(\s\w[^<\/>]*)?>\s*<\/\1\b[^<>]*>/gi,
				function( $0, $1, $2 ) {
					if ( ( $2 && /^ref/i.test( $1 ) ) || /^[bh]r$/i.test( $1 ) ) {
						return '<' + $1.toLowerCase() + ( $2 || '' ) + ' />';
					}
					return $2 && /\bclear:/i.test( $2 ) ? $0 : '';
				}
			);
			/* Remove inline elements with no attributes */
			while ( /<(font|span)\s*>\s*(?:<(?!\1)|[^<])*?\s*<\/\1[^<>]*>/i.test( t ) ) {
				t = t.replace( /<(font|span)\s*>\s*((?:<(?!\1)|[^<])*?)\s*<\/\1[^<>]*>/gi, '$2' );
			}
			t = t.replace(
				/<font\s+color[\s"',=]*(#[\dA-F]{3,6}|[a-z]{3,20})[\s"';]*>((?:<(?!font)|[^<])*?)<\/font[^<>]*>/gi,
				'<span style="color:$1;">$2<\/span>'
			);
			t = t.replace(
				/<font\s+size[\s"',=]*(?:-[2-9]|[01])[\s"';]*>((?:<(?!font)|[^<])*?)<\/font[^<>]*>/gi,
				'<small>$1<\/small>'
			);
			t = t.replace(
				/<font\s+size[\s"',=]*(?:[+-]0|3)[\s"';]*>((?:<(?!font)|[^<])*?)<\/font[^<>]*>/gi,
				'<span style="font-size:larger;">$1<\/span>'
			);
			/* Merge nested inline tags */
			t = t.replace(
				/<(abbr|cite|mark|q|s|small|u)\s*><(font|span)\s+style\s*=\s*["']?([^\n"<>]*?);?["']?\s*>([^<>]*)<\/\2\s*>\s*(?=<\/\1\s*>)/gi,
				'<$1 style="$3;">$4'
			);
			t = t.replace(
				/(<span\b[^<>]*?)\s+style\s*=\s*["']?([^\n"<>]*?);?["']?\s*><span\s+style\s*=\s*["']?([^\n"<>]*?);?["']?\s*>([^<>]*)<\/span\s*>\s*(?=<\/span\s*>)/gi,
				'$1 style="$2; $3;">$4'
			);

			/* Verschiedenste Formen von HTML-Zeilenumbrüchen durch einheitliche ersetzen */
			t = t.replace( /<(?:[\s\/\\]*br\b)+\s*(\s\w[^<>]*?)?[\s.\/\\]*>/gi, '<br$1 />' );
			/* Unnötige HTML-Zeilenumbrüche entfernen, wenn sowieso ein Absatz folgt */
			t = t.replace( / *<br \/>(?=\n[\n#*:;])/gi, '' );
			t = t.replace(
				/<(ref|small|su[bp])\b\s*(\s\w[^<>]*?)?\s*><small\s*>([^<>]*)<\/small\s*><\/\1\s*>/gi,
				'<$1$2>$3<\/$1>'
			);
			t = t.replace(
				/<small\s*><(ref|small|su[bp])\b\s*(\s\w[^<>]*?)?\s*?( ?\/|>[^<>]*<\/\1)\s*><\/small\s*>/gi,
				'<$1$2$3>'
			);
			/* Drop old navigation bar wrapper, see [[Template:NaviBlock]] */
			return t.replace(
				/<div\s+class[^<>\w]*BoxenVerschmelzen[^<>\w]*>\s*(\{\{[^#:<>{}]*\}\})\s*<\/div>/gi,
				'$1'
			);
		},
		cleanGalleries: function( t ) {
			return t.replace(
				/<gallery\b([^<>]*)>([^<>]+)<\/gallery\b[^<>]*>/gi,
				function( $0, $1, $2 ) {
					return '<gallery' + $1 + '>' + $2
						.replace( /^(\s*)\[+([^[\]]*)\]\]?\s*$/gm, '$1$2' )
						.replace( /^(\s*)\[+/gm, '$1' ) + '<\/gallery>';
				}
			);
		},
		cleanHeadlines: function( t ) {
			/* Fettung zumindest kompletter Überschriften ist unerwünscht */
			t = t.replace( /^(=+) *'''([^\n']+)''' *(?==+$)/gm, '$1 $2 ' );
			/* Repariert kaputte Überschriften, entfernt Doppelpunkte, setzt Leerzeichen */
			t = t.replace( /^(=+) *(.*[^\s=:]) *:? *\1$/gm, '$1 $2 $1' );
			/* Normalize "External links" headlines, use "Weblinks" in German */
			return t.replace(
				/^== *(?:Externer?|External)?(?:&nbsp;|\s)*(?:Weblinks?|Links?|Webseiten?|Websites?) *=+/gim,
				this.lang === 'de' ? '== Weblinks ==' : '== External links =='
			);
		},
		cleanThumbnails: function( t ) {
			if ( this.localisation === 'de' ) {
				/* Unnötiges "rechts" kürzen */
				t = t.replace(
					/(\[\[Datei:[^\n[\]]*[^\s[\]|])\s*\|+\s*(?:(?:mini|miniatur|thumb)\s*\|+\s*r(?:echts|ight)|r(?:echts|ight)\s*\|+\s*(?:mini|miniatur|thumb))\s*\|+\s*/gi,
					'$1|thumb|'
				);
				/* Set the order to "thumb|upright" if one isn't localized */
				t = t.replace(
					/(\[\[Datei:[^\n[\]]*[^\s[\]|])\s*\|+\s*(?:upright([\s=_\d.]*)\|+\s*(?:mini|miniatur|thumb)|(?:hochkan|uprigh)t([\s=_\d.]*)\|+\s*thumb)\s*\|+\s*/gi,
					'$1|mini|hochkant$2$3|'
				);
				t = t.replace(
					/(\[\[Datei:[^\n[\]]*[^\s[\]|])\s*\|+\s*(?:mini|thumb)\s*\|+\s*/gi,
					'$1|mini|'
				);
				t = t.replace(
					/(\[\[Datei:[^\n[\]]*[^\s[\]|])\s*\|+\s*r(?:echts|ight)\s*\|+\s*/gi,
					'$1|rechts|'
				);
				/* Änderung von "miniatur" in "mini" nur zusammen mit anderen Änderungen */
				t = t.replace(
					/(\[\[Datei:[^\n[\]]*[^\s[\]|])\s*\|+\s*(?:((?:left|none|cent[er]+|[en]*framed?|frameless|upright)\s*\|+)\s*miniatur|miniatur\s*(\|+\s*(?:left|none|cent[er]+|[en]*framed?|frameless|upright)))\s*\|+\s*/gi,
					'$1|$2mini$3|'
				);
				t = t.replace(
					/(\[\[Datei:[^\n[\]]*[^\s[\]|])\s*\|+\s*l(?:inks|eft)\s*\|+\s*/gi,
					'$1|links|'
				);
				t = t.replace(
					/(\[\[Datei:[^\n[\]]*[^\s[\]|])\s*\|+\s*(?:oh|no)ne\s*\|+\s*/gi,
					'$1|ohne|'
				);
				t = t.replace(
					/(\[\[Datei:[^\n[\]]*[^\s[\]|])\s*\|+\s*(?:zentriert|cent[er]+)\s*\|+\s*/gi,
					'$1|zentriert|'
				);
				t = t.replace(
					/(\[\[Datei:[^\n[\]]*[^\s[\]|])\s*\|+\s*(?:gerahmt|[en]*framed?)\s*\|+\s*/gi,
					'$1|gerahmt|'
				);
				t = t.replace(
					/(\[\[Datei:[^\n[\]]*[^\s[\]|])\s*\|+\s*(?:rahmenlo|frameles)s\s*\|+\s*/gi,
					'$1|rahmenlos|'
				);
				t = t.replace(
					/(\[\[Datei:[^\n[\]]*[^\s[\]|])\s*\|+\s*(?:hochkan|uprigh)t[\s=_]*([\d.]*)\s*\|+\s*/gi,
					function( $0, $1, $2 ) { return $1 + '|hochkant' + ( $2 ? '=' + $2 : '' ) + '|'; }
				);
			}
			/* vertical-align values from the CSS standard */
			t = t.replace(
				/(\[\[(?:Datei|File):[^\n[\]]*[^\s[\]|])\s*\|+\s*(?:grundlinie|baseline)\s*\|+\s*/gi,
				'$1|baseline|'
			);
			t = t.replace(
				/(\[\[(?:Datei|File):[^\n[\]]*[^\s[\]|])\s*\|+\s*(?:tief(?:gestellt)?|sub)\s*\|+\s*/gi,
				'$1|sub|'
			);
			t = t.replace(
				/(\[\[(?:Datei|File):[^\n[\]]*[^\s[\]|])\s*\|+\s*(?:hoch(?:gestellt)?|sup|super)\s*\|+\s*/gi,
				'$1|super|'
			);
			t = t.replace(
				/(\[\[(?:Datei|File):[^\n[\]]*[^\s[\]|])\s*\|+\s*(?:oben|top)\s*\|+\s*/gi,
				'$1|top|'
			);
			t = t.replace(
				/(\[\[(?:Datei|File):[^\n[\]]*[^\s[\]|])\s*\|+\s*text-(?:oben|top)\s*\|+\s*/gi,
				'$1|text-top|'
			);
			t = t.replace(
				/(\[\[(?:Datei|File):[^\n[\]]*[^\s[\]|])\s*\|+\s*mi(?:tt|ddl)e\s*\|+\s*/gi,
				'$1|middle|'
			);
			t = t.replace(
				/(\[\[(?:Datei|File):[^\n[\]]*[^\s[\]|])\s*\|+\s*(?:unten|bottom)\s*\|+\s*/gi,
				'$1|bottom|'
			);
			return t.replace(
				/(\[\[(?:Datei|File):[^\n[\]]*[^\s[\]|])\s*\|+\s*text-(?:unten|bottom)\s*\|+\s*/gi,
				'$1|text-bottom|'
			);
		},
		cleanExternalLinks: function( t ) {
			t = t.replace( /\b(?:http(s?)(?::+\/*|\/\/+:*)\b)+/gi, 'http$1://' );
			/* Doppelte eckige Klammern um Weblinks vereinfachen */
			t = t.replace( /\[+ *(https?:\/\/[^\n[\]]*?) *\]+/gi, '[$1]' );
			/* Weblinks mit senkrechtem Strich reparieren */
			t = t.replace( /(\[https?:\/\/[^\s[\]|]*?) *\| *(?=[^\s=[\]|]+\])/gi, '$1 ' );
			/* Schrägstriche am Ende einfacher Domains ergänzen */
			t = t.replace( /(\[https?:\/\/\w[\w.-]*\w\.\w+) +/gi, '$1/ ' );
			/* Domains klein schreiben, egal ob beschriftet oder nicht */
			return t.replace( /\bhttps?:\/\/\b[0-9a-z.-]*[A-Z][\w.-]*/g, function( $0 ) {
				return $0.toLowerCase();
			} );
		},
		cleanWikimediaLinks: function( t ) {
			if ( typeof window.autoFormatWikimediaLinks !== 'undefined'
				&& !window.autoFormatWikimediaLinks
			) {
				return t;
			}

			var wiki = mw.config.get( 'wgDBname' ).replace( /wiki$/i, '' ),
				ns = mw.config.get( 'wgFormattedNamespaces' )[-1];

			/* Permanente Weblinks in Spezialseiten-Syntax umwandeln */
			var permaLinkReplace = function( $0, $1, $2, $3, $4 ) {
				var m = /^(\d*([^#]*))(.*)$/.exec( $3 );
				/* Must use {{fullurl:…}} when there are more parameters than title and oldid */
				if ( m && m[2] ) {
					/* {{fullurl::|oldid=…}} with no page name is not possible any more */
					if ( !$2 ) {
						return $0;
					}
					return '[{\{fullurl:' + ( $1 === wiki ? '' : $1 + ':' )
						+ $2.replace( /_/g, ' ' ) + '|oldid=' + m[1] + '}}' + m[3]
						+ ( typeof $4 === 'string' ? ' ' + $4 : '' ) + ']';
				} else {
					return '[[:' + $1 + ':' + ( $1 === wiki ? ns : 'Special' )
						+ ':Permanent' + ( $1 === 'de' ? 'er ' : '' ) + 'Link/' + $3
						+ ( typeof $4 === 'string' ? '|' + $4 : '' ) + ']]';
				}
			};
			/* Weblinks auf Sprachversionen (auch auf die eigene) in Wikilinks umwandeln */
			var interWikiReplace = function( $0, $1, $2, $3 ) {
				/* Auf Alternative ausweichen, wenn Parameter enthalten wind */
				var m = /^([^?]*)\?([^#]*)(.*)$/.exec( $2 );
				try {
					return m ? '[{\{fullurl:' +
						( $1 === wiki ? '' : $1 + ':' ) +
						decodeURIComponent( m[1] ).replace( /_/g, ' ' ) + '|' + m[2] + '}}' + m[3] +
						( typeof $3 === 'string' ? ' ' + $3 : '' ) + ']' :
						'[[:' + $1 + ':' + $2.replace( /_/g, ' ' ) +
							( typeof $3 === 'string' ? '|' + $3 : '' ) + ']]';
				} catch ( ex ) {
					return $0;
				}
			};
			/* Alle projektinternen Weblinks protokollrelativ machen */
			t = t.replace( /\[ *https?:\/+(?=[a-z-]+\.wikipedia\.org\b)/gi, '[//' );
			/* Schreibweise [[Weblink#Anker mit Leerzeichen|Beschriftung]] reparieren */
			t = t.replace(
				/\[+\/\/([a-z-]+)\.wikipedia\.org\/w\/[\w.]*\?(?:title=([^\s&[\]|]*)&)?oldid=([^\n?[\]|]+?) *\|+ *([^\n[\]|]*?) *\]+/gi,
				permaLinkReplace
			);
			t = t.replace(
				/\[+\/\/([a-z-]+)\.wikipedia\.org\/wiki\/([^\n[\]|]*?) *\|+ *([^\n[\]|]*?) *\]+/gi,
				interWikiReplace
			);
			/* Schreibweise [Weblink#Anker Beschriftung] umwandeln */
			t = t.replace(
				/\[+\/\/([a-z-]+)\.wikipedia\.org\/w\/[\w.]*\?(?:title=([^\s&[\]|]*)&)?oldid=([^\s?[\]|]+) +([^\n[\]|]+?) *\]+/gi,
				permaLinkReplace
			);
			t = t.replace(
				/\[+\/\/([a-z-]+)\.wikipedia\.org\/wiki\/([^\s[\]|]*) +([^\n[\]|]+?) *\]+/gi,
				interWikiReplace
			);
			/* Schreibweise [Weblink#Anker] umwandeln */
			t = t.replace(
				/\[+\/\/([a-z-]+)\.wikipedia\.org\/w\/[\w.]*\?(?:title=([^\s&[\]|]*)&)?oldid=([^\s?[\]|]+) *\]+/gi,
				permaLinkReplace
			);
			t = t.replace(
				/\[+\/\/([a-z-]+)\.wikipedia\.org\/wiki\/([^\s[\]|]*) *\]+/gi,
				interWikiReplace
			);
			/* Verbliebene projektinterne Weblinks ohne eckige Klammern ebenfalls umwandeln */
			t = t.replace(
				/\bhttps?:\/\/([a-z-]+)\.wikipedia\.org\/w\/[\w.]*\?(?:title=([^\s&[\]|]*)&)?oldid=([^\s?<>[\]{|}]*[^\s!"),.:;<>?[\\\]{|}])(?=[\s!),.:;<]|$)/gim,
				permaLinkReplace
			);
			return t.replace(
				/\bhttps?:\/\/([a-z-]+)\.wikipedia\.org\/wiki\/([^\s<>\[\]{|}]*[^\s!",.:;<>?\[\\\]{|}])(?=[\s!,.;<]|$)/gim,
				interWikiReplace
			);
		},
		cleanInternalLinks: function( t ) {
			var wiki = mw.config.get( 'wgDBname' ).replace( /wiki$/i, '' ),
				ns = mw.config.get( 'wgFormattedNamespaces' )[-1];

			/* Unnötig gewordene Vorlage in Spezialseiten-Syntax umwandeln */
			t = t.replace(
				/\{\{\s*Permalink\s*\|[^{|}]*\|\s*(\d+(?: ?#[^{|}]*?)?)\s*(?:(\|)\s*([^{|}]*?))?\s*\}\}/gi,
				'[[' + ns + ':Permanent' + ( wiki === 'de' ? 'er ' : '' ) + 'Link/$1$2$3]]'
			);
			/* Make selected "fullurl" parser function calls more compact */
			t = t.replace(
				/\{\{\s*fullurl:\s*([^\n{|}]+)\|\s*(?:diff=prev&oldid=(\d+)|oldid=(\d+)&diff=prev)\s*\}\}/gi,
				'{\{fullurl:$1|diff=$2$3}}'
			);

			/* https://www.mediawiki.org/wiki/Help:Lint_errors/multi-colon-escape */
			t = t.replace( /\[\[::+/gi, '[[:' );

			/* Wikilinks mit unnötigem Präfix ":w:de:", "w:de:" oder ":de:" vereinfachen */
			t = t.replace(
				new RegExp(
					'\\[\\[ *(?::? *w *)?: *' + wiki
						+ ' *: *(((?:Bild|Datei|File|Image|[CK]ategor[iy]e?) *:)?[^\\n[\\]]*\\S) *\\]\\]',
					'gi'
				),
				function( $0, $1, $2 ) {
					return '[[' + ( $2 ? ':' : '' ) + $1 + ']]';
				}
			);

			/* Anker in internen Links dekodieren */
			t = t.replace(
				/(\[\[[^\n#[\]{|]*#)([^\n#[\]|]+)(?=\|?[^\n#[\]|}]*\]\])/g,
				function( $0, $1, $2 ) {
					try {
						/* Kodierung einiger Zeichen beibehalten (%25, %5B, %5D, %7B-%7D) */
						return $1 + decodeURIComponent( $2.replace( /\.(?=[289A-E][\dA-F]|[357][B-F]|40|60)/g, '%' ) ).
							replace( /[%[\]{|}]/g, function( $0 ) {
								return '%' + $0.charCodeAt( 0 ).toString( 16 ).toUpperCase();
							} );
					} catch ( ex ) {
						return $0;
					}
				}
			);
			/* Sonstige kodierte Linkziele dekodieren */
			t = t.replace(
				/\[\[([^\n#%[\]{|}]*%[2-9A-E][^\n#[\]{|}]*)(?=#?[^\n[\]{|}]*\|?[^\n[\]{|}]*\]\])/gi,
				function( $0, $1 ) {
					try {
						/* Kodierung einiger Zeichen beibehalten (%25, %3C, %3E, %5B, %5D, %7B-%7D) */
						return '[[' + decodeURIComponent( $1 ).replace( /[%<>[\]{|}]/g, function( $0 ) {
							return '%' + $0.charCodeAt( 0 ).toString( 16 ).toUpperCase();
						} );
					} catch ( ex ) {
						return $0;
					}
				}
			);
			/* Verbliebene Unterstriche aus Links entfernen */
			t = t.replace(
				/\[\[[^\n[\]_{|}]+_[^\n[\]{|}]+(?=\|?[^\n[\]{|}]*\]\])/g,
				function( $0 ) {
					return $0.replace( /_/g, ' ' );
				}
			);

			/* Save relevant spaces at the beginning of links */
			t = t.replace( /(?: +|(\S))(\[\[[^\n[\]|]\|) +/g, '$1 $2' );
			/* Save relevant spaces at the end of links */
			t = t.replace( /(\[\[[^\n[\]|]\|[^\n[\]|]*[^\s[\]|]) +]](?: +|(?=\S))/g, '$1]] ' );
			/* [[Link|Dash-]] wird zu [[Link|Dash]]- und [[Link|Die]]s zu [[Link|Dies]], weil besser lesbar;
			   MediaWiki akzeptiert hier wirklich nur Kleinbuchstaben, ä, ö, ü und ß */
			t = t.replace(
				/\[\[ *([^\n[\]|]+?) *(\|[^\n[\]|]+?)(?:(-+)]](?![^\w"'(<[«\xC0-\u024F‚„‹])|]]([a-zßäöü]*))/g,
				'[[$1$2$4]]$3'
			);
			t = t.replace( /(^|[^'])\[\[([^\n:[\]|]+)\|('{2,5}) *\2 *\3]](?!')/g, '$1$3[[$2]]$3' );

			var unmaskLinks = typeof window.autoFormatMaskedLinks === 'undefined'
					|| window.autoFormatMaskedLinks,
				capitalLinks = /^\w+wiki$/.test( mw.config.get( 'wgDBname' ) );
			/* [[Link|Link]]s werden zu [[Link]]s weil kürzer und besser lesbar */
			return t.replace(
				new RegExp(
					'\\[\\[([^\\n:[\\]|])([^\\n:[\\]|]*)\\| *([^\\n:[\\]|]\\2)('
						+ ( unmaskLinks ? '[^\\n[\\]|]' : '[a-zßäöü]' )
						+ '*?) *]]',
					'g'
				),
				function( $0, $1, $2, $3, $4 ) {
					return ( capitalLinks
						? $1.toLowerCase() !== $3.charAt().toLowerCase()
						: $1 !== $3.charAt() )
						? $0
						: '[[' + $3 + ']]' + $4;
				}
			);
		},
		cleanDuplicateLinks: function( t ) {
			/* Remove links from dates that start with a year (e.g. ISO) */
			t = t.replace(
				/\[+([12]\d{3}\W+(?:3[01]|[12]\d|0?[1-9])\W+(?:3[01]|[12]\d|0?[1-9]))\]+/g,
				'$1'
			);

			/* Never link dates and years in Persondata templates */
			var re = /\{\{\s*P(erson(?:endaten|data)\b[^{}]*\|\s*(?:GEBURTSD|STERBED|DATE)[\s\w]*=[^\n=[\]{|}]*)\[+([^\n=[\]{|}]+)\]+/i;
			while ( re.test( t ) ) {
				t = t.replace( re, '{\{P$1$2' );
			}

			/* Exclude articles with titles like "1. März" or "March 1" */
			if ( /^(3[01]|[12]\d|[1-9])\.? \S+$/.test( mw.config.get( 'wgTitle' ) )
				|| /^\w+ (3[01]|[12]\d|[1-9])$/.test( mw.config.get( 'wgTitle' ) )
				|| /\[\[[CK]ategor[iy]e?:(Tag|Days of the year)[|\]]|\{\{(Artikel Jahr|Year nav)\s*[|}]/i.test( t )
			) {
				return t;
			}
			/* Exclude files and infoboxes from the start of the article */
			var m = /^(?:\s*\[\[\w+:(?:\[\[[^\n\]]*\]\]|[^\n\]])*\]\])*(?:\s*\{\{(?:\{\{[^}]*\}\}|[^}])*\}\})+/.exec( t ),
				start = m ? m[0].length : 0,
				found = [],
				a = [];
			/* Unlink years that are linked more than one time */
			re = /\[\[ *([12]\d{3}) *\]\]/g;
			/* Jeweils ersten Fund eines Jahres merken, danach entlinken */
			while ( m = re.exec( t ) ) {
				if ( m.index >= start ) {
					found[m[1]] ? a.push( m ) : found[m[1]] = true;
				}
			}
			var r = '',
				p = 0;
			for ( var i = 0; i < a.length; i++ ) {
				r += t.slice( p, a[i].index ) + a[i][1];
				p = a[i].index + a[i][0].length;
			}
			return p ? r + t.slice( p ) : t;
		},
		cleanDates: function( t ) {
			var months = mw.config.get( 'wgMonthNames' ) || ['', 'Januar', 'Februar', 'März', 'April',
				'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'];
			if ( this.lang === 'de' && /österreichbezogen\b/i.test( t ) ) {
				months[1] = 'Jänner';
			}

			/* Add missing space between day and month */
			t = t.replace( new RegExp( '([\\s!\'(>|„](?:3[01]|[12]\\d|0?[1-9])\\.?)(?=(?:' +
				months.slice( 1 ).join( '|' ) + ')\\b)', 'g' ), '$1 ' );
			/* No non-breaking space between month and year */
			t = t.replace( new RegExp( '(\\b(?:3[01]|[12]\\d|0?[1-9])\\.?(?:[\\s\\xA0]|&nbsp;)+(?:' +
				months.slice( 1 ).join( '|' ) + '))(?:\xA0|&nbsp;)(?=[12]\\d{3}\\b)', 'g' ), '$1 ' );
			if ( this.lang !== 'fi' ) {
				/* Missverständliches deutsches Datumsformat durch Langform ersetzen */
				var separator = this.lang === 'en' ? ' ' : '. ';
				t = t.replace(
					/([\s'(>„])(3[01]|[12]\d|0?[1-9])\. *(1[012]|0?[1-9])\. *(?=[12]\d{3}[!,.:;?]?[\s')<\]“](?!\w*\d))/g,
					function( $0, $1, $2, $3 ) {
						return $1 + ( $2 | 0 ) + separator + months[$3 | 0] + ' ';
					}
				);
			}
			/* Unspaced dashes in "1850–14 January" are bad style in German and English */
			var dash = this.lang === 'ru' ? '—' : '–';
			separator = this.lang === 'de' ? ' bis ' : ' – ';
			t = t.replace(
				/(\b +[12]\d{3}'*) *[–—−-] *('*(?:3[01]|[12]\d|0?[1-9])\.?) *([A-S][a-zä]{2,}\b)/g,
				function( $0, $1, $2, $3 ) {
					for ( var i = months.length; --i; ) {
						if ( $3 === months[i] ) {
							return $1 + separator + $2 + ' ' + $3;
						}
					}
					return $0;
				}
			);
			/* Bis-Striche in 4-stellige Jahreszahlenbereiche einsetzen */
			t = t.replace(
				/([\s!'(>|„])(?:\[\[ *([12]\d{3}) *\]\]|([12]\d{3})) *[–—-] *(?:\[\[ *([12]\d{3}) *\]\]|([12]\d{3}))(?=[!,.:;?]?[\s!')\/<\]|}“])/g,
				function( $0, $1, $2, $3, $4, $5 ) {
					return ( $2 || $3 ) < ( $4 || $5 ) ? $1 + ( $2 || $3 ) + dash + ( $4 || $5 ) : $0;
				}
			);
			/* Bis-Striche in 2-stellige Jahreszahlenbereiche einsetzen */
			t = t.replace(
				/([\s!'(>|„][12]\d(\d\d)) *[—-] *(?=(1[3-9]|[2-9]\d)[!,.:;?]?(?:[\s!')\/<\]|“]|$)|\?)/g,
				function( $0, $1, $2, $3 ) {
					return !$3 || $2 < $3 ? $1 + dash : $0;
				}
			);
			/* "1980 – 90" becomes "1980–1990" in the German Wikipedia, "1980–90" otherwise */
			var full = typeof window.autoFormatShortYearRanges !== 'undefined'
				? window.autoFormatShortYearRanges : this.lang === 'de';
			t = t.replace(
				/([\s!'(>|„]([12]\d)(\d\d)) *– *(?!(?:3[01]|[12]\d|0[1-9])\.? [A-S][a-zä]{2,}\b)(?=(\d\d)[!,.:;?]?(?:[\s!')\/<|“]|$))/g,
				function( $0, $1, $2, $3, $4 ) {
					return $3 < $4 ? $1 + '–' + ( full ? $2 : '' ) : $0;
				}
			);
			/* ISSNs aber ohne Bis-Striche, wichtig nach den Jahreszahlen */
			return t.replace( /(IS\wN\W*\d{4})–(?=\d)/g, '$1-' );
		},
		/**
		 * @param {string} t
		 * @return {string}
		 */
		cleanTypography: function( t ) {
			var de = this.lang === 'de',
				ru = this.lang === 'ru';

			/* Double quotes */
			if ( de || ru ) {
				t = t.replace(
					/(^|[\s!#'(*+\/:;>[|-])(?:"|,,)(?![\s>])([^\n"“”„]*[^\s"(;=“”„])"(?=[\s!'),.\/:;<?\]}-]|$)/g,
					ru || /\bschweizbezogen\b/i.test( t )
						&& ( t.indexOf( '«' ) !== -1 || t.indexOf( '„' ) === -1 )
						? '$1«$2»'
						: '$1„$2“'
				);
			}
			t = t.replace(
				/\{\{\s*((?:Zitat|")\s*\|\s*(?:(?:1|Text)\s*=)?[^={|}]*)/gi,
				function( $0, $1 ) {
					return '{\{' + $1.replace( /„([^\n‘‚“”„]+)“/g, '‚$1‘' );
				}
			);
			if ( this.lang !== 'en' ) {
				/* Replace exactly three dots with ellipsis */
				t = t.replace( /(^|[ '(>[|„])\.\.\.(?=[ '),<?\]}“]|$)/gm, '$1…' );
			}
			t = t.replace( /[,;](?:[ \xA0]|&nbsp;)*†(?: |&nbsp;)*(?=[\w[])/gi, '; † ' );
			t = t.replace(
				/\( *([\d,.]*\d(?: |&nbsp;)*[KMk]i?B)(?:ytes?)?([,;]) *([A-Z]{3,4}(?:\W+Datei)?) *\)/g,
				'($3$2 $1)'
			);
			t = t.replace(
				/\( *([A-Z]{3,4}(?:\W+Datei)?)([,;]) *([\d,.]*\d)(?: |&nbsp;)*([KMk]i?B)(?:ytes?)? *\)/g,
				function( $0, $1, $2, $3, $4 ) {
					$3 = $3.replace( de ? /\b\.(?=\d{3}\b)/g : /\b,(?=\d{3}\b)/g, '' );
					$3 = $3.replace( /^(\d*),(?=\d*$)/, '$1.' );
					$3 = ( $4.charAt() === 'M' ? Math.round( $3 * 10 ) / 10 : Math.round( $3 ) ) || $3;
					return '(' + $1 + ( de ? ( '; ' + $3 ).replace( /\./, ',' ) : $2 + ' ' + $3 )
						+ '&nbsp;' + $4 + ')';
				}
			);
			/* Bis-Striche bei Seitenzahlen */
			t = t.replace(
				/\b(Sp?\.|Seiten?|Spalten?) *(\d+) *[–—−-] *(?=\d+(?:[\s!),.\/:;<?\]|}“]|$))/g,
				'$1 $2–'
			);
			if ( this.lang !== 'it' ) {
				t = t.replace(
					/([\w"')>\]\xC0-\u024F“]) +-(,?) +(?=[\w"'(\[\xC0-\u024F„])/g,
					'$1 –$2 '
				);
			}
			return t;
		},
		cleanUnits: function( t ) {
			/* Prozentwerte erhalten seit Mitte 2007 automatisch ein geschütztes Leerzeichen */
			t = t.replace( /(\S)(?:\xA0|&nbsp;)(?=%)/gi, '$1 ' );
			if ( this.lang === 'de' || this.lang === 'ru' ) {
				t = t.replace(
					/([\s'(*+;«„][\u2212-]?\d+(?:[,–]\d+)?)(?=%[\s!'),.:<?\]|»“](?! *[\d"#);]))/gi,
					'$1 '
				);
				t = t.replace(
					/((?:\d|\b)[cmk]?m) *<[Ss][Uu][Pp]\s*>\s*([23²³])\s*<\/[Ss][Uu]\w\s*>(?=[\s!"'),\-.:;<?\]{|}–“])/g,
					function( $0, $1, $2 ) {
						return $1 + ( { '2': '²', '3': '³' }[$2] || $2 );
					}
				);
			}
			/* Maßeinheiten immer mit Leerzeichen */
			return t.replace(
				/([ '(*+:;„][\u2212-]?\d+(?:[,–]\d+)?) ?(k[Bgm]|Ki?B|k?Hz|[MGT](?:i?B|Hz)|cm|ha|m[lm]|[gm€¥])(?=[²³]?[ !'),.\/:;<?“])/g,
				'$1&nbsp;$2'
			);
		},
		cleanNonBreakingSpaces: function( t ) {
			/* Paragraf, Abs. und Satz mit geschützten Leerzeichen */
			t = t.replace(
				/§(?: *|&nbsp;)(\d\w* +Ab?s?\.)(?: *|&nbsp;)(\d+ +S\.) *(?=\d)/gi,
				'§&nbsp;$1&nbsp;$2&nbsp;'
			);
			t = t.replace( /§(?: *|&nbsp;)(\d\w* +Ab?s?\.) *(?=\d)/gi, '§&nbsp;$1&nbsp;' );
			t = t.replace( /§ *(?=\d)/gi, '§&nbsp;' );

			/* No non-breaking spaces in headlines */
			return t.replace( /^=.*&nbsp;.*=$/gim, function( $0 ) {
				return $0.replace( /(?:&nbsp;|\s)+/gi, ' ' );
			} );
		},
		cleanISBNs: function( t ) {
			t = t.replace( /\bISBN\W*(?:\d+&shy;(?=\d))+/gi, function ( $0 ) {
				return $0.replace( /&shy;/g, '' );
			} );
			/* ISBNs mit Bindestrichen gliedern */
			return t.replace(
				/(^|[\s#'(*>|])(?:(ISBN\d?\s*=\s*)|ISBN(?:-?1[03]\b| *1[03]:)?:?\s*)(9-?7-?[89]-?)?([013][\d\u2010-\u2012\u2212-]{8,}[\dX]\b)/gim,
				function( $0, $1, $2, $3, $4 ) {
					return $1 + ( $2 || 'ISBN ' ) + ( $3 || '' ).replace( /^9\D*7\D*(\d)\D*/, '97$1-' ) + $4.
						/* Remove all dashes */
						replace( /[^\dX]+/gi, '' ).
						/* Group 0 for English books */
						replace( /^0([01]\d)(\d{6})\B/, '0$1-$2-' ).
						replace( /^0([2-6]\d\d)(\d{5})\B/, '0$1-$2-' ).
						replace( /^0(7\d{3}|8[0-4]\d\d)(\d{4})\B/, '0$1-$2-' ).
						replace( /^0(8[5-9]\d{3})(\d{3})\B/, '0$1-$2-' ).
						replace( /^0(9[0-4]\d{4})(\d\d)\B/, '0$1-$2-' ).
						replace( /^0(9[5-9]\d{5})(\d)\B/, '0$1-$2-' ).
						/* Group 1 for English books */
						replace( /^1(0\d)(\d{6})\B/, '1$1-$2-' ).
						replace( /^1([1-3]\d\d)(\d{5})\B/, '1$1-$2-' ).
						replace( /^1(4\d{3}|5[0-4]\d\d)(\d{4})\B/, '1$1-$2-' ).
						replace( /^1(5[5-9]\d{3}|[67]\d{4}|8[0-5]\d{3}|86[0-8]\d\d|869[0-7]\d)(\d{3})\B/, '1$1-$2-' ).
						replace( /^1(869[89]\d\d|8[7-9]\d{4}|9[0-8]\d{4}|99[0-8]\d{3})(\d\d)\B/, '1$1-$2-' ).
						replace( /^1(999\d{4})(\d)\B/, '1$1-$2-' ).
						/* Group 3 for German books */
						replace( /^3(0[0-24-9]|1\d)(\d{6})\B/, '3$1-$2-' ).
						replace( /^3(03[0-3]|[2-6]\d\d)(\d{5})\B/, '3$1-$2-' ).
						replace( /^3(03[4-6]\d|7\d{3}|8[0-4]\d\d)(\d{4})\B/, '3$1-$2-' ).
						replace( /^3(03[7-9]\d\d|8[5-9]\d{3}|95[4-9]\d\d|9[69]\d{3})(\d{3})\B/, '3$1-$2-' ).
						replace( /^3(9[0-4]\d{4})(\d\d)\B/, '3$1-$2-' ).
						replace( /^3(95[0-3]\d{4}|9[78]\d{5})(\d)\B/, '3$1-$2-' ).
						/* Add missing dash after group */
						replace( /^([0-57]|6\d\d|8\d|9[0-4]|9[5-8]\d|99[0-8]\d|999\d\d)\B/, '$1-' );
				}
			);
		},
		cleanISSNs: function( t ) {
			return t.replace(
				/(^|[\s#'(*>{|])ISSN *(\|?)[ #:\u2010-\u2014\u2212-]*((?:\d[ \u2010-\u2014\u2212-]*){7}[\dX]\b)/gi,
				function( $0, $1, $2, $3 ) {
					return $1 + 'ISSN' + ( $2 || ' ' ) + $3.replace( /[^\dX]+/gi, '' )
						.replace( /^(.{4})/, '$1-' );
				}
			);
		},
		cleanPMIDs: function( t ) {
			return t.replace(
				/(^|[\s#'(*=>|])PMID[ #:\u2010-\u2014\u2212-]*(?=\d+\b)/gi,
				'$1PMID '
			);
		},
		cleanReferences: function( t ) {
			t = t.replace(
				/<\s*references\s*(\s\b[^<>]*?)?\s*(?:\/|>\s*<\s*\/\s*references)\s*>/gi,
				'<references$1 />'
			);
			t = t.replace( /<\s*references\s*(\s\b[^<\/>]*?)?\s*>/gi, '<references$1>' );
			t = t.replace( /<\s*\/\s*references\s*>/gi, '<\/references>' );
			if ( this.isAll ) {
				var re = /(<references[^<\/>]*)>/g,
					m;
				while ( m = re.exec( t ) ) {
					if ( t.indexOf( '<\/references>', m.index ) < 0 ) {
						t = t.slice( 0, m.index ) + m[1] + ' />' + t.slice( m.index + m[0].length );
					}
				}
			}
			t = t.replace( /< *ref\s*(\s\b[^<>]*?)\s*(?:\/+|>\s*<\s*\/+\s*ref) *>/gi, '<ref$1 />' );

			/* Zeilenumbrüche in Einzelnachweisen nur oben im Artikel entfernen */
			var i = t.indexOf( '<references' ),
				slice;
			if ( i > 0 ) {
				slice = t.slice( i );
				slice = slice.replace( /< *ref\s*(\s\b[^<\/>]*?)?\s*>[\t ]*/gi, '<ref$1>' );
				slice = slice.replace( /(?:(\n[\t ]*)|[\t ]*)<\s*\/+\s*ref\s*>/gi, '$1<\/ref>' );
				t = t.slice( 0, i );
			}
			t = t.replace( /< *ref\s*(\s\b[^<\/>]*?)?\s*>\s*/gi, '<ref$1>' );
			t = t.replace( /\s*<\s*\/+\s*ref\s*>/gi, '<\/ref>' );
			if ( slice ) {
				t += slice;
			}

			/* Leerzeichen zwischen Satzende und <ref> oder zwei <ref> entfernen */
			t = t.replace( /([!,.;?]|<ref\b[^<>]*(?:\/|>[^<>]*<\/ref)>) +(?=<ref[ >])/gi, '$1' );
			/* Zwei gleiche Satzzeichen vor und nach einem <ref> auf eins kürzen */
			return t.replace( /([!,.:;?])(<ref\b[^<>]*(?:\/|>[^<>]*<\/ref)>)\1/gi, '$1$2' );
		},
		cleanCategories: function( t ) {
			if ( this.lang !== 'de' && this.lang !== 'en' ) {
				return t;
			}

			t = t.replace(
				/\{\{\s*(SORTIERUNG|DEFAULT ?\w*SORT\w*)\s*[:|][\s\xA0]*/gi,
				this.localisation === 'de' ? '{\{SORTIERUNG:' : this.localisation ? '{\{DEFAULTSORT:' : '{\{$1:'
			);

			/* Match every character thats in one of the two replacement maps or should be deleted */
			var re = /["&'\-\/?`¡-¥©-´·-ſǍ-\u01ED\u01F8-\u021B\u02B0-\u036FΆ-ώ\u0400-Ј\u040D-ј\u045DўҐ-ғҚқҢңҮ-ұҺһ\u04D0-\u04D7\u1E00-ỹ\u2010-•′″‹›−ff-st]/g;
			/* Unicodeblock Lateinisch-1, Ergänzung (U+0080 bis U+00FF) */
			var trSet1 = '"/?¡¢£¤¥©ª«¬®°±²³·¹º»¿ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝàáâãäåçèéêëìíîïðñòóôõö÷øùúûüýÿ';
			var trSet2 = '    cL YCa  R  23 1o  AAAAAACEEEEIIIIDNOOOOOxOUUUUYaaaaaaceeeeiiiidnooooo ouuuuyy';
			/* Unicodeblock Lateinisch, erweitert-A (U+0100 bis U+017F) */
			trSet1 += 'ĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬĭĮįİıĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŔŕŖŗŘř';
			trSet2 += 'AaAaAaCcCcCcCcDdDdEeEeEeEeEeGgGgGgGgHhHhIiIiIiIiIiJjKkkLlLlLlLlLlNnNnNnnNnOoOoOoRrRrRr';
			trSet1 += 'ŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſ';
			trSet2 += 'SsSsSsSsTtTtTtUuUuUuUuUuUuWwYyYZzZzZzs';
			/* Unicodeblock Lateinisch, erweitert-B (U+0180 bis U+024F) */
			trSet1 += 'ǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǤǥǦǧǨǩǪǫǬǭǸǹǺǻǾǿȀȁȂȃȄȅȆȇȈȉȊȋȌȍȎȏȐȑȒȓȔȕȖȗȘșȚț';
			trSet2 += 'AaIiOoUuUuUuUuUueAaAaGgGgKkOoOoNnAaOoAaAaEeEeIiIiOoOoRrRrUuUuSsTt';
			/* Unicodeblock Kyrillisch (U+0400 bis U+04FF) */
			trSet1 += '\u0400ІЈ\u040DЎАБВГДЕЗИЙКЛМНОПРСТУФЦЪЫЭабвгдезийклмнопрстуфцъыэ\u0450іј\u045DўҐґҚқҮүҰұҺһӐӑӒӓӖӗ';
			trSet2 += 'EIJIUABWGDESIJKLMNOPRSTUFZAYEabwgdesijklmnoprstufzayeeijiuGgQqUuUuHhAaAaEe';
			/* Unicodeblock Lateinisch, weiterer Zusatz (U+1E00 bis U+1EFF) */
			trSet1 += 'ḀḁḂḃḄḅḆḇḈḉḊḋḌḍḎḏḐḑḒḓḔḕḖḗḘḙḚḛḜḝḞḟḠḡḢḣḤḥḦḧḨḩḪḫḬḭḮḯḰḱḲḳḴḵḶḷḸḹḺḻḼḽḾḿṀṁṂṃṄṅṆṇṈṉṊṋṌṍṎṏṐṑṒṓṔṕṖṗ';
			trSet2 += 'AaBbBbBbCcDdDdDdDdDdEeEeEeEeEeFfGgHhHhHhHhHhIiIiKkKkKkLlLlLlLlMmMmMmNnNnNnNnOoOoOoOoPpPp';
			trSet1 += 'ṘṙṚṛṜṝṞṟṠṡṢṣṤṥṦṧṨṩṪṫṬṭṮṯṰṱṲṳṴṵṶṷṸṹṺṻṼṽṾṿẀẁẂẃẄẅẆẇẈẉẊẋẌẍẎẏẐẑẒẓẔẕẖẗẘẙẚẛ\u1E9C\u1E9D\u1E9F';
			trSet2 += 'RrRrRrRrSsSsSsSsSsTtTtTtTtUuUuUuUuUuVvVvWwWwWwWwWwXxXxYyZzZzZzhtwyasssd';
			trSet1 += 'ẠạẢảẤấẦầẨẩẪẫẬậẮắẰằẲẳẴẵẶặẸẹẺẻẼẽẾếỀềỂểỄễỆệỈỉỊịỌọỎỏỐốỒồỔổỖỗỘộỚớỜờỞởỠỡỢợỤụỦủỨứỪừỬửỮữỰựỲỳỴỵỶỷỸỹ';
			trSet2 += 'AaAaAaAaAaAaAaAaAaAaAaAaEeEeEeEeEeEeEeEeIiIiOoOoOoOoOoOoOoOoOoOoOoOoUuUuUuUuUuUuUuYyYyYyYy';
			/* Unicodeblock Allgemeine Interpunktion (U+2000 bis U+206F) */
			trSet1 += '\u2012—―\u2016‗‘‚\u201B“”„\u201F†‡•′″‹›−';
			trSet2 += '                    ';
			var trMap = {
				'&': 'und', '¼': '14', '½': '12', '¾': '34',
				'Æ': 'Ae', 'Þ': 'Th', '\u1E9E': 'SS', 'ß': 'ss', 'æ': 'ae', 'þ': 'th', 'IJ': 'Ij',
				'ij': 'ij', 'Œ': 'Oe', 'œ': 'oe', 'Ǣ': 'Ae', 'ǣ': 'ae', 'Ǽ': 'Ae', 'ǽ': 'ae',
				/* Unicodeblock Griechisch und Koptisch (U+0370 bis U+03FF) */
				'Ά': 'Alpha', 'Έ': 'Epsilon', 'Ή': 'Eta', 'Ί': 'Iota', 'Ό': 'Omikron',
				'Ύ': 'Ypsilon', 'Ώ': 'Omega', 'ΐ': 'iota', 'Α': 'Alpha', 'Β': 'Beta', 'Γ': 'Gamma',
				'Δ': 'Delta', 'Ε': 'Epsilon', 'Ζ': 'Zeta', 'Η': 'Eta', 'Θ': 'Theta', 'Ι': 'Iota',
				'Κ': 'Kappa', 'Λ': 'Lambda', 'Μ': 'My', 'Ν': 'Ny', 'Ξ': 'Xi', 'Ο': 'Omikron',
				'Π': 'Pi', 'Ρ': 'Rho', 'Σ': 'Sigma', 'Τ': 'Tau', 'Υ': 'Ypsilon', 'Φ': 'Phi',
				'Χ': 'Chi', 'Ψ': 'Psi', 'Ω': 'Omega', 'Ϊ': 'Iota', 'Ϋ': 'Ypsilon', 'ά': 'alpha',
				'έ': 'epsilon', 'ή': 'eta', 'ί': 'iota', 'ΰ': 'ypsilon', 'α': 'alpha', 'β': 'beta',
				'γ': 'gamma', 'δ': 'delta', 'ε': 'epsilon', 'ζ': 'zeta', 'η': 'eta', 'θ': 'theta',
				'ι': 'iota', 'κ': 'kappa', 'λ': 'lambda', 'μ': 'my', 'ν': 'ny', 'ξ': 'xi',
				'ο': 'omikron', 'π': 'pi', 'ρ': 'rho', 'ς': 'sigma', 'σ': 'sigma', 'τ': 'tau',
				'υ': 'ypsilon', 'φ': 'phi', 'χ': 'chi', 'ψ': 'psi', 'ω': 'omega', 'ϊ': 'iota',
				'ϋ': 'ypsilon', 'ό': 'omikron', 'ύ': 'ypsilon', 'ώ': 'omega',
				/* Unicodeblock Kyrillisch (U+0400 bis U+04FF) */
				'Ё': 'Jo', 'Ђ': 'Dje', 'Ѓ': 'Gje', 'Є': 'Je', 'Ѕ': 'Dze', 'Ї': 'Ji', 'Џ': 'Dsche',
				'Ж': 'Sch', 'Х': 'Ch', 'Ч': 'Tsch', 'Ш': 'Sch', 'Щ': 'Schtsch', 'Ю': 'Ju',
				'Я': 'Ja', 'ж': 'sch', 'х': 'ch', 'ч': 'tsch', 'ш': 'sch', 'щ': 'schtsch',
				'ю': 'ju', 'я': 'ja', 'ё': 'jo', 'ђ': 'dje', 'ѓ': 'gje', 'є': 'je', 'ѕ': 'dze',
				'ї': 'ji', 'Ғ': 'Gh', 'ғ': 'gh', 'Ң': 'Ng', 'ң': 'ng', 'Ӕ': 'Ae', 'ӕ': 'ae',
				/* Unicodeblock Alphabetische Präsentationsformen (U+FB00 bis U+FB4F) */
				'ff': 'ff', 'fi': 'fi', 'fl': 'fl', 'ffi': 'ffi', 'ffl': 'ffl', 'ſt': 'st', 'st': 'st'
			};
			trSet1 += this.lang === 'de' ? "–" : "'-–";
			trSet2 += this.lang === 'de' ? " " : "'--";
			var trReplace = function( $0, $1, $2 ) {
				return $1 + $2.replace( /&#?\w+;/g, ' ' ).replace( re,function( $0 ) {
					/* Some characters are replaced with the empty charAt(-1) on purpose */
					return trMap[$0] || trSet2.charAt( trSet1.indexOf( $0 ) );
				} ).replace( /(\S) +(?= |$)/g, '$1' ).replace( /(\S)# */g, '$1 #' );
			};
			t = t.replace( /(\{\{(?:SORTIERUNG|DEFAULT\w*SORT\w*):)([^\n{}]+)(?=\}\})/g, trReplace );
			t = t.replace( /(\[\[[CK]ategor[iy]e?:[^\n[\]|]+\|)([^\n[\]|]+)(?=\]\])/g, trReplace );

			/* Groß-/Kleinschreibung wird seit dem 8. März 2011 ignoriert */
			var title = escapeRE( mw.config.get( 'wgTitle' ) );
			t = t.replace(
				new RegExp( '\\{\\{(?:SORTIERUNG|DEFAULT\\w*SORT\\w*):\\s*' + title + '\\}\\}\\s*', 'gi' ),
				''
			);
			var m = /\{\{(?:SORTIERUNG|DEFAULT\w*SORT\w*):([^\n{}]*)/.exec( t );
			t = t.replace( new RegExp( '(\\[\\[[CK]ategor[iy]e?:[^[\\]|]*)\\|'
				+ ( m && escapeRE( m[1] ) || title ) + '\\s*(?=\\]\\])', 'gi' ), '$1' );
			return t.replace(
				/(\[\[[CK]ategor[iy]e?:)([a-z])/g,
				function( $0, $1, $2 ) {
					return $1 + $2.toUpperCase();
				}
			);
		},
		cleanNewlines: function( t ) {
			/* Mehrfache Leerzeilen auf einzelne reduzieren */
			t = t.replace( this.isDisambiguation ? /\n{3,}(?=\n)/g : /\n{3,}/g, '\n\n' );
			/* Keine Leerzeile vor einzeiligen <references /> */
			t = t.replace( /(==\n)\n+(?=<references[^\n<>]*\/>\n\n)/gi, '$1' );
			/* Leerzeile nach Einzelnachweisen */
			t = t.replace(
				/(<\/?references[^\n<>]*>)\s*(?=\{\{Navi(?:gationsleiste |Block)|\{\{SORTIERUNG:|\{\{DEFAULT\w*SORT\w*:|\[\[[CK]ategor[iy]e?:)/gi,
				'$1\n\n'
			);
			/* Leerzeile zwischen Listen/bestimten Vorlagen und Kategorienblock */
			t = t.replace(
				/(\{\{(?:Begriffsklärung|Coordinate|Navi(?:gationsleiste |Block)|Normdaten)[^{}]*\}\}|^\* *[h[{][^\n]*)\s*(?=\{\{SORTIERUNG:|\{\{DEFAULT\w*SORT\w*:|\[\[[CK]ategor[iy]e?:)/gim,
				'$1\n\n'
			);
			/* Split categories into separate lines (don't make this a look-ahead, it's slow!) */
			t = t.replace( /([^\s>-]) *(\[\[[CK]ategor[iy]e?:[^\n[\]]*\]\])/gi, '$1\n$2' );
			t = t.replace( /(\[\[[CK]ategor[iy]e?:[^\n[\]]*\]\]) *(?![\s<-]|$)/gi, '$1\n' );
			t = t.replace(
				/(\[\[[CK]ategor[iy]e?:[^\n[\]]*\]\]\n) *(?!\[\[[CK]ategor[iy]e?:|[\s<-]|$)/gi,
				'$1\n'
			);
			/* Keine Leerzeile zwischen SORTIERUNG und Kategorie */
			t = t.replace(
				/(\{\{(?:SORTIERUNG|DEFAULT\w*SORT\w*):[^\n{}]*\}\})\s*(?=\[\[[CK]ategor[iy]e?:)/gi,
				'$1\n'
			);
			/* Two empty lines in front of English stub templates */
			return t.replace(
				/(\[\[[CK]ategor[iy]e?:[^\n[\]]*\]\])\s*(?=\{\{[\w-]+-stub\b)/gi,
				'$1\n\n\n'
			);
		},
		cleanTemplates: function( t ) {
			var de = this.lang === 'de';

			t = t.replace( /\{\{\s*:?\s*(?:Vorlage|Template)\s*:\s*/gi, '{\{' );
			/* Unterstriche aus allen Vorlagennamen entfernen */
			t = t.replace(
				/(?:^|[^{])\{\{([ \da-z\xC0-\u024F-]*_[ \w\xC0-\u024F-]*[|}])/gi,
				function( $0, $1 ) {
					return /^[A-Z_]+\}$/.test( $1 )
						? $0
						: $0.replace( /_+(?=[|}])/, '' ).replace( /[ _]+/g, ' ' ).replace( /\{ +/, '{' );
				}
			);
			/* Drop empty templates */
			t = t.replace(
				/\{\{(?:Datum|e?dtsx?|Format(?:Date\d*|Num\w*|Zahl\w*)|Literatur|nts|Sort(?:Date\d*|Key\w*))[\s|]*\}\}(?!\})/gi,
				''
			);
			/* Wirkungslose Leerzeilen aus Vorlagen entfernen */
			while ( /^\{\{(?:<(?:br|file>)[^>]*>|[^<>{}])*\n\n+ *[|}]/m.test( t ) ) {
				t = t.replace( /^(\{\{(?:<(?:br|file>)[^>]*>|[^<>{}])*\n)\n+(?= *[|}])/gm, '$1' );
			}

			/* Use the "Commons category" template instead of "Commons" with a category */
			t = t.replace( /\{\{\s*Commons *(?:cat|category)?\s*\|\s*[CK]ategor[iy]e?\s*:\s*/gi,
				de ? '{\{Commonscat|' : '{\{Commons category|' );

			/* Projektweit einheitliche Schreibweisen für häufig verwendete Vorlagen */
			t = t.replace(
				/\{\{\s*(-|Br|Breakafterimages|Clr)[\s|]*(?=\}\})/gi,
				de ? '{\{Absatz' : '{\{$1'
			);
			t = t.replace(
				/\{\{\s*(?:Absatz|(Clear)(?:[ |]*(?:all|both))?)[\s|]*(?=\}\})/gi,
				de ? '{\{Absatz' : function( $0, $1 ) { return '{\{' + ( $1 || 'Clear' ); }
			);
			t = t.replace(
				/\{\{\s*(?:Artikel über lebende Pe\w*|BLP)[\s|]*(?=\}\})/gi,
				de ? '{\{Artikel über lebende Person' : '{\{BLP'
			);
			t = t.replace(
				/\{\{\s*(?:Belege|Quellen?)(?: *fehlen)?(?:[\s|]*(?=\}\})| *(?=\s*\|))/gi,
				'{\{Belege fehlen'
			);
			t = t.replace( /\{\{\s*(?:Benutzer(?:in)?|IP|User|Vandale)\s*\|\s*/gi,
				de ? '{\{Benutzer|' : '{\{User|' );
			t = t.replace( /\{\{\s*Commons(?:[\s|]*(?=\}\})|\s*(\|)\s*)/gi, '{\{Commons$1' );
			t = t.replace( /\{\{\s*Commons *cat(?:egory)?(?:[\s|]*(?=\}\})|\s*(\|)\s*)/gi,
				de ? '{\{Commonscat$1' : '{\{Commons category$1' );
			t = t.replace( /\{\{\s*Dieser *Artikel\s*\|\s*/gi, '{\{Dieser Artikel|' );
			t = t.replace( /\{\{\s*DOI\s*\|\s*/gi, '{\{DOI|' );
			t = t.replace( /\{\{\s*dts(x?)\s*\|\s*/gi, '{\{dts$1|' );
			t = t.replace( /\{\{\s*Erledigt[\s|~]*\}\}/gi, '{\{Erledigt|~~\~~}}' );
			t = t.replace(
				/\{\{\s*(?:Gefallen|Fallen|Verlust|Verschlechtert|Decrease|Down|Loss)[\s|]*(?=\}\})/gi,
				de ? '{\{Gefallen' : '{\{decrease'
			);
			t = t.replace(
				/\{\{\s*(?:Gestiegen|Steigen|Gewinn|Profit|Verbessert|Increase|Gain)[\s|]*(?=\}\})/gi,
				de ? '{\{Gestiegen' : '{\{increase'
			);
			t = t.replace(
				/\{\{\s*(?:Hauptartikel|Hauptseite|Main|Main *articles?|See *main)\s*\|\s*/gi,
				de ? '{\{Hauptartikel|' : '{\{Main|'
			);
			t = t.replace( /\{\{\s*IMDb\s*\|\s*(\w+)\s*/gi, '{\{IMDb|$1' );
			t = t.replace( /\{\{\s*(?:Internetquelle|Weblink)(?=\s*\|)/gi, '{\{Internetquelle' );
			t = t.replace(
				/\{\{\s*(?:In *TeX *konvertieren|TeX)(?:[\s|]*(?=\}\})|\s*(\|)\s*)/gi,
				'{\{In TeX konvertieren$1'
			);
			t = t.replace( /\{\{\s*lang\s*\|\s*/gi, '{\{lang|' );
			t = t.replace( /\{\{\s*Link *([FG]A)\s*\|\s*/gi, '{\{Link $1|' );
			t = t.replace( /\{\{\s*nts\s*\|\s*/gi, '{\{nts|' );
			t = t.replace( /\{\{\s*(?:Nur *Liste|Liste)(?:[\s|]*(?=\}\})| *(?=\s*\|))/gi, '{\{Nur Liste' );
			t = t.replace( /\{\{\s*Okina[\s|]*\}\}/gi, '\u02BB' );
			t = t.replace( /\{\{\s*Rotten *Tomatoes\s*\|\s*/gi, '{\{Rotten Tomatoes|' );
			t = t.replace(
				/\{\{\s*S(?:iehe *auch|ee[ -]*also)\s*\|\s*/gi,
				de ? '{\{Siehe auch|' : '{\{See also|'
			);
			t = t.replace(
				/\{\{\s*(?:SortDate|Datesort)\d*\s*\|\s*/gi,
				de ? '{\{SortDate|' : '{\{dts|'
			);
			t = t.replace(
				/\{\{\s*SortKey(Name)?\s*\|\s*/gi,
				de ? '{\{SortKey$1|' : function( $0, $1 ) { return $1 ? '{\{sortname|' : '{\{sort|'; }
			);
			t = t.replace(
				/\{\{\s*(?:(?:Toter|Bad|Broken|Dead)[ -]*Link|404|Dead|DL)[\s|]*(?=[|}])/gi,
				de ? '{\{Toter Link' : '{\{dead link'
			);
			t = t.replace(
				/\{\{\s*(u)nsign?(?:iert|ed)?\s*\|\s*/gi,
				de ? '{\{$1nsigniert|' : '{\{$1nsigned|'
			);
			t = t.replace(
				/\{\{\s*(?:Unverändert|Stabil|Steady|Nochange|Unchanged)[\s|]*(?=\}\})/gi,
				de ? '{\{Unverändert' : '{\{steady'
			);
			t = t.replace(
				/\{\{\s*(?:Vorlage|Tl?1?|Temp|Template(?: *link)?)\s*\|\s*/gi,
				de ? '{\{Vorlage|' : '{\{tl|'
			);
			t = t.replace(
				/\{\{\s*Wik(ibooks|inews|iquote|isource|ivoyage|tionary)[\s|]*(?=[|}])/gi,
				'{\{Wik$1'
			);

			/* Lower case German language template names "enS" and so on */
			t = t.replace(
				/\{\{\s*([A-Za-z])([a-z]+S)(?:[\s|]*(?=\}\})|\s*(\|)\s*)/g,
				function( $0, $1, $2, $3 ) {
					return '{\{' + $1.toLowerCase() + $2 + ( $3 || '' );
				}
			);
			t = t.replace(
				/\{\{\s*IMDb *([a-z])(\w+)\s*\|\s*/gi,
				function( $0, $1, $2 ) {
					return '{\{IMDb ' + ( de ? $1.toUpperCase() : $1.toLowerCase() ) + $2 + '|';
				}
			);

			t = t.replace( /\(\{\{\s*B\s*((?:\|[^\n{|}]*){2,4})\}\}\)/gi, '{\{Bibel$1}}' );
			/* Remove navigation bar wrapper if it contains a single navigation bar only */
			t = t.replace( /\{\{\s*NaviBlock\s*\|[\s|]*([^\n<>{|}]+)[\s|]*(?=\}\})/gi, '{\{$1' );
			t = t.replace(
				/\{\{\s*(NaviBlock[^<>{}]*?)(?:[\s|]-*)*(?=\}\})/gi,
				function( $0, $1 ) {
					return '{\{' + $1.replace( /\s*\|(?:-*[\s|])*/g, '\n|' ) + '\n';
				}
			);
			t = t.replace( /\{\{\s*Normdaten\s*\|\s*PND\s*=\s*/g, '{\{Normdaten|TYP=p|GND=' );
			t = t.replace( /\{\{\s*WBA\s*\|\s*/gi, '{\{Waybackarchiv|' );
			t = t.replace(
				/\[ *\{\{\s*Wayback\w*\s*\|\s*url\s*=\s*[^\s\d{|}]*(\d{1,14})\/(\w+:[^\s{|}]*)[^{}]*\}\}\s+([^[\]|]*)\]/gi,
				'{\{Webarchiv | url=$2 | wayback=$1 | text=$3}}'
			);

			return t.replace( /(\|\s*(?:Breit|Läng)engrad\s*=\s*[\d.\/]*?)\/[\/0]*(?=[\n|}])/g, '$1' );
		},
		cleanRedundantTemplateParameters: function( t ) {
			var parameters = window.redundantTemplateParameters || [
				'(?:IMDb(?: Name| Titel)?|OFDb|Rotten Tomatoes)|2',
				'Infobox (?:Arcade|Computer- und Videospiel|Musikalbum)|Titel',
				'Infobox (?:Bahnhof|Band|Burg|Chemikalie|County \\(Vereinigte Staaten\\)|Eishockeyspieler|Flug(?:gesellschaft|hafen|zeug)|Fußballsaison|Gemeinde in '
					+ '(?:Deutschland|Österreich)|Gemeindeverband in Deutschland|Hochschule|Landkreis|Medaillen|Militärische Einheit|Ort in '
					+ '(?:den Niederlanden|den Vereinigten Staaten|der Türkei|Portugal)|Schiff|Schutzgebiet|Software|Stadion|Tennis(?:spieler|turnierjahrgang)|Unternehmen)|Name',
				'Infobox (?:Berg|Burg|Fluss|Gebirgsgruppe|Insel|Ort|See|Stadt in Lateinamerika|Stausee|Verwaltungseinheit)|NAME',
				'Infobox Brücke|BEZEICHNUNG',
				'Infobox Fußballspieler|kurzname',
				'Infobox Galaxie|Caption',
				'Infobox Gemeinde in Italien|nomeComune',
				'Infobox Gemeinde in Spanien|Gemeinde',
				'Infobox Gemeinde in Spanien|nombre',
				'Infobox Militärischer Konflikt|KONFLIKT',
				'Infobox Nationalpark|title',
				'Infobox Ort in der Schweiz|NAME_ORT',
				'Infobox Ort in (?:Polen|Tschechien)|Ort',
				'Infobox Ortsteil einer Gemeinde(?: in Deutschland)?|Ortsteil',
				'Infobox PKW-Modell|Modell',
				'Infobox (?:Publikation|Nationalpark)|titel',
				'Infobox Schule|Schulname'
			];
			var title = '\\s*(?:' +
				escapeRE( mw.config.get( 'wgTitle' ) ).replace( /\s+/g, '\\s+' ) +
				'|\\{+\\w*\\}+)?\\s*';
			for ( var i = parameters.length; i--; ) {
				var m = /^(.+)\|(\d+)$/.exec( parameters[i] );
				var re = m ? m[1] + '\\s*(?:\\|[^{|}]*){' + ( m[2] - 1 ) + '})\\|' + title + '(?=\\}\\})' :
					parameters[i].replace( /[\s_]+/g, '[\\s_]+' ).replace( /\|(?=[^|]*$)/, '\\s*(?:\\|[^{}]*)?)\\|\\s*' ) +
						'\\s*=' + title + '(?=\\||\\}\\})';
				t = t.replace( new RegExp( '(\\{\\{\\s*' + re, 'g' ), '$1' );
			}
			return t;
		},
		cleanTemplatesByRules: function( t ) {
			var rules = window.autoFormatTemplates || [{ name: 'Personendaten', format: '|_=_\n' }];
			for ( var rule in rules ) {
				if ( !rules[rule] || !rules[rule].name ) {
					continue;
				}
				rule = rules[rule];
				/* Format muss minimalst |_=_ lauten */
				if ( !rule.format ) {
					rule.format = '';
				}
				if ( rule.format.indexOf( '|' ) < 0 ) {
					rule.format = '|' + rule.format;
				}
				if ( rule.format.indexOf( '_' ) < 0 ) {
					rule.format = rule.format.replace( '|', '|_' );
				}
				if ( rule.format.indexOf( '=' ) < 0 ) {
					rule.format += '=';
				}
				if ( rule.format.match( /_+/g ).length < 2 ) {
					rule.format += '_';
				}
				var re = new RegExp( '\\{\\{[\\s\\xA0]*' + rule.name.replace( /[\s_]+/g, '[\\s_]+' )
					+ '(\\s*<![^>|}]*>)?[\\s\\xA0]*\\|', 'gi' ),
					m,
					a = [];
				while ( m = re.exec( t ) ) {
					a.push( m );
				}
				for ( var i = a.length; i--; ) {
					t = this.cleanTemplateByRule( t, rule, a[i].index + 2, a[i][1] );
				}
			}
			return t;
		},
		cleanTemplateByRule: function( t, rule, start, comment ) {
			var parameters,
				p = '',
				pos = start - 1,
				nesting = { '[': 0, '{': 0 };

			while ( ++pos < t.length ) {
				var c = t.charAt( pos );
				if ( c === '[' || c === '{' ) {
					nesting[c]++;
				} else if ( c === ']' && nesting['[']-- <= 0 ) {
					return t;
				} else if ( c === '}' && nesting['{']-- <= 0 ) {
					/* Parsing started after opening brackets, so stop before closing */
					if ( t.charAt( pos + 1 ) !== '}' ) {
						return t;
					}
					if ( parameters ) {
						parameters.push( p );
					}
					break;
				} else if ( c === '|' && nesting['['] <= 0 && nesting['{'] <= 0 ) {
					if ( parameters ) {
						parameters.push( p );
					} else {
						parameters = [];
					}
					p = '';
				}
				p += c;
			}
			if ( pos >= t.length || nesting['['] > 0 ) {
				return t;
			}

			var m = /((_+)#*)( *)[^_]*((_+)#*)( *)/.exec( rule.format );
			var kMax = m ? m[1].length : 0,
				kMin = m ? m[2].length : 0,
				kFix = m ? m[3].length : 0,
				vMax = m ? m[4].length : 0,
				vMin = m && m[5].length > 1 ? m[5].length : 0,
				vFix = m ? m[6].length : 0;
			var result = rule.name + ( comment || '' ) + ( /\n$/.test( rule.format ) ? '\n' : '' );
			for ( var f, i = 0; parameters && i < parameters.length; i++ ) {
				p = parameters[i];
				if ( !( m = /^\s*\|[\s\xA0]*(([^=|]*?) *)[\s\xA0]*=[\t \xA0]*([\s\S]*? *)\s*$/.exec( p ) ) ) {
					/* Leere unbenannte Parameter verwerfen, wenn ein benannter folgt */
					if ( !/^\s*\|-*\s*$/.test( p ) || ( parameters[i + 1] && parameters[i + 1].indexOf( '=' ) < 1 ) ) {
						result += p;
					}
					continue;
				}
				p = rule.parameters && typeof rule.parameters[m[2]] !== 'undefined' ? rule.parameters[m[2]] : m[1];
				/* Parameter verwerfen, die in den Regeln mit false oder ähnlich markiert sind */
				if ( !p ) {
					continue;
				}
				for ( f = 0; ( f < kFix || kMax && p.length > kMax ) && /\s$/.test( p ); f++ ) {
					p = p.slice( 0, -1 );
				}
				for ( f = 0; ( f < vFix || vMax && m[3].length > vMax ) && /\s$/.test( m[3] ); f++ ) {
					m[3] = m[3].slice( 0, -1 );
				}
				while ( p.length < kMin ) {
					p += ' ';
				}
				while ( m[3].length < vMin ) {
					m[3] += ' ';
				}
				result += rule.format.replace( /_+#*([^_]*)_+#*/, p.replace( /\$/g, '$$$$' ) + '$1' +
					m[3].replace( /\$/g, '$$$$' ) );
			}
			if ( rule.format.indexOf( '\n' ) >= 0 ) {
				if ( typeof rule.trim === 'undefined' || rule.trim ) {
					result = result.replace( /[\t\r ]+$/gm, '' );
				}
				/* Schließendes }} immer auf eine eigene Zeile, wenn irgendein Umbruch im Spiel ist */
				result = result.replace( /\n+\s*$/, '' ) + '\n';
			}
			return t.slice( 0, start ) + result + t.slice( pos );
		},
		executeUserReplacements: function( t ) {
			var from,
				replacements = window.autoFormatReplacements || {};

			for ( from in replacements ) {
				var to = replacements[from];
				/* Wenn die Ersetzungen kein assoziatives Objekt sondern ein 2-dimensionales Array sind */
				if ( typeof to === 'object' && to.length > 1 ) {
					from = to[0];
					to = to[1];
				}
				/* If the search pattern is a regular expression already, 'function' is for older Chrome */
				if ( typeof from === 'object' || typeof from === 'function' ) {
					t = t.replace( from, to );
					continue;
				}
				/* Leere Suchmuster sicherheitshalber nicht zulassen */
				if ( /^\s*$/.test( from ) || typeof to !== 'string' ) {
					continue;
				}

				/* Die meisten Regex-Zeichen maskieren, außer Zeichenklassen */
				from = from.replace( /([$()*+.?^{|}])/g, '\\$1' );
				to = to.replace( /\$/g, '$$$$' );
				/* Wortgrenzen beachten */
				from = from.replace( /^(?=\w|\\d)/, '\\b' ).replace( /(\w)$/, '$1\\b' );
				var a = [];
				for ( var re = /\\[dw]/g, m, i = 1; m = re.exec( from ); a.push( m ) ) {
					to = to.replace( m[0], '$' + i++ );
				}
				for ( i = a.length; i--; ) {
					from = from.slice( 0, a[i].index ) + ( a[i][0] === '\\d' ? '(\\d+)' :
						'([A-Za-z\xB5\xC0-\xD6\xD8-\xF6\xF8-\u024F]+)' ) +
						from.slice( a[i].index + 2 );
				}
				/* Look-ahead verwenden, wenn ein Platzhalter in Suchmuster und Ersatz am Ende steht */
				if ( /\+\)\\b$/.test( from ) && new RegExp( '\\$' + a.length + '$' ).test( to ) ) {
					from = from.replace( /([^()]+)\)\\b$/, '?=$1\\b)' );
					to = to.replace( /\$\d+$/, '' );
				}
				/* Allow optional spaces after dots in the search pattern */
				from = from.replace( /\\\.(?=[(\w\xC0-\u024F])/g, '\\.(?:[ \xA0]|&nbsp;)*' );
				t = t.replace( new RegExp( from, 'g' ), to );
			}
			return t;
		},
		backupNowikis: function( t ) {
			this.nowikis = [];
			var re = /<(nowiki|includeonly|syntaxhighlight|source|html|pre|code|graph|mapframe|score|templatedata|templatestyles|timeline|hiero|math)\b(?!\s*\/>)[\s\S]*?<\/\1\s*>/gi;
			var m;
			while ( m = re.exec( t ) ) {
				delete m.input;
				this.nowikis.push( m );
			}
			for ( var i = this.nowikis.length; i--; ) {
				var placeholder = '<nowiki>' + i + '<\/nowiki>';
				t = t.slice( 0, this.nowikis[i].index ) + placeholder +
					t.slice( this.nowikis[i].index + this.nowikis[i][0].length );
				if ( /^<\w+\s*>\s*<\/\w+\s*>$/.test( this.nowikis[i][0] ) ) {
					this.nowikis[i][0] = /^no/i.test( this.nowikis[i][1] ) ? '<nowiki />' : '';
				} else if ( /^s[oy]/i.test( this.nowikis[i][1] ) ) {
					this.nowikis[i][0] = this.nowikis[i][0].replace( /^(<)\w+|\w+\s*(?=>$)/g, '$1syntaxhighlight' );
				}
				this.nowikis[i][1] = placeholder;
				delete this.nowikis[i].index;
			}
			return t;
		},
		restoreNowikis: function( t ) {
			for ( var i = 0, len = this.nowikis.length, index = 0; i < len; i++ ) {
				index = t.indexOf( this.nowikis[i][1], index );
				if ( index >= 0 ) {
					t = t.slice( 0, index ) + this.nowikis[i][0] +
						t.slice( index + this.nowikis[i][1].length );
				}
			}
			delete this.nowikis;
			return t;
		},
		backupFilenames: function( t ) {
			/* Dateinamen retten incl. Vereinheitlichung als "Datei:" */
			this.files = [];
			var ns = mw.config.get( 'wgFormattedNamespaces' )[6],
				ext = mw.config.get( 'wgFileExtensions' ) || ['png', 'gif', 'jpg', 'jpeg', 'tiff',
				'tif', 'xcf', 'pdf', 'mid', 'ogg', 'ogv', 'svg', 'djvu', 'oga', 'flac', 'wav', 'webm'];
			/* Match <gallery> lines, [[File:Thumbnails]] and template parameters with file names */
			var m,
				re = new RegExp(
				'(^ *|\\[\\[:*(?:\\w+:)?)\\s*(' + ns + '|Bild|File|Image) *: *([^\\n[\\]|]*?) *(?=[\\n\\]|])|'
					+ '(^ *|\\|\\n?(?:[^=[\\]{|}]*=)? *)\\s*([^\\n/[\\]{|}]*\\.(?:'
					+ ext.join( '|' ) + '))(?= *[\\n|}])|'
					+ '(\\|\\s*Commons(?:cat)? *= *)([^\\n/[\\]{|}]*)(?=[\\n|}])',
				'gim'
			);
			while ( m = re.exec( t ) ) {
				var o = ( m[6] || ( m[5] ? m[4] : m[1] ) ).length;
				m.index += o;
				m.l = m[0].length - o;
				/* Multiple underscores and spaces never have a meaning in filenames */
				m[3] = ( m[6] ? m[7] : m[5] || m[3] ).replace( /(?:[ _\xA0]|%20|%5F|%C2%A0|&nbsp;)+/gi, ' ' );
				this.files.push( m );
			}
			var r = '',
				p = 0;
			for ( var i = 0; i < this.files.length; i++ ) {
				this.files[i][0] = '<file>' + i + '<\/file>';
				r += t.slice( p, this.files[i].index );
				if ( this.files[i][2] ) {
					/* Einheitliche Schreibweise und Leerzeichenausgleich */
					r += ( this.localisation && !/\w:$/.test( this.files[i][1] ) ? ns : this.files[i][2] ) + ':';
				}
				r += this.files[i][0];
				p = this.files[i].index + this.files[i].l;
			}
			return p ? r + t.slice( p ) : t;
		},
		restoreFilenames: function( t ) {
			/* Gerettete Dateinamen wieder einsetzen */
			var r = '',
				p = 0;

			for ( var index, i = 0; i < this.files.length; i++ ) {
				if ( ( index = t.indexOf( this.files[i][0], p ) ) < 0 ) {
					continue;
				}
				r += t.slice( p, index ) + this.files[i][3];
				p = index + this.files[i][0].length;
				delete this.files[i];
			}
			if ( p ) {
				t = r + t.slice( p );
			}
			/* Fehlschläge nochmal versuchen, passiert bspw. bei umsortierten Galeriezeilen */
			for ( i = this.files.length; i--; ) {
				if ( this.files[i] ) {
					t = t.replace( this.files[i][0], this.files[i][3] );
				}
			}
			delete this.files;
			return t;
		}
	};

	var label = window.autoFormatterButtonLabel || 'Auto-Format';

	mw.loader.using( 'user.options', function() {
		if ( mw.user.options.get( 'usebetatoolbar' ) ) {
			mw.loader.using( 'ext.wikiEditor', function() {
				$( function() {
					$( '#wpTextbox1' ).wikiEditor( 'addToToolbar', {
						'section': 'main',
						'group': 'format',
						'tools': {
							'autoFormatter': {
								'label': label,
								'type': 'button',
								'icon': '//upload.wikimedia.org/wikipedia/commons/thumb/2/2c/Broom_icon.svg/22px-Broom_icon.svg.png',
								'action': {
									'type': 'callback',
									'execute': function() { return mw.libs.autoFormatter.click( this ); }
								}
							}
						}
					} );
				} );
			} );
		} else if ( mw.user.options.get( 'showtoolbar' ) ) {
			mw.loader.using( 'mediawiki.action.edit', function() {
				mw.toolbar.addButton(
					'//upload.wikimedia.org/wikipedia/commons/2/2e/Button_broom.png',
					label,
					'', '', '',
					'mw-customeditbutton-autoFormatter'
				);
				$( function() {
					$( '#mw-customeditbutton-autoFormatter' ).click( function() {
						return mw.libs.autoFormatter.click( this );
					} );
				} );
			} );
		} else {
			$( function() {
				/* Notfalls als Link unter dem Bearbeitungsfenster */
				var b = $( '.editButtons' ),
					c = b.children().last(),
					a = $( '<a href="#">' + label + '<\/a>' );

				( c.is( 'span' ) ? c : b ).append( $( '.mw-editButtons-pipe-separator', b ).first().clone() );
				a.click( function() { return mw.libs.autoFormatter.click( this ); } );
				b.append( a );
			} );
		}
	} );
} )( jQuery, mediaWiki );
// </nowiki>

var autoFormatMaskedLinks = false;
var autoFormatReplacements = [
[' অকল্যান ', ' অকল্যাণ '],
[' অকারন ', ' অকারণ '],
[' অগ্রগন্য ', ' অগ্রগণ্য '],
[' অগ্রহায়ন ', ' অগ্রহায়ণ '],
[' অংক ', ' অঙ্ক '],
[' অংকন ', ' অঙ্কন '],
[' অংকুর ', ' অঙ্কুর '],
[' অংগ ', ' অঙ্গ '],
[' অংগন ', ' অঙ্গন '],
[' অংগাংগী ', ' অঙ্গাঙ্গি '],
[' অচিন্ত্যনীয় ', ' অচিন্তনীয় '],
[' অচিন্ত ', ' অচিন্ত্য '],
[' অঞ্জলী ', ' অঞ্জলি '],
[' পরমানু ', ' পরমাণু '],
[' অতিথী ', ' অতিথি '],
[' অতিষ্ট ', ' অতিষ্ঠ '],
[' অতিব ', ' অতীব '],
[' অত্যাধিক ', ' অত্যধিক '],
[' অত্যান্ত ', ' অত্যন্ত '],
[' অদ্ভূত ', ' অদ্ভুত '],
[' অদ্যপি ', ' অদ্যাপি '],
[' অদ্যবদি ', ' অদ্যাবধি '],
[' অধঃস্তন ', ' অধস্তন '],
[' অধিকরন ', ' অধিকরণ '],
[' অধীনস্ত ', ' অধীনস্থ '],
[' অধ্যাবসায় ', ' অধ্যবসায় '],
[' অধ্যায়ণ ', ' অধ্যয়ন '],
[' অধ্যূষিত ', ' অধ্যুষিত '],
[' অনিন্দসুন্দর ', ' অনিন্দ্যসুন্দর '],
[' অনিষ্ঠ ', ' অনিষ্ট '],
[' অনুকুল ', ' অনুকূল '],
[' অনুসঙ্গ ', ' অনুষঙ্গ '],
[' অনুর্ধ্ব ', ' অনূর্ধ্ব '],
[' অন্তকরণ ', ' অন্তঃকরণ '],
[' অন্তর্ভূক্ত ', ' অন্তর্ভুক্ত '],
[' অন্তঃসত্তা ', ' অন্তসত্ত্বা '],
[' অন্তর্মুখি ', ' অন্তর্মুখী '],
[' অন্যমনষ্ক ', ' অন্যমনস্ক '],
[' অণ্বেষণ ', ' অন্বেষণ '],
[' অর্পণা ', ' অপর্ণা '],
[' অপসৃয়মান ', ' অপসৃয়মাণ '],
[' অপাংক্তেয় ', ' অপাঙ্‌ক্তেয় '],
[' অপেক্ষমান ', ' অপেক্ষমাণ '],
[' অভিভুত ', ' অভিভূত '],
[' অভিমুখি ', ' অভিমুখী '],
[' আভ্যন্তরীণ ', ' অভ্যন্তরীণ '],
[' অভ্যস্থ ', ' অভ্যস্ত '],
[' অমিতাক্ষর ', ' অমিত্রাক্ষর '],
[' অমানুসিক ', ' অমানুষিক '],
[' অমাবশ্যা ', ' অমাবস্যা '],
[' অর্ধ্ব ', ' অর্ধ '],
[' অশিরিরী ', ' অশরীরী '],
[' অসুয়া ', ' অসূয়া '],
[' অস্তমান ', ' অস্তায়মান '],
[' অলংঘ ', ' অলঙ্ঘ্য '],
[' অহঃরহ ', ' অহরহ '],
[' আকাবাকা ', ' আঁকাবাঁকা '],
[' আস্তাকুঁড় ', ' আঁস্তাকুড় '],
[' আকষ্কিক ', ' আকস্মিক '],
[' আকাংখা ', ' আকাঙ্ক্ষা '],
[' আকূল ', ' আকুল '],
[' আকুতি ', ' আকূতি '],
[' আক্রমন ', ' আক্রমণ '],
[' আটপৌড়ে ', ' আটপৌরে '],
[' আড়ৎ ', ' আড়ত '],
[' আড়ষ্ঠ ', ' আড়ষ্ট '],
[' আঁড়াআড়ি ', ' আড়াআড়ি '],
[' আঁড়িপাতা ', ' আড়িপাতা '],
[' আনবিক ', ' আণবিক '],
[' আতংক ', ' আতঙ্ক '],
[' আত্মস্যাৎ ', ' আত্মসাৎ '],
[' আদ্যান্ত ', ' আদ্যন্ত '],
[' আনুষাঙ্গিক ', ' আনুষঙ্গিক '],
[' আপোষ ', ' আপোস '],
[' আপাততঃ ', ' আপাতত '],
[' আপাতঃদৃষ্টে ', ' আপাতদৃষ্টে '],
[' অভ্যন্তরিক ', ' আভ্যন্তরিক '],
[' আয়ত্ব ', ' আয়ত্ত '],
[' আয়ত্বাধীন ', ' আয়ত্তাধীন '],
[' আরাম্ভ ', ' আরম্ভ '],
[' আদ্র ', ' আর্দ্র '],
[' আলিংগন ', ' আলিঙ্গন '],
[' আলোচ্যমান ', ' আলোচ্য '],
[' আশংকা ', ' আশঙ্কা '],
[' আশক্তি ', ' আসক্তি '],
[' আশ্বস্থ ', ' আশ্বস্ত '],
[' ইংগিত ', ' ইঙ্গিত '],
[' ইতিপূর্বে ', ' ইতঃপূর্বে '],
[' ইতঃস্তত ', ' ইতস্তত '],
[' ইতিমধ্যে ', ' ইতোমধ্যে '],
[' ইদানিং ', ' ইদানীং '],
[' ইয়ত্বা ', ' ইয়ত্তা '],
[' ইষ্ঠ ', ' ইষ্ট '],
[' ঈস্পিত ', ' ঈপ্সিত '],
[' ইষৎ ', ' ঈষৎ '],
[' উচিৎ ', ' উচিত '],
[' উচ্চৈস্বরে ', ' উচ্চৈঃস্বরে '],
[' উচ্ছ্বল ', ' উচ্ছল '],
[' উশৃঙ্খল ', ' উচ্ছৃঙ্খল '],
[' উজ্বল ', ' উজ্জ্বল '],
[' উৎকর্ষতা ', ' উৎকর্ষ '],
[' উত্তরন ', ' উত্তরণ '],
[' উত্তরসুরী ', ' উত্তরসূরি '],
[' উত্তলন ', ' উত্তোলন '],
[' উত্যক্ত ', ' উত্ত্যক্ত '],
[' উদীচি ', ' উদীচী '],
[' উদ্বিঘ্ন ', ' উদ্বিগ্ন '],
[' উদ্ভিজ ', ' উদ্ভিজ্জ '],
[' উদ্ভুত ', ' উদ্ভূত '],
[' উদ্দান ', ' উদ্যান '],
[' উদ্দ্যোগ ', ' উদ্যোগ '],
[' ঊনিশ ', ' উনিশ '],
[' উপকুল ', ' উপকূল '],
[' উপরোক্ত ', ' উপরিউক্ত '],
[' উপলক্ষ্য ', ' উপলক্ষ '],
[' উপচার্য ', ' উপাচার্য '],
[' উভয়চর ', ' উভচর '],
[' উনবিংশ ', ' ঊনবিংশ '],
[' উর্ধ্ব ', ' ঊর্ধ্ব '],
[' উর্মি ', ' ঊর্মি '],
[' উষর ', ' ঊষর '],
[' উহ্য ', ' ঊহ্য '],
[' একনিষ্ট ', ' একনিষ্ঠ '],
[' একাধিক্রমে ', ' একাদিক্রমে '],
[' এককৃত ', ' একীকৃত '],
[' একভূত ', ' একীভূত '],
[' এক্ষুণি ', ' এক্ষুনি '],
[' এতদ্‌সঙ্গে ', ' এতৎসঙ্গে '],
[' এতদ্‌সত্ত্বেও ', ' এতৎসত্ত্বেও '],
[' এশিয় ', ' এশীয় '],
[' ঐক্যতান ', ' ঐকতান '],
[' ঐকবদ্ধ ', ' ঐক্যবদ্ধ '],
[' ঐক্যতা ', ' একতা '],
[' ঐক্যমত ', ' ঐকমত্য '],
[' ওতঃপ্রোত ', ' ওতপ্রোত '],
[' ঔচিত্ত ', ' ঔচিত্য '],
[' উদ্ধত্য ', ' ঔদ্ধত্য '],
[' কংকণ ', ' কঙ্কণ '],
[' কংকাল ', ' কঙ্কাল '],
[' কটুক্তি ', ' কটূক্তি '],
[' কনা ', ' কণা '],
[' কন্ঠস্ত ', ' কণ্ঠস্থ '],
[' কন্ঠশিল্পী ', ' কণ্ঠশিল্পী '],
[' কথপোকথন ', ' কথোপকথন '],
[' কদাচিত ', ' কদাচিৎ '],
[' কনিষ্ট ', ' কনিষ্ঠ '],
[' কয়েদী ', ' কয়েদি '],
[' করনিক ', ' করণিক '],
[' কতৃক ', ' কর্তৃক '],
[' কতৃত্ত্ব ', ' কর্তৃত্ব '],
[' কতৃপক্ষ ', ' কর্তৃপক্ষ '],
[' কর্তী ', ' কর্ত্রী '],
[' কর্মচারি ', ' কর্মচারী '],
[' কলংক ', ' কলঙ্ক '],
[' কলসী ', ' কলসি '],
[' কল্যান ', ' কল্যাণ '],
[' কল্যানীয়াষু ', ' কল্যাণীয়াসু '],
[' কল্যানীয়েসু ', ' কল্যাণীয়েষু '],
[' কষ্ঠি ', ' কষ্টি '],
[' কাকলী ', ' কাকলি '],
[' কাংখিত ', ' কাঙ্খিত '],
[' কাঁচ ', ' কাচ '],
[' কাচা ', ' কাঁচা '],
[' কাঁছাকাছি ', ' কাছাকাছি '],
[' কাতলা ', ' কাৎলা '],
[' কার্যতঃ ', ' কার্যত '],
[' কিংবদন্তী ', ' কিংবদন্তি '],
[' কিম্বা ', ' কিংবা '],
[' কূটিল ', ' কুটিল '],
[' কুৎসিৎ ', ' কুৎসিত '],
[' কুটনীতি ', ' কূটনীতি '],
[' কৃচ্ছতা ', ' কৃচ্ছ্রতা '],
[' কৃচ্ছসাধন ', ' কৃচ্ছ্রসাধন '],
[' কৃষিজীবি ', ' কৃষিজীবী '],
[' কৃষ্টিবান ', ' কৃষ্টিমান '],
[' কেন্দ্রিয় ', ' কেন্দ্রীয় '],
[' কেরাণী ', ' কেরানি '],
[' কোণাকুণি ', ' কোনাকুনি '],
[' কৌতূক ', ' কৌতুক '],
[' কৌতুহল ', ' কৌতূহল '],
[' কচিৎ ', ' ক্বচিৎ '],
[' ক্রুর ', ' ক্রূর '],
[' ক্ষীয়মান ', ' ক্ষীয়মাণ '],
[' ক্ষুন্ন ', ' ক্ষুণ্ণ '],
[' ক্ষুব্দ ', ' ক্ষুব্ধ '],
[' খেতমজুর ', ' ক্ষেতমজুর '],
[' ক্ষেপন ', ' ক্ষেপণ '],
[' ক্ষেপনাস্ত্র ', ' ক্ষেপণাস্ত্র '],
[' খঞ্জনী ', ' খঞ্জনি '],
[' খুটিনাটি ', ' খুঁটিনাটি '],
[' খুড়ী ', ' খুড়ি '],
[' খুশী ', ' খুশি '],
[' খেলাধূলা ', ' খেলাধুলা '],
[' খেলোয়ার ', ' খেলোয়াড় '],
[' খোজ ', ' খোঁজ '],
[' খোলাখোলি ', ' খোলাখুলি '],
[' গগণ ', ' গগন '],
[' গংগা ', ' গঙ্গা '],
[' গন্‌জ ', ' গঞ্জ '],
[' গড্ডালিকা ', ' গড্ডলিকা '],
[' গন ', ' গণ '],
[' গননা ', ' গণনা '],
[' গনিত ', ' গণিত '],
[' গন্য ', ' গণ্য '],
[' গত্যান্তর ', ' গত্যন্তর '],
[' গবেষনা ', ' গবেষণা '],
[' গরীব ', ' গরিব '],
[' গর্ধব ', ' গর্ধভ '],
[' গাড়ী ', ' গাড়ি '],
[' গার্হস্থ ', ' গার্হস্থ্য '],
[' গীর্জা ', ' গির্জা '],
[' গুড়া ', ' গুঁড়া '],
[' গুড়ো ', ' গুঁড়ো '],
[' গুণে গুণে ', ' গুনে গুনে '],
[' গৃহস্ত ', ' গৃহস্থ '],
[' গৃহিত ', ' গৃহীত '],
[' গোধুলি ', ' গোধূলি '],
[' গোষ্ঠি ', ' গোষ্ঠী '],
[' গোস্পদ ', ' গোষ্পদ '],
[' গ্রন্থী ', ' গ্রন্থি '],
[' গ্রহন ', ' গ্রহণ '],
[' গ্রহিতা ', ' গ্রহীতা '],
[' গ্রামীন ', ' গ্রামীণ '],
[' গ্রীক ', ' গ্রিক '],
[' গ্রীস ', ' গ্রিস '],
[' ঘনিষ্ট ', ' ঘনিষ্ঠ '],
[' ঘরণী ', ' ঘরনি '],
[' ঘাটি ', ' ঘাঁটি '],
[' ঘূণ ', ' ঘুণ '],
[' ঘুসখোর ', ' ঘুষখোর '],
[' ঘুর্নি ', ' ঘূর্ণি '],
[' ঘুর্ণীয়মান ', ' ঘূর্ণায়মান '],
[' ঘুরাঘুরি ', ' ঘোরাঘুরি '],
[' ঘোষনা ', ' ঘোষণা '],
[' ঘ্রান ', ' ঘ্রাণ '],
[' চরক ', ' চড়ক '],
[' চত্তর ', ' চত্বর '],
[' চাকরানী ', ' চাকরানি '],
[' চাকরী ', ' চাকরি '],
[' চাকুরী ', ' চাকুরী '],
[' চাতুর্যতা ', ' চাতুর্য '],
[' চীৎকার ', ' চিৎকার '],
[' চুড়মার ', ' চুরমার '],
[' চুড়ান্ত ', ' চূড়ান্ত '],
[' চূষ্য ', ' চোষ্য '],
[' চৌচিড় ', ' চৌচির '],
[' ছাকনি ', ' ছাঁকনি '],
[' ছাকা ', ' ছাঁকা '],
[' ছাত্রীবাস ', ' ছাত্রীনিবাস '],
[' ছোওয়া ', ' ছোঁয়া '],
[' ছোকড়া ', ' ছোকরা '],
[' ছোটখাট ', ' ছোটোখাটো '],
[' ছোটাছোটি ', ' ছোটাছুটি '],
[' জংগল ', ' জঙ্গল '],
[' জগত ', ' জগৎ '],
[' জঘণ্য ', ' জঘন্য '],
[' জটীল ', ' জটিল '],
[' জবানবন্দী ', ' জবানবন্দি '],
[' জ্বরাজীর্ণ ', ' জরাজীর্ণ '],
[' জরুরী ', ' জরুরি '],
[' জাগরুক ', ' জাগরূক '],
[' জাতী ', ' জাতি '],
[' জাতিয় ', ' জাতীয় '],
[' জাতীয়করন ', ' জাতীয়করণ '],
[' যাদুঘর ', ' জাদুঘর '],
[' জানুয়ারী ', ' জানুয়ারি '],
[' জিনিষ ', ' জিনিস '],
[' জীবীকা ', ' জীবিকা '],
[' জেষ্ঠ্য ', ' জ্যেষ্ঠ '],
[' জৈষ্ঠ্য ', ' জ্যৈষ্ঠ '],
[' টাকশাল ', ' টাঁকশাল '],
[' টেঁকসই ', ' টেকসই '],
[' ডাইনী ', ' ডাইনি '],
[' তক্ষুণি ', ' তক্ষুনি '],
[' তছরূপ ', ' তছরুপ '],
[' তড়িত ', ' তড়িৎ '],
[' ততক্ষণাৎ ', ' তৎক্ষণাৎ '],
[' তদসংক্রান্ত ', ' তৎসংক্রান্ত '],
[' ততধিক ', ' ততোধিক '],
[' তত্তজ্ঞান ', ' তত্ত্বজ্ঞান '],
[' তত্তাবধান ', ' তত্ত্বাবধান '],
[' তত্তাবদায়ক ', ' তত্ত্বাবধায়ক '],
[' তৎবিষয়ক ', ' তদ্বিষয়ক '],
[' তদানুসারে ', ' তদনুসারে '],
[' তদ্রুপ ', ' তদ্রূপ '],
[' তফাত ', ' তফাৎ '],
[' তরংগ ', ' তরঙ্গ '],
[' তর্জনি ', ' তর্জনী '],
[' তষ্কর ', ' তস্কর '],
[' তাঁতী ', ' তাঁতি '],
[' তাবত ', ' তাবৎ '],
[' তিতীক্ষা ', ' তিতিক্ষা '],
[' তিরষ্কার ', ' তিরস্কার '],
[' ত্যজ্য ', ' ত্যাজ্য '],
[' ত্রান ', ' ত্রাণ '],
[' ত্রিভূজ ', ' ত্রিভুজ '],
[' তরান্বিত ', ' ত্বরান্বিত '],
[' ত্বরিৎ ', ' ত্বরিত '],
[' থুত্থুরে ', ' থুত্থুড়ে '],
[' দক্ষিন ', ' দক্ষিণ '],
[' দণ্ডবত ', ' দণ্ডবৎ '],
[' দরকারী ', ' দরকারি '],
[' দরুণ ', ' দরুন '],
[' দারিদ্রতা ', ' দরিদ্রতা, দারিদ্র '],
[' দারুন ', ' দারুণ '],
[' দিকভ্রান্ত ', ' দিগভ্রান্ত '],
[' দিঘী ', ' দিঘি '],
[' দিক্ষা ', ' দীক্ষা '],
[' দীর্ঘসূত্রিতা ', ' দীর্ঘসূত্রতা '],
[' দুরাবস্থা ', ' দুরবস্থা '],
[' দূরারোগ্য ', ' দুরারোগ্য '],
[' দূরুহ ', ' দুরূহ '],
[' দূর্গ ', ' দুর্গ '],
[' দুষ্কৃতীকারী ', ' দুষ্কৃতকারী '],
[' দুতাবাস ', ' দূতাবাস '],
[' দুরবীক্ষন ', ' দূরবীক্ষণ '],
[' দূরবীক্ষন ', ' দূরবীক্ষণ '],
[' দূরবীণ ', ' দূরবীন '],
[' দোষনীয় ', ' দূষণীয় '],
[' দৃঢ়করণ ', ' দৃঢ়ীকরণ '],
[' দৃষ্টিকোন ', ' দৃষ্টিকোণ '],
[' দৃষ্ঠিভঙ্গি ', ' দৃষ্টিভঙ্গি '],
[' দেদীপ্যমাণ ', ' দেদীপ্যমান '],
[' দেরী ', ' দেরি '],
[' দৈনতা ', ' দীনতা, দৈন্য '],
[' দুষ ', ' দোষ '],
[' দ্বন্দ ', ' দ্বন্দ্ব '],
[' দ্বিতীয়তঃ ', ' দ্বিতীয়ত '],
[' ধরণ ', ' ধরন '],
[' ধ্বস ', ' ধ্স '],
[' ধ্বস্তাধ্বস্তি ', ' ধ্স্তাধস্তি '],
[' ধাধা ', ' ধাঁধা '],
[' ধারন ', ' ধারণ '],
[' ধারনা ', ' ধারণা '],
[' ধূলা ', ' ধুলা '],
[' ধুমপান ', ' ধূমপান '],
[' ধুর্ত ', ' ধূর্ত '],
[' ধুলি ', ' ধূলি '],
[' ধুসর ', ' ধূসর '],
[' ধজা ', ' ধ্বজা '],
[' ধ্বনী ', ' ধ্বনি '],
[' নচেত ', ' নচেৎ '],
[' নচ্ছাড় ', ' নচ্ছাড় '],
[' নবীণ ', ' নবীন '],
[' নমষ্কার ', ' নমস্কার '],
[' নিক্কন ', ' নিক্বণ '],
[' নীচে ', ' নিচে '],
[' নীজ ', ' নিজ '],
[' নিন্দ্যনীয় ', ' নিন্দনীয় '],
[' নীরলস ', ' নিরলস '],
[' নিরুপন ', ' নিরূপণ '],
[' নির্নয় ', ' নির্ণয় '],
[' নির্দোষী ', ' নির্দোষ '],
[' নির্ধনী ', ' নির্ধন '],
[' নিস্কাশন ', ' নিষ্কাশন '],
[' নিস্প্রয়োজন ', ' নিষ্প্রয়োজন '],
[' নিরব ', ' নীরব '],
[' নিরস ', ' নীরস '],
[' নিরোগ ', ' নীরোগ '],
[' নিহারীকা ', ' নীহারিকা '],
[' নিস্প্রভ ', ' নিষ্প্রভ '],
[' নৈশব্দ্য ', ' নৈঃশব্দ্য '],
[' ন্যয্য ', ' ন্যায্য '],
[' ন্যয় ', ' ন্যায় '],
[' নূন্যতম ', ' ন্যূনতম '],
[' নৃসংশ ', ' নৃশংস '],
[' পক্ক ', ' পক্ব '],
[' পংক্তি ', ' পঙক্তি '],
[' পংক ', ' পঙ্ক '],
[' পড়শী ', ' পড়শি '],
[' পড়াশুনা ', ' পড়াশোনা '],
[' পন্য ', ' পণ্য '],
[' পথিকৃত ', ' পথিকৃৎ '],
[' পথমধ্যে ', ' পথিমধ্যে '],
[' পরবর্তীতে ', ' পরবর্তীকালে '],
[' পরমানু ', ' পরমাণু '],
[' পরষ্পর ', ' পরস্পর '],
[' পরাস্থ ', ' পরাস্ত '],
[' পরিনাম ', ' পরিণাম '],
[' পরিবহণ ', ' পরিবহন '],
[' পরিমান ', ' পরিমাণ '],
[' পরিস্কার ', ' পরিষ্কার '],
[' পরিষ্ফুট ', ' পরিস্ফুট '],
[' পশ্চাদপট ', ' পশ্চাৎপট '],
[' পশ্চাদপদ ', ' পশ্চাৎপদ '],
[' পশ্চাৎগামী ', ' পশ্চাদগামী '],
[' পশ্চাৎভূমি ', ' পশ্চাদভূমি '],
[' পারদর্শীতা ', ' পারদর্শিতা '],
[' পারমানবিক ', ' পারমাণবিক '],
[' পার্বন ', ' পার্বণ '],
[' পালংক ', ' পালঙ্ক '],
[' পাষান ', ' পাষাণ '],
[' পিপিলিকা ', ' পিপীলিকা '],
[' পিচাশ ', ' পিশাচ '],
[' পিঠস্থান ', ' পীঠস্থান '],
[' পুংখানুপুংখ ', ' পুঙ্খানুপুঙ্খ '],
[' পূজো ', ' পুজো '],
[' পুজা ', ' পূজা '],
[' পুন্য ', ' পুণ্য '],
[' পূর্ণগঠন ', ' পুনর্গঠন '],
[' পুণবিবেচনা ', ' পুনর্বিবেচনা '],
[' পূবালী ', ' পুবালি '],
[' পুরষ্কার ', ' পুরস্কার '],
[' পুস্করিনী ', ' পুষ্করিণী '],
[' পুর্ন ', ' পূর্ণ '],
[' পৈত্রিক ', ' পৈতৃক '],
[' পোষাক ', ' পোশাক '],
[' পৌনঃপৌনিক ', ' পৌনঃপুনিক '],
[' পৌরহিত্য ', ' পৌরোহিত্য '],
[' প্রজ্জলন ', ' প্রজ্বলন '],
[' প্রজ্জলিত ', ' প্রজ্বলিত '],
[' প্রণয়ণ ', ' প্রণয়ন '],
[' প্রনালী ', ' প্রণালী '],
[' প্রনিধান ', ' প্রণিধান '],
[' প্রতিকুল ', ' প্রতিকূল '],
[' প্রতিযোগীতা ', ' প্রতিযোগিতা '],
[' প্রত্যয়ণ ', ' প্রত্যায়ন '],
[' প্রথমতঃ ', ' প্রথমত '],
[' প্রধানতঃ ', ' প্রধানত '],
[' প্রবীন ', ' প্রবীণ '],
[' প্রবাহমাণ ', ' প্রবাহমান '],
[' প্রভুত ', ' প্রভূত '],
[' প্রয়ান ', ' প্রয়াণ '],
[' প্রসংশা ', ' প্রশংসা '],
[' প্রশস্থ ', ' প্রশস্ত '],
[' প্রসংগ ', ' প্রসঙ্গ '],
[' প্রাংগন ', ' প্রাঙ্গণ '],
[' প্রাণপন ', ' প্রাণপণ '],
[' প্রানীজগৎ ', ' প্রাণীজগৎ '],
[' প্রানীবিদ্যা ', ' প্রাণীবিদ্যা '],
[' ফলপ্রসু ', ' ফলপ্রসূ '],
[' ফলতঃ ', ' ফলত '],
[' ফাল্গুণ ', ' ফাল্গুন '],
[' ফেব্রুয়ারী ', ' ফেব্রুয়ারি '],
[' বংগ ', ' বঙ্গ '],
[' বনিক ', ' বণিক '],
[' বন্টন ', ' বণ্টন '],
[' বনষ্পতি ', ' বনস্পতি '],
[' বন্দোপাধ্যায় ', ' বন্দ্যোপাধ্যায় '],
[' বয়োকনিষ্ট ', ' বয়ঃকনিষ্ঠ '],
[' বয়ষ্ক ', ' বয়স্ক '],
[' বর্ণালী ', ' বর্ণালি '],
[' বর্ত্তমান ', ' বর্তমান '],
[' বর্ষন ', ' বর্ষণ '],
[' বাঁশী ', ' বাঁশি '],
[' বাকদত্তা ', ' বাগদত্তা '],
[' বাঞ্চনীয় ', ' বাঞ্ছনীয় '],
[' বাঞ্চা ', ' বাঞ্ছা '],
[' বাড়ী ', ' বাড়ি '],
[' বাদুর ', ' বাদুড় '],
[' বানিজ্য ', ' বাণিজ্য '],
[' বিদ্যান ', ' বিদ্বান '],
[' বিপদজনক ', ' বিপজ্জনক '],
[' বিপনন ', ' বিপণন '],
[' বিপনী ', ' বিপণী '],
[' বিপদগ্রস্থ ', ' বিপদগ্রস্ত '],
[' বিশ্বস্থ ', ' বিশ্বস্ত '],
[' বিষ্ফোরণ ', ' বিস্ফোরণ '],
[' বীভৎস্য ', ' বীভৎস '],
[' বুদ্ধজীবী ', ' বুদ্ধিজীবি '],
[' বেশী ', ' বেশি '],
[' ব্যাতিক্রম ', ' ব্যতিক্রম '],
[' ব্যাথা ', ' ব্যথা '],
[' ব্যাবধান ', ' ব্যবধান '],
[' ব্যাবহার ', ' ব্যবহার '],
[' ব্যাভিচার ', ' ব্যভিচার '],
[' ব্যায় ', ' ব্যয় '],
[' ব্যার্থ ', ' ব্যর্থ '],
[' ব্যকরণ ', ' ব্যাকরণ '],
[' ব্যপক ', ' ব্যাপক '],
[' ব্যাপি ', ' ব্যাপী '],
[' ব্যহত ', ' ব্যাহত '],
[' বুৎপত্তি ', ' ব্যুৎপত্তি '],
[' ব্রাক্ষণ ', ' ব্রাহ্মণ '],
[' ভংগ ', ' ভঙ্গ '],
[' ভংগী ', ' ভঙ্গি '],
[' ভংগুর ', ' ভঙ্গুর '],
[' ভনিতা ', ' ভণিতা '],
[' ভবিষ্যৎবাণী ', ' ভবিষ্যদ্বাণী '],
[' ভরনপোষণ ', ' ভরণপোষণ '],
[' ভষ্ম ', ' ভস্ম '],
[' ভাষ্কর ', ' ভাস্কর '],
[' ভিখারী ', ' ভিখারি '],
[' ভীড় ', ' ভিড় '],
[' ভিরু ', ' ভীরু '],
[' ভুড়ি ', ' ভুঁড়ি '],
[' ভূবন ', ' ভুবন '],
[' ভূয়া ', ' ভুয়া '],
[' ভূল ', ' ভুল '],
[' ভুতপূর্ব ', ' ভূতপূর্ব '],
[' ভুমিষ্ট ', ' ভূমিষ্ঠ '],
[' ভুয়সী ', ' ভূয়সী '],
[' ভুরিভোজন ', ' ভূরিভোজন '],
[' ভৌগলিক ', ' ভৌগোলিক '],
[' ভ্রমন ', ' ভ্রমণ '],
[' ভ্রাম্যমান ', ' ভ্রাম্যমাণ '],
[' ভ্রুক্ষেপ ', ' ভ্রূক্ষেপ '],
[' মজুরী ', ' মজুরি '],
[' মণিষা ', ' মনীষা '],
[' মনিষী ', ' মনীষী '],
[' মনমালিন্য ', ' মনোমালিন্য '],
[' মন্ত্রনালয় ', ' মন্ত্রণালয় '],
[' ময়ুর ', ' ময়ূর '],
[' মিরিচিকা ', ' মরীচিকা '],
[' মরুদ্যান ', ' মরূদ্যান '],
[' মশারী ', ' মশারি '],
[' মস্তিস্ক ', ' মস্তিষ্ক '],
[' মহত্ত ', ' মহত্ত্ব '],
[' মহামতী ', ' মহামতি '],
[' মহামারি ', ' মহামারী '],
[' মহিয়সী ', ' মহীয়সী '],
[' মাংশ ', ' মাংস '],
[' মানিক্য ', ' মানিক '],
[' মাসী ', ' মাসি '],
[' মাহাত্ম ', ' মাহাত্ম্য '],
[' মিতালী ', ' মিতালি '],
[' মিমাংসা ', ' মীমাংসা '],
[' মুখস্ত ', ' মুখস্থ '],
[' মূখ্য ', ' মুখ্য '],
[' মুদ্রন ', ' মুদ্রণ '],
[' মুর্ধন্য ', ' মূর্ধন্য '],
[' মুমুর্ষ ', ' মুমূর্ষ '],
[' মুষ্ঠি ', ' মুষ্টি '],
[' মুহূর্মুহু ', ' মুহুর্মুহু '],
[' মুহুর্ত ', ' মুহূর্ত '],
[' মুত্র ', ' মূত্র '],
[' মুর্খ ', ' মূর্খ '],
[' মুর্তি ', ' মূর্তি '],
[' মূল্যায়ণ ', ' মূল্যায়ন '],
[' মুঢ় ', ' মূঢ় '],
[' মোটামোটি ', ' মোটামুটি '],
[' মুহ্যবান ', ' মোহ্যমান '],
[' মৌনতা ', ' মৌন '],
[' মৃয়মান ', ' ম্রিয়মাণ '],
[' যক্ষা ', ' যক্ষ্মা '],
[' যথেষ্ঠ ', ' যথেষ্ট '],
[' যদ্যাপি ', ' যদ্যপি '],
[' যন্ত্রনা ', ' যন্ত্রণা '],
[' রংগ ', ' রঙ্গ '],
[' রঙ্গিণ ', ' রঙ্গিন '],
[' রঙিণ ', ' রঙিন '],
[' রথি ', ' রথী '],
[' রাংগামাটি ', ' রাঙ্গামাটি '],
[' রসায়ণ ', ' রসায়ন '],
[' রামায়ন ', ' রামায়ণ '],
[' রাষ্ট্রিয় ', ' রাষ্ট্রীয় '],
[' রূপায়ন ', ' রূপায়ণ '],
[' রোপন ', ' রোপণ '],
[' লংকা ', ' লঙ্কা '],
[' লংঘন ', ' লঙ্ঘন '],
[' লক্ষ্যণীয় ', ' লক্ষণীয় '],
[' লক্ষী ', ' লক্ষ্মী '],
[' লঘুকরণ ', ' লঘূকরণ '],
[' লজ্জাষ্কর ', ' লজ্জাকর '],
[' লবন ', ' লবণ '],
[' লাইব্রেরী ', ' লাইব্রেরি '],
[' লাবন্য ', ' লাবণ্য '],
[' সখ ', ' শখ '],
[' শংকর ', ' শঙ্কর '],
[' শংকা ', ' শঙ্কা '],
[' শংকিত ', ' শঙ্কিত '],
[' সনাক্ত ', ' শনাক্ত '],
[' শরীক ', ' শরিক '],
[' শশাংক ', ' শশাঙ্ক '],
[' শাড়ী ', ' শাড়ি '],
[' শারীরীক ', ' শারীরিক '],
[' শাশুড়ী ', ' শাশুড়ি '],
[' শ্বাশত ', ' শাশ্বত '],
[' শিক্ষাঙ্গন ', ' শিক্ষাঙ্গণ '],
[' শিরচ্ছেদ ', ' শিরশ্ছেদ '],
[' শিরধার্য ', ' শিরোধার্য '],
[' শিরনাম ', ' শিরোনাম '],
[' শিরমণি ', ' শিরোমণি '],
[' শুভাকাংখী ', ' শুভাকাঙ্খী '],
[' শুশ্রুষা ', ' শুশ্রূষা '],
[' শূণ্য ', ' শুন্য '],
[' শৃংখলা ', ' শৃঙ্খলা '],
[' সৌখিন ', ' শৌখিন '],
[' শ্রদ্ধাঞ্জলী ', ' শ্রদ্ধাঞ্জলি '],
[' শ্রদ্ধাভাজনীয় ', ' শ্রদ্ধাভাজন '],
[' শ্রদ্ধাষ্পদ ', ' শ্রদ্ধাস্পদ '],
[' শ্রমজীবি ', ' শ্রমজীবী '],
[' শ্রাবন ', ' শ্রাবণ '],
[' শ্রীমতি ', ' শ্রীমতী '],
[' শ্রেষ্ট ', ' শ্রেষ্ঠ '],
[' শশুর ', ' শ্বশুর '],
[' শশ্মান ', ' শ্মশান '],
[' ষষ্ট ', ' ষষ্ঠ '],
[' ষষ্ঠদশ ', ' ষোড়শ '],
[' সংগা ', ' সংজ্ঞা '],
[' সম্বরণ ', ' সংবরণ '],
[' সম্বর্ধনা ', ' সংবর্ধনা '],
[' সম্বলিত ', ' সংবলিত '],
[' সংগী ', ' সঙ্গী '],
[' স্বচ্ছল ', ' সচ্ছল '],
[' সতীন ', ' সতিন '],
[' সত্বেও ', ' সত্ত্বেও '],
[' সত্যয়িত ', ' সত্যায়িত '],
[' সদ্যস্নাত ', ' সদ্যঃস্নাত '],
[' সদ্যজাত ', ' সদ্যোজাত '],
[' সমীচিন ', ' সমীচীন '],
[' সন্মান ', ' সম্মান '],
[' সন্মানীত ', ' সম্মানীত '],
[' সন্মুখ ', ' সম্মুখ '],
[' সন্মেলন ', ' সম্মেলন '],
[' সরকারী ', ' সরকারি '],
[' সরণী ', ' সরণি '],
[' স্বরস্বতী ', ' সরস্বতী '],
[' সর্বাঙ্গীন ', ' সর্বাঙ্গীণ '],
[' সলজ্জিত ', ' সলজ্জ '],
[' সশংকিত ', ' সশঙ্ক '],
[' স্বস্ত্রীক ', ' সস্ত্রীক '],
[' সহকারি ', ' সহকারী '],
[' সাড়াশী ', ' সাঁড়াশি '],
[' সাংগ ', ' সাঙ্গ '],
[' সাক্ষাতকার ', ' সাক্ষাৎকার '],
[' সাধারন ', ' সাধারণ '],
[' সান্তনা ', ' সান্ত্বনা '],
[' সামগ্রীক ', ' সামগ্রিক '],
[' স্বাতন্ত্র ', ' স্বাতন্ত্র্য '],
[' স্বাধীকার ', ' স্বাধিকার '],
[' স্বায়ত্ত্বশাসন ', ' স্বায়ত্তশাসন '],
[' সরনী ', ' সরণি '],
[' স্মরন ', ' স্মরণ '],
[' স্রোতঃস্বতী ', ' স্রোতস্বতী '],
[' হৃদপিণ্ড ', ' হৃৎপিণ্ড '],
[' হীনমন্যতা ', ' হীনম্মন্যতা '],
[' হৃদস্পন্দন ', ' হৃৎস্পন্দন '],
[' হৃৎরোগ ', ' হৃদরোগ '],
[' পুরসভা ', ' পৌরসভা '],
['Category:', 'বিষয়শ্রেণী:'],
['category:', 'বিষয়শ্রেণী:'],
['Template:', ''],
['টেমপ্লেট:', ''],
['\<(?:\s*)references?(?:\s*\/|\s*\/\s*)\>', '{{সূত্র তালিকা}}'],
[ / +<ref\b/g, '<ref'],
[ /(\n[*#]+) *([^\s*#:;])/g, '$1 $2'],
[ /([^\s=|] ) +(?=[^\s=|])/g, '$1'],
[ /<!--+ *(?=[^\s-])([^>]*[^\s-]) *--+>/g, '<!-- $1 -->']
];

// This script aligns dates into one of two formats allowed by [[WP:MOSNUM]].
// PLEASE READ THE DOCUMENTATION at [[User:Ohconfucius/script/MOSNUM dates]] (click on the link above) before using.

// Feedback and constructive criticism are welcome

/**
 * TemplateScript adds configurable templates and scripts to the sidebar, and adds an example regex editor.
 * @see https://meta.wikimedia.org/wiki/TemplateScript
 */
// <pre>
if ($.inArray(mw.config.get('wgAction'), ['edit', 'submit']) !== -1) {
	$.ajax(
		'//tools-static.wmflabs.org/meta/scripts/pathoschild.templatescript.js',
		{dataType: 'script', cache: true}
	).done(function () {
		$.when(
			mw.loader.using(['mediawiki.util']),
			$.ajax('//en.wikipedia.org/w/index.php?title=User:Ohconfucius/script/MOSNUM_utils.js&action=raw&ctype=text/javascript',
				{dataType: 'script', cache: true}),
			$.ready
		).done(function () {
			var add = function() {
            return mw.util.addPortletLink.apply(mw.util, arguments);
			};

			$(add('p-tb', '#', 'DATES to dmy', 'dmy-unitfixer', 'Align all dates to dmy', '', '')).click(ohc_all_to_dmy_driver);
			$(add('p-tb', '#', 'DATES to mdy', 'mdy-unitfixer', 'Align all dates to mdy', '', '')).click(ohc_all_to_mdy_driver);
//			$(add('p-tb', '#', 'Expand ref dates', 't-expandref', 'Expand month names within refs', '', '')).click(ohc_expand_ref_dates_driver);
//			$(add('p-tb', '#', 'Expand all dates', 't-expandall', 'Expand month names throughout', '', '')).click(ohc_expand_all_dates_driver);
			$( add('p-tb', '#', 'US-slash dates', 't-US', 'US-slash', '', '') ).click(ohc_US_slash_dates_driver);
			$( add('p-tb', '#', 'UK-slash dates', 't-UK', 'UK-slash', '', '') ).click(ohc_UK_slash_dates_driver);
		});
	});
}

function ohc_fix_unambiguous_dates()
{
	// resolvable ambiguous date formats
	// UK style
	ohc_regex(/([^-\w/:\.])@DD\.@MM\.@YYYY(?=[^-–/\w&])/gi, "$1@Day @Month @YYYY", function(d) {
		if (d.d == d.m) return true;
		if (d.d > 12) return true;
		return false;
		});
	ohc_regex(/([^-\w/:\.])@DD\/@MM\/@YYYY(?=[^-–/\w&])/gi, "$1@Day @Month @YYYY", function(d) {
		if (d.d == d.m) return true;
		if (d.d > 12) return true;
		return false;
		});

	// US style
	ohc_regex(/([^-\w/:\.])@MM\.@DD\.@YYYY(?=[^-–/\w&])/gi, "$1@Month @Day, @YYYY", function(d) {
		if (d.d > 12) return true;
		return false;
		});
	ohc_regex(/([^-\w/:\.])@MM\/@DD\/@YYYY(?=[^-–/\w&])/gi, "$1@Month @Day, @YYYY", function(d) {
		if (d.d > 12) return true;
		return false;
		});
}

function ohc_US_slash_dates_to_mdy()
{
//ranges
	ohc_regex(/([^-\d/:\.])@MM\/@DD\/@YYNN(&nbsp;|\s)?(?:(?:[-–—]|&[mn]dash;)(?:&nbsp;|\s)?)@MM\/@DD\/@YYNN(?=[^-–/\w&])/gi, "$1@Mon1 @Day1, @Year1$2 – @Mon2 @Day2, @Year2");
	ohc_regex(/([^-\d/:\.])@MM\.@DD\.@YYNN(&nbsp;|\s)?(?:(?:[-–—]|&[mn]dash;)(?:&nbsp;|\s)?)@MM\.@DD\.@YYNN(?=[^-–/\w&])/gi, "$1@Mon1 @Day1, @Year1$2 – @Mon2 @Day2, @Year2");
	ohc_regex(/(\| ?)@MM\/@DD\/@YYNN(&nbsp;|\s)?(?:(?:[-–—]|&[mn]dash;)(?:&nbsp;|\s)?)@MM\/@DD\/@YYNN(?=\s*\|)/gi, "$1@Mon1 @Day1, @Year1$2 – @Mon2 @Day2, @Year2");
	ohc_regex(/(\| ?)@MM\.@DD\.@YYNN(&nbsp;|\s)?(?:(?:[-–—]|&[mn]dash;)(?:&nbsp;|\s)?)@MM\.@DD\.@YYNN(?=\s*\|)/gi, "$1@Mon1 @Day1, @Year1$2 – @Mon @Day2, @Year2");

// resolvable ambiguous date formats
	ohc_regex(/([^-\d/:\.])@MM\/@DD\/@YYNN(?=[^-–/\w&])/gi, '$1@Month @Day, @YYYY');
	ohc_regex(/([^-\d/:\.])@MM\.@DD\.@YYNN(?=[^-–/\w&])/gi, '$1@Month @Day, @YYYY');
	ohc_regex(/([^-\d/:\.])@MM[-–]@DD[-–]@YYNN(?=[^-–/\w&])/gi, '$1@Month @Day, @YYYY');
	ohc_regex(/(\| ?)@MM\/@DD\/@YYNN(?=\s*\|)/gi, '$1@Month @Day, @YYYY');
	ohc_regex(/(\| ?)@MM\.@DD\.@YYNN(?=\s*\|)/gi, '$1@Month @Day, @YYYY');
//	ohc_regex(/(\| ?)@MM[-–]@DD[-–]@YYNN(?=\s*\|)/gi, '$1@Month @Day, @YYYY');
}
 
function ohc_UK_slash_dates_to_dmy()
{
//ranges
	ohc_regex(/([^-\d/:\.])@DD\/@MM\/@YYNN(&nbsp;|\s)?(?:(?:[-–—]|&[mn]dash;)(?:&nbsp;|\s)?)@DD\/@MM\/@YYNN(?=[^-–/\w&])/gi, "$1@Day1 @Mon1 @Year1$2 – @Day2 @Mon2 @Year2");
	ohc_regex(/([^-\d/:\.])@DD\.@MM\.@YYNN(&nbsp;|\s)?(?:(?:[-–—]|&[mn]dash;)(?:&nbsp;|\s)?)@DD\.@MM\.@YYNN(?=[^-–/\w&])/gi, "$1@Day1 @Mon1 @Year1$2 – @Day2 @Mon2 @Year2");
	ohc_regex(/(\| ?)@DD\/@MM\/@YYNN(&nbsp;|\s)?(?:(?:[-–—]|&[mn]dash;)(?:&nbsp;|\s)?)@DD\/@MM\/@YYNN(?=\s*\|)/gi, "$1@Day1 @Mon1 @Year1$2 – @Day2 @Mon2 @Year2");
	ohc_regex(/(\| ?)@DD\.@MM\.@YYNN(&nbsp;|\s)?(?:(?:[-–—]|&[mn]dash;)(?:&nbsp;|\s)?)@DD\.@MM\.@YYNN(?=\s*\|)/gi, "$1@Day1 @Mon1 @Year1$2 – @Day2 @Mon2 @Year2");

// resolvable ambiguous date formats
	ohc_regex(/([^-\d/:\.])@DD\/@MM\/@YYNN(?=[^-–/\w&])/gi, '$1@Day @Month @YYYY');
	ohc_regex(/([^-\d/:\.])@DD\.@MM\.@YYNN(?=[^-–/\w&])/gi, '$1@Day @Month @YYYY');
	ohc_regex(/([^-\d/:\.])@DD[-–]@MM[-–]@YYNN(?=[^-–/\w&])/gi, '$1@Day @Month @YYYY');
	ohc_regex(/(\| ?)@DD\/@MM\/@YYNN(?=\s*\|)/gi, '$1@Day @Month @YYYY');
	ohc_regex(/(\| ?)@DD\.@MM\.@YYNN(?=\s*\|)/gi, '$1@Day @Month @YYYY');
//	ohc_regex(/(\| ?)@DD[-–]@MM[-–]@YYNN(?=\s*\|)/gi, '$1@Day @Month @YYYY');
}

function ohc_remove_leading_zeroes()
{
	ohc_regex(/(\D[^\w\/])@Month\s@ZD@th?,?\s@YYYY(?=\W\D)/gi, "$1@LMonth @Day, @LYear");
	ohc_regex(/(\D[^\w\/])@Month\s@ZD@th?(?=\W\D)/gi, "$1@LMonth @Day");
	ohc_regex(/(\D[^\w\/])@ZD@th?\s@Month\s@YYYY(?=\W\D)/gi, "$1@Day @LMonth @LYear");
	ohc_regex(/(\D[^\w\/])@ZD@th?\s@Month(?=\W\D)/gi, "$1@Day @LMonth");
}

function ohc_delink_dates()
{
	//add missing space between wikilinks
	regex(/(\]\])(\[\[)/gi, '$1 $2');  //remove (?!file:) to ensure a space between all links
 
	 // rem redundant quote marks and parentheses
	regex(/(\|\s*(?:publication|archive|access|air|)-?date\s*=\s*)\'\'\'([^|}\[\]]*)\'\'\'(?=\s*[|}])/gi, "$1$2");
	regex(/(\|\s*(?:publication|archive|access|air|)-?date\s*=\s*)\'\'([^|}\[\]]*)\'\'(?=\s*[|}])/gi, "$1$2");
	regex(/(\|\s*(?:publication|archive|access|air|)-?date\s*=\s*)\"([^|}\[\]]*)\"(?=\s*[|}])/gi, "$1$2");
	regex(/(\|\s*(?:publication|archive|access|air|)-?date\s*=\s*)\(([^|}\[\]]*)\)(?=\s*[|}])/gi, "$1$2");

//delink unpiped dates
	//delink full dates
	ohc_regex(/\[\[@Day[\s_](?:of[\s_])?@Month(?:\]\]\s?\[\[\| )@YYYY\]\]/gi, "@Day @LMonth @YYYY");
	ohc_regex(/\[\[@Month (?:the\s)?@Day(?:\]\],? \[\[|, )@YYYY\]\]/gi, "@LMonth @Day, @YYYY");

	//delink yyyy-mm-dd dates
	ohc_regex(/\[\[@YYYY(?:\]\]-\[\[|-)@MM-@DD\]\]/gi, "@YYYY-@MM-@DD");
	ohc_regex(/@YYYY-\[\[@MM-@DD\]\]/gi, "@YYYY-@MM-@DD");

	//underscore and nbsp in linked dates
	ohc_regex(/\[\[@DD@th?(?:\s|_|&nbsp;)@Month\]\]/gi, "@Day @LMonth");
	ohc_regex(/\[\[@Month(?:\s|_|&nbsp;)@DD@th?\]\]@th?/gi, "@LMonth @Day"); //consolidated regex with flexible removal of ordinal simple date
	ohc_regex(/\[\[@Day @Month\]\]/gi, "@Day @LMonth");
	ohc_regex(/\[\[@Month @YYYY\]\]/gi, "@LMonth @YYYY");
	ohc_regex(/\[\[@YYYY\]\]/gi, "@YYYY");

	//remove leading zero and links from linked date
	ohc_regex(/\[\[@Month(?:[ _]|&nbsp;)@ZD@th\]\]/gi, "@LMonth @Day");
	ohc_regex(/\[\[@ZD@th(?:[ _]|&nbsp;)@Month\]\]/gi, "@Day @LMonth");

	// remove nowrap template from dm and md dates
	ohc_regex(/(date[ ]*=[ ]*)\{\{(?:j|no ?(?:break|wrap))\|(?:@DD(?:[ _]|&nbsp;)@Month)( @yyyy|)\}\}/gi, '$1@DD @LMonth$2');
	ohc_regex(/(date[ ]*=[ ]*)\{\{(?:j|no ?(?:break|wrap))\|(?:@Month(?:[ _]|&nbsp;)@DD)( @yyyy|)\}\}/gi, '$1@LMonth @DD$2');
	
	//delink single dm or 'dth the m'
	ohc_regex(/(?:the\s)?\[\[@Day@th?[\s_](?:of[\s_])?@Month\]\]/gi, "@Day @LMonth");
	//delink single md or 'm the dth'
	ohc_regex(/\[\[@Month[\s_](?:the[\s_])?@Day@th?\]\](?=\W)/gi, "@LMonth @Day");

//month+day piped
	ohc_regex(/\[\[(?:@dd@th?[\s_](?:of[\s_])?@month|@month[\s_]@dd@th?)\|((?:@month |)@day)@th?\]\]/gi, "$1");
	ohc_regex(/\[\[(?:@dd@th?[\s_](?:of[\s_])?@month|@month[\s_]@dd@th?)\|@Day@th?[\s_](@month|)\]\]/gi, "@Day $1");

//	ohc_regex(/\[\[@month @dd(?:#[^|]+|)\|([^|\]]+)@th?\]\]/gi, "$1");
//	ohc_regex(/\[\[@dd @month(?:#[^|]+|)\|([^|\]]+)@th?\]\]/gi, "$1");
	ohc_regex(/\[\[@month @yyyy(?:#[^|]+|)\|([^|\]]+)\]\]/gi, "$1");

	//month+day+year pseudo-ISO dates
	ohc_regex(/\[\[@Month @DD\|\d\d-\d\d\]\]-(?:\[\[)?(?:@yyyy[^|]*\|)?@YYYY(?:\]\])/gi, "@Day @LMonth @YYYY");
	ohc_regex(/\[\[@DD\s@Month\|\d\d-\d\d\]\]-(?:\[\[)?(?:@yyyy[^|]*\|)?@YYYY(?:\]\])/gi, "@Day @LMonth @YYYY");

	//'[[month day|xxXxx]]Xyyyy ' to 'month day, year'
	ohc_regex(/\[\[@Month\s@Day\|@dd.@dd\]\].@YYYY/gi, "@LMonth @Day, @YYYY");
	 //'[[day month|xxXxx]]Xyyyy' to 'day month year'
	ohc_regex(/\[\[@Day\s@Month\|@dd.@dd\]\].@YYYY/gi, "@Day @LMonth @YYYY");

// century
	regex(/\[\[((?:first|second|third|(?:four|fif|six|seven|eigh|nin|ten|eleven|twelf|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twentie)th|twenty[\s\-]first[\s\-])centur(?:y|ies)(?:\s(?:AD|BC|CE|BCE))?)\]\]/gi, '$1');
	regex(/\[\[(?:first|second|third|(?:four|fif|six|seven|eigh|nin|ten|eleven|twelf|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twentie)th|twenty[\s\-]first)[\s\-_]centur(?:y|ies)(?:\s(?:AD|BC|CE|BCE))?\|([^\]]{1,30})\]\]/gi, '$1');
	regex(/\[\[(\d{1,2}(?:st|[nr]d|th))[\s\-_](centur(?:y|ies))(\s(?:AD|BC|CE|BCE)|)\]\]/gi, '$1 $2$3');
	ohc_regex(/\[\[\d{1,2}@th[\s\-_]centur(?:y|ies)(?:\s(?:AD|BC|CE|BCE)|)\|([^\]]{1,30})\]\]/gi, '$1');

	// months
	ohc_regex(/\[\[@Month\]\]/gi, "@LMonth");
	ohc_regex(/\[\[@FullMonth\|([^\]]{1,30})\]\]/gi, "$1");

	// decades and years
	regex(/(\d{1,3}0)[‘`´’′]?s/g, '$1s');
	regex(/\[\[(\d{1,3}0)\'?s\]\]/g, '$1s');
	regex(/\[\[\d{1,3}0\'?s?\|([^\]]{1,30})\]\]/g, '$1');
	regex(/\[\[(\d{1,3}0)\'?(s)?\s(AD|BC|CE|BCE)\]\]/gi, '$1$2 $3');
	regex(/\[\[(\d{1,4}[\s_]?)(AD|BC|CE|BCE)\]\]/gi, '$1$2');
	regex(/\[\[(AD|BC|CE|BCE)([\s_]?)(\d{1,4})\]\]/gi, '$1$2$3');
	ohc_regex(/([-–])\[\[\s?@yyyy\s?\|\s?(\d{2,4})\s?\]\]/gi, '$1$2'); //piped year
	regex(/\[\[([12]\d{3}|[1-9]\d{0,2})\]\]/gi, '$1');
	regex(/\[\[\d{1,3}0\'?s?\s(?:AD|BC|CE|BCE)\|([^\]]{1,30})\]\]/gi, '$1');
	regex(/\[\[\d{1,3}0\'?s?\s\(decade\)\|([^\]]{1,30})\]\]/gi, '$1');

	//month+year
	//Identify surprise or 'Easter egg' diversions linking month+years to year articles. Turn them into month+year links to be dealt with below
	ohc_regex(/\[\[@yyyy in[^|\]]+\|@Day @Month @YYYY\]\]/gi, "@Day @LMonth @YYYY");
	ohc_regex(/\[\[@yyyy in[^|\]]+\|@Month @Day,? @YYYY\]\]/gi, "@LMonth @Day, @YYYY");
	ohc_regex(/\[\[@yyyy#[^|\]]+\|(@month\s|)(@yyyy)\]\]/gi, "$1$2");
	ohc_regex(/\[\[@yyyy#[^|\]]+\|(@month|@yyyy)\]\]/gi, "$1");
	ohc_regex(/\[\[(@month\s@yyyy)\]\]/gi, "$1");
	ohc_regex(/\[\[@month\s@yyyy\|([^\]]{1,30})\]\]/gi, "$1");
	ohc_regex(/\[\[(?:List of |)Bollywood films of @yyyy\|@YYYY\]\](?= [^\[]{2}^B)/gi, "@YYYY");

	ohc_regex(/(\[\[@yyyy[^|\]]+\|@yyyy)(\]\])( season)/gi, "$1$3$2");

	//removed piped years when in full date (excepting disambiguated parentheses - updated 24/2/2012)
//	ohc_regex(/\[\[[^|\]\(\)]{1,32}\|@YYYY\]\]/gi, '@Year');  // 23/6/2021 – disabled delinking "other" year-in articles

	//Identify surprise or 'Easter egg' diversions linking months to year or "year in" articles.
	ohc_regex(/\[\[\d{1,4}#[^|\]]+\|@Month\]\]/gi, "@LMonth");
	ohc_regex(/\[\[@yyyy \w[^|\]]{3,12}\|@Year\]\]/gi, '@Year');

	// month and day piped
	ohc_regex(/\[\[@month[\s_]@day\|@MM-@DD\]\]/gi, "@MM-@DD");
	ohc_regex(/\[\[@month[\s_]@day\|([^\]]{1,30})\]\]/gi, "$1");
	ohc_regex(/\[\[@day(?:\s|_|@th )(?:of[\s_]|)?@month\|([^\]]{1,30})\]\]/gi, "$1");

	//years piped
	regex(/\[\[\d{1,4}\|([^\]]{1,30})\]\]/gi, '$1');
}

function ohc_fix_common_errors()
{
	ohc_regex(/(\d)<sup>@th<\/sup>/gi, '$1th');
	// remove dashbot comment from dates
	regex(/<!-- ?DASHBot ?-->/gi, '');
	ohc_regex(/(\|\s*(?:date|year)\s*=)\s*c(?:irca|a\.)?\s?((?:@day |)@month @year)(?=[\s\n]*[<|}])/gi, '$1c. $2'); //add space
//common cs1 errors
	regex(/(\|\s*(?:date|year)\s*=)\s*(1[7-9]\d|20[0-1])\?(?=[\s\n]*[<|}])/gi, '$1c. $20'); 
	regex(/(\|\s*(?:date|year)\s*=\s*(1[7-9])\d{2})[-–](\d{2})(?=[\s\n]*[<|}])/gi, '$1–$2$3'); 
//	regex(/(\|\s*(?:date|year)\s*=\s*(20)[0-1]\d)[-–]([0-2]\d)(?=[\s\n]*[<|}])/gi, '$1–$2$3'); 
	regex(/(\|\s*(?:date|year)\s*=\s*)@YYYY\s*[-–/]\s*@YYYY(?=[\s\n]*[<|}])/gi, '$1@YYYY1–@YYYY2'); //common cs1 error
	regex(/(\|\s*(?:date)\s*=)\s*s(pring|ummer),?\s*((?:1[7-9]\d|20[0-1])\d)(?=[\s\n]*[<|}])/gi, '$1S$2 $3'); //common cs1 error
	regex(/(\|\s*(?:date)\s*=)\s*a(utumn),?\s*((?:1[7-9]\d|20[0-1])\d)(?=[\s\n]*[<|}])/gi, '$1A$2 $3'); //common cs1 error
	regex(/(\|\s*(?:date)\s*=)\s*f(all),?\s*((?:1[7-9]\d|20[0-1])\d)(?=[\s\n]*[<|}])/gi, '$1F$2 $3'); //common cs1 error
	regex(/(\|\s*(?:date)\s*=)\s*w(inter),?\s*((?:1[7-9]\d|20[0-1])\d)(?=[\s\n]*[<|}])/gi, '$1W$2 $3'); //common cs1 error
	ohc_regex(/(\|\s*access-?date\s*=)\s*(@month @year)(?=[\s\n]*[<|}])/gi, '$11 $2'); //common cs1 error
//	ohc_regex(/(\|\s*date\s*=\s*)@year\?(?=[\s\n]*[<|}])/gi, '$1@Year'); //common cs1 error
//	ohc_regex(/(\|\s*(?:date|year)\s*=)\s*@year\?(?=[\s\n]*[<|}])/gi, '$1c. @Year'); //common cs1 error
//	ohc_regex(/(\|\s*(?:date|year)\s*=)\s*(@month @year)\?(?=[\s\n]*[<|}])/gi, '$1c. $2'); //common cs1 error
	ohc_regex(/(\|\s*access-?date\s*=)\s*@month @day, (1[7-9]\d{2}|2000)(?=[\s\n]*[<|}])/gi, '$1'); //rem access date before Wikipedia (জানুয়ারি 2001)
	ohc_regex(/(\|\s*access-?date\s*=)\s*@day @month.? (1[7-9]\d{2}|2000)(?=[\s\n]*[<|}])/gi, '$1'); //rem access date before Wikipedia (জানুয়ারি 2001)
	ohc_regex(/(\|\s*access-?date\s*=)\s*31( (?:এপ্রিল|জুন|সেপ্টেম্বর|নভেম্বর) @year)(?=[\s\n]*[<|}])/gi, '$130$2'); //rem nonsense access date (short months)
	ohc_regex(/(\|\s*access-?date\s*=)\s*29( ফেব্রুয়ারি (?:200[1235679]|201[1345789]))(?=[\s\n]*[<|}])/gi, '$128$2'); //rem nonsense access date 29 ফেব্রুয়ারি (non-leap year)
	ohc_regex(/(\|\s*access-?date\s*=)\s*(?:3[01])( ফেব্রুয়ারি @yyyy)(?=[\s\n]*[<|}])/gi, '$128$2'); //rem nonsense access dates ফেব্রুয়ারি
	regex(/(\|\s*access-?date\s*=)\s*(\d{4})(?=[\s\n]*[<|}])/gi, ''); //common cs1 error
	
	//month+day+year pseudo-ISO dates
	ohc_regex(/(\|\s*(?:publication|archive|access|air|)-?date\s*=\s*@dd)-@Mon-@YYYY/gi, "$1 @FullMonth @YYYY");
	ohc_regex(/(\|\s*(?:publication|archive|access|air|)-?date\s*=\s*)@YYYY-@DD-@Mon/gi, "$1 @DD @FullMonth @YYYY");

	regex(/(\|\s*(?:date|year)\s*=)\s*(?:(?:date |)unknown|(?:not? |non-|un)date[ds])(?=[\s\n]*[<|}])/gi, '$1n.d.'); //common cs1 error
	regex(/(\|\s*(?:date|year)\s*=)\s*n\.?d(?=[\s\n]*[<|}])/gi, '$1n.d.'); //common cs1 error
	regex(/(\|\s*)year(\s*=\s*)(?=n\.?d\.)(?=[\s\n]*[<|}])/gi, '$1date$2'); //common cs1 error

   // remove parasitic metadata -  days of the week/descriptives
	ohc_regex(/(\|\s*(?:publication|archive|access|air|)-?date\s*=\s*)(?:[^|}\d]*|)@Day\s+@Month\s+@YYYY((?:[a-z]\b|)\s?)[^|<}]*(?=[\s\n]*[<|}])/gi, "$1@Day @Month @YYYY$2"); //rem negate "<", "hyphens" "dashes" 26/6/2020
	ohc_regex(/(\|\s*(?:publication|archive|access|air|)-?date\s*=\s*)[^|}]*@Month\s+@Day,\s+@YYYY((?:[a-z]\b|)\s?)[^|<}]*(?=[\s\n]*[<|}])/gi, "$1@Month @Day, @YYYY$2"); //rem negate "<", "hyphens" "dashes" 26/6/2020
//	ohc_regex(/(\|\s*date\s*=\s*)(?:[^|}–<]*\D|)@Day\s+@Month\s+@YYYY ?– ?@Day\s+@Month\s+@YYYY[^|}–<]*(?=[\s\n]*[<|}])/gi, "$1@Day1 @Mon1 @Year1 – @Day2 @Mon2 @Year2");
//	ohc_regex(/(\|\s*date\s*=\s*)[^|}–<]*@Month\s+@Day,\s+@YYYY ?– ?@Month @Day, @YYYY[^|}–<]*(?=[\s\n]*[<|}])/gi, "$1@Mon1 @Day1, @Year1 – @@Mon2 Day2, @Year2");
//	regex(/(\|\s*author\s*=\s*)(?:posted|published)(?: by\b| on\b|)[\s:](?=\w)/gi, "$1");
//	regex(/(\|\s*(?:date|archive-?date|access-?date|author|year)\s*=\s*)(?:accessed|retrieved|entered|posted|published|(?:last |)updated?|©)(?: by\b| on\b|)[\s:]*(?=\w)/gi, "$1");
	regex(/(\|\s*(?:author|first|last)\s*=\s*)(?:by\b|on\b)[\s:]*(?=\w)/gi, "$1");
	regex(/(\|\s*(?:date|archive-?date|access-?date|author|first|last)\s*=\s*)(?:(?:Mon|Tues|Wednes|Thurs|Fri|Satur|Sun)day,?)\s/gi, "$1");
	regex(/(\|\s*(?:date|archive-?date|access-?date|author|first|last)\s*=\s*)(?:Mon|Tues?|Wed|Thur?|Fri|Sat)[\.,]?\s/gi, "$1"); //<!-- rem "Sun" - false positives -->

   // remove deprecated parameters (|day= and |month)
 	ohc_regex(/(\|\s*)day(?:\s*=\s*)@DD ?\| ?month(?:\s*=\s*)@Month ?\| ?year(?:\s*=\s*)@YYYY(?=[|}\s])/gi, '$1date=@Day @Month @Year'); 
 	ohc_regex(/(\|\s*)year(?:\s*=\s*)@YYYY ?\| ?month(?:\s*=\s*)@Month ?\| ?day(?:\s*=\s*)@DD(?=[|}\s])/gi, '$1date=@Month @Day, @Year'); 
 	
// typos
	ohc_regex(/(date *= *)@Day @Month ?@th/gi, '$1@Day @Month'); 
	ohc_regex(/(date *= *)@Day @Month\w(?= \d{3,4})/gi, '$1@Day @Month'); 

	ohc_regex(/(date *= *(?:[12]?\d|30|31) )(জানুয়ারি|Febr)[\w ]?[aur]{3,4}\w{0,2}(?= (?:1[6-9]\d|20[01])\d\b)/gi, '$1$2uary'); 
	ohc_regex(/(date *= *(?:[12]?\d|30|31) )J[anu]{3,5}r\w{0,2}(?= (?:1[6-9]\d|20[01])\d\b)/gi, '$1জানুয়ারি');
	ohc_regex(/(date *= *(?:[12]?\d) )Febua?r\w{0,2}(?= (?:1[6-9]\d|20[01])\d\b)/gi, '$1ফেব্রুয়ারি');
	ohc_regex(/(date *= *(?:[12]?\d|30|31) )M\w{2,3}ch(?= (?:1[6-9]\d|20[01])\d\b)/gi, '$1মার্চ'); 
	ohc_regex(/(date *= *(?:[12]?\d|30) )A[bpv\[]\w{2,3}l\w?(?= (?:1[6-9]\d|20[01])\d\b)/gi, '$1এপ্রিল');
	ohc_regex(/(date *= *(?:[12]?\d|30|31) )Ma[tui](?= (?:1[6-9]\d|20[01])\d\b)/gi, '$1মে'); 
	ohc_regex(/(date *= *(?:[12]?\d|30) )J\wn\w(?= (?:1[6-9]\d|20[01])\d\b)/gi, '$1জুন'); 
	ohc_regex(/(date *= *(?:[12]?\d|30) )J\w{1,2}e(?= (?:1[6-9]\d|20[01])\d\b)/gi, '$1জুন'); 
	ohc_regex(/(date *= *(?:[12]?\d|30|31) )জুলাই\w{1,2}(?= (?:1[6-9]\d|20[01])\d\b)/gi, '$1জুলাই'); 
	ohc_regex(/(date *= *(?:[12]?\d|30|31) )A[oug]{2,3}\w{1,4}t(?:\w|us)?(?= (?:1[6-9]\d|20[01])\d\b)/gi, '$1আগষ্ট'); 
	ohc_regex(/(date *= *(?:[12]?\d|30|31) )(সেপ্টেম্বর|নভেম্বর|ডিসেম্বর)\w{2,4}b[er]{1,2}\w?(?= (?:1[6-9]\d|20[01])\d\b)/gi, '$1$2ember'); 
	ohc_regex(/(date *= *(?:[12]?\d|30) )S\w{0,2}p[ \[]?\w{2,5}[er]{2,3}\w?(?= (?:1[6-9]\d|20[01])\d\b)/gi, '$1সেপ্টেম্বর'); 
	ohc_regex(/(date *= *(?:[12]?\d|30|31) )O\w{0,2}t\w{1,3}[er]{2,3}\w?(?= (?:1[6-9]\d|20[01])\d\b)/gi, '$1অক্টোবর'); 
	ohc_regex(/(date *= *(?:[12]?\d|30) )[MN]\w{1,2}[bv] ?\w{1,3}b[er]{1,2}\w?(?= (?:1[6-9]\d|20[01])\d\b)/gi, '$1নভেম্বর'); 
	ohc_regex(/(date *= *(?:[12]?\d|30|31) )D[ie]?[cs] ?\w{1,4}b[er]{1,2}\w?(?= (?:1[6-9]\d|20[01])\d\b)/gi, '$1ডিসেম্বর'); 

	ohc_regex(/(date *= *)@Month\w(?=(?: (?:[12]?\d|30|31),?|) (?:1[6-9]\d|20[01])\d\b)/gi, '$1@Month'); //rem stray digit at the end of year string
 
	ohc_regex(/(date *= *)(জানুয়ারি|Febr)[\w ]?[aur]{3,4}\w{0,2}(?=(?: (?:[12]?\d|30|31),?|) (?:1[6-9]\d|20[01])\d\b)/gi, '$1$2uary'); 
	ohc_regex(/(date *= *)J[anu]{3,5}r\w{0,2}(?=(?: (?:[12]?\d|30|31),?|) (?:1[6-9]\d|20[01])\d\b)/gi, '$1জানুয়ারি');
	ohc_regex(/(date *= *)Febua?r\w{0,2}(?=(?: (?:[12]?\d),?|) (?:1[6-9]\d|20[01])\d\b)/gi, '$1ফেব্রুয়ারি');
	ohc_regex(/(date *= *)M\w{2,3}ch(?=(?: (?:[12]?\d|30|31),?|) (?:1[6-9]\d|20[01])\d\b)/gi, '$1মার্চ'); 
	ohc_regex(/(date *= *)A[bpv\[]\w{2,3}l\w?(?=(?: (?:[12]?\d|30),?|) (?:1[6-9]\d|20[01])\d\b)/gi, '$1এপ্রিল');
	ohc_regex(/(date *= *)Ma[tui](?=(?: (?:[12]?\d|30|31),?|) (?:1[6-9]\d|20[01])\d\b)/gi, '$1মে'); 
	ohc_regex(/(date *= *)J\wn\w(?=(?: (?:[12]?\d|30),?|) (?:1[6-9]\d|20[01])\d\b)/gi, '$1জুন'); 
	ohc_regex(/(date *= *)J\w{1,2}e(?=(?: (?:[12]?\d|30),?|) (?:1[6-9]\d|20[01])\d\b)/gi, '$1জুন'); 
	ohc_regex(/(date *= *)জুলাই\w{1,2}(?=(?: (?:[12]?\d|30|31),?|) (?:1[6-9]\d|20[01])\d\b)/gi, '$1জুলাই'); 
	ohc_regex(/(date *= *)A[oug]{2,3}\w{1,4}t(?:\w|us)?(?=(?: (?:[12]?\d|30|31),?|) (?:1[6-9]\d|20[01])\d\b)/gi, '$1আগষ্ট'); 
	ohc_regex(/(date *= *)(সেপ্টেম্বর|নভেম্বর|ডিসেম্বর)\w{2,4}b[er]{1,2}\w?(?=(?: (?:[12]?\d|30|31),?|) (?:1[6-9]\d|20[01])\d\b)/gi, '$1$2ember'); 
	ohc_regex(/(date *= *)S\w{0,2}p[ \[]?\w{2,5}[er]{2,3}\w?(?=(?: (?:[12]?\d|30),?|) (?:1[6-9]\d|20[01])\d\b)/gi, '$1সেপ্টেম্বর'); 
	ohc_regex(/(date *= *)O\w{0,2}t\w{1,3}[er]{2,3}\w?(?=(?: (?:[12]?\d|30|31),?|) (?:1[6-9]\d|20[01])\d\b)/gi, '$1অক্টোবর'); 
	ohc_regex(/(date *= *)[MN]\w{1,2}[bv] ?\w{1,3}b[er]{1,2}\w?(?=(?: (?:[12]?\d|30),?|) (?:1[6-9]\d|20[01])\d\b)/gi, '$1নভেম্বর'); 
	ohc_regex(/(date *= *)D[ie]?[cs] ?\w{1,4}b[er]{1,2}\w?(?=(?: (?:[12]?\d|30|31),?|) (?:1[6-9]\d|20[01])\d\b)/gi, '$1ডিসেম্বর'); 

//insert comma to separate date from army unit
	ohc_regex(/@FullMonth ((?:the |)\d\d*@th (?:Air(?:borne|)|Arm(?:ou?red|y)|Artillery|Battalion|Brigade|Co(?:mpan|)y|Division|Fleet|Group|Infantry|Land|Panzer|Regiment|Squadron|Sqn)\b)/g, "@Month, $1");

	// remove parasitic metadata - time
	ohc_regex(/(\|\s*\w*date\s*=\s*@yyyy-@mm-@dd)\s?(?:T[0-2]\d:[0-5]\d:[0-5]\d(?:\s*|&nbsp;|)(?:GMT\s*|UTC\s*|[A-Z]{1,2}[DS]T\s*|Z))(?=\s*[|}])/g, "$1");
	ohc_regex(/(\|\s*\w*date\s*=\s*@month @day,? @yyyy)\s?(?:,? [0-2]?\d[\.:][0-5]\d(?:\s*|&nbsp;)(?:[apAP][mM]\s*|)(?:GMT\s*|UTC\s*|[A-Z]{1,2}[DS]T\s*|))(?=\|)/g, "$1");
	ohc_regex(/(\|\s*\w*date\s*=\s*@day @month,? @yyyy)\s?(?:,? [0-2]?\d[\.:][0-5]\d(?:\s*|&nbsp;)(?:[apAP][mM]\s*|)(?:GMT\s*|UTC\s*|[A-Z]{1,2}[DS]T\s*|))(?=\|)/g, "$1");
	ohc_regex(/(\|\s*\w*date\s*=\s*\w[\w\s]+@month @day,? @yyyy)\s?(?:,? [0-2]?\d[\.:][0-5]\d(?:\s*|&nbsp;)(?:[apAP][mM]\s*|)(?:GMT\s*|UTC\s*|[A-Z]{1,2}[DS]T\s*|))(?=\|)/g, "$1");
	ohc_regex(/(\|\s*\w*date\s*=\s*\w[\w\s]+@day @month,? @yyyy)\s?(?:,? [0-2]?\d[\.:][0-5]\d(?:\s*|&nbsp;)(?:[apAP][mM]\s*|)(?:GMT\s*|UTC\s*|[A-Z]{1,2}[DS]T\s*|))(?=\|)/g, "$1");
	ohc_regex(/(\|\s*\w*date\s*=[^:|}]*)\s?(?:T?[0-2]\d:[0-5]\d:[0-5]\d(?:\s*|&nbsp;|)(?:GMT\s*|UTC\s*|[A-Z]{1,2}[DS]T\s*|Z))/g, "$1");

//  add back spaces or comma or remove other single artefact after date string	
	ohc_regex(/(\|\s*(?:publication|archive|access|air|)-?date\s*=\s*)(?:on |)@Day\s{,2}@Month\s{,2}@YYYY[^a-z{}]?(?=\s*[|}\n])/gi, "$1@Day @Month @YYYY$2");
	ohc_regex(/(\|\s*(?:publication|archive|access|air|)-?date\s*=\s*)(?:on |)@Month\s{,2}@Day,?\s{,2}@YYYY[^a-z{}]?(?=\s*[|}\n])/gi, "$1@Month @Day, @YYYY$2");
	//long-hand palliative for observed failure to insert spaces
	ohc_regex(/(\|\s*(?:archive|access|air)-?date\s*=\s*)(?:on |)([0-2]?\d|30|31)\s*(জানুয়ারি|ফেব্রুয়ারি|মার্চ|এপ্রিল|মে|জুন|জুলাই|আগষ্ট|সেপ্টেম্বর|অক্টোবর|নভেম্বর|ডিসেম্বর)\s*((?:19\d|20[0-1])\d\s?)[^|{}\s<>]*(?=\s*[|}])/gi, "$1$2 $3 $4");
//	ohc_regex(/(\|\s*(?:publication|)-?date\s*=\s*)(?:on |)@Day\s*@Month\s*@YYYY([a-z]\s?|\s?)\w*[^|{}<>]*(?=[|}])/gi, "$1@Day @Month @YYYY$2");
//	ohc_regex(/(\|\s*(?:publication|)-?date\s*=\s*)(?:on |)@Month\s*@Day,\s*@YYYY([a-z]\s?|\s?)\w*[^|{}<>]*(?=[|}])/gi, "$1@Month @Day, @YYYY$2");

//remove extraneous bracket //from Batty
	ohc_regex(/{{(\s*[Cc]it(?:e|ation))([^}]+)(\s*\|\s*(?:archive-?|access-?|publication-?)?date\s*=\s*)([\w\s-]+)\](?=\s*[\|}<])/gi, '{{$1$2$3$4');  

	//fix bda template redirect
//	regex(/\{\{bda\|([^}]+)\}\}/gi, '{{birth date and age|$1}}');
//	regex(/\{\{dda\|([^}]+)\}\}/gi, '{{death date and age|$1}}');

	//zap redundant {{date}}, {{accessdate}} {{retrieved}}, {{monthname}} and {{#dateformat}}
//	regex(/({{(?:end|start)[-–]date)\|df=y(?:es|)/gi, "$1"); //rem deprecated parameter - disabled: doesn't work here, so ejected to the formatting script
	ohc_regex(/{{#formatdate:@YYYY-@MM-@DD(?:[^\}]*)}}/gi, "@Day @Month @YYYY");
	regex(/{{#formatdate:([^}]+)}}/gi, "$1");
	regex(/\{\{#dateformat:([^}\|]+)(?:\|dmy|\|mdy)?\}\}/gi, '$1');
//	ohc_regex(/(date[ ]*=[ ]*)\{\{(?:Start|End) ?date(?:\|df=y(?:es|)|)\|@YYYY\|@MM\|@DD(?:\|df=y(?:es|)|)\}\}/gi, '$1@Month @DD, @YYYY');  //stripping start/end template notes inside "|date=" parameter (line 72)
	ohc_regex(/{{#formatdate:@YYYY-@MM-@DD(?:\|(?:[dmy]{3}|iso)|)}}/gi, "@Day @Month @YYYY");
	ohc_regex(/\{\{date\|@YYYY-@MM-@DD\}\}/gi, "@Day @Month @YYYY");
	ohc_regex(/\{\{date\|(@DD[\-\s]@Mon|@Mon[\-\s]@DD)\}\}/gi, "@Day @Month");
	regex(/\{\{date\|([^}\|]+)(?:\|l?(?:[dmy]{3}|iso|none|link))?\}\}/gi, '$1');
	ohc_regex(/[ ]*\{\{accessdate\|@YYYY-@MM-@DD[ ]*\}\}/gi, " Retrieved @YYYY-@MM-@DD");
	ohc_regex(/[ ]*\{\{retrieved[ ]*\|[ ]accessdate=([\-\w, ]*)\}\}/gi, " Retrieved $1");
//	ohc_regex(/(date[ ]*=[ ]*|\w{2,}[ ]*)\{\{(?:start|end).date[^|}]*(?:\|df=y(?:es|)|)\|@YYYY(?:\|df=y(?:es|)|)\}\}/gi, '$1@YYYY');  //stripping start/end template (disabling to placate Pigsonthewing)
//	ohc_regex(/\{\{(?:Start|End) date(?:\|df=y(?:es|)|)\|@YYYY\|@MM\}\}/gi, '@Month @YYYY')  //stripping start/end template notes
//	ohc_regex(/<!--(?:Use)? \{\{(?:Start|End) date\|@YYYY\|@MM\|@DD\}\} -->/gi, '');  //stripping start/end template notes
	ohc_regex(/(\{\{MONTHNAME\|@MM\}\})/gi, "@Month")

//expand one and two-digit years in ranges
	regex(/(\()@Month @YYYY[-–]@Month @YYNN(\))/gi, '$1@Month1 @YYYY1 – @Month2 @YYYY2$2');
	regex(/(\(1[789])(\d)(1)[-–]([2-9]\))/gi, '$1$2$3–$2$4');
	regex(/(\(1[789])(\d)(2)[-–]([3-9]\))/gi, '$1$2$3–$2$4');
	regex(/(\(1[789])(\d)(3)[-–]([4-9]\))/gi, '$1$2$3–$2$4');
	regex(/(\(1[789])(\d)(4)[-–]([5-9]\))/gi, '$1$2$3–$2$4');
	regex(/(\(1[789])(\d)(5)[-–]([6-9]\))/gi, '$1$2$3–$2$4');
	regex(/(\(1[789])(\d)(6)[-–]([7-9]\))/gi, '$1$2$3–$2$4');
	regex(/(\(1[789])(\d)(7)[-–]([8-9]\))/gi, '$1$2$3–$2$4');
	regex(/(\(1[789])(\d)(8)[-–](9\))/gi, '$1$2$3–$2$4');
	regex(/(\(20)([01])(1)[-–]([2-9]\))/gi, '$1$2$3–$2$4');
	regex(/(\(20)([01])(2)[-–]([3-9]\))/gi, '$1$2$3–$2$4');
	regex(/(\(20)([01])(3)[-–]([4-9]\))/gi, '$1$2$3–$2$4');
	regex(/(\(20)([01])(4)[-–]([5-9]\))/gi, '$1$2$3–$2$4');
	regex(/(\(20)([01])(5)[-–]([6-9]\))/gi, '$1$2$3–$2$4');
	regex(/(\(20)([01])(6)[-–]([7-9]\))/gi, '$1$2$3–$2$4');
	regex(/(\(20)([01])(7)[-–]([8-9]\))/gi, '$1$2$3–$2$4');
	regex(/(\(20)([01])(8)[-–](9\))/gi, '$1$2$3–$2$4');

	ohc_regex(/(\W)@DD@th?, @DD@th?((?:[ ]|&nbsp;)(?:and|&|to|or)(?:[ ]|&nbsp;))@DD@th?(?:\sof\s?)?([ ]|&nbsp;)@Month(?=\W)/gi, '$1@Day1, @Day2$2@Day3$3@LMonth');
	ohc_regex(/(\W)@DD@th?((?:[ ]|&nbsp;)(?:and|&|to|or)(?:[ ]|&nbsp;))@DD@th?(?:\sof\s?|)([ ]|&nbsp;)@Month(?=\W)/gi, '$1@Day1$2@Day2$3@LMonth');
	ohc_regex(/(\W)the @DD@th(?:\sof|)\s@Month,? @YYYY(?=\W\D)/g, '$1@Day @LMonth @YYYY');
	ohc_regex(/(\W)the @DD@th(?:\sof|)\s@Month(?=\W\D)/g, '$1@Day @LMonth');
	ohc_regex(/(\W)@Day@th?(?:\sof|)([ _]|&nbsp;|{{(?:break|nbsp)}})@Month(?=[^|\]\w])/gi, '$1@Day$2@LMonth');
	ohc_regex(/(\W)@Month\s(?:the\s)?@DD@th?,(?:\sthe\s)?(?: |&nbsp;)@DD@th?(\s(?:and|&|to|or)(?:[ _]|&nbsp;))(?:the\s)?@DD@th?(?=[^|\]\w])/gi, '$1@LMonth @Day1, @Day2$2@Day3');
	ohc_regex(/(\W)(@month)\s(@day)((?:,\s@day){0,6}),?(\/|\s?[-–]\s?|\s(?:and|&|to|or)\s+?)@Day@th?(?:,?(?:[ _]|&nbsp;)|\sof\s)?(\d{3,4}\W\D)/gi, '$1$2 $3$4$5@Day, $6');
	ohc_regex(/(\W)(@month)\s(@day)((?:,\s@day){0,6}),?(\/|\s?[-–]\s?|\s(?:and|&|to|or)\s+?)@Day@th?(?=\W\D)/gi, '$1$2 $3$4$5@Day');
	ohc_regex(/(\W)@Month([ _]|&nbsp;|{{(?:break|nbsp)}})(?:the\s)?@DD@th?,? @Year/gi, '$1@LMonth$2@Day, @Year');
	ohc_regex(/(\W)@Month @Day(?:\sof|,|)([ _]|&nbsp;|{{(?:break|nbsp)}})@Year(?=[^|\]\w])/gi, '$1@Month @Day,$2@Year');

	// consolidating/amalgamating date fields
	ohc_regex(/(\|[ ]*date[ ]*=[ ]*@day)\s*\|[ ]*month=[ ]*(@month)\s*\|[ ]*year=[ ]*(@yyyy[ ]*)(?=[|}\s])/gi, "$1 $2 $3");
	ohc_regex(/(\|[ ]*date[ ]*=[ ]*@day.?@month)\s*\|[ ]*year=[ ]*(@yyyy[ ]*)(?=[|}\s])/gi, "$1 $2");
	ohc_regex(/(\|[ ]*date[ ]*=[ ]*@month.?@day)\s*\|[ ]*year=[ ]*(@yyyy[ ]*)(?=[|}\s])/gi, "$1 $2");

	// eliminating dates and time placed in author parameter
	//removing artefacts from Indian news sites (TNN আগষ্ট 30, 2012, 05.46AM)
	ohc_regex(/(\|\s*author\s*=\s*(?:[A-Z]{2,3}\b))(?:[^|}]*)\d{4}, [\d\.:]{4,5}(&nbsp;|)[AP]M IST(?=[ ]*\|)/g, '$1$2');
//	ohc_regex(/(\|\s*author=(?:[^\[\]|{}]*))(TNN|PTI) @day @month @yyyy, [\d\.:]{4,5}(&nbsp;|)[AP]M IST(?=[ ]*\|)/g, '$1$2');

	ohc_regex(/(\|\s*author\s*=\s*)@month @day,? @yyyy\s?(?:,? [0-2]?\d[\.:][0-5]\d(?:\s*|&nbsp;)(?:[apAP][mM]\s*|)(?:GMT\s*|UTC\s*|[A-Z]{1,2}[DS]T\s*|)|)(?=\|)/g, "$1");
	ohc_regex(/(\|\s*author\s*=\s*)@day @month,? @yyyy\s?(?:,? [0-2]?\d[\.:][0-5]\d(?:\s*|&nbsp;)(?:[apAP][mM]\s*|)(?:GMT\s*|UTC\s*|[A-Z]{1,2}[DS]T\s*|)|)(?=\|)/g, "$1");
	ohc_regex(/(\|\s*author\s*=\s*\w[\w\s]+)@month @day,? @yyyy(?:[^\[\]|{}]*)(?=[|}])/g, "$1");
	ohc_regex(/(\|\s*author\s*=\s*\w[\w\s]+)@day @month,? @yyyy(?:[^\[\]|{}]*)(?=[|}])/g, "$1");
	ohc_regex(/(\|\s*author\s*=\s*(?:\w[\w\s]+)?)@dd-@mm-@yyyy/gi, "$1");
	ohc_regex(/(\|\s*author\s*=\s*(?:\w[\w\s]+)?)@YYYY-@MM-@DD ?/gi, "$1");
	regex(/(\|\s*(?:date|archive-?date|access-?date|author)\s*=\s*(?:\w[\w\s]+)?)[0-2]\d:[0-5]\d(?:[ ]|&nbsp;)?(?:[ap]m|[ap]\.m\.|)(?: ?(?:[A-Z]{1,2}T|UTC)[\.,]?|)/gi, "$1");
//	ohc_regex(/(\|\s*author\s*=\s*(?:\w[\w\s]+)?)\s*[0-2]\d[\.:][0-5]\d(?:[\.:][0-5]\d|)/gi, "$1"); //let's see later if we need this

	// eliminating mm-dd-yyyy dates
	ohc_regex(/(\|\s*(?:publication|archive|access|air|)-?date\s*=\s*)@MM[-–\/\.=\s](1[3-9]|2\d|3[01])[-–\/\.=\s]@YYYY/gi, "$1@Month $2, @YYYY");
	ohc_regex(/(\|\s*(?:publication|archive|access|air|)-?date\s*=\s*)@Mon[-–\/\.=\s](1[3-9]|2\d|3[01])[-–\/\.=\s]@YYYY/gi, "$1@Month $2, @YYYY");
	ohc_regex(/[ ](?:Accessed|Retrieved)(?:(?: online|) on|:?)[ ]@MM[-–\/\.=\s](1[3-9]|2\d|3[01])[-–\/\.=\s]@YYYY(?=\D)/gi, " Retrieved @Month $1, @YYYY");
//	ohc_regex(/[ ](?:Accessed|Retrieved)(?:(?: online|) on|:?)[ ]@YYYY,? @Month @DD(?=\D)/gi, " Retrieved @Day @Month @YYYY");

	ohc_regex(/([ =|])@Mon[-–](1[3-9]|2\d|3[01])[-–]@YYYY(?=[^-–\d/])/gi, "$1@Mon $2, @YYYY"); 
	ohc_regex(/([ =|])@Mon\/(1[3-9]|2\d|3[01])\/@YYYY(?=[^-–\d/])/gi, "$1@Mon $2, @YYYY"); 
	ohc_regex(/([ =|])@Mon\.(1[3-9]|2\d|3[01])\.@YYYY(?=[^-–\d/])/gi, "$1@Mon $2, @YYYY"); 
	ohc_regex(/([ =|])@Mon (1[3-9]|2\d|3[01]) @YYYY(?=[^-–\d/])/gi, "$1@Mon $2, @YYYY"); 
	ohc_regex(/([ =|])@MM[-–](1[3-9]|2\d|3[01])[-–]@YYYY(?=[^-–\d/])/gi, "$1@Mon $2, @YYYY"); 
	ohc_regex(/([ =|])@MM\/(1[3-9]|2\d|3[01])\/@YYYY(?=[^-–\d/])/gi, "$1@Mon $2, @YYYY"); 
	ohc_regex(/([ =|])@MM\.(1[3-9]|2\d|3[01])\.@YYYY(?=[^-–\d/])/gi, "$1@Mon $2, @YYYY"); 
	ohc_regex(/([ =|])@MM (1[3-9]|2\d|3[01]) @YYYY(?=[^-–\d/])/gi, "$1@Mon $2, @YYYY"); 

	// eliminating dd-mm-yyyy dates (assumed default)
	ohc_regex(/(\|\s*(?:publication|archive|access|air|)-?date\s*=\s*)@DD[-–\/\.=\s]@MM[-–\/\.=\s]@YYYY/gi, "$1@Day @Month @YYYY");
	ohc_regex(/(\|\s*(?:publication|archive|access|air|)-?date\s*=\s*)@DD[-–\/\.=\s]@Mon[-–\/\.=\s]@YYYY/gi, "$1@Day @Month @YYYY");
	ohc_regex(/[ ](?:Accessed|Retrieved)(?:(?: online|) on|:?)[ ]@DD[-–\/\.=\s]@MM[-–\/\.=\s]@YYYY(?=\D)/gi, " Retrieved @Day @Month @YYYY");
	ohc_regex(/[ ](?:Accessed|Retrieved)(?:(?: online|) on|:?)[ ]@YYYY,? @Month @DD(?=\D)/gi, " Retrieved @Day @Month @YYYY");
	ohc_regex(/([ =|])@DD[-–]@Mon[-–]@YYYY(?=[^-–\d/])/gi, "$1@Day @Month @YYYY"); 
	ohc_regex(/([ =|])@DD\/@Mon\/@YYYY(?=[^-–\d/])/gi, "$1@Day @Month @YYYY"); 
	ohc_regex(/([ =|])@DD\.@Mon\.@YYYY(?=[^-–\d/])/gi, "$1@Day @Month @YYYY");
	ohc_regex(/([ =|])@DD @Mon @YYYY(?=[^-–\d/])/gi, "$1@Day @Month @YYYY"); 
	ohc_regex(/([ =|])@DD[-–]@MM[-–]@YYYY(?=[^-–\d/])/gi, "$1@Day @Month @YYYY"); 
	ohc_regex(/([ =|])@DD\/@MM\/@YYYY(?=[^-–\d/])/gi, "$1@Day @Month @YYYY"); 
	ohc_regex(/([ =|])@DD\.@MM\.@YYYY(?=[^-–\d/])/gi, "$1@Day @Month @YYYY");
	ohc_regex(/([ =|])@DD @MM @YYYY(?=[^-–\d/])/gi, "$1@Day @Month @YYYY"); 
	ohc_regex(/(\|\s*(?:publication|archive|access|air|)-?date\s*=\s*)@DD[-–\/\.=\s]@Month[-–\/\.=\s]@YYNN(?=\s*[|}\n])/gi, '$1@Day @Month @YYYY');

//convert yyyy-dd-mm to yyyy-mm-dd
	ohc_regex(/{{(\s*[Cc]it(?:e|ation))([^}]+)(\s*\|\s*(?:publication|archive|access|air|)-?date\s*=\s*(?:1[0-9]|20)\d{2})[-/\.=\s](1[3-9]|2\d|3[01])[-/\.=\s](0?\d|1[0-2])(\s*[\|}<])/gi, '{{$1$2$3-$5-$4$6'); //from Batty

// eliminating other errant formats
	ohc_regex(/(\|(?:[\w ]*)date\s*=\s*)([0-2]?\d|30|31) @Month \2,? @YYYY(?=\s*[|}])/gi, "$1$2 @Month @YYYY"); //repeated digits
	ohc_regex(/(\|\s*(?:publication|archive|access|air|)-?date\s*=\s*)@Day ?@Month ?200([01]\d)[^\s|}]?(?=\s*[|}])/gi, "$1@Day @Month 20$2");
	ohc_regex(/(\|\s*(?:publication|archive|access|air|)-?date\s*=\s*)@Month ?@Day,? ?200([01]\d)[^\s|}]?(?=\s*[|}])/gi, "$1@Month @Day, 20$2");

	ohc_regex(/([ ]\()@DD-@MM-@YYYY(\)\W)/gi, '$1@Day @Month @YYYY$2');
	ohc_regex(/([ ]\()@DD-@Month-@YYYY(\)\W)/gi, '$1@Day @Month @YYYY$2');
	ohc_regex(/(\|(?:[\w ]*)date\s*=\s*)@Month, @DD, @YYYY(?=\s*[|}])/gi, "$1@Day @Month @YYYY");
	ohc_regex(/(\|(?:[\w ]*)date\s*=\s*)@DD[\.,] @Month,? @YYYY(?=\s*[|}])/gi, "$1@Day @Month @YYYY");
	ohc_regex(/(\|(?:[\w ]*)date\s*=\s*)@YYYY,? @Month @DD(?=\s*[|}])/gi, "$1@Day @Month @YYYY");
	ohc_regex(/(\|(?:[\w ]*)date\s*=\s*)@YYYY,? @DD @Month(?=\s*[|}])/gi, "$1@Day @Month @YYYY");
	ohc_regex(/[ ]\(@YYYY,? @Month @DD\)/gi, " (@Day @Month @YYYY)");
	ohc_regex(/[ ]\(@YYYY @MM @DD\)/gi, " (@Day @Month @YYYY)");
	ohc_regex(/[ ]\(@YYYY, @DD @Month\)/gi, " (@Day @Month @YYYY)");
	ohc_regex(/(\|(?:[\w ]*)date\s*=\s*)@YYYY,? @Month(?=\s*[|}])/gi, "$1@Month @YYYY");
	ohc_regex(/[ ]\(@YYYY, @Month\)/gi, " (@Month @YYYY)");
	ohc_regex(/[ ]\(@Mon@YYYY\)/gi, " (@Mon @YYYY)");

	//CS1 errors ISO-like dates (too few or too many digits)
	ohc_regex(/(date\s*=\s*)(?:\[\[)?@YYYY(?:\]\][–—‐]\[\[|[–—‐])@MM[\-–—‐]@DD(?:\]\])?(?=\s*[|}])/gi, "$1@YYYY-@ZM-@ZD"); //ndashes and emdashes
	ohc_regex(/(\|\s*access-?date\s*=)\s*@YYYY-0[–—]@DD(?=\s*[|}])/gi, ""); //rem nonsense access date
	ohc_regex(/(\|(?:[\w ]*)date\s*=\s*)@YYYY[-–—]@MM[-–—]@DD(?=\s*[|}])/gi, "$1@YYYY-@ZM-@ZD"); //ndashes and emdashes
//	ohc_regex(/(\|(?:[\w ]*)date\s*=\s*)@YYYY[\-–—‐]@MM(?=\s*[|}])/gi, "$1@Month @YYYY"); //transform "yyyy-mm" to "month year"
	ohc_regex(/(<ref[^>]*>[^<]+?)([\s\(])@YYYY[–—]@MM[–—]@DD([^-\w\/%,<][^<]*?<\/ref>)/gi, "$1$2@Day @Month @YYYY$3");
	ohc_regex(/(<ref[^>]*>[^<]+?)([\s\(])@YYYY[-]@MM[-]([1-9])([^-\w\/%,<][^<]*?<\/ref>)/gi, "$1$2$3 @Month @YYYY$4");  

	// spaces and commas between month and year
	ohc_regex(/@Month(?:,?|\s+of|)(\s|&nbsp;)@YYYY(?=\D)/gi, "@LMonth$1@YYYY");

// fix month names (capitalize, remove dots)
	ohc_regex(/(\W)@DD\s@FullMonth(\s+|\s*,)/gi, "$1@Day @FullMonth$2");
	ohc_regex(/(\W)@DD\s@Mon(\s+|\s*,)/gi, "$1@Day @Mon$2");
	ohc_regex(/(\W)@FullMonth\s@DD(\s+|\s*,)/gi, "$1@FullMonth @Day$2");
	ohc_regex(/(\W)@Mon\s@DD(\s+|\s*,)/gi, "$1@Mon @Day$2");
	regex(/(\d(?:st|nd|rd|th) )C(entur(?:ies|y))(?=[ ]*(=|BC|AD|CE))/g, '$1c$2');
//	regex(/(\d(?:st|nd|rd|th) )C(entur(?:ies|y))(?![ \-][A-Z]\w*|''|")/g, '$1c$2');

	//spaces and commas - in date formats
	ohc_regex(/(\D\W\[?\[?@dd)[ ]+(@month)(\]\])?[ ]*,[ ]*(\[?\[?@yyyy(\sAD|\sBC|\sCE|\sBCE|)\]?\]?\W\D)/gi, "$1 $2$3 $4");
	ohc_regex(/(\D\W\[?\[?)(@month)[ ]+(@dd)(\]?\]?)(?:[ ]*,[ ]*)(\[?\[?@yyyy(\sAD|\sBC|\sCE|\sBCE|)\]?\]?\W\D)/gi, "$1$2 $3$4, $5");
	ohc_regex(/(\D\W\[?\[?)(@month)[ ]+(@dd)(\]?\]?)[ ]+(\[?\[?@yyyy(\sAD|\sBC|\sCE|\sBCE|)\]?\]?\W\D)/gi, "$1$2 $3$4, $5");

	ohc_regex(/(@month)(?:, | of )(@yyyy\w)/gi, "$1 $2"); //repeat after delinking

	// spaces and commas - md-md and dm-dm date ranges
	ohc_regex(/(\D\W)@Month\s@DD(&nbsp;|\s)(?:[-–—]|&[mn]dash;)(?:&nbsp;|\s)?@Month\s@DD(?=\W\D)/gi, "$1@LMonth1 @Day1$2– @LMonth2 @Day2");
	ohc_regex(/(\D\W)@Month\s@DD(?:[-–—]|&[mn]dash;)(?:&nbsp;|\s)?@Month\s@DD(?=\W\D)/gi, "$1@LMonth1 @Day1 – @LMonth2 @Day2");
	ohc_regex(/(\D\W)@DD\s@Month(&nbsp;|\s)(?:[-–—]|&[mn]dash;)(?:&nbsp;|\s)?@DD\s@Month(?=\W\D)/gi, "$1@Day1 @LMonth1$2– @Day2 @LMonth2");
	ohc_regex(/(\D\W)@DD\s@Month(?:[-–—]|&[mn]dash;)(?:&nbsp;|\s)?@DD\s@Month(?=\W\D)/gi, "$1@Day1 @LMonth1 – @Day2 @LMonth2");

	// spaces and commas - d-dm and md-d date ranges
	ohc_regex(/(\D\W)@Month(\s|&nbsp;)@DD@th?(?:(?:\s*|&nbsp;|)[-–](?:\s*|&nbsp;|))@DD@th?(?=\W\D)/gi, "$1@LMonth1$2@Day1–@Day2");
	ohc_regex(/(\D\W)@DD@th?(?:(?:\s*|&nbsp;|)[-–](?:\s*|&nbsp;|))@DD@th?(\s|&nbsp;)@Month(?=\W\D)/gi, "$1@Day1–@Day2$2@LMonth1");

	// spaces and commas between month and year (again)
	ohc_regex(/@Month(?:,\s+|\s+of\s+)@YYYY(\w)/gi, "@LMonth @YYYY$1");
}

/** ------------------------------------------------------------------------- */
/// ISO to long format

function ohc_ISO_to_dmy_in_citations()
{
	//ISO dates within single citation
	ohc_regex(/(\|\s*(?:publication|archive|access|air|designation\d?_|)-?date\s*=\s*)@YYYY[-–]@MM[-–]@DD(?=\W\D)/gi, "$1@Day @Month @YYYY");
}

function ohc_ISO_to_mdy_in_citations()
{
	//ISO dates within single citation
	ohc_regex(/(\|\s*(?:publication|archive|access|air|designation\d?_|)-?date\s*=\s*)@YYYY[-–]@MM[-–]@DD(?=\W\D)/gi,  "$1@Month @Day, @YYYY");
}

function ohc_ISO_to_dmy_in_references()
{
	//multiple calls for multiple dates within single citation
	ohc_regex(/(<ref[^>]*>[^<]+?)([\s\(])@YYYY[-–]@MM[-–]@DD([^-\w\/%,<][^<]*?<\/ref>)/gi, "$1$2@Day @Month @YYYY$3");
	ohc_regex(/(<ref[^>]*>[^<]+?)([\s\(])@YYYY[-–]@MM[-–]@DD(<\/ref>)/gi, "$1$2@Day @Month @YYYY$3");
}

function ohc_ISO_to_mdy_in_references()
{
	//multiple calls for multiple dates within single citation
	ohc_regex(/(<ref[^>]*>[^<]+?)([\s\(])@YYYY[-–]@MM[-–]@DD([^-\w\/%,<][^<]*?<\/ref>)/gi, "$1$2@Month @Day, @YYYY$3");
	ohc_regex(/(<ref[^>]*>[^<]+?)([\s\(])@YYYY[-–]@MM[-–]@DD(<\/ref>)/gi, "$1$2@Month @Day, @YYYY$3");
}

// currently unused
function ohc_ISO_to_dmy_anywhere()
{
	//multiple calls for multiple dates within single citation
	ohc_regex(/([^-\w/])@YYYY[-–]@MM[-–]@DD([^-\w/])/gi, '$1@Day @Month @YYYY$2');
	ohc_regex(/([^-\w/])@YYYY[-–]@MM[-–]@DD([^-\w/])/gi, '$1@Day @Month @YYYY$2');
	ohc_regex(/([^-\w/])@YYYY[-–]@MM[-–]@DD([^-\w/])/gi, '$1@Day @Month @YYYY$2');
}

// currently unused
function ohc_ISO_to_mdy_anywhere()
{
	//multiple calls for multiple dates within single citation
	ohc_regex(/([^-\w/])@YYYY[-–]@MM[-–]@DD([^-\w/])/gi, '$1@Month @Day, @YYYY$2');
	ohc_regex(/([^-\w/])@YYYY[-–]@MM[-–]@DD([^-\w/])/gi, '$1@Month @Day, @YYYY$2');
	ohc_regex(/([^-\w/])@YYYY[-–]@MM[-–]@DD([^-\w/])/gi, '$1@Month @Day, @YYYY$2');
}

function ohc_delink_ISO_to_dmy()
{
	ohc_ISO_to_dmy_in_citations();
	ohc_ISO_to_dmy_in_references();
	regex(/([^\w\/\-%,])@YYYY-@MM-@DD(<\s?\/ref.*?>)/g, '$1@Day @Month @Year$2');
	ohc_regex(/(\|\|[ ]*)@YYYY[-–]@MM[-–]@DD([ ]*\|\|)/gi, '$1{{dts|format=dmy|@YYYY|@MM|@DD}}$2');  //dts template for sortable tables
	ohc_regex(/(\{\{dts\|format=)mdy\|/gi, '$1dmy|');  //flip dts template formats
}

function ohc_delink_ISO_to_mdy()
{
	ohc_ISO_to_mdy_in_citations();
	ohc_ISO_to_mdy_in_references();
	regex(/([^\w\/\-%,])@YYYY-@MM-@DD(<\s?\/ref.*?>)/g, '$1@Month @Day, @Year$2');
	ohc_regex(/(\|\|[ ]*)@YYYY[-–]@MM[-–]@DD([ ]*\|\|)/gi, '$1{{dts|@YYYY|@MM|@DD}}$2');  //dts template for sortable tables (mdy is default)
	ohc_regex(/(\{\{dts\|)format=(?:mdy|dmy|) ?\|/gi, '$1');  //flip dts template formats
}

function ohc_delink_year_in_X()
{
//	ohc_regex(/\{\{(?:avyear|by|baseball\syear|fy|ly|mlby|mlb\syear|scy|sdy)\|(@year)\}\}/gi, "$1"); //disabled 3/5/21 discussion at https://en.wikipedia.org/w/index.php?title=Wikipedia_talk:WikiProject_Baseball&oldid=1021203365#Links_to_baseball_year_articles_in_infobox?
//	ohc_regex(/\{\{(?:avyear|by|baseball\syear|fy|ly|mlby|mlb\syear|scy|sdy)\|@year\|(@year)\}\}/gi, "$1");
	ohc_regex(/\[\[@yyyy\sin\s[^|\]]+\|((?:(?:@day |)@month |)@yyyy)\]\]/gi, '$1');
	regex(/\[\[(?:\d{4}[-–]\d{2} in English football)\|((?:(?:@Day |)@Month |)@YYYY)\]\]/gi, '$1'); 

	regex(/\[\[\d{4} Major League Baseball season\|(\d{4})(\sseason)?\]\]/gi, '$1$2');
}


// format parameter must be 'dmy' or 'mdy'
function ohc_fix_dts_template(format)
{
	// dts - format=dmy in this case (per D12000)
	// per {{dts}} doc, remove the obsolete link=off param
	regex(/(\{\{dts[^}]*)(?:\|link=off)/gi, '$1');
	ohc_regex(/(\{\{dts\s*\|\s*@year\s*\|\s*@month\s*\|\s*@day\s*\|\s*format=)(?:dmy|mdy)(\}\})/gi, '$1'+format+'$2');
	ohc_regex(/(\{\{dts\s*\|\s*format=)(?:dmy|mdy)(\s*\|\s*@year\s*\|\s*@month\s*\|\s*@day\s*\}\})/gi, '$1'+format+'$2');
	ohc_regex(/(\{\{dts\s*\|\s*@year\s*\|\s*@month\s*\|\s*@day\s*)(\}\})/gi, '$1|format='+format+'$2');

   // stripping – {{dts}} serves no purpose inside date parameters
	ohc_regex(/(\|(?:[\w ]*)date\s*=\s*)\{\{dts\s*\|\s*format=(?:dmy|mdy)\s*\|\s*([|}]*)\}\}(?=\s*[|}])/gi, "$1$2");
	ohc_regex(/(\|(?:[\w ]*)date\s*=\s*)\{\{dts\s*\|\s*([|}]*)(?:\|\s*format=(?:dmy|mdy)\s*|)\}\}(?=\s*[|}])/gi, "$1$2");
	ohc_regex(/(\|(?:[\w ]*)date\s*=\s*)\{\{dts\s*\|\s*format=(?:dmy|mdy)\s*\|\s*@YYYY(\s*\|\s*|-)@MM(\s*\|\s*|-)@DD\s*\}\}(?=\s*[|}])/gi, "$1@YYYY-@MM-@DD ");
	ohc_regex(/(\|(?:[\w ]*)date\s*=\s*)\{\{dts\s*\|\s*@YYYY(\s*\|\s*|-)@MM(\s*\|\s*|-)@DD\s*\|\s*format=(?:dmy|mdy)\s*\}\}(?=\s*[|}])/gi, "$1@YYYY-@MM-@DD ");
}

// format parameter must be 'dmy' or 'mdy'
function ohc_fix_gr_template(format)
{
	// GR - date formatting parameter
	// per {GR} doc, insert date formatting param
	regex(/(\{\{GR\|\d\d?)(?!\|date)/gi, '$1|dateform=' + format);
}

function ohc_dates_to_dmy()
{
	regex(/\|df=[mdy]{3}(?:-all|)(?=\s*[|}])/gi, '');
	regex(/\|format=mdy/gi, '|format=dmy');
	//change start and end templates; vgrelease new v=2 or mdy is default
	regex(/(\{\{(?:start date|end date)[^|}]*\|)df=ye?s?\|([^}]*df=ye?s?)/gi, '$1$2');
	regex(/(\{\{vgrelease new[^|}]*\|)(?:v=1\||)([A-Z]{2,3}\|)/g, '$1v=2|$2');
	ohc_regex(/(\|\s*(?:begin|end|first|last)\s*=\s*)@YYYY[-–]@MM[-–]@DD(?=\W\D)/gi, "$1@Day @Month @YYYY"); //spotted at [[Template:Infobox recurring event]]
 
	//change birth and death templates
	regex(/(\{\{(?:(?:Birth|Death) date(?: and age|)|launch|release|start)[^}]*\|)m(f=ye?s?)/gi, '$1d$2'); // substitute df for mf 
	regex(/(\{\{(?:(?:Birth|Death) date(?: and age|)|launch|release|start|film ?date|Wayback)[\|\d]+)(\}\})/gi, '$1|df=y$2'); //insert df parameter
	regex(/(\{\{(?:(?:Birth|Death) date(?: and age|)|launch|release|start|film ?date|Wayback)[\|\d]+\|)df=ye?s?\|([^}]*df=ye?s?)/gi, '$1$2'); //put date format parameter at the end
	regex(/(\{\{(?:start date|end date)\|)df=ye?s?\|((?:1[789]|20)\d{2}\}\})/gi, '$1$2');  //date format parameter not needed – year only

	//convert date ranges (md,d,d-dy to d,d,d-dmy; md,d,d-d to d,d,d-dm; md,d,d to d,d,dm)
	ohc_regex(/(\D\W)@Month((?:\s@day?,?){1,6}),?(\/|\s?(?:[-–]|&ndash;)\s?|(?:[ _]|&nbsp;)(?:and|&|to|or)(?:[ _]|&nbsp;)+?)@Day,?\s(?:of\s)?(@yyyy\W\D)/gi, "$1$2$3@Day @LMonth $4");
	ohc_regex(/(\D\W)@Month((?:\s@day?,?){1,6}),?(\/|\s?(?:[-–]|&ndash;)\s?|(?:[ _]|&nbsp;)(?:and|&|to|or)(?:[ _]|&nbsp;)+?)@Day(?=\W\D)/gi, "$1$2$3@Day @LMonth");

//	ohc_regex(/(\D\W)@Month((?:\s@day?,?){1,6}) @Day(?=\W\D)/gi, "$1$2 @Day @LMonth"); //disabling as unlikely and ungrammatical constructions causing false positives

	//'md, md,' to 'dm, dm,'
	ohc_regex(/(\D\W)@Month @Day, @Month @Day(?=[,\.]\W\D)/gi, "$1@Day1 @LMonth1, @Day2 @LMonth2");

	//convert simple mdy dates to dmy
	ohc_regex(/(p(?:g?\.?|age) ?\d+|p(?:p\.?|ages) ?\d+[-–]\d+), @Month((?:\s@day?,?){1,6}) @Day(?=\W\D)/gi, "$1. $2 @Day @LMonth");
	ohc_regex(/(\D\W)@Month\s@Day,?\s@Year(\s?(?:AD|BC|CE|BCE)\W\D)/gi, "$1@Day @LMonth @Year$2");
	ohc_regex(/(\|\s*term_(?:end|start)\d\s*=\s*|\D\W)@Month\s@Day,?\s@YYYY(?=\W\D)/gi, "$1@Day @LMonth @Year");
	ohc_regex(/(\|\s*term_(?:end|start)\d\s*=\s*|\D\W)@Month\s@Day(?=\W\D)/gi, "$1@Day @LMonth");

	//Month+day_number " 7th মার্চ" -> "7 মার্চ"
	ohc_regex(/(\D\W)@Day\s@Month\s@YYYY(?=\W\D)/gi, "$1@Day @LMonth @Year");
	ohc_regex(/(\D\W)@Day\s@Month(?=\W\D)/gi, "$1@Day @LMonth");
	ohc_regex(/(\D\W)@Month\s@Day,?\s@Year(?=\W\D)/gi, "$1@Day @LMonth @Year");

	//dates with embedded nbsp
	ohc_regex(/(\D\W)@Month([ _]|&nbsp;)(\d{1,2},(?: |&nbsp;)\d{1,2}(?:\s(?:and|&|to|or)(?:[ _]|&nbsp;))\d{1,2})(?=[^|\]\w])/gi, '$1$3$2@LMonth ');
	ohc_regex(/(\D\W)@Month([ _]|&nbsp;|{{(?:break|nbsp)}})@Day,([ _]|&nbsp;|{{(?:break|nbsp)}})@YYYY(?=[^|\]\w])/gi, '$1@Day$2@Month$3@Year');

	//remove comma
	ohc_regex(/(\D\W)@Day\s@Month,\s?@Year(?=\W\D)/gi, "$1@Day @LMonth @Year");

	//	remove "the" from "on the dd month"
	ohc_regex(/(on |by )the @Day\s@Month(?=[ ,\)\.])/gi, "$1@Day @LMonth");

	//remove space from date range conversion
	ohc_regex(/(\D ) @Day(\/|\s?(?:[-–]|&ndash;)\s?|(?:[ _]|&nbsp;)(?:and|&|to|or)(?:[ _]|&nbsp;)+?)/gi, "$1@Day$2");
}

function ohc_dates_to_mdy()
{
	//change birth and death templates – mf=y is the default; vgrelease new v=2 or mdy is default
	regex(/\|df=[mdy]{3}(?:-all|)(?=\s*[|}])/gi, '');
	regex(/\|df=y(?:es|)(?=[|}\s])/gi, '');
	regex(/(mf=y(?:es|)\|[^}]*\|)(?:mf=y(?:es|)\|)/gi, '$1');
	regex(/(\{\{vgrelease new[^|}]*\|)(?:v=2\||)([A-Z]{2,3}\|)/g, '$1$2');
	ohc_regex(/(\|\s*(?:begin|end|first|last)\s*=\s*)@YYYY[-–]@MM[-–]@DD(?=\W\D)/gi, "$1@Month @Day, @YYYY");

	//convert date ranges (d,d,d-dmy to md,d,d-dy; d,d,d-dm to md,d,d-d; dm,d,d to md,d,d)
	ohc_regex(/(\D\W)@Day((?:, @day){0,5})(\/|\s?(?:[-–]|&ndash;)\s?|\s(?:and|&|to|or)\s+?)@Day\s@Month,? @YYYY(?=\W\D)/gi, "$1@LMonth @Day1$2$3@Day2, @YYYY");
	ohc_regex(/(\D\W)@Day((?:, @day){0,5})(\/|\s?(?:[-–]|&ndash;)\s?|\s(?:and|&|to|or)\s+?)@Day\s@Month(?=\W\D)/gi, "$1@LMonth @Day1$2$3@Day2");
//	ohc_regex(/(\D\W)@Day((?:, @day){0,5})\s@Month,? @YYYY(?=\W\D)/gi, "$1@LMonth @Day1$2, @YYYY"); //disabling as unlikely and ungrammatical constructions causing false positives
//	ohc_regex(/(\D\W)@Day((?:, @day){0,5})\s@Month(?=\W\D)/gi, "$1@LMonth @Day1$2"); //disabling as unlikely and ungrammatical constructions causing false positives

	//'dm, dm,' to 'md, md,'
	ohc_regex(/(\D\W)@Day @Month, @Day @Month(?=[,\.]?\W\D)/gi, "$1@LMonth1 @Day1, @LMonth2 @Day2");

	//convert simple dmy dates to mdy
	ohc_regex(/(p(?:g?\.?|age) ?\d+|p(?:p\.?|ages) ?\d+[-–]\d+), @Month((?:\s@day?,?){1,6}) @Day(?=\W\D)/gi, "$1. @LMonth $2 @Day");
	ohc_regex(/(\D\W)@Day(\s|&nbsp;)@Month,?(\s|&nbsp;)@Year(?=\W\D)/gi, "$1@LMonth$2@Day,$3@Year");
	ohc_regex(/(\|\s*term_(?:end|start)\d\s*=\s*|\D\W)@Day[ ]+@Month,?\s@YYYY(?=\W\D)/gi, "$1@LMonth @Day, @Year");
	ohc_regex(/(\|\s*term_(?:end|start)\d\s*=\s*|\D\W)@Day[ ]+@Month(?=\W\D)/gi, "$1@LMonth @Day");

	//Month+day_number "মার্চ 7th" -> "মার্চ 7"
	ohc_regex(/(\D\W)@Month\s@Day@th?,?\s@YYYY(?=\W\D)/gi, "$1@LMonth @Day, @YYYY");
	ohc_regex(/(\D\W)@Day@th?(\s|&nbsp;)@Month(\s|&nbsp;)@YYYY(?=\W\D)/gi, "$1@LMonth$2@Day,$3@YYYY");
	ohc_regex(/(\D\W)@Month(\s|&nbsp;)@Day(?=\W\D)/gi, "$1@LMonth$2@Day");
	ohc_regex(/(\D\W)@Day@th?(\s|&nbsp;)@Month([,\.])(?=\W\D)/gi, "$1@LMonth$2@Day$3");

	//add comma where missing
	ohc_regex(/(\D\W)@Month\s@Day,?\s@YYYY,?(?=\s\w)/gi, "$1@LMonth @Day, @YYYY,");
	//rem superfluous comma where applicable
	ohc_regex(/(\D[^\w\/])@Month\s@ZD,,(?=\W\D|\b)/gi, "$1@LMonth @Day,");
}

function ohc_fix_dmy_redundancies()
{
	//month-range redundancies (repeating month names)
	ohc_regex(/([\D]@dd)@th? @Month[ ]{1,2}((?:to|and|-|–)[ ]{1,2}@dd)@th? @Month/, "$1 $2 @LMonth", function(d1, d2) {
		if (d1.m == d2.m) return true;
		return false;
	});
}
//not currently used
function ohc_fix_mdy_redundancies()
{
	//month-range redundancies (repeating month names)
	ohc_regex(/(@Month[ ]{1,2}@dd)@th? (to|and|-|–)[ ]{1,2}@Month[ ]{1,2}@DD@th?/, "$1 $2 @LDay", function(d1, d2) {
		if (d1.m == d2.m) return true;
		return false;
	});
}

function ohc_expand_ref_dates()
{
	ohc_regex(/(\|\s*(?:publication|archive|access|air|)-?date\s*=\s*)@Month @YYYY(?=\s*[|}])/gi, "$1@FullMonth @YYYY");
	ohc_regex(/(\|\s*(?:publication|archive|access|air|)-?date\s*=\s*)@Day @Month @YYYY(?=\s*[|}])/gi, "$1@Day @FullMonth @YYYY");
	ohc_regex(/(\|\s*(?:publication|archive|access|air|)-?date\s*=\s*)@Month @Day, @YYYY(?=\s*[|}])/gi, "$1@FullMonth @Day, @YYYY");

	ohc_regex(/(\|\s*(?:publication|archive|access|air|)-?date\s*=\s*)((?:[01-2]?\d|30|31) |)@Month @YYYY ?(?:-|–|&ndash;) ?((?:[01-3]?\d|30|31) |)@Month @YYYY(?=\s*[|}])/gi, "$1$2 @FullMonth1 @YYYY1 – $3@FullMonth2 @YYYY2");
	ohc_regex(/(\|\s*(?:publication|archive|access|air|)-?date\s*=\s*)@Month @Day(, (?:19|20)\d\d) ?(?:-|–|&ndash;) ?@Month @Day, @YYYY(?=\s*[|}])/gi, "$1@FullMonth1 @Day1$2 – @FullMonth2 @Day2, @YYYY");
	ohc_regex(/(\|\s*(?:publication|archive|access|air|)-?date\s*=\s*)@Day @Month,?( (?:19|20)\d\d) ?(?:-|–|&ndash;) ?@Day @Month @YYYY(?=\s*[|}])/gi, "$1@Day1 @FullMonth1$2 – @Day2 @FullMonth2 @YYYY");
	ohc_regex(/(\|\s*(?:publication|archive|access|air|)-?date\s*=\s*)@Month,?( (?:19|20)\d\d) ?(?:-|–|&ndash;) ?@Month,? @YYYY(?=\s*[|}])/gi, "$1@FullMonth1$2 – @FullMonth2 @YYYY");
	ohc_regex(/(\|\s*(?:publication|archive|access|air|)-?date\s*=\s*)((?:19|20)\d\d) ?(?:-|–|&ndash;) ?@Month @YYYY(?=\s*[|}])/gi, "$1@$2 – @FullMonth @YYYY");

	ohc_regex(/(<ref[^>]*>(?:[^<]+?[\s\(]|))((?:[01-2]?\d|30|31) |)@Month @YYYY ?(?:-|–|&ndash;) ?((?:[01-3]?\d|30|31) |)@Month @YYYY(?=(?:[^-\w\/%,<][^<]*?|)<\/ref>)/gi, "$1$2@FullMonth1 @YYYY1 – $3@FullMonth2 @YYYY2");
	ohc_regex(/(<ref[^>]*>(?:[^<]+?[\s\(]|))@Month @Day(, (?:19|20)\d\d) ?(?:-|–|&ndash;) ?@Month @Day, @YYYY(?=(?:[^-\w\/%,<][^<]*?|)<\/ref>)/gi, "$1@FullMonth1 @Day1$2 – @FullMonth2 @Day2, @YYYY");
	ohc_regex(/(<ref[^>]*>(?:[^<]+?[\s\(]|))@Day @Month,?( (?:19|20)\d\d) ?(?:-|–|&ndash;) ?@Day @Month @YYYY(?=(?:[^-\w\/%,<][^<]*?|)<\/ref>)/gi, "$1@Day1 @FullMonth1$2 – @Day2 @FullMonth2 @YYYY");
	ohc_regex(/(<ref[^>]*>(?:[^<]+?[\s\(]|))@Month,?( (?:19|20)\d\d) ?(?:-|–|&ndash;) ?@Month,? @YYYY(?=(?:[^-\w\/%,<][^<]*?|)<\/ref>)/gi, "$1@FullMonth1$2 – @FullMonth2 @YYYY");
	ohc_regex(/(<ref[^>]*>(?:[^<]+?[\s\(]|))((?:19|20)\d\d) ?(?:-|–|&ndash;) ?@Month @YYYY(?=(?:[^-\w\/%,<][^<]*?|)<\/ref>)/gi, "$1$2 – @FullMonth @YYYY");
}

function ohc_expand_all_dates()
{
	ohc_regex(/([^-\w/])@Month @YYYY(?=[^-\w/])/gi, '$1@FullMonth @YYYY');
	ohc_regex(/([^-\w/])@Day @Month @YYYY(?=[^-\w/])/gi, '$1@Day @FullMonth @YYYY');
	ohc_regex(/([^-\w/])@Month @Day, @YYYY(?=[^-\w/])/gi, '$1@FullMonth @Day, @YYYY');

	ohc_regex(/([^-\w/])((?:[01-2]?\d|30|31) |)@Month @YYYY ?(?:-|–|&ndash;) ?((?:[01-3]?\d|30|31) |)@Month @YYYY(?=[^-\w/])/gi, "$1$2@FullMonth1 @YYYY1 – $3@FullMonth2 @YYYY2");
	ohc_regex(/([^-\w/])@Month @Day(, (?:19|20)\d\d) ?(?:-|–|&ndash;) ?@Month @Day, @YYYY(?=[^-\w/])/gi, "$1@FullMonth1 @Day1$2 – @FullMonth2 @Day2, @YYYY");
	ohc_regex(/([^-\w/])@Day @Month,?( (?:19|20)\d\d) ?(?:-|–|&ndash;) ?@Day @Month @YYYY(?=[^-\w/])/gi, "$1@Day1 @FullMonth1$2 – @Day2 @FullMonth2 @YYYY");
	ohc_regex(/([^-\w/])@Month,?( (?:19|20)\d\d) ?(?:-|–|&ndash;) ?@Month,? @YYYY(?=[^-\w/])/gi, "$1@FullMonth1$2 – @FullMonth2 @YYYY");
	ohc_regex(/([^-\w/])((?:19|20)\d\d) ?(?:-|–|&ndash;) ?@Month @YYYY(?=[^-\w/])/gi, "$1$2 – @FullMonth @YYYY");

	ohc_regex(/([ ]\(|\|\s*)@Day @Month @YYYY(?=\)\W|\s*[|\n])/gi, "$1@Day @FullMonth @YYYY");
	ohc_regex(/([ ]\(|\|\s*)@Month @Day,? @YYYY(?=\)\W|\s*[|\n])/gi, "$1@FullMonth @Day, @YYYY");
	ohc_regex(/([ ]\((?:c\. |))@Month @YYYY ?(?:-|–|&nbsp;) ?@Day @Month @YYYY(?=\)\W)/gi, "$1@FullMonth1 @YYYY1 – @Day @FullMonth2 @YYYY2");
	ohc_regex(/([ ]\((?:c\. |))@Month @YYYY ?(?:-|–|&nbsp;) ?@Month @YYYY(?=\)\W)/gi, "$1@FullMonth1 @YYYY1 – @FullMonth2 @YYYY2");
	ohc_regex(/([ ]\((?:c\. |))@YYYY ?(?:-|–|&nbsp;) ?@Month @YYYY(?=\)\W)/gi, "$1@YYYY1 – @FullMonth @YYYY2");
	ohc_regex(/([ ]\((?:c\. |))@Month ?(?:-|–|&nbsp;) ?@Month @YYYY(?=\)\W)/gi, "$1@FullMonth1 – @FullMonth2 @YYYY");
	ohc_regex(/([ ]\((?:c\. |))@Month @YYYY(?=\)\W)/gi, "$1@FullMonth @YYYY");
}

function ohc_abbrev_ref_dates()
{
	ohc_regex(/(\|\s*(?:publication|archive|access|air|)-?date\s*=\s*)@Day @Month @YYYY(?=\s*[|}])/gi, "$1@Day @Mon @YYYY");
	ohc_regex(/(<ref[^>]*>(?:[^<]+?[\s\(]|))([12]?\d|30|31) (জানুয়ারি|ফেব্রুয়ারি|মার্চ|এপ্রিল|মে|জুন|জুলাই|আগষ্ট|অক্টোবর|Oct|নভেম্বর|ডিসেম্বর)(?:r?uary|ch|il|[ey]|ust|(?:t?em|o)ber)( (?:19\d|20[01])\d)(?=(?:[^-\w\/%,<][^<]*?|)<\/ref>)/gi, "$1$2 $3$4");
	ohc_regex(/([ ]\()@Day @Month @YYYY([^-\w\/])/gi, "$1@Day @Mon @YYYY$2");
 
	ohc_regex(/(\|\s*(?:publication|archive|access|air|)-?date\s*=\s*)@Month @Day, @YYYY(?=\s*[|}])/gi, "$1@Mon @Day, @YYYY");
	ohc_regex(/(<ref[^>]*>(?:[^<]+?[\s\(]|))(জানুয়ারি|ফেব্রুয়ারি|মার্চ|এপ্রিল|মে|জুন|জুলাই|আগষ্ট|অক্টোবর|Oct|নভেম্বর|ডিসেম্বর)(?:r?uary|ch|il|[ey]|ust|(?:t?em|o)ber) ([12]?\d|30|31),( (?:19\d|20[01])\d)(?=(?:[^-\w\/%,<][^<]*?|)<\/ref>)/gi, "$1$2 $3,$4");
	ohc_regex(/([^-\w\/])@Month @Day, @YYYY([^-\w\/])/gi, '$1@Mon @Day, @YYYY$2');
}
 
//not currently used
function ohc_abbrev_all_dates()
{
	ohc_regex(/([^-\w/])@Day @Month @YYYY(?=[^-\w/])/gi, '$1@Day @Mon @YYYY');
	ohc_regex(/([^-\w/])@Month @Day, @YYYY(?=[^-\w/])/gi, '$1@Mon @Day, @YYYY');
}

//not currently used
function ohc_dmy_publication_dates()
{
	ohc_regex(/(\|\s*(?:publication|archive|access|air|)-?date\s*=\s*)@Month @Day,? @YYYY/gi, "$1@Day @Month @YYYY"); // conversion of dates in references outside of the protection loop (eg for quotations etc.)
	ohc_regex(/(\|\s*(?:publication|archive|access|air|)-?date\s*=\s*)(?:\[\[)?@YYYY(?:\]\][-–]\[\[|[-–])@MM[-–]@DD(?:\]\])?(?=\s*[|}])/gi, "$1@Day @Month @YYYY");
	//replace ISO dates (within parentheses) only within refs
	ohc_regex(/(<ref[^>]*>[^<]+?)([ ]\()@YYYY-@MM-@DD(\))(\W[^<]*?<\/ref>)/gi, "$1$2@Day @Month @YYYY$3$4");
}

function ohc_mdy_publication_dates()
{
	ohc_regex(/(\|\s*(?:publication|archive|access|air|)-?date\s*=\s*)@Day @Month @YYYY/gi, "$1@Month @Day, @YYYY"); // conversion of dates in references outside of the protection loop (eg for quotations etc.)
	ohc_regex(/(\|\s*(?:publication|archive|access|air|)-?date\s*=\s*)(?:\[\[)?@YYYY(?:\]\][-–]\[\[|[-–])@MM[-–]@DD(?:\]\])?(?=\s*[|}])/gi, "$1@Month @Day, @YYYY"); 
	//replace ISO dates (within parentheses) only within refs
	ohc_regex(/(<ref[^>]*>[^<]+?)([ ]\()@YYYY-@MM-@DD(\))(\W[^<]*?<\/ref>)/gi, "$1$2@Month @Day, @YYYY$3$4");
}

function ohc_Bigendian_ref_dates() {
	// Add a tag to the summary box
	regex(/(\{\{use (?:mdy|dmy) dates)(?:\|cs1-dates=\w{1,2}|)(\|[^\}\|]+\}\})/gi, '$1|cs1-dates=y$2');
}

/** ------------------------------------------------------------------------ **/
/// EDIT SUMMARIES & USE DMY TEMPLATE
// this function modified 2019-03-27 from [[Special:Permalink/846525463]]
// format parameter must be 'dmy' or 'mdy'
function ohc_use_dates_template(format) 
{
	var txt = document.editform.wpTextbox1;
	// current month-year
	var currentDate = new Date();
	var currmonth = currentDate.getMonth();
	var curryear = currentDate.getFullYear();
	var myMonths = ["জানুয়ারি", "ফেব্রুয়ারি", "মার্চ", "এপ্রিল", "মে", "জুন", "জুলাই", "আগষ্ট", "সেপ্টেম্বর", "অক্টোবর", "নভেম্বর", "ডিসেম্বর"];
	var curryyyymm = myMonths[currmonth] + ' ' + curryear;

// step 1: normalize redirect template names to canonical template names 'Use dmy dates' or 'Use mdy dates' according to 'format' argument 
// rename redirects 'dmy', 'mdy', 'usedmydates', 'usemdydates' ('usedmydates' and 'usemdydates' are not currently listed as redirects but might be encountered?)
	regex(/\{\{ *(?:use(?:dmy|mdy)dates|dmy|mdy) *([\|\}])/gi, '{{Use ' + format + ' dates$1');
// rename redirects 'usedmy', 'usemdy', 'use dmy', 'use mdy' to canonical form
	regex(/\{\{ *use *(?:dmy|mdy) *([\|\}])/gi, '{{Use ' + format + ' dates$1');
// strip leading / trailing whitespace from 'use xxx dates'
	regex(/\{\{ *use (?:dmy|mdy) dates *([\|\}])/gi, '{{Use ' + format + ' dates$1');

// step 2: look for a canonical template name (the above might not have had anthing to work on) ; if found continue, write new template else
	var rxpdd = new RegExp("{{Use " + format + " dates", "gi");	// here we search for canonical form {{use xxx dates}} that has current date
	var dflagfound = txt.value.search(rxpdd);
	if (dflagfound === -1) {
		txt.value = '{{Use ' + format + ' dates|date=' + curryyyymm + '}}\r\n' + txt.value;	// not found so insert new template at top of wikitext
		return;																	// and done
	}

// step 3: rewrite existing canonical templates; add or refresh |date= to current month year; preserve |cs1-dates= as is
	regex(/(\{\{use (?:dmy|mdy) dates)\| *date *=[^\|]*\| *cs1\-dates *= *([^\|\}]*?) *\}\}/gi, '$1|date=' + curryyyymm + '|cs1-dates=$2}}');	// with |date= followed by |cs1-dates=
	regex(/(\{\{use (?:dmy|mdy) dates)\| *cs1\-dates *= *([^\|\}]*?) *\| *date *=[^\}]*\}\}/gi, '$1|date=' + curryyyymm + '|cs1-dates=$2}}');	// with |cs1-dates= followed by |date=
	regex(/(\{\{use (?:dmy|mdy) dates)\| *date *=[^\|\}]*\}\}/gi, '$1|date=' + curryyyymm + '}}');												// with |date=
	regex(/(\{\{use (?:dmy|mdy) dates)\| *cs1\-dates *= *([^\|\}]*?) \}\}/gi, '$1|date=' + curryyyymm + '|cs1-dates=$2}}');						// with |cs1-dates
	regex(/(\{\{use (?:dmy|mdy) dates)\}\}/gi, '$1|date=' + curryyyymm + '}}');																	// no parameters so add |date=curryyyymm 
	regex(/(\{\{[\t_ ]*use[\t_ ]+(?:dmy|mdy)[\t_ ]+dates[^{}]*\}\})([\r\n\t ]*)(\{\{[\t ]*short description[^{}]*\}\})/gi, '$3$2$1');			// repositioning "short description" template at the top
}



/** ------------------------------------------------------------------------ **/
/// DATE PROTECTION

var linkmap = [];

function ohc_protect_dates()
{
	// protects dates within links, quotes, etc
	// the sensitive part is stored and replaced with a unique identifier,
	// which is later replaced with the stored part.
 
	var protect_function = function(s, begin, replace, end) {
		linkmap.push(replace);
		return begin + "⍌"+(linkmap.length-1)+"⍍" + end;
	};
//\|x=
	regex(/(<timeline>)([\s\S]*?)(<\/timeline>)/gi, protect_function);
	regex(/(<!--)([^<\{\}]*?)(-->)/gi, protect_function);
	regex(/(<math>)([\s\S]*?)(<\/math>)/gi, protect_function);
	regex(/((?:{(?:Wikimedia |)Commons ?|C ?))(Cat(?:egory|))\|[^{}*](})/gi, protect_function);
	regex(/(<ref)([^>]+)(>)/gi, protect_function);
	regex(/((?:Category|Image|File):)([^|\]]*)([|\]])/gi, protect_function);
	regex(/(\{(?:See ?also|Main))(\|[^}]*)(\})/gi, protect_function);
	regex(/(\{\{(?:double ?|external ?|wide ?)image\s?\|)([^}]+)(\})/gi, protect_function);
	regex(/(\{\{(?:harvnb|r|wikisource)\|)([^}]+)(\})/gi, protect_function);
	regex(/(\{\{(?:Canadian federal by-election))([^}]+)(\}\})/gi, protect_function);
	
	regex(/(\[(?:https?:|ftp:))([^\]]*)(\])/gi, protect_function);
	regex(/(>[ ]*(?:https?:|ftp:))([^< >\]]*)([ ]*<)/gi, protect_function);
//	regex(/(https?:|ftp:)([^\s\]]*)([\s\]])/gi, protect_function);
	regex(/(<blockquote>)([\s\S]*?)(<\/blockquote>)/gi, protect_function);
	regex(/(<noinclude>)([\s\S]*?)(<\/noinclude>)/gi, protect_function);
	regex(/(<gallery)([\s\S]*?)(<\/gallery>)/gi, protect_function);
	regex(/(<poem>)([\s\S]*?)(<\/poem>)/gi, protect_function);
	regex(/(\{[^\{]{0,6}(?:quot[^|]{1,7}\s?|sic)\|)([^}]+)(\})/gi, protect_function);
	regex(/((?:image\d?|image_skyline|image[ _]location\d?|image[ _]name|image[ _]file|img|map\d|pic)\s*=)([^|}]*)([|}])/gi, protect_function);
	regex(/([\|\{]\s*(?:file(?:name\d?|)|image\d?|image location\d?|img|pic|Cover|(?:trans-?|)title|quote|chapter|journal|url|archiveurl|work|doi|club|at|volume|reporter)\s*=)([^|\}⍍]*)([|}])/gi, protect_function);
	regex(/([\|\{]\s*(?:file(?:name\d?|)|image\d?|image location\d?|img|pic|Cover|(?:trans-?|)title|quote|chapter|journal|url|archiveurl|work|doi|club|at|volume|reporter)\s*=)([^|\}⍍]*)([|}])/gi, protect_function);
	regex(/([\|\{]\s*(?:season)\s*=)(\s*\[\[[^\]]*\]\]\s*)([|}])/gi, protect_function);
	regex(/([\|\{]\s*(?:[xy])\s*=)(\s*[^\|]+\s*)(\|)/gi, protect_function);
	regex(/(\{\{navsource\|)([^}]+)(\})/gi, protect_function);
	regex(/(\{\{(?:singlechart)\|)([^}]+)(\})/gi, protect_function);
	regex(/(\{\{(?:defaultsort|graph):)([^}]+)(\})/gi, protect_function);
	regex(/(["“])([^"”\n]*)(["”])/gi, protect_function);
	regex(/(.)(\(\{\{by\|[12]\d{3}\}\}[-–]\{\{by\|)([12]\d{3}[ ]*\}\}\))/gi, protect_function);
	regex(/(.)(\(\{\{by\|[12]\d{3}\}\}(?:[-–]present|))(\))/gi, protect_function);
	regex(/(\[\[)(4AD)(\]\]|\|)/gi, protect_function);

	//retraining redirects containing a date
	regex(/(\[\[)(?:সেপ্টেম্বর 3 Society)(\]\]|\|)/gi, '$1Jiusan Society$2');
	regex(/(\[\[)(?:জুন 4th incident)(\]\]|\|)/gi, '$1Tiananmen Square protests of 1989$2');
	regex(/(\[\[)(?:5@th? অক্টোবর (?:\(Serbia\)|overthrow))(\]\]|\|)/gi, '$1Overthrow of Slobodan Milošević$2');
	regex(/(\[\[)(?:অক্টোবর 5@th?(?: \(Serbia\)| overthrow|, 2000))(\]\]|\|)/gi, '$1Overthrow of Slobodan Milošević$2');

	//protect alternate meanings of 'মে' and 'মার্চ' (note: not case insensitive)
//	ohc_regex(/([^\w])(@day,?\s{0,3}মে)([^\w][^\d])/g, protect_function);  //disabled 26 মে – not case senstitve: false negatives in converting dates in মে
	ohc_regex(/([^\w])(মার্চ\s@day)(\s(?:mile|kilomet|met))/g, protect_function);

	//protect all links containing a date and some text
	ohc_regex(/(\[\[)(\s*\w[^\]\|\n]+?@day[^\]\|\n]+?@fullmonth[^\]\|\n]*)(\]\]|\|)/gi, protect_function);
	ohc_regex(/(\[\[)([^\]\|\n]*?@day[^\]\|\n]+?@fullmonth(?:,? @year|) \D[^\]\|\n]+\w\s*)(\]\]|\|)/gi, protect_function);
	ohc_regex(/(\[\[)(\s*\w[^\]\|\n]+?@fullmonth[^\]\|\n]+?@day[^\]\|\n]*)(\|)/gi, protect_function);
	ohc_regex(/(\[\[)([^\]\|\n]*?@fullmonth[^\]\|\n]+?@day(?:, @year|) \D[^\]\|\n]+\w\s*)(\]\]|\|)/gi, protect_function);

	//protects certain dates
	regex(/(\[\[)(4AD)([\s\S])/gi, protect_function);
	regex(/([\s\S])(মার্চ (?:8|14) Alliance)([\s\S])/gi, protect_function);
	regex(/([\s\S])(23rd মার্চ 1931: Shaheed)([\s\S])/gi, protect_function);
	regex(/([\s\S])(Long মার্চ [1-7])([\s\S])/gi, protect_function);
	regex(/([\s\S])(National সেপ্টেম্বর 11 Memorial & Museum)([\s\S])/gi, protect_function);
	regex(/([\s\S])(Queen Elizabeth II সেপ্টেম্বর 11th Garden)([\s\S])/gi, protect_function);
	regex(/([\s\S])(Bombay মার্চ 12)([\s\S])/gi, protect_function);
	regex(/([\s\S])(movement 2 জুন)([\s\S])/gi, protect_function);
	regex(/([\s\S])(6th\sof অক্টোবর City)([\s\S])/gi, protect_function);
	regex(/([\s\S])(Party Workers' Liberation Front 30th of মে)([\s\S])/gi, protect_function);
	regex(/([\s\S])(4th\sof আগষ্ট regime)([\s\S])/gi, protect_function);
	regex(/([\s\S])(19th\sof এপ্রিল movement)([\s\S])/gi, protect_function);
	regex(/([\s\S])(জুন 4th (?:incident|museum))([\s\S])/gi, protect_function);
	regex(/([\s\S])(The Battle Of Marston Moor \(জুলাই 2nd,? 1644\))([\s\S])/gi, protect_function);
	regex(/([\s\S])(Night of জানুয়ারি 16th)([\s\S])/gi, protect_function);
	regex(/([\s\S])(Observance of 5th নভেম্বর Act)([\s\S])/gi, protect_function);
	regex(/(\[\[)(13 মে incident)(\|)/gi, protect_function);
	regex(/(\'\'\')(22nd\sof মে)(\'\'\')/gi, protect_function);
	regex(/(\[\[)(22nd\sof মে \(film\))([|\]\'])/gi, protect_function);
	regex(/(\[\[)(জুলাই 12, 2007, Baghdad airstrike)(\|)/gi, protect_function);
	
	regex(/(\[\[)(নভেম্বর 1828)(\]\])/gi, protect_function);
	regex(/(.)(4th\sof জুলাই)(.)/gi, protect_function);
	regex(/(\[\[)((?:2300|2000)\s?AD)(\]\])/gi, protect_function);
	regex(/(\[\[)(29 ফেব্রুয়ারি)(\]\])/gi, protect_function);
	regex(/(\[\[)(ফেব্রুয়ারি 29)(\]\])/gi, protect_function);

	// works names
//	regex(/(.)(protect string)(.)/gi, protect_function);
	regex(/(.)(11\/22\/63)(.)/gi, protect_function);
	regex(/(.)(1\.1\.1994)(.)/gi, protect_function);
	regex(/([\s\S])(2\.13\.61)([\s\S])/gi, protect_function);
//	regex(/(.)(4th of জুলাই, Asbury)(.)/gi, protect_function); //protected above globally
	regex(/(.)(26 অক্টোবর 1993)(.)/gi, protect_function);
	regex(/(\[\[|\'\')(জুন 1, 1974)(.)/gi, protect_function);
	regex(/(\[\[|\'\')(জুলাই 15, 1972)(.)/gi, protect_function);
	regex(/(\[\[|\'\')(আগষ্ট 1914)(.)/gi, protect_function);
	ohc_regex(/(\[\[|\'\')(@fullmonth @dd@th? \((?:@yyyy |)film\)(?:\|@fullmonth @dd@th?|))([\s\S])/gi, protect_function);
	ohc_regex(/(\[\[|\'\')(@dd@th? @fullmonth \((?:@yyyy |)film\)(?:\|@dd@th? @fullmonth|))([\s\S])/gi, protect_function);
//	regex(/(Les Bains Douches 18)( ডিসেম্বর 1979)(.)/gi, protect_function);
	regex(/(আগষ্ট)( 7, 4:15)(.)/gi, protect_function);
	regex(/(In Concert, Zürich, অক্টোবর)( 28, 1979)(.)/gi, protect_function);
	regex(/(CBGB OMFUG Masters: Live জুন)( 29, 2001)(.)/gi, protect_function);
	ohc_regex(/(Live at [\w ]*,? [1-3]\d)( @fullmonth)(.)/gi, protect_function);
	ohc_regex(/(Live at [\w ]*,? @fullmonth)( @dd)(.)/gi, protect_function);
	ohc_regex(/(Bootmoon Series: [\w ]*[-–] @fullmonth)( @day, @YYYY)(.)/gi, protect_function);

// expressions and grammatical strings including modal "মে"
	regex(/(\W)((?:\d{1,3}) মে)((?: have(?: \w+|)|) be)/g, protect_function);
	regex(/(\W)((?:\d{3}|3[2-9]|[4-9]\d)\/\d ডিসেম্বর(?:l\.?|))(\W)/gi, protect_function);
	regex(/(\W)((?:\d{2,3})\/\d ডিসেম্বর(?:l\.?|))( \(\d\d? overs)/gi, protect_function);
}

/** ------------------------------------------------------------------------ **/
/// DATE PROTECTION FOR ALL REF SECTION

var linkmap = [];

function ohc_protect_dates_ref() 
{
	// protects dates within links, quotes, etc
	// the sensitive part is stored and replaced with a unique identifier,
	// which is later replaced with the stored part.

	var protect_function = function (s, begin, replace, end) {
		linkmap.push(replace);
		return begin + "⍌" + (linkmap.length - 1) + "⍍" + end;
	};

	regex(/(<ref\s?(?:>|name=[^>]+))([^<]+)(<\/ref>)/gi, protect_function);
	regex(/(<timeline>)([\s\S]*?)(<\/timeline>)/gi, protect_function);
	regex(/(<math>)([\s\S]*?)(<\/math>)/gi, protect_function);
	regex(/((?:{(?:Wikimedia |)Commons ?|C ?))(Cat(?:egory|))\|[^{}*](})/gi, protect_function);
	regex(/((?:Category|Image|File):)([^|\]]*)([|\]])/gi, protect_function);
	regex(/(\{(?:See ?also|Main))(\|[^}]*)(\})/gi, protect_function);
	regex(/(\{\{(?:double ?|external ?|wide ?)image\s?\|)([^}]+)(\})/gi, protect_function);
	regex(/(\{\{(?:harvnb|wikisource)\|)([^}]+)(\})/gi, protect_function);
	regex(/(\[(?:https?:|ftp:))([^\]]*)(\])/gi, protect_function);
	regex(/(>[ ]*(?:https?:|ftp:))([^< >\]]*)([ ]*<)/gi, protect_function);
	//regex(/(https?:|ftp:)([^\s\]]*)([\s\]])/gi, protect_function);
	regex(/(<blockquote>)([\s\S]*?)(<\/blockquote>)/gi, protect_function);
	regex(/(\{[^\{]{0,6}(?:quot[^|]{1,7}\s?|sic)\|)([^}]+)(\})/gi, protect_function);
	regex(/((?:image\d?|image_skyline|image[ _]location\d?|image[ _]name|image[ _]file|img|pic)\s*=)([^|}]*)([|}])/gi, protect_function);
	regex(/([\|\{]\s*(?:file(?:name\d?|)|image\d?|image location\d?|img|pic|Cover|title|quote|chapter|journal|url|archiveurl|work|doi|club|at|volume|reporter)\s*=)([^|\}⍍]*)([|}])/gi, protect_function);
	regex(/([\|\{]\s*(?:file(?:name\d?|)|image\d?|image location\d?|img|pic|Cover|title|quote|chapter|journal|url|archiveurl|work|doi|club|at|volume|reporter)\s*=)([^|\}⍍]*)([|}])/gi, protect_function);
	regex(/([\|\{]\s*(?:season)\s*=)(\s*\[\[[^\]]*\]\]\s*)([|}])/gi, protect_function);
	regex(/(\{\{navsource\|)([^}]+)(\})/gi, protect_function);
	regex(/(\{\{singlechart\|)([^}]+)(\})/gi, protect_function);
	regex(/(\{\{defaultsort:)([^}]+)(\})/gi, protect_function);
	regex(/([\s\(>]")([^"\n]*)(")/gi, protect_function);
	regex(/([\s\(>]“)([^”\n]*)(”)/gi, protect_function);
	regex(/(.)(\(\{\{by\|[12]\d{3}\}\}[-–]\{\{by\|)([12]\d{3}[ ]*\}\}\))/gi, protect_function);
	regex(/(.)(\(\{\{by\|[12]\d{3}\}\}(?:[-–]present|))(\))/gi, protect_function);

	//retraining redirects containing a date
	regex(/(\[\[)(?:সেপ্টেম্বর 3 Society)(\]\]|\|)/gi, '$1Jiusan Society$2');
	regex(/(\[\[)(?:জুন 4th incident)(\]\]|\|)/gi, '$1Tiananmen Square protests of 1989$2');
	ohc_regex(/(\[\[)(?:5@th? অক্টোবর (?:\(Serbia\)|overthrow))(\]\]|\|)/gi, '$1Overthrow of Slobodan Milošević$2');
	ohc_regex(/(\[\[)(?:অক্টোবর 5@th?(?: \(Serbia\)| overthrow|, 2000))(\]\]|\|)/gi, '$1Overthrow of Slobodan Milošević$2');

	//protect alternate meanings of 'মে' and 'মার্চ' (note: not case insensitive)
	ohc_regex(/([^\w])(@day,?\s{0,3}মে)([^\w][^\d])/g, protect_function);
	ohc_regex(/([^\w])(মার্চ\s@day)(\s(?:mile|kilomet|met))/g, protect_function);

	//protect all links containing a date and some text
	ohc_regex(/(\[\[)(\s*\w[^\]\|\n]+?@day[^\]\|\n]+?@fullmonth[^\]\|\n]*)(\]\]|\|)/gi, protect_function);
	ohc_regex(/(\[\[)([^\]\|\n]*?@day[^\]\|\n]+?@fullmonth(?:,? @year|) \D[^\]\|\n]+\w\s*)(\]\]|\|)/gi, protect_function);
	ohc_regex(/(\[\[)(\s*\w[^\]\|\n]+?@fullmonth[^\]\|\n]+?@day[^\]\|\n]*)(\|)/gi, protect_function);
	ohc_regex(/(\[\[)([^\]\|\n]*?@fullmonth[^\]\|\n]+?@day(?:, @year|) \D[^\]\|\n]+\w\s*)(\]\]|\|)/gi, protect_function);

	//protects certain dates
	regex(/(\[\[)(4AD)([\s\S])/gi, protect_function);
	regex(/([\s\S])(মার্চ (?:8|14) Alliance)([\s\S])/gi, protect_function);
	regex(/([\s\S])(23rd মার্চ 1931: Shaheed)([\s\S])/gi, protect_function);
	regex(/([\s\S])(Long মার্চ [1-7])([\s\S])/gi, protect_function);
	regex(/([\s\S])(Bombay মার্চ 12)([\s\S])/gi, protect_function);
	regex(/([\s\S])(movement 2 জুন)([\s\S])/gi, protect_function);
	regex(/([\s\S])(6th\sof অক্টোবর City)([\s\S])/gi, protect_function);
	regex(/([\s\S])(Party Workers' Liberation Front 30th of মে)([\s\S])/gi, protect_function);
	regex(/([\s\S])(4th\sof আগষ্ট regime)([\s\S])/gi, protect_function);
	regex(/([\s\S])(19th\sof এপ্রিল movement)([\s\S])/gi, protect_function);
	regex(/([\s\S])(জুন 4th incident)([\s\S])/gi, protect_function);
	regex(/([\s\S])(The Battle Of Marston Moor \(জুলাই 2nd,? 1644\))([\s\S])/gi, protect_function);
	regex(/([\s\S])(Night of জানুয়ারি 16th)([\s\S])/gi, protect_function);
	regex(/([\s\S])(Observance of 5th নভেম্বর Act)([\s\S])/gi, protect_function);
	regex(/(\[\[)(13 মে incident)(\|)/gi, protect_function);
	regex(/(\'\'\')(22nd\sof মে)(\'\'\')/gi, protect_function);
	regex(/(\[\[)(22nd\sof মে \(film\))([|\]\'])/gi, protect_function);
	regex(/(\[\[)(জুলাই 12, 2007, Baghdad airstrike)(\|)/gi, protect_function);
	
	regex(/(\[\[)(নভেম্বর 1828)(\]\])/gi, protect_function);
	regex(/(.)(4th\sof জুলাই)(.)/gi, protect_function);
	regex(/(\[\[)((?:2300|2000)\s?AD)(\]\])/gi, protect_function);
	regex(/(\[\[)(29 ফেব্রুয়ারি)(\]\])/gi, protect_function);
	regex(/(\[\[)(ফেব্রুয়ারি 29)(\]\])/gi, protect_function);

	// works names
	//regex(/(.)(protect string)(.)/gi, protect_function);
	regex(/(.)(11\/22\/63)(.)/gi, protect_function);
	regex(/(.)(1\.1\.1994)(.)/gi, protect_function);
	regex(/([\s\S])(2\.13\.61)([\s\S])/gi, protect_function);
	//regex(/(.)(4th of জুলাই, Asbury)(.)/gi, protect_function); //protected above globally
	regex(/(.)(26 অক্টোবর 1993)(.)/gi, protect_function);
	regex(/(\[\[|\'\')(জুন 1, 1974)(.)/gi, protect_function);
	regex(/(\[\[|\'\')(জুলাই 15, 1972)(.)/gi, protect_function);
	regex(/(\[\[|\'\')(আগষ্ট 1914)(.)/gi, protect_function);
	ohc_regex(/(\[\[|\'\')(@fullmonth @dd@th? \((?:@yyyy |)film\)(?:\|@fullmonth @dd@th?|))([\s\S])/gi, protect_function);
	ohc_regex(/(\[\[|\'\')(@dd@th? @fullmonth \((?:@yyyy |)film\)(?:\|@dd@th? @fullmonth|))([\s\S])/gi, protect_function);
	//regex(/(Les Bains Douches 18)( ডিসেম্বর 1979)(.)/gi, protect_function);
	regex(/(আগষ্ট)( 7, 4:15)(.)/gi, protect_function);
	regex(/(In Concert, Zürich, অক্টোবর)( 28, 1979)(.)/gi, protect_function);
	regex(/(CBGB OMFUG Masters: Live জুন)( 29, 2001)(.)/gi, protect_function);
	ohc_regex(/(Live at [\w ]*,? [1-3]\d)( @fullmonth)(.)/gi, protect_function);
	ohc_regex(/(Live at [\w ]*,? @fullmonth)( @dd)(.)/gi, protect_function);
	ohc_regex(/(Bootmoon Series: [\w ]*[-–] @fullmonth)( @day, @YYYY)(.)/gi, protect_function);

	regex(/(\W)((?:\d{3}|3[2-9]|[4-9]\d)\/\d ডিসেম্বর(?:l\.?|))(\W)/gi, protect_function);
	regex(/(\W)((?:\d{2,3})\/\d ডিসেম্বর(?:l\.?|))( \(\d\d? overs)/gi, protect_function);
}


/** ------------------------------------------------------------------------ **/
/// DATE PROTECTION FOR SLASH modules

var linkmap = [];

function ohc_protect_dates_slash() 
{
	// protects dates within links, quotes, etc
	// the sensitive part is stored and replaced with a unique identifier,
	// which is later replaced with the stored part.

	var protect_function = function (s, begin, replace, end) {
		linkmap.push(replace);
		return begin + "⍌" + (linkmap.length - 1) + "⍍" + end;
	};

	regex(/(<ref\s?(?:>|name=[^>]+))([^<]+)(<\/ref>)/gi, protect_function);
	regex(/(<timeline>)([\s\S]*?)(<\/timeline>)/gi, protect_function);
	regex(/(<math>)([\s\S]*?)(<\/math>)/gi, protect_function);
	regex(/((?:{(?:Wikimedia |)Commons ?|C ?))(Cat(?:egory|))\|[^{}*](})/gi, protect_function);
	regex(/((?:Category|Image|File):)([^|\]]*)([|\]])/gi, protect_function);
	regex(/(\{(?:See ?also|Main))(\|[^}]*)(\})/gi, protect_function);
	regex(/(\{\{(?:double ?|external ?|wide ?)image\s?\|)([^}]+)(\})/gi, protect_function);
	regex(/(\{\{(?:harvnb|wikisource)\|)([^}]+)(\})/gi, protect_function);
	regex(/(\[(?:https?:|ftp:))([^\]]*)(\])/gi, protect_function);
	regex(/(>[ ]*(?:https?:|ftp:))([^< >\]]*)([ ]*<)/gi, protect_function);
	//regex(/(https?:|ftp:)([^\s\]]*)([\s\]])/gi, protect_function);
	regex(/(<blockquote>)([\s\S]*?)(<\/blockquote>)/gi, protect_function);
	regex(/(\{[^\{]{0,6}(?:quot[^|]{1,7}\s?|sic)\|)([^}]+)(\})/gi, protect_function);
	regex(/((?:image\d?|image_skyline|image[ _]location\d?|image[ _]name|image[ _]file|img|pic)\s*=)([^|}]*)([|}])/gi, protect_function);
	regex(/([\|\{]\s*(?:file(?:name\d?|)|image\d?|image location\d?|img|pic|Cover|title|quote|chapter|journal|url|archiveurl|work|doi|club|at|volume|reporter)\s*=)([^|\}⍍]*)([|}])/gi, protect_function);
	regex(/([\|\{]\s*(?:file(?:name\d?|)|image\d?|image location\d?|img|pic|Cover|title|quote|chapter|journal|url|archiveurl|work|doi|club|at|volume|reporter)\s*=)([^|\}⍍]*)([|}])/gi, protect_function);
	regex(/([\|\{]\s*(?:season)\s*=)(\s*\[\[[^\]]*\]\]\s*)([|}])/gi, protect_function);
	regex(/(\{\{navsource\|)([^}]+)(\})/gi, protect_function);
	regex(/(\{\{singlechart\|)([^}]+)(\})/gi, protect_function);
	regex(/(\{\{defaultsort:)([^}]+)(\})/gi, protect_function);
	regex(/([\s\(>]")([^"\n]*)(")/gi, protect_function);
	regex(/([\s\(>]“)([^”\n]*)(”)/gi, protect_function);
	regex(/(.)(\(\{\{by\|[12]\d{3}\}\}[-–]\{\{by\|)([12]\d{3}[ ]*\}\}\))/gi, protect_function);
	regex(/(.)(\(\{\{by\|[12]\d{3}\}\}(?:[-–]present|))(\))/gi, protect_function);

}

function ohc_unprotect_dates() 
{
	//unprotect all dates
	regex(/[♫]/g, '');
	regex(/⍌([0-9]+)⍍/g, function (x, n) {
		var res = linkmap[n];
		res = res.replace(/⍌([0-9]+)⍍/g, function (x, n) {
			var res = linkmap[n];
			res = res.replace(/⍌([0-9]+)⍍/g, function (x, n) {
				var res = linkmap[n];
				res = res.replace(/⍌([0-9]+)⍍/g, function (x, n) {
					return linkmap[n];
				});
				return res;
			});
			return res;
		});
		return res;
	});
}

function ohc_MOSNUM_edit_summary() 
{
	//Add a tag to the summary box
	setoptions(minor = 'true');
	setreason('date formats per [[MOS:DATEFORMAT]] by [[WP:MOSNUMscript|script]]', 'append');
	doaction('diff');
}

function ohc_bigendien_edit_summary() 
{
	//Add a tag to the summary box
	setoptions(minor = 'true');
	setreason('ymd ref dates', 'append');
	doaction('diff');
}

function ohc_expand_edit_summary() 
{
	//Add a tag to the summary box
	setoptions(minor = 'true');
	setreason('expand month names', 'append');
	doaction('diff');
}

function ohc_slash_edit_summary() 
{
	//Add a tag to the summary box
	setoptions(minor = 'true');
	setreason('resolved slash dates', 'append');
	doaction('diff');
}

function ohc_abbrev_edit_summary() 
{
	//Add a tag to the summary box
	setoptions(minor = 'true');
	setreason('abbrev month names', 'append');
	doaction('diff');
}

/** ------------------------------------------------------------------------ **/
/// CUSTOMIZATION POINTS
function ohc_customize_all_to_dmy() {
}

function ohc_customize_all_to_mdy() {
}

function ohc_customize_body_to_dmy() {
}

function ohc_customize_body_to_mdy() {
}

function ohc_customize_ISO_to_dmy() {
}

function ohc_customize_ISO_to_mdy() {
}

/** ------------------------------------------------------------------------ **/
function ohc_body_dates_to_dmy() 
{
	ohc_use_dates_template('dmy');

	ohc_fix_common_errors();
	ohc_fix_dts_template('dmy');
	ohc_fix_gr_template('dmy');
	ohc_dates_to_dmy();
	ohc_remove_leading_zeroes();
	ohc_fix_dmy_redundancies();
}

function ohc_body_dates_to_mdy() 
{
	ohc_use_dates_template('mdy');
	ohc_fix_common_errors();
	ohc_fix_dts_template('mdy');
	ohc_fix_gr_template('mdy');
	ohc_dates_to_mdy();
	ohc_remove_leading_zeroes();
	ohc_fix_mdy_redundancies();
}

/** ------------------------------------------------------------------------ **/
function ohc_all_to_dmy_driver(e) 
{
	e.preventDefault();
	ohc_delink_dates();
	ohc_protect_dates();
	ohc_fix_unambiguous_dates();
	ohc_body_dates_to_dmy();
	ohc_delink_ISO_to_dmy();
	ohc_delink_year_in_X();
	ohc_customize_all_to_dmy();
	ohc_ISO_to_dmy_in_citations();
	ohc_unprotect_dates();

	ohc_MOSNUM_edit_summary();
}

function ohc_all_to_mdy_driver(e) 
{
	e.preventDefault();
	ohc_delink_dates();
	ohc_protect_dates();
	ohc_fix_unambiguous_dates();
	ohc_body_dates_to_mdy();
	ohc_delink_ISO_to_mdy();
	ohc_delink_year_in_X();
	ohc_customize_all_to_mdy();
	ohc_ISO_to_mdy_in_citations();
	ohc_unprotect_dates();

	ohc_MOSNUM_edit_summary();
}

function ohc_dmy_publication_dates_driver(e) 
{
	e.preventDefault();
//	ohc_delink_dates();
	ohc_protect_dates();
	ohc_body_dates_to_dmy();
	ohc_customize_body_to_dmy();
	ohc_dmy_publication_dates();
	ohc_unprotect_dates();

	ohc_MOSNUM_edit_summary();
}

function ohc_mdy_publication_dates_driver(e) 
{
	e.preventDefault();
//	ohc_delink_dates();
	ohc_protect_dates();
	ohc_body_dates_to_mdy();
	ohc_customize_body_to_mdy();
	ohc_mdy_publication_dates();
	ohc_unprotect_dates();

	ohc_MOSNUM_edit_summary();

}

function ohc_body_to_dmy_driver(e) 
{
	e.preventDefault();
//	ohc_delink_dates();
	ohc_protect_dates_ref();
	ohc_body_dates_to_dmy();
	ohc_customize_body_to_dmy();
	ohc_unprotect_dates();

	ohc_MOSNUM_edit_summary();
}

function ohc_body_to_mdy_driver(e) 
{
	e.preventDefault();
//	ohc_delink_dates();
	ohc_protect_dates_ref();
	ohc_body_dates_to_mdy();
	ohc_customize_body_to_mdy();
	ohc_unprotect_dates();

	ohc_MOSNUM_edit_summary();
}

function ohc_ISO_to_dmy_driver(e) 
{
	e.preventDefault();
	ohc_protect_dates();
	ohc_delink_ISO_to_dmy();
	ohc_customize_ISO_to_dmy();
	ohc_unprotect_dates();

//	ohc_MOSNUM_edit_summary();
}

function ohc_ISO_to_mdy_driver(e) {
	e.preventDefault();
	ohc_protect_dates();
	ohc_delink_ISO_to_mdy();
	ohc_customize_ISO_to_mdy();
	ohc_unprotect_dates();

//	ohc_MOSNUM_edit_summary();
}

function ohc_delink_year_in_X_driver(e) 
{
	e.preventDefault();
	ohc_delink_year_in_X();
}

function ohc_expand_ref_dates_driver(e) {
	e.preventDefault();
	ohc_expand_ref_dates();
	ohc_protect_dates();
	ohc_unprotect_dates();
	ohc_expand_edit_summary();
}

function ohc_expand_all_dates_driver(e) 
{
	e.preventDefault();
	ohc_expand_ref_dates();
	ohc_protect_dates();
	ohc_expand_all_dates();
	ohc_unprotect_dates();
	ohc_expand_edit_summary();
}

function ohc_abbrev_ref_dates_driver(e) 
{
	e.preventDefault();
	ohc_protect_dates();
	ohc_abbrev_ref_dates();
	ohc_unprotect_dates();
	ohc_slash_edit_summary();
}

function ohc_UK_slash_dates_driver(e) 
{
	e.preventDefault();
	ohc_expand_ref_dates();
	ohc_protect_dates_slash();
		ohc_UK_slash_dates_to_dmy();
	ohc_unprotect_dates();
	ohc_slash_edit_summary();
}

function ohc_US_slash_dates_driver(e) 
{
	e.preventDefault();
	ohc_expand_ref_dates();
	ohc_protect_dates_slash();
		ohc_US_slash_dates_to_mdy();
	ohc_unprotect_dates();
	ohc_expand_edit_summary();
}

// </pre>

//সংশ্লিষ্ট পাতা ত্যাগ না করেই অন্য পাতা থেকে পুনর্নির্দেশ করা যাবে।
//<nowiki>
( function () {
	var redir = $(mw.util.addPortletLink('p-tb','#','পুনর্নির্দেশক','পুনর্নির্দেশ তৈরিকারী','পুনর্নির্দেশ তৈরিকারী','','#pt-mytalk'));
	$( redir ).click( function() {
			var redirec = prompt("যে পাতা থেকে এই পাতায় পুনর্নির্দেশ করতে চান তার নাম লিখুন:", "");
		  if (redirec === null || redirec === "") {
				alert( 'আপনি কোনও নাম প্রবেশ করান নি। দয়া করে আবার চেষ্টা করুন।' );	  
		  } else  {
			   var params = {
					action: 'edit',
					title: redirec ,
					createonly: 1,
					prependtext: '#পুনর্নির্দেশ [[' + mw.config.get("wgPageName") + ']]',
					appendtext: " \n" + '{{একটি পুনর্নির্দেশ}}',
					summary: '[[' + mw.config.get("wgPageName") + ']] পাতায় পুনর্নির্দেশ করা হল' ,
					format: 'json'
				};
				api = new mw.Api();
			api.postWithToken( 'csrf', params ).done( function ( data ) {
				alert( 'সফলভাবে ' + redirec + ' পাতা থেকে একটি পুনর্নির্দেশ তৈরি করা হয়েছে!' );
			});
		  }
			}
	);
}() );
//</nowiki>

mw.loader.using(['mediawiki.api', 'mediawiki.Title'], function () {
	"use strict";

	var config = mw.config.get(['wgNamespaceNumber', 'wgTitle', 'wgUserGroups', 'skin']);

	function removeBlanks(arr) {
		var ret = [];
		var i, len;
		for (i = 0, len = arr.length; i < len; i++) {
			var s = arr[i];
			s = s.trim();
			if (s) {
				ret.push(s);
			}
		}
		return ret;
	}

	function doMassDelete() {
		document.getElementById("wpMassDeleteSubmit").disabled = true;
		var articles = document.getElementById("wpMassDeletePages").value.split("\n");
		articles = removeBlanks(articles);
		if (!articles.length) {
			return;
		}
		var
			api = new mw.Api(),
			wpMassDeleteReasons = document.getElementById("wpMassDeleteReasons").value,
			wpMassDeleteReason = document.getElementById("wpMassDeleteReason").value,
			deleted = 0,
			failed = [],
			error = [],
			deferreds = [],
			reason = wpMassDeleteReasons == "other" ?
				wpMassDeleteReason :
				wpMassDeleteReasons + (wpMassDeleteReason ? " (" + wpMassDeleteReason + ")" : ""),
			onSuccess = function () {
				deleted++;
				document.getElementById("wpMassDeleteSubmit").value = "(" + deleted + ")";
			};

		function makeDeleteFunc(article) {
			return function () {
				return $.Deferred(function (deferred) {
					var promise = api.postWithToken('delete', {
						format: 'json',
						action: 'delete',
						title: article,
						reason: reason
					});
					promise.done(onSuccess);
					promise.fail(function (code, obj) {
						failed.push(article);
						error.push(obj.error.info);
					});
					promise.always(function () {
						deferred.resolve();
					});
				});
			};
		}

		// Make a chain of deferred objects. We chain them rather than execute them in
		// parallel so that we don't make 1000 simultaneous delete requests and bring the
		// site down. We use deferred objects rather than the promise objects returned
		// from the API request so that the chain continues even if some articles gave
		// errors.
		var deferred = makeDeleteFunc(articles[0])();
		for (var i = 1, len = articles.length; i < len; i++) {
			deferred = deferred.then(makeDeleteFunc(articles[i]));
		}

		// Show the output and do cleanup once all the requests are done.
		$.when(deferred).then(function () {
			document.getElementById("wpMassDeleteSubmit").value = "সম্পন্ন (" + deleted + ")";
			if (failed.length) {
				var $failedList = $('<ul>');
				for(var x = 0; x < failed.length; x++) {
					// Link the titles in the "failed" array
					var failedTitle = mw.Title.newFromText(failed[x]);
					var $failedItem = $('<li>');
					if (failedTitle) {
						$failedItem.append( $('<a>')
							.attr('href', failedTitle.getUrl())
							.text(failed[x])
						);
					} else {
						$failedItem.text(failed[x]);
					}
					$failedItem.append(document.createTextNode(': ' + error[x]));
					$failedList.append($failedItem);
				}
				$('#wpMassDeleteFailedContainer')
					.append($('<br />'))
					.append($('<b>')
						.text('Failed deletions:')
					)
					.append($failedList);
			}
		});
	}
	 
	function massdeleteform() {
		var bodyContent = (config.skin == "cologneblue" ? "নিবন্ধ" : "bodyContent");
		document.getElementsByTagName("h1")[0].textContent = "গন অপসারণ";
		document.getElementById(bodyContent).innerHTML =			'<form id="wpMassDelete" name="wpMassDelete">' +
			'<b>আপনি যদি এই সরঞ্জামটির অপব্যবহার করেন তবে এটি আপনার দোষ, আমার নয়।</b>' +
			'<div id="wpMassDeleteFailedContainer"></div>' +
			'<br />' +
				'পাতার তালিকা (প্রতি লাইনে একটি):<br />' +
					'<textarea tabindex="1" accesskey="," name="wpMassDeletePages" id="wpMassDeletePages" rows="10" cols="80"></textarea>' +
				'<br /><br /><table style="background-color:transparent">' +
					'<tr><td>সাধারণ কারণ:</td>' +
						'<td><select id="wpMassDeleteReasons">' +
							'<optgroup label="অন্যান্য মানদণ্ড">' +
								'<option value="অন্যান্য">অন্যান্য কারণ</option>' +
							'</optgroup>' +
							'<optgroup label="সাধারণ মানদণ্ড">' +
									'<option value="অপ্রয়োজনীয় বা ভাঙা পুনঃনির্দেশ">অপ্রয়োজনীয় বা ভাঙা পুনঃনির্দেশ</option>' +
									'<option value="G2: Test page">স২: পরীক্ষামূলক পাতা</option>' +
									'<option value="[[WP:CSD#G3|G3]]: [[WP:Vandalism|Vandalism]]">স৩: নিশ্চিত ধ্বংসপ্রবণতা ও ভয়ানক ধোঁকাবাজি</option>' +
									'<option value="[[WP:CSD#G3|G3]]: Blatant [[WP:Do not create hoaxes|hoax]]">স৩: ধোঁকাবাজি</option>' +
									'<option value="[[WP:CSD#G4|G4]]: Recreation of a page that was [[WP:DEL|deleted]] per a [[WP:XFD|deletion discussion]]">স৪: আলোচনার মাধ্যমে অপসারিত পাতা পুনরায় তৈরিকরণ</option>' +
									'<option value="[[WP:CSD#G5|G5]]: Creation by a [[WP:BLOCK|blocked]] or [[WP:BAN|banned]] user in violation of block or ban">স৫: নিষিদ্ধ বা অবরুদ্ধ ব্যবহারকারী দ্বারা সৃষ্ট পাতা</option>' +
									'<option value="স৬: গৃহস্থালি ও নিয়মমাফিক (অবিতর্কিত) পরিষ্করণ">স৬: প্রযুক্তিগত অপসারণ</option>' +
									'<option value="[[WP:CSD#G7|G7]]: One author who has requested deletion or blanked the page">স৭: লেখক বা প্রনেতা কর্তৃক অপসারণের অনুরোধ</option>' +
									'<option value="[[WP:CSD#G8|G8]]: Page dependent on a deleted or nonexistent page">স৮: অনাথ আলাপ পাতা</option>' +
									'<option value="[[WP:CSD#G10|G10]]: [[WP:ATP|Attack page]] or negative unsourced [[WP:BLP|BLP]]">স১০: আক্রমণাত্মক পাতা</option>' +
									'<option value="[[WP:CSD#G11|G11]]: Unambiguous [[WP:NOTADVERTISING|advertising]] or promotion">স১১: দ্ব্যর্থহীন বিজ্ঞাপন বা প্রচারণা</option>' +
									'<option value="[[WP:CSD#G12|G12]]: Unambiguous [[WP:CV|copyright infringement]]">স১২: কপিরাইট লঙ্ঘন</option>' +
									'<option value="[[WP:CSD#G13|G13]]: Abandoned draft or [[WP:AFC|Articles for Creation]] submission – to retrieve it, see [[WP:REFUND/G13]]">স১৩: পরিত্যক্ত খসড়া</option>' +
								'</optgroup>' +
								'<optgroup label="নিবন্ধ">' +
									'<option value="[[WP:CSD#A1|A1]]: Short article without enough context to identify the subject">নি১: কোন প্রসঙ্গ নেই</option>' +
									'<option value="[[WP:CSD#A2|A2]]: Article in a foreign language that exists on another project">নি২: অন্য কোন উইকিমিডিয়া প্রকল্পে বিদ্যমান বিদেশি ভাষার নিবন্ধ</option>' +
									'<option value="[[WP:CSD#A3|A3]]: Article that has no meaningful, substantive content">নি৩: বিষয়বস্তু বিহীন নিবন্ধ</option>' +
									'<option value="[[WP:CSD#A5|A5]]: Article that has been transwikied to another project">নি৫: অন্য কোনো উইকি প্রকল্পে বিদ্যমান নিবন্ধ</option>' +
									'<option value="[[WP:CSD#A7|A7]]: No credible indication of importance (individuals, animals, organizations, web content, events)">নি৭: গুরুত্বের ব্যাখ্যা নেই (ব্যক্তি, প্রাণি, সংস্থা, ওয়েব বিষয়বস্তু বা ঘটনা)</option>' +
									'<option value="[[WP:CSD#A9|A9]]: Music recording by redlinked artist and no indication of importance or significance">নি৯: গুরুত্বের ব্যাখ্যা নেই (সঙ্গীত রেকর্ড)</option>' +
									'<option value="[[WP:CSD#A10|A10]]: Recently created article that duplicates an existing topic">নি১০: সাম্প্রতিক তৈরি নিবন্ধ যা বিদ্যমান কোন বিষয়ের অনুলিপি</option>' +
									'<option value="[[WP:CSD#A11|A11]]: [[Wikipedia:Wikipedia is not for things made up one day|Made up]] by article creator or an associate, and no indication of importance/significance">নি১১: স্পষ্টত আবিষ্কৃত বা উদ্ভাবিত</option>' +
								'</optgroup>' +
								'<optgroup label="পুনঃনির্দেশ">' +
									'<option value="[[WP:CSD#R2|R2]]: Cross-[[WP:NS|namespace]] [[WP:R|redirect]] from mainspace">প২: আন্তঃ-নামস্থান পুনর্নির্দেশনা</option>' +
									'<option value="[[WP:CSD#R3|R3]]: Recently created, implausible [[WP:R|redirect]]">প৩: অসঙ্গত পুনঃনির্দেশ</option>' +
								'</optgroup>' +
								'<optgroup label="ছবি এবং অন্যান্য মিডিয়া">' +
									'<option value="[[WP:CSD#F1|F1]]: File redundant to another on Wikipedia">চ১: অপ্রয়োজনীয়</option>' +
									'<option value="[[WP:CSD#F2|F2]]: Corrupt or empty file, or a file description page for a file on Commons">চ২: ত্রুটিপূর্ণ, অনুপস্থিত অথবা শুন্য ফাইল</option>' +
									'<option value="[[WP:CSD#F3|F3]]: File with improper license">চ৩: অসম্পূর্ণ লাইসেন্স</option>' +
									'<option value="[[WP:CSD#F4|F4]]: Lack of licensing information">চ৪: লাইসেন্স তথ্যের অপ্রতুলতা</option>' +
									'<option value="[[WP:CSD#F5|F5]]: Unused non-free media">চ৫: অনাথ মুক্ত-নয় চিত্রসমূহের ব্যবহার</option>' +
									'<option value="[[WP:CSD#F6|F6]]: Non-free file without [[WP:RAT|fair-use rationale]]">চ৬: মুক্ত-নয় উপাদান ব্যবহারের যৌক্তিকতার অভাব</option>' +
									'<option value="[[WP:CSD#F7|F7]]: [[WP:NFCC|Invalid]] fair-use claim">চ৭: অকার্যকর ন্যায্য ব্যবহারের দাবী</option>' +
									'<option value="[[WP:CSD#F8|F8]]: Media file available on Commons">চ৮: উইকিমিডিয়া কমন্স এ অভিন্ন চিত্রের প্রাপ্যতা</option>' +
									'<option value="[[WP:CSD#F9|F9]]: File [[WP:COPYVIO|copyright violation]]">চ৯: সুস্পষ্টভাবে কপিরাইট লঙ্ঘন</option>' +
									'<option value="[[WP:CSD#F10|F10]]: Useless media file">চ১০: অপ্রয়োজনীয় নন-মিডিয়া ফাইলসমুহ</option>' +
									'<option value="[[WP:CSD#F11|F11]]: No evidence of permission">চ১১: অনুমোদনের প্রমাণ অনুপস্থিত</option>' +
								'</optgroup>' +
								'<optgroup label="বিষয়শ্রেণী">' +
									'<option value="[[WP:CSD#C1|C1]]: Empty category">বি১: খালি বিষয়শ্রেণী</option>' +
									'<option value="[[WP:CSD#C2|C2]]: Speedy renaming">বি২: দ্রুত পুনঃনামকরণ</option>' +
									'<option value="[[WP:CSD#G8|G8]]: Populated by deleted or retargeted template">স৮: অস্তিত্বহীন বা অপসারণকৃত পাতার উপর নির্ভরশীল পাতা</option>' +
								'</optgroup>' +
								'<optgroup label="ব্যবহারকারী">' +
									'<option value="[[WP:CSD#U1|U1]]: User request to delete page in own userspace">ব্য১: ব্যবহারকারীর অনুরোধ</option>' +
									'<option value="[[WP:CSD#U2|U2]]: Userpage or subpage of a nonexistent user">ব্য২: অস্তিত্বহীন ব্যবহারকারী</option>' +
									'<option value="[[WP:CSD#U3|U3]]: [[WP:NFC|Non-free]] [[Help:Gallery|gallery]]">ব্য৩: মুক্ত নয় ছবির গ্যালারি</option>' +
									'<option value="[[WP:CSD#U5|U5]]: [[WP:NOTWEBHOST|Misuse of Wikipedia as a web host]]">ব্য৫: ওয়েব হোস্ট হিসাবে উইকিপিডিয়ার ভয়ানক অপব্যবহার</option>' +
								'</optgroup>' +
								'<optgroup label="টেমপ্লেট">' +
									'<option value="[[WP:CSD#T2|T2]]: Template that unambiguously misrepresents established policy">ট২: স্পষ্ট ভুল উপস্থাপনা</option>' +
									'<option value="T3: Unused, redundant template">ট৩: অপ্রয়োজনীয় এবং অব্যবহৃত</option>' +
									'<option value="[[WP:CSD#G8|G8]]: Component or documentation of a deleted template">স৮: অস্তিত্বহীন টেমপ্লেট</option>' +
								'</optgroup>' +
								'<optgroup label="প্রবেশদ্বার">' +
									'<option value="[[WP:CSD#P1|P1]]: [[WP:P|Portal]] page that would be subject to speedy deletion as an article">প১: কোন পোর্টাল যা একটি নিবন্ধ হিসাবে দ্রুত অপসারণের যোগ্য</option>' +
									'<option value="P2: Portal without a substantial topic base">প২: অসম্পূর্ণ পোর্টাল.</option>' +
								'</optgroup>' +
								'<optgroup label="অন্যান্য">' +
									'<option value="PROD: Nominated for seven days with no objection">কোন আপত্তি ছাড়াই সাত দিনেরও বেশি সময় মনোনীত</option>' +
									'<option value="BLP: Nominated for seven days with no reliable sources present in the article">উৎস ছাড়া সাত দিনেরও বেশি সময় ধরে পরে থাকা নিবন্ধ</option>' +
									'<option value="Listed at Copyright problems for over seven days">সাত দিনেরও বেশি সময় ধরে কপিরাইট সমস্যায় তালিকাভুক্ত</option>' +
								'</optgroup>' +
							'</optgroup>' +
						'</select></td></tr>' +
				'<tr><td>অন্যান্য/অতিরিক্ত কারণ:</td>' +
					'<td><input type="text" id="wpMassDeleteReason" name="wpMassDeleteReason" maxlength="255" /></td></tr>' +
					'<tr><td><input type="button" id="wpMassDeleteSubmit" name="wpMassDeleteSubmit" value="অপসারণ" /></td>' +
			'</form>';
		document.getElementById("wpMassDeleteReasons").onchange = function() {
			var maxlength = (document.getElementById("wpMassDeleteReasons").value == "অন্যান্য" ? 255 : 252-document.getElementById("wpMassDeleteReasons").value.length); //It's 252 because of the three characters (" ()") in addition to the selected summary.
			document.getElementById("wpMassDeleteReason").setAttribute("maxlength", maxlength);
		};
		document.getElementById("wpMassDeleteSubmit").addEventListener("click", function (e) {
			doMassDelete();
		});
	}
		if ( mw.config.get('wgCanonicalSpecialPageName') === 'Blankpage' && mw.config.get('wgTitle').split('/', 2)[1] === 'Massdelete' ) {
			massdeleteform();
	}
});

	$.when(mw.loader.using('mediawiki.util'), $.ready).then(function () {
	    mw.util.addPortletLink(
	    'p-tb',
	    mw.util.getUrl('Special:BlankPage/Massdelete'),
	    'গন-অপসারণ'
	    );
	});
//<nowiki>
( function () {
	var talkp = $(mw.util.addPortletLink('p-tb','#','স্বাগত জানান','স্বাগত জানান','স্বাগত জানান','','#pt-mytalk'));
	$( talkp ).click( function() {
			var talk = prompt("কোন ধরনের স্বাগত বার্তা যুক্ত করতে চান এমন টেমপ্লেটটি লিখুন {{Subst:}} সাথে, অন্যথায় পূর্বনির্ধারিত {{Subst:স্বাগতম}} যুক্ত হবে:", "");
		  if (talk === null || talk === "") {
		    var params1 = {
					action: 'edit',
					title: 'User talk:' + mw.config.get("wgRelevantUserName"),
					prependtext: '{{Subst:স্বাগতম}}'
					,
					summary: 'ভারতপিডিয়ায় স্বাগতম!',
					format: 'json'
				};
				api = new mw.Api();
			
			api.postWithToken( 'csrf', params1 ).done( function ( data ) {
				alert( 'সফলভাবে স্বাগত জানানো হয়েছে!' );
			} );
		  
		  } else {
			   var params = {
					action: 'edit',
					title: 'User talk:' + mw.config.get("wgRelevantUserName"),
					prependtext: talk
					,
					summary: 'ভারতপিডিয়ায় স্বাগত!',
					format: 'json'
				};
				api = new mw.Api();
			
			api.postWithToken( 'csrf', params ).done( function ( data ) {
				alert( 'সফলভাবে স্বাগত জানানো হয়েছে!' );
			} );
		  }
			}
	);
}() );
//</nowiki>
//<nowiki>
console.time('mobileUndo');
$.when(mw.loader.using(['mediawiki.util', 'mediawiki.api', 'oojs-ui-windows', 'oojs-ui-core', 'oojs-ui.styles.icons-editing-core'])).then(function() {
    return new mw.Api().getMessages(['editundo', 'Undo-nochange']);
}).then(function(globalmessages) {
    var mobileUndo, i18n_lang = mw.config.get('wgUserLanguage');
    var i18n = {
        "en": {
            "mu-success": "Successful",
            "mu-fail": "Failed",
            "mu-loading": "Loading...",
            "editsummary-ad": "",
            "mu-undo-successful": "Revert successful.... Reloading in a sec",
            "mu-empty-reponse-from-server": "An empty response was received from the server",
            "mu-edit-summary-prompt": "Add a reason to your edit summary !",
            "mu-edit-summary-prompt-placeholder": "Reason...",
            "mu-thank-success": "Thanked",
            "mu-thank-confirm": "Send public thanks ?",
            "mu-thank-loading": "Thanking...",
            "mu-thank-successful": "You thanked $1.",
            "mu-thank-failed": "Failed to thank $1.",
            "mu-http-error":"HTTP error: "
        },
        "bn": {
            "mu-success": "সফল",
            "mu-fail": "ব্যর্থ হয়েছে",
            "mu-loading": "লোড করা হচ্ছে...",
            "editsummary-ad": "",
            "mu-undo-successful": "পূর্বাবস্থায় ফেরত যাওয়া সফল হয়েছে.... পুনঃলোড করা হচ্ছে",
            "mu-empty-reponse-from-server": "সার্ভার থেকে একটি খালি প্রতিক্রিয়া পাওয়া গেছে।",
            "mu-edit-summary-prompt": "সম্পাদনা সারাংশে কারণ উল্লেখ করুন!",
            "mu-edit-summary-prompt-placeholder": "কারণ...",
            "mu-thank-success": "ধন্যবাদ দিয়েছেন",
            "mu-thank-confirm": "প্রকাশ্য ধন্যবাদ জানাবেন?",
            "mu-thank-loading": "ধন্যবাদ জানানো হচ্ছে...",
            "mu-thank-successful": "আপনি $1 কে ধন্যবাদ জানিয়েছেন।",
            "mu-thank-failed": "$1 কে ধন্যবাদ জানানো ব্যর্থ হয়েছে।",
            "mu-http-error":"HTTP ত্রুটি: "
        }
    };
	if(undefined === i18n[i18n_lang]){
		i18n_lang = 'en';
	}
    if (mw.config.get('wgCanonicalSpecialPageName') === 'MobileDiff') {
        mw.util.addCSS('#mw-mf-userinfo .mobileUndo-ui .mw-ui-icon.mw-ui-icon-before:before{display:none;}\n#mobileUndo > a > span.oo-ui-iconElement-icon.oo-ui-icon-editUndo.oo-ui-image-invert{display:inline-block; position:initial;}\n#mobileUndo > a{padding:0.57142857em 0.9375em;}'+
        '#mw-mf-userinfo > div > div.mobileUndo-ui > a > div{line-height:normal;}');
        if (mw.config.get('wgVisualEditor').pageLanguageDir === 'ltr') {
            $('#mw-mf-userinfo .post-content').append($('<div>').attr('class', 'mobileUndo-ui').css({
                'display': 'inline-block',
                'float': 'right'
            }));
        } else {
            $('#mw-mf-userinfo .post-content').append($('<div>').attr('class', 'mobileUndo-ui').css({
                'display': 'inline-block',
                'float': 'left'
            }));
        }
        $('.mobileUndo-ui').append($('.mw-mf-action-button').remove().css({
            'clear': 'none'
        }));
        if (!$('.warningbox').length && mw.config.get('wgRelevantPageIsProbablyEditable')) {
            mobileUndo = new OO.ui.ButtonWidget({
                label: (globalmessages.editundo).charAt(0).toUpperCase() + (globalmessages.editundo).slice(1),
                icon: 'editUndo',
                title: 'mobileUndo',
                flags: ['destructive', 'primary'],
                id: 'mobileUndo'
            });
            $('.mobileUndo-ui').append(mobileUndo.$element);
            if (mw.config.get('wgVisualEditor').pageLanguageDir === 'ltr') {
                $('#mobileUndo').css('margin-right', '0.3em');
            } else {
                $('#mobileUndo').css('margin-left', '0.3em');
            }
        }
        window.wgRelevantUser = function() {
            var user;
            if ($('.mw-mf-user-link').text() !== '') {
                user = $('.mw-mf-user-link').text();
            } else {
                user = $('#mw-mf-userinfo .post-content div:nth-child(2)').text();
            }
            return user;
        };
        window.wgRevId = ($('#mw-mf-diffarea > div.mw-mf-diff-info > h3 > a').attr('href')).split('&oldid=')[1];
        var revId = wgRevId;
        console.log(revId);
        var username = wgRelevantUser();
        $('#mw-mf-userinfo .post-content .mobileUndo-ui .mw-mf-action-button').click(function(e) {
            e.preventDefault();
            OO.ui.confirm(i18n[i18n_lang]['mu-thank-confirm']).done(function(confirmed) {
                if (confirmed) {
                    $('.mw-mf-action-button').css('pointer-events', 'none').text(i18n[i18n_lang]['mu-thank-loading']);
                    var api = new mw.Api();
                    api.postWithToken('csrf', {
                        action: "thank",
                        rev: revId,
                    }).done(function(result) {
                        mw.notify((i18n[i18n_lang]['mu-thank-successful']).replace(/\$1/g, username));
                        $('.mw-mf-action-button').text(i18n[i18n_lang]['mu-thank-success']);
                    }).fail(function() {
                        mw.notify((i18n[i18n_lang]['mu-thank-failed']).replace(/\$1/g, username));
                        $('.mw-mf-action-button').text(i18n[i18n_lang]['mu-failed']);
                    });
                }
            });
        });
        console.timeEnd('mobileUndo');
        mobileUndo.on('click', function() {
            OO.ui.prompt(i18n[i18n_lang]['mu-edit-summary-prompt'], {
                textInput: {
                    placeholder: i18n[i18n_lang]['mu-edit-summary-prompt-placeholder'] 
                }
            }).done(function(customEditSummary) {
                $.when(mw.loader.using('mediawiki.api')).then(function() {
                    return new mw.Api().getMessages(['undo-summary'], {
                        amlang: mw.config.get('wgServerName').split('.wik')[0]
                    });
                }).then(function(message) {
                    var editSummaryMessage = message['undo-summary'];
                    var editSummary = editSummaryMessage.replace(/\$1/g, revId);
                    editSummary = editSummary.replace(/\$2/g, username);
                    if (customEditSummary !== null) {
                        mobileUndo.setDisabled(true);
                        editSummary = editSummary + ' ' + customEditSummary + (i18n[i18n_lang]['editsummary-ad']);
                        //call the API
                        var api = new mw.Api({
                            ajax: {
                                headers: {
                                    'Api-User-Agent': 'mobileUndo/2.0.2(https://en.wikipedia.org/wiki/User:FR30799386/undo.js)'
                                }
                            }
                        });
                        //Feedback UI
                        mobileUndo.setLabel(i18n[i18n_lang]['mu-loading']);
                        api.postWithToken('csrf', {
                            action: "edit",
                            title: mw.config.get('wgRelevantPageName'),
                            summary: editSummary,
                            undo: revId,
                        }).done(function(result) {
                            if (result.edit.code === 'abusefilter-warning' || result.edit.code === 'abusefilter-disallowed') {
                                mobileUndo.setLabel(i18n[i18n_lang]['mu-fail']);
                                OO.ui.alert($('<p>').html(result.edit.warning), {
                                    title: result.edit.info
                                }).done(function() {});
                                return;
                            } else if (typeof result.edit.nochange !== 'undefined') {
                                mobileUndo.setLabel(i18n[i18n_lang]['mu-fail']);
                                OO.ui.alert($('<p>').html(globalmessages['Undo-nochange'])).done(function() {});
                                return;
                            }
                            console.log(result);
                            mobileUndo.setLabel(i18n[i18n_lang]['mu-success']);
                            mw.notify(i18n[i18n_lang]['mu-undo-successful']);
                            setTimeout(function() {
                                location.href = mw.util.getUrl('Special:MobileDiff/' + result.edit.newrevid);
                            }, 1500);
                        }).fail(function(code, jqxhr) {
                            mobileUndo.setLabel(i18n[i18n_lang]['mu-fail']);
                            var details;
                            if (code === 'http' && jqxhr.textStatus === 'error') {
                                details = i18n[i18n_lang]['mu-http-error'] + jqxhr.xhr.status;
                            } else if (code === 'http') {
                                details = i18n[i18n_lang]['mu-http-error'] + jqxhr.textStatus;
                            } else if (code === 'ok-but-empty') {
                                details = i18n[i18n_lang]['mu-empty response-from-server'];
                            } else {
                                details = jqxhr.error.info;
                            }
                            OO.ui.alert($('<p>').html(details)).done(function() {});
                        });
                    }
                });
            });
        });
    }
});
//End of code
//</nowiki>
window.wgRelevantUser = function() {
    var user;
    	if ($('.mw-mf-user-link').text() !== '') {
        	user = $('.mw-mf-user-link').text();
    	} else {
        	user = $('#mw-mf-userinfo .post-content div:nth-child(2)').text();
    	}
    return user;
    };
var href = ($('#mw-mf-diffarea > div.mw-mf-diff-info > h3 > a').attr('href')) || '';
window.wgRevId = href.split('&oldid=')[1];
if( $('#mw-mf-diffarea > ul > li.revision-history-next').length ) {
	$('#mw-mf-diffarea > div.mw-mf-diff-info > h3').append(
		$('<a>').attr('id','mobileRestore').attr('href','javascript:void(0)').append(
			$('<b>').text('(পুনরুদ্ধার)')
		)
	);
}
$('#mobileRestore').click(function(e){
	e.preventDefault();
	$('#mobileRestore b').text('(লোড হচ্ছে....)');
	$('#mobileRestore').css('pointer-events','none');
	var customEditSummary = prompt('পুনরুদ্ধারের কারণ (ঐচ্ছিক)');
	if(customEditSummary === null) {
		$('#mobileRestore b').text('(পুনরুদ্ধার)');
		$('#mobileRestore').css('pointer-events','auto');
		return;
	}
	var username =wgRelevantUser();
	var editSummary = '[[Special:Contributions/'+username+'|'+username+']] ([[User talk:'+username+'|আলাপ]])-এর করা ' +wgRevId+ 'নং সংস্করণ পুনরুদ্ধার করা হয়েছে';
	editSummary = editSummary + customEditSummary + ' (পুনরুদ্ধারায়ন)';
	$.when(mw.loader.load('mediawiki.api')).then(function(){
		var api = new mw.Api();
		api.get({
			'action':'query',
			'prop':'revisions',
			'titles':mw.config.get('wgRelevantPageName'),
			'rvprop':'ids'
		}).done(function(result){
			if(result.query.pages) {
				var StartRevId = result.query.pages[mw.config.get('wgRelevantArticleId')].revisions[0].revid;
				console.log(StartRevId);
				api.postWithToken('csrf', {
                    action: "edit",
                    title: mw.config.get('wgRelevantPageName'),
                    summary: editSummary,
                    undo:StartRevId,
					undoafter:wgRevId,
                }).done(function(result) {
                    if (typeof result.edit.nochange !== 'undefined') {
                    	$('#mobileRestore b').text('(Failed)');
						alert( 'No change occured');
                        return;
                    }
					console.log(result);
					$('#mobileRestore b').text('(সফলভাবে হয়েছে)')
                    mw.notify('সংস্করণ পুনরুদ্ধার সফল হয়েছে.... পুনঃলোড করা হচ্ছে');
					setTimeout(function() {
                      location.href = mw.util.getUrl('Special:MobileDiff/' + result.edit.newrevid);
                    }, 1500);
                }).fail(function(code, jqxhr) {
                	$('#mobileRestore b').text('(পুনরুদ্ধার কার্য বাতিল করা হয়েছে)');
                    var details;
                    if (code === 'http' && jqxhr.textStatus === 'error') {
                        details = 'HTTP error: ' + jqxhr.xhr.status;
                    } else if (code === 'http') {
                        details = 'HTTP error: ' + jqxhr.textStatus;
                    } else if (code === 'ok-but-empty') {
                        details = 'An empty response was given the server';
                    } else {
                        details = jqxhr.error.info;
                    }
                    alert( details );
                });
			} else {
				alert('Failed to retrieve page details');
			}
		});
	});
});
if(mw.config.get('wgCanonicalSpecialPageName') === 'MobileDiff') {
	mw.loader.using('mediawiki.util', function() {
		var ele_a = document.createElement('a');
		ele_a.setAttribute('href', mw.util.getUrl(mw.config.get('wgRelevantPageName'), {action: 'history'}));
		ele_a.innerHTML = '(ইতিহাস)';
		document.getElementsByTagName('h2')[0].appendChild(ele_a);
	});
}
/** Description: AUTOMATIC SIGNING: if not sure, warn.
/** Description: AUTOMATIC SIGNING: if not sure, warn.
*** aut. signing / (automatische Unterschrift) ***
* @documentation: see [[w:de:User:Perhelion/signing]]
* @revision: 16:11, 6 December 2017 (UTC)
* @authors:
*  created 23.04.2006 [[w:de:User:Olliminatore]] version 1.56 13.03.2007
*  updated 23.04.2006 [[w:en:User:Ilmari Karonen]]
*  updated 19.09.2011 – 29.12.2011 [[User:Perhelion]], FIX for non Gecko
*  updated 31.12.2011 [[w:de:User:PerfektesChaos]], some code improvements
*  updated 19.06.2014 Perhelion, fixes (code tidy up, jshint) gimmicks added
*  updated 09.09.2014 [[w:de:User:Schnark]] (code cosmetic)
*  –2016 Perhelion
* tested only on modern browsers <nowiki>
* @license released dual-licensed under the terms of the GFDL v1.2 or the GPL v2.
* required modules: 'jquery.textSelection','mediawiki.language','mediawiki.util', 'mediawiki.action.edit.preview'
* ToDo:  exlcude LivePreview with session save, use hook content 
**/
(function($,mw){'use strict';if(!mw.libs||mw.libs.threadSign)throw new Error('Initializing of threadSign stopped because it was already executed');var name='AutoSign',ns=mw.config.get('wgNamespaceNumber'),$textarea,$editform,minoredit,txtOld='',CmtE='',txtLen,lrLen,txtEndLen,txtOldEnd,reUser='',signTxt=[],txtOldL;var c=$.extend({usersignature:window.usersignature||'-- ~~\~~',sigAccessKey:'>',sigText:null},mw.config.get(['wgDBname','wgAction','wgContentLanguage','wgRelevantUserName','wgFormattedNamespaces','wgUserName','wgPageName','wgIsArticle']));var ts={version:'v1.93d',$sigBox:$(),$label:$(),onoff:$.noop,init:function(){if(ts.config instanceof Object)
c=$.extend(c,ts.config);if(mw.config.get('wgIsArticle'))return;var newSection=/section=new/.test(location.search);if(!c.sigText)
c.sigText=c.usersignature;c.sigText=' '+$.trim(c.sigText)+'\n';var regpages=null,whitelist=[],blacklist=[],p,len;$textarea=$('#wpTextbox1');if(!$textarea.length)return;minoredit=document.forms.editform.wpMinoredit;txtOld=$.trim($textarea.val());txtOldL=txtOld.length;if(!minoredit||newSection||!txtOldL)
c.dSum='';if(ns===4){if(c.regpages){regpages=c.regpages;if(!$.isArray(regpages)||typeof regpages[0]!=='string')
return alert('Config error: "'+regpages+'" must be of type string array.');}
blacklist=[/\/[Ii]ntro$/,/\/[Hh]eader$/,/\/[Aa]rchive?[ _/]/,/\/\d{4}\/\d\d\/\d\d$/];switch(c.wgDBname){case'enwiki':whitelist=[':Requests for undeletion',':Requests for adminship/',':Requests for arbitration/',':Requests for permissions',' for deletion',' for discussion',':Dispute resolution noticeboard',':Adminship survey',':Deletion review',':Cleanup',':SVG help',':Arbitration/',':Village pump',':Articles for deletion','.*noticeboard.*',':page protection','mediation)',':Bot requests',':Help desk',':Editor review',':Media copyright questions'];break;case'dewiki':whitelist=[':Löschkandidaten/','erkstatt','wünsche',':Auskunft',':Café',':Fragen von Neulingen',':Fragen zur Wikipedia',':Verbesserungsvorschläge',':Urheberrechtsfragen',':Kandidat',':Löschprüfung',':Sperrprüfung','Meinung',':Qualitätssicherung/',' Bilder',':Review',':Vandalismusmeldung','/Anfragen','Notizen',':Tellerrand',':WikiProjekt Vorlagen',':Projektdiskussion',':WikiProjekt Wappen',':Redaktion '];break;case'commonswiki':whitelist=['illage pump',':Forum',':Help desk',':Bots/',' requests/',' candidates/',':Administrators\' ',':Translators\' noticeboard',' for discussion/',':Graphic Lab'];break;}
for(p=0,len=blacklist.length;p<len;p++){if(blacklist[p].test(c.wgPageName)){whitelist='';break;}}
regpages=(regpages&&whitelist)?whitelist.concat(regpages):whitelist;if(newSection)
regpages='';if(whitelist){if($.isArray(regpages))
for(p=0,len=regpages.length;p<len;p++){if(c.wgPageName.indexOf(regpages[p].replace(/ /g,'_'))!==-1){regpages='';break;}}
if(c.wgDBname==='enwiki'){$('.hiddencats li').children('a').each(function(){if(this.text&&/Non-talk pages that are automatically signed$/.test(this.text))
regpages='';});}
if(regpages){$.when(mw.loader.load('mediawiki.util'),$.ready).then(function(){$.getJSON(mw.util.wikiScript('api'),{action:'query',prop:'pageprops',indexpageids:true,titles:c.wgPageName,cache:true,format:'json',timeout:3000}).done(function(json){if(!json||!json.query||!json.query.pages)
return console.log('could not get page info!');json=json.query.pages[json.query.pageids];if(json&&json.pageprops&&typeof json.pageprops.newsectionlink!=='undefined'){if('Perhelion'===c.wgUserName)alert('AutoSign: Page was still not registered!');c.regpages='';}}).always(function(){ts.exec();});});}else{c.regpages='';return ts.exec();}}}else{if(ns%2===1)
regpages='';c.regpages=regpages;if(regpages===''||ns===2)
return ts.exec();}},_cntOcc:function(txt){var sig=/~{3}/g,falseRe=/(\{\{subst\:unsig.*?\}\})|(<(nowiki|pre)>[\s\S]*?<\/(nowiki|pre)>)|(<!--[\s\S]*?-->)/ig,count=0,cnt2=0,cnt=0;while(sig.test(txt))
cnt++;count=txt.match(falseRe)||[];for(var i=0;i<count.length;i++){while(sig.test(count[i]))
cnt2++;}
mw.log(cnt,cnt2);return[cnt,cnt2];},setIndentation:function(e){var $textarea=$(e.target);var txt=$textarea.val();var pos=$textarea.textSelection('getCaretPosition');if(!pos)
return;var txtE=txt.slice(pos);txt=txt.slice(0,pos);var lrI=txt.lastIndexOf('\n');var line=txt.slice(lrI+1,pos);this.indent="";if(line){var lrM=line.match(/^[:*#]+ ?/);if(lrM){var lrLen=lrM[0].length;if(lrLen){$textarea.val(txt+'\n'+lrM[0]+txtE);this.indent=[pos,lrLen];lrLen++;$textarea.textSelection('setSelection',{start:pos+lrLen});e.preventDefault();}}}
return;},rmvIndentation:function(e){var $textarea=$(e.target);var txt=$textarea.val();var pos=this.indent[0];if(pos){pos++;var txtE=txt.slice(pos+this.indent[1]);txt=txt.slice(0,pos);this.indent="";$textarea.val(txt+txtE);$textarea.textSelection('setSelection',{start:pos});return e.preventDefault();}},stripeCmt:function(txt){var cmtRe=/(<!--[\s\S]*?-->)(?!\n*<!--)/g;var cmtRight='';CmtE='';while(cmtRe.test(txt)){CmtE='\n'+RegExp.lastMatch;}
if(CmtE){var cmtEndI=cmtRe.lastIndex;if(cmtEndI<txt.length&&cmtEndI>txtLen){cmtRight=txt.slice(cmtEndI);}
txt=$.trim(txt.slice(0,cmtEndI-CmtE.length));CmtE+=cmtRight;}
return txt;},rmvIndent:function(txt,cmtE,pos){var lrLi=0;if(lrLen){if(cmtE){txt=ts.stripeCmt(txt);cmtE=CmtE;}
lrLi=txt.lastIndexOf('\n');txt=txt.slice(0,lrLi)+txt.slice(lrLi).replace(new RegExp('\\n[:*# ]+ *'+$.trim(reUser)+' *$'),'')+cmtE;reUser='';lrLen='';}
$textarea.val(txt);if(pos)
$textarea.textSelection('setSelection',{start:pos}).textSelection('scrollToCaretPosition').focus();return txt;},getUser:function(){var txt=txtOld;var strRe=new RegExp('\\[\\[(?:'+c.wgFormattedNamespaces[2]+'(?:in)?|'+c.wgFormattedNamespaces[3]+'|User(?:[ _]talk)?): ?([^\\]\\|[]+)(?:\\|([^\\]\[]+))?\\]\\]','ig');var topicPosters=txt.match(strRe)||[];var posterList=[];topicPosters=$.grep(topicPosters.reverse(),function(p,i){return $.inArray(p,topicPosters)===i;});var u=topicPosters.length,reUser,userDict={};while(u--)
while(strRe.test(topicPosters[u])){reUser=RegExp.$1;if(!mw.util.isIPAddress(reUser,false))
posterList.push([RegExp.lastMatch,reUser,RegExp.$2]);}
posterList=$.grep(posterList,function(p,i){return $.inArray(p,posterList)===i;});u=posterList.length;var d=0;while(u--){reUser=posterList[u];var userMatch=reUser.shift();if(reUser[1]){if(new RegExp(c.wgFormattedNamespaces[3]+'|User[ _]talk','i').test(userMatch))
reUser.pop();else{reUser[1]=$.trim(reUser[1]);if(reUser[1].indexOf(' ')>3)
reUser.pop();}}
var user=reUser[0]||'';user=$.trim(user.replace(strRe,'$1'));if(user){if(user.indexOf('/')!==-1)
user=user.split('/')[0];else if(user.indexOf('#')!==-1){user=user.split('#')[0];}
if(reUser[0]!==user){reUser=[user];}else if(reUser[1]&&reUser[1]===user)
reUser.pop();if(user===c.wgUserName||userDict[user]&&(!reUser[1]||userDict[user][1])){posterList.splice(u,1);d++;}else if(userDict[user]){posterList.splice(userDict[user][0]-d,1);d++;posterList[userDict[user][0]-d]=reUser;}else{userDict[user]=[u,reUser[0]];posterList[u]=reUser;}}}
return posterList.reverse();},createDropDown:function(e){e.stopPropagation();e.preventDefault();var tar=e.target,userName,userNick;var selOkTxt='--- OK ---';var posterList=this.getUser();posterList=$.grep(posterList,function(p){return(p&&p[0]!==c.wgRelevantUserName);});var u=posterList.length;var posterLen=u;while(u--){var reUser=posterList[u];userName=reUser[0];userNick=(reUser[1])?reUser[1]:'';userNick=(userNick||userName).replace(/\w\-+\w/g,' ').replace(/(\w)[\d-\.]+|[\d-\.]+(\w)/g,'$1$2');posterList[u]=$('<option>',{value:userName,text:userNick});}
var getSelectedOptions=function getSelectedOptions(tar,event){var sel=this||document.getElementById('mention-select'),opts=sel.options,oLen=opts.length-1,bOk;ts.userNames='';userName=[];if(oLen>0){var ind=opts[opts.selectedIndex];if(ind&&ind.value!==selOkTxt){if(tar.title==='Ping'&&event.ctrlKey){bOk=opts[oLen].selected;for(var i=0;i<oLen;i++){var opt=opts[i];if(opt.selected)
userName.push(opt.value);}}else{var $sel=$(sel).hide();userName=[ind.value,ind.text];if(tar.title==='Ping'){userName.pop();ind.value=opts[oLen].value;ind.selected=false;}
window.setTimeout(function(){$sel.show();},200);}
if(!event.ctrlKey||bOk)
return tar.onclick(userName);ts.userNames=userName;}
else return tar.onclick('');}};if(posterLen<2){userName=[userName];if(tar.title!=='Ping')
userName.push(userNick);return tar.onclick(userName);}
var $sel=$('<select>',{id:'mention-select',multiple:1}).on('click',function(e){getSelectedOptions(tar,e);}).append(posterList).on("blur",function(e){if(!e.ctrlKey)
$(this).parent().remove();});if(tar.title==='Ping')
$sel.append($('<option>',{style:'text-align:center',text:selOkTxt}));$sel.attr("size",Math.min(6,posterLen));$sel=$('<div>').css({position:"absolute",top:tar.offsetTop-22,left:tar.offsetLeft+24,zIndex:77}).append($sel);$(tar).parent().append($sel);$sel.children().first().focus().find("option:first").prop("selected",1);},setPing:function(e){if(e.target&&!($textarea.textSelection('getSelection')||ts.userNames))
return this.createDropDown(e);else if(ts.userNames&&e.target){e=ts.userNames;ts.userNames='';}
e=(e&&e[0])?e.join('|'):'';return $textarea.textSelection('encapsulateSelection',{pre:'{{Ping|',peri:e,post:'}}'});},mentionUser:function(e){var isSel=$textarea.textSelection('getSelection');if(e.target&&!(isSel||e.ctrlKey))
return this.createDropDown(e);return $textarea.textSelection('encapsulateSelection',{pre:'[['+c.wgFormattedNamespaces[2]+':',peri:(e[0]||'')+'|'+(e[1]||''),post:isSel?'|]]':']]'});},enable:function(){if(this.enabled)
return;this.toggleSigBox();this.enabled=true;this.onoff(1);},disable:function(){if(!this.enabled)
return;this.toggleSigBox();this.enabled=0;this.onoff(0);},exec:function(){$editform=$('#editform');var r='\n',sum=document.forms.editform.wpSummary,n=/\n/,bSig=!(c.regpages!==''||ns===2);if(window.wikEd)
return alert(name,'is not compatible with wikEd');if(bSig)
ts.useLivePreview();$textarea.on('keypress',function(e){if(e.which===13)
return ts.setIndentation(e);if(e.which===8&&ts.indent)
return ts.rmvIndentation(e);ts.indent="";});if(mw.language&&$.inArray('de',mw.language.getFallbackLanguageChain())!==-1)
signTxt={boxTitle:'Signiere automatisch. ',boxText:'Signieren',btnAlt:'Manuelle Signatur',confirm:'Es wurde keine Signierung gefunden. Trotzdem fortfahren?'};else
signTxt={boxTitle:'Sign this edit automatic. ',boxText:'AutoSign',btnAlt:'Manual signing',confirm:'No signing was found. Continue anyway?'};signTxt.hi=($.inArray(c.wgContentLanguage,['de','nn','da'])!==-1)?'Hallo ':'Hey ';if(!$editform.length)
return;ts.setOutdent=function(){var txt=$textarea.val();var outdent=(c.wgDBname==='enwiki')?'\n{{od}}':'\n:┌{{padleft:┘|22|─}}\n';var pos=$textarea.textSelection('getCaretPosition');if(pos<0)
pos=txt.length;if(n.test(txt[pos])&&!n.test(txt[pos-1]))
pos++;if(txt[pos+1]&&n.test(txt[pos+1]))
pos++;ts.rmvIndent($.trim(txt.slice(0,pos))+outdent+txt.slice(pos),CmtE);};this.doSig=function(e,pos){var txt=$textarea.val();var sigText=c.sigText;if(!pos){pos=$textarea.textSelection('getCaretPosition');}else{if(pos<0)
pos=txt.length;var tmpRe=/\}\}\s*$/;if(tmpRe.test(txt.slice(pos-4,pos))){var lrIndex=txt.slice(0,pos).replace(/\s+$/,'').lastIndexOf(r);var tmpTxt=txt.slice(lrIndex,pos);if(/\|1\s*=[^\n]*(\}\})\s*$/.test(tmpTxt)){tmpRe=tmpTxt.search(tmpRe);pos=lrIndex+tmpRe;sigText=sigText.replace(/\n+$/,'');}}}
if(txt[pos]&&n.test(txt[pos])&&!n.test(txt[pos-1]))
pos++;if(txt[pos+1]&&n.test(txt[pos+1]))
pos++;this.rmvIndent(txt.slice(0,pos).replace(/\s+$/,'')+sigText+txt.slice(pos),CmtE,pos);if(c.dSum){if(!/^(?:(\/\*.+?\*\/ *))([^ ])|^([^/]+?)(?!\/\*.+?\*\/ *)/.test(sum.value)){sum.value+=c.dSum;}
c.dSum='';}
return e;};var oBox={'type':'checkbox','name':'wpAutoSign','id':'wpAutoSign','checked':bSig,'accessKey':c.sigAccessKey,selected:bSig};var oLabel={'for':'wpAutoSign',title:signTxt.boxTitle+ts.version,align:'inline',label:signTxt.boxText};var cURL='https://upload.wikimedia.org/wikipedia/commons/thumb/';var $sBtn=$('<img>',{src:cURL+'5/52/Tango_style_insert-signature_icon.svg/22px-Tango_style_insert-signature_icon.svg.png','title':'AutoSign','rel':'AutoSign','alt':signTxt.btnAlt,'width':'22','onclick':'mw.libs.threadSign.doSig(event)','height':'22','style':'cursor:pointer','class':'tool'});var $pBtn=$sBtn.clone().attr({src:cURL+'f/fa/Tango_style_ping_icon.svg/22px-Tango_style_ping_icon.svg.png',title:'Ping',alt:'',rel:'Ping',onclick:'mw.libs.threadSign.setPing(event)'});var $mBtn=$sBtn.clone().attr({src:cURL+'6/6b/Flow-mention.svg/22px-Flow-mention.svg.png',title:'Mention',alt:'',rel:'Mention',onclick:'mw.libs.threadSign.mentionUser(event)'}).css({opacity:'.6'});var $oBtn=$sBtn.clone().attr({src:cURL+'b/bb/Tango_style_outdent_icon.svg/22px-Tango_style_outdent_icon.svg.png',title:'Outdent',alt:'',rel:'Outdent',onclick:'mw.libs.threadSign.setOutdent()'});var threadSignBtns=[$sBtn,$oBtn,$pBtn,$mBtn];var txt=txtOld;if(!txt){if(ns===3&&!minoredit&&c.wgRelevantUserName!==c.wgUserName){txt=signTxt.hi+c.wgRelevantUserName+',\n';$textarea.val(txt).textSelection('setSelection',{start:txt.length-1}).focus();}}else if(/-->$/.test(txt))
txt=ts.stripeCmt(txt);txtLen=txt.length;var lrI=txt.lastIndexOf(r)+1,lrR=txt.slice(lrI),lrM=lrR.match(/^[:*#]+/);lrLen=(lrM)?lrM[0].length:0;txtEndLen=(Math.min(18,lrR.length)+lrLen)* -1;txtOldEnd=txtOld.slice(txtEndLen);if(c.wgAction==='edit'){if(lrLen&&lrI+lrLen+1<txtLen){lrI=':';lrLen++;if(lrLen===2&&lrM[0]!==':'){lrI='';lrLen=1;}
$textarea.val(txt+r+lrM[0]+lrI+' '+CmtE);txtLen+=lrLen+2;}else if(!lrLen&&c.autoSalut&&txtOldEnd&&/\d{4} \((?:CES?T|UTC)\)[^\d]*?$/.test(lrR)){lrLen++;reUser=this.getUser().pop()||"";lrI='';if(reUser){lrI=': ';reUser=(reUser[1]&&/\w+/.test(reUser[1]))?reUser[1]:reUser[0];if(reUser)
reUser=signTxt.hi+reUser.replace(/\d+$/g,'')+', ';lrLen+=reUser.length;}
txtLen+=lrLen+lrI.length;$textarea.val(txt+r+lrI+reUser+CmtE);}else{lrLen=0;if(txt){txtLen++;$textarea.val(txt+r+CmtE);}}}
if(bSig&&txt)
$(window).on('load',function(){$textarea.textSelection('setSelection',{start:txtLen}).textSelection('scrollToCaretPosition').focus();});if(minoredit){this.offSigBox(minoredit);$(minoredit).on('change',this.offSigBox);}
$('#wpSave, #wpPreview, #wpDiff, #wpMinoredit').on("click",{name:name},ts.doSign);var makeCheckbox=function($label){return $label.css({'padding':'2px 6px','border-color':(!bSig?'#C00;color:#A00':'')}).addClass((bSig?'usermessage':'')).after(threadSignBtns);};var makeCheckboxOOUI=function(){mw.loader.using('oojs-ui-core').done(function(){var checkbox=new OO.ui.CheckboxInputWidget(oBox);var field=new OO.ui.FieldLayout(checkbox,oLabel);ts.onoff=function(on){checkbox.setSelected(on);};ts.$sigBox=checkbox.$element.find('input').updateTooltipAccessKeys();ts.$label=makeCheckbox(field.$element.find('label'));ts.$sigBox.on('change',ts.toggleSigBox);checkbox.on('change',function(){if(checkbox.isSelected())
ts.enable();else
ts.disable();});$('.editCheckboxes > .oo-ui-layout').append(field.$element);});};var makeCheckboxCommon=function(){oLabel.text=oLabel.label;var $label=$('<label>',oLabel),$checkbox=$('<span>').addClass('oo-ui-fieldLayout-body');ts.$sigBox=$('<input>',oBox).on('change',ts.toggleSigBox).updateTooltipAccessKeys();ts.$sigBox.on('change',ts.toggleSigBox);$checkbox.append(ts.$sigBox,$label);ts.$label=makeCheckbox($label);$('.editCheckboxes').append($checkbox);};if(!ts.$sigBox.length){if($('#wpSummaryLabel').hasClass('oo-ui-layout'))
makeCheckboxOOUI();else
makeCheckboxCommon();}},useLivePreview:function(){if(((minoredit&&!minoredit.checked)||ts.$sigBox.prop('checked'))&&mw.user.options.get('uselivepreview')!=1){mw.user.options.set('uselivepreview',1);mw.loader.load('mediawiki.action.edit.preview');}},toggleSigBox:function(){ts.useLivePreview();ts.$label.toggleClass('usermessage');},offSigBox:function(e){if(e.type&&e.type==='change')
e=e.target;if(!ts.$sigBox.prop('checked'))
return;ts.$sigBox.prop('disabled',e.checked);},doSign:function(e){function _chkEdit(c,pos){pos=txt.indexOf(c,pos--);if(pos>1){var txtEnd=txt.substr(pos,24).replace(/(^\s+)/,'');var txtNewEnd=txt.slice(pos-16,pos);var oldp=(c==='\n')?txtOld.lastIndexOf(txtEnd):0;if(!oldp&&/-->$/.test(txtEnd)){c=txt.lastIndexOf('<!--');if(c<pos)
pos=c--;}
if(oldp!==-1&&oldp<pos-3&&txtOld.indexOf(txtNewEnd+RegExp.$1+txtEnd)===-1){return pos;}}}
var tolerance=4;var txt=$.trim($textarea.val());if((minoredit&&minoredit.checked)||!ts.$sigBox.prop('checked'))
return ts.rmvIndent(txt,CmtE);if(!txt)
return;var cOld=ts._cntOcc(txtOld),cNew=ts._cntOcc(txt),oldp,txtEnd,pos;if(cNew[0]-cNew[1])
return ts.rmvIndent(txt,CmtE);if(cNew[0]<=cOld[1]){if(!CmtE){mw.log("lrLen,txtEndLen",lrLen,txtEndLen);txtEnd=[txt.substr(txtEndLen-(lrLen?lrLen+1:0),-txtEndLen),txt.slice(txtEndLen)];oldp=txtOldL+txtEndLen;mw.log('Is last line identical?\n"%s"\n"%s"',txtOldEnd,txtEnd,txtEnd[1]);if(!txtOld||$.inArray(txtOldEnd,txtEnd)<0){return ts.doSig(e,-1);}}
pos=$textarea.textSelection('getCaretPosition');pos=_chkEdit('\n',pos);if(pos){return ts.doSig(e,pos);}
txt=ts.rmvIndent(txt,CmtE);if(txt.length>(txtOldL+tolerance)){var lines=txt.match(/.+/gm)||[],linesOld=txtOld.match(/.+/gm)||[];if(lines.length>linesOld.length){lines=lines.filter(function(x){return linesOld.indexOf(x)<0;}).pop()||[];if(lines.length){pos=txt.lastIndexOf(lines);return ts.doSig(e,pos+lines.length);}}}
if(CmtE){pos=_chkEdit('<!--',txtLen);if(pos)
return ts.doSig(e,pos);}}
if(e.target.name==='wpSave'){$editform.submit(function(e){if(!confirm(signTxt.confirm)){e.preventDefault();e.stopPropagation();mw.log.warn(name,txtOld,txt);return false;}});}
return e;}};mw.libs.threadSign=ts;if(mw.config.get('wgPageContentModel')==='wikitext'){$(document).trigger('loadWikiScript',['Perhelion/signing.js',ts]);$.when(mw.loader.using(['jquery.textSelection','mediawiki.language','user.options','mediawiki.util']),$.ready).then(function(){$(ts.init);});}}
(jQuery,mediaWiki));
// EOF </nowiki>
/* If you want to use this script, simply add the following line to your monobook.js:
 
importScript('User:Anomie/ajaxpreview.js'); // Linkback: [[User:Anomie/ajaxpreview.js]]
 
* (Please keep the comment so I can see how many people use this).
*/

var AJAXPreview={
    node:null,
    txt:null,
    timer:null,
    idx:0,

    spinner:function(){
        switch(AJAXPreview.idx++){
          case 0:
            AJAXPreview.node.innerHTML='<center style="font-size:50pt">|</center>';
            break;
          case 1:
            AJAXPreview.node.innerHTML='<center style="font-size:50pt">/</center>';
            break;
          case 2:
            AJAXPreview.node.innerHTML='<center style="font-size:50pt">–</center>';
            break;
          case 3:
            AJAXPreview.node.innerHTML='<center style="font-size:50pt">\\</center>';
            AJAXPreview.idx=0;
            break;
        }
        AJAXPreview.node.style.display='block';
    },

    callback:function(r){
        if(AJAXPreview.timer) window.clearInterval(AJAXPreview.timer);
        AJAXPreview.timer=null;
        if(!r.parse || !r.parse.text || !r.parse.text['*']){
            AJAXPreview.node.innerHTML='<div style="border:1px solid #f00;background-color:#fcc;color:#f00;text-align:center">Bad response</div>';
            throw new Error('Bad response');
        }
        AJAXPreview.node.innerHTML=r.parse.text['*']+'<br />';
        AJAXPreview.node.style.display='block';

        // Set a timeout to allow the browser a chance to parse the innerHTML
        window.setTimeout(function(){
        	mw.hook( 'wikipage.content' ).fire( $( AJAXPreview.node ) );
            for(var i=AJAXPreview.$OnLoadHooks.length-1; i>=0; i--)
                AJAXPreview.$OnLoadHooks[i].call(window, AJAXPreview.node);
        }, 250);
    },

    doError:function(xhr,textStatus,errorThrown){
        if(AJAXPreview.timer) window.clearInterval(AJAXPreview.timer);
        AJAXPreview.timer=null;
        while(AJAXPreview.node.firstChild) AJAXPreview.node.removeChild(AJAXPreview.node.firstChild);
        var d=document.createElement('DIV');
        d.style.border='1px solid #f00';
        d.style.backgroundColor='#fcc';
        d.style.color='#f00';
        d.style.textAlign='center';
        d.appendChild(document.createTextNode('AJAX Error: '+textStatus+' '+errorThrown));
        AJAXPreview.node.appendChild(d);
        AJAXPreview.node.style.display='block';
        throw new Error('AJAX error: '+textStatus+' '+errorThrown);
    },

    doPreview:function(ev){
        if(!ev) ev=window.event;
        var txt=AJAXPreview.getTextContent();
        var refs=AJAXPreview.getRefs(txt);
        var need=[];
        var groups={};
        for(var g in refs){
            groups[g]='';
            for(var n in refs[g]){
                if(refs[g][n].text===null) need.push([g,n]);
            }
        }
        var doPreview2=function(wikitext,sts,xhr){
            if(wikitext){
                refs=AJAXPreview.getRefs(wikitext);
                for(var i=need.length-1; i>=0; i--){
                    var x=refs[need[i][0]][need[i][1]];
                    if(!x) continue;
                    if(x.type=='tag'){
                        groups[need[i][0]]+='\x7b\x7b#tag:ref|'+x.text+'|name='+need[i][1]+'|group='+need[i][0]+'\x7d\x7d';
                    } else {
                        groups[need[i][0]]+='\x3cref name="'+need[i][1]+'" group="'+need[i][0]+'"\x3e'+x.text+'\x3c/ref\x3e';
                    }
                }
            }
            txt+='\n\n\x7b\x7b-\x7d\x7d\n----\n';
            for(var g in groups){
                txt+='\n;'+(g?'Group '+g:'References')+'\n\x7b\x7breflist|2|group='+g+'|refs='+groups[g]+'\x7d\x7d';
            }

            jQuery.ajax({
                url:mw.util.wikiScript('api'),
                dataType:'json',
                type:'POST',
                data:{
                    format:'json',
                    action:'parse',
                    pst:1,
                    text:txt,
                    title:mw.config.get('wgPageName'),
                    prop:'text',
                    disableeditsection:1,
                    preview:1,
                    templatesandboxtitle:mw.config.get('wgPageName'),
                    templatesandboxtext:txt
                },
                success:AJAXPreview.callback,
                error:AJAXPreview.doError
            });
        };
        mw.loader.using('mediawiki.util', function(){
            if(need.length>0){
                jQuery.ajax({
                    url:mw.util.wikiScript('index'),
                    dataType:'text',
                    type:'GET',
                    data:{ action:'raw', title:mw.config.get('wgPageName') },
                    success:doPreview2,
                    error:AJAXPreview.doError
                });
            } else {
                doPreview2(null,null,null);
            }
        });

        var x=document.getElementById('wikiDiff');
        if(x) x.parentNode.removeChild(x);
        if(AJAXPreview.timer) window.clearInterval(AJAXPreview.timer);
        AJAXPreview.timer=window.setInterval(AJAXPreview.spinner, 250);

        this.blur();
        window.scrollTo(0,0);
        if(ev){ // OOUI may not have an event here
            if(ev.preventDefault) ev.preventDefault();
            if(ev.stopPropagation) ev.stopPropagation();
            ev.returnValue=false;
            ev.cancelBubble=true;
        }
        return false;
    },

    getRefs:function(txt){
        var g;

        var refs={};

        // The new "list-defined references" have to be handled specially,
        // which means we have to manage to pull them out of the wikitext. Fun.
        // First, do the XML-style tags.
        txt=txt.replace(/<references((?:\s+[^>]*[^\/>])?)(?:\/>|>((?:.|[\r\n])*?)(<\/references>|$))/ig, function(x,p,t,c){
            p=p.replace(/\s+$/g,'');
            g=p.match(/\sgroup="([^\x22]*)"/i);
            if(!g) g=p.match(/\sgroup='([^\x27]*)'/i);
            if(!g) g=p.match(/\sgroup=(\S*)/i);
            g=g?g[1]:'';
            refs=AJAXPreview.getRefs2(t,g,refs);
            return '';
        });

        // Next, to reflist and #tag:references
        txt=AJAXPreview.process_templates(txt,function(n,p,o){
            var c=null, g='';
            if(n=='Reflist'){
                for(var j=0; j<p.length; j++){
                    var m=p[j].match(/^\s*refs\s*=\s*((?:.|[\r\n])*?)\s*$/);
                    if(m) c=m[1];
                    var m=p[j].match(/^\s*group\s*=\s*([\x22\x27]?)([^\x22\x27]+?)\1\s*$/);
                    if(m) g=m[2];
                }
                if(c===null) c='';
            } else if(/^#tag:\s*references$/i.test(n)){
                c=p.length ? p.shift() : '';
                for(var j=0; j<p.length; j++){
                    var m=p[j].match(/^\s*group\s*=\s*([\x22\x27]?)([^\x22\x27]+?)\1\s*$/);
                    if(m) g=m[2];
                }
            } else {
                return null;
            }
            refs=AJAXPreview.getRefs2(c,g,refs);
            return '';
        });

        return AJAXPreview.getRefs2(txt,'',refs);
    },
    getRefs2:function(txt,defgroup,refs){
        var g,n;

        // First, pull out regular <refs>. We can do this with a regex.
        txt.replace(/<ref((?:\s+\S+=(?:"[^\x22]*"|'[^\x27]*'|\S*?))*)\s*(?:\/>|>((?:.|[\r\n])*?)<\/ref>)/ig, function(x,p,t){
            g=p.match(/\sgroup="([^\x22]*)"/i);
            if(!g) g=p.match(/\sgroup='([^\x27]*)'/i);
            if(!g) g=p.match(/\sgroup=(\S*)/i);
            g=g?g[1]:defgroup;
            if(typeof(refs[g])=='undefined') refs[g]={};
            n=p.match(/\sname="([^\x22]*)"/i);
            if(!n) n=p.match(/\sname='([^\x27]*)'/i);
            if(!n) n=p.match(/\sname=(\S*)/i);
            if(!n) return null;
            n=n[1];
            if(typeof(refs[g][n])=='undefined') refs[g][n]={text:null,type:'?'};
            if(refs[g][n].text===null && typeof(t)!='undefined' && t!=='' && t!==null){
                refs[g][n].text=t;
                refs[g][n].type='ref'
            }
            return null;
        });

        // Second, if it looks like there are #tag refs, parse them too
        AJAXPreview.process_templates(txt,function(nm,p,o){
            if(!/^#tag:\s*ref$/i.test(nm)) return null;
            g=defgroup; n=null;
            for(var j=p.length-1; j>=1; j--){
                var m=p[j].match(/^\s*group\s*=\s*([\x22\x27]?)([^\x22\x27]+?)\1\s*$/);
                if(m) g=m[2];
                var m=p[j].match(/^\s*name\s*=\s*([\x22\x27]?)([^\x22\x27]+?)\1\s*$/);
                if(m) n=m[2];
            }
            if(typeof(refs[g])=='undefined') refs[g]={};
            if(n!==null){
                if(typeof(refs[g][n])=='undefined') refs[g][n]={text:null,type:'?'};
                if(refs[g][n].text===null && p[0]!==''){
                    refs[g][n].text=p[0];
                    refs[g][n].type='tag'
                }
            }
            return null;
        });

        return refs;
    },

    process_templates:function(txt,cb,data){
        var stack=[], i=0;
        while(i<txt.length){
            var x=stack.length?stack[stack.length-1]:null;
            var xb=null;
            for(var j=0; j<stack.length; j++){
                if(stack[j].char=='\x5b') xb=stack[j];
            }
            if(txt.substr(i,2)=='\x7b\x7b'){
                var ct;
                for(ct=2; txt.substr(i+ct,1)=='\x7b'; ct++);
                stack.push({char:'\x7b',start:i,count:ct,pstart:i+ct,params:[]});
                i+=ct;
            } else if(txt.substr(i,2)=='\x5b\x5b'){
                var ct;
                for(ct=2; txt.substr(i+ct,1)=='\x5b'; ct++);
                stack.push({char:'\x5b',start:i,count:ct,pstart:i+ct,params:[]});
                i+=ct;
            } else if(x && x.char=='\x7b' && txt.substr(i,2)=='\x7d\x7d'){
                var ct;
                for(ct=2; txt.substr(i+ct,1)=='\x7d'; ct++);
                if(ct>x.count) ct=x.count;
                i+=ct;
                x.params.push(txt.substring(x.pstart,i-ct));
                // First, parse out variables
                while(ct>=3){
                    x.count-=3;
                    ct-=3;
                    var s=x.start-x.count;
                    x.params=[txt.substring(s,i-x.count)];
                }
                // Any left is templates
                while(ct>=2){
                    x.count-=2;
                    ct-=2;
                    var s=x.start+x.count;
                    var orig=txt.substring(s,i-ct);
                    var name=x.params.shift();
                    var oname=name;
                    name=name.replace(/_/g,' ');
                    name=name.replace(/^\s+|\s+$/g,'');
                    name=name.replace(/  +/g,' ');
                    name=name.replace(/^Template\s*:\s*/ig,'');
                    name=name.substr(0,1).toUpperCase()+name.substr(1);
                    var ret=cb(name, x.params, orig, data, oname);
                    if(ret===null){
                        x.params=[orig];
                    } else {
                        ret=""+ret;
                        var d=(ret=='' && (s==0 || txt.substr(s-1,1)=='\n') && txt.substr(i-ct,1)=='\n')?1:0;
                        txt=txt.substr(0,s)+ret+txt.substr(i-ct+d);
                        i=s+ret.length+ct;
                        x.params=[ret];
                    }
                }
                if(x.count<2){
                    stack.pop();
                } else {
                    // The one we just completed might not be the end of the
                    // param, so reset the param array and pstart
                    x.params=[];
                    x.pstart=x.start+x.count;
                }
            } else if(xb && txt.substr(i,2)=='\x5d\x5d'){
                // Drop any pending templates, they're not really templates
                while(stack[stack.length-1]!=xb) stack.pop();
                var ct;
                for(ct=2; txt.substr(i+ct,1)=='\x5d'; ct++);
                if(ct>xb.count) ct=xb.count;
                i+=ct;
                xb.count-=ct;
                if(xb.count<2){
                    stack.pop();
                } else {
                    // The one we just completed might not be the end of the
                    // param, so reset the param array and pstart
                    xb.params=[];
                    xb.pstart=xb.start+xb.count;
                }
            } else if(x && txt.substr(i,1)=='|'){
                x.params.push(txt.substring(x.pstart,i));
                x.pstart=++i;
            } else {
                i++;
            }
        }
        return txt;
    },
 
    onLoad:function(){
        var action=mw.config.get('wgAction');
        if(action!='edit' && action!='submit') return;

        var editForm=document.getElementById('editform');
        if(!editForm) return;
        var sectionField = editForm.elements['wpSection'];
        var isSection=(sectionField && sectionField.value!="");
        var p=editForm.elements["wpPreview"];
        if(!p) return;

        AJAXPreview.node=document.getElementById('wikiPreview');
        if(!AJAXPreview.node) return;
        AJAXPreview.txt=editForm.elements["wpTextbox1"];
        if(!AJAXPreview.txt) return;

    	mw.loader.using( [ 'oojs-ui-core' ] ).done( function () {
            var b = new OO.ui.ButtonWidget( {
	            label: 'Ajax Preview'+(isSection?' w/Refs':''),
    	        tabIndex: p.tabIndex
        	} );
        	b.on( 'click', AJAXPreview.doPreview );
        	$( p ).before( b.$element, ' ' );
    	} );
        p.value='Preview';

        // Hooks for standard functions
        if(typeof(window.createCollapseButtons) == 'function')
            AJAXPreview.AddOnLoadHook(createCollapseButtons);
        if(typeof(window.createNavigationBarToggleButton) == 'function')
            AJAXPreview.AddOnLoadHook(createNavigationBarToggleButton);
    },

    getTextContent:function(){
        return AJAXPreview.txt.value;
    },

    // Add callback functions here.
    AddOnLoadHook:function(f){
        AJAXPreview.$OnLoadHooks.push(f);
    },
    $OnLoadHooks:[]
};

$(document).ready(AJAXPreview.onLoad);
// vim: ts=4 sw=4 et
//<nowiki>
function loadReplyLink( $, mw, isOnSectionWatchlistPage ) {
    var TIMESTAMP_REGEX = /\(UTC(?:(?:−|\+)\d+?(?:\.\d+)?)?\)\S*?\s*$/m;
    var EDIT_REQ_REGEX = /^((Semi|Template|Extended-confirmed)-p|P)rotected edit request on \d\d? \w+ \d{4}/;
    var EDIT_REQ_TPL_REGEX = /\{\{edit (template|fully|extended|semi)-protected\s*(\|.+?)*\}\}/;
    var LITERAL_SIGNATURE = "~~" + "~~"; // split up because it might get processed
    var i18n = {
        "en": {
            "rl-advert": " (using [[w:en:User:Enterprisey/reply-link|reply-link]])",
            "rl-error-status": "There was an error while replying! Please leave a note at " +
                "<a href='https://en.wikipedia.org/wiki/User_talk:Enterprisey/reply-link'>the script's talk page</a>" +
                " with any errors in <a href='https://en.wikipedia.org/wiki/WP:JSERROR'>the browser console</a>, if possible.",
            "rl-replying-to": "Replying to ",
            "rl-reloading": "automatically reloading",
            "rl-reload": "Reload",
            "rl-saved": "Reply saved!",
            "rl-cancel": "cancel ",
            "rl-placeholder": "Reply here!",
            "rl-reply": "Reply",
            "rl-preview": "Preview",
            "rl-cancel-button": "Cancel",
            "rl-started-reply": "You've started a reply but haven't posted it",
            "rl-loading": "Loading...",
            "rl-reply-label": "reply",
            "rl-to-label": " to ",
            "rl-auto-indent": "Automatically indent?",
            "rl-out-of-date": "Someone has edited this page since you started replying!",
            "rl-edit-fail": "While replying, the edit failed."
        },
        "pt": {
            "rl-advert": "(usando [[w:en:User:Enterprisey/reply-link|reply-link]])",
            "rl-error-status": "Ocorreu um erro ao responder! Por favor deixe um comentário na " +
                "<a href='https://en.wikipedia.org/wiki/User_talk:Enterprisey/reply-link'>página de discussão do script</a>" +
                " informando os erros que apareçam <a href='https://en.wikipedia.org/wiki/WP:JSERROR'>no console do navegador</a>, se possível.",
            "rl-replying-to": "Respondendo a ",
            "rl-reloading": "recarregando automaticamente",
            "rl-reload": "Recarregar",
            "rl-saved": "Resposta publicada!",
            "rl-cancel": "cancelar ",
            "rl-placeholder": "Responda aqui!",
            "rl-reply": "Responder",
            "rl-preview": "Prever",
            "rl-cancel-button": "Cancelar",
            "rl-started-reply": "Você começou a responder, mas não publicou sua resposta",
            "rl-loading": "Carregando...",
            "rl-reply-label": "responder",
            "rl-to-label": " a ",
            "rl-auto-indent": "Indentar automaticamente?"
        }
    };
    var HEADER_SELECTOR = "h1,h2,h3,h4,h5,h6";
    var MAX_UNICODE_DECIMAL = 1114111;
    var HEADER_REGEX = /^\s*=(=*)\s*(.+?)\s*\1=\s*(?:<!--.+?-->\s*)?$/gm;
    var JUMP_COOKIE_KEY = "reply_link_jump";

    // T:TDYK, used at the end of loadReplyLink
    var TTDYK = "Template:Did_you_know_nominations";
    var RFA_PG = "Wikipedia:Requests_for_adminship/";

    // Threshold for indentation when we offer to outdent
    var OUTDENT_THRESH = 8;

    // All of the interface message keys that we explicitly load
    var INT_MSG_KEYS = [ "mycontris" ];

    // Date format regexes in signatures (i.e. the "default date format")
    var DATE_FMT_RGX = {
        "//en.wikipedia.org": /\d\d:\d\d,\s\d{1,2}\s\w+?\s\d{4}/.source,
        "//test.wikipedia.org": /\d\d:\d\d,\s\d{1,2}\s\w+?\s\d{4}/.source,
        "//simple.wikipedia.org": /\d\d:\d\d,\s\d{1,2}\s\w+?\s\d{4}/.source,
        "//en.wikisource.org": /\d\d:\d\d,\s\d{1,2}\s\w+?\s\d{4}/.source,
        "//meta.wikimedia.org": /\d\d:\d\d,\s\d{1,2}\s\w+?\s\d{4}/.source,
        "//pt.wikipedia.org": /\d\dh\d\dmin\sde \d{1,2} de \w+? de \d{4}/.source,
        "//commons.wikimedia.org": /\d\d:\d\d,\s\d{1,2}\s\w+?\s\d{4}/.source
    }

    // Shared API object
    var api;

    /*
     * Regex *sources* for a "userspace" link. Basically the
     * localized equivalent of User( talk)?|Special:Contributions/
     * Initialized in buildUserspcLinkRgx, which is called near the top
     * of the closure in handleWrapperClick.
     *
     * Three subproperties: und for underscores instead of spaces (e.g.
     * "User_talk"), spc for spaces (e.g. "User talk"), and both for
     * a regex combining the two (used for matching on wikitext).
     */
    var userspcLinkRgx = null;

    /**
     * This dictionary is some global state that holds a dictionary
     * for each "(reply)" link (keyed by their unique IDs):
     *
     *  - indentation, the indentation string for the comment (e.g. ":*::")
     *  - sigIdx, the zero-based index of the signature from the top
     *    of the section
     *
     * This dictionary is populated in attachLinks, and unpacked in the
     * click handler for the links (defined in attachLinkAfterNode); the
     * values are then passed to doReply.
     */
    var metadata = {};

    /**
     * This global string flag is:
     *
     *  - "AfD" if the current page is an AfD page
     *  - "MfD" if the current page is an MfD page
     *  - "TfD" if the current page is a TfD log page
     *  - "CfD" if the current page is a CfD log page
     *  - "FfD" if the current page is a FfD log page
     *  - "" otherwise
     *
     * This flag is initialized in onReady and used in attachLinkAfterNode
     */
    var xfdType;

    /**
     * The current page name, including namespace, because we may be reading it
     * a lot (especially in findUsernameInElem if we're on someone's user
     * talk page). Has underscores instead of spaces!
     */
    var currentPageName;

    /**
     * A map for signatures that contain redirects, so that they can still
     * pass the sanity check. This will be updated manually, because I
     * don't want the overhead of a whole 'nother API call in the middle
     * of the reply process. If this map grows too much, though, I'll
     * consider switching to either a toolforge-hosted API or the
     * Wikipedia API. Used in doReply, for the username sanity check.
     */
    var sigRedirectMapping = {
        "Salvidrim": "Salvidrim!"
    };

    /**
     * When the reply is saved via API, this flag is set to true to
     * disable the onbeforeunload handler.
     */
    var replyWasSaved = false;

    /**
     * Cache for getWikitext.
     */
    var getWikitextCache = {};

    // Polyfill from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
    if( !String.prototype.includes ) {
        String.prototype.includes = function( search, start ) {
            if( search instanceof RegExp ) {
                throw TypeError('first argument must not be a RegExp');
            }
            if( start === undefined ) {
                start = 0;
            }
            return this.indexOf( search, start ) !== -1;
        };
    }

    /**
     * Get the formatted namespace name for a namespace ID.
     * Quick ref: user = 2, proj = 4
     */
    function fmtNs( nsId ) {
        return mw.config.get( "wgFormattedNamespaces" )[ nsId ];
    }

    /**
     * Escapes a string for inclusion in a regex.
     */
    function escapeForRegex( s ) {
        return s.replace( /[-\/\\^$*+?.()|[\]{}]/g, '\\$&' );
    }

    /*
     * MediaWiki turns spaces before certain punctuation marks
     * into non-breaking spaces, so fix those. This is done by
     * the armorFrenchSpaces function in Mediawiki, in the file
     * /includes/parser/Sanitizer.php
     */
    function deArmorFrenchSpaces( text ) {
        return text.replace( /\xA0([?:;!%»›])/g, " $1" )
            .replace( /([«‹])\xA0/g, "$1 " );
    }

    /**
     * Remove duplicates from an array.
     * https://stackoverflow.com/a/9229821/1757964
     */
    function removeDuplicates( array ) {
        var seen = {};
        return array.filter( function( item ) {
            return seen.hasOwnProperty( item ) ? false : ( seen[ item ] = true );
        } );
    }

    /**
     * Capitalize the first letter of a string.
     */
    function capFirstLetter( someString ) {
        return someString.charAt( 0 ).toUpperCase() + someString.slice( 1 );
    }

    /**
     * Namespace name to ID.
     * For example, nsNameToId( "Template" ) === 10.
     */
    function nsNameToId( nsName ) {
        return mw.config.get( "wgNamespaceIds" )[ nsName.toLowerCase().replace( / /g, "_" ) ];
    }

    /**
     * Canonical-ize a namespace.
     */
    function canonicalizeNs( ns ) {
        return fmtNs( nsNameToId( ns ) );
    }

    /**
     * This function converts any (index-able) iterable into a list.
     */
    function iterableToList( nl ) {
        var len = nl.length;
        var arr = new Array( len );
        for( var i = 0; i < len; i++ ) arr[i] = nl[i];
        return arr;
    }

    /**
     * Process HTML character entities.
     * From https://stackoverflow.com/a/46851765
     */
    function processCharEntities( text ) {
        var el = document.createElement('div');
        return text.replace( /\&[#0-9a-z]+;/gi, function ( enc ) {
            el.innerHTML = enc;
            return el.innerText
        } );
    }

    /**
     * Process HTML character entities, MediaWiki style
     * From https://stackoverflow.com/a/46851765
     */
    function processCharEntitiesWikitext( text ) {
        var el = document.createElement('div');
        return text.replace( /\&[#0-9a-z]+;/gi, function ( enc ) {
            if( /#\d+/.test( enc ) ) {
                if( parseInt( enc.slice( 1 ) ) > MAX_UNICODE_DECIMAL ) {
                    return enc;
                }
            }
            el.innerHTML = enc;
            return el.innerText
        } );
    }

    /**
     * When there's a panel being shown, this function sets the status
     * in the panel to the first argument. The callback function is
     * optional.
     */
    function setStatus ( status, callback ) {
        var statusElement = $( "#reply-dialog-status" );
        statusElement.fadeOut( function () {
            statusElement.html( status ).fadeIn( callback );
        } );
    }

    /**
     * Sets the panel status when an error happened. Good for use in
     * catch blocks.
     */
    function setStatusError( e ) {
        console.error(e);
        setStatus( mw.msg( "rl-error-status" ) );
        if( e.message ) {
            console.log( "Content request error: " + JSON.stringify( e.message ) );
        }
        console.log( "DEBUG INFORMATION: '"+currentPageName+"' @ " + mw.config.get( "wgCurRevisionId" ) );
        throw e;
    }

    /**
     * Given some wikitext, processes it to get just the text content.
     * This function should be identical to the MediaWiki function
     * that gets the wikitext between the equal signs and comes up
     * with the id's that anchor the headers.
     */
    function wikitextToTextContent( wikitext ) {
        return processCharEntities( wikitext )
            .replace( /\[\[:?(?:[^\|\]]+?\|)?([^\]\|]+?)\]\]/g, "$1" )
            .replace( /\{\{\s*tl\s*\|\s*(.+?)\s*\}\}/g, "{{$1}}" )
            .replace( /\{\{\s*[Uu]\s*\|\s*(.+?)\s*\}\}/g, "$1" )
            .replace( /('''?)(.+?)\1/g, "$2" )
            .replace( /<s>(.+?)<\/s>/g, "$1" )
            .replace( /<big>(.+?)<\/big>/g, "$1" )
            .replace( /<span.*?>(.*?)<\/span>/g, "$1" );
    }

    function wikitextHeaderEqualsDomHeader( wikitextHeader, domHeader ) {
        return wikitextToTextContent( wikitextHeader ) === deArmorFrenchSpaces( domHeader );
    }

    /**
     * Finds and returns the div that is the immediate parent of the
     * first talk page header on the page, so that we can read all the
     * sections by iterating through its child nodes.
     */
    function findMainContentEl() {

        // Which header are we looking for?
        var targetHeader = "h2";
        if( xfdType || currentPageName.startsWith( RFA_PG ) ) targetHeader = "h3";
        if( currentPageName.startsWith( TTDYK ) ) targetHeader = "h4";

        // The element itself will be the text span in the h2; its
        // parent will be the h2; and the parent of the h2 is the
        // content container that we want
        var candidates = document.querySelectorAll( targetHeader + " > span.mw-headline" );
        if( !candidates.length ) {
            return document.getElementById( "mw-content-text" );
        }
        var candidate = candidates[ candidates.length - 1 ].parentElement.parentElement;

        // Compatibility with User:Kephir/gadgets/unclutter.js
        if( candidate.className.includes( "kephir-unclutter-discussion-wrapper" ) ) {
            candidate = candidate.parentElement;
        }

        // Compatibility with User:Enterprisey/hover-edit-section
        // That script puts each section in its own div, so we need to
        // go out another level if it's running
        if( candidate.className === "hover-edit-section" ) {
            candidate = candidate.parentElement;
        }

        return candidate;
    }

    /**
     * Gets the wikitext of a page with the given title (namespace required).
     * Returns an object with keys "content" and "timestamp".
     */
    function getWikitext( title, useCaching ) {
        if( useCaching === undefined ) useCaching = false;
        if( useCaching && getWikitextCache[ title ] ) {
            return $.when( getWikitextCache[ title ] );
        }
        return $.getJSON(
            mw.util.wikiScript( "api" ),
            {
                format: "json",
                action: "query",
                prop: "revisions",
                rvprop: "timestamp|content|ids",
                rvslots: "main",
                rvlimit: 1,
                titles: title,
                formatversion: 2,
            }
        ).then( function ( data ) {
            if( data.query.pages[0].revisions ) {
                var rev = data.query.pages[0].revisions[0];
                var result = { revId: rev.revid, timestamp: rev.timestamp, content: rev.slots.main.content };
                getWikitextCache[ title ] = result;
                return result;
            } else {
                console.error( data );
                throw new Error( "[getWikitext] bad response: " + data );
                return {};
            }
        } );
    }

    function getLastRevId( title ) {
        return $.getJSON(
            mw.util.wikiScript( "api" ),
            {
                format: "json",
                action: "query",
                prop: "revisions",
                rvprop: "ids",
                rvslots: "main",
                rvlimit: 1,
                titles: title,
                formatversion: 2,
            }
        ).then( function ( data ) {
            return data.query.pages[0].revisions[0].revid;
        } );
    }

    function getPathToElement( givenEl ) {
        var path = [];
        var currEl = givenEl;
        while( ( currEl.id !== "mw-content-text" ) && ( currEl.tagName.toLowerCase() !== "body" ) ) {
            path.push( iterableToList( currEl.parentNode.children ).indexOf( currEl ) );
            currEl = currEl.parentNode;
        }
        return path.join( "|" );
    }

    function followPathToElement( path ) {
        path = path.split( "|" );
        var el = document.getElementById( "mw-content-text" );
        for( var i = path.length - 1; i >= 0; i-- ) {
            el = el.children[parseInt(path[i])];
        }
        return el;
    }

    function highlightContainerOf( el ) {
        outer:
        while( true ) {
            switch( el.tagName.toLowerCase() ) {
                case "ul":
                case "ol":
                case "li":
                case "dd":
                case "dl":
                case "p":
                case "div":
                case "table":
                case "td":
                    break outer;
            }
            el = el.parentNode;
        }
        el.className += "reply-link-jump-highlight";
    }

    function getTimestampGivenAuthorLink( authorLink ) {
        var currNode = authorLink;
        // The .localcomments element check is for compatibilty with the [[WP:Comments in Local Time]] gadget
        while( !currNode.textContent.includes( "(UTC)" ) && ( currNode.className !== "localcomments" ) ) {
            if( currNode.nextSibling ) {
                currNode = currNode.nextSibling;
            } else {
                currNode = currNode.parentNode;
            }
        }
        if( currNode.textContent.includes( "(UTC)" ) ) {
            var matches = currNode.textContent.match( new RegExp( DATE_FMT_RGX[mw.config.get( "wgServer" )], "g" ) );
            if( matches.length > 0 ) {
                return matches[ matches.length - 1 ];
            }
        } else if( currNode.className === "localcomments" ) {
            var matches = currNode.getAttribute( "title" ).match( new RegExp( DATE_FMT_RGX[mw.config.get( "wgServer" )], "g" ) );
            if( matches.length > 0 ) {
                return matches[ matches.length - 1 ];
            }
        }
        return null;
    }

    /**
     * Creates userspcLinkRgx. Called in handleWrapperClick and the test
     * runner at the bottom.
     */
    function buildUserspcLinkRgx() {
        if( userspcLinkRgx ) {
            return;
        }

        var nsIdMap = mw.config.get( "wgNamespaceIds" );
        var nsRgxFragments = [];
        var contribsSecondFrag = ":" + escapeForRegex( mw.messages.get( "mycontris" ) ) + "\\/";
        for( var nsName in nsIdMap ) {
            if( !nsIdMap.hasOwnProperty( nsName ) ) continue;
            switch( nsIdMap[nsName] ) {
                case 2:
                case 3:
                    nsRgxFragments.push( escapeForRegex( capFirstLetter( nsName ) ) + "\\s*:" );
                    break;
                case -1:
                    nsRgxFragments.push( escapeForRegex( capFirstLetter( nsName ) ) + contribsSecondFrag );
                    break;
            }
        }
        userspcLinkRgx = {};
        userspcLinkRgx.spc = "(?:" + nsRgxFragments.join( "|" ).replace( /_/g, " " ) + ")";
        userspcLinkRgx.und = userspcLinkRgx.spc.replace( / /g, "_" );
        userspcLinkRgx.both = userspcLinkRgx.spc.replace( / /g, "(?: |_)" );
    }

    /**
     * Is there a signature (four tildes) present in the given text,
     * outside of a nowiki element?
     */
    function hasSig( text ) {

        // no literal signature?
        if( !text.includes( LITERAL_SIGNATURE ) ) return false;

        // if there's a literal signature and no nowiki elements,
        // there must be a real signature
        if( !text.includes( "<nowiki>" ) ) return true;

        // Save all nowiki spans
        var nowikiSpanStarts = []; // list of ignored span beginnings
        var nowikiSpanLengths = []; // list of ignored span lengths
        var NOWIKI_RE = /<nowiki>.*?<\/nowiki>/g;
        var spanMatch;
        do {
            spanMatch = NOWIKI_RE.exec( text );
            if( spanMatch ) {
                nowikiSpanStarts.push( spanMatch.index );
                nowikiSpanLengths.push( spanMatch[0].length );
            }
        } while( spanMatch );

        // So that we don't check every ignore span every time
        var nowikiSpanStartIdx = 0;

        var LIT_SIG_RE = new RegExp( LITERAL_SIGNATURE, "g" );
        var sigMatch;

        matchLoop:
        do {
            sigMatch = LIT_SIG_RE.exec( text );
            if( sigMatch ) {

                // Check that we're not inside a nowiki
                for( var nwIdx = nowikiSpanStartIdx; nwIdx <
                    nowikiSpanStarts.length; nwIdx++ ) {
                    if( sigMatch.index > nowikiSpanStarts[nwIdx] ) {
                        if ( sigMatch.index + sigMatch[0].length <=
                            nowikiSpanStarts[nwIdx] + nowikiSpanLengths[nwIdx] ) {

                            // Invalid sig
                            continue matchLoop;
                        } else {

                            // We'll never encounter this span again, since
                            // headers only get later and later in the wikitext
                            nowikiSpanStartIdx = nwIdx;
                        }
                    }
                }

                // We aren't inside a nowiki
                return true;
            }
        } while( sigMatch );
        return false;
    }

    /**
     * Given an Element object, attempt to recover a username from it.
     * Also will check up to two elements prior to the passed element.
     * Returns null if no username was found. Otherwise, returns an
     * object with these properties:
     *
     *  - username: The username that we found.
     *  - link: The DOM element for the link from which we got the
     *    username.
     */
    function findUsernameInElem( el ) {
        if( !el ) return null;
        var links;
        for( let i = 0; i < 3; i++ ) {
            if( el === null ) break;
            links = el.tagName.toLowerCase() === "a" ? [ el ]
                : el.querySelectorAll( "a" );
            //console.log(i,"top of outer for in findUsernameInElem ",el, " links -> ",links);

            // Compatibility with "Comments in Local Time"
            if( el.className.includes( "localcomments" ) ) i--;

            // If we couldn't get any links, try again with prev elem
            if( !links ) continue;

            var link; // his name isn't zelda
            for( var j = 0; j < links.length; j++ ) {
                link = links[j];

                //console.log(link,decodeURIComponent(link.getAttribute("href")));
                if( link.className.includes( "mw-selflink" ) ) {
                    return { username: currentPageName.replace( /.+:/, "" )
                        .replace( /_/g, " " ), link: link };
                }

                // Also matches redlinks. Why people have redlinks in their sigs on
                // purpose, I may never know.
                //console.log( "^\\/(?:wiki\\/" + userspcLinkRgx.und + /(.+?)(?:\/.+?)?(?:#.+)?|w\/index\.php\?title=User(?:_talk)?:(.+?)&action=edit&redlink=1/.source + ")$" )
                var sigLinkRe = new RegExp( "\\/(?:wiki\\/" + userspcLinkRgx.und + /(.+?)(?:\/.+?)?(?:#.+)?|w\/index\.php\?title=/.source + userspcLinkRgx.und + /(.+?)&action=edit&redlink=1/.source + ")$" );
                var liveDecodedHref = decodeURIComponent( link.getAttribute( "href" ) );
                if( liveDecodedHref.startsWith( "/" ) ) {
                    liveDecodedHref = "https:" + mw.config.get( "wgServer" ) + liveDecodedHref;
                }
                var usernameMatch = sigLinkRe.exec( liveDecodedHref );
                if( usernameMatch ) {
                //console.log("usernameMatch",usernameMatch)
                    var rawUsername = usernameMatch[1] ? usernameMatch[1] : usernameMatch[2];
                    return {
                        username: decodeURIComponent( rawUsername ).replace( /_/g, " " ),
                        link: link
                    };
                }
            }

            // Go backwards one element and try again
            el = el.previousElementSibling;
        }
        return null;
    }

    /**
     * Given a reply-link-wrapper span, attempts to find who wrote
     * the comment that precedes it. For information about the return
     * value, see the documentation for findUsernameInElem.
     */
    function getCommentAuthor( wrapper ) {
        var sigNode = wrapper.previousSibling;
        //console.log(sigNode,sigNode.style,sigNode.style ? sigNode.style.getPropertyValue("size"):"");
        var smallOrFake = sigNode.nodeType === 1 &&
                ( sigNode.tagName.toLowerCase() === "small" ||
                ( sigNode.tagName.toLowerCase() === "span" &&
                    sigNode.style && ( sigNode.style.getPropertyValue( "font-size" ) === "85%" ||
                                       sigNode.style.getPropertyValue( "font-size" ).indexOf( "small" ) === 0 ) ) );

        var possUserLinkElem = ( smallOrFake && sigNode.children.length > 1 )
            ? sigNode.children[sigNode.children.length-1]
            : sigNode.previousElementSibling;
        return findUsernameInElem( possUserLinkElem );
    }

    /**
     * Given the wikitext of a section, attempt to find the first edit
     * request template in it, and then mark that template as answered.
     * Returns the modified section wikitext.
     */
    function markEditReqAnswered( sectionWikitext ) {
        var editReqMatch = EDIT_REQ_TPL_REGEX.exec( sectionWikitext );
        if( !editReqMatch ) {
            console.error( "Couldn't find an edit request!" );
            return sectionWikitext;
        }

        var ansParamMatch = /ans(wered)?=.*?(\||\}\})/.exec( editReqMatch[0] );
        if( !ansParamMatch ) {
            sectionWikitext = sectionWikitext.replace(
                editReqMatch[0],
                editReqMatch[0].replace( "}}", "answered=yes}}" )
            );
        } else {
            var newEditReqTpl = editReqMatch[0].replace( ansParamMatch[0],
                "answered=yes" + ansParamMatch[2] );
            sectionWikitext = sectionWikitext.replace(
                editReqMatch[0],
                newEditReqTpl
            );
        }
        return sectionWikitext;
    }

    function allContentHeaders() {
        var allHeaders = document.querySelector( "#mw-content-text" )
            .querySelectorAll( HEADER_SELECTOR );
        return iterableToList( allHeaders )
            .filter( function ( header ) {
                // The word "Contents" at the top of the table of contents is a heading
                return ( header.getAttribute( "id" ) !== "mw-toc-heading" );
            } );
    }

    /**
     * Given a header element, finds the title (full with namespace, spaces
     * instead of underscores) of the page it's from.
     */
    function pageNameOfHeader( header ) {
        var editLinks = iterableToList( header.querySelectorAll( ".mw-editsection a" ) )
            .filter( function ( e ) { return e.textContent.indexOf( "edit" ) === 0; } );
        if( editLinks.length ) {
            var encoded = editLinks[0]
                .getAttribute( "href" )
                .match( /title=(.+?)(?:$|&)/ )
                [1];
            return decodeURIComponent( encoded ).replace( /_/g, " " );
        } else {
            return null;
        }
    }

    /**
     * Given a DOM object in the current page corresponding to a link in a
     * signature, locate the section header (i.e. h1, h2, etc element) for the
     * section containing that comment.
     */
    function findSectionHeaderElement( sigLinkElem ) {
        var nearestHeader = null;
        var currElem = sigLinkElem;
        var sigLinkTopPos = sigLinkElem.getBoundingClientRect().top;

        loop:
        while( ( currElem.id !== "mw-content-text" ) && ( currElem.tagName.toLowerCase() !== "body" ) ) {
            var familiarTagName = false;
            switch( currElem.tagName.toLowerCase() ) {
                case "ul":
                case "ol":
                case "li":
                case "dd":
                case "dl":
                case "a":
                case "i":
                case "code":
                    // Headers aren't in these elements (and it would be a waste to check)
                    break;
                case "h1":
                case "h2":
                case "h3":
                case "h4":
                case "h5":
                case "h6":
                    // Well, that was convenient (found a header)
                    nearestHeader = currElem;
                    break loop;
                case "p":
                case "span": // unlikely, but we'll check anyway
                case "div":
                case "table": // yeah, sometimes people put their whole talk page in a template
                case "td":
                case "sub":
                case "sup":
                case "b":
                    familiarTagName = true;
                default:
                    var tagName = currElem.tagName.toLowerCase();
                    if( !familiarTagName ) {
                        // just in case there's a tag not listed here that needs special handling
                        console.warn( "unknown tag name ", tagName, " ", currElem );
                    }
                    var childHeaders = currElem.querySelectorAll( HEADER_SELECTOR );
                    if( childHeaders ) {
                        childHeaders = iterableToList( childHeaders )
                            .filter( function ( header ) {
                                // We don't want to pick up headers below the comment
                                return header.getBoundingClientRect().top < sigLinkTopPos;
                            } );
                        if( childHeaders.length > 0 ) {
                            nearestHeader = childHeaders[childHeaders.length - 1];
                            break loop;
                        }
                    }
                    break;
            } // end switch ( currElem.tagName )

            if( currElem.previousElementSibling ) {
                currElem = currElem.previousElementSibling;
            } else {
                currElem = currElem.parentNode;
            }
        } // end while

        if( nearestHeader === null ) {
            console.warn( "nearestHeader was null" );
        }
        return nearestHeader;
    }

    /**
     * Finds a section in the given page's wikitext.
     *
     * If givenHeaderEl is null, that means it's the "zeroth" section, i.e.
     * the section that ends at the first page header.
     */
	function findSectionInPageWikitext( givenHeaderEl, pageTitle, pageWikitext ) {
        var allHeaders = document.querySelector( "#mw-content-text" )
            .querySelectorAll( HEADER_SELECTOR );
        var allHeadersFromTarget = iterableToList( allHeaders )
            .filter( function ( header ) {
                // The word "Contents" at the top of the table of contents is a heading
                return ( header.getAttribute( "id" ) !== "mw-toc-heading" ) &&
                    pageNameOfHeader( header ) === pageTitle;
            } );

        // Find all the headers in the wikitext

        // Save all ignored spans
        var ignoredSpanStarts = []; // list of ignored span beginnings
        var ignoredSpanLengths = []; // list of ignored span lengths
        var IGNORED_RE = /(?:<(nowiki|pre|noinclude|source)>[\s\S]*?<\/\1>)|<!--[\s\S]+?-->/g;
        var spanMatch;
        do {
            spanMatch = IGNORED_RE.exec( pageWikitext );
            if( spanMatch ) {
                ignoredSpanStarts.push( spanMatch.index );
                ignoredSpanLengths.push( spanMatch[0].length );
            }
        } while( spanMatch );

        // So that we don't check every ignore span every time
        var ignoredSpanStartIdx = 0;

        var headerMatches = [];
        var headerMatch;

        matchLoop:
        do {
            headerMatch = HEADER_REGEX.exec( pageWikitext );
            if( headerMatch ) {

                // Check that we're not inside a ignored span
                for( var ignoredIdx = ignoredSpanStartIdx; ignoredIdx <
                    ignoredSpanStarts.length; ignoredIdx++ ) {
                    if( headerMatch.index > ignoredSpanStarts[ignoredIdx] ) {
                        if ( headerMatch.index + headerMatch[0].length <=
                            ignoredSpanStarts[ignoredIdx] + ignoredSpanLengths[ignoredIdx] ) {

                            // Not a header, since we're inside a ignored span
                            continue matchLoop;
                        } else {

                            // We'll never encounter this span again, since
                            // headers only get later and later in the wikitext
                            ignoredSpanStartIdx = ignoredIdx;
                        }
                    }
                }
                headerMatches.push( headerMatch );
            }
        } while( headerMatch );

        // We'll use this dictionary to calculate the duplicate index
        var headersByText = {};
        for( var i = 0; i < headerMatches.length; i++ ) {

            // Group 2 of HEADER_REGEX is the header text
            var text = headerMatches[i][2];
            headersByText[text] = ( headersByText[text] || [] ).concat( i );
        }

        // allHeadersFromTarget should contain every header we found in the wikitext
        // (and more, if sourcePageName was transcluded multiple times)
        if( allHeadersFromTarget.length % headerMatches.length !== 0 ) {
            for( var i = 0; i < Math.max( allHeadersFromTarget.length, headerMatches.length ); i++ ) {
                console.error( i, allHeadersFromTarget[i], allHeadersFromTarget[i] && allHeadersFromTarget[i].textContent, headerMatches[i] );
            }
            throw new Error( "non-divisble header list lengths" );
        }

        if( givenHeaderEl === null ) {
            var sectionEndIdx = headerMatches[0] ? headerMatches[0].index : pageWikitext.length;
            return {
                title: "",
                dupIdx: 0,
                startIdx: 0,
                endIdx: sectionEndIdx,
                idxInDomHeaders: -1,
            };
        }

        var headerIdx = allHeadersFromTarget.indexOf( givenHeaderEl );
        if( headerIdx < 0 ) {
            console.error( 'givenHeaderEl', givenHeaderEl );
            console.error( 'allHeadersFromTarget', allHeadersFromTarget );
            throw new Error( "givenHeaderEl not in allHeadersFromTarget" );
        }
        var trueHeaderIdx = headerIdx % headerMatches.length;
        var headerText = headerMatches[trueHeaderIdx][2];

        // NOTE! The duplicate index is calculated relative to the
        // *wikitext* header matches (because that's how the backend
        // does it)! That is, if we have a page that includes two
        // headers, both called "a", and we transclude that page
        // twice, the result will be four headers called "a". But we
        // want to assign those four headers, respectively, the
        // duplicate indices of 0, 1, 0, 1. That's why we use
        // trueHeaderIdx here, not headerIdx.
        var dupIdx = headersByText[headerText].indexOf( trueHeaderIdx );

        var sectionStartIdx = headerMatches[trueHeaderIdx].index;
        var sectionEndIdx = headerMatches[trueHeaderIdx + 1]
                ? headerMatches[trueHeaderIdx + 1].index
                : pageWikitext.length;

        return {
            title: headerText,
            dupIdx: dupIdx,
            startIdx: sectionStartIdx,
            endIdx: sectionEndIdx,
            idxInDomHeaders: headerIdx,
        };
    }

    /**
     * Given a DOM object in the current page corresponding to a link in a
     * signature, locate the section containing that comment. That section may
     * not be in the current page!
     */
    function findSectionMain( sigLinkElem ) {
        var nearestHeader = findSectionHeaderElement( sigLinkElem );
        var pageTitle = ( nearestHeader ? pageNameOfHeader( nearestHeader ) : currentPageName ).replace( /_/g, " " );
        return getWikitext( pageTitle, /* useCaching */ true ).then( function ( revObj ) {
            var pageText = revObj.content;
            var sectionObj = findSectionInPageWikitext( nearestHeader, pageTitle, pageText );
            sectionObj.pageTitle = pageTitle;
            sectionObj.revObj = revObj;
            sectionObj.headerEl = nearestHeader;
            //sectionObj.level = parseInt( nearestHeader.tagName.substring( 1 ) ); // that is, cut off the "h" at the beginning
            return sectionObj;
        }, function ( err ) { throw new Error( err ); } );
    }

    /**
     * Converts a (zero-based) signature index to a pair of string indices into
     * the given section wikitext, indicating the start and the end of the
     * requested signature. The return value is an object with two properties,
     * "start" for the starting index and "end" for the ending index (i.e. the
     * index of the first character after the signature).
     *
     * Returns null if we couldn't find anything.
     */
    function sigIdxToStrIdx( sectionWikitext, sigIdx ) {
        //console.log( "In sigIdxToStrIdx, sigIdx = " + sigIdx );

        // There are certain regions that we skip while attaching links:
        //
        //  - Spans with the class delsort-notice
        //  - Divs with the class xfd-relist (and other divs)
        //
        // So, we grab the corresponding wikitext regions with regexes,
        // and store each region's start index in spanStartIndices, and
        // each region's length in spanLengths. Then, whenever we find a
        // signature with the right index, if it's included in one of
        // these regions, we skip it and move on.
        var spanStartIndices = [];
        var spanLengths = [];
        var DELSORT_SPAN_RE_TXT = /<small class="delsort-notice">(?:<small>.+?<\/small>|.)+?<\/small>/.source;
        var XFD_RELIST_RE_TXT = /<div class="xfd_relist"[\s\S]+?<\/div>(\s*|<!--.+?-->)*/.source;
        var SKIP_REGION_RE = new RegExp("(" + DELSORT_SPAN_RE_TXT + ")|(" +
            XFD_RELIST_RE_TXT + ")|(" +
            /<s>.+?<\/s>/.source + ")", // struck regions (I don't care about nested ones)
            "ig");
        var skipRegionMatch;
        while( ( skipRegionMatch = SKIP_REGION_RE.exec( sectionWikitext ) ) !== null ) {
            spanStartIndices.push( skipRegionMatch.index );
            spanLengths.push( skipRegionMatch[0].length );
        }

        // Also skip transclusions of {{tq}} and {{tq2}}. These transclusions
        // have a high chance of containing other templates, so instead search
        // for closing curly braces at the right nesting level with a counter.
        var TQ_START_RE = /\{\{\s*tq2?/g;
        var tqStartMatch;
        while( ( tqStartMatch = TQ_START_RE.exec( sectionWikitext ) ) !== null ) {
            var currentNestingLevel = 2; // two curly braces started the template
            var wikitextIdx = tqStartMatch.index + tqStartMatch[0].length;
            while( ( currentNestingLevel > 0 ) && ( wikitextIdx < sectionWikitext.length ) ) {
                if( sectionWikitext.charAt( wikitextIdx ) === "{" ) {
                    currentNestingLevel += 1;
                } else if( sectionWikitext.charAt( wikitextIdx ) === "}" ) {
                    currentNestingLevel -= 1;
                }
                wikitextIdx += 1;
            }

            spanStartIndices.push( tqStartMatch.index );
            spanLengths.push( wikitextIdx - tqStartMatch.index );
        }
        //console.log(spanStartIndices,spanLengths);

        var dateFmtRgx = DATE_FMT_RGX[mw.config.get( "wgServer" )];
        if( !dateFmtRgx ) {
            throw new Error( "Error! I don't know the native date format used by the server '" + mw.config.get( "wgServer" ) + "'!" );
        }
        /*
         * I apologize for making you have to read this regex.
         * I made a summary, though:
         *
         *  - a wikilink, without a ]] inside it
         *  - some text, without a link to userspace or user talk space
         *  - a timestamp
         *  - as an alternative to all of the above, an autosigned script
         *    and a timestamp
         *  - some comments/whitespace or some non-whitespace
         *  - finally, the end of the line
         *
         * It's also localized.
         */
        var sigRgxSrc = "(?:" + /\[\[\s*(?:m:)?:?\s*/.source + "(" + userspcLinkRgx.both +
                /([^\]\n]|\](?!\]))*?/.source + ")" + /\]\]\)?/.source + "(" +
                /[^\[\n]|\[(?!\[)|\[\[/.source + "(?!" + userspcLinkRgx.both +
                "))*?" + DATE_FMT_RGX[mw.config.get( "wgServer" )] +
                /\s+\(UTC\)|class\s*=\s*"autosigned".+?\(UTC\)<\/small>/.source +
                ")" + /(\S*([ \t\f]|<!--.*?-->)*(?:\{\{.+?\}\})?(?!\S)|\s?\S+([ \t\f]|<!--.*?-->)*)$/.source;
        var sigRgx = new RegExp( sigRgxSrc, "igm" );
        var matchIdx = 0;
        var match;
        var matchIdxEnd;
        var dstSpnIdx;

        sigMatchLoop:
        for( ; true ; matchIdx++ ) {
            match = sigRgx.exec( sectionWikitext );
            if( !match ) {
                console.error("[sigIdxToStrIdx] out of matches, matchIdx was",matchIdx,"sigIdx was",sigIdx);
                return null;
            }
            //console.log( "sig match (matchIdx = " + matchIdx + ") is >" + match[0] + "< (index = " + match.index + ")" );

            matchIdxEnd = match.index + match[0].length;

            // Validate that we're not inside a delsort span
            for( dstSpnIdx = 0; dstSpnIdx < spanStartIndices.length; dstSpnIdx++ ) {
                //console.log(spanStartIndices[dstSpnIdx],match.index,
                //    matchIdxEnd, spanStartIndices[dstSpnIdx] +
                //        spanLengths[dstSpnIdx] );
                if( match.index > spanStartIndices[dstSpnIdx] &&
                    ( matchIdxEnd <= spanStartIndices[dstSpnIdx] +
                        spanLengths[dstSpnIdx] ) ) {

                    // That wasn't really a match (as in, this match does not
                    // correspond to any sig idx in the DOM), so we can't
                    // increment matchIdx
                    matchIdx--;

                    continue sigMatchLoop;
                }
            }

            if( matchIdx === sigIdx ) {
                return {
                    start: match.index,
                    end: match.index + match[0].length,
                };
            }
        }
    }

    /**
     * Inserts fullReply on the next sensible line after strIdx in
     * sectionWikitext. indentLvl is the indentation level of the
     * comment we're replying to.
     *
     * This function essentially takes the indentation level and
     * position of the current comment, and looks for the first comment
     * that's indented strictly less than the current one. Then, it
     * puts the reply on the line right before that comment, and returns
     * the modified section wikitext.
     */
    function insertTextAfterIdx( sectionWikitext, strIdx, indentLvl, fullReply ) {
        //console.log( "[insertTextAfterIdx] indentLvl = " + indentLvl );

        // strIdx should point to the end of a line
        var counter = 0;
        while( ( sectionWikitext[ strIdx ] !== "\n" ) && ( counter++ <= 50 ) ) strIdx++;

        var slicedSecWikitext = sectionWikitext.slice( strIdx );
        //console.log("slicedSecWikitext = >>" + slicedSecWikitext.slice(0,50) + "<<");
        slicedSecWikitext = slicedSecWikitext.replace( /^\n/, "" );
        var candidateLines = slicedSecWikitext.split( "\n" );
        //console.log( "candidateLines =", candidateLines );

        // number of the line in sectionWikitext that'll be right after reply
        var replyLine = 0;

        var INDENT_RE = /^[:*#]+/;
        if( slicedSecWikitext.trim().length > 0 ) {
            var currIndentation, currIndentationLvl, i;

            // Now, loop through all the comments replying to that
            // one and place our reply after the last one
            for( i = 0; i < candidateLines.length; i++ ) {
                if( candidateLines[i].trim() === "" ) {
                    continue;
                }

                // Detect indentation level of current line
                currIndentation = INDENT_RE.exec( candidateLines[i] );
                currIndentationLvl = currIndentation ? currIndentation[0].length : 0;
                //console.log(i + ">" + candidateLines[i] + "< => " + currIndentationLvl);

                if( currIndentationLvl <= indentLvl ) {

                    // If it's an XfD, we might have found a relist
                    // comment instead, so check for that
                    if( xfdType && /<div class="xfd_relist"/.test( candidateLines[i] ) ) {

                        // Our reply might go on the line above the xfd_relist line
                        var potentialReplyLine = i;

                        // Walk through the relist notice, line by line
                        // After this loop, i will point to the line on which
                        // the notice ends
                        var NEW_COMMENTS_RE = /Please add new comments below this line/;
                        while( !NEW_COMMENTS_RE.test( candidateLines[i] ) ) {
                            i++;
                        }

                        // Relists are treated as if they're indented at level 1
                        if( 1 <= indentLvl ) {
                            replyLine = potentialReplyLine;
                            break;
                        }
                    } else {
                        //console.log( "cIL <= iL, breaking" );
                        break;
                    }
                } else {
                    replyLine = i + 1;
                }
            }
            if( i === candidateLines.length ) {
                replyLine = i;
            }
        } else {

            // In this case, we may be replying to the last comment in a section
            replyLine = candidateLines.length;
        }

        // Walk backwards until non-empty line
        while( replyLine >= 1 && candidateLines[replyLine - 1].trim() === "" ) replyLine--;

        //console.log( "replyLine = " + replyLine );

        // Splice into slicedSecWikitext
        slicedSecWikitext = candidateLines
            .slice( 0, replyLine )
            .concat( [ fullReply ], candidateLines.slice( replyLine ) )
            .join( "\n" );

        // We may need an additional newline if the two slices don't have any
        var optionalNewline = ( !sectionWikitext.slice( 0, strIdx ).endsWith( "\n" ) &&
                    !slicedSecWikitext.startsWith( "\n" ) ) ? "\n" : "";

        // Splice into sectionWikitext
        sectionWikitext = sectionWikitext.slice( 0, strIdx ) +
            optionalNewline + slicedSecWikitext;

        return sectionWikitext;
    }

    function performInPlaceReload( sigLinkElem, sectionObj ) {
        return $.getJSON(
            mw.util.wikiScript( "api" ),
            {
                format: "json",
                action: "parse",
                prop: "text",
                section: sectionObj.idxInDomHeaders + 1,
                page: sectionObj.pageTitle,
                formatversion: 2,
            }
        ).then( function ( parseResult ) {
            if( parseResult.parse.text ) {
                var cmtLinkPath = getPathToElement( sigLinkElem );

                // Delete all DOM elements in the current section
                var nextHeaderEl = allContentHeaders()[sectionObj.idxInDomHeaders + 1];
                var currEl = sectionObj.headerEl.nextElementSibling;
                while( currEl && ( currEl !== nextHeaderEl ) ) {
                    var nextEl = currEl.nextElementSibling;
                    currEl.parentNode.removeChild( currEl );
                    currEl = nextEl;
                }

                // Now write in the new stuff
                var newHtml = new DOMParser().parseFromString( parseResult.parse.text, "text/html" );

                // Select inside of .mw-parser-output
                newHtml = newHtml.querySelector( ".mw-parser-output" );

                // Remove initial header
                newHtml.removeChild( newHtml.children[0] );

                $( sectionObj.headerEl ).after( newHtml.children );
                mw.hook( "wikipage.content" ).fire( $( newHtml.children ) );

                delete getWikitextCache[sectionObj.pageTitle];

                var newCmtLink = followPathToElement( cmtLinkPath );
                highlightContainerOf( newCmtLink );
            } else {
                console.error( parseResult );
                setStatus( "Failed to load in new version." );
            }
        } );
    }

    /**
     * Using the text in #reply-dialog-field, add a reply to the current page.
     * rplyToXfdNom is true if we're replying to an XfD nom, in which case we
     * should use an asterisk instead of a colon.  revObj is the object returned
     * by getWikitext for the page with the comment; sectionObj is the object
     * returned by findSectionMain for the comment.
     *
     * Returns a Deferred that resolves/rejects when the reply succeeds/fails.
     */
    function doReply( parentCmtObj, cmtAuthorAndLink, rplyToXfdNom, sectionObj, canMakeSectionEdit ) {
        var deferred = $.Deferred();

        var revObj = sectionObj.revObj;
        var wikitext = revObj.content;

        try {

            // Generate reply in wikitext form
            var reply = document.getElementById( "reply-dialog-field" ).value.trim();

            // Add a signature if one isn't already there
            if( !hasSig( reply ) ) {
                reply += " " + ( window.replyLinkSigPrefix ?
                    window.replyLinkSigPrefix : "" ) + LITERAL_SIGNATURE;
            }

            var isUsingAutoIndentation = window.replyLinkAutoIndentation === "checkbox"
                ? ( !document.getElementById( "reply-link-option-auto-indent" ) ||
                    document.getElementById( "reply-link-option-auto-indent" ).checked )
                : window.replyLinkAutoIndentation === "always";
            if( isUsingAutoIndentation ) {

                var replyLines = reply.split( "\n" );

                // If we're outdenting, reset indentation and add the
                // outdent template. This requires that there be at least
                // one character of indentation.
                var outdentCheckbox = document.getElementById( "reply-link-option-outdent" );
                if( outdentCheckbox && outdentCheckbox.checked ) {
                    replyLines[0] = "{" + "{od|" + parentCmtObj.indentation.slice( 0, -1 ) +
                        "}}" + replyLines[0];
                    parentCmtObj.indentation = "";
                }

                // Compose reply by adding indentation at the beginning of
                // each line (if not replying to an XfD nom) or {{pb}}'s
                // between lines (if replying to an XfD nom)
                var fullReply;
                if( rplyToXfdNom ) {

                    // If there's a list in this reply, it's a bad idea to
                    // use pb's, even though the markup'll probably be broken
                    if( replyLines.some( function ( l ) { return l.substr( 0, 1 ) === "*"; } ) ) {
                        fullReply = replyLines.map( function ( line ) {
                            return parentCmtObj.indentation + "*" + line;
                        } ).join( "\n" );
                    } else {
                        fullReply = parentCmtObj.indentation + "* " + replyLines.join( "{{pb}}" );
                    }
                } else {
                    fullReply = replyLines.map( function ( line ) {
                        return parentCmtObj.indentation + ":" + line;
                    } ).join( "\n" );
                }
            } else {
                fullReply = reply;
            }

            var sectionWikitext = wikitext.slice( sectionObj.startIdx, sectionObj.endIdx )
                .trim(); // extra whitespace just messes stuff up
            var oldSectionWikitext = sectionWikitext; // We'll String.replace old w/ new

            // Now, obtain the index of the end of the comment
            var sigStartStrIdx = null;
            var sigEndStrIdx = null;
            if( !parentCmtObj.endStrIdx ) {
                var strIndices = sigIdxToStrIdx( sectionWikitext, parentCmtObj.sigIdx );
                sigStartStrIdx = strIndices && strIndices.start;
                sigEndStrIdx = strIndices && strIndices.end;
            } else {
                sigEndStrIdx = parentCmtObj.endStrIdx;
            }

            // Check for a valid sigEndStrIdx
            if( sigEndStrIdx === null ) {
                throw( "Null sigEndStrIdx (signature not found in wikitext)" );
            }

            // Determine the user who wrote the comment, for
            // edit-summary and sanity-check purposes
            var userRgx = new RegExp( /\[\[\s*(?:m:)?:?\s*/.source + userspcLinkRgx.both + /\s*(.+?)(?:\/.+?)?(?:#.+?)?\s*(?:\|.+?)?\]\]/.source, "ig" );
            var userMatches = processCharEntitiesWikitext( sectionWikitext.slice( sigStartStrIdx || 0, sigEndStrIdx ) ).match( userRgx );
            var cmtAuthorWktxt = userRgx.exec( userMatches[userMatches.length - 1] )[1];

            if( cmtAuthorWktxt === "DoNotArchiveUntil" ) {
                userRgx.lastIndex = 0;
                cmtAuthorWktxt = userRgx.exec( userMatches[userMatches.length - 2] )[1];
            }

            // Normalize case, because that's what happens during
            // wikitext-to-HTML processing; also underscores to spaces
            function sanitizeUsername( u ) {
                u = u.charAt( 0 ).toUpperCase() + u.substr( 1 );
                return u.replace( /_/g, " " );
            }
            cmtAuthorWktxt = sanitizeUsername( cmtAuthorWktxt );
            var cmtAuthorDom = sanitizeUsername( cmtAuthorAndLink.username );

            // Is the sig username the same as the DOM one?  We attempt to check
            // sigRedirectMapping in case the naive check fails
            if( cmtAuthorWktxt !== cmtAuthorDom &&
                    processCharEntitiesWikitext( cmtAuthorWktxt ) !== cmtAuthorDom &&
                    sigRedirectMapping[ cmtAuthorWktxt ] !== cmtAuthorDom ) {
                throw new Error( "Sig username assert failed! Found " +
                    cmtAuthorWktxt + " but expected " + cmtAuthorDom +
                    " (wikitext vs DOM)" );
            }

            // Another check: timestamp
            var htmlTimestamp = getTimestampGivenAuthorLink( cmtAuthorAndLink.link );
            var textTimestampMatches = sectionWikitext.slice( sigStartStrIdx || 0, sigEndStrIdx ).match( new RegExp( DATE_FMT_RGX[mw.config.get( "wgServer" )], "g" ) );
            if( textTimestampMatches.length > 0 ) {
                var textTimestamp = textTimestampMatches[ textTimestampMatches.length - 1 ];
                if( htmlTimestamp !== textTimestamp ) {
                    throw new Error( "Timestamp assert failed! HTML had '" + htmlTimestamp + "' but wikitext had '" + textTimestamp + "'" );
                }
            } else {
                console.warn( "textTimestampMatches was empty" );
            }

            // Actually insert our reply into the section wikitext
            sectionWikitext = insertTextAfterIdx( sectionWikitext, sigEndStrIdx,
                    parentCmtObj.indentation.length, fullReply );

            // Also, if the user wanted the edit request to be answered, do that
            var editReqCheckbox = document.getElementById( "reply-link-option-edit-req" );
            var markedEditReq = false;
            if( editReqCheckbox && editReqCheckbox.checked ) {
                sectionWikitext = markEditReqAnswered( sectionWikitext );
                markedEditReq = true;
            }

            // If the user preferences indicate a dry run, print what the
            // wikitext would have been post-edit and bail out
            var dryRunCheckbox = document.getElementById( "reply-link-option-dry-run" );
            if( window.replyLinkDryRun === "always" || ( dryRunCheckbox && dryRunCheckbox.checked ) ) {
                console.log( "~~~~~~ DRY RUN CONCLUDED ~~~~~~" );
                console.log( sectionWikitext );
                setStatus( "Check the console for the dry-run results." );
                document.querySelector( "#reply-link-buttons button" ).disabled = false;
                deferred.resolve();
                return deferred;
            }

            // Build summary
            var defaultSummmary = mw.msg( "rl-replying-to" ) +
                ( rplyToXfdNom ? xfdType + " nomination by " : "" ) +
                cmtAuthorWktxt +
                ( markedEditReq ? " and marking edit request as answered" : "" );
            var customSummaryField = document.getElementById( "reply-link-summary" );
            var summaryCore = defaultSummmary;
            if( window.replyLinkCustomSummary && customSummaryField.value ) {
                summaryCore = customSummaryField.value.trim();
            }
            var sectionId = sectionObj.headerEl ? sectionObj.headerEl.querySelector( "span.mw-headline" ).id : sectionObj.title;
            var summary = "/* " + sectionId.replace( /_/g, " " ) + " */ " + summaryCore + mw.msg( "rl-advert" );

            var editParams = {
                action: "edit",
                title: sectionObj.pageTitle,
                summary: summary,
                basetimestamp: revObj.timestamp,
            };

            if( canMakeSectionEdit && ( sectionObj.idxInDomHeaders !== null ) ) {
                editParams.section = sectionObj.idxInDomHeaders + 1;
                if( sectionWikitext.startsWith( oldSectionWikitext ) ) {
                    editParams.appendtext = "\n" + sectionWikitext.substring( oldSectionWikitext.length ).trim();
                } else {
                    editParams.text = sectionWikitext;
                }
            } else {
                var newWikitext = wikitext.replace( oldSectionWikitext, sectionWikitext );
                editParams.text = newWikitext;
            }

            // Send another request, this time to actually edit the page
            api.postWithEditToken( editParams ).done ( function ( data ) {

                // We put this function on the window object because we
                // give the user a "reload" link, and it'll trigger the function.
                // TODO goodness knows why I made this a property on the window object
                window.replyLinkReload = function () {
                    window.location.hash = sectionId;
                    var path = getPathToElement( cmtAuthorAndLink.link );
                    document.cookie = JUMP_COOKIE_KEY + "=" + path;
                    window.location.reload( true );
                };

                if ( data && data.edit && data.edit.result && data.edit.result == "Success" ) {
                    var needPurge = sectionObj.pageTitle !== currentPageName.replace( /_/g, " " );

                    function finishReply( _ ) {
                        if( canMakeSectionEdit && window.replyLinkAutoReload && window.replyLinkLoadNewInPlace ) {
                            performInPlaceReload( cmtAuthorAndLink.link, sectionObj );
                        } else {
                            var reloadHtml = window.replyLinkAutoReload ? mw.msg( "rl-reloading" )
                                : "<a href='javascript:window.replyLinkReload()' class='reply-link-reload'>" + mw.msg( "rl-reload" ) + "</a>";
                            setStatus( mw.msg( "rl-saved" ) + " (" + reloadHtml + ")" );

                            // Required to permit reload to happen, checked in onbeforeunload
                            replyWasSaved = true;

                            if( window.replyLinkAutoReload ) {
                                window.replyLinkReload();
                            }

                            deferred.resolve();
                        }
                    }

                    if( needPurge ) {
                        setStatus( "Reply saved! Purging..." );
                        api.post( { action: "purge", titles: currentPageName } ).done( finishReply );
                    } else {
                        finishReply();
                    }
                } else {
                    if( data && data.edit && data.edit.spamblacklist ) {
                        setStatus( "Error! Your post contained a link on the <a href=" +
                            "\"https://en.wikipedia.org/wiki/Wikipedia:Spam_blacklist\"" +
                            ">spam blacklist</a>. Remove the link(s) to: " +
                            data.edit.spamblacklist.split( "|" ).join( ", " ) + " to allow saving." );
                        document.querySelector( "#reply-link-buttons button" ).disabled = false;
                    } else {
                        setStatus( "While saving, the edit query returned an error." +
                            " Check the browser console for more information." );
                    }

                    deferred.reject();
                }
                //console.log(data);
                document.getElementById( "reply-dialog-field" ).style["background-image"] = "";
            } ).fail ( function( code, result ) {
                setStatus( mw.msg( "rl-edit-fail" ) );
                console.log(code);
                console.log(result);
                deferred.reject();
            } );
        } catch ( e ) {
            setStatusError( e );
            deferred.reject();
        }

        return deferred;
    }

    function checkCanMakeSectionEdit( sectionObj ) {
        var fullWikitext = sectionObj.revObj.content;

        if( sectionObj.idxInDomHeaders === null ) {
            return $.when( false );
        }

        // First, check if includeonly and noinclude are gonna ruin our day, by
        // seeing if there are any section headers inside includeonly and
        // noinclude elements.
        var disruptiveSectionRegex = /<(includeonly|noinclude)>[\s\S]+?==[\s\S]+?<\/(\1)>/;
        if( disruptiveSectionRegex.test( fullWikitext ) ) {
            return $.when( false );
        }

        return $.getJSON(
            mw.util.wikiScript( "api" ),
            {
                format: "json",
                action: "parse",
                prop: "wikitext",
                section: sectionObj.idxInDomHeaders + 1,
                page: sectionObj.pageTitle,
                formatversion: 2,
            }
        ).then( function ( parseResult ) {
            var parseSectionWikitext = parseResult.parse.wikitext;
            var officialSectionWikitext = fullWikitext.slice( sectionObj.startIdx, sectionObj.endIdx )
                .trim();
            // Trim because parseSectionWikitext also gets trimmed by the API
            if( officialSectionWikitext !== parseSectionWikitext ) {
                // Bit of debug info
                /*
                console.log( "oswlen",officialSectionWikitext.length,"pswlen",parseSectionWikitext.length );
                for ( var i = 0; i < Math.max( officialSectionWikitext.length, parseSectionWikitext.length ); i++  ) {
                    if( officialSectionWikitext[i] !== parseSectionWikitext[i] ) {
                        console.log( 'osw substr',
                            JSON.stringify( officialSectionWikitext.substring( i ) ),
                            'psw substr',
                            JSON.stringify( parseSectionWikitext.substring( i ) ) );
                        break;
                    }
                }
                */
            }
            return officialSectionWikitext === parseSectionWikitext;
        } );
    }

    function handleWrapperClick( linkLabel, parent, rplyToXfdNom, parentCmtObj, sectionObj ) {
        return function ( evt ) {
            $.when( mw.messages.exists( INT_MSG_KEYS[0] ) ? 1 :
                    api.loadMessages( INT_MSG_KEYS ) ).then( function () {
                var newLink = this;
                var newLinkWrapper = this.parentNode;

                buildUserspcLinkRgx();

                // Remove previous panel
                var prevPanel = document.getElementById( "reply-link-panel" );
                if( prevPanel ) {
                    prevPanel.remove();
                }

                // Reset previous cancel links
                var cancelLinks = iterableToList( document.querySelectorAll(
                            ".reply-link-wrapper a" ) );
                cancelLinks.forEach( function ( el ) {
                    if( el != newLink ) el.textContent = el.dataset.originalLabel;
                } );

                // Handle disable action
                if( newLink.textContent === linkLabel ) {

                    // Disable this link
                    newLink.textContent = mw.msg( "rl-cancel" ) + linkLabel;
                } else {

                    // We've already cancelled the reply
                    newLink.textContent = linkLabel;
                    evt.preventDefault();
                    return false;
                }

                // Figure out the username of the author
                // of the comment we're replying to
                var cmtAuthorAndLink = getCommentAuthor( newLinkWrapper );

                try {
                    var cmtAuthor = cmtAuthorAndLink.username,
                        cmtLink = cmtAuthorAndLink.link;
                } catch ( e ) {
                    setStatusError( e );
                }

                // Create panel
                var panelEl = document.createElement( "div" );
                panelEl.id = "reply-link-panel";
                panelEl.innerHTML = "<textarea id='reply-dialog-field' class='mw-ui-input'" +
                    " placeholder='" + mw.msg( "rl-placeholder" ) + "'></textarea>" +
                    ( window.replyLinkCustomSummary ? "<label for='reply-link-summary'>Summary: </label>" +
                        "<input id='reply-link-summary' class='mw-ui-input' placeholder='Edit summary' " +
                        "value='Replying to " + cmtAuthor.replace( /'/g, "&#39;" ) + "'/><br />" : "" ) +
                    "<table style='border-collapse:collapse'><tr><td id='reply-link-buttons' style='width: " +
                    ( window.replyLinkPreloadPing === "button" ? "325" : "255" ) + "px'>" +
                    "<button id='reply-dialog-button' class='mw-ui-button mw-ui-progressive'>" + mw.msg( "rl-reply" ) + "</button> " +
                    "<button id='reply-link-preview-button' class='mw-ui-button'>" + mw.msg( "rl-preview" ) + "</button>" +
                    ( window.replyLinkPreloadPing === "button" ?
                        " <button id='reply-link-ping-button' class='mw-ui-button'>Ping</button>" : "" ) +
                    "<button id='reply-link-cancel-button' class='mw-ui-button mw-ui-quiet mw-ui-destructive'>" + mw.msg( "rl-cancel-button" ) + "</button></td>" +
                    "<td id='reply-dialog-status'></span><div style='clear:left'></td></tr></table>" +
                    "<div id='reply-link-options' class='gone-on-empty' style='margin-top: 0.5em'></div>" +
                    "<div id='reply-link-preview' class='gone-on-empty' style='border: thin dashed gray; padding: 0.5em; margin-top: 0.5em'></div>";
                parent.insertBefore( panelEl, newLinkWrapper.nextSibling );
                var replyDialogField = document.getElementById( "reply-dialog-field" );
                replyDialogField.style = "padding: 0.625em; min-height: 10em; margin-bottom: 0.75em; line-height: 1.3";
                if( window.replyLinkPreloadPing === "always" &&
                        cmtAuthor &&
                        cmtAuthor !== mw.config.get( "wgUserName" ) &&
                        cmtAuthor !== mw.config.get( "wgRelevantUserName" ) &&
                        !/(\d+.){3}\d+/.test( cmtAuthor ) ) {
                    replyDialogField.value = window.replyLinkPreloadPingTpl.replace( "##", cmtAuthor );
                }

                // Fill up #reply-link-options
                function newOption( id, text, defaultOn ) {
                    var newCheckbox = document.createElement( "input" );
                    newCheckbox.type = "checkbox";
                    newCheckbox.id = id;
                    if( defaultOn ) {
                        newCheckbox.checked = true;
                    }
                    var newLabel = document.createElement( "label" );
                    newLabel.htmlFor = id;
                    newLabel.appendChild( document.createTextNode( text ) );
                    document.getElementById( "reply-link-options" ).appendChild( newCheckbox );
                    document.getElementById( "reply-link-options" ).appendChild( newLabel );
                }

                if( parentCmtObj.sigIdx === null && parentCmtObj.endStrIdx === null ) {
                    parentCmtObj.sigIdx = metadata[this.id].sigIdx;
                }

                // If the dry-run option is "checkbox", add an option to make it
                // a dry run
                if( window.replyLinkDryRun === "checkbox" ) {
                    newOption( "reply-link-option-dry-run", "Don't actually edit?", true );
                }

                // If the current section header text indicates an edit request,
                // offer to mark it as answered
                //if( ourMetadata[1] && EDIT_REQ_REGEX.test( ourMetadata[1][1] ) ) {
                //    newOption( "reply-link-option-edit-req", "Mark edit request as answered?", false );
                //}

                // If the previous comment was indented by OUTDENT_THRESH,
                // offer to outdent
                if( parentCmtObj.indentation.length >= OUTDENT_THRESH ) {
                    newOption( "reply-link-option-outdent", "Outdent?", false );
                }

                if( window.replyLinkAutoIndentation === "checkbox" ) {
                    newOption( "reply-link-option-auto-indent", mw.msg( "rl-auto-indent" ), true );
                }

                /* Commented out because I could never get it to work
                // Autofill with a recommendation if we're replying to a nom
                if( rplyToXfdNom ) {
                    replyDialogField.value = "'''Comment'''";

                    // Highlight the "Comment" part so the user can change it
                    var range = document.createRange();
                    range.selectNodeContents( replyDialogField );
                    //range.setStart( replyDialogField, 3 ); // start of "Comment"
                    //range.setEnd( replyDialogField, 10 ); // end of "Comment"
                    var sel = window.getSelection();
                    sel.removeAllRanges();
                    sel.addRange( range );
                }*/

                // Close handler
                window.onbeforeunload = function ( e ) {
                    if( !replyWasSaved &&
                            document.getElementById( "reply-dialog-field" ) &&
                            document.getElementById( "reply-dialog-field" ).value ) {
                        var txt = mw.msg( "rl-started-reply" );
                        e.returnValue = txt;
                        return txt;
                    }
                };

                // Start loading in the section object, so we don't have to do it in startReply
                try {
                    var sectionObjPromise = ( sectionObj === null ) ? findSectionMain( cmtLink ) : $.when( sectionObj );
                } catch ( e ) {
                    console.error( e );
                    setStatus( "Error locating the section: " + e );
                    document.querySelector( "#reply-link-buttons button" ).disabled = true;
                }

                // Also, check if we can get away with sending just a section edit
                var canMakeSectionEditPromise = sectionObjPromise.then( checkCanMakeSectionEdit );

                // Called by the "Reply" button, Ctrl-Enter in the text area, and
                // Enter/Ctrl-Enter in the summary field
                function startReply() {

                    // Change UI to make it clear we're performing an operation
                    document.getElementById( "reply-dialog-field" ).style["background-image"] =
                        "url(" + window.replyLinkPendingImageUrl + ")";
                    document.querySelector( "#reply-link-buttons button" ).disabled = true;
                    setStatus( mw.msg( "rl-loading" ) );

                    var revidCheckPromise = sectionObjPromise.then( function ( sectionObj ) {
                        return getLastRevId( sectionObj.pageTitle );
                    } );

                    $.when(
                        sectionObjPromise,
                        revidCheckPromise,
                        canMakeSectionEditPromise,
                    ).then( function ( sectionObj, currentRevId, canMakeSectionEdit ) {
                        if( currentRevId > sectionObj.pageRevId ) {
                            // Someone's edited this page since we parsed it
                            setStatus( mw.msg( "rl-out-of-date" ) );
                        } else {
                            doReply(
                                parentCmtObj,
                                cmtAuthorAndLink,
                                rplyToXfdNom,
                                sectionObj,
                                canMakeSectionEdit
                            );
                        }
                    }, function ( err ) {
                        console.error( err );
                        setStatus( "Error (async), probably while locating the section: " + err );
                    } );
                }

                // Event listener for the "Reply" button
                document.getElementById( "reply-dialog-button" )
                    .addEventListener( "click", startReply );

                // Event listener for the text area
                document.getElementById( "reply-dialog-field" )
                    .addEventListener( "keydown", function ( e ) {
                        if( e.ctrlKey && ( e.keyCode == 10 || e.keyCode == 13 ) ) {
                            startReply();
                        }
                    } );

                // Event listener for the "Preview" button
                document.getElementById( "reply-link-preview-button" )
                    .addEventListener( "click", function () {
                        var reply = document.getElementById( "reply-dialog-field" ).value.trim();

                        // Add a signature if one isn't already there
                        if( !hasSig( reply ) ) {
                            reply += " " + ( window.replyLinkSigPrefix ?
                                window.replyLinkSigPrefix : "" ) + LITERAL_SIGNATURE;
                        }

                        var sanitizedCode = encodeURIComponent( reply );
                        sectionObjPromise.then( function ( sectionObj ) {
                            $.post( "https:" + mw.config.get( "wgServer" ) +
                                "/w/api.php?action=parse&format=json&title=" +
                                    encodeURIComponent( sectionObj.pageTitle ) + "&text=" + sanitizedCode +
                                    "&pst=1&prop=text&formatversion=2",
                                function ( res ) {
                                    if ( !res || !res.parse || !res.parse.text ) return console.error( "Preview failed" );
                                    document.getElementById( "reply-link-preview" ).innerHTML = res.parse.text;
                                    // Add target="_blank" to links to make them open in a new tab by default
                                    var links = document.querySelectorAll( "#reply-link-preview a" );
                                    for( var i = 0, n = links.length; i < n; i++ ) {
                                        links[i].setAttribute( "target", "_blank" );
                                    }
                                } );
                        } );
                    } );

                if( window.replyLinkPreloadPing === "button" ) {
                    document.getElementById( "reply-link-ping-button" )
                        .addEventListener( "click", function () {
                            var cmtAuthorEscaped = cmtAuthor.replace( /=/g, "{{=}}" );
                            replyDialogField.value = window.replyLinkPreloadPingTpl
                                .replace( "##", cmtAuthorEscaped ) + replyDialogField.value;
                        } );
                }

                // Event listener for the "Cancel" button
                document.getElementById( "reply-link-cancel-button" )
                    .addEventListener( "click", function () {
                        newLink.textContent = linkLabel;
                        panelEl.remove();
                    } );

                // Event listeners for the custom edit summary field
                if( window.replyLinkCustomSummary ) {
                    document.getElementById( "reply-link-summary" )
                        .addEventListener( "keydown", function ( e ) {
                            if( e.keyCode == 10 || e.keyCode == 13 ) {
                                startReply();
                            }
                        } );
                }

                if( newLinkWrapper.dataset.replyLinkInstant === true ) {
                    startReply();
                    newLinkWrapper.dataset.replyLinkInstant = false;
                }

                if( window.replyLinkTestInstantReply ) {
                    startReply();
                }
            }.bind( this ) );

            // Cancel default event handler
            evt.preventDefault();
            return false;
        }
    }

    /**
     * Adds a "(reply)" link after the provided text node, giving it
     * the provided element id. anyIndentation is true if there's any
     * indentation (i.e. indentation string is not the empty string)
     */
    function attachLinkAfterNode( node, preferredId, parentCmtObj, sectionObj ) {

        // Choose a parent node - walk up tree until we're under a dd, li,
        // p, or div. This walk is a bit unsafe, but this function should
        // only get called in a place where the walk will succeed.
        var parent = node;
        do {
            parent = parent.parentNode;
        } while( !( /^(p|dd|li|div|td)$/.test( parent.tagName.toLowerCase() ) ) );

        // Determine whether we're replying to an XfD nom
        var rplyToXfdNom = false;
        if( xfdType === "AfD" || xfdType === "MfD" ) {

            // If the parent comment is non-indented, we are replying to a nom
            rplyToXfdNom = !parentCmtObj.sigIdx;
        } else if( xfdType === "TfD" || xfdType === "FfD" ) {

            // If the sibling before the previous sibling of this node
            // is a h4, then this is a nom
            rplyToXfdNom = parent.previousElementSibling &&
                parent.previousElementSibling.previousElementSibling &&
                parent.previousElementSibling.previousElementSibling.nodeType === 1 &&
                parent.previousElementSibling.previousElementSibling.tagName.toLowerCase() === "h4";
        } else if( xfdType === "CfD" ) {

            // If our grandparent is a dl and our grandparent's previous
            // sibling is a h4, then this is a nom
            rplyToXfdNom = parent.parentNode.tagName.toLowerCase() === "dl" &&
                parent.parentNode.previousElementSibling.nodeType === 1 &&
                parent.parentNode.previousElementSibling.tagName.toLowerCase() === "h4";
        }

        // Choose link label: if we're replying to an XfD, customize it
        var linkLabel = mw.msg( "rl-reply-label" ) + ( rplyToXfdNom ? mw.msg( "rl-to-label" ) + xfdType : "" );

        // Construct new link
        var newLinkWrapper = document.createElement( "span" );
        newLinkWrapper.className = "reply-link-wrapper";
        var newLink = document.createElement( "a" );
        newLink.href = "#";
        newLink.id = preferredId;
        newLink.dataset.originalLabel = linkLabel;
        newLink.appendChild( document.createTextNode( linkLabel ) );
        newLink.addEventListener( "click", handleWrapperClick( linkLabel, parent, rplyToXfdNom, parentCmtObj, sectionObj ) );
        newLinkWrapper.appendChild( document.createTextNode( " (" ) );
        newLinkWrapper.appendChild( newLink );
        newLinkWrapper.appendChild( document.createTextNode( ")" ) );

        // Insert new link into DOM
        parent.insertBefore( newLinkWrapper, node.nextSibling );
    }

    /**
     * Uses attachLinkAfterTextNode to add a reply link after every
     * timestamp on the page.
     */
    function attachLinks () {
        var mainContent = findMainContentEl();
        if( !mainContent ) {
            console.error( "No main content element found; exiting." );
            return;
        }

        var contentEls = mainContent.children;

        // Find the index of the first header in contentEls
        var headerIndex = 0;
        for( headerIndex = 0; headerIndex < contentEls.length; headerIndex++ ) {
            if( contentEls[ headerIndex ].matches( HEADER_SELECTOR ) ) break;
        }

        // If we didn't find any headers at all, that's a problem and we
        // should bail
        if( mainContent.querySelector( "div.hover-edit-section" ) ) {
            headerIndex = 0;
        } else if( headerIndex === contentEls.length ) {
            console.error( "Didn't find any headers - hit end of loop!" );
            return;
        }

        // We also should include the first header
        if( headerIndex > 0 ) {
            headerIndex--;
        }

        // Each element is a 2-element list of [level, node]
        var parseStack = iterableToList( contentEls ).slice( headerIndex );
        parseStack.reverse();
        parseStack = parseStack.map( function ( el ) { return [ "", el ]; } );

        // Main parse loop
        var node;
        var currIndentation; // A string of symbols, like ":*::"
        var newIndentSymbol;
        var stackEl; // current element from the parse stack
        var idNum = 0; // used to make id's for the links
        var linkId = ""; // will be the element id for this link
        while( parseStack.length ) {
            stackEl = parseStack.pop();
            node = stackEl[1];
            currIndentation = stackEl[0];

            // Compatibility with "Comments in Local Time"
            var isLocalCommentsSpan = node.nodeType === 1 &&
                "span" === node.tagName.toLowerCase() &&
                node.className.includes( "localcomments" );

            var isSmall = node.nodeType === 1 && (
                    node.tagName.toLowerCase() === "small" ||
                    ( node.tagName.toLowerCase() === "span" &&
                    node.style && node.style.getPropertyValue( "font-size" ) === "85%" ) );

            // Small nodes are okay, unless they're delsort notices
            var isOkSmallNode = isSmall &&
                !node.className.includes( "delsort-notice" );

            if( ( node.nodeType === 3 ) ||
                    isOkSmallNode ||
                    isLocalCommentsSpan )  {

                // If the current node has a timestamp, attach a link to it
                // Also, no links after timestamps, because it's just like
                // having normal text afterwards, which is rejected (because
                // that means someone put a timestamp in the middle of a
                // paragraph)
                var hasLinkAfterwardsNotInBlockEl = node.nextElementSibling &&
                    ( node.nextElementSibling.tagName.toLowerCase() === "a" ||
                        ( node.nextElementSibling.tagName.match( /^(span|small)$/i ) &&
                            node.nextElementSibling.querySelector( "a" ) ) );
                if( TIMESTAMP_REGEX.test( node.textContent ) &&
                        ( node.previousSibling || isSmall ) &&
                        !hasLinkAfterwardsNotInBlockEl ) {
                    linkId = "reply-link-" + idNum;
                    var parentCmtObj = {
                        indentation: currIndentation,
                        sigIdx: null,
                        endStrIdx: null
                    };
                    attachLinkAfterNode( node, linkId, parentCmtObj, /* sectionObj */ null );
                    idNum++;

                    // Update global metadata dictionary
                    metadata[linkId] = {};
                    //metadata[linkId].indentation = currIndentation; // It's already being passed into attachLinkAfterNode
                }
            } else if( node.nodeType === 1 &&
                    /^(div|p|dl|dd|ul|li|span|ol|table|tbody|tr|td)$/.test( node.tagName.toLowerCase() ) ) {
                switch( node.tagName.toLowerCase() ) {
                    case "dl": newIndentSymbol = ":"; break;
                    case "ul": newIndentSymbol = "*"; break;
                    case "ol": newIndentSymbol = "#"; break;
                    case "div":
                        if( node.className.includes( "xfd_relist" ) || node.className.includes( "thumbcaption" ) ) {
                            continue;
                        }
                        break;
                    default: newIndentSymbol = ""; break;
                }

                var childNodes = node.childNodes;
                for( let i = 0, numNodes = childNodes.length; i < numNodes; i++ ) {
                    parseStack.push( [ currIndentation + newIndentSymbol,
                        childNodes[i] ] );
                }
            }
        }

        // This loop adds sigIdx entries in the metadata dictionary
        var sigIdxEls = iterableToList( mainContent.querySelectorAll(
                HEADER_SELECTOR + ",span.reply-link-wrapper a" ) );
        var currSigIdx = 0, j, numSigIdxEls, currHeaderEl, currHeaderData;
        var headerIdx = 0; // index of the current header
        var headerLvl = 0; // level of the current header
        for( j = 0, numSigIdxEls = sigIdxEls.length; j < numSigIdxEls; j++ ) {
            var headerTagNameMatch = /^h(\d+)$/.exec(
                sigIdxEls[j].tagName.toLowerCase() );
            if( headerTagNameMatch ) {
                currHeaderEl = sigIdxEls[j];

                // Test to make sure we're not in the table of contents
                if( currHeaderEl.parentNode.className === "toctitle" ) {
                    continue;
                }

                // Reset signature counter
                currSigIdx = 0;
            } else {
                metadata[ sigIdxEls[j].id ].sigIdx = currSigIdx;
                currSigIdx++;
            }
        }

        // Disable links inside hatnotes, archived discussions
        var badRegionsSelector = "div.archived,div.resolved,table";
        var badRegions = mainContent.querySelectorAll( badRegionsSelector );
        for( var i = 0; i < badRegions.length; i++ ) {
            var badRegion = badRegions[i];
            var insideArchived = badRegion.querySelectorAll( ".reply-link-wrapper" );
            for( var j = 0; j < insideArchived.length; j++ ) {
                insideArchived[j].parentNode.removeChild( insideArchived[j] );
            }
        }
    }

    function runTestMode() {

        // We never want to make actual edits
        window.replyLinkDryRun = "always";

        // Simulate having a panel open
        $( "#mw-content-text" )
            .append( $( "<div>" )
                .append( $( "<textarea>" ).attr( "id", "reply-dialog-field" ).val( "hi" ) )
                .append( $( "<div>" ).attr( "id", "reply-link-buttons" )
                    .append( $( "<button> " ) ) ) );

        mw.util.addCSS( ".reply-link-wrapper { background-color: orange; }" );

        api.loadMessages( INT_MSG_KEYS ).then( function () {
            buildUserspcLinkRgx();

            // Statistics variables
            var successes = 0, failures = 0;

            // Run one test on a wrapper link
            function runOneTestOn( wrapper ) {
                try {
                    var cmtAuthorAndLink = getCommentAuthor( wrapper );
                    var ourMetadata = metadata[ wrapper.children[0].id ];
                    findSectionMain( cmtAuthorAndLink.link ).then( function ( sectionObj ) {
                        doReply(
                            ourMetadata.indentation,
                            ourMetadata.sigIdx,
                            cmtAuthorAndLink,
                            /* rplyToXfdNom */ false,
                            sectionObj
                        ).done( function () {
                            wrapper.style.background = "green";
                            successes++;
                        } ).fail( function () {
                            wrapper.style.background = "red";
                            failures++;
                        } );
                    } );
                } catch ( e ) {
                    console.error( e );
                    wrapper.style.background = "red";
                    failures++;
                }
            }

            var wrappers = Array.from( document.querySelectorAll( ".reply-link-wrapper" ) );
            function runOneTest() {
                var wrapper = wrappers.shift();
                if( wrapper ) {
                    runOneTestOn( wrapper );
                    setTimeout( runOneTest, 250 );
                } else {
                    var results = successes + " successes, " + failures + " failures";
                    $( "#mw-content-text" ).prepend( results ).append( results );
                }
            }
            //console.log = function() {};
            setTimeout( runOneTest, 0 );
        } );
    }

    function onReady() {
        var lang_code = mw.config.get( "wgUserLanguage" )
        // Replace default English interface by translation if available
        var interface_messages = $.extend( {}, i18n.en, i18n[ lang_code.split('-')[0] ], i18n[ lang_code ] );
        // Define interface messages
        mw.messages.set( interface_messages );

        // Exit if history page or edit page or oldid
        if( mw.config.get( "wgAction" ) === "history" ) return;
        if( document.getElementById( "editform" ) ) return;
        if( window.location.search.includes( "oldid=" ) ) return;

        api = new mw.Api();

        mw.util.addCSS(
            "#reply-link-panel { padding: 1em; margin-left: 1.6em; "+
              "max-width: 1200px; width: 66%; margin-top: 0.5em; }"+
            ".gone-on-empty:empty { display: none; }"
        );
        mw.loader.load( "https://en.wikipedia.org/w/index.php?title=User:Enterprisey/mw-ui-button.css&action=raw&ctype=text/css", "text/css" );

        // Pre-load interface messages; we will check again when a (reply)
        // link is clicked
        api.loadMessages( INT_MSG_KEYS );

        // Initialize the xfdType global variable, which must happen
        // before the call to attachLinks
        currentPageName = mw.config.get( "wgPageName" );
        xfdType = "";
        if( mw.config.get( "wgNamespaceNumber" ) === 4) {
            if( currentPageName.startsWith( "Wikipedia:Articles_for_deletion/" ) ) {
                xfdType = "AfD";
            } else if( currentPageName.startsWith( "Wikipedia:Miscellany_for_deletion/" ) ) {
                xfdType = "MfD";
            } else if( currentPageName.startsWith( "Wikipedia:Templates_for_discussion/Log/" ) ) {
                xfdType = "TfD";
            } else if( currentPageName.startsWith( "Wikipedia:Categories_for_discussion/Log/" ) ) {
                xfdType = "CfD";
            } else if( currentPageName.startsWith( "Wikipedia:Files_for_discussion/" ) ) {
                xfdType = "FfD";
            }
        }

        // Default values for some preferences
        function defaultValue( prefName, defaultValue ) { if( window[prefName] === undefined ) window[prefName] = defaultValue; }
        defaultValue( "replyLinkAutoReload",       !isOnSectionWatchlistPage );
        defaultValue( "replyLinkDryRun",           "never" );
        defaultValue( "replyLinkPreloadPing",      "always" );
        defaultValue( "replyLinkPreloadPingTpl",   "{{u|##}}, " );
        defaultValue( "replyLinkCustomSummary",    false );
        defaultValue( "replyLinkTestMode",         false );
        defaultValue( "replyLinkTestInstantReply", false );
        defaultValue( "replyLinkAutoIndentation",  "checkbox" );
        defaultValue( "replyLinkLoadNewInPlace",   true );

        // Insert "reply" links into DOM
        if( !isOnSectionWatchlistPage ) {
            attachLinks();
        }

        // If test mode is enabled, create a link for that
        if( window.replyLinkTestMode &&
                document.getElementsByClassName( "reply-link-sig-check-container" ).length === 0 ) {
            mw.util.addPortletLink( "p-cactions", "#", "reply-link test mode", "pt-reply-link-test" )
                .addEventListener( "click", runTestMode );

            var dryRunToCheckboxLink = mw.util.addPortletLink( "p-cactions", "#",
                    "reply-link: dry-run = checkbox", "pt-reply-link-dry-run-checkbox",
                    "Set window.replyLinkDryRun to 'checkbox'" )
                .addEventListener( "click", function () { window.replyLinkDryRun = "checkbox" } );

            // Also add "sig check" links to each section header
            $( "#mw-content-text" ).find( HEADER_SELECTOR ).each( function ( idx, header ) {
                $( header ).find( ".mw-editsection *" ).last().before(
                    "<span style='color: #54595d'> | </span>",
                    $( "<span>", { "class": "reply-link-sig-check-container" } ).append(
                        $( "<a>" )
                            .attr( "href", "#" )
                            .text( "sig check" )
                            .click( function () {
                                buildUserspcLinkRgx();
                                var sigEls = $( header ).nextUntil( HEADER_SELECTOR ).find( '.reply-link-wrapper' ).toArray();
                                findSectionMain( sigEls[0] ).then( function ( sectionObj ) {
                                    var sectionWikitext = sectionObj.revObj.content.substring( sectionObj.startIdx, sectionObj.endIdx );
                                    for( var sigIdx = 0; sigIdx < sigEls.length; sigIdx++ ) {
                                        var strIndices = sigIdxToStrIdx( sectionWikitext, sigIdx );
                                        var sigText = sectionWikitext.substring( strIndices.start, strIndices.end );
                                        $( sigEls[sigIdx] ).last().before( " ", $( "<abbr>", { title: sigText } ).text( sigText.substring( sigText.length - 50 ) ) );
                                    }
                                } );
                                return false;
                            } ) ) );
            } );
        }

        // This large string creats the "pending" texture
        window.replyLinkPendingImageUrl = "data:image/gif;base64,R0lGODlhGAAYAKIGAP7+/vv7+/Ly8u/v7+7u7v///////wAAACH/C05FVFNDQVBFMi4wAwEAAAAh+QQFAAAGACwAAAAAGAAYAAADU0hKAvUwvjCWbTIXahfWEdcxDgiJ3Wdu1UiUK5quUzuqoHzBuZ3yGp0HmBEqcEHfjmYkMZXDp8sZgx6JkiayaKWatFhJd1uckrPWcygdXrvUJ1sCACH5BAUAAAYALAAAAAAYABgAAANTSLokUDBKGAZbbupSr8qb1HlgSFnkY55eo67jVZoxM4c189IoubKtmyaH2W2IH+OwJ1NOkK4fVPhk2pwia1GqTXJbUVg3zANTs2asZHwWpX+cQQIAIfkEBQAABgAsAAAAABgAGAAAA1E4tLwCJcoZQ2uP6hLUJdk2dR8IiRL5hSjnXSyqwmc7Y7X84m21MzHRrZET/oA9V8nUGwKLGqcDSpEybcdpM3vVLYNRLrgqpo7K2685hcaqkwkAIfkEBQAABgAsAAAAABgAGAAAA1RYFUP+TgBFq2IQSstxjhNnNR+xiVVQmiF6kdnpLrDWul58o7k9vyUZrvYQ8oigHy24E/UgzQ4yonwWo6kp62dNzrrbr9YoXZEt4HPWjKWk20CmKwEAIfkEBQAABgAsAAAAABgAGAAAA1NYWjH08Amwam0xTstxlhR3OR+xiYv3nahCrmHLlGbcqpqN4hB7vzmZggcSMoA9nYhYMzJ9O2RRyCQoO1KJM9uUVaFYGtjyvY7E5hR3fC6x1WhRAgAh+QQFAAAGACwAAAAAGAAYAAADVFi6FUMwQgGYVU5Kem3WU9UtH8iN2AMSJ1pq7fhuoquaNXrDubyyvc4shCLtIjHZkVhsLIFN5yopfFIvQ2gze/U8CUHsVxDNam2/rjEdZpjVKTYjAQAh+QQFAAAGACwAAAAAGAAYAAADU1i6G0MwQgGYVU5Kem3WU9U1D0hwI1aCaPqxortq7fjSsT1veXfzqcUuUrOZTj3fEBlUmYrKZ/LyCzULVWYzC6Uuu57vNHwcM7KnKxpMOrKdUkUCACH5BAUAAAYALAAAAAAYABgAAANTWLqsMSTKKEC7b856W9aU1S0fyI0OBBInWmrt+G6iq5q1fMN5N0sx346GSq1YPcwQmLwsQ0XHMShcUZXWpud53WajhR8SLO4yytozN016EthGawIAIfkEBQAABgAsAAAAABgAGAAAA1MoUNzOYZBJ53o41ipwltukeI4WEiMJgWGqmu31sptLwrV805zu4T3V6oTyfYi2H4+SPJ6aDyDTiFmKqFEktmSFRrvbhrQoHMbKhbGX+wybc+hxAgAh+QQFAAAGACwAAAAAGAAYAAADVEgqUP7QhaHqajFPW1nWFEd4H7SJBFZKoSisz+mqpcyRq23hdXvTH10HCEKNiBHhBVZQHplOXtC3Q5qoQyh2CYtaIdsn1CidosrFGbO5RSfb35gvAQAh+QQFAAAGACwAAAAAGAAYAAADU0iqAvUwvjCWbTIXahfWEdcRHzhVY2mKnQqynWOeIzPTtZvBl7yiKd8L2BJqeB7jjti7IRlKyZMUDTGTzis0W6Nyc1XIVJfRep1dslSrtoJvG1QCACH5BAUAAAYALAAAAAAYABgAAANSSLoqUDBKGAZbbupSb3ub1HlZGI1XaXIWCa4oo5ox9tJteof1sm+9xoqS0w2DhBmwKPtNkEoN1Cli2o7WD9ajhWWT1NM3+hyHiVzwlkuemIecBAAh+QQFAAAGACwAAAAAGAAYAAADUxhD3CygyEnlcg3WXQLOEUcpH6GJE/mdaHdhLKrCYTs7sXiDrbQ/NdkLF9QNHUXO79FzlUzJyhLam+Y21ujoyLNxgdUv1fu8SsXmbVmbQrN97l4CACH5BAUAAAYALAAAAAAYABgAAANSWBpD/k4ARetq8EnLWdYTV3kfsYkV9p3oUpphW5AZ29KQjeKgfJU6ES8Su6lyxd2x5xvCfLPlIymURqDOpywbtHCpXqvW+OqOxGbKt4kGn8vuBAAh+QQFAAAGACwAAAAAGAAYAAADU1iqMfTwCbBqbTFOy3GWFHc5H7GJi/edaKFmbEuuYeuWZt2+UIzyIBtjptH9iD2jCJgTupBBIdO3hDalVoKykxU4mddddzvCUS3gc7mkTo2xZmUCACH5BAUAAAYALAAAAAAYABgAAANTWLoaQzBCAZhtT0Z6rdNb1S0fSHAjZp5iWoKom8Ht+GqxPeP1uEs52yrYuYVSpN+kV1SykCoatGBcTqtPKJZ42TK7TsLXExZcy+PkMB2VIrHZQgIAIfkEBQAABgAsAAAAABgAGAAAA1RYuhxDMEIBmFVOSnpt1lPVLR/IjdgDEidaau34bqKrmrV8w3k3RzHfjoZaDIE934qVvPyYxdQqKJw2PUdo9El1ZrtYa7TAvTayBDMJLRg/tbYlJwEAIfkEBQAABgAsAAAAABgAGAAAA1IItdwbg8gphbsFUioUZtpWeV8WiURXPqeorqFLfvH2ljU3Y/l00y3b7tIbrUyo1NBRVB6bv09Qd8wko7yp8al1clFYYjfMHC/L4HOjSF6bq80EACH5BAUAAAYALAAAAAAYABgAAANTSALV/i0MQqtiMEtrcX4bRwkfFIpL6Zxcqhas5apxNZf16OGTeL2wHmr3yf1exltR2CJqmDKnCWqTgqg6YAF7RPq6NKxy6Rs/y9YrWpszT9fAWgIAOw==";


        // Respond to any [[User:Enterprisey/reply-link auto instant reply]] transclusions
        var autoReplies = document.querySelectorAll( ".reply-link-auto-instant-reply" );
        if( autoReplies.length > 0 ) {
            window.replyLinkTestInstantReply = true;
        }
        for( var i = 0; i < autoReplies.length; i++ ) {
            var el = autoReplies[i];
            while( el && el.className !== "reply-link-wrapper" ) {
                el = el.nextElementSibling;
            }
            if( el ) {
                el.dataset.replyLinkInstant = true;
                el.querySelector( "a" ).click();
            }
        }

        // Jump CSS
        mw.loader.addStyleTag( "@keyframes reply-link-jump-highlight-keyframes { from { background-color: #ffb; } to { background-color: transparent; } } .reply-link-jump-highlight { animation: reply-link-jump-highlight-keyframes  2s; }" );

        // Timeout to give other scripts time to load
        setTimeout( function () {

            // If there's an element to jump to, jump to it
            var jumpCookieIdx = document.cookie.indexOf( JUMP_COOKIE_KEY );
            if( jumpCookieIdx >= 0 ) {
                try {
                    var path = new RegExp( JUMP_COOKIE_KEY + "=([^;]+)" ).exec( document.cookie )[1];
                    var el = followPathToElement( path );
                    el.scrollIntoView();
                    highlightContainerOf( el );
                } catch( e ) { console.error(e); }
                document.cookie = JUMP_COOKIE_KEY + "=; expires=Thu, 01 Jan 1970 00:00:01 GMT";
            }
        }, 500 );
    } // end function onReady

    mw.loader.load( "mediawiki.ui.input", "text/css" );
    mw.loader.using( [ "mediawiki.util", "mediawiki.api" ] ).then( function () {
        mw.hook( "wikipage.content" ).add( onReady );
        if( isOnSectionWatchlistPage ) {
            mw.hook( "replylink.attachlinkafter" ).add( attachLinkAfterNode );
        }
    } );

    // Return functions for testing
    return {
        "iterableToList": iterableToList,
        "sigIdxToStrIdx": sigIdxToStrIdx,
        "insertTextAfterIdx": insertTextAfterIdx,
        "wikitextToTextContent": wikitextToTextContent
    };
}

// Export functions for testing
if( typeof module === typeof {} ) {
    module.exports = { "loadReplyLink": loadReplyLink };
}

// If we're in the right environment, load the script
if( jQuery !== undefined && mediaWiki !== undefined ) {
    var currNamespace = mw.config.get( "wgNamespaceNumber" );

    // Also enable on T:TDYK and its subpages
    var ttdykPage = mw.config.get( "wgPageName" ).indexOf( "Template:Did_you_know_nominations" ) === 0;

    // Normal "read" view and not a diff view
    var normalView = mw.config.get( "wgIsArticle" ) &&
            !mw.config.get( "wgDiffOldId" );

    if( normalView && ( currNamespace % 2 === 1 || currNamespace === 4 || ttdykPage ) ) {
        loadReplyLink( jQuery, mediaWiki );
    }

    if( currNamespace === -1 && ( mw.config.get( "wgTitle" ) === "BlankPage/section-watchlist" ) ) {
        loadReplyLink( jQuery, mediaWiki, /* section-watchlist */ true );
    }
}
//</nowiki>