require "asciimath"
require "nokogiri"
require "htmlentities"
require "yaml"
require "rsec"
require_relative "string"
require_relative "parse"
module Asciimath2UnitsML
MATHML_NS = "http://www.w3.org/1998/Math/MathML".freeze
UNITSML_NS = "http://unitsml.nist.gov/2005".freeze
class Conv
def initialize
@prefixes_id = read_yaml("../unitsdb/prefixes.yaml")
@prefixes = flip_name_and_id(@prefixes_id)
@quantities = read_yaml("../unitsdb/quantities.yaml")
@units_id = read_yaml("../unitsdb/units.yaml")
@units = flip_name_and_id(@units_id)
@parser = parser
end
# https://www.w3.org/TR/mathml-units/ section 2: delimit number Invisible-Times unit
def Asciimath2UnitsML(expression)
xml = Nokogiri::XML(asciimath2mathml(expression))
MathML2UnitsML(xml).to_xml
end
def MathML2UnitsML(xml)
xml.xpath(".//m:mtext", "m" => MATHML_NS).each do |x|
next unless %r{^unitsml\(.+\)$}.match(x.text)
text = x.text.sub(%r{^unitsml\((.+)\)$}m, "\\1")
units = parse(text)
delim = x&.previous_element&.name == "mn" ? "" : ""
x.replace("#{delim}#{mathmlsymbol(units)}\n#{unitsml(units, text)}")
end
xml
end
def asciimath2mathml(expression)
AsciiMath::MathMLBuilder.new(:msword => true).append_expression(
AsciiMath.parse(HTMLEntities.new.decode(expression)).ast).to_s.
gsub(/