瀏覽代碼

Support for github-style code blocks

Roger Braun 13 年之前
父節點
當前提交
a589a987d4
共有 1 個文件被更改,包括 39 次插入3 次删除
  1. 39 3
      src/showdown.js

+ 39 - 3
src/showdown.js

@@ -355,6 +355,7 @@ var _RunBlockGamut = function(text) {
 	text = text.replace(/^[ ]{0,2}([ ]?\_[ ]?){3,}[ \t]*$/gm,key);
 
 	text = _DoLists(text);
+  text = _DoGithubCodeBlocks(text);
 	text = _DoCodeBlocks(text);
 	text = _DoBlockQuotes(text);
 
@@ -889,12 +890,48 @@ var _DoCodeBlocks = function(text) {
 	return text;
 }
 
+var _DoGithubCodeBlocks = function(text) {
+//
+//  Process Github-style code blocks
+//  Example:
+//  ```ruby
+//  def hello_world(x)
+//    puts "Hello, #{x}"
+//  end
+//  ```
+//  
+
+
+	// attacklab: sentinel workarounds for lack of \A and \Z, safari\khtml bug
+	text += "~0";
+	
+	text = text.replace(/\n```(.*)\n([^`]+)\n```/g,
+		function(wholeMatch,m1,m2) {
+			var language = m1;
+			var codeblock = m2;
+		
+			codeblock = _EncodeCode(codeblock);
+			codeblock = _Detab(codeblock);
+			codeblock = codeblock.replace(/^\n+/g,""); // trim leading newlines
+			codeblock = codeblock.replace(/\n+$/g,""); // trim trailing whitespace
+
+			codeblock = "<pre><code class=" + language + ">" + codeblock + "\n</code></pre>";
+
+			return hashBlock(codeblock);
+		}
+	);
+
+	// attacklab: strip sentinel
+	text = text.replace(/~0/,"");
+
+	return text;
+}
+
 var hashBlock = function(text) {
 	text = text.replace(/(^\n+|\n+$)/g,"");
 	return "\n\n~K" + (g_html_blocks.push(text)-1) + "K\n\n";
 }
 
-
 var _DoCodeSpans = function(text) {
 //
 //   *  Backtick quotes are used for <code></code> spans.
@@ -946,7 +983,6 @@ var _DoCodeSpans = function(text) {
 	return text;
 }
 
-
 var _EncodeCode = function(text) {
 //
 // Encode/escape certain characters inside Markdown code runs.
@@ -1299,4 +1335,4 @@ var escapeCharacters_callback = function(wholeMatch,m1) {
 } // end of Showdown.converter
 
 // export
-if (typeof exports != 'undefined') exports.Showdown = Showdown;
+if (typeof exports != 'undefined') exports.Showdown = Showdown;