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
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE DeriveGeneric #-}
{- |
Module : Text.Pandoc.Chunks
Copyright : Copyright (C) 2022-2023 John MacFarlane
License : GNU GPL, version 2 or above
Maintainer : John MacFarlane <[email protected]>
Stability : alpha
Portability : portable
Functions and types for splitting a Pandoc into subdocuments,
e.g. for conversion into a set of HTML pages.
-}
module Text.Pandoc.Chunks
( Chunk(..)
, ChunkedDoc(..)
, PathTemplate(..)
, splitIntoChunks
, toTOCTree
, SecInfo(..)
) where
import Text.Pandoc.Definition
import Text.Pandoc.Shared (makeSections, stringify, inlineListToIdentifier)
import Text.Pandoc.Walk (Walkable(..))
import Data.Text (Text)
import Text.Printf (printf)
import Data.Maybe (fromMaybe, isNothing)
import qualified Data.Map as M
import qualified Data.Text as T
import Data.String (IsString)
import GHC.Generics (Generic)
import Text.HTML.TagSoup (Tag (TagOpen), fromAttrib, parseTags)
import Data.Tree (Tree(..))
-- | Split 'Pandoc' into 'Chunk's, e.g. for conversion into
-- a set of HTML pages or EPUB chapters.
splitIntoChunks :: PathTemplate -- ^ Template for filepath
-> Bool -- ^ Number sections
-> Maybe Int -- ^ Base heading level
-> Int -- ^ Chunk level -- level of section to split at
-> Pandoc
-> ChunkedDoc
splitIntoChunks pathTemplate numberSections mbBaseLevel
chunklev (Pandoc meta blocks) =
addNav .
fixInternalReferences .
walk rmNavAttrs .
(\chunks -> ChunkedDoc{ chunkedMeta = meta
, chunkedChunks = chunks
, chunkedTOC = toTOCTree' chunks }) .
makeChunks chunklev pathTemplate meta .
makeSections numberSections mbBaseLevel $ blocks
-- | Add chunkNext, chunkPrev, chunkUp
addNav :: ChunkedDoc -> ChunkedDoc
addNav chunkedDoc =
chunkedDoc{ chunkedChunks =
addNext . addPrev . addUp $ chunkedChunks chunkedDoc }
addUp :: [Chunk] -> [Chunk]
addUp (c : d : ds)
| chunkLevel c < chunkLevel d
= c : addUp (d{ chunkUp = Just c } : ds)
| chunkLevel c == chunkLevel d
= c : addUp (d{ chunkUp = chunkUp c} : ds)
addUp (c:cs) = c : addUp cs
addUp [] = []
addNext :: [Chunk] -> [Chunk]
addNext cs = zipWith go cs (map Just (tail cs) ++ [Nothing])
where
go c nxt = c{ chunkNext = nxt }
addPrev :: [Chunk] -> [Chunk]
addPrev cs = zipWith go cs (Nothing : map Just cs)
where
go c prev = c{ chunkPrev = prev }
-- | Fix internal references so they point to the path of the chunk.
fixInternalReferences :: ChunkedDoc -> ChunkedDoc
fixInternalReferences chunkedDoc = walk fixInternalRefs chunkedDoc
where
fixInternalRefs :: Inline -> Inline
fixInternalRefs il@(Link attr ils (src,tit))
= case T.uncons src of
Just ('#', ident) -> Link attr ils (src', tit)
where src' = case M.lookup ident refMap of
Just chunk -> T.pack (chunkPath chunk) <> src
Nothing -> src
_ -> il
fixInternalRefs il = il
refMap = foldr chunkToRefs mempty (chunkedChunks chunkedDoc)
chunkToRefs chunk m =
let idents = chunkId chunk : getIdents (chunkContents chunk)
in foldr (\ident -> M.insert ident chunk) m idents
getIdents bs = query getBlockIdent bs ++ query getInlineIdent bs
getBlockIdent :: Block -> [Text]
getBlockIdent (Div (ident, _, _) _)
| not (T.null ident) = [ident]
getBlockIdent (Header _ (ident, _, _) _)
| not (T.null ident) = [ident]
getBlockIdent (Table (ident,_,_) _ _ _ _ _)
| not (T.null ident) = [ident]
getBlockIdent (RawBlock fmt raw)
| isHtmlFormat fmt
= foldr (\tag ->
case tag of
TagOpen{} ->
case fromAttrib "id" tag of
"" -> id
x -> (x:)
_ -> id)
[] (parseTags raw)
getBlockIdent _ = []
getInlineIdent :: Inline -> [Text]
getInlineIdent (Span (ident, _, _) _)
| not (T.null ident) = [ident]
getInlineIdent (Link (ident, _, _) _ _)
| not (T.null ident) = [ident]
getInlineIdent (Image (ident, _, _) _ _)
| not (T.null ident) = [ident]
getInlineIdent (RawInline fmt raw)
| isHtmlFormat fmt
= foldr (\tag ->
case tag of
TagOpen{} ->
case fromAttrib "id" tag of
"" -> id
x -> (x:)
_ -> id)
[] (parseTags raw)
getInlineIdent _ = []
isHtmlFormat :: Format -> Bool
isHtmlFormat (Format "html") = True
isHtmlFormat (Format "html4") = True
isHtmlFormat (Format "html5") = True
isHtmlFormat _ = False
makeChunks :: Int -> PathTemplate -> Meta -> [Block] -> [Chunk]
makeChunks chunklev pathTemplate meta = secsToChunks 1
where
isChunkHeader :: Block -> Bool
isChunkHeader (Div (_,"section":_,_) (Header n _ _:_)) = n <= chunklev
isChunkHeader _ = False
secsToChunks :: Int -> [Block] -> [Chunk]
secsToChunks chunknum bs =
case break isChunkHeader bs of
([], []) -> []
([], (d@(Div attr@(_,"section":_,_) (h@(Header lvl _ _) : bs')) : rest))
| chunklev == lvl ->
-- If the header is of the same level as chunks, create a chunk
toChunk chunknum d :
secsToChunks (chunknum + 1) rest
| chunklev > lvl ->
case break isChunkHeader bs' of
(xs, ys) -> toChunk chunknum (Div attr (h:xs)) :
secsToChunks (chunknum + 1) (ys ++ rest)
(xs, ys) -> toChunk chunknum
(Div ("",["preamble"],[]) xs) :
secsToChunks (chunknum + 1) ys
toChunk :: Int -> Block -> Chunk
toChunk chunknum
(Div (divid,"section":classes,kvs) (h@(Header lvl _ ils) : bs)) =
Chunk
{ chunkHeading = ils
, chunkId = divid
, chunkLevel = lvl
, chunkNumber = chunknum
, chunkSectionNumber = secnum
, chunkPath = chunkpath
, chunkUp = Nothing
, chunkNext = Nothing
, chunkPrev = Nothing
, chunkUnlisted = "unlisted" `elem` classes
, chunkContents =
[Div (divid,"section":classes,kvs') (h : bs)]
}
where kvs' = kvs ++ [("nav-path", T.pack chunkpath)]
secnum = lookup "number" kvs
chunkpath = resolvePathTemplate pathTemplate chunknum
(stringify ils)
divid
(fromMaybe "" secnum)
toChunk chunknum (Div ("",["preamble"],[]) bs) =
Chunk
{ chunkHeading = docTitle meta
, chunkId = inlineListToIdentifier mempty $ docTitle meta
, chunkLevel = 0
, chunkNumber = chunknum
, chunkSectionNumber = Nothing
, chunkPath = resolvePathTemplate pathTemplate chunknum
(stringify (docTitle meta))
(inlineListToIdentifier mempty (docTitle meta))
"0"
, chunkUp = Nothing
, chunkPrev = Nothing
, chunkNext = Nothing
, chunkUnlisted = False
, chunkContents = bs
}
toChunk _ b = error $ "toChunk called on inappropriate block " <> show b
-- should not happen
-- Remove some attributes we added just to construct chunkNext etc.
rmNavAttrs :: Block -> Block
rmNavAttrs (Div (ident,classes,kvs) bs) =
Div (ident,classes,filter (not . isNavAttr) kvs) bs
where
isNavAttr (k,_) = "nav-" `T.isPrefixOf` k
rmNavAttrs b = b
resolvePathTemplate :: PathTemplate
-> Int -- ^ Chunk number
-> Text -- ^ Stringified heading text
-> Text -- ^ Section identifier
-> Text -- ^ Section number
-> FilePath
resolvePathTemplate (PathTemplate templ) chunknum headingText ident secnum =
T.unpack .
T.replace "%n" (T.pack $ printf "%03d" chunknum) .
T.replace "%s" secnum .
T.replace "%h" headingText .
T.replace "%i" ident $
templ
-- | A 'PathTemplate' is a FilePath in which certain codes
-- will be substituted with information from a 'Chunk'.
-- @%n@ will be replaced with the chunk number
-- (padded with leading 0s to 3 digits),
-- @%s@ with the section number of the heading,
-- @%h@ with the (stringified) heading text,
-- @%i@ with the section identifier.
-- For example, @"section-%s-%i.html"@ might be resolved to
-- @"section-1.2-introduction.html"@.
newtype PathTemplate =
PathTemplate { unPathTemplate :: Text }
deriving (Show, IsString)
-- | A part of a document (typically a chapter or section, or
-- the part of a section before its subsections).
data Chunk =
Chunk
{ chunkHeading :: [Inline]
, chunkId :: Text
, chunkLevel :: Int
, chunkNumber :: Int
, chunkSectionNumber :: Maybe Text
, chunkPath :: FilePath
, chunkUp :: Maybe Chunk
, chunkPrev :: Maybe Chunk
, chunkNext :: Maybe Chunk
, chunkUnlisted :: Bool
, chunkContents :: [Block]
}
deriving (Show, Eq, Generic)
instance Walkable Inline Chunk where
query f chunk = query f (chunkContents chunk)
walk f chunk = chunk{ chunkContents = walk f (chunkContents chunk) }
walkM f chunk = do
contents <- walkM f (chunkContents chunk)
return chunk{ chunkContents = contents }
instance Walkable Block Chunk where
query f chunk = query f (chunkContents chunk)
walk f chunk = chunk{ chunkContents = walk f (chunkContents chunk) }
walkM f chunk = do
contents <- walkM f (chunkContents chunk)
return chunk{ chunkContents = contents }
-- | A 'Pandoc' broken into 'Chunk's for writing to separate files.
data ChunkedDoc =
ChunkedDoc
{ chunkedMeta :: Meta
, chunkedTOC :: Tree SecInfo
, chunkedChunks :: [Chunk]
} deriving (Show, Eq, Generic)
instance Walkable Inline ChunkedDoc where
query f doc = query f (chunkedChunks doc) <> query f (chunkedMeta doc)
walk f doc = doc{ chunkedMeta = walk f (chunkedMeta doc)
, chunkedChunks = walk f (chunkedChunks doc)
}
walkM f doc = do
meta' <- walkM f (chunkedMeta doc)
chunks' <- walkM f (chunkedChunks doc)
return $ doc{ chunkedMeta = meta'
, chunkedChunks = chunks' }
instance Walkable Block ChunkedDoc where
query f doc = query f (chunkedChunks doc) <> query f (chunkedMeta doc)
walk f doc = doc{ chunkedMeta = walk f (chunkedMeta doc)
, chunkedChunks = walk f (chunkedChunks doc)
}
walkM f doc = do
meta' <- walkM f (chunkedMeta doc)
chunks' <- walkM f (chunkedChunks doc)
return $ doc{ chunkedMeta = meta'
, chunkedChunks = chunks' }
-- | Data for a section in a hierarchical document.
data SecInfo =
SecInfo
{ secTitle :: [Inline]
, secNumber :: Maybe Text
, secId :: Text
, secPath :: Text
, secLevel :: Int
} deriving (Show, Eq, Generic)
instance Walkable Inline SecInfo where
query f sec = query f (secTitle sec)
walk f sec = sec{ secTitle = walk f (secTitle sec) }
walkM f sec = do
st <- walkM f (secTitle sec)
return sec{ secTitle = st }
-- | Create tree of sections with titles, links, and numbers,
-- in a form that can be turned into a table of contents.
-- Presupposes that the '[Block]' is the output of 'makeSections'.
toTOCTree :: [Block] -> Tree SecInfo
toTOCTree =
Node SecInfo{ secTitle = []
, secNumber = Nothing
, secId = ""
, secPath = ""
, secLevel = 0 } . foldr go []
where
go :: Block -> [Tree SecInfo] -> [Tree SecInfo]
go (Div (ident,_,_) (Header lev (_,classes,kvs) ils : subsecs))
| not (isNothing (lookup "number" kvs) && "unlisted" `elem` classes)
= ((Node SecInfo{ secTitle = ils
, secNumber = lookup "number" kvs
, secId = ident
, secPath = ""
, secLevel = lev } (foldr go [] subsecs)) :)
go (Div _ [d@Div{}]) = go d -- #8402
go _ = id
toTOCTree' :: [Chunk] -> Tree SecInfo
toTOCTree' =
Node SecInfo{ secTitle = []
, secNumber = Nothing
, secId = ""
, secPath = ""
, secLevel = 0 } . getNodes . filter (not . skippable)
where
skippable c = isNothing (chunkSectionNumber c) && chunkUnlisted c
getNodes :: [Chunk] -> [Tree SecInfo]
getNodes (c:cs) =
let (as, bs) = span (\d -> chunkLevel d > chunkLevel c) cs
secinfo = SecInfo{ secTitle = chunkHeading c,
secNumber = chunkSectionNumber c,
secId = chunkId c,
secPath = T.pack $ chunkPath c,
secLevel = chunkLevel c }
in Node secinfo (getNodes as) : getNodes bs
getNodes [] = []
|