git.iko.soy/typeable/pandoc
on master help sign in
HTML writer: keep attributes from code nested below pre tag.

If a code block is defined with `<pre><code class="language-x">…</code></pre>`, where the `<pre>` element has no attributes, then the attributes from the `<code>` element are used instead. Any leading `language-` prefix is dropped in the code's *class* attribute are dropped to improve syntax highlighting. Closes: #7221

commit1843a8793a9043a45c8c427b06f100461889d7ef authorAlbert Krewinkel <albert@zeitkraut.de> dateMon 17 May 2021, 18:08 (5 years ago) parent25f5b92
2 files changed+23−1
src/Text/Pandoc/Readers/HTML.hs+12−1 test/Tests/Readers/HTML.hs+11
src/Text/Pandoc/Readers/HTML.hs+12−1
@@ -557,7 +557,18 @@ pFigure = try $ do
557557pCodeBlock :: PandocMonad m => TagParser m Blocks
558558pCodeBlock = try $ do
559559 TagOpen _ attr' <- pSatisfy (matchTagOpen "pre" [])
560− let attr = toAttr attr'
560+ -- if the `pre` has no attributes, try if it is followed by a `code`
561+ -- element and use those attributes if possible.
562+ attr <- case attr' of
563+ _:_ -> pure (toAttr attr')
564+ [] -> option nullAttr $ do
565+ TagOpen _ codeAttr <- pSatisfy (matchTagOpen "code" [])
566+ pure $ toAttr
567+ [ (k, v') | (k, v) <- codeAttr
568+ -- strip language from class
569+ , let v' = if k == "class"
570+ then fromMaybe v (T.stripPrefix "language-" v)
571+ else v ]
561572 contents <- manyTill pAny (pCloses "pre" <|> eof)
562573 let rawText = T.concat $ map tagToText contents
563574 -- drop leading newline if any
test/Tests/Readers/HTML.hs+11
@@ -108,6 +108,17 @@ tests = [ testGroup "base tag"
108108 "<header id=\"title\">Title</header>" =?>
109109 divWith ("title", mempty, mempty) (plain "Title")
110110 ]
111+ , testGroup "code block"
112+ [ test html "attributes in pre > code element" $
113+ "<pre><code id=\"a\" class=\"python\">\nprint('hi')\n</code></pre>"
114+ =?>
115+ codeBlockWith ("a", ["python"], []) "print('hi')"
116+
117+ , test html "attributes in pre take precendence" $
118+ "<pre id=\"c\"><code id=\"d\">\nprint('hi mom!')\n</code></pre>"
119+ =?>
120+ codeBlockWith ("c", [], []) "print('hi mom!')"
121+ ]
111122 , askOption $ \(QuickCheckTests numtests) ->
112123 testProperty "Round trip" $
113124 withMaxSuccess (if QuickCheckTests numtests == defaultValue