git.iko.soy/typeable/pandoc
on master help sign in
Text.Pandoc.XML: add toHtml5Entities.

[API change]

commit5350ce26b463ccb8edc7b0c7b1be72558e87992c authorJohn MacFarlane <jgm@berkeley.edu> dateThu 1 Nov 2018, 15:59 (8 years ago) parent614b1c0
1 file changed+18
src/Text/Pandoc/XML.hs+18
src/Text/Pandoc/XML.hs+18
@@ -35,6 +35,7 @@ module Text.Pandoc.XML ( escapeCharForXML,
3535 inTagsSimple,
3636 inTagsIndented,
3737 toEntities,
38+ toHtml5Entities,
3839 fromEntities ) where
3940
4041import Prelude
@@ -43,6 +44,8 @@ import Data.Text (Text)
4344import qualified Data.Text as T
4445import Text.HTML.TagSoup.Entity (lookupEntity)
4546import Text.Pandoc.Pretty
47+import qualified Data.Map as M
48+import Text.HTML.TagSoup.Entity (htmlEntities)
4649
4750-- | Escape one character as needed for XML.
4851escapeCharForXML :: Char -> String
@@ -100,6 +103,21 @@ toEntities = T.concatMap go
100103 where go c | isAscii c = T.singleton c
101104 | otherwise = T.pack ("&#" ++ show (ord c) ++ ";")
102105
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+
103121-- Unescapes XML entities
104122fromEntities :: String -> String
105123fromEntities ('&':xs) =