Module:AuxTOCDetect

From Wikisource
Jump to navigation Jump to search
local p = {}

function p.main(frame)
    local title = mw.title.getCurrentTitle()
    local indexContent = title:getContent() -- Get the content of the current Index page

    -- Use a pattern that captures links to the main namespace without a subpage component
    -- Assuming links are formatted as ''[[Page Name|Display Text]]''
    local linkPattern = "%[%[([^|%]]+)|" -- Matches links that do not include the '/' character
    local mainLink = indexContent:match(linkPattern)

    if mainLink and not mainLink:find("/") then -- Ensures the link is not to a subpage
        local mainPageTitle = mw.title.new(mainLink, 0) -- 0 is the namespace ID for the main namespace
        if mainPageTitle and mainPageTitle.exists then
            local mainPageContent = mainPageTitle:getContent()
            -- Find the complete AuxTOC template call including its opening and closing braces
            local auxtocComplete = mainPageContent:match('({{AuxTOC|.-}})')
			if not auxtocComplete then
			    auxtocComplete = mainPageContent:match('({{Auxiliary Table of Contents|.-}})')
			end
			if not auxtocComplete then
			    auxtocComplete = mainPageContent:match('({{Auxiliary table of contents|.-}})')
			end

            if auxtocComplete then
                -- Process the AuxTOC template with parameters as an actual template call
                local result = frame:preprocess(auxtocComplete)
                return result
            else
                return "AuxTOC not found on the main page."
            end
        else
        	-- This needs to not return anything if there's a red link, since an error while the
        	-- proofread pages are processing with pywikibot, the error could lead users to remove 
        	-- the template prematurely.
            return ""
        end
    else
        return "No suitable main namespace link found in the Index page."
    end
end

return p