From 92b40b2ae075d1aba194c77460b7d016b5f09caf Mon Sep 17 00:00:00 2001 From: Marc Durdin Date: Mon, 26 Feb 2024 12:12:51 +0700 Subject: [PATCH] chore: support hash headers in Markdown parser If we don't have a `---\ntitle: ...\n---` section, then we should instead search for the first heading in the document, rather than just having 'Untitled page'. This is helpful for generated documentation where we might not have the heading available, e.g. with keymanapp/keyman#10839. --- _common/MarkdownHost.php | 31 ++++++++++++++++++++----------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/_common/MarkdownHost.php b/_common/MarkdownHost.php index 6bd4d56..8df3758 100644 --- a/_common/MarkdownHost.php +++ b/_common/MarkdownHost.php @@ -52,27 +52,36 @@ function __construct($file) { // $lines = explode("\n", $contents); + $headers = []; $found = count($lines) > 3 && rtrim($lines[0]) == '---'; - $headers = []; - for($i = 1; $i < count($lines); $i++) { - if($lines[$i] == '---') break; - if(!preg_match('/^([a-z0-9_-]+):(.+)$/', $lines[$i], $match)) { - $found = false; - break; - } else { - $headers[$match[1]] = trim($match[2]); + if($found) { + for($i = 1; $i < count($lines); $i++) { + if($lines[$i] == '---') break; + if(!preg_match('/^([a-z0-9_-]+):(.+)$/', $lines[$i], $match)) { + $found = false; + break; + } else { + $headers[$match[1]] = trim($match[2]); + } } + $found = $found && $i < count($lines); } - $found = $found && $i < count($lines); - - if($found) $contents = implode("\n", array_slice($lines, $i)); if(isset($headers['redirect'])) { header("Location: {$headers['redirect']}"); exit; } + if($found) { + $contents = implode("\n", array_slice($lines, $i)); + } else { + // We are going to search for the first '#' style heading + if(preg_match('/^(#)+ (.+)$/m', $contents, $sub)) { + $headers['title'] = $sub[2]; + } + } + $this->pagetitle = isset($headers['title']) ? $headers['title'] : 'Untitled'; $this->showMenu = isset($headers['showmenu']) ? $headers['showmenu'] == 'true' : true;