Subst.hs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. {-# LANGUAGE PackageImports #-}
  2. -- Usage: a paragraph containing just [My page](!subst)
  3. -- will be replaced by the contents of My page.
  4. --
  5. -- Limitations: it is assumed that My page is
  6. -- formatted with markdown, and contains no metadata.
  7. module Subst (plugin) where
  8. --import "MonadCatchIO-mtl" Control.Monad.CatchIO (try)
  9. import Control.Monad.Catch (try)
  10. import Data.FileStore (FileStoreError, retrieve)
  11. import Text.Pandoc (def, readMarkdown)
  12. import Network.Gitit.ContentTransformer (inlinesToString)
  13. import Network.Gitit.Interface
  14. import Network.Gitit.Framework (filestoreFromConfig)
  15. plugin :: Plugin
  16. plugin = mkPageTransformM substituteIntoBlock
  17. substituteIntoBlock :: [Block] -> PluginM [Block]
  18. substituteIntoBlock ((Para [Link attr ref ("!subst", _)]):xs) =
  19. do let target = inlinesToString ref
  20. cfg <- askConfig
  21. let fs = filestoreFromConfig cfg
  22. article <- try $ liftIO (retrieve fs (target ++ ".page") Nothing)
  23. case article :: Either FileStoreError String of
  24. Left _ -> let txt = Str ("[" ++ target ++ "](!subst)")
  25. alt = "'" ++ target ++ "' doesn't exist. Click here to create it."
  26. lnk = Para [Link attr [txt] (target,alt)]
  27. in (lnk :) `fmap` substituteIntoBlock xs
  28. -- Right a -> let (Pandoc _ content) = readMarkdown def a
  29. -- in (content ++) `fmap` substituteIntoBlock xs
  30. Right a -> case readMarkdown def a of
  31. Left err ->
  32. let content = [Para $ [Str "Error parsing markdown in subst?"]] in
  33. (content ++) `fmap` substituteIntoBlock xs
  34. Right (Pandoc _ content) -> (content ++) `fmap` substituteIntoBlock xs
  35. substituteIntoBlock (x:xs) = (x:) `fmap` substituteIntoBlock xs
  36. substituteIntoBlock [] = return []