Module:IPA pronunciation key

From Wiktionary, the free dictionary
Jump to navigation Jump to search
local export = {}

function export.process(frame)
	local text = frame.args[1] or frame:getParent().args[1]
	
	local getByCanonicalName = require("Module:languages").getByCanonicalName
	local cell_languages = {}
	local i = 0
	
	for lang_name in text:gmatch("\n!%s*%[%[([^%]]+)%]%]") do
		if not lang_name:find("IPA") then
			i = i + 1
			if lang_name == "Croatian" then lang_name = "Serbo-Croatian" end
			cell_languages[i] = getByCanonicalName(lang_name) or error("The language name " .. lang_name .. " is not recognized.")
		end
	end
	
	local full_link = require "Module:links".full_link
	local function link_word(lang, entry, alt)
		return full_link {
			lang = lang,
			term = entry,
			alt = alt,
		}
	end
	
	local function link_row(row)
		local indices = {}
		for match_start in row:gmatch "[\n|]|()" do
			table.insert(indices, match_start)
		end
		table.insert(indices, #row + 1) -- add 1 here because 1 is subtracted in the loop over indices
		assert(#indices == #cell_languages + 2)
		local output = {}
		table.insert(output, row:sub(1, assert(indices[1]) - 1))
		for i = 1, #indices - 1 do
			local cell = row:sub(indices[i], indices[i + 1] - 1)
			local linked_cell
			if i > 1 then
				linked_cell = cell:gsub(
				"(%[%[([^%]]+)%]%])",
				function(link, link_text)
					if link_text:find("'''") and not link_text:find("|") then
						local lang = assert(cell_languages[i - 1])
						return link_word(lang, link_text:gsub("'''", ""), link_text)
					else
						return link
					end
				end)
			else
				linked_cell = cell
			end
			table.insert(output, linked_cell)
		end
		return table.concat(output)
	end
	
	local background_color = "#E6E6E6"
	
	return (text
		:gsub("(| +)-", "%1 " .. ' style="background: ' .. background_color .. ';" | —')
		:gsub("(<big>)([^<]+)(</big>)", '%1<span class="IPA">%2</span>%3')
		:gsub("|%-[^\n]*\n+|[^\n]*\n+|[^\n]*", link_row))
end

return export