Module:Headinglist

From Soyjak Wiki, the free ensoyclopedia
Jump to navigationJump to search

-- Module:TopHeadings
-- Returns a list of top-level headings with links

local p = {}

-- Helper: strip wikilinks ([[Page]] or [[Page|Label]])
local function stripLinks(text)
    text = mw.ustring.gsub(text, "%[%[[^|%]]+|([^%]]+)%]%]", "%1")
    text = mw.ustring.gsub(text, "%[%[([^%]]+)%]%]", "%1")
    return text
end

-- Correct MediaWiki-style heading id
local function headingToId(heading)
    return mw.uri.anchorEncode(heading)
end

function p.list(frame)
    local pageName = frame.args.page or mw.title.getCurrentTitle().prefixedText
    local title = mw.title.new(pageName)
    if not title then return "Invalid page. [[File:Retardedsoy.gif|50px]]" end
    
    local content = title:getContent()
    if not content then return "No content [[File:Retardedsoy.gif|50px]]" end
    
    local headings = {}
    
    for heading in content:gmatch("\n*==%s*(.-)%s*==") do
        table.insert(headings, stripLinks(heading))
    end
    
    if #headings == 0 then
        return "No top-level headings. [[File:Retardedsoy.gif|50px]]"
    end
    
    local listItems = {}
    for _, heading in ipairs(headings) do
        local id = headingToId(heading)
        table.insert(listItems, string.format("# [[%s#%s|%s]]", pageName, id, heading))
    end
    
    return table.concat(listItems, "\n")
end

return p