diff --git a/src/Adapters/CommonMark/CodeBlockRenderer.php b/src/Adapters/CommonMark/CodeBlockRenderer.php index 4ba1917..a177bde 100644 --- a/src/Adapters/CommonMark/CodeBlockRenderer.php +++ b/src/Adapters/CommonMark/CodeBlockRenderer.php @@ -41,11 +41,15 @@ public function render(Node $node, ChildNodeRendererInterface $childRenderer) protected function detectGrammar(FencedCode $node): Grammar|string { if (! isset($node->getInfoWords()[0]) || $node->getInfoWords()[0] === '') { - return 'txt'; + return Grammar::Txt; } preg_match('/[a-zA-Z]+/', $node->getInfoWords()[0], $matches); + if (! $this->phiki->environment->grammars->has($matches[0])) { + return Grammar::Txt; + } + return $matches[0]; } } diff --git a/tests/.pest/snapshots/Adapters/CommonMark/PhikiExtensionTest/it_falls_back_to_txt_if_the_grammar_doesnt_exist.snap b/tests/.pest/snapshots/Adapters/CommonMark/PhikiExtensionTest/it_falls_back_to_txt_if_the_grammar_doesnt_exist.snap new file mode 100644 index 0000000..0dd5421 --- /dev/null +++ b/tests/.pest/snapshots/Adapters/CommonMark/PhikiExtensionTest/it_falls_back_to_txt_if_the_grammar_doesnt_exist.snap @@ -0,0 +1,2 @@ +
class A {}
+
diff --git a/tests/Adapters/CommonMark/PhikiExtensionTest.php b/tests/Adapters/CommonMark/PhikiExtensionTest.php
index 1e6e8f3..b4aed43 100644
--- a/tests/Adapters/CommonMark/PhikiExtensionTest.php
+++ b/tests/Adapters/CommonMark/PhikiExtensionTest.php
@@ -65,3 +65,21 @@ class A {}
expect($generated)->toMatchSnapshot();
});
+
+it('falls back to txt if the grammar doesnt exist', function () {
+ $environment = new Environment;
+
+ $environment
+ ->addExtension(new CommonMarkCoreExtension)
+ ->addExtension(new PhikiExtension('github-dark'));
+
+ $markdown = new MarkdownConverter($environment);
+
+ $generated = $markdown->convert(<<<'MD'
+ ```nonexistentlang
+ class A {}
+ ```
+ MD);
+
+ expect($generated)->toMatchSnapshot();
+});