Ir para o conteúdo

Módulo:Link de predefinição em geral: mudanças entre as edições

De Wiki TokuDrive
Importando predefinição/módulo da Wikipédia em português para manter layout
Importando predefinição/módulo da Wikipédia em português para manter layout
 
Linha 1: Linha 1:
-- Isso implementa a Predefinição:Tlg
-- Implementa a infraestrutura de [[Predefinição:Tlg]] e de outras
-- predefinições da família de ligações para predefinições.
local getArgs = require('Módulo:Arguments').getArgs
local getArgs = require('Módulo:Arguments').getArgs
local p = {}
local p = {}


-- É uma string que não está vazia?
-- É uma string que não está vazia?
local function _ne(s)  
local function _ne(s)
return s ~= nil and s ~= ""
    return s ~= nil and s ~= ''
end
end


local nw = mw.text.nowiki
local nw = mw.text.nowiki


-- Retorna um argumento posicional independentemente de sua chave ter
-- sido armazenada como número ou como representação textual do número.
local function getPositionalArg(args, index)
    local value = args[index]
    if value == nil then
        value = args[tostring(index)]
    end
    return value
end
-- Retorna, em ordem, somente os índices posicionais realmente presentes.
--
-- Não percorremos de 2 até o maior índice: uma chamada artificial como
-- |999999999=x não deve provocar centenas de milhões de iterações.
local function getNumericArgIndexes(args)
    local indexes = {}
    local seen = {}
    for key in pairs(args) do
        local index
        if type(key) == 'number' then
            if key >= 2 and key % 1 == 0 then
                index = key
            end
        elseif type(key) == 'string'
            and key:match('^[1-9]%d*$') then
            local n = tonumber(key)
            if n and n >= 2 then
                index = n
            end
        end
        if index and not seen[index] then
            seen[index] = true
            indexes[#indexes + 1] = index
        end
    end
    table.sort(indexes)
    return indexes
end
-- Divide uma representação de parâmetro nomeado no primeiro "=".
--
-- Exemplo:
--    url=https://example.org/?a=b
-- torna-se:
--    chave = "url"
--    valor = "https://example.org/?a=b"
--
-- Uma string que começa por "=" continua sendo tratada como argumento
-- posicional, como no comportamento histórico.
local function splitNamedParameter(value)
    local pos = value:find('=', 1, true)
    if not pos then
        return nil
    end
    -- Nomes e valores de parâmetros nomeados têm os espaços externos
    -- removidos pelo MediaWiki; reproduzimos esse comportamento aqui.
    local key = mw.text.trim(value:sub(1, pos - 1))
    if key == '' then
        return nil
    end
    local val = mw.text.trim(value:sub(pos + 1))
    return key, val
end
-- Acrescenta o domínio Predefinição: quando o título fornecido não
-- possui um domínio reconhecido.
local function addTemplate(s)
local function addTemplate(s)
local i, _ = s:find(':', 1, true)
    if not _ne(s) then
if i == nil then
        return ''
return 'Predefinição:' .. s
    end
end
 
local ns = s:sub(1, i - 1)
    local i = s:find(':', 1, true)
if ns == '' or mw.site.namespaces[ns] then
 
return s
    if i == nil then
else
        return 'Predefinição:' .. s
return 'Predefinição:' .. s
    end
end
 
end
    local ns = s:sub(1, i - 1)
 
    if ns == '' or mw.site.namespaces[ns] then
        return s
    end


local function trimTemplate(s)
    return 'Predefinição:' .. s
local needle = 'predefinição:'
if s:sub(1, needle:len()):lower() == needle then
return s:sub(needle:len() + 1)
else
return s
end
end
end


-- Constrói a parte do link
-- Constrói a parte correspondente ao nome e à ligação.
local function linkTitle(args)
local function linkTitle(args)
    local firstArg = getPositionalArg(args, 1)
local titleObj
 
if args['1'] then
    local titleObj
-- Isso lida com :Page e outros NS
    if _ne(firstArg) then
titleObj = mw.title.new(args['1'], 'Predefinição')
        -- Isso lida com :Página e outros domínios.
else
        titleObj = mw.title.new(firstArg, 'Predefinição')
titleObj = mw.title.getCurrentTitle()
    else
end
        titleObj = mw.title.getCurrentTitle()
    end
local textPart = args.alttext
 
if not _ne(textPart) then
    local textPart = args.alttext
if titleObj ~= nil then
 
-- Opção Recomendada (Usando ID numérico do namespace 10):
    if not _ne(textPart) then
textPart = titleObj:inNamespace(10) and args['1'] or titleObj.fullText
        if titleObj ~= nil then
else
            -- 10 é o identificador numérico do domínio Predefinição.
-- ligação vermelha
            if titleObj:inNamespace(10) and _ne(firstArg) then
textPart = args['1']
                textPart = firstArg
end
            else
end
                textPart = titleObj.fullText
            end
if _ne(args.subst) then
        else
-- hack: a coisa do ns acima provavelmente está quebrada
            -- Título inválido: conserva o texto fornecido, produzindo
textPart = 'subst:' .. textPart
            -- posteriormente uma ligação vermelha quando possível.
end
            textPart = firstArg or ''
        end
if _ne(args.brace) then
    end
textPart = nw('{{') .. textPart .. nw('}}')
 
elseif _ne(args.braceinside) then
    if _ne(args.subst) then
textPart = nw('{') .. textPart .. nw('}')
        textPart = 'subst:' .. textPart
end
    end
 
    if _ne(args.brace) then
        textPart = nw('{{') .. textPart .. nw('}}')
    elseif _ne(args.braceinside) then
        textPart = nw('{') .. textPart .. nw('}')
    end
 
    local titlePart
 
    if _ne(args.nolink) then
        titlePart = textPart
    else
        local target
 
        if titleObj ~= nil then
            target = titleObj.fullText
        else
            target = addTemplate(firstArg)
        end
 
        titlePart = '[[' .. target .. '|' .. textPart .. ']]'
    end
 
    if _ne(args.braceinside) then
        titlePart = nw('{') .. titlePart .. nw('}')
    end
 
    local bold =
        _ne(args.bold)
        or _ne(args.boldlink)
        or _ne(args.boldname)
 
    if bold then
        titlePart = "'''" .. titlePart .. "'''"
    end
 
    if _ne(args.nowrapname) then
        titlePart =
            '<span class="nowrap">'
            .. titlePart
            .. '</span>'
    end


local titlePart
    return titlePart
if _ne(args.nolink) then
titlePart = textPart
else
titlePart = '[[' .. (titleObj ~= nil and titleObj.fullText or addTemplate(args['1'])) ..
'|' .. textPart .. ']]'
end
if _ne(args.braceinside) then
titlePart = nw('{') .. titlePart .. nw('}')
end
local bold = _ne(args.bold) or _ne(args.boldlink) or _ne(args.boldname)
if bold then
titlePart = "'''" .. titlePart .. "'''"
end
if _ne(args.nowrapname) then
titlePart = '<span class="nowrap">' .. titlePart .. '</span>'
end
return titlePart
end
end


function p.main(frame)
function p.main(frame)
local args = getArgs(frame, {
    local args = getArgs(frame, {
trim = true,
        trim = true,
removeBlanks = false
        removeBlanks = false
})
    })
return p._main(args)
 
    return p._main(args)
end
end


function p._main(args)
function p._main(args)
local italic = _ne(args.italic) or _ne(args.italics)
    local italic =
local dontBrace = _ne(args.brace) or _ne(args.braceinside)
        _ne(args.italic)
local code = _ne(args.code) or _ne(args.tt)
        or _ne(args.italics)
local show_result = _ne(args._show_result)
 
local expand = _ne(args._expand)
    local dontBrace =
        _ne(args.brace)
local titlePart = linkTitle(args)
        or _ne(args.braceinside)
 
-- Constrói os argumentos
    local code =
local textPart = ""
        _ne(args.code)
local textPartBuffer = "&#124;"
        or _ne(args.tt)
local codeArguments = {}
 
local codeArgumentsString = ""
    local showResult = _ne(args._show_result)
local i = 2
    local expand = _ne(args._expand)
local j = 1
 
while args[i] do
    local firstArg = getPositionalArg(args, 1)
local val = args[i]
    local titlePart = linkTitle(args)
if val ~= "" then
 
if _ne(args.nowiki) then
    -- Constrói os argumentos mostrados.
-- Remove as marcações nowiki primeiro porque chamar nw em algo que já contém marcações nowiki irá
    local textPart = ''
-- desmontar o marcador de faixa nowiki e resultará na exibição literal de UNIQ...QINU
    local textPartBuffer = '&#124;'
val = nw(mw.text.unstripNoWiki(val))
 
end
    -- Argumentos usados por _show_result.
local k, v = string.match(val, "(.*)=(.*)")
    --
if not k then
    -- "j" representa o próximo índice posicional da chamada reconstruída
codeArguments[j] = val
    -- para _show_result. Argumentos ausentes ou vazios são omitidos,
j = j + 1
    -- portanto ele não corresponde necessariamente ao índice recebido
else
    -- por este módulo.
codeArguments[k] = v
    local codeArguments = {}
end
    local j = 1
codeArgumentsString = codeArgumentsString .. textPartBuffer .. val
 
if italic then
    -- Representação em wikitexto usada pelo link para ExpandTemplates.
val = '<span style="font-style:italic;">' .. val .. '</span>'
    -- Os separadores são acrescentados diretamente para não substituir
end
    -- entidades &#124; que façam parte do próprio valor do argumento.
textPart = textPart .. textPartBuffer .. val
    local expandArgumentsString = ''
end
 
i = i + 1
    for _, i in ipairs(getNumericArgIndexes(args)) do
end
        local val = getPositionalArg(args, i)
 
        if val ~= nil and val ~= '' then
            if _ne(args.nowiki) then
                -- Remove primeiro eventuais marcadores internos de <nowiki>.
                -- Aplicar mw.text.nowiki diretamente a uma string que já
                -- contenha strip markers pode expor literalmente UNIQ...QINU.
                val = nw(mw.text.unstripNoWiki(val))
            end
 
            local key, value = splitNamedParameter(val)
 
            if key then
                codeArguments[key] = value
            else
                codeArguments[j] = val
                j = j + 1
            end
 
            -- O itálico é aplicado ao argumento inteiro, inclusive quando
            -- ele representa um parâmetro nomeado (por exemplo, "a=b").
            -- Isso preserva o comportamento histórico da interface.
            local displayedVal = val
            if italic then
                displayedVal =
                    '<span style="font-style:italic;">'
                    .. displayedVal
                    .. '</span>'
            end
 
            expandArgumentsString =
                expandArgumentsString
                .. '|'
                .. val
 
            textPart =
                textPart
                .. textPartBuffer
                .. displayedVal
        end
    end
 
    -- Envoltório final.
    local ret = titlePart .. textPart
 
    if not dontBrace then
        ret = nw('{{') .. ret .. nw('}}')
    end
 
    if _ne(args.a) then
        ret = nw('*') .. '&nbsp;' .. ret
    end
 
    if _ne(args.kbd) then
        ret = '<kbd>' .. ret .. '</kbd>'
    end
 
    if code then
        ret = '<code>' .. ret .. '</code>'
    elseif _ne(args.plaincode) then
        ret =
            '<code style="border:none;background:transparent;color:inherit">'
            .. ret
            .. '</code>'
    end
 
    if _ne(args.nowrap) then
        ret =
            '<span class="nowrap">'
            .. ret
            .. '</span>'
    end
 
    if _ne(args.debug) then
        ret =
            ret
            .. '\n<pre>'
            .. mw.text.encode(mw.dumpObject(args))
            .. '</pre>'
    end
 
    -- Mostra o resultado da predefinição representada.
    --
    -- Chamadas sem nome não são expandidas: elas continuam podendo ser
    -- exibidas para diagnóstico, mas não provocam erro em addTemplate().
    if showResult and _ne(firstArg) then
        if _ne(args.nocat) then
            codeArguments.nocat = true
        end
 
        local result = mw.getCurrentFrame():expandTemplate {
            title = addTemplate(firstArg),
            args = codeArguments
        }
 
        ret = ret .. ' → ' .. result
    end


-- envoltório final
    -- Adiciona ligação para Especial:Expandir predefinições.
local ret = titlePart .. textPart
    if expand and _ne(firstArg) then
if not dontBrace then ret = nw('{{') .. ret .. nw('}}') end
        local query =
if _ne(args.a) then ret = nw('*') .. '&nbsp;' .. ret end
            mw.text.encode(
if _ne(args.kbd) then ret = '<kbd>' .. ret .. '</kbd>' end
                '{{'
if code then
                .. addTemplate(firstArg)
ret = '<code>' .. ret .. '</code>'
                .. expandArgumentsString
elseif _ne(args.plaincode) then
                .. '}}'
ret = '<code style="border:none;background:transparent;color:inherit">' .. ret .. '</code>'
            )
end
if _ne(args.nowrap) then ret = '<span class="nowrap">' .. ret .. '</span>' end
--[[ Embrulhar como 'HTML'?
local span = mw.html.create('span')
span:wikitext(ret)
--]]
if _ne(args.debug) then ret = ret .. '\n<pre>' .. mw.text.encode(mw.dumpObject(args)) .. '</pre>' end


if show_result then
        local url =
if _ne(args.nocat) then codeArguments['nocat'] = true end
            mw.uri.fullUrl(
local result = mw.getCurrentFrame():expandTemplate{title = addTemplate(args[1]), args = codeArguments}
                'special:ExpandTemplates',
ret = ret .. " → " .. result
                'wpInput=' .. query
end
            )


if expand then
        ret =
local query = mw.text.encode('{{' .. addTemplate(args[1]) .. string.gsub(codeArgumentsString, textPartBuffer, "|") .. '}}')
            ret
local url = mw.uri.fullUrl('special:ExpandTemplates', 'wpInput=' .. query)
            .. ' ['
mw.log()
            .. tostring(url)
ret = ret .. " [" .. tostring(url) .. "]"
            .. ']'
end
    end


return ret
    return ret
end
end


return p
return p

Edição atual tal como às 04h59min de 27 de setembro de 2026

-- Implementa a infraestrutura de Predefinição:Tlg e de outras -- predefinições da família de ligações para predefinições. local getArgs = require('Módulo:Arguments').getArgs

local p = {}

-- É uma string que não está vazia? local function _ne(s)

   return s ~= nil and s ~= 

end

local nw = mw.text.nowiki

-- Retorna um argumento posicional independentemente de sua chave ter -- sido armazenada como número ou como representação textual do número. local function getPositionalArg(args, index)

   local value = args[index]
   if value == nil then
       value = args[tostring(index)]
   end
   return value

end

-- Retorna, em ordem, somente os índices posicionais realmente presentes. -- -- Não percorremos de 2 até o maior índice: uma chamada artificial como -- |999999999=x não deve provocar centenas de milhões de iterações. local function getNumericArgIndexes(args)

   local indexes = {}
   local seen = {}
   for key in pairs(args) do
       local index
       if type(key) == 'number' then
           if key >= 2 and key % 1 == 0 then
               index = key
           end
       elseif type(key) == 'string'
           and key:match('^[1-9]%d*$') then
           local n = tonumber(key)
           if n and n >= 2 then
               index = n
           end
       end
       if index and not seen[index] then
           seen[index] = true
           indexes[#indexes + 1] = index
       end
   end
   table.sort(indexes)
   return indexes

end

-- Divide uma representação de parâmetro nomeado no primeiro "=". -- -- Exemplo: -- url=https://example.org/?a=b -- torna-se: -- chave = "url" -- valor = "https://example.org/?a=b" -- -- Uma string que começa por "=" continua sendo tratada como argumento -- posicional, como no comportamento histórico. local function splitNamedParameter(value)

   local pos = value:find('=', 1, true)
   if not pos then
       return nil
   end
   -- Nomes e valores de parâmetros nomeados têm os espaços externos
   -- removidos pelo MediaWiki; reproduzimos esse comportamento aqui.
   local key = mw.text.trim(value:sub(1, pos - 1))
   if key ==  then
       return nil
   end
   local val = mw.text.trim(value:sub(pos + 1))
   return key, val

end

-- Acrescenta o domínio Predefinição: quando o título fornecido não -- possui um domínio reconhecido. local function addTemplate(s)

   if not _ne(s) then
       return 
   end
   local i = s:find(':', 1, true)
   if i == nil then
       return 'Predefinição:' .. s
   end
   local ns = s:sub(1, i - 1)
   if ns ==  or mw.site.namespaces[ns] then
       return s
   end
   return 'Predefinição:' .. s

end

-- Constrói a parte correspondente ao nome e à ligação. local function linkTitle(args)

   local firstArg = getPositionalArg(args, 1)
   local titleObj
   if _ne(firstArg) then
       -- Isso lida com :Página e outros domínios.
       titleObj = mw.title.new(firstArg, 'Predefinição')
   else
       titleObj = mw.title.getCurrentTitle()
   end
   local textPart = args.alttext
   if not _ne(textPart) then
       if titleObj ~= nil then
           -- 10 é o identificador numérico do domínio Predefinição.
           if titleObj:inNamespace(10) and _ne(firstArg) then
               textPart = firstArg
           else
               textPart = titleObj.fullText
           end
       else
           -- Título inválido: conserva o texto fornecido, produzindo
           -- posteriormente uma ligação vermelha quando possível.
           textPart = firstArg or 
       end
   end
   if _ne(args.subst) then
       textPart = 'subst:' .. textPart
   end
   if _ne(args.brace) then
       textPart = nw('Predefinição:') .. textPart .. nw('')
   elseif _ne(args.braceinside) then
       textPart = nw('{') .. textPart .. nw('}')
   end
   local titlePart
   if _ne(args.nolink) then
       titlePart = textPart
   else
       local target
       if titleObj ~= nil then
           target = titleObj.fullText
       else
           target = addTemplate(firstArg)
       end
       titlePart = '' .. textPart .. ''
   end
   if _ne(args.braceinside) then
       titlePart = nw('{') .. titlePart .. nw('}')
   end
   local bold =
       _ne(args.bold)
       or _ne(args.boldlink)
       or _ne(args.boldname)
   if bold then
       titlePart = "" .. titlePart .. ""
   end
   if _ne(args.nowrapname) then
       titlePart =
           ''
           .. titlePart
           .. ''
   end
   return titlePart

end

function p.main(frame)

   local args = getArgs(frame, {
       trim = true,
       removeBlanks = false
   })
   return p._main(args)

end

function p._main(args)

   local italic =
       _ne(args.italic)
       or _ne(args.italics)
   local dontBrace =
       _ne(args.brace)
       or _ne(args.braceinside)
   local code =
       _ne(args.code)
       or _ne(args.tt)
   local showResult = _ne(args._show_result)
   local expand = _ne(args._expand)
   local firstArg = getPositionalArg(args, 1)
   local titlePart = linkTitle(args)
   -- Constrói os argumentos mostrados.
   local textPart = 
   local textPartBuffer = '|'
   -- Argumentos usados por _show_result.
   --
   -- "j" representa o próximo índice posicional da chamada reconstruída
   -- para _show_result. Argumentos ausentes ou vazios são omitidos,
   -- portanto ele não corresponde necessariamente ao índice recebido
   -- por este módulo.
   local codeArguments = {}
   local j = 1
   -- Representação em wikitexto usada pelo link para ExpandTemplates.
   -- Os separadores são acrescentados diretamente para não substituir
   -- entidades | que façam parte do próprio valor do argumento.
   local expandArgumentsString = 
   for _, i in ipairs(getNumericArgIndexes(args)) do
       local val = getPositionalArg(args, i)
       if val ~= nil and val ~=  then
           if _ne(args.nowiki) then
               -- Remove primeiro eventuais marcadores internos de <nowiki>.
               -- Aplicar mw.text.nowiki diretamente a uma string que já
               -- contenha strip markers pode expor literalmente UNIQ...QINU.
               val = nw(mw.text.unstripNoWiki(val))
           end
           local key, value = splitNamedParameter(val)
           if key then
               codeArguments[key] = value
           else
               codeArguments[j] = val
               j = j + 1
           end
           -- O itálico é aplicado ao argumento inteiro, inclusive quando
           -- ele representa um parâmetro nomeado (por exemplo, "a=b").
           -- Isso preserva o comportamento histórico da interface.
           local displayedVal = val
           if italic then
               displayedVal =
                   ''
                   .. displayedVal
                   .. ''
           end
           expandArgumentsString =
               expandArgumentsString
               .. '|'
               .. val
           textPart =
               textPart
               .. textPartBuffer
               .. displayedVal
       end
   end
   -- Envoltório final.
   local ret = titlePart .. textPart
   if not dontBrace then
       ret = nw('Predefinição:') .. ret .. nw('')
   end
   if _ne(args.a) then
       ret = nw('*') .. ' ' .. ret
   end
   if _ne(args.kbd) then
       ret = '' .. ret .. ''
   end
   if code then
       ret = '' .. ret .. ''
   elseif _ne(args.plaincode) then
       ret =
           ''
           .. ret
           .. ''
   end
   if _ne(args.nowrap) then
       ret =
           ''
           .. ret
           .. ''
   end
   if _ne(args.debug) then
       ret =
           ret

.. '\n

'
            .. mw.text.encode(mw.dumpObject(args))
            .. '

'

   end
   -- Mostra o resultado da predefinição representada.
   --
   -- Chamadas sem nome não são expandidas: elas continuam podendo ser
   -- exibidas para diagnóstico, mas não provocam erro em addTemplate().
   if showResult and _ne(firstArg) then
       if _ne(args.nocat) then
           codeArguments.nocat = true
       end
       local result = mw.getCurrentFrame():expandTemplate {
           title = addTemplate(firstArg),
           args = codeArguments
       }
       ret = ret .. ' → ' .. result
   end
   -- Adiciona ligação para Especial:Expandir predefinições.
   if expand and _ne(firstArg) then
       local query =
           mw.text.encode(
               '{{'
               .. addTemplate(firstArg)
               .. expandArgumentsString
               .. '}}'
           )
       local url =
           mw.uri.fullUrl(
               'special:ExpandTemplates',
               'wpInput=' .. query
           )
       ret =
           ret
           .. ' ['
           .. tostring(url)
           .. ']'
   end
   return ret

end

return p