{-# Language CPP #-} module Rendering.Render (ToHtml, toHtml) where import Data.List import Data.List.Utils import Data.Maybe (isJust, fromJust) import System.Environment (lookupEnv) import System.IO.Unsafe (unsafePerformIO) import AST #ifdef CABAL import Paths_Blogdown #endif import Rendering.RenderOptions class ToHtml a where toHtml :: RenderOptions -> a -> String dataFileContents :: FilePath -> String dataFileContents relPath = unsafePerformIO $ do dataDirOverride <- lookupEnv "blogdown_datadir_override" if isJust dataDirOverride then readFile $ fromJust dataDirOverride ++ "/" ++ relPath else #ifdef CABAL getDataFileName relPath >>= readFile #else readFile relPath #endif optionalJS :: RenderOptions -> String optionalJS r = if (inlineJS r) then "\n" else "" optionalCSS :: RenderOptions -> String optionalCSS r = if (inlineCSS r) then "\n" else "" instance ToHtml AST where toHtml r (AST bs Nothing) = (unlines $ map (toHtml r) bs) ++ optionalCSS r ++ optionalJS r toHtml r (AST bs (Just f)) = body ++ footnotes ++ "\n" ++ optionalCSS r ++ optionalJS r where body = unlines $ map (toHtml r) bs footnotes = toHtml r f withTag :: String -> String -> String withTag tag content = "<" ++ tag ++ ">" ++ content ++ "" ++ tag ++ ">" showAttrs :: [(String, String)] -> String showAttrs attrs = unwords $ map (\(name, val) -> name ++ "=\"" ++ val ++ "\"") attrs withTagAttrs :: String -> [(String, String)] -> String -> String withTagAttrs tag attrs content = "<" ++ tag ++ " " ++ showAttrs attrs ++ ">" ++ content ++ "" ++ tag ++ ">" fancyUnlines :: [String] -> String fancyUnlines = concat . intersperse "\n" escapeHtml :: String -> String escapeHtml = concatMap escapeChar where escapeChar '<' = "<" escapeChar '>' = ">" escapeChar c = [c] instance ToHtml FootnoteDefs where toHtml r (FootnoteDefs fs) = withTagAttrs "ol" [("start", show $ footnoteIndexFrom r), ("class", "footnotes")] $ unlines $ map (toHtml r) $ sortOn index fs instance ToHtml FootnoteDef where toHtml r (FootnoteDef index ls) = withTagAttrs "li" [("id", (footnotePrefix r) ++ "-footnote-" ++ show index)] content' where content = fancyUnlines $ map (toHtml r) ls content' = if footnoteBacklinks r then withTagAttrs "a" [("href", "#a-" ++ (footnotePrefix r) ++ "-footnote-" ++ show index)] "^" ++ "\n" ++ content else content stripEndingNewline :: String -> String stripEndingNewline s = if last s == '\n' then init s else s instance ToHtml Block where toHtml _ HardRule = "