Aller au contenu

« Module:Delink » : différence entre les versions

De Wreck
Modèle:Élision>Vriullop
 
m 1 version importée
 
(17 versions intermédiaires par 5 utilisateurs non affichées)
Ligne 1 : Ligne 1 :
-- This module de-links most wikitext.
-- This module de-links most wikitext.


p = {}
local p = {}


local function delinkReversePipeTrick(s)
local function delinkReversePipeTrick(s)
     if mw.ustring.match(s, "^%[%[|.*[|\n]") then -- Check for newlines or multiple pipes.
     if s:find('^%[%[|.*[|\n]') or s == '[[|]]' then -- Check for newlines or multiple pipes.
         return s
         return s
     else
     else
         return mw.ustring.match(s, "%[%[|(.*)%]%]")
         return s:match('%[%[|(.*)%]%]')
     end
     end
end
end


local function delinkPipeTrick(s)
local function delinkPipeTrick(s)
     local linkarea, display = "", ""
     -- s the tile area, without bracket nor pipe
     -- We need to deal with colons, brackets, and commas, per [[Help:Pipe trick]].
     -- We need to deal with colons, brackets, and commas, per [[Help:Pipe trick]].
   
 
     -- First, remove the text before the first colon, if any.
     -- First, remove the text before the first colon, if any.
     if mw.ustring.match(s, ":") then
     s = s:gsub('^(.-:)', '')
        s = mw.ustring.match(s, "%[%[.-:(.*)|%]%]")
 
    -- If there are no colons, grab all of the text apart from the square brackets and the pipe.
    else
        s = mw.ustring.match(s, "%[%[(.*)|%]%]")
    end
   
     -- Next up, brackets and commas.
     -- Next up, brackets and commas.
     if mw.ustring.match(s, "%(.-%)$") then -- Brackets trump commas.
     if s:find('%(.-%)$') then -- Brackets trump commas.
         s = mw.ustring.match(s, "(.-) ?%(.-%)$")
         s = s:match('(.-) ?%(.-%)$')
     elseif mw.ustring.match(s, ",") then -- If there are no brackets, display only the text before the first comma.
     elseif s:find(',') then -- If there are no brackets, display only the text before the first comma.
         s = mw.ustring.match(s, "(.-),.*$")
         s = s:match('(.-),.*$')
     end
     end
     return s
     return s
Ligne 33 : Ligne 28 :


local function delinkWikilink(s)
local function delinkWikilink(s)
     local result = s
    -- s is a string starting with '[[' and ending with ']]'. It does not contain any other ']]' strings.
 
    -- Deal with nested links
     local nested = '[[' .. s:sub(3):gsub('%[%[.-%]%]$', delinkWikilink)
    if nested ~= s then
        return nested
    end
 
     -- Deal with the reverse pipe trick.
     -- Deal with the reverse pipe trick.
     if mw.ustring.match(result, "%[%[|") then
     if s:find('^%[%[|') then
         return delinkReversePipeTrick(result)
         return delinkReversePipeTrick(s)
     end
     end
   
 
    result = mw.uri.decode(result, "PATH") -- decode percent-encoded entities. Leave underscores and plus signs.
    result = mw.text.decode(result, true) -- decode HTML entities.
   
     -- Check for bad titles. To do this we need to find the
     -- Check for bad titles. To do this we need to find the
     -- title area of the link, i.e. the part before any pipes.
     -- title area of the link, i.e. the part before any pipes.
     local titlearea
     local titlearea, display = s:match('^%[%[(.-)|(.*)%]%]$')
    if mw.ustring.match(result, "|") then -- Find if we're dealing with a piped link.
     titlearea = titlearea or s:sub(3, -3)
        titlearea = mw.ustring.match(result, "^%[%[(.-)|.*%]%]")
 
     else
    titlearea = mw.uri.decode(titlearea, 'PATH') -- decode percent-encoded entities. Leave underscores and plus signs.
        titlearea = mw.ustring.match(result, "^%[%[(.-)%]%]")
    titlearea = mw.text.decode(titlearea, true) -- decode HTML entities.
     end
 
    local temptitlearea, fragment = titlearea:match('^(.-)#(.*)$')
     temptitlearea = temptitlearea or titlearea
    fragment = fragment or ''
 
     -- Check for bad characters.
     -- Check for bad characters.
     if mw.ustring.match(titlearea, "[%[%]<>{}%%%c\n]") then
     if not mw.ustring.isutf8(titlearea)
        or temptitlearea:find('[%[%]<>|{}%z%c\n]')
        or temptitlearea:find('%%%x%x')
        or temptitlearea:find('&..-;')
        or fragment:find('[%[%]{}%c\n]')
    then
         return s
         return s
     end
     end
   
 
 
     -- Check for categories, interwikis, and files.
     -- Check for categories, interwikis, and files.
     local colonprefix = mw.ustring.match(result, "%[%[(.-):.*%]%]") or "" -- Get the text before the first colon.
     local colonprefix = titlearea:match('^(.-):') or '' -- Get the text before the first colon.
    local ns = mw.site.namespaces[colonprefix] -- see if this is a known namespace
     if mw.language.isKnownLanguageTag(colonprefix)
     if mw.language.isKnownLanguageTag(colonprefix)
    or mw.ustring.match(colonprefix, "^[Cc]ategory$")
        or ns and (ns.id == 6 or ns.id == 14)
    or mw.ustring.match(colonprefix, "^[Ff]ile$")
     then
     or mw.ustring.match(colonprefix, "^[Ii]mage$") then
         return ''
         return ""
     end
     end
   
 
     -- Remove the colon if the link is using the [[Help:Colon trick]].
     -- Remove the colon if the link is using the [[Help:Colon trick]].
     if mw.ustring.match(result, "%[%[:") then
     if titlearea:sub(1, 1) == ':' then
         result = "[[" .. mw.ustring.match(result, "%[%[:(.*%]%])")
         titlearea = titlearea:sub(2)
     end
     end
   
 
     -- Deal with links using the [[Help:Pipe trick]].
     -- Deal with links using the [[Help:Pipe trick]].
     if mw.ustring.match(result, "^%[%[[^|]*|%]%]") then
     if display == '' then
         return delinkPipeTrick(result)
         return delinkPipeTrick(titlearea)
     end
     end
   
 
     -- Find the display area of the wikilink
     -- Find the display area of the wikilink
     if mw.ustring.match(result, "|") then -- Find if we're dealing with a piped link.
     if not display then -- Find if we're dealing with a piped link.
        result = mw.ustring.match(result, "^%[%[.-|(.+)%]%]")
         -- Remove new lines from the display of multiline piped links,
         -- Remove new lines from the display of multiline piped links,
         -- where the pipe is before the first new line.
         -- where the pipe is before the first new line.
         result = mw.ustring.gsub(result, "\n", "")
         titlearea = titlearea:gsub('\n', '')
    else
        result = mw.ustring.match(result, "^%[%[(.-)%]%]")
     end
     end


     return result
     return display or titlearea
end
end


Ligne 90 : Ligne 96 :
     -- Assume we have already delinked internal wikilinks, and that
     -- Assume we have already delinked internal wikilinks, and that
     -- we have been passed some text between two square brackets [foo].
     -- we have been passed some text between two square brackets [foo].
   
 
     -- If the text contains a line break it is not formatted as a URL, regardless of other content.
     -- If the text contains a line break it is not formatted as a URL, regardless of other content.
     if mw.ustring.match(s, "\n") then
     if s:find('\n') then
         return s
         return s
     end
     end
   
 
     -- Check if the text has a valid URL prefix and at least one valid URL character.
     -- Check if the text has a valid URL prefix and at least one valid URL character.
     local valid_url_prefixes = {"//", "http://", "https://", "ftp://", "gopher://", "mailto:", "news:", "irc://"}  
     local valid_url_prefixes = {'//', 'http://', 'https://', 'ftp://', 'gopher://', 'mailto:', 'news:', 'irc://'}
     local url_prefix
     local url_prefix
     for i,v in ipairs(valid_url_prefixes) do
     for i,v in ipairs(valid_url_prefixes) do
         if mw.ustring.match(s, '^%[' .. v ..'[^"%s].*%]' ) then
         if s:find( '^%[' .. v ..'[^"%s].*%]' ) then
             url_prefix = v
             url_prefix = v
             break
             break
         end
         end
     end
     end
   
 
     -- Get display text
     -- Get display text
     if not url_prefix then
     if not url_prefix then
         return s
        -- Deal with nested links or send back original string.
         return "[" .. mw.ustring.gsub( mw.ustring.sub(s, 2), "%[.-%]", delinkURL )
     end
     end
     s = mw.ustring.match(s, "^%[" .. url_prefix .. "(.*)%]") -- Grab all of the text after the URL prefix and before the final square bracket.
     s = s:match('^%[' .. url_prefix .. '(.*)%]') -- Grab all of the text after the URL prefix and before the final square bracket.
     s = mw.ustring.match(s, '^.-(["<> ].*)') or "" -- Grab all of the text after the first URL separator character ("<> ).
     s = s:match('^.-(["<> [].*)') or '' -- Grab all of the text after the first URL separator character ("<> ).
     s = mw.ustring.match(s, "^%s*(%S.*)$") or "" -- If the separating character was a space, trim it off.
     s = s:match('^%s*(%S.*)$') or '' -- If the separating character was a space, trim it off.
   
 
     s_decoded = mw.text.decode(s, true)
     local s_decoded = mw.text.decode(s, true)
     if mw.ustring.match(s_decoded, "%c") then
     if s_decoded:find('%c') then
         return s
         return s
     else  
     else
         return s_decoded
         return s_decoded
     end
     end
end
end


local function delinkLinkClass(s, pattern, delinkFunction)
    if not type(s) == "string" then
        error("Attempt to de-link non-string input.", 2)
    end
    if not ( type(pattern) == "string" and mw.ustring.sub(pattern, 1, 1) == "^" ) then
        error('Invalid pattern detected. Patterns must begin with "^".', 2)
    end
    -- Iterate over the text string, and replace any matched text. using the
    -- delink function. We need to iterate character by character rather
    -- than just use gsub, otherwise nested links aren't detected properly.
    local result = ""
    while mw.ustring.len(s) > 0 do
        -- Replace text using one iteration of gsub.
        s = mw.ustring.gsub(s, pattern, delinkFunction, 1)
        -- Append the left-most character to the result string.
        result = result .. mw.ustring.sub(s, 1, 1)
        s = mw.ustring.sub(s, 2, -1)
    end
    return result
end


local function _delink(args)
function p._delink(args)
     local text = args[1] or ""
     local text = args[1] or ''
     if args.refs == "yes" then
     if args.refs == 'yes' then
         -- Remove any [[Help:Strip markers]] representing ref tags. In most situations  
         -- Remove any [[Help:Strip markers]] representing ref tags. In most situations
         -- this is not a good idea - only use it if you know what you are doing!
         -- this is not a good idea - only use it if you know what you are doing!
         text = mw.ustring.gsub(text, "UNIQ%w*%-ref%-%d*%-QINU", "")
         text = mw.text.unstrip(text)
     end
     end
     if not (args.comments == "no") then
     if not (args.comments == 'no') then
         text = mw.ustring.gsub(text, "<!%-%-.-%-%->", "") -- Remove html comments.
         text = text:gsub('<!%-%-.-%-%->', '') -- Remove html comments.
     end
     end
     if not (args.wikilinks == "no") then
     if not (args.wikilinks == 'no') then
         text = delinkLinkClass(text, "^%[%[.-%]%]", delinkWikilink) -- De-link wikilinks.
         text = text:gsub('%[%[.-%]%]', delinkWikilink) -- De-link wikilinks.
     end
     end
     if not (args.urls == "no") then
     if not (args.urls == 'no') then
         text = delinkLinkClass(text, "^%[.-%]", delinkURL) -- De-link URLs.
         text = text:gsub('%[.-%]', delinkURL) -- De-link URLs.
     end
     end
     if not (args.whitespace == "no") then
     if not (args.whitespace == 'no') then
         -- Replace single new lines with a single space, but leave double new lines
         -- Replace single new lines with a single space, but leave double new lines
         -- and new lines only containing spaces or tabs before a second new line.
         -- and new lines only containing spaces or tabs before a second new line.
         text = mw.ustring.gsub(text, "([^\n \t][ \t]*)\n([ \t]*[^\n \t])", "%1 %2")
         text = text:gsub('([^\n \t])[ \t]*\n\t*([^\n \t])', '%1 %2')
         text = mw.ustring.gsub(text, "[ \t]+", " ") -- Remove extra tabs and spaces.
         text = text:gsub('\n\t+', '\n') -- Remove leading tab.
        text = text:gsub('[ \t]+', ' ') -- Remove extra tabs and spaces.
    end
    if not (args.nowiki == 'no') then
        text = mw.text.unstripNoWiki(text)
     end
     end
     return text
     return text
Ligne 183 : Ligne 174 :
         args = frame
         args = frame
     end
     end
     return _delink(args)
     return p._delink(args)
end
end


return p
return p

Dernière version du 24 février 2026 à 02:14

La documentation pour ce module peut être créée à Module:Delink/doc

-- This module de-links most wikitext.

local p = {}

local function delinkReversePipeTrick(s)
    if s:find('^%[%[|.*[|\n]') or s == '[[|]]' then -- Check for newlines or multiple pipes.
        return s
    else
        return s:match('%[%[|(.*)%]%]')
    end
end

local function delinkPipeTrick(s)
    -- s the tile area, without bracket nor pipe
    -- We need to deal with colons, brackets, and commas, per [[Help:Pipe trick]].

    -- First, remove the text before the first colon, if any.
    s = s:gsub('^(.-:)', '')

    -- Next up, brackets and commas.
    if s:find('%(.-%)$') then -- Brackets trump commas.
        s = s:match('(.-) ?%(.-%)$')
    elseif s:find(',') then -- If there are no brackets, display only the text before the first comma.
        s = s:match('(.-),.*$')
    end
    return s
end

local function delinkWikilink(s)
    -- s is a string starting with '[[' and ending with ']]'. It does not contain any other ']]' strings.

    -- Deal with nested links
    local nested = '[[' .. s:sub(3):gsub('%[%[.-%]%]$', delinkWikilink)
    if nested ~= s then
        return nested
    end

    -- Deal with the reverse pipe trick.
    if s:find('^%[%[|') then
        return delinkReversePipeTrick(s)
    end

    -- Check for bad titles. To do this we need to find the
    -- title area of the link, i.e. the part before any pipes.
    local titlearea, display = s:match('^%[%[(.-)|(.*)%]%]$')
    titlearea = titlearea or s:sub(3, -3)

    titlearea = mw.uri.decode(titlearea, 'PATH') -- decode percent-encoded entities. Leave underscores and plus signs.
    titlearea = mw.text.decode(titlearea, true) -- decode HTML entities.

    local temptitlearea, fragment = titlearea:match('^(.-)#(.*)$')
    temptitlearea = temptitlearea or titlearea
    fragment = fragment or ''

    -- Check for bad characters.
    if not mw.ustring.isutf8(titlearea)
        or temptitlearea:find('[%[%]<>|{}%z%c\n]')
        or temptitlearea:find('%%%x%x')
        or temptitlearea:find('&..-;')
        or fragment:find('[%[%]{}%c\n]')
    then
        return s
    end


    -- Check for categories, interwikis, and files.
    local colonprefix = titlearea:match('^(.-):') or '' -- Get the text before the first colon.
    local ns = mw.site.namespaces[colonprefix] -- see if this is a known namespace
    if mw.language.isKnownLanguageTag(colonprefix)
        or ns and (ns.id == 6 or ns.id == 14)
    then
        return ''
    end

    -- Remove the colon if the link is using the [[Help:Colon trick]].
    if titlearea:sub(1, 1) == ':' then
        titlearea = titlearea:sub(2)
    end

    -- Deal with links using the [[Help:Pipe trick]].
    if display == '' then
        return delinkPipeTrick(titlearea)
    end

    -- Find the display area of the wikilink
    if not display then -- Find if we're dealing with a piped link.
        -- Remove new lines from the display of multiline piped links,
        -- where the pipe is before the first new line.
        titlearea = titlearea:gsub('\n', '')
    end

    return display or titlearea
end

local function delinkURL(s)
    -- Assume we have already delinked internal wikilinks, and that
    -- we have been passed some text between two square brackets [foo].

    -- If the text contains a line break it is not formatted as a URL, regardless of other content.
    if s:find('\n') then
        return s
    end

    -- Check if the text has a valid URL prefix and at least one valid URL character.
    local valid_url_prefixes = {'//', 'http://', 'https://', 'ftp://', 'gopher://', 'mailto:', 'news:', 'irc://'}
    local url_prefix
    for i,v in ipairs(valid_url_prefixes) do
        if s:find( '^%[' .. v ..'[^"%s].*%]' ) then
            url_prefix = v
            break
        end
    end

    -- Get display text
    if not url_prefix then
        -- Deal with nested links or send back original string.
        return "[" .. mw.ustring.gsub( mw.ustring.sub(s, 2), "%[.-%]", delinkURL )
    end
    s = s:match('^%[' .. url_prefix .. '(.*)%]') -- Grab all of the text after the URL prefix and before the final square bracket.
    s = s:match('^.-(["<> [].*)') or '' -- Grab all of the text after the first URL separator character ("<> ).
    s = s:match('^%s*(%S.*)$') or '' -- If the separating character was a space, trim it off.

    local s_decoded = mw.text.decode(s, true)
    if s_decoded:find('%c') then
        return s
    else
        return s_decoded
    end
end


function p._delink(args)
    local text = args[1] or ''
    if args.refs == 'yes' then
        -- Remove any [[Help:Strip markers]] representing ref tags. In most situations
        -- this is not a good idea - only use it if you know what you are doing!
        text = mw.text.unstrip(text)
    end
    if not (args.comments == 'no') then
        text = text:gsub('<!%-%-.-%-%->', '') -- Remove html comments.
    end
    if not (args.wikilinks == 'no') then
        text = text:gsub('%[%[.-%]%]', delinkWikilink) -- De-link wikilinks.
    end
    if not (args.urls == 'no') then
        text = text:gsub('%[.-%]', delinkURL) -- De-link URLs.
    end
    if not (args.whitespace == 'no') then
        -- Replace single new lines with a single space, but leave double new lines
        -- and new lines only containing spaces or tabs before a second new line.
        text = text:gsub('([^\n \t])[ \t]*\n\t*([^\n \t])', '%1 %2')
        text = text:gsub('\n\t+', '\n') -- Remove leading tab.
        text = text:gsub('[ \t]+', ' ') -- Remove extra tabs and spaces.
    end
    if not (args.nowiki == 'no') then
        text = mw.text.unstripNoWiki(text)
    end
    return text
end

function p.delink(frame)
    local args
    if frame == mw.getCurrentFrame() then
        -- We're being called via #invoke. If the invoking template passed any args, use
        -- them. Otherwise, use the args that were passed into the template.
        args = frame:getParent().args
        for k, v in pairs(frame.args) do
            args = frame.args
            break
        end
    else
        -- We're being called from another module or from the debug console, so assume
        -- the args are passed in directly.
        args = frame
    end
    return p._delink(args)
end

return p