Jump to content

Module:BronMeat/WordLinker

From Wikipedia, the free encyclopedia

local p = {}

function p.autolink(frame)
    -- Get the text from args (support both direct invoke and template)
    local text = frame.args[1] or frame:getParent().args[1] or ''
    
    -- Parse exclude list (comma-separated words)
    local exclude_str = frame.args.exclude or ''
    local exclude = {}
    for word in string.gmatch(exclude_str, '[^,]+') do
        exclude[mw.ustring.lower(mw.text.trim(word))] = true
    end
    
    -- Parse custom links (format: word1=target1|word2=target2)
    local custom_str = frame.args.custom or ''
    local custom = {}
    for pair in string.gmatch(custom_str, '[^|]+') do
        local parts = mw.text.split(pair, '=')
        if #parts == 2 then
            local key = mw.ustring.lower(mw.text.trim(parts[1]))
            local val = mw.text.trim(parts[2])
            custom[key] = val
        end
    end
   
    -- Replace words with links, skipping excluded, short words, and using custom targets where specified
    text = mw.ustring.gsub(text, "([%a']+)", function(word)
        local lower = mw.ustring.lower(word)
        if exclude[lower] or #word < 2 then
            return word
        end
        local target = custom[lower] or word
        if target == word then
            return '[[' .. word .. ']]'
        else
            return '[[' .. target .. '|' .. word .. ']]'
        end
    end)
    
    return text
end

return p