Convertir LaTex a HTML manteniendo las ecuaciones como LaTeX excepto las etiquetas

Convertir LaTex a HTML manteniendo las ecuaciones como LaTeX excepto las etiquetas

Convertir LaTeX a HTML manteniendo ecuaciones como LaTeXexplica cómo usar \VerbMath en tex4ht para convertir LaTeX a HTML manteniendo las ecuaciones iguales. Como referencia, agregaré que para varias líneas se puede usar el entorno alineado como se explicaaquí.

Sin embargo, estas soluciones no funcionan con etiquetas. Entonces lo que me gustaría es una manera de convertir

\begin{equation}
1=1 \label{eq}
\end{equation}

Equation \ref{eq}

en

\begin{equation}
1=1~~~(7)
\end{equation}

Equation (7)

donde (7) es la numeración correcta de la ecuación. ¿Se puede hacer esto con tex4ht o hay algún otro script que lo haga?

Nota: Mathjax puede resolver etiquetas/referencias, pero no quiero usar Mathjax.

Respuesta1

Editar:

Como no desea utilizar MathJax, necesita posprocesar su texto para reemplazar etiquetas y referencias cruzadas e insertar números de ecuación. Afortunadamente, podemos usar make4htarchivos de compilación para eso.

Archivo de muestra:

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

\newcommand\mjref[1]{\ref{#1}}
\begin{document}
\begin{equation}
1=1 \label{eq}
\end{equation}

\begin{align}
  1 + a = 2\\
  2 - a = 1
\end{align}

Equation \mjref{eq} 
\end{document}

Los detalles sobre \mjrefse encuentran en la respuesta original, estos detalles aún se aplican. Usaremos un paquete modificado para mantener las matemáticas de LaTeX sin cambios latex-unchanged.sty:

\RequirePackage{verbatim,etoolbox}
\AtBeginDocument{%
  \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}{}
% 
\newcommand\VerbMath[1]{%
\ifcsdef{#1}{%
  \renewenvironment{#1}{%
    \NoFonts%
    \Configure{verbatim}{}{}
    \HChar{92}begin\{#1\}%
    \verbatim}{\endverbatim\HChar{92}end\{#1\}\EndNoFonts}%
}{}%
}

\VerbMath{align}
\VerbMath{equation}
\VerbMath{equation*}
  }

.cfgArchivo ligeramente modificado :

\RequirePackage{latex-unchanged} 
\Preamble{xhtml,html5}
\begin{document}
\renewcommand\mjref[1]{\NoFonts\HChar{92}eqref\{#1\}\EndNoFonts}
\EndPreamble

Y ahora lo interesante:

El archivo de compilación, llamado youfilename.mk4:

local filter = require "make4ht-filter"
local crossref = require "crossref"
local process = filter { crossref }

Make:match(".html$", process)

Esto declara que todos los archivos html deben procesarse con crossrefla biblioteca, que hará todo el trabajo duro. Guarde el siguiente código como crossref.lua:

-- counter values for particular counters will be saved here
local eqcounter = 0
-- pattern which will be inserted as equation number
local counter_pattern = "~~~(%i)"

-- list of environments to insert counters
local processed = {"equation", "align"}
local labels = {}


-- this function takes pattern for ending text (it is end environment or
-- \\ as line breaks in aligns) and insert counter numbers before the matched text
-- it also removes \labels and store them for future use
local function insert_counter(text, pattern, counter)
  local counter_pat = string.format(counter_pattern, counter)
  -- remove labels
  local removed_labels = text:gsub('%s*\\label{(.-)}', function(name)
    -- save counter under label name
    print("save label", name, counter)
    labels[name] = counter
    return ''
  end)
  local inserted = removed_labels:gsub(pattern, counter_pat .. '%0')
  print("inserted", inserted)
  return inserted
end

local function handle_counter(env, name)
  eqcounter = eqcounter + 1
  -- we need to support align environments, which will have multiple counters
  if env:match('\\\\') then
    local parts = {}
    local ending = env:gsub('(.-)\\\\', function(part)
      table.insert(parts, part)
      return ''
    end)
    local results = {}
    -- we first process lines ending with \\, the last line without this will be processd
    -- with usual code for end environment
    for _, part in ipairs(parts) do
      print("part", part)
      table.insert(results, insert_counter(part, '(%s*)$',eqcounter))
      eqcounter = eqcounter + 1
    end
    env  = table.concat(results, '\\\\') .. '\\\\' ..ending
  end
  -- now insert counter for the whole environment
  return insert_counter(env, '(%s*\\end{'.. name ..'}', eqcounter)
end

local function handle_refs(text)
  -- modify the pattern to match the referencing macro you use
  return text:gsub('\\eqref{(.-)}', function(label)
    local counter = labels[label]
    if not counter then return '??' end
    return string.format("(%i)", counter)
  end)
end

return function(s)
  -- process math environments defined in processed table
  for _, name in ipairs(processed) do
    -- match the whole environments and replace them with modified version
    s = s:gsub('(\\begin{' ..name .. '}.-\\end{'.. name ..'})', function(environment)
      return handle_counter(environment, name)
    end)
  end
  -- handle ref commands in text
  s = handle_refs(s)
  return s
end

Los detalles están en los comentarios del código fuente.

Compilar usando:

make4ht -uc myconfig4.cfg -e youfilename.mk4 sample.tex

Este es el resultado:

<!--l. 7--><p class="noindent" >\begin{equation}
1=1~~~(1)
\end{equation}

</p><!--l. 11--><p class="noindent" >\begin{align}
1+a=2~~~(2)\\
2-a=1~~~(3)
\end{align}
</p><!--l. 16--><p class="noindent" >Equation (1)</p> 

Respuesta original:

MathJax admite etiquetas y referencias cruzadas, por lo que tal vez sea más realista dejar que maneje no solo \label, sino también \ref. Definiría una macro personalizada para hacer referencia a entornos matemáticos, que se puede redefinir para insertar \ref{labelname}cuando se compila el documento con tex4ht. No \reflo redefiniría, porque probablemente no quieras perder la capacidad de hacer referencias a secciones o figuras.

Algo como esto:

\documentclass{article}
\usepackage{amsmath}

\newcommand\mjref[1]{\ref{#1}}
\begin{document}
\begin{equation}
1=1 \label{eq}
\end{equation}

Equation \mjref{eq} 
\end{document}

Se puede encontrar la versión actual del código de MathJax con macros LaTeXpaquete helpers4ht. No está en CTAN, puedes usar solomathjax-latex4ht.stypaquete.

El archivo de configuración se puede simplificar un poco:

\RequirePackage{mathjax-latex-4ht} 
\Preamble{xhtml}
\begin{document}
\renewcommand\mjref[1]{\NoFonts\HChar{92}eqref\{#1\}\EndNoFonts}
\EndPreamble

Lo único interesante es la redefinición del \mjrefcomando, que desactiva temporalmente la inserción de etiquetas HTML para fuentes y utiliza \HChar{92}para insertar el \carácter mediante su código ASCII.

El código HTML resultante es el siguiente:

<!--l. 7--><p class="noindent" >\begin{equation}
1=1\label{eq}
\end{equation}
</p><!--l. 11--><p class="noindent" >Equation \eqref{eq}</p> 

MathJax lo representa de esta manera:

ingrese la descripción de la imagen aquí

información relacionada