پرش به محتوا

مدیاویکی:Gadget-Extra-Editbuttons-persianwikitools.js: تفاوت میان نسخه‌ها

از دانشنامه علوم انسانی
imported>علیرضا
+addColumnToRefTemplate()
imported>علیرضا
اصلاح ویرایش قبل + reindent + اصلاح‌های جزئی برای کدنویسی بهتر
خط ۷: خط ۷:
/*global persianTools, persianToolsDictionary, autoEd, console*/
/*global persianTools, persianToolsDictionary, autoEd, console*/
var persianWikiTools = (function () {
var persianWikiTools = (function () {
'use strict';
    'use strict';


function descendingFromComparetor(x, y) {
    function descendingFromComparetor(x, y) {
return x.from - y.from;
        return x.from - y.from;
}
    }


function replaceExcept(text, callback, excepts) {
    function replaceExcept(text, callback, excepts) {
var match, result = [], i, ranges, minRange, to, min, max;
        var match, result = [],
while (text !== '') {
            i, ranges, minRange, to, min, max;
ranges = [];
        while (text !== '') {
            ranges = [];


for (i in excepts) {
            for (i in excepts) {
if (excepts.hasOwnProperty(i)) {
                if (excepts.hasOwnProperty(i)) {
// a global regex should be reset before calls
                    // a global regex should be reset before calls
excepts[i].lastIndex = 0;
                    excepts[i].lastIndex = 0;
match = excepts[i].exec(text);
                    match = excepts[i].exec(text);
if (match !== null) {
                    if (match !== null) {
ranges.push({
                        ranges.push({
from: match.index,
                            from: match.index,
to: match.index + match[0].length
                            to: match.index + match[0].length
});
                        });
}
                    }
}
                }
}
            }


// so nothing is matched
            // so nothing is matched
if (ranges.length === 0) {
            if (ranges.length === 0) {
result.push(callback(text));
                result.push(callback(text));
break;
                break;
}
            }


minRange = ranges.sort(descendingFromComparetor)[0];
            minRange = ranges.sort(descendingFromComparetor)[0];
min = minRange.from;
            min = minRange.from;


to = [];
            to = [];
for (i in ranges) {
            for (i in ranges) {
if (ranges.hasOwnProperty(i)) {
                if (ranges.hasOwnProperty(i)) {
if (ranges[i].from <= minRange.to) {
                    if (ranges[i].from <= minRange.to) {
to.push(ranges[i].to);
                        to.push(ranges[i].to);
}
                    }
}
                }
}
            }
max = Math.max.apply(null, to);
            max = Math.max.apply(null, to);


result.push(callback(text.substr(0, min)));
            result.push(callback(text.substr(0, min)));
result.push(text.substr(min, max - min));
            result.push(text.substr(min, max - min));
// console.log('Excepted: "' + text.substr(min, max - min) + '"');
            // console.log('Excepted: "' + text.substr(min, max - min) + '"');
text = text.substr(max);
            text = text.substr(max);
}
        }
return result.join('');
        return result.join('');
}
    }


var patterns = {
    var patterns = {
arabicDigitsEnglishContext: /[a-z][a-z %"'\._:\|,\-\\\/\(\)\#\^\+\d><–\[\]&?{}]*\d|(\d|[a-z])[a-z %"'\._:\|,\-\\\/\(\)\#\^\+\d><–\[\]&?{}]*[a-z]\d*/gi,
        arabicDigitsEnglishContext: /[a-z][a-z %"'\._:\|,\-\\\/\(\)\#\^\+\d><–\[\]&?{}]*\d|(\d|[a-z])[a-z %"'\._:\|,\-\\\/\(\)\#\^\+\d><–\[\]&?{}]*[a-z]\d*/gi,
arabicTagEnclosed: /\{\{(?:عربی|شروع عربی|آغاز عربی)\}\}([\s\S]*?)\{\{(?:پایان عربی)\}\}/g,
        arabicTagEnclosed: /\{\{(?:عربی|شروع عربی|آغاز عربی)\}\}([\s\S]*?)\{\{(?:پایان عربی)\}\}/g,
argumentsBlacklist: /(?:accessdate|namespace|doi|style|شابک|عرض|bibcode|isbn|pmid|arxiv)\s*\=\s*[^\|\}]*/gi,
        argumentsBlacklist: /(?:accessdate|namespace|doi|style|شابک|عرض|bibcode|isbn|pmid|arxiv)\s*\=\s*[^\|\}]*/gi,
color: /#(?:[abcdef0-9]{8}|[abcdef0-9]{6}|[abcdef0-9]{3})/gi,
        color: /#(?:[abcdef0-9]{8}|[abcdef0-9]{6}|[abcdef0-9]{3})/gi,
colorAsParameter: /\=\s*(?:[abcdef0-9]{8}|[abcdef0-9]{6}|[abcdef0-9]{3})(?:[\s\|\}]|$)/gi,
        colorAsParameter: /\=\s*(?:[abcdef0-9]{8}|[abcdef0-9]{6}|[abcdef0-9]{3})(?:[\s\|\}]|$)/gi,
// space, ", \t, \n, {, |, }, ... they will interfere with wiki markup
        // space, ", \t, \n, {, |, }, ... they will interfere with wiki markup
decodeUriBlacklist: /(?:%20|%5C|%5E|%60|%23|%25|%3C|%3E|%5B|%5D|%22|%09|%0A|%7B|%7C|%7D)/gi,
        decodeUriBlacklist: /(?:%20|%5C|%5E|%60|%23|%25|%3C|%3E|%5B|%5D|%22|%09|%0A|%7B|%7C|%7D)/gi,
englishDate: /\d{1,2},? [a-z]{3,} \d{2,4}/gi, // 3, May 2013
        englishDate: /\d{1,2},? [a-z]{3,} \d{2,4}/gi, // 3, May 2013
fileNames: /(?:پرونده|File|تصویر|Image)\:.*?(?=\||\]|\n|$)/gi, // don't capture | after
        fileNames: /(?:پرونده|File|تصویر|Image)\:.*?(?=\||\]|\n|$)/gi, // don't capture | after
fileParameter: /\|\s*(image|تصویر)\s*\=\s*.*/g,
        fileParameter: /\|\s*(image|تصویر)\s*\=\s*.*/g,
ipSign: /\[\[ویژه:مشارکت\u200cها.*?\]\]/g,
        ipSign: /\[\[ویژه:مشارکت\u200cها.*?\]\]/g,
isbn: /ISBN [\d\-]*/gi,
        isbn: /ISBN [\d\-]*/gi,
galleryTag: /<gallery.*?>[\s\S]*?<\/gallery>/g,
        galleryTag: /<gallery.*?>[\s\S]*?<\/gallery>/g,
htmlAttributes: /(?:style|colspan|color|rowspan|cellpadding|cellspacing|height|width|size|border|thumbtime|name|perrow)\s*[\=\:]\s*(?:['\"].*?['\"]|[\da-z]+)/gi,
        htmlAttributes: /(?:style|colspan|color|rowspan|cellpadding|cellspacing|height|width|size|border|thumbtime|name|perrow)\s*[\=\:]\s*(?:['\"].*?['\"]|[\da-z]+)/gi,
htmlEntity: /&#\d+;/,
        htmlEntity: /&#\d+;/,
imagePixelSize: /[\|=] *[x\d]+?(px|پیکسل)[\]\|\s]/g, // means it will capture |10px| and |10x10px|
        imagePixelSize: /[\|=] *[x\d]+?(px|پیکسل)[\]\|\s]/g, // means it will capture |10px| and |10x10px|
insideQuote: /".*?"/g,
        insideQuote: /".*?"/g,
wikilinkTargets: /\[[^\[|\]]+/g,
        wikilinkTargets: /\[[^\[|\]]+/g,
linksOnEnglishContext: /[a-z][\:\,\. ]*\[\[[\da-z\-\, ]*/gi,
        linksOnEnglishContext: /[a-z][\:\,\. ]*\[\[[\da-z\-\, ]*/gi,
mathTag: /<math.*?>[\s\S]*?<\/math>/g,
        mathTag: /<math.*?>[\s\S]*?<\/math>/g,
otherLanguagesInline: /\{\{(?:به .+?|به انگلیسی|انگلیسی|عربی|حدیث|به عربی)[\s\S]*?\}\}/g,
        otherLanguagesInline: /\{\{(?:به .+?|به انگلیسی|انگلیسی|عربی|حدیث|به عربی)[\s\S]*?\}\}/g,
parameter: /\{\{\{\d+/gi,
        parameter: /\{\{\{\d+/gi,
parenthesesAfterDigits: /\w\s?\([\w\s\.\-]*?\)/g,
        parenthesesAfterDigits: /\w\s?\([\w\s\.\-]*?\)/g,
parenthesesHa: /\)ها/g,
        parenthesesHa: /\)ها/g,
ref: /(?:<ref[^\/]*?>[\s\S]*?<\/ref>|<ref[^\/]*?\/>)/g, // inside <ref></ref> and <ref/>
        ref: /(?:<ref[^\/]*?>[\s\S]*?<\/ref>|<ref[^\/]*?\/>)/g, // inside <ref></ref> and <ref/>
signatures: /\[\[(?:کاربر|User|بحث[ _]کاربر|User[_ ]talk)\:.*?\]\]/gi,
        signatures: /\[\[(?:کاربر|User|بحث[ _]کاربر|User[_ ]talk)\:.*?\]\]/gi,
sourceTag: /(<source.*?>[\s\S]*?<\/source>|<syntaxhighlight.*?>[\s\S]*?<\/syntaxhighlight>|<code.*?>[\s\S]*?<\/code>|<timeline.*?>[\s\S]*?<\/timeline>)/g,
        sourceTag: /(<source.*?>[\s\S]*?<\/source>|<syntaxhighlight.*?>[\s\S]*?<\/syntaxhighlight>|<code.*?>[\s\S]*?<\/code>|<timeline.*?>[\s\S]*?<\/timeline>)/g,
tagNames: /<\/?[a-zA-Z\d]*/g,
        tagNames: /<\/?[a-zA-Z\d]*/g,
templateEnglishName: /(الگو|Template):[a-z][a-z\d\-\+_]+/gi,
        templateEnglishName: /(الگو|Template):[a-z][a-z\d\-\+_]+/gi,
templateParameterName: /\|\s*(?=[a-z_]*\d)[a-z_\d]*\s*\=/gi,
        templateParameterName: /\|\s*(?=[a-z_]*\d)[a-z_\d]*\s*\=/gi,
translatedUrl: /.(کام|نت|آی‌آر)/g,
        translatedUrl: /.(کام|نت|آی\u200cآر)/g,
url: /\/\/.*?(?=[\s\n\|\}\]<]|$)/gi // بدون https?: هم ممکن است
        url: /\/\/.*?(?=[\s\n\|\}\]<]|$)/gi // بدون https?: هم ممکن است
};
    };


function wikiConvertToPersianCharacters(text) {
    function wikiConvertToPersianCharacters(text) {
return replaceExcept(
        return replaceExcept(
text,
            text,
persianTools.toStandardPersianCharacters,
            persianTools.toStandardPersianCharacters, [patterns.otherLanguagesInline, patterns.arabicTagEnclosed, patterns.fileNames, patterns.signatures, patterns.url]
[patterns.otherLanguagesInline, patterns.arabicTagEnclosed, patterns.fileNames, patterns.signatures, patterns.url]
        );
);
    }
}


if (!String.prototype.trim) { // if is not available currently
    if (!String.prototype.trim) { // if is not available currently
String.prototype.trim = function () {
        String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g, '');
            return this.replace(/^\s+|\s+$/g, '');
};
        };
}
    }
function quotation(text) {
 
// این تابع زمانی گیومه را به فارسی تیدیل می‌کند که در پاراگراف مورد نظر تعداد گیومهٔ لاتین زوج باشد.
    function quotation(text) {
var lines = text.split(/\n\n/);
            // این تابع زمانی گیومه را به فارسی تیدیل می\u200cکند که در پاراگراف مورد نظر تعداد گیومهٔ لاتین زوج باشد.
var result = [];
            var lines = text.split(/\n\n/);
for (var i = 0; i < lines.length; ++i) {
            var result = [];
var line = lines[i];
            for (var i = 0; i < lines.length; ++i) {
if ((line.match(/"/g) || []).length % 2 === 0) { // count of quote marks
                var line = lines[i];
// تبدیل گیومهٔ لاتین به فارسی
                if ((line.match(/"/g) || []).length % 2 === 0) { // count of quote marks
// این دستور در ابتدا باشد تا فاصله‌های قبل و بعد گیومه هم اصلاح شود
                    // تبدیل گیومهٔ لاتین به فارسی
line = line.replace(
                    // این دستور در ابتدا باشد تا فاصله\u200cهای قبل و بعد گیومه هم اصلاح شود
new RegExp('(^|[' + persianTools.persianCharacters + '،»؛\\s\\n]+)"((?:\\[\\[|).*?[' + persianTools.persianCharacters + '\\n]+?(?:\\]\\]|))"([' + persianTools.persianCharacters + '،«؛\\s\\n$\.])', 'g'),
                    line = line.replace(
'$1«$2»$3'
                        new RegExp('(^|[' + persianTools.persianCharacters + '،»؛\\s\\n]+)"((?:\\[\\[|).*?[' + persianTools.persianCharacters + '\\n]+?(?:\\]\\]|))"([' + persianTools.persianCharacters + '،«؛\\s\\n$\.])', 'g'),
);
                        '$1«$2»$3'
// if some of quote marks are remained from conversion, something might wrong, revert
                    );
if (line.match(/"/g)) {
                    // if some of quote marks are remained from conversion, something might wrong, revert
line = lines[i];
                    if (line.match(/"/g)) {
}
                        line = lines[i];
}
                    }
// ”“ تبدیل
line = line.replace(
new RegExp('(^|[' + persianTools.persianCharacters + '،»؛\\s\\n]+)“((?:\\[\\[|).*?[' + persianTools.persianCharacters + '\\n]+?(?:\\]\\]|))”([' + persianTools.persianCharacters + '،«؛\\s\\n$\.])', 'g'),
'$1«$2»$3'
);
result.push(line);
}
return result.join('\n\n');
}
var content;
// اگر شمار پانویس\u200cها بیش از ۶ تا بود، الگوی پانویس را دو ستونه کند.
function addColumnToRefTemplate(text) {
    if (text.match(/<ref>/gi).length >= 6) {
        var refTemplate = /\{{2}پانویس([^\}\{]+)?\}{2}/i.exec(content);
        var hasColumn = false;
        if (typeof refTemplate[1] !== "undefined") {
            var refParams = refTemplate[1].split("|");
            for (var i = refParams.length - 1; i >= 0; i--) {
                // اگر الگوی پانویس از پیش ستون برایش تعریف نشده\u200cباشد.
                if (refParams[i].length == 1) {
                    hasColumn = true;
                    break;
                 }
                 }
                // ”“ تبدیل
                line = line.replace(
                    new RegExp('(^|[' + persianTools.persianCharacters + '،»؛\\s\\n]+)“((?:\\[\\[|).*?[' + persianTools.persianCharacters + '\\n]+?(?:\\]\\]|))”([' + persianTools.persianCharacters + '،«؛\\s\\n$\.])', 'g'),
                    '$1«$2»$3'
                );
                result.push(line);
             }
             }
            return result.join('\n\n');
        }
        // اگر شمار پانویس\u200cها بیش از ۶ تا بود، الگوی پانویس را دو ستونه کند.
    function addColumnToRefTemplate(text) {
        if (text.match(/<ref>/gi).length >= 6) {
            var refTemplate = /\{{2}پانویس([^\}\{]+)?\}{2}/i.exec(text);
            var hasColumn = false;
            if (typeof refTemplate[1] !== 'undefined') {
                var refParams = refTemplate[1].split('|');
                for (var i = refParams.length - 1; i >= 0; i--) {
                    // اگر الگوی پانویس از پیش ستون برایش تعریف نشده\u200cباشد.
                    if (refParams[i].length == 1) {
                        hasColumn = true;
                        break;
                    }
                }
            }
            if (typeof refTemplate[1] === 'undefined' || !hasColumn)
                return text.replace(refTemplate[0], refTemplate[0].replace('}}', '|۲}}'));
         }
         }
        if (typeof refTemplate[1] === "undefined" || !hasColumn)
            return text.replace(refTemplate[0], refTemplate[0].replace("}}", "|۲}}"));
     }
     }
}
function wikiPunctuation(text) {
text = quotation(text);
text = replaceExcept(
text,
function (text) {
text = text.replace(
new RegExp('([' + persianTools.persianCharactersNoVowels + '])ـ+([' + persianTools.persianCharactersNoVowels + '])', 'g'),
'$1$2'
);
return text.replace(new RegExp('([' + persianTools.persianCharacters + '])(\\]\\]|), (\\[\\[|)?(?=[' + persianTools.persianCharacters + "])", 'g'), '$1$2، $3');
},
[patterns.fileNames, patterns.url, patterns.galleryTag, patterns.sourceTag, patterns.translatedUrl, patterns.parenthesesHa]
);
return replaceExcept(
text,
function (text) {
return persianTools.punctuation(text)
.replace(/^([*#]+)([^*#\:\s])/mg, '$1 $2') // Adds a space after the # or * for lists
.replace(/^([*#]+) {2,}([^*#\:\s])/mg, '$1 $2'); // Trim more that one space after the # or * for lists
},
[patterns.fileNames, patterns.url, patterns.wikilinkTargets, patterns.galleryTag, patterns.sourceTag, patterns.translatedUrl, patterns.parenthesesHa]
)
.replace(/\n{3,}/g, '\n\n') // Cosmetic changes bot replaces
.replace(/\[\[(رده|الگو|ویکی\u200cپدیا)\: +/g, '[[$1:')
.replace(/[\n\s]*\{\{[•·ن](w?)\}\}\s*/g, '{{•$1}} ')
.replace(/ *(<\/? ?br ?\/?>|\{\{بر\}\}) */g, '{{سخ}}')
.replace(/(<\/ref>)\s+(<ref)/g, '$1$2')
.replace(/([^=])[\s\n]+<ref(?!erences)/g, '$1<ref')
.replace(/(\n?)[\s\n]+?<\/ref>/g, '$1</ref>')
.replace(/([^=])\n+(\=.*?\=\n+)/g, '$1\n\n$2')
.replace(/^(\={2,}) +[\:,;>&\^#@•→←↔↑↓—–…~٫،؛ٔ]/mg, '$1') // Cleanup headers
.replace(/[\:,;<&\^#@•→←↔↑↓—–…~٫،؛ٔ] +(\={2,})$/mg, '$1')
.replace(/^(\={2,}\s*)(«)([^\n«»]*?)(»)(\s*\={2,})/mg, '$1 $3 $5')
.replace(/^(\={2,}) *'+(.*?)'+ *(\={2,})/mg, '$1 $2 $3')
.replace(/^[●⚫⬤]/mg, '*') // Wikify bullets in start of lines
.replace(/^#\s*(REDIRECT|تغییر[ _]?مسیر)/gi, '#تغییرمسیر')
.replace(/^#تغییرمسیر(?=\S)/g, '#تغییرمسیر ') // Adds a space after #REDIRECT
.replace(/(\={2,}) *([^\n\r]*?) *(\={2,})/g, '$1 $2 $3') // Format headings level 2 and above
// فاصله‌های اضافی را از داخل پیوند به بیرون منتقل کند تا اگر اضافه بودند در کدهای دیگر حذف شوند
.replace(/\[\[(\s*)(.*?)(\s*)\]\]/g, '$1[[$2]]$3')
// تبدیل به نویسه / یکی کردن فاصله های مجازی پشت سرهم
.replace(/(\{\{فم\}\}|\&zwnj\;|\u200c+)/g, '\u200c')
// Full stop and comma should be before citation. See en:WP:REFPUNC
.replace(/ *((?:<ref[^\/]*?>.*?<\/ref>)+)([\.،,:])?/g, '$2$1')
.replace(/([^.])([\.،,:]){2}((?:<ref[^\/]*?>.*?<\/ref>)+)/g, '$1$2$3')
.replace(/ *((?:<ref[^\/]*?\/>)+)([\.،,:])/g, '$2$1')
.replace(/([^.])([\.،,:]){2}(((?:<ref[^\/]*?\/>)+)+)/g, '$1$2$3')
.replace(/\{\{(?:DEFAULTSORT|[Dd]efaultsort|ترتیب|ترتیب[‌ ]پیش[‌ ]?فرض) *[|:] *(?=.*?}})/g, '{{ترتیب‌پیش‌فرض:')
.replace(/\{\{(ترتیب‌پیش‌فرض|DEFAULTSORT)\:[-\w,\s\(\)]+\}\}\n?/g, '')
.replace(/(\{\{ترتیب‌پیش‌فرض\:)\s/g, '$1')
//نچسبیدن و+فاصله به براکت که محصول اشتباه در تایپ کردن است
.replace(']]و ', ']] و ')
.trim();
}


function wikiUrlMinifier(text) {
    function wikiPunctuation(text) {
return text
        text = quotation(text);
.replace(patterns.url, function (x) {
        text = replaceExcept(
return replaceExcept(
            text,
x,
            function (text) {
function (x) {
                text = text.replace(
try {
                    new RegExp('([' + persianTools.persianCharactersNoVowels + '])ـ+([' + persianTools.persianCharactersNoVowels + '])', 'g'),
x = decodeURI(x);
                    '$1$2'
} catch (e) { mw.notify(e); }
                );
return x;
                return text.replace(new RegExp('([' + persianTools.persianCharacters + '])(\\]\\]|), (\\[\\[|)?(?=[' + persianTools.persianCharacters + '])', 'g'), '$1$2، $3');
},
            }, [patterns.fileNames, patterns.url, patterns.galleryTag, patterns.sourceTag, patterns.translatedUrl, patterns.parenthesesHa]
[patterns.decodeUriBlacklist]
        );
);
        return replaceExcept(
})
                text,
                function (text) {
                    return persianTools.punctuation(text)
                        .replace(/^([*#]+)([^*#\:\s])/mg, '$1 $2') // Adds a space after the # or * for lists
                        .replace(/^([*#]+) {2,}([^*#\:\s])/mg, '$1 $2'); // Trim more that one space after the # or * for lists
                }, [patterns.fileNames, patterns.url, patterns.wikilinkTargets, patterns.galleryTag, patterns.sourceTag, patterns.translatedUrl, patterns.parenthesesHa]
            )
            .replace(/\n{3,}/g, '\n\n') // Cosmetic changes bot replaces
            .replace(/\[\[(رده|الگو|ویکی\u200cپدیا)\: +/g, '[[$1:')
            .replace(/[\n\s]*\{\{[•·ن](w?)\}\}\s*/g, '{{•$1}} ')
            .replace(/ *(<\/? ?br ?\/?>|\{\{بر\}\}) */g, '{{سخ}}')
            .replace(/(<\/ref>)\s+(<ref)/g, '$1$2')
            .replace(/([^=])[\s\n]+<ref(?!erences)/g, '$1<ref')
            .replace(/(\n?)[\s\n]+?<\/ref>/g, '$1</ref>')
            .replace(/([^=])\n+(\=.*?\=\n+)/g, '$1\n\n$2')
            .replace(/^(\={2,}) +[\:,;>&\^#@•→←↔↑↓—–…~٫،؛ٔ]/mg, '$1') // Cleanup headers
            .replace(/[\:,;<&\^#@•→←↔↑↓—–…~٫،؛ٔ] +(\={2,})$/mg, '$1')
            .replace(/^(\={2,}\s*)(«)([^\n«»]*?)(»)(\s*\={2,})/mg, '$1 $3 $5')
            .replace(/^(\={2,}) *'+(.*?)'+ *(\={2,})/mg, '$1 $2 $3')
            .replace(/^[●⚫⬤]/mg, '*') // Wikify bullets in start of lines
            .replace(/^#\s*(REDIRECT|تغییر[ _]?مسیر)/gi, '#تغییرمسیر')
            .replace(/^#تغییرمسیر(?=\S)/g, '#تغییرمسیر ') // Adds a space after #REDIRECT
            .replace(/(\={2,}) *([^\n\r]*?) *(\={2,})/g, '$1 $2 $3') // Format headings level 2 and above
            // فاصله\u200cهای اضافی را از داخل پیوند به بیرون منتقل کند تا اگر اضافه بودند در کدهای دیگر حذف شوند
            .replace(/\[\[(\s*)(.*?)(\s*)\]\]/g, '$1[[$2]]$3')
            // تبدیل به نویسه / یکی کردن فاصله های مجازی پشت سرهم
            .replace(/(\{\{فم\}\}|\&zwnj\;|\u200c+)/g, '\u200c')
            // Full stop and comma should be before citation. See en:WP:REFPUNC
            .replace(/ *((?:<ref[^\/]*?>.*?<\/ref>)+)([\.،,:])?/g, '$2$1')
            .replace(/([^.])([\.،,:]){2}((?:<ref[^\/]*?>.*?<\/ref>)+)/g, '$1$2$3')
            .replace(/ *((?:<ref[^\/]*?\/>)+)([\.،,:])/g, '$2$1')
            .replace(/([^.])([\.،,:]){2}(((?:<ref[^\/]*?\/>)+)+)/g, '$1$2$3')
            .replace(/\{\{(?:DEFAULTSORT|[Dd]efaultsort|ترتیب|ترتیب[\u200c ]پیش[\u200c ]?فرض) *[|:] *(?=.*?}})/g, '{{ترتیب\u200cپیش\u200cفرض:')
            .replace(/\{\{(ترتیب\u200cپیش\u200cفرض|DEFAULTSORT)\:[-\w,\s\(\)]+\}\}\n?/g, '')
            .replace(/(\{\{ترتیب\u200cپیش\u200cفرض\:)\s/g, '$1')
            //نچسبیدن و+فاصله به براکت که محصول اشتباه در تایپ کردن است
            .replace(']]و ', ']] و ')
            .trim();
    }


// Strip the http(s) prefix
    function wikiUrlMinifier(text) {
.replace(/\[(https?\:)(?=\/\/(?:[\w\-]+)\.(wiki(pedia|media|data|source|news|oyage|quote)|wiktionary)\.org\/[^\s\]]*)/g, '[');
        return text
}
            .replace(patterns.url, function (x) {
                return replaceExcept(
                    x,
                    function (x) {
                        try {
                            x = decodeURI(x);
                        } catch (e) {
                            mw.notify(e);
                        }
                        return x;
                    }, [patterns.decodeUriBlacklist]
                );
            })


function wikiTextDigitsToPersian(text) {
        // Strip the http(s) prefix
text = replaceExcept(
        .replace(/\[(https?\:)(?=\/\/(?:[\w\-]+)\.(wiki(pedia|media|data|source|news|oyage|quote)|wiktionary)\.org\/[^\s\]]*)/g, '[');
text,
    }
persianTools.toPersianDigits,
[patterns.url, patterns.argumentsBlacklist, patterns.mathTag, patterns.imagePixelSize, patterns.fileNames, patterns.ref,
patterns.sourceTag, patterns.arabicDigitsEnglishContext, patterns.signatures, patterns.htmlEntity,
patterns.htmlAttributes, patterns.fileParameter, patterns.templateParameterName, patterns.ipSign,
patterns.parenthesesAfterDigits, patterns.otherLanguagesInline, patterns.isbn, patterns.englishDate,
patterns.parameter, patterns.color, patterns.templateEnglishName, patterns.linksOnEnglishContext,
patterns.colorAsParameter, patterns.tagNames]
);
return text
// Decimal point, and thousands' separator
.replace(/([۱۲۳۴۵۶۷۸۹۰])\.([۱۲۳۴۵۶۷۸۹۰])/g, '$1٫$2')
.replace(/([۱۲۳۴۵۶۷۸۹۰]),([۱۲۳۴۵۶۷۸۹۰])/g, '$1٬$2');
}


function dictationReplace(x, y, extensions, text) {
    function wikiTextDigitsToPersian(text) {
return text.replace(
        text = replaceExcept(
new RegExp(
            text,
'(^|[^' + persianTools.persianCharacters + '])(\\s|\u200c|_|)(' + x + ')(\\s|_)(' + y + ')(\\s|\u200c|_|)(' +
            persianTools.toPersianDigits, [patterns.url, patterns.argumentsBlacklist, patterns.mathTag, patterns.imagePixelSize, patterns.fileNames, patterns.ref,
extensions + ')($|[^' + persianTools.persianCharacters + '])',
                patterns.sourceTag, patterns.arabicDigitsEnglishContext, patterns.signatures, patterns.htmlEntity,
'g'
                patterns.htmlAttributes, patterns.fileParameter, patterns.templateParameterName, patterns.ipSign,
),
                patterns.parenthesesAfterDigits, patterns.otherLanguagesInline, patterns.isbn, patterns.englishDate,
'$1$2$3\u200c$5$6$7$8'
                patterns.parameter, patterns.color, patterns.templateEnglishName, patterns.linksOnEnglishContext,
);
                patterns.colorAsParameter, patterns.tagNames
}
            ]
        );
        return text
            // Decimal point, and thousands' separator
            .replace(/([۱۲۳۴۵۶۷۸۹۰])\.([۱۲۳۴۵۶۷۸۹۰])/g, '$1٫$2')
            .replace(/([۱۲۳۴۵۶۷۸۹۰]),([۱۲۳۴۵۶۷۸۹۰])/g, '$1٬$2');
    }


// it has dependency to MediaWiki:Gadget-Extra-Editbuttons-Dictionary.js
    function dictationReplace(x, y, extensions, text) {
function dictation(text) {
        return text.replace(
var i, dictionary = persianToolsDictionary, NASB = '\u064b'; // ًـ
            new RegExp(
for (i in dictionary.complexes) {
                '(^|[^' + persianTools.persianCharacters + '])(\\s|\u200c|_|)(' + x + ')(\\s|_)(' + y + ')(\\s|\u200c|_|)(' +
if (dictionary.complexes.hasOwnProperty(i)) {
                extensions + ')($|[^' + persianTools.persianCharacters + '])',
text = dictationReplace(
                'g'
i,
            ),
dictionary.complexes[i],
            '$1$2$3\u200c$5$6$7$8'
'ی|ها|های|هایی|هایم|هایت|هایش|هایمان|هایتان|هایشان|',
        );
text
    }
);
}
}
// for last name
text = dictationReplace(
dictionary.personNames,
'ی|زاده|نیا|گان|فر|نژاد|یان|ی\u200cها|یها',
'ی|',
text
);
// for 'آباد's
text = dictationReplace(
dictionary.personNames + '|' + dictionary.addToAbad,
'آباد',
'زاده|نیا|پور|گان|فر|نژاد|ی|یان|ها|های|هایی|ی\u200cها|یها|',
text
);
// for first names
for (i in dictionary.firstNameComplex) {
if (dictionary.firstNameComplex.hasOwnProperty(i)) {
text = text.replace(
new RegExp(
'(^|[^' + persianTools.persianCharacters + ']|\\s|_)(' + i + ')(\\s|_)(' +
dictionary.firstNameComplex[i] + ')(\\s|_)($|[^' + persianTools.persianCharacters + ']|[^' +
persianTools.persianCharacters + '])',
'g'
),
'$1$2\u200c$4$5$6'
);
}
}
// for colors
text = dictationReplace(
dictionary.colorsNames,
'فام|گون',
'زاده|نیا|پور|گان|فر|نژاد|ی|ها|های|هایی|ی\u200cها|یها|هایم|هایت|هایش|هایمان|هایتان|هایشان|',
text
);
// for numbers
text = dictationReplace(
dictionary.persianNumbers,
'گانه|ماهه',
'زاده|نیا|پور|گان|فر|نژاد|ی|ها|های|هایی|هایم|هایت|هایش|هایمان|هایتان|هایشان|',
text
);
// wrong dictation
for (i in dictionary.forReplace) {
if (dictionary.forReplace.hasOwnProperty(i)) {
text = text.replace(
new RegExp(
'(^|[^' + persianTools.persianCharacters + '])(\\s|\u200c|_|)(' + i + ')(\\s|\u200c|_|)($|[^' +
persianTools.persianCharacters + '])',
'g'
),
'$1$2' + dictionary.forReplace[i] + '$4$5'
);
}
}


    // it has dependency to MediaWiki:Gadget-Extra-Editbuttons-Dictionary.js
    function dictation(text) {
        var i, dictionary = persianToolsDictionary,
            NASB = '\u064b'; // ًـ
        for (i in dictionary.complexes) {
            if (dictionary.complexes.hasOwnProperty(i)) {
                text = dictationReplace(
                    i,
                    dictionary.complexes[i],
                    'ی|ها|های|هایی|هایم|هایت|هایش|هایمان|هایتان|هایشان|',
                    text
                );
            }
        }
        // for last name
        text = dictationReplace(
            dictionary.personNames,
            'ی|زاده|نیا|گان|فر|نژاد|یان|ی\u200cها|یها',
            'ی|',
            text
        );
        // for 'آباد's
        text = dictationReplace(
            dictionary.personNames + '|' + dictionary.addToAbad,
            'آباد',
            'زاده|نیا|پور|گان|فر|نژاد|ی|یان|ها|های|هایی|ی\u200cها|یها|',
            text
        );
        // for first names
        for (i in dictionary.firstNameComplex) {
            if (dictionary.firstNameComplex.hasOwnProperty(i)) {
                text = text.replace(
                    new RegExp(
                        '(^|[^' + persianTools.persianCharacters + ']|\\s|_)(' + i + ')(\\s|_)(' +
                        dictionary.firstNameComplex[i] + ')(\\s|_)($|[^' + persianTools.persianCharacters + ']|[^' +
                        persianTools.persianCharacters + '])',
                        'g'
                    ),
                    '$1$2\u200c$4$5$6'
                );
            }
        }
        // for colors
        text = dictationReplace(
            dictionary.colorsNames,
            'فام|گون',
            'زاده|نیا|پور|گان|فر|نژاد|ی|ها|های|هایی|ی\u200cها|یها|هایم|هایت|هایش|هایمان|هایتان|هایشان|',
            text
        );
        // for numbers
        text = dictationReplace(
            dictionary.persianNumbers,
            'گانه|ماهه',
            'زاده|نیا|پور|گان|فر|نژاد|ی|ها|های|هایی|هایم|هایت|هایش|هایمان|هایتان|هایشان|',
            text
        );
        // wrong dictation
        for (i in dictionary.forReplace) {
            if (dictionary.forReplace.hasOwnProperty(i)) {
                text = text.replace(
                    new RegExp(
                        '(^|[^' + persianTools.persianCharacters + '])(\\s|\u200c|_|)(' + i + ')(\\s|\u200c|_|)($|[^' +
                        persianTools.persianCharacters + '])',
                        'g'
                    ),
                    '$1$2' + dictionary.forReplace[i] + '$4$5'
                );
            }
        }
        // کلماتی که آ دارند
        text = text.replace(
            new RegExp('(^| |_|«|»)(' + dictionary.wordsWithA + ')(ی|ئی|یی|)(?= |«|»|\\.|،|_|$)', 'g'),
            function (x) {
                return x.replace(/ا/i, 'آ');
            } // 'i' is just to trick bidi algorithm on code view
        );
        text = text.replace(/به دست\u200cآورد/g, 'به دست آورد'); // Solving a bug!
        text = persianTools.normalizeZwnj(text);
        return text.replace(new RegExp('([\\s\\n\.،«»؛])(' + dictionary.needsNasb + ')([\\s\\n\.،«»؛])(\\u064b|)', 'g'), '$1$2' + NASB + '$3');
    }


// کلماتی که آ دارند
    function wikiDictation(text) {
text = text.replace(
        return replaceExcept(
new RegExp('(^| |_|«|»)(' + dictionary.wordsWithA + ')(ی|ئی|یی|)(?= |«|»|\\.|،|_|$)', 'g'),
            text,
function (x) { return x.replace(/ا/i, 'آ'); } // 'i' is just to trick bidi algorithm on code view
            dictation, [patterns.fileNames, patterns.signatures, patterns.url, patterns.galleryTag, patterns.insideQuote]
);
        );
    }
text = text.replace(/به دست\u200cآورد/g, 'به دست آورد'); // Solving a bug!
text = persianTools.normalizeZwnj(text);
return text.replace(new RegExp('([\\s\\n\.،«»؛])(' + dictionary.needsNasb + ')([\\s\\n\.،«»؛])(\\u064b|)', 'g'), '$1$2' + NASB +'$3');
}


function wikiDictation(text) {
    function wikiApplyOrthography(text) {
return replaceExcept(
        return replaceExcept(
text,
            text,
dictation,
            persianTools.applyOrthography, [patterns.fileNames, patterns.signatures, patterns.url, patterns.galleryTag]
[patterns.fileNames, patterns.signatures, patterns.url, patterns.galleryTag, patterns.insideQuote]
        ).replace(patterns.galleryTag, function (gallery) {
);
            // apply `applyOrthography` on gallery descriptions separatly
}
            return gallery.replace(/^([^\|]*?\|)(.*)$/mg, function (x, y, z) {
                return y + persianTools.applyOrthography(z);
function wikiApplyOrthography(text) {
            });
return replaceExcept(
        });
text,
    }
persianTools.applyOrthography,
 
[patterns.fileNames, patterns.signatures, patterns.url, patterns.galleryTag]
    // probably should be exactly same above but for applyZwnj
).replace(patterns.galleryTag, function (gallery) {
    function wikiApplyZwnj(text) {
// apply `applyOrthography` on gallery descriptions separatly
        return replaceExcept(
return gallery.replace(/^([^\|]*?\|)(.*)$/mg, function (x, y, z) {
            text,
return y + persianTools.applyOrthography(z);
            persianTools.applyZwnj, [patterns.fileNames, patterns.signatures, patterns.url, patterns.galleryTag]
});
        ).replace(patterns.galleryTag, function (gallery) {
});
            // apply `applyOrthography` on gallery descriptions separatly
}
            return gallery.replace(/^([^\|]*?\|)(.*)$/mg, function (x, y, z) {
                return y + persianTools.applyZwnj(z);
// probably should be exactly same above but for applyZwnj
            });
function wikiApplyZwnj(text) {
        });
return replaceExcept(
    }
text,
 
persianTools.applyZwnj,
    function superTool(text) {
[patterns.fileNames, patterns.signatures, patterns.url, patterns.galleryTag]
        text = persianWikiTools.wikiConvertToPersianCharacters(text);
).replace(patterns.galleryTag, function (gallery) {
        text = persianWikiTools.wikiApplyZwnj(text);
// apply `applyOrthography` on gallery descriptions separatly
        text = persianWikiTools.wikiApplyOrthography(text);
return gallery.replace(/^([^\|]*?\|)(.*)$/mg, function (x, y, z) {
        if (mw.config.get('wgNamespaceNumber') !== 10) {
return y + persianTools.applyZwnj(z);
            text = persianWikiTools.wikiTextDigitsToPersian(text);
});
        }
});
        text = persianWikiTools.wikiUrlMinifier(text);
}
        text = persianWikiTools.wikiDictation(text);
        text = persianWikiTools.wikiPunctuation(text);
function superTool(text) {
        //ابزارهای بیشتر برگرفته از ویکی\u200cپدیای انگلیسی [[Mediawiki:Gadget-Extra-Editbuttons-autoed.js]]
text = persianWikiTools.wikiConvertToPersianCharacters(text);
        text = autoEd.autoEdISBN(text);
text = persianWikiTools.wikiApplyZwnj(text);
        text = autoEd.autoEdWhitespace(text);
text = persianWikiTools.wikiApplyOrthography(text);
        // text = autoEd.autoEdWikilinks(text);
if (mw.config.get('wgNamespaceNumber') !== 10) {
        text = autoEd.autoEdHTMLtoWikitext(text);
text = persianWikiTools.wikiTextDigitsToPersian(text);
        text = autoEd.autoEdHeadlines(text);
}
        // text = autoEd.autoEdTemplates(text);
text = persianWikiTools.wikiUrlMinifier(text);
        text = autoEd.autoEdTablestoWikitext(text);
text = persianWikiTools.wikiDictation(text);
        text = autoEd.autoEdExtraBreaks(text);
text = persianWikiTools.wikiPunctuation(text);
        // text = autoEd.autoEdLinks(text);
//ابزارهای بیشتر برگرفته از ویکی‌پدیای انگلیسی [[Mediawiki:Gadget-Extra-Editbuttons-autoed.js]]
        text = persianWikiTools.addColumnToRefTemplate(text);
text = autoEd.autoEdISBN(text);
        return text;
text = autoEd.autoEdWhitespace(text);
    }
// text = autoEd.autoEdWikilinks(text);
 
text = autoEd.autoEdHTMLtoWikitext(text);
    function superToolMove(text) {
text = autoEd.autoEdHeadlines(text);
        text = persianWikiTools.wikiConvertToPersianCharacters(text);
// text = autoEd.autoEdTemplates(text);
        text = persianTools.applyZwnj(text);
text = autoEd.autoEdTablestoWikitext(text);
        text = persianWikiTools.wikiApplyOrthography(text);
text = autoEd.autoEdExtraBreaks(text);
        text = persianWikiTools.wikiTextDigitsToPersian(text);
// text = autoEd.autoEdLinks(text);
        text = persianWikiTools.wikiUrlMinifier(text);
return text;
        text = persianWikiTools.wikiDictation(text);
}
        text = persianWikiTools.wikiPunctuation(text);
        return text;
function superToolMove(text) {
    }
text = persianWikiTools.wikiConvertToPersianCharacters(text);
text = persianTools.applyZwnj(text);
text = persianWikiTools.wikiApplyOrthography(text);
text = persianWikiTools.wikiTextDigitsToPersian(text);
text = persianWikiTools.wikiUrlMinifier(text);
text = persianWikiTools.wikiDictation(text);
text = persianWikiTools.wikiPunctuation(text);
return text;
}


return {
    return {
superTool: superTool,
        superTool: superTool,
superToolMove: superToolMove,
        superToolMove: superToolMove,
dictation: dictation,
        dictation: dictation,
wikiApplyOrthography: wikiApplyOrthography,
        wikiApplyOrthography: wikiApplyOrthography,
wikiApplyZwnj: wikiApplyZwnj,
        wikiApplyZwnj: wikiApplyZwnj,
wikiConvertToPersianCharacters: wikiConvertToPersianCharacters,
        wikiConvertToPersianCharacters: wikiConvertToPersianCharacters,
wikiDictation: wikiDictation,
        wikiDictation: wikiDictation,
wikiPunctuation: wikiPunctuation,
        wikiPunctuation: wikiPunctuation,
wikiUrlMinifier: wikiUrlMinifier,
        wikiUrlMinifier: wikiUrlMinifier,
wikiTextDigitsToPersian: wikiTextDigitsToPersian
        wikiTextDigitsToPersian: wikiTextDigitsToPersian,
};
        addColumnToRefTemplate: addColumnToRefTemplate
    };
}());
}());
if (typeof window !== "undefined") {
if (typeof window !== 'undefined') {
window.persianWikiTools = persianWikiTools;
    window.persianWikiTools = persianWikiTools;
}
}

نسخهٔ ۱۱ مارس ۲۰۱۵، ساعت ۲۱:۰۶

// <nowiki> // DO NOT REMOVE THIS LINE EVER
/**
 * Wikipedia specific Persian text style improvement tools
 * Tests: [[مدیاویکی:Gadget-Extra-Editbuttons-tests.js]] [[وپ:تست]]
 * See also: [[مدیاویکی:Gadget-Extra-Editbuttons-persiantools.js]]
 */
/*global persianTools, persianToolsDictionary, autoEd, console*/
var persianWikiTools = (function () {
    'use strict';

    function descendingFromComparetor(x, y) {
        return x.from - y.from;
    }

    function replaceExcept(text, callback, excepts) {
        var match, result = [],
            i, ranges, minRange, to, min, max;
        while (text !== '') {
            ranges = [];

            for (i in excepts) {
                if (excepts.hasOwnProperty(i)) {
                    // a global regex should be reset before calls
                    excepts[i].lastIndex = 0;
                    match = excepts[i].exec(text);
                    if (match !== null) {
                        ranges.push({
                            from: match.index,
                            to: match.index + match[0].length
                        });
                    }
                }
            }

            // so nothing is matched
            if (ranges.length === 0) {
                result.push(callback(text));
                break;
            }

            minRange = ranges.sort(descendingFromComparetor)[0];
            min = minRange.from;

            to = [];
            for (i in ranges) {
                if (ranges.hasOwnProperty(i)) {
                    if (ranges[i].from <= minRange.to) {
                        to.push(ranges[i].to);
                    }
                }
            }
            max = Math.max.apply(null, to);

            result.push(callback(text.substr(0, min)));
            result.push(text.substr(min, max - min));
            // console.log('Excepted: "' + text.substr(min, max - min) + '"');
            text = text.substr(max);
        }
        return result.join('');
    }

    var patterns = {
        arabicDigitsEnglishContext: /[a-z][a-z %"'\._:\|,\-\\\/\(\)\#\^\+\d><–\[\]&?{}]*\d|(\d|[a-z])[a-z %"'\._:\|,\-\\\/\(\)\#\^\+\d><–\[\]&?{}]*[a-z]\d*/gi,
        arabicTagEnclosed: /\{\{(?:عربی|شروع عربی|آغاز عربی)\}\}([\s\S]*?)\{\{(?:پایان عربی)\}\}/g,
        argumentsBlacklist: /(?:accessdate|namespace|doi|style|شابک|عرض|bibcode|isbn|pmid|arxiv)\s*\=\s*[^\|\}]*/gi,
        color: /#(?:[abcdef0-9]{8}|[abcdef0-9]{6}|[abcdef0-9]{3})/gi,
        colorAsParameter: /\=\s*(?:[abcdef0-9]{8}|[abcdef0-9]{6}|[abcdef0-9]{3})(?:[\s\|\}]|$)/gi,
        // space, ", \t, \n, {, |, }, ... they will interfere with wiki markup
        decodeUriBlacklist: /(?:%20|%5C|%5E|%60|%23|%25|%3C|%3E|%5B|%5D|%22|%09|%0A|%7B|%7C|%7D)/gi,
        englishDate: /\d{1,2},? [a-z]{3,} \d{2,4}/gi, // 3, May 2013
        fileNames: /(?:پرونده|File|تصویر|Image)\:.*?(?=\||\]|\n|$)/gi, // don't capture | after
        fileParameter: /\|\s*(image|تصویر)\s*\=\s*.*/g,
        ipSign: /\[\[ویژه:مشارکت\u200cها.*?\]\]/g,
        isbn: /ISBN [\d\-]*/gi,
        galleryTag: /<gallery.*?>[\s\S]*?<\/gallery>/g,
        htmlAttributes: /(?:style|colspan|color|rowspan|cellpadding|cellspacing|height|width|size|border|thumbtime|name|perrow)\s*[\=\:]\s*(?:['\"].*?['\"]|[\da-z]+)/gi,
        htmlEntity: /&#\d+;/,
        imagePixelSize: /[\|=] *[x\d]+?(px|پیکسل)[\]\|\s]/g, // means it will capture |10px| and |10x10px|
        insideQuote: /".*?"/g,
        wikilinkTargets: /\[[^\[|\]]+/g,
        linksOnEnglishContext: /[a-z][\:\,\. ]*\[\[[\da-z\-\, ]*/gi,
        mathTag: /<math.*?>[\s\S]*?<\/math>/g,
        otherLanguagesInline: /\{\{(?:به .+?|به انگلیسی|انگلیسی|عربی|حدیث|به عربی)[\s\S]*?\}\}/g,
        parameter: /\{\{\{\d+/gi,
        parenthesesAfterDigits: /\w\s?\([\w\s\.\-]*?\)/g,
        parenthesesHa: /\)ها/g,
        ref: /(?:<ref[^\/]*?>[\s\S]*?<\/ref>|<ref[^\/]*?\/>)/g, // inside <ref></ref> and <ref/>
        signatures: /\[\[(?:کاربر|User|بحث[ _]کاربر|User[_ ]talk)\:.*?\]\]/gi,
        sourceTag: /(<source.*?>[\s\S]*?<\/source>|<syntaxhighlight.*?>[\s\S]*?<\/syntaxhighlight>|<code.*?>[\s\S]*?<\/code>|<timeline.*?>[\s\S]*?<\/timeline>)/g,
        tagNames: /<\/?[a-zA-Z\d]*/g,
        templateEnglishName: /(الگو|Template):[a-z][a-z\d\-\+_]+/gi,
        templateParameterName: /\|\s*(?=[a-z_]*\d)[a-z_\d]*\s*\=/gi,
        translatedUrl: /.(کام|نت|آی\u200cآر)/g,
        url: /\/\/.*?(?=[\s\n\|\}\]<]|$)/gi // بدون https?: هم ممکن است
    };

    function wikiConvertToPersianCharacters(text) {
        return replaceExcept(
            text,
            persianTools.toStandardPersianCharacters, [patterns.otherLanguagesInline, patterns.arabicTagEnclosed, patterns.fileNames, patterns.signatures, patterns.url]
        );
    }

    if (!String.prototype.trim) { // if is not available currently
        String.prototype.trim = function () {
            return this.replace(/^\s+|\s+$/g, '');
        };
    }

    function quotation(text) {
            // این تابع زمانی گیومه را به فارسی تیدیل می\u200cکند که در پاراگراف مورد نظر تعداد گیومهٔ لاتین زوج باشد.
            var lines = text.split(/\n\n/);
            var result = [];
            for (var i = 0; i < lines.length; ++i) {
                var line = lines[i];
                if ((line.match(/"/g) || []).length % 2 === 0) { // count of quote marks
                    // تبدیل گیومهٔ لاتین به فارسی
                    // این دستور در ابتدا باشد تا فاصله\u200cهای قبل و بعد گیومه هم اصلاح شود
                    line = line.replace(
                        new RegExp('(^|[' + persianTools.persianCharacters + '،»؛\\s\\n]+)"((?:\\[\\[|).*?[' + persianTools.persianCharacters + '\\n]+?(?:\\]\\]|))"([' + persianTools.persianCharacters + '،«؛\\s\\n$\.])', 'g'),
                        '$1«$2»$3'
                    );
                    // if some of quote marks are remained from conversion, something might wrong, revert
                    if (line.match(/"/g)) {
                        line = lines[i];
                    }
                }
                // ”“ تبدیل 
                line = line.replace(
                    new RegExp('(^|[' + persianTools.persianCharacters + '،»؛\\s\\n]+)“((?:\\[\\[|).*?[' + persianTools.persianCharacters + '\\n]+?(?:\\]\\]|))”([' + persianTools.persianCharacters + '،«؛\\s\\n$\.])', 'g'),
                    '$1«$2»$3'
                );
                result.push(line);
            }
            return result.join('\n\n');
        }
        // اگر شمار پانویس\u200cها بیش از ۶ تا بود، الگوی پانویس را دو ستونه کند.
    function addColumnToRefTemplate(text) {
        if (text.match(/<ref>/gi).length >= 6) {
            var refTemplate = /\{{2}پانویس([^\}\{]+)?\}{2}/i.exec(text);
            var hasColumn = false;
            if (typeof refTemplate[1] !== 'undefined') {
                var refParams = refTemplate[1].split('|');
                for (var i = refParams.length - 1; i >= 0; i--) {
                    // اگر الگوی پانویس از پیش ستون برایش تعریف نشده\u200cباشد.
                    if (refParams[i].length == 1) {
                        hasColumn = true;
                        break;
                    }
                }
            }
            if (typeof refTemplate[1] === 'undefined' || !hasColumn)
                return text.replace(refTemplate[0], refTemplate[0].replace('}}', '|۲}}'));
        }
    }

    function wikiPunctuation(text) {
        text = quotation(text);
        text = replaceExcept(
            text,
            function (text) {
                text = text.replace(
                    new RegExp('([' + persianTools.persianCharactersNoVowels + '])ـ+([' + persianTools.persianCharactersNoVowels + '])', 'g'),
                    '$1$2'
                );
                return text.replace(new RegExp('([' + persianTools.persianCharacters + '])(\\]\\]|), (\\[\\[|)?(?=[' + persianTools.persianCharacters + '])', 'g'), '$1$2، $3');
            }, [patterns.fileNames, patterns.url, patterns.galleryTag, patterns.sourceTag, patterns.translatedUrl, patterns.parenthesesHa]
        );
        return replaceExcept(
                text,
                function (text) {
                    return persianTools.punctuation(text)
                        .replace(/^([*#]+)([^*#\:\s])/mg, '$1 $2') // Adds a space after the # or * for lists
                        .replace(/^([*#]+) {2,}([^*#\:\s])/mg, '$1 $2'); // Trim more that one space after the # or * for lists
                }, [patterns.fileNames, patterns.url, patterns.wikilinkTargets, patterns.galleryTag, patterns.sourceTag, patterns.translatedUrl, patterns.parenthesesHa]
            )
            .replace(/\n{3,}/g, '\n\n') // Cosmetic changes bot replaces
            .replace(/\[\[(رده|الگو|ویکی\u200cپدیا)\: +/g, '[[$1:')
            .replace(/[\n\s]*\{\{[•·ن](w?)\}\}\s*/g, '{{•$1}} ')
            .replace(/ *(<\/? ?br ?\/?>|\{\{بر\}\}) */g, '{{سخ}}')
            .replace(/(<\/ref>)\s+(<ref)/g, '$1$2')
            .replace(/([^=])[\s\n]+<ref(?!erences)/g, '$1<ref')
            .replace(/(\n?)[\s\n]+?<\/ref>/g, '$1</ref>')
            .replace(/([^=])\n+(\=.*?\=\n+)/g, '$1\n\n$2')
            .replace(/^(\={2,}) +[\:,;>&\^#@•→←↔↑↓—–…~٫،؛ٔ]/mg, '$1') // Cleanup headers
            .replace(/[\:,;<&\^#@•→←↔↑↓—–…~٫،؛ٔ] +(\={2,})$/mg, '$1')
            .replace(/^(\={2,}\s*)(«)([^\n«»]*?)(»)(\s*\={2,})/mg, '$1 $3 $5')
            .replace(/^(\={2,}) *'+(.*?)'+ *(\={2,})/mg, '$1 $2 $3')
            .replace(/^[●⚫⬤]/mg, '*') // Wikify bullets in start of lines
            .replace(/^#\s*(REDIRECT|تغییر[ _]?مسیر)/gi, '#تغییرمسیر')
            .replace(/^#تغییرمسیر(?=\S)/g, '#تغییرمسیر ') // Adds a space after #REDIRECT
            .replace(/(\={2,}) *([^\n\r]*?) *(\={2,})/g, '$1 $2 $3') // Format headings level 2 and above
            // فاصله\u200cهای اضافی را از داخل پیوند به بیرون منتقل کند تا اگر اضافه بودند در کدهای دیگر حذف شوند
            .replace(/\[\[(\s*)(.*?)(\s*)\]\]/g, '$1[[$2]]$3')
            // تبدیل به نویسه / یکی کردن فاصله های مجازی پشت سرهم
            .replace(/(\{\{فم\}\}|\&zwnj\;|\u200c+)/g, '\u200c')
            // Full stop and comma should be before citation. See en:WP:REFPUNC
            .replace(/ *((?:<ref[^\/]*?>.*?<\/ref>)+)([\.،,:])?/g, '$2$1')
            .replace(/([^.])([\.،,:]){2}((?:<ref[^\/]*?>.*?<\/ref>)+)/g, '$1$2$3')
            .replace(/ *((?:<ref[^\/]*?\/>)+)([\.،,:])/g, '$2$1')
            .replace(/([^.])([\.،,:]){2}(((?:<ref[^\/]*?\/>)+)+)/g, '$1$2$3')
            .replace(/\{\{(?:DEFAULTSORT|[Dd]efaultsort|ترتیب|ترتیب[\u200c ]پیش[\u200c ]?فرض) *[|:] *(?=.*?}})/g, '{{ترتیب\u200cپیش\u200cفرض:')
            .replace(/\{\{(ترتیب\u200cپیش\u200cفرض|DEFAULTSORT)\:[-\w,\s\(\)]+\}\}\n?/g, '')
            .replace(/(\{\{ترتیب\u200cپیش\u200cفرض\:)\s/g, '$1')
            //نچسبیدن و+فاصله به براکت که محصول اشتباه در تایپ کردن است
            .replace(']]و ', ']] و ')
            .trim();
    }

    function wikiUrlMinifier(text) {
        return text
            .replace(patterns.url, function (x) {
                return replaceExcept(
                    x,
                    function (x) {
                        try {
                            x = decodeURI(x);
                        } catch (e) {
                            mw.notify(e);
                        }
                        return x;
                    }, [patterns.decodeUriBlacklist]
                );
            })

        // Strip the http(s) prefix
        .replace(/\[(https?\:)(?=\/\/(?:[\w\-]+)\.(wiki(pedia|media|data|source|news|oyage|quote)|wiktionary)\.org\/[^\s\]]*)/g, '[');
    }

    function wikiTextDigitsToPersian(text) {
        text = replaceExcept(
            text,
            persianTools.toPersianDigits, [patterns.url, patterns.argumentsBlacklist, patterns.mathTag, patterns.imagePixelSize, patterns.fileNames, patterns.ref,
                patterns.sourceTag, patterns.arabicDigitsEnglishContext, patterns.signatures, patterns.htmlEntity,
                patterns.htmlAttributes, patterns.fileParameter, patterns.templateParameterName, patterns.ipSign,
                patterns.parenthesesAfterDigits, patterns.otherLanguagesInline, patterns.isbn, patterns.englishDate,
                patterns.parameter, patterns.color, patterns.templateEnglishName, patterns.linksOnEnglishContext,
                patterns.colorAsParameter, patterns.tagNames
            ]
        );
        return text
            // Decimal point, and thousands' separator
            .replace(/([۱۲۳۴۵۶۷۸۹۰])\.([۱۲۳۴۵۶۷۸۹۰])/g, '$1٫$2')
            .replace(/([۱۲۳۴۵۶۷۸۹۰]),([۱۲۳۴۵۶۷۸۹۰])/g, '$1٬$2');
    }

    function dictationReplace(x, y, extensions, text) {
        return text.replace(
            new RegExp(
                '(^|[^' + persianTools.persianCharacters + '])(\\s|\u200c|_|)(' + x + ')(\\s|_)(' + y + ')(\\s|\u200c|_|)(' +
                extensions + ')($|[^' + persianTools.persianCharacters + '])',
                'g'
            ),
            '$1$2$3\u200c$5$6$7$8'
        );
    }

    // it has dependency to MediaWiki:Gadget-Extra-Editbuttons-Dictionary.js
    function dictation(text) {
        var i, dictionary = persianToolsDictionary,
            NASB = '\u064b'; // ًـ
        for (i in dictionary.complexes) {
            if (dictionary.complexes.hasOwnProperty(i)) {
                text = dictationReplace(
                    i,
                    dictionary.complexes[i],
                    'ی|ها|های|هایی|هایم|هایت|هایش|هایمان|هایتان|هایشان|',
                    text
                );
            }
        }
        // for last name
        text = dictationReplace(
            dictionary.personNames,
            'ی|زاده|نیا|گان|فر|نژاد|یان|ی\u200cها|یها',
            'ی|',
            text
        );
        // for 'آباد's
        text = dictationReplace(
            dictionary.personNames + '|' + dictionary.addToAbad,
            'آباد',
            'زاده|نیا|پور|گان|فر|نژاد|ی|یان|ها|های|هایی|ی\u200cها|یها|',
            text
        );
        // for first names
        for (i in dictionary.firstNameComplex) {
            if (dictionary.firstNameComplex.hasOwnProperty(i)) {
                text = text.replace(
                    new RegExp(
                        '(^|[^' + persianTools.persianCharacters + ']|\\s|_)(' + i + ')(\\s|_)(' +
                        dictionary.firstNameComplex[i] + ')(\\s|_)($|[^' + persianTools.persianCharacters + ']|[^' +
                        persianTools.persianCharacters + '])',
                        'g'
                    ),
                    '$1$2\u200c$4$5$6'
                );
            }
        }
        // for colors
        text = dictationReplace(
            dictionary.colorsNames,
            'فام|گون',
            'زاده|نیا|پور|گان|فر|نژاد|ی|ها|های|هایی|ی\u200cها|یها|هایم|هایت|هایش|هایمان|هایتان|هایشان|',
            text
        );
        // for numbers
        text = dictationReplace(
            dictionary.persianNumbers,
            'گانه|ماهه',
            'زاده|نیا|پور|گان|فر|نژاد|ی|ها|های|هایی|هایم|هایت|هایش|هایمان|هایتان|هایشان|',
            text
        );
        // wrong dictation
        for (i in dictionary.forReplace) {
            if (dictionary.forReplace.hasOwnProperty(i)) {
                text = text.replace(
                    new RegExp(
                        '(^|[^' + persianTools.persianCharacters + '])(\\s|\u200c|_|)(' + i + ')(\\s|\u200c|_|)($|[^' +
                        persianTools.persianCharacters + '])',
                        'g'
                    ),
                    '$1$2' + dictionary.forReplace[i] + '$4$5'
                );
            }
        }


        // کلماتی که آ دارند
        text = text.replace(
            new RegExp('(^| |_|«|»)(' + dictionary.wordsWithA + ')(ی|ئی|یی|)(?= |«|»|\\.|،|_|$)', 'g'),
            function (x) {
                return x.replace(/ا/i, 'آ');
            } // 'i' is just to trick bidi algorithm on code view
        );

        text = text.replace(/به دست\u200cآورد/g, 'به دست آورد'); // Solving a bug!
        text = persianTools.normalizeZwnj(text);
        return text.replace(new RegExp('([\\s\\n\.،«»؛])(' + dictionary.needsNasb + ')([\\s\\n\.،«»؛])(\\u064b|)', 'g'), '$1$2' + NASB + '$3');
    }

    function wikiDictation(text) {
        return replaceExcept(
            text,
            dictation, [patterns.fileNames, patterns.signatures, patterns.url, patterns.galleryTag, patterns.insideQuote]
        );
    }

    function wikiApplyOrthography(text) {
        return replaceExcept(
            text,
            persianTools.applyOrthography, [patterns.fileNames, patterns.signatures, patterns.url, patterns.galleryTag]
        ).replace(patterns.galleryTag, function (gallery) {
            // apply `applyOrthography` on gallery descriptions separatly
            return gallery.replace(/^([^\|]*?\|)(.*)$/mg, function (x, y, z) {
                return y + persianTools.applyOrthography(z);
            });
        });
    }

    // probably should be exactly same above but for applyZwnj
    function wikiApplyZwnj(text) {
        return replaceExcept(
            text,
            persianTools.applyZwnj, [patterns.fileNames, patterns.signatures, patterns.url, patterns.galleryTag]
        ).replace(patterns.galleryTag, function (gallery) {
            // apply `applyOrthography` on gallery descriptions separatly
            return gallery.replace(/^([^\|]*?\|)(.*)$/mg, function (x, y, z) {
                return y + persianTools.applyZwnj(z);
            });
        });
    }

    function superTool(text) {
        text = persianWikiTools.wikiConvertToPersianCharacters(text);
        text = persianWikiTools.wikiApplyZwnj(text);
        text = persianWikiTools.wikiApplyOrthography(text);
        if (mw.config.get('wgNamespaceNumber') !== 10) {
            text = persianWikiTools.wikiTextDigitsToPersian(text);
        }
        text = persianWikiTools.wikiUrlMinifier(text);
        text = persianWikiTools.wikiDictation(text);
        text = persianWikiTools.wikiPunctuation(text);
        //ابزارهای بیشتر برگرفته از ویکی\u200cپدیای انگلیسی [[Mediawiki:Gadget-Extra-Editbuttons-autoed.js]]
        text = autoEd.autoEdISBN(text);
        text = autoEd.autoEdWhitespace(text);
        // text = autoEd.autoEdWikilinks(text);
        text = autoEd.autoEdHTMLtoWikitext(text);
        text = autoEd.autoEdHeadlines(text);
        // text = autoEd.autoEdTemplates(text);
        text = autoEd.autoEdTablestoWikitext(text);
        text = autoEd.autoEdExtraBreaks(text);
        // text = autoEd.autoEdLinks(text);
        text = persianWikiTools.addColumnToRefTemplate(text);
        return text;
    }

    function superToolMove(text) {
        text = persianWikiTools.wikiConvertToPersianCharacters(text);
        text = persianTools.applyZwnj(text);
        text = persianWikiTools.wikiApplyOrthography(text);
        text = persianWikiTools.wikiTextDigitsToPersian(text);
        text = persianWikiTools.wikiUrlMinifier(text);
        text = persianWikiTools.wikiDictation(text);
        text = persianWikiTools.wikiPunctuation(text);
        return text;
    }

    return {
        superTool: superTool,
        superToolMove: superToolMove,
        dictation: dictation,
        wikiApplyOrthography: wikiApplyOrthography,
        wikiApplyZwnj: wikiApplyZwnj,
        wikiConvertToPersianCharacters: wikiConvertToPersianCharacters,
        wikiDictation: wikiDictation,
        wikiPunctuation: wikiPunctuation,
        wikiUrlMinifier: wikiUrlMinifier,
        wikiTextDigitsToPersian: wikiTextDigitsToPersian,
        addColumnToRefTemplate: addColumnToRefTemplate
    };
}());
if (typeof window !== 'undefined') {
    window.persianWikiTools = persianWikiTools;
}