Module:dercat

From Wiktionary, the free dictionary
Jump to navigation Jump to search

Used by {{dercat}}.


local m_languages = require("Module:languages")

local check_ancestor = require("Module:etymology").check_ancestor
local format_categories = require("Module:utilities").format_categories
local insert = table.insert
local ipairs = ipairs
local process_params = require("Module:parameters").process

local export = {}

local function add_category(categories, adjective, target_lang_name, source_lang_name)
	if target_lang_name == source_lang_name and adjective == "derived" then
		insert(categories, target_lang_name .. " terms borrowed back into " .. source_lang_name)
	else
		insert(categories, target_lang_name .. " terms " .. adjective .. " from " .. source_lang_name)
	end
end

function export.dercat(frame)
	local args = process_params(frame:getParent().args, {
		[1] = { required = true },
		[2] = { list = true, required = true },
		["inh"] = { type = "number" },
	})

	local target_lang = m_languages.getByCode(args[1], 1)
	local target_lang_name = target_lang:getCanonicalName()
	local categories = {}
	local has_cutoff = false
	for _, lang_code in ipairs(args[2]) do
		if lang_code == "<" then
			has_cutoff = true
			break
		end
	end
	for i, source_lang_code in ipairs(args[2]) do
		-- Accept family and etymology language codes.
		if source_lang_code == "<" then
			has_cutoff = false
		else
			local source_lang = m_languages.getByCode(source_lang_code, i, true, true)
			local source_lang_name = source_lang:getDisplayForm()
			add_category(categories, "derived", target_lang_name, source_lang_name)
			if has_cutoff or (args.inh and i <= args.inh) then
				check_ancestor(target_lang, source_lang)
				add_category(categories, "inherited", target_lang_name, source_lang_name)
			end
		end
	end
	return format_categories(categories, target_lang)
end

return export