[aur-dev] [PATCH 1/4] Convert markdown codeblocks to HTML code blocks
Marcel Korpel
marcel.korpel at gmail.com
Sat Jul 11 18:21:59 UTC 2015
Only codeblocks delimited with ```<newline> are supported.
Signed-off-by: Marcel Korpel <marcel.korpel at gmail.com>
---
web/lib/aur.inc.php | 49 +++++++++++++++++++++++++++++++++++++++----------
1 file changed, 39 insertions(+), 10 deletions(-)
diff --git a/web/lib/aur.inc.php b/web/lib/aur.inc.php
index 411d5ee..4b1850f 100644
--- a/web/lib/aur.inc.php
+++ b/web/lib/aur.inc.php
@@ -596,7 +596,8 @@ function comment_by_id($comment_id) {
}
/**
- * Process submitted comments so any links can be followed
+ * Process submitted comments so any links can be followed and
+ * parse markdown code blocks (within ```<newline>)
*
* @param string $comment Raw user submitted package comment
*
@@ -605,23 +606,51 @@ function comment_by_id($comment_id) {
function parse_comment($comment) {
$url_pattern = '/(\b(?:https?|ftp):\/\/[\w\/\#~:.?+=&%@!\-;,]+?' .
'(?=[.:?\-;,]*(?:[^\w\/\#~:.?+=&%@!\-;,]|$)))/iS';
+ $md_codeblock_delimiter = '/(```)\R/';
+ $md_codeblock_active = false;
- $matches = preg_split($url_pattern, $comment, -1,
+ $blocks = preg_split($md_codeblock_delimiter, $comment, -1,
PREG_SPLIT_DELIM_CAPTURE);
$html = '';
- for ($i = 0; $i < count($matches); $i++) {
+ for ($i = 0; $i < count($blocks); $i++) {
if ($i % 2) {
- # convert links
- $html .= '<a href="' . htmlspecialchars($matches[$i]) .
- '">' . htmlspecialchars($matches[$i]) . '</a>';
- }
- else {
- # convert everything else
- $html .= nl2br(htmlspecialchars($matches[$i]));
+ // add start/end of code block
+ if ($md_codeblock_active) {
+ $html .= '</code></pre><p>';
+ $md_codeblock_active = false;
+ } else {
+ $html .= '</p><pre><code>';
+ $md_codeblock_active = true;
+ }
+ } else {
+ if ($md_codeblock_active) {
+ // do not convert code blocks (white-space and newlines are
+ // preserved)
+ $html .= htmlspecialchars($blocks[$i]);
+ } else {
+ $matches = preg_split($url_pattern, $blocks[$i], -1,
+ PREG_SPLIT_DELIM_CAPTURE);
+
+ for ($j = 0; $j < count($matches); $j++) {
+ if ($j % 2) {
+ // convert links
+ $html .= '<a href="' . htmlspecialchars($matches[$j]) .
+ '">' . htmlspecialchars($matches[$j]) . '</a>';
+ } else {
+ // convert everything else
+ $html .= nl2br(htmlspecialchars($matches[$j]));
+ }
+ }
+ }
}
}
+ // close possible open code block
+ if ($md_codeblock_active) {
+ $html .= '</code></pre><p>';
+ }
+
return $html;
}
--
2.4.5
More information about the aur-dev
mailing list