Module:LinkParser: Difference between revisions
// via Wikitext Extension for VSCode |
// via Wikitext Extension for VSCode |
||
| (3 intermediate revisions by the same user not shown) | |||
| Line 1: | Line 1: | ||
-- | --[[ | ||
* Name: LinkParser | |||
* Author: Mark W. Datysgeld | |||
* Description: Comprehensive link handling module for both external links and internal wiki links with caching | |||
* Notes: URL normalization (protocol stripping, www removal); wiki link extraction, preservation, and automatic application; caching for both link types; supports autoWikiLink field configuration; preserves wiki links during processing | |||
]] | |||
local p = {} | local p = {} | ||
| Line 74: | Line 78: | ||
-- @return Processed value or boolean based on mode | -- @return Processed value or boolean based on mode | ||
function p.processWikiLink(value, mode) | function p.processWikiLink(value, mode) | ||
mode = mode or "extract" | mode = mode or "extract" | ||
if not value or value == "" then | if not value or value == "" then | ||
return mode == "check" and false or value | return mode == "check" and false or value | ||
end | end | ||
local cacheKey = value .. ":" .. mode | local cacheKey = value .. ":" .. mode | ||
if wikiLinkCache[cacheKey] ~= nil then | if wikiLinkCache[cacheKey] ~= nil then | ||
return wikiLinkCache[cacheKey] | return wikiLinkCache[cacheKey] | ||
end | end | ||
-- | -- A single regex to capture the page name and optional display text | ||
local | local pageName, displayText = value:match("^%[%[([^|]+)|?(.*)%]%]$") | ||
if mode == "check" then | if mode == "check" then | ||
local isWikiLink = (pageName ~= nil) | |||
wikiLinkCache[cacheKey] = isWikiLink | wikiLinkCache[cacheKey] = isWikiLink | ||
return isWikiLink | return isWikiLink | ||
end | end | ||
if not pageName then | |||
if not | |||
wikiLinkCache[cacheKey] = value | wikiLinkCache[cacheKey] = value | ||
return value | return value | ||
end | end | ||
-- | -- If displayText is empty, it means the format was [[PageName]], so use pageName | ||
if displayText == "" then | |||
displayText = pageName | |||
displayText = pageName | |||
end | end | ||
local result | local result | ||
if mode == "extract" then | if mode == "extract" then | ||
result = pageName | result = pageName | ||
elseif mode == "strip" then | elseif mode == "strip" then | ||
result = displayText | result = displayText | ||
else | else | ||
-- | result = pageName -- Default to extract for unknown modes | ||
end | end | ||
wikiLinkCache[cacheKey] = result | wikiLinkCache[cacheKey] = result | ||
return result | return result | ||
end | end | ||