Improved --toc generation.

This commit is contained in:
John MacFarlane 2019-12-17 11:59:29 -08:00
parent 80728c8b31
commit d0918627ca
4 changed files with 61 additions and 9 deletions

View file

@ -28,7 +28,7 @@ import Network.HTTP (urlEncode)
import Text.Pandoc.Class (PandocMonad)
import Text.Pandoc.Definition
import Text.Pandoc.Options
import Text.Pandoc.Shared (capitalize, isHeaderBlock, isTightList,
import Text.Pandoc.Shared (capitalize, isTightList,
linesToPara, onlySimpleTableCells, taskListItemToAscii, tshow)
import Text.Pandoc.Templates (renderTemplate)
import Text.Pandoc.Walk (walk, walkM)
@ -40,12 +40,10 @@ import Text.DocLayout (literal, render)
-- | Convert Pandoc to CommonMark.
writeCommonMark :: PandocMonad m => WriterOptions -> Pandoc -> m Text
writeCommonMark opts (Pandoc meta blocks) = do
let headerBlocks = filter isHeaderBlock blocks
toc <- if writerTableOfContents opts
then blocksToCommonMark opts
[ toTableOfContents opts headerBlocks ]
then blocksToCommonMark opts [ toTableOfContents opts blocks ]
else return mempty
let (blocks', notes) = runState (walkM processNotes blocks) []
notes' = if null notes
then []

View file

@ -208,9 +208,8 @@ pandocToMarkdown opts (Pandoc meta blocks) = do
mmdTitleBlock metadata
| otherwise -> empty
Nothing -> empty
let headerBlocks = filter isHeaderBlock blocks
toc <- if writerTableOfContents opts
then blockToMarkdown opts ( toTableOfContents opts headerBlocks )
then blockToMarkdown opts ( toTableOfContents opts blocks )
else return mempty
-- Strip off final 'references' header if markdown citations enabled
let blocks' = if isEnabled Ext_citations opts

View file

@ -103,8 +103,7 @@ writeRTF options doc = do
(fmap literal . inlinesToRTF)
meta'
body <- blocksToRTF 0 AlignDefault blocks
toc <- blocksToRTF 0 AlignDefault
[toTableOfContents options $ filter isHeaderBlock blocks]
toc <- blocksToRTF 0 AlignDefault [toTableOfContents options blocks]
let context = defField "body" body
$ defField "spacer" spacer
$(if writerTableOfContents options

56
test/command/toc.md Normal file
View file

@ -0,0 +1,56 @@
```
% pandoc -s --toc -t markdown
# A
## b
# B
## b
::: interior
# C
## cc
# D
:::
::: blue
# E
## e
:::
^D
- [A](#a)
- [b](#b)
- [B](#b-1)
- [b](#b-2)
- [E](#e)
- [e](#e-1)
A
=
b
-
B
=
b
-
::: {.interior}
C
=
cc
--
D
=
:::
::: {.blue}
E
=
e
-
:::
```