Module:HelperStrConverter

From MaRDI portal

Documentation for this module may be created at Module:HelperStrConverter/doc

------------------------------------------------------------------------------------
--                                 HelperStrConverter                             --
--                                                                                --
-- This module includes a number of helper functions for dealing with             --
-- String conversions.                                                            --
------------------------------------------------------------------------------------


local M = {}

local supers = {
	["0"]="⁰",["1"]="¹",["2"]="²",["3"]="³",["4"]="⁴",
	["5"]="⁵",["6"]="⁶",["7"]="⁷",["8"]="⁸",["9"]="⁹",
	["n"]="ⁿ",["k"]="ᵏ",["i"]="ⁱ",["j"]="ʲ",["m"]="ᵐ"
}

local subs = {
	["0"]="₀",["1"]="₁",["2"]="₂",["3"]="₃",["4"]="₄",
	["5"]="₅",["6"]="₆",["7"]="₇",["8"]="₈",["9"]="₉"
}

local function to_super(s)
	return (s:gsub(".", function(c) return supers[c] or c end))
end

local function to_sub(s)
	return (s:gsub(".", function(c) return subs[c] or c end))
end

local function strip_latex(s)
	s = s:gsub("\\%a+%b{}", function(cmd)
		return cmd:match("{(.*)}")
	end)

	s = s:gsub("\\%a+", "")

	s = s:gsub("[{}]", "")

	s = s:gsub("(%a)_(%d+)", function(base, sub)
		return base .. to_sub(sub)
	end)

	s = s:gsub("%s+", " ")

	return s
end

local function convert_exponents(txt)
	txt = txt:gsub("(%d)%^{(%w+)}", function(base, exp)
		return base .. to_super(exp)
	end)

	txt = txt:gsub("(%d)%^(%w+)", function(base, exp)
		return base .. to_super(exp)
	end)

	return txt
end

local function convert_subscripts(txt)
	txt = txt:gsub("(%a)_(%d+)", function(base, sub)
		return base .. to_sub(sub)
	end)

	return txt
end

function M.cleanTitle(frame)
	local text = frame.args[1] or ""
	if type(text) ~= "string" then text = tostring(text) end

	text = text:gsub("%$(.-)%$", function(tex)
		local base, exp = tex:match("^(%a)%^(%d)$")
		if base and exp and supers[exp] then
			return base .. supers[exp]
		end
		return tex
	end)

	text = text:gsub("\\%((.-)\\%)", function(inner)
		return strip_latex(inner)
	end)

	text = text:gsub("\\%[(.-)\\%]", function(inner)
		return strip_latex(inner)
	end)

	text = convert_exponents(text)
	text = convert_subscripts(text)

	text = text:gsub("%s+", " "):gsub("^%s*(.-)%s*$", "%1")
	return text
end



return M