Documentation for this module may be created at မော်ဂျူး:mdf-translit/doc

local export = {}

local gsub = mw.ustring.gsub
local lower = mw.ustring.lower
local trim = mw.text.trim

local letters = {
	["А"]="A", ["Б"]="B", ["В"]="V", ["Г"]="G", ["Д"]="D", ["Е"]="E", ["Ё"]="O", ["Ж"]="Ž", ["З"]="Z", ["И"]="I", ["Й"]="J",
	["К"]="K", ["Л"]="L", ["М"]="M", ["Н"]="N", ["О"]="O", ["П"]="P", ["Р"]="R", ["С"]="S", ["Т"]="T", ["У"]="U", ["Ф"]="F",
	["Х"]="H", ["Ц"]="C", ["Ч"]="Č", ["Ш"]="Š", ["Щ"]="Šč", ["Ъ"]="Ə", ["Ы"]="I", ["Ь"]="", ["Э"]="E", ["Ю"]="U", ["Я"]="A",
	["а"]="a", ["б"]="b", ["в"]="v", ["г"]="g", ["д"]="d", ["е"]="e", ["ё"]="o", ["ж"]="ž", ["з"]="z", ["и"]="i", ["й"]="j",
	["к"]="k", ["л"]="l", ["м"]="m", ["н"]="n", ["о"]="o", ["п"]="p", ["р"]="r", ["с"]="s", ["т"]="t", ["у"]="u", ["ф"]="f",
	["х"]="h", ["ц"]="c", ["ч"]="č", ["ш"]="š", ["щ"]="šč", ["ъ"]="ə", ["ы"]="i", ["ь"]="", ["э"]="e", ["ю"]="u", ["я"]="a",
}

local palatals = {
	["Д"]="Ď", ["З"] = "Ź", ["Л"] = "Ľ", ["Н"] = "Ń", ["Р"] = "Ŕ", ["С"] = "Ś", ["Т"] = "Ť", ["Ц"] = "Ć",
	["д"]="ď", ["з"] = "ź", ["л"] = "ľ", ["н"] = "ń", ["р"] = "ŕ", ["с"] = "ś", ["т"] = "ť", ["ц"] = "ć",
}

local vowels = "АОУЫЭЯЁЮИЕЬаоуыэяёюиеь"
local front = "ЕЁИЮЯеёиюя"
local accents = "́̀"
local nondentals = "бвгжкпмшБВГЖКПМШ"

function export.tr(text, lang, sc)
	-- make all word borders have a space
	text = " " .. text .. " "

	-- front vowels after another vowel are written with initial j
	text = gsub(text, "([" .. vowels .. "][" .. accents .. "]?)([еёиюя])", "%1j%2")
	text = gsub(text, "([" .. vowels .. "][" .. accents .. "]?)([ЕЁИЮЯ])", "%1J%2")
	-- repeat to catch all instances
	text = gsub(text, "([" .. vowels .. "][" .. accents .. "]?)([еёиюя])", "%1j%2")
	text = gsub(text, "([" .. vowels .. "][" .. accents .. "]?)([ЕЁИЮЯ])", "%1J%2")
	-- е, ё, ю, я at the beginning of a word are also written with initial j
	text = gsub(text, " ([еёюя])", " j%1")
	text = gsub(text, " ([ЕЁЮЯ])", " J%1")

	-- я after non-dental consonants becomes ä
	text = gsub(text, "([".. nondentals .."])я", "%1ä")
	text = gsub(text, "([".. nondentals .."])Я", "%1Ä")
	-- ё after non-dental consonants becomes œ
	text = gsub(text, "([".. nondentals .."])ё", "%1ö")
	text = gsub(text, "([".. nondentals .."])Ё", "%1Ö")

	-- make Е, Ё, Ю, Я lowercase if preceding a non-capital letter
	text = gsub(text, "([ЕЁЮЯ])([^%u])", function(v, l)
		return lower(v) .. l
	end)

	-- dental consonants before ь and front vowels are palatalized
	for i, v in pairs(palatals) do
		text = gsub(text, i .. "ь", v)
		text = gsub(text, i .. "([" .. front .. "])", v .. "%1")
	end

	-- ъ and ь are omitted before a front vowel
	text = gsub(text, "ъ([" .. front .. "])","j%1")
	text = gsub(text, "Ъ([" .. front .. "])","J%1")

	return trim(gsub(text, ".", letters))
end

return export