Module:Autocat/sandbox

Lua
CodeDiscussionEditHistoryLinksLink count Subpages:DocumentationTestsResultsSandboxLive code All modules

Documentation for this module may be created at Module:Autocat/sandbox/doc

Code

-- =============================================================================
-- Automatically add categories to a page
-- =============================================================================

require("strict")

local makesortkey  = require "Module:MakeSortKey"

local p = {}

-- -----------------------------------------------------------------------------
-- Main function
-- -----------------------------------------------------------------------------

function p.autoCat(candidates, criterion, sortkey)
	local catredir = require("Module:Resolve category redirect")
	-- Make sure that sortkey is not nil
	local sortkey2 = sortkey or ""
	-- Compile list of categories to include
	local result = ""
	for chain in candidates:gmatch("[^\n]+") do
		local category, sortkey1
		for candidate in chain:gmatch("[^;]+") do
			local base
			base, sortkey1 = candidate:match("(.*):(.*)")
			if not base then
				base = candidate
				sortkey1 = ""
			end
			if base ~= "-" then
				-- First try meta category "by criterion"
				if criterion then
					category = "Category:" .. base .. " by " .. criterion
					if mw.title.new(category).exists then
						sortkey1 = ""	-- No sort prefix in meta categories
						break
					end
				end
				-- Then try the base category
				category = "Category:" .. base
				if mw.title.new(category).exists then
					break
				end
			else
				-- "-" means we don't want any category at this point
				category = nil
			end
		end
		if category then
			local category_name = mw.ustring.sub(category, 10, mw.ustring.len(category))
			local category2 = "Category:" .. catredir.rtarget(category_name, mw.getCurrentFrame())
			result = result .. "[[" .. category2
			if sortkey1 .. sortkey2 ~= "" then
				result = result .. "|" .. makesortkey.makeSortKey(sortkey1 .. sortkey2)
			end
			result = result .. "]]"
		end
	end
	return result
end

-- =============================================================================

return p