Integrate PlantUML diagrams into Hakyll (Old)

Posted on October 2, 2012
Tags: hacksoft

** Go here Integrate PlantUML diagrams into Hakyll (Updated) that uses Hakyll libraries rather than my reinvent-the-wheel-bad implementations**

0.0.2 Pandocs filtering

Now we need to modify site.hs so that Hakyll will transform a PlantUML code block into a html img that links to the Planttext generated image.
We can do this with Hakyll’s Pandocs Filtering.


--Pandoc filtering, 
addToCodeBlock :: Pandoc -> Pandoc 
addToCodeBlock  = walk ftranslate 
  where ftranslate :: Block -> Block
        ftranslate (CodeBlock ("",["plantuml"],[]) txt ) = RawBlock (Format "html") (planthtml txt)
        ftranslate x = x 

ftranslate (CodeBlock ("",["plantuml"],[]) txt ) pattern matches CodeBlock objects in pandoc and finds “plantuml” annotations denoted by the Attr object ("",["plantuml"],[])
The Content of our CodeBlock is pattern matched as txt.

After pattern matching it converts it into a raw html block, and applies our “Code to Img DOM” transformation function planthtml on the content.

INPUT Markdown codeblock :

'''plantuml
@startuml  
Alice->Bob : I am using hex  
@enduml
'''

Output DOM element :

0.0.3 Full Code

add under “build-depends” in your .cabal file

pandoc,
pandoc-types,
text  

Add to your site.hs

import           Text.Pandoc.Definition  
import           Text.Pandoc.Walk
import           Data.Text  

import Numeric (showHex)
import Data.Char (ord)
strToASCII :: [Char] -> [Int]
strToASCII xs = fmap ord xs

asciiToHex :: [Int] -> [String]
asciiToHex xs = fmap (\x -> showHex x "") xs

plantUMLhex :: [Char] -> String 
plantUMLhex xs = (concat.  asciiToHex . strToASCII) xs

-- replaceLF replaces markdown doublespace newlines hex with plantUML compatible newline hex
replaceLF :: T.Text -> T.Text 
replaceLF xs =  (T.replace "20200" "0a") xs

hexCode :: T.Text -> T.Text 
hexCode y = (replaceLF (T.pack ( plantUMLhex (T.unpack y))))

planthtml :: T.Text -> T.Text 
planthtml y = T.pack ("<figure><img src='http://www.plantuml.com/plantuml/svg/~h" <> (T.unpack $ hexCode y) <>"'></figure>") 

--Pandoc filtering, 
addToCodeBlock :: Pandoc -> Pandoc 
addToCodeBlock  = walk ftranslate 
  where ftranslate :: Block -> Block
        ftranslate (CodeBlock ("",["plantuml"],[]) txt ) = RawBlock (Format "html") (planthtml txt)
        ftranslate x = x 
mathJaxAddedCompiler :: Compiler (Item String)
mathJaxAddedCompiler = pandocCompilerWithTransform readMathjaxOptions writeMathjaxOptions addToCodeBlock
simpleCompiler :: Compiler (Item String)
simpleCompiler = pandocCompilerWithTransform defaultHakyllReaderOptions defaultHakyllWriterOptions addToCodeBlock