module Math ( compileMath ) where import System.IO.Temp (withSystemTempDirectory) import System.Process (callProcess) import System.Directory (copyFile, getCurrentDirectory, setCurrentDirectory) import System.FilePath (takeFileName, FilePath(..), ()) import Control.Monad import Control.Exception (bracket) import Control.DeepSeq (($!!)) compileMath :: String -> IO String compileMath = withSystemTempDirectory "math" . compileMath' compileMath' :: String -> FilePath -> IO String compileMath' input tmpDir = do mapM_ (copyToTmp . ("tex" )) [ "preamble.tex" , "preview.dtx" , "preview.ins" ] withCurrentDirectory tmpDir $ do callProcess "latex" [ "-interaction=batchmode" , "preview.ins" ] writeFile (tmpDir "image.tex") input callProcess "latex" [ "-interaction=batchmode" , "image.tex" ] callProcess "dvisvgm" [ "--exact" , "--no-fonts" , tmpDir "image.dvi" ] (\x -> return $!! x) =<< (readFile $ tmpDir "image.svg") where copyToTmp fp = copyFile fp (tmpDir takeFileName fp) withCurrentDirectory :: FilePath -- ^ Directory to execute in -> IO a -- ^ Action to be executed -> IO a withCurrentDirectory dir action = bracket getCurrentDirectory setCurrentDirectory $ \ _ -> do setCurrentDirectory dir action