From 255f5de1621876c4b75eeeb6e972df4a2c643255 Mon Sep 17 00:00:00 2001 From: Ingo Schommer Date: Mon, 10 Jan 2011 10:59:22 +0000 Subject: [PATCH] BUGFIX Improved DocumentationParser to avoid empty lines in pre tags, deal with normal markdown code blocks, and html encode lines within pre tags --- code/DocumentationParser.php | 24 ++++++++++++++++++------ tests/DocumentationParserTest.php | 13 ++++++++++++- tests/docs/en/test.md | 3 ++- 3 files changed, 32 insertions(+), 8 deletions(-) diff --git a/code/DocumentationParser.php b/code/DocumentationParser.php index a010efa..98cff2f 100644 --- a/code/DocumentationParser.php +++ b/code/DocumentationParser.php @@ -54,17 +54,29 @@ class DocumentationParser { $lines = split("\n", $md); foreach($lines as $i => $line) { - if(preg_match('/^\t*:::\s*(.*)/', $line, $matches)) { - // first line + if(!$started && preg_match('/^\t*:::\s*(.*)/', $line, $matches)) { + // first line with custom formatting $started = true; $lines[$i] = sprintf('
', $matches[1]);
-			} elseif($started && preg_match('/^\t(.*)/', $line, $matches)) {
-				// remove first tab (subsequent tabs are part of the code)
-				$lines[$i] = $matches[1];
+			} elseif(preg_match('/^\t(.*)/', $line, $matches)) {
+				// inner line of ::: block, or first line of standard markdown code block
+				// regex removes first tab (any following tabs are part of the code).
+				$lines[$i] = ($started) ? '' : '
' . "\n";
+				$lines[$i] .= htmlentities($matches[1], ENT_COMPAT, 'UTF-8');
 				$inner = true;
+				$started = true;
 			} elseif($started && $inner) {
+				// remove any previous blank lines
+				$j = $i-1;
+				while(isset($lines[$j]) && preg_match('/^[\t\s]*$/', $lines[$j])) {
+					unset($lines[$j]);
+					$j--;
+				}
+				
 				// last line, close pre
-				$lines[$i] = '
' . "\n" . $line; + $lines[$i] = '
' . "\n\n" . $line; + + // reset state $started = $inner = false; } } diff --git a/tests/DocumentationParserTest.php b/tests/DocumentationParserTest.php index 33c1577..8f70f2b 100644 --- a/tests/DocumentationParserTest.php +++ b/tests/DocumentationParserTest.php @@ -17,10 +17,21 @@ code block with multiple lines and tab indent + and escaped < brackets + +Normal text after code block HTML; - $this->assertContains($expected, $result); + $this->assertContains($expected, $result, 'Custom code blocks with ::: prefix'); + + $expected = << +code block +without formatting prefix + +HTML; + $this->assertContains($expected, $result, 'Traditional markdown code blocks'); } function testImageRewrites() { diff --git a/tests/docs/en/test.md b/tests/docs/en/test.md index a536a19..9f7d357 100644 --- a/tests/docs/en/test.md +++ b/tests/docs/en/test.md @@ -16,7 +16,8 @@ test with multiple lines and tab indent - + and escaped < brackets + Normal text after code block code block