Bước tới nội dung

Mô đun:gl-pron

Từ điển mở Wiktionary
--Based on [[Module:es-pronunc]] by Benwing2

local export = {}

local m_IPA = require("Module:IPA")
local m_table = require("Module:table")
local audio_module = "Module:audio"
local put_module = "Module:parse utilities"

local force_cat = false

local lang = require("Module:languages").getByCode("gl")

local u = mw.ustring.char
local rfind = mw.ustring.find
local rsubn = mw.ustring.gsub
local rsplit = mw.text.split
local ulower = mw.ustring.lower
local usub = mw.ustring.sub
local ulen = mw.ustring.len
local unfd = mw.ustring.toNFD
local unfc = mw.ustring.toNFC

local AC = u(0x0301) -- acute =  ́
local GR = u(0x0300) -- grave =  ̀
local CFLEX = u(0x0302) -- circumflex = ^ 
local CARO = u(0x030C) -- caron 
local TILDE = u(0x0303) -- tilde =  ̃
local DIA = u(0x0308) -- diaeresis =  ̈
local DOTA = u(0x0307) -- dot above
local DOTB = u(0x0323) --dot below
local BREVE = u(0x0306) --breve

local vowel = "aeiouüɛɔɐɪʊɑAEIOUÜ" -- vowel
local V = "[" .. vowel .. "]" -- vowel class
local accent = AC .. GR .. CARO
local accent_c = "[" .. accent .. "]"
local stress = AC
local stress_c = "[" .. AC .. "]"
local ipa_stress = "ˈˌ"
local ipa_stress_c = "[" .. ipa_stress .. "]"
local sylsep = "%-." -- hyphen included for syllabifying from spelling
local sylsep_c = "[" .. sylsep .. "]"
local wordsep = "# "
local separator_not_wordsep = accent .. ipa_stress .. sylsep
local separator = separator_not_wordsep .. wordsep
local separator_c = "[" .. separator .. "]"
local C = "[^" .. vowel .. separator .. "]" -- consonant class

local unstressed_words = m_table.listToSet({ --all words in this list containing non-final <e,o> should be listed later (look for "handle vowels"). FIXME add more unstressed words
	"a", "as", "o", "os", -- definite articles
	"con", "de", "en", "por", "sen", "so", --prepositions
})

-- version of rsubn() that discards all but the first return value
local function rsub(term, foo, bar)
	local retval = rsubn(term, foo, bar)
	return retval
end

-- version of rsubn() that returns a 2nd argument boolean indicating whether
-- a substitution was made.
local function rsubb(term, foo, bar)
	local retval, nsubs = rsubn(term, foo, bar)
	return retval, nsubs > 0
end

-- apply rsub() repeatedly until no change
local function rsub_repeatedly(term, foo, bar)
	while true do
		local new_term = rsub(term, foo, bar)
		if new_term == term then
			return term
		end
		term = new_term
	end
end

local function decompose(text)
	-- decompose everything but ñ and ü
	text = unfd(text)
	text = rsub(text, ".[" .. TILDE .. DIA .. "]", {
		["n" .. TILDE] = "ñ",
		["N" .. TILDE] = "Ñ",
		["u" .. DIA] = "ü",
		["U" .. DIA] = "Ü",
	})
	return text
end

local function split_on_comma(term)
	if term:find(",%s") then
		return require(put_module).split_on_comma(term)
	else
		return rsplit(term, ",")
	end
end

-- Remove any HTML from the formatted text and resolve links, since the extra characters don't contribute to the
-- displayed length.
local function convert_to_raw_text(text)
	text = rsub(text, "<.->", "")
	if text:find("%[%[") then
		text = require("Module:links").remove_links(text)
	end
	return text
end

-- Return the approximate displayed length in characters.
local function textual_len(text)
	return ulen(convert_to_raw_text(text))
end

local function construct_default_differences(dialect)
	if dialect == "Standard" then
		return {
			need_seseo = false,
			gheada_different = false,
		}
	end
	return nil
end

-- Main syllable-division algorithm
local function syllabify_from_spelling_or_pronun(text)
    -- Part 1: Divide before the last consonant in a cluster of consonants between vowels.
	-- Then move the syllable division marker leftwards over clusters that can form onsets.
	text = rsub_repeatedly(text, "(" .. V .. accent_c .. "*)(" .. C .. V .. ")", "%1.%2")
	text = rsub_repeatedly(text, "(" .. V .. accent_c .. "*" .. C .. "+)(" .. C .. V .. ")", "%1.%2")
	local cluster_r = is_spelling and "rɾ" or "ɾ"
	-- Don't divide Cl or Cr where C is a stop or fricative, except for dl.
	text = rsub(text, "([pbfvkctg])%.([l" .. cluster_r .. "])", ".%1%2")
	text = text:gsub("d%.([" .. cluster_r .. "])", ".d%1")
	-- Don't divide ll or rr.
	text = rsub(text, "([lr])%.%1", ".%1%1")

	-- Part 2: Divide hiatuses. Any aeo, or stressed iuüy, should be syllabically divided from a following aeo or
	-- stressed iuüy. Also divide ii and uu sequences
	text = rsub_repeatedly(text, "([aeoɛɔAEO]" .. accent_c .. "*)(h?[aeoɛɔ])", "%1.%2")
	text = rsub_repeatedly(text, "([aeoɛɔAEO]" .. accent_c .. "*)(h?" .. V .. stress_c .. ")", "%1.%2")
	text = rsub(text, "([iuüyIUÜY]" .. stress_c .. ")(h?[aeoɛɔ])", "%1.%2")
	text = rsub_repeatedly(text, "([iuüyIUÜY]" .. stress_c .. ")(h?" .. V .. stress_c .. ")", "%1.%2")
	text = rsub_repeatedly(text, "([iI]" .. accent_c .. "*)(h?i)", "%1.%2")
	text = rsub_repeatedly(text, "([uU]" .. accent_c .. "*)(h?u)", "%1.%2")

	return text
end

-- Generate the IPA of a given respelling.

function export.IPA(text, dialect, phonetic)
	local distincion = dialect == "Standard" or dialect == "Gheada"
	local gheismo = dialect == "Gheada" or dialect == "Gheada-seseo"
	local gheada_different = false
	local need_seseo = false

	text = ulower(text or mw.title.getCurrentTitle().text)
	-- decompose everything but ñ and ü
	text = decompose(text)
	-- convert commas and en/en dashes to IPA foot boundaries
	text = rsub(text, "%s*[,–—]%s*", " | ")
	-- question mark or exclamation point in the middle of a sentence -> IPA foot boundary
	text = rsub(text, "([^%s])%s*[¡!¿?]%s*([^%s])", "%1 | %2")

	-- canonicalize multiple spaces and remove leading and trailing spaces
	local function canon_spaces(text)
		text = rsub(text, "%s+", " ")
		text = rsub(text, "^ ", "")
		text = rsub(text, " $", "")
		return text
	end

	text = canon_spaces(text)

	-- Make prefixes unstressed unless they have an explicit stress marker; also make certain monosyllabic words unstressed.
	local words = rsplit(text, " ")
	for i, word in ipairs(words) do
		if rfind(word, "%-$") and not rfind(word, accent_c) or unstressed_words[word] then
			-- add CARO to the last vowel not the first one, or we will mess up 'que' by
			-- adding the CARO after the 'u'
			words[i] = rsub(word, "^(.*" .. V .. ")", "%1" .. CARO)
		end
	end
	text = table.concat(words, " ")
	-- Convert hyphens to spaces
	text = rsub(text, "%-", " ")
	-- canonicalize multiple spaces again, which may have been introduced by hyphens
	text = canon_spaces(text)
	-- now eliminate punctuation
	text = rsub(text, "[¡!¿?']", "")
	-- put # at word beginning and end and double ## at text/foot boundary beginning/end
	text = rsub(text, " | ", "# | #")
	text = "##" .. rsub(text, " ", "# #") .. "##"

	--handle vowels (internally, we use an accute accent to denote stress)
	text = rsub(text, "a" .. BREVE, "ɐ")
	text = rsub(text, "e" .. BREVE, "ɪ")
	text = rsub(text, "o" .. BREVE, "ʊ")
	text = rsub(text, "e" .. GR, "ɛ" .. AC)
	text = rsub(text, "o" .. GR, "ɔ" .. AC)
	text = rsub(text, "e" .. CFLEX, "E" .. AC) --temporary symbol
	text = rsub(text, "o" .. CFLEX, "O" .. AC) --temporary symbol
	text = rsub(text, "o".. DOTB, "ɔ")
	text = rsub(text, "e" .. DOTB, "ɛ")
	text = rsub(text, "e" .. DOTA, "E") --temporary symbols. we will use <e o> for undetermined mid vowels. The template will return an error
	text = rsub(text, "o" .. DOTA, "O") --if they remain in pre-tonic or accented syllables
	
	--handle reintegrationist norm forms, if any
	-- "nh" and word-final M stay unchanged so they won't affect standard forms.
	text = rsub(text, "mh", "nh")
	text = rsub(text, "lh", "ll")
	text = rsub(text, "ç", "z")
	text = rsub(text, "ss", "s")
	text = rsub(text, "g([ieɛE])", "x%1")
	text = rsub(text, "j", "x")
	
	--determine the values of <e,o> automatically (in some cases only)
	text = rsub(text, "ol#", "ɔl#")
	text = rsub(text, "ols#", "ɔls#")
	text = rsub(text, "el#", "ɛl#")
	text = rsub(text, "els#", "ɛls#")
	text = rsub(text, "ou", "Ou")
	text = rsub(text, "edo#", "Edo#")
	text = rsub(text, "edos#", "Edos#")
	text = rsub(text, "ello#", "Ello#")
	text = rsub(text, "ellos#", "Ellos#")
	text = rsub(text, "eza#", "Eza#")
	text = rsub(text, "ezas#", "Ezas#")
	text = rsub(text, "o" .. AC .. "n#", "O" .. AC .. "n#")
	text = rsub(text, "o" .. AC .. "ns#", "O" .. AC .. "ns#")
	text = rsub(text, "mente#", "mEnte#") --the -mente ending in adverbs will be handled automatically
	
	--some prepositions/function words will be handled automatically (no need to add "de")
	text = rsub(text, "#en#", "#En")
	text = rsub(text, "#co" .. CARO .. "n#", "#cʊ" .. CARO .. "n#")
	text = rsub(text, "#po" .. CARO .. "r#", "#pʊ" .. CARO .. "r#")
	text = rsub(text, "#si" .. CARO .. "n#", "#sɪn#")

	--FIXME add automatic suport for prefixes such as termo-, ...
	
	-- handle certain combinations
	text = rsub(text, "ch", "ĉ") --not the real sound
	text = rsub(text, "nh", "ŋ")
	text = rsub(text, "ll", "ɟ")
	text = rsub(text, "#p([st])", "#%1") -- [[psicoloxía]], [[pterodáctilo]]

	--c, g, q
	text = rsub(text, "c([ieɛE])", (distincion and "θ" or "z") .. "%1") -- not the real seseo sound
	text = rsub(text, "gu([ieɛE])", "g%1")
	text = rsub(text, "gü([ieɛE])", "gu%1")
	text = rsub(text, "qu([ieɛE])", "k%1")
	text = rsub(text, "z", distincion and "θ" or "z") -- not the real seseo sound
	if rfind(text, "[θz]") then
		need_seseo = true
	end
	
	-- map various consonants to their phoneme equivalent (we will switch to the correct <ɡ> later)
	text = rsub(text, "[vgñrxc]", {["v"]="b", ["ñ"]="ɲ", ["r"]="ɾ", ["x"]="ʃ", ["c"] = "k" })

	-- trill/tap
	text = rsub(text, "ɾɾ", "r")
	text = rsub(text, "([#lnszθ])ɾ", "%1r")

	--assimilation of nasals
	text = rsub(text, "n([# .]*[bp])", "m%1")
	text = rsub(text, "n([# .]*[kg])", "ŋ%1")
	text = rsub(text, "ns#", "ŋs#")
	text = rsub(text, "mn", "ŋn")
	text = rsub(text, "nm", "ŋm")
	text = rsub(text, "(" .. V .. ")gn(" .. V .. ")", "%1ŋn%2")
	text = rsub(text, "n##", "ŋ##")
	text = rsub(text, "n# #(" .. V .. ")", "ŋ# #%1")

	-- remove silent h before syllable division
	text = rsub(text, "h", "")

	-- convert i/u between vowels to glide
	local vowel_to_glide = { ["i"] = "j", ["u"] = "w" }
	-- i and u between vowels -> consonant-like substitutions: [[paranoia]]...
	text = rsub_repeatedly(text, "(.*" .. V .. accent_c .. "*h?)([iu])(" .. V .. ")",
		function (v1, iu, v2) return v1 .. vowel_to_glide[iu] .. v2 end
	)
	
	--some special cases involving the sequences <iu, ui>
	text = rsub(text, "iu#", "iw#")
	text = rsub(text, "iu" .. AC, "i.u" .. AC)

	--syllable division
	text = syllabify_from_spelling_or_pronun(text)

	--diphthongs
	text = rsub(text, "i([aeɛoɔuEO])", "j%1")
	text = rsub(text, "u([aeɛoɔuiEO])", "w%1")

	local accent_to_stress_mark = { [AC] = "ˈ", [GR] = "ˌ", [CARO] = "" }

	local function accent_word(word, syllables)
		-- Now stress the word. If any accent exists in the word (including ^ indicating an unaccented word),
		-- put the stress mark(s) at the beginning of the indicated syllable(s). Otherwise, apply the default
		-- stress rule.
		if rfind(word, accent_c) then
			for i = 1, #syllables do
				syllables[i] = rsub(syllables[i], "^(.*)(" .. accent_c .. ")(.*)$",
					function(pre, accent, post) return accent_to_stress_mark[accent] .. pre .. post end
				)
			end
		else
			-- Default stress rule. Words without vowels (e.g. IPA foot boundaries) don't get stress.
			if #syllables > 1 and (rfind(word, "[^" .. vowel .. "nŋs#]#") or rfind(word, C .. "[nŋs]#")) or #syllables == 1 and rfind(word, V) then
				syllables[#syllables] = "ˈ" .. syllables[#syllables]
			elseif #syllables > 1 then
				syllables[#syllables - 1] = "ˈ" .. syllables[#syllables - 1]
			end
		end
	end

	local words = rsplit(text, " ")
	for j, word in ipairs(words) do
		-- accentuation
		local syllables = rsplit(word, "%.")

		if rfind(word, "mEn%.te#") then
			local mente_syllables
			-- Words ends in -mente (converted above to -mênte); add a stress to the preceding portion
			mente_syllables = {}
			mente_syllables[2] = table.remove(syllables)
			mente_syllables[1] = table.remove(syllables)
			accent_word(table.concat(syllables, "."), syllables)
			accent_word(table.concat(mente_syllables, "."), mente_syllables)
			table.insert(syllables, mente_syllables[1])
			table.insert(syllables, mente_syllables[2])
		else
			accent_word(word, syllables)
		end
		
		--if the aperture of the stressed vowel is not given, throw an error
		for i = 1, #syllables do
			if string.find(syllables[i], "ˈ") and (string.find(syllables[i], "e") or string.find(syllables[i], "o")) then
				error("Please specify whether the stressed vowels are close-mid or open-mid (see documentation for details).") 
			end
		end

		--Reduction of word-final vowels
		if not string.find(syllables[#syllables], "ˈ") then
		  syllables[#syllables] = rsub(syllables[#syllables], "a#", "ɐ#")
		  syllables[#syllables] = rsub(syllables[#syllables], "ɛ#", "ɪ#")
		  syllables[#syllables] = rsub(syllables[#syllables], "e#", "ɪ#")
		  syllables[#syllables] = rsub(syllables[#syllables], "ɔ#", "ʊ#")
		  syllables[#syllables] = rsub(syllables[#syllables], "o#", "ʊ#")
		end
		
		-- Reconstruct the word.
		words[j] = table.concat(syllables, ".")
		words[j] = rsub_repeatedly(words[j], "ˈ(.+)ˈ", "ˌ%1ˈ")--make all primary stresses but the last one be secondary
		words[j] = rsub(words[j], "%.(" .. ipa_stress_c .. ")", "%1") -- suppress syllable mark before IPA stress indicator
		
		--determine whether there's an undetermined vowel in the pre-tonic part (exclude monosyllabic unaccented words)
		if string.find(words[j], "ˈ") then
			local extracted = string.match(words[j], "(.*)ˈ") -- take everything before the stressed syllable
			if string.find(extracted, "e") or string.find(extracted, "o") then
				error("Please specify whether the pre-tonic vowels are close-mid or open-mid (see documentation for details).") 
			end
		end
	end

	text = table.concat(words, " ")
	text = rsub(text, "E", "e") --no need for the fake symbols anymore
	text = rsub(text, "O", "o") 
	
	--diphthongs
	text = rsub(text, "([aeɛoɔ])i", "%1j")
	text = rsub(text, "([aeɛo])u", "%1w")
	
	--we will use /wi/ after velar sounds and /uj/ elsewhere
	text = rsub(text, "wi", "uj")
	text = rsub(text, "([kgħ])uj", "%1wi")
	text = rsub(text, "ju", "iw")

	--real sound of seseo Z
	text = rsub(text, "z", "s") 

	--phonetic transcription
	if phonetic then
		--allophones of /a/
		text = rsub(text, "al", "ɑl") --syllable ending in /l/
		text = rsub(text, "aŋ", "ɑŋ") --preceded or followed by /ŋ/ in the same syllable  --
		text = rsub(text, "a" .. TILDE .. "ŋ", "ɑ" .. TILDE .. "ŋ")
		text = rsub(text, "ŋa", "ŋɑ") 
		text = rsub(text, "aw", "ɑw") --in the falling dipthong /aw/
		text = rsub(text, "aˈu", "ɑˈu") --hiatus with /aˈu/
		text = rsub(text, "a%.([oʊ])", "ɑ.%1") --followed by /o/~/ʊ/
		text = rsub(text, "([gk])a", "%1ɑ") --in contact with /k/ or /g/
		text = rsub(text, "a([gk])", "ɑ%1")
		text = rsub(text, "a%.([gk])", "ɑ.%1")
		text = rsub(text, "aˈ([gk])", "ɑˈ%1")
		
		text = rsub(text, "a([ɟʃĉj])", "a̠%1") --before palatal consonants/in a the falling dipthong /aj/
		text = rsub(text, "a%.([ɟʃĉj])", "a̠.%1")
		
		--nasalization between nasal consonants
		text = rsub(text, "([ŋmnɲ])(" .. V .. ")%.([ŋmnɲ])", "%1%2" .. TILDE .. ".%3")
		text = rsub(text, "([ŋmnɲ])(" .. V .. ")ˈ([ŋmnɲ])", "%1%2" .. TILDE .. "ˈ%3")
		text = rsub(text, "([ŋmnɲ])(" .. V .. ")([ŋmnɲ])", "%1%2" .. TILDE .. "%3")
		
		-- θ, s before voiced consonants
		local voiced = "mnɲbdɟgʎ"
		local r = "ɾr"
		local tovoiced = {
			["θ"] = "θ̬",
			["s"] = "z",
		}
		local function voice(sound, following)
			return tovoiced[sound] .. following
		end
		text = rsub(text, "([θs])(" .. separator_c .. "*[" .. voiced .. r .. "])", voice)

		--allophones of /s/
		text = rsub(text, "s([ĉʃ])", "S%1") --fake symbol
		text = rsub(text, "s%.([ĉʃ])", "S.%1")
		text = rsub(text, "z([ɲɟ])", "Z%1") --fake symbol
		text = rsub(text, "z%.([ɲɟ])", "Z.%1")
		
		-- fricative vs. stop allophones; first convert stops to fricatives, then back to stops after nasals and sometimes after l
		local stop_to_fricative = {["b"] = "β", ["d"] = "ð", ["g"] = "ɣ"}
		local fricative_to_stop = {["β"] = "b", ["ð"] = "d", ["ɣ"] = "g"}
		text = rsub(text, "[bdg]", stop_to_fricative)
		text = rsub(text, "([mnɲŋ]" .. separator_c .. "*)([βɣ])",
			function(nasal, fricative) return nasal .. fricative_to_stop[fricative] end
		)
		text = rsub(text, "([lʎmnɲŋ]" .. separator_c .. "*)ð",
			function(nasal_l, fricative) return nasal_l .. "d" end
		)
		text = rsub(text, "(##" .. ipa_stress_c .. "*)([βɣð])",
			function(stress, fricative) return stress .. fricative_to_stop[fricative] end
		)
		
		--plosives before consonants
		text = rsub(text, "([βɣð])%.([smtʃ])", function(fricative, consonant) return fricative_to_stop[fricative] .. "." .. consonant end )

		--/t,d/ are dental
		text = rsub(text, "[td]", {["t"] = "t̪", ["d"] = "d̪"})

		--/s/ and its voiced allophone [z] are usually apico-alveolar in non-seseo dialects
		if distincion then
			text = rsub(text, "[sz]", {["s"] = "s̺", ["z"] = "z̺"})
		end
		
		-- nasal assimilation before consonants
		local labiodental, dental, palatalized =
			"ɱ", "n̪", "nʲ"
		local nasal_assimilation = {
			["f"] = labiodental,
			["t"] = dental, ["d"] = dental,
			["θ"] = dental,
			["ĉ"] = palatalized,
			["ʃ"] = palatalized,
		}
		text = rsub(text, "n(" .. separator_c .. "*)(.)",
			function(stress, following) return (nasal_assimilation[following] or "n") .. stress .. following end
		)

		-- lateral assimilation before consonants
		text = rsub(text, "l(" .. separator_c .. "*)(.)",
			function(stress, following)
				local l = "l"
				if following == "t" or following == "d" or following == "θ" then -- dentialveolar
					l = "l̪"
				elseif following == "ĉ" or following == "ʃ" then -- alveolopalatal
					l = "lʲ"
				elseif following == "k" or following == "ɣ" then -- velarized
					l = "ɫ"
				end
				return l .. stress .. following
			end)
		text = rsub(text, "l#", "ɫ#")
	end
	
	--dialectal gheada
	text = rsub(text, "g", (gheismo and "ħ" or "g"))
	text = rsub(text, "ɣ", (gheismo and "ħ" or "ɣ"))
	if rfind(text, "[gɣħ]") then
		gheada_different = true
	end

	-- convert fake symbols to real ones
	local final_conversions =  {
		["ĉ"] = "t͡ʃ", -- fake "ch" to real "ch"
		["S"] = "sʲ",
		["Z"] = "zʲ",
		["g"] = "ɡ", --non-IPA to IPA
	}
	text = rsub(text, "[ĉSZg]", final_conversions)
	text = rsub(text, "([βðɣ])", "%1̞")    -- voiced fricatives are actually approximants
	
	--don't show vowel reduction in phonemic transcriptions
	if not phonetic then
		text = rsub(text, "ʊ", "o")
		text = rsub(text, "ɪ", "e")	
		text = rsub(text, "ɐ", "a")
	end
	
	-- remove # symbols at word and text boundaries
	text = rsub(text, "#", "")
	text = unfc(text)

	local differences = nil
	if dialect == "Standard" then
		differences = {
			gheada_different = gheada_different,
			need_seseo = need_seseo,
		}
	end
	local ret = {
		text = text,
		differences = differences,
	}
	return ret
end

function export.IPA_string(frame)
	local iparams = {
		[1] = {},
		["style"] = {required = true},
		["phonetic"] = {type = "boolean"},
	}
	local iargs = require("Module:parameters").process(frame.args, iparams)
	local retval = export.IPA(iargs[1], iargs.style, iargs.phonetic)
	return retval.text
end


-- Generate all relevant dialect pronunciations and group into styles. See [[Module:es-pronunc]] for details.
local function express_all_styles(style_spec, dodialect)
	local ret = {
		pronun = {},
		expressed_styles = {},
	}

	local function express_style(hidden_tag, tag, representative_dialect, matching_styles)
		matching_styles = matching_styles or representative_dialect

		-- If style specified, make sure it matches the requested style.
		local style_matches
		if not style_spec then
			style_matches = true
		else
			local style_parts = rsplit(matching_styles, "%-")
			local or_styles = rsplit(style_spec, "%s*,%s*")
			for _, or_style in ipairs(or_styles) do
				local and_styles = rsplit(or_style, "%s*%+%s*")
				local and_matches = true
				for _, and_style in ipairs(and_styles) do
					local negate
					if and_style:find("^%-") then
						and_style = and_style:gsub("^%-", "")
						negate = true
					end
					local this_style_matches = false
					for _, part in ipairs(style_parts) do
						if part == and_style then
							this_style_matches = true
							break
						end
					end
					if negate then
						this_style_matches = not this_style_matches
					end
					if not this_style_matches then
						and_matches = false
					end
				end
				if and_matches then
					style_matches = true
					break
				end
			end
		end
		if not style_matches then
			return
		end

		-- Fetch the representative dialect's pronunciation if not already present.
		if not ret.pronun[representative_dialect] then
			dodialect(ret, representative_dialect)
		end
		-- Insert the new style into the style group, creating the group if necessary.
		local new_style = {
			tag = tag,
			pronun = ret.pronun[representative_dialect],
		}
		for _, hidden_tag_style in ipairs(ret.expressed_styles) do
			if hidden_tag_style.tag == hidden_tag then
				table.insert(hidden_tag_style.styles, new_style)
				return
			end
		end
		table.insert(ret.expressed_styles, {
			tag = hidden_tag,
			styles = {new_style},
		})
	end

	-- For each type of difference, figure out if the difference exists in any of the given respellings.
	dodialect(ret, "Standard")
	local differences = {}
	for _, difftype in ipairs { "need_seseo", "gheada_different" } do
		for _, pronun in ipairs(ret.pronun["Standard"]) do
			if pronun.differences[difftype] then
				differences[difftype] = true
			end
		end
	end
	local need_seseo = differences.need_seseo
	local gheada_different = differences.gheada_different

	-- Now, based on the observed differences, figure out how to combine the individual dialects into styles and
	-- style groups.
	if not gheada_different then
		if not need_seseo then
			express_style(false, false, "Standard")
		else
			express_style(false, "standard", "Standard")
			express_style(false, "seseo", "Seseo")
		end
	else
		if not need_seseo then
			express_style(false, "standard", "Standard")
			express_style(false, "gheada", "Gheada")
		else
			express_style(false, "standard", "Standard")
			express_style(false, "gheada", "Gheada")
			express_style(false, "gheada and seseo", "Gheada-seseo")
		end
	end

	return ret
end


local function format_all_styles(expressed_styles, format_style, width)
	for i, style_group in ipairs(expressed_styles) do
		if #style_group.styles == 1 then
			style_group.formatted, style_group.formatted_len =
				format_style(style_group.styles[1].tag, style_group.styles[1], i == 1)
		else
			style_group.formatted, style_group.formatted_len =
				format_style(style_group.tag, style_group.styles[1], i == 1)
			for j, style in ipairs(style_group.styles) do
				style.formatted, style.formatted_len =
					format_style(style.tag, style, i == 1 and j == 1)
			end
		end
	end

	local maxlen = 0
	for i, style_group in ipairs(expressed_styles) do
		local this_len = style_group.formatted_len
		if #style_group.styles > 1 then
			for _, style in ipairs(style_group.styles) do
				this_len = math.max(this_len, style.formatted_len)
			end
		end
		maxlen = math.max(maxlen, this_len)
	end

	local lines = {}

	local need_major_hack = false
	for i, style_group in ipairs(expressed_styles) do
		if #style_group.styles == 1 then
			table.insert(lines, style_group.formatted)
			need_major_hack = false
		else
			local inline = '\n<div class="vsShow" style="display:none">\n' .. style_group.formatted .. "</div>"
			local full_prons = {}
			for _, style in ipairs(style_group.styles) do
				table.insert(full_prons, style.formatted)
			end
			local full = '\n<div class="vsHide">\n' .. table.concat(full_prons, "\n") .. "</div>"
			local em_length = math.floor(maxlen * width) --this allows us to have a different coefficient in IPA transcriptions and rhymes
			table.insert(lines, '<div class="vsSwitcher" data-toggle-category="pronunciations" style="width: ' .. em_length .. 'em; max-width:100%;"><span class="vsToggleElement" style="float: right;">&nbsp;</span>' .. inline .. full .. "</div>")
			need_major_hack = true
		end
	end

	-- major hack to get bullets working on the next line after a div box
	return table.concat(lines, "\n") .. (need_major_hack and "\n<span></span>" or "")
end


local function dodialect_pronun(args, ret, dialect)
	ret.pronun[dialect] = {}
	for i, term in ipairs(args.terms) do
		local phonemic, phonetic, differences
		if term.raw then
			phonemic = term.raw_phonemic
			phonetic = term.raw_phonetic
			differences = construct_default_differences(dialect)
		else
			phonemic = export.IPA(term.term, dialect, false)
			phonetic = export.IPA(term.term, dialect, true)
			differences = phonemic.differences
			phonemic = phonemic.text
			phonetic = phonetic.text
		end
		local refs
		if not term.ref then
			refs = nil
		else
			refs = {}
			for _, refspec in ipairs(term.ref) do
				local this_refs = require("Module:references").parse_references(refspec)
				for _, this_ref in ipairs(this_refs) do
					table.insert(refs, this_ref)
				end
			end
		end

		ret.pronun[dialect][i] = {
			raw = term.raw,
			phonemic = phonemic,
			phonetic = phonetic,
			refs = refs,
			q = term.q,
			qq = term.qq,
			a = term.a,
			aa = term.aa,
			differences = differences,
		}
	end
end

local function generate_pronun(args)
	local function this_dodialect_pronun(ret, dialect)
		dodialect_pronun(args, ret, dialect)
	end

	local ret = express_all_styles(args.style, this_dodialect_pronun)

	local function format_style(tag, expressed_style, is_first)
		local pronunciations = {}
		local formatted_pronuns = {}

		local function ins(formatted_part)
			table.insert(formatted_pronuns, formatted_part)
		end

		-- Loop through each pronunciation. For each one, add the phonemic and phonetic versions to `pronunciations`,
		-- for formatting by [[Module:IPA]], and also create an approximation of the formatted version so that we can
		-- compute the appropriate width of the HTML switcher div box that holds the different per-dialect variants.
		for j, pronun in ipairs(expressed_style.pronun) do
			-- Add tag to left qualifiers if first one
			-- FIXME: Consider using accent qualifier for the tag instead.
			local qs = pronun.q
			if j == 1 and tag then
				if qs then
					qs = m_table.deepcopy(qs)
					table.insert(qs, tag)
				else
					qs = {tag}
				end
			end

			local first_pronun = #pronunciations + 1

			if not pronun.phonemic and not pronun.phonetic then
				error("Internal error: Saw neither phonemic nor phonetic pronunciation")
			end

			if pronun.phonemic then -- missing if 'raw:[...]' given
				-- don't display syllable division markers in phonemic
				local slash_pron = "/" .. pronun.phonemic:gsub("%.", "") .. "/"
				table.insert(pronunciations, {
					pron = slash_pron,
				})
				ins(slash_pron)
			end

			if pronun.phonetic then -- missing if 'raw:/.../' given
				local bracket_pron = "[" .. pronun.phonetic .. "]"
				table.insert(pronunciations, {
					pron = bracket_pron,
				})
				ins(bracket_pron)
			end

			local last_pronun = #pronunciations

			if qs then
				pronunciations[first_pronun].q = qs
			end
			if pronun.a then
				pronunciations[first_pronun].a = pronun.a
			end
			if j > 1 then
				pronunciations[first_pronun].separator = ", "
				ins(", ")
			end
			if pronun.qq then
				pronunciations[last_pronun].qq = pronun.qq
			end
			if pronun.aa then
				pronunciations[last_pronun].aa = pronun.aa
			end
			if qs or pronun.qq or pronun.a or pronun.aa then
				-- Note: This inserts the actual formatted qualifier text, including HTML and such, but the later call
				-- to textual_len() removes all HTML and reduces links.
				ins(require("Module:pron qualifier").format_qualifiers {
					lang = lang,
					text = "",
					q = qs,
					qq = pronun.qq,
					a = pronun.a,
					aa = pronun.aa,
				})
			end

			if pronun.refs then
				pronunciations[last_pronun].refs = pronun.refs
				-- Approximate the reference using a footnote notation. This will be slightly inaccurate if there are
				-- more than nine references but that is rare.
				ins(string.rep("[1]", #pronun.refs))
			end
			if first_pronun ~= last_pronun then
				pronunciations[last_pronun].separator = " "
				ins(" ")
			end
		end

		local bullet = string.rep("*", args.bullets) .. " "
		-- Here we construct the formatted line in `formatted`, and also try to construct the equivalent without HTML
		-- and wiki markup in `formatted_for_len`, so we can compute the approximate textual length for use in sizing
		-- the toggle box with the "more" button on the right.
		local pre = is_first and args.pre and args.pre .. " " or ""
		local post = is_first and args.post and " " .. args.post or ""
		local formatted = bullet .. pre .. m_IPA.format_IPA_full { lang = lang, items = pronunciations, separator = "" } .. post
		local formatted_for_len = bullet .. pre .. "IPA(key): " .. table.concat(formatted_pronuns) .. post
		return formatted, textual_len(formatted_for_len)
	end

	ret.text = format_all_styles(ret.expressed_styles, format_style, 0.55)

	return ret
end


local function parse_respelling(respelling, pagename, parse_err)
	local raw_respelling = respelling:match("^raw:(.*)$")
	if raw_respelling then
		local raw_phonemic, raw_phonetic = raw_respelling:match("^/(.*)/ %[(.*)%]$")
		if not raw_phonemic then
			raw_phonemic = raw_respelling:match("^/(.*)/$")
		end
		if not raw_phonemic then
			raw_phonetic = raw_respelling:match("^%[(.*)%]$")
		end
		if not raw_phonemic and not raw_phonetic then
			parse_err(("Unable to parse raw respelling '%s', should be one of /.../, [...] or /.../ [...]")
				:format(raw_respelling))
		end
		return {
			raw = true,
			raw_phonemic = raw_phonemic,
			raw_phonetic = raw_phonetic,
		}
	end
	if respelling == "+" then
		respelling = pagename
	end
	return {term = respelling}
end

-- Return the number of syllables of a phonemic representation, which should have syllable dividers in it but no hyphens.
local function get_num_syl_from_phonemic(phonemic)
	-- Maybe we should just count vowels instead of the below code.
	phonemic = rsub(phonemic, "|", " ") -- remove IPA foot boundaries
	local words = rsplit(phonemic, " +")
	for i, word in ipairs(words) do
		-- IPA stress marks are syllable divisions if between characters; otherwise just remove.
		word = rsub(word, "(.)[ˌˈ](.)", "%1.%2")
		word = rsub(word, "[ˌˈ]", "")
		words[i] = word
	end
	-- There should be a syllable boundary between words.
	phonemic = table.concat(words, ".")
	return ulen(rsub(phonemic, "[^.]", "")) + 1
end


-- Get the rhyme by truncating everything up through the last stress mark + any following consonants, and remove
-- syllable boundary markers.
local function convert_phonemic_to_rhyme(phonemic)
	return rsub(rsub(phonemic, ".*[ˌˈ]", ""), "^[^" .. vowel .. "]*", ""):gsub("%.", ""):gsub("t͡ʃ", "tʃ")
end


local function split_syllabified_spelling(spelling)
	return rsplit(spelling, "%.")
end


-- "Align" syllabification to original spelling by matching character-by-character, allowing for extra syllable and
-- accent markers in the syllabification. If we encounter an extra syllable marker (.), we allow and keep it. If we
-- encounter an extra accent marker in the syllabification, we drop it. In any other case, we return nil indicating
-- the alignment failed.
local function align_syllabification_to_spelling(syllab, spelling)
	local result = {}
	local syll_chars = rsplit(decompose(syllab), "")
	local spelling_chars = rsplit(decompose(spelling), "")
	local i = 1
	local j = 1
	while i <= #syll_chars or j <= #spelling_chars do
		local ci = syll_chars[i]
		local cj = spelling_chars[j]
		if ci == cj then
			table.insert(result, ci)
			i = i + 1
			j = j + 1
		elseif ci == "." then
			table.insert(result, ci)
			i = i + 1
		elseif ci == AC or ci == GR or ci == CARO then
			-- skip character
			i = i + 1
		else
			-- non-matching character
			return nil
		end
	end
	if i <= #syll_chars or j <= #spelling_chars then
		-- left-over characters on one side or the other
		return nil
	end
	return unfc(table.concat(result))
end

-- Word should already be decomposed.
local function word_has_vowels(word)
	return rfind(word, V)
end


local function all_words_have_vowels(term)
	local words = rsplit(decompose(term), "[ %-]")
	for i, word in ipairs(words) do
		-- Allow empty word; this occurs with prefixes and suffixes.
		if word ~= "" and not word_has_vowels(word) then
			return false
		end
	end
	return true
end


local function should_generate_rhyme_from_respelling(term)
	local words = rsplit(decompose(term), " +")
	return #words == 1 and -- no if multiple words
		not words[1]:find(".%-.") and -- no if word is composed of hyphenated parts (e.g. [[Austria-Hungría]])
		not words[1]:find("%-$") and -- no if word is a prefix
		not (words[1]:find("^%-") and words[1]:find(CARO)) and -- no if word is an unstressed suffix
		word_has_vowels(words[1]) -- no if word has no vowels (e.g. a single letter)
end


local function should_generate_rhyme_from_ipa(ipa)
	return not ipa:find("%s") and word_has_vowels(decompose(ipa))
end


local function dodialect_specified_rhymes(rhymes, parsed_respellings, rhyme_ret, dialect)
	rhyme_ret.pronun[dialect] = {}
	for _, rhyme in ipairs(rhymes) do
		local num_syl = rhyme.num_syl
		local no_num_syl = false

		-- If user explicitly gave the rhyme but didn't explicitly specify the number of syllables and term is single-word, try to take the number of syllables from the phonemic.
		if not no_num_syl and not num_syl then
			for _, parsed in ipairs(parsed_respellings) do
				for dialect, pronun in pairs(parsed.pronun.pronun[dialect]) do
					-- Check that pronun.phonemic exists (it may not if raw phonetic-only pronun is given).
					if pronun.phonemic then
						if not should_generate_rhyme_from_ipa(pronun.phonemic) then
							no_num_syl = true
							break
						end
						-- Count number of syllables by looking at syllable boundaries (including stress marks).
						local this_num_syl = get_num_syl_from_phonemic(pronun.phonemic)
						m_table.insertIfNot(num_syl, this_num_syl)
					end
				end
				if no_num_syl then
					break
				end
			end
			if no_num_syl or #num_syl == 0 then
				num_syl = nil
			end
		end

		table.insert(rhyme_ret.pronun[dialect], {
			rhyme = rhyme.rhyme,
			num_syl = num_syl,
			qualifiers = rhyme.qualifiers,
			differences = construct_default_differences(dialect),
		})
	end
end


local function parse_pron_modifier(arg, parse_err, generate_obj, param_mods, no_split_on_comma)
	local retval = {}

	if arg:find("<") then
		local insert = { store = "insert" }
		param_mods.q = insert
		param_mods.qq = insert
		param_mods.a = insert
		param_mods.aa = insert
		return require(put_module).parse_inline_modifiers(arg, {
			param_mods = param_mods,
			generate_obj = generate_obj,
			parse_err = parse_err,
			splitchar = not no_split_on_comma and "," or nil,
		})
	elseif no_split_on_comma then
		table.insert(retval, generate_obj(arg))
	else
		for _, term in ipairs(split_on_comma(arg)) do
			table.insert(retval, generate_obj(term))
		end
	end

	return retval
end


local function parse_rhyme(arg, parse_err)
	local function generate_obj(term)
		return {rhyme = term}
	end
	local param_mods = {
		s = {
			item_dest = "num_syl",
			convert = function(arg, parse_err)
				local nsyls = rsplit(arg, ",")
				for i, nsyl in ipairs(nsyls) do
					if not nsyl:find("^[0-9]+$") then
						parse_err("Number of syllables '" .. nsyl .. "' should be numeric")
					end
					nsyls[i] = tonumber(nsyl)
				end
				return nsyls
			end,
		},
	}

	return parse_pron_modifier(arg, parse_err, generate_obj, param_mods)
end

local function parse_homophone(arg, parse_err)
	local function generate_obj(term)
		return {term = term}
	end
	local param_mods = {
		t = {
			-- We need to store the <t:...> inline modifier into the "gloss" key of the parsed term,
			-- because that is what [[Module:links]] (called from [[Module:homophones]]) expects.
			item_dest = "gloss",
		},
		gloss = {},
		pos = {},
		alt = {},
		lit = {},
		id = {},
		g = {
			-- We need to store the <g:...> inline modifier into the "genders" key of the parsed term,
			-- because that is what [[Module:links]] (called from [[Module:homophones]]) expects.
			item_dest = "genders",
			convert = function(arg)
				return rsplit(arg, ",")
			end,
		},
	}

	return parse_pron_modifier(arg, parse_err, generate_obj, param_mods)
end


local function generate_audio_obj(arg)
	local file, gloss
	if arg:find("#") then
		file, gloss = arg:match("^(.-)%s*#%s*(.*)$")
	else
		file, gloss = arg:match("^(.-)%s*;%s*(.*)$")
	end
	if not file then
		file = arg
		gloss = "Audio"
	end
	return {file = file, gloss = gloss}
end


local function parse_audio(arg, parse_err)
	-- None other than qualifiers
	local param_mods = {}

	-- Don't split on comma because some filenames have embedded commas not followed by a space
	-- (typically followed by an underscore).
	return parse_pron_modifier(arg, parse_err, generate_audio_obj, param_mods, "no split on comma")
end


-- External entry point for {{es-pr}}.
function export.show_pr(frame)
	local params = {
		[1] = {list = true},
		["rhyme"] = {},
		["hmp"] = {},
		["audio"] = {list = true},
		["pagename"] = {},
	}
	local parargs = frame:getParent().args
	local args = require("Module:parameters").process(parargs, params)
	local pagename = args.pagename or mw.title.getCurrentTitle().subpageText

	-- Parse the arguments.
	local respellings = #args[1] > 0 and args[1] or {"+"}
	local parsed_respellings = {}
	local function overall_parse_err(msg, arg, val)
		error(msg .. ": " .. arg .. "=" .. val)
	end
	local overall_rhyme = args.rhyme and
		parse_rhyme(args.rhyme, function(msg) overall_parse_err(msg, "rhyme", args.rhyme) end) or nil
	local overall_hmp = args.hmp and
		parse_homophone(args.hmp, function(msg) overall_parse_err(msg, "hmp", args.hmp) end) or nil
	local overall_audio
	if args.audio then
		overall_audio = {}
		for _, audio in ipairs(args.audio) do
			local parsed_audio = parse_audio(audio, function(msg) overall_parse_err(msg, "audio", audio) end)
			if #parsed_audio > 1 then
				error("Internal error: Saw more than one object returned from parse_audio")
			end
			table.insert(overall_audio, parsed_audio[1])
		end
	end
	for i, respelling in ipairs(respellings) do
		if respelling:find("<") then
			local param_mods = {
				pre = { overall = true },
				post = { overall = true },
				style = { overall = true },
				bullets = {
					overall = true,
					convert = function(arg, parse_err)
						if not arg:find("^[0-9]+$") then
							parse_err("Modifier 'bullets' should have a number as argument, but saw '" .. arg .. "'")
						end
						return tonumber(arg)
					end,
				},
				rhyme = {
					overall = true,
					store = "insert-flattened",
					convert = parse_rhyme,
				},
				hmp = {
					overall = true,
					store = "insert-flattened",
					convert = parse_homophone,
				},
				audio = {
					overall = true,
					store = "insert-flattened",
					convert = parse_audio,
				},
				ref = { store = "insert" },
				q = { store = "insert" },
				qq = { store = "insert" },
				a = { store = "insert" },
				aa = { store = "insert" },
			}

			local parsed = require(put_module).parse_inline_modifiers(respelling, {
				paramname = i,
				param_mods = param_mods,
				generate_obj = function(term, parse_err)
					return parse_respelling(term, pagename, parse_err)
				end,
				splitchar = ",",
				outer_container = {
					audio = {}, rhyme = {}, hmp = {}
				}
			})
			if not parsed.bullets then
				parsed.bullets = 1
			end
			table.insert(parsed_respellings, parsed)
		else
			local termobjs = {}
			local function parse_err(msg)
				error(msg .. ": " .. i .. "=" .. respelling)
			end
			for _, term in ipairs(split_on_comma(respelling)) do
				table.insert(termobjs, parse_respelling(term, pagename, parse_err))
			end
			table.insert(parsed_respellings, {
				terms = termobjs,
				audio = {},
				rhyme = {},
				hmp = {},
				bullets = 1,
			})
		end
	end

	-- Loop over individual respellings, processing each.
	for _, parsed in ipairs(parsed_respellings) do
		parsed.pronun = generate_pronun(parsed)
		local no_auto_rhyme = false
		for _, term in ipairs(parsed.terms) do
			if term.raw then
				if not should_generate_rhyme_from_ipa(term.raw_phonemic or term.raw_phonetic) then
					no_auto_rhyme = true
					break
				end
			elseif not should_generate_rhyme_from_respelling(term.term) then
				no_auto_rhyme = true
				break
			end
		end

		-- Generate the rhymes.
		local function dodialect_rhymes_from_pronun(rhyme_ret, dialect)
			rhyme_ret.pronun[dialect] = {}

			if not parsed.pronun.pronun[dialect] then
				dodialect_pronun(parsed, parsed.pronun, dialect)
			end
			for _, pronun in ipairs(parsed.pronun.pronun[dialect]) do
				-- We should have already excluded multiword terms and terms without vowels from rhyme generation (see
				-- `no_auto_rhyme` below). But make sure to check that pronun.phonemic exists (it may not if raw
				-- phonetic-only pronun is given).
				if pronun.phonemic then
					-- Count number of syllables by looking at syllable boundaries (including stress marks).
					local num_syl = get_num_syl_from_phonemic(pronun.phonemic)
					-- Get the rhyme by truncating everything up through the last stress mark + any following
					-- consonants, and remove syllable boundary markers.
					local rhyme = convert_phonemic_to_rhyme(pronun.phonemic)
					local saw_already = false
					for _, existing in ipairs(rhyme_ret.pronun[dialect]) do
						if existing.rhyme == rhyme then
							saw_already = true
							-- We already saw this rhyme but possibly with a different number of syllables,
							-- e.g. if the user specified two pronunciations 'biología' (4 syllables) and
							-- 'bi.ología' (5 syllables), both of which have the same rhyme /ia/.
							m_table.insertIfNot(existing.num_syl, num_syl)
							break
						end
					end
					if not saw_already then
						local rhyme_diffs = nil
						if dialect == "Standard" then
							rhyme_diffs = {}
							if rhyme:find("θ") then
								rhyme_diffs.need_seseo = true
							end
							if rhyme:find("ɡ") then
								rhyme_diffs.gheada_different = true
							end
						end
						table.insert(rhyme_ret.pronun[dialect], {
							rhyme = rhyme,
							num_syl = {num_syl},
							differences = rhyme_diffs,
						})
					end
				end
			end
		end

		if #parsed.rhyme == 0 then
			if overall_rhyme or no_auto_rhyme then
				parsed.rhyme = nil
			else
				parsed.rhyme = express_all_styles(parsed.style, dodialect_rhymes_from_pronun)
			end
		else
			local no_rhyme = false
			for _, rhyme in ipairs(parsed.rhyme) do
				if rhyme.rhyme == "-" then
					no_rhyme = true
					break
				end
			end
			if no_rhyme then
				parsed.rhyme = nil
			else
				local function this_dodialect(rhyme_ret, dialect)
					return dodialect_specified_rhymes(parsed.rhyme, {parsed}, rhyme_ret, dialect)
				end
				parsed.rhyme = express_all_styles(parsed.style, this_dodialect)
			end
		end
	end

	if overall_rhyme then
		local no_overall_rhyme = false
		for _, orhyme in ipairs(overall_rhyme) do
			if orhyme.rhyme == "-" then
				no_overall_rhyme = true
				break
			end
		end
		if no_overall_rhyme then
			overall_rhyme = nil
		else
			local function dodialect_overall_rhyme(rhyme_ret, dialect)
				return dodialect_specified_rhymes(overall_rhyme, parsed_respellings, rhyme_ret, dialect)
			end
			overall_rhyme = express_all_styles(parsed.style, dodialect_overall_rhyme)
		end
	end

	-- If all sets of pronunciations have the same rhymes, display them only once at the bottom.
	-- Otherwise, display rhymes beneath each set, indented.
	local first_rhyme_ret
	local all_rhyme_sets_eq = true
	for j, parsed in ipairs(parsed_respellings) do
		if j == 1 then
			first_rhyme_ret = parsed.rhyme
		elseif not m_table.deepEquals(first_rhyme_ret, parsed.rhyme) then
			all_rhyme_sets_eq = false
			break
		end
	end

	local function format_rhyme(rhyme_ret, num_bullets)
		local function format_rhyme_style(tag, expressed_style, is_first)
			local pronunciations = {}
			local rhymes = {}
			for _, pronun in ipairs(expressed_style.pronun) do
				table.insert(rhymes, pronun)
			end
			local data = {
				lang = lang,
				rhymes = rhymes,
				qualifiers = tag and {tag} or nil,
				force_cat = force_cat,
			}
			local bullet = string.rep("*", num_bullets) .. " "
			local formatted = bullet .. require("Module:rhymes").format_rhymes(data)
			local formatted_for_len_parts = {}
			table.insert(formatted_for_len_parts, bullet .. "Rhymes: " .. (tag and "(" .. tag .. ") " or ""))
			for j, pronun in ipairs(expressed_style.pronun) do
				if j > 1 then
					table.insert(formatted_for_len_parts, ", ")
				end
				if pronun.qualifiers then
					table.insert(formatted_for_len_parts, "(" .. table.concat(pronun.qualifiers, ", ") .. ") ")
				end
				table.insert(formatted_for_len_parts, "-" .. pronun.rhyme)
			end
			return formatted, textual_len(table.concat(formatted_for_len_parts))
		end

		return format_all_styles(rhyme_ret.expressed_styles, format_rhyme_style, 0.75)
	end

	-- If all sets of pronunciations have the same homophones, display them only once at the bottom.
	-- Otherwise, display homophones beneath each set, indented.
	local first_hmps
	local all_hmp_sets_eq = true
	for j, parsed in ipairs(parsed_respellings) do
		if j == 1 then
			first_hmps = parsed.hmp
		elseif not m_table.deepEquals(first_hmps, parsed.hmp) then
			all_hmp_sets_eq = false
			break
		end
	end

	local function format_homophones(hmps, num_bullets)
		local hmptext = require("Module:homophones").format_homophones { lang = lang, homophones = hmps }
		return string.rep("*", num_bullets) .. " " .. hmptext
	end

	local function format_audio(audios, num_bullets)
		local ret = {}
		for i, audio in ipairs(audios) do
			local text = require(audio_module).format_audio {
				lang = lang,
				file = audio.file,
				caption = audio.gloss,
				q = audio.q,
				qq = audio.qq,
				a = audio.a,
				aa = audio.aa,
			}
			table.insert(ret, string.rep("*", num_bullets) .. " " .. text)
		end
		return table.concat(ret, "\n")
	end

	local textparts = {}
	local min_num_bullets = 9999
	for j, parsed in ipairs(parsed_respellings) do
		if parsed.bullets < min_num_bullets then
			min_num_bullets = parsed.bullets
		end
		if j > 1 then
			table.insert(textparts, "\n")
		end
		table.insert(textparts, parsed.pronun.text)
		if #parsed.audio > 0 then
			table.insert(textparts, "\n")
			-- If only one pronunciation set, add the audio with the same number of bullets, otherwise
			-- indent audio by one more bullet.
			table.insert(textparts, format_audio(parsed.audio,
				#parsed_respellings == 1 and parsed.bullets or parsed.bullets + 1))
		end
		if not all_rhyme_sets_eq and parsed.rhyme then
			table.insert(textparts, "\n")
			table.insert(textparts, format_rhyme(parsed.rhyme, parsed.bullets + 1))
		end
		if not all_hmp_sets_eq and #parsed.hmp > 0 then
			table.insert(textparts, "\n")
			table.insert(textparts, format_homophones(parsed.hmp, parsed.bullets + 1))
		end
	end
	if overall_audio and #overall_audio > 0 then
		table.insert(textparts, "\n")
		table.insert(textparts, format_audio(overall_audio, min_num_bullets))
	end
	if all_rhyme_sets_eq and first_rhyme_ret then
		table.insert(textparts, "\n")
		table.insert(textparts, format_rhyme(first_rhyme_ret, min_num_bullets))
	end
	if overall_rhyme then
		table.insert(textparts, "\n")
		table.insert(textparts, format_rhyme(overall_rhyme, min_num_bullets))
	end
	if all_hmp_sets_eq and #first_hmps > 0 then
		table.insert(textparts, "\n")
		table.insert(textparts, format_homophones(first_hmps, min_num_bullets))
	end
	if overall_hmp and #overall_hmp > 0 then
		table.insert(textparts, "\n")
		table.insert(textparts, format_homophones(overall_hmp, min_num_bullets))
	end

	return table.concat(textparts)
end

return export