public
Fork of mojombo/github-flavored-markdown
Description:
Homepage:
Clone URL: git://github.com/github/github-flavored-markdown.git
mojombo (author)
Mon Jun 08 11:53:40 -0700 2009
commit  a28709dfc97cfec9ca7909f014562e644344b167
tree    cda4b1f339b994be70b55470f119c7bd0ab58307
parent  5be9a3e94f39b42a3a8d4a4c7f44c9472a800431
100644 67 lines (54 sloc) 1.874 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
require 'digest/md5'
 
def gfm(text)
  # Extract pre blocks
  extractions = {}
  text.gsub!(%r{<pre>.*?</pre>}m) do |match|
    md5 = Digest::MD5.hexdigest(match)
    extractions[md5] = match
    "{gfm-extraction-#{md5}}"
  end
 
  # prevent foo_bar_baz from ending up with an italic word in the middle
  text.gsub!(/(^(?! {4}|\t)\w+_\w+_\w[\w_]*)/) do |x|
    x.gsub('_', '\_') if x.split('').sort.to_s[0..1] == '__'
  end
 
  # in very clear cases, let newlines become <br /> tags
  text.gsub!(/(\A|^$\n)(^\w[^\n]*\n)(^\w[^\n]*$)+/m) do |x|
    x.gsub(/^(.+)$/, "\\1 ")
  end
 
  # Insert pre block extractions
  text.gsub!(/\{gfm-extraction-([0-9a-f]{32})\}/) do
    extractions[$1]
  end
 
  text
end
 
if $0 == __FILE__
  require 'test/unit'
  require 'shoulda'
 
  class GFMTest < Test::Unit::TestCase
    context "GFM" do
      should "not touch single underscores inside words" do
        assert_equal "foo_bar", gfm("foo_bar")
      end
 
      should "not touch underscores in code blocks" do
        assert_equal " foo_bar_baz", gfm(" foo_bar_baz")
      end
 
      should "not touch underscores in pre blocks" do
        assert_equal "<pre>\nfoo_bar_baz\n</pre>", gfm("<pre>\nfoo_bar_baz\n</pre>")
      end
 
      should "escape two or more underscores inside words" do
        assert_equal "foo\\_bar\\_baz", gfm("foo_bar_baz")
      end
 
      should "turn newlines into br tags in simple cases" do
        assert_equal "foo \nbar ", gfm("foo\nbar")
      end
 
      should "convert newlines in all groups" do
        assert_equal "apple \npear \norange\n\nruby \npython \nerlang",
                     gfm("apple\npear\norange\n\nruby\npython\nerlang")
      end
 
      should "not convert newlines in lists" do
        assert_equal "# foo\n# bar", gfm("# foo\n# bar")
        assert_equal "* foo\n* bar", gfm("* foo\n* bar")
      end
    end
  end
end