Quick tip - Markdown with hard breaks
I am currently readying Trackplace for the world. Trackplace is a simple web app that can help you track and share things. It's been a personal project/hobby of mine for a while and it'll be fun to see it out the wild soon...
Anyways... the site uses Markdown via the BlueCloth gem to markup portions of the site. While I personally love Markdown, almost all my friends who are beta-testing the site complain that "the site bunches up all my lines" or "I can't make a new line".
This is due to Markdown's choice of paragraph implementation:
A paragraph is simply one or more consecutive lines of text, separated by one or more blank lines.
The implication of the “one or more consecutive lines of text” rule is that Markdown supports “hard-wrapped” text paragraphs. This differs significantly from most other text-to-HTML formatters (including Movable Type’s “Convert Line Breaks” option) which translate every line break character in a paragraph into a <br /> tag.
Yet I needed Markdown to respect a "\n" from the user...
As Paul Graham said:
Part of what software has to do is explain itself. So to write good software you have to understand how little users understand. They're going to walk up to the software with no preparation, and it had better do what they guess it will, because they're not going to read the manual.
I first started playing with regular expressions to post-process the html from BlueCloth. But that got real hairy real fast. Just when I thought all was lost... Hpricot turns up to save the day. Hpricot really is one of my new favorite tools - thanks Why! Basically I only wanted to insert hard breaks inside paragraphs and so a simple helper does the trick.
application_helper.rb
require 'hpricot'
module ApplicationHelper
def md(str)
return '' if str.blank?
# --- [ add hard line breaks ] ---
returning html = BlueCloth.new(str).to_html do
Hpricot(html).search("//p").each do |p|
html.sub!(p.to_s, p.to_s.gsub(%r{\n+}, "\n<br/>\n"))
end
end
end
end


3 Comments
markdown manual (daringfireball):
When you do want to insert a
break tag using Markdown, you end a line with two or more spaces, then type return.
Works like a charm for me
Joeri - You are definately right and I myself use the two spaces frequently.
However the average user of a web application has no idea what Markdown is and even if they did they would'nt read the manual. So in this case I needed a way to tweak Bluecloth/Markdown just a bit to give the user what he/she expected.
Fantastic, thanks very much. I'd been scratching my head about this for a while.
I too agree with you that 95% of people expect a line break to be turned into a line break. Redcloth has also gone down the line of not having hard breaks, so this is fantastically handy.
Commenting is closed for this article.