Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Markdown Line Breaks in Code Blocks

Using Redcarpet, when I include something like the following in my markdown, it does not respect any line breaks or indention. I've tried two spaces at the end of lines. Extra lines between code. Nothing seems to work.

```xml
<?xml version="1.0" encoding="UTF-8"?>
<hash>
   <money>3</money>
</hash>

```

I see:

<?xml version="1.0" encoding="UTF-8"?> <hash> <money>3</money> </hash>

Here are the Redcarpet settings:

Redcarpet::Markdown.new(Redcarpet::Render::HTML, :autolink => true, :space_after_headers => true, :fenced_code_blocks => true, :no_intra_emphasis => true, :lax_html_blocks => true)

What do I need to do to make the lines break properly and preserve indention, just like here or on GitHub?

Update - And the source looks like:

<pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
                &lt;hash&gt;
                &lt;money&gt;3&lt;/money&gt;
                &lt;/hash&gt;  
                </code></pre>
like image 730
Karl Avatar asked Feb 03 '23 05:02

Karl


2 Answers

Try wrapping the markdown result in the find_and_preserve Haml helper

# Assuming a setup like this:
markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML)
code_snippet = "    <xml>\n      <tag/>\n    </xml>"

# This should prevent undesirable spaces within code blocks:
find_and_preserve(markdown.render(code_snippet)).html_safe

When you wrap the render call with the find_and_preserve Haml helper, all newlines within <pre> tags in the markdown output are escaped with equivalent HTML entities, and the Haml auto-indention will then ignore them.

like image 186
Ryan McGeary Avatar answered Feb 07 '23 12:02

Ryan McGeary


The result of parsing has newlines inside a <pre> block for me:

require 'redcarpet'
md = Redcarpet::Markdown.new(Redcarpet::Render::HTML, fenced_code_blocks:true)

puts md.render("```xml\n<foo>\n</foo>\n```")
#=> <pre><code class="xml">&lt;foo&gt;
#=> &lt;/foo&gt;
#=> </code></pre>
  1. Confirm that you are seeing a similar wrapper in your output HTML
  2. Set your CSS to use preformatting in <pre> blocks:

    pre { white-space:pre }
    
like image 34
Phrogz Avatar answered Feb 07 '23 13:02

Phrogz