module Asciimath2UnitsML class Conv def multiplier(x) case x when :space { html: " ", mathml: "" } when :nospace { html: "", mathml: "" } else { html: HTMLEntities.new.encode(x), mathml: "#{HTMLEntities.new.encode(x)}" } end end def render(unit, style) @symbols[unit][style] || unit end def htmlent(x) HTMLEntities.new.decode(x).split(/([<>&])/) .map { |c| /[<>'"]/.match(c) ? c : HTMLEntities.new.encode(c, :hexadecimal) }.join end def htmlsymbol(units, normalise) units.map do |u| if u[:multiplier] then u[:multiplier] == "*" ? @multiplier[:html] : u[:multiplier] elsif u[:unit].nil? && u[:prefix] @prefixes[u[:prefix]].html else base = (u[:prefix] || "") + render(normalise ? @units[u[:unit]].symbolid : u[:unit], :html) htmlsymbol_exponent(u, base) end end.join("") end def htmlsymbol_exponent(u, base) if u[:display_exponent] == "0.5" base = "√#{base}" elsif u[:display_exponent] exp = "#{u[:display_exponent].sub(/-/, "−")}" base += exp end base end def mathmlsymbol(units, normalise, multiplier = nil) multiplier = multiplier ? "#{multiplier}" : @multiplier[:mathml] exp = units.map do |u| if u[:multiplier] then u[:multiplier] == "*" ? multiplier : "#{u[:multiplier]}" elsif u[:unit].nil? && u[:prefix] %(#{htmlent(@prefixes[u[:prefix]].html)}) else mathmlsymbol1(u, normalise) end end.join("") end def mathmlsymbol1(u, normalise) base = render(normalise ? @units[u[:unit]].symbolid : u[:unit], :mathml) if u[:prefix] prefix = htmlent(@prefixes[u[:prefix]].html) base = base.match(//) ? base.sub(//, "#{prefix}") : "#{prefix}#{base}" end mathmlsymbol_exponent(u, base) end def mathmlsymbol_exponent(u, base) if u[:display_exponent] == "0.5" base = "#{base}" elsif u[:display_exponent] exp = "#{u[:display_exponent]}".sub(/-/, "") base = "#{base}#{exp}" end base end def mathmlsymbolwrap(units, normalise) <<~END #{mathmlsymbol(units, normalise)} END end end end