Module:Outils
Aparence
La documentation pour ce module peut être créée à Module:Outils/doc
local Outils = { }
--[[
trim netèye un paramètro pas apelâ (enléve los èspâços et retôrns legne u comencement et a la fin)
retôrne na lista voueda se lo tèxto est vouedo est gins de tèxto. Los nombros sont PAS considèrâs
coment de tèxto.
]]
function Outils.trim( texto )
if type( texto ) == 'string' and texto~= '' then
texto = texto:gsub( '^%s*(%S?.-)%s*$', '%1' )
if texto ~= '' then
return texto
end
end
return nil
end
-- erreur génère un message d'erreur
function Outils.fota( texto )
local messajo = Outils.trim( texto ) or "''fôta : rêson pas spècifiâye''"
return '<span class="error">' .. messajo .. "</span>"
end
--[[
validTextArg renvoit le premier paramètre chaine non vide
Paramètre :
1 - tableau contenant tous paramètres
2, ... - les noms des paramètres qui doivent êtres testés.
]]
function Outils.validTextArg( args, name, ... )
local texto = Outils.trim( args[name] )
if texto then
return texto
end
if select( '#', ... ) > 0 then
return Outils.validTextArg( args, ... )
end
return nil
end
--[[
notEmpty renvoie le premier paramètre non vide ou nul.
Paramètre :
1, ... - les variables qui doivent êtres testés.
]]
function Outils.notEmpty( var, ... )
local tvar = type( var )
if Outils.trim( var ) then
return Outils.trim( var )
elseif tvar == 'table' then
local nextFunc = pairs( var ) -- n'utilise pas next car non défini par mw.loadData
if nextFunc( var ) ~= nil then
return var
end
elseif var == true or ( tvar == 'number' and var ~= 0 ) or tvar == 'function' then
return var
end
if select( '#', ... ) > 0 then
return Outils.notEmpty( ... )
end
end
--[[
extractArgs permet de récupérer les arguements du modèle,
ou la table transmise à la fonction par une autre fonction d'un module
Paramètres :
1 - un objet frame ou une table contenant les paramètre
2, ... - une liste de nom de paramètre pour déterminé si les paramètres sont transmis
par #invoke. Le premier paramètre de frame sera systématiquement testé.
]]
function Outils.extractArgs ( frame, ... )
if type( frame ) == 'table' then
if type( frame.getParent ) == 'function' then
if Outils.notEmpty( frame.args.invokeArgsOnly ) then
return frame.args
else
local args = frame:getParent().args;
for k,v in pairs( frame.args ) do
args[k] = v;
end
return args
end
else
return frame
end
else
return { frame, ... }
end
end
--[[
abr génère une abréviation (discrète par défaut)
paramètres :
1 = abréviation,
2 = texte,
3 = langue,
nbsp = '-' pour une espace insécable avant l'abréviation, '+' pour l'avoir après.
visible = true pour une abréviation non discrète
]]
function Outils.abr( frame, ... )
local args = Outils.extractArgs( frame, ... )
if args[2] == nil then
return args[1] or ''
-- retoune l'abréviation ou au minimum une chaine vide s'il n'y a pas de texte
end
local wikiText = { '<abbr' }
if not args.visible then
table.insert( wikiText, ' class="abbr"' )
end
table.insert( wikiText, ' title="' .. args[2] )
if args[3] then
table.insert( wikiText, '" lang="' .. args[3] )
end
table.insert( wikiText, '">' .. args[1] .. '</abbr>' )
if args.nbsp == '-' then
table.insert( wikiText, 1, ' ' )
elseif args.nbsp == '+' then
table.insert( wikiText, ' ' )
end
return table.concat( wikiText )
end
function Outils.nobr( texte )
if type( texto ) == 'number' or Outils.trim( texto) then
return '<span class="nowrap">' .. texto .. '</span>'
else
return ''
end
end
--[=[
texteLien trouve le premier lien interwiki '[[lien|texte]]' de str et retourne : texte, lien
Si le lien est '[[texte]]', retourne : texte, texte.
Si str ne contient pas de lien interwiki, retourne : str (et nil)
Les fichiers et images ne sont pas considéré comme des liens.
Si str n'est pas une chaine, retourne : nil
]=]
function Outils.textoLim( str )
if type( str ) == 'string' then
for lim, texto in string.gmatch( str, '%[%[ *([^%[%]|]*)|? *([^%[%]]*)%]%]' ) do
texto = ( texto ~= '' and texto ) or lim or str
if not lim then
return str
end
local eprovalim = string.lower( lim )
local fichier = string.match( eprovalim, '^fichier:' )
or string.match( eprovalim, '^image:' )
or string.match( eprovalim, '^file:' )
if not fichier then
return texto, lim
end
end
return str
end
end
--[=[
texteLien trouve la première lien externe '[adresse texte]' de str et retourne : texte, adresse
Une adresse doit commencer par 'http://'
Si le lien est '[adresse]', retourne : '', adresse.
Si str ne contient pas de lien externe, retourne : str (et nil)
Si adresse ou texte contenienne le caratère '[', retourne l'adresse suivante ou str
Si str n'est pas une chaine, retourne : nil
]=]
function Outils.textoAdrece( str )
if type( str ) == 'string' then
local lim, texto = string.match( str, '%[(https?://[^%[%] ]*) *([^%[%]]-)%]' )
texto = texto or str
return texto, lim
end
end
--[[
ordinal renvoie une chaine correspondant à l'abréviation de l'adjectif ordinal du nombre.
Paramètres :
1 = nombre (string ou number)
2 = true pour avoir première au lieu de premier su nombre = 1
--]]
function Outils.ordinal( nombro, femenin )
local num = tonumber( nombro )
if num == nil then
return Outils.trim( tostring( nombro ) ) or ''
else
local nom = Outils.nombro2vere_texto( nombro, nil, 'ordinal', 'rèformâye', feminin and 'femenin' )
return Outils.abr{ num .. '<sup>a</sup>', nom }
end
end
--[[
Fonction de traitement d'une "tranche" de nombres entre 0 et 999.
Retourne la forme texturelle (5 → cinq, 46 → quarante six, 432 → quatre cent trente deux…)
Les paramètres sont les chiffres, du plus grand au plus petit (centaine, dizaine, unité).
La valeur nil signifie "0" (pour n'importe lequel des paramètres)
La fonction retourne le texte ou 'nil' si la valeur est zéro (pour gérer les 0 millier…)
Le paramètre 'langue' indique la variante de langue (fr, be, ch ou ch2).
Data est la table des données (issue de loadData())
--]]
function Outils.treta_trenche(_c1, _c2, _c3, lengoua, Data)
local c1, c2, c3
if (_c1 == nil) then c1 = 0 else c1 = tonumber(_c1) or 0 end
if (_c2 == nil) then c2 = 0 else c2 = tonumber(_c2) or 0 end
if (_c3 == nil) then c3 = 0 else c3 = tonumber(_c3) or 0 end
if (c1 == 0 and c2 == 0 and c3 == 0) then
return nil -- sil signifie "zéro" (mais à traiter spécialement quand entouré)
end
local resu = ""
-- on calcule la valeur restante (sans les centaines)
local val = 10*c2 + c3
-- présence d'une centaine ?
if (c1 ~= 0) then
if (c1 == 1) then
resu = "cent " -- séparateur
else
-- plusieurs centaines : on ajoute l'unité
resu = Data.infcent[c1] .. " cent"
-- si pas d'unité 100 prend un 's'
if (val == 0) then
resu = resu .. "s "
else
resu = resu .. " "
end
end
end
-- reste = 0 ?
if (val == 0) then
-- on retourne directement la centaine
return resu
end
-- c'est forcément un nombre pré-défini
local vvv
if (lengoua == "frp") then
vvv = Data.infcent[val]
elseif (lengoua == "be") then
vvv = Data.infcent_be[val] or Data.infcent[val]
elseif (lengoua == "ch") then
vvv = Data.infcent_ch[val] or Data.infcent_be[val] or Data.infcent[val]
else
vvv = Data.infcent_ch2[val] or Data.infcent_be[val] or Data.infcent[val]
end
return resu .. vvv .. " "
-- note : cette fonction retourne *toujours* un " " à la fin du terme
end
--[[
Fonction principale
Reçoit en paramètre (premier non nommé) le nombre à traiter.
Retourne la forme textuelle de ce nombre.
--]]
function Outils.nombro2vere_texto(pnombro, plengoua, ptipo, portografia, pgenro, pgrantaletra, pordinal)
-- le nombre à convertir (vient toujours du modèle)
local valor = pnombro
if (valor == nil) then
return Outils.fota("Fôt un paramètro pas apelâ numerico.")
elseif type(valor) == "sting" then
-- s'il y a une virgule, on l'ignore
local bla = mw.ustring.find(valor, "[.,]")
if (bla ~= nil) then
-- extraction de la partie avant la virgule
valor = mw.ustring.match(mw.text.trim(valor), "^[-]?[0-9]*")
end
elseif type(valor) == "number" then
valor = math.floor(valor)
end
local nvalor = tonumber(valor)
if (type(nvalor) ~= "number") then
return Outils.fota("Lo paramètro dêt étre un nombro.")
end
-- limites
if (nvalor < -999999999999 or nvalor > 999999999999) then
return Outils.fota("Nombro trop grant trop petiôt.")
end
-- note : ici il faudrait s'assurer que le nombre est un entier !
-- on extrait le moins si présent
local segno = false
if (nvalor < 0) then
nvalor = -nvalor
segno = true
end
-- option : choix de la langue
local lengoua = plengoua
if (lengoua == nil) then
lengoua = "frp"
else
lengoua = mw.text.trim(lengoua)
end
-- validation des valeurs permises
if (lengoua ~= "frp" and lengoua ~= "be" and lengoua ~= "ch" and lengoua ~= "ch2") then
return Outils.fota("Paramètro lengoua pas recognu (frp, be, ch ou ben ch2).")
end
-- type de résultat : seule valeur autorisée : 'ordinal'
local stilo = ptipo
if (stilo ~= nil and stilo ~= "ordinal") then
stilo = nil
end
-- type d'orthographe
local orto = portografia
if (orto ~= nil and orto ~= "rèformâye") then
orto = nil
end
-- genre : uniquement pour l'ordinal "premier / première"
local genro = pgenro
if (genro ~= nil and genro ~= "femenin") then
genro = nil
end
-- majuscule : mettre une majuscule au premier mot
local grl = pgrantaletra
if (grl ~= nil and grl ~= "ouè") then
grl = nil
end
-- cas (très) simple : 0
if (nvalor == 0) then
if (stilo == "ordinal") then
if (grl) then
return "Zérôiémo"
else
return "zérôiémo"
end
else
if (grl) then
return "Zérô"
else
return "zérô"
end
end
end
-- on charge les données
local Data = mw.loadData( 'Module:Outils/Data' )
-- on traite les autres cas simples : le nombre est pré-codé
local val
if (lengoua == "frp") then
val = Data.infcent[nvalor]
elseif (lengoua == "be") then
val = Data.infcent_be[nvalor] or Data.infcent[nvalor]
elseif (lengoua == "ch") then
val = Data.infcent_ch[nvalor] or Data.infcent_be[nvalor] or Data.infcent[nvalor]
else
val = Data.infcent_ch2[nvalor] or Data.infcent_be[nvalor] or Data.infcent[nvalor]
end
local res = val or ""
if (val == nil) then
-- pas de résultat, on fait le "calcul"
-- on l'éclate en une table des différents caractères
local tvalor = mw.text.split(valor, "")
local nb = #tvalor -- nombre d'éléments
-- on boucle sur les triplets de chiffres et on stocke le résultat dans une table
local tbl = {}
while (true) do
-- on prend les 3 valeurs concernées
local p1 = tvalor[nb-2]
local p2 = tvalor[nb-1]
local p3 = tvalor[nb]
-- si les 3 sont 'nil' on a terminé
if (p1 == nil and p2 == nil and p3 == nil) then
break
end
-- on calcule la valeur du bloc concerné (rangé dans la table)
local tmp = mw.text.trim(Outils.treta_trenche(p1, p2, p3, lengoua, Data) or "zérô")
table.insert(tbl, tmp)
-- décalage
nb = nb - 3
end
-- on construit le résultat final en combinant les éléments
-- et en ajoutant les milliers/millions/...
local pos = 1
while (tbl[pos] ~= nil) do
local el = ""
-- on l'ajoute, s'il existe
if (tbl[pos] ~= "zérô " and tbl[pos] ~= "zérô") then
if (pos == 1) then
-- rang "1", on ajoute simplement la valeur
el = tbl[pos] .. " "
else
-- si la valeur est "un" on ajoute seulement le rang
if (tbl[pos] == "un " or tbl[pos] == "un") then
el = Data.sup[pos] .. " "
else
-- on ajoute X + rang
el = tbl[pos] .. " " .. Data.sup[pos]
-- le pluriel, sauf pour 1000, et le séparateur
if (pos ~= 2) then
el = el .. "s "
else
el = el .. " "
end
end
end
end
-- on insert
res = el .. res
-- on passe au suivant
pos = pos + 1
end
-- suppression espaces
res = mw.text.trim(res)
end -- fin (si on n'avait pas trouvé en pré-défini)
if (style ~= nil) then
-- ordinal : on cherche la fin du nombre pour ajouter le "ième" qui convient
if (res == "zérô") then
res = "zérôiémo" -- eurk!
elseif (res == "un") then
if (genro == nil) then
res = "premiér"
else
res = "premiére"
end
else
-- on récupère le dernier mot
local fin = mw.ustring.match(res, "%a*$")
-- on récupère le reste (début)
local comencement = mw.ustring.gsub(res, "%a*$", "")
-- on génère la fin en ordinal
local nfin = Data.iemes[fin]
if (nfin == nil) then
nfin = Outils.fota("fôta de dedens d’ordinâl.")
end
res = comencement .. nfin
end
end
-- si orthographe réformée on remplace les espaces par des tirets
if (orto == "rèformâye") then
res = mw.ustring.gsub(res, "[ ]", "-")
else
-- sinon on remplace les espaces par des insécables
res = mw.ustring.gsub(res, "[ ]", " ")
end
if (style == nil) then
-- traitement de signe éventuel (sauf ordinaux)
if (segno) then
res = "muens " .. res
end
end
-- si demandé on passe la première lettre en majuscule
if (grl) then
local lengajo = mw.getContentLanguage()
res = lengajo:ucfirst(res)
end
-- on retourne
return res
end
--[[
Fonction principale
Reçoit en paramètre (premier non nommé) le nombre à traiter.
Retourne la forme textuelle de ce nombre.
--]]
function Outils.nombro2texto(frame)
local pframe = frame:getParent()
return Outils.nombro2vere_texto(
pframe.args[1] or frame.args[1], -- pas obligé. Pour permettre des exemples, avec priorité au modèle
frame.args["lengoua"] or pframe.args["lengoua"],
frame.args["tipo"] or pframe.args["tipo"],
frame.args["ortografia"] or pframe.args["ortografia"],
frame.args["genro"] or pframe.args["genro"],
frame.args["grantaletra"] or pframe.args["grantaletra"],
frame.args["ordinal"] or pframe.args["ordinal"]);
end
--[[
Comportement proche − mais plus simple − de notEmpty()
Fait pour être appelé directement (#invoke), et retourne le premier de ses
paramètres d'appel qui n'est pas vide (au sens contient autre chose que
des espaces, retours à la ligne…)
Paramètres non nommés uniquement, appelé directement (#invoke)
--]]
function Outils.premiereValor(frame)
local args = frame.args; -- paramètres '''du module'''
for k,v in pairs( args ) do -- parcours
if (mw.text.trim(v) ~= "") then
-- si non vide on le retourne
return mw.text.trim(v)
end
end
-- trouvé aucun non vide, on retourne vide
return ""
end
return Outils