git.iko.soy/typeable/pandoc
on master help sign in
Text.Pandoc.XML: add toHtml5Entities.
5350ce2John MacFarlane
src/Text/Pandoc/XML.hs+18
@@ -35,6 +35,7 @@ module Text.Pandoc.XML ( escapeCharForXML,
35 inTagsSimple,
35 inTagsSimple,
36 inTagsIndented,
36 inTagsIndented,
37 toEntities,
37 toEntities,
38+ toHtml5Entities,
38 fromEntities ) where
39 fromEntities ) where
39
40
40import Prelude
41import Prelude
@@ -43,6 +44,8 @@ import Data.Text (Text)
43import qualified Data.Text as T
44import qualified Data.Text as T
44import Text.HTML.TagSoup.Entity (lookupEntity)
45import Text.HTML.TagSoup.Entity (lookupEntity)
45import Text.Pandoc.Pretty
46import Text.Pandoc.Pretty
47+import qualified Data.Map as M
48+import Text.HTML.TagSoup.Entity (htmlEntities)
46
49
47-- | Escape one character as needed for XML.
50-- | Escape one character as needed for XML.
48escapeCharForXML :: Char -> String
51escapeCharForXML :: Char -> String
@@ -100,6 +103,21 @@ toEntities = T.concatMap go
100 where go c | isAscii c = T.singleton c
103 where go c | isAscii c = T.singleton c
101 | otherwise = T.pack ("&#" ++ show (ord c) ++ ";")
104 | otherwise = T.pack ("&#" ++ show (ord c) ++ ";")
102
105
106+-- | Escape all non-ascii characters using HTML5 entities, falling
107+-- back to numerical entities.
108+toHtml5Entities :: Text -> Text
109+toHtml5Entities = T.concatMap go
110+ where go c | isAscii c = T.singleton c
111+ | otherwise =
112+ case M.lookup c html5EntityMap of
113+ Just t -> T.singleton '&' <> t <> T.singleton ';'
114+ Nothing -> T.pack ("&#" ++ show (ord c) ++ ";")
115+
116+html5EntityMap :: M.Map Char Text
117+html5EntityMap = M.fromList [(c, T.takeWhile (/=';') (T.pack ent))
118+ | (ent@(_:_), [c]) <- htmlEntities
119+ , last ent == ';']
120+
103-- Unescapes XML entities
121-- Unescapes XML entities
104fromEntities :: String -> String
122fromEntities :: String -> String
105fromEntities ('&':xs) =
123fromEntities ('&':xs) =