pandoc/trypandoc/trypandoc.hs

65 lines
2.6 KiB
Haskell
Raw Normal View History

2015-05-28 06:19:59 +02:00
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Network.Wai.Handler.CGI
import Network.Wai
import Control.Applicative ((<$>))
import Data.Maybe (mapMaybe, fromMaybe)
import Network.HTTP.Types.Status (status200)
import Network.HTTP.Types.Header (hContentType)
import Network.HTTP.Types.URI (queryToQueryText)
import Text.Pandoc
2017-06-10 21:38:08 +02:00
import Text.Pandoc.Highlighting (pygments)
import Text.Pandoc.Readers (getReader, Reader(..))
import Text.Pandoc.Writers (getWriter, Writer(..))
2015-05-28 06:21:26 +02:00
import Text.Pandoc.Error (PandocError)
import Text.Pandoc.Shared (tabFilter)
import Data.Aeson
import qualified Data.Text as T
import Data.Text (Text)
main :: IO ()
main = run app
app :: Application
app req respond = do
let query = queryToQueryText $ queryString req
let getParam x = maybe (error $ T.unpack x ++ " paramater not set")
return $ lookup x query
text <- getParam "text" >>= checkLength . fromMaybe T.empty
fromFormat <- fromMaybe "" <$> getParam "from"
toFormat <- fromMaybe "" <$> getParam "to"
2017-06-10 21:38:08 +02:00
let reader = case getReader (T.unpack fromFormat) of
Right (TextReader r) -> r readerOpts
_ -> error $ "could not find reader for "
++ T.unpack fromFormat
let writer = case getWriter (T.unpack toFormat) of
Right (TextWriter w) -> w writerOpts
2017-06-10 21:38:08 +02:00
_ -> error $ "could not find writer for " ++
T.unpack toFormat
let result = case runPure $ reader (tabFilter 4 text) >>= writer of
Right s -> s
2015-05-28 06:18:17 +02:00
Left err -> error (show err)
let output = encode $ object [ T.pack "html" .= result
, T.pack "name" .=
if fromFormat == "markdown_strict"
then T.pack "pandoc (strict)"
else T.pack "pandoc"
, T.pack "version" .= pandocVersion]
respond $ responseLBS status200 [(hContentType,"text/json; charset=UTF-8")] output
checkLength :: Text -> IO Text
checkLength t =
if T.length t > 10000
then error "exceeds length limit of 10,000 characters"
else return t
writerOpts :: WriterOptions
writerOpts = def { writerReferenceLinks = True,
writerEmailObfuscation = NoObfuscation,
writerHTMLMathMethod = MathJax (defaultMathJaxURL ++
"MathJax.js?config=TeX-AMS_CHTML-full"),
2017-06-10 21:38:08 +02:00
writerHighlightStyle = Just pygments }
readerOpts :: ReaderOptions
2017-06-10 21:38:08 +02:00
readerOpts = def