跳转到内容

模組:PatternedCandidateUtils2

维基百科,自由的百科全书

这是本页的一个历史版本,由Vanished user 1929210留言 | 贡献2017年1月13日 (五) 14:38编辑。这可能和当前版本存在着巨大的差异。

--[[
                      警告

              本模組並不能正確地工作!

除非有人能夠重寫encodetitle,解析<pre>和<nowiki>內容,
然後解析模板、連結等內容,再解決重複標題……否則只能善意地假定
發言的人不會導致程式錯誤。
]]--

local z = {}

function getCandidates( frame )
    local page = mw.title.new( frame.args.title ):getContent()
    local matches = {}
    local black = {}
    if frame.args.black then
        for b in mw.text.gsplit( frame.args.black, '|', true ) do
            black[b] = true
        end
    end
    for m in mw.ustring.gmatch( page, frame.args.pattern ) do
        if not black[m] then
            table.insert( matches, m )
        end
    end
    return matches
end

function z.count( frame )
    return #getCandidates( frame )
end

local function encodetitle( frame, text )
    --[[
        基於 WP:AGF,假設不會發生以下事情:
        1. 有人故意在標題中放不完整的括號
        2. 有人在標題中放<pre>、<code>、<nowiki>、<ref>甚至在裡面加入換行
        3. 跟前面已有標題重複
        4. 標題中有圖片
        5. 有標題無內容
    ]]--
    local r = mw.text.trim(frame:preprocess(text or ''))

    -- 展開連結
    r = string.gsub(r, '%[%[[^%|%]\n]-%|([^\n]-)%]%]', '%1')
    r = string.gsub(r, '%[%[:?([^\n]-)%]%]', '%1')

    -- 更換特殊字元
    r = string.gsub(r, '\n', '')
    r = string.gsub(r, '%[', '&#91;')
    r = string.gsub(r, '%]', '&#93;')
    r = string.gsub(r, '%|', '&#124;')
    r = string.gsub(r, '{', '&#123;')
    r = string.gsub(r, '}', '&#125;')

    return r
end

function z.list( frame )
    local list = getCandidates( frame )
    local linkprefix = mw.text.trim(frame.args.linkprefix)
    for i = 1, #list do
        if linkprefix then
            local title = encodetitle(frame, list[i])
            list[i] = '[[:' .. linkprefix .. title .. '|' .. title .. ']]'
        else
            list[i] = '[[:' .. list[i] .. ']]'
        end
    end
    if #list > 0 then
        return table.concat( list, '-' )
    else
        return '暂无'
    end
end

function z.listtalk( frame )
    frame.args.pattern = '[^=]==%s*([^=]+)%s*==[^=]'
    if frame.args[1] and not frame.args.title then
        frame.args.title = frame.args[1]
    end
    frame.args.linkprefix = mw.text.trim(frame.args.title or '') .. '#'
    return z.list(frame)
end

return z