跳转到内容

MediaWiki:Gadget-DotsSyntaxHighlighter.js:修订间差异

勤求古训,博采众方
无编辑摘要
鹿野耕云留言 | 贡献
无编辑摘要
 
(未显示2个用户的8个中间版本)
第1行: 第1行:
//Syntax highlighter with various advantages
//See [[User:Remember the dot/Syntax highlighter]] for more information
/* This file may be used under the terms of any of the following
  licenses, as well as any later version of the same licenses:
  GNU General Public License 2.0
  <https://www.gnu.org/licenses/old-licenses/gpl-2.0.html>
  Creative Commons Attribution-ShareAlike 3.0 Unported License
  <https://creativecommons.org/licenses/by-sa/3.0/>
  GNU Free Documentation License 1.2
  <https://www.gnu.org/licenses/old-licenses/fdl-1.2.html>
*/
mw.loader.using("jquery.client", function() {
mw.loader.using("jquery.client", function() {
     "use strict";
     "use strict";
   
    // 安全的配置访问函数
    function safeConfigAccess(config, property, defaultValue) {
        if (!config || !config[property]) return defaultValue;
        return config[property];
    }
   
    // CSS颜色值验证函数
    function isValidCSSColor(colorValue) {
        if (!colorValue || typeof colorValue !== 'string') return false;
       
        // 移除前后空格
        colorValue = colorValue.trim();
       
        // 检查常见CSS颜色格式
        var colorFormats = [
            // 十六进制颜色 (#FFF, #FFFFFF)
            /^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})$/,
            // RGB颜色 (rgb(255,255,255))
            /^rgb\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*\)$/,
            // RGBA颜色 (rgba(255,255,255,0.5))
            /^rgba\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*(0|1|0\.\d+)\s*\)$/,
            // HSL颜色 (hsl(120,100%,50%))
            /^hsl\(\s*\d{1,3}\s*,\s*\d{1,3}%\s*,\s*\d{1,3}%\s*\)$/,
            // HSLA颜色 (hsla(120,100%,50%,0.5))
            /^hsla\(\s*\d{1,3}\s*,\s*\d{1,3}%\s*,\s*\d{1,3}%\s*,\s*(0|1|0\.\d+)\s*\)$/,
            // 命名颜色 (red, blue, transparent)
            /^(transparent|inherit|initial|unset|currentColor|revert|revert-layer)$/i
        ];
       
        // 检查是否为有效的CSS命名颜色
        var namedColors = [
            'black', 'silver', 'gray', 'white', 'maroon', 'red', 'purple', 'fuchsia',
            'green', 'lime', 'olive', 'yellow', 'navy', 'blue', 'teal', 'aqua',
            'orange', 'aliceblue', 'antiquewhite', 'aquamarine', 'azure', 'beige',
            'bisque', 'blanchedalmond', 'blueviolet', 'brown', 'burlywood', 'cadetblue',
            'chartreuse', 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson',
            'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray', 'darkgreen',
            'darkgrey', 'darkkhaki', 'darkmagenta', 'darkolivegreen', 'darkorange',
            'darkorchid', 'darkred', 'darksalmon', 'darkseagreen', 'darkslateblue',
            'darkslategray', 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink',
            'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick', 'floralwhite',
            'forestgreen', 'gainsboro', 'ghostwhite', 'gold', 'goldenrod', 'greenyellow',
            'grey', 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', 'khaki',
            'lavender', 'lavenderblush', 'lawngreen', 'lemonchiffon', 'lightblue',
            'lightcoral', 'lightcyan', 'lightgoldenrodyellow', 'lightgray', 'lightgreen',
            'lightgrey', 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue',
            'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow', 'limegreen',
            'linen', 'magenta', 'mediumaquamarine', 'mediumblue', 'mediumorchid',
            'mediumpurple', 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen',
            'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream', 'mistyrose',
            'moccasin', 'navajowhite', 'oldlace', 'olivedrab', 'orangered', 'orchid',
            'palegoldenrod', 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip',
            'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'rosybrown', 'royalblue',
            'saddlebrown', 'salmon', 'sandybrown', 'seagreen', 'seashell', 'sienna',
            'skyblue', 'slateblue', 'slategray', 'slategrey', 'snow', 'springgreen',
            'steelblue', 'tan', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat',
            'whitesmoke', 'yellowgreen'
        ];
       
        // 检查格式匹配
        for (var i = 0; i < colorFormats.length; i++) {
            if (colorFormats[i].test(colorValue)) {
                return true;
            }
        }
       
        // 检查命名颜色
        if (namedColors.indexOf(colorValue.toLowerCase()) !== -1) {
            return true;
        }
       
        return false;
    }
   
    // 安全的颜色配置访问函数
    function safeColorAccess(config, property, defaultValue) {
        var colorValue = safeConfigAccess(config, property, defaultValue);
       
        // 如果颜色值为"normal",返回默认值
        if (colorValue === "normal") {
            return defaultValue;
        }
       
        // 验证颜色值有效性
        if (colorValue && !isValidCSSColor(colorValue)) {
            console.warn('Invalid CSS color value for ' + property + ': "' + colorValue + '", using default: "' + defaultValue + '"');
            return defaultValue;
        }
       
        return colorValue || defaultValue;
    }
   
    // 查找匹配的标签结束位置,处理嵌套标签
    function findMatchingTagEnd(text, startPos, tagName) {
        var openTag = "<" + tagName + ">";
        var closeTag = "</" + tagName + ">";
        var stack = 1; // 当前已经有一个开始标签
        var pos = startPos;
       
        while (pos < text.length) {
            var nextOpen = text.indexOf(openTag, pos);
            var nextClose = text.indexOf(closeTag, pos);
           
            // 如果找不到闭合标签,返回文本末尾
            if (nextClose === -1) return text.length;
           
            // 如果下一个开始标签在闭合标签之前,增加栈深度
            if (nextOpen !== -1 && nextOpen < nextClose) {
                stack++;
                pos = nextOpen + openTag.length;
            } else {
                stack--;
                pos = nextClose + closeTag.length;
               
                // 如果栈为空,返回当前闭合标签的结束位置
                if (stack === 0) return pos;
            }
        }
       
        return text.length; // 如果找不到匹配的闭合标签,返回文本末尾
    }
   
    var e = mw.config.get("wgUrlProtocols"),
        r = "&(?:(?:n(?:bsp|dash)|m(?:dash|inus)|lt|e[mn]sp|thinsp|amp|quot|gt|shy|zwnj|lrm|rlm|Alpha|Beta|Epsilon|Zeta|Eta|Iota|Kappa|[Mm]u|micro|Nu|[Oo]micron|[Rr]ho|Tau|Upsilon|Chi)|#x[0-9a-fA-F]+);\\n*",
        t = "\\[(?:\\[|(?:" + e + "))|\\{(?:\\{\\{?|\\|)|<(?:[:A-Z_a-z][-:\\w]*(?=/?>| |\\n)|!--[\\s\\S]*?-->\\n*)|(?:" + e + ")[^\\s\"<>[\\]{-}]*[^\\s\",\\.:;<>[\\]{-}]\\n*|^(?:=|[*#:;]+\\n*|-{4,}\\n*)|\\\\'\\\\'(?:\\\\')?|~{3,5}\\n*|" + r,
        l = null, g = null, d = null, c = "", y = null, p = null, f = null, b = -1,
        lastText = ""; // 记录上一次的文本内容


    //variables that are preserved between function calls
     var regexCache = {};
    var wpTextbox0;
      
    var wpTextbox1;
     function C(e) {
    var syntaxStyleTextNode;
        var cacheKey = e;
    var lastText;
        if (!regexCache[cacheKey]) {
     var maxSpanNumber = -1; //the number of the last span available, used to tell if creating additional spans is necessary
            try {
     var highlightSyntaxIfNeededIntervalID;
                regexCache[cacheKey] = new RegExp("(" + e + ")\\n*|" + t, "gm");
     var attributeObserver;
            } catch (err) {
    var parentObserver;
                console.error("Syntax highlighter: 正则表达式构建失败", err, "e:", e);
 
                regexCache[cacheKey] = new RegExp(t, "gm"); // 使用默认正则降级
    /* Define context-specific regexes, one for every common token that ends the
            }
      current context.
         }
 
         return regexCache[cacheKey];
      An attempt has been made to search for the most common syntaxes first,
      thus maximizing performance. Syntaxes that begin with the same character
      are searched for at the same time.
 
      Supported wiki syntaxes from most common to least common:
          [[internal link]] [http:// named external link]
          {{template}} {{{template parameter}}} {| table |}
          <tag> <!-- comment -->
          http:// bare external link
          =Heading= * unordered list # ordered list : indent ; small heading ---- horizontal line
          ''italic'' '''bold'''
          three tildes username four tildes signature five tildes timestamp
          &entity;
 
      The tag-matching regex follows the XML standard closely so that users
      won't feel like they have to escape sequences that MediaWiki will never
      consider to be tags.
 
      Only entities for characters which need to be escaped or cannot be
      unambiguously represented in a monospace font are highlighted, such as
      Greek letters that strongly resemble Latin letters. Use of other entities
      is discouraged as a matter of style. For the same reasons, numeric
      entities should be in hexadecimal (giving character codes in decimal only
      adds confusion).
 
      Newlines are sucked up into ending tokens (including comments, bare
      external links, lists, horizontal lines, signatures, entities, etc.) to
      avoid creating spans with nothing but newlines in them.
 
      Flags: g for global search, m for make ^ match the beginning of each line
      and $ the end of each line
    */
    var wgUrlProtocols = mw.config.get("wgUrlProtocols");
    var entityRegexBase = "&(?:(?:n(?:bsp|dash)|m(?:dash|inus)|lt|e[mn]sp|thinsp|amp|quot|gt|shy|zwn?j|lrm|rlm|Alpha|Beta|Epsilon|Zeta|Eta|Iota|Kappa|[Mm]u|micro|Nu|[Oo]micron|[Rr]ho|Tau|Upsilon|Chi)|#x[0-9a-fA-F]+);\n*";
    var breakerRegexBase = "\\[(?:\\[|(?:" + wgUrlProtocols + "))|\\{(?:\\{\\{?|\\|)|<(?:[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:\\w\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD-\\.\u00B7\u0300-\u036F\u203F-\u203F-\u2040]*(?=/?>| |\n)|!--[^]*?-->\n*)|(?:" + wgUrlProtocols.replace("|\\/\\/", "") + ")[^\\s\"<>[\\]{-}]*[^\\s\",\\.:;<>[\\]{-}]\n*|^(?:=|[*#:;]+\n*|-{4,}\n*)|\\\\'\\\\'(?:\\\\')?|~{3,5}\n*|" + entityRegexBase;
    function breakerRegexWithPrefix(prefix)
    {
         //the stop token has to be at the beginning of the regex so that it takes precedence over substrings of itself.
         return new RegExp("(" + prefix + ")\n*|" + breakerRegexBase, "gm");
     }
     }
    function nowikiTagBreakerRegex(tagName)
    {
        return new RegExp("(</" + tagName + ">)\n*|" + entityRegexBase, "gm");
    }
    var defaultBreakerRegex          = new RegExp(breakerRegexBase, "gm");
    var wikilinkBreakerRegex          = breakerRegexWithPrefix("]][a-zA-Z]*");
    var namedExternalLinkBreakerRegex = breakerRegexWithPrefix("]");
    var parameterBreakerRegex        = breakerRegexWithPrefix("}}}");
    var templateBreakerRegex          = breakerRegexWithPrefix("}}");
    var tableBreakerRegex            = breakerRegexWithPrefix("\\|}");
    var headingBreakerRegex          = breakerRegexWithPrefix("\n");
    var tagBreakerRegexCache          = {};
    var nowikiTagBreakerRegexCache    = {};


     function highlightSyntax()
     var x = new RegExp(t, "gm"),
    {
        k = C("]][a-zA-Z]*"),
         lastText = wpTextbox1.value;
         v = C("]"),
         /* Backslashes and apostrophes are CSS-escaped at the beginning and all
         w = C("}}}"),
          parsing regexes and functions are designed to match. On the other hand,
        z = C("}}"),
          newlines are not escaped until written so that in the regexes ^ and $
         H = C("\\|}"),
          work for both newlines and the beginning or end of the string. */
        S = C("\\n"),
         var text = lastText.replace(/['\\]/g, "\\$&") + "\n"; //add a newline to fix scrolling and parsing issues
        T = {},
         var i = 0; //the location of the parser as it goes through var text
         L = {};


        var css = "";
    // 增量更新状态管理
         var spanNumber = 0;
    var lastHighlightState = null,
         var lastColor;
         lastSpanCount = 0,
         spanCache = {};


        //writes text into to-be-created span elements of wpTextbox0 using ::after pseudo-elements
    function E() {
        function writeText(text, color)
         try {
         {
            var currentText = g.value;
             //no need to use another span if using the same color
           
             if (color != lastColor)
             // 增量更新检查:如果文本内容没有变化,直接返回
            {
             if (currentText === lastText) {
                 css += "'}";
                 return;
                //whitespace is omitted in the hope of increasing performance
            }
                if (color)
           
                 {
            // 增量更新优化:计算文本变化范围并用于局部解析
                    //"background-color" is 6 characters longer than "background" but the browser processes it faster
            var changeStart = 0, changeEnd = currentText.length;
                    css += "#s" + spanNumber + "{background-color:" + color + "}";
            var isIncrementalUpdate = false;
           
            if (lastText && currentText !== lastText) {
                 // 找到文本变化的起始位置
                for (changeStart = 0; changeStart < Math.min(currentText.length, lastText.length); changeStart++) {
                    if (currentText[changeStart] !== lastText[changeStart]) break;
                 }
                 }
                 css += "#s" + spanNumber + "::after{content:'"; //spans will be created with IDs s0 through sN
                  
                 lastColor = color;
                // 找到文本变化的结束位置(从末尾开始比较)
                 ++spanNumber;
                for (changeEnd = 0; changeEnd < Math.min(currentText.length, lastText.length); changeEnd++) {
                    if (currentText[currentText.length - 1 - changeEnd] !== lastText[lastText.length - 1 - changeEnd]) break;
                }
                changeEnd = currentText.length - changeEnd;
               
                // 判断是否适合增量更新:变化范围较小且不在语法结构边界
                isIncrementalUpdate = (changeEnd - changeStart) < Math.min(currentText.length * 0.3, 200) &&
                                    changeStart > 0 && changeEnd < currentText.length;
            }
           
            lastText = currentText;
           
            // 确保b变量有正确的初始值
            if (b === -1) {
                // 如果是第一次运行,需要初始化b为当前span数量
                 var existingSpans = l.querySelectorAll('span[id^="s"]');
                 b = existingSpans.length;
             }
             }
             css += text;
        } catch (error) {
             // 捕获正则匹配和DOM操作中的异常
            console.error('Syntax highlighter error:', error);
            return;
         }
         }
       
        var i, h = (c = currentText).replace(/['\\]/g, "\\$&") + "\\n",
            m = 0,
            o = "",
            r = 0;


         /* About assumedBold and assumedItalic:
         // 最大递归深度限制
        var MAX_RECURSION_DEPTH = 1000;


          Highlighting bold or italic markup presents a special challenge
        function u(e, t) {
          because the actual MediaWiki parser uses multiple passes to determine
            t != i && (o += "'}", t && (o += "#s" + r + "{background-color:" + t + "}"), o += "#s" + r + "::after{content:'", i = t, ++r), o += e;
          which ticks represent start tags and which represent end tags.
        }
          Because that would be too slow for us here, we instead keep track of
          what kinds of unclosed opening ticks have been encountered and use
          that to make a good guess as to whether the next ticks encountered
          are an opening tag or a closing tag.


          The major downsides to this method are that '''apostrophe italic''
        var e = Date.now();
          and ''italic apostrophe''' are not highlighted correctly, and bold
          and italic are both highlighted in the same color.


          To permit ''The best<ref>''Reference Title''</ref> book ever'',
        // 精确增量更新:基于changeStart和changeEnd的局部解析
          assumedBold and assumedItalic are saved on the stack and reset to
        if (isIncrementalUpdate && lastHighlightState) {
          undefined (essentially, false) when recursing into a new block. */
            // 方法1:智能边界定位(当前实现)- 基于CSS状态复用
            var startMarker = "#s" + (Math.floor(changeStart / 50)) + "::after";
            var markerIndex = lastHighlightState.indexOf(startMarker);
            if (markerIndex !== -1) {
                var prefixCSS = lastHighlightState.substring(0, markerIndex);
                // 确保CSS语法完整
                if (prefixCSS.endsWith("'}")) {
                    o = prefixCSS;
                    r = Math.floor(changeStart / 50);
                    m = changeStart;
                }
            }
           
            // 方法2:语法边界检测(高级优化)- 需要修改递归逻辑
            // 检测变化点前后的语法结构,确保解析上下文正确
            var syntaxBoundaryStart = findSyntaxBoundary(currentText, changeStart, -1); // 向前查找语法边界
            var syntaxBoundaryEnd = findSyntaxBoundary(currentText, changeEnd, 1);      // 向后查找语法边界
           
            if (syntaxBoundaryStart >= 0 && syntaxBoundaryEnd <= currentText.length) {
                // 如果找到合适的语法边界,使用精确的局部解析
                m = Math.max(0, syntaxBoundaryStart);
                // 这里需要修改递归解析函数以支持从指定位置开始解析
                console.log("精确增量更新:从位置", m, "开始解析");
            }
        } else {
            // 如果不是增量更新或lastHighlightState为null,确保从文本开头开始解析
            m = 0;
            o = "";
            r = 0;
        }
       
        // 语法边界检测辅助函数 - 增强wikitext专属边界检测
        function findSyntaxBoundary(text, position, direction) {
            var boundary = position;
            var maxSearch = 100; // 最大搜索范围
           
            // wikitext专属语法边界列表(按优先级排序)
            var wikitextBoundaries = [
                // 多字符边界(高优先级)
                '[[', ']]', '{{', '}}', '{{{', '}}}', '{|', '|}', '<!--', '-->',
                // 单字符边界
                '\n', '>', '}', ']', '=', '<', '|', ';', '*', '#', ':', '-', '~', '\\', '&'
            ];
           
            for (var i = 0; i < maxSearch; i++) {
                var currentPos = boundary + (direction * i);
                if (currentPos < 0 || currentPos >= text.length) break;
               
                // 优先检测多字符wikitext边界
                for (var j = 0; j < wikitextBoundaries.length; j++) {
                    var boundaryStr = wikitextBoundaries[j];
                    if (boundaryStr.length > 1) {
                        // 多字符边界检测
                        if (currentPos + boundaryStr.length <= text.length &&
                            text.substring(currentPos, currentPos + boundaryStr.length) === boundaryStr) {
                            return currentPos + (direction > 0 ? boundaryStr.length : 0);
                        }
                    } else {
                        // 单字符边界检测
                        if (text.charAt(currentPos) === boundaryStr) {
                            return currentPos + (direction > 0 ? 1 : 0);
                        }
                    }
                }
            }
           
            return direction > 0 ? text.length : 0;
        }


         function highlightBlock(color, breakerRegex, assumedBold, assumedItalic)
         // 基于显式调用栈的迭代解析器
         {
        var stack = [{
            text: h,
            pos: m,
            regex: x,
            color: "",
            boldState: false,
            italicState: false,
            context: "root"
        }];
       
        var MAX_STACK_DEPTH = 1000; // 最大栈深度限制
       
         while (stack.length > 0 && stack.length < MAX_STACK_DEPTH) {
            var currentTask = stack.pop();
            var text = currentTask.text;
            var pos = currentTask.pos;
            var regex = currentTask.regex;
            var color = currentTask.color;
            var boldState = currentTask.boldState;
            var italicState = currentTask.italicState;
            var context = currentTask.context;
           
            // 处理当前解析任务
             var match;
             var match;
 
             regex.lastIndex = pos;
             for (breakerRegex.lastIndex = i; match = breakerRegex.exec(text); breakerRegex.lastIndex = i)
           
            {
            while ((match = regex.exec(text)) !== null) {
                 if (match[1])
                 if (match[1]) {
                {
                     // 匹配到结束标记,处理剩余文本并返回
                     //end token found
                     u(text.substring(pos, regex.lastIndex), color);
                     writeText(text.substring(i, breakerRegex.lastIndex), color);
                     m = regex.lastIndex;
                     i = breakerRegex.lastIndex;
                     break;
                     return;
                 }
                 }
 
               
                 var endIndexOfLastColor = breakerRegex.lastIndex - match[0].length;
                 var matchStart = regex.lastIndex - match[0].length;
                 if (i < endIndexOfLastColor) //avoid calling writeText with text == "" to improve performance
               
                {
                // 处理匹配前的文本
                     writeText(text.substring(i, endIndexOfLastColor), color);
                 if (pos < matchStart) {
                     u(text.substring(pos, matchStart), color);
                 }
                 }
 
               
                 i = breakerRegex.lastIndex;
                 pos = regex.lastIndex;
 
               
                 switch (match[0].charAt(0)) //cases in this switch should be arranged from most common to least common
                // 根据匹配内容处理不同的语法元素
                {
                 switch (match[0].charAt(0)) {
                     case "[":
                     case "[":
                         if (match[0].charAt(1) == "[")
                         if (match[0].charAt(1) === "[") {
                        {
                             // 内部链接 [[...]]
                             //wikilink
                             u("[[", safeColorAccess(syntaxHighlighterConfig, 'wikilinkColor', color) || color);
                             writeText("[[", syntaxHighlighterConfig.wikilinkColor || color);
                             stack.push({
                             highlightBlock(syntaxHighlighterConfig.wikilinkColor || color, wikilinkBreakerRegex);
                                text: text,
                         }
                                pos: pos,
                        else
                                regex: k,
                        {
                                color: safeColorAccess(syntaxHighlighterConfig, 'wikilinkColor', color) || color,
                             //named external link
                                boldState: boldState,
                             writeText(match[0], syntaxHighlighterConfig.externalLinkColor || color);
                                italicState: italicState,
                             highlightBlock(syntaxHighlighterConfig.externalLinkColor || color, namedExternalLinkBreakerRegex);
                                context: "wikilink"
                            });
                         } else {
                             // 外部链接 [...]
                             u(match[0], safeColorAccess(syntaxHighlighterConfig, 'externalLinkColor', color) || color);
                             stack.push({
                                text: text,
                                pos: pos,
                                regex: v,
                                color: safeColorAccess(syntaxHighlighterConfig, 'externalLinkColor', color) || color,
                                boldState: boldState,
                                italicState: italicState,
                                context: "externalLink"
                            });
                         }
                         }
                         break;
                         break;
                   
                     case "{":
                     case "{":
                         if (match[0].charAt(1) == "{")
                         if (match[0].charAt(1) === "{") {
                        {
                             if (match[0].length === 3) {
                             if (match[0].length == 3)
                                 // 参数 {{{...}}}
                            {
                                 u("{{{", safeColorAccess(syntaxHighlighterConfig, 'parameterColor', color) || color);
                                 //parameter
                                 stack.push({
                                 writeText("{{{", syntaxHighlighterConfig.parameterColor || color);
                                    text: text,
                                 highlightBlock(syntaxHighlighterConfig.parameterColor || color, parameterBreakerRegex);
                                    pos: pos,
                             }
                                    regex: w,
                            else
                                    color: safeColorAccess(syntaxHighlighterConfig, 'parameterColor', color) || color,
                            {
                                    boldState: boldState,
                                 //template
                                    italicState: italicState,
                                 writeText("{{", syntaxHighlighterConfig.templateColor || color);
                                    context: "parameter"
                                 highlightBlock(syntaxHighlighterConfig.templateColor || color, templateBreakerRegex);
                                });
                             } else {
                                 // 模板 {{...}}
                                 u("{{", safeColorAccess(syntaxHighlighterConfig, 'templateColor', color) || color);
                                 stack.push({
                                    text: text,
                                    pos: pos,
                                    regex: z,
                                    color: safeColorAccess(syntaxHighlighterConfig, 'templateColor', color) || color,
                                    boldState: boldState,
                                    italicState: italicState,
                                    context: "template"
                                });
                             }
                             }
                         }
                         } else {
                        else //|
                             // 表格 {|...|}
                        {
                             u("{|", safeColorAccess(syntaxHighlighterConfig, 'tableColor', color) || color);
                             //table
                             stack.push({
                             writeText("{|", syntaxHighlighterConfig.tableColor || color);
                                text: text,
                             highlightBlock(syntaxHighlighterConfig.tableColor || color, tableBreakerRegex);
                                pos: pos,
                                regex: H,
                                color: safeColorAccess(syntaxHighlighterConfig, 'tableColor', color) || color,
                                boldState: boldState,
                                italicState: italicState,
                                context: "table"
                            });
                         }
                         }
                         break;
                         break;
                   
                     case "<":
                     case "<":
                         if (match[0].charAt(1) == "!")
                         if (match[0].charAt(1) === "!") {
                        {
                             // 注释 <!-- ... -->
                             //comment tag
                             u(match[0], safeColorAccess(syntaxHighlighterConfig, 'commentColor', color) || color);
                             writeText(match[0], syntaxHighlighterConfig.commentColor || color);
                         } else {
                            break;
                             // HTML标签
                         }
                             var tagEnd = text.indexOf(">", pos) + 1;
                        else
                             if (tagEnd === 0) {
                        {
                                 u("<", color);
                             //some other kind of tag, search for its end
                                 pos = pos - match[0].length + 1;
                            //the search is made easier because XML attributes may not contain the character ">"
                             } else {
                             var tagEnd = text.indexOf(">", i) + 1;
                             if (tagEnd == 0)
                            {
                                 //not a tag, just a "<" with some text after it
                                writeText("<", color);
                                 i = i - match[0].length + 1;
                                break;
                             }
 
                            if (text.charAt(tagEnd - 2) == "/")
                            {
                                //empty tag
                                writeText(text.substring(i - match[0].length, tagEnd), syntaxHighlighterConfig.tagColor || color);
                                i = tagEnd;
                            }
                            else
                            {
                                 var tagName = match[0].substring(1);
                                 var tagName = match[0].substring(1);
 
                               
                                 if (syntaxHighlighterConfig.sourceTags.indexOf(tagName) != -1)
                                 if (text.charAt(tagEnd - 2) !== "/") {
                                {
                                    if (safeConfigAccess(syntaxHighlighterConfig, 'voidTags', []).indexOf(tagName) === -1) {
                                    //tag that contains text in a different programming language
                                        if (safeConfigAccess(syntaxHighlighterConfig, 'sourceTags', []).indexOf(tagName) !== -1) {
                                    var stopAfter = "</" + tagName + ">";
                                            // 源代码标签
                                    var endIndex = text.indexOf(stopAfter, i);
                                            var closeTag = "</" + tagName + ">";
                                    if (endIndex == -1)
                                            var tagEndPos = findMatchingTagEnd(text, pos, tagName);
                                    {
                                            u(text.substring(pos - match[0].length, tagEndPos), safeColorAccess(syntaxHighlighterConfig, 'tagColor', color) || color);
                                        endIndex = text.length;
                                            pos = tagEndPos;
                                    }
                                        } else if (safeConfigAccess(syntaxHighlighterConfig, 'nowikiTags', []).indexOf(tagName) !== -1) {
                                    else
                                            // nowiki标签
                                    {
                                            u(text.substring(pos - match[0].length, tagEnd), safeColorAccess(syntaxHighlighterConfig, 'tagColor', color) || color);
                                        endIndex += stopAfter.length;
                                            pos = tagEnd;
                                    }
                                            stack.push({
                                    writeText(text.substring(i - match[0].length, endIndex), syntaxHighlighterConfig.tagColor || color);
                                                text: text,
                                    i = endIndex;
                                                pos: pos,
                                }
                                                regex: L[tagName] || (L[tagName] = C("</" + tagName + ">")),
                                else if (syntaxHighlighterConfig.nowikiTags.indexOf(tagName) != -1)
                                                color: safeColorAccess(syntaxHighlighterConfig, 'tagColor', color) || color,
                                {
                                                boldState: boldState,
                                    //tag that can contain only HTML entities
                                                italicState: italicState,
                                    writeText(text.substring(i - match[0].length, tagEnd), syntaxHighlighterConfig.tagColor || color);
                                                context: "tag"
                                    i = tagEnd;
                                            });
                                    highlightBlock(syntaxHighlighterConfig.tagColor || color, nowikiTagBreakerRegexCache[tagName]);
                                        } else {
                                }
                                            // 普通标签
                                else
                                            u(text.substring(pos - match[0].length, tagEnd), safeColorAccess(syntaxHighlighterConfig, 'tagColor', color) || color);
                                {
                                            pos = tagEnd;
                                    //ordinary tag
                                            T[tagName] = T[tagName] || C("</" + tagName + ">");
                                    writeText(text.substring(i - match[0].length, tagEnd), syntaxHighlighterConfig.tagColor || color);
                                            stack.push({
                                    i = tagEnd;
                                                text: text,
                                    if (!tagBreakerRegexCache[tagName])
                                                pos: pos,
                                    {
                                                regex: T[tagName],
                                        tagBreakerRegexCache[tagName] = breakerRegexWithPrefix("</" + tagName + ">");
                                                color: safeColorAccess(syntaxHighlighterConfig, 'tagColor', color) || color,
                                                boldState: boldState,
                                                italicState: italicState,
                                                context: "tag"
                                            });
                                        }
                                    } else {
                                        u(text.substring(pos - match[0].length, tagEnd), safeColorAccess(syntaxHighlighterConfig, 'tagColor', color) || color);
                                        pos = tagEnd;
                                     }
                                     }
                                     highlightBlock(syntaxHighlighterConfig.tagColor || color, tagBreakerRegexCache[tagName]);
                                } else {
                                     u(text.substring(pos - match[0].length, tagEnd), safeColorAccess(syntaxHighlighterConfig, 'tagColor', color) || color);
                                    pos = tagEnd;
                                 }
                                 }
                             }
                             }
                         }
                         }
                         break;
                         break;
                   
                     case "=":
                     case "=":
                         if (/[^=]=+$/.test(text.substring(i, text.indexOf("\n", i)))) //the line begins and ends with an equals sign and has something else in the middle
                         if (/[^=]=+$/.test(text.substring(pos, text.indexOf("\\n", pos)))) {
                        {
                             // 标题
                             //heading
                             u("=", safeColorAccess(syntaxHighlighterConfig, 'headingColor', color) || color);
                             writeText("=", syntaxHighlighterConfig.headingColor || color);
                             stack.push({
                             highlightBlock(syntaxHighlighterConfig.headingColor || color, headingBreakerRegex);
                                text: text,
                         }
                                pos: pos,
                        else
                                regex: S,
                        {
                                color: safeColorAccess(syntaxHighlighterConfig, 'headingColor', color) || color,
                             writeText("=", color); //move on, process this line as regular wikitext
                                boldState: boldState,
                                italicState: italicState,
                                context: "heading"
                            });
                         } else {
                             u("=", color);
                         }
                         }
                         break;
                         break;
                   
                     case "*":
                     case "*":
                     case "#":
                     case "#":
                     case ":":
                     case ":":
                         //unordered list, ordered list, indent, small heading
                         // 列表和缩进
                        //just highlight the marker
                         u(match[0], safeColorAccess(syntaxHighlighterConfig, 'listOrIndentColor', color) || color);
                         writeText(match[0], syntaxHighlighterConfig.listOrIndentColor || color);
                         break;
                         break;
                   
                     case ";":
                     case ";":
                         //small heading
                         // 定义列表
                         writeText(";", syntaxHighlighterConfig.headingColor || color);
                         u(";", safeColorAccess(syntaxHighlighterConfig, 'headingColor', color) || color);
                         highlightBlock(syntaxHighlighterConfig.headingColor || color, headingBreakerRegex);
                         stack.push({
                            text: text,
                            pos: pos,
                            regex: S,
                            color: safeColorAccess(syntaxHighlighterConfig, 'headingColor', color) || color,
                            boldState: boldState,
                            italicState: italicState,
                            context: "heading"
                        });
                         break;
                         break;
                   
                     case "-":
                     case "-":
                         //horizontal line
                         // 水平线
                         writeText(match[0], syntaxHighlighterConfig.hrColor || color);
                         u(match[0], safeColorAccess(syntaxHighlighterConfig, 'hrColor', color) || color);
                         break;
                         break;
                   
                     case "\\":
                     case "\\":
                         writeText(match[0], syntaxHighlighterConfig.boldOrItalicColor || color);
                         // 粗体和斜体
                         if (match[0].length == 6)
                        u(match[0], safeColorAccess(syntaxHighlighterConfig, 'boldOrItalicColor', color) || color);
                        {
                       
                            //bold
                         if (match[0].length === 6) {
                            if (assumedBold)
                             // 处理粗体
                            {
                             if (boldState) {
                                //end tag
                                 if (!italicState) {
                                if (assumedItalic)
                                     // 结束粗体
                                {
                                     boldState = false;
                                    //end of bold part of bold-italic block
                                    //block is now italic-only
                                    assumedBold = false;
                                }
                                else
                                {
                                    //end of bold block
                                    return;
                                }
                            }
                            else
                            {
                                //start tag
                                if (assumedItalic)
                                {
                                    //start of bold part of previously italic-only block
                                    //block is now bold-italic
                                    assumedBold = true;
                                }
                                else
                                {
                                    //start of bold block
                                    highlightBlock(syntaxHighlighterConfig.boldOrItalicColor || color, defaultBreakerRegex, true, false);
                                }
                            }
                        }
                        else
                        {
                             //italic
                             if (assumedItalic)
                            {
                                //end tag
                                 if (assumedBold)
                                {
                                     //end of italic part of bold-italic block
                                    //block is now bold-only
                                     assumedItalic = false;
                                 }
                                 }
                                 else
                            } else {
                                 {
                                 if (italicState) {
                                     //end of italic block
                                    // 开始粗体(已有斜体)
                                     return;
                                    boldState = true;
                                 } else {
                                     // 开始粗体
                                    stack.push({
                                        text: text,
                                        pos: pos,
                                        regex: x,
                                        color: safeColorAccess(syntaxHighlighterConfig, 'boldOrItalicColor', color) || color,
                                        boldState: true,
                                        italicState: false,
                                        context: "bold"
                                     });
                                 }
                                 }
                             }
                             }
                            else
                        } else {
                             {
                             // 处理斜体
                                //start tag
                            if (italicState) {
                                if (assumedBold)
                                 if (!boldState) {
                                 {
                                     // 结束斜体
                                     //start of italic part of previously bold-only block
                                     italicState = false;
                                    //block is now bold-italic
                                     assumedItalic = true;
                                 }
                                 }
                                 else
                            } else {
                                 {
                                 if (boldState) {
                                     //start of italic block
                                    // 开始斜体(已有粗体)
                                     highlightBlock(syntaxHighlighterConfig.boldOrItalicColor || color, defaultBreakerRegex, false, true);
                                    italicState = true;
                                 } else {
                                     // 开始斜体
                                     stack.push({
                                        text: text,
                                        pos: pos,
                                        regex: x,
                                        color: safeColorAccess(syntaxHighlighterConfig, 'boldOrItalicColor', color) || color,
                                        boldState: false,
                                        italicState: true,
                                        context: "italic"
                                    });
                                 }
                                 }
                             }
                             }
                         }
                         }
                         break;
                         break;
                   
                     case "&":
                     case "&":
                         //entity
                         // HTML实体
                         writeText(match[0], syntaxHighlighterConfig.entityColor || color);
                         u(match[0], safeColorAccess(syntaxHighlighterConfig, 'entityColor', color) || color);
                         break;
                         break;
                   
                     case "~":
                     case "~":
                         //username, signature, timestamp
                         // 签名
                         writeText(match[0], syntaxHighlighterConfig.signatureColor || color);
                         u(match[0], safeColorAccess(syntaxHighlighterConfig, 'signatureColor', color) || color);
                         break;
                         break;
                   
                     default:
                     default:
                         //bare external link
                         // 默认处理
                         writeText(match[0], syntaxHighlighterConfig.externalLinkColor || color);
                         u(match[0], safeColorAccess(syntaxHighlighterConfig, 'externalLinkColor', color) || color);
                 }
                 }
               
                // 将当前任务重新推入栈中,继续处理剩余文本
                stack.push({
                    text: text,
                    pos: pos,
                    regex: regex,
                    color: color,
                    boldState: boldState,
                    italicState: italicState,
                    context: context
                });
                // 移除break语句,让循环继续处理当前任务的剩余文本
             }
             }
           
            // 如果当前任务处理完毕,处理剩余文本
            if (match === null && pos < text.length) {
                u(text.substring(pos), color);
                m = text.length;
            }
           
         }
         }
 
          
 
         // 检查栈深度限制:使用stack.length来反映实际栈大小
        //start!
         if (stack.length >= MAX_STACK_DEPTH) {
        var startTime = Date.now();
             console.error('Stack depth exceeded maximum limit:', stack.length);
         highlightBlock("", defaultBreakerRegex);
            // 退出循环,避免无限递归 - 通过设置stack为空数组来终止循环
 
            stack = [];
         //output the leftovers (if any) to make sure whitespace etc. matches
         if (i < text.length)
        {
             writeText(text.substring(i), "");
         }
         }
 
       
         //if highlighting took too long, disable it.
         // 处理剩余文本
         var endTime = Date.now();
         if (m < h.length) {
        /*if (typeof(bestTime) == "undefined")
             u(h.substring(m), "");
        {
             window.bestTime = endTime - startTime;
            document.title = bestTime;
            highlightSyntaxIfNeededIntervalID = setInterval(highlightSyntax, 250);
         }
         }
        else
        {
            if (endTime - startTime < bestTime)
            {
                bestTime = endTime - startTime;
                document.title = bestTime;
            }
        }//*/
        if (endTime - startTime > syntaxHighlighterConfig.timeout)
        {
            clearInterval(highlightSyntaxIfNeededIntervalID);
            wpTextbox1.removeEventListener("input", highlightSyntax);
            wpTextbox1.removeEventListener("scroll", syncScrollX);
            wpTextbox1.removeEventListener("scroll", syncScrollY);
            attributeObserver.disconnect();
            parentObserver.disconnect();
            syntaxStyleTextNode.nodeValue = "";


            var errorMessage = {
        var t = Date.now();
                be: "Падсьветка сынтаксісу на гэтай старонцы была адключаная, бо заняла шмат часу. Максымальна дапушчальны час апэрацыі — $1мс, а на вашым кампутары яна заняла $2мс. Паспрабуйце зачыніць нейкія закладкі і праграмы і націснуць «Праглядзець» або «Паказаць зьмены». Калі гэта не дапаможа, паспрабуйце іншы броўзэр; калі й гэта не дапаможа, выкарыстайце магутнейшы кампутар.",
        if (t - e > safeConfigAccess(syntaxHighlighterConfig, 'timeout', 20)) {
                ca: "S'ha desactivat el remarcar de sintaxi en aquesta pàgina perquè ha trigat massa temps. El temps màxim permès per a remarcar és $1ms, i el vostre ordinador ha trigat $2ms. Proveu tancar algunes pestanyes i programes i fer clic en \"Mostra la previsualització\" o \"Mostra els canvis\". Si no funciona això, proveu un altre navegador web, i si això no funciona, proveu un ordinador més ràpid.",
            clearInterval(y);
                de: "Die Syntaxhervorhebung wurde auf dieser Seite deaktiviert, da diese zu lange gedauert hat. Die maximal erlaubte Zeit zur Hervorhebung beträgt $1ms und dein Computer benötigte $2ms. Versuche einige Tabs und Programme zu schließen und klicke \"Vorschau zeigen\" oder \"Änderungen zeigen\". Wenn das nicht funktioniert, probiere einen anderen Webbrowser und wenn immer noch nicht, probiere einen schnelleren Computer.",
            g.removeEventListener("input", E);
                el: "Η έμφαση σύνταξης έχει απενεργοποιηθεί σε αυτήν τη σελίδα γιατί αργούσε πολύ. Ο μέγιστος επιτρεπτός χρόνος για την έμφαση σύνταξης είναι $1ms και ο υπολογιστής σας έκανε $2ms. Δοκιμάστε να κλείσετε μερικές καρτέλες και προγράμματα και να κάνετε κλικ στην «Εμφάνιση προεπισκόπησης» ή στην «Εμφάνιση αλλαγών». Αν αυτό δεν δουλέψει, δοκιμάστε έναν διαφορετικό περιηγητή και αν ούτε αυτό δουλέψει, δοκιμάστε έναν ταχύτερο υπολογιστή.",
            g.removeEventListener("scroll", R);
                en: "Syntax highlighting on this page was disabled because it took too long. The maximum allowed highlighting time is $1ms, and your computer took $2ms. Try closing some tabs and programs and clicking \"Show preview\" or \"Show changes\". If that doesn't work, try a different web browser, and if that doesn't work, try a faster computer.",
            g.removeEventListener("scroll", F);
                es: "Se desactivó el resaltar de sintaxis en esta página porque tardó demasiado. El tiempo máximo permitido para resaltar es $1ms, y tu ordenador tardó $2ms. Prueba cerrar algunas pestañas y programas y hacer clic en \"Mostrar previsualización\" o \"Mostrar cambios\". Si no funciona esto, prueba otro navegador web, y si eso no funciona, prueba un ordenador más rápido.",
            p.disconnect();
                fa: "از آنجایی که زمان زیادی صرف آن می‌شد، برجسته‌سازی نحو در این صفحه غیرفعال شده است. بیشینهٔ زمان برجسته‌سازی برای ابزار $1ms تعریف شده در حالی که رایانهٔ شما $2ms زمان نیاز داشت. می‌توانید بستن برخی سربرگ‌ها و برنامه‌ها و سپس کلیک‌کردن دکمهٔ «پیش‌نمایش» یا «نمایش تغییرات» را بیازمایید. اگر جواب نداد مرورگر دیگری را امتحان کنید؛ و اگر باز هم جواب نداد، رایانهٔ سریع‌تری را بیازمایید.",
            f.disconnect();
                fi: "Syntaksin korostus on pois käytöstä tällä sivulla, koska siinä kesti liian kauan. Suurin sallittu korostukseen käytetty aika on $1ms, ja tietokoneellasi kesti $2ms. Kokeile sulkea joitain välilehtiä tai ohjelmia ja paina \"Esikatsele\" tai \"Näytä muutokset\". Jos se ei toimi, kokeile toista selainta, ja jos se ei toimi, kokeile nopeampaa tietokonetta.",
            d.nodeValue = "";
                fr: "La coloration syntaxique a été désactivée sur cette page en raison d'un temps de chargement trop important ($2ms). Le temps maximum autorisé est $1ms. Vous pouvez essayer de fermer certains onglets et programmes et cliquez sur \"Prévisualisation\" ou \"Voir mes modifications\". Si cela ne fonctionne pas, essayez un autre navigateur web, et si cela ne fonctionne toujours pas, essayez un ordinateur plus rapide.",
            var a = {
                hu: "A szintaxiskiemelés ezen az oldalon le lett tiltva, mert túl sokáig tartott. A maximális engedélyezett kiemelési idő $1 ms, és a géped $2 ms-ig dolgozott. Próbálj meg bezárni néhány fület és programot, és klikkelj az „Előnézet megtekintése” vagy a „Változtatások megtekintése” gombra. Ha ez nem működik, próbálj meg egy másik böngészőt, és ha ez sem működik, próbáld meg egy gyorsabb gépen.",
                 zh: "此页面上的语法突出显示被禁用,因为它花费的时间太长。允许的突出显示时间最长为$1毫秒,而您的计算机则为$2毫秒。请尝试关闭一些标签和程序,然后单击\"显示预览\"\"显示更改\"。如果不起作用,请尝试使用其他网页浏览器,如果还不起作用,请尝试使用速度更快的计算机。",
                hy: "Շարադասության ընդգծումը այս էջում անջատվել է, քանի որ այն չափից շատ է տևել։ Ընդգծման թույլատրելի առավելագույն ժամանակը $1 միլիվայրկյան է, բայց այս էջում տևել է $2 միլիվայրկյան։ Փորձեք անջատել որոշ ներդիրներ կամ ծրագրեր և սեղմել «Նախադիտել» կամ «Կատարված փոփոխությունները»։ Կրկին չաշխատելու դեպքում փորձեք այլ վեբ դիտարկիչ, եթե կրկին չաշխատի, փորձեք ավելի արագ համակարգիչ։",
                 "zh-hans": "此页面上的语法突出显示被禁用,因为它花费的时间太长。允许的突出显示时间最长为$1毫秒,而您的计算机则为$2毫秒。请尝试关闭一些标签和程序,然后单击\"显示预览\"\"显示更改\"。如果不起作用,请尝试使用其他网页浏览器,如果还不起作用,请尝试使用速度更快的计算机。",
                io: "Sintaxo-hailaitar en ca pagino esis nekapabligata pro ke konsumis tro multa tempo. La maxima permisata hailaitala tempo es $1ms, e tua ordinatro konsumis $2ms. Probez klozar kelka tabi e programi e kliktar \"Previdar\" o \"Montrez chanji\". Se to ne funcionas, probez altra brauzero, e se to ne funcionas, probez plu rapida ordinatro.",
                 "zh-hant": "此頁面上的語法突出顯示被禁用,因為它花費的時間太長。允許的突出顯示時間最長為$1毫秒,而您的計算機則為$2毫秒。請嘗試關閉一些標籤和程序,然後單擊\"顯示預覽\"\"顯示更改\"。如果不起作用,請嘗試使用其他網頁瀏覽器,如果还不起作用,請嘗試使用速度更快的計算機。"
                it: "L'evidenziazione delle sintassi su questa pagina è stata disabilitata perché ha richiesto troppo tempo. Il tempo massimo per l'evidenziazione è di $1ms e al tuo computer sono serviti $2ms. Prova a chiudere alcune schede e programmi e ricarica la pagina cliccando su \"Visualizza anteprima\" o \"Mostra modifiche\". Se non funziona ancora, prova con un web browser differente e, in ultima alternativa, prova ad utilizzare un computer più veloce.",
                 ja: "このページでの構文の強調表示は、時間がかかりすぎたため無効になりました。許容される時間の最大値は$1ミリ秒で、ご利用のコンピューターでは$2ミリ秒かかりました。いくつかのタブやプログラムを閉じて、「プレビューを表示」または「差分を表示」をクリックしてみてください。それが機能しない場合は、別のWebブラウザーをお試しください。それが機能しない場合は、より高速なコンピューターでお試しください。",
                ko: "이 문서에서의 문법 강조가 너무 오래 걸러서 해제되었습니다. 최대로 할당된 강조 시간은 $1ms인데, 당신의 컴퓨터는 $2ms이나 걸렸습니다. 탭과 프로그램을 일부 닫으신 후에 \"미리 보기\"\"차이 보기\"를 클릭하시기 바랍니다. 만약 작동하지 않으면 다른 웹 브라우저로 시도해보시고, 그래도 안되면 더 빠른 컴퓨터를 이용하십시오",
                 pl: "Podświetlanie składni na tej stronie zostało wyłączone, ponieważ wczytywanie trwało zbyt długo. Maksymalny dozwolony czas wynosi $1ms, Twojemu komputerowi zajęło to $2ms. Spróbuj zamknąć kilka zakładek lub programów w tle, a następnie kliknij „Pokaż podgląd” lub „Podgląd zmian”. Jeśli to nie zadziała, wypróbuj inną przeglądarkę internetową lub szybszy komputer.",
                pt: "O marcador de sintaxe foi desativado nesta página porque demorou demais. O tempo máximo permitido para marcar é de $1ms, e seu computador demorou $2ms. Tente fechar algumas abas e programas e clique em \"Mostrar previsão\" ou \"Mostrar alterações\". Se isso não funcionar, tente usar um outro navegador web, e se ainda não funcionar, tente em um computador mais rápido.",
                 ru: "Подсветка синтаксиса на странице была отключена, так как заняла слишком долго. Максимальное допустимое время операции - $1мс, сейчас на вашем компьютере она заняла $2мс. Попробуйте закрыть несколько вкладок и программ, затем нажать «Предварительный просмотр» или «Внесённые изменения». Если это не поможет, попробуйте другой браузер; если и это не поможет, используйте более быстрый компьютер.",
                sr: "Истицање синтаксе на овој страници је онемогућено јер се одвија предуго. Максимално дозвољено време истицања је $1ms, а на Вашем рачунару траје $2ms. Покушајте затворити неке картице и програме или кликните на „Прикажи претпреглед” или „Прикажи измене”. Ако то не ради, покушајте са другим веб-прегледачем, а ако и тада не ради, покушајте са бржим рачунаром.",
                vec: "L'evidensiasion de łe sintasi so sta voxe ła xe dexabiłitada par che ła ga dimandà masa tenpo. El tenpo màsemo par l'evidensiasion ła xe de $1ms e al to dispoxidivo a ghene xe cadesti $2ms. Proa a sarar calche scheda e programa e recarga ła pàjina schiciando so \"Varda ła anteprima\" o \"Mostra canbiaminti\". Se no el funsiona oncora, proa co on altro navegador web difarente e, cofà ùltema alternadiva, proa a doparar on dispoxidivo pì sèłero.",
                zh: "此頁面上的語法突出顯示被禁用,因為它花費的時間太長。允許的突出顯示時間最長為$1毫秒,而您的計算機則為$2毫秒。請嘗試關閉一些標籤和程序,然後單擊“顯示預覽”或“顯示更改”。如果不起作用,請嘗試使用其他網頁瀏覽器,如果还不起作用,請嘗試使用速度更快的計算機。",
             };
             };
             var wgUserLanguage = mw.config.get("wgUserLanguage");
             var n = mw.config.get("wgUserLanguage");
            a = a[n] || a["zh-hant"] || a.zh;
            return g.style.backgroundColor = "", g.style.marginTop = "0", l.removeAttribute("dir"), l.removeAttribute("lang"), l.setAttribute("style", "color:red; font-size:small"), void (l.textContent = a.replace("$1", safeConfigAccess(syntaxHighlighterConfig, 'timeout', 20)).replace("$2", t - e));
        }


            errorMessage = errorMessage[wgUserLanguage] || errorMessage[wgUserLanguage.substring(0, wgUserLanguage.indexOf("-"))] || errorMessage.en;
        // 智能增量更新:只更新变化的CSS样式部分
 
        var newCSS = o.substring(2).replace(/\\n/g, "\\A ") + "'}";
            wpTextbox1.style.backgroundColor = "";
        newCSS += "#wpTextbox0>span::after{visibility:hidden}";
            wpTextbox1.style.marginTop = "0";
       
            wpTextbox0.removeAttribute("dir");
        // 如果CSS内容没有变化,避免不必要的DOM操作
            wpTextbox0.removeAttribute("lang");
        if (lastHighlightState !== newCSS) {
            wpTextbox0.setAttribute("style", "color:red; font-size:small");
             d.nodeValue = newCSS;
 
             lastHighlightState = newCSS;
             wpTextbox0.textContent = errorMessage.replace("$1", syntaxHighlighterConfig.timeout).replace("$2", endTime - startTime);
             return;
         }
         }
 
          
         //do we have enough span elements to match the generated CSS?
         // 智能span元素管理:只创建或删除需要的元素
         //this step isn't included in the above benchmark because it takes a highly variable amount of time
         if (b < r) {
         if (maxSpanNumber < spanNumber)
            // 需要添加新的span元素
        {
             var s = document.createDocumentFragment();
             var fragment = document.createDocumentFragment();
             for (; b < r; b++) {
             do
                 var span = document.createElement("span");
            {
                span.id = "s" + b;
                 fragment.appendChild(document.createElement("span")).id = "s" + ++maxSpanNumber;
                s.appendChild(span);
                spanCache[b] = span; // 缓存span元素
            }
            l.appendChild(s);
        } else if (b > r) {
            // 需要删除多余的span元素
            for (var j = b - 1; j >= r; j--) {
                var spanToRemove = document.getElementById("s" + j);
                if (spanToRemove && spanToRemove.parentNode === l) {
                    l.removeChild(spanToRemove);
                    delete spanCache[j]; // 清理缓存
                }
             }
             }
             while (maxSpanNumber < spanNumber);
             b = r;
            wpTextbox0.appendChild(fragment);
         }
         }
        /* finish CSS: move the extra '} from the beginning to the end and CSS-
          escape newlines. CSS ignores the space after the hex code of the
          escaped character */
        css = css.substring(2).replace(/\n/g, "\\A ") + "'}";
        //visibility:hidden prevents the background text from being picked up during in-page search in Firefox
        css += "#wpTextbox0>span::after{visibility:hidden}";
        syntaxStyleTextNode.nodeValue = css;
     }
     }


     function syncScrollX()
     function R() {
    {
         l.scrollLeft = g.scrollLeft;
         wpTextbox0.scrollLeft = wpTextbox1.scrollLeft;
     }
     }


     function syncScrollY()
     function F() {
    {
         l.scrollTop = g.scrollTop;
         wpTextbox0.scrollTop = wpTextbox1.scrollTop;
     }
     }


     function syncTextDirection()
     function a() {
    {
         l.dir = g.dir;
         wpTextbox0.dir = wpTextbox1.dir;
     }
     }


     function syncParent()
     function n() {
    {
         g.previousSibling != l && (g.parentNode.insertBefore(l, g), f.disconnect(), f.observe(g.parentNode, {
         if (wpTextbox1.previousSibling != wpTextbox0)
            childList: !0
        {
        }));
            wpTextbox1.parentNode.insertBefore(wpTextbox0, wpTextbox1);
            parentObserver.disconnect();
            parentObserver.observe(wpTextbox1.parentNode, {childList: true});
        }
     }
     }


     //this function runs once every 500ms to detect changes to wpTextbox1's text that the input event does not catch
     function s() {
    //this happens when another script changes the text without knowing that the syntax highlighter needs to be informed
         g.value != c && E();
    function highlightSyntaxIfNeeded()
         g.scrollLeft != l.scrollLeft && R();
    {
         g.scrollTop != l.scrollTop && F();
         if (wpTextbox1.value != lastText)
         var e = window.getComputedStyle(l).height,
        {
             t = g.offsetHeight ? window.getComputedStyle(g).height : "0px";
            highlightSyntax();
        e != t && (l.style.height = t, g.style.marginTop = "-" + t);
         }
        if (wpTextbox1.scrollLeft != wpTextbox0.scrollLeft)
        {
            syncScrollX();
         }
        if (wpTextbox1.scrollTop != wpTextbox0.scrollTop)
        {
            syncScrollY();
         }
        if (wpTextbox1.offsetHeight != wpTextbox0.offsetHeight)
        {
             var height = wpTextbox1.offsetHeight + "px";
            wpTextbox0.style.height = height;
            wpTextbox1.style.marginTop = "-" + height;
        }
     }
     }


     function setup()
     function i() {
    {
         // 浏览器兼容性检查:如果MutationObserver不被支持,自动禁用高亮功能
         wpTextbox1 = document.getElementById("wpTextbox1");
         if (!window.MutationObserver) {
        if (!wpTextbox1) return; //another script (such as the Visual Editor) has removed the edit box
             console.warn("Syntax highlighter disabled: MutationObserver not supported");
 
             return;
        function configureColor(parameterName, hardcodedFallback, defaultOk)
         {
            if (typeof(syntaxHighlighterConfig[parameterName]) == "undefined")
            {
                syntaxHighlighterConfig[parameterName] = syntaxHighlighterSiteConfig[parameterName];
             }
 
            if (syntaxHighlighterConfig[parameterName] == "normal")
            {
                syntaxHighlighterConfig[parameterName] = hardcodedFallback;
             }
            else if (typeof(syntaxHighlighterConfig[parameterName]) != "undefined")
            {
                return;
            }
            else if (typeof(syntaxHighlighterConfig.defaultColor) != "undefined" && defaultOk)
            {
                syntaxHighlighterConfig[parameterName] = syntaxHighlighterConfig.defaultColor;
            }
            else
            {
                syntaxHighlighterConfig[parameterName] = hardcodedFallback;
            }
         }
         }
 
       
        // 全局变量安全检查:确保syntaxHighlighterConfig和syntaxHighlighterSiteConfig存在
        window.syntaxHighlighterConfig = window.syntaxHighlighterConfig || {};
         window.syntaxHighlighterSiteConfig = window.syntaxHighlighterSiteConfig || {};
         window.syntaxHighlighterSiteConfig = window.syntaxHighlighterSiteConfig || {};
         window.syntaxHighlighterConfig = window.syntaxHighlighterConfig || {};
          
        var e, t, i;


         //use 3-digit colors instead of 6-digit colors for performance
         function o(e, t, i) {
        configureColor("backgroundColor",    "#FFF",  false); //white
            void 0 === syntaxHighlighterConfig[e] && (syntaxHighlighterConfig[e] = syntaxHighlighterSiteConfig[e] || t);
        configureColor("foregroundColor",    "#000",  false); //black
            "normal" == syntaxHighlighterConfig[e] ? syntaxHighlighterConfig[e] = t : void 0 !== syntaxHighlighterConfig[e] || (void 0 !== syntaxHighlighterConfig.defaultColor && i ? syntaxHighlighterConfig[e] = syntaxHighlighterConfig.defaultColor : syntaxHighlighterConfig[e] = t);
        configureColor("boldOrItalicColor",  "#EEE",  true);  //gray
         }
        configureColor("commentColor",      "#EFE",  true);  //green
        configureColor("entityColor",        "#DFD",  true);  //green
        configureColor("externalLinkColor",  "#EFF",  true);  //cyan
        configureColor("headingColor",      "#EEE",  true);  //gray
        configureColor("hrColor",           "#EEE", true);  //gray
        configureColor("listOrIndentColor",  "#EFE",  true); //green
        configureColor("parameterColor",    "#FC6",  true);  //orange
        configureColor("signatureColor",    "#FC6",  true); //orange
         configureColor("tagColor",          "#FEF",  true);  //pink
        configureColor("tableColor",        "#FFC",  true);  //yellow
        configureColor("templateColor",      "#FFC",  true);  //yellow
        configureColor("wikilinkColor",      "#EEF",  true);  //blue


         //tag lists are ordered from most common to least common
        (g = document.getElementById("wpTextbox1")) && (document.getElementById("wpTextbox0") || (window.syntaxHighlighterSiteConfig = window.syntaxHighlighterSiteConfig || {}, window.syntaxHighlighterConfig = window.syntaxHighlighterConfig || {},
         syntaxHighlighterConfig.nowikiTags = syntaxHighlighterConfig.nowikiTags || syntaxHighlighterSiteConfig.nowikiTags || ["nowiki", "pre"];
         // 补充缺失的默认数组配置
        syntaxHighlighterConfig.sourceTags = syntaxHighlighterConfig.sourceTags || syntaxHighlighterSiteConfig.sourceTags || ["math", "syntaxhighlight", "source", "timeline", "hiero"];
        syntaxHighlighterConfig.voidTags = syntaxHighlighterConfig.voidTags || [],
        syntaxHighlighterConfig.timeout = syntaxHighlighterConfig.timeout || syntaxHighlighterSiteConfig.timeout || 20;
        syntaxHighlighterConfig.sourceTags = syntaxHighlighterConfig.sourceTags || [],
 
         syntaxHighlighterConfig.nowikiTags = syntaxHighlighterConfig.nowikiTags || [],
        syntaxHighlighterConfig.nowikiTags.forEach(function(tagName) {
       
             nowikiTagBreakerRegexCache[tagName] = nowikiTagBreakerRegex(tagName);
        o("backgroundColor", "#FFF", !1), o("foregroundColor", "#000", !1), o("boldOrItalicColor", "#EEE", !0), o("commentColor", "#EFE", !0), o("entityColor", "#DFD", !0), o("externalLinkColor", "#EFF", !0), o("headingColor", "#EEE", !0), o("hrColor", "#EEE", !0), o("listOrIndentColor", "#EFE", !0), o("parameterColor", "#FC6", !0), o("signatureColor", "#FC6", !0), o("tagColor", "#FEF", !0), o("tableColor", "#FFC", !0), o("templateColor", "#FFC", !0), o("wikilinkColor", "#EEF", !0), syntaxHighlighterConfig.nowikiTags = syntaxHighlighterConfig.nowikiTags || syntaxHighlighterSiteConfig.nowikiTags || ["nowiki", "pre"], syntaxHighlighterConfig.sourceTags = syntaxHighlighterConfig.sourceTags || syntaxHighlighterSiteConfig.sourceTags || ["math", "syntaxhighlight", "source", "timeline", "hiero"], syntaxHighlighterConfig.voidTags = syntaxHighlighterConfig.voidTags || syntaxHighlighterSiteConfig.voidTags || [], syntaxHighlighterConfig.timeout = syntaxHighlighterConfig.timeout || syntaxHighlighterSiteConfig.timeout || 20, syntaxHighlighterConfig.nowikiTags.forEach(function(e) {
        });
             var cacheKey = "nowiki_" + e;
 
            if (!regexCache[cacheKey]) {
         wpTextbox0 = document.createElement("div");
                regexCache[cacheKey] = new RegExp("(</" + e + ">)\\n*|" + r, "gm");
 
            }
        var syntaxStyleElement = document.createElement("style");
            L[e] = regexCache[cacheKey];
         syntaxStyleTextNode = syntaxStyleElement.appendChild(document.createTextNode(""));
         }), l = document.createElement("div"), e = document.createElement("style"),
 
        // 添加样式冲突防护
        //the styling of the textbox and the background div must be kept very similar
         e.setAttribute("scoped", "scoped"), // 限制样式仅作用于当前组件
         var wpTextbox1Style = window.getComputedStyle(wpTextbox1);
         e.setAttribute("data-syntax-highlighter", "true"), // 便于识别和调试
 
         d = e.appendChild(document.createTextNode("")), i = "vertical" == (t = window.getComputedStyle(g)).resize || "both" == t.resize ? "vertical" : "none", l.dir = g.dir, l.id = "wpTextbox0", l.lang = g.lang, l.style.backgroundColor = syntaxHighlighterConfig.backgroundColor, l.style.borderBottomLeftRadius = t.borderBottomLeftRadius, l.style.borderBottomRightRadius = t.borderBottomRightRadius, l.style.borderBottomStyle = t.borderBottomStyle, l.style.borderBottomWidth = t.borderBottomWidth, l.style.borderColor = "transparent", l.style.borderLeftStyle = t.borderLeftStyle, l.style.borderLeftWidth = t.borderLeftWidth, l.style.borderRightStyle = t.borderRightStyle, l.style.borderRightWidth = t.borderRightWidth, l.style.borderTopLeftRadius = t.borderTopLeftRadius, l.style.borderTopRightRadius = t.borderTopRightRadius, l.style.borderTopStyle = t.borderTopStyle, l.style.borderTopWidth = t.borderTopWidth, l.style.boxSizing = "border-box", l.style.clear = t.clear, l.style.fontFamily = t.fontFamily, l.style.fontSize = t.fontSize, l.style.lineHeight = "normal", l.style.marginBottom = "0", l.style.marginLeft = "0", l.style.marginRight = "0", l.style.marginTop = "0", l.style.overflowX = "auto", l.style.overflowY = "scroll", l.style.resize = i, l.style.tabSize = t.tabSize, l.style.whiteSpace = "pre-wrap", l.style.width = "100%", l.style.wordWrap = "normal", g.style.backgroundColor = "transparent", g.style.borderBottomLeftRadius = t.borderBottomLeftRadius, g.style.borderBottomRightRadius = t.borderBottomRightRadius, g.style.borderBottomStyle = t.borderBottomStyle, g.style.borderBottomWidth = t.borderBottomWidth, g.style.borderLeftStyle = t.borderLeftStyle, g.style.borderLeftWidth = t.borderLeftWidth, g.style.borderRightStyle = t.borderRightStyle, g.style.borderRightWidth = t.borderRightWidth, g.style.borderTopLeftRadius = t.borderTopLeftRadius, g.style.borderTopRightRadius = t.borderTopRightRadius, g.style.borderTopStyle = t.borderTopStyle, g.style.borderTopWidth = t.borderTopWidth, g.style.boxSizing = "border-box", g.style.clear = t.clear, g.style.color = syntaxHighlighterConfig.foregroundColor, g.style.fontFamily = t.fontFamily, g.style.fontSize = t.fontSize, g.style.lineHeight = "normal", g.style.marginLeft = "0", g.style.marginRight = "0", g.style.marginTop = "-" + t.height, g.style.overflowX = "auto", g.style.overflowY = "scroll", g.style.padding = "0", g.style.resize = i, g.style.tabSize = t.tabSize, g.style.whiteSpace = "pre-wrap", g.style.width = "100%", g.style.wordWrap = "normal", g.parentNode.insertBefore(l, g), document.head.appendChild(e), g.addEventListener("input", E), g.addEventListener("scroll", R), g.addEventListener("scroll", F), (p = new MutationObserver(a)).observe(g, {
        //horizontal resize would look horribly choppy, better to make the user resize the browser window instead
            attributes: !0
         var resize = (wpTextbox1Style.resize == "vertical" || wpTextbox1Style.resize == "both" ? "vertical" : "none");
        }), (f = new MutationObserver(n)).observe(g.parentNode, {
 
            childList: !0
        wpTextbox0.dir                           = wpTextbox1.dir;
        }), y = setInterval(s, 500), E()));
        wpTextbox0.id                           = "wpTextbox0";
        wpTextbox0.lang                         = wpTextbox1.lang; //lang determines which font "monospace" is
        wpTextbox0.style.backgroundColor         = syntaxHighlighterConfig.backgroundColor;
        wpTextbox0.style.borderBottomLeftRadius = wpTextbox1Style.borderBottomLeftRadius;
        wpTextbox0.style.borderBottomRightRadius = wpTextbox1Style.borderBottomRightRadius;
        wpTextbox0.style.borderBottomStyle       = wpTextbox1Style.borderBottomStyle;
        wpTextbox0.style.borderBottomWidth       = wpTextbox1Style.borderBottomWidth;
        wpTextbox0.style.borderColor             = "transparent";
        wpTextbox0.style.borderLeftStyle         = wpTextbox1Style.borderLeftStyle;
        wpTextbox0.style.borderLeftWidth         = wpTextbox1Style.borderLeftWidth;
        wpTextbox0.style.borderRightStyle       = wpTextbox1Style.borderRightStyle;
        wpTextbox0.style.borderRightWidth       = wpTextbox1Style.borderRightWidth;
        wpTextbox0.style.borderTopLeftRadius     = wpTextbox1Style.borderTopLeftRadius;
        wpTextbox0.style.borderTopRightRadius   = wpTextbox1Style.borderTopRightRadius;
        wpTextbox0.style.borderTopStyle         = wpTextbox1Style.borderTopStyle;
        wpTextbox0.style.borderTopWidth         = wpTextbox1Style.borderTopWidth;
        wpTextbox0.style.boxSizing               = "border-box";
        wpTextbox0.style.clear                   = wpTextbox1Style.clear;
        wpTextbox0.style.fontFamily             = wpTextbox1Style.fontFamily;
        wpTextbox0.style.fontSize               = wpTextbox1Style.fontSize;
        wpTextbox0.style.lineHeight             = "normal";
        wpTextbox0.style.marginBottom           = "0";
        wpTextbox0.style.marginLeft             = "0";
        wpTextbox0.style.marginRight             = "0";
        wpTextbox0.style.marginTop               = "0";
        wpTextbox0.style.overflowX               = "auto";
        wpTextbox0.style.overflowY               = "scroll";
        wpTextbox0.style.resize                 = resize;
        wpTextbox0.style.tabSize                 = wpTextbox1Style.tabSize;
        wpTextbox0.style.whiteSpace             = "pre-wrap";
        wpTextbox0.style.width                   = "100%";
        wpTextbox0.style.wordWrap               = "normal"; //see below
 
        wpTextbox1.style.backgroundColor         = "transparent";
        wpTextbox1.style.borderBottomLeftRadius = wpTextbox1Style.borderBottomLeftRadius;
        wpTextbox1.style.borderBottomRightRadius = wpTextbox1Style.borderBottomRightRadius;
        wpTextbox1.style.borderBottomStyle       = wpTextbox1Style.borderBottomStyle;
        wpTextbox1.style.borderBottomWidth       = wpTextbox1Style.borderBottomWidth;
        wpTextbox1.style.borderLeftStyle         = wpTextbox1Style.borderLeftStyle;
        wpTextbox1.style.borderLeftWidth         = wpTextbox1Style.borderLeftWidth;
        wpTextbox1.style.borderRightStyle       = wpTextbox1Style.borderRightStyle;
        wpTextbox1.style.borderRightWidth       = wpTextbox1Style.borderRightWidth;
        wpTextbox1.style.borderTopLeftRadius     = wpTextbox1Style.borderTopLeftRadius;
        wpTextbox1.style.borderTopRightRadius   = wpTextbox1Style.borderTopRightRadius;
        wpTextbox1.style.borderTopStyle         = wpTextbox1Style.borderTopStyle;
        wpTextbox1.style.borderTopWidth         = wpTextbox1Style.borderTopWidth;
        wpTextbox1.style.boxSizing               = "border-box";
        wpTextbox1.style.clear                   = wpTextbox1Style.clear;
        wpTextbox1.style.color                   = syntaxHighlighterConfig.foregroundColor;
        wpTextbox1.style.fontFamily             = wpTextbox1Style.fontFamily;
        wpTextbox1.style.fontSize               = wpTextbox1Style.fontSize;
        wpTextbox1.style.lineHeight             = "normal";
        wpTextbox1.style.marginBottom            = wpTextbox1Style.marginBottom; //lock to pixel value because the top margin was also locked to a pixel value when it was moved to wpTextbox0
        wpTextbox1.style.marginLeft              = "0";
        wpTextbox1.style.marginRight            = "0";
        wpTextbox1.style.overflowX               = "auto";
        wpTextbox1.style.overflowY               = "scroll";
        wpTextbox1.style.padding                 = "0";
        wpTextbox1.style.resize                 = resize;
        wpTextbox1.style.tabSize                 = wpTextbox1Style.tabSize;
        wpTextbox1.style.whiteSpace             = "pre-wrap";
        wpTextbox1.style.width                   = "100%";
        wpTextbox1.style.wordWrap               = "normal"; //overall more visually appealing
 
        //lock both heights to pixel values so that the browser zoom feature works better
        wpTextbox1.style.height = wpTextbox0.style.height = wpTextbox1.offsetHeight + "px";
 
        //insert wpTextbox0 underneath wpTextbox1
        wpTextbox1.style.marginTop      = -wpTextbox1.offsetHeight + "px";
        wpTextbox1.parentNode.insertBefore(wpTextbox0, wpTextbox1);
 
        document.head.appendChild(syntaxStyleElement);
 
        wpTextbox1.addEventListener("input", highlightSyntax);
        wpTextbox1.addEventListener("scroll", syncScrollX);
        wpTextbox1.addEventListener("scroll", syncScrollY);
        attributeObserver = new MutationObserver(syncTextDirection);
        attributeObserver.observe(wpTextbox1, {attributes: true});
        parentObserver = new MutationObserver(syncParent);
        parentObserver.observe(wpTextbox1.parentNode, {childList: true});
        highlightSyntaxIfNeededIntervalID = setInterval(highlightSyntaxIfNeeded, 500);
        highlightSyntax();
     }
     }


 
     var o = mw.config.get("wgAction"),
    //enable the highlighter only when editing wikitext pages
        e = $.client.profile().layout;
    //in the future a separate parser could be added for CSS and JS pages
     "edit" != o && "submit" != o || "wikitext" != mw.config.get("wgPageContentModel") || "trident" == e || ("complete" == document.readyState ? i() : window.addEventListener("load", i));
    //blacklist Internet Explorer and Edge, they're just too broken
   
     var wgAction = mw.config.get("wgAction");
    // 添加页面卸载时的资源清理逻辑
    var layoutEngine = $.client.profile().layout;
     function cleanup() {
     if ((wgAction == "edit" || wgAction == "submit") && mw.config.get("wgPageContentModel") == "wikitext" && layoutEngine != "trident" && layoutEngine != "edge")
         // 清理定时器
     {
         if (y) {
         //give other scripts an opportunity to set syntaxHighlighterConfig
             clearInterval(y);
         if (document.readyState == "complete")
            y = null;
        {
             setup();
         }
         }
         else
         // 清理观察者
         {
         [p, f].forEach(observer => observer?.disconnect());
             window.addEventListener("load", setup);
        // 清理事件监听
        if (g) {
             g.removeEventListener("input", E);
            g.removeEventListener("scroll", R);
            g.removeEventListener("scroll", F);
         }
         }
        // 清理DOM元素
        l?.parentNode?.removeChild(l);
        d?.parentNode?.parentNode?.removeChild(d.parentNode); // 移除style元素
        // 重置变量
        l = g = d = c = y = p = f = b = null;
     }
     }
    // 双重事件监听确保清理
    window.addEventListener('beforeunload', cleanup);
    window.addEventListener('unload', cleanup);
});
});

2025年11月20日 (四) 23:41的最新版本

mw.loader.using("jquery.client", function() {
    "use strict";
    
    // 安全的配置访问函数
    function safeConfigAccess(config, property, defaultValue) {
        if (!config || !config[property]) return defaultValue;
        return config[property];
    }
    
    // CSS颜色值验证函数
    function isValidCSSColor(colorValue) {
        if (!colorValue || typeof colorValue !== 'string') return false;
        
        // 移除前后空格
        colorValue = colorValue.trim();
        
        // 检查常见CSS颜色格式
        var colorFormats = [
            // 十六进制颜色 (#FFF, #FFFFFF)
            /^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})$/,
            // RGB颜色 (rgb(255,255,255))
            /^rgb\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*\)$/,
            // RGBA颜色 (rgba(255,255,255,0.5))
            /^rgba\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*(0|1|0\.\d+)\s*\)$/,
            // HSL颜色 (hsl(120,100%,50%))
            /^hsl\(\s*\d{1,3}\s*,\s*\d{1,3}%\s*,\s*\d{1,3}%\s*\)$/,
            // HSLA颜色 (hsla(120,100%,50%,0.5))
            /^hsla\(\s*\d{1,3}\s*,\s*\d{1,3}%\s*,\s*\d{1,3}%\s*,\s*(0|1|0\.\d+)\s*\)$/,
            // 命名颜色 (red, blue, transparent)
            /^(transparent|inherit|initial|unset|currentColor|revert|revert-layer)$/i
        ];
        
        // 检查是否为有效的CSS命名颜色
        var namedColors = [
            'black', 'silver', 'gray', 'white', 'maroon', 'red', 'purple', 'fuchsia', 
            'green', 'lime', 'olive', 'yellow', 'navy', 'blue', 'teal', 'aqua',
            'orange', 'aliceblue', 'antiquewhite', 'aquamarine', 'azure', 'beige',
            'bisque', 'blanchedalmond', 'blueviolet', 'brown', 'burlywood', 'cadetblue',
            'chartreuse', 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson',
            'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray', 'darkgreen',
            'darkgrey', 'darkkhaki', 'darkmagenta', 'darkolivegreen', 'darkorange',
            'darkorchid', 'darkred', 'darksalmon', 'darkseagreen', 'darkslateblue',
            'darkslategray', 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink',
            'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick', 'floralwhite',
            'forestgreen', 'gainsboro', 'ghostwhite', 'gold', 'goldenrod', 'greenyellow',
            'grey', 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', 'khaki',
            'lavender', 'lavenderblush', 'lawngreen', 'lemonchiffon', 'lightblue',
            'lightcoral', 'lightcyan', 'lightgoldenrodyellow', 'lightgray', 'lightgreen',
            'lightgrey', 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue',
            'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow', 'limegreen',
            'linen', 'magenta', 'mediumaquamarine', 'mediumblue', 'mediumorchid',
            'mediumpurple', 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen',
            'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream', 'mistyrose',
            'moccasin', 'navajowhite', 'oldlace', 'olivedrab', 'orangered', 'orchid',
            'palegoldenrod', 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip',
            'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'rosybrown', 'royalblue',
            'saddlebrown', 'salmon', 'sandybrown', 'seagreen', 'seashell', 'sienna',
            'skyblue', 'slateblue', 'slategray', 'slategrey', 'snow', 'springgreen',
            'steelblue', 'tan', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat',
            'whitesmoke', 'yellowgreen'
        ];
        
        // 检查格式匹配
        for (var i = 0; i < colorFormats.length; i++) {
            if (colorFormats[i].test(colorValue)) {
                return true;
            }
        }
        
        // 检查命名颜色
        if (namedColors.indexOf(colorValue.toLowerCase()) !== -1) {
            return true;
        }
        
        return false;
    }
    
    // 安全的颜色配置访问函数
    function safeColorAccess(config, property, defaultValue) {
        var colorValue = safeConfigAccess(config, property, defaultValue);
        
        // 如果颜色值为"normal",返回默认值
        if (colorValue === "normal") {
            return defaultValue;
        }
        
        // 验证颜色值有效性
        if (colorValue && !isValidCSSColor(colorValue)) {
            console.warn('Invalid CSS color value for ' + property + ': "' + colorValue + '", using default: "' + defaultValue + '"');
            return defaultValue;
        }
        
        return colorValue || defaultValue;
    }
    
    // 查找匹配的标签结束位置,处理嵌套标签
    function findMatchingTagEnd(text, startPos, tagName) {
        var openTag = "<" + tagName + ">";
        var closeTag = "</" + tagName + ">";
        var stack = 1; // 当前已经有一个开始标签
        var pos = startPos;
        
        while (pos < text.length) {
            var nextOpen = text.indexOf(openTag, pos);
            var nextClose = text.indexOf(closeTag, pos);
            
            // 如果找不到闭合标签,返回文本末尾
            if (nextClose === -1) return text.length;
            
            // 如果下一个开始标签在闭合标签之前,增加栈深度
            if (nextOpen !== -1 && nextOpen < nextClose) {
                stack++;
                pos = nextOpen + openTag.length;
            } else {
                stack--;
                pos = nextClose + closeTag.length;
                
                // 如果栈为空,返回当前闭合标签的结束位置
                if (stack === 0) return pos;
            }
        }
        
        return text.length; // 如果找不到匹配的闭合标签,返回文本末尾
    }
    
    var e = mw.config.get("wgUrlProtocols"),
        r = "&(?:(?:n(?:bsp|dash)|m(?:dash|inus)|lt|e[mn]sp|thinsp|amp|quot|gt|shy|zwnj|lrm|rlm|Alpha|Beta|Epsilon|Zeta|Eta|Iota|Kappa|[Mm]u|micro|Nu|[Oo]micron|[Rr]ho|Tau|Upsilon|Chi)|#x[0-9a-fA-F]+);\\n*",
        t = "\\[(?:\\[|(?:" + e + "))|\\{(?:\\{\\{?|\\|)|<(?:[:A-Z_a-z][-:\\w]*(?=/?>| |\\n)|!--[\\s\\S]*?-->\\n*)|(?:" + e + ")[^\\s\"<>[\\]{-}]*[^\\s\",\\.:;<>[\\]{-}]\\n*|^(?:=|[*#:;]+\\n*|-{4,}\\n*)|\\\\'\\\\'(?:\\\\')?|~{3,5}\\n*|" + r,
        l = null, g = null, d = null, c = "", y = null, p = null, f = null, b = -1,
        lastText = ""; // 记录上一次的文本内容

    var regexCache = {};
    
    function C(e) {
        var cacheKey = e;
        if (!regexCache[cacheKey]) {
            try {
                regexCache[cacheKey] = new RegExp("(" + e + ")\\n*|" + t, "gm");
            } catch (err) {
                console.error("Syntax highlighter: 正则表达式构建失败", err, "e:", e);
                regexCache[cacheKey] = new RegExp(t, "gm"); // 使用默认正则降级
            }
        }
        return regexCache[cacheKey];
    }

    var x = new RegExp(t, "gm"),
        k = C("]][a-zA-Z]*"),
        v = C("]"),
        w = C("}}}"),
        z = C("}}"),
        H = C("\\|}"),
        S = C("\\n"),
        T = {},
        L = {};

    // 增量更新状态管理
    var lastHighlightState = null,
        lastSpanCount = 0,
        spanCache = {};

    function E() {
        try {
            var currentText = g.value;
            
            // 增量更新检查:如果文本内容没有变化,直接返回
            if (currentText === lastText) {
                return;
            }
            
            // 增量更新优化:计算文本变化范围并用于局部解析
            var changeStart = 0, changeEnd = currentText.length;
            var isIncrementalUpdate = false;
            
            if (lastText && currentText !== lastText) {
                // 找到文本变化的起始位置
                for (changeStart = 0; changeStart < Math.min(currentText.length, lastText.length); changeStart++) {
                    if (currentText[changeStart] !== lastText[changeStart]) break;
                }
                
                // 找到文本变化的结束位置(从末尾开始比较)
                for (changeEnd = 0; changeEnd < Math.min(currentText.length, lastText.length); changeEnd++) {
                    if (currentText[currentText.length - 1 - changeEnd] !== lastText[lastText.length - 1 - changeEnd]) break;
                }
                changeEnd = currentText.length - changeEnd;
                
                // 判断是否适合增量更新:变化范围较小且不在语法结构边界
                isIncrementalUpdate = (changeEnd - changeStart) < Math.min(currentText.length * 0.3, 200) && 
                                     changeStart > 0 && changeEnd < currentText.length;
            }
            
            lastText = currentText;
            
            // 确保b变量有正确的初始值
            if (b === -1) {
                // 如果是第一次运行,需要初始化b为当前span数量
                var existingSpans = l.querySelectorAll('span[id^="s"]');
                b = existingSpans.length;
            }
        } catch (error) {
            // 捕获正则匹配和DOM操作中的异常
            console.error('Syntax highlighter error:', error);
            return;
        }
        
        var i, h = (c = currentText).replace(/['\\]/g, "\\$&") + "\\n",
            m = 0,
            o = "",
            r = 0;

        // 最大递归深度限制
        var MAX_RECURSION_DEPTH = 1000;

        function u(e, t) {
            t != i && (o += "'}", t && (o += "#s" + r + "{background-color:" + t + "}"), o += "#s" + r + "::after{content:'", i = t, ++r), o += e;
        }

        var e = Date.now();

        // 精确增量更新:基于changeStart和changeEnd的局部解析
        if (isIncrementalUpdate && lastHighlightState) {
            // 方法1:智能边界定位(当前实现)- 基于CSS状态复用
            var startMarker = "#s" + (Math.floor(changeStart / 50)) + "::after";
            var markerIndex = lastHighlightState.indexOf(startMarker);
            if (markerIndex !== -1) {
                var prefixCSS = lastHighlightState.substring(0, markerIndex);
                // 确保CSS语法完整
                if (prefixCSS.endsWith("'}")) {
                    o = prefixCSS;
                    r = Math.floor(changeStart / 50);
                    m = changeStart;
                }
            }
            
            // 方法2:语法边界检测(高级优化)- 需要修改递归逻辑
            // 检测变化点前后的语法结构,确保解析上下文正确
            var syntaxBoundaryStart = findSyntaxBoundary(currentText, changeStart, -1); // 向前查找语法边界
            var syntaxBoundaryEnd = findSyntaxBoundary(currentText, changeEnd, 1);      // 向后查找语法边界
            
            if (syntaxBoundaryStart >= 0 && syntaxBoundaryEnd <= currentText.length) {
                // 如果找到合适的语法边界,使用精确的局部解析
                m = Math.max(0, syntaxBoundaryStart);
                // 这里需要修改递归解析函数以支持从指定位置开始解析
                console.log("精确增量更新:从位置", m, "开始解析");
            }
        } else {
            // 如果不是增量更新或lastHighlightState为null,确保从文本开头开始解析
            m = 0;
            o = "";
            r = 0;
        }
        
        // 语法边界检测辅助函数 - 增强wikitext专属边界检测
        function findSyntaxBoundary(text, position, direction) {
            var boundary = position;
            var maxSearch = 100; // 最大搜索范围
            
            // wikitext专属语法边界列表(按优先级排序)
            var wikitextBoundaries = [
                // 多字符边界(高优先级)
                '[[', ']]', '{{', '}}', '{{{', '}}}', '{|', '|}', '<!--', '-->',
                // 单字符边界
                '\n', '>', '}', ']', '=', '<', '|', ';', '*', '#', ':', '-', '~', '\\', '&'
            ];
            
            for (var i = 0; i < maxSearch; i++) {
                var currentPos = boundary + (direction * i);
                if (currentPos < 0 || currentPos >= text.length) break;
                
                // 优先检测多字符wikitext边界
                for (var j = 0; j < wikitextBoundaries.length; j++) {
                    var boundaryStr = wikitextBoundaries[j];
                    if (boundaryStr.length > 1) {
                        // 多字符边界检测
                        if (currentPos + boundaryStr.length <= text.length && 
                            text.substring(currentPos, currentPos + boundaryStr.length) === boundaryStr) {
                            return currentPos + (direction > 0 ? boundaryStr.length : 0);
                        }
                    } else {
                        // 单字符边界检测
                        if (text.charAt(currentPos) === boundaryStr) {
                            return currentPos + (direction > 0 ? 1 : 0);
                        }
                    }
                }
            }
            
            return direction > 0 ? text.length : 0;
        }

        // 基于显式调用栈的迭代解析器
        var stack = [{
            text: h,
            pos: m,
            regex: x,
            color: "",
            boldState: false,
            italicState: false,
            context: "root"
        }];
        
        var MAX_STACK_DEPTH = 1000; // 最大栈深度限制
        
        while (stack.length > 0 && stack.length < MAX_STACK_DEPTH) {
            var currentTask = stack.pop();
            var text = currentTask.text;
            var pos = currentTask.pos;
            var regex = currentTask.regex;
            var color = currentTask.color;
            var boldState = currentTask.boldState;
            var italicState = currentTask.italicState;
            var context = currentTask.context;
            
            // 处理当前解析任务
            var match;
            regex.lastIndex = pos;
            
            while ((match = regex.exec(text)) !== null) {
                if (match[1]) {
                    // 匹配到结束标记,处理剩余文本并返回
                    u(text.substring(pos, regex.lastIndex), color);
                    m = regex.lastIndex;
                    break;
                }
                
                var matchStart = regex.lastIndex - match[0].length;
                
                // 处理匹配前的文本
                if (pos < matchStart) {
                    u(text.substring(pos, matchStart), color);
                }
                
                pos = regex.lastIndex;
                
                // 根据匹配内容处理不同的语法元素
                switch (match[0].charAt(0)) {
                    case "[":
                        if (match[0].charAt(1) === "[") {
                            // 内部链接 [[...]]
                            u("[[", safeColorAccess(syntaxHighlighterConfig, 'wikilinkColor', color) || color);
                            stack.push({
                                text: text,
                                pos: pos,
                                regex: k,
                                color: safeColorAccess(syntaxHighlighterConfig, 'wikilinkColor', color) || color,
                                boldState: boldState,
                                italicState: italicState,
                                context: "wikilink"
                            });
                        } else {
                            // 外部链接 [...]
                            u(match[0], safeColorAccess(syntaxHighlighterConfig, 'externalLinkColor', color) || color);
                            stack.push({
                                text: text,
                                pos: pos,
                                regex: v,
                                color: safeColorAccess(syntaxHighlighterConfig, 'externalLinkColor', color) || color,
                                boldState: boldState,
                                italicState: italicState,
                                context: "externalLink"
                            });
                        }
                        break;
                    
                    case "{":
                        if (match[0].charAt(1) === "{") {
                            if (match[0].length === 3) {
                                // 参数 {{{...}}}
                                u("{{{", safeColorAccess(syntaxHighlighterConfig, 'parameterColor', color) || color);
                                stack.push({
                                    text: text,
                                    pos: pos,
                                    regex: w,
                                    color: safeColorAccess(syntaxHighlighterConfig, 'parameterColor', color) || color,
                                    boldState: boldState,
                                    italicState: italicState,
                                    context: "parameter"
                                });
                            } else {
                                // 模板 {{...}}
                                u("{{", safeColorAccess(syntaxHighlighterConfig, 'templateColor', color) || color);
                                stack.push({
                                    text: text,
                                    pos: pos,
                                    regex: z,
                                    color: safeColorAccess(syntaxHighlighterConfig, 'templateColor', color) || color,
                                    boldState: boldState,
                                    italicState: italicState,
                                    context: "template"
                                });
                            }
                        } else {
                            // 表格 {|...|}
                            u("{|", safeColorAccess(syntaxHighlighterConfig, 'tableColor', color) || color);
                            stack.push({
                                text: text,
                                pos: pos,
                                regex: H,
                                color: safeColorAccess(syntaxHighlighterConfig, 'tableColor', color) || color,
                                boldState: boldState,
                                italicState: italicState,
                                context: "table"
                            });
                        }
                        break;
                    
                    case "<":
                        if (match[0].charAt(1) === "!") {
                            // 注释 <!-- ... -->
                            u(match[0], safeColorAccess(syntaxHighlighterConfig, 'commentColor', color) || color);
                        } else {
                            // HTML标签
                            var tagEnd = text.indexOf(">", pos) + 1;
                            if (tagEnd === 0) {
                                u("<", color);
                                pos = pos - match[0].length + 1;
                            } else {
                                var tagName = match[0].substring(1);
                                
                                if (text.charAt(tagEnd - 2) !== "/") {
                                    if (safeConfigAccess(syntaxHighlighterConfig, 'voidTags', []).indexOf(tagName) === -1) {
                                        if (safeConfigAccess(syntaxHighlighterConfig, 'sourceTags', []).indexOf(tagName) !== -1) {
                                            // 源代码标签
                                            var closeTag = "</" + tagName + ">";
                                            var tagEndPos = findMatchingTagEnd(text, pos, tagName);
                                            u(text.substring(pos - match[0].length, tagEndPos), safeColorAccess(syntaxHighlighterConfig, 'tagColor', color) || color);
                                            pos = tagEndPos;
                                        } else if (safeConfigAccess(syntaxHighlighterConfig, 'nowikiTags', []).indexOf(tagName) !== -1) {
                                            // nowiki标签
                                            u(text.substring(pos - match[0].length, tagEnd), safeColorAccess(syntaxHighlighterConfig, 'tagColor', color) || color);
                                            pos = tagEnd;
                                            stack.push({
                                                text: text,
                                                pos: pos,
                                                regex: L[tagName] || (L[tagName] = C("</" + tagName + ">")),
                                                color: safeColorAccess(syntaxHighlighterConfig, 'tagColor', color) || color,
                                                boldState: boldState,
                                                italicState: italicState,
                                                context: "tag"
                                            });
                                        } else {
                                            // 普通标签
                                            u(text.substring(pos - match[0].length, tagEnd), safeColorAccess(syntaxHighlighterConfig, 'tagColor', color) || color);
                                            pos = tagEnd;
                                            T[tagName] = T[tagName] || C("</" + tagName + ">");
                                            stack.push({
                                                text: text,
                                                pos: pos,
                                                regex: T[tagName],
                                                color: safeColorAccess(syntaxHighlighterConfig, 'tagColor', color) || color,
                                                boldState: boldState,
                                                italicState: italicState,
                                                context: "tag"
                                            });
                                        }
                                    } else {
                                        u(text.substring(pos - match[0].length, tagEnd), safeColorAccess(syntaxHighlighterConfig, 'tagColor', color) || color);
                                        pos = tagEnd;
                                    }
                                } else {
                                    u(text.substring(pos - match[0].length, tagEnd), safeColorAccess(syntaxHighlighterConfig, 'tagColor', color) || color);
                                    pos = tagEnd;
                                }
                            }
                        }
                        break;
                    
                    case "=":
                        if (/[^=]=+$/.test(text.substring(pos, text.indexOf("\\n", pos)))) {
                            // 标题
                            u("=", safeColorAccess(syntaxHighlighterConfig, 'headingColor', color) || color);
                            stack.push({
                                text: text,
                                pos: pos,
                                regex: S,
                                color: safeColorAccess(syntaxHighlighterConfig, 'headingColor', color) || color,
                                boldState: boldState,
                                italicState: italicState,
                                context: "heading"
                            });
                        } else {
                            u("=", color);
                        }
                        break;
                    
                    case "*":
                    case "#":
                    case ":":
                        // 列表和缩进
                        u(match[0], safeColorAccess(syntaxHighlighterConfig, 'listOrIndentColor', color) || color);
                        break;
                    
                    case ";":
                        // 定义列表
                        u(";", safeColorAccess(syntaxHighlighterConfig, 'headingColor', color) || color);
                        stack.push({
                            text: text,
                            pos: pos,
                            regex: S,
                            color: safeColorAccess(syntaxHighlighterConfig, 'headingColor', color) || color,
                            boldState: boldState,
                            italicState: italicState,
                            context: "heading"
                        });
                        break;
                    
                    case "-":
                        // 水平线
                        u(match[0], safeColorAccess(syntaxHighlighterConfig, 'hrColor', color) || color);
                        break;
                    
                    case "\\":
                        // 粗体和斜体
                        u(match[0], safeColorAccess(syntaxHighlighterConfig, 'boldOrItalicColor', color) || color);
                        
                        if (match[0].length === 6) {
                            // 处理粗体
                            if (boldState) {
                                if (!italicState) {
                                    // 结束粗体
                                    boldState = false;
                                }
                            } else {
                                if (italicState) {
                                    // 开始粗体(已有斜体)
                                    boldState = true;
                                } else {
                                    // 开始粗体
                                    stack.push({
                                        text: text,
                                        pos: pos,
                                        regex: x,
                                        color: safeColorAccess(syntaxHighlighterConfig, 'boldOrItalicColor', color) || color,
                                        boldState: true,
                                        italicState: false,
                                        context: "bold"
                                    });
                                }
                            }
                        } else {
                            // 处理斜体
                            if (italicState) {
                                if (!boldState) {
                                    // 结束斜体
                                    italicState = false;
                                }
                            } else {
                                if (boldState) {
                                    // 开始斜体(已有粗体)
                                    italicState = true;
                                } else {
                                    // 开始斜体
                                    stack.push({
                                        text: text,
                                        pos: pos,
                                        regex: x,
                                        color: safeColorAccess(syntaxHighlighterConfig, 'boldOrItalicColor', color) || color,
                                        boldState: false,
                                        italicState: true,
                                        context: "italic"
                                    });
                                }
                            }
                        }
                        break;
                    
                    case "&":
                        // HTML实体
                        u(match[0], safeColorAccess(syntaxHighlighterConfig, 'entityColor', color) || color);
                        break;
                    
                    case "~":
                        // 签名
                        u(match[0], safeColorAccess(syntaxHighlighterConfig, 'signatureColor', color) || color);
                        break;
                    
                    default:
                        // 默认处理
                        u(match[0], safeColorAccess(syntaxHighlighterConfig, 'externalLinkColor', color) || color);
                }
                
                // 将当前任务重新推入栈中,继续处理剩余文本
                stack.push({
                    text: text,
                    pos: pos,
                    regex: regex,
                    color: color,
                    boldState: boldState,
                    italicState: italicState,
                    context: context
                });
                // 移除break语句,让循环继续处理当前任务的剩余文本
            }
            
            // 如果当前任务处理完毕,处理剩余文本
            if (match === null && pos < text.length) {
                u(text.substring(pos), color);
                m = text.length;
            }
            
        }
        
        // 检查栈深度限制:使用stack.length来反映实际栈大小
        if (stack.length >= MAX_STACK_DEPTH) {
            console.error('Stack depth exceeded maximum limit:', stack.length);
            // 退出循环,避免无限递归 - 通过设置stack为空数组来终止循环
            stack = [];
        }
        
        // 处理剩余文本
        if (m < h.length) {
            u(h.substring(m), "");
        }

        var t = Date.now();
        if (t - e > safeConfigAccess(syntaxHighlighterConfig, 'timeout', 20)) {
            clearInterval(y);
            g.removeEventListener("input", E);
            g.removeEventListener("scroll", R);
            g.removeEventListener("scroll", F);
            p.disconnect();
            f.disconnect();
            d.nodeValue = "";
            var a = {
                zh: "此页面上的语法突出显示被禁用,因为它花费的时间太长。允许的突出显示时间最长为$1毫秒,而您的计算机则为$2毫秒。请尝试关闭一些标签和程序,然后单击\"显示预览\"或\"显示更改\"。如果不起作用,请尝试使用其他网页浏览器,如果还不起作用,请尝试使用速度更快的计算机。",
                "zh-hans": "此页面上的语法突出显示被禁用,因为它花费的时间太长。允许的突出显示时间最长为$1毫秒,而您的计算机则为$2毫秒。请尝试关闭一些标签和程序,然后单击\"显示预览\"或\"显示更改\"。如果不起作用,请尝试使用其他网页浏览器,如果还不起作用,请尝试使用速度更快的计算机。",
                "zh-hant": "此頁面上的語法突出顯示被禁用,因為它花費的時間太長。允許的突出顯示時間最長為$1毫秒,而您的計算機則為$2毫秒。請嘗試關閉一些標籤和程序,然後單擊\"顯示預覽\"或\"顯示更改\"。如果不起作用,請嘗試使用其他網頁瀏覽器,如果还不起作用,請嘗試使用速度更快的計算機。"
            };
            var n = mw.config.get("wgUserLanguage");
            a = a[n] || a["zh-hant"] || a.zh;
            return g.style.backgroundColor = "", g.style.marginTop = "0", l.removeAttribute("dir"), l.removeAttribute("lang"), l.setAttribute("style", "color:red; font-size:small"), void (l.textContent = a.replace("$1", safeConfigAccess(syntaxHighlighterConfig, 'timeout', 20)).replace("$2", t - e));
        }

        // 智能增量更新:只更新变化的CSS样式部分
        var newCSS = o.substring(2).replace(/\\n/g, "\\A ") + "'}";
        newCSS += "#wpTextbox0>span::after{visibility:hidden}";
        
        // 如果CSS内容没有变化,避免不必要的DOM操作
        if (lastHighlightState !== newCSS) {
            d.nodeValue = newCSS;
            lastHighlightState = newCSS;
        }
        
        // 智能span元素管理:只创建或删除需要的元素
        if (b < r) {
            // 需要添加新的span元素
            var s = document.createDocumentFragment();
            for (; b < r; b++) {
                var span = document.createElement("span");
                span.id = "s" + b;
                s.appendChild(span);
                spanCache[b] = span; // 缓存span元素
            }
            l.appendChild(s);
        } else if (b > r) {
            // 需要删除多余的span元素
            for (var j = b - 1; j >= r; j--) {
                var spanToRemove = document.getElementById("s" + j);
                if (spanToRemove && spanToRemove.parentNode === l) {
                    l.removeChild(spanToRemove);
                    delete spanCache[j]; // 清理缓存
                }
            }
            b = r;
        }
    }

    function R() {
        l.scrollLeft = g.scrollLeft;
    }

    function F() {
        l.scrollTop = g.scrollTop;
    }

    function a() {
        l.dir = g.dir;
    }

    function n() {
        g.previousSibling != l && (g.parentNode.insertBefore(l, g), f.disconnect(), f.observe(g.parentNode, {
            childList: !0
        }));
    }

    function s() {
        g.value != c && E();
        g.scrollLeft != l.scrollLeft && R();
        g.scrollTop != l.scrollTop && F();
        var e = window.getComputedStyle(l).height,
            t = g.offsetHeight ? window.getComputedStyle(g).height : "0px";
        e != t && (l.style.height = t, g.style.marginTop = "-" + t);
    }

    function i() {
        // 浏览器兼容性检查:如果MutationObserver不被支持,自动禁用高亮功能
        if (!window.MutationObserver) {
            console.warn("Syntax highlighter disabled: MutationObserver not supported");
            return;
        }
        
        // 全局变量安全检查:确保syntaxHighlighterConfig和syntaxHighlighterSiteConfig存在
        window.syntaxHighlighterConfig = window.syntaxHighlighterConfig || {};
        window.syntaxHighlighterSiteConfig = window.syntaxHighlighterSiteConfig || {};
        
        var e, t, i;

        function o(e, t, i) {
            void 0 === syntaxHighlighterConfig[e] && (syntaxHighlighterConfig[e] = syntaxHighlighterSiteConfig[e] || t);
            "normal" == syntaxHighlighterConfig[e] ? syntaxHighlighterConfig[e] = t : void 0 !== syntaxHighlighterConfig[e] || (void 0 !== syntaxHighlighterConfig.defaultColor && i ? syntaxHighlighterConfig[e] = syntaxHighlighterConfig.defaultColor : syntaxHighlighterConfig[e] = t);
        }

        (g = document.getElementById("wpTextbox1")) && (document.getElementById("wpTextbox0") || (window.syntaxHighlighterSiteConfig = window.syntaxHighlighterSiteConfig || {}, window.syntaxHighlighterConfig = window.syntaxHighlighterConfig || {}, 
        // 补充缺失的默认数组配置
        syntaxHighlighterConfig.voidTags = syntaxHighlighterConfig.voidTags || [],
        syntaxHighlighterConfig.sourceTags = syntaxHighlighterConfig.sourceTags || [],
        syntaxHighlighterConfig.nowikiTags = syntaxHighlighterConfig.nowikiTags || [],
        
        o("backgroundColor", "#FFF", !1), o("foregroundColor", "#000", !1), o("boldOrItalicColor", "#EEE", !0), o("commentColor", "#EFE", !0), o("entityColor", "#DFD", !0), o("externalLinkColor", "#EFF", !0), o("headingColor", "#EEE", !0), o("hrColor", "#EEE", !0), o("listOrIndentColor", "#EFE", !0), o("parameterColor", "#FC6", !0), o("signatureColor", "#FC6", !0), o("tagColor", "#FEF", !0), o("tableColor", "#FFC", !0), o("templateColor", "#FFC", !0), o("wikilinkColor", "#EEF", !0), syntaxHighlighterConfig.nowikiTags = syntaxHighlighterConfig.nowikiTags || syntaxHighlighterSiteConfig.nowikiTags || ["nowiki", "pre"], syntaxHighlighterConfig.sourceTags = syntaxHighlighterConfig.sourceTags || syntaxHighlighterSiteConfig.sourceTags || ["math", "syntaxhighlight", "source", "timeline", "hiero"], syntaxHighlighterConfig.voidTags = syntaxHighlighterConfig.voidTags || syntaxHighlighterSiteConfig.voidTags || [], syntaxHighlighterConfig.timeout = syntaxHighlighterConfig.timeout || syntaxHighlighterSiteConfig.timeout || 20, syntaxHighlighterConfig.nowikiTags.forEach(function(e) {
            var cacheKey = "nowiki_" + e;
            if (!regexCache[cacheKey]) {
                regexCache[cacheKey] = new RegExp("(</" + e + ">)\\n*|" + r, "gm");
            }
            L[e] = regexCache[cacheKey];
        }), l = document.createElement("div"), e = document.createElement("style"), 
        // 添加样式冲突防护
        e.setAttribute("scoped", "scoped"), // 限制样式仅作用于当前组件
        e.setAttribute("data-syntax-highlighter", "true"), // 便于识别和调试
        d = e.appendChild(document.createTextNode("")), i = "vertical" == (t = window.getComputedStyle(g)).resize || "both" == t.resize ? "vertical" : "none", l.dir = g.dir, l.id = "wpTextbox0", l.lang = g.lang, l.style.backgroundColor = syntaxHighlighterConfig.backgroundColor, l.style.borderBottomLeftRadius = t.borderBottomLeftRadius, l.style.borderBottomRightRadius = t.borderBottomRightRadius, l.style.borderBottomStyle = t.borderBottomStyle, l.style.borderBottomWidth = t.borderBottomWidth, l.style.borderColor = "transparent", l.style.borderLeftStyle = t.borderLeftStyle, l.style.borderLeftWidth = t.borderLeftWidth, l.style.borderRightStyle = t.borderRightStyle, l.style.borderRightWidth = t.borderRightWidth, l.style.borderTopLeftRadius = t.borderTopLeftRadius, l.style.borderTopRightRadius = t.borderTopRightRadius, l.style.borderTopStyle = t.borderTopStyle, l.style.borderTopWidth = t.borderTopWidth, l.style.boxSizing = "border-box", l.style.clear = t.clear, l.style.fontFamily = t.fontFamily, l.style.fontSize = t.fontSize, l.style.lineHeight = "normal", l.style.marginBottom = "0", l.style.marginLeft = "0", l.style.marginRight = "0", l.style.marginTop = "0", l.style.overflowX = "auto", l.style.overflowY = "scroll", l.style.resize = i, l.style.tabSize = t.tabSize, l.style.whiteSpace = "pre-wrap", l.style.width = "100%", l.style.wordWrap = "normal", g.style.backgroundColor = "transparent", g.style.borderBottomLeftRadius = t.borderBottomLeftRadius, g.style.borderBottomRightRadius = t.borderBottomRightRadius, g.style.borderBottomStyle = t.borderBottomStyle, g.style.borderBottomWidth = t.borderBottomWidth, g.style.borderLeftStyle = t.borderLeftStyle, g.style.borderLeftWidth = t.borderLeftWidth, g.style.borderRightStyle = t.borderRightStyle, g.style.borderRightWidth = t.borderRightWidth, g.style.borderTopLeftRadius = t.borderTopLeftRadius, g.style.borderTopRightRadius = t.borderTopRightRadius, g.style.borderTopStyle = t.borderTopStyle, g.style.borderTopWidth = t.borderTopWidth, g.style.boxSizing = "border-box", g.style.clear = t.clear, g.style.color = syntaxHighlighterConfig.foregroundColor, g.style.fontFamily = t.fontFamily, g.style.fontSize = t.fontSize, g.style.lineHeight = "normal", g.style.marginLeft = "0", g.style.marginRight = "0", g.style.marginTop = "-" + t.height, g.style.overflowX = "auto", g.style.overflowY = "scroll", g.style.padding = "0", g.style.resize = i, g.style.tabSize = t.tabSize, g.style.whiteSpace = "pre-wrap", g.style.width = "100%", g.style.wordWrap = "normal", g.parentNode.insertBefore(l, g), document.head.appendChild(e), g.addEventListener("input", E), g.addEventListener("scroll", R), g.addEventListener("scroll", F), (p = new MutationObserver(a)).observe(g, {
            attributes: !0
        }), (f = new MutationObserver(n)).observe(g.parentNode, {
            childList: !0
        }), y = setInterval(s, 500), E()));
    }

    var o = mw.config.get("wgAction"),
        e = $.client.profile().layout;
    "edit" != o && "submit" != o || "wikitext" != mw.config.get("wgPageContentModel") || "trident" == e || ("complete" == document.readyState ? i() : window.addEventListener("load", i));
    
    // 添加页面卸载时的资源清理逻辑
    function cleanup() {
        // 清理定时器
        if (y) {
            clearInterval(y);
            y = null;
        }
        // 清理观察者
        [p, f].forEach(observer => observer?.disconnect());
        // 清理事件监听
        if (g) {
            g.removeEventListener("input", E);
            g.removeEventListener("scroll", R);
            g.removeEventListener("scroll", F);
        }
        // 清理DOM元素
        l?.parentNode?.removeChild(l);
        d?.parentNode?.parentNode?.removeChild(d.parentNode); // 移除style元素
        // 重置变量
        l = g = d = c = y = p = f = b = null;
    }
    // 双重事件监听确保清理
    window.addEventListener('beforeunload', cleanup);
    window.addEventListener('unload', cleanup);
});