Jump to content

Module:wikilinks

ពីWiktionary

--[=[
This module strips square brackets out or replaces them. May be furtherlt merged or moved to other modules
]=]
local specns={file='file',image='file',category='cat'} -- table of NS, refs on which are unusual
return {
    rl=function(f)
        local tf=f:getParent(); -- Call it in template {{Delink|some [[wikitext]] with [[foo|link]]s}}
        return ( string.gsub(tf.args[1], "%[%[(%s*([^|%]]+)%s*)|?(.-)]](%a*)", function(a,l,c,e)
            -- NOTE: in other projects other characters can "glue" to the wikilink, in RuWP mw.ustring.gsub() must be here
            --do return table.concat({'{',a or 'nil',l or 'nil',c or 'nil',e or 'nil','}'},"*") end--
            l = l:gsub("%s+"," ");
            if not (a:sub(1,1)==':') and specns[(l:lower():match("^(.*):") or {})[1]] then
                -- was unescaped specNS ref; yes, they are such
                if l:lower():match("^(.*):")[1]=='cat' then
                    if  tf.args["cat"] then -- string to replace, %1=catname, %2=key, %3=mode, %%="%"
                        return table.concat{ l:gsub("^.-:%s*",''), '|', c }:gsub( "^(.-)|([^|]*)|?(.-)$", tf.args["cat"] ) .. e
                    elseif tf.args["tcat"] or tf.args["template"] then --special template or knowing argument t=cat
                        return frame:expandTemplate{
                            title = tf.args["tcat"] or tf.args["template"],
                            args = { l:gsub("^.-:%s*",''), t='category', c:gsub("^(.-)|(.*)") }
                        }..e
                    else return e -- strip all categories by default
                    end
                else-- Fixme:file syntax currently is not well supported, so fileref can use only filename and all
                    if  tf.args["file"] then -- string to replace, %1=filename, %2=parameters, %%="%"
                        return table.concat{ l:gsub("^.-:%s*",''), '|', c }:gsub( "^(.-)|(.*)", tf.args["file"] ) .. e
                    elseif tf.args["tfile"] or tf.args["template"] then --special template or knowing argument t=file
                        return frame:expandTemplate{
                            title = tf.args["tfile"] or tf.args["template"],
                            args = { l:gsub("^.-:%s*",''), c~='' and a..'|'..c or a, t='file' }
                        }..e
                    else return e -- strip all files by default
                    end
                end
            end
            l=string.gsub(l,"^: *", tf.args[":"] or "%1");-- replacement for initial ":"
            if tf.args["template"] then
                return frame:expandTemplate{title=tf.args["template"],args={l,c~='' and c..e or a..e}} -- pass link and text to template
                elseif c=='' then return a..e else return c..e -- just trim link out
            end
        end) )
    end
}