Module:ExtractSection

From JoJo's Bizarre Encyclopedia - JoJo Wiki
Revision as of 19:04, 23 December 2024 by HudgynS (talk | contribs)
Jump to navigation Jump to search

Documentation for this module may be created at Module:ExtractSection/doc

local p = {}

-- Helper function to extract content under a specific section header
function p.extractSection(content, header)
    -- Define the pattern to find the section header
    local startPattern = mw.ustring.gsub(header, "=", "%%=")
    -- Find the start of the specified header
    local sectionStart, sectionEnd = mw.ustring.find(content, startPattern)
    -- If the section is not found, return nil
    if not sectionStart then
        return nil
    end
    -- Find the next section header (either === or higher)
    local nextHeaderPattern = "\n==+%s*[^=]"
    local nextHeaderStart, nextHeaderEnd = mw.ustring.find(content, nextHeaderPattern, sectionEnd + 1)
    -- Extract the content until the next section header or the end of the content
    if nextHeaderStart then
        return mw.ustring.sub(content, sectionEnd + 1, nextHeaderStart - 1)
    else
        return mw.ustring.sub(content, sectionEnd + 1)
    end
end

function p.extractTab(content, label)
    local pattern = label .. "|"
    local pattern2 = label .. " *= *"
    local matchStart, matchEnd = string.find(content, pattern)
    if not matchStart then
        matchStart, matchEnd = string.find(content, pattern2)
        if not matchStart then
            return nil
        end
    end

    local tab = ""
    local braceCount = 0
    local i = matchEnd + 1
    local isNewLine = false

    while i <= #value do
        local char = value:sub(i, i)

        if char == '{' then
            braceCount = braceCount + 1
        elseif char == '}' then
            braceCount = braceCount - 1
        end

        if braceCount == 0 and char == '\n' then
            isNewLine = true
        elseif isNewLine and char == '|' then
            break
        else
            isNewLine = false
            tab = tab .. char
        end

        i = i + 1
    end

    return tab
end

function p.transclude(frame)
    local args = frame:getParent().args
    local content = args[1]
    local field = args[2]
    local mode = args["mode"]

    if not (content and field) then
        return "Error: Missing parameters."
    end

    local content = mw.title.new(content):getContent()
    if not content then
        return "Error: Page not found"
    end

    if mode == "tab" then
        return frame:preprocess(extractTab(content, field))
    end
    return frame:preprocess(extractSection(content, field))
end

return p