پرش به محتوا

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

از دانشنامه علوم انسانی
imported>علیرضا
جز خنثی‌سازی ویرایش 14913449 توسط علیرضا (بحث)
imported>Yamaha5
جز ویرایش علیرضا (بحث) به آخرین تغییری که Ebraminio انجام داده بود واگردانده شد
خط ۷: خط ۷:
/*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 = [],
var match, result = [], i, ranges, minRange, to, min, max;
            i, ranges, minRange, to, min, max;
while (text !== '') {
        while (text !== '') {
ranges = [];
            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: /.(کام|نت|آی\u200cآر)/g,
translatedUrl: /.(کام|نت|آی‌آر)/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, [patterns.otherLanguagesInline, patterns.arabicTagEnclosed, patterns.fileNames, patterns.signatures, patterns.url]
persianTools.toStandardPersianCharacters,
        );
[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) {
// این تابع زمانی گیومه را به فارسی تیدیل می‌کند که در پاراگراف مورد نظر تعداد گیومهٔ لاتین زوج باشد.
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
// تبدیل گیومهٔ لاتین به فارسی
// این دستور در ابتدا باشد تا فاصله‌های قبل و بعد گیومه هم اصلاح شود
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');
}
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 quotation(text) {
function wikiUrlMinifier(text) {
            // این تابع زمانی گیومه را به فارسی تیدیل می\u200cکند که در پاراگراف مورد نظر تعداد گیومهٔ لاتین زوج باشد.
return text
            var lines = text.split(/\n\n/);
.replace(patterns.url, function (x) {
            var result = [];
return replaceExcept(
            for (var i = 0; i < lines.length; ++i) {
x,
                var line = lines[i];
function (x) {
                if ((line.match(/"/g) || []).length % 2 === 0) { // count of quote marks
try {
                    // تبدیل گیومهٔ لاتین به فارسی
x = decodeURI(x);
                    // این دستور در ابتدا باشد تا فاصله\u200cهای قبل و بعد گیومه هم اصلاح شود
} catch (e) { mw.notify(e); }
                    line = line.replace(
return x;
                        new RegExp('(^|[' + persianTools.persianCharacters + '،»؛\\s\\n]+)"((?:\\[\\[|).*?[' + persianTools.persianCharacters + '\\n]+?(?:\\]\\]|))"([' + persianTools.persianCharacters + '،«؛\\s\\n$\.])', 'g'),
},
                        '$1«$2»$3'
[patterns.decodeUriBlacklist]
                    );
);
                    // 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('}}', '|۲}}'));
        }
       
        return text;
    }


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


        // Strip the http(s) prefix
function dictationReplace(x, y, extensions, text) {
        .replace(/\[(https?\:)(?=\/\/(?:[\w\-]+)\.(wiki(pedia|media|data|source|news|oyage|quote)|wiktionary)\.org\/[^\s\]]*)/g, '[');
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'
);
}


    function wikiTextDigitsToPersian(text) {
// it has dependency to MediaWiki:Gadget-Extra-Editbuttons-Dictionary.js
        text = replaceExcept(
function dictation(text) {
            text,
var i, dictionary = persianToolsDictionary, NASB = '\u064b'; // ًـ
            persianTools.toPersianDigits, [patterns.url, patterns.argumentsBlacklist, patterns.mathTag, patterns.imagePixelSize, patterns.fileNames, patterns.ref,
for (i in dictionary.complexes) {
                patterns.sourceTag, patterns.arabicDigitsEnglishContext, patterns.signatures, patterns.htmlEntity,
if (dictionary.complexes.hasOwnProperty(i)) {
                patterns.htmlAttributes, patterns.fileParameter, patterns.templateParameterName, patterns.ipSign,
text = dictationReplace(
                patterns.parenthesesAfterDigits, patterns.otherLanguagesInline, patterns.isbn, patterns.englishDate,
i,
                patterns.parameter, patterns.color, patterns.templateEnglishName, patterns.linksOnEnglishContext,
dictionary.complexes[i],
                patterns.colorAsParameter, patterns.tagNames
'ی|ها|های|هایی|هایم|هایت|هایش|هایمان|هایتان|هایشان|',
            ]
text
        );
);
        return text
}
            // Decimal point, and thousands' separator
}
            .replace(/([۱۲۳۴۵۶۷۸۹۰])\.([۱۲۳۴۵۶۷۸۹۰])/g, '$1٫$2')
// for last name
            .replace(/([۱۲۳۴۵۶۷۸۹۰]),([۱۲۳۴۵۶۷۸۹۰])/g, '$1٬$2');
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'
);
}
}


    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) {
text = text.replace(
        var i, dictionary = persianToolsDictionary,
new RegExp('(^| |_|«|»)(' + dictionary.wordsWithA + ')(ی|ئی|یی|)(?= |«|»|\\.|،|_|$)', 'g'),
            NASB = '\u064b'; // ًـ
function (x) { return x.replace(/ا/i, 'آ'); } // 'i' is just to trick bidi algorithm on code view
        for (i in dictionary.complexes) {
);
            if (dictionary.complexes.hasOwnProperty(i)) {
                text = dictationReplace(
text = text.replace(/به دست\u200cآورد/g, 'به دست آورد'); // Solving a bug!
                    i,
text = persianTools.normalizeZwnj(text);
                    dictionary.complexes[i],
return text.replace(new RegExp('([\\s\\n\.،«»؛])(' + dictionary.needsNasb + ')([\\s\\n\.،«»؛])(\\u064b|)', 'g'), '$1$2' + NASB +'$3');
                    'ی|ها|های|هایی|هایم|هایت|هایش|هایمان|هایتان|هایشان|',
}
                    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'
                );
            }
        }


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);
//ابزارهای بیشتر برگرفته از ویکی‌پدیای انگلیسی [[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);
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 {
        text = text.replace(
superTool: superTool,
            new RegExp('(^| |_|«|»)(' + dictionary.wordsWithA + ')(ی|ئی|یی|)(?= |«|»|\\.|،|_|$)', 'g'),
superToolMove: superToolMove,
            function (x) {
dictation: dictation,
                return x.replace(/ا/i, 'آ');
wikiApplyOrthography: wikiApplyOrthography,
            } // 'i' is just to trick bidi algorithm on code view
wikiApplyZwnj: wikiApplyZwnj,
        );
wikiConvertToPersianCharacters: wikiConvertToPersianCharacters,
 
wikiDictation: wikiDictation,
        text = text.replace(/به دست\u200cآورد/g, 'به دست آورد'); // Solving a bug!
wikiPunctuation: wikiPunctuation,
        text = persianTools.normalizeZwnj(text);
wikiUrlMinifier: wikiUrlMinifier,
        return text.replace(new RegExp('([\\s\\n\.،«»؛])(' + dictionary.needsNasb + ')([\\s\\n\.،«»؛])(\\u064b|)', 'g'), '$1$2' + NASB + '$3');
wikiTextDigitsToPersian: wikiTextDigitsToPersian
    }
};
 
    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') {
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: /.(کام|نت|آی‌آر)/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) {
		// این تابع زمانی گیومه را به فارسی تیدیل می‌کند که در پاراگراف مورد نظر تعداد گیومهٔ لاتین زوج باشد.
		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
				// تبدیل گیومهٔ لاتین به فارسی
				// این دستور در ابتدا باشد تا فاصله‌های قبل و بعد گیومه هم اصلاح شود
				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');
	}
	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) {
		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);
		//ابزارهای بیشتر برگرفته از ویکی‌پدیای انگلیسی [[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);
		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
	};
}());
if (typeof window !== "undefined") {
	window.persianWikiTools = persianWikiTools;
}