--------------------------------------------------------------------------------
{-# LANGUAGE LambdaCase #-}
module Text.Pandoc.Extended
    ( module Text.Pandoc

    , plainToPara
    , newlineToSpace

    , readPlainText
    ) where


--------------------------------------------------------------------------------
import           Data.Char          (isSpace)
import           Data.Data.Extended (grecT)
import qualified Data.Text          as T
import           Prelude
import           Text.Pandoc


--------------------------------------------------------------------------------
plainToPara :: [Block] -> [Block]
plainToPara :: [Block] -> [Block]
plainToPara = forall a b. (a -> b) -> [a] -> [b]
map forall a b. (a -> b) -> a -> b
$ \case
    Plain [Inline]
inlines -> [Inline] -> Block
Para [Inline]
inlines
    Block
block         -> Block
block


--------------------------------------------------------------------------------
newlineToSpace :: [Inline] -> [Inline]
newlineToSpace :: [Inline] -> [Inline]
newlineToSpace = forall a b. (Data a, Data b) => (a -> a) -> b -> b
grecT forall a b. (a -> b) -> a -> b
$ \case
    Inline
SoftBreak -> Inline
Space
    Inline
LineBreak -> Inline
Space
    Inline
inline    -> Inline
inline


--------------------------------------------------------------------------------
-- | A plain-text reader.  Always returns empty metadata.
readPlainText :: T.Text -> Pandoc
readPlainText :: Text -> Pandoc
readPlainText = Meta -> [Block] -> Pandoc
Pandoc forall a. Monoid a => a
mempty forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall (f :: * -> *) a. Applicative f => a -> f a
pure forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Inline] -> Block
Plain forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> [Inline]
go
  where
    go :: Text -> [Inline]
go Text
txt0 = case Text -> Maybe (Char, Text)
T.uncons Text
txt0 of
        Maybe (Char, Text)
Nothing           -> []
        Just (Char
' ',  Text
txt1) -> Inline
Space forall a. a -> [a] -> [a]
: Text -> [Inline]
go Text
txt1
        Just (Char
'\r', Text
txt1) -> Text -> [Inline]
go Text
txt1
        Just (Char
'\n', Text
txt1) -> Inline
SoftBreak forall a. a -> [a] -> [a]
: Text -> [Inline]
go Text
txt1
        Just (Char
c,    Text
txt1) ->
            let (Text
pre, Text
post) = (Char -> Bool) -> Text -> (Text, Text)
T.break Char -> Bool
isSpace Text
txt1 in
            Text -> Inline
Str (Char -> Text -> Text
T.cons Char
c Text
pre) forall a. a -> [a] -> [a]
: Text -> [Inline]
go Text
post