dev

This module was made as a sandbox for the Links module. This documentation is kept to prevent redlinks.


--<pre> Creates links and changes wikitext when it detects external links
-- Syntax
-- {{#invoke:links|main|page/url|label|type=ext/local}}
local p = {}

function p.link(url,desc,typ)
    local url = url or ""
    local lenUrl = mw.ustring.len(url)
    local uMatch = mw.ustring.match

    if typ == "ext" and (not uMatch(url, "%.") or  lenUrl < 3)
            or lenUrl < 1 then
        return
    end

    local prefix = "[["
    local suffix = "]]"
    local separator = "|"

    if url:match("^[Cc]ategory:") and typ ~= "ext" then
        prefix = "[[:"
    end

    -- Adapt if url is external
    if typ ~= "local"  and (uMatch(url, "www%.") or uMatch(url, "^http"))
            or typ == "ext" then
        prefix = "[//"

        if uMatch(url, "^http") then
            prefix = "["
        end

        suffix = "]"
        separator = " "
    end

    local desc = desc or ""

    if mw.ustring.len(desc) < 1 then
        separator = ""
    end

    return prefix .. url .. separator .. desc .. suffix
end

function p.main(frame)
    local args = require("Dev:Arguments").getArgs(frame)
    
    return p.link(args[1] or args.page , args[2] or args.desc,args.type)
end

-- This creates and format many links
function p.batch(frame)
    local args = require("Dev:Arguments").getArgs(frame)
    local separator = args.separator
    local delimiter = args.delimiter
    
    return  p.createLinkBatch(args, separator, delimiter)
end

--@links : a table containg links, e.g. {'Lua label1 type','www.google.com google ext'}
--@separator: a separator between each link
--@delimiter : an optional delimiter that will separate the label, link & type
function p.createLinkBatch(links, separator, delimiter)
    local linkTable = {}
    local linkBatch,linkUrl,linkLabel,linkType = "","","",""
    local delimiter = delimiter or "%s"
    local separator = separator or " • "
    local linkLen = 0
    
    for _, linkData in ipairs(links) do
        linkLen = linkData:len()
        linkType = linkData:sub(linkLen-2)
        
        if linkType ~="ext" and linkType ~= "int" then
            linkType = ""
        else 
            linkData = linkData:sub(1, linkLen-4)
        end
        
        linkTable = mw.text.split(linkData, delimiter)
        
        linkUrl = linkTable[1]
        linkLabel = linkTable[2]
        linkBatch = linkBatch .. p.link(linkUrl,linkLabel,linkType) .. separator
    end
    
    return linkBatch
end

return p