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
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ViewPatterns #-}
{- |
Module : Text.Pandoc.Writers.CommonMark
Copyright : Copyright (C) 2015-2020 John MacFarlane
License : GNU GPL, version 2 or above
Maintainer : John MacFarlane <jgm@berkeley.edu>
Stability : alpha
Portability : portable
Conversion of 'Pandoc' documents to CommonMark.
CommonMark: <http://commonmark.org>
-}
module Text.Pandoc.Writers.CommonMark (writeCommonMark) where
import CMarkGFM
import Control.Monad.State.Strict (State, get, modify, runState)
import Data.Char (isAscii)
import Data.Foldable (foldrM)
import Data.List (transpose)
import Data.Text (Text)
import qualified Data.Text as T
import Network.HTTP (urlEncode)
import Text.Pandoc.Class.PandocMonad (PandocMonad)
import Text.Pandoc.Definition
import Text.Pandoc.Options
import Text.Pandoc.Shared (capitalize, isTightList,
linesToPara, onlySimpleTableCells, taskListItemToAscii, tshow)
import Text.Pandoc.Templates (renderTemplate)
import Text.Pandoc.Walk (walk, walkM)
import Text.Pandoc.Writers.HTML (writeHtml5String, tagWithAttributes)
import Text.Pandoc.Writers.Shared
import Text.Pandoc.XML (toHtml5Entities)
import Text.DocLayout (literal, render)
-- | Convert Pandoc to CommonMark.
writeCommonMark :: PandocMonad m => WriterOptions -> Pandoc -> m Text
writeCommonMark opts (Pandoc meta blocks) = do
toc <- if writerTableOfContents opts
then blocksToCommonMark opts [ toTableOfContents opts blocks ]
else return mempty
let (blocks', notes) = runState (walkM processNotes blocks) []
notes' = [OrderedList (1, Decimal, Period) $ reverse notes | not (null notes)]
main <- blocksToCommonMark opts (blocks' ++ notes')
metadata <- metaToContext opts
(fmap (literal . T.stripEnd) . blocksToCommonMark opts)
(fmap (literal . T.stripEnd) . inlinesToCommonMark opts)
meta
let context =
-- for backwards compatibility we populate toc
-- with the contents of the toc, rather than a boolean:
defField "toc" toc
$ defField "table-of-contents" toc
$ defField "body" main metadata
return $
case writerTemplate opts of
Nothing -> main
Just tpl -> render Nothing $ renderTemplate tpl context
softBreakToSpace :: Inline -> Inline
softBreakToSpace SoftBreak = Space
softBreakToSpace x = x
processNotes :: Inline -> State [[Block]] Inline
processNotes (Note bs) = do
modify (bs :)
notes <- get
return $ Str $ "[" <> tshow (length notes) <> "]"
processNotes x = return x
node :: NodeType -> [Node] -> Node
node = Node Nothing
blocksToCommonMark :: PandocMonad m => WriterOptions -> [Block] -> m Text
blocksToCommonMark opts bs = do
let cmarkOpts = [optHardBreaks | isEnabled Ext_hard_line_breaks opts]
colwidth = if writerWrapText opts == WrapAuto
then Just $ writerColumns opts
else Nothing
nodes <- blocksToNodes opts bs
return $ T.stripEnd $
nodeToCommonmark cmarkOpts colwidth $
node DOCUMENT nodes
inlinesToCommonMark :: PandocMonad m => WriterOptions -> [Inline] -> m Text
inlinesToCommonMark opts ils = return $
nodeToCommonmark cmarkOpts colwidth $
node PARAGRAPH (inlinesToNodes opts ils)
where cmarkOpts = [optHardBreaks | isEnabled Ext_hard_line_breaks opts]
colwidth = if writerWrapText opts == WrapAuto
then Just $ writerColumns opts
else Nothing
blocksToNodes :: PandocMonad m => WriterOptions -> [Block] -> m [Node]
blocksToNodes opts = foldrM (blockToNodes opts) []
blockToNodes :: PandocMonad m => WriterOptions -> Block -> [Node] -> m [Node]
blockToNodes opts (Plain xs) ns =
return (node PARAGRAPH (inlinesToNodes opts xs) : ns)
blockToNodes opts (Para xs) ns =
return (node PARAGRAPH (inlinesToNodes opts xs) : ns)
blockToNodes opts (LineBlock lns) ns = blockToNodes opts (linesToPara lns) ns
blockToNodes _ (CodeBlock (_,classes,_) xs) ns = return
(node (CODE_BLOCK (T.unwords classes) xs) [] : ns)
blockToNodes opts (RawBlock (Format f) xs) ns
| f == "html" && isEnabled Ext_raw_html opts
= return (node (HTML_BLOCK xs) [] : ns)
| (f == "latex" || f == "tex") && isEnabled Ext_raw_tex opts
= return (node (CUSTOM_BLOCK xs T.empty) [] : ns)
| f == "markdown"
= return (node (CUSTOM_BLOCK xs T.empty) [] : ns)
| otherwise = return ns
blockToNodes opts (BlockQuote bs) ns = do
nodes <- blocksToNodes opts bs
return (node BLOCK_QUOTE nodes : ns)
blockToNodes opts (BulletList items) ns = do
let exts = writerExtensions opts
nodes <- mapM (blocksToNodes opts . taskListItemToAscii exts) items
return (node (LIST ListAttributes{
listType = BULLET_LIST,
listDelim = PERIOD_DELIM,
listTight = isTightList items,
listStart = 1 }) (map (node ITEM) nodes) : ns)
blockToNodes opts (OrderedList (start, _sty, delim) items) ns = do
let exts = writerExtensions opts
nodes <- mapM (blocksToNodes opts . taskListItemToAscii exts) items
return (node (LIST ListAttributes{
listType = ORDERED_LIST,
listDelim = case delim of
OneParen -> PAREN_DELIM
TwoParens -> PAREN_DELIM
_ -> PERIOD_DELIM,
listTight = isTightList items,
listStart = start }) (map (node ITEM) nodes) : ns)
blockToNodes _ HorizontalRule ns = return (node THEMATIC_BREAK [] : ns)
blockToNodes opts (Header lev _ ils) ns =
return (node (HEADING lev) (inlinesToNodes opts ils) : ns)
blockToNodes opts (Div attr bs) ns = do
nodes <- blocksToNodes opts bs
let op = tagWithAttributes opts True False "div" attr
if isEnabled Ext_raw_html opts
then return (node (HTML_BLOCK op) [] : nodes ++
[node (HTML_BLOCK (T.pack "</div>")) []] ++ ns)
else return (nodes ++ ns)
blockToNodes opts (DefinitionList items) ns =
blockToNodes opts (BulletList items') ns
where items' = map dlToBullet items
dlToBullet (term, (Para xs : ys) : zs) =
Para (term ++ [LineBreak] ++ xs) : ys ++ concat zs
dlToBullet (term, (Plain xs : ys) : zs) =
Plain (term ++ [LineBreak] ++ xs) : ys ++ concat zs
dlToBullet (term, xs) =
Para term : concat xs
blockToNodes opts t@(Table _ blkCapt specs thead tbody tfoot) ns =
let (capt, aligns, _widths, headers, rows) = toLegacyTable blkCapt specs thead tbody tfoot
in if isEnabled Ext_pipe_tables opts && onlySimpleTableCells (headers : rows)
then do
-- We construct a table manually as a CUSTOM_BLOCK, for
-- two reasons: (1) cmark-gfm currently doesn't support
-- rendering TABLE nodes; (2) we can align the column sides;
-- (3) we can render the caption as a regular paragraph.
let capt' = node PARAGRAPH (inlinesToNodes opts capt)
-- backslash | in code and raw:
let fixPipe (Code attr xs) =
Code attr (T.replace "|" "\\|" xs)
fixPipe (RawInline format xs) =
RawInline format (T.replace "|" "\\|" xs)
fixPipe x = x
let toCell [Plain ils] = T.strip
$ nodeToCommonmark [] Nothing
$ node (CUSTOM_INLINE mempty mempty)
$ inlinesToNodes opts
$ walk (fixPipe . softBreakToSpace) ils
toCell [Para ils] = T.strip
$ nodeToCommonmark [] Nothing
$ node (CUSTOM_INLINE mempty mempty)
$ inlinesToNodes opts
$ walk (fixPipe . softBreakToSpace) ils
toCell [] = ""
toCell xs = error $ "toCell encountered " ++ show xs
let separator = " | "
let starter = "| "
let ender = " |"
let rawheaders = map toCell headers
let rawrows = map (map toCell) rows
let maximum' [] = 0
maximum' xs = maximum xs
let colwidths = map (maximum' . map T.length) $
transpose (rawheaders:rawrows)
let toHeaderLine len AlignDefault = T.replicate len "-"
toHeaderLine len AlignLeft = ":" <>
T.replicate (max (len - 1) 1) "-"
toHeaderLine len AlignRight =
T.replicate (max (len - 1) 1) "-" <> ":"
toHeaderLine len AlignCenter = ":" <>
T.replicate (max (len - 2) 1) (T.pack "-") <> ":"
let rawheaderlines = zipWith toHeaderLine colwidths aligns
let headerlines = starter <> T.intercalate separator rawheaderlines <>
ender
let padContent (align, w) t' =
let padding = w - T.length t'
halfpadding = padding `div` 2
in case align of
AlignRight -> T.replicate padding " " <> t'
AlignCenter -> T.replicate halfpadding " " <> t' <>
T.replicate (padding - halfpadding) " "
_ -> t' <> T.replicate padding " "
let toRow xs = starter <> T.intercalate separator
(zipWith padContent (zip aligns colwidths) xs) <>
ender
let table' = toRow rawheaders <> "\n" <> headerlines <> "\n" <>
T.intercalate "\n" (map toRow rawrows)
return (node (CUSTOM_BLOCK table' mempty) [] :
if null capt
then ns
else capt' : ns)
else do -- fall back to raw HTML
s <- writeHtml5String def $! Pandoc nullMeta [t]
return (node (HTML_BLOCK s) [] : ns)
blockToNodes _ Null ns = return ns
inlinesToNodes :: WriterOptions -> [Inline] -> [Node]
inlinesToNodes opts = foldr (inlineToNodes opts) []
inlineToNodes :: WriterOptions -> Inline -> [Node] -> [Node]
inlineToNodes opts (Str s) = stringToNodes opts s'
where s' = if isEnabled Ext_smart opts
then unsmartify opts s
else s
inlineToNodes _ Space = (node (TEXT (T.pack " ")) [] :)
inlineToNodes _ LineBreak = (node LINEBREAK [] :)
inlineToNodes opts SoftBreak
| isEnabled Ext_hard_line_breaks opts = (node (TEXT " ") [] :)
| writerWrapText opts == WrapNone = (node (TEXT " ") [] :)
| otherwise = (node SOFTBREAK [] :)
inlineToNodes opts (Emph xs) = (node EMPH (inlinesToNodes opts xs) :)
inlineToNodes opts (Strong xs) = (node STRONG (inlinesToNodes opts xs) :)
inlineToNodes opts (Strikeout xs)
| isEnabled Ext_strikeout opts = (node (CUSTOM_INLINE "~~" "~~") (inlinesToNodes opts xs) :)
| isEnabled Ext_raw_html opts = ((node (HTML_INLINE (T.pack "<s>")) [] : inlinesToNodes opts xs ++
[node (HTML_INLINE (T.pack "</s>")) []]) ++ )
| otherwise = (inlinesToNodes opts xs ++)
inlineToNodes opts (Superscript xs) =
if isEnabled Ext_raw_html opts
then ((node (HTML_INLINE (T.pack "<sup>")) [] : inlinesToNodes opts xs ++
[node (HTML_INLINE (T.pack "</sup>")) []]) ++ )
else case traverse toSuperscriptInline xs of
Just xs' | not (writerPreferAscii opts)
-> (inlinesToNodes opts xs' ++)
_ ->
((node (TEXT (T.pack "^(")) [] : inlinesToNodes opts xs ++
[node (TEXT (T.pack ")")) []]) ++ )
inlineToNodes opts (Subscript xs) =
if isEnabled Ext_raw_html opts
then ((node (HTML_INLINE (T.pack "<sub>")) [] : inlinesToNodes opts xs ++
[node (HTML_INLINE (T.pack "</sub>")) []]) ++ )
else case traverse toSubscriptInline xs of
Just xs' | not (writerPreferAscii opts)
-> (inlinesToNodes opts xs' ++)
_ ->
((node (TEXT (T.pack "_(")) [] : inlinesToNodes opts xs ++
[node (TEXT (T.pack ")")) []]) ++ )
inlineToNodes opts (SmallCaps xs) =
if isEnabled Ext_raw_html opts
then ((node (HTML_INLINE (T.pack "<span class=\"smallcaps\">")) []
: inlinesToNodes opts xs ++
[node (HTML_INLINE (T.pack "</span>")) []]) ++ )
else (inlinesToNodes opts (capitalize xs) ++)
inlineToNodes opts (Link _ ils (url,tit)) =
(node (LINK url tit) (inlinesToNodes opts ils) :)
-- title beginning with fig: indicates implicit figure
inlineToNodes opts (Image alt ils (url,T.stripPrefix "fig:" -> Just tit)) =
inlineToNodes opts (Image alt ils (url,tit))
inlineToNodes opts (Image _ ils (url,tit)) =
(node (IMAGE url tit) (inlinesToNodes opts ils) :)
inlineToNodes opts (RawInline (Format f) xs)
| f == "html" && isEnabled Ext_raw_html opts
= (node (HTML_INLINE xs) [] :)
| (f == "latex" || f == "tex") && isEnabled Ext_raw_tex opts
= (node (CUSTOM_INLINE xs T.empty) [] :)
| f == "markdown"
= (node (CUSTOM_INLINE xs T.empty) [] :)
| otherwise = id
inlineToNodes opts (Quoted qt ils) =
((node (HTML_INLINE start) [] :
inlinesToNodes opts ils ++ [node (HTML_INLINE end) []]) ++)
where (start, end) = case qt of
SingleQuote
| isEnabled Ext_smart opts -> ("'","'")
| writerPreferAscii opts ->
("‘", "’")
| otherwise -> ("‘", "’")
DoubleQuote
| isEnabled Ext_smart opts -> ("\"", "\"")
| writerPreferAscii opts ->
("“", "”")
| otherwise -> ("“", "”")
inlineToNodes _ (Code _ str) = (node (CODE str) [] :)
inlineToNodes opts (Math mt str) =
case writerHTMLMathMethod opts of
WebTeX url ->
let core = inlineToNodes opts
(Image nullAttr [Str str] (url <> T.pack (urlEncode $ T.unpack str), str))
sep = if mt == DisplayMath
then (node LINEBREAK [] :)
else id
in (sep . core . sep)
_ ->
case mt of
InlineMath ->
(node (HTML_INLINE ("\\(" <> str <> "\\)")) [] :)
DisplayMath ->
(node (HTML_INLINE ("\\[" <> str <> "\\]")) [] :)
inlineToNodes opts (Span ("",["emoji"],kvs) [Str s]) =
case lookup "data-emoji" kvs of
Just emojiname | isEnabled Ext_emoji opts ->
(node (TEXT (":" <> emojiname <> ":")) [] :)
_ -> (node (TEXT s) [] :)
inlineToNodes opts (Span attr ils) =
let nodes = inlinesToNodes opts ils
op = tagWithAttributes opts True False "span" attr
in if isEnabled Ext_raw_html opts
then ((node (HTML_INLINE op) [] : nodes ++
[node (HTML_INLINE (T.pack "</span>")) []]) ++)
else (nodes ++)
inlineToNodes opts (Cite _ ils) = (inlinesToNodes opts ils ++)
inlineToNodes _ (Note _) = id -- should not occur
-- we remove Note elements in preprocessing
stringToNodes :: WriterOptions -> Text -> [Node] -> [Node]
stringToNodes opts s
| not (writerPreferAscii opts) = (node (TEXT s) [] :)
| otherwise = step s
where
step input =
let (ascii, rest) = T.span isAscii input
this = node (TEXT ascii) []
nodes = case T.uncons rest of
Nothing -> id
Just (nonAscii, rest') ->
let escaped = toHtml5Entities (T.singleton nonAscii)
in (node (HTML_INLINE escaped) [] :) . step rest'
in (this :) . nodes
toSubscriptInline :: Inline -> Maybe Inline
toSubscriptInline Space = Just Space
toSubscriptInline (Span attr ils) = Span attr <$> traverse toSubscriptInline ils
toSubscriptInline (Str s) = Str . T.pack <$> traverse toSubscript (T.unpack s)
toSubscriptInline LineBreak = Just LineBreak
toSubscriptInline SoftBreak = Just SoftBreak
toSubscriptInline _ = Nothing
toSuperscriptInline :: Inline -> Maybe Inline
toSuperscriptInline Space = Just Space
toSuperscriptInline (Span attr ils) = Span attr <$> traverse toSuperscriptInline ils
toSuperscriptInline (Str s) = Str . T.pack <$> traverse toSuperscript (T.unpack s)
toSuperscriptInline LineBreak = Just LineBreak
toSuperscriptInline SoftBreak = Just SoftBreak
toSuperscriptInline _ = Nothing
|