-

本WIKI编辑权限开放,欢迎收藏起来防止迷路,也希望有爱的小伙伴和我们一起编辑哟~ 编辑帮助:目录BWIKI反馈留言板


请选择语言:

版本250722.2
全站通知:

模块:效果说明高亮

来自赛尔号WIKI_BWIKI_哔哩哔哩
跳到导航 跳到搜索

此模块的文档可以在模块:效果说明高亮/doc创建

-- Module:KeywordTooltip
local p = {}

-- 1. 读取“模板:效果说明”里的 #switch 键值对,返回 table
local function getKeywords()
    -- 缓存,同一次请求只解析一次
    if p._kwCache then return p._kwCache end
    local txt = mw.title.new('模板:效果说明'):getContent() or ''
    p._kwCache = {}
    for key, desc in string.gmatch(txt, '|%s*([^=|]+)%s*=%s*([^\n]+)') do
        key  = mw.text.trim(key)
        desc = mw.text.trim(desc)
        if key ~= '' and desc ~= '' then
            p._kwCache[key] = desc
        end
    end
    return p._kwCache
end

-- 2. 转义魔法字符,用于 gmatch/gsub
local function esc(s)
    return s:gsub('[%(%)%.%%%+%-%*%?%[%]%^%$]', '%%%1')
end

-- 3. 主入口:高亮 + 跳过已包装关键词
function p.annotate(frame)
    local text = frame.args[1] or ''
    local kws  = getKeywords()

    -- 按长度降序,避免短词覆盖长词
    local sorted = {}
    for k in pairs(kws) do table.insert(sorted, k) end
    table.sort(sorted, function(a, b) return #a > #b end)

    for _, k in ipairs(sorted) do
        local pat = esc(k)
        -- 用函数式替换,可检查上下文
        text = text:gsub(pat, function(w)
            -- 取当前匹配的真实位置(gsub 每次传整个匹配)
            local pos = text:find(pat, 1, true) -- 简单定位,够用
            local ctx = text:sub(math.max(1, pos - 40), pos + #w + 40)

            -- 已处于 {{效果说明|...}} 内部 → 原样返回
            if ctx:match('{{%s*效果说明%s*|%s*' .. esc(w) .. '%s*}}') then
                return w
            end
            -- 否则套模板
            return '{{效果说明|' .. w .. '}}'
        end)
    end

    -- 强制二次解析,让 {{效果说明|...}} 真正展开
    return frame:preprocess(text)
end

return p