MathML도 tex4ht의 LaTeX 코딩이 필요합니다.

Oct 09 2020

아래 파일을 MathML형식으로 변환하고 Semantic 태그 의 LaTeX코딩이 필요합니다 MathML.

MWE :

\documentclass{article}
\usepackage[T1]{fontenc}

\begin{document}

\article{Article Title Here}
\author{Author Name Here}
\maketitle

\section{Introduction}

This is the sample paragraph.
 \begin{equation}\label{eq1-11}
T\,^{\prime}_{\mu \nu} = \left( \frac{\partial \xi^\alpha} {\partial\xi^{\prime\mu}}\right) \left( \frac{\partial \xi^\beta}{\partial \xi^{\prime\nu}} \right) T_{\alpha \beta}
\end{equation}

Please refer the equations \ref{eq1-11} for the further testing.
\end{document}

답변

1 michal.h21 Oct 11 2020 at 19:43

이를 달성하는 방법은 여러 가지가 있습니다.

  1. 모든 수학 콘텐츠를 포착하도록 TeX4ht를 구성하고 두 번 조판합니다. 한 번은 MathML을 사용하고 두 번째는 축어 텍스트로 사용합니다.
  2. MathML 콘텐츠를 구문 분석하고 LaTeX 코드로 다시 변환
  3. 입력 TeX 파일을 사전 처리하고 작업하기 더 쉬운 방식으로 수정하십시오.

첫 번째 방법은 TeX4ht의 MathJax 옵션에 사용하는 코드를 재사용 할 수 mathjax-latex-4ht.4ht있습니다. 자세한 내용 은 파일 을 참조하십시오.

두 번째 방법은 원래 입력과 동일한 LaTeX 코드를 생성하지 않습니다. 당신에게 문제가 될 수 있습니다. LuaXML을 사용 하여 변환 할 수 있습니다 .

제 답변에서 세 번째 방법을 제시하겠습니다. 이는 두 가지 구성 요소로 구성됩니다. 입력 LaTeX 파일을 수학 콘텐츠에 대해 구문 분석하고 추가 매크로로 표시하는 입력 필터와 결과 HTML 파일을 수정하여 올바른 MathML 구조를 생성하는 make4ht DOM 필터입니다.

다음은 입력 필터입니다. 표준 입력에서 입력을 읽고 수정 된 출력을 인쇄합니다.

파일 altmath.lua:

-- insert envrionmnets that should be handled by the script here
local math_environments = {
  equation = true,
  displaymath = true,
  ["equation*"] = true,

}

-- macros that will be inserted to the updated document
local macros = [[
\NewDocumentCommand\inlinemath {mv} {\HCode{<span class="inlinemath">}#1\HCode{<span class="alt">}\NoFonts #2\EndNoFonts\HCode{</span></span>}}
\NewDocumentEnvironment{altdisplaymath}{} {\ifvmode\IgnorePar\fi\EndP\HCode{<div class="altmath">}} {\ifvmode\IgnorePar\fi\EndP\HCode{</div>}}
]]

-- we will insert macros before the second control sequence (we assume that first is \documentclass
local cs_counter = 0

-- we will hanlde inline and diplay math differently
local inline  = 1
local display = 2

local function handle_math(input, nexts, stop, buffer, mathtype)
  local content = input:sub(nexts, stop)
  local format = "\\inlinemath{%s}{%s}" -- format used to insert math content back to the doc
  -- set format for display math
  if mathtype == display then
    format = [[
\begin{altdisplaymath}
%s
\begin{verbatim}
%s
\end{verbatim}
\end{altdisplaymath}
]]
  end
  buffer[#buffer + 1] =  string.format(format, content, content )
end

local function find_next(input, start, buffer)
  -- find next cs or math start
  local nexts, stop = input:find("[$\\]", start) local mathtype if nexts then -- save current text chunk from the input buffer buffer[#buffer+1] = input:sub(start, nexts - 1) local kind, nextc = input:match("(.)(.)", nexts) if kind == "\\" then -- handle cs -- insert our custom TeX macros before second control sequence cs_counter = cs_counter + 1 if cs_counter == 2 then buffer[#buffer+1] = macros end if nextc == "(" then -- inline math _, stop = input:find("\\)", nexts) mathtype = inline elseif nextc == "[" then -- display math _, stop = input:find("\\]", nexts) mathtype = display else -- maybe environment? -- find environment name local env_name = input:match("^begin%s*{(.-)}", nexts+1) -- it must be enabled as math environment if env_name and math_environments[env_name] then _, stop = input:find("\\end%s*{" .. env_name .. "}", nexts) mathtype = display else -- not math environment buffer[#buffer+1] = "\\" -- save backspace that was eaten by the processor return stop + 1 -- return back to the main loop end end else -- handle $
      if nextc == "$" then -- display math _, stop = input:find("%$%$", nexts + 1) mathtype = display else -- inline math _, stop = input:find("%$", nexts + 1)
        mathtype = inline
      end
    end
    if not stop then -- something failed, move one char next
      return nexts + 1
    end
    -- save math  content to the buffer
    handle_math(input, nexts, stop, buffer, mathtype)
  else
    -- if we cannot find any more cs or math, we need to insert rest of the input 
    -- to the output buffer
    buffer[#buffer+1] = input:sub(start, string.len(input))
    return nil
  end
  return stop + 1
end

-- process the input buffer, detect inline and display math and also math environments
local function process(input)
  local buffer = {} -- buffer where text chunks are stored
  local start = 1
  start = find_next(input, start,buffer)
  while start do
    start = find_next(input, start, buffer)
  end
  return table.concat(buffer) -- convert output buffer to string
end


local content = io.read("*all")
print(process(content))

다음 명령을 사용하여 테스트 할 수 있습니다.

texlua altmath.lua < sample.tex

이것은 원본 TeX 파일의 수정 된 버전입니다.

\documentclass{article}
\NewDocumentCommand\inlinemath {mv} {\HCode{<span class="inlinemath">}#1\HCode{<span class="alt">}\NoFonts #2\EndNoFonts\HCode{</span></span>}}
\NewDocumentEnvironment{altdisplaymath}{} {\ifvmode\IgnorePar\fi\EndP\HCode{<div class="altmath">}} {\ifvmode\IgnorePar\fi\EndP\HCode{</div>}}
\usepackage[T1]{fontenc}

\begin{document}

\title{Article Title Here}
\author{Author Name Here}
\maketitle

\section{Introduction}

This is the sample paragraph with \inlinemath{$a=b^2$}{$a=b^2$} inline math. Different \inlinemath{\(a=c^2\)}{\(a=c^2\)} type of math.
 \begin{altdisplaymath}
\begin{equation}\label{eq1-11}
T\,^{\prime}_{\mu \nu} = \left( \frac{\partial \xi^\alpha} {\partial\xi^{\prime\mu}}\right) \left( \frac{\partial \xi^\beta}{\partial \xi^{\prime\nu}} \right) T_{\alpha \beta}
\end{equation}
\begin{verbatim}
\begin{equation}\label{eq1-11}
T\,^{\prime}_{\mu \nu} = \left( \frac{\partial \xi^\alpha} {\partial\xi^{\prime\mu}}\right) \left( \frac{\partial \xi^\beta}{\partial \xi^{\prime\nu}} \right) T_{\alpha \beta}
\end{equation}
\end{verbatim}
\end{altdisplaymath}


Please refer the equations \ref{eq1-11} for the further testing.
\end{document}

\documentclass명령 뒤에 매크로 정의를 삽입하는 것을 볼 수 있습니다 . \inlinemath명령과 altdisplaymath환경을 정의 합니다. 정의에는 변환 된 파일에 HTML 태그를 직접 삽입하는 코드가 포함되어 있습니다. TeX4ht와 함께 사용하도록 설계되었습니다.

다음을 사용하여 파일을 HTML로 변환 할 수 있습니다.

texlua altmath.lua < sample.tex | make4ht -j sample - "mathml"

다음 코드를 생성합니다.

<span class='inlinemath'><!-- l. 14 --><math xmlns='http://www.w3.org/1998/Math/MathML' display='inline'><mi>a</mi> <mo class='MathClass-rel'>=</mo> <msup><mrow><mi>b</mi></mrow><mrow><mn>2</mn></mrow></msup></math><span class='alt'>$a=b^2$</span></span> 

또는

<div class='altmath'> <!-- tex4ht:inline --><table class='equation'><tr><td>
<!-- l. 16 --><math xmlns='http://www.w3.org/1998/Math/MathML' display='block' class='equation'>
                       <mstyle class='label' id='x1-1001r1'></mstyle><!-- endlabel --><mi>T</mi><msubsup><mrow><mspace width='0.17em' class='thinspace'></mspace></mrow><mrow><mi mathvariant='italic'>μν</mi></mrow><mrow><mi>′</mi></mrow></msubsup> <mo class='MathClass-rel'>=</mo> <mrow><mo form='prefix' fence='true'> (</mo><mrow> <mfrac><mrow><mi>∂</mi><msup><mrow><mi>ξ</mi></mrow><mrow><mi>α</mi></mrow></msup></mrow>
<mrow><mi>∂</mi><msup><mrow><mi>ξ</mi></mrow><mrow><mi mathvariant='italic'>′μ</mi></mrow></msup></mrow></mfrac> </mrow><mo form='postfix' fence='true'>)</mo></mrow> <mrow><mo form='prefix' fence='true'> (</mo><mrow> <mfrac><mrow><mi>∂</mi><msup><mrow><mi>ξ</mi></mrow><mrow><mi>β</mi></mrow></msup></mrow>
<mrow><mi>∂</mi><msup><mrow><mi>ξ</mi></mrow><mrow><mi mathvariant='italic'>′ν</mi></mrow></msup></mrow></mfrac> </mrow><mo form='postfix' fence='true'>)</mo></mrow> <msub><mrow><mi>T</mi></mrow><mrow><mi mathvariant='italic'>αβ</mi></mrow></msub>
</math></td><td class='eq-no'>(1)</td></tr></table>
<!-- l. 18 --><p class='nopar'>

</p>
   <pre id='verbatim-1' class='verbatim'>
\begin{equation}\label{eq1-11}
T\,^{\prime}_{\mu \nu} = \left( \frac{\partial \xi^\alpha} {\partial\xi^{\prime\mu}}\right) \left( \frac{\partial \xi^\beta}{\partial \xi^{\prime\nu}} \right) T_{\alpha \beta}
\end{equation}
</pre>
<!-- l. 23 --><p class='nopar'> </p></div>

올바른 MathML 구조를 생성하려면 make4ht DOM 필터를 사용해야합니다. 다음 파일을 다른 이름으로 저장하십시오 build.lua.

local domfilter = require "make4ht-domfilter"

-- find mathml and insert TeX as an alternative annotation
local function update_mathml(element, class)
  local alt_element_t = element:query_selector(class)
  if not alt_element_t and not alt_element_t[1] then return nil end
  -- save alt element contents and remove it from the document
  local alt_contents = alt_element_t[1]:get_children()
  alt_element_t[1]:remove_node()
  -- create a new structure of the mathml element ->
  -- mathml 
  --   semantics
  --     mrow -> math content
  --     annotation -> saved TeX
  local mathml = element:query_selector("math")[1]
  local mathml_contents = mathml:get_children()
  local semantics = mathml:create_element("semantics")
  local mrow = semantics:create_element("mrow")
  mrow._children = mathml_contents -- this trick places saved original mathml content into a new <mrow>
  semantics:add_child_node(mrow)
  local annotation = semantics:create_element("annotation", {encoding="application/x-tex"})
  annotation._children = alt_contents
  semantics:add_child_node(annotation)
  mathml._children = {semantics}
end

local process = domfilter {
  function(dom)
    for _, inline in ipairs(dom:query_selector(".inlinemath")) do
      update_mathml(inline, ".alt")
    end
    for _, display in ipairs(dom:query_selector(".altmath")) do
      update_mathml(display, ".verbatim")
    end
    return dom
  end
}

사용자 정의 <span>및 <div>요소에 대한 HTML 파일을 구문 분석하고 대체 텍스트를 가져와 MathML 코드의 '`요소로 삽입합니다.

결과는 다음과 같습니다.

   <h3 class='sectionHead'><span class='titlemark'>1   </span> <a id='x1-10001'></a>Introduction</h3>
<!-- l. 14 --><p class='noindent'>This  is  the  sample  paragraph  with
<span class='inlinemath'><!-- l. 14 --><math display='inline' xmlns='http://www.w3.org/1998/Math/MathML'><semantics><mrow><mi>a</mi> <mo class='MathClass-rel'>=</mo> <msup><mrow><mi>b</mi></mrow><mrow><mn>2</mn></mrow></msup></mrow><annotation encoding='application/x-tex'>$a=b^2$</annotation></semantics></math></span> inline math.
Different <span class='inlinemath'><!-- l. 14 --><math display='inline' xmlns='http://www.w3.org/1998/Math/MathML'><semantics><mrow><mrow><mi>a</mi> <mo class='MathClass-rel'>=</mo> <msup><mrow><mi>c</mi></mrow><mrow><mn>2</mn></mrow></msup></mrow></mrow><annotation encoding='application/x-tex'>\(a=c^2\)</annotation></semantics></math></span>
type of math. </p><div class='altmath'> <!-- tex4ht:inline --><table class='equation'><tr><td>
<!-- l. 16 --><math class='equation' xmlns='http://www.w3.org/1998/Math/MathML' display='block'><semantics><mrow>
                       <mstyle id='x1-1001r1' class='label'></mstyle><!-- endlabel --><mi>T</mi><msubsup><mrow><mspace width='0.17em' class='thinspace'></mspace></mrow><mrow><mi mathvariant='italic'>μν</mi></mrow><mrow><mi>′</mi></mrow></msubsup> <mo class='MathClass-rel'>=</mo> <mrow><mo fence='true' form='prefix'> (</mo><mrow> <mfrac><mrow><mi>∂</mi><msup><mrow><mi>ξ</mi></mrow><mrow><mi>α</mi></mrow></msup></mrow>
<mrow><mi>∂</mi><msup><mrow><mi>ξ</mi></mrow><mrow><mi mathvariant='italic'>′μ</mi></mrow></msup></mrow></mfrac> </mrow><mo fence='true' form='postfix'>)</mo></mrow> <mrow><mo fence='true' form='prefix'> (</mo><mrow> <mfrac><mrow><mi>∂</mi><msup><mrow><mi>ξ</mi></mrow><mrow><mi>β</mi></mrow></msup></mrow>
<mrow><mi>∂</mi><msup><mrow><mi>ξ</mi></mrow><mrow><mi mathvariant='italic'>′ν</mi></mrow></msup></mrow></mfrac> </mrow><mo fence='true' form='postfix'>)</mo></mrow> <msub><mrow><mi>T</mi></mrow><mrow><mi mathvariant='italic'>αβ</mi></mrow></msub>
</mrow><annotation encoding='application/x-tex'>
\begin{equation}\label{eq1-11}
T\,^{\prime}_{\mu \nu} = \left( \frac{\partial \xi^\alpha} {\partial\xi^{\prime\mu}}\right) \left( \frac{\partial \xi^\beta}{\partial \xi^{\prime\nu}} \right) T_{\alpha \beta}
\end{equation}
</annotation></semantics></math></td><td class='eq-no'>(1)</td></tr></table>
<!-- l. 18 --><p class='nopar'>

</p>
   
<!-- l. 23 --><p class='nopar'> </p></div>
MadyYuvi Oct 09 2020 at 15:37

다만 MWE많은 LaTeX의 코딩 오류를 가지고, 나는 고정했고 수정 된 태그는 다음과 같습니다

\documentclass{article} 
\usepackage[T1]{fontenc}

\begin{document}

\title{Article Title Here}

\author{Author Name Here}

\maketitle

\section{Introduction}

This is the sample paragraph.
\begin{equation}\label{eq1-11}
T\,^{\prime}_{\mu \nu} = \left( \frac{\partial \xi^{\alpha}}
{\partial\xi^{\prime\mu}}\right) \left( \frac{\partial \xi^{\beta}}{\partial \xi^{\prime\nu}} \right) T_{\alpha \beta}
\end{equation}

Please refer the equations \ref{eq1-11} for the further testing.
\end{document}

오류를 수정 한 후 명령을 실행했습니다.

htlatex test "xhtml,mathml,mathml-" " -cunihft" "-cvalidate -p"

그것은 멋지게 변환 ...

편집하다

LaTeX변환 된 에서 태그를 표시해야하는 경우 HTML아래 .cfg파일 을 사용 하십시오.

conversion.cfg

\RequirePackage{verbatim,etoolbox}

\Preamble{xhtml}
\def\AltMathOne#1${\HCode{\detokenize{\(#1\)}}$}
\Configure{$}{}{}{\expandafter\AltMathOne} \def\AltlMath#1\){\HCode{\detokenize{\(#1\)}}\)} \Configure{()}{\AltlMath}{} \def\AltlDisplay#1\]{\HCode{\detokenize{\[#1\]}}\]} \Configure{[]}{\AltlDisplay}{} \def\AltDisplayOne#1#2$${#1\HCode{\detokenize{$$#2$$}}$$} \Configure{$$}{}{}{\AltDisplayOne}{}{}
\newcommand\VerbMath[1]{%
\ifcsdef{#1}{%
  \renewenvironment{#1}{%
    \NoFonts%
  \Configure{verbatim}{}{} % suppress <br /> tags
    \texttt{\string\begin\{#1\}}\HCode{\Hnewline}% we need to use \texttt to get all characters right
      \verbatim}{\endverbatim\texttt{\string\end\{#1\}}\EndNoFonts}%
}{}%
}
\VerbMath{align}
\VerbMath{equation}
\VerbMath{equation*}

\begin{document}

\EndPreamble

그런 다음 실행 명령 :

htlatex sample "conversion" " " "-cvalidate -p"