1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
|
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ViewPatterns #-}
{- |
Module : Text.Pandoc.XML
Copyright : Copyright (C) 2006-2020 John MacFarlane
License : GNU GPL, version 2 or above
Maintainer : John MacFarlane <jgm@berkeley.edu>
Stability : alpha
Portability : portable
Functions for escaping and formatting XML.
-}
module Text.Pandoc.XML ( escapeCharForXML,
escapeStringForXML,
inTags,
selfClosingTag,
inTagsSimple,
inTagsIndented,
toEntities,
toHtml5Entities,
fromEntities,
html4Attributes,
html5Attributes,
rdfaAttributes ) where
import Data.Char (isAscii, isSpace, ord)
import Data.Text (Text)
import qualified Data.Text as T
import Text.HTML.TagSoup.Entity (lookupEntity, htmlEntities)
import Text.DocLayout
import Text.Printf (printf)
import qualified Data.Map as M
import Data.String
import qualified Data.Set as Set
-- | Escape one character as needed for XML.
escapeCharForXML :: Char -> Text
escapeCharForXML x = case x of
'&' -> "&"
'<' -> "<"
'>' -> ">"
'"' -> """
c -> T.singleton c
-- | Escape string as needed for XML. Entity references are not preserved.
escapeStringForXML :: Text -> Text
escapeStringForXML = T.concatMap escapeCharForXML . T.filter isLegalXMLChar
where isLegalXMLChar c = c == '\t' || c == '\n' || c == '\r' ||
(c >= '\x20' && c <= '\xD7FF') ||
(c >= '\xE000' && c <= '\xFFFD') ||
(c >= '\x10000' && c <= '\x10FFFF')
-- see https://www.w3.org/TR/xml/#charsets
-- | Escape newline characters as
escapeNls :: Text -> Text
escapeNls = T.concatMap $ \case
'\n' -> " "
c -> T.singleton c
-- | Return a text object with a string of formatted XML attributes.
attributeList :: (HasChars a, IsString a) => [(Text, Text)] -> Doc a
attributeList = hcat . map
(\(a, b) -> text (T.unpack $ " " <> escapeStringForXML a <> "=\"" <>
escapeNls (escapeStringForXML b) <> "\""))
-- | Put the supplied contents between start and end tags of tagType,
-- with specified attributes and (if specified) indentation.
inTags :: (HasChars a, IsString a)
=> Bool -> Text -> [(Text, Text)] -> Doc a -> Doc a
inTags isIndented tagType attribs contents =
let openTag = char '<' <> text (T.unpack tagType) <> attributeList attribs <>
char '>'
closeTag = text "</" <> text (T.unpack tagType) <> char '>'
in if isIndented
then openTag $$ nest 2 contents $$ closeTag
else openTag <> contents <> closeTag
-- | Return a self-closing tag of tagType with specified attributes
selfClosingTag :: (HasChars a, IsString a)
=> Text -> [(Text, Text)] -> Doc a
selfClosingTag tagType attribs =
char '<' <> text (T.unpack tagType) <> attributeList attribs <> text " />"
-- | Put the supplied contents between start and end tags of tagType.
inTagsSimple :: (HasChars a, IsString a)
=> Text -> Doc a -> Doc a
inTagsSimple tagType = inTags False tagType []
-- | Put the supplied contents in indented block btw start and end tags.
inTagsIndented :: (HasChars a, IsString a)
=> Text -> Doc a -> Doc a
inTagsIndented tagType = inTags True tagType []
-- | Escape all non-ascii characters using numerical entities.
toEntities :: Text -> Text
toEntities = T.concatMap go
where go c | isAscii c = T.singleton c
| otherwise = T.pack (printf "&#x%X;" (ord c))
-- | Escape all non-ascii characters using HTML5 entities, falling
-- back to numerical entities.
toHtml5Entities :: Text -> Text
toHtml5Entities = T.concatMap go
where go c | isAscii c = T.singleton c
| otherwise =
case M.lookup c html5EntityMap of
Just t -> T.singleton '&' <> t <> T.singleton ';'
Nothing -> T.pack ("&#" ++ show (ord c) ++ ";")
html5EntityMap :: M.Map Char Text
html5EntityMap = foldr go mempty htmlEntities
where go (ent, s) entmap =
case s of
[c] -> M.insertWith
(\new old -> if T.length new > T.length old
then old
else new) c ent' entmap
where ent' = T.takeWhile (/=';') (T.pack ent)
_ -> entmap
-- Unescapes XML entities
fromEntities :: Text -> Text
fromEntities = T.pack . fromEntities'
fromEntities' :: Text -> String
fromEntities' (T.uncons -> Just ('&', xs)) =
case lookupEntity $ T.unpack ent' of
Just c -> c <> fromEntities' rest
Nothing -> "&" <> fromEntities' xs
where (ent, rest) = case T.break (\c -> isSpace c || c == ';') xs of
(zs,T.uncons -> Just (';',ys)) -> (zs,ys)
(zs, ys) -> (zs,ys)
ent'
| Just ys <- T.stripPrefix "#X" ent = "#x" <> ys -- workaround tagsoup bug
| Just ('#', _) <- T.uncons ent = ent
| otherwise = ent <> ";"
fromEntities' t = case T.uncons t of
Just (x, xs) -> x : fromEntities' xs
Nothing -> ""
html5Attributes :: Set.Set Text
html5Attributes = Set.fromList
[ "abbr"
, "accept"
, "accept-charset"
, "accesskey"
, "action"
, "allow"
, "allowfullscreen"
, "allowpaymentrequest"
, "allowusermedia"
, "alt"
, "as"
, "async"
, "autocapitalize"
, "autocomplete"
, "autofocus"
, "autoplay"
, "charset"
, "checked"
, "cite"
, "class"
, "color"
, "cols"
, "colspan"
, "content"
, "contenteditable"
, "controls"
, "coords"
, "crossorigin"
, "data"
, "datetime"
, "decoding"
, "default"
, "defer"
, "dir"
, "dirname"
, "disabled"
, "download"
, "draggable"
, "enctype"
, "enterkeyhint"
, "for"
, "form"
, "formaction"
, "formenctype"
, "formmethod"
, "formnovalidate"
, "formtarget"
, "headers"
, "height"
, "hidden"
, "high"
, "href"
, "hreflang"
, "http-equiv"
, "id"
, "imagesizes"
, "imagesrcset"
, "inputmode"
, "integrity"
, "is"
, "ismap"
, "itemid"
, "itemprop"
, "itemref"
, "itemscope"
, "itemtype"
, "kind"
, "label"
, "lang"
, "list"
, "loading"
, "loop"
, "low"
, "manifest"
, "max"
, "maxlength"
, "media"
, "method"
, "min"
, "minlength"
, "multiple"
, "muted"
, "name"
, "nomodule"
, "nonce"
, "novalidate"
, "onabort"
, "onafterprint"
, "onauxclick"
, "onbeforeprint"
, "onbeforeunload"
, "onblur"
, "oncancel"
, "oncanplay"
, "oncanplaythrough"
, "onchange"
, "onclick"
, "onclose"
, "oncontextmenu"
, "oncopy"
, "oncuechange"
, "oncut"
, "ondblclick"
, "ondrag"
, "ondragend"
, "ondragenter"
, "ondragexit"
, "ondragleave"
, "ondragover"
, "ondragstart"
, "ondrop"
, "ondurationchange"
, "onemptied"
, "onended"
, "onerror"
, "onfocus"
, "onhashchange"
, "oninput"
, "oninvalid"
, "onkeydown"
, "onkeypress"
, "onkeyup"
, "onlanguagechange"
, "onload"
, "onloadeddata"
, "onloadedmetadata"
, "onloadend"
, "onloadstart"
, "onmessage"
, "onmessageerror"
, "onmousedown"
, "onmouseenter"
, "onmouseleave"
, "onmousemove"
, "onmouseout"
, "onmouseover"
, "onmouseup"
, "onoffline"
, "ononline"
, "onpagehide"
, "onpageshow"
, "onpaste"
, "onpause"
, "onplay"
, "onplaying"
, "onpopstate"
, "onprogress"
, "onratechange"
, "onrejectionhandled"
, "onreset"
, "onresize"
, "onscroll"
, "onsecuritypolicyviolation"
, "onseeked"
, "onseeking"
, "onselect"
, "onstalled"
, "onstorage"
, "onsubmit"
, "onsuspend"
, "ontimeupdate"
, "ontoggle"
, "onunhandledrejection"
, "onunload"
, "onvolumechange"
, "onwaiting"
, "onwheel"
, "open"
, "optimum"
, "pattern"
, "ping"
, "placeholder"
, "playsinline"
, "poster"
, "preload"
, "readonly"
, "referrerpolicy"
, "rel"
, "required"
, "reversed"
, "role"
, "rows"
, "rowspan"
, "sandbox"
, "scope"
, "selected"
, "shape"
, "size"
, "sizes"
, "slot"
, "span"
, "spellcheck"
, "src"
, "srcdoc"
, "srclang"
, "srcset"
, "start"
, "step"
, "style"
, "tabindex"
, "target"
, "title"
, "translate"
, "type"
, "typemustmatch"
, "updateviacache"
, "usemap"
, "value"
, "width"
, "workertype"
, "wrap"
]
-- See https://en.wikipedia.org/wiki/RDFa, https://www.w3.org/TR/rdfa-primer/
rdfaAttributes :: Set.Set Text
rdfaAttributes = Set.fromList
[ "about"
, "rel"
, "rev"
, "src"
, "href"
, "resource"
, "property"
, "content"
, "datatype"
, "typeof"
, "vocab"
, "prefix"
]
html4Attributes :: Set.Set Text
html4Attributes = Set.fromList
[ "abbr"
, "accept"
, "accept-charset"
, "accesskey"
, "action"
, "align"
, "alink"
, "alt"
, "archive"
, "axis"
, "background"
, "bgcolor"
, "border"
, "cellpadding"
, "cellspacing"
, "char"
, "charoff"
, "charset"
, "checked"
, "cite"
, "class"
, "classid"
, "clear"
, "code"
, "codebase"
, "codetype"
, "color"
, "cols"
, "colspan"
, "compact"
, "content"
, "coords"
, "data"
, "datetime"
, "declare"
, "defer"
, "dir"
, "disabled"
, "enctype"
, "face"
, "for"
, "frame"
, "frameborder"
, "headers"
, "height"
, "href"
, "hreflang"
, "hspace"
, "http-equiv"
, "id"
, "ismap"
, "label"
, "lang"
, "language"
, "link"
, "longdesc"
, "marginheight"
, "marginwidth"
, "maxlength"
, "media"
, "method"
, "multiple"
, "name"
, "nohref"
, "noresize"
, "noshade"
, "nowrap"
, "object"
, "onblur"
, "onchange"
, "onclick"
, "ondblclick"
, "onfocus"
, "onkeydown"
, "onkeypress"
, "onkeyup"
, "onload"
, "onmousedown"
, "onmousemove"
, "onmouseout"
, "onmouseover"
, "onmouseup"
, "onreset"
, "onselect"
, "onsubmit"
, "onunload"
, "profile"
, "prompt"
, "readonly"
, "rel"
, "rev"
, "rows"
, "rowspan"
, "rules"
, "scheme"
, "scope"
, "scrolling"
, "selected"
, "shape"
, "size"
, "span"
, "src"
, "standby"
, "start"
, "style"
, "summary"
, "tabindex"
, "target"
, "text"
, "title"
, "usemap"
, "valign"
, "value"
, "valuetype"
, "version"
, "vlink"
, "vspace"
, "width"
]
|