Module:Category handler: Difference between revisions

Ganaram inukshuk (talk | contribs)
No edit summary
ArrowHead294 (talk | contribs)
m Wikitext debugger option
 
(16 intermediate revisions by one other user not shown)
Line 7: Line 7:
-- Basic category handler, based on Wikipedia's category handler. It categorizes
-- Basic category handler, based on Wikipedia's category handler. It categorizes
-- pages, given a table of categories as input, and suppresses categorization if
-- pages, given a table of categories as input, and suppresses categorization if
-- the page is in the table of excluded namespaces.
-- the page is in the table of excluded namespaces, or table of excluded
-- suffixes (subpages).
-- The most common categorizing templates that have/require complex rules are:
-- The most common categorizing templates that have/require complex rules are:
-- - Infoboxes; these usually shouldn't categorize if they're outside the main
-- - Infoboxes; these usually shouldn't categorize if they're outside the main
--  namespace.
--  namespace.
-- - Certain mboxes; some mboxes categorize certain pages, but they shouldn't
-- - Certain mboxes; some mboxes categorize pages, but if that mbox categorizes
--  categorize their own documentation.
--  templates/modules and are placed on that page's /doc subpage, it should
--  categorize the page on which the documentation is transcluded, not the /doc
--  page itself.
-- - Categorizing templates used on their own /doc pages as examples; a special
--  case of the previous case; passing in debug=1 disables all categorization.


-- Default list of namespaces in which to suppress categorization. Most
-- Default list of namespaces in which to suppress categorization. Most
Line 21: Line 26:
-- Adjust as needed!
-- Adjust as needed!
local DEFAULT_SUPPRESSED_NAMESPACES = {
local DEFAULT_SUPPRESSED_NAMESPACES = {
["main"] = false,
     ["talk"] = true,
     ["talk"] = true,
     ["user"] = true,
     ["user"] = true,
Line 45: Line 51:
}
}


-- Helper function: check if current namespace is excluded
-- List of namespace aliases
-- Accepts an optional table, containing or overriding other namespaces' rules
-- For "main", this is so editors can type in "main" since the main namespace's
local function is_suppressed_namespace(title, ns_override)
-- actual name is "". For "xw"-related namespaces, these are shorthands.
local ns_text
local NAMESPACE_ALIASES = {
[""] = "main", -- "" is treated as "main"
["xw"] = "xenharmonic wiki", -- Shorthand
["xw talk"] = "xenharmonic wiki talk" -- Shorthand
}


if type(title) == "table" and title.nsText then
-- Helper function
ns_text = mw.ustring.lower(title.nsText or '')
-- Converts namespace aliases to their actual names
elseif type(title) == "string" then
-- Must be placed before is_suppressed_namespace()
ns_text = mw.ustring.lower(title)
local function normalize_ns(ns)
else
ns = mw.ustring.lower(mw.text.trim(ns or "")) -- Convert to lowercase and and trim extra spaces
ns_text = mw.ustring.lower(mw.title.getCurrentTitle().nsText or '')
if ns == "" then ns = "main" end -- Empty-string is assumed to be "main"
if NAMESPACE_ALIASES[ns] then
return NAMESPACE_ALIASES[ns]
end
end
return ns
end


-- Helper function: check if current namespace is excluded
-- Accepts an optional table, containing or overriding other namespaces' rules
local function is_suppressed_namespace(ns_override)
-- Get current namespace, or aliased namespace, as lowercase
local curr_ns = normalize_ns(mw.title.getCurrentTitle().nsText)
-- Build table of suppressed namespaces; start with default list
local namespaces = {}
local namespaces = {}
for k, v in pairs(DEFAULT_SUPPRESSED_NAMESPACES) do
for k, v in pairs(DEFAULT_SUPPRESSED_NAMESPACES) do
namespaces[k] = v
namespaces[normalize_ns(k)] = v
end
end


-- Then extend/override list using ns_override, if available
if type(ns_override) == "table" then
if type(ns_override) == "table" then
for k, v in pairs(ns_override) do
for k, v in pairs(ns_override) do
namespaces[k] = v
namespaces[normalize_ns(k)] = v
end
end
end
end


return namespaces[ns_text] or false
-- Return; if no namespace found, default to false
return namespaces[curr_ns] or false
end
end


Line 76: Line 99:
-- Accepts an opiontal table, containing additional suffixes to suppress
-- Accepts an opiontal table, containing additional suffixes to suppress
-- Suffix and custom suffixes are lowercased to guarantee matching
-- Suffix and custom suffixes are lowercased to guarantee matching
local function has_suppressed_suffix(title, suffixes_override)
local function has_suppressed_suffix(suffixes_override)
local title_obj
local title = mw.title.getCurrentTitle()
local pagename = mw.ustring.lower(title.text)


if type(title) == "table" and title.text then
-- Build table of suppressed suffixes, start with default suffixes
title_obj = title
elseif type(title) == "string" then
title_obj = mw.title.new(title)
else
title_obj = mw.title.getCurrentTitle()
end
 
local pagename = mw.ustring.lower(title_obj.text or '')
local suffixes = {}
local suffixes = {}
-- Include default suppressed suffixes
for _, suffix in ipairs(DEFAULT_SUPPRESSED_SUFFIXES) do
for _, suffix in ipairs(DEFAULT_SUPPRESSED_SUFFIXES) do
table.insert(suffixes, suffix)
table.insert(suffixes, suffix)
end
end


-- Add custom overrides
-- Then append additional suffixes, if available (append, not replace)
if type(suffixes_override) == "table" then
if type(suffixes_override) == "table" then
for _, suffix in ipairs(suffixes_override) do
for _, suffix in ipairs(suffixes_override) do
Line 102: Line 116:
end
end


-- Check if the page name ends with any of the suffixes (as subpages)
-- Find and match suffix
for _, suffix in ipairs(suffixes) do
for _, suffix in ipairs(suffixes) do
suffix = mw.text.trim(mw.ustring.lower(suffix or ''))
suffix = mw.ustring.lower(mw.text.trim(suffix or '')) -- Also normalize
if suffix ~= '' then
if suffix ~= '' then
local pattern = '/' .. mw.ustring.gsub(suffix, '([%^%$%(%)%%%.%[%]%*%+%-%?])', '%%%1') .. '$'
local pattern = '/' .. mw.ustring.gsub(suffix, '([%^%$%(%)%%%.%[%]%*%+%-%?])', '%%%1') .. '$'
Line 114: Line 128:


return false
return false
end
-- Helper function: strips suffix from title
local function strip_suffix(title, suffix)
    local text = title.text
    if mw.ustring.sub(text, -mw.ustring.len(suffix)) == suffix then
        return mw.title.new(mw.ustring.sub(text, 1, -mw.ustring.len(suffix)-1), title.ns)
    end
    return title
end
end


Line 129: Line 134:
-- Disallows categories if it's in a suppressed namespace or the page has a
-- Disallows categories if it's in a suppressed namespace or the page has a
-- suppressed suffix (subpage)
-- suppressed suffix (subpage)
function p._category_handler(cats, ns_override, suffixes_override, is_debug)
function p._category_handler(cats, is_debug, ns_override, suffixes)
    cats = cats or {}
local cats = cats or {}
    is_debug = yesno(is_debug, false)
local is_debug = yesno(is_debug, false)
-- Test values; should be commented out for normal use
--local cats = cats or {"Abstract MOS patterns", "7-tone scales"}
--local ns_override = ns_override or { ["module"] = true }
-- If in a suppressed namespace/prefix, or in debug mode (suppresses ALL
-- categorization) don't bother
if is_suppressed_namespace(ns_override)
or has_suppressed_suffix(suffixes)
or is_debug then
return ''
end


    local frame = mw.getCurrentFrame()
-- Otherwise, categorize
    local parent_frame = frame:getParent()
local result = ''
    local parent_title = parent_frame and mw.title.new(parent_frame:getTitle()) or mw.title.getCurrentTitle()
for _, cat in ipairs(cats) do
 
cat = mw.text.trim(cat or '')
    -- If parent page is a documentation subpage (e.g. ends with /doc), switch to base page
if cat ~= '' then
    parent_title = strip_suffix(parent_title, "/doc")
result = result .. string.format('[[Category:%s]]', cat)
 
end
    local suppressed_ns = is_suppressed_namespace(parent_title, ns_override)
end
    local suppressed_suffix = has_suppressed_suffix(parent_title, suffixes_override)
    local is_content = parent_title.isContentPage
 
    if is_debug or suppressed_ns or suppressed_suffix or not is_content then
        local reason = is_debug and "debug mode"
            or (suppressed_ns and "suppressed namespace")
            or (suppressed_suffix and "suppressed suffix")
            or (not is_content and "non-content page")
            or "unknown"
 
        -- Return a debug comment explaining why categorization was suppressed
        return string.format(
            "<!-- categorization suppressed: %s; is_debug=%s; suppressed_ns=%s; suppressed_suffix=%s; is_content=%s -->",
            reason,
            tostring(is_debug),
            tostring(suppressed_ns),
            tostring(suppressed_suffix),
            tostring(is_content)
        )
    end
 
    local result = ''
    for _, cat in ipairs(cats) do
        cat = mw.text.trim(cat or '')
        if cat ~= '' then
            result = result .. string.format('[[Category:%s]]', cat)
        end
    end


    return result
return result
end
end


Line 176: Line 165:
function p.category_handler(frame)
function p.category_handler(frame)
local args = getArgs(frame)
local args = getArgs(frame)
local cats_unparsed        = args["categories"] or ""
local excluded_ns_unparsed = args["excluded_ns"] or "" -- Additional namespaces to exclude (EG, a template that should not be used within main namespace, which is allowed by default)
local excluded_ns_unparsed = args["excluded_ns"] or ""
local allowed_ns_unparsed  = args["allowed_ns" ] or "" -- Namespaces to allow; overrides default list (EG, a template that should be used within user namespace, which is disallowed by default)
local suffixes_unparsed    = args["suffixes"] or ""
local suffixes_unparsed    = args["suffixes"   ] or "" -- Additional page suffixes in which to disallow categories
local is_debug             = yesno(args["debug"], false)
local is_debug = yesno(args["debug"], false) -- Parse debug mode; setting this to TRUE disables all categories
local wtext = yesno(args["wtext"]) -- Used to show the underlying Wikitext


-- Parse categories
-- Parse categories
-- Categories are entered using unnamed params
local cats = {}
local cats = {}
for cat in mw.text.gsplit(cats_unparsed, "[,\n]") do
for _, cat in ipairs(args) do
cat = mw.text.trim(cat)
cat = mw.text.trim(cat)
if cat ~= "" then
if cat ~= "" then
Line 190: Line 181:
end
end


-- Parse excluded namespaces (added/overrides default)
-- Parse excluded namespaces
-- These are added in addition to the default list
-- This currently can't force-allow suppressed namespaces as template input,
-- only disallow additional namespaces
local ns_override = {}
local ns_override = {}
for ns in mw.text.gsplit(excluded_ns_unparsed, "[;\n]") do
for ns in mw.text.gsplit(excluded_ns_unparsed, "[;\n]") do
Line 196: Line 190:
if ns ~= "" then
if ns ~= "" then
ns_override[ns] = true
ns_override[ns] = true
end
end
-- Parse allowed namespaces
-- This gets added to the ns_override array, with values set to FALSE
-- EG, Template:TODO is used in several namespaces that are normally
-- suppressed: user, talk, help, and maybe xw talk
for ns in mw.text.gsplit(allowed_ns_unparsed, "[;\n]") do
ns = mw.text.trim(ns)
if ns ~= "" then
ns_override[ns] = false
end
end
end
end
Line 208: Line 213:
end
end


return p._category_handler(cats, ns_override, suffixes, is_debug)
local result = p._category_handler(cats, is_debug, ns_override, suffixes)
if wtext then
result = "<syntaxhighlight lang=\"wikitext\">" .. result .. "</syntaxhighlight>"
end
return frame:preprocess(result)
end
end


return p
return p