Module:Subpages

From Guild of Archivists

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

-- subpages = require('Module:Subpages).subpages
-- for page in subpages('Page') do ... end

local _M = {}

function _M.subpages(page)
    page = string.gsub( page, '^%s*%[*%[%[(.-)%]%]%]*%s*$', function(l)
        return string.gsub( l, '^([^|]*)|.*$', '%1', 1 )
    end, 1 ) 
        :gsub( '[%s_]+', ' ' )
        :gsub( '/+', '/' )
        :gsub( '^%s', '', 1 )
        :gsub( '%s$', '', 1 )
        :gsub( '/$', '', 1 );
 
    if page == '' then
        page = tostring( mw.title.getCurrentTitle() );
    elseif mw.ustring.sub( page, 1, 1) == '/' then
        page = table.concat{ tostring( mw.title.getCurrentTitle() ), page };
    end
    
    local sub, prefix = mw.ustring.sub
    
    prefix, page = pcall(mw.title.new, page, 0)
    if prefix and page then
        prefix = string.len( page.text ) + 2
        page = mw.ustring.gmatch(
            mw.text.unstrip(
                mw:getCurrentFrame():preprocess('{{Special:PrefixIndex/' .. page.prefixedText .. '/}}')
            ),
            '<a href="[^"]*" title="[^"]*">(.-)</a>'
        )
    else
        prefix = nil
        page = function() return nil end
    end
    
    return function()
        local pg = page()
        return pg and sub(pg, prefix) or nil
    end
end

return _M