[英]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
的結果-如果失敗, texMathToMathML
( id
)返回錯誤,如果成功, 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.