Módulo:Ligação para predefinição
-- 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