summaryrefslogtreecommitdiff
path: root/src/Math.hs
blob: e927fddf8312071a48e67e6b67f7955da40d0882 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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