Jump to content

Module:Category disambiguation

Permanently protected module
From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Theknightwho (talk | contribs) at 12:54, 16 February 2024 (Add further comments.). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

local concat = table.concat
local getArgs = require("Module:Arguments").getArgs
local insert = table.insert
local messageBox = require("Module:Message box").main

local title = mw.title.getCurrentTitle()
local namespace = title.namespace
local title_text = title.text

local p = {}

function p.main(frame)
	local args
	-- Documentation example.
	if namespace == 10 and title_text:match("Category disambiguation") then
		args = {
			"the bird genus",
			"Eremophila (bird)",
			"the plant genus",
			"Eremophila (plant)"
		}
	-- Otherwise, process input arguments. We want to keep blanks in the list or ipairs will terminate early, but if allowredlink is blank it should be nil.
	else
		args = getArgs(frame, {
			removeBlanks = false,
		})
	end
	
	local allowredlink = args.allowredlink ~= "" and args.allowredlink or nil
	local list, topic, needs_fixing = {}
	
	-- It would be better to iterate in steps of 2, but we can't get the length of a frame argument table without iterating over it since the arguments are accessed via metamethods.
	-- A category is only added to `list` if both arguments are provided for it. If an odd number of arguments are supplied, the final argument is just ignored.
	for i, arg in ipairs(args) do
		if i % 2 == 1 then
			topic = arg
		else
			insert(
				list,
				"*For " .. topic .. ", see '''[[:Category:" .. arg .. "]].'''"
			)
			-- Add "needs fixing" category if:
			-- (1) We're in the category namespace.
			-- (2) allowredlink isn't set.
			-- (3) The category is a redlink. (Use :getContent() to avoid triggering the expensive parser function count.)
			if (
				not needs_fixing and
				namespace == 14 and
				not (allowredlink or mw.title.new(arg, 14):getContent())
			) then
				needs_fixing = true
			end
		end
	end
	
	if #list < 2 then
		error("Please supply at least two categories, using the first four parameters")
	end
	
	return messageBox("cmbox", {
		type  = "content",
		image = "[[File:Disambig gray.svg|50px]]",
		text = "'''This category is not in use because it has an ambiguous title.'''" .. 
			frame:expandTemplate{
				title = "Plainlist",
				args = {
					concat(list, "\n"),
					style = "margin-left:1.6em;"
				}
			} ..
			"'''Note:''' This category page should be empty.  All entries should be recategorized under one of the above categories or an appropriate subcategory."
	}) .. (needs_fixing and "[[Category:Wikipedia category-disambiguation box parameter needs fixing|∃" ..
		title_text .. "]]" or "")
end

return p