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