Jump to content

Module:IPA

Permanently protected module
From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Erutuon (talk | contribs) at 23:36, 22 June 2017 (better way to do it, borrowed from wikt:Module:script utilities, where it is used to insert line breaks into Mongolian text...). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

local p = {}

local match = mw.ustring.match
local gsub = mw.ustring.gsub
local U = mw.ustring.char

local function IPAspan(text)
	return
		'<span title="Representation in the International Phonetic Alphabet (IPA)" class="IPA">' ..
		text ..
		'</span>'
end

local function ine(text)
	if text == "" then
		return nil
	else
		return text
	end
end

function p.tag(frame)
	local linkHelpPage = require('Module:Yesno')(frame.args.link, false)
	
	local args = frame:getParent().args[1] and frame:getParent().args
		or frame.args
	local namespace = mw.title.getCurrentTitle().nsText
	
	local text, lang
	
	local err = {}
	local IPApage
	
	if linkHelpPage then
		text = ine(args[2])
		lang = ine(args[1])
	
		if lang then
			IPApage = mw.loadData("Module:IPA/data")[lang]
			
			if not IPApage then 
				table.insert(err, "[No IPA key for the language code " .. lang.."]")
			end
		else
			table.insert(err, "[language code?]")
		end
	else
		text = ine(args[1])
	end
	
	local output = ""
	
	if text then
		-- Replaces regular g with IPA g.
		local function IPAg(text)
			return gsub(text, U(0x67), U(0x261))
		end
		
		if match(text, "%[%[") then
			--[[	First, escape targets of wikilinks,
					replacing them with sequences $1, $2, ... .		]]
			local escaped = {}
			
			local i = 1
			for link_target in mw.ustring.gmatch(text, "%[%[([^|]+|)") do
				escaped[i] = link_target
				text = mw.ustring.gsub(text, link_target, "$" .. i)
				i = i + 1
			end
			
			text = IPAg(text)
		
			-- Unescape targets of wikilinks.
			text = mw.ustring.gsub(
				text,
				"$(%d)",
				function(a)
					a = tonumber(a)
					return escaped[a]
				end
			)
		else
			text = IPAg(text)
		end
		
		text = IPAspan(text)
	
		if IPApage then
			output = "[[" .. IPApage .. "|" .. text .. "]]"
		elseif text then
			output = text
		end
	else
		table.insert(err, "[IPA symbols?]")
	end
	
	if #err > 0 then
		err = "<sup>" .. table.concat(err) .. "</sup>"
	else
		err = ""
	end
	
	-- Makes the error message show only in preview mode.
	if frame:preprocess("{{REVISIONID}}") == "" then
		output = output .. err
	end
	
	return output
end

return p