Модуль:Wikitext

З Вікіпедыі, свабоднай энцыклапедыі

Дакументацыю да гэтага модуля можна стварыць у Модуль:Wikitext/Дакументацыя

--[[
Службовыя функцыі для канверсіі вікітэксту

Сінтаксіс: функцыя з малой літары - для {{#invoke:wikitext|fun|...}},
з загалоўнай - для require(wikitext).Fun()
]]

specns={file='file',image='file',category='cat',
    ['да']='cat',['катэгорыя']='cat',['выява']='file',['выява']='file'}

linkprefs="http:// gopher:// https:// mailto: news:// ftp:// irc:// //"

local function Delink(text,repl,cat,file,href,colon)
    return ( --выдаленне вікі-спасылак
        mw.ustring.gsub(text, "%[%[(%s*([^|%]]+)%s*)|?(.-)%]%](%a*)", function(a,l,c,e)
        l = l:gsub("%s+"," ");
        if specns[mw.ustring.lower(l):match("^(.*):")] then
            -- спасылка на спецыяльнае п. і.
            if specns[mw.ustring.lower(l):match("^(.*):")]=='cat' then--катэгорыя
                if cat then -- радок замены, %1=catname, %2=key, %3=mode, %%="%"
                    return table.concat{ l:gsub("^.-:%s*",''), '|', c }:gsub( "^(.-)|([^|]*)|?(.-)$", cat ) .. e
                else 
                    return e -- выдаляць па змоўчанні ўсе катэгорыі
                end
            else--выява. Fixme:пакуль усе палі апісання выявы не выдаюцца шаблонам
                if  file then -- радок замены, %1=filename, %2=parameters, %%="%"
                    return table.concat{ l:gsub("^.-:%s*",''), '|', c }:gsub( "^(.-)|(.*)", file ) .. e
                else return e -- выразаць фалы
                end
            end--if(выява ці катэгорыя)
        end--if(спец. прасторы)
        l=string.gsub(l,"^: *", colon or "%1");-- замена пачатковага ":"
        if repl then
            return mw.ustring.gsub(l..'|'..(c=='' and a..e or c..e),"^(.-)|(.*)$",repl)
        else
            if c=='' then return a..e else return c..e end-- выразаны 
        end
    end
):gsub(
    "(%[([%a%._\/~%%%-%+&#%?!=%(%)@]+)%s*(.-)%])", function(a,r,t)
        --вырезатор знешніх спасылак
        local p,i=r:match('^(%a*:?//)(.*)')
        if not p then p,i=r:match('^(mailto:)(.*)') end
        if p then-- Гэта URL
            if href then
                return (p..' '..i..' '..t):gsub("^(.-) (.-) (.*)$",href) 
            else
                return t
            end
        else-- Гэта не URL
            return a
        end
    end--вырезатор
) )
end

local function Detag(t)
    if t == nil or t == '' then
    	return ''
    end
    -- Выразаны двукоссі і > з литералов у тэгах, а потым самі литералы
    local text,j,i,k=t,0;
    repeat 
        text,i=text:gsub('(</?%a[^>"\']*")[^"]*\\["\\]',"%1");--першая \", \\ з 1-го литерала
        text,k=text:gsub("(</?%a[^>\"']*')[^']*\\['\\]","%1");--першая \', \\ з 1-го литерала
        if i+k==0 then--1-й литерал вычышчаны
            text,j=text:gsub("(</?%a[^>]*)(['\"]).-%2","%1")
        end
    until i+j+k==0
-- і выразаць тэгі, а таксама ''курсіў'' і '''тлусты'''
    return (text:gsub("'''?",""):gsub('</?%a[^>]*>',''))
end

local function Nodis(t) -- Прыбірае ўдакладненні ў дужках
    return (t:gsub('%s*%([^%)]+%)$',''))
end


return {
delink=function(f) -- Выдаляе спасылкі з вікітэксту
    local tf=f:getParent()
    return Delink(
        f.args[1] or tf.args[1],
        f.args['repl'] or tf.args['repl'],
        f.args['cat'] or tf.args['cat'],
        f.args['file'] or tf.args['file'],
        f.args['href'] or tf.args['href'],
        f.args[':'] or tf.args[':']
        )
end; Delink=Delink;

detag=function(f)
    return Detag(f.args[1] or f:getParent().args[1])
end; Detag=Detag;

plain=function(f)
    local tf=f:getParent()
    return Detag(Delink(
        f.args[1] or tf.args[1],
        f.args['repl'] or tf.args['repl'],
        f.args['cat'] or tf.args['cat'],
        f.args['file'] or tf.args['file'],
        f.args['href'] or tf.args['href'],
        f.args[':'] or tf.args[':']
        ));
end;

nodis=function(f)
    return Nodis(f.args[1] or f:getParent().args[1])
end;Nodis=Nodis
}