git.iko.soy/typeable/pandoc
on master help sign in
Docx Writer: Filter out illegal XML characters

Fixes #1992

commitf3aa03ee8609f26cfc3fd250a957fe4376458d97 authorMatthew Pickering <matthewtpickering@gmail.com> dateSun 29 Mar 2015, 13:35 (12 years ago) parentaa49dec
1 file changed+19−2
src/Text/Pandoc/Writers/Docx.hs+19−2
src/Text/Pandoc/Writers/Docx.hs+19−2
@@ -1,4 +1,4 @@
1−{-# LANGUAGE ScopedTypeVariables, PatternGuards #-}
1+{-# LANGUAGE ScopedTypeVariables, PatternGuards, ViewPatterns #-}
22{-
33Copyright (C) 2012-2014 John MacFarlane <jgm@berkeley.edu>
44
@@ -66,6 +66,7 @@ import Text.Pandoc.MIME (MimeType, getMimeType, getMimeTypeDef,
6666 extensionFromMimeType)
6767import Control.Applicative ((<$>), (<|>), (<*>))
6868import Data.Maybe (fromMaybe, mapMaybe, maybeToList)
69+import Data.Char (ord)
6970
7071data ListMarker = NoMarker
7172 | BulletMarker
@@ -176,13 +177,29 @@ renumId f renumMap e
176177renumIds :: (QName -> Bool) -> (M.Map String String) -> [Element] -> [Element]
177178renumIds f renumMap = map (renumId f renumMap)
178179
180+-- | Certain characters are invalid in XML even if escaped.
181+-- See #1992
182+stripInvalidChars :: Pandoc -> Pandoc
183+stripInvalidChars = bottomUp (filter isValidChar)
184+
185+-- | See XML reference
186+isValidChar :: Char -> Bool
187+isValidChar (ord -> c)
188+ | c == 0x9 = True
189+ | c == 0xA = True
190+ | c == 0xD = True
191+ | 0x20 <= c && c <= 0xD7FF = True
192+ | 0xE000 <= c && c <= 0xFFFD = True
193+ | 0x10000 <= c && c <= 0x10FFFF = True
194+ | otherwise = False
195+
179196-- | Produce an Docx file from a Pandoc document.
180197writeDocx :: WriterOptions -- ^ Writer options
181198 -> Pandoc -- ^ Document to convert
182199 -> IO BL.ByteString
183200writeDocx opts doc@(Pandoc meta _) = do
184201 let datadir = writerUserDataDir opts
185− let doc' = walk fixDisplayMath doc
202+ let doc' = stripInvalidChars . walk fixDisplayMath $ doc
186203 username <- lookup "USERNAME" <$> getEnvironment
187204 utctime <- getCurrentTime
188205 refArchive <- liftM (toArchive . toLazy) $