ImgTex.hs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. module ImgTex (plugin) where
  2. {-
  3. This plugin provides a clear math LaTeX output.
  4. (* latex and dvipng executable must be in the path.)
  5. like this:
  6. ~~~ {.dvipng}
  7. \nabla \times \bm{V}
  8. =
  9. \frac{1}{h_1 h_2 h_3}
  10. \begin{vmatrix}
  11. h_1 e_1 & h_2 e_2 & h_3 e_3 \\
  12. \frac{\partial}{\partial q_{1}} &
  13. \frac{\partial}{\partial q_{2}} &
  14. \frac{\partial}{\partial q_{3}} \\
  15. h_1 V_1 & h_2 V_2 & h_3 V_3
  16. \end{vmatrix}
  17. ~~~
  18. License: GPL
  19. written by Kohei OZAKI <i@smly.org>
  20. modified by John MacFarlane to use withTempDir
  21. -}
  22. import Network.Gitit.Interface
  23. import System.Process (system)
  24. import System.Directory
  25. import Data.ByteString.Lazy.UTF8 (fromString)
  26. import Data.Digest.Pure.SHA
  27. import System.FilePath
  28. import Control.Monad.Trans (liftIO)
  29. plugin :: Plugin
  30. plugin = mkPageTransformM transformBlock
  31. templateHeader, templateFooter :: String
  32. templateHeader = concat
  33. [ "\\documentclass[12pt]{article}\n"
  34. , "\\usepackage{amsmath,amssymb,bm}\n"
  35. , "\\begin{document}\n"
  36. , "\\thispagestyle{empty}\n"
  37. , "\\[\n"]
  38. templateFooter =
  39. "\n"
  40. ++ "\\]\n"
  41. ++ "\\end{document}\n"
  42. transformBlock :: Block -> PluginM Block
  43. transformBlock (CodeBlock (_, classes, namevals) contents)
  44. | "dvipng" `elem` classes = do
  45. cfg <- askConfig
  46. let (name, outfile) = case lookup "name" namevals of
  47. Just fn -> ([Str fn], fn ++ ".png")
  48. Nothing -> ([], uniqueName contents ++ ".png")
  49. curr <- liftIO getCurrentDirectory
  50. liftIO $ withTempDir "gitit-imgtex" $ \tmpdir -> do
  51. setCurrentDirectory tmpdir
  52. writeFile (outfile ++ ".tex") (templateHeader ++ contents ++ templateFooter)
  53. system $ "latex " ++ outfile ++ ".tex > /dev/null"
  54. setCurrentDirectory curr
  55. system $ "dvipng -T tight -bd 1000 -freetype0 -Q 5 --gamma 1.3 " ++
  56. (tmpdir </> outfile <.> "dvi") ++ " -o " ++ (staticDir cfg </> "img" </> outfile)
  57. return $ Para [Image name ("/img" </> outfile, "")]
  58. transformBlock x = return x
  59. uniqueName :: String -> String
  60. uniqueName = showDigest . sha1 . fromString