The test_existence function tracks instances of {{glossary}} that link to anchors not found in Appendix:Glossary. See Category:Pages linking to anchors not found in Appendix:Glossary. It uses the data module Module:glossary/data to determine if the anchor exists.


local export = {}

local require_when_needed = require("Module:require when needed")

local anchor_encode = mw.uri.anchorEncode
local normalize_anchor = require_when_needed("Module:get IDs", "normalize_anchor")
local nowiki = require_when_needed("Module:string/nowiki")

function export.def(frame)
	local required_default_ = {required = true, default = ""}
	local args = require("Module:parameters").process(frame:getParent().args, {
		[1] = required_default_,
		[2] = required_default_,
	})
	
	local term = args[1]
	return "; <span id=\"" .. anchor_encode(term) .. "\">" .. term .. "</span>\n: " .. args[2]
end

local function get_link(formatted_anchor, text, anchor)
	return "[[Appendix:Glossary#" .. nowiki(formatted_anchor) .. "|" .. (text or anchor) .. "]]"
end

function export.link(frame)
	local args = require("Module:parameters").process(frame:getParent().args, {
		[1] = {required = true, default = ""},
		[2] = true,
	})
	
	local data = mw.loadData("Module:glossary/data")
	
	local anchor, text = args[1], args[2]
	local formatted_anchor = normalize_anchor(anchor)
	if data[formatted_anchor] then
		return get_link(formatted_anchor, text, anchor)
	end
	
	local lower_anchor = anchor:ulower()
	formatted_anchor = normalize_anchor(lower_anchor)
	
	local link = get_link(formatted_anchor, text, anchor)
	
	if data[formatted_anchor] or formatted_anchor == "" then
		return link
	end
	
	mw.log("The anchor " .. lower_anchor
		.. (lower_anchor ~= anchor and " or " .. anchor or "")
		.. " does not exist in Appendix:Glossary.")
	
	return link
		.. "[[Category:Pages linking to anchors not found in Appendix:Glossary|"
		.. lower_anchor .. "]]"
end

return export