Python-Markdown / markdown

A Python implementation of John Gruber’s Markdown with Extension support.
https://python-markdown.github.io/
BSD 3-Clause "New" or "Revised" License
3.8k stars 862 forks source link

Fenced code blocks with newlines not parsed into html <code> blocks #1458

Closed SNeugber closed 7 months ago

SNeugber commented 7 months ago

I found a behaviour I wasn't expecting: when fenced code blocks contain newlines they are split up into individual <p> paragraphs, instead of one big <code> block.

Would you be able to clarify if this is a bug or not?

Sample code to reproduce:

import markdown

md_text_ok = """
\`\`\` # Having to escape this for github... ignore the back slashes please
foo
\`\`\`
"""

rendered = markdown.markdown(md_text_ok) # -> '<p><code>foo</code></p>'

md_text_broken = """
\`\`\`

foo
\`\`\`
"""

rendered = markdown.markdown(md_text_broken) # -> '<p>```</p>\n<p>foo\n```</p>'
waylan commented 7 months ago

You need to enable the fenced_code extension.

markdown.markdown(some_text, extensions=['fenced_code'])
SNeugber commented 7 months ago

Oooh, I was not aware, my bad. Thanks for clarifying, it works now :+1:

pythoninthegrass commented 5 months ago

Thanks for the solution @waylan! Was able to get my template working like so:

#!/usr/bin/env python

import markdown

msg = """
# Hello, world!

This is a **test email** from [Resend](https://resend.com).

\```bash
python -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements.txt
./send_email.py
\```
""".lstrip()

html = markdown.markdown(msg, extensions=["fenced_code"])

print(html)

(Ignore the escaped code block in nested markdown. Probably a better way to do it on GitHub, but don't have the bandwidth to find out)