Skip to content

Instantly share code, notes, and snippets.

@rplacd
Last active May 12, 2016 09:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rplacd/9a14dc3e0715be0157516d59c2722d81 to your computer and use it in GitHub Desktop.
Save rplacd/9a14dc3e0715be0157516d59c2722d81 to your computer and use it in GitHub Desktop.
Convert Bird-style .lhs to Markdown.
#!/usr/bin/env stack
-- stack runghc --package text --package turtle
{-# LANGUAGE OverloadedStrings #-}
{-
lxx2md.hs (-l|--lang LANG)
A filter that converts Bird-style lhs in Markdown ``` blocks.
Combines consecutive Bird-tracked lines into single blocks.
KNOWN ISSUES
- Does not reject program lines next to text lines.
- Assumes that newlines are \n.
COPYING
Do whatever you want - but it'd be nice to know how things
get improved.
-}
import Turtle
import qualified Data.Text.Lazy as L
import qualified Data.Text.Lazy.IO as L
data Block = Text L.Text | Code L.Text
deriving Show
main :: IO ()
main = do
lang <- (fmap L.fromStrict) (options "lxx2md" opts)
lines <- (fmap L.lines) L.getContents
putLines (map (render lang) (coalesce $ parse lines))
return ()
where opts = optText "lang" 'l' "The language string Markdown code blocks are given."
parse :: [L.Text] -> [Block]
parse [] = []
parse (l:ls) = case L.stripPrefix ">" l of
Nothing -> Text l : parse ls
Just l' -> Code l' : parse ls
coalesce :: [Block] -> [Block]
coalesce [] = []
coalesce [a] = [a]
coalesce (Text a:Text b:cs) =
coalesce $ Text (a +++ "\n" +++ b) : coalesce cs
coalesce (Code a:Code b:cs) =
coalesce $ Code (a +++ "\n" +++ b) : coalesce cs
coalesce (a:b:cs) = a : b : coalesce cs
render :: L.Text -> Block -> L.Text
render ____ (Text text) = text
render lang (Code text) = "```" +++ lang +++ "\n" +++ text +++ "\n```"
putLines :: [L.Text] -> IO [()]
putLines = mapM L.putStrLn
(+++) = L.append
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment