Skip to content

Instantly share code, notes, and snippets.

@eungjun-yi
Created April 10, 2012 08:53
Show Gist options
  • Save eungjun-yi/2349475 to your computer and use it in GitHub Desktop.
Save eungjun-yi/2349475 to your computer and use it in GitHub Desktop.
Coffeescript port of gfm at https://gist.github.com/118964
crypto = require 'crypto'
gfm = (text) ->
# Extract pre blocks
extractions = {}
text = text.replace /<pre>(\n|.)*?<\/pre>/gm, (match) ->
md5 = crypto.createHash('md5').update(match).digest('hex')
extractions[md5] = match
'{gfm-extraction-' + md5 + '}'
# prevent foo_bar_baz from ending up with an italic word in the middle
text = text.replace /(^(?! {4}|\t)\w+_\w+_\w[\w_]*)/gm, (x) ->
x.replace /_/g, '\\_' if (x.match /_/g).length >= 2
# in very clear cases, let newlines become <br /> tags
text = text.replace /^[\w\<][^\n]*\n+/gm, (x) ->
if x.match /\n{2}/ then x else x.trim() + ' \n'
# Insert pre block extractions
text = text.replace /\{gfm-extraction-([0-9a-f]{32})\}/gm, (x, p1) ->
"\n\n" + extractions[p1]
exports.gfm = gfm
assert = require 'assert'
gfm = (require './gfm').gfm
suite 'GFMTest', () ->
test "not touch single underscores inside words", () ->
assert.equal gfm("foo_bar"), "foo_bar"
test "not touch underscores in code blocks", () ->
assert.equal gfm(" foo_bar_baz"), " foo_bar_baz"
test "not touch underscores in pre blocks", () ->
assert.equal gfm("<pre>\nfoo_bar_baz\n</pre>"), "\n\n<pre>\nfoo_bar_baz\n</pre>"
test "not treat pre blocks with pre-text differently", () ->
a = "\n\n<pre>\nthis is `a\\_test` and this\\_too\n</pre>"
b = "hmm<pre>\nthis is `a\\_test` and this\\_too\n</pre>"
assert.equal gfm(b)[3..-1], gfm(a)[2..-1]
test "escape two or more underscores inside words", () ->
assert.equal "foo\\_bar\\_baz", gfm("foo_bar_baz")
test "turn newlines into br tags in simple cases", () ->
assert.equal gfm("foo\nbar"), "foo \nbar"
test "convert newlines in all groups", () ->
assert.equal gfm("apple\npear\norange\n\nruby\npython\nerlang"),
"apple \npear \norange\n\nruby \npython \nerlang"
test "convert newlines in even long groups", () ->
assert.equal gfm("apple\npear\norange\nbanana\n\nruby\npython\nerlang"),
"apple \npear \norange \nbanana\n\nruby \npython \nerlang",
test "not convert newlines in lists", () ->
assert.equal gfm("# foo\n# bar"), "# foo\n# bar"
assert.equal gfm("* foo\n* bar"), "* foo\n* bar"
@eungjun-yi
Copy link
Author

Dependencies

  • mocha
  • node

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment