簡體   English   中英

Pandoc過濾器模仿默認的MathML轉換

[英]Pandoc filter mimicking default MathML conversion

我正在Haskell中編寫Pandoc JSON過濾器 ,該過濾器應使用外部應用程序將顯示LaTeX數學轉換為SVG,而內聯LaTeX數學應通過pandoc內部轉換為MathML。

第一個SVG位工作正常; 是MathML位應該模仿標准的pandoc行為,這給我帶來了問題。

瀏覽黑客,我找到texMathToMathML代碼示例 (請參見下文)。 此函數返回Either String Element

但是,我需要的是返回IO String的函數tex2mml (請參見下文)。 要實現此tex2mml ,需要在tex2mml的定義中添加什么?

tex2mml latex = texMathToMathML DisplayInline latex

我正在(X)Ubuntu LTS 16.04上安裝以下pandoc 1.16.0.2軟件包來執行此操作:

$ sudo apt install pandoc libghc-pandoc-prof

這是我到目前為止所獲得的摘錄:

#!/usr/bin/env runhaskell

import Text.Pandoc.JSON
import Control.Applicative ((<$>))
import Text.TeXMath (writeMathML, readTeX, DisplayType( DisplayInline ) )
import Text.XML.Light (Element)


texMathToMathML :: DisplayType -> String -> Either String Element
texMathToMathML dt s = writeMathML dt <$> readTeX s


tex2mml :: String -> IO String
tex2mml latex = texMathToMathML DisplayInline latex


main :: IO ()
main = toJSONFilter tex2math
  where tex2math (Math (DisplayMath) latex) = do
          svg <- tex2svg latex
          return (Math (DisplayMath) (svg))

        tex2math (Math (InlineMath) latex) = do
          mml <- tex2mml latex
          return (Math (InlineMath) (mml))

        tex2math other = return other

拜托,請耐心等待,因為我絕對是Haskell的初學者。 任何有關代碼改進的建議都將受到歡迎!

誠然,我對Pandoc和問題域並不熟悉,但是如果正確理解了tex2mml函數的用途,那么我相信這應該可以實現您想要的:

import Control.Applicative ((<$>))
import Text.Pandoc.JSON
import Text.TeXMath
       (writeMathML, readTeX, DisplayType(DisplayInline))
import Text.XML.Light (Element,showElement)

texMathToMathML :: DisplayType -> String -> Either String Element
texMathToMathML dt s = writeMathML dt <$> readTeX s

tex2mml :: String -> String
tex2mml latex = either id showElement (texMathToMathML DisplayInline latex)

-- actual definition of tex2svg goes here
tex2svg = undefined

main :: IO ()
main = toJSONFilter tex2math
  where
    tex2math :: Inline -> IO Inline
    tex2math (Math DisplayMath latex) = do
      svg <- tex2svg latex
      return (Math DisplayMath svg)
    tex2math (Math InlineMath latex) = return (Math InlineMath (tex2mml latex))
    tex2math other = return other

我正在使用either函數來檢查轉換函數texMathToMathML的結果-如果失敗, texMathToMathMLid )返回錯誤,如果成功, showElement函數用於將Element轉換為其XML字符串表示形式。

如果您發現更清晰,也可以使用模式匹配來重寫它:

tex2mml :: String -> String
tex2mml latex = case texMathToMathML DisplayInline latex of
  Left err -> err
  Right xml -> showElement xml

由於計算是純粹的,因此不需要將其嵌入IO monad中,並且結果可以直接傳遞到Math構造函數中。

如果您希望漂亮地打印XML字符串或希望在輸出中包含XML文檔標題,則Text.XML.Light.Output模塊中還有其他功能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM