Module:ja-link/multi

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


local export = {}

local m_template_parser = require("Module:template parser")

local class_else_type = m_template_parser.class_else_type
local ja_link = require("Module:ja-link").link
local parse = m_template_parser.parse
local pcall = pcall
local process_params = require("Module:parameters").process

local alias_of_3 = {alias_of = 3}
local boolean = {type = "boolean"}
local params = {
	[1] = {required = true},
	[2] = true,
	[3] = true,
	["gloss"] = alias_of_3,
	["t"] = alias_of_3,
	["linkto"] = {allow_empty = true},
	["rom"] = true,
	["lit"] = true,
	["pos"] = true,
	["id"] = true,
	["hist"] = boolean,
	["caps"] = boolean,
	["self"] = {type = "boolean", default = false},
}

local function process_template(args, lang)
	args = process_params(args, params)
	return ja_link({
		lang = lang,
		lemma = args[1],
		kana = args[2],
		gloss = args[3],
		lit = args["lit"],
		pos = args["pos"],
		id = args["id"],
		linkto = args["linkto"],
		tr = args["rom"],
	}, {
		caps = args["caps"],
		hist = args["hist"],
		disableSelfLink = args["self"],
	})
end

function export.main(frame)
	local text = frame:getParent().args["data"]
	if not text then
		return ""
	end
	local lang = require("Module:languages").getByCode(frame.args[1] or "ja")
	local Jpan_template = lang:getCode() .. "-r"
	
	text = parse(frame:getParent().args["data"])
	for node, parent, key in text:__pairs("next_node") do
		local class = class_else_type(node)
		if class ~= "wikitext" then
			local new
			if class == "template" and node:get_name() == Jpan_template then
				local success, result = pcall(process_template, node:get_arguments(), lang)
				if success then
					new = result
				end
			end
			if not new then
				new = node:expand()
			end
			if parent then
				parent[key] = new
			else
				text = new
			end
		end
	end
	return tostring(text)
end

return export