Markdown Line Breaks in Code Blocks

本秂侑毒 提交于 2019-12-05 06:58:13

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.

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 }
    
darKoram

On Github, all I needed to do was wrap my indented/formatted text with <pre> and </pre> tags.

Try this script to isolate whether it's something in your app or redcarpet.

I'm not able to reproduce the issue you're having (With the redcarpet-2.1.1 gem). Put this into a file, then run it (ruby redcarpet_test.rb):

require 'rubygems'
require 'redcarpet'

md = %Q{...
```xml
<?xml version="1.0" encoding="UTF-8"?>
<hash>
   <money>3</money>
</hash>
```
...}

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

puts r.render md

That results appropriately with:

<p>...
<code>xml
&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>
...</p>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!