· 8 years ago · Mar 02, 2018, 08:10 AM
1module ImgTexPlugin (plugin) where
2{-
3
4This plugin provides a clear math LaTeX output.
5(latex and dvipng executable must be in the path.)
6
7like this:
8
9~~~ {.dvipng}
10\nabla \times \bm{V}
11=
12\frac{1}{h_1 h_2 h_3}
13 \begin{vmatrix}
14 h_1 e_1 & h_2 e_2 & h_3 e_3 \\
15 \frac{\partial}{\partial q_{1}} &
16 \frac{\partial}{\partial q_{2}} &
17 \frac{\partial}{\partial q_{3}} \\
18 h_1 V_1 & h_2 V_2 & h_3 V_3
19 \end{vmatrix}
20~~~
21
22License: GPL
23written by Kohei Ozaki <eowner at gmail.com>
24
25-}
26
27import Gitit.Interface
28import Text.Pandoc.Shared
29import System.Process (system)
30import System.Directory
31import Data.Char (ord)
32import Data.ByteString.Lazy.UTF8 (fromString)
33import Data.Digest.Pure.SHA
34import Data.Generics (everywhereM, mkM)
35import System.FilePath
36import Control.Monad.Trans (liftIO)
37
38plugin :: Plugin
39plugin = PageTransform dvipngTransform
40
41tmpdir = "/var/tmp"
42teximgdir = "img"
43
44templateHeader =
45 ( "\\documentclass[12pt]{article}\n"
46 ++ "\\usepackage{amsmath,amssymb,bm}\n"
47 ++ "\\begin{document}\n"
48 ++ "\\thispagestyle{empty}\n"
49 ++ "\\[\n"
50 )
51
52templateFooter =
53 ( "\n"
54 ++ "\\]\n"
55 ++ "\\end{document}\n"
56 )
57
58dvipngTransform :: AppState -> Pandoc -> Web Pandoc
59dvipngTransform st = everywhereM (mkM (transformBlock st))
60
61transformBlock :: AppState -> Block -> Web Block
62transformBlock st (CodeBlock (id, classes, namevals) contents)
63 | "dvipng" `elem` classes = do
64 let outfile = uniqueName contents ++ ".png"
65 liftIO $ do
66 cacheCheck <- doesFileExist (teximgdir </> outfile)
67 case cacheCheck of
68 False -> do
69 curr <- getCurrentDirectory
70 initTempDir outfile
71 writeFile (outfile++".tex") (templateHeader ++ contents ++ templateFooter)
72 system $ "latex " ++ (outfile++".tex") ++ " > /dev/null"
73 setCurrentDirectory curr
74 system $ "dvipng -T tight -bd 1000 -freetype0 -Q 5 --gamma 1.3 "
75 ++ tmpdir </> "gitit-tmp-" ++ outfile </> outfile ++ ".dvi"
76 ++ " -o " ++ (staticDir (config st) </> teximgdir </> outfile)
77 ++ " > /dev/null"
78 finishTempDir outfile
79 True -> return ()
80 return $ Para [Image [] ("/" ++ teximgdir </> outfile, "")]
81transformBlock _ x = return x
82
83mkTempDirName :: String -> String
84mkTempDirName = \s -> tmpdir </> "gitit-tmp-" ++ s
85
86initTempDir :: String -> IO ()
87initTempDir = (\f -> createDirectory f >> setCurrentDirectory f) . mkTempDirName
88
89finishTempDir :: String -> IO ()
90finishTempDir = removeDirectoryRecursive . mkTempDirName
91
92uniqueName :: String -> String
93uniqueName = showDigest . sha1 . fromString