Module:Languages

From Wikiversity

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

p = {}

function p.subpages(frame)
    local args, pargs = frame.args, ( frame:getParent() or {} ).args or {}
    local where, success = args.page or args[1] or pargs.page or pargs[1] or ''
    local string = mw.ustring
    
    where = string.gsub( where, '^%s*%[*%[%[(.-)%]%]%]*%s*$', function(l)
        return string.gsub( l, '^([^|]*)|.*$', '%1', 1 )
    end, 1 )
        :gsub( '[%s_]+', ' ' )
        :gsub( '/+', '/' )
        :gsub( '^%s', '', 1 )
        :gsub( '%s$', '', 1 )
        :gsub( '/$', '', 1 );
    
    if where == '' then
        where = tostring( mw.title.getCurrentTitle() )
    elseif mw.ustring.sub( where, 1, 1) == '/' then
        where = table.concat({ tostring( mw.title.getCurrentTitle() ), where })
    end
    
    success, where = pcall(function(title) return mw.title.new( title, 0 ) end, where )
    if not success or not where then return '' end
    
    local prefix = string.len( where.text ) + 2
    local function language( name )
        local name = string.sub( name, prefix )
        local lang = mw.language.fetchLanguageName( string.lower( name ) )
        if lang ~= '' then
            return name, table.concat({ string.upper( string.sub( lang, 1, 1 ) ), string.sub( lang, 2 ) })
        end
    end
    
    local subpages, links, pg, lang = string.gmatch(
        mw.text.unstrip( frame:preprocess('{{Special:PrefixIndex/' .. where.prefixedText .. '/}}') ),
        '<a href="[^"]*" title="[^"]*">(.-)</a>'
    ), {}
    
    for page in subpages do
        pg, lang = language( page )
        if lang then
            table.insert( links, table.concat({
                '<span lang="', string.lower(pg), '">',
                '[[', where.prefixedText, '/', pg, '|', lang, ']]',
                '</span>'
            }) )
        end
    end
    
    return table.concat( links, '&nbsp;·&nbsp;' )
end

function p.browse(frame)
    local args, list, string = ( frame:getParent() or frame ).args or {}, {}, mw.ustring
    local fetch, length = mw.language.fetchLanguageName, 0
    
    for lang, text in pairs(args) do
        local l = string.lower( lang )
        local f = fetch( l )
        if string.match( text, '%S' ) and f ~= '' then
            f = table.concat({ string.upper( string.sub(f, 1, 1) ), string.sub(f, 2) })
            table.insert( list, table.concat({
                '<div lang="', l, '" xml:lang="', l, '" class="lang-', l, '">',
                '<span style="font-weight:bold">', f, ':</span>&emsp;',
                text, '</div>'
            }) )
            length = length + 1
        end
    end
    
    list = table.concat( list, '\n' )
    
    if length > 1 then
        list = table.concat( { '<div class="multilingual">', list, '</div>' }, '\n' )
    end
    
    return list
end

return p