Módulo:term etymology

A documentación deste módulo pódese crear en "Módulo:term etymology/uso"

local export = {}

local m_languages = require("Module:languages")

local function create_parameters(param_text)
	local params = {}
	for _, p in ipairs(mw.text.split(param_text, '|')) do
		local k, v = mw.ustring.match(p, "([^=]*)=(.*)")
		if k then
			params[k] = v
		else
			table.insert(params, p)
		end
	end
	return params
end

local function internal_expansion(args)
	local lang, term = args[2], args[3]
	
	lang = m_languages.getByCode(lang)
		or require("Module:etymology languages").getByCode(lang)
		or m_languages.err(lang, 1)
		
	local entryLang = require("Module:etymology").getNonEtymological(lang)
	
	return export.getEtymology(entryLang, term)
end

function export.getEtymology(lang, term)
	local page = mw.title.new(require("Module:links").getLinkPage(term, lang))
	local content = page:getContent()
	
	if not content then
		return ""
	end
	
	local _, index = mw.ustring.find(content, "\n==" .. lang:getCanonicalName() .. "==", nil, true)
	if not index then
		_, index = mw.ustring.find(content, "^==" .. require("Module:utilities").pattern_escape(lang:getCanonicalName()) .. "==", nil, false)
	end
	if not index then
		error("Language not found: " .. lang:getCanonicalName() .. ".")
	end
	_, next_lang = mw.ustring.find(content, "\n==[^=\n]+==", index, false)
	_, index = mw.ustring.find(content, "\n(====?)Etymology%1", index, false)
	if (not index) or (next_lang and next_lang < index) then
		error("Etymology not found")
	end
	
	local etymology = mw.ustring.match(content, "(.-)%\n+=+", index + 1)
	
	etymology = mw.text.trim(etymology)
	
	etymology = mw.ustring.gsub(
		etymology,
		"{{termetym|([^}]*)}}",
		function(text)
			return internal_expansion(create_parameters(text))
		end
	)
	
	etymology = mw.ustring.gsub(etymology, "{{PIE root|%S*|%S*}}%s", "")
	etymology = mw.ustring.gsub(etymology, "<ref.->.-</ref>", "") -- remove ref tags
	etymology = mw.ustring.gsub(etymology, "<ref.->", "") -- remove closed tags ref tags
	etymology = mw.ustring.gsub(etymology, "(.-)%.%s+.*", "%1") -- everything after the first sentence period if present
	etymology = mw.ustring.gsub(etymology, "%.$", "")
	
	etymology = mw.ustring.gsub(
		etymology,
		"^(%a)",
		function (letter)
			return mw.ustring.lower(letter)
		end
	)
	
	return etymology
	
end

return export